artdaq  v3_11_00
SharedMemoryEventManager.cc
1 
2 #include "artdaq/DAQrate/SharedMemoryEventManager.hh"
3 #include <sys/wait.h>
4 
5 #include <memory>
6 #include <numeric>
7 
8 #include "artdaq-core/Core/StatisticsCollection.hh"
9 #include "artdaq-core/Utilities/TraceLock.hh"
10 
11 #define TRACE_NAME (app_name + "_SharedMemoryEventManager").c_str()
12 
13 #define TLVL_BUFFER 40
14 #define TLVL_BUFLCK 41
15 
16 #define build_key(seed) ((seed) + ((GetPartitionNumber() + 1) << 16) + (getpid() & 0xFFFF))
17 
18 std::mutex artdaq::SharedMemoryEventManager::sequence_id_mutex_;
19 std::mutex artdaq::SharedMemoryEventManager::subrun_event_map_mutex_;
20 const std::string artdaq::SharedMemoryEventManager::
21  FRAGMENTS_RECEIVED_STAT_KEY("SharedMemoryEventManagerFragmentsReceived");
22 const std::string artdaq::SharedMemoryEventManager::
23  EVENTS_RELEASED_STAT_KEY("SharedMemoryEventManagerEventsReleased");
24 
25 artdaq::SharedMemoryEventManager::SharedMemoryEventManager(const fhicl::ParameterSet& pset, fhicl::ParameterSet art_pset)
26  : SharedMemoryManager(pset.get<uint32_t>("shared_memory_key", build_key(0xEE000000)),
27  pset.get<size_t>("buffer_count"),
28  pset.has_key("max_event_size_bytes") ? pset.get<size_t>("max_event_size_bytes") : pset.get<size_t>("expected_fragments_per_event") * pset.get<size_t>("max_fragment_size_bytes"),
29  pset.get<size_t>("stale_buffer_timeout_usec", pset.get<size_t>("event_queue_wait_time", 5) * 1000000),
30  !pset.get<bool>("broadcast_mode", false))
31  , num_art_processes_(pset.get<size_t>("art_analyzer_count", 1))
32  , num_fragments_per_event_(pset.get<size_t>("expected_fragments_per_event"))
33  , queue_size_(pset.get<size_t>("buffer_count"))
34  , run_id_(0)
35  , max_subrun_event_map_length_(pset.get<size_t>("max_subrun_lookup_table_size", 100))
36  , max_event_list_length_(pset.get<size_t>("max_event_list_length", 100))
37  , update_run_ids_(pset.get<bool>("update_run_ids_on_new_fragment", true))
38  , use_sequence_id_for_event_number_(pset.get<bool>("use_sequence_id_for_event_number", true))
39  , overwrite_mode_(!pset.get<bool>("use_art", true) || pset.get<bool>("overwrite_mode", false) || pset.get<bool>("broadcast_mode", false))
40  , init_fragment_count_(pset.get<size_t>("init_fragment_count", pset.get<bool>("send_init_fragments", true) ? 1 : 0))
41  , running_(false)
42  , buffer_writes_pending_()
43  , open_event_report_interval_ms_(pset.get<int>("open_event_report_interval_ms", pset.get<int>("incomplete_event_report_interval_ms", -1)))
44  , last_open_event_report_time_(std::chrono::steady_clock::now())
45  , last_backpressure_report_time_(std::chrono::steady_clock::now())
46  , last_fragment_header_write_time_(std::chrono::steady_clock::now())
47  , event_timing_(pset.get<size_t>("buffer_count"))
48  , broadcast_timeout_ms_(pset.get<int>("fragment_broadcast_timeout_ms", 3000))
49  , run_event_count_(0)
50  , run_incomplete_event_count_(0)
51  , subrun_event_count_(0)
52  , subrun_incomplete_event_count_(0)
53  , oversize_fragment_count_(0)
54  , maximum_oversize_fragment_count_(pset.get<int>("maximum_oversize_fragment_count", 1))
55  , restart_art_(false)
56  , always_restart_art_(pset.get<bool>("restart_crashed_art_processes", true))
57  , manual_art_(pset.get<bool>("manual_art", false))
58  , current_art_pset_(art_pset)
59  , art_cmdline_(pset.get<std::string>("art_command_line", "art -c #CONFIG_FILE#"))
60  , art_process_index_offset_(pset.get<size_t>("art_index_offset", 0))
61  , minimum_art_lifetime_s_(pset.get<double>("minimum_art_lifetime_s", 2.0))
62  , art_event_processing_time_us_(pset.get<size_t>("expected_art_event_processing_time_us", 1000000))
63  , requests_(nullptr)
64  , tokens_(nullptr)
65  , data_pset_(pset)
66  , broadcasts_(pset.get<uint32_t>("broadcast_shared_memory_key", build_key(0xBB000000)),
67  pset.get<size_t>("broadcast_buffer_count", 10),
68  pset.get<size_t>("broadcast_buffer_size", 0x100000),
69  pset.get<int>("expected_art_event_processing_time_us", 100000) * pset.get<size_t>("buffer_count"), false)
70 {
71  subrun_event_map_[0] = 1;
72  SetMinWriteSize(sizeof(detail::RawEventHeader) + sizeof(detail::RawFragmentHeader));
73  broadcasts_.SetMinWriteSize(sizeof(detail::RawEventHeader) + sizeof(detail::RawFragmentHeader));
74 
75  if (!pset.get<bool>("use_art", true))
76  {
77  TLOG(TLVL_INFO) << "BEGIN SharedMemoryEventManager CONSTRUCTOR with use_art:false";
78  num_art_processes_ = 0;
79  }
80  else
81  {
82  TLOG(TLVL_INFO) << "BEGIN SharedMemoryEventManager CONSTRUCTOR with use_art:true";
83  TLOG(TLVL_TRACE) << "art_pset is " << art_pset.to_string();
84  }
85 
86  if (manual_art_)
87  current_art_config_file_ = std::make_shared<art_config_file>(art_pset, GetKey(), GetBroadcastKey());
88  else
89  current_art_config_file_ = std::make_shared<art_config_file>(art_pset);
90 
91  if (overwrite_mode_ && num_art_processes_ > 0)
92  {
93  TLOG(TLVL_WARNING) << "Art is configured to run, but overwrite mode is enabled! Check your configuration if this in unintentional!";
94  }
95  else if (overwrite_mode_)
96  {
97  TLOG(TLVL_INFO) << "Overwrite Mode enabled, no configured art processes at startup";
98  }
99 
100  for (size_t ii = 0; ii < size(); ++ii)
101  {
102  buffer_writes_pending_[ii] = 0;
103  // Make sure the mutexes are created once
104  std::lock_guard<std::mutex> lk(buffer_mutexes_[ii]);
105  }
106 
107  if (!IsValid())
108  {
109  throw cet::exception(app_name + "_SharedMemoryEventManager") << "Unable to attach to Shared Memory!"; // NOLINT(cert-err60-cpp)
110  }
111 
112  TLOG(TLVL_TRACE) << "Setting Writer rank to " << my_rank;
113  SetRank(my_rank);
114  TLOG(TLVL_DEBUG) << "Writer Rank is " << GetRank();
115 
118 
119  // fetch the monitoring parameters and create the MonitoredQuantity instances
120  statsHelper_.createCollectors(pset, 100, 30.0, 60.0, EVENTS_RELEASED_STAT_KEY);
121 
122  TLOG(TLVL_TRACE) << "END CONSTRUCTOR";
123 }
124 
126 {
127  TLOG(TLVL_TRACE) << "DESTRUCTOR";
128  if (running_)
129  {
130  try
131  {
132  endOfData();
133  }
134  catch (...)
135  {
136  // IGNORED
137  }
138  }
139  TLOG(TLVL_TRACE) << "Destructor END";
140 }
141 
142 bool artdaq::SharedMemoryEventManager::AddFragment(detail::RawFragmentHeader frag, void* dataPtr)
143 {
144  if (!running_) return true;
145 
146  TLOG(TLVL_TRACE) << "AddFragment(Header, ptr) BEGIN frag.word_count=" << frag.word_count
147  << ", sequence_id=" << frag.sequence_id;
148  auto buffer = getBufferForSequenceID_(frag.sequence_id, true, frag.timestamp);
149  TLOG(TLVL_TRACE) << "Using buffer " << buffer << " for seqid=" << frag.sequence_id;
150  if (buffer == -1)
151  {
152  return false;
153  }
154  if (buffer == -2)
155  {
156  TLOG(TLVL_ERROR) << "Dropping event because data taking has already passed this event number: " << frag.sequence_id;
157  return true;
158  }
159 
160  auto hdr = getEventHeader_(buffer);
161  if (update_run_ids_)
162  {
163  hdr->run_id = run_id_;
164  }
165  hdr->subrun_id = GetSubrunForSequenceID(frag.sequence_id);
166 
167  TLOG(TLVL_TRACE) << "AddFragment before Write calls";
168  Write(buffer, dataPtr, frag.word_count * sizeof(RawDataType));
169 
170  TLOG(TLVL_TRACE) << "Checking for complete event";
171  auto fragmentCount = GetFragmentCount(frag.sequence_id);
172  hdr->is_complete = fragmentCount == num_fragments_per_event_ && buffer_writes_pending_[buffer] == 0;
173  TLOG(TLVL_TRACE) << "hdr->is_complete=" << std::boolalpha << hdr->is_complete
174  << ", fragmentCount=" << fragmentCount
175  << ", num_fragments_per_event=" << num_fragments_per_event_
176  << ", buffer_writes_pending_[buffer]=" << buffer_writes_pending_[buffer];
177 
178  complete_buffer_(buffer);
179  if (requests_)
180  {
181  requests_->SendRequest(true);
182  }
183 
184  TLOG(TLVL_TRACE) << "AddFragment END";
185  statsHelper_.addSample(FRAGMENTS_RECEIVED_STAT_KEY, frag.word_count * sizeof(RawDataType));
186  return true;
187 }
188 
189 bool artdaq::SharedMemoryEventManager::AddFragment(FragmentPtr frag, size_t timeout_usec, FragmentPtr& outfrag)
190 {
191  TLOG(TLVL_TRACE) << "AddFragment(FragmentPtr) BEGIN";
192  auto hdr = *reinterpret_cast<detail::RawFragmentHeader*>(frag->headerAddress()); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
193  auto data = frag->headerAddress();
194  auto start = std::chrono::steady_clock::now();
195  bool sts = false;
196  while (!sts && TimeUtils::GetElapsedTimeMicroseconds(start) < timeout_usec)
197  {
198  sts = AddFragment(hdr, data);
199  if (!sts)
200  {
201  usleep(1000);
202  }
203  }
204  if (!sts)
205  {
206  outfrag = std::move(frag);
207  }
208  TLOG(TLVL_TRACE) << "AddFragment(FragmentPtr) RETURN " << std::boolalpha << sts;
209  return sts;
210 }
211 
212 artdaq::RawDataType* artdaq::SharedMemoryEventManager::WriteFragmentHeader(detail::RawFragmentHeader frag, bool dropIfNoBuffersAvailable)
213 {
214  if (!running_) return nullptr;
215  TLOG(14) << "WriteFragmentHeader BEGIN";
216  auto buffer = getBufferForSequenceID_(frag.sequence_id, true, frag.timestamp);
217 
218  if (buffer < 0)
219  {
220  if (buffer == -1 && !dropIfNoBuffersAvailable)
221  {
222  std::unique_lock<std::mutex> bp_lk(sequence_id_mutex_);
223  if (TimeUtils::GetElapsedTime(last_backpressure_report_time_) > 1.0)
224  {
225  TLOG(TLVL_WARNING) << app_name << ": Back-pressure condition: All Shared Memory buffers have been full for " << TimeUtils::GetElapsedTime(last_fragment_header_write_time_) << " s!";
226  last_backpressure_report_time_ = std::chrono::steady_clock::now();
227  }
228  return nullptr;
229  }
230  if (buffer == -2)
231  {
232  TLOG(TLVL_ERROR) << "Dropping fragment with sequence id " << frag.sequence_id << " and fragment id " << frag.fragment_id << " because data taking has already passed this event.";
233  }
234  else
235  {
236  TLOG(TLVL_INFO) << "Dropping fragment with sequence id " << frag.sequence_id << " and fragment id " << frag.fragment_id << " because there is no room in the queue and reliable mode is off.";
237  }
238  dropped_data_.emplace_back(frag, std::make_unique<Fragment>(frag.word_count - frag.num_words()));
239  auto it = dropped_data_.rbegin();
240 
241  TLOG(TLVL_DEBUG + 3) << "Dropping fragment with sequence id " << frag.sequence_id << " and fragment id " << frag.fragment_id << " into "
242  << static_cast<void*>(it->second->dataBegin()) << " sz=" << it->second->dataSizeBytes();
243 
244  return it->second->dataBegin();
245  }
246 
247  last_backpressure_report_time_ = std::chrono::steady_clock::now();
248  last_fragment_header_write_time_ = std::chrono::steady_clock::now();
249  // Increment this as soon as we know we want to use the buffer
250  buffer_writes_pending_[buffer]++;
251 
252  if (metricMan)
253  {
254  metricMan->sendMetric("Input Fragment Rate", 1, "Fragments/s", 1, MetricMode::Rate);
255  }
256 
257  TLOG(TLVL_BUFLCK) << "WriteFragmentHeader: obtaining buffer_mutexes lock for buffer " << buffer;
258 
259  std::unique_lock<std::mutex> lk(buffer_mutexes_.at(buffer));
260 
261  TLOG(TLVL_BUFLCK) << "WriteFragmentHeader: obtained buffer_mutexes lock for buffer " << buffer;
262 
263  auto hdrpos = reinterpret_cast<RawDataType*>(GetWritePos(buffer)); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
264  Write(buffer, &frag, frag.num_words() * sizeof(RawDataType));
265 
266  auto pos = reinterpret_cast<RawDataType*>(GetWritePos(buffer)); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
267  if (frag.word_count - frag.num_words() > 0)
268  {
269  auto sts = IncrementWritePos(buffer, (frag.word_count - frag.num_words()) * sizeof(RawDataType));
270 
271  if (!sts)
272  {
273  reinterpret_cast<detail::RawFragmentHeader*>(hdrpos)->word_count = frag.num_words(); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
274  reinterpret_cast<detail::RawFragmentHeader*>(hdrpos)->type = Fragment::InvalidFragmentType; // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
275  TLOG(TLVL_ERROR) << "Dropping over-size fragment with sequence id " << frag.sequence_id << " and fragment id " << frag.fragment_id << " because there is no room in the current buffer for this Fragment! (Keeping header)";
276  dropped_data_.emplace_back(frag, std::make_unique<Fragment>(frag.word_count - frag.num_words()));
277  auto it = dropped_data_.rbegin();
278 
279  oversize_fragment_count_++;
280 
281  if (maximum_oversize_fragment_count_ > 0 && oversize_fragment_count_ >= maximum_oversize_fragment_count_)
282  {
283  throw cet::exception("Too many over-size Fragments received! Please adjust max_event_size_bytes or max_fragment_size_bytes!");
284  }
285 
286  TLOG(TLVL_DEBUG + 3) << "Dropping over-size fragment with sequence id " << frag.sequence_id << " and fragment id " << frag.fragment_id
287  << " into " << static_cast<void*>(it->second->dataBegin());
288  return it->second->dataBegin();
289  }
290  }
291  TLOG(14) << "WriteFragmentHeader END";
292  return pos;
293 }
294 
295 void artdaq::SharedMemoryEventManager::DoneWritingFragment(detail::RawFragmentHeader frag)
296 {
297  TLOG(TLVL_TRACE) << "DoneWritingFragment BEGIN";
298 
299  auto buffer = getBufferForSequenceID_(frag.sequence_id, false, frag.timestamp);
300  if (buffer < 0)
301  {
302  for (auto it = dropped_data_.begin(); it != dropped_data_.end(); ++it)
303  {
304  if (it->first == frag)
305  {
306  dropped_data_.erase(it);
307  return;
308  }
309  }
310  if (buffer == -1)
311  {
312  Detach(true, "SharedMemoryEventManager",
313  "getBufferForSequenceID_ returned -1 in DoneWritingFragment. This indicates a possible mismatch between expected Fragment count and the actual number of Fragments received.");
314  }
315  return;
316  }
317 
318  statsHelper_.addSample(FRAGMENTS_RECEIVED_STAT_KEY, frag.word_count * sizeof(RawDataType));
319  {
320  TLOG(TLVL_BUFLCK) << "DoneWritingFragment: obtaining buffer_mutexes lock for buffer " << buffer;
321 
322  std::unique_lock<std::mutex> lk(buffer_mutexes_.at(buffer));
323 
324  TLOG(TLVL_BUFLCK) << "DoneWritingFragment: obtained buffer_mutexes lock for buffer " << buffer;
325 
326  TLOG(TLVL_DEBUG) << "DoneWritingFragment: Received Fragment with sequence ID " << frag.sequence_id << " and fragment id " << frag.fragment_id << " (type " << static_cast<int>(frag.type) << ")";
327  auto hdr = getEventHeader_(buffer);
328  if (update_run_ids_)
329  {
330  hdr->run_id = run_id_;
331  }
332  hdr->subrun_id = GetSubrunForSequenceID(frag.sequence_id);
333 
334  TLOG(TLVL_TRACE) << "DoneWritingFragment: Updating buffer touch time";
335  TouchBuffer(buffer);
336 
337  if (buffer_writes_pending_[buffer] > 1)
338  {
339  TLOG(TLVL_TRACE) << "Done writing fragment, but there's another writer. Not doing bookkeeping steps.";
340  buffer_writes_pending_[buffer]--;
341  return;
342  }
343  TLOG(TLVL_TRACE) << "Done writing fragment, and no other writer. Doing bookkeeping steps.";
344  auto frag_count = GetFragmentCount(frag.sequence_id);
345  hdr->is_complete = frag_count >= num_fragments_per_event_;
346 
347  if (frag_count > num_fragments_per_event_)
348  {
349  TLOG(TLVL_WARNING) << "DoneWritingFragment: This Event has more Fragments ( " << frag_count << " ) than specified in configuration ( " << num_fragments_per_event_ << " )!"
350  << " This is probably due to a misconfiguration and is *not* a reliable mode!";
351  }
352 
353  TLOG(TLVL_TRACE) << "DoneWritingFragment: Received Fragment with sequence ID " << frag.sequence_id << " and fragment id " << frag.fragment_id << ", count/expected = " << frag_count << "/" << num_fragments_per_event_;
354 #if ART_SUPPORTS_DUPLICATE_EVENTS
355  if (!hdr->is_complete && released_incomplete_events_.count(frag.sequence_id))
356  {
357  hdr->is_complete = frag_count >= released_incomplete_events_[frag.sequence_id] && buffer_writes_pending_[buffer] == 0;
358  }
359 #endif
360 
361  complete_buffer_(buffer);
362 
363  // Move this down here to avoid race condition
364  buffer_writes_pending_[buffer]--;
365  }
366  if (requests_)
367  {
368  requests_->SendRequest(true);
369  }
370  TLOG(TLVL_TRACE) << "DoneWritingFragment END";
371 }
372 
373 size_t artdaq::SharedMemoryEventManager::GetFragmentCount(Fragment::sequence_id_t seqID, Fragment::type_t type)
374 {
375  return GetFragmentCountInBuffer(getBufferForSequenceID_(seqID, false), type);
376 }
377 
378 size_t artdaq::SharedMemoryEventManager::GetFragmentCountInBuffer(int buffer, Fragment::type_t type)
379 {
380  if (buffer < 0)
381  {
382  return 0;
383  }
384  ResetReadPos(buffer);
385  IncrementReadPos(buffer, sizeof(detail::RawEventHeader));
386 
387  size_t count = 0;
388 
389  while (MoreDataInBuffer(buffer))
390  {
391  auto fragHdr = reinterpret_cast<artdaq::detail::RawFragmentHeader*>(GetReadPos(buffer)); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
392  IncrementReadPos(buffer, fragHdr->word_count * sizeof(RawDataType));
393  if (type != Fragment::InvalidFragmentType && fragHdr->type != type)
394  {
395  continue;
396  }
397  TLOG(TLVL_TRACE) << "Adding Fragment with size=" << fragHdr->word_count << " to Fragment count";
398  ++count;
399  }
400 
401  return count;
402 }
403 
404 void artdaq::SharedMemoryEventManager::RunArt(const std::shared_ptr<art_config_file>& config_file, size_t process_index, const std::shared_ptr<std::atomic<pid_t>>& pid_out)
405 {
406  do
407  {
408  auto start_time = std::chrono::steady_clock::now();
409  send_init_frags_();
410  TLOG(TLVL_INFO) << "Starting art process with config file " << config_file->getFileName();
411 
412  pid_t pid = 0;
413 
414  if (!manual_art_)
415  {
416  pid = fork();
417  if (pid == 0)
418  { /* child */
419  // 23-May-2018, KAB: added the setting of the partition number env var
420  // in the environment of the child art process so that Globals.hh
421  // will pick it up there and provide it to the artdaq classes that
422  // are used in data transfers, etc. within the art process.
423  std::string envVarKey = "ARTDAQ_PARTITION_NUMBER";
424  std::string envVarValue = std::to_string(GetPartitionNumber());
425  if (setenv(envVarKey.c_str(), envVarValue.c_str(), 1) != 0)
426  {
427  TLOG(TLVL_ERROR) << "Error setting environment variable \"" << envVarKey
428  << "\" in the environment of a child art process. "
429  << "This may result in incorrect TCP port number "
430  << "assignments or other issues, and data may "
431  << "not flow through the system correctly.";
432  }
433  envVarKey = "ARTDAQ_APPLICATION_NAME";
434  envVarValue = app_name;
435  if (setenv(envVarKey.c_str(), envVarValue.c_str(), 1) != 0)
436  {
437  TLOG(TLVL_DEBUG) << "Error setting environment variable \"" << envVarKey
438  << "\" in the environment of a child art process. ";
439  }
440  envVarKey = "ARTDAQ_RANK";
441  envVarValue = std::to_string(my_rank);
442  if (setenv(envVarKey.c_str(), envVarValue.c_str(), 1) != 0)
443  {
444  TLOG(TLVL_DEBUG) << "Error setting environment variable \"" << envVarKey
445  << "\" in the environment of a child art process. ";
446  }
447 
448  TLOG(TLVL_TRACE) << "Parsing art command line";
449  auto args = parse_art_command_line_(config_file, process_index);
450 
451  TLOG(TLVL_TRACE) << "Calling execvp with application name " << args[0];
452  execvp(args[0], &args[0]);
453 
454  TLOG(TLVL_TRACE) << "Application exited, cleaning up";
455  for (auto& arg : args)
456  {
457  delete[] arg;
458  }
459 
460  exit(1);
461  }
462  }
463  else
464  {
465  //Using cin/cout here to ensure console is active (artdaqDriver)
466  std::cout << "Please run the following command in a separate terminal:" << std::endl
467  << "art -c " << config_file->getFileName() << std::endl
468  << "Then, in a third terminal, execute: \"ps aux|grep [a]rt -c " << config_file->getFileName() << "\" and note the PID of the art process." << std::endl
469  << "Finally, return to this window and enter the pid: " << std::endl;
470  std::cin >> pid;
471  }
472  *pid_out = pid;
473 
474  TLOG(TLVL_INFO) << "PID of new art process is " << pid;
475  {
476  std::unique_lock<std::mutex> lk(art_process_mutex_);
477  art_processes_.insert(pid);
478  }
479  siginfo_t status;
480  auto sts = 0;
481  if (!manual_art_)
482  {
483  sts = waitid(P_PID, pid, &status, WEXITED);
484  }
485  else
486  {
487  while (kill(pid, 0) >= 0) usleep(10000);
488 
489  TLOG(TLVL_INFO) << "Faking good exit status, please see art process for actual exit status!";
490  status.si_code = CLD_EXITED;
491  status.si_status = 0;
492  }
493  TLOG(TLVL_INFO) << "Removing PID " << pid << " from process list";
494  {
495  std::unique_lock<std::mutex> lk(art_process_mutex_);
496  art_processes_.erase(pid);
497  }
498  if (sts < 0)
499  {
500  TLOG(TLVL_WARNING) << "Error occurred in waitid for art process " << pid << ": " << errno << " (" << strerror(errno) << ").";
501  }
502  else if (status.si_code == CLD_EXITED && status.si_status == 0)
503  {
504  TLOG(TLVL_INFO) << "art process " << pid << " exited normally, " << (restart_art_ ? "restarting" : "not restarting");
505  }
506  else
507  {
508  auto art_lifetime = TimeUtils::GetElapsedTime(start_time);
509  if (art_lifetime < minimum_art_lifetime_s_)
510  {
511  restart_art_ = false;
512  }
513 
514  auto exit_type = "exited with status code";
515  switch (status.si_code)
516  {
517  case CLD_DUMPED:
518  case CLD_KILLED:
519  exit_type = "was killed with signal";
520  break;
521  case CLD_EXITED:
522  default:
523  break;
524  }
525 
526  TLOG((restart_art_ ? TLVL_WARNING : TLVL_ERROR))
527  << "art process " << pid << " " << exit_type << " " << status.si_status
528  << (status.si_code == CLD_DUMPED ? " (core dumped)" : "")
529  << " after running for " << std::setprecision(2) << std::fixed << art_lifetime << " seconds, "
530  << (restart_art_ ? "restarting" : "not restarting");
531  }
532  } while (restart_art_);
533 }
534 
536 {
537  restart_art_ = always_restart_art_;
538  if (num_art_processes_ == 0)
539  {
540  return;
541  }
542  for (size_t ii = 0; ii < num_art_processes_; ++ii)
543  {
544  StartArtProcess(current_art_pset_, ii);
545  }
546 }
547 
548 pid_t artdaq::SharedMemoryEventManager::StartArtProcess(fhicl::ParameterSet pset, size_t process_index)
549 {
550  static std::mutex start_art_mutex;
551  std::unique_lock<std::mutex> lk(start_art_mutex);
552  //TraceLock lk(start_art_mutex, 15, "StartArtLock");
553  restart_art_ = always_restart_art_;
554  auto initialCount = GetAttachedCount();
555  auto startTime = std::chrono::steady_clock::now();
556 
557  if (pset != current_art_pset_ || !current_art_config_file_)
558  {
559  current_art_pset_ = pset;
560  if (manual_art_)
561  current_art_config_file_ = std::make_shared<art_config_file>(pset, GetKey(), GetBroadcastKey());
562  else
563  current_art_config_file_ = std::make_shared<art_config_file>(pset);
564  }
565  std::shared_ptr<std::atomic<pid_t>> pid(new std::atomic<pid_t>(-1));
566  boost::thread thread([=] { RunArt(current_art_config_file_, process_index, pid); });
567  thread.detach();
568 
569  auto currentCount = GetAttachedCount() - initialCount;
570  while ((currentCount < 1 || *pid <= 0) && (TimeUtils::GetElapsedTime(startTime) < 5 || manual_art_))
571  {
572  usleep(10000);
573  currentCount = GetAttachedCount() - initialCount;
574  }
575  if ((currentCount < 1 || *pid <= 0) && manual_art_)
576  {
577  TLOG(TLVL_WARNING) << "Manually-started art process has not connected to shared memory or has bad PID: connected:" << currentCount << ", PID:" << pid;
578  return 0;
579  }
580  if (currentCount < 1 || *pid <= 0)
581  {
582  TLOG(TLVL_WARNING) << "art process has not started after 5s. Check art configuration!"
583  << " (pid=" << *pid << ", attachedCount=" << currentCount << ")";
584  return 0;
585  }
586 
587  TLOG(TLVL_INFO) << std::setw(4) << std::fixed << "art initialization took "
588  << TimeUtils::GetElapsedTime(startTime) << " seconds.";
589 
590  return *pid;
591 }
592 
594 {
595  restart_art_ = false;
596  //current_art_config_file_ = nullptr;
597  //current_art_pset_ = fhicl::ParameterSet();
598 
599  auto check_pids = [&](bool print) {
600  std::unique_lock<std::mutex> lk(art_process_mutex_);
601  for (auto pid = pids.begin(); pid != pids.end();)
602  {
603  // 08-May-2018, KAB: protect against killing invalid PIDS
604 
605  if (*pid <= 0)
606  {
607  TLOG(TLVL_WARNING) << "Removing an invalid PID (" << *pid
608  << ") from the shutdown list.";
609  pid = pids.erase(pid);
610  }
611  else if (kill(*pid, 0) < 0)
612  {
613  pid = pids.erase(pid);
614  }
615  else
616  {
617  if (print)
618  {
619  std::cout << *pid << " ";
620  }
621  ++pid;
622  }
623  }
624  };
625  auto count_pids = [&]() {
626  std::unique_lock<std::mutex> lk(art_process_mutex_);
627  return pids.size();
628  };
629  check_pids(false);
630  if (count_pids() == 0)
631  {
632  TLOG(14) << "All art processes already exited, nothing to do.";
633  usleep(1000);
634  return;
635  }
636 
637  if (!manual_art_)
638  {
639  int graceful_wait_ms = art_event_processing_time_us_ * size() * 10 / 1000;
640  int gentle_wait_ms = art_event_processing_time_us_ * size() * 2 / 1000;
641  int int_wait_ms = art_event_processing_time_us_ * size() / 1000;
642  auto shutdown_start = std::chrono::steady_clock::now();
643 
644  // if (!overwrite_mode_)
645  {
646  TLOG(TLVL_TRACE) << "Waiting up to " << graceful_wait_ms << " ms for all art processes to exit gracefully";
647  for (int ii = 0; ii < graceful_wait_ms; ++ii)
648  {
649  usleep(1000);
650 
651  check_pids(false);
652  if (count_pids() == 0)
653  {
654  TLOG(TLVL_INFO) << "All art processes exited after " << TimeUtils::GetElapsedTimeMilliseconds(shutdown_start) << " ms.";
655  return;
656  }
657  }
658  }
659 
660  {
661  TLOG(TLVL_TRACE) << "Gently informing art processes that it is time to shut down";
662  std::unique_lock<std::mutex> lk(art_process_mutex_);
663  for (auto pid : pids)
664  {
665  TLOG(TLVL_TRACE) << "Sending SIGQUIT to pid " << pid;
666  kill(pid, SIGQUIT);
667  }
668  }
669 
670  TLOG(TLVL_TRACE) << "Waiting up to " << gentle_wait_ms << " ms for all art processes to exit from SIGQUIT";
671  for (int ii = 0; ii < gentle_wait_ms; ++ii)
672  {
673  usleep(1000);
674 
675  check_pids(false);
676  if (count_pids() == 0)
677  {
678  TLOG(TLVL_INFO) << "All art processes exited after " << TimeUtils::GetElapsedTimeMilliseconds(shutdown_start) << " ms (SIGQUIT).";
679  return;
680  }
681  }
682 
683  {
684  TLOG(TLVL_TRACE) << "Insisting that the art processes shut down";
685  std::unique_lock<std::mutex> lk(art_process_mutex_);
686  for (auto pid : pids)
687  {
688  kill(pid, SIGINT);
689  }
690  }
691 
692  TLOG(TLVL_TRACE) << "Waiting up to " << int_wait_ms << " ms for all art processes to exit from SIGINT";
693  for (int ii = 0; ii < int_wait_ms; ++ii)
694  {
695  usleep(1000);
696 
697  check_pids(false);
698 
699  if (count_pids() == 0)
700  {
701  TLOG(TLVL_INFO) << "All art processes exited after " << TimeUtils::GetElapsedTimeMilliseconds(shutdown_start) << " ms (SIGINT).";
702  return;
703  }
704  }
705 
706  TLOG(TLVL_TRACE) << "Killing remaning art processes with extreme prejudice";
707  while (count_pids() > 0)
708  {
709  {
710  std::unique_lock<std::mutex> lk(art_process_mutex_);
711  kill(*pids.begin(), SIGKILL);
712  usleep(1000);
713  }
714  check_pids(false);
715  }
716  TLOG(TLVL_INFO) << "All art processes exited after " << TimeUtils::GetElapsedTimeMilliseconds(shutdown_start) << " ms (SIGKILL).";
717  }
718  else
719  {
720  std::cout << "Please shut down all art processes, then hit return/enter" << std::endl;
721  while (count_pids() > 0)
722  {
723  std::cout << "The following PIDs are running: ";
724  check_pids(true);
725  std::cout << std::endl;
726  usleep(500000);
727  }
728  }
729 }
730 
731 void artdaq::SharedMemoryEventManager::ReconfigureArt(fhicl::ParameterSet art_pset, run_id_t newRun, int n_art_processes)
732 {
733  TLOG(TLVL_DEBUG) << "ReconfigureArt BEGIN";
734  if (restart_art_ || !always_restart_art_) // Art is running
735  {
736  endOfData();
737  }
738  for (size_t ii = 0; ii < broadcasts_.size(); ++ii)
739  {
740  broadcasts_.MarkBufferEmpty(ii, true);
741  }
742  if (newRun == 0)
743  {
744  newRun = run_id_ + 1;
745  }
746 
747  if (art_pset != current_art_pset_ || !current_art_config_file_)
748  {
749  current_art_pset_ = art_pset;
750  if (manual_art_)
751  current_art_config_file_ = std::make_shared<art_config_file>(art_pset, GetKey(), GetBroadcastKey());
752  else
753  current_art_config_file_ = std::make_shared<art_config_file>(art_pset);
754  }
755 
756  if (n_art_processes != -1)
757  {
758  TLOG(TLVL_INFO) << "Setting number of art processes to " << n_art_processes;
759  num_art_processes_ = n_art_processes;
760  }
761  startRun(newRun);
762  TLOG(TLVL_DEBUG) << "ReconfigureArt END";
763 }
764 
766 {
767  running_ = false;
768  init_fragments_.clear();
769  received_init_frags_.clear();
770  TLOG(TLVL_DEBUG) << "SharedMemoryEventManager::endOfData";
771  restart_art_ = false;
772 
773  auto start = std::chrono::steady_clock::now();
774  auto pendingWriteCount = std::accumulate(buffer_writes_pending_.begin(), buffer_writes_pending_.end(), 0, [](int a, auto& b) { return a + b.second.load(); });
775  TLOG(TLVL_DEBUG) << "endOfData: Waiting for " << pendingWriteCount << " pending writes to complete";
776  while (pendingWriteCount > 0 && TimeUtils::GetElapsedTimeMicroseconds(start) < 1000000)
777  {
778  usleep(10000);
779  pendingWriteCount = std::accumulate(buffer_writes_pending_.begin(), buffer_writes_pending_.end(), 0, [](int a, auto& b) { return a + b.second.load(); });
780  }
781 
782  size_t initialStoreSize = GetOpenEventCount();
783  TLOG(TLVL_DEBUG) << "endOfData: Flushing " << initialStoreSize
784  << " stale events from the SharedMemoryEventManager.";
785  int counter = initialStoreSize;
786  while (!active_buffers_.empty() && counter > 0)
787  {
788  complete_buffer_(*active_buffers_.begin());
789  counter--;
790  }
791  TLOG(TLVL_DEBUG) << "endOfData: Done flushing, there are now " << GetOpenEventCount()
792  << " stale events in the SharedMemoryEventManager.";
793 
794  TLOG(TLVL_DEBUG) << "Waiting for " << (ReadReadyCount() + (size() - WriteReadyCount(overwrite_mode_))) << " outstanding buffers...";
795  start = std::chrono::steady_clock::now();
796  auto lastReadCount = ReadReadyCount() + (size() - WriteReadyCount(overwrite_mode_));
797  auto end_of_data_wait_us = art_event_processing_time_us_ * (lastReadCount > 0 ? lastReadCount : 1); //size();
798 
799  auto outstanding_buffer_wait_time = art_event_processing_time_us_ > 100000 ? 100000 : art_event_processing_time_us_;
800 
801  // We will wait until no buffer has been read for the end of data wait seconds, or no art processes are left.
802  while (lastReadCount > 0 && (end_of_data_wait_us == 0 || TimeUtils::GetElapsedTimeMicroseconds(start) < end_of_data_wait_us) && get_art_process_count_() > 0)
803  {
804  auto temp = ReadReadyCount() + (size() - WriteReadyCount(overwrite_mode_));
805  if (temp != lastReadCount)
806  {
807  TLOG(TLVL_TRACE) << "Waiting for " << temp << " outstanding buffers...";
808  lastReadCount = temp;
809  start = std::chrono::steady_clock::now();
810  }
811  if (lastReadCount > 0)
812  {
813  TLOG(19) << "About to sleep " << outstanding_buffer_wait_time << " us - lastReadCount=" << lastReadCount << " size=" << size() << " end_of_data_wait_us=" << end_of_data_wait_us;
814  usleep(outstanding_buffer_wait_time);
815  }
816  }
817 
818  TLOG(TLVL_DEBUG) << "endOfData: After wait for outstanding buffers. Still outstanding: " << lastReadCount << ", time waited: "
819  << TimeUtils::GetElapsedTime(start) << " s / " << (end_of_data_wait_us / 1000000.0) << " s, art process count: " << get_art_process_count_();
820 
821  TLOG(TLVL_DEBUG) << "endOfData: Broadcasting EndOfData Fragment";
822  FragmentPtrs broadcast;
823  broadcast.emplace_back(Fragment::eodFrag(GetBufferCount()));
824  bool success = broadcastFragments_(broadcast);
825  if (!success)
826  {
827  TLOG(TLVL_DEBUG) << "endOfData: Clearing buffers to make room for EndOfData Fragment";
828  for (size_t ii = 0; ii < broadcasts_.size(); ++ii)
829  {
830  broadcasts_.MarkBufferEmpty(ii, true);
831  }
832  broadcastFragments_(broadcast);
833  }
834  auto endOfDataProcessingStart = std::chrono::steady_clock::now();
835  while (get_art_process_count_() > 0)
836  {
837  TLOG(TLVL_DEBUG) << "There are " << get_art_process_count_() << " art processes remaining. Proceeding to shutdown.";
838 
839  ShutdownArtProcesses(art_processes_);
840  }
841  TLOG(TLVL_DEBUG) << "It took " << TimeUtils::GetElapsedTime(endOfDataProcessingStart) << " s for all art processes to close after sending EndOfData Fragment";
842 
843  ResetAttachedCount();
844 
845  TLOG(TLVL_DEBUG) << "endOfData: Clearing buffers";
846  for (size_t ii = 0; ii < size(); ++ii)
847  {
848  MarkBufferEmpty(ii, true);
849  }
850  // ELF 06/04/2018: Cannot clear broadcasts here, we want the EndOfDataFragment to persist until it's time to start art again...
851  // TLOG(TLVL_TRACE) << "endOfData: Clearing broadcast buffers";
852  // for (size_t ii = 0; ii < broadcasts_.size(); ++ii)
853  // {
854  // broadcasts_.MarkBufferEmpty(ii, true);
855  // }
856  released_events_.clear();
857  released_incomplete_events_.clear();
858 
859  TLOG(TLVL_DEBUG) << "endOfData END";
860  TLOG(TLVL_INFO) << "EndOfData Complete. There were " << GetLastSeenBufferID() << " buffers processed.";
861  return true;
862 }
863 
865 {
866  running_ = true;
867  init_fragments_.clear();
868  received_init_frags_.clear();
869  statsHelper_.resetStatistics();
870  TLOG(TLVL_TRACE) << "startRun: Clearing broadcast buffers";
871  for (size_t ii = 0; ii < broadcasts_.size(); ++ii)
872  {
873  broadcasts_.MarkBufferEmpty(ii, true);
874  }
875  released_events_.clear();
876  released_incomplete_events_.clear();
877  StartArt();
878  run_id_ = runID;
879  {
880  std::unique_lock<std::mutex> lk(subrun_event_map_mutex_);
881  subrun_event_map_.clear();
882  subrun_event_map_[0] = 1;
883  }
884  run_event_count_ = 0;
885  run_incomplete_event_count_ = 0;
886  requests_ = std::make_unique<RequestSender>(data_pset_);
887  if (requests_)
888  {
889  requests_->SetRunNumber(static_cast<uint32_t>(run_id_));
890  }
891  if (data_pset_.has_key("routing_token_config"))
892  {
893  auto rmPset = data_pset_.get<fhicl::ParameterSet>("routing_token_config");
894  if (rmPset.get<bool>("use_routing_manager", false))
895  {
896  tokens_ = std::make_unique<TokenSender>(rmPset);
897  tokens_->SetRunNumber(static_cast<uint32_t>(run_id_));
898  tokens_->SendRoutingToken(queue_size_, run_id_);
899  }
900  }
901  TLOG(TLVL_DEBUG) << "Starting run " << run_id_
902  << ", max queue size = "
903  << queue_size_
904  << ", queue size = "
905  << GetLockedBufferCount();
906  if (metricMan)
907  {
908  metricMan->sendMetric("Run Number", static_cast<uint64_t>(run_id_), "Run", 1, MetricMode::LastPoint | MetricMode::Persist);
909  }
910 }
911 
913 {
914  TLOG(TLVL_INFO) << "Ending run " << run_id_;
915  FragmentPtr endOfRunFrag(new Fragment(static_cast<size_t>(ceil(sizeof(my_rank) /
916  static_cast<double>(sizeof(Fragment::value_type))))));
917 
918  TLOG(TLVL_DEBUG) << "Shutting down RequestSender";
919  requests_.reset(nullptr);
920  TLOG(TLVL_DEBUG) << "Shutting down TokenSender";
921  tokens_.reset(nullptr);
922 
923  TLOG(TLVL_DEBUG) << "Broadcasting EndOfRun Fragment";
924  endOfRunFrag->setSystemType(Fragment::EndOfRunFragmentType);
925  *endOfRunFrag->dataBegin() = my_rank;
926  FragmentPtrs broadcast;
927  broadcast.emplace_back(std::move(endOfRunFrag));
928  broadcastFragments_(broadcast);
929 
930  TLOG(TLVL_INFO) << "Run " << run_id_ << " has ended. There were " << run_event_count_ << " events in this run.";
931  run_event_count_ = 0;
932  run_incomplete_event_count_ = 0;
933  oversize_fragment_count_ = 0;
934  {
935  std::unique_lock<std::mutex> lk(subrun_event_map_mutex_);
936  subrun_event_map_.clear();
937  subrun_event_map_[0] = 1;
938  }
939  return true;
940 }
941 
943 {
944  // Generated EndOfSubrun Fragments have Sequence ID 0 and should be ignored
945  if (boundary == 0 || boundary == Fragment::InvalidSequenceID)
946  {
947  return;
948  }
949 
950  std::unique_lock<std::mutex> lk(subrun_event_map_mutex_);
951 
952  // Don't re-rollover to an already-defined subrun
953  if (!subrun_event_map_.empty() && subrun_event_map_.rbegin()->second == subrun)
954  {
955  return;
956  }
957  TLOG(TLVL_INFO) << "Will roll over to subrun " << subrun << " when I reach Sequence ID " << boundary;
958  subrun_event_map_[boundary] = subrun;
959  while (subrun_event_map_.size() > max_subrun_event_map_length_)
960  {
961  subrun_event_map_.erase(subrun_event_map_.begin());
962  }
963 }
964 
966 {
967  Fragment::sequence_id_t seqID = 0;
968  subrun_id_t subrun = 0;
969  {
970  std::unique_lock<std::mutex> lk(subrun_event_map_mutex_);
971  for (auto& it : subrun_event_map_)
972  {
973  if (it.first >= seqID)
974  {
975  seqID = it.first + 1;
976  }
977  if (it.second >= subrun)
978  {
979  subrun = it.second + 1;
980  }
981  }
982  }
983  rolloverSubrun(seqID, subrun);
984 }
985 
987 {
988  if (metricMan)
989  {
990  metricMan->sendMetric("Open Event Count", GetOpenEventCount(), "events", 1, MetricMode::LastPoint);
991  metricMan->sendMetric("Pending Event Count", GetPendingEventCount(), "events", 1, MetricMode::LastPoint);
992  }
993 
994  if (open_event_report_interval_ms_ > 0 && GetLockedBufferCount() != 0u)
995  {
996  if (TimeUtils::GetElapsedTimeMilliseconds(last_open_event_report_time_) < static_cast<size_t>(open_event_report_interval_ms_))
997  {
998  return;
999  }
1000 
1001  last_open_event_report_time_ = std::chrono::steady_clock::now();
1002  std::ostringstream oss;
1003  oss << "Open Events (expecting " << num_fragments_per_event_ << " Fragments): ";
1004  for (auto& ev : active_buffers_)
1005  {
1006  auto hdr = getEventHeader_(ev);
1007  oss << hdr->sequence_id << " (has " << GetFragmentCount(hdr->sequence_id) << " Fragments), ";
1008  }
1009  TLOG(TLVL_DEBUG) << oss.str();
1010  }
1011 }
1012 
1013 bool artdaq::SharedMemoryEventManager::broadcastFragments_(FragmentPtrs& frags)
1014 {
1015  if (frags.empty())
1016  {
1017  TLOG(TLVL_ERROR) << "Requested broadcast but no Fragments given!";
1018  return false;
1019  }
1020  if (!broadcasts_.IsValid())
1021  {
1022  TLOG(TLVL_ERROR) << "Broadcast attempted but broadcast shared memory is unavailable!";
1023  return false;
1024  }
1025  TLOG(TLVL_DEBUG) << "Broadcasting Fragments with seqID=" << frags.front()->sequenceID()
1026  << ", type " << detail::RawFragmentHeader::SystemTypeToString(frags.front()->type())
1027  << ", size=" << frags.front()->sizeBytes() << "B.";
1028  auto buffer = broadcasts_.GetBufferForWriting(false);
1029  TLOG(TLVL_DEBUG) << "broadcastFragments_: after getting buffer 1st buffer=" << buffer;
1030  auto start_time = std::chrono::steady_clock::now();
1031  while (buffer == -1 && TimeUtils::GetElapsedTimeMilliseconds(start_time) < static_cast<size_t>(broadcast_timeout_ms_))
1032  {
1033  usleep(10000);
1034  buffer = broadcasts_.GetBufferForWriting(false);
1035  }
1036  TLOG(TLVL_DEBUG) << "broadcastFragments_: after getting buffer w/timeout, buffer=" << buffer << ", elapsed time=" << TimeUtils::GetElapsedTime(start_time) << " s.";
1037  if (buffer == -1)
1038  {
1039  TLOG(TLVL_ERROR) << "Broadcast of fragment type " << frags.front()->typeString() << " failed due to timeout waiting for buffer!";
1040  return false;
1041  }
1042 
1043  TLOG(TLVL_DEBUG) << "broadcastFragments_: Filling in RawEventHeader";
1044  auto hdr = reinterpret_cast<detail::RawEventHeader*>(broadcasts_.GetBufferStart(buffer)); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
1045  hdr->run_id = run_id_;
1046  hdr->subrun_id = GetSubrunForSequenceID(frags.front()->sequenceID());
1047  hdr->sequence_id = frags.front()->sequenceID();
1048  hdr->is_complete = true;
1049  broadcasts_.IncrementWritePos(buffer, sizeof(detail::RawEventHeader));
1050 
1051  for (auto& frag : frags)
1052  {
1053  TLOG(TLVL_DEBUG) << "broadcastFragments_ before Write calls";
1054  if (frag->sequenceID() != hdr->sequence_id || frag->type() != frags.front()->type())
1055  {
1056  TLOG(TLVL_WARNING) << "Not sending fragment because its SequenceID or Type disagrees with leading Fragment";
1057  continue;
1058  }
1059  broadcasts_.Write(buffer, frag->headerAddress(), frag->size() * sizeof(RawDataType));
1060  }
1061 
1062  TLOG(TLVL_DEBUG) << "broadcastFragments_ Marking buffer full";
1063  broadcasts_.MarkBufferFull(buffer, -1);
1064  TLOG(TLVL_DEBUG) << "broadcastFragments_ Complete";
1065  return true;
1066 }
1067 
1068 artdaq::detail::RawEventHeader* artdaq::SharedMemoryEventManager::getEventHeader_(int buffer)
1069 {
1070  return reinterpret_cast<detail::RawEventHeader*>(GetBufferStart(buffer)); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
1071 }
1072 
1074 {
1075  std::unique_lock<std::mutex> lk(subrun_event_map_mutex_);
1076 
1077  TLOG(TLVL_TRACE) << "GetSubrunForSequenceID BEGIN map size = " << subrun_event_map_.size();
1078  auto it = subrun_event_map_.begin();
1079  subrun_id_t subrun = 1;
1080 
1081  while (it->first <= seqID && it != subrun_event_map_.end())
1082  {
1083  TLOG(TLVL_TRACE) << "Map has sequence ID " << it->first << ", subrun " << it->second << " (looking for <= " << seqID << ")";
1084  subrun = it->second;
1085  ++it;
1086  }
1087 
1088  TLOG(TLVL_DEBUG) << "GetSubrunForSequenceID returning subrun " << subrun << " for sequence ID " << seqID;
1089  return subrun;
1090 }
1091 
1092 int artdaq::SharedMemoryEventManager::getBufferForSequenceID_(Fragment::sequence_id_t seqID, bool create_new, Fragment::timestamp_t timestamp)
1093 {
1094  TLOG(14) << "getBufferForSequenceID " << seqID << " BEGIN";
1095  std::unique_lock<std::mutex> lk(sequence_id_mutex_);
1096 
1097  TLOG(14) << "getBufferForSequenceID obtained sequence_id_mutex for seqid=" << seqID;
1098 
1099  auto buffers = GetBuffersOwnedByManager();
1100  for (auto& buf : buffers)
1101  {
1102  auto hdr = getEventHeader_(buf);
1103  if (hdr->sequence_id == seqID)
1104  {
1105  TLOG(14) << "getBufferForSequenceID " << seqID << " returning " << buf;
1106  return buf;
1107  }
1108  }
1109 
1110 #if !ART_SUPPORTS_DUPLICATE_EVENTS
1111  if (released_incomplete_events_.count(seqID) != 0u)
1112  {
1113  TLOG(TLVL_ERROR) << "Event " << seqID << " has already been marked \"Incomplete\" and sent to art!";
1114  return -2;
1115  }
1116  if (released_events_.count(seqID) != 0u)
1117  {
1118  TLOG(TLVL_ERROR) << "Event " << seqID << " has already been completed and released to art! Check configuration for inconsistent Fragment count per event!";
1119  return -2;
1120  }
1121 #endif
1122 
1123  if (!create_new)
1124  {
1125  return -1;
1126  }
1127 
1128  check_pending_buffers_(lk);
1129  int new_buffer = GetBufferForWriting(false);
1130 
1131  if (new_buffer == -1)
1132  {
1133  new_buffer = GetBufferForWriting(overwrite_mode_);
1134  }
1135 
1136  if (new_buffer == -1)
1137  {
1138  return -1;
1139  }
1140  TLOG(TLVL_BUFLCK) << "getBufferForSequenceID_: obtaining buffer_mutexes lock for buffer " << new_buffer;
1141  std::unique_lock<std::mutex> buffer_lk(buffer_mutexes_.at(new_buffer));
1142  TLOG(TLVL_BUFLCK) << "getBufferForSequenceID_: obtained buffer_mutexes lock for buffer " << new_buffer;
1143 
1144  event_timing_[new_buffer] = std::chrono::steady_clock::now();
1145 
1146  auto hdr = getEventHeader_(new_buffer);
1147  hdr->is_complete = false;
1148  hdr->run_id = run_id_;
1149  hdr->subrun_id = GetSubrunForSequenceID(seqID);
1150  hdr->event_id = use_sequence_id_for_event_number_ ? static_cast<uint32_t>(seqID) : static_cast<uint32_t>(timestamp);
1151  hdr->sequence_id = seqID;
1152  hdr->timestamp = timestamp;
1153  buffer_writes_pending_[new_buffer] = 0;
1154  IncrementWritePos(new_buffer, sizeof(detail::RawEventHeader));
1155  SetMFIteration("Sequence ID " + std::to_string(seqID));
1156 
1157  TLOG(TLVL_BUFFER) << "getBufferForSequenceID placing " << new_buffer << " to active.";
1158  active_buffers_.insert(new_buffer);
1159  TLOG(TLVL_BUFFER) << "Buffer occupancy now (total,full,reading,empty,pending,active)=("
1160  << size() << ","
1161  << ReadReadyCount() << ","
1162  << WriteReadyCount(true) - WriteReadyCount(false) - ReadReadyCount() << ","
1163  << WriteReadyCount(false) << ","
1164  << pending_buffers_.size() << ","
1165  << active_buffers_.size() << ")";
1166 
1167  if (requests_)
1168  {
1169  requests_->AddRequest(seqID, timestamp);
1170  }
1171  TLOG(14) << "getBufferForSequenceID " << seqID << " returning newly initialized buffer " << new_buffer;
1172  return new_buffer;
1173 }
1174 
1175 bool artdaq::SharedMemoryEventManager::hasFragments_(int buffer)
1176 {
1177  if (buffer == -1)
1178  {
1179  return true;
1180  }
1181  if (!CheckBuffer(buffer, BufferSemaphoreFlags::Writing))
1182  {
1183  return true;
1184  }
1185  ResetReadPos(buffer);
1186  IncrementReadPos(buffer, sizeof(detail::RawEventHeader));
1187  return MoreDataInBuffer(buffer);
1188 }
1189 
1190 void artdaq::SharedMemoryEventManager::complete_buffer_(int buffer)
1191 {
1192  auto hdr = getEventHeader_(buffer);
1193  if (hdr->is_complete)
1194  {
1195  TLOG(TLVL_DEBUG) << "complete_buffer_: This fragment completes event " << hdr->sequence_id << ".";
1196 
1197  {
1198  TLOG(TLVL_BUFFER) << "complete_buffer_ moving " << buffer << " from active to pending.";
1199 
1200  TLOG(TLVL_BUFLCK) << "complete_buffer_: obtaining sequence_id_mutex lock for seqid=" << hdr->sequence_id;
1201  std::unique_lock<std::mutex> lk(sequence_id_mutex_);
1202  TLOG(TLVL_BUFLCK) << "complete_buffer_: obtained sequence_id_mutex lock for seqid=" << hdr->sequence_id;
1203  active_buffers_.erase(buffer);
1204  pending_buffers_.insert(buffer);
1205  released_events_.insert(hdr->sequence_id);
1206  while (released_events_.size() > max_event_list_length_)
1207  {
1208  released_events_.erase(released_events_.begin());
1209  }
1210 
1211  TLOG(TLVL_BUFFER) << "Buffer occupancy now (total,full,reading,empty,pending,active)=("
1212  << size() << ","
1213  << ReadReadyCount() << ","
1214  << WriteReadyCount(true) - WriteReadyCount(false) - ReadReadyCount() << ","
1215  << WriteReadyCount(false) << ","
1216  << pending_buffers_.size() << ","
1217  << active_buffers_.size() << ")";
1218  }
1219  if (requests_)
1220  {
1221  requests_->RemoveRequest(hdr->sequence_id);
1222  }
1223  }
1224  CheckPendingBuffers();
1225 }
1226 
1227 bool artdaq::SharedMemoryEventManager::bufferComparator(int bufA, int bufB)
1228 {
1229  return getEventHeader_(bufA)->sequence_id < getEventHeader_(bufB)->sequence_id;
1230 }
1231 
1233 {
1234  TLOG(TLVL_BUFLCK) << "CheckPendingBuffers: Obtaining sequence_id_mutex_";
1235  std::unique_lock<std::mutex> lk(sequence_id_mutex_);
1236  TLOG(TLVL_BUFLCK) << "CheckPendingBuffers: Obtained sequence_id_mutex_";
1237  check_pending_buffers_(lk);
1238 }
1239 
1240 void artdaq::SharedMemoryEventManager::check_pending_buffers_(std::unique_lock<std::mutex> const& lock)
1241 {
1242  TLOG(14) << "check_pending_buffers_ BEGIN Locked=" << std::boolalpha << lock.owns_lock();
1243 
1244  auto buffers = GetBuffersOwnedByManager();
1245  for (auto buf : buffers)
1246  {
1247  if (ResetBuffer(buf) && (pending_buffers_.count(buf) == 0u))
1248  {
1249  TLOG(15) << "check_pending_buffers_ Incomplete buffer detected, buf=" << buf << " active_bufers_.count(buf)=" << active_buffers_.count(buf) << " buffer_writes_pending_[buf]=" << buffer_writes_pending_[buf].load();
1250  auto hdr = getEventHeader_(buf);
1251  if ((active_buffers_.count(buf) != 0u) && buffer_writes_pending_[buf].load() == 0)
1252  {
1253  if (requests_)
1254  {
1255  requests_->RemoveRequest(hdr->sequence_id);
1256  }
1257  TLOG(TLVL_BUFFER) << "check_pending_buffers_ moving buffer " << buf << " from active to pending";
1258  active_buffers_.erase(buf);
1259  pending_buffers_.insert(buf);
1260  TLOG(TLVL_BUFFER) << "Buffer occupancy now (total,full,reading,empty,pending,active)=("
1261  << size() << ","
1262  << ReadReadyCount() << ","
1263  << WriteReadyCount(true) - WriteReadyCount(false) - ReadReadyCount() << ","
1264  << WriteReadyCount(false) << ","
1265  << pending_buffers_.size() << ","
1266  << active_buffers_.size() << ")";
1267 
1268  run_incomplete_event_count_++;
1269  if (metricMan)
1270  {
1271  metricMan->sendMetric("Incomplete Event Rate", 1, "events/s", 3, MetricMode::Rate);
1272  }
1273  if (released_incomplete_events_.count(hdr->sequence_id) == 0u)
1274  {
1275  released_incomplete_events_[hdr->sequence_id] = num_fragments_per_event_ - GetFragmentCountInBuffer(buf);
1276  }
1277  else
1278  {
1279  released_incomplete_events_[hdr->sequence_id] -= GetFragmentCountInBuffer(buf);
1280  }
1281  TLOG(TLVL_WARNING) << "Active event " << hdr->sequence_id << " is stale. Scheduling release of incomplete event (missing " << released_incomplete_events_[hdr->sequence_id] << " Fragments) to art.";
1282  }
1283  }
1284  }
1285 
1286  std::list<int> sorted_buffers(pending_buffers_.begin(), pending_buffers_.end());
1287  sorted_buffers.sort([this](int a, int b) { return bufferComparator(a, b); });
1288 
1289  auto counter = 0;
1290  double eventSize = 0;
1291  double eventTime = 0;
1292  for (auto buf : sorted_buffers)
1293  {
1294  auto hdr = getEventHeader_(buf);
1295  auto thisEventSize = BufferDataSize(buf);
1296 
1297  TLOG(TLVL_DEBUG) << "Releasing event " << std::to_string(hdr->sequence_id) << " in buffer " << buf << " to art, "
1298  << "event_size=" << thisEventSize << ", buffer_size=" << BufferSize();
1299  statsHelper_.addSample(EVENTS_RELEASED_STAT_KEY, thisEventSize);
1300 
1301  TLOG(TLVL_BUFFER) << "check_pending_buffers_ removing buffer " << buf << " moving from pending to full";
1302  MarkBufferFull(buf);
1303  run_event_count_++;
1304  counter++;
1305  eventSize += thisEventSize;
1306  eventTime += TimeUtils::GetElapsedTime(event_timing_[buf]);
1307  pending_buffers_.erase(buf);
1308  TLOG(TLVL_BUFFER) << "Buffer occupancy now (total,full,reading,empty,pending,active)=("
1309  << size() << ","
1310  << ReadReadyCount() << ","
1311  << WriteReadyCount(true) - WriteReadyCount(false) - ReadReadyCount() << ","
1312  << WriteReadyCount(false) << ","
1313  << pending_buffers_.size() << ","
1314  << active_buffers_.size() << ")";
1315  }
1316 
1317  if (tokens_ && tokens_->RoutingTokenSendsEnabled())
1318  {
1319  TLOG(TLVL_TRACE) << "Sent tokens: " << tokens_->GetSentTokenCount() << ", Event count: " << run_event_count_;
1320  auto outstanding_tokens = tokens_->GetSentTokenCount() - run_event_count_;
1321  auto available_buffers = WriteReadyCount(overwrite_mode_);
1322 
1323  TLOG(TLVL_TRACE) << "check_pending_buffers_: outstanding_tokens: " << outstanding_tokens << ", available_buffers: " << available_buffers
1324  << ", tokens_to_send: " << available_buffers - outstanding_tokens;
1325 
1326  if (available_buffers > outstanding_tokens)
1327  {
1328  auto tokens_to_send = available_buffers - outstanding_tokens;
1329 
1330  while (tokens_to_send > 0)
1331  {
1332  TLOG(35) << "check_pending_buffers_: Sending a Routing Token";
1333  tokens_->SendRoutingToken(1, run_id_);
1334  tokens_to_send--;
1335  }
1336  }
1337  }
1338 
1339  if (statsHelper_.readyToReport())
1340  {
1341  std::string statString = buildStatisticsString_();
1342  TLOG(TLVL_INFO) << statString;
1343  }
1344 
1345  if (metricMan)
1346  {
1347  TLOG(14) << "check_pending_buffers_: Sending Metrics";
1348  metricMan->sendMetric("Event Rate", counter, "Events", 1, MetricMode::Rate);
1349  metricMan->sendMetric("Data Rate", eventSize, "Bytes", 1, MetricMode::Rate);
1350  if (counter > 0)
1351  {
1352  metricMan->sendMetric("Average Event Size", eventSize / counter, "Bytes", 1, MetricMode::Average);
1353  metricMan->sendMetric("Average Event Building Time", eventTime / counter, "s", 1, MetricMode::Average);
1354  }
1355 
1356  metricMan->sendMetric("Events Released to art this run", run_event_count_, "Events", 1, MetricMode::LastPoint);
1357  metricMan->sendMetric("Incomplete Events Released to art this run", run_incomplete_event_count_, "Events", 1, MetricMode::LastPoint);
1358  if (tokens_ && tokens_->RoutingTokenSendsEnabled())
1359  {
1360  metricMan->sendMetric("Tokens sent", tokens_->GetSentTokenCount(), "Tokens", 2, MetricMode::LastPoint);
1361  }
1362 
1363  auto bufferReport = GetBufferReport();
1364  int full = 0, empty = 0, writing = 0, reading = 0;
1365  for (auto& buf : bufferReport)
1366  {
1367  switch (buf.second)
1368  {
1369  case BufferSemaphoreFlags::Full:
1370  full++;
1371  break;
1372  case BufferSemaphoreFlags::Empty:
1373  empty++;
1374  break;
1375  case BufferSemaphoreFlags::Writing:
1376  writing++;
1377  break;
1378  case BufferSemaphoreFlags::Reading:
1379  reading++;
1380  break;
1381  }
1382  }
1383  auto total = size();
1384  TLOG(15) << "Buffer usage: full=" << full << ", empty=" << empty << ", writing=" << writing << ", reading=" << reading << ", total=" << total;
1385 
1386  metricMan->sendMetric("Shared Memory Full Buffers", full, "buffers", 2, MetricMode::LastPoint);
1387  metricMan->sendMetric("Shared Memory Available Buffers", empty, "buffers", 2, MetricMode::LastPoint);
1388  metricMan->sendMetric("Shared Memory Pending Buffers", writing, "buffers", 2, MetricMode::LastPoint);
1389  metricMan->sendMetric("Shared Memory Reading Buffers", reading, "buffers", 2, MetricMode::LastPoint);
1390  if (total > 0)
1391  {
1392  metricMan->sendMetric("Shared Memory Full %", full * 100 / static_cast<double>(total), "%", 2, MetricMode::LastPoint);
1393  metricMan->sendMetric("Shared Memory Available %", empty * 100 / static_cast<double>(total), "%", 2, MetricMode::LastPoint);
1394  }
1395  }
1396  TLOG(14) << "check_pending_buffers_ END";
1397 }
1398 
1399 std::vector<char*> artdaq::SharedMemoryEventManager::parse_art_command_line_(const std::shared_ptr<art_config_file>& config_file, size_t process_index)
1400 {
1401  auto offset_index = process_index + art_process_index_offset_;
1402  TLOG(16) << "parse_art_command_line_: Parsing command line " << art_cmdline_ << ", config_file: " << config_file->getFileName() << ", index: " << process_index << " (w/offset: " << offset_index << ")";
1403  std::string art_cmdline_tmp = art_cmdline_;
1404  auto filenameit = art_cmdline_tmp.find("#CONFIG_FILE#");
1405  if (filenameit != std::string::npos)
1406  {
1407  art_cmdline_tmp.replace(filenameit, 13, config_file->getFileName());
1408  }
1409  auto indexit = art_cmdline_tmp.find("#PROCESS_INDEX#");
1410  if (indexit != std::string::npos)
1411  {
1412  art_cmdline_tmp.replace(indexit, 15, std::to_string(offset_index));
1413  }
1414  TLOG(16) << "parse_art_command_line_: After replacing index and config parameters, command line is " << art_cmdline_tmp;
1415 
1416  std::istringstream iss(art_cmdline_tmp);
1417  auto tokens = std::vector<std::string>{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
1418  std::vector<char*> output;
1419 
1420  for (auto& token : tokens)
1421  {
1422  TLOG(16) << "parse_art_command_line_: Adding cmdline token " << token << " to output list";
1423  output.emplace_back(new char[token.length() + 1]);
1424  memcpy(output.back(), token.c_str(), token.length());
1425  output.back()[token.length()] = '\0'; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
1426  }
1427  output.emplace_back(nullptr);
1428 
1429  return output;
1430 }
1431 
1432 void artdaq::SharedMemoryEventManager::send_init_frags_()
1433 {
1434  if (init_fragments_.size() >= init_fragment_count_ && init_fragment_count_ > 0)
1435  {
1436  TLOG(TLVL_INFO) << "Broadcasting " << init_fragments_.size() << " Init Fragment(s) to all art subprocesses...";
1437 
1438 #if 0
1439  std::string fileName = "receiveInitMessage_" + std::to_string(my_rank) + ".bin";
1440  std::fstream ostream(fileName.c_str(), std::ios::out | std::ios::binary);
1441  ostream.write(reinterpret_cast<char*>(init_fragment_->dataBeginBytes()), init_fragment_->dataSizeBytes());
1442  ostream.close();
1443 #endif
1444 
1445  broadcastFragments_(init_fragments_);
1446  TLOG(TLVL_TRACE) << "Init Fragment sent";
1447  }
1448  else if (init_fragment_count_ > 0 && init_fragments_.size() == 0)
1449  {
1450  TLOG(TLVL_WARNING) << "Cannot send Init Fragment(s) because I haven't yet received them! Set send_init_fragments to false or init_fragment_count to 0 if this process does not receive serialized art events to avoid potentially lengthy timeouts!";
1451  }
1452  else if (init_fragment_count_ > 0)
1453  {
1454  TLOG(TLVL_INFO) << "Cannot send Init Fragment(s) because I haven't yet received them (have " << init_fragments_.size() << " of " << init_fragment_count_ << ")!";
1455  }
1456  else
1457  {
1458  // Send an empty Init Fragment so that ArtdaqInput knows that this is a pure-Fragment input
1459  artdaq::FragmentPtrs begin_run_fragments_;
1460  begin_run_fragments_.emplace_back(new artdaq::Fragment());
1461  begin_run_fragments_.back()->setSystemType(artdaq::Fragment::InitFragmentType);
1462  broadcastFragments_(begin_run_fragments_);
1463  }
1464 }
1465 
1467 {
1468  static std::mutex init_fragment_mutex;
1469  std::lock_guard<std::mutex> lk(init_fragment_mutex);
1470  if (received_init_frags_.count(frag->fragmentID()) == 0)
1471  {
1472  TLOG(TLVL_DEBUG) << "Received Init Fragment from rank " << frag->fragmentID() << ". Now have " << init_fragments_.size() + 1 << " of " << init_fragment_count_;
1473  received_init_frags_.insert(frag->fragmentID());
1474  init_fragments_.push_back(std::move(frag));
1475 
1476  // Don't send until all init fragments have been received
1477  if (init_fragments_.size() >= init_fragment_count_)
1478  {
1479  send_init_frags_();
1480  }
1481  }
1482  else
1483  {
1484  TLOG(TLVL_TRACE) << "Ignoring duplicate Init Fragment from rank " << frag->fragmentID();
1485  }
1486 }
1487 
1489 {
1490  TLOG(TLVL_DEBUG) << "UpdateArtConfiguration BEGIN";
1491  if (art_pset != current_art_pset_ || !current_art_config_file_)
1492  {
1493  current_art_pset_ = art_pset;
1494  if (manual_art_)
1495  current_art_config_file_ = std::make_shared<art_config_file>(art_pset, GetKey(), GetBroadcastKey());
1496  else
1497  current_art_config_file_ = std::make_shared<art_config_file>(art_pset);
1498  }
1499  TLOG(TLVL_DEBUG) << "UpdateArtConfiguration END";
1500 }
1501 
1502 std::string artdaq::SharedMemoryEventManager::buildStatisticsString_() const
1503 {
1504  std::ostringstream oss;
1505  oss << app_name << " statistics:" << std::endl;
1506 
1507  artdaq::MonitoredQuantityPtr mqPtr =
1508  artdaq::StatisticsCollection::getInstance().getMonitoredQuantity(EVENTS_RELEASED_STAT_KEY);
1509  if (mqPtr.get() != nullptr)
1510  {
1511  artdaq::MonitoredQuantityStats stats;
1512  mqPtr->getStats(stats);
1513  oss << " Event statistics: " << stats.recentSampleCount << " events released at " << stats.recentSampleRate
1514  << " events/sec, effective data rate = "
1515  << (stats.recentValueRate / 1024.0 / 1024.0)
1516  << " MB/sec, monitor window = " << stats.recentDuration
1517  << " sec, min::max event size = " << (stats.recentValueMin / 1024.0 / 1024.0)
1518  << "::" << (stats.recentValueMax / 1024.0 / 1024.0) << " MB" << std::endl;
1519  if (stats.recentSampleRate > 0.0)
1520  {
1521  oss << " Average time per event: ";
1522  oss << " elapsed time = " << (1.0 / stats.recentSampleRate) << " sec" << std::endl;
1523  }
1524  }
1525 
1526  mqPtr = artdaq::StatisticsCollection::getInstance().getMonitoredQuantity(FRAGMENTS_RECEIVED_STAT_KEY);
1527  if (mqPtr.get() != nullptr)
1528  {
1529  artdaq::MonitoredQuantityStats stats;
1530  mqPtr->getStats(stats);
1531  oss << " Fragment statistics: " << stats.recentSampleCount << " fragments received at " << stats.recentSampleRate
1532  << " fragments/sec, effective data rate = "
1533  << (stats.recentValueRate / 1024.0 / 1024.0)
1534  << " MB/sec, monitor window = " << stats.recentDuration
1535  << " sec, min::max fragment size = " << (stats.recentValueMin / 1024.0 / 1024.0)
1536  << "::" << (stats.recentValueMax / 1024.0 / 1024.0) << " MB" << std::endl;
1537  }
1538 
1539  oss << " Event counts: Run -- " << run_event_count_ << " Total, " << run_incomplete_event_count_ << " Incomplete."
1540  << " Subrun -- " << subrun_event_count_ << " Total, " << subrun_incomplete_event_count_ << " Incomplete. "
1541  << std::endl;
1542  return oss.str();
1543 }
void addMonitoredQuantityName(std::string const &statKey)
Add a MonitoredQuantity name to the list.
void AddInitFragment(FragmentPtr &frag)
Set the stored Init fragment, if one has not yet been set already.
void ShutdownArtProcesses(std::set< pid_t > &pids)
Shutdown a set of art processes.
virtual ~SharedMemoryEventManager()
SharedMemoryEventManager Destructor.
Fragment::sequence_id_t sequence_id_t
Copy Fragment::sequence_id_t into local scope.
void ReconfigureArt(fhicl::ParameterSet art_pset, run_id_t newRun=0, int n_art_processes=-1)
Restart all art processes, using the given fhicl code to configure the new art processes.
RawDataType * WriteFragmentHeader(detail::RawFragmentHeader frag, bool dropIfNoBuffersAvailable=false)
Get a pointer to a reserved memory area for the given Fragment header.
RawEvent::run_id_t run_id_t
Copy RawEvent::run_id_t into local scope.
size_t GetFragmentCount(Fragment::sequence_id_t seqID, Fragment::type_t type=Fragment::InvalidFragmentType)
Get the count of Fragments of a given type in an event.
void UpdateArtConfiguration(fhicl::ParameterSet art_pset)
Updates the internally-stored copy of the art configuration.
pid_t StartArtProcess(fhicl::ParameterSet pset, size_t process_index)
Start one art process.
void StartArt()
Start all the art processes.
subrun_id_t GetSubrunForSequenceID(Fragment::sequence_id_t seqID)
Get the subrun number that the given Sequence ID would be assigned to.
SharedMemoryEventManager(const fhicl::ParameterSet &pset, fhicl::ParameterSet art_pset)
SharedMemoryEventManager Constructor.
void RunArt(const std::shared_ptr< art_config_file > &config_file, size_t process_index, const std::shared_ptr< std::atomic< pid_t >> &pid_out)
Run an art instance, recording the return codes and restarting it until the end flag is raised...
void rolloverSubrun()
Add a subrun transition immediately after the highest currently define sequence ID.
void sendMetrics()
Send metrics to the MetricManager, if one has been instantiated in the application.
static const std::string FRAGMENTS_RECEIVED_STAT_KEY
Key for Fragments Received MonitoredQuantity.
bool createCollectors(fhicl::ParameterSet const &pset, int defaultReportIntervalFragments, double defaultReportIntervalSeconds, double defaultMonitorWindow, std::string const &primaryStatKeyName)
Create MonitoredQuantity objects for all names registered with the StatisticsHelper.
bool endRun()
Send an EndOfRunFragment to the art thread.
void DoneWritingFragment(detail::RawFragmentHeader frag)
Used to indicate that the given Fragment is now completely in the buffer. Will check for buffer compl...
static const std::string EVENTS_RELEASED_STAT_KEY
Key for the Events Released MonitoredQuantity.
uint32_t GetBroadcastKey()
Gets the shared memory key of the broadcast SharedMemoryManager.
bool endOfData()
Indicate that the end of input has been reached to the art processes.
RawEvent::subrun_id_t subrun_id_t
Copy RawEvent::subrun_id_t into local scope.
void startRun(run_id_t runID)
Start a Run.
size_t GetFragmentCountInBuffer(int buffer, Fragment::type_t type=Fragment::InvalidFragmentType)
Get the count of Fragments of a given type in a buffer.
void CheckPendingBuffers()
Check for buffers which are ready to be marked incomplete and released to art and issue tokens for an...