artdaq  v3_09_02
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  TLOG(TLVL_WARNING) << "Bad Omen: Data Buffer has exceeded its size limits. "
289  << "(seq_id=" << next_sequence_id_ << ", frag_id=" << id
290  << ", frags=" << dataBuffer->DataBufferDepthFragments << "/" << maxDataBufferDepthFragments_
291  << ", szB=" << dataBuffer->DataBufferDepthBytes << "/" << maxDataBufferDepthBytes_ << ")"
292  << ", timestamps=" << dataBuffer->DataBuffer.front()->timestamp() << "-" << dataBuffer->DataBuffer.back()->timestamp();
293  TLOG(TLVL_TRACE) << "Bad Omen: Possible causes include requests not getting through or Ignored-mode BR issues";
294  first = false;
295  }
296  if (waittime % 5 && waittime != lastwaittime)
297  {
298  TLOG(TLVL_WAITFORBUFFERREADY) << "getDataLoop: Data Retreival paused for " << waittime << " ms waiting for data buffer to drain";
299  }
300  lastwaittime = waittime;
301  usleep(1000);
302  }
303  else
304  {
305  std::lock_guard<std::mutex> lk(dataBuffer->DataBufferMutex);
306  if (dataBufferIsTooLarge(id))
307  {
308  auto begin = dataBuffer->DataBuffer.begin();
309  if (begin == dataBuffer->DataBuffer.end())
310  {
311  TLOG(TLVL_WARNING) << "Data buffer is reported as too large, but doesn't contain any Fragments! Possible corrupt memory!";
312  continue;
313  }
314  if (*begin)
315  {
316  TLOG(TLVL_WAITFORBUFFERREADY) << "waitForDataBufferReady: Dropping Fragment with timestamp " << (*begin)->timestamp() << " from data buffer (Buffer over-size, circular data buffer mode)";
317 
318  dataBuffer->DataBufferDepthBytes -= (*begin)->sizeBytes();
319  dataBuffer->DataBuffer.erase(begin);
320  dataBuffer->DataBufferDepthFragments = dataBuffer->DataBuffer.size();
321  dataBuffer->BufferFragmentKept = false; // If any Fragments are removed from data buffer, then we know we don't have to ignore the first one anymore
322  }
323  }
324  }
325  }
326  return true;
327 }
328 
329 bool artdaq::FragmentBuffer::dataBufferIsTooLarge(Fragment::fragment_id_t id)
330 {
331  if (!dataBuffers_.count(id))
332  {
333  TLOG(TLVL_ERROR) << "DataBufferError: "
334  << "Error in FragmentBuffer: Cannot check size of data buffer for ID " << id << " because it does not exist!";
335  throw cet::exception("DataBufferError") << "Error in FragmentBuffer: Cannot check size of data buffer for ID " << id << " because it does not exist!";
336  }
337  auto dataBuffer = dataBuffers_[id];
338  return (maxDataBufferDepthFragments_ > 0 && dataBuffer->DataBufferDepthFragments.load() > maxDataBufferDepthFragments_) ||
339  (maxDataBufferDepthBytes_ > 0 && dataBuffer->DataBufferDepthBytes.load() > maxDataBufferDepthBytes_);
340 }
341 
342 void artdaq::FragmentBuffer::getDataBufferStats(Fragment::fragment_id_t id)
343 {
344  if (!dataBuffers_.count(id))
345  {
346  TLOG(TLVL_ERROR) << "DataBufferError: "
347  << "Error in FragmentBuffer: Cannot get stats of data buffer for ID " << id << " because it does not exist!";
348  throw cet::exception("DataBufferError") << "Error in FragmentBuffer: Cannot get stats of data buffer for ID " << id << " because it does not exist!";
349  }
350  auto dataBuffer = dataBuffers_[id];
351 
352  if (metricMan)
353  {
354  TLOG(TLVL_GETBUFFERSTATS) << "getDataBufferStats: Sending Metrics";
355  metricMan->sendMetric("Buffer Depth Fragments", dataBuffer->DataBufferDepthFragments.load(), "fragments", 1, MetricMode::LastPoint);
356  metricMan->sendMetric("Buffer Depth Bytes", dataBuffer->DataBufferDepthBytes.load(), "bytes", 1, MetricMode::LastPoint);
357 
358  auto bufferDepthFragmentsPercent = dataBuffer->DataBufferDepthFragments.load() * 100 / static_cast<double>(maxDataBufferDepthFragments_);
359  auto bufferDepthBytesPercent = dataBuffer->DataBufferDepthBytes.load() * 100 / static_cast<double>(maxDataBufferDepthBytes_);
360  metricMan->sendMetric("Fragment Buffer Full %Fragments", bufferDepthFragmentsPercent, "%", 3, MetricMode::LastPoint);
361  metricMan->sendMetric("Fragment Buffer Full %Bytes", bufferDepthBytesPercent, "%", 3, MetricMode::LastPoint);
362  metricMan->sendMetric("Fragment Buffer Full %", bufferDepthFragmentsPercent > bufferDepthBytesPercent ? bufferDepthFragmentsPercent : bufferDepthBytesPercent, "%", 1, MetricMode::LastPoint);
363  }
364  TLOG(TLVL_GETBUFFERSTATS) << "getDataBufferStats: frags=" << dataBuffer->DataBufferDepthFragments.load() << "/" << maxDataBufferDepthFragments_
365  << ", sz=" << dataBuffer->DataBufferDepthBytes.load() << "/" << maxDataBufferDepthBytes_;
366 }
367 
368 void artdaq::FragmentBuffer::checkDataBuffer(Fragment::fragment_id_t id)
369 {
370  if (!dataBuffers_.count(id))
371  {
372  TLOG(TLVL_ERROR) << "DataBufferError: "
373  << "Error in FragmentBuffer: Cannot check data buffer for ID " << id << " because it does not exist!";
374  throw cet::exception("DataBufferError") << "Error in FragmentBuffer: Cannot check data buffer for ID " << id << " because it does not exist!";
375  }
376 
377  if (dataBuffers_[id]->DataBufferDepthFragments > 0 && mode_ != RequestMode::Single && mode_ != RequestMode::Ignored)
378  {
379  auto dataBuffer = dataBuffers_[id];
380  std::lock_guard<std::mutex> lk(dataBuffer->DataBufferMutex);
381 
382  // Eliminate extra fragments
383  while (dataBufferIsTooLarge(id))
384  {
385  auto begin = dataBuffer->DataBuffer.begin();
386  TLOG(TLVL_CHECKDATABUFFER) << "checkDataBuffer: Dropping Fragment with timestamp " << (*begin)->timestamp() << " from data buffer (Buffer over-size)";
387  dataBuffer->DataBufferDepthBytes -= (*begin)->sizeBytes();
388  dataBuffer->DataBuffer.erase(begin);
389  dataBuffer->DataBufferDepthFragments = dataBuffer->DataBuffer.size();
390  dataBuffer->BufferFragmentKept = false; // If any Fragments are removed from data buffer, then we know we don't have to ignore the first one anymore
391  }
392 
393  TLOG(TLVL_CHECKDATABUFFER) << "DataBufferDepthFragments is " << dataBuffer->DataBufferDepthFragments << ", DataBuffer.size is " << dataBuffer->DataBuffer.size();
394  if (dataBuffer->DataBufferDepthFragments > 0 && staleTimeout_ > 0)
395  {
396  TLOG(TLVL_CHECKDATABUFFER) << "Determining if Fragments can be dropped from data buffer";
397  Fragment::timestamp_t last = dataBuffer->DataBuffer.back()->timestamp();
398  Fragment::timestamp_t min = last > staleTimeout_ ? last - staleTimeout_ : 0;
399  for (auto it = dataBuffer->DataBuffer.begin(); it != dataBuffer->DataBuffer.end();)
400  {
401  if ((*it)->timestamp() < min)
402  {
403  TLOG(TLVL_CHECKDATABUFFER) << "checkDataBuffer: Dropping Fragment with timestamp " << (*it)->timestamp() << " from data buffer (timeout=" << staleTimeout_ << ", min=" << min << ")";
404  dataBuffer->DataBufferDepthBytes -= (*it)->sizeBytes();
405  dataBuffer->BufferFragmentKept = false; // If any Fragments are removed from data buffer, then we know we don't have to ignore the first one anymore
406  it = dataBuffer->DataBuffer.erase(it);
407  dataBuffer->DataBufferDepthFragments = dataBuffer->DataBuffer.size();
408  }
409  else
410  {
411  break;
412  }
413  }
414  }
415  }
416 }
417 
418 void artdaq::FragmentBuffer::applyRequestsIgnoredMode(artdaq::FragmentPtrs& frags)
419 {
420  // dataBuffersMutex_ is held by calling function
421  // We just copy everything that's here into the output.
422  TLOG(TLVL_APPLYREQUESTS) << "Mode is Ignored; Copying data to output";
423  for (auto& id : dataBuffers_)
424  {
425  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
426  std::move(id.second->DataBuffer.begin(), id.second->DataBuffer.end(), std::inserter(frags, frags.end()));
427  id.second->DataBufferDepthBytes = 0;
428  id.second->DataBufferDepthFragments = 0;
429  id.second->BufferFragmentKept = false;
430  id.second->DataBuffer.clear();
431  }
432 }
433 
434 void artdaq::FragmentBuffer::applyRequestsSingleMode(artdaq::FragmentPtrs& frags)
435 {
436  // We only care about the latest request received. Send empties for all others.
437  auto requests = requestBuffer_->GetRequests();
438  while (requests.size() > 1)
439  {
440  // std::map is ordered by key => Last sequence ID in the map is the one we care about
441  requestBuffer_->RemoveRequest(requests.begin()->first);
442  requests.erase(requests.begin());
443  }
444  sendEmptyFragments(frags, requests);
445 
446  // If no requests remain after sendEmptyFragments, return
447  if (requests.size() == 0 || !requests.count(next_sequence_id_)) return;
448 
449  for (auto& id : dataBuffers_)
450  {
451  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
452  if (id.second->DataBufferDepthFragments > 0)
453  {
454  assert(id.second->DataBufferDepthFragments == 1);
455  TLOG(TLVL_APPLYREQUESTS) << "Mode is Single; Sending copy of last event";
456  for (auto& fragptr : id.second->DataBuffer)
457  {
458  // Return the latest data point
459  auto frag = fragptr.get();
460  auto newfrag = std::unique_ptr<artdaq::Fragment>(new Fragment(next_sequence_id_, frag->fragmentID()));
461  newfrag->resize(frag->size() - detail::RawFragmentHeader::num_words());
462  memcpy(newfrag->headerAddress(), frag->headerAddress(), frag->sizeBytes());
463  newfrag->setTimestamp(requests[next_sequence_id_]);
464  newfrag->setSequenceID(next_sequence_id_);
465  frags.push_back(std::move(newfrag));
466  }
467  }
468  else
469  {
470  sendEmptyFragment(frags, next_sequence_id_, id.first, "No data for");
471  }
472  }
473  requestBuffer_->RemoveRequest(next_sequence_id_);
474  ++next_sequence_id_;
475 }
476 
477 void artdaq::FragmentBuffer::applyRequestsBufferMode(artdaq::FragmentPtrs& frags)
478 {
479  // We only care about the latest request received. Send empties for all others.
480  auto requests = requestBuffer_->GetRequests();
481  while (requests.size() > 1)
482  {
483  // std::map is ordered by key => Last sequence ID in the map is the one we care about
484  requestBuffer_->RemoveRequest(requests.begin()->first);
485  requests.erase(requests.begin());
486  }
487  sendEmptyFragments(frags, requests);
488 
489  // If no requests remain after sendEmptyFragments, return
490  if (requests.size() == 0 || !requests.count(next_sequence_id_)) return;
491 
492  for (auto& id : dataBuffers_)
493  {
494  TLOG(TLVL_DEBUG) << "applyRequestsBufferMode: Creating ContainerFragment for Buffered Fragments";
495  frags.emplace_back(new artdaq::Fragment(next_sequence_id_, id.first));
496  frags.back()->setTimestamp(requests[next_sequence_id_]);
497  ContainerFragmentLoader cfl(*frags.back());
498  cfl.set_missing_data(false); // Buffer mode is never missing data, even if there IS no data.
499 
500  // If we kept a Fragment from the previous iteration, but more data has arrived, discard it
501  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
502  if (id.second->BufferFragmentKept && id.second->DataBufferDepthFragments > 1)
503  {
504  id.second->DataBufferDepthBytes -= id.second->DataBuffer.front()->sizeBytes();
505  id.second->DataBuffer.erase(id.second->DataBuffer.begin());
506  id.second->DataBufferDepthFragments = id.second->DataBuffer.size();
507  }
508 
509  // Buffer mode TFGs should simply copy out the whole dataBuffer_ into a ContainerFragment
510  FragmentPtrs fragsToAdd;
511  std::move(id.second->DataBuffer.begin(), --id.second->DataBuffer.end(), std::back_inserter(fragsToAdd));
512  id.second->DataBuffer.erase(id.second->DataBuffer.begin(), --id.second->DataBuffer.end());
513 
514  if (fragsToAdd.size() > 0)
515  {
516  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsBufferMode: Adding " << fragsToAdd.size() << " Fragments to Container";
517  cfl.addFragments(fragsToAdd);
518  }
519 
520  if (id.second->DataBuffer.size() == 1)
521  {
522  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsBufferMode: Adding Fragment with timestamp " << id.second->DataBuffer.front()->timestamp() << " to Container with sequence ID " << next_sequence_id_;
523  cfl.addFragment(id.second->DataBuffer.front());
524  if (bufferModeKeepLatest_)
525  {
526  id.second->BufferFragmentKept = true;
527  id.second->DataBufferDepthBytes = id.second->DataBuffer.front()->sizeBytes();
528  id.second->DataBufferDepthFragments = id.second->DataBuffer.size(); // 1
529  }
530  else
531  {
532  id.second->DataBuffer.clear();
533  id.second->BufferFragmentKept = false;
534  id.second->DataBufferDepthBytes = 0;
535  id.second->DataBufferDepthFragments = 0;
536  }
537  }
538  }
539  requestBuffer_->RemoveRequest(next_sequence_id_);
540  ++next_sequence_id_;
541 }
542 
543 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)
544 {
545  auto dataBuffer = dataBuffers_[id];
546 
547  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode_CheckAndFillDataBuffer: Checking that data exists for request window " << seq;
548  Fragment::timestamp_t min = ts > windowOffset_ ? ts - windowOffset_ : 0;
549  Fragment::timestamp_t max = ts + windowWidth_ > windowOffset_ ? ts + windowWidth_ - windowOffset_ : 1;
550 
551  TLOG(TLVL_APPLYREQUESTS) << "ApplyRequestsWindowsMode_CheckAndFillDataBuffer: min is " << min << ", max is " << max
552  << " and first/last points in buffer are " << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.front()->timestamp() : 0)
553  << "/" << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.back()->timestamp() : 0)
554  << " (sz=" << dataBuffer->DataBufferDepthFragments << " [" << dataBuffer->DataBufferDepthBytes.load()
555  << "/" << maxDataBufferDepthBytes_ << "])";
556  bool windowClosed = dataBuffer->DataBufferDepthFragments > 0 && dataBuffer->DataBuffer.back()->timestamp() >= max;
557  bool windowTimeout = !windowClosed && TimeUtils::GetElapsedTimeMicroseconds(requestBuffer_->GetRequestTime(seq)) > window_close_timeout_us_;
558  if (windowTimeout)
559  {
560  TLOG(TLVL_WARNING) << "applyRequestsWindowMode_CheckAndFillDataBuffer: A timeout occurred waiting for data to close the request window ({" << min << "-" << max
561  << "}, buffer={" << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.front()->timestamp() : 0) << "-"
562  << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.back()->timestamp() : 0)
563  << "} ). Time waiting: "
564  << TimeUtils::GetElapsedTimeMicroseconds(requestBuffer_->GetRequestTime(seq)) << " us "
565  << "(> " << window_close_timeout_us_ << " us).";
566  }
567  if (windowClosed || windowTimeout)
568  {
569  TLOG(TLVL_DEBUG) << "applyRequestsWindowMode_CheckAndFillDataBuffer: Creating ContainerFragment for Window-requested Fragments";
570  frags.emplace_back(new artdaq::Fragment(seq, id));
571  frags.back()->setTimestamp(ts);
572  ContainerFragmentLoader cfl(*frags.back());
573 
574  // In the spirit of NOvA's MegaPool: (RS = Request start (min), RE = Request End (max))
575  // --- | Buffer Start | --- | Buffer End | ---
576  //1. RS RE | | | |
577  //2. RS | | RE | |
578  //3. RS | | | | RE
579  //4. | | RS RE | |
580  //5. | | RS | | RE
581  //6. | | | | RS RE
582  //
583  // 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.
584  // 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
585  // If the dataBuffer has size 0, then windowClosed will be false
586  if (!windowClosed || (dataBuffer->DataBufferDepthFragments > 0 && dataBuffer->DataBuffer.front()->timestamp() > min))
587  {
588  TLOG(TLVL_DEBUG) << "applyRequestsWindowMode_CheckAndFillDataBuffer: Request window starts before and/or ends after the current data buffer, setting ContainerFragment's missing_data flag!"
589  << " (requestWindowRange=[" << min << "," << max << "], "
590  << "buffer={" << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.front()->timestamp() : 0) << "-"
591  << (dataBuffer->DataBufferDepthFragments > 0 ? dataBuffer->DataBuffer.back()->timestamp() : 0) << "}";
592  cfl.set_missing_data(true);
593  }
594 
595  auto it = dataBuffer->DataBuffer.begin();
596  // Likely that it will be closer to the end...
597  if (windowTimeout)
598  {
599  it = dataBuffer->DataBuffer.end();
600  --it;
601  while (it != dataBuffer->DataBuffer.begin())
602  {
603  if ((*it)->timestamp() < min)
604  {
605  break;
606  }
607  --it;
608  }
609  }
610 
611  FragmentPtrs fragsToAdd;
612  // Do a little bit more work to decide which fragments to send for a given request
613  for (; it != dataBuffer->DataBuffer.end();)
614  {
615  Fragment::timestamp_t fragT = (*it)->timestamp();
616  if (fragT < min)
617  {
618  ++it;
619  continue;
620  }
621  if (fragT > max || (fragT == max && windowWidth_ > 0))
622  { break; }
623 
624  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode_CheckAndFillDataBuffer: Adding Fragment with timestamp " << (*it)->timestamp() << " to Container";
625  if (uniqueWindows_)
626  {
627  dataBuffer->DataBufferDepthBytes -= (*it)->sizeBytes();
628  fragsToAdd.emplace_back(std::move(*it));
629  it = dataBuffer->DataBuffer.erase(it);
630  }
631  else
632  {
633  fragsToAdd.emplace_back(it->get());
634  ++it;
635  }
636  }
637 
638  if (fragsToAdd.size() > 0)
639  {
640  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode_CheckAndFillDataBuffer: Adding " << fragsToAdd.size() << " Fragments to Container";
641  cfl.addFragments(fragsToAdd);
642 
643  // Don't delete Fragments which are still in the Fragment buffer
644  if (!uniqueWindows_)
645  {
646  for (auto& frag : fragsToAdd)
647  {
648  frag.release();
649  }
650  }
651  fragsToAdd.clear();
652  }
653 
654  dataBuffer->DataBufferDepthFragments = dataBuffer->DataBuffer.size();
655  dataBuffer->WindowsSent[seq] = std::chrono::steady_clock::now();
656  if (seq > dataBuffer->HighestRequestSeen) dataBuffer->HighestRequestSeen = seq;
657  }
658 }
659 
660 void artdaq::FragmentBuffer::applyRequestsWindowMode(artdaq::FragmentPtrs& frags)
661 {
662  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode BEGIN";
663 
664  auto requests = requestBuffer_->GetRequests();
665 
666  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode: Starting request processing for " << requests.size() << " requests";
667  for (auto req = requests.begin(); req != requests.end();)
668  {
669  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode: processing request with sequence ID " << req->first << ", timestamp " << req->second;
670 
671  while (req->first < next_sequence_id_ && requests.size() > 0)
672  {
673  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsWindowMode: Clearing passed request for sequence ID " << req->first;
674  requestBuffer_->RemoveRequest(req->first);
675  req = requests.erase(req);
676  }
677  if (requests.size() == 0) break;
678 
679  for (auto& id : dataBuffers_)
680  {
681  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
682  if (!id.second->WindowsSent.count(req->first))
683  {
684  applyRequestsWindowMode_CheckAndFillDataBuffer(frags, id.first, req->first, req->second);
685  }
686  }
687  checkSentWindows(req->first);
688  ++req;
689  }
690 
691  // Check sent windows for requests that can be removed
692  std::set<artdaq::Fragment::sequence_id_t> seqs;
693  for (auto& id : dataBuffers_)
694  {
695  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
696  for (auto& seq : id.second->WindowsSent)
697  {
698  seqs.insert(seq.first);
699  }
700  }
701  for (auto& seq : seqs)
702  {
703  checkSentWindows(seq);
704  }
705 }
706 
708 {
709  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsSequenceIDMode BEGIN";
710 
711  auto requests = requestBuffer_->GetRequests();
712 
713  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsSequenceIDMode: Starting request processing";
714  for (auto req = requests.begin(); req != requests.end();)
715  {
716  TLOG(TLVL_APPLYREQUESTS) << "applyRequestsSequenceIDMode: Checking that data exists for request SequenceID " << req->first;
717 
718  for (auto& id : dataBuffers_)
719  {
720  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
721  if (!id.second->WindowsSent.count(req->first))
722  {
723  TLOG(29) << "Searching id " << id.first << " for Fragments with Sequence ID " << req->first;
724  for (auto it = id.second->DataBuffer.begin(); it != id.second->DataBuffer.end();)
725  {
726  auto seq = (*it)->sequenceID();
727  TLOG(29) << "applyRequestsSequenceIDMode: Fragment SeqID " << seq << ", request ID " << req->first;
728  if (seq == req->first)
729  {
730  TLOG(29) << "applyRequestsSequenceIDMode: Adding Fragment to output";
731  id.second->WindowsSent[req->first] = std::chrono::steady_clock::now();
732  id.second->DataBufferDepthBytes -= (*it)->sizeBytes();
733  frags.push_back(std::move(*it));
734  it = id.second->DataBuffer.erase(it);
735  id.second->DataBufferDepthFragments = id.second->DataBuffer.size();
736  }
737  else
738  {
739  ++it;
740  }
741  }
742  }
743  if (req->first > id.second->HighestRequestSeen) id.second->HighestRequestSeen = req->first;
744  }
745  checkSentWindows(req->first);
746  ++req;
747  }
748 
749  // Check sent windows for requests that can be removed
750  std::set<artdaq::Fragment::sequence_id_t> seqs;
751  for (auto& id : dataBuffers_)
752  {
753  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
754  for (auto& seq : id.second->WindowsSent)
755  {
756  seqs.insert(seq.first);
757  }
758  }
759  for (auto& seq : seqs)
760  {
761  checkSentWindows(seq);
762  }
763 }
764 
765 bool artdaq::FragmentBuffer::applyRequests(artdaq::FragmentPtrs& frags)
766 {
767  if (check_stop())
768  {
769  return false;
770  }
771 
772  // Wait for data, if in ignored mode, or a request otherwise
773  if (mode_ == RequestMode::Ignored)
774  {
775  auto start_time = std::chrono::steady_clock::now();
776  while (dataBufferFragmentCount_() == 0 && TimeUtils::GetElapsedTime(start_time) < 1.0)
777  {
778  if (check_stop()) return false;
779  std::unique_lock<std::mutex> lock(dataConditionMutex_);
780  dataCondition_.wait_for(lock, std::chrono::milliseconds(10), [this]() { return dataBufferFragmentCount_() > 0; });
781  }
782  }
783  else if (requestBuffer_ == nullptr)
784  {
785  TLOG(TLVL_ERROR) << "Request Buffer must be set (via SetRequestBuffer) before applyRequests/getData can be called!";
786  return false;
787  }
788  else
789  {
790  if ((check_stop() && requestBuffer_->size() == 0)) return false;
791 
792  std::unique_lock<std::mutex> lock(dataConditionMutex_);
793  dataCondition_.wait_for(lock, std::chrono::milliseconds(10));
794 
795  checkDataBuffers();
796 
797  // Wait up to 1000 ms for a request...
798  auto counter = 0;
799 
800  while (requestBuffer_->size() == 0 && counter < 100)
801  {
802  if (check_stop()) return false;
803 
804  checkDataBuffers();
805 
806  requestBuffer_->WaitForRequests(10); // milliseconds
807  counter++;
808  }
809  }
810 
811  if (systemFragmentCount_.load() > 0)
812  {
813  std::lock_guard<std::mutex> lk(systemFragmentMutex_);
814  TLOG(TLVL_INFO) << "Copying " << systemFragmentCount_.load() << " System Fragments into output";
815 
816  std::move(systemFragments_.begin(), systemFragments_.end(), std::inserter(frags, frags.end()));
817  systemFragments_.clear();
818  systemFragmentCount_ = 0;
819  }
820 
821  switch (mode_)
822  {
823  case RequestMode::Single:
824  applyRequestsSingleMode(frags);
825  break;
826  case RequestMode::Window:
827  applyRequestsWindowMode(frags);
828  break;
829  case RequestMode::Buffer:
830  applyRequestsBufferMode(frags);
831  break;
832  case RequestMode::SequenceID:
833  applyRequestsSequenceIDMode(frags);
834  break;
835  case RequestMode::Ignored:
836  default:
837  applyRequestsIgnoredMode(frags);
838  break;
839  }
840 
841  getDataBuffersStats();
842 
843  if (frags.size() > 0)
844  TLOG(TLVL_APPLYREQUESTS) << "Finished Processing requests, returning " << frags.size() << " fragments, current ev_counter is " << next_sequence_id_;
845  return true;
846 }
847 
848 bool artdaq::FragmentBuffer::sendEmptyFragment(artdaq::FragmentPtrs& frags, size_t seqId, Fragment::fragment_id_t fragmentId, std::string desc)
849 {
850  TLOG(TLVL_EMPTYFRAGMENT) << desc << " sequence ID " << seqId << ", sending empty fragment";
851  auto frag = new Fragment();
852  frag->setSequenceID(seqId);
853  frag->setFragmentID(fragmentId);
854  frag->setSystemType(Fragment::EmptyFragmentType);
855  frags.emplace_back(FragmentPtr(frag));
856  return true;
857 }
858 
859 void artdaq::FragmentBuffer::sendEmptyFragments(artdaq::FragmentPtrs& frags, std::map<Fragment::sequence_id_t, Fragment::timestamp_t>& requests)
860 {
861  if (requests.size() > 0)
862  {
863  TLOG(TLVL_SENDEMPTYFRAGMENTS) << "Sending Empty Fragments for Sequence IDs from " << next_sequence_id_ << " up to but not including " << requests.begin()->first;
864  while (requests.begin()->first > next_sequence_id_)
865  {
866  for (auto& fid : dataBuffers_)
867  {
868  sendEmptyFragment(frags, next_sequence_id_, fid.first, "Missed request for");
869  }
870  ++next_sequence_id_;
871  }
872  }
873 }
874 
875 void artdaq::FragmentBuffer::checkSentWindows(artdaq::Fragment::sequence_id_t seq)
876 {
877  TLOG(TLVL_CHECKWINDOWS) << "checkSentWindows: Checking if request " << seq << " can be removed from request list";
878  bool seqComplete = true;
879  bool seqTimeout = false;
880  for (auto& id : dataBuffers_)
881  {
882  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
883  if (!id.second->WindowsSent.count(seq) || id.second->HighestRequestSeen < seq)
884  {
885  seqComplete = false;
886  }
887  if (id.second->WindowsSent.count(seq) && TimeUtils::GetElapsedTimeMicroseconds(id.second->WindowsSent[seq]) > missing_request_window_timeout_us_)
888  {
889  seqTimeout = true;
890  }
891  }
892  if (seqComplete)
893  {
894  TLOG(TLVL_CHECKWINDOWS) << "checkSentWindows: Request " << seq << " is complete, removing from requestBuffer_.";
895  requestBuffer_->RemoveRequest(seq);
896 
897  if (next_sequence_id_ == seq)
898  {
899  TLOG(TLVL_CHECKWINDOWS) << "checkSentWindows: Sequence ID matches ev_counter, incrementing ev_counter (" << next_sequence_id_ << ")";
900 
901  for (auto& id : dataBuffers_)
902  {
903  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
904  id.second->WindowsSent.erase(seq);
905  }
906 
907  ++next_sequence_id_;
908  }
909  }
910  if (seqTimeout)
911  {
912  TLOG(TLVL_CHECKWINDOWS) << "checkSentWindows: Sent Window history indicates that requests between " << next_sequence_id_ << " and " << seq << " have timed out.";
913  while (next_sequence_id_ <= seq)
914  {
915  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!";
916  requestBuffer_->RemoveRequest(next_sequence_id_);
917 
918  for (auto& id : dataBuffers_)
919  {
920  std::lock_guard<std::mutex> lk(id.second->DataBufferMutex);
921  id.second->WindowsSent.erase(next_sequence_id_);
922  }
923 
924  ++next_sequence_id_;
925  }
926  }
927 }
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.