artdaq  3.12.07
CommandableFragmentGenerator.cc
1 #include "TRACE/tracemf.h" // Pre-empt TRACE/trace.h from Fragment.hh.
2 #include "artdaq/DAQdata/Globals.hh"
3 #define TRACE_NAME (app_name + "_CommandableFragmentGenerator").c_str() // include these 2 first -
4 
5 #include "artdaq/Generators/CommandableFragmentGenerator.hh"
6 
7 #include "artdaq-core/Data/ContainerFragmentLoader.hh"
8 #include "artdaq-core/Data/Fragment.hh"
9 #include "artdaq-core/Utilities/TimeUtils.hh"
11 
12 #include "cetlib_except/exception.h"
13 #include "fhiclcpp/ParameterSet.h"
14 
15 #include <boost/exception/all.hpp>
16 #include <boost/lexical_cast.hpp>
17 #include <boost/thread.hpp>
18 
19 #include <sys/poll.h>
20 #include <algorithm>
21 #include <chrono>
22 #include <exception>
23 #include <fstream>
24 #include <iomanip>
25 #include <iostream>
26 #include <iterator>
27 #include <limits>
28 #include <memory>
29 #include <mutex>
30 #include <thread>
31 
32 #define TLVL_GETNEXT 35
33 #define TLVL_GETNEXT_VERBOSE 36
34 #define TLVL_CHECKSTOP 37
35 #define TLVL_EVCOUNTERINC 38
36 #define TLVL_GETDATALOOP 39
37 #define TLVL_GETDATALOOP_DATABUFFWAIT 40
38 #define TLVL_GETDATALOOP_VERBOSE 41
39 #define TLVL_WAITFORBUFFERREADY 42
40 #define TLVL_GETBUFFERSTATS 43
41 #define TLVL_CHECKDATABUFFER 44
42 #define TLVL_GETMONITORINGDATA 45
43 #define TLVL_APPLYREQUESTS 46
44 #define TLVL_SENDEMPTYFRAGMENTS 47
45 #define TLVL_CHECKWINDOWS 48
46 #define TLVL_EMPTYFRAGMENT 49
47 
49  : mutex_()
50  , useMonitoringThread_(ps.get<bool>("separate_monitoring_thread", false))
51  , monitoringInterval_(ps.get<int64_t>("hardware_poll_interval_us", 0))
52  , isHardwareOK_(true)
53  , run_number_(-1)
54  , subrun_number_(-1)
55  , timeout_(std::numeric_limits<uint64_t>::max())
56  , timestamp_(std::numeric_limits<uint64_t>::max())
57  , should_stop_(true)
58  , exception_(false)
59  , latest_exception_report_("none")
60  , ev_counter_(1)
61  , sleep_on_stop_us_(0)
62 {
63  auto fragment_ids = ps.get<std::vector<artdaq::Fragment::fragment_id_t>>("fragment_ids", std::vector<artdaq::Fragment::fragment_id_t>());
64 
65  TLOG(TLVL_DEBUG + 33) << "artdaq::CommandableFragmentGenerator::CommandableFragmentGenerator(ps)";
66  int fragment_id = ps.get<int>("fragment_id", -99);
67 
68  if (fragment_id != -99)
69  {
70  if (!fragment_ids.empty())
71  {
72  latest_exception_report_ = R"(Error in CommandableFragmentGenerator: can't both define "fragment_id" and "fragment_ids" in FHiCL document)";
73  TLOG(TLVL_ERROR) << latest_exception_report_;
74  throw cet::exception(latest_exception_report_);
75  }
76 
77  fragment_ids.emplace_back(fragment_id);
78  }
79 
80  if(ps.has_key("generated_fragments_per_event")) {
81  TLOG(TLVL_WARNING) << "Ignoring deprecated configuration parameter \"generated_fragments_per_event\"";
82  }
83 
84  int first_fragment_id = std::numeric_limits<int>::max();
85  for (auto& id : fragment_ids)
86  {
87  if (id < first_fragment_id) first_fragment_id = id;
88  expectedTypes_[id] = artdaq::Fragment::EmptyFragmentType;
89  }
90  instance_name_for_metrics_ = "BoardReader." + boost::lexical_cast<std::string>(first_fragment_id);
91 
92  sleep_on_stop_us_ = ps.get<int>("sleep_on_stop_us", 0);
93 }
94 
96 {
97  joinThreads();
98 }
99 
101 {
102  should_stop_ = true;
103  TLOG(TLVL_DEBUG + 32) << "Joining monitoringThread";
104  try
105  {
106  if (monitoringThread_.joinable())
107  {
108  monitoringThread_.join();
109  }
110  }
111  catch (...)
112  {
113  // IGNORED
114  }
115  TLOG(TLVL_DEBUG + 32) << "joinThreads complete";
116 }
117 
119 {
120  bool result = true;
121 
122  if (check_stop()) usleep(sleep_on_stop_us_);
123  if (exception() || should_stop_) return false;
124 
125  if (!useMonitoringThread_ && monitoringInterval_ > 0)
126  {
127  TLOG(TLVL_GETNEXT) << "getNext: Checking whether to collect Monitoring Data";
128  auto now = std::chrono::steady_clock::now();
129 
130  if (TimeUtils::GetElapsedTimeMicroseconds(lastMonitoringCall_, now) >= static_cast<size_t>(monitoringInterval_))
131  {
132  TLOG(TLVL_GETNEXT) << "getNext: Collecting Monitoring Data";
133  isHardwareOK_ = checkHWStatus_();
134  TLOG(TLVL_GETNEXT) << "getNext: isHardwareOK_ is now " << std::boolalpha << isHardwareOK_;
135  lastMonitoringCall_ = now;
136  }
137  }
138 
139  try
140  {
141  std::lock_guard<std::mutex> lk(mutex_);
142  if (!isHardwareOK_)
143  {
144  TLOG(TLVL_ERROR) << "Stopping CFG because the hardware reports bad status!";
145  return false;
146  }
147  TLOG(TLVL_DEBUG + 33) << "getNext: Calling getNext_ w/ ev_counter()=" << ev_counter();
148  try
149  {
150  result = getNext_(output);
151  }
152  catch (...)
153  {
154  throw;
155  }
156  TLOG(TLVL_DEBUG + 33) << "getNext: Done with getNext_ - ev_counter() now " << ev_counter();
157  for (auto& dataIter : output)
158  {
159  TLOG(TLVL_GETNEXT_VERBOSE) << "getNext: getNext_() returned fragment with sequenceID = " << dataIter->sequenceID()
160  << ", type = " << dataIter->typeString() << ", id = " << std::to_string(dataIter->fragmentID())
161  << ", timestamp = " << dataIter->timestamp() << ", and sizeBytes = " << dataIter->sizeBytes();
162 
163  auto fragId = dataIter->fragmentID();
164  auto type = dataIter->type();
165 
166  // ELF, 2020 July 16: System Fragments are excluded from these checks
167  if (Fragment::isSystemFragmentType(type))
168  {
169  continue;
170  }
171 
172  if (!expectedTypes_.count(fragId))
173  {
174  TLOG(TLVL_ERROR) << "Received Fragment with Fragment ID " << fragId << ", which is not in the declared list of Fragment IDs! Aborting!";
175  return false;
176  }
177  if (expectedTypes_[fragId] == Fragment::EmptyFragmentType)
178  expectedTypes_[fragId] = type;
179  else if (expectedTypes_[fragId] != type)
180  {
181  TLOG(TLVL_WARNING) << "Received Fragment with Fragment ID " << fragId << " and type " << dataIter->typeString() << "(" << type << "), which does not match expected type for this ID (" << expectedTypes_[fragId] << ")";
182  }
183  }
184  }
185  catch (const cet::exception& e)
186  {
187  latest_exception_report_ = "cet::exception caught in getNext(): ";
188  latest_exception_report_.append(e.what());
189  TLOG(TLVL_ERROR) << "getNext: cet::exception caught: " << e;
190  set_exception(true);
191  return false;
192  }
193  catch (const boost::exception& e)
194  {
195  latest_exception_report_ = "boost::exception caught in getNext(): ";
196  latest_exception_report_.append(boost::diagnostic_information(e));
197  TLOG(TLVL_ERROR) << "getNext: boost::exception caught: " << boost::diagnostic_information(e);
198  set_exception(true);
199  return false;
200  }
201  catch (const std::exception& e)
202  {
203  latest_exception_report_ = "std::exception caught in getNext(): ";
204  latest_exception_report_.append(e.what());
205  TLOG(TLVL_ERROR) << "getNext: std::exception caught: " << e.what();
206  set_exception(true);
207  return false;
208  }
209  catch (...)
210  {
211  latest_exception_report_ = "Unknown exception caught in getNext().";
212  TLOG(TLVL_ERROR) << "getNext: unknown exception caught";
213  set_exception(true);
214  return false;
215  }
216 
217  if (!result)
218  {
219  TLOG(TLVL_DEBUG + 32) << "getNext: Either getNext_ or applyRequests returned false, stopping";
220  }
221 
222  if (metricMan && !output.empty())
223  {
224  auto timestamp = output.front()->timestamp();
225 
226  if (output.size() > 1)
227  { // Only bother sorting if >1 entry
228  for (auto& outputfrag : output)
229  {
230  if (outputfrag->timestamp() > timestamp)
231  {
232  timestamp = outputfrag->timestamp();
233  }
234  }
235  }
236 
237  metricMan->sendMetric("Last Timestamp", timestamp, "Ticks", 1, MetricMode::LastPoint);
238  }
239 
240  return result;
241 }
242 
244 {
245  TLOG(TLVL_CHECKSTOP) << "CFG::check_stop: should_stop=" << should_stop() << ", exception status =" << int(exception());
246 
247  if (!should_stop()) return false;
248 
249  return true;
250 }
251 
253 {
254  TLOG(TLVL_EVCOUNTERINC) << "ev_counter_inc: Incrementing ev_counter from " << ev_counter() << " by " << step;
255  return ev_counter_.fetch_add(step);
256 } // returns the prev value
257 
258 void artdaq::CommandableFragmentGenerator::StartCmd(int run, uint64_t timeout, uint64_t timestamp)
259 {
260  TLOG(TLVL_DEBUG + 33) << "Start Command received.";
261  if (run < 0)
262  {
263  TLOG(TLVL_ERROR) << "negative run number";
264  throw cet::exception("CommandableFragmentGenerator") << "negative run number"; // NOLINT(cert-err60-cpp)
265  }
266 
267  timeout_ = timeout;
268  timestamp_ = timestamp;
269  ev_counter_.store(1);
270 
271  should_stop_.store(false);
272  exception_.store(false);
273  run_number_ = run;
274  subrun_number_ = 1;
275  latest_exception_report_ = "none";
276 
277  start();
278 
279  std::unique_lock<std::mutex> lk(mutex_);
280  if (useMonitoringThread_) startMonitoringThread();
281  TLOG(TLVL_DEBUG + 33) << "Start Command complete.";
282 }
283 
284 void artdaq::CommandableFragmentGenerator::StopCmd(uint64_t timeout, uint64_t timestamp)
285 {
286  TLOG(TLVL_DEBUG + 33) << "Stop Command received.";
287 
288  timeout_ = timeout;
289  timestamp_ = timestamp;
290 
291  stopNoMutex();
292  should_stop_.store(true);
293  std::unique_lock<std::mutex> lk(mutex_);
294  stop();
295 
296  joinThreads();
297  TLOG(TLVL_DEBUG + 33) << "Stop Command complete.";
298 }
299 
300 void artdaq::CommandableFragmentGenerator::PauseCmd(uint64_t timeout, uint64_t timestamp)
301 {
302  TLOG(TLVL_DEBUG + 33) << "Pause Command received.";
303  timeout_ = timeout;
304  timestamp_ = timestamp;
305 
306  pauseNoMutex();
307  should_stop_.store(true);
308  std::unique_lock<std::mutex> lk(mutex_);
309 
310  pause();
311 }
312 
313 void artdaq::CommandableFragmentGenerator::ResumeCmd(uint64_t timeout, uint64_t timestamp)
314 {
315  TLOG(TLVL_DEBUG + 33) << "Resume Command received.";
316  timeout_ = timeout;
317  timestamp_ = timestamp;
318 
319  subrun_number_ += 1;
320  should_stop_ = false;
321 
322  // no lock required: thread not started yet
323  resume();
324 
325  std::unique_lock<std::mutex> lk(mutex_);
326  // if (useDataThread_) startDataThread();
327  // if (useMonitoringThread_) startMonitoringThread();
328  TLOG(TLVL_DEBUG + 33) << "Resume Command complete.";
329 }
330 
331 std::string artdaq::CommandableFragmentGenerator::ReportCmd(std::string const& which)
332 {
333  TLOG(TLVL_DEBUG + 33) << "Report Command received.";
334  std::lock_guard<std::mutex> lk(mutex_);
335 
336  // 14-May-2015, KAB: please see the comments associated with the report()
337  // methods in the CommandableFragmentGenerator.hh file for more information
338  // on the use of those methods in this method.
339 
340  // check if the child class has something meaningful for this request
341  std::string childReport = reportSpecific(which);
342  if (childReport.length() > 0) { return childReport; }
343 
344  // handle the requests that we can take care of at this level
345  if (which == "latest_exception")
346  {
347  return latest_exception_report_;
348  }
349 
350  // check if the child class has provided a catch-all report function
351  childReport = report();
352  if (childReport.length() > 0) { return childReport; }
353 
354  // ELF: 5/31/2019: Let BoardReaderCore's report handle this...
355  /*
356  // if we haven't been able to come up with any report so far, say so
357  std::string tmpString = "The \"" + which + "\" command is not ";
358  tmpString.append("currently supported by the ");
359  tmpString.append(metricsReportingInstanceName());
360  tmpString.append(" fragment generator.");
361  */
362  TLOG(TLVL_DEBUG + 33) << "Report Command complete.";
363  return ""; // tmpString;
364 }
365 
366 // Default implemenetations of state functions
368 {
369 #pragma message "Using default implementation of CommandableFragmentGenerator::pauseNoMutex()"
370 }
371 
373 {
374 #pragma message "Using default implementation of CommandableFragmentGenerator::pause()"
375 }
376 
378 #pragma message "Using default implementation of CommandableFragmentGenerator::resume()"
379 }
380 
382 {
383 #pragma message "Using default implementation of CommandableFragmentGenerator::report()"
384  return "";
385 }
386 
387 std::string artdaq::CommandableFragmentGenerator::reportSpecific(std::string const& /*unused*/)
388 {
389 #pragma message "Using default implementation of CommandableFragmentGenerator::reportSpecific(std::string)"
390  return "";
391 }
392 
394 {
395 #pragma message "Using default implementation of CommandableFragmentGenerator::checkHWStatus_()"
396  return true;
397 }
398 
399 bool artdaq::CommandableFragmentGenerator::metaCommand(std::string const& /*unused*/, std::string const& /*unused*/)
400 {
401 #pragma message "Using default implementation of CommandableFragmentGenerator::metaCommand(std::string, std::string)"
402  return true;
403 }
404 
406 {
407  if (monitoringThread_.joinable())
408  {
409  monitoringThread_.join();
410  }
411  TLOG(TLVL_INFO) << "Starting Hardware Monitoring Thread";
412  try
413  {
414  monitoringThread_ = boost::thread(&CommandableFragmentGenerator::getMonitoringDataLoop, this);
415  char tname[16]; // Size 16 - see man page pthread_setname_np(3) and/or prctl(2)
416  snprintf(tname, sizeof(tname) - 1, "%d-CFGMon", my_rank); // NOLINT
417  tname[sizeof(tname) - 1] = '\0'; // assure term. snprintf is not too evil :)
418  auto handle = monitoringThread_.native_handle();
419  pthread_setname_np(handle, tname);
420  }
421  catch (const boost::exception& e)
422  {
423  TLOG(TLVL_ERROR) << "Caught boost::exception starting Hardware Monitoring thread: " << boost::diagnostic_information(e) << ", errno=" << errno;
424  throw cet::exception("ThreadError") << "Caught boost::exception starting Hardware Monitoring thread: " << boost::diagnostic_information(e) << ", errno=" << errno << std::endl;
425  }
426 }
427 
429 {
430  while (!should_stop())
431  {
432  if (should_stop() || monitoringInterval_ <= 0)
433  {
434  TLOG(TLVL_DEBUG + 32) << "getMonitoringDataLoop: should_stop() is " << std::boolalpha << should_stop()
435  << " and monitoringInterval is " << monitoringInterval_ << ", returning";
436  return;
437  }
438  TLOG(TLVL_GETMONITORINGDATA) << "getMonitoringDataLoop: Determining whether to call checkHWStatus_";
439 
440  auto now = std::chrono::steady_clock::now();
441  if (TimeUtils::GetElapsedTimeMicroseconds(lastMonitoringCall_, now) >= static_cast<size_t>(monitoringInterval_))
442  {
443  isHardwareOK_ = checkHWStatus_();
444  TLOG(TLVL_GETMONITORINGDATA) << "getMonitoringDataLoop: isHardwareOK_ is now " << std::boolalpha << isHardwareOK_;
445  lastMonitoringCall_ = now;
446  }
447  usleep(monitoringInterval_ / 10);
448  }
449 }
CommandableFragmentGenerator(const fhicl::ParameterSet &ps)
CommandableFragmentGenerator Constructor.
virtual bool checkHWStatus_()
Check any relavent hardware status registers. Return false if an error condition exists that should h...
virtual ~CommandableFragmentGenerator()
CommandableFragmentGenerator Destructor.
void getMonitoringDataLoop()
This function regularly calls checkHWStatus_(), and sets the isHardwareOK flag accordingly.
artdaq::Fragment::fragment_id_t fragment_id() const
Get the Fragment ID of this Fragment generator.
std::string ReportCmd(std::string const &which="")
Get a report about a user-specified run-time quantity.
virtual bool metaCommand(std::string const &command, std::string const &arg)
The meta-command is used for implementing user-specific commands in a CommandableFragmentGenerator.
void StopCmd(uint64_t timeout, uint64_t timestamp)
Stop the CommandableFragmentGenerator.
void StartCmd(int run, uint64_t timeout, uint64_t timestamp)
Start the CommandableFragmentGenerator.
virtual void pauseNoMutex()
On call to PauseCmd, pauseNoMutex() is called prior to PauseCmd acquiring the mutex ...
bool check_stop()
Routine used by applyRequests to make sure that all outstanding requests have been fulfilled before r...
void ResumeCmd(uint64_t timeout, uint64_t timestamp)
Resume the CommandableFragmentGenerator.
bool getNext(FragmentPtrs &output) overridefinal
getNext calls either applyRequests or getNext_ to get any data that is ready to be sent to the EventB...
void PauseCmd(uint64_t timeout, uint64_t timestamp)
Pause the CommandableFragmentGenerator.
void startMonitoringThread()
Function that launches the monitoring thread (getMonitoringDataLoop())
virtual void pause()
If a CommandableFragmentGenerator subclass is reading from hardware, the implementation of pause() sh...
virtual void resume()
The subrun number will be incremented before a call to resume.
virtual std::string report()
Let&#39;s say that the contract with the report() functions is that they return a non-empty string if the...
size_t ev_counter_inc(size_t step=1)
Increment the event counter.
virtual std::string reportSpecific(std::string const &what)
Report the status of a specific quantity
void joinThreads()
Join any data-taking threads. Should be called when destructing CommandableFragmentGenerator.