1 #ifndef artdaq_ArtModules_detail_SharedMemoryReader_hh
2 #define artdaq_ArtModules_detail_SharedMemoryReader_hh
4 #include "artdaq/DAQdata/Globals.hh"
5 #include "artdaq-core/Utilities/ExceptionHandler.hh"
6 #include "art/Framework/Core/Frameworkfwd.h"
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"
27 #include "artdaq-core/Data/RawEvent.hh"
36 template<std::map<artdaq::Fragment::type_t, std::
string> getDefaultTypes() = artdaq::Fragment::MakeSystemTypeMap >
78 art::ProductRegistryHelper& help,
79 art::SourceHelper
const& pm)
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())));
102 char const* artapp_env = getenv(
"ARTDAQ_APPLICATION_NAME");
103 std::string artapp_str =
"";
104 if (artapp_env != NULL)
106 artapp_str = std::string(artapp_env) +
"_";
109 app_name = artapp_str +
"art" + std::to_string(
incoming_events->GetMyId());
114 metricMan->initialize(ps.get<fhicl::ParameterSet>(
"metrics", fhicl::ParameterSet()), app_name);
115 metricMan->do_start();
120 ExceptionHandler(ExceptionHandlerRethrow::no,
"Error loading metrics in SharedMemoryReader()");
127 help.reconstitutes<Fragments, art::InEvent>(
pretend_module_name,
"Container" + it->second);
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)
134 help.reconstitutes<Fragments, art::InEvent>(
pretend_module_name,
"Container" + it->second);
136 TLOG_INFO(
"SharedMemoryReader") <<
"SharedMemoryReader initialized with ParameterSet: " << ps.to_string();
152 art::ProductRegistryHelper& help,
153 art::SourceHelper
const& pm,
173 void readFile(std::string
const&, art::FileBlock*& fb)
175 TLOG_ARB(5,
"SharedMemoryReader") <<
"readFile enter/start";
176 fb =
new art::FileBlock(art::FileFormatVersion(1,
"RawEvent2011"),
"nothing");
196 art::SubRunPrincipal*
const & inSR,
197 art::RunPrincipal*& outR,
198 art::SubRunPrincipal*& outSR,
199 art::EventPrincipal*& outE)
201 TLOG_DEBUG(
"SharedMemoryReader") <<
"readNext BEGIN";
218 TLOG_INFO(
"SharedMemoryReader") <<
"Shutdown Message received, returning false (should exit art)";
222 auto read_start_time = std::chrono::steady_clock::now();
224 bool keep_looping =
true;
225 bool got_event =
false;
227 if (sleepTimeUsec > 100000) sleepTimeUsec = 100000;
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)
238 TLOG_TRACE(
"SharedMemoryReader") <<
"ReadyForRead spin end, poll begin";
239 while (!got_event && TimeUtils::GetElapsedTime(start_time) <
waiting_time)
244 usleep(sleepTimeUsec);
248 TLOG_TRACE(
"SharedMemoryReader") <<
"ReadyForRead loops END";
251 TLOG_INFO(
"SharedMemoryReader")
252 <<
"InputFailure: Reading timed out in SharedMemoryReader::readNext()";
259 TLOG_INFO(
"SharedMemoryReader") <<
"Did not receive an event from Shared Memory, returning false";
263 TLOG_DEBUG(
"SharedMemoryReader") <<
"Got Event!";
264 auto got_event_time = std::chrono::steady_clock::now();
266 auto errflag =
false;
268 if (errflag)
goto start;
270 if (errflag)
goto start;
271 if (fragmentTypes.size() == 0)
273 TLOG_ERROR(
"SharedMemoryReader") <<
"Event has no Fragments! Aborting!";
277 auto firstFragmentType = *fragmentTypes.begin();
278 TLOG_DEBUG(
"SharedMemoryReader") <<
"First Fragment type is " << (int)firstFragmentType <<
" (" <<
fragment_type_map_[firstFragmentType] <<
")";
285 if (firstFragmentType == Fragment::EndOfDataFragmentType)
287 TLOG_DEBUG(
"SharedMemoryReader") <<
"Received shutdown message, returning false";
298 art::Timestamp currentTime = 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);
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 <<
")";
311 currentTime = ((hi_res_time.tv_sec & 0xffffffff) << 32) |
312 (hi_res_time.tv_nsec & 0xffffffff);
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;
321 if (inR == 0 || inR->run() != evtHeader->run_id)
323 outR =
pmaker.makeRunPrincipal(evtHeader->run_id,
327 if (firstFragmentType == Fragment::EndOfRunFragmentType)
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);
336 else if (firstFragmentType == Fragment::EndOfSubrunFragmentType)
339 if (inR == 0 || inR->run() != evtHeader->run_id)
341 outSR =
pmaker.makeSubRunPrincipal(evtHeader->run_id,
342 evtHeader->subrun_id,
344 art::EventID
const evid(art::EventID::flushEvent(outSR->id()));
345 outE =
pmaker.makeEventPrincipal(evid, currentTime);
353 if (inSR != 0 && !inSR->id().isFlush() && inSR->subRun() == evtHeader->subrun_id)
355 art::EventID
const evid(art::EventID::flushEvent(inR->id()));
356 outSR =
pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
357 outE =
pmaker.makeEventPrincipal(evid, currentTime);
364 outSR =
pmaker.makeSubRunPrincipal(evtHeader->run_id,
365 evtHeader->subrun_id,
367 art::EventID
const evid(art::EventID::flushEvent(outSR->id()));
368 outE =
pmaker.makeEventPrincipal(evid, currentTime);
380 art::SubRunID subrun_check(evtHeader->run_id, evtHeader->subrun_id);
381 if (inSR == 0 || subrun_check != inSR->id())
383 outSR =
pmaker.makeSubRunPrincipal(evtHeader->run_id,
384 evtHeader->subrun_id,
387 outE =
pmaker.makeEventPrincipal(evtHeader->run_id,
388 evtHeader->subrun_id,
393 std::map<Fragment::type_t, std::string>::const_iterator iter_end =
395 for (
auto& type_code : fragmentTypes)
397 std::map<Fragment::type_t, std::string>::const_iterator iter =
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;
403 for (
auto &frag : *product)
405 if (iter != iter_end)
407 if (type_code == artdaq::Fragment::ContainerFragmentType)
409 std::unordered_map<std::string, std::unique_ptr<Fragments>> derived_fragments;
410 derived_fragments[iter->second] = std::make_unique<Fragments>();
412 for (
size_t ii = 0; ii < product->size(); ++ii)
414 ContainerFragment cf(product->at(ii));
416 if (contained_type != iter_end)
418 auto label = iter->second + contained_type->second;
419 if (!derived_fragments.count(label))
421 derived_fragments[label] = std::make_unique<Fragments>();
423 derived_fragments[label]->emplace_back(std::move(product->at(ii)));
427 derived_fragments[iter->second]->emplace_back(std::move(product->at(ii)));
431 for (
auto& type : derived_fragments)
433 put_product_in_principal(std::move(type.second),
442 put_product_in_principal(std::move(product),
450 put_product_in_principal(std::move(product),
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 \""
461 TLOG_TRACE(
"SharedMemoryReader") <<
"After putting fragments in event";
463 auto read_finish_time = std::chrono::steady_clock::now();
466 TLOG_ARB(10,
"SharedMemoryReader") <<
"readNext: bytesRead=" <<
bytesRead <<
" qsize=" << qsize <<
" cap=" << qcap <<
" metricMan=" << (
void*)metricMan.get();
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);
476 TLOG_TRACE(
"SharedMemoryReader") <<
"Returning from readNext";
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.
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.