1 #ifndef artdaq_ArtModules_detail_SharedMemoryReader_hh
2 #define artdaq_ArtModules_detail_SharedMemoryReader_hh
4 #include "art/Framework/Core/Frameworkfwd.h"
5 #include "artdaq-core/Utilities/ExceptionHandler.hh"
6 #include "artdaq/DAQdata/Globals.hh"
9 #include "art/Framework/Core/FileBlock.h"
10 #include "art/Framework/Core/ProductRegistryHelper.h"
11 #include "art/Framework/IO/Sources/SourceHelper.h"
12 #include "art/Framework/IO/Sources/put_product_in_principal.h"
13 #include "art/Framework/Principal/EventPrincipal.h"
14 #include "art/Framework/Principal/RunPrincipal.h"
15 #include "art/Framework/Principal/SubRunPrincipal.h"
16 #include "artdaq-core/Core/SharedMemoryEventReceiver.hh"
17 #include "artdaq-core/Core/SharedMemoryManager.hh"
18 #include "artdaq-core/Data/ContainerFragment.hh"
19 #include "artdaq-core/Data/Fragment.hh"
20 #include "artdaq-core/Utilities/TimeUtils.hh"
21 #include "canvas/Persistency/Provenance/FileFormatVersion.h"
22 #include "fhiclcpp/ParameterSet.h"
26 #include "artdaq-core/Data/RawEvent.hh"
44 virtual void SetBasicTypes(std::map<Fragment::type_t, std::string>
const& type_map)
52 virtual void AddExtraType(artdaq::Fragment::type_t type_id, std::string type_name)
54 type_map_[type_id] = type_name;
63 if (type_map_.count(type_id) > 0) {
return type_map_[type_id]; }
64 return unidentified_instance_name;
74 std::set<std::string> output;
75 for (
const auto& map_iter : type_map_)
77 std::string instance_name = map_iter.second;
78 if (!output.count(instance_name))
80 output.insert(instance_name);
81 TLOG_TRACE(
"DefaultFragmentTypeTranslator") <<
"Adding product instance name \"" << map_iter.second
82 <<
"\" to list of expected names";
86 auto container_type = type_map_.find(Fragment::type_t(artdaq::Fragment::ContainerFragmentType));
87 if (container_type != type_map_.end())
89 std::string container_type_name = container_type->second;
90 std::set<std::string> tmp_copy = output;
91 for (
const auto& set_iter : tmp_copy)
93 output.insert(container_type_name + set_iter);
106 virtual std::pair<bool, std::string>
109 auto type_map_end = type_map_.end();
110 bool success_code =
true;
111 std::string instance_name;
113 auto primary_type = type_map_.find(fragment.type());
114 if (primary_type != type_map_end)
116 instance_name = primary_type->second;
117 if (fragment.type() == artdaq::Fragment::ContainerFragmentType)
119 artdaq::ContainerFragment cf(fragment);
120 auto contained_type = type_map_.find(cf.fragment_type());
121 if (contained_type != type_map_end)
123 instance_name += contained_type->second;
129 instance_name = unidentified_instance_name;
130 success_code =
false;
133 return std::make_pair(success_code, instance_name);
137 std::map<Fragment::type_t, std::string> type_map_;
143 template<std::map<artdaq::Fragment::type_t, std::
string> getDefaultTypes() = artdaq::Fragment::MakeSystemTypeMap,
144 class FTT = artdaq::detail::DefaultFragmentTypeTranslator>
187 art::ProductRegistryHelper& help,
188 art::SourceHelper
const& pm)
211 new SharedMemoryEventReceiver(ps.get<uint32_t>(
"shared_memory_key", 0xBEE70000 + getppid()),
212 ps.get<uint32_t>(
"broadcast_shared_memory_key", 0xCEE70000 + getppid())));
214 TLOG(TLVL_INFO,
"SharedMemoryReader") <<
"Rank set to " << my_rank;
216 char const* artapp_env = getenv(
"ARTDAQ_APPLICATION_NAME");
217 std::string artapp_str =
"";
218 if (artapp_env != NULL)
220 artapp_str = std::string(artapp_env) +
"_";
223 app_name = artapp_str +
"art" + std::to_string(
incoming_events->GetMyId());
225 artapp_env = getenv(
"ARTDAQ_RANK");
226 if (artapp_env != NULL && my_rank < 0)
228 my_rank = std::atoi(artapp_env);
230 TLOG(TLVL_INFO) <<
"app_name is " << app_name <<
", rank " << my_rank;
236 metricMan->initialize(ps.get<fhicl::ParameterSet>(
"metrics", fhicl::ParameterSet()), app_name);
237 metricMan->do_start();
242 ExceptionHandler(ExceptionHandlerRethrow::no,
"Error loading metrics in SharedMemoryReader()");
247 translator_.SetBasicTypes(getDefaultTypes());
248 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>>());
249 for (
auto it = extraTypes.begin(); it != extraTypes.end(); ++it)
251 translator_.AddExtraType(it->first, it->second);
253 std::set<std::string> instance_names = translator_.GetAllProductInstanceNames();
254 for (
const auto& set_iter : instance_names)
259 TLOG_INFO(
"SharedMemoryReader") <<
"SharedMemoryReader initialized with ParameterSet: " << ps.to_string();
262 #if ART_HEX_VERSION < 0x30000
271 SharedMemoryReader(fhicl::ParameterSet
const& ps, art::ProductRegistryHelper& help, art::SourceHelper
const& pm,
272 art::MasterProductRegistry&)
290 void readFile(std::string
const&, art::FileBlock*& fb)
292 TLOG_ARB(5,
"SharedMemoryReader") <<
"readFile enter/start";
293 fb =
new art::FileBlock(art::FileFormatVersion(1,
"RawEvent2011"),
"nothing");
312 bool readNext(art::RunPrincipal*
const& inR, art::SubRunPrincipal*
const& inSR, art::RunPrincipal*& outR,
313 art::SubRunPrincipal*& outSR, art::EventPrincipal*& outE)
315 TLOG_DEBUG(
"SharedMemoryReader") <<
"readNext BEGIN";
332 TLOG_INFO(
"SharedMemoryReader") <<
"Shutdown Message received, returning false (should exit art)";
336 auto read_start_time = std::chrono::steady_clock::now();
338 bool keep_looping =
true;
339 bool got_event =
false;
341 if (sleepTimeUsec > 100000) sleepTimeUsec = 100000;
344 TLOG_TRACE(
"SharedMemoryReader") <<
"ReadyForRead loops BEGIN";
345 keep_looping =
false;
346 auto start_time = std::chrono::steady_clock::now();
347 while (!got_event && TimeUtils::GetElapsedTimeMicroseconds(start_time) < 1000)
352 TLOG_TRACE(
"SharedMemoryReader") <<
"ReadyForRead spin end, poll begin";
353 while (!got_event && TimeUtils::GetElapsedTime(start_time) <
waiting_time)
358 usleep(sleepTimeUsec);
363 TLOG_TRACE(
"SharedMemoryReader") <<
"ReadyForRead loops END";
366 TLOG_INFO(
"SharedMemoryReader") <<
"InputFailure: Reading timed out in SharedMemoryReader::readNext()";
373 TLOG_INFO(
"SharedMemoryReader") <<
"Did not receive an event from Shared Memory, returning false";
377 TLOG_DEBUG(
"SharedMemoryReader") <<
"Got Event!";
378 auto got_event_time = std::chrono::steady_clock::now();
380 auto errflag =
false;
382 if (errflag)
goto start;
384 if (errflag)
goto start;
385 if (fragmentTypes.size() == 0)
387 TLOG_ERROR(
"SharedMemoryReader") <<
"Event has no Fragments! Aborting!";
391 auto firstFragmentType = *fragmentTypes.begin();
392 TLOG_DEBUG(
"SharedMemoryReader") <<
"First Fragment type is " << (int)firstFragmentType <<
" ("
399 if (firstFragmentType == Fragment::EndOfDataFragmentType)
401 TLOG_DEBUG(
"SharedMemoryReader") <<
"Received shutdown message, returning false";
412 art::Timestamp currentTime = 0;
414 art::TimeValue_t lo_res_time = time(0);
415 TLOG_ARB(15,
"SharedMemoryReader") <<
"lo_res_time = " << lo_res_time;
416 currentTime = ((lo_res_time & 0xffffffff) << 32);
418 timespec hi_res_time;
419 int retcode = clock_gettime(CLOCK_REALTIME, &hi_res_time);
420 TLOG_ARB(15,
"SharedMemoryReader") <<
"hi_res_time tv_sec = " << hi_res_time.tv_sec
421 <<
" tv_nsec = " << hi_res_time.tv_nsec <<
" (retcode = " << retcode <<
")";
424 currentTime = ((hi_res_time.tv_sec & 0xffffffff) << 32) | (hi_res_time.tv_nsec & 0xffffffff);
428 TLOG_ERROR(
"SharedMemoryReader")
429 <<
"Unable to fetch a high-resolution time with clock_gettime for art::Event Timestamp. "
430 <<
"The art::Event Timestamp will be zero for event " << evtHeader->event_id;
434 if (inR == 0 || inR->run() != evtHeader->run_id)
436 outR =
pmaker.makeRunPrincipal(evtHeader->run_id, currentTime);
439 if (firstFragmentType == Fragment::EndOfRunFragmentType)
441 art::EventID
const evid(art::EventID::flushEvent());
442 outR =
pmaker.makeRunPrincipal(evid.runID(), currentTime);
443 outSR =
pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
444 outE =
pmaker.makeEventPrincipal(evid, currentTime);
448 else if (firstFragmentType == Fragment::EndOfSubrunFragmentType)
451 if (inR == 0 || inR->run() != evtHeader->run_id)
453 outSR =
pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
454 #if ART_HEX_VERSION > 0x30000
455 art::EventID
const evid(art::EventID::flushEvent(outSR->subRunID()));
457 art::EventID
const evid(art::EventID::flushEvent(outSR->id()));
459 outE =
pmaker.makeEventPrincipal(evid, currentTime);
467 #if ART_HEX_VERSION > 0x30000
468 if (inSR != 0 && !inSR->subRunID().isFlush() && inSR->subRun() == evtHeader->subrun_id)
470 if (inSR != 0 && !inSR->id().isFlush() && inSR->subRun() == evtHeader->subrun_id)
473 #if ART_HEX_VERSION > 0x30000
474 art::EventID
const evid(art::EventID::flushEvent(inR->runID()));
476 art::EventID
const evid(art::EventID::flushEvent(inR->id()));
478 outSR =
pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
479 outE =
pmaker.makeEventPrincipal(evid, currentTime);
486 outSR =
pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
487 #if ART_HEX_VERSION > 0x30000
488 art::EventID
const evid(art::EventID::flushEvent(outSR->subRunID()));
490 art::EventID
const evid(art::EventID::flushEvent(outSR->id()));
492 outE =
pmaker.makeEventPrincipal(evid, currentTime);
504 art::SubRunID subrun_check(evtHeader->run_id, evtHeader->subrun_id);
505 #if ART_HEX_VERSION > 0x30000
506 if (inSR == 0 || subrun_check != inSR->subRunID())
509 if (inSR == 0 || subrun_check != inSR->id())
512 outSR =
pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
514 outE =
pmaker.makeEventPrincipal(evtHeader->run_id, evtHeader->subrun_id, evtHeader->event_id, currentTime);
516 double fragmentLatency = 0;
517 double fragmentLatencyMax = 0.0;
518 size_t fragmentCount = 0;
521 for (
auto& type_code : fragmentTypes)
523 TLOG_TRACE(
"SharedMemoryReader") <<
"Before GetFragmentsByType call, type is " << (int)type_code;
524 auto product =
incoming_events->GetFragmentsByType(errflag, type_code);
525 TLOG_TRACE(
"SharedMemoryReader") <<
"After GetFragmentsByType call, number of fragments is " << product->size();
526 if (errflag)
goto start;
528 std::unordered_map<std::string, std::unique_ptr<Fragments>> derived_fragments;
529 for (
auto& frag : *product)
532 auto latency_s = frag.getLatency(
true);
533 double latency = latency_s.tv_sec + (latency_s.tv_nsec / 1000000000.0);
535 fragmentLatency += latency;
537 if (latency > fragmentLatencyMax) fragmentLatencyMax = latency;
539 std::pair<bool, std::string> instance_name_result =
541 std::string label = instance_name_result.second;
542 if (!instance_name_result.first)
544 TLOG_WARNING(
"SharedMemoryReader")
545 <<
"UnknownFragmentType: The product instance name mapping for fragment type \"" << ((int)type_code)
546 <<
"\" is not known. Fragments of this "
549 if (!derived_fragments.count(label))
551 derived_fragments[label] = std::make_unique<Fragments>();
553 derived_fragments[label]->emplace_back(std::move(frag));
555 for (
auto& type : derived_fragments)
557 put_product_in_principal(std::move(type.second),
563 TLOG_TRACE(
"SharedMemoryReader") <<
"After putting fragments in event";
565 auto read_finish_time = std::chrono::steady_clock::now();
568 TLOG_ARB(10,
"SharedMemoryReader") <<
"readNext: bytesRead=" <<
bytesRead <<
" qsize=" << qsize <<
" cap=" << qcap
569 <<
" metricMan=" << (
void*)metricMan.get();
572 metricMan->sendMetric(
"Avg Processing Time", artdaq::TimeUtils::GetElapsedTime(
last_read_time, read_start_time),
573 "s", 2, MetricMode::Average);
574 metricMan->sendMetric(
"Avg Input Wait Time", artdaq::TimeUtils::GetElapsedTime(read_start_time, got_event_time),
575 "s", 3, MetricMode::Average);
576 metricMan->sendMetric(
"Avg Read Time", artdaq::TimeUtils::GetElapsedTime(got_event_time, read_finish_time),
"s",
577 3, MetricMode::Average);
578 metricMan->sendMetric(
"bytesRead",
bytesRead,
"B", 3, MetricMode::LastPoint);
580 metricMan->sendMetric(
"queue%Used", static_cast<unsigned long int>(qsize * 100 / qcap),
"%", 5,
581 MetricMode::LastPoint);
583 metricMan->sendMetric(
"SharedMemoryReader Latency", fragmentLatency / fragmentCount,
"s", 4, MetricMode::Average);
584 metricMan->sendMetric(
"SharedMemoryReader Maximum Latency", fragmentLatencyMax,
"s", 4, MetricMode::Maximum);
587 TLOG_TRACE(
"SharedMemoryReader") <<
"Returning from readNext";
bool hasMoreData() const
Whether more data is expected from the SharedMemoryReader.
void closeCurrentFile()
Emulate closing a file. No-Op.
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.
size_t bytesRead
running total of number of bytes received
The SharedMemoryReader is a class which implements the methods needed by art::Source.
SharedMemoryReader(SharedMemoryReader const &)=delete
Copy Constructor is deleted.
static void CleanUpGlobals()
Clean up statically-allocated Manager class instances.
std::string pretend_module_name
The module name to store data under.
bool shutdownMsgReceived
Whether a shutdown message has been received.
bool resume_after_timeout
Whether to resume if the dequeue action times out.
double waiting_time
The amount of time to wait for an event from the queue.
std::unique_ptr< SharedMemoryEventReceiver > incoming_events
The events from the EventStore.
SharedMemoryReader(fhicl::ParameterSet const &ps, art::ProductRegistryHelper &help, art::SourceHelper const &pm)
SharedMemoryReader Constructor.
unsigned readNext_calls_
The number of times readNext has been called.
virtual void SetBasicTypes(std::map< Fragment::type_t, std::string > const &type_map)
Sets the basic types to be translated. (Should not include "container" types.)
void readFile(std::string const &, art::FileBlock *&fb)
Emulate opening a file.
bool outputFileCloseNeeded
If an explicit output file close message is needed.
virtual void AddExtraType(artdaq::Fragment::type_t type_id, std::string type_name)
Adds an additional type to be translated.
SharedMemoryReader & operator=(SharedMemoryReader const &)=delete
Copy Assignment operator is deleted.
virtual std::string GetInstanceNameForType(artdaq::Fragment::type_t type_id, std::string unidentified_instance_name)
Returns the basic translation for the specified type. Defaults to the specified unidentified_instance...
art::SourceHelper const & pmaker
An art::SourceHelper instance.
virtual std::pair< bool, std::string > GetInstanceNameForFragment(artdaq::Fragment const &fragment, std::string unidentified_instance_name)
Returns the product instance name for the specified fragment, based on the types that have been speci...
std::string unidentified_instance_name
The name to use for unknown Fragment types.
virtual std::set< std::string > GetAllProductInstanceNames()
Returns the full set of product instance names which may be present in the data, based on the types t...
SharedMemoryReader(fhicl::ParameterSet const &ps, art::ProductRegistryHelper &help, art::SourceHelper const &pm, art::MasterProductRegistry &)
SharedMemoryReader Constructor.
The DefaultFragmentTypeTranslator class provides default behavior for experiment-specific customizati...
std::chrono::steady_clock::time_point last_read_time
Time last read was completed.
virtual ~SharedMemoryReader()
SharedMemoryReader destructor.