artdaq  v3_02_01
RoutingMasterCore.cc
1 #include <sys/un.h>
2 #include <sys/time.h>
3 #include <sys/epoll.h>
4 #include <arpa/inet.h>
5 #include <netdb.h>
6 #include <pthread.h>
7 #include <sched.h>
8 #include <algorithm>
9 
10 #include "canvas/Utilities/Exception.h"
11 #include "cetlib_except/exception.h"
12 
13 #define TRACE_NAME (app_name + "_RoutingMasterCore").c_str() // include these 2 first -
14 #include "artdaq/DAQdata/Globals.hh" // to get tracemf.h before trace.h
15 #include "artdaq-core/Data/Fragment.hh"
16 #include "artdaq-core/Utilities/ExceptionHandler.hh"
17 
18 #include "artdaq/Application/RoutingMasterCore.hh"
19 #include "artdaq/Application/Routing/makeRoutingMasterPolicy.hh"
22 
23 const std::string artdaq::RoutingMasterCore::
24 TABLE_UPDATES_STAT_KEY("RoutingMasterCoreTableUpdates");
25 const std::string artdaq::RoutingMasterCore::
26 TOKENS_RECEIVED_STAT_KEY("RoutingMasterCoreTokensReceived");
27 
29  : received_token_counter_()
30  , shutdown_requested_(false)
31  , stop_requested_(false)
32  , pause_requested_(false)
33  , token_socket_(-1)
34  , table_socket_(-1)
35  , ack_socket_(-1)
36 {
37  TLOG(TLVL_DEBUG) << "Constructor" ;
40  metricMan = &metricMan_;
41 }
42 
44 {
45  TLOG(TLVL_DEBUG) << "Destructor" ;
46  if (ev_token_receive_thread_.joinable()) ev_token_receive_thread_.join();
47 }
48 
49 bool artdaq::RoutingMasterCore::initialize(fhicl::ParameterSet const& pset, uint64_t, uint64_t)
50 {
51  TLOG(TLVL_DEBUG) << "initialize method called with "
52  << "ParameterSet = \"" << pset.to_string()
53  << "\"." ;
54 
55  // pull out the relevant parts of the ParameterSet
56  fhicl::ParameterSet daq_pset;
57  try
58  {
59  daq_pset = pset.get<fhicl::ParameterSet>("daq");
60  }
61  catch (...)
62  {
63  TLOG(TLVL_ERROR)
64  << "Unable to find the DAQ parameters in the initialization "
65  << "ParameterSet: \"" + pset.to_string() + "\"." ;
66  return false;
67  }
68 
69  if (daq_pset.has_key("rank"))
70  {
71  if (my_rank >= 0 && daq_pset.get<int>("rank") != my_rank) {
72  TLOG(TLVL_WARNING) << "Routing Master rank specified at startup is different than rank specified at configure! Using rank received at configure!";
73  }
74  my_rank = daq_pset.get<int>("rank");
75  }
76  if (my_rank == -1)
77  {
78  TLOG(TLVL_ERROR) << "Routing Master rank not specified at startup or in configuration! Aborting";
79  exit(1);
80  }
81 
82  try
83  {
84  policy_pset_ = daq_pset.get<fhicl::ParameterSet>("policy");
85  }
86  catch (...)
87  {
88  TLOG(TLVL_ERROR)
89  << "Unable to find the policy parameters in the DAQ initialization ParameterSet: \"" + daq_pset.to_string() + "\"." ;
90  return false;
91  }
92 
93  // pull out the Metric part of the ParameterSet
94  fhicl::ParameterSet metric_pset;
95  try
96  {
97  metric_pset = daq_pset.get<fhicl::ParameterSet>("metrics");
98  }
99  catch (...) {} // OK if there's no metrics table defined in the FHiCL
100 
101  if (metric_pset.is_empty())
102  {
103  TLOG(TLVL_INFO) << "No metric plugins appear to be defined" ;
104  }
105  try
106  {
107  metricMan_.initialize(metric_pset, app_name);
108  }
109  catch (...)
110  {
111  ExceptionHandler(ExceptionHandlerRethrow::no,
112  "Error loading metrics in RoutingMasterCore::initialize()");
113  }
114 
115  // create the requested CommandableFragmentGenerator
116  auto policy_plugin_spec = policy_pset_.get<std::string>("policy", "");
117  if (policy_plugin_spec.length() == 0)
118  {
119  TLOG(TLVL_ERROR)
120  << "No fragment generator (parameter name = \"policy\") was "
121  << "specified in the policy ParameterSet. The "
122  << "DAQ initialization PSet was \"" << daq_pset.to_string() << "\"." ;
123  return false;
124  }
125  try
126  {
127  policy_ = artdaq::makeRoutingMasterPolicy(policy_plugin_spec, policy_pset_);
128  }
129  catch (...)
130  {
131  std::stringstream exception_string;
132  exception_string << "Exception thrown during initialization of policy of type \""
133  << policy_plugin_spec << "\"";
134 
135  ExceptionHandler(ExceptionHandlerRethrow::no, exception_string.str());
136 
137  TLOG(TLVL_DEBUG) << "FHiCL parameter set used to initialize the policy which threw an exception: " << policy_pset_.to_string() ;
138 
139  return false;
140  }
141 
142  rt_priority_ = daq_pset.get<int>("rt_priority", 0);
143  sender_ranks_ = daq_pset.get<std::vector<int>>("sender_ranks");
144  num_receivers_ = policy_->GetReceiverCount();
145 
146  receive_ack_events_ = std::vector<epoll_event>(sender_ranks_.size());
147  receive_token_events_ = std::vector<epoll_event>(num_receivers_ + 1);
148 
149  auto mode = daq_pset.get<bool>("senders_send_by_send_count", false);
151  max_table_update_interval_ms_ = daq_pset.get<size_t>("table_update_interval_ms", 1000);
152  current_table_interval_ms_ = max_table_update_interval_ms_;
153  max_ack_cycle_count_ = daq_pset.get<size_t>("table_ack_retry_count", 5);
154  receive_token_port_ = daq_pset.get<int>("routing_token_port", 35555);
155  send_tables_port_ = daq_pset.get<int>("table_update_port", 35556);
156  receive_acks_port_ = daq_pset.get<int>("table_acknowledge_port", 35557);
157  send_tables_address_ = daq_pset.get<std::string>("table_update_address", "227.128.12.28");
158  receive_address_ = daq_pset.get<std::string>("routing_master_hostname", "localhost");
159 
160  // fetch the monitoring parameters and create the MonitoredQuantity instances
161  statsHelper_.createCollectors(daq_pset, 100, 30.0, 60.0, TABLE_UPDATES_STAT_KEY);
162 
163  shutdown_requested_.store(false);
164  start_recieve_token_thread_();
165  return true;
166 }
167 
168 bool artdaq::RoutingMasterCore::start(art::RunID id, uint64_t, uint64_t)
169 {
170  stop_requested_.store(false);
171  pause_requested_.store(false);
172 
173  statsHelper_.resetStatistics();
174  policy_->Reset();
175 
176  metricMan_.do_start();
177  run_id_ = id;
178  table_update_count_ = 0;
179  received_token_count_ = 0;
180 
181  TLOG(TLVL_DEBUG) << "Started run " << run_id_.run() ;
182  return true;
183 }
184 
185 bool artdaq::RoutingMasterCore::stop(uint64_t, uint64_t)
186 {
187  TLOG(TLVL_DEBUG) << "Stopping run " << run_id_.run()
188  << " after " << table_update_count_ << " table updates."
189  << " and " << received_token_count_ << " received tokens." ;
190  stop_requested_.store(true);
191  return true;
192 }
193 
194 bool artdaq::RoutingMasterCore::pause(uint64_t, uint64_t)
195 {
196  TLOG(TLVL_DEBUG) << "Pausing run " << run_id_.run()
197  << " after " << table_update_count_ << " table updates."
198  << " and " << received_token_count_ << " received tokens." ;
199  pause_requested_.store(true);
200  return true;
201 }
202 
203 bool artdaq::RoutingMasterCore::resume(uint64_t, uint64_t)
204 {
205  TLOG(TLVL_DEBUG) << "Resuming run " << run_id_.run() ;
206  policy_->Reset();
207  pause_requested_.store(false);
208  metricMan_.do_start();
209  return true;
210 }
211 
213 {
214  shutdown_requested_.store(true);
215  if (ev_token_receive_thread_.joinable()) ev_token_receive_thread_.join();
216  policy_.reset(nullptr);
217  metricMan_.shutdown();
218  return true;
219 }
220 
221 bool artdaq::RoutingMasterCore::soft_initialize(fhicl::ParameterSet const& pset, uint64_t e, uint64_t f)
222 {
223  TLOG(TLVL_DEBUG) << "soft_initialize method called with "
224  << "ParameterSet = \"" << pset.to_string()
225  << "\"." ;
226  return initialize(pset, e, f);
227 }
228 
229 bool artdaq::RoutingMasterCore::reinitialize(fhicl::ParameterSet const& pset, uint64_t e, uint64_t f)
230 {
231  TLOG(TLVL_DEBUG) << "reinitialize method called with "
232  << "ParameterSet = \"" << pset.to_string()
233  << "\"." ;
234  return initialize(pset, e, f);
235 }
236 
238 {
239  if (rt_priority_ > 0)
240  {
241 #pragma GCC diagnostic push
242 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
243  sched_param s_param = {};
244  s_param.sched_priority = rt_priority_;
245  if (pthread_setschedparam(pthread_self(), SCHED_RR, &s_param))
246  TLOG(TLVL_WARNING) << "setting realtime priority failed" ;
247 #pragma GCC diagnostic pop
248  }
249 
250  // try-catch block here?
251 
252  // how to turn RT PRI off?
253  if (rt_priority_ > 0)
254  {
255 #pragma GCC diagnostic push
256 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
257  sched_param s_param = {};
258  s_param.sched_priority = rt_priority_;
259  int status = pthread_setschedparam(pthread_self(), SCHED_RR, &s_param);
260  if (status != 0)
261  {
262  TLOG(TLVL_ERROR)
263  << "Failed to set realtime priority to " << rt_priority_
264  << ", return code = " << status ;
265  }
266 #pragma GCC diagnostic pop
267  }
268 
269  //MPI_Barrier(local_group_comm_);
270 
271  TLOG(TLVL_DEBUG) << "Sending initial table." ;
272  auto startTime = artdaq::MonitoredQuantity::getCurrentTime();
273  auto nextSendTime = startTime;
274  double delta_time;
275  while (true)
276  {
277  if (stop_requested_ || pause_requested_) { break; }
278  startTime = artdaq::MonitoredQuantity::getCurrentTime();
279 
280  if (startTime >= nextSendTime)
281  {
282  auto table = policy_->GetCurrentTable();
283  if (table.size() > 0)
284  {
285  send_event_table(table);
286  ++table_update_count_;
287  delta_time = artdaq::MonitoredQuantity::getCurrentTime() - startTime;
288  statsHelper_.addSample(TABLE_UPDATES_STAT_KEY, delta_time);
289  TLOG(16) << "process_fragments TABLE_UPDATES_STAT_KEY=" << delta_time ;
290  }
291  else
292  {
293  TLOG(TLVL_WARNING) << "No tokens received in this update interval! This is most likely a Very Bad Thing!" ;
294  }
295  auto max_tokens = policy_->GetMaxNumberOfTokens();
296  if (max_tokens > 0)
297  {
298  auto frac = table.size() / static_cast<double>(max_tokens);
299  if (frac > 0.75) current_table_interval_ms_ = 9 * current_table_interval_ms_ / 10;
300  if (frac < 0.5) current_table_interval_ms_ = 11 * current_table_interval_ms_ / 10;
301  if (current_table_interval_ms_ > max_table_update_interval_ms_) current_table_interval_ms_ = max_table_update_interval_ms_;
302  if (current_table_interval_ms_ < 1) current_table_interval_ms_ = 1;
303  }
304  nextSendTime = startTime + current_table_interval_ms_ / 1000.0;
305  TLOG(TLVL_DEBUG) << "current_table_interval_ms is now " << current_table_interval_ms_ ;
306  }
307  else
308  {
309  usleep(current_table_interval_ms_ * 10); // 1/100 of the table update interval
310  }
311  }
312 
313  metricMan_.do_stop();
314 
315  return table_update_count_;
316 }
317 
319 {
320  // Reconnect table socket, if necessary
321  if (table_socket_ == -1)
322  {
323  table_socket_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
324  if (table_socket_ < 0)
325  {
326  TLOG(TLVL_ERROR) << "I failed to create the socket for sending Data Requests! Errno: " << errno ;
327  exit(1);
328  }
329  auto sts = ResolveHost(send_tables_address_.c_str(), send_tables_port_, send_tables_addr_);
330  if (sts == -1)
331  {
332  TLOG(TLVL_ERROR) << "Unable to resolve table_update_address" ;
333  exit(1);
334  }
335 
336  auto yes = 1;
337  if (receive_address_ != "localhost")
338  {
339  TLOG(TLVL_DEBUG) << "Making sure that multicast sending uses the correct interface for hostname " << receive_address_ ;
340  struct in_addr addr;
341  sts = ResolveHost(receive_address_.c_str(), addr);
342  if (sts == -1)
343  {
344  throw art::Exception(art::errors::Configuration) << "RoutingMasterCore: Unable to resolve routing_master_address" << std::endl;;
345  }
346 
347  if (setsockopt(table_socket_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0)
348  {
349  throw art::Exception(art::errors::Configuration) <<
350  "RoutingMasterCore: Unable to enable port reuse on table update socket" << std::endl;
351  exit(1);
352  }
353 
354  if (setsockopt(table_socket_, IPPROTO_IP, IP_MULTICAST_LOOP, &yes, sizeof(yes)) < 0)
355  {
356  TLOG(TLVL_ERROR) << "Unable to enable multicast loopback on table socket" ;
357  exit(1);
358  }
359  if (setsockopt(table_socket_, IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr)) == -1)
360  {
361  TLOG(TLVL_ERROR) << "Cannot set outgoing interface. Errno: " << errno ;
362  exit(1);
363  }
364  }
365  if (setsockopt(table_socket_, SOL_SOCKET, SO_BROADCAST, (void*)&yes, sizeof(int)) == -1)
366  {
367  TLOG(TLVL_ERROR) << "Cannot set request socket to broadcast. Errno: " << errno ;
368  exit(1);
369  }
370  }
371 
372  // Reconnect ack socket, if necessary
373  if (ack_socket_ == -1)
374  {
375  ack_socket_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
376  if (ack_socket_ < 0)
377  {
378  throw art::Exception(art::errors::Configuration) << "RoutingMasterCore: Error creating socket for receiving table update acks!" << std::endl;
379  exit(1);
380  }
381 
382  struct sockaddr_in si_me_request;
383 
384  auto yes = 1;
385  if (setsockopt(ack_socket_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0)
386  {
387  throw art::Exception(art::errors::Configuration) <<
388  "RoutingMasterCore: Unable to enable port reuse on ack socket" << std::endl;
389  exit(1);
390  }
391  memset(&si_me_request, 0, sizeof(si_me_request));
392  si_me_request.sin_family = AF_INET;
393  si_me_request.sin_port = htons(receive_acks_port_);
394  si_me_request.sin_addr.s_addr = htonl(INADDR_ANY);
395  if (bind(ack_socket_, reinterpret_cast<struct sockaddr *>(&si_me_request), sizeof(si_me_request)) == -1)
396  {
397  throw art::Exception(art::errors::Configuration) <<
398  "RoutingMasterCore: Cannot bind request socket to port " << receive_acks_port_ << std::endl;
399  exit(1);
400  }
401  TLOG(TLVL_DEBUG) << "Listening for acks on 0.0.0.0 port " << receive_acks_port_ ;
402  }
403 
404  auto acks = std::unordered_map<int, bool>();
405  for (auto& r : sender_ranks_)
406  {
407  acks[r] = false;
408  }
409  auto counter = 0U;
410  auto start_time = std::chrono::steady_clock::now();
411  while (std::count_if(acks.begin(), acks.end(), [](std::pair<int, bool> p) {return !p.second; }) > 0)
412  {
413  // Send table update
414  auto header = detail::RoutingPacketHeader(routing_mode_, packet.size());
415  auto packetSize = sizeof(detail::RoutingPacketEntry) * packet.size();
416 
417  TLOG(TLVL_DEBUG) << "Sending table information for " << header.nEntries << " events to multicast group " << send_tables_address_ << ", port " << send_tables_port_ ;
418  if (sendto(table_socket_, &header, sizeof(detail::RoutingPacketHeader), 0, reinterpret_cast<struct sockaddr *>(&send_tables_addr_), sizeof(send_tables_addr_)) < 0)
419  {
420  TLOG(TLVL_ERROR) << "Error sending request message header" ;
421  }
422  if (sendto(table_socket_, &packet[0], packetSize, 0, reinterpret_cast<struct sockaddr *>(&send_tables_addr_), sizeof(send_tables_addr_)) < 0)
423  {
424  TLOG(TLVL_ERROR) << "Error sending request message data" ;
425  }
426 
427  // Collect acks
428 
429  auto first = packet[0].sequence_id;
430  auto last = packet.rbegin()->sequence_id;
431  TLOG(TLVL_DEBUG) << "Expecting acks to have first= " << first << ", and last= " << last ;
432 
433 
434  auto startTime = std::chrono::steady_clock::now();
435  while (std::count_if(acks.begin(), acks.end(), [](std::pair<int, bool> p) {return !p.second; }) > 0)
436  {
437  auto table_ack_wait_time_ms = current_table_interval_ms_ / max_ack_cycle_count_;
438  if (TimeUtils::GetElapsedTimeMilliseconds(startTime) > table_ack_wait_time_ms)
439  {
440  if (counter > max_ack_cycle_count_ && table_update_count_ > 0)
441  {
442  TLOG(TLVL_ERROR) << "Did not receive acks from all senders after resending table " << counter
443  << " times during the table_update_interval. Check the status of the senders!" ;
444  break;
445  }
446  TLOG(TLVL_WARNING) << "Did not receive acks from all senders within the table_ack_wait_time. Resending table update" ;
447  break;
448  }
449 
450  TLOG(20) << "send_event_table: Polling Request socket for new requests" ;
451  auto ready = true;
452  while (ready)
453  {
455  if (recvfrom(ack_socket_, &buffer, sizeof(detail::RoutingAckPacket), MSG_DONTWAIT, NULL, NULL) < 0)
456  {
457  if (errno == EWOULDBLOCK || errno == EAGAIN)
458  {
459  TLOG(20) << "send_event_table: No more ack datagrams on ack socket." ;
460  ready = false;
461  }
462  else
463  {
464  TLOG(TLVL_ERROR) << "An unexpected error occurred during ack packet receive" ;
465  exit(2);
466  }
467  }
468  else
469  {
470  TLOG(TLVL_DEBUG) << "Ack packet from rank " << buffer.rank << " has first= " << buffer.first_sequence_id
471  << " and last= " << buffer.last_sequence_id ;
472  if (acks.count(buffer.rank) && buffer.first_sequence_id == first && buffer.last_sequence_id == last)
473  {
474  TLOG(TLVL_DEBUG) << "Received table update acknowledgement from sender with rank " << buffer.rank << "." ;
475  acks[buffer.rank] = true;
476  TLOG(TLVL_DEBUG) << "There are now " << std::count_if(acks.begin(), acks.end(), [](std::pair<int, bool> p) {return !p.second; })
477  << " acks outstanding" ;
478  }
479  else
480  {
481  if (!acks.count(buffer.rank))
482  {
483  TLOG(TLVL_ERROR) << "Received acknowledgement from invalid rank " << buffer.rank << "!"
484  << " Cross-talk between RoutingMasters means there's a configuration error!" ;
485  }
486  else
487  {
488  TLOG(TLVL_WARNING) << "Received acknowledgement from rank " << buffer.rank
489  << " that had incorrect sequence ID information. Discarding." ;
490  }
491  }
492  }
493  }
494  usleep(table_ack_wait_time_ms * 1000 / 10);
495  }
496  }
497  if (metricMan)
498  {
499  artdaq::TimeUtils::seconds delta = std::chrono::steady_clock::now() - start_time;
500  metricMan->sendMetric("Avg Table Acknowledge Time", delta.count(), "seconds", 3, MetricMode::Average);
501  }
502 }
503 
504 void artdaq::RoutingMasterCore::receive_tokens_()
505 {
506  while (!shutdown_requested_)
507  {
508  TLOG(TLVL_DEBUG) << "Receive Token loop start" ;
509  if (token_socket_ == -1)
510  {
511  TLOG(TLVL_DEBUG) << "Opening token listener socket" ;
512  token_socket_ = TCP_listen_fd(receive_token_port_, 3 * sizeof(detail::RoutingToken));
513 
514  if (token_epoll_fd_ != -1) close(token_epoll_fd_);
515  struct epoll_event ev;
516  token_epoll_fd_ = epoll_create1(0);
517  ev.events = EPOLLIN | EPOLLPRI;
518  ev.data.fd = token_socket_;
519  if (epoll_ctl(token_epoll_fd_, EPOLL_CTL_ADD, token_socket_, &ev) == -1)
520  {
521  TLOG(TLVL_ERROR) << "Could not register listen socket to epoll fd" ;
522  exit(3);
523  }
524  }
525  if (token_socket_ == -1 || token_epoll_fd_ == -1)
526  {
527  TLOG(TLVL_DEBUG) << "One of the listen sockets was not opened successfully." ;
528  return;
529  }
530 
531  auto nfds = epoll_wait(token_epoll_fd_, &receive_token_events_[0], receive_token_events_.size(), current_table_interval_ms_);
532  if (nfds == -1)
533  {
534  perror("epoll_wait");
535  exit(EXIT_FAILURE);
536  }
537 
538  TLOG(TLVL_DEBUG) << "Received " << nfds << " events" ;
539  for (auto n = 0; n < nfds; ++n)
540  {
541  if (receive_token_events_[n].data.fd == token_socket_)
542  {
543  TLOG(TLVL_DEBUG) << "Accepting new connection on token_socket" ;
544  sockaddr_in addr;
545  socklen_t arglen = sizeof(addr);
546  auto conn_sock = accept(token_socket_, (struct sockaddr *)&addr, &arglen);
547 
548  if (conn_sock == -1)
549  {
550  perror("accept");
551  exit(EXIT_FAILURE);
552  }
553 
554  receive_token_addrs_[conn_sock] = std::string(inet_ntoa(addr.sin_addr));
555  struct epoll_event ev;
556  ev.events = EPOLLIN | EPOLLET;
557  ev.data.fd = conn_sock;
558  if (epoll_ctl(token_epoll_fd_, EPOLL_CTL_ADD, conn_sock, &ev) == -1)
559  {
560  perror("epoll_ctl: conn_sock");
561  exit(EXIT_FAILURE);
562  }
563  }
564  else
565  {
566  auto startTime = artdaq::MonitoredQuantity::getCurrentTime();
567  detail::RoutingToken buff;
568  auto sts = read(receive_token_events_[n].data.fd, &buff, sizeof(detail::RoutingToken));
569  if (sts != sizeof(detail::RoutingToken) || buff.header != TOKEN_MAGIC)
570  {
571  TLOG(TLVL_ERROR) << "Received invalid token from " << receive_token_addrs_[receive_token_events_[n].data.fd] ;
572  }
573  else
574  {
575  TLOG(TLVL_DEBUG) << "Received token from " << buff.rank << " indicating " << buff.new_slots_free << " slots are free." ;
576  received_token_count_ += buff.new_slots_free;
578  {
579  policy_->AddReceiverToken(buff.rank, buff.new_slots_free);
580  }
581  else if (routing_mode_ == detail::RoutingMasterMode::RouteBySendCount)
582  {
583  if (!received_token_counter_.count(buff.rank)) received_token_counter_[buff.rank] = 0;
584  received_token_counter_[buff.rank] += buff.new_slots_free;
585  TLOG(TLVL_DEBUG) << "RoutingMasterMode is RouteBySendCount. I have " << received_token_counter_[buff.rank] << " tokens for rank " << buff.rank << " and I need " << sender_ranks_.size() << "." ;
586  while (received_token_counter_[buff.rank] >= sender_ranks_.size())
587  {
588  TLOG(TLVL_DEBUG) << "RoutingMasterMode is RouteBySendCount. I have " << received_token_counter_[buff.rank] << " tokens for rank " << buff.rank << " and I need " << sender_ranks_.size()
589  << "... Sending token to policy" ;
590  policy_->AddReceiverToken(buff.rank, 1);
591  received_token_counter_[buff.rank] -= sender_ranks_.size();
592  }
593  }
594  }
595  auto delta_time = artdaq::MonitoredQuantity::getCurrentTime() - startTime;
596  statsHelper_.addSample(TOKENS_RECEIVED_STAT_KEY, delta_time);
597 
598  }
599  }
600  }
601 }
602 
603 void artdaq::RoutingMasterCore::start_recieve_token_thread_()
604 {
605  if (ev_token_receive_thread_.joinable()) ev_token_receive_thread_.join();
606  TLOG(TLVL_INFO) << "Starting Token Reception Thread" ;
607  ev_token_receive_thread_ = boost::thread(&RoutingMasterCore::receive_tokens_, this);
608 }
609 
610 std::string artdaq::RoutingMasterCore::report(std::string const&) const
611 {
612  std::string resultString;
613 
614  // if we haven't been able to come up with any report so far, say so
615  auto tmpString = app_name + " run number = " + std::to_string(run_id_.run())
616  + ", table updates sent = " + std::to_string(table_update_count_)
617  + ", Receiver tokens received = " + std::to_string(received_token_count_);
618  return tmpString;
619 }
620 
621 std::string artdaq::RoutingMasterCore::buildStatisticsString_() const
622 {
623  std::ostringstream oss;
624  oss << app_name << " statistics:" << std::endl;
625 
626  auto mqPtr = artdaq::StatisticsCollection::getInstance().getMonitoredQuantity(TABLE_UPDATES_STAT_KEY);
627  if (mqPtr.get() != nullptr)
628  {
629  artdaq::MonitoredQuantityStats stats;
630  mqPtr->getStats(stats);
631  oss << " Table Update statistics: "
632  << stats.recentSampleCount << " table updates sent at "
633  << stats.recentSampleRate << " table updates/sec, , monitor window = "
634  << stats.recentDuration << " sec" << std::endl;
635  oss << " Average times per table update: ";
636  if (stats.recentSampleRate > 0.0)
637  {
638  oss << " elapsed time = "
639  << (1.0 / stats.recentSampleRate) << " sec";
640  }
641  oss << ", avg table acknowledgement wait time = "
642  << (mqPtr->getRecentValueSum() / sender_ranks_.size()) << " sec" << std::endl;
643  }
644 
645  mqPtr = artdaq::StatisticsCollection::getInstance().getMonitoredQuantity(TOKENS_RECEIVED_STAT_KEY);
646  if (mqPtr.get() != nullptr)
647  {
648  artdaq::MonitoredQuantityStats stats;
649  mqPtr->getStats(stats);
650  oss << " Received Token statistics: "
651  << stats.recentSampleCount << " tokens received at "
652  << stats.recentSampleRate << " tokens/sec, , monitor window = "
653  << stats.recentDuration << " sec" << std::endl;
654  oss << " Average times per token: ";
655  if (stats.recentSampleRate > 0.0)
656  {
657  oss << " elapsed time = "
658  << (1.0 / stats.recentSampleRate) << " sec";
659  }
660  oss << ", input token wait time = "
661  << mqPtr->getRecentValueSum() << " sec" << std::endl;
662  }
663 
664  return oss.str();
665 }
666 
667 void artdaq::RoutingMasterCore::sendMetrics_()
668 {
669  auto mqPtr = artdaq::StatisticsCollection::getInstance().getMonitoredQuantity(TABLE_UPDATES_STAT_KEY);
670  if (mqPtr.get() != nullptr)
671  {
672  artdaq::MonitoredQuantityStats stats;
673  mqPtr->getStats(stats);
674  metricMan_.sendMetric("Table Update Count", static_cast<unsigned long>(stats.fullSampleCount), "updates", 1, MetricMode::Accumulate);
675  metricMan_.sendMetric("Table Update Rate", stats.recentSampleRate, "updates/sec", 1, MetricMode::Average);
676  metricMan_.sendMetric("Average Sender Acknowledgement Time", (mqPtr->getRecentValueSum() / sender_ranks_.size()), "seconds", 3, MetricMode::Average);
677  }
678 
679  mqPtr = artdaq::StatisticsCollection::getInstance().getMonitoredQuantity(TOKENS_RECEIVED_STAT_KEY);
680  if (mqPtr.get() != nullptr)
681  {
682  artdaq::MonitoredQuantityStats stats;
683  mqPtr->getStats(stats);
684  metricMan_.sendMetric("Receiver Token Count", static_cast<unsigned long>(stats.fullSampleCount), "updates", 1, MetricMode::Accumulate);
685  metricMan_.sendMetric("Receiver Token Rate", stats.recentSampleRate, "updates/sec", 1, MetricMode::Average);
686  metricMan_.sendMetric("Total Receiver Token Wait Time", mqPtr->getRecentValueSum(), "seconds", 3, MetricMode::Average);
687  }
688 }
bool resume(uint64_t, uint64_t)
Resumes the RoutingMasterCore.
size_t process_event_table()
Main loop of the RoutingMasterCore. Determines when to send the next table update, asks the RoutingMasterPolicy for the table to send, and sends it.
void addMonitoredQuantityName(std::string const &statKey)
Add a MonitoredQuantity name to the list.
int ResolveHost(char const *host_in, in_addr &addr)
Convert a string hostname to a in_addr suitable for socket communication.
Definition: TCPConnect.cc:33
bool soft_initialize(fhicl::ParameterSet const &pset, uint64_t timeout, uint64_t timestamp)
Soft-Initializes the RoutingMasterCore.
static const std::string TOKENS_RECEIVED_STAT_KEY
Key for the Tokens Received MonitoredQuantity.
A row of the Routing Table.
bool reinitialize(fhicl::ParameterSet const &pset, uint64_t timeout, uint64_t timestamp)
Reinitializes the RoutingMasterCore.
bool start(art::RunID id, uint64_t, uint64_t)
Start the RoutingMasterCore.
A RoutingAckPacket contains the rank of the table receiver, plus the first and last sequence IDs in t...
RoutingMasterCore()
RoutingMasterCore Constructor.
Events should be routed by sequence ID (BR -&gt; EB)
bool initialize(fhicl::ParameterSet const &pset, uint64_t, uint64_t)
Processes the initialize request.
The RoutingToken contains the magic bytes, the rank of the token sender, and the number of slots free...
int TCP_listen_fd(int port, int rcvbuf)
Create a TCP listening socket on the given port and INADDR_ANY, with the given receive buffer...
Fragment::sequence_id_t first_sequence_id
The first sequence ID in the received RoutingPacket.
bool pause(uint64_t, uint64_t)
Pauses the RoutingMasterCore.
The header of the Routing Table, containing the magic bytes and the number of entries.
Fragment::sequence_id_t last_sequence_id
The last sequence ID in the received RoutingPacket.
std::vector< RoutingPacketEntry > RoutingPacket
A RoutingPacket is simply a vector of RoutingPacketEntry objects. It is not suitable for network tran...
bool stop(uint64_t, uint64_t)
Stops the RoutingMasterCore.
int rank
The rank from which the RoutingAckPacket came.
size_t nEntries
The number of RoutingPacketEntries in the RoutingPacket.
std::unique_ptr< RoutingMasterPolicy > makeRoutingMasterPolicy(std::string const &policy_plugin_spec, fhicl::ParameterSet const &ps)
Load a RoutingMasterPolicy plugin.
std::string report(std::string const &) const
Send a report on the current status of the RoutingMasterCore.
static const std::string TABLE_UPDATES_STAT_KEY
Key for Table Update count MonnitoredQuantity.
bool shutdown(uint64_t)
Shuts Down the RoutingMasterCore.
void send_event_table(detail::RoutingPacket table)
Sends a detail::RoutingPacket to the table receivers.
Events should be routed by send count (EB -&gt; Agg)