artdaq  v3_10_03
FragmentBuffer.cc
1 #include "artdaq/DAQdata/Globals.hh"
2 #define TRACE_NAME (app_name + "_FragmentBuffer").c_str() // include these 2 first -
3 
4 #include "artdaq/DAQrate/FragmentBuffer.hh"
5 
6 #include <boost/exception/all.hpp>
7 #include <boost/throw_exception.hpp>
8 
9 #include <iterator>
10 #include <limits>
11 
12 #include "canvas/Utilities/Exception.h"
13 #include "cetlib_except/exception.h"
14 #include "fhiclcpp/ParameterSet.h"
15 
16 #include "artdaq-core/Data/ContainerFragmentLoader.hh"
17 #include "artdaq-core/Data/Fragment.hh"
18 #include "artdaq-core/Utilities/ExceptionHandler.hh"
19 #include "artdaq-core/Utilities/SimpleLookupPolicy.hh"
20 #include "artdaq-core/Utilities/TimeUtils.hh"
21 
22 #include <sys/poll.h>
23 #include <algorithm>
24 #include <fstream>
25 #include <iomanip>
26 #include <iostream>
27 #include <iterator>
29 
30 #define TLVL_GETNEXT 10
31 #define TLVL_GETNEXT_VERBOSE 20
32 #define TLVL_CHECKSTOP 11
33 #define TLVL_EVCOUNTERINC 12
34 #define TLVL_GETDATALOOP 13
35 #define TLVL_GETDATALOOP_DATABUFFWAIT 21
36 #define TLVL_GETDATALOOP_VERBOSE 20
37 #define TLVL_WAITFORBUFFERREADY 15
38 #define TLVL_GETBUFFERSTATS 16
39 #define TLVL_CHECKDATABUFFER 17
40 #define TLVL_GETMONITORINGDATA 18
41 #define TLVL_APPLYREQUESTS 9
42 #define TLVL_SENDEMPTYFRAGMENTS 19
43 #define TLVL_CHECKWINDOWS 14
44 #define TLVL_EMPTYFRAGMENT 22
45 
46 artdaq::FragmentBuffer::FragmentBuffer(const fhicl::ParameterSet& ps)
47  : next_sequence_id_(1)
48  , requestBuffer_()
49  , bufferModeKeepLatest_(ps.get<bool>("buffer_mode_keep_latest", false))
50  , windowOffset_(ps.get<Fragment::timestamp_t>("request_window_offset", 0))
51  , windowWidth_(ps.get<Fragment::timestamp_t>("request_window_width", 0))
52  , staleTimeout_(ps.get<Fragment::timestamp_t>("stale_fragment_timeout", 0))
53  , expectedType_(ps.get<Fragment::type_t>("expected_fragment_type", Fragment::type_t(Fragment::EmptyFragmentType)))
54  , uniqueWindows_(ps.get<bool>("request_windows_are_unique", true))
55  , missing_request_window_timeout_us_(ps.get<size_t>("missing_request_window_timeout_us", 5000000))
56  , window_close_timeout_us_(ps.get<size_t>("window_close_timeout_us", 2000000))
57  , circularDataBufferMode_(ps.get<bool>("circular_buffer_mode", false))
58  , maxDataBufferDepthFragments_(ps.get<int>("data_buffer_depth_fragments", 1000))
59  , maxDataBufferDepthBytes_(ps.get<size_t>("data_buffer_depth_mb", 1000) * 1024 * 1024)
60  , systemFragmentCount_(0)
61  , should_stop_(false)
62 {
63  auto fragment_ids = ps.get<std::vector<artdaq::Fragment::fragment_id_t>>("fragment_ids", std::vector<artdaq::Fragment::fragment_id_t>());
64 
65  TLOG(TLVL_TRACE) << "artdaq::FragmentBuffer::FragmentBuffer(ps)";
66  int fragment_id = ps.get<int>("fragment_id", -99);
67 
68  if (fragment_id != -99)
69  {
70  if (fragment_ids.size() != 0)
71  {
72  auto report = "Error in FragmentBuffer: can't both define \"fragment_id\" and \"fragment_ids\" in FHiCL document";
73  TLOG(TLVL_ERROR) << report;
74  throw cet::exception(report);
75  }
76  else
77  {
78  fragment_ids.emplace_back(fragment_id);
79  }
80  }
81 
82  for (auto& id : fragment_ids)
83  {
84  dataBuffers_[id] = std::make_shared<DataBuffer>();
85  dataBuffers_[id]->DataBufferDepthBytes = 0;
86  dataBuffers_[id]->DataBufferDepthFragments = 0;
87  dataBuffers_[id]->HighestRequestSeen = 0;
88  dataBuffers_[id]->BufferFragmentKept = false;
89  }
90 
91  std::string modeString = ps.get<std::string>("request_mode", "ignored");
92  if (modeString == "single" || modeString == "Single")
93  {
94  mode_ = RequestMode::Single;
95  }
96  else if (modeString.find("buffer") != std::string::npos || modeString.find("Buffer") != std::string::npos)
97  {
98  mode_ = RequestMode::Buffer;
99  }
100  else if (modeString == "window" || modeString == "Window")
101  {
102  mode_ = RequestMode::Window;
103  }
104  else if (modeString.find("ignore") != std::string::npos || modeString.find("Ignore") != std::string::npos)
105  {
106  mode_ = RequestMode::Ignored;
107  }
108  else if (modeString.find("sequence") != std::string::npos || modeString.find("Sequence") != std::string::npos)
109  {
110  mode_ = RequestMode::SequenceID;
111  }
112  TLOG(TLVL_DEBUG) << "Request mode is " << printMode_();
113 }
114 
116 {
117  TLOG(TLVL_INFO) << "Fragment Buffer Destructor; Clearing data buffers";
118  Reset(true);
119 }
120 
122 {
123  should_stop_ = stop;
124  next_sequence_id_ = 1;
125  for (auto& id : dataBuffers_)
126  {
127  std::lock_guard<std::mutex> dlk(id.second->DataBufferMutex);
128  id.second->DataBufferDepthBytes = 0;
129  id.second->DataBufferDepthFragments = 0;
130  id.second->BufferFragmentKept = false;
131  id.second->DataBuffer.clear();
132  }
133 
134  {
135  std::lock_guard<std::mutex> lk(systemFragmentMutex_);
136  systemFragments_.clear();
137  systemFragmentCount_ = 0;
138  }
139 }
140 
142 {
143  std::unordered_map<Fragment::fragment_id_t, FragmentPtrs> frags_by_id;
144  while (!frags.empty())
145  {
146  auto dataIter = frags.begin();
147  auto frag_id = (*dataIter)->fragmentID();
148 
149  if ((*dataIter)->type() == Fragment::EndOfRunFragmentType || (*dataIter)->type() == Fragment::EndOfSubrunFragmentType || (*dataIter)->type() == Fragment::InitFragmentType)
150  {
151  std::lock_guard<std::mutex> lk(systemFragmentMutex_);
152  systemFragments_.emplace_back(std::move(*dataIter));
153  systemFragmentCount_++;
154  frags.erase(dataIter);
155  continue;
156  }
157 
158  if (!dataBuffers_.count(frag_id))
159  {
160  throw cet::exception("FragmentIDs") << "Received Fragment with Fragment ID " << frag_id << ", which is not in the declared Fragment IDs list!";
161  }
162 
163  frags_by_id[frag_id].emplace_back(std::move(*dataIter));
164  frags.erase(dataIter);
165  }
166 
167  auto type_it = frags_by_id.begin();
168  while (type_it != frags_by_id.end())
169  {
170  auto frag_id = type_it->first;
171 
172  waitForDataBufferReady(frag_id);
173  auto dataBuffer = dataBuffers_[frag_id];
174  std::lock_guard<std::mutex> dlk(dataBuffer->DataBufferMutex);
175  switch (mode_)
176  {
177  case RequestMode::Single:
178  {
179  auto dataIter = type_it->second.rbegin();
180  TLOG(TLVL_TRACE) << "Adding Fragment with Fragment ID " << frag_id << ", Sequence ID " << (*dataIter)->sequenceID() << ", and Timestamp " << (*dataIter)->timestamp() << " to buffer";
181  dataBuffer->DataBuffer.clear();
182  dataBuffer->DataBufferDepthBytes = (*dataIter)->sizeBytes();
183  dataBuffer->DataBuffer.emplace_back(std::move(*dataIter));
184  dataBuffer->DataBufferDepthFragments = 1;
185  type_it->second.clear();
186  }
187  break;
188  case RequestMode::Buffer:
189  case RequestMode::Ignored:
190  case RequestMode::Window:
191  case RequestMode::SequenceID:
192  default:
193  while (!type_it->second.empty())
194  {
195  auto dataIter = type_it->second.begin();
196  TLOG(TLVL_TRACE) << "Adding Fragment with Fragment ID " << frag_id << ", Sequence ID " << (*dataIter)->sequenceID() << ", and Timestamp " << (*dataIter)->timestamp() << " to buffer";
197 
198  dataBuffer->DataBufferDepthBytes += (*dataIter)->sizeBytes();
199  dataBuffer->DataBuffer.emplace_back(std::move(*dataIter));
200  type_it->second.erase(dataIter);
201  }
202  dataBuffer->DataBufferDepthFragments = dataBuffer->DataBuffer.size();
203  break;
204  }
205  getDataBufferStats(frag_id);
206  ++type_it;
207  }
208  dataCondition_.notify_all();
209 }
210 
212 {
213  TLOG(TLVL_CHECKSTOP) << "CFG::check_stop: should_stop=" << should_stop_.load();
214 
215  if (!should_stop_.load()) return false;
216  if (mode_ == RequestMode::Ignored)
217  {
218  return true;
219  }
220 
221  if (requestBuffer_ != nullptr)
222  {
223  // check_stop returns true if the CFG should stop. We should wait for the Request Buffer to report Request Receiver stopped before stopping.
224  TLOG(TLVL_DEBUG) << "should_stop is true, requestBuffer_->isRunning() is " << std::boolalpha << requestBuffer_->isRunning();
225  if (!requestBuffer_->isRunning())
226  {
227  return true;
228  }
229  }
230  return false;
231 }
232 
234 {
235  switch (mode_)
236  {
237  case RequestMode::Single:
238  return "Single";
239  case RequestMode::Buffer:
240  return "Buffer";
241  case RequestMode::Window:
242  return "Window";
243  case RequestMode::Ignored:
244  return "Ignored";
245  case RequestMode::SequenceID:
246  return "SequenceID";
247  }
248 
249  return "ERROR";
250 }
251 
253 {
254  size_t count = 0;
255  for (auto& id : dataBuffers_) count += id.second->DataBufferDepthFragments;
256  count += systemFragmentCount_.load();
257  return count;
258 }
259 
260 bool artdaq::FragmentBuffer::waitForDataBufferReady(Fragment::fragment_id_t id)
261 {
262  if (!dataBuffers_.count(id))
263  {
264  TLOG(TLVL_ERROR) << "DataBufferError: "
265  << "Error in FragmentBuffer: Cannot wait for data buffer for ID " << id << " because it does not exist!";
266  throw cet::exception("DataBufferError") << "Error in FragmentBuffer: Cannot wait for data buffer for ID " << id << " because it does not exist!";
267  }
268  auto startwait = std::chrono::steady_clock::now();
269  auto first = true;
270  auto lastwaittime = 0ULL;
271  auto dataBuffer = dataBuffers_[id];
272 
273  while (dataBufferIsTooLarge(id))
274  {
275  if (!circularDataBufferMode_)
276  {
277  if (should_stop_.load())
278  {
279  TLOG(TLVL_DEBUG) << "Run ended while waiting for buffer to shrink!";
280  getDataBufferStats(id);
281  dataCondition_.notify_all();
282  return false;
283  }
284  auto waittime = TimeUtils::GetElapsedTimeMilliseconds(startwait);
285 
286  if (first || (waittime != lastwaittime && waittime % 1000 == 0))
287  {
288  std::lock_guard<std::mutex> lk(dataBuffer->DataBufferMutex);
289  if (dataBufferIsTooLarge(id))
290  {
291  TLOG(TLVL_WARNING) << "Bad Omen: Data Buffer has exceeded its size limits. "
292  << "(seq_id=" << next_sequence_id_ << ", frag_id=" << id
293  << ", frags=" << dataBuffer->DataBufferDepthFragments << "/" << maxDataBufferDepthFragments_
294  << ", szB=" << dataBuffer->DataBufferDepthBytes << "/" << maxDataBufferDepthBytes_ << ")"
295  << ", timestamps=" << dataBuffer->DataBuffer.front()->timestamp() << "-" << dataBuffer->DataBuffer.back()->timestamp();
296  TLOG(TLVL_TRACE) << "Bad Omen: Possible causes include requests not getting through or Ignored-mode BR issues";
297  }
298  first = false;
299  }
300  if (waittime % 5 && waittime != lastwaittime)
301  {
302  TLOG(TLVL_WAITFORBUFFERREADY) << "getDataLoop: Data Retreival paused for " << waittime << " ms waiting for data buffer to drain";
303  }
304  lastwaittime = waittime;
305  usleep(1000);
306  }
307  else
308  {
309  std::lock_guard<std::mutex> lk(dataBuffer->DataBufferMutex);
310  if (dataBufferIsTooLarge(id))
311  {
312  auto begin = dataBuffer->DataBuffer.begin();
313  if (begin == dataBuffer->DataBuffer.end())
314  {
315  TLOG(TLVL_WARNING) << "Data buffer is reported as too large, but doesn't contain any Fragments! Possible corrupt memory!";
316  continue;
317  }
318  if (*begin)
319  {
320  TLOG(TLVL_WAITFORBUFFERREADY) << "waitForDataBufferReady: Dropping Fragment with timestamp " << (*begin)->timestamp() << " from data buffer (Buffer over-size, circular data buffer mode)";
321 
322  dataBuffer->DataBufferDepthBytes -= (*begin)->sizeBytes();
323  dataBuffer->DataBuffer.erase(begin);
324  dataBuffer->DataBufferDepthFragments = dataBuffer->DataBuffer.size();
325  dataBuffer->BufferFragmentKept = false; // If any Fragments are removed from data buffer, then we know we don't have to ignore the first one anymore
326  }
327  }
328  }
329  }
330  return true;
331 }
332 
333 bool artdaq::FragmentBuffer::dataBufferIsTooLarge(Fragment::fragment_id_t id)
334 {
335  if (!dataBuffers_.count(id))
336  {
337  TLOG(TLVL_ERROR) << "DataBufferError: "
338  << "Error in FragmentBuffer: Cannot check size of data buffer for ID " << id << " because it does not exist!";
339  throw cet::exception("DataBufferError") << "Error in FragmentBuffer: Cannot check size of data buffer for ID " << id << " because it does not exist!";
340  }
341  auto dataBuffer = dataBuffers_[id];
342  return (maxDataBufferDepthFragments_ > 0 && dataBuffer->DataBufferDepthFragments.load() > maxDataBufferDepthFragments_) ||
343  (maxDataBufferDepthBytes_ > 0 && dataBuffer->DataBufferDepthBytes.load() > maxDataBufferDepthBytes_);
344 }
345 
346 void artdaq::FragmentBuffer::getDataBufferStats(Fragment::fragment_id_t id)
347 {
348  if (!dataBuffers_.count(id))
349  {
350  TLOG(TLVL_ERROR) << "DataBufferError: "
351  << "Error in FragmentBuffer: Cannot get stats of data buffer for ID " << id << " because it does not exist!";
352  throw cet::exception("DataBufferError") << "Error in FragmentBuffer: Cannot get stats of data buffer for ID " << id << " because it does not exist!";
353  }
354  auto dataBuffer = dataBuffers_[id];
355 
356  if (metricMan)
357  {
358  TLOG(TLVL_GETBUFFERSTATS) << "getDataBufferStats: Sending Metrics";
359  metricMan->sendMetric("Buffer Depth Fragments", dataBuffer->DataBufferDepthFragments.load(), "fragments", 1, MetricMode::LastPoint);
360  metricMan->sendMetric("Buffer Depth Bytes", dataBuffer->DataBufferDepthBytes.load(), "bytes", 1, MetricMode::LastPoint);
361 
362  auto bufferDepthFragmentsPercent = dataBuffer->DataBufferDepthFragments.load() * 100 / static_cast<double>(maxDataBufferDepthFragments_);
363  auto bufferDepthBytesPercent = dataBuffer->DataBufferDepthBytes.load() * 100 / static_cast<double>(maxDataBufferDepthBytes_);
364  metricMan->sendMetric("Fragment Buffer Full %Fragments", bufferDepthFragmentsPercent, "%", 3, MetricMode::LastPoint);
365  metricMan->sendMetric("Fragment Buffer Full %Bytes", bufferDepthBytesPercent, "%", 3, MetricMode::LastPoint);
366  metricMan->sendMetric("Fragment Buffer Full %", bufferDepthFragmentsPercent > bufferDepthBytesPercent ? bufferDepthFragmentsPercent : bufferDepthBytesPercent, "%", 1, MetricMode::LastPoint);
367  }
368  TLOG(TLVL_GETBUFFERSTATS) << "getDataBufferStats: frags=" << dataBuffer->DataBufferDepthFragments.load() << "/" << maxDataBufferDepthFragments_
369  << ", sz=" << dataBuffer->DataBufferDepthBytes.load() << "/" << maxDataBufferDepthBytes_;
370 }
371 
372 void artdaq::FragmentBuffer::checkDataBuffer(Fragment::fragment_id_t id)
373 {
374  if (!dataBuffers_.count(id))
375  {
376  TLOG(TLVL_ERROR) << "DataBufferError: "
377  << "Error in FragmentBuffer: Cannot check data buffer for ID " << id << " because it does not exist!";
378  throw cet::exception("DataBufferError") << "Error in FragmentBuffer: Cannot check data buffer for ID " << id << " because it does not exist!";
379  }
380 
381  if (dataBuffers_[id]->DataBufferDepthFragments > 0 && mode_ != RequestMode::Single && mode_ != RequestMode::Ignored)
382  {
383  auto dataBuffer = dataBuffers_[id];
384  std::lock_guard<std::mutex> lk(dataBuffer->DataBufferMutex);
385 
386  // Eliminate extra fragments
387  while (dataBufferIsTooLarge(id))
388  {
389  auto begin = dataBuffer->DataBuffer.begin();
390  TLOG(TLVL_CHECKDATABUFFER) << "checkDataBuffer: Dropping Fragment with timestamp " << (*begin)->timestamp() << " from data buffer (Buffer over-size)";
391  dataBuffer->DataBufferDepthBytes -= (*begin)->sizeBytes();
392  dataBuffer->DataBuffer.erase(begin);
393  dataBuffer->DataBufferDepthFragments = dataBuffer->DataBuffer.size();
394  dataBuffer->BufferFragmentKept = false; // If any Fragments are removed from data buffer, then we know we don't have to ignore the first one anymore
395  }
396 
397  TLOG(TLVL_CHECKDATABUFFER) << "DataBufferDepthFragments is " << dataBuffer->DataBufferDepthFragments << ", DataBuffer.size is " << dataBuffer->DataBuffer.size();
398  if (dataBuffer->DataBufferDepthFragments > 0 && staleTimeout_ > 0)
399  {
400  TLOG(TLVL_CHECKDATABUFFER) << "Determining if Fragments can be dropped from data buffer";
401  Fragment::timestamp_t last = dataBuffer->DataBuffer.back()->timestamp();
402  Fragment::timestamp_t min = last > staleTimeout_ ? last - staleTimeout_ : 0;
403  for (auto it = dataBuffer->DataBuffer.begin(); it != dataBuffer->DataBuffer.end();)
404  {
405  if ((*it)->timestamp() < min)
406  {
407  TLOG(TLVL_CHECKDATABUFFER) << "checkDataBuffer: Dropping Fragment with timestamp " << (*it)->timestamp() << " from data buffer (timeout=" << staleTimeout_ << ", min=" << min << ")";
408  dataBuffer->DataBufferDepthBytes -= (*it)->sizeBytes();
409  dataBuffer->BufferFragmentKept = false; // If any Fragments are removed from data buffer, then we know we don't have to ignore the first one anymore
410  it = dataBuffer->DataBuffer.erase(it);
411  dataBuffer->DataBufferDepthFragments = dataBuffer->DataBuffer.size();
412  }
413  else
414  {
415  break;
416  }
417  }
418  }
419  }
420 }
421 
422 void artdaq::FragmentBuffer::applyRequestsIgnoredMode(artdaq::FragmentPtrs& frags)
423 {
424  // dataBuffersMutex_ is held by calling function
425  // We just copy everything that's here into the output.
426  TLOG(TLVL_APPLYREQUESTS) << "Mode is Ignored; Copying data to output";
427  for (auto& id : dataBuffers_)
428  {
429  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
430  if (id.second && !id.second->DataBuffer.empty() && id.second->DataBuffer.back()->sequenceID() >= next_sequence_id_)
431  {
432  next_sequence_id_ = id.second->DataBuffer.back()->sequenceID() + 1;
433  }
434  std::move(id.second->DataBuffer.begin(), id.second->DataBuffer.end(), std::inserter(frags, frags.end()));
435  id.second->DataBufferDepthBytes = 0;
436  id.second->DataBufferDepthFragments = 0;
437  id.second->BufferFragmentKept = false;
438  id.second->DataBuffer.clear();
439  }
440 }
441 
442 void artdaq::FragmentBuffer::applyRequestsSingleMode(artdaq::FragmentPtrs& frags)
443 {
444  // We only care about the latest request received. Send empties for all others.
445  auto requests = requestBuffer_->GetRequests();
446  while (requests.size() > 1)
447  {
448  // std::map is ordered by key => Last sequence ID in the map is the one we care about
449  requestBuffer_->RemoveRequest(requests.begin()->first);
450  requests.erase(requests.begin());
451  }
452  sendEmptyFragments(frags, requests);
453 
454  // If no requests remain after sendEmptyFragments, return
455  if (requests.size() == 0 || !requests.count(next_sequence_id_)) return;
456 
457  for (auto& id : dataBuffers_)
458  {
459  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
460  if (id.second->DataBufferDepthFragments > 0)
461  {
462  assert(id.second->DataBufferDepthFragments == 1);
463  TLOG(TLVL_APPLYREQUESTS) << "Mode is Single; Sending copy of last event";
464  for (auto& fragptr : id.second->DataBuffer)
465  {
466  // Return the latest data point
467  auto frag = fragptr.get();
468  auto newfrag = std::unique_ptr<artdaq::Fragment>(new Fragment(next_sequence_id_, frag->fragmentID()));
469  newfrag->resize(frag->size() - detail::RawFragmentHeader::num_words());
470  memcpy(newfrag->headerAddress(), frag->headerAddress(), frag->sizeBytes());
471  newfrag->setTimestamp(requests[next_sequence_id_]);
472  newfrag->setSequenceID(next_sequence_id_);
473  frags.push_back(std::move(newfrag));
474  }
475  }
476  else
477  {
478  sendEmptyFragment(frags, next_sequence_id_, id.first, "No data for");
479  }
480  }
481  requestBuffer_->RemoveRequest(next_sequence_id_);
482  ++next_sequence_id_;
483 }
484 
485 void artdaq::FragmentBuffer::applyRequestsBufferMode(artdaq::FragmentPtrs& frags)
486 {
487  // We only care about the latest request received. Send empties for all others.
488  auto requests = requestBuffer_->GetRequests();
489  while (requests.size() > 1)
490  {
491  // std::map is ordered by key => Last sequence ID in the map is the one we care about
492  requestBuffer_->RemoveRequest(requests.begin()->first);
493  requests.erase(requests.begin());
494  }
495  sendEmptyFragments(frags, requests);
496 
497  // If no requests remain after sendEmptyFragments, return
498  if (requests.size() == 0 || !requests.count(next_sequence_id_)) return;
499 
500  for (auto& id : dataBuffers_)
501  {
502  TLOG(TLVL_DEBUG) << "applyRequestsBufferMode: Creating ContainerFragment for Buffered Fragments";
503  frags.emplace_back(new artdaq::Fragment(next_sequence_id_, id.first));
504  frags.back()->setTimestamp(requests[next_sequence_id_]);
505  ContainerFragmentLoader cfl(*frags.back());
506  cfl.set_missing_data(false); // Buffer mode is never missing data, even if there IS no data.
507 
508  // If we kept a Fragment from the previous iteration, but more data has arrived, discard it
509  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
510  if (id.second->BufferFragmentKept && id.second->DataBufferDepthFragments > 1)
511  {
512  id.second->DataBufferDepthBytes -= id.second->DataBuffer.front()->sizeBytes();
513  id.second->DataBuffer.erase(id.second->DataBuffer.begin());
514  id.second->DataBufferDepthFragments = id.second->DataBuffer.size();
515  }
516 
517  // Buffer mode TFGs should simply copy out the whole dataBuffer_ into a ContainerFragment
518  FragmentPtrs fragsToAdd;
519  std::move(id.second->DataBuffer.begin(), --id.second->DataBuffer.end(), std::back_inserter(fragsToAdd));
520  id.second->DataBuffer.erase(id.second->DataBuffer.begin(), --id.second->DataBuffer.end());
521 
522  if (fragsToAdd.size() > 0)
523  {
524  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsBufferMode: Adding " << fragsToAdd.size() << " Fragments to Container";
525  cfl.addFragments(fragsToAdd);
526  }
527 
528  if (id.second->DataBuffer.size() == 1)
529  {
530  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsBufferMode: Adding Fragment with timestamp " << id.second->DataBuffer.front()->timestamp() << " to Container with sequence ID " << next_sequence_id_;
531  cfl.addFragment(id.second->DataBuffer.front());
532  if (bufferModeKeepLatest_)
533  {
534  id.second->BufferFragmentKept = true;
535  id.second->DataBufferDepthBytes = id.second->DataBuffer.front()->sizeBytes();
536  id.second->DataBufferDepthFragments = id.second->DataBuffer.size(); // 1
537  }
538  else
539  {
540  id.second->DataBuffer.clear();
541  id.second->BufferFragmentKept = false;
542  id.second->DataBufferDepthBytes = 0;
543  id.second->DataBufferDepthFragments = 0;
544  }
545  }
546  }
547  requestBuffer_->RemoveRequest(next_sequence_id_);
548  ++next_sequence_id_;
549 }
550 
551 void artdaq::FragmentBuffer::applyRequestsWindowMode_CheckAndFillDataBuffer(artdaq::FragmentPtrs& frags, artdaq::Fragment::fragment_id_t id, artdaq::Fragment::sequence_id_t seq, artdaq::Fragment::timestamp_t ts)
552 {
553  auto dataBuffer = dataBuffers_[id];
554 
555  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode_CheckAndFillDataBuffer: Checking that data exists for request window " << seq;
556  Fragment::timestamp_t min = ts > windowOffset_ ? ts - windowOffset_ : 0;
557  Fragment::timestamp_t max = ts + windowWidth_ > windowOffset_ ? ts + windowWidth_ - windowOffset_ : 1;
558 
559  TLOG(TLVL_APPLYREQUESTS) << "ApplyRequestsWindowsMode_CheckAndFillDataBuffer: min is " << min << ", max is " << max
560  << " and first/last points in buffer are " << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.front()->timestamp() : 0)
561  << "/" << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.back()->timestamp() : 0)
562  << " (sz=" << dataBuffer->DataBufferDepthFragments << " [" << dataBuffer->DataBufferDepthBytes.load()
563  << "/" << maxDataBufferDepthBytes_ << "])";
564  bool windowClosed = dataBuffer->DataBufferDepthFragments > 0 && dataBuffer->DataBuffer.back()->timestamp() >= max;
565  bool windowTimeout = !windowClosed && TimeUtils::GetElapsedTimeMicroseconds(requestBuffer_->GetRequestTime(seq)) > window_close_timeout_us_;
566  if (windowTimeout)
567  {
568  TLOG(TLVL_WARNING) << "applyRequestsWindowMode_CheckAndFillDataBuffer: A timeout occurred waiting for data to close the request window ({" << min << "-" << max
569  << "}, buffer={" << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.front()->timestamp() : 0) << "-"
570  << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.back()->timestamp() : 0)
571  << "} ). Time waiting: "
572  << TimeUtils::GetElapsedTimeMicroseconds(requestBuffer_->GetRequestTime(seq)) << " us "
573  << "(> " << window_close_timeout_us_ << " us).";
574  }
575  if (windowClosed || windowTimeout)
576  {
577  TLOG(TLVL_DEBUG) << "applyRequestsWindowMode_CheckAndFillDataBuffer: Creating ContainerFragment for Window-requested Fragments";
578  frags.emplace_back(new artdaq::Fragment(seq, id));
579  frags.back()->setTimestamp(ts);
580  ContainerFragmentLoader cfl(*frags.back());
581 
582  // In the spirit of NOvA's MegaPool: (RS = Request start (min), RE = Request End (max))
583  // --- | Buffer Start | --- | Buffer End | ---
584  //1. RS RE | | | |
585  //2. RS | | RE | |
586  //3. RS | | | | RE
587  //4. | | RS RE | |
588  //5. | | RS | | RE
589  //6. | | | | RS RE
590  //
591  // If RE (or RS) is after the end of the buffer, we wait for window_close_timeout_us_. If we're here, then that means that windowClosed is false, and the missing_data flag should be set.
592  // If RS (or RE) is before the start of the buffer, then missing_data should be set to true, as data is assumed to arrive in the buffer in timestamp order
593  // If the dataBuffer has size 0, then windowClosed will be false
594  if (!windowClosed || (dataBuffer->DataBufferDepthFragments > 0 && dataBuffer->DataBuffer.front()->timestamp() > min))
595  {
596  TLOG(TLVL_DEBUG) << "applyRequestsWindowMode_CheckAndFillDataBuffer: Request window starts before and/or ends after the current data buffer, setting ContainerFragment's missing_data flag!"
597  << " (requestWindowRange=[" << min << "," << max << "], "
598  << "buffer={" << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.front()->timestamp() : 0) << "-"
599  << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.back()->timestamp() : 0) << "}";
600  cfl.set_missing_data(true);
601  }
602 
603  auto it = dataBuffer->DataBuffer.begin();
604  // Likely that it will be closer to the end...
605  if (windowTimeout)
606  {
607  it = dataBuffer->DataBuffer.end();
608  --it;
609  while (it != dataBuffer->DataBuffer.begin())
610  {
611  if ((*it)->timestamp() < min)
612  {
613  break;
614  }
615  --it;
616  }
617  }
618 
619  FragmentPtrs fragsToAdd;
620  // Do a little bit more work to decide which fragments to send for a given request
621  for (; it != dataBuffer->DataBuffer.end();)
622  {
623  Fragment::timestamp_t fragT = (*it)->timestamp();
624  if (fragT < min)
625  {
626  ++it;
627  continue;
628  }
629  if (fragT > max || (fragT == max && windowWidth_ > 0))
630  { break; }
631 
632  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode_CheckAndFillDataBuffer: Adding Fragment with timestamp " << (*it)->timestamp() << " to Container";
633  if (uniqueWindows_)
634  {
635  dataBuffer->DataBufferDepthBytes -= (*it)->sizeBytes();
636  fragsToAdd.emplace_back(std::move(*it));
637  it = dataBuffer->DataBuffer.erase(it);
638  }
639  else
640  {
641  fragsToAdd.emplace_back(it->get());
642  ++it;
643  }
644  }
645 
646  if (fragsToAdd.size() > 0)
647  {
648  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode_CheckAndFillDataBuffer: Adding " << fragsToAdd.size() << " Fragments to Container";
649  cfl.addFragments(fragsToAdd);
650 
651  // Don't delete Fragments which are still in the Fragment buffer
652  if (!uniqueWindows_)
653  {
654  for (auto& frag : fragsToAdd)
655  {
656  frag.release();
657  }
658  }
659  fragsToAdd.clear();
660  }
661 
662  dataBuffer->DataBufferDepthFragments = dataBuffer->DataBuffer.size();
663  dataBuffer->WindowsSent[seq] = std::chrono::steady_clock::now();
664  if (seq > dataBuffer->HighestRequestSeen) dataBuffer->HighestRequestSeen = seq;
665  }
666 }
667 
668 void artdaq::FragmentBuffer::applyRequestsWindowMode(artdaq::FragmentPtrs& frags)
669 {
670  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode BEGIN";
671 
672  auto requests = requestBuffer_->GetRequests();
673 
674  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode: Starting request processing for " << requests.size() << " requests";
675  for (auto req = requests.begin(); req != requests.end();)
676  {
677  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode: processing request with sequence ID " << req->first << ", timestamp " << req->second;
678 
679  while (req->first < next_sequence_id_ && requests.size() > 0)
680  {
681  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode: Clearing passed request for sequence ID " << req->first;
682  requestBuffer_->RemoveRequest(req->first);
683  req = requests.erase(req);
684  }
685  if (requests.size() == 0) break;
686 
687  for (auto& id : dataBuffers_)
688  {
689  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
690  if (!id.second->WindowsSent.count(req->first))
691  {
692  applyRequestsWindowMode_CheckAndFillDataBuffer(frags, id.first, req->first, req->second);
693  }
694  }
695  checkSentWindows(req->first);
696  ++req;
697  }
698 
699  // Check sent windows for requests that can be removed
700  std::set<artdaq::Fragment::sequence_id_t> seqs;
701  for (auto& id : dataBuffers_)
702  {
703  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
704  for (auto& seq : id.second->WindowsSent)
705  {
706  seqs.insert(seq.first);
707  }
708  }
709  for (auto& seq : seqs)
710  {
711  checkSentWindows(seq);
712  }
713 }
714 
716 {
717  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsSequenceIDMode BEGIN";
718 
719  auto requests = requestBuffer_->GetRequests();
720 
721  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsSequenceIDMode: Starting request processing";
722  for (auto req = requests.begin(); req != requests.end();)
723  {
724  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsSequenceIDMode: Checking that data exists for request SequenceID " << req->first;
725 
726  for (auto& id : dataBuffers_)
727  {
728  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
729  if (!id.second->WindowsSent.count(req->first))
730  {
731  TLOG(29) << "Searching id " << id.first << " for Fragments with Sequence ID " << req->first;
732  for (auto it = id.second->DataBuffer.begin(); it != id.second->DataBuffer.end();)
733  {
734  auto seq = (*it)->sequenceID();
735  TLOG(29) << "applyRequestsSequenceIDMode: Fragment SeqID " << seq << ", request ID " << req->first;
736  if (seq == req->first)
737  {
738  TLOG(29) << "applyRequestsSequenceIDMode: Adding Fragment to output";
739  id.second->WindowsSent[req->first] = std::chrono::steady_clock::now();
740  id.second->DataBufferDepthBytes -= (*it)->sizeBytes();
741  frags.push_back(std::move(*it));
742  it = id.second->DataBuffer.erase(it);
743  id.second->DataBufferDepthFragments = id.second->DataBuffer.size();
744  }
745  else
746  {
747  ++it;
748  }
749  }
750  }
751  if (req->first > id.second->HighestRequestSeen) id.second->HighestRequestSeen = req->first;
752  }
753  checkSentWindows(req->first);
754  ++req;
755  }
756 
757  // Check sent windows for requests that can be removed
758  std::set<artdaq::Fragment::sequence_id_t> seqs;
759  for (auto& id : dataBuffers_)
760  {
761  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
762  for (auto& seq : id.second->WindowsSent)
763  {
764  seqs.insert(seq.first);
765  }
766  }
767  for (auto& seq : seqs)
768  {
769  checkSentWindows(seq);
770  }
771 }
772 
773 bool artdaq::FragmentBuffer::applyRequests(artdaq::FragmentPtrs& frags)
774 {
775  if (check_stop())
776  {
777  return false;
778  }
779 
780  // Wait for data, if in ignored mode, or a request otherwise
781  if (mode_ == RequestMode::Ignored)
782  {
783  auto start_time = std::chrono::steady_clock::now();
784  while (dataBufferFragmentCount_() == 0 && TimeUtils::GetElapsedTime(start_time) < 1.0)
785  {
786  if (check_stop()) return false;
787  std::unique_lock<std::mutex> lock(dataConditionMutex_);
788  dataCondition_.wait_for(lock, std::chrono::milliseconds(10), [this]() { return dataBufferFragmentCount_() > 0; });
789  }
790  }
791  else if (requestBuffer_ == nullptr)
792  {
793  TLOG(TLVL_ERROR) << "Request Buffer must be set (via SetRequestBuffer) before applyRequests/getData can be called!";
794  return false;
795  }
796  else
797  {
798  if ((check_stop() && requestBuffer_->size() == 0)) return false;
799 
800  std::unique_lock<std::mutex> lock(dataConditionMutex_);
801  dataCondition_.wait_for(lock, std::chrono::milliseconds(10));
802 
803  checkDataBuffers();
804 
805  // Wait up to 1000 ms for a request...
806  auto counter = 0;
807 
808  while (requestBuffer_->size() == 0 && counter < 100)
809  {
810  if (check_stop()) return false;
811 
812  checkDataBuffers();
813 
814  requestBuffer_->WaitForRequests(10); // milliseconds
815  counter++;
816  }
817  }
818 
819  if (systemFragmentCount_.load() > 0)
820  {
821  std::lock_guard<std::mutex> lk(systemFragmentMutex_);
822  TLOG(TLVL_INFO) << "Copying " << systemFragmentCount_.load() << " System Fragments into output";
823 
824  std::move(systemFragments_.begin(), systemFragments_.end(), std::inserter(frags, frags.end()));
825  systemFragments_.clear();
826  systemFragmentCount_ = 0;
827  }
828 
829  switch (mode_)
830  {
831  case RequestMode::Single:
832  applyRequestsSingleMode(frags);
833  break;
834  case RequestMode::Window:
835  applyRequestsWindowMode(frags);
836  break;
837  case RequestMode::Buffer:
838  applyRequestsBufferMode(frags);
839  break;
840  case RequestMode::SequenceID:
841  applyRequestsSequenceIDMode(frags);
842  break;
843  case RequestMode::Ignored:
844  default:
845  applyRequestsIgnoredMode(frags);
846  break;
847  }
848 
849  getDataBuffersStats();
850 
851  if (frags.size() > 0)
852  TLOG(TLVL_APPLYREQUESTS) << "Finished Processing requests, returning " << frags.size() << " fragments, current ev_counter is " << next_sequence_id_;
853  return true;
854 }
855 
856 bool artdaq::FragmentBuffer::sendEmptyFragment(artdaq::FragmentPtrs& frags, size_t seqId, Fragment::fragment_id_t fragmentId, std::string desc)
857 {
858  TLOG(TLVL_EMPTYFRAGMENT) << desc << " sequence ID " << seqId << ", sending empty fragment";
859  auto frag = new Fragment();
860  frag->setSequenceID(seqId);
861  frag->setFragmentID(fragmentId);
862  frag->setSystemType(Fragment::EmptyFragmentType);
863  frags.emplace_back(FragmentPtr(frag));
864  return true;
865 }
866 
867 void artdaq::FragmentBuffer::sendEmptyFragments(artdaq::FragmentPtrs& frags, std::map<Fragment::sequence_id_t, Fragment::timestamp_t>& requests)
868 {
869  if (requests.size() > 0)
870  {
871  TLOG(TLVL_SENDEMPTYFRAGMENTS) << "Sending Empty Fragments for Sequence IDs from " << next_sequence_id_ << " up to but not including " << requests.begin()->first;
872  while (requests.begin()->first > next_sequence_id_)
873  {
874  for (auto& fid : dataBuffers_)
875  {
876  sendEmptyFragment(frags, next_sequence_id_, fid.first, "Missed request for");
877  }
878  ++next_sequence_id_;
879  }
880  }
881 }
882 
883 void artdaq::FragmentBuffer::checkSentWindows(artdaq::Fragment::sequence_id_t seq)
884 {
885  TLOG(TLVL_CHECKWINDOWS) << "checkSentWindows: Checking if request " << seq << " can be removed from request list";
886  bool seqComplete = true;
887  bool seqTimeout = false;
888  for (auto& id : dataBuffers_)
889  {
890  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
891  if (!id.second->WindowsSent.count(seq) || id.second->HighestRequestSeen < seq)
892  {
893  seqComplete = false;
894  }
895  if (id.second->WindowsSent.count(seq) && TimeUtils::GetElapsedTimeMicroseconds(id.second->WindowsSent[seq]) > missing_request_window_timeout_us_)
896  {
897  seqTimeout = true;
898  }
899  }
900  if (seqComplete)
901  {
902  TLOG(TLVL_CHECKWINDOWS) << "checkSentWindows: Request " << seq << " is complete, removing from requestBuffer_.";
903  requestBuffer_->RemoveRequest(seq);
904 
905  if (next_sequence_id_ == seq)
906  {
907  TLOG(TLVL_CHECKWINDOWS) << "checkSentWindows: Sequence ID matches ev_counter, incrementing ev_counter (" << next_sequence_id_ << ")";
908 
909  for (auto& id : dataBuffers_)
910  {
911  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
912  id.second->WindowsSent.erase(seq);
913  }
914 
915  ++next_sequence_id_;
916  }
917  }
918  if (seqTimeout)
919  {
920  TLOG(TLVL_CHECKWINDOWS) << "checkSentWindows: Sent Window history indicates that requests between " << next_sequence_id_ << " and " << seq << " have timed out.";
921  while (next_sequence_id_ <= seq)
922  {
923  if (next_sequence_id_ < seq) TLOG(TLVL_CHECKWINDOWS) << "Missed request for sequence ID " << next_sequence_id_ << "! Will not send any data for this sequence ID!";
924  requestBuffer_->RemoveRequest(next_sequence_id_);
925 
926  for (auto& id : dataBuffers_)
927  {
928  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
929  id.second->WindowsSent.erase(next_sequence_id_);
930  }
931 
932  ++next_sequence_id_;
933  }
934  }
935 }
void AddFragmentsToBuffer(FragmentPtrs frags)
Add Fragments to the FragmentBuffer.
size_t dataBufferFragmentCount_()
Get the total number of Fragments in all data buffers.
std::string printMode_()
Return the string representation of the current RequestMode.
bool applyRequests(FragmentPtrs &frags)
See if any requests have been received, and add the corresponding data Fragment objects to the output...
FragmentBuffer(const fhicl::ParameterSet &ps)
FragmentBuffer Constructor.
bool waitForDataBufferReady(Fragment::fragment_id_t id)
Wait for the data buffer to drain (dataBufferIsTooLarge returns false), periodically reporting status...
void applyRequestsIgnoredMode(artdaq::FragmentPtrs &frags)
Create fragments using data buffer for request mode Ignored. Precondition: dataBufferMutex_ and reque...
void applyRequestsWindowMode_CheckAndFillDataBuffer(artdaq::FragmentPtrs &frags, artdaq::Fragment::fragment_id_t id, artdaq::Fragment::sequence_id_t seq, artdaq::Fragment::timestamp_t ts)
bool check_stop()
Routine used by applyRequests to make sure that all outstanding requests have been fulfilled before r...
void Reset(bool stop)
Reset the FragmentBuffer (flushes all Fragments from buffers)
void checkSentWindows(Fragment::sequence_id_t seq)
Check the windows_sent_ooo_ map for sequence IDs that may be removed.
artdaq::Fragment::fragment_id_t fragment_id() const
Get the Fragment ID of this Fragment generator.
void checkDataBuffer(Fragment::fragment_id_t id)
Perform data buffer pruning operations for the given buffer. If the RequestMode is Single...
bool dataBufferIsTooLarge(Fragment::fragment_id_t id)
Test the configured constraints on the data buffer.
bool sendEmptyFragment(FragmentPtrs &frags, size_t sequenceId, Fragment::fragment_id_t fragmentId, std::string desc)
Send an EmptyFragmentType Fragment.
void applyRequestsBufferMode(artdaq::FragmentPtrs &frags)
Create fragments using data buffer for request mode Buffer. Precondition: dataBufferMutex_ and reques...
void applyRequestsWindowMode(artdaq::FragmentPtrs &frags)
Create fragments using data buffer for request mode Window. Precondition: dataBufferMutex_ and reques...
virtual ~FragmentBuffer()
FragmentBuffer Destructor.
void sendEmptyFragments(FragmentPtrs &frags, std::map< Fragment::sequence_id_t, Fragment::timestamp_t > &requests)
This function is for Buffered and Single request modes, as they can only respond to one data request ...
void applyRequestsSequenceIDMode(artdaq::FragmentPtrs &frags)
Create fragments using data buffer for request mode SequenceID. Precondition: dataBufferMutex_ and re...
void applyRequestsSingleMode(artdaq::FragmentPtrs &frags)
Create fragments using data buffer for request mode Single. Precondition: dataBufferMutex_ and reques...
void getDataBufferStats(Fragment::fragment_id_t id)
Calculate the size of the dataBuffer and report appropriate metrics.