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