DUNE-DAQ
DUNE Trigger and Data Acquisition software
Loading...
Searching...
No Matches
SNBDataHandlingModel.hxx
Go to the documentation of this file.
1// Declarations for SNBDataHandlingModel
2
3#include <folly/coro/BlockingWait.h>
4#include <folly/coro/Timeout.h>
5
6#include <typeinfo>
7
8namespace dunedaq {
9namespace snbmodules {
10
11template<class RDT, class RHT, class LBT, class RPT, class IDT>
12void
14{
15 // Setup request queues
16 // setup_request_queues(mcfg);
17 try {
18 for (auto input : mcfg->get_inputs()) {
19 if (input->get_data_type() == "DataRequest") {
20 m_data_request_receiver = get_iom_receiver<dfmessages::DataRequest>(input->UID());
21 } else {
22 m_raw_data_receiver_connection_name = input->UID();
23 // Parse for prefix
24 std::string conn_name = input->UID();
25 const char delim = '_';
26 std::vector<std::string> words;
27 std::size_t start;
28 std::size_t end = 0;
29 while ((start = conn_name.find_first_not_of(delim, end)) != std::string::npos) {
30 end = conn_name.find(delim, start);
31 words.push_back(conn_name.substr(start, end - start));
32 }
33
34 TLOG_DEBUG(TLVL_WORK_STEPS) << "Initialize connection based on uid: " << m_raw_data_receiver_connection_name
35 << " front word: " << words.front();
36
37 std::string cb_prefix("cb");
38 if (words.front() == cb_prefix) {
39 m_callback_mode = true;
40 }
41
42 if (!m_callback_mode) {
43 m_raw_data_receiver = get_iom_receiver<IDT>(m_raw_data_receiver_connection_name);
44 m_raw_receiver_timeout_ms = std::chrono::milliseconds(input->get_recv_timeout_ms());
45 }
46 }
47 }
48 for (auto output : mcfg->get_outputs()) {
49 if (output->get_data_type() == "TimeSync") {
50 m_generate_timesync = true;
51 m_timesync_sender = get_iom_sender<dfmessages::TimeSync>(output->UID());
52 m_timesync_connection_name = output->UID();
53 break;
54 }
55 }
56 } catch (const ers::Issue& excpt) {
57 throw datahandlinglibs::ResourceQueueError(ERS_HERE, "raw_input or frag_output", "SNBDataHandlingModel", excpt);
58 }
59
60 // Raw input connection sensibility check
61 if (!m_callback_mode && m_raw_data_receiver == nullptr) {
62 ers::error(datahandlinglibs::ConfigurationError(ERS_HERE, m_sourceid, "Non callback mode, and receiver is unset!"));
63 }
64
65 // Instantiate functionalities
66 m_error_registry.reset(new datahandlinglibs::FrameErrorRegistry());
67 m_error_registry->set_ers_metadata("DLH of SourceID[" + std::to_string(mcfg->get_source_id()) + "] ");
68 m_latency_buffer_impl.reset(new LBT());
69 m_raw_processor_impl.reset(new RPT(m_error_registry, mcfg->get_post_processing_enabled()));
70 m_request_handler_impl.reset(new RHT(m_latency_buffer_impl, m_error_registry));
71
72 register_node(mcfg->get_module_configuration()->get_latency_buffer()->UID(), m_latency_buffer_impl);
73 register_node(mcfg->get_module_configuration()->get_data_processor()->UID(), m_raw_processor_impl);
74 register_node(mcfg->get_module_configuration()->get_request_handler()->UID(), m_request_handler_impl);
75
76 // m_request_handler_impl->init(args);
77 // m_raw_processor_impl->init(args);
78 m_request_handler_supports_cutoff_timestamp = m_request_handler_impl->supports_cutoff_timestamp();
79 m_fake_trigger = false;
80 m_raw_receiver_sleep_us = std::chrono::microseconds::zero();
81 m_sourceid.id = mcfg->get_source_id();
82 m_sourceid.subsystem = RDT::subsystem;
83 m_processing_delay_ticks = mcfg->get_module_configuration()->get_post_processing_delay_ticks();
84 m_post_processing_delay_min_wait = mcfg->get_module_configuration()->get_post_processing_delay_min_wait();
85 m_post_processing_delay_max_wait = mcfg->get_module_configuration()->get_post_processing_delay_max_wait();
86
87 // Configure implementations:
88 m_raw_processor_impl->conf(mcfg);
89 // Configure the latency buffer before the request handler so the request handler can check for alignment
90 // restrictions
91 try {
92 m_latency_buffer_impl->conf(mcfg->get_module_configuration()->get_latency_buffer());
93 } catch (const std::bad_alloc& be) {
95 datahandlinglibs::ConfigurationError(ERS_HERE, m_sourceid, "Latency Buffer can't be allocated with size!"));
96 }
97 m_request_handler_impl->conf(mcfg);
98}
99
100template<class RDT, class RHT, class LBT, class RPT, class IDT>
101void
102SNBDataHandlingModel<RDT, RHT, LBT, RPT, IDT>::conf(const appfwk::DAQModule::CommandData_t& /*args*/)
103{
104 // Register callbacks if operating in that mode.
105 if (m_callback_mode) {
106 // Configure and register consume callback
107 m_consume_callback =
108 std::bind(&SNBDataHandlingModel<RDT, RHT, LBT, RPT, IDT>::consume_callback, this, std::placeholders::_1);
109
110 // Register callback
112 dmcbr->register_callback<IDT>(m_raw_data_receiver_connection_name, m_consume_callback);
113 }
114
115 // Configure threads:
116 m_consumer_thread.set_name("consumer", m_sourceid.id);
117 if (m_generate_timesync) {
118 m_timesync_thread.set_name("timesync", m_sourceid.id);
119 }
120 if (m_processing_delay_ticks) {
121 m_postprocess_scheduler_thread.set_name("pprocsched", m_sourceid.id);
122 m_timekeeper = std::make_unique<folly::ThreadWheelTimekeeper>();
123 }
124}
125
126template<class RDT, class RHT, class LBT, class RPT, class IDT>
127void
128SNBDataHandlingModel<RDT, RHT, LBT, RPT, IDT>::start(const appfwk::DAQModule::CommandData_t& args)
129{
130 // Reset opmon variables
131 m_sum_payloads = 0;
132 m_num_payloads = 0;
133 m_sum_requests = 0;
134 m_num_requests = 0;
135 m_num_lb_insert_failures = 0;
136 m_stats_packet_count = 0;
137 m_rawq_timeout_count = 0;
138 m_num_post_processing_delay_max_waits = 0;
139
140 m_t0 = std::chrono::high_resolution_clock::now();
141
142 m_run_number = args.value<dunedaq::daqdataformats::run_number_t>("run", 1);
143
144 TLOG_DEBUG(TLVL_WORK_STEPS) << "Starting threads...";
145 m_raw_processor_impl->start(args);
146 m_request_handler_impl->start(args);
147 if (!m_callback_mode) {
148 m_consumer_thread.set_work(&SNBDataHandlingModel<RDT, RHT, LBT, RPT, IDT>::run_consume, this);
149 }
150 if (m_generate_timesync) {
151 m_timesync_thread.set_work(&SNBDataHandlingModel<RDT, RHT, LBT, RPT, IDT>::run_timesync, this);
152 }
153 if (m_processing_delay_ticks) {
155 this);
156 }
157 // Register callback to receive and dispatch data requests
158 m_data_request_receiver->add_callback(
159 std::bind(&SNBDataHandlingModel<RDT, RHT, LBT, RPT, IDT>::dispatch_requests, this, std::placeholders::_1));
160}
161
162template<class RDT, class RHT, class LBT, class RPT, class IDT>
163void
164SNBDataHandlingModel<RDT, RHT, LBT, RPT, IDT>::stop(const appfwk::DAQModule::CommandData_t& args)
165{
166 TLOG_DEBUG(TLVL_WORK_STEPS) << "Stoppping threads...";
167
168 // Stop receiving data requests as first thing
169 m_data_request_receiver->remove_callback();
170 // Stop the other threads
171 m_request_handler_impl->stop(args);
172 if (m_generate_timesync) {
173 while (!m_timesync_thread.get_readiness()) {
174 std::this_thread::sleep_for(std::chrono::milliseconds(10));
175 }
176 }
177 if (!m_callback_mode) {
178 while (!m_consumer_thread.get_readiness()) {
179 std::this_thread::sleep_for(std::chrono::milliseconds(10));
180 }
181 }
182 if (m_processing_delay_ticks) {
183 m_baton.post(); // In case the coroutine is still waiting when the consumer has stopped
184 while (!m_postprocess_scheduler_thread.get_readiness()) {
185 std::this_thread::sleep_for(std::chrono::milliseconds(10));
186 }
187 }
188 TLOG_DEBUG(TLVL_WORK_STEPS) << "Flushing latency buffer with occupancy: " << m_latency_buffer_impl->occupancy();
189 m_latency_buffer_impl->flush();
190 m_raw_processor_impl->stop(args);
191 m_raw_processor_impl->reset_last_daq_time();
192}
193
194template<class RDT, class RHT, class LBT, class RPT, class IDT>
195void
197{
199 ri.set_sum_payloads(m_sum_payloads.load());
200 ri.set_num_payloads(m_num_payloads.exchange(0));
201
202 ri.set_num_data_input_timeouts(m_rawq_timeout_count.exchange(0));
203
204 auto now = std::chrono::high_resolution_clock::now();
205 int new_packets = m_stats_packet_count.exchange(0);
206 double seconds = std::chrono::duration_cast<std::chrono::microseconds>(now - m_t0).count() / 1000000.;
207 m_t0 = now;
208
209 // 08-May-2025, KAB: added a message to warn users when latency buffer inserts are failing.
210 int local_num_lb_insert_failures = m_num_lb_insert_failures.exchange(0);
211 if (local_num_lb_insert_failures != 0) {
212 ers::warning(datahandlinglibs::NonZeroLatencyBufferInsertFailures(
213 ERS_HERE, m_sourceid, local_num_lb_insert_failures, ri.num_payloads()));
214 }
215
216 ri.set_rate_payloads_consumed(new_packets / seconds / 1000.);
217 ri.set_num_lb_insert_failures(local_num_lb_insert_failures);
218 ri.set_sum_requests(m_sum_requests.load());
219 ri.set_num_requests(m_num_requests.exchange(0));
220 ri.set_num_post_processing_delay_max_waits(m_num_post_processing_delay_max_waits.exchange(0));
221 ri.set_last_daq_timestamp(m_raw_processor_impl->get_last_daq_time());
222 ri.set_newest_timestamp(m_raw_processor_impl->get_last_daq_time());
223 ri.set_oldest_timestamp(m_request_handler_impl->get_oldest_time());
224
225 this->publish(std::move(ri));
226}
227
228template<class RDT, class RHT, class LBT, class RPT, class IDT>
229void
231{
232 if constexpr (std::is_same_v<IDT, RDT>) {
233 process_item(std::move(payload));
234 } else {
235 auto transformed = transform_payload(payload);
236 for (auto& i : transformed) {
237 process_item(std::move(i));
238 }
239 }
240}
241
242template<class RDT, class RHT, class LBT, class RPT, class IDT>
243void
245{
246 transform_and_process(std::move(payload));
247}
248
249template<class RDT, class RHT, class LBT, class RPT, class IDT>
250void
252{
253 m_raw_processor_impl->preprocess_item(&payload);
254 if (m_request_handler_supports_cutoff_timestamp) {
255 int64_t diff1 = payload.get_timestamp() - m_request_handler_impl->get_cutoff_timestamp();
256 if (diff1 <= 0) {
257 // m_request_handler_impl->increment_tardy_tp_count();
258 ers::warning(datahandlinglibs::DataPacketArrivedTooLate(ERS_HERE,
259 m_sourceid,
260 m_run_number,
261 payload.get_timestamp(),
262 m_request_handler_impl->get_cutoff_timestamp(),
263 diff1,
264 (static_cast<double>(diff1) / 62500.0)));
265 }
266 }
267 while (m_latency_buffer_impl->isFull()) {
268 std::this_thread::sleep_for(std::chrono::milliseconds(1));
269 }
270 if (!m_latency_buffer_impl->write(std::move(payload))) {
271 // TLOG_DEBUG(TLVL_TAKE_NOTE) << "***ERROR: Latency buffer insert failed! (Payload timestamp=" <<
272 // payload.get_timestamp() << ")";
273 m_num_lb_insert_failures++;
274 return;
275 }
276
277 if (m_processing_delay_ticks == 0) {
278 m_raw_processor_impl->postprocess_item(m_latency_buffer_impl->back());
279 ++m_num_payloads;
280 ++m_sum_payloads;
281 ++m_stats_packet_count;
282 } else {
283 m_baton.post();
284 }
285}
286
287template<class RDT, class RHT, class LBT, class RPT, class IDT>
288void
290{
291 folly::coro::blockingWait(postprocess_schedule());
292}
293
294template<class RDT, class RHT, class LBT, class RPT, class IDT>
295void
297{
298
299 TLOG_DEBUG(TLVL_WORK_STEPS) << "Consumer thread started...";
300 m_rawq_timeout_count = 0;
301 m_num_payloads = 0;
302 m_sum_payloads = 0;
303 m_stats_packet_count = 0;
304 m_num_post_processing_delay_max_waits = 0;
305
306 while (m_run_marker.load()) {
307 // Try to acquire data
308
309 auto opt_payload = m_raw_data_receiver->try_receive(m_raw_receiver_timeout_ms);
310
311 if (opt_payload) {
312 IDT& payload = opt_payload.value();
313 transform_and_process(std::move(payload));
314 } else {
315 ++m_rawq_timeout_count;
316 // Protection against a zero sleep becoming a yield
317 if (m_raw_receiver_sleep_us != std::chrono::microseconds::zero())
318 std::this_thread::sleep_for(m_raw_receiver_sleep_us);
319 }
320 }
321 TLOG_DEBUG(TLVL_WORK_STEPS) << "Consumer thread joins... ";
322}
323
324template<class RDT, class RHT, class LBT, class RPT, class IDT>
325folly::coro::Task<void>
327{
328
329 // TLOG_DEBUG(TLVL_WORK_STEPS) << "Postprocess schedule coroutine started...";
330 timestamp_t newest_ts = 0;
331 timestamp_t end_win_ts = 0;
332 bool first_cycle = true;
333 auto last_post_proc_time = std::chrono::system_clock::now();
334 auto now = last_post_proc_time;
335 std::chrono::milliseconds milliseconds;
336 RDT processed_element;
337
338 // Deferral of the post processing, to allow elements being reordered in the LB
339 // Basically, find data older than a certain timestamp and process all data since the last post-processed element up
340 // to that value
341 while (m_run_marker.load()) {
342 try {
343 co_await folly::coro::timeout(
344 m_baton.operator co_await(), std::chrono::milliseconds{ m_post_processing_delay_max_wait }, m_timekeeper.get());
345 m_baton.reset();
346 } catch (const folly::FutureTimeout&) {
347 ++m_num_post_processing_delay_max_waits;
348 }
349
350 if (m_latency_buffer_impl->occupancy() == 0) {
351 continue;
352 }
353
354 now = std::chrono::system_clock::now();
355 milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_post_proc_time);
356
357 if (static_cast<uint64_t>(milliseconds.count()) <= m_post_processing_delay_min_wait) {
358 continue;
359 }
360
361 last_post_proc_time = now;
362
363 // Get the LB boundaries
364 auto tail = m_latency_buffer_impl->back();
365 newest_ts = tail->get_timestamp();
366
367 if (first_cycle) {
368 auto head = m_latency_buffer_impl->front();
369 processed_element.set_timestamp(head->get_timestamp());
370 first_cycle = false;
371 // TLOG() << "***** First pass post processing *****";
372 }
373
374 if (newest_ts - processed_element.get_timestamp() > m_processing_delay_ticks) {
375 end_win_ts = newest_ts - m_processing_delay_ticks;
376 auto start_iter = m_latency_buffer_impl->lower_bound(processed_element, false);
377 processed_element.set_timestamp(end_win_ts);
378 auto end_iter = m_latency_buffer_impl->lower_bound(processed_element, false);
379
380 for (auto it = start_iter; it != end_iter; ++it) {
381 m_raw_processor_impl->postprocess_item(&(*it));
382 ++m_num_payloads;
383 ++m_sum_payloads;
384 ++m_stats_packet_count;
385 }
386 }
387 }
388}
389
390template<class RDT, class RHT, class LBT, class RPT, class IDT>
391void
393{
394 TLOG_DEBUG(TLVL_WORK_STEPS) << "TimeSync thread started...";
395 m_num_requests = 0;
396 m_sum_requests = 0;
397 uint64_t msg_seqno = 0;
398 timestamp_t prev_timestamp = 0;
399 auto once_per_run = true;
400 size_t zero_timestamp_count = 0;
401 size_t duplicate_timestamp_count = 0;
402 size_t total_timestamp_count = 0;
403 while (m_run_marker.load()) {
404 try {
405 auto timesyncmsg = dfmessages::TimeSync(m_raw_processor_impl->get_last_daq_time());
406 ++total_timestamp_count;
407 // daq_time is zero for the first received timesync, and may
408 // be the same as the previous daq_time if the data has
409 // stopped flowing. In both cases we don't send the TimeSync
410 if (timesyncmsg.daq_time != 0 && timesyncmsg.daq_time != prev_timestamp) {
411 prev_timestamp = timesyncmsg.daq_time;
412 timesyncmsg.run_number = m_run_number;
413 timesyncmsg.sequence_number = ++msg_seqno;
414 timesyncmsg.source_id = m_sourceid.id;
415 TLOG_DEBUG(TLVL_TIME_SYNCS) << "New timesync: daq=" << timesyncmsg.daq_time
416 << " wall=" << timesyncmsg.system_time << " run=" << timesyncmsg.run_number
417 << " seqno=" << timesyncmsg.sequence_number
418 << " source_id=" << timesyncmsg.source_id;
419 try {
420 dfmessages::TimeSync timesyncmsg_copy(timesyncmsg);
421 m_timesync_sender->send(std::move(timesyncmsg_copy), std::chrono::milliseconds(500));
422 } catch (ers::Issue& excpt) {
424 datahandlinglibs::TimeSyncTransmissionFailed(ERS_HERE, m_sourceid, m_timesync_connection_name, excpt));
425 }
426
427 if (m_fake_trigger) {
429 ++m_current_fake_trigger_id;
430 dr.trigger_number = m_current_fake_trigger_id;
431 dr.trigger_timestamp = timesyncmsg.daq_time > 500 * us ? timesyncmsg.daq_time - 500 * us : 0;
432 auto width = 300000;
433 uint offset = 100;
436 dr.request_information.component = m_sourceid;
437 dr.data_destination = "data_fragments_q";
438 TLOG_DEBUG(TLVL_WORK_STEPS) << "Issuing fake trigger based on timesync. " << " ts=" << dr.trigger_timestamp
439 << " window_begin=" << dr.request_information.window_begin
440 << " window_end=" << dr.request_information.window_end;
441 m_request_handler_impl->issue_request(dr);
442
443 ++m_num_requests;
444 ++m_sum_requests;
445 }
446 } else {
447 if (timesyncmsg.daq_time == 0) {
448 ++zero_timestamp_count;
449 }
450 if (timesyncmsg.daq_time == prev_timestamp) {
451 ++duplicate_timestamp_count;
452 }
453 if (once_per_run) {
454 TLOG() << "Timesync with DAQ time 0 won't be sent out as it's an invalid sync.";
455 once_per_run = false;
456 }
457 }
458 } catch (const iomanager::TimeoutExpired& excpt) {
459 // ++m_timesyncqueue_timeout;
460 }
461 // Split up the 100ms sleep into 10 sleeps of 10ms, so we respond to "stop" quicker
462 for (size_t i = 0; i < 10; ++i) {
463 std::this_thread::sleep_for(std::chrono::milliseconds(10));
464 if (!m_run_marker.load()) {
465 break;
466 }
467 }
468 }
469 once_per_run = true;
470 TLOG_DEBUG(TLVL_WORK_STEPS) << "TimeSync thread joins... (timestamp count, zero/same/total = "
471 << zero_timestamp_count << "/" << duplicate_timestamp_count << "/"
472 << total_timestamp_count << ")";
473}
474
475template<class RDT, class RHT, class LBT, class RPT, class IDT>
476void
478{
479 if (data_request.request_information.component != m_sourceid) {
481 datahandlinglibs::RequestSourceIDMismatch(ERS_HERE, m_sourceid, data_request.request_information.component));
482 return;
483 }
484 TLOG_DEBUG(TLVL_QUEUE_POP) << "Received DataRequest" << " for trig/seq_number " << data_request.trigger_number << "."
485 << data_request.sequence_number << ", runno " << data_request.run_number
486 << ", trig timestamp " << data_request.trigger_timestamp
487 << ", SourceID: " << data_request.request_information.component << ", window begin/end "
488 << data_request.request_information.window_begin << "/"
489 << data_request.request_information.window_end
490 << ", dest: " << data_request.data_destination;
491 m_request_handler_impl->issue_request(data_request);
492 ++m_num_requests;
493 ++m_sum_requests;
494}
495
496} // namespace snbmodules
497} // namespace dunedaq
#define ERS_HERE
const dunedaq::appmodel::LatencyBuffer * get_latency_buffer() const
Get "latency_buffer" relationship value.
uint64_t get_post_processing_delay_ticks() const
Get "post_processing_delay_ticks" attribute value. Number of clock tick by which post processing of i...
const dunedaq::appmodel::DataProcessor * get_data_processor() const
Get "data_processor" relationship value.
uint64_t get_post_processing_delay_max_wait() const
Get "post_processing_delay_max_wait" attribute value. Maximum wait time (ms) before post processing c...
uint64_t get_post_processing_delay_min_wait() const
Get "post_processing_delay_min_wait" attribute value. Minimum time (ms) between consecutive post proc...
const dunedaq::appmodel::RequestHandler * get_request_handler() const
Get "request_handler" relationship value.
const dunedaq::appmodel::DataHandlerConf * get_module_configuration() const
Get "module_configuration" relationship value.
uint32_t get_source_id() const
Get "source_id" attribute value.
bool get_post_processing_enabled() const
Get "post_processing_enabled" attribute value.
const std::string & UID() const noexcept
const std::vector< const dunedaq::confmodel::Connection * > & get_inputs() const
Get "inputs" relationship value. List of connections to/from this module.
const std::vector< const dunedaq::confmodel::Connection * > & get_outputs() const
Get "outputs" relationship value. Output connections from this module.
static std::shared_ptr< DataMoveCallbackRegistry > get()
void start(const appfwk::DAQModule::CommandData_t &args)
void init(const appmodel::DataHandlerModule *modconf)
Forward calls from the appfwk.
void conf(const appfwk::DAQModule::CommandData_t &args)
void stop(const appfwk::DAQModule::CommandData_t &args)
void dispatch_requests(dfmessages::DataRequest &data_request)
void run_timesync()
Function that will be run in its own thread and sends periodic timesync messages by pushing them to t...
void run_consume()
Function that will be run in its own thread to read the raw packets from the connection and add them ...
Base class for any user define issue.
Definition Issue.hpp:69
double offset
static int64_t now()
#define TLOG_DEBUG(lvl,...)
Definition Logging.hpp:112
#define TLOG(...)
Definition macro.hpp:22
uint32_t run_number_t
Type used to represent run number.
Definition Types.hpp:20
Including Qt Headers.
static std::shared_ptr< iomanager::SenderConcept< Datatype > > get_iom_sender(iomanager::ConnectionId const &id)
static std::shared_ptr< iomanager::ReceiverConcept< Datatype > > get_iom_receiver(iomanager::ConnectionId const &id)
void warning(const Issue &issue)
Definition ers.hpp:115
void error(const Issue &issue)
Definition ers.hpp:81
timestamp_t window_end
End of the data collection window.
SourceID component
The Requested Component.
timestamp_t window_begin
Start of the data collection window.
This message represents a request for data sent to a single component of the DAQ.
sequence_number_t sequence_number
Sequence Number of the request.
trigger_number_t trigger_number
Trigger number the request corresponds to.
timestamp_t trigger_timestamp
Timestamp of trigger.
run_number_t run_number
The current run number.
A synthetic message used to ensure that all elements of a DAQ system are synchronized.
Definition TimeSync.hpp:25