3#include <folly/coro/BlockingWait.h>
4#include <folly/coro/Timeout.h>
5#include <folly/futures/ThreadWheelTimekeeper.h>
6#include <folly/coro/CurrentExecutor.h>
7#include <folly/CancellationToken.h>
12namespace datahandlinglibs {
14template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
22 if (input->get_data_type() ==
"DataRequest") {
26 m_raw_data_receiver_connection_name = input->UID();
28 std::string conn_name = input->UID();
29 const char delim =
'_';
30 std::vector<std::string> words;
33 while ((start = conn_name.find_first_not_of(delim, end)) != std::string::npos) {
34 end = conn_name.find(delim, start);
35 words.push_back(conn_name.substr(start, end - start));
38 TLOG_DEBUG(TLVL_WORK_STEPS) <<
"Initialize connection based on uid: "
39 << m_raw_data_receiver_connection_name <<
" front word: " << words.front();
41 std::string cb_prefix(
"cb");
42 if (words.front() == cb_prefix) {
43 m_callback_mode =
true;
46 if (!m_callback_mode) {
48 m_raw_receiver_timeout_ms = std::chrono::milliseconds(input->get_recv_timeout_ms());
53 if (output->get_data_type() ==
"TimeSync") {
54 m_generate_timesync =
true;
56 m_timesync_connection_name = output->UID();
61 throw ResourceQueueError(
ERS_HERE,
"raw_input or frag_output",
"DataHandlingModel", excpt);
65 if (!m_callback_mode && m_raw_data_receiver ==
nullptr) {
66 ers::error(ConfigurationError(
ERS_HERE, m_sourceid,
"Non callback mode, and receiver is unset!"));
71 m_error_registry->set_ers_metadata(
"DLH of SourceID[" + std::to_string(mcfg->
get_source_id()) +
"] ");
72 m_latency_buffer_impl.reset(
new LBT());
74 m_request_handler_impl.reset(
new RHT(m_latency_buffer_impl, m_error_registry));
82 m_request_handler_supports_cutoff_timestamp = m_request_handler_impl->supports_cutoff_timestamp();
83 m_fake_trigger =
false;
84 m_raw_receiver_sleep_us = std::chrono::microseconds::zero();
86 m_sourceid.subsystem = RDT::subsystem;
91 if (m_processing_delay_ticks) {
94 "Delayed postprocessing (post_processing_delay_ticks > 0) requires a sorted buffer (SkipList). "
95 "Queue buffers (FixedRateQueue, BinarySearchQueue) expect in-order data and must use post_processing_delay_ticks = 0."));
100 m_raw_processor_impl->conf(mcfg);
105 }
catch (
const std::bad_alloc& be) {
106 ers::error(ConfigurationError(
ERS_HERE, m_sourceid,
"Latency Buffer can't be allocated with size!"));
108 m_request_handler_impl->conf(mcfg);
111template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
116 if (m_callback_mode) {
122 dmcbr->register_callback<
IDT>(m_raw_data_receiver_connection_name, m_consume_callback);
126 m_consumer_thread.set_name(
"consumer", m_sourceid.id);
127 if (m_generate_timesync) {
128 m_timesync_thread.set_name(
"timesync", m_sourceid.id);
130 if (m_processing_delay_ticks) {
131 m_postprocess_scheduler_thread.set_name(
"pprocsched", m_sourceid.id);
132 m_timekeeper = std::make_unique<folly::ThreadWheelTimekeeper>();
137template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
146 m_num_lb_insert_failures = 0;
147 m_stats_packet_count = 0;
148 m_rawq_timeout_count = 0;
149 m_num_post_processing_delay_max_waits = 0;
151 m_t0 = std::chrono::high_resolution_clock::now();
155 TLOG_DEBUG(TLVL_WORK_STEPS) <<
"Starting threads...";
156 m_raw_processor_impl->start(args);
157 m_request_handler_impl->start(args);
158 if (!m_callback_mode) {
161 if (m_generate_timesync) {
164 if (m_processing_delay_ticks) {
168 m_data_request_receiver->add_callback(
172template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
176 TLOG_DEBUG(TLVL_WORK_STEPS) <<
"Stoppping threads...";
179 m_data_request_receiver->remove_callback();
181 m_request_handler_impl->stop(args);
182 if (m_generate_timesync) {
183 while (!m_timesync_thread.get_readiness()) {
184 std::this_thread::sleep_for(std::chrono::milliseconds(10));
187 if (!m_callback_mode) {
188 while (!m_consumer_thread.get_readiness()) {
189 std::this_thread::sleep_for(std::chrono::milliseconds(10));
192 if (m_processing_delay_ticks) {
194 while (!m_postprocess_scheduler_thread.get_readiness()) {
195 std::this_thread::sleep_for(std::chrono::milliseconds(10));
198 TLOG_DEBUG(TLVL_WORK_STEPS) <<
"Flushing latency buffer with occupancy: " << m_latency_buffer_impl->occupancy();
199 m_latency_buffer_impl->flush();
200 m_raw_processor_impl->stop(args);
201 m_raw_processor_impl->reset_last_daq_time();
204template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
214 auto now = std::chrono::high_resolution_clock::now();
215 int new_packets = m_stats_packet_count.exchange(0);
216 double seconds = std::chrono::duration_cast<std::chrono::microseconds>(
now - m_t0).count() / 1000000.;
220 int local_num_lb_insert_failures = m_num_lb_insert_failures.exchange(0);
221 if (local_num_lb_insert_failures != 0) {
234 this->publish(std::move(ri));
237template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
240 if constexpr (std::is_same_v<IDT, RDT>) {
241 process_item(std::move(payload));
243 auto transformed = transform_payload(payload);
244 for (
auto& i : transformed) {
245 process_item(std::move(i));
250template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
253 transform_and_process(std::move(payload));
256template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
260 m_raw_processor_impl->preprocess_item(&payload);
261 if (m_request_handler_supports_cutoff_timestamp) {
262 int64_t diff1 = payload.get_timestamp() - m_request_handler_impl->get_cutoff_timestamp();
265 ers::warning(DataPacketArrivedTooLate(
ERS_HERE, m_sourceid, m_run_number, payload.get_timestamp(),
266 m_request_handler_impl->get_cutoff_timestamp(), diff1,
267 (
static_cast<double>(diff1)/62500.0)));
270 if (!m_latency_buffer_impl->write(std::move(payload))) {
272 m_num_lb_insert_failures++;
276 if (m_processing_delay_ticks == 0) {
277 m_raw_processor_impl->postprocess_item(m_latency_buffer_impl->back());
280 ++m_stats_packet_count;
286template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
290 folly::coro::blockingWait(postprocess_schedule());
293template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
298 TLOG_DEBUG(TLVL_WORK_STEPS) <<
"Consumer thread started...";
299 m_rawq_timeout_count = 0;
302 m_stats_packet_count = 0;
303 m_num_post_processing_delay_max_waits = 0;
305 while (m_run_marker.load()) {
308 auto opt_payload = m_raw_data_receiver->try_receive(m_raw_receiver_timeout_ms);
311 IDT& payload = opt_payload.value();
312 transform_and_process(std::move(payload));
314 ++m_rawq_timeout_count;
316 if ( m_raw_receiver_sleep_us != std::chrono::microseconds::zero())
317 std::this_thread::sleep_for(m_raw_receiver_sleep_us);
320 TLOG_DEBUG(TLVL_WORK_STEPS) <<
"Consumer thread joins... ";
323template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
324folly::coro::Task<void>
328 TLOG_DEBUG(TLVL_WORK_STEPS) <<
"Postprocess schedule coroutine started...";
329 TLOG() <<
"***** Starting post-process coroutine with timout " << m_post_processing_delay_max_wait <<
" *****";
333 *m_raw_processor_impl,
334 m_processing_delay_ticks,
335 m_post_processing_delay_min_wait,
336 m_post_processing_delay_max_wait };
338 const auto wait_data = [
this]() -> folly::coro::Task<void> {
341 auto token =
co_await folly::coro::co_current_cancellation_token;
342 folly::CancellationCallback cb(token, [
this] { m_baton.post(); });
346 while (m_run_marker.load()) {
347 bool timeout =
false;
349 if ( m_post_processing_delay_max_wait > 0 ) {
351 co_await folly::coro::timeout(
353 std::chrono::milliseconds{ m_post_processing_delay_max_wait },
356 }
catch (
const folly::FutureTimeout&) {
358 ++m_num_post_processing_delay_max_waits;
366 if (
auto processed = sched_algo.run(timeout); processed > 0) {
367 m_num_payloads += processed;
368 m_sum_payloads += processed;
369 m_stats_packet_count += processed;
375template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
379 TLOG_DEBUG(TLVL_WORK_STEPS) <<
"TimeSync thread started...";
382 uint64_t msg_seqno = 0;
384 auto once_per_run =
true;
385 size_t zero_timestamp_count = 0;
386 size_t duplicate_timestamp_count = 0;
387 size_t total_timestamp_count = 0;
388 while (m_run_marker.load()) {
391 ++total_timestamp_count;
395 if (timesyncmsg.daq_time != 0 && timesyncmsg.daq_time != prev_timestamp) {
396 prev_timestamp = timesyncmsg.daq_time;
397 timesyncmsg.run_number = m_run_number;
398 timesyncmsg.sequence_number = ++msg_seqno;
399 timesyncmsg.source_id = m_sourceid.id;
400 TLOG_DEBUG(TLVL_TIME_SYNCS) <<
"New timesync: daq=" << timesyncmsg.daq_time
401 <<
" wall=" << timesyncmsg.system_time <<
" run=" << timesyncmsg.run_number
402 <<
" seqno=" << timesyncmsg.sequence_number <<
" source_id=" << timesyncmsg.source_id;
405 m_timesync_sender->send(std::move(timesyncmsg_copy), std::chrono::milliseconds(500));
411 if (m_fake_trigger) {
413 ++m_current_fake_trigger_id;
415 dr.
trigger_timestamp = timesyncmsg.daq_time > 500 * us ? timesyncmsg.daq_time - 500 * us : 0;
422 TLOG_DEBUG(TLVL_WORK_STEPS) <<
"Issuing fake trigger based on timesync. "
426 m_request_handler_impl->issue_request(dr);
432 if (timesyncmsg.daq_time == 0) {++zero_timestamp_count;}
433 if (timesyncmsg.daq_time == prev_timestamp) {++duplicate_timestamp_count;}
435 TLOG() <<
"Timesync with DAQ time 0 won't be sent out as it's an invalid sync.";
436 once_per_run =
false;
439 }
catch (
const iomanager::TimeoutExpired& excpt) {
443 for (
size_t i=0; i<10; ++i) {
444 std::this_thread::sleep_for(std::chrono::milliseconds(10));
445 if (!m_run_marker.load()) {
451 TLOG_DEBUG(TLVL_WORK_STEPS) <<
"TimeSync thread joins... (timestamp count, zero/same/total = "
452 << zero_timestamp_count <<
"/" << duplicate_timestamp_count <<
"/"
453 << total_timestamp_count <<
")";
456template<
class RDT,
class RHT,
class LBT,
class RPT,
class IDT>
464 TLOG_DEBUG(TLVL_QUEUE_POP) <<
"Received DataRequest"
472 m_request_handler_impl->issue_request(data_request);
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.
void consume_callback(IDT &&payload)
std::uint64_t timestamp_t
void init(const appmodel::DataHandlerModule *modconf)
Forward calls from the appfwk.
void stop(const appfwk::DAQModule::CommandData_t &args)
virtual void generate_opmon_data() override
void start(const appfwk::DAQModule::CommandData_t &args)
void run_postprocess_scheduler()
void conf(const appfwk::DAQModule::CommandData_t &args)
void dispatch_requests(dfmessages::DataRequest &data_request)
void process_item(RDT &&payload)
void run_consume()
Function that will be run in its own thread to read the raw packets from the connection and add them ...
void run_timesync()
Function that will be run in its own thread and sends periodic timesync messages by pushing them to t...
void transform_and_process(IDT &&payload)
folly::coro::Task< void > postprocess_schedule()
static std::shared_ptr< DataMoveCallbackRegistry > get()
void set_sum_payloads(::uint64_t value)
void set_num_lb_insert_failures(::uint64_t value)
void set_rate_payloads_consumed(double value)
void set_sum_requests(::uint64_t value)
void set_num_post_processing_delay_max_waits(::uint64_t value)
void set_last_daq_timestamp(::uint64_t value)
void set_oldest_timestamp(::uint64_t value)
void set_num_data_input_timeouts(::uint64_t value)
::uint64_t num_payloads() const
void set_num_payloads(::uint64_t value)
void set_num_requests(::uint64_t value)
void set_newest_timestamp(::uint64_t value)
Base class for any user define issue.
#define TLOG_DEBUG(lvl,...)
static std::shared_ptr< iomanager::SenderConcept< Datatype > > get_iom_sender(iomanager::ConnectionId const &id)
SourceID[" << sourceid << "] Command daqdataformats::SourceID Readout Initialization std::string initerror Configuration std::string conferror Configuration std::string conferror TimeSyncTransmissionFailed
static std::shared_ptr< iomanager::ReceiverConcept< Datatype > > get_iom_receiver(iomanager::ConnectionId const &id)
void warning(const Issue &issue)
void error(const Issue &issue)
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.
std::string data_destination
ComponentRequest request_information
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.