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"
28 #define build_key(seed) seed + ((GetPartitionNumber() + 1) << 16) + (getppid() & 0xFFFF)
46 virtual void SetBasicTypes(std::map<Fragment::type_t, std::string>
const& type_map)
54 virtual void AddExtraType(artdaq::Fragment::type_t type_id, std::string type_name)
66 return unidentified_instance_name;
76 std::set<std::string> output;
79 std::string instance_name = map_iter.second;
80 if (!output.count(instance_name))
82 output.insert(instance_name);
83 TLOG_TRACE(
"DefaultFragmentTypeTranslator") <<
"Adding product instance name \"" << map_iter.second
84 <<
"\" to list of expected names";
88 auto container_type = type_map_.find(Fragment::type_t(artdaq::Fragment::ContainerFragmentType));
89 if (container_type != type_map_.end())
91 std::string container_type_name = container_type->second;
92 std::set<std::string> tmp_copy = output;
93 for (
const auto& set_iter : tmp_copy)
95 output.insert(container_type_name + set_iter);
108 virtual std::pair<bool, std::string>
112 bool success_code =
true;
113 std::string instance_name;
115 auto primary_type =
type_map_.find(fragment.type());
116 if (primary_type != type_map_end)
118 instance_name = primary_type->second;
119 if (fragment.type() == artdaq::Fragment::ContainerFragmentType)
121 artdaq::ContainerFragment cf(fragment);
122 auto contained_type =
type_map_.find(cf.fragment_type());
123 if (contained_type != type_map_end)
125 instance_name += contained_type->second;
131 instance_name = unidentified_instance_name;
132 success_code =
false;
135 return std::make_pair(success_code, instance_name);
145 template<std::map<artdaq::Fragment::type_t, std::
string> getDefaultTypes() = artdaq::Fragment::MakeSystemTypeMap,
146 class FTT = artdaq::detail::DefaultFragmentTypeTranslator>
189 art::ProductRegistryHelper& help,
190 art::SourceHelper
const& pm)
213 new SharedMemoryEventReceiver(ps.get<uint32_t>(
"shared_memory_key", build_key(0xEE000000)),
214 ps.get<uint32_t>(
"broadcast_shared_memory_key", build_key(0xBB000000))));
216 TLOG(TLVL_INFO,
"SharedMemoryReader") <<
"Rank set to " << my_rank;
218 char const* artapp_env = getenv(
"ARTDAQ_APPLICATION_NAME");
219 std::string artapp_str =
"";
220 if (artapp_env != NULL)
222 artapp_str = std::string(artapp_env) +
"_";
225 app_name = artapp_str +
"art" + std::to_string(
incoming_events->GetMyId());
227 artapp_env = getenv(
"ARTDAQ_RANK");
228 if (artapp_env != NULL && my_rank < 0)
230 my_rank = std::atoi(artapp_env);
232 TLOG(TLVL_INFO) <<
"app_name is " << app_name <<
", rank " << my_rank;
238 metricMan->initialize(ps.get<fhicl::ParameterSet>(
"metrics", fhicl::ParameterSet()), app_name);
239 metricMan->do_start();
244 ExceptionHandler(ExceptionHandlerRethrow::no,
"Error loading metrics in SharedMemoryReader()");
250 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>>());
251 for (
auto it = extraTypes.begin(); it != extraTypes.end(); ++it)
255 std::set<std::string> instance_names =
translator_.GetAllProductInstanceNames();
256 for (
const auto& set_iter : instance_names)
261 TLOG_INFO(
"SharedMemoryReader") <<
"SharedMemoryReader initialized with ParameterSet: " << ps.to_string();
264 #if ART_HEX_VERSION < 0x30000
273 SharedMemoryReader(fhicl::ParameterSet
const& ps, art::ProductRegistryHelper& help, art::SourceHelper
const& pm,
274 art::MasterProductRegistry&)
292 void readFile(std::string
const&, art::FileBlock*& fb)
294 TLOG_ARB(5,
"SharedMemoryReader") <<
"readFile enter/start";
295 fb =
new art::FileBlock(art::FileFormatVersion(1,
"RawEvent2011"),
"nothing");
314 bool readNext(art::RunPrincipal*
const& inR, art::SubRunPrincipal*
const& inSR, art::RunPrincipal*& outR,
315 art::SubRunPrincipal*& outSR, art::EventPrincipal*& outE)
317 TLOG_DEBUG(
"SharedMemoryReader") <<
"readNext BEGIN";
334 TLOG_INFO(
"SharedMemoryReader") <<
"Shutdown Message received, returning false (should exit art)";
338 auto read_start_time = std::chrono::steady_clock::now();
340 bool keep_looping =
true;
341 bool got_event =
false;
343 if (sleepTimeUsec > 100000) sleepTimeUsec = 100000;
346 TLOG_TRACE(
"SharedMemoryReader") <<
"ReadyForRead loops BEGIN";
347 keep_looping =
false;
348 auto start_time = std::chrono::steady_clock::now();
349 while (!got_event && TimeUtils::GetElapsedTimeMicroseconds(start_time) < 1000)
354 TLOG_TRACE(
"SharedMemoryReader") <<
"ReadyForRead spin end, poll begin";
355 while (!got_event && TimeUtils::GetElapsedTime(start_time) <
waiting_time)
360 usleep(sleepTimeUsec);
365 TLOG_TRACE(
"SharedMemoryReader") <<
"ReadyForRead loops END";
368 TLOG_INFO(
"SharedMemoryReader") <<
"InputFailure: Reading timed out in SharedMemoryReader::readNext()";
375 TLOG_INFO(
"SharedMemoryReader") <<
"Did not receive an event from Shared Memory, returning false";
379 TLOG_DEBUG(
"SharedMemoryReader") <<
"Got Event!";
380 auto got_event_time = std::chrono::steady_clock::now();
382 auto errflag =
false;
384 if (errflag)
goto start;
386 if (errflag)
goto start;
387 if (fragmentTypes.size() == 0)
389 TLOG_ERROR(
"SharedMemoryReader") <<
"Event has no Fragments! Aborting!";
393 auto firstFragmentType = *fragmentTypes.begin();
394 TLOG_DEBUG(
"SharedMemoryReader") <<
"First Fragment type is " << (int)firstFragmentType <<
" ("
401 if (firstFragmentType == Fragment::EndOfDataFragmentType)
403 TLOG_DEBUG(
"SharedMemoryReader") <<
"Received shutdown message, returning false";
414 art::Timestamp currentTime = 0;
416 art::TimeValue_t lo_res_time = time(0);
417 TLOG_ARB(15,
"SharedMemoryReader") <<
"lo_res_time = " << lo_res_time;
418 currentTime = ((lo_res_time & 0xffffffff) << 32);
420 timespec hi_res_time;
421 int retcode = clock_gettime(CLOCK_REALTIME, &hi_res_time);
422 TLOG_ARB(15,
"SharedMemoryReader") <<
"hi_res_time tv_sec = " << hi_res_time.tv_sec
423 <<
" tv_nsec = " << hi_res_time.tv_nsec <<
" (retcode = " << retcode <<
")";
426 currentTime = ((hi_res_time.tv_sec & 0xffffffff) << 32) | (hi_res_time.tv_nsec & 0xffffffff);
430 TLOG_ERROR(
"SharedMemoryReader")
431 <<
"Unable to fetch a high-resolution time with clock_gettime for art::Event Timestamp. "
432 <<
"The art::Event Timestamp will be zero for event " << evtHeader->event_id;
436 if (inR == 0 || inR->run() != evtHeader->run_id)
438 outR =
pmaker.makeRunPrincipal(evtHeader->run_id, currentTime);
441 if (firstFragmentType == Fragment::EndOfRunFragmentType)
443 art::EventID
const evid(art::EventID::flushEvent());
444 outR =
pmaker.makeRunPrincipal(evid.runID(), currentTime);
445 outSR =
pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
446 outE =
pmaker.makeEventPrincipal(evid, currentTime);
450 else if (firstFragmentType == Fragment::EndOfSubrunFragmentType)
453 if (inR == 0 || inR->run() != evtHeader->run_id)
455 outSR =
pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
456 #if ART_HEX_VERSION > 0x30000
457 art::EventID
const evid(art::EventID::flushEvent(outSR->subRunID()));
459 art::EventID
const evid(art::EventID::flushEvent(outSR->id()));
461 outE =
pmaker.makeEventPrincipal(evid, currentTime);
469 #if ART_HEX_VERSION > 0x30000
470 if (inSR != 0 && !inSR->subRunID().isFlush() && inSR->subRun() == evtHeader->subrun_id)
472 if (inSR != 0 && !inSR->id().isFlush() && inSR->subRun() == evtHeader->subrun_id)
475 #if ART_HEX_VERSION > 0x30000
476 art::EventID
const evid(art::EventID::flushEvent(inR->runID()));
478 art::EventID
const evid(art::EventID::flushEvent(inR->id()));
480 outSR =
pmaker.makeSubRunPrincipal(evid.subRunID(), currentTime);
481 outE =
pmaker.makeEventPrincipal(evid, currentTime);
488 outSR =
pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
489 #if ART_HEX_VERSION > 0x30000
490 art::EventID
const evid(art::EventID::flushEvent(outSR->subRunID()));
492 art::EventID
const evid(art::EventID::flushEvent(outSR->id()));
494 outE =
pmaker.makeEventPrincipal(evid, currentTime);
506 art::SubRunID subrun_check(evtHeader->run_id, evtHeader->subrun_id);
507 #if ART_HEX_VERSION > 0x30000
508 if (inSR == 0 || subrun_check != inSR->subRunID())
511 if (inSR == 0 || subrun_check != inSR->id())
514 outSR =
pmaker.makeSubRunPrincipal(evtHeader->run_id, evtHeader->subrun_id, currentTime);
516 outE =
pmaker.makeEventPrincipal(evtHeader->run_id, evtHeader->subrun_id, evtHeader->event_id, currentTime);
518 double fragmentLatency = 0;
519 double fragmentLatencyMax = 0.0;
520 size_t fragmentCount = 0;
523 for (
auto& type_code : fragmentTypes)
525 TLOG_TRACE(
"SharedMemoryReader") <<
"Before GetFragmentsByType call, type is " << (int)type_code;
526 auto product =
incoming_events->GetFragmentsByType(errflag, type_code);
527 TLOG_TRACE(
"SharedMemoryReader") <<
"After GetFragmentsByType call, number of fragments is " << product->size();
528 if (errflag)
goto start;
530 std::unordered_map<std::string, std::unique_ptr<Fragments>> derived_fragments;
531 for (
auto& frag : *product)
534 auto latency_s = frag.getLatency(
true);
535 double latency = latency_s.tv_sec + (latency_s.tv_nsec / 1000000000.0);
537 fragmentLatency += latency;
539 if (latency > fragmentLatencyMax) fragmentLatencyMax = latency;
541 std::pair<bool, std::string> instance_name_result =
543 std::string label = instance_name_result.second;
544 if (!instance_name_result.first)
546 TLOG_WARNING(
"SharedMemoryReader")
547 <<
"UnknownFragmentType: The product instance name mapping for fragment type \"" << ((int)type_code)
548 <<
"\" is not known. Fragments of this "
551 if (!derived_fragments.count(label))
553 derived_fragments[label] = std::make_unique<Fragments>();
555 derived_fragments[label]->emplace_back(std::move(frag));
557 for (
auto& type : derived_fragments)
559 put_product_in_principal(std::move(type.second),
565 TLOG_TRACE(
"SharedMemoryReader") <<
"After putting fragments in event";
567 auto read_finish_time = std::chrono::steady_clock::now();
570 TLOG_ARB(10,
"SharedMemoryReader") <<
"readNext: bytesRead=" <<
bytesRead <<
" qsize=" << qsize <<
" cap=" << qcap
571 <<
" metricMan=" << (
void*)metricMan.get();
574 metricMan->sendMetric(
"Avg Processing Time", artdaq::TimeUtils::GetElapsedTime(
last_read_time, read_start_time),
575 "s", 2, MetricMode::Average);
576 metricMan->sendMetric(
"Avg Input Wait Time", artdaq::TimeUtils::GetElapsedTime(read_start_time, got_event_time),
577 "s", 3, MetricMode::Average);
578 metricMan->sendMetric(
"Avg Read Time", artdaq::TimeUtils::GetElapsedTime(got_event_time, read_finish_time),
"s",
579 3, MetricMode::Average);
580 metricMan->sendMetric(
"bytesRead",
bytesRead,
"B", 3, MetricMode::LastPoint);
582 metricMan->sendMetric(
"queue%Used", static_cast<unsigned long int>(qsize * 100 / qcap),
"%", 5,
583 MetricMode::LastPoint);
585 metricMan->sendMetric(
"SharedMemoryReader Latency", fragmentLatency / fragmentCount,
"s", 4, MetricMode::Average);
586 metricMan->sendMetric(
"SharedMemoryReader Maximum Latency", fragmentLatencyMax,
"s", 4, MetricMode::Maximum);
589 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.
FTT translator_
An instance of the template parameter FragmentTypeTranslator that translates Fragment Type IDs to str...
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.
std::map< Fragment::type_t, std::string > type_map_
Map relating Fragment Type to strings.
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.