1 #include "TRACE/tracemf.h"
2 #include "artdaq-core/Data/Fragment.hh"
4 #define TRACE_NAME "TransferWrapper"
6 #include "artdaq/ArtModules/detail/TransferWrapper.hh"
8 #include "artdaq-core/Utilities/ExceptionHandler.hh"
9 #include "artdaq-core/Utilities/TimeUtils.hh"
10 #include "artdaq/DAQdata/NetMonHeader.hh"
11 #include "artdaq/ExternalComms/MakeCommanderPlugin.hh"
12 #include "artdaq/TransferPlugins/MakeTransferPlugin.hh"
14 #include "cetlib_except/exception.h"
15 #include "fhiclcpp/ParameterSet.h"
32 void signal_handler(
int signal)
34 gSignalStatus = signal;
38 : timeoutInUsecs_(pset.get<std::size_t>(
"timeoutInUsecs", 100000))
39 , last_received_data_()
40 , last_report_(std::chrono::steady_clock::now())
44 , dispatcherHost_(pset.get<std::string>(
"dispatcherHost",
"localhost"))
45 , dispatcherPort_(pset.get<std::string>(
"dispatcherPort",
"5266"))
46 , serverUrl_(pset.get<std::string>(
"server_url",
"http://" + dispatcherHost_ +
":" + dispatcherPort_ +
"/RPC2"))
47 , maxEventsBeforeInit_(pset.get<std::size_t>(
"maxEventsBeforeInit", 5))
48 , allowedFragmentTypes_(pset.get<std::vector<int>>(
"allowedFragmentTypes", {226, 227, 229}))
49 , runningStateTimeout_(pset.get<
double>(
"dispatcherConnectTimeout", 0))
50 , runningStateInterval_us_(pset.get<
size_t>(
"dispatcherConnectRetryInterval_us", 1000000))
51 , quitOnFragmentIntegrityProblem_(pset.get<
bool>(
"quitOnFragmentIntegrityProblem",
true))
52 , multi_run_mode_(pset.get<
bool>(
"allowMultipleRuns",
false))
53 , monitorRegistered_(
false)
55 std::signal(SIGINT, signal_handler);
61 metricMan->initialize(pset.get<fhicl::ParameterSet>(
"metrics", fhicl::ParameterSet()),
"Online Monitor");
62 metricMan->do_start();
67 ExceptionHandler(ExceptionHandlerRethrow::no,
"TransferWrapper: could not configure metrics");
71 if (runningStateInterval_us_ < 1000)
73 TLOG(TLVL_WARNING) <<
"Invalid value " << runningStateInterval_us_ <<
" us detected for dispatcherConnectRetryInterval_us. Setting to 1000 us";
74 runningStateInterval_us_ = 1000;
76 if (runningStateInterval_us_ > 30000000)
78 TLOG(TLVL_WARNING) <<
"Invalid value " << runningStateInterval_us_ <<
" us detected for dispatcherConnectRetryInterval_us. Setting to 30,000,000 us";
79 runningStateInterval_us_ = 30000000;
82 fhicl::ParameterSet new_pset(pset);
83 if (!new_pset.has_key(
"server_url"))
85 new_pset.put<std::string>(
"server_url", serverUrl_);
94 artdaq::FragmentPtrs fragmentPtrs;
95 bool receivedFragment =
false;
96 static bool initialized =
false;
97 static size_t fragments_received = 0;
99 while (gSignalStatus == 0)
101 receivedFragment =
false;
102 auto fragmentPtr = std::make_unique<artdaq::Fragment>();
104 while (!receivedFragment)
106 if (gSignalStatus != 0)
108 TLOG(TLVL_INFO) <<
"Ctrl-C appears to have been hit";
112 if (!monitorRegistered_)
115 if (!monitorRegistered_)
123 auto result = transfer_->receiveFragment(*fragmentPtr, timeoutInUsecs_);
127 receivedFragment =
true;
128 fragments_received++;
130 static size_t cntr = 0;
131 auto mod = ++cntr % 10;
145 TLOG(TLVL_INFO) <<
"Received " << cntr << suffix <<
" event, "
146 <<
"seqID == " << fragmentPtr->sequenceID()
147 <<
", type == " << fragmentPtr->typeString();
148 last_received_data_ = std::chrono::steady_clock::now();
153 TLOG(TLVL_ERROR) <<
"Transfer Plugin disconnected or other unrecoverable error. Shutting down.";
164 auto tlvl = TLVL_DEBUG + 33;
165 if (artdaq::TimeUtils::GetElapsedTime(last_report_) > 1.0 && artdaq::TimeUtils::GetElapsedTime(last_received_data_) > 1.0)
168 last_report_ = std::chrono::steady_clock::now();
171 auto last_received_milliseconds = artdaq::TimeUtils::GetElapsedTimeMilliseconds(last_received_data_);
175 TLOG(tlvl) <<
"Timeout occurred in call to transfer_->receiveFragmentFrom; will try again"
176 <<
", status = " << result <<
", last received data " << last_received_milliseconds <<
" ms ago.";
181 ExceptionHandler(ExceptionHandlerRethrow::yes,
182 "Problem receiving data in TransferWrapper::receiveMessage");
186 if (fragmentPtr->type() == artdaq::Fragment::EndOfDataFragmentType)
202 checkIntegrity(*fragmentPtr);
204 if (initialized || fragmentPtr->type() == artdaq::Fragment::InitFragmentType)
207 fragmentPtrs.push_back(std::move(fragmentPtr));
211 if (fragments_received > maxEventsBeforeInit_)
213 throw cet::exception(
"TransferWrapper") <<
"First " << maxEventsBeforeInit_ <<
" events received did not include the \"Init\" event containing necessary info for art; exiting...";
222 std::unordered_map<artdaq::Fragment::type_t, std::unique_ptr<artdaq::Fragments>> output;
224 auto ptrs = receiveMessage();
225 for (
auto& ptr : ptrs)
227 auto fragType = ptr->type();
228 auto fragPtr = ptr.release();
231 if (output.count(fragType) == 0u)
233 output[fragType] = std::make_unique<artdaq::Fragments>();
236 output[fragType]->emplace_back(std::move(*fragPtr));
242 void artdaq::TransferWrapper::checkIntegrity(
const artdaq::Fragment& fragment)
const
244 const size_t artdaqheader = artdaq::detail::RawFragmentHeader::num_words() *
245 sizeof(artdaq::detail::RawFragmentHeader::RawDataType);
246 const auto payload =
static_cast<size_t>(fragment.dataEndBytes() - fragment.dataBeginBytes());
248 const size_t totalsize = fragment.sizeBytes();
250 const auto type =
static_cast<size_t>(fragment.type());
252 if (totalsize != artdaqheader + metadata + payload)
254 std::stringstream errmsg;
255 errmsg <<
"Error: artdaq fragment of type " << fragment.typeString() <<
", sequence ID " << fragment.sequenceID() <<
" has internally inconsistent measures of its size, signalling data corruption: in bytes,"
256 <<
" total size = " << totalsize <<
", artdaq fragment header = " << artdaqheader <<
", metadata = " << metadata <<
", payload = " << payload;
258 TLOG(TLVL_ERROR) << errmsg.str();
260 if (quitOnFragmentIntegrityProblem_)
262 throw cet::exception(
"TransferWrapper") << errmsg.str();
268 auto findloc = std::find(allowedFragmentTypes_.begin(), allowedFragmentTypes_.end(),
static_cast<int>(type));
270 if (findloc == allowedFragmentTypes_.end())
272 std::stringstream errmsg;
273 errmsg <<
"Error: artdaq fragment appears to have type "
274 << type <<
", not found in the allowed fragment types list";
276 TLOG(TLVL_ERROR) << errmsg.str();
277 if (quitOnFragmentIntegrityProblem_)
279 throw cet::exception(
"TransferWrapper") << errmsg.str();
286 void artdaq::TransferWrapper::registerMonitor()
290 transfer_.reset(
nullptr);
295 ExceptionHandler(ExceptionHandlerRethrow::yes,
296 "TransferWrapper: failure in call to MakeTransferPlugin");
299 auto start = std::chrono::steady_clock::now();
300 auto sts = getDispatcherStatus();
301 while (sts !=
"Running" && (runningStateTimeout_ == 0 || TimeUtils::GetElapsedTime(start) < runningStateTimeout_))
303 TLOG(TLVL_DEBUG + 32) <<
"Dispatcher state: " << sts;
304 if (gSignalStatus != 0)
306 TLOG(TLVL_INFO) <<
"Ctrl-C appears to have been hit";
309 TLOG(TLVL_INFO) <<
"Waited " << std::fixed << std::setprecision(2) << TimeUtils::GetElapsedTime(start) <<
" s / " << runningStateTimeout_ <<
" s for Dispatcher to enter the Running state (state=" << sts <<
")";
310 usleep(runningStateInterval_us_);
311 sts = getDispatcherStatus();
313 if (sts !=
"Running")
318 auto dispatcherConfig = pset_.get<fhicl::ParameterSet>(
"dispatcher_config");
324 TLOG(TLVL_INFO) <<
"Attempting to register this monitor (\"" << transfer_->uniqueLabel()
325 <<
"\") with the dispatcher aggregator";
327 auto status = commander_->send_register_monitor(dispatcherConfig.to_string());
329 TLOG(TLVL_INFO) <<
"Response from dispatcher is \"" << status <<
"\"";
331 if (status ==
"Success")
333 monitorRegistered_ =
true;
337 TLOG(TLVL_WARNING) <<
"Error in TransferWrapper: attempt to register with dispatcher did not result in the \"Success\" response";
344 void artdaq::TransferWrapper::unregisterMonitor()
346 if (!monitorRegistered_)
348 TLOG(TLVL_WARNING) <<
"The function to unregister the monitor was called, but the monitor doesn't appear to be registered";
352 auto start_time = std::chrono::steady_clock::now();
354 while (artdaq::TimeUtils::GetElapsedTime(start_time) < 5.0 && waiting)
356 std::string sts = getDispatcherStatus();
363 TLOG(TLVL_INFO) <<
"The Dispatcher returned \"busy\", will wait 0.5s and retry";
368 if (sts !=
"Running" && sts !=
"Ready")
370 TLOG(TLVL_WARNING) <<
"The Dispatcher is not in the Running or Ready state, will not attempt to unregister (state: " << sts <<
")";
377 TLOG(TLVL_WARNING) <<
"A timeout occurred waiting for the Dispatcher to leave the \"busy\" state, will not attempt to unregister";
384 TLOG(TLVL_INFO) <<
"Requesting that this monitor (" << transfer_->uniqueLabel()
385 <<
") be unregistered from the dispatcher aggregator";
387 auto status = commander_->send_unregister_monitor(transfer_->uniqueLabel());
389 TLOG(TLVL_INFO) <<
"Response from dispatcher is \"" << status <<
"\"";
391 if (status ==
"Success")
395 else if (status ==
"busy")
397 TLOG(TLVL_DEBUG + 32) <<
"The Dispatcher returned \"busy\", will retry in 0.5s";
401 TLOG(TLVL_WARNING) <<
"The Dispatcher returned status " << status <<
" when attempting to unregister this monitor!";
408 TLOG(TLVL_INFO) <<
"Successfully unregistered the monitor from the Dispatcher";
409 monitorRegistered_ =
false;
412 std::string artdaq::TransferWrapper::getDispatcherStatus()
416 return commander_->send_status();
418 catch (std::exception
const& ex)
420 TLOG(TLVL_WARNING) <<
"An exception was thrown trying to collect the Dispatcher's status. Most likely cause is the application is no longer running.";
427 if (monitorRegistered_)
435 ExceptionHandler(ExceptionHandlerRethrow::no,
436 "An exception occurred when trying to unregister monitor during TransferWrapper's destruction");
Commandable is the base class for all artdaq components which implement the artdaq state machine...
TransferWrapper(const fhicl::ParameterSet &pset)
TransferWrapper Constructor.
static void CleanUpGlobals()
Clean up statically-allocated Manager class instances.
virtual ~TransferWrapper()
TransferWrapper Destructor.
std::unique_ptr< artdaq::TransferInterface > MakeTransferPlugin(const fhicl::ParameterSet &pset, const std::string &plugin_label, TransferInterface::Role role)
Load a TransferInterface plugin.
artdaq::FragmentPtrs receiveMessage()
Receive a Fragment from the TransferInterface, and send it to art.
This TransferInterface is a Receiver.
volatile std::sig_atomic_t gSignalStatus
Stores singal from signal handler.
std::unique_ptr< artdaq::CommanderInterface > MakeCommanderPlugin(const fhicl::ParameterSet &commander_pset, artdaq::Commandable &commandable)
Load a CommanderInterface plugin.
Value that is to be returned when a Transfer plugin determines that no more data will be arriving...
For code clarity, things checking for successful receive should check retval >= NO_RANK_INFO.
std::unordered_map< artdaq::Fragment::type_t, std::unique_ptr< artdaq::Fragments > > receiveMessages()
Receive all messsages for an event from ArtdaqSharedMemoryService.