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