artdaq  v3_01_00
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 "art/Framework/Core/Frameworkfwd.h"
6 
7 #include "art/Framework/Core/FileBlock.h"
8 #include "art/Framework/Core/ProductRegistryHelper.h"
9 #include "art/Framework/IO/Sources/SourceHelper.h"
10 #include "art/Framework/Principal/EventPrincipal.h"
11 #include "art/Framework/Principal/RunPrincipal.h"
12 #include "art/Framework/Principal/SubRunPrincipal.h"
13 #include "artdaq-core/Core/SharedMemoryManager.hh"
14 #include "artdaq-core/Utilities/TimeUtils.hh"
15 #include "fhiclcpp/ParameterSet.h"
16 #include "artdaq-core/Data/Fragment.hh"
17 #include "artdaq-core/Data/ContainerFragment.hh"
18 #include "artdaq-core/Core/SharedMemoryEventReceiver.hh"
19 #include "art/Framework/IO/Sources/put_product_in_principal.h"
20 #include "canvas/Persistency/Provenance/FileFormatVersion.h"
21 #include <sys/time.h>
22 
23 
24 #include <string>
25 #include <map>
26 #include "artdaq-core/Data/RawEvent.hh"
27 
28 namespace artdaq
29 {
30  namespace detail
31  {
35  template<std::map<artdaq::Fragment::type_t, std::string> getDefaultTypes() = artdaq::Fragment::MakeSystemTypeMap >
37  {
41  SharedMemoryReader(SharedMemoryReader const&) = delete;
42 
48 
49  art::SourceHelper const& pmaker;
50  std::unique_ptr<SharedMemoryEventReceiver> incoming_events;
51  double waiting_time;
53  std::string pretend_module_name;
57  size_t bytesRead;
58  //std::unique_ptr<SharedMemoryManager> data_shm; ///< SharedMemoryManager containing data
59  //std::unique_ptr<SharedMemoryManager> broadcast_shm; ///< SharedMemoryManager containing broadcasts (control Fragments)
60 
75  SharedMemoryReader(fhicl::ParameterSet const& ps,
76  art::ProductRegistryHelper& help,
77  art::SourceHelper const& pm)
78  : pmaker(pm)
79  , waiting_time(ps.get<double>("waiting_time", 86400.0))
80  , resume_after_timeout(ps.get<bool>("resume_after_timeout", true))
81  , pretend_module_name(ps.get<std::string>("raw_data_label", "daq"))
82  , unidentified_instance_name("unidentified")
83  , shutdownMsgReceived(false)
84  , outputFileCloseNeeded(false)
85  , bytesRead(0)
86  , fragment_type_map_(getDefaultTypes())
87  , readNext_calls_(0)
88  {
89  // For testing
90  //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"))))
91  //{
92  // 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")));
93  // 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)));
94  //}
95  incoming_events.reset(new SharedMemoryEventReceiver(ps.get<uint32_t>("shared_memory_key", 0xBEE70000 + getppid()), ps.get<uint32_t>("broadcast_shared_memory_key", 0xCEE70000 + getppid())));
96 
97  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, unidentified_instance_name);
98  for (auto it = fragment_type_map_.begin(); it != fragment_type_map_.end(); ++it)
99  {
100  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, it->second);
101  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, "Container" + it->second);
102  }
103  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>>());
104  for (auto it = extraTypes.begin(); it != extraTypes.end(); ++it)
105  {
106  fragment_type_map_[it->first] = it->second;
107  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, it->second);
108  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, "Container" + it->second);
109  }
110  TLOG_INFO("SharedMemoryReader") << "SharedMemoryReader initialized with ParameterSet: " << ps.to_string() ;
111  //for(auto& type : fragment_type_map_)
112  //{
113  // TLOG_INFO("SharedMemoryReader") << "Fragment Type " << type.second << " has typeid " << std::to_string(type.first) ;
114  //}
115  }
116 
125  SharedMemoryReader(fhicl::ParameterSet const& ps,
126  art::ProductRegistryHelper& help,
127  art::SourceHelper const& pm,
128  art::MasterProductRegistry&) : SharedMemoryReader(ps, help, pm)
129  {}
130 
134  virtual ~SharedMemoryReader() = default;
135 
140 
145  void readFile(std::string const&, art::FileBlock*& fb)
146  {
147  TLOG_ARB(5, "SharedMemoryReader") <<"readFile enter/start";
148  fb = new art::FileBlock(art::FileFormatVersion(1, "RawEvent2011"), "nothing");
149  }
150 
155  bool hasMoreData() const { return (!shutdownMsgReceived); }
156 
167  bool readNext(art::RunPrincipal* const & inR,
168  art::SubRunPrincipal* const & inSR,
169  art::RunPrincipal*& outR,
170  art::SubRunPrincipal*& outSR,
171  art::EventPrincipal*& outE)
172  {
173  TLOG_DEBUG("SharedMemoryReader") << "readNext BEGIN" ;
174  /*if (outputFileCloseNeeded) {
175  outputFileCloseNeeded = false;
176  return false;
177  }*/
178  // Establish default 'results'
179  outR = 0;
180  outSR = 0;
181  outE = 0;
182  // Try to get an event from the queue. We'll continuously loop, either until:
183  // 1) we have read a RawEvent off the queue, or
184  // 2) we have timed out, AND we are told the when we timeout we
185  // should stop.
186  // In any case, if we time out, we emit an informational message.
187 
188  if (shutdownMsgReceived) return false;
189 
190  start:
191  bool keep_looping = true;
192  bool got_event = false;
193  auto sleepTimeUsec = waiting_time * 1000; // waiting_time * 1000000 us/s / 1000 reps = us/rep
194  if (sleepTimeUsec > 100000) sleepTimeUsec = 100000; // Don't wait longer than 1/10th of a second
195  while (keep_looping)
196  {
197  keep_looping = false;
198  auto start_time = std::chrono::steady_clock::now();
199  while (!got_event && TimeUtils::GetElapsedTime(start_time) < waiting_time)
200  {
201  got_event = incoming_events->ReadyForRead();
202  if (!got_event)
203  {
204  usleep(sleepTimeUsec);
205  //TLOG_INFO("SharedMemoryReader") << "Waited " << std::to_string(TimeUtils::GetElapsedTime(start_time)) << " of " << std::to_string(waiting_time) ;
206  }
207  }
208  if (!got_event)
209  {
210  TLOG_INFO("SharedMemoryReader")
211  << "InputFailure: Reading timed out in SharedMemoryReader::readNext()" ;
212  keep_looping = resume_after_timeout;
213  }
214  }
215 
216  if (!got_event)
217  {
218  TLOG_INFO("SharedMemoryReader") << "Did not receive an event from Shared Memory, returning false" ;
219  shutdownMsgReceived = true;
220  return false;
221  }
222  TLOG_DEBUG("SharedMemoryReader") << "Got Event!" ;
223 
224  auto errflag = false;
225  auto evtHeader = incoming_events->ReadHeader(errflag);
226  if (errflag) goto start; // Buffer was changed out from under reader!
227  auto fragmentTypes = incoming_events->GetFragmentTypes(errflag);
228  if (errflag) goto start; // Buffer was changed out from under reader!
229  if (fragmentTypes.size() == 0)
230  {
231  TLOG_ERROR("SharedMemoryReader") << "Event has no Fragments! Aborting!" ;
232  incoming_events->ReleaseBuffer();
233  return false;
234  }
235  auto firstFragmentType = *fragmentTypes.begin();
236  TLOG_DEBUG("SharedMemoryReader") << "First Fragment type is " << std::to_string(firstFragmentType) << " (" << fragment_type_map_[firstFragmentType] << ")" ;
237 
238  // We return false, indicating we're done reading, if:
239  // 1) we did not obtain an event, because we timed out and were
240  // configured NOT to keep trying after a timeout, or
241  // 2) the event we read was the end-of-data marker: a null
242  // pointer
243  if (firstFragmentType == Fragment::EndOfDataFragmentType)
244  {
245  TLOG_DEBUG("SharedMemoryReader") << "Received shutdown message, returning false" ;
246  shutdownMsgReceived = true;
247  incoming_events->ReleaseBuffer();
248  return false;
249  }
250 
251  size_t qsize = incoming_events->ReadReadyCount(); // save the qsize at this point
252 
253  // Check the number of fragments in the RawEvent. If we have a single
254  // fragment and that fragment is marked as EndRun or EndSubrun we'll create
255  // the special principals for that.
256  art::Timestamp currentTime = time(0);
257 
258  // make new run if inR is 0 or if the run has changed
259  if (inR == 0 || inR->run() != evtHeader->run_id)
260  {
261  outR = pmaker.makeRunPrincipal(evtHeader->run_id,
262  currentTime);
263  }
264 
265  if (firstFragmentType == Fragment::EndOfRunFragmentType)
266  {
267  art::EventID const evid(art::EventID::flushEvent());
268  outR = pmaker.makeRunPrincipal(evid.runID(), currentTime);
269  outSR = pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
270  outE = pmaker.makeEventPrincipal(evid, currentTime);
271  incoming_events->ReleaseBuffer();
272  return true;
273  }
274  else if (firstFragmentType == Fragment::EndOfSubrunFragmentType)
275  {
276  // Check if inR == 0 or is a new run
277  if (inR == 0 || inR->run() != evtHeader->run_id)
278  {
279  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id,
280  evtHeader->subrun_id,
281  currentTime);
282  art::EventID const evid(art::EventID::flushEvent(outSR->id()));
283  outE = pmaker.makeEventPrincipal(evid, currentTime);
284  }
285  else
286  {
287  // If the previous subrun was neither 0 nor flush and was identical with the current
288  // subrun, then it must have been associated with a data event. In that case, we need
289  // to generate a flush event with a valid run but flush subrun and event number in order
290  // to end the subrun.
291  if (inSR != 0 && !inSR->id().isFlush() && inSR->subRun() == evtHeader->subrun_id)
292  {
293  art::EventID const evid(art::EventID::flushEvent(inR->id()));
294  outSR = pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
295  outE = pmaker.makeEventPrincipal(evid, currentTime);
296  // If this is either a new or another empty subrun, then generate a flush event with
297  // valid run and subrun numbers but flush event number
298  //} else if(inSR==0 || inSR->id().isFlush()){
299  }
300  else
301  {
302  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id,
303  evtHeader->subrun_id,
304  currentTime);
305  art::EventID const evid(art::EventID::flushEvent(outSR->id()));
306  outE = pmaker.makeEventPrincipal(evid, currentTime);
307  // Possible error condition
308  //} else {
309  }
310  outR = 0;
311  }
312  //outputFileCloseNeeded = true;
313  incoming_events->ReleaseBuffer();
314  return true;
315  }
316 
317  // make new subrun if inSR is 0 or if the subrun has changed
318  art::SubRunID subrun_check(evtHeader->run_id, evtHeader->subrun_id);
319  if (inSR == 0 || subrun_check != inSR->id())
320  {
321  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id,
322  evtHeader->subrun_id,
323  currentTime);
324  }
325  outE = pmaker.makeEventPrincipal(evtHeader->run_id,
326  evtHeader->subrun_id,
327  evtHeader->sequence_id,
328  currentTime);
329 
330  // insert the Fragments of each type into the EventPrincipal
331  std::map<Fragment::type_t, std::string>::const_iterator iter_end =
332  fragment_type_map_.end();
333  for (auto& type_code : fragmentTypes)
334  {
335  std::map<Fragment::type_t, std::string>::const_iterator iter =
336  fragment_type_map_.find(type_code);
337  auto product = incoming_events->GetFragmentsByType(errflag, type_code);
338  if (errflag) goto start; // Buffer was changed out from under reader!
339  for (auto &frag : *product)
340  bytesRead += frag.sizeBytes();
341  if (iter != iter_end)
342  {
343  if (type_code == artdaq::Fragment::ContainerFragmentType)
344  {
345  std::unordered_map<std::string, std::unique_ptr<Fragments>> derived_fragments;
346  derived_fragments[iter->second] = std::make_unique<Fragments>();
347 
348  for (size_t ii = 0; ii < product->size(); ++ii)
349  {
350  ContainerFragment cf(product->at(ii));
351  auto contained_type = fragment_type_map_.find(cf.fragment_type());
352  if (contained_type != iter_end)
353  {
354  auto label = iter->second + contained_type->second;
355  if (!derived_fragments.count(label))
356  {
357  derived_fragments[label] = std::make_unique<Fragments>();
358  }
359  derived_fragments[label]->emplace_back(std::move(product->at(ii)));
360  }
361  else
362  {
363  derived_fragments[iter->second]->emplace_back(std::move(product->at(ii)));
364  }
365  }
366 
367  for (auto& type : derived_fragments)
368  {
369  put_product_in_principal(std::move(type.second),
370  *outE,
372  type.first);
373  }
374 
375  }
376  else
377  {
378  put_product_in_principal(std::move(product),
379  *outE,
381  iter->second);
382  }
383  }
384  else
385  {
386  put_product_in_principal(std::move(product),
387  *outE,
390  TLOG_WARNING("SharedMemoryReader")
391  << "UnknownFragmentType: The product instance name mapping for fragment type \""
392  << ((int)type_code) << "\" is not known. Fragments of this "
393  << "type will be stored in the event with an instance name of \""
394  << unidentified_instance_name << "\"." ;
395  }
396  }
397  incoming_events->ReleaseBuffer();
398  TLOG_ARB(10, "SharedMemoryReader") << "readNext: bytesRead=" << std::to_string(bytesRead) << " qsize=" << std::to_string(qsize) << " cap=" << std::to_string(incoming_events->size()) << " metricMan=" << (void*)metricMan ;
399  if (metricMan)
400  {
401  metricMan->sendMetric("bytesRead", bytesRead, "B", 5, MetricMode::Accumulate, "", true);
402  metricMan->sendMetric("queue%Used", static_cast<unsigned long int>(qsize * 100 / incoming_events->size()), "%", 5, MetricMode::LastPoint, "", true);
403  }
404 
405  return true;
406  }
407 
408  std::map<Fragment::type_t, std::string> fragment_type_map_;
409  unsigned readNext_calls_;
410  };
411  } // detail
412 } // artdaq
413 
414 
415 #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.
virtual ~SharedMemoryReader()=default
SharedMemoryReader destructor.
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.
size_t bytesRead
running total of number of bytes received
void closeCurrentFile()
Emulate closing a file. No-Op.
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.