artdaq  v3_04_01
SharedMemoryReader.hh
1 #ifndef artdaq_ArtModules_detail_SharedMemoryReader_hh
2 #define artdaq_ArtModules_detail_SharedMemoryReader_hh
3 
4 #include "artdaq/DAQdata/Globals.hh"
5 #include "artdaq-core/Utilities/ExceptionHandler.hh"
6 #include "art/Framework/Core/Frameworkfwd.h"
7 
8 #include "art/Framework/Core/FileBlock.h"
9 #include "art/Framework/Core/ProductRegistryHelper.h"
10 #include "art/Framework/IO/Sources/SourceHelper.h"
11 #include "art/Framework/Principal/EventPrincipal.h"
12 #include "art/Framework/Principal/RunPrincipal.h"
13 #include "art/Framework/Principal/SubRunPrincipal.h"
14 #include "artdaq-core/Core/SharedMemoryManager.hh"
15 #include "artdaq-core/Utilities/TimeUtils.hh"
16 #include "fhiclcpp/ParameterSet.h"
17 #include "artdaq-core/Data/Fragment.hh"
18 #include "artdaq-core/Data/ContainerFragment.hh"
19 #include "artdaq-core/Core/SharedMemoryEventReceiver.hh"
20 #include "art/Framework/IO/Sources/put_product_in_principal.h"
21 #include "canvas/Persistency/Provenance/FileFormatVersion.h"
22 #include <sys/time.h>
23 
24 
25 #include <string>
26 #include <map>
27 #include "artdaq-core/Data/RawEvent.hh"
28 
29 namespace artdaq
30 {
31  namespace detail
32  {
36  template<std::map<artdaq::Fragment::type_t, std::string> getDefaultTypes() = artdaq::Fragment::MakeSystemTypeMap >
38  {
42  SharedMemoryReader(SharedMemoryReader const&) = delete;
43 
49 
50  art::SourceHelper const& pmaker;
51  std::unique_ptr<SharedMemoryEventReceiver> incoming_events;
52  double waiting_time;
54  std::string pretend_module_name;
58  size_t bytesRead;
59  std::chrono::steady_clock::time_point last_read_time;
60  //std::unique_ptr<SharedMemoryManager> data_shm; ///< SharedMemoryManager containing data
61  //std::unique_ptr<SharedMemoryManager> broadcast_shm; ///< SharedMemoryManager containing broadcasts (control Fragments)
62 
77  SharedMemoryReader(fhicl::ParameterSet const& ps,
78  art::ProductRegistryHelper& help,
79  art::SourceHelper const& pm)
80  : pmaker(pm)
81  , waiting_time(ps.get<double>("waiting_time", 86400.0))
82  , resume_after_timeout(ps.get<bool>("resume_after_timeout", true))
83  , pretend_module_name(ps.get<std::string>("raw_data_label", "daq"))
84  , unidentified_instance_name("unidentified")
85  , shutdownMsgReceived(false)
86  , outputFileCloseNeeded(false)
87  , bytesRead(0)
88  , last_read_time(std::chrono::steady_clock::now())
89  , fragment_type_map_(getDefaultTypes())
90  , readNext_calls_(0)
91  {
92 
93  // For testing
94  //if (ps.has_key("buffer_count") && (ps.has_key("max_event_size_bytes") || (ps.has_key("expected_fragments_per_event") && ps.has_key("max_fragment_size_bytes"))))
95  //{
96  // data_shm.reset(new SharedMemoryManager(ps.get<uint32_t>("shared_memory_key", 0xBEE70000 + getppid()), ps.get<int>("buffer_count"), ps.has_key("max_event_size_bytes") ? ps.get<size_t>("max_event_size_bytes") : ps.get<size_t>("expected_fragments_per_event") * ps.get<size_t>("max_fragment_size_bytes")));
97  // broadcast_shm.reset(new SharedMemoryManager(ps.get<uint32_t>("broadcast_shared_memory_key", 0xCEE70000 + getppid()), ps.get<int>("broadcast_buffer_count", 5), ps.get<size_t>("broadcast_buffer_size", 0x100000)));
98  //}
99  incoming_events.reset(new SharedMemoryEventReceiver(ps.get<uint32_t>("shared_memory_key", 0xBEE70000 + getppid()), ps.get<uint32_t>("broadcast_shared_memory_key", 0xCEE70000 + getppid())));
100  my_rank = incoming_events->GetRank();
101 
102  char const* artapp_env = getenv("ARTDAQ_APPLICATION_NAME");
103  std::string artapp_str = "";
104  if (artapp_env != NULL)
105  {
106  artapp_str = std::string(artapp_env) + "_";
107  }
108 
109  app_name = artapp_str + "art" + std::to_string(incoming_events->GetMyId());
110 
111  try {
112  if (metricMan)
113  {
114  metricMan->initialize(ps.get<fhicl::ParameterSet>("metrics", fhicl::ParameterSet()), app_name);
115  metricMan->do_start();
116  }
117  }
118  catch (...)
119  {
120  ExceptionHandler(ExceptionHandlerRethrow::no, "Error loading metrics in SharedMemoryReader()");
121  }
122 
123  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, unidentified_instance_name);
124  for (auto it = fragment_type_map_.begin(); it != fragment_type_map_.end(); ++it)
125  {
126  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, it->second);
127  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, "Container" + it->second);
128  }
129  auto extraTypes = ps.get<std::vector<std::pair<Fragment::type_t, std::string>>>("fragment_type_map", std::vector<std::pair<Fragment::type_t, std::string>>());
130  for (auto it = extraTypes.begin(); it != extraTypes.end(); ++it)
131  {
132  fragment_type_map_[it->first] = it->second;
133  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, it->second);
134  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, "Container" + it->second);
135  }
136  TLOG_INFO("SharedMemoryReader") << "SharedMemoryReader initialized with ParameterSet: " << ps.to_string();
137  //for(auto& type : fragment_type_map_)
138  //{
139  // TLOG_INFO("SharedMemoryReader") << "Fragment Type " << type.second << " has typeid " << type.first ;
140  //}
141  }
142 
151  SharedMemoryReader(fhicl::ParameterSet const& ps,
152  art::ProductRegistryHelper& help,
153  art::SourceHelper const& pm,
154  art::MasterProductRegistry&) : SharedMemoryReader(ps, help, pm)
155  {}
156 
162  }
163 
168 
173  void readFile(std::string const&, art::FileBlock*& fb)
174  {
175  TLOG_ARB(5, "SharedMemoryReader") << "readFile enter/start";
176  fb = new art::FileBlock(art::FileFormatVersion(1, "RawEvent2011"), "nothing");
177  }
178 
183  bool hasMoreData() const { return (!shutdownMsgReceived); }
184 
195  bool readNext(art::RunPrincipal* const & inR,
196  art::SubRunPrincipal* const & inSR,
197  art::RunPrincipal*& outR,
198  art::SubRunPrincipal*& outSR,
199  art::EventPrincipal*& outE)
200  {
201  TLOG_DEBUG("SharedMemoryReader") << "readNext BEGIN";
202  /*if (outputFileCloseNeeded) {
203  outputFileCloseNeeded = false;
204  return false;
205  }*/
206  // Establish default 'results'
207  outR = 0;
208  outSR = 0;
209  outE = 0;
210  // Try to get an event from the queue. We'll continuously loop, either until:
211  // 1) we have read a RawEvent off the queue, or
212  // 2) we have timed out, AND we are told the when we timeout we
213  // should stop.
214  // In any case, if we time out, we emit an informational message.
215 
216  if (shutdownMsgReceived)
217  {
218  TLOG_INFO("SharedMemoryReader") << "Shutdown Message received, returning false (should exit art)";
219  return false;
220  }
221 
222  auto read_start_time = std::chrono::steady_clock::now();
223  start:
224  bool keep_looping = true;
225  bool got_event = false;
226  auto sleepTimeUsec = waiting_time * 1000; // waiting_time * 1000000 us/s / 1000 reps = us/rep
227  if (sleepTimeUsec > 100000) sleepTimeUsec = 100000; // Don't wait longer than 1/10th of a second
228  while (keep_looping)
229  {
230  TLOG_TRACE("SharedMemoryReader") << "ReadyForRead loops BEGIN";
231  keep_looping = false;
232  auto start_time = std::chrono::steady_clock::now();
233  while (!got_event && TimeUtils::GetElapsedTimeMicroseconds(start_time) < 1000)
234  {
235  // BURN CPU for 1 ms!
236  got_event = incoming_events->ReadyForRead();
237  }
238  TLOG_TRACE("SharedMemoryReader") << "ReadyForRead spin end, poll begin";
239  while (!got_event && TimeUtils::GetElapsedTime(start_time) < waiting_time)
240  {
241  got_event = incoming_events->ReadyForRead();
242  if (!got_event)
243  {
244  usleep(sleepTimeUsec);
245  //TLOG_INFO("SharedMemoryReader") << "Waited " << TimeUtils::GetElapsedTime(start_time) << " of " << waiting_time ;
246  }
247  }
248  TLOG_TRACE("SharedMemoryReader") << "ReadyForRead loops END";
249  if (!got_event)
250  {
251  TLOG_INFO("SharedMemoryReader")
252  << "InputFailure: Reading timed out in SharedMemoryReader::readNext()";
253  keep_looping = resume_after_timeout;
254  }
255  }
256 
257  if (!got_event)
258  {
259  TLOG_INFO("SharedMemoryReader") << "Did not receive an event from Shared Memory, returning false";
260  shutdownMsgReceived = true;
261  return false;
262  }
263  TLOG_DEBUG("SharedMemoryReader") << "Got Event!";
264  auto got_event_time = std::chrono::steady_clock::now();
265 
266  auto errflag = false;
267  auto evtHeader = incoming_events->ReadHeader(errflag);
268  if (errflag) goto start; // Buffer was changed out from under reader!
269  auto fragmentTypes = incoming_events->GetFragmentTypes(errflag);
270  if (errflag) goto start; // Buffer was changed out from under reader!
271  if (fragmentTypes.size() == 0)
272  {
273  TLOG_ERROR("SharedMemoryReader") << "Event has no Fragments! Aborting!";
274  incoming_events->ReleaseBuffer();
275  return false;
276  }
277  auto firstFragmentType = *fragmentTypes.begin();
278  TLOG_DEBUG("SharedMemoryReader") << "First Fragment type is " << (int)firstFragmentType << " (" << fragment_type_map_[firstFragmentType] << ")";
279 
280  // We return false, indicating we're done reading, if:
281  // 1) we did not obtain an event, because we timed out and were
282  // configured NOT to keep trying after a timeout, or
283  // 2) the event we read was the end-of-data marker: a null
284  // pointer
285  if (firstFragmentType == Fragment::EndOfDataFragmentType)
286  {
287  TLOG_DEBUG("SharedMemoryReader") << "Received shutdown message, returning false";
288  shutdownMsgReceived = true;
289  incoming_events->ReleaseBuffer();
290  return false;
291  }
292 
293  size_t qsize = incoming_events->ReadReadyCount(); // save the qsize at this point
294 
295  // Check the number of fragments in the RawEvent. If we have a single
296  // fragment and that fragment is marked as EndRun or EndSubrun we'll create
297  // the special principals for that.
298  art::Timestamp currentTime = 0;
299 #if 0
300  art::TimeValue_t lo_res_time = time(0);
301  TLOG_ARB(15, "SharedMemoryReader") << "lo_res_time = " << lo_res_time;
302  currentTime = ((lo_res_time & 0xffffffff) << 32);
303 #endif
304  timespec hi_res_time;
305  int retcode = clock_gettime(CLOCK_REALTIME, &hi_res_time);
306  TLOG_ARB(15, "SharedMemoryReader") << "hi_res_time tv_sec = " << hi_res_time.tv_sec
307  << " tv_nsec = " << hi_res_time.tv_nsec
308  << " (retcode = " << retcode << ")";
309  if (retcode == 0)
310  {
311  currentTime = ((hi_res_time.tv_sec & 0xffffffff) << 32) |
312  (hi_res_time.tv_nsec & 0xffffffff);
313  }
314  else
315  {
316  TLOG_ERROR("SharedMemoryReader") << "Unable to fetch a high-resolution time with clock_gettime for art::Event Timestamp. "
317  << "The art::Event Timestamp will be zero for event " << evtHeader->event_id;
318  }
319 
320  // make new run if inR is 0 or if the run has changed
321  if (inR == 0 || inR->run() != evtHeader->run_id)
322  {
323  outR = pmaker.makeRunPrincipal(evtHeader->run_id,
324  currentTime);
325  }
326 
327  if (firstFragmentType == Fragment::EndOfRunFragmentType)
328  {
329  art::EventID const evid(art::EventID::flushEvent());
330  outR = pmaker.makeRunPrincipal(evid.runID(), currentTime);
331  outSR = pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
332  outE = pmaker.makeEventPrincipal(evid, currentTime);
333  incoming_events->ReleaseBuffer();
334  return true;
335  }
336  else if (firstFragmentType == Fragment::EndOfSubrunFragmentType)
337  {
338  // Check if inR == 0 or is a new run
339  if (inR == 0 || inR->run() != evtHeader->run_id)
340  {
341  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id,
342  evtHeader->subrun_id,
343  currentTime);
344  art::EventID const evid(art::EventID::flushEvent(outSR->id()));
345  outE = pmaker.makeEventPrincipal(evid, currentTime);
346  }
347  else
348  {
349  // If the previous subrun was neither 0 nor flush and was identical with the current
350  // subrun, then it must have been associated with a data event. In that case, we need
351  // to generate a flush event with a valid run but flush subrun and event number in order
352  // to end the subrun.
353  if (inSR != 0 && !inSR->id().isFlush() && inSR->subRun() == evtHeader->subrun_id)
354  {
355  art::EventID const evid(art::EventID::flushEvent(inR->id()));
356  outSR = pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
357  outE = pmaker.makeEventPrincipal(evid, currentTime);
358  // If this is either a new or another empty subrun, then generate a flush event with
359  // valid run and subrun numbers but flush event number
360  //} else if(inSR==0 || inSR->id().isFlush()){
361  }
362  else
363  {
364  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id,
365  evtHeader->subrun_id,
366  currentTime);
367  art::EventID const evid(art::EventID::flushEvent(outSR->id()));
368  outE = pmaker.makeEventPrincipal(evid, currentTime);
369  // Possible error condition
370  //} else {
371  }
372  outR = 0;
373  }
374  //outputFileCloseNeeded = true;
375  incoming_events->ReleaseBuffer();
376  return true;
377  }
378 
379  // make new subrun if inSR is 0 or if the subrun has changed
380  art::SubRunID subrun_check(evtHeader->run_id, evtHeader->subrun_id);
381  if (inSR == 0 || subrun_check != inSR->id())
382  {
383  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id,
384  evtHeader->subrun_id,
385  currentTime);
386  }
387  outE = pmaker.makeEventPrincipal(evtHeader->run_id,
388  evtHeader->subrun_id,
389  evtHeader->event_id,
390  currentTime);
391 
392  // insert the Fragments of each type into the EventPrincipal
393  std::map<Fragment::type_t, std::string>::const_iterator iter_end =
394  fragment_type_map_.end();
395  for (auto& type_code : fragmentTypes)
396  {
397  std::map<Fragment::type_t, std::string>::const_iterator iter =
398  fragment_type_map_.find(type_code);
399  TLOG_TRACE("SharedMemoryReader") << "Before GetFragmentsByType call, type is " << (int)type_code;
400  auto product = incoming_events->GetFragmentsByType(errflag, type_code);
401  TLOG_TRACE("SharedMemoryReader") << "After GetFragmentsByType call";
402  if (errflag) goto start; // Buffer was changed out from under reader!
403  for (auto &frag : *product)
404  bytesRead += frag.sizeBytes();
405  if (iter != iter_end)
406  {
407  if (type_code == artdaq::Fragment::ContainerFragmentType)
408  {
409  std::unordered_map<std::string, std::unique_ptr<Fragments>> derived_fragments;
410  derived_fragments[iter->second] = std::make_unique<Fragments>();
411 
412  for (size_t ii = 0; ii < product->size(); ++ii)
413  {
414  ContainerFragment cf(product->at(ii));
415  auto contained_type = fragment_type_map_.find(cf.fragment_type());
416  if (contained_type != iter_end)
417  {
418  auto label = iter->second + contained_type->second;
419  if (!derived_fragments.count(label))
420  {
421  derived_fragments[label] = std::make_unique<Fragments>();
422  }
423  derived_fragments[label]->emplace_back(std::move(product->at(ii)));
424  }
425  else
426  {
427  derived_fragments[iter->second]->emplace_back(std::move(product->at(ii)));
428  }
429  }
430 
431  for (auto& type : derived_fragments)
432  {
433  put_product_in_principal(std::move(type.second),
434  *outE,
436  type.first);
437  }
438 
439  }
440  else
441  {
442  put_product_in_principal(std::move(product),
443  *outE,
445  iter->second);
446  }
447  }
448  else
449  {
450  put_product_in_principal(std::move(product),
451  *outE,
454  TLOG_WARNING("SharedMemoryReader")
455  << "UnknownFragmentType: The product instance name mapping for fragment type \""
456  << ((int)type_code) << "\" is not known. Fragments of this "
457  << "type will be stored in the event with an instance name of \""
458  << unidentified_instance_name << "\".";
459  }
460  }
461  TLOG_TRACE("SharedMemoryReader") << "After putting fragments in event";
462 
463  auto read_finish_time = std::chrono::steady_clock::now();
464  incoming_events->ReleaseBuffer();
465  auto qcap = incoming_events->size();
466  TLOG_ARB(10, "SharedMemoryReader") << "readNext: bytesRead=" << bytesRead << " qsize=" << qsize << " cap=" << qcap << " metricMan=" << (void*)metricMan.get();
467  if (metricMan)
468  {
469  metricMan->sendMetric("Avg Processing Time", artdaq::TimeUtils::GetElapsedTime(last_read_time, read_start_time), "s", 2, MetricMode::Average);
470  metricMan->sendMetric("Avg Input Wait Time", artdaq::TimeUtils::GetElapsedTime(read_start_time, got_event_time), "s", 3, MetricMode::Average);
471  metricMan->sendMetric("Avg Read Time", artdaq::TimeUtils::GetElapsedTime(got_event_time, read_finish_time), "s", 3, MetricMode::Average);
472  metricMan->sendMetric("bytesRead", bytesRead, "B", 3, MetricMode::LastPoint);
473  if (qcap > 0) metricMan->sendMetric("queue%Used", static_cast<unsigned long int>(qsize * 100 / qcap), "%", 5, MetricMode::LastPoint);
474  }
475 
476  TLOG_TRACE("SharedMemoryReader") << "Returning from readNext";
477  last_read_time = std::chrono::steady_clock::now();
478  return true;
479  }
480 
481  std::map<Fragment::type_t, std::string> fragment_type_map_;
482  unsigned readNext_calls_;
483  };
484  } // detail
485 } // artdaq
486 
487 
488 #endif /* artdaq_ArtModules_detail_SharedMemoryReader_hh */
The SharedMemoryReader is a class which implements the methods needed by art::Source.
unsigned readNext_calls_
The number of times readNext has been called.
SharedMemoryReader(fhicl::ParameterSet const &ps, art::ProductRegistryHelper &help, art::SourceHelper const &pm)
SharedMemoryReader Constructor.
SharedMemoryReader(fhicl::ParameterSet const &ps, art::ProductRegistryHelper &help, art::SourceHelper const &pm, art::MasterProductRegistry &)
SharedMemoryReader Constructor.
static void CleanUpGlobals()
Clean up statically-allocated Manager class instances.
Definition: Globals.hh:150
art::SourceHelper const & pmaker
An art::SourceHelper instance.
SharedMemoryReader & operator=(SharedMemoryReader const &)=delete
Copy Assignment operator is deleted.
double waiting_time
The amount of time to wait for an event from the queue.
bool resume_after_timeout
Whether to resume if the dequeue action times out.
std::string unidentified_instance_name
The name to use for unknown Fragment types.
bool outputFileCloseNeeded
If an explicit output file close message is needed.
std::unique_ptr< SharedMemoryEventReceiver > incoming_events
The events from the EventStore.
virtual ~SharedMemoryReader()
SharedMemoryReader destructor.
size_t bytesRead
running total of number of bytes received
void closeCurrentFile()
Emulate closing a file. No-Op.
std::chrono::steady_clock::time_point last_read_time
Time last read was completed.
std::string pretend_module_name
The module name to store data under.
bool readNext(art::RunPrincipal *const &inR, art::SubRunPrincipal *const &inSR, art::RunPrincipal *&outR, art::SubRunPrincipal *&outSR, art::EventPrincipal *&outE)
Dequeue a RawEvent and declare its Fragment contents to art, creating Run, SubRun, and EventPrincipal objects as necessary.
std::map< Fragment::type_t, std::string > fragment_type_map_
The Fragment type names that this SharedMemoryReader knows about.
bool hasMoreData() const
Whether more data is expected from the SharedMemoryReader.
void readFile(std::string const &, art::FileBlock *&fb)
Emulate opening a file.
SharedMemoryReader(SharedMemoryReader const &)=delete
Copy Constructor is deleted.
bool shutdownMsgReceived
Whether a shutdown message has been received.