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