artdaq  v3_11_00
TransferWrapper.cc
1 #include "artdaq/DAQdata/Globals.hh"
2 #define TRACE_NAME "TransferWrapper"
3 
4 #include "artdaq-core/Data/Fragment.hh"
5 #include "artdaq-core/Utilities/ExceptionHandler.hh"
6 #include "artdaq-core/Utilities/TimeUtils.hh"
7 #include "artdaq/ArtModules/detail/TransferWrapper.hh"
8 #include "artdaq/DAQdata/NetMonHeader.hh"
9 #include "artdaq/ExternalComms/MakeCommanderPlugin.hh"
10 #include "artdaq/TransferPlugins/MakeTransferPlugin.hh"
11 
12 #include "cetlib/BasicPluginFactory.h"
13 #include "cetlib_except/exception.h"
14 #include "fhiclcpp/ParameterSet.h"
15 
16 #include <csignal>
17 #include <iostream>
18 #include <limits>
19 #include <memory>
20 #include <sstream>
21 #include <string>
22 
23 namespace {
24  volatile std::sig_atomic_t gSignalStatus = 0;
25 }
26 
31 void signal_handler(int signal)
32 {
33  gSignalStatus = signal;
34 }
35 
36 artdaq::TransferWrapper::TransferWrapper(const fhicl::ParameterSet& pset)
37  : timeoutInUsecs_(pset.get<std::size_t>("timeoutInUsecs", 100000))
38  , last_received_data_()
39  , last_report_(std::chrono::steady_clock::now())
40  , transfer_(nullptr)
41  , commander_(nullptr)
42  , pset_(pset)
43  , dispatcherHost_(pset.get<std::string>("dispatcherHost", "localhost"))
44  , dispatcherPort_(pset.get<std::string>("dispatcherPort", "5266"))
45  , serverUrl_(pset.get<std::string>("server_url", "http://" + dispatcherHost_ + ":" + dispatcherPort_ + "/RPC2"))
46  , maxEventsBeforeInit_(pset.get<std::size_t>("maxEventsBeforeInit", 5))
47  , allowedFragmentTypes_(pset.get<std::vector<int>>("allowedFragmentTypes", { 226, 227, 229 }))
48  , runningStateTimeout_(pset.get<double>("dispatcherConnectTimeout", 0))
49  , runningStateInterval_us_(pset.get<size_t>("dispatcherConnectRetryInterval_us", 1000000))
50  , quitOnFragmentIntegrityProblem_(pset.get<bool>("quitOnFragmentIntegrityProblem", true))
51  , multi_run_mode_(pset.get<bool>("allowMultipleRuns", false))
52  , monitorRegistered_(false)
53 {
54  std::signal(SIGINT, signal_handler);
55 
56  try
57  {
58  if (metricMan)
59  {
60  metricMan->initialize(pset.get<fhicl::ParameterSet>("metrics", fhicl::ParameterSet()), "Online Monitor");
61  metricMan->do_start();
62  }
63  }
64  catch (...)
65  {
66  ExceptionHandler(ExceptionHandlerRethrow::no, "TransferWrapper: could not configure metrics");
67  }
68 
69  // Clamp possible values
70  if (runningStateInterval_us_ < 1000)
71  {
72  TLOG(TLVL_WARNING) << "Invalid value " << runningStateInterval_us_ << " us detected for dispatcherConnectRetryInterval_us. Setting to 1000 us";
73  runningStateInterval_us_ = 1000;
74  }
75  if (runningStateInterval_us_ > 30000000)
76  {
77  TLOG(TLVL_WARNING) << "Invalid value " << runningStateInterval_us_ << " us detected for dispatcherConnectRetryInterval_us. Setting to 30,000,000 us";
78  runningStateInterval_us_ = 30000000;
79  }
80 
81  fhicl::ParameterSet new_pset(pset);
82  if (!new_pset.has_key("server_url"))
83  {
84  new_pset.put<std::string>("server_url", serverUrl_);
85  }
86 
88  commander_ = MakeCommanderPlugin(new_pset, c);
89 }
90 
92 {
93  artdaq::FragmentPtrs fragmentPtrs;
94  bool receivedFragment = false;
95  static bool initialized = false;
96  static size_t fragments_received = 0;
97 
98  while (gSignalStatus == 0)
99  {
100  receivedFragment = false;
101  auto fragmentPtr = std::make_unique<artdaq::Fragment>();
102 
103  while (!receivedFragment)
104  {
105  if (gSignalStatus != 0)
106  {
107  TLOG(TLVL_INFO) << "Ctrl-C appears to have been hit";
108  unregisterMonitor();
109  return fragmentPtrs;
110  }
111  if (!monitorRegistered_)
112  {
113  registerMonitor();
114  if (!monitorRegistered_)
115  {
116  return fragmentPtrs;
117  }
118  }
119 
120  try
121  {
122  auto result = transfer_->receiveFragment(*fragmentPtr, timeoutInUsecs_);
123 
125  {
126  receivedFragment = true;
127  fragments_received++;
128 
129  static size_t cntr = 0;
130  auto mod = ++cntr % 10;
131  auto suffix = "-th";
132  if (mod == 1)
133  {
134  suffix = "-st";
135  }
136  if (mod == 2)
137  {
138  suffix = "-nd";
139  }
140  if (mod == 3)
141  {
142  suffix = "-rd";
143  }
144  TLOG(TLVL_INFO) << "Received " << cntr << suffix << " event, "
145  << "seqID == " << fragmentPtr->sequenceID()
146  << ", type == " << fragmentPtr->typeString();
147  last_received_data_ = std::chrono::steady_clock::now();
148  continue;
149  }
151  {
152  TLOG(TLVL_ERROR) << "Transfer Plugin disconnected or other unrecoverable error. Shutting down.";
153  if (multi_run_mode_) {
154  unregisterMonitor();
155  initialized = false;
156  continue;
157  }
158  return fragmentPtrs;
159  }
160  else
161  {
162  auto tlvl = TLVL_TRACE;
163  if (artdaq::TimeUtils::GetElapsedTime(last_report_) > 1.0 && artdaq::TimeUtils::GetElapsedTime(last_received_data_) > 1.0)
164  {
165  tlvl = TLVL_WARNING;
166  last_report_ = std::chrono::steady_clock::now();
167  }
168 
169  auto last_received_milliseconds = artdaq::TimeUtils::GetElapsedTimeMilliseconds(last_received_data_);
170 
171  // 02-Jun-2018, KAB: added status/result printout
172  // to-do: add another else clause that explicitly checks for RECV_TIMEOUT
173  TLOG(tlvl) << "Timeout occurred in call to transfer_->receiveFragmentFrom; will try again"
174  << ", status = " << result << ", last received data " << last_received_milliseconds << " ms ago.";
175  }
176  }
177  catch (...)
178  {
179  ExceptionHandler(ExceptionHandlerRethrow::yes,
180  "Problem receiving data in TransferWrapper::receiveMessage");
181  }
182  }
183 
184  if (fragmentPtr->type() == artdaq::Fragment::EndOfDataFragmentType)
185  {
186  //if (monitorRegistered_)
187  //{
188  // unregisterMonitor();
189  //}
190  if (multi_run_mode_)
191  {
192  unregisterMonitor();
193  initialized = false;
194  continue;
195  }
196 
197  return fragmentPtrs;
198  }
199 
200  checkIntegrity(*fragmentPtr);
201 
202  if (initialized || fragmentPtr->type() == artdaq::Fragment::InitFragmentType)
203  {
204  initialized = true;
205  fragmentPtrs.push_back(std::move(fragmentPtr));
206  break;
207  }
208 
209  if (fragments_received > maxEventsBeforeInit_)
210  {
211  throw cet::exception("TransferWrapper") << "First " << maxEventsBeforeInit_ << " events received did not include the \"Init\" event containing necessary info for art; exiting..."; // NOLINT(cert-err60-cpp)
212  }
213  }
214 
215  return fragmentPtrs;
216 }
217 
218 std::unordered_map<artdaq::Fragment::type_t, std::unique_ptr<artdaq::Fragments>> artdaq::TransferWrapper::receiveMessages()
219 {
220  std::unordered_map<artdaq::Fragment::type_t, std::unique_ptr<artdaq::Fragments>> output;
221 
222  auto ptrs = receiveMessage();
223  for (auto& ptr : ptrs)
224  {
225  auto fragType = ptr->type();
226  auto fragPtr = ptr.release();
227  ptr.reset(nullptr);
228 
229  if (output.count(fragType) == 0u)
230  {
231  output[fragType] = std::make_unique<artdaq::Fragments>();
232  }
233 
234  output[fragType]->emplace_back(std::move(*fragPtr));
235  }
236 
237  return output;
238 }
239 
240 void artdaq::TransferWrapper::checkIntegrity(const artdaq::Fragment& fragment) const
241 {
242  const size_t artdaqheader = artdaq::detail::RawFragmentHeader::num_words() *
243  sizeof(artdaq::detail::RawFragmentHeader::RawDataType);
244  const auto payload = static_cast<size_t>(fragment.dataEndBytes() - fragment.dataBeginBytes());
245  const size_t metadata = sizeof(artdaq::NetMonHeader);
246  const size_t totalsize = fragment.sizeBytes();
247 
248  const auto type = static_cast<size_t>(fragment.type());
249 
250  if (totalsize != artdaqheader + metadata + payload)
251  {
252  std::stringstream errmsg;
253  errmsg << "Error: artdaq fragment of type " << fragment.typeString() << ", sequence ID " << fragment.sequenceID() << " has internally inconsistent measures of its size, signalling data corruption: in bytes,"
254  << " total size = " << totalsize << ", artdaq fragment header = " << artdaqheader << ", metadata = " << metadata << ", payload = " << payload;
255 
256  TLOG(TLVL_ERROR) << errmsg.str();
257 
258  if (quitOnFragmentIntegrityProblem_)
259  {
260  throw cet::exception("TransferWrapper") << errmsg.str(); // NOLINT(cert-err60-cpp)
261  }
262 
263  return;
264  }
265 
266  auto findloc = std::find(allowedFragmentTypes_.begin(), allowedFragmentTypes_.end(), static_cast<int>(type));
267 
268  if (findloc == allowedFragmentTypes_.end())
269  {
270  std::stringstream errmsg;
271  errmsg << "Error: artdaq fragment appears to have type "
272  << type << ", not found in the allowed fragment types list";
273 
274  TLOG(TLVL_ERROR) << errmsg.str();
275  if (quitOnFragmentIntegrityProblem_)
276  {
277  throw cet::exception("TransferWrapper") << errmsg.str(); // NOLINT(cert-err60-cpp)
278  }
279 
280  return;
281  }
282 }
283 
284 void artdaq::TransferWrapper::registerMonitor()
285 {
286  try
287  {
288  transfer_.reset(nullptr);
289  transfer_ = MakeTransferPlugin(pset_, "transfer_plugin", TransferInterface::Role::kReceive);
290  }
291  catch (...)
292  {
293  ExceptionHandler(ExceptionHandlerRethrow::yes,
294  "TransferWrapper: failure in call to MakeTransferPlugin");
295  }
296 
297  auto start = std::chrono::steady_clock::now();
298  auto sts = getDispatcherStatus();
299  while (sts != "Running" && (runningStateTimeout_ == 0 || TimeUtils::GetElapsedTime(start) < runningStateTimeout_))
300  {
301  TLOG(TLVL_DEBUG) << "Dispatcher state: " << sts;
302  if (gSignalStatus != 0)
303  {
304  TLOG(TLVL_INFO) << "Ctrl-C appears to have been hit";
305  return;
306  }
307  TLOG(TLVL_INFO) << "Waited " << std::fixed << std::setprecision(2) << TimeUtils::GetElapsedTime(start) << " s / " << runningStateTimeout_ << " s for Dispatcher to enter the Running state (state=" << sts << ")";
308  usleep(runningStateInterval_us_);
309  sts = getDispatcherStatus();
310  }
311  if (sts != "Running")
312  {
313  return;
314  }
315 
316  auto dispatcherConfig = pset_.get<fhicl::ParameterSet>("dispatcher_config");
317 
318  int retry = 3;
319 
320  while (retry > 0)
321  {
322  TLOG(TLVL_INFO) << "Attempting to register this monitor (\"" << transfer_->uniqueLabel()
323  << "\") with the dispatcher aggregator";
324 
325  auto status = commander_->send_register_monitor(dispatcherConfig.to_string());
326 
327  TLOG(TLVL_INFO) << "Response from dispatcher is \"" << status << "\"";
328 
329  if (status == "Success")
330  {
331  monitorRegistered_ = true;
332  break;
333  }
334 
335  TLOG(TLVL_WARNING) << "Error in TransferWrapper: attempt to register with dispatcher did not result in the \"Success\" response";
336  usleep(100000);
337 
338  retry--;
339  }
340 }
341 
342 void artdaq::TransferWrapper::unregisterMonitor()
343 {
344  if (!monitorRegistered_)
345  {
346  TLOG(TLVL_WARNING) << "The function to unregister the monitor was called, but the monitor doesn't appear to be registered";
347  return;
348  }
349 
350  auto start_time = std::chrono::steady_clock::now();
351  bool waiting = true;
352  while (artdaq::TimeUtils::GetElapsedTime(start_time) < 5.0 && waiting)
353  {
354  std::string sts = getDispatcherStatus();
355 
356  if (sts.empty())
357  return;
358 
359  if (sts == "busy")
360  {
361  TLOG(TLVL_INFO) << "The Dispatcher returned \"busy\", will wait 0.5s and retry";
362  usleep(500000);
363  continue;
364  }
365 
366  if (sts != "Running" && sts != "Ready")
367  {
368  TLOG(TLVL_WARNING) << "The Dispatcher is not in the Running or Ready state, will not attempt to unregister (state: " << sts << ")";
369  return;
370  }
371  waiting = false;
372  }
373  if (waiting)
374  {
375  TLOG(TLVL_WARNING) << "A timeout occurred waiting for the Dispatcher to leave the \"busy\" state, will not attempt to unregister";
376  return;
377  }
378 
379  int retry = 3;
380  while (retry > 0)
381  {
382  TLOG(TLVL_INFO) << "Requesting that this monitor (" << transfer_->uniqueLabel()
383  << ") be unregistered from the dispatcher aggregator";
384 
385  auto status = commander_->send_unregister_monitor(transfer_->uniqueLabel());
386 
387  TLOG(TLVL_INFO) << "Response from dispatcher is \"" << status << "\"";
388 
389  if (status == "Success")
390  {
391  break;
392  }
393  else if (status == "busy")
394  {
395  TLOG(TLVL_DEBUG) << "The Dispatcher returned \"busy\", will retry in 0.5s";
396  }
397  else
398  {
399  TLOG(TLVL_WARNING) << "The Dispatcher returned status " << status << " when attempting to unregister this monitor!";
400  //throw cet::exception("TransferWrapper") << "Error in TransferWrapper: attempt to unregister with dispatcher did not result in the \"Success\" response";
401  }
402  retry--;
403  usleep(500000);
404  }
405 
406  TLOG(TLVL_INFO) << "Successfully unregistered the monitor from the Dispatcher";
407  monitorRegistered_ = false;
408 }
409 
410 std::string artdaq::TransferWrapper::getDispatcherStatus()
411 {
412  try
413  {
414  return commander_->send_status();
415  }
416  catch (std::exception const& ex)
417  {
418  TLOG(TLVL_WARNING) << "An exception was thrown trying to collect the Dispatcher's status. Most likely cause is the application is no longer running.";
419  return "";
420  }
421 }
422 
424 {
425  if (monitorRegistered_)
426  {
427  try
428  {
429  unregisterMonitor();
430  }
431  catch (...)
432  {
433  ExceptionHandler(ExceptionHandlerRethrow::no,
434  "An exception occurred when trying to unregister monitor during TransferWrapper's destruction");
435  }
436  }
438 }
Commandable is the base class for all artdaq components which implement the artdaq state machine...
Definition: Commandable.hh:20
TransferWrapper(const fhicl::ParameterSet &pset)
TransferWrapper Constructor.
static void CleanUpGlobals()
Clean up statically-allocated Manager class instances.
Definition: Globals.hh:150
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.
Header with length information for NetMonTransport messages.
Definition: NetMonHeader.hh:13
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 &gt;= NO_RANK_INFO.
std::unordered_map< artdaq::Fragment::type_t, std::unique_ptr< artdaq::Fragments > > receiveMessages()
Receive all messsages for an event from ArtdaqSharedMemoryService.