artdaq_demo_hdf5  v1_00_00
HDFFileReader.hh
1 #ifndef artdaq_ArtModules_detail_HDFFileReader_hh
2 #define artdaq_ArtModules_detail_HDFFileReader_hh
3 
4 #include "artdaq/DAQdata/Globals.hh"
5 
6 #include "artdaq-core/Data/ContainerFragment.hh"
7 #include "artdaq-core/Data/Fragment.hh"
8 #include "artdaq-core/Data/RawEvent.hh"
9 #include "artdaq-core/Utilities/ExceptionHandler.hh"
10 #include "artdaq-core/Utilities/TimeUtils.hh"
11 #include "artdaq-demo-hdf5/HDF5/MakeDatasetPlugin.hh"
12 #include "artdaq/ArtModules/ArtdaqFragmentNamingService.h"
13 
14 #include "art/Framework/Core/Frameworkfwd.h"
15 
16 #include "art/Framework/Core/FileBlock.h"
17 #include "art/Framework/Core/ProductRegistryHelper.h"
18 #include "art/Framework/IO/Sources/SourceHelper.h"
19 #include "art/Framework/IO/Sources/put_product_in_principal.h"
20 #include "art/Framework/Principal/EventPrincipal.h"
21 #include "art/Framework/Principal/RunPrincipal.h"
22 #include "art/Framework/Principal/SubRunPrincipal.h"
23 #include "art/Framework/Services/Registry/ServiceHandle.h"
24 #include "canvas/Persistency/Provenance/FileFormatVersion.h"
25 #include "fhiclcpp/ParameterSet.h"
26 
27 #include <sys/time.h>
28 #include <map>
29 #include <string>
30 
31 namespace artdaq {
32 namespace detail {
33 
38 {
42  HDFFileReader(HDFFileReader const&) = delete;
43 
48  HDFFileReader& operator=(HDFFileReader const&) = delete;
49 
50  art::SourceHelper const& pmaker;
51  std::string pretend_module_name;
53  size_t bytesRead;
54  std::chrono::steady_clock::time_point last_read_time;
55  unsigned readNext_calls_;
56  std::unique_ptr<artdaq::hdf5::FragmentDataset> inputFile_;
57 
70  HDFFileReader(fhicl::ParameterSet const& ps,
71  art::ProductRegistryHelper& help,
72  art::SourceHelper const& pm)
73  : pmaker(pm)
74  , pretend_module_name(ps.get<std::string>("raw_data_label", "daq"))
75  , shutdownMsgReceived(false)
76  , bytesRead(0)
77  , last_read_time(std::chrono::steady_clock::now())
78  , readNext_calls_(0)
79  {
80 #if 0
81  volatile bool keep_looping = true;
82  while (keep_looping)
83  {
84  usleep(10000);
85  }
86 #endif
87  art::ServiceHandle<ArtdaqFragmentNamingServiceInterface> translator;
88  inputFile_ = artdaq::hdf5::MakeDatasetPlugin(ps, "dataset");
89 
90  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, translator->GetUnidentifiedInstanceName());
91 
92  // Workaround for #22979
93  help.reconstitutes<Fragments, art::InRun>(pretend_module_name, translator->GetUnidentifiedInstanceName());
94  help.reconstitutes<Fragments, art::InSubRun>(pretend_module_name, translator->GetUnidentifiedInstanceName());
95 
96  try
97  {
98  if (metricMan)
99  {
100  metricMan->initialize(ps.get<fhicl::ParameterSet>("metrics", fhicl::ParameterSet()), "art");
101  metricMan->do_start();
102  }
103  }
104  catch (...)
105  {
106  artdaq::ExceptionHandler(artdaq::ExceptionHandlerRethrow::no, "Error loading metrics in HDFFileReader()");
107  }
108 
109  std::set<std::string> instance_names = translator->GetAllProductInstanceNames();
110  for (const auto& set_iter : instance_names)
111  {
112  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, set_iter);
113  }
114 
115  TLOG_INFO("HDFFileReader") << "HDFFileReader initialized with ParameterSet: " << ps.to_string();
116  }
117 
118 #if ART_HEX_VERSION < 0x30000
119 
127  HDFFileReader(fhicl::ParameterSet const& ps, art::ProductRegistryHelper& help, art::SourceHelper const& pm,
128  art::MasterProductRegistry&)
129  : HDFFileReader(ps, help, pm) {}
130 #endif
131 
135  virtual ~HDFFileReader() {}
136 
141 
146  void readFile(std::string const&, art::FileBlock*& fb)
147  {
148  TLOG_ARB(5, "HDFFileReader") << "readFile enter/start";
149  fb = new art::FileBlock(art::FileFormatVersion(1, "RawEvent2011"), "nothing");
150  }
151 
156  bool hasMoreData() const
157  {
158  TLOG(TLVL_DEBUG, "HDFFileReader") << "hasMoreData returning " << std::boolalpha << !shutdownMsgReceived;
159  return (!shutdownMsgReceived);
160  }
161 
172  bool readNext(art::RunPrincipal* const& inR, art::SubRunPrincipal* const& inSR, art::RunPrincipal*& outR,
173  art::SubRunPrincipal*& outSR, art::EventPrincipal*& outE)
174  {
175  TLOG_DEBUG("HDFFileReader") << "readNext BEGIN";
176  art::ServiceHandle<ArtdaqFragmentNamingServiceInterface> translator;
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 
189  {
190  TLOG_INFO("HDFFileReader") << "Shutdown Message received, returning false (should exit art)";
191  return false;
192  }
193 
194  auto read_start_time = std::chrono::steady_clock::now();
195 
196  std::unordered_map<artdaq::Fragment::type_t, std::unique_ptr<artdaq::Fragments>> eventMap = inputFile_->readNextEvent();
197  if (eventMap.size() == 0)
198  {
199  TLOG_ERROR("HDFFileReader") << "No data received, either because of incompatible plugin or end of file. Returning false (should exit art)";
200  shutdownMsgReceived = true;
201  return false;
202  }
203 
204  auto got_event_time = std::chrono::steady_clock::now();
205  auto firstFragmentType = eventMap.begin()->first;
206  TLOG_DEBUG("HDFFileReader") << "First Fragment type is " << (int)firstFragmentType << " ("
207  << translator->GetInstanceNameForType(firstFragmentType) << ")";
208  // We return false, indicating we're done reading, if:
209  // 1) we did not obtain an event, because we timed out and were
210  // configured NOT to keep trying after a timeout, or
211  // 2) the event we read was the end-of-data marker: a null
212  // pointer
213  if (firstFragmentType == Fragment::EndOfDataFragmentType)
214  {
215  TLOG_DEBUG("HDFFileReader") << "Received shutdown message, returning false";
216  shutdownMsgReceived = true;
217  return false;
218  }
219 
220  auto evtHeader = inputFile_->getEventHeader(eventMap.begin()->second->at(0).sequenceID());
221  if (evtHeader == nullptr)
222  {
223  TLOG_DEBUG("HDFFileReader") << "Did not receive Event Header for sequence ID " << eventMap.begin()->second->at(0).sequenceID() << ", skipping event";
224  return true;
225  }
226  else
227  {
228  TLOG_TRACE("HDFFileReader") << "EventHeader has Run " << evtHeader->run_id << ", SubRun " << evtHeader->subrun_id << ", Event " << evtHeader->event_id << ", SeqID " << evtHeader->sequence_id << ", IsComplete " << evtHeader->is_complete;
229  }
230  // Check the number of fragments in the RawEvent. If we have a single
231  // fragment and that fragment is marked as EndRun or EndSubrun we'll create
232  // the special principals for that.
233  art::Timestamp currentTime = 0;
234 #if 0
235  art::TimeValue_t lo_res_time = time(0);
236  TLOG_ARB(15, "HDFFileReader") << "lo_res_time = " << lo_res_time;
237  currentTime = ((lo_res_time & 0xffffffff) << 32);
238 #endif
239  timespec hi_res_time;
240  int retcode = clock_gettime(CLOCK_REALTIME, &hi_res_time);
241  TLOG_ARB(15, "HDFFileReader") << "hi_res_time tv_sec = " << hi_res_time.tv_sec
242  << " tv_nsec = " << hi_res_time.tv_nsec << " (retcode = " << retcode << ")";
243  if (retcode == 0)
244  {
245  currentTime = ((hi_res_time.tv_sec & 0xffffffff) << 32) | (hi_res_time.tv_nsec & 0xffffffff);
246  }
247  else
248  {
249  TLOG_ERROR("HDFFileReader")
250  << "Unable to fetch a high-resolution time with clock_gettime for art::Event Timestamp. "
251  << "The art::Event Timestamp will be zero for event " << evtHeader->event_id;
252  }
253 
254  // make new run if inR is 0 or if the run has changed
255  if (inR == 0 || inR->run() != evtHeader->run_id)
256  {
257  outR = pmaker.makeRunPrincipal(evtHeader->run_id, currentTime);
258  }
259 
260  if (firstFragmentType == Fragment::EndOfRunFragmentType)
261  {
262  art::EventID const evid(art::EventID::flushEvent());
263  outR = pmaker.makeRunPrincipal(evid.runID(), currentTime);
264  outSR = pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
265  outE = pmaker.makeEventPrincipal(evid, currentTime);
266  return true;
267  }
268  else if (firstFragmentType == Fragment::EndOfSubrunFragmentType)
269  {
270  // Check if inR == 0 or is a new run
271  if (inR == 0 || inR->run() != evtHeader->run_id)
272  {
273  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
274 #if ART_HEX_VERSION > 0x30000
275  art::EventID const evid(art::EventID::flushEvent(outSR->subRunID()));
276 #else
277  art::EventID const evid(art::EventID::flushEvent(outSR->id()));
278 #endif
279  outE = pmaker.makeEventPrincipal(evid, currentTime);
280  }
281  else
282  {
283  // If the previous subrun was neither 0 nor flush and was identical with the current
284  // subrun, then it must have been associated with a data event. In that case, we need
285  // to generate a flush event with a valid run but flush subrun and event number in order
286  // to end the subrun.
287 #if ART_HEX_VERSION > 0x30000
288  if (inSR != 0 && !inSR->subRunID().isFlush() && inSR->subRun() == evtHeader->subrun_id)
289 #else
290  if (inSR != 0 && !inSR->id().isFlush() && inSR->subRun() == evtHeader->subrun_id)
291 #endif
292  {
293 #if ART_HEX_VERSION > 0x30000
294  art::EventID const evid(art::EventID::flushEvent(inR->runID()));
295 #else
296  art::EventID const evid(art::EventID::flushEvent(inR->id()));
297 #endif
298  outSR = pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
299  outE = pmaker.makeEventPrincipal(evid, currentTime);
300  // If this is either a new or another empty subrun, then generate a flush event with
301  // valid run and subrun numbers but flush event number
302  //} else if(inSR==0 || inSR->id().isFlush()){
303  }
304  else
305  {
306  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
307 #if ART_HEX_VERSION > 0x30000
308  art::EventID const evid(art::EventID::flushEvent(outSR->subRunID()));
309 #else
310  art::EventID const evid(art::EventID::flushEvent(outSR->id()));
311 #endif
312  outE = pmaker.makeEventPrincipal(evid, currentTime);
313  // Possible error condition
314  //} else {
315  }
316  outR = 0;
317  }
318  // outputFileCloseNeeded = true;
319  return true;
320  }
321 
322  // make new subrun if inSR is 0 or if the subrun has changed
323  art::SubRunID subrun_check(evtHeader->run_id, evtHeader->subrun_id);
324 #if ART_HEX_VERSION > 0x30000
325  if (inSR == 0 || subrun_check != inSR->subRunID())
326  {
327 #else
328  if (inSR == 0 || subrun_check != inSR->id())
329  {
330 #endif
331  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
332  }
333  outE = pmaker.makeEventPrincipal(evtHeader->run_id, evtHeader->subrun_id, evtHeader->event_id, currentTime);
334 
335  // insert the Fragments of each type into the EventPrincipal
336  for (auto& fragmentTypePair : eventMap)
337  {
338  auto type_code = fragmentTypePair.first;
339  TLOG_TRACE("HDFFileReader") << "Before GetFragmentsByType call, type is " << (int)type_code;
340  TLOG_TRACE("HDFFileReader") << "After GetFragmentsByType call, number of fragments is " << fragmentTypePair.second->size();
341 
342  std::unordered_map<std::string, std::unique_ptr<Fragments>> derived_fragments;
343  for (auto& frag : *fragmentTypePair.second)
344  {
345  bytesRead += frag.sizeBytes();
346 
347  std::pair<bool, std::string> instance_name_result =
348  translator->GetInstanceNameForFragment(frag);
349  std::string label = instance_name_result.second;
350  if (!instance_name_result.first)
351  {
352  TLOG_WARNING("HDFFileReader")
353  << "UnknownFragmentType: The product instance name mapping for fragment type \"" << ((int)type_code)
354  << "\" is not known. Fragments of this "
355  << "type will be stored in the event with an instance name of \"" << label << "\".";
356  }
357  if (!derived_fragments.count(label))
358  {
359  derived_fragments[label] = std::make_unique<Fragments>();
360  }
361  auto fragSize = frag.size();
362  TLOG_TRACE("HDFFileReader") << "Moving Fragment with size " << fragSize << " from type map (type=" << type_code << ") to derived map label=" << label;
363  derived_fragments[label]->emplace_back(std::move(frag));
364  }
365  TLOG_TRACE("HDFFileReader") << "Placing derived fragments in outE";
366  for (auto& type : derived_fragments)
367  {
368  put_product_in_principal(std::move(type.second),
369  *outE,
371  type.first);
372  }
373  }
374  TLOG_TRACE("HDFFileReader") << "After putting fragments in event";
375 
376  auto read_finish_time = std::chrono::steady_clock::now();
377  TLOG_ARB(10, "HDFFileReader") << "readNext: bytesRead=" << bytesRead << " metricMan=" << (void*)metricMan.get();
378  if (metricMan)
379  {
380  metricMan->sendMetric("Avg Processing Time", artdaq::TimeUtils::GetElapsedTime(last_read_time, read_start_time),
381  "s", 2, MetricMode::Average);
382  metricMan->sendMetric("Avg Input Wait Time", artdaq::TimeUtils::GetElapsedTime(read_start_time, got_event_time),
383  "s", 3, MetricMode::Average);
384  metricMan->sendMetric("Avg Read Time", artdaq::TimeUtils::GetElapsedTime(got_event_time, read_finish_time), "s",
385  3, MetricMode::Average);
386  metricMan->sendMetric("bytesRead", bytesRead, "B", 3, MetricMode::LastPoint);
387  }
388 
389  TLOG_TRACE("HDFFileReader") << "Returning from readNext";
390  last_read_time = std::chrono::steady_clock::now();
391  return true;
392  }
393 };
394 } // namespace detail
395 } // namespace artdaq
396 
397 #endif /* artdaq_ArtModules_detail_HDFFileReader_hh */
The HDFFileReader is a class which implements the methods needed by art::Source.
art::SourceHelper const & pmaker
An art::SourceHelper instance.
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.
HDFFileReader(HDFFileReader const &)=delete
Copy Constructor is deleted.
std::string pretend_module_name
The module name to store data under.
HDFFileReader(fhicl::ParameterSet const &ps, art::ProductRegistryHelper &help, art::SourceHelper const &pm)
HDFFileReader Constructor.
HDFFileReader & operator=(HDFFileReader const &)=delete
Copy Assignment operator is deleted.
bool shutdownMsgReceived
Whether a shutdown message has been received.
void readFile(std::string const &, art::FileBlock *&fb)
Emulate opening a file.
std::unique_ptr< artdaq::hdf5::FragmentDataset > inputFile_
The Dataset plugin which this input source will be reading from.
HDFFileReader(fhicl::ParameterSet const &ps, art::ProductRegistryHelper &help, art::SourceHelper const &pm, art::MasterProductRegistry &)
HDFFileReader Constructor.
virtual ~HDFFileReader()
HDFFileReader destructor.
size_t bytesRead
running total of number of bytes received
unsigned readNext_calls_
The number of times readNext has been called.
void closeCurrentFile()
Emulate closing a file. No-Op.
std::chrono::steady_clock::time_point last_read_time
Time last read was completed.
bool hasMoreData() const
Whether more data is expected from the HDFFileReader.