artdaq_demo_hdf5  v1_03_01
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/FileBlock.h"
15 #include "art/Framework/Core/ProductRegistryHelper.h"
16 #include "art/Framework/IO/Sources/SourceHelper.h"
17 #include "art/Framework/IO/Sources/put_product_in_principal.h"
18 #include "art/Framework/Principal/EventPrincipal.h"
19 #include "art/Framework/Principal/RunPrincipal.h"
20 #include "art/Framework/Principal/SubRunPrincipal.h"
21 #include "art/Framework/Services/Registry/ServiceHandle.h"
22 #include "canvas/Persistency/Provenance/FileFormatVersion.h"
23 #include "fhiclcpp/ParameterSet.h"
24 
25 #include <sys/time.h>
26 #include <map>
27 #include <string>
28 
29 namespace artdaq {
30 namespace detail {
31 
36 {
40  HDFFileReader(HDFFileReader const&) = delete;
41 
46  HDFFileReader& operator=(HDFFileReader const&) = delete;
50  HDFFileReader(HDFFileReader&&) = delete;
51 
57 
58  art::SourceHelper const& pmaker;
59  std::string pretend_module_name;
61  size_t bytesRead;
62  std::chrono::steady_clock::time_point last_read_time;
63  unsigned readNext_calls_;
64  std::unique_ptr<artdaq::hdf5::FragmentDataset> inputFile_;
65 
78  HDFFileReader(fhicl::ParameterSet const& ps,
79  art::ProductRegistryHelper& help,
80  art::SourceHelper const& pm)
81  : pmaker(pm)
82  , pretend_module_name(ps.get<std::string>("raw_data_label", "daq"))
83  , shutdownMsgReceived(false)
84  , bytesRead(0)
85  , last_read_time(std::chrono::steady_clock::now())
86  , readNext_calls_(0)
87  {
88 #if 0
89  volatile bool keep_looping = true;
90  while (keep_looping)
91  {
92  usleep(10000);
93  }
94 #endif
95  art::ServiceHandle<ArtdaqFragmentNamingServiceInterface> translator;
96  inputFile_ = artdaq::hdf5::MakeDatasetPlugin(ps, "dataset");
97 
98  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, translator->GetUnidentifiedInstanceName());
99 
100  // Workaround for #22979
101  help.reconstitutes<Fragments, art::InRun>(pretend_module_name, translator->GetUnidentifiedInstanceName());
102  help.reconstitutes<Fragments, art::InSubRun>(pretend_module_name, translator->GetUnidentifiedInstanceName());
103 
104  try
105  {
106  if (metricMan)
107  {
108  metricMan->initialize(ps.get<fhicl::ParameterSet>("metrics", fhicl::ParameterSet()), "art");
109  metricMan->do_start();
110  }
111  }
112  catch (...)
113  {
114  artdaq::ExceptionHandler(artdaq::ExceptionHandlerRethrow::no, "Error loading metrics in HDFFileReader()");
115  }
116 
117  std::set<std::string> instance_names = translator->GetAllProductInstanceNames();
118  for (const auto& set_iter : instance_names)
119  {
120  help.reconstitutes<Fragments, art::InEvent>(pretend_module_name, set_iter);
121  }
122 
123  TLOG_INFO("HDFFileReader") << "HDFFileReader initialized with ParameterSet: " << ps.to_string();
124  }
125 
129  virtual ~HDFFileReader() {}
130 
135 
140  void readFile(std::string const&, art::FileBlock*& fb)
141  {
142  TLOG_ARB(5, "HDFFileReader") << "readFile enter/start";
143  fb = new art::FileBlock(art::FileFormatVersion(1, "RawEvent2011"), "nothing");
144  }
145 
150  bool hasMoreData() const
151  {
152  TLOG(TLVL_DEBUG, "HDFFileReader") << "hasMoreData returning " << std::boolalpha << !shutdownMsgReceived;
153  return (!shutdownMsgReceived);
154  }
155 
166  bool readNext(art::RunPrincipal* const& inR, art::SubRunPrincipal* const& inSR, art::RunPrincipal*& outR,
167  art::SubRunPrincipal*& outSR, art::EventPrincipal*& outE)
168  {
169  TLOG_DEBUG("HDFFileReader") << "readNext BEGIN";
170  art::ServiceHandle<ArtdaqFragmentNamingServiceInterface> translator;
171 
172  // Establish default 'results'
173  outR = nullptr;
174  outSR = nullptr;
175  outE = nullptr;
176  // Try to get an event from the queue. We'll continuously loop, either until:
177  // 1) we have read a RawEvent off the queue, or
178  // 2) we have timed out, AND we are told the when we timeout we
179  // should stop.
180  // In any case, if we time out, we emit an informational message.
181 
183  {
184  TLOG_INFO("HDFFileReader") << "Shutdown Message received, returning false (should exit art)";
185  return false;
186  }
187 
188  auto read_start_time = std::chrono::steady_clock::now();
189 
190  std::unordered_map<artdaq::Fragment::type_t, std::unique_ptr<artdaq::Fragments>> eventMap = inputFile_->readNextEvent();
191  if (eventMap.empty())
192  {
193  TLOG_ERROR("HDFFileReader") << "No data received, either because of incompatible plugin or end of file. Returning false (should exit art)";
194  shutdownMsgReceived = true;
195  return false;
196  }
197 
198  auto got_event_time = std::chrono::steady_clock::now();
199  auto firstFragmentType = eventMap.begin()->first;
200  TLOG_DEBUG("HDFFileReader") << "First Fragment type is " << static_cast<int>(firstFragmentType) << " ("
201  << translator->GetInstanceNameForType(firstFragmentType) << ")";
202  // We return false, indicating we're done reading, if:
203  // 1) we did not obtain an event, because we timed out and were
204  // configured NOT to keep trying after a timeout, or
205  // 2) the event we read was the end-of-data marker: a null
206  // pointer
207  if (firstFragmentType == Fragment::EndOfDataFragmentType)
208  {
209  TLOG_DEBUG("HDFFileReader") << "Received shutdown message, returning false";
210  shutdownMsgReceived = true;
211  return false;
212  }
213 
214  auto evtHeader = inputFile_->getEventHeader(eventMap.begin()->second->at(0).sequenceID());
215  if (evtHeader == nullptr)
216  {
217  TLOG_DEBUG("HDFFileReader") << "Did not receive Event Header for sequence ID " << eventMap.begin()->second->at(0).sequenceID() << ", skipping event";
218  return true;
219  }
220  else
221  {
222  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;
223  }
224  // Check the number of fragments in the RawEvent. If we have a single
225  // fragment and that fragment is marked as EndRun or EndSubrun we'll create
226  // the special principals for that.
227  art::Timestamp currentTime = 0;
228 #if 0
229  art::TimeValue_t lo_res_time = time(0);
230  TLOG_ARB(15, "HDFFileReader") << "lo_res_time = " << lo_res_time;
231  currentTime = ((lo_res_time & 0xffffffff) << 32);
232 #endif
233  timespec hi_res_time;
234  int retcode = clock_gettime(CLOCK_REALTIME, &hi_res_time);
235  TLOG_ARB(15, "HDFFileReader") << "hi_res_time tv_sec = " << hi_res_time.tv_sec
236  << " tv_nsec = " << hi_res_time.tv_nsec << " (retcode = " << retcode << ")";
237  if (retcode == 0)
238  {
239  currentTime = ((hi_res_time.tv_sec & 0xffffffff) << 32) | (hi_res_time.tv_nsec & 0xffffffff);
240  }
241  else
242  {
243  TLOG_ERROR("HDFFileReader")
244  << "Unable to fetch a high-resolution time with clock_gettime for art::Event Timestamp. "
245  << "The art::Event Timestamp will be zero for event " << evtHeader->event_id;
246  }
247 
248  // make new run if inR is 0 or if the run has changed
249  if (inR == nullptr || inR->run() != evtHeader->run_id)
250  {
251  outR = pmaker.makeRunPrincipal(evtHeader->run_id, currentTime);
252  }
253 
254  if (firstFragmentType == Fragment::EndOfRunFragmentType)
255  {
256  art::EventID const evid(art::EventID::flushEvent());
257  outR = pmaker.makeRunPrincipal(evid.runID(), currentTime);
258  outSR = pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
259  outE = pmaker.makeEventPrincipal(evid, currentTime);
260  return true;
261  }
262  else if (firstFragmentType == Fragment::EndOfSubrunFragmentType)
263  {
264  // Check if inR == 0 or is a new run
265  if (inR == nullptr || inR->run() != evtHeader->run_id)
266  {
267  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
268 
269  art::EventID const evid(art::EventID::flushEvent(outSR->subRunID()));
270 
271  outE = pmaker.makeEventPrincipal(evid, currentTime);
272  }
273  else
274  {
275  // If the previous subrun was neither 0 nor flush and was identical with the current
276  // subrun, then it must have been associated with a data event. In that case, we need
277  // to generate a flush event with a valid run but flush subrun and event number in order
278  // to end the subrun.
279 
280  if (inSR != nullptr && !inSR->subRunID().isFlush() && inSR->subRun() == evtHeader->subrun_id)
281 
282  {
283  art::EventID const evid(art::EventID::flushEvent(inR->runID()));
284 
285  outSR = pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
286  outE = pmaker.makeEventPrincipal(evid, currentTime);
287  // If this is either a new or another empty subrun, then generate a flush event with
288  // valid run and subrun numbers but flush event number
289  //} else if(inSR==0 || inSR->id().isFlush()){
290  }
291  else
292  {
293  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
294 
295  art::EventID const evid(art::EventID::flushEvent(outSR->subRunID()));
296 
297  outE = pmaker.makeEventPrincipal(evid, currentTime);
298  // Possible error condition
299  //} else {
300  }
301  outR = nullptr;
302  }
303  // outputFileCloseNeeded = true;
304  return true;
305  }
306 
307  // make new subrun if inSR is 0 or if the subrun has changed
308  art::SubRunID subrun_check(evtHeader->run_id, evtHeader->subrun_id);
309 
310  if (inSR == nullptr || subrun_check != inSR->subRunID())
311  {
312 
313  outSR = pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
314  }
315  outE = pmaker.makeEventPrincipal(evtHeader->run_id, evtHeader->subrun_id, evtHeader->event_id, currentTime);
316 
317  // insert the Fragments of each type into the EventPrincipal
318  for (auto& fragmentTypePair : eventMap)
319  {
320  auto type_code = fragmentTypePair.first;
321  TLOG_TRACE("HDFFileReader") << "Before GetFragmentsByType call, type is " << static_cast<int>(type_code);
322  TLOG_TRACE("HDFFileReader") << "After GetFragmentsByType call, number of fragments is " << fragmentTypePair.second->size();
323 
324  std::unordered_map<std::string, std::unique_ptr<Fragments>> derived_fragments;
325  for (auto& frag : *fragmentTypePair.second)
326  {
327  bytesRead += frag.sizeBytes();
328 
329  std::pair<bool, std::string> instance_name_result =
330  translator->GetInstanceNameForFragment(frag);
331  std::string label = instance_name_result.second;
332  if (!instance_name_result.first)
333  {
334  TLOG_WARNING("HDFFileReader")
335  << "UnknownFragmentType: The product instance name mapping for fragment type \"" << static_cast<int>(type_code)
336  << "\" is not known. Fragments of this "
337  << "type will be stored in the event with an instance name of \"" << label << "\".";
338  }
339  if (!derived_fragments.count(label))
340  {
341  derived_fragments[label] = std::make_unique<Fragments>();
342  }
343  auto fragSize = frag.size();
344  TLOG_TRACE("HDFFileReader") << "Moving Fragment with size " << fragSize << " from type map (type=" << type_code << ") to derived map label=" << label;
345  derived_fragments[label]->emplace_back(std::move(frag));
346  }
347  TLOG_TRACE("HDFFileReader") << "Placing derived fragments in outE";
348  for (auto& type : derived_fragments)
349  {
350  put_product_in_principal(std::move(type.second),
351  *outE,
353  type.first);
354  }
355  }
356  TLOG_TRACE("HDFFileReader") << "After putting fragments in event";
357 
358  auto read_finish_time = std::chrono::steady_clock::now();
359  TLOG_ARB(10, "HDFFileReader") << "readNext: bytesRead=" << bytesRead << " metricMan=" << static_cast<void*>(metricMan.get());
360  if (metricMan)
361  {
362  metricMan->sendMetric("Avg Processing Time", artdaq::TimeUtils::GetElapsedTime(last_read_time, read_start_time),
363  "s", 2, MetricMode::Average);
364  metricMan->sendMetric("Avg Input Wait Time", artdaq::TimeUtils::GetElapsedTime(read_start_time, got_event_time),
365  "s", 3, MetricMode::Average);
366  metricMan->sendMetric("Avg Read Time", artdaq::TimeUtils::GetElapsedTime(got_event_time, read_finish_time), "s",
367  3, MetricMode::Average);
368  metricMan->sendMetric("bytesRead", bytesRead, "B", 3, MetricMode::LastPoint);
369  }
370 
371  TLOG_TRACE("HDFFileReader") << "Returning from readNext";
372  last_read_time = std::chrono::steady_clock::now();
373  return true;
374  }
375 };
376 } // namespace detail
377 } // namespace artdaq
378 
379 #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.
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.