Belle II Software  release-05-02-19
ZMQConfirmedInput Class Reference

Input part of a confirmed connection. More...

#include <ZMQConfirmedConnection.h>

Inheritance diagram for ZMQConfirmedInput:
Collaboration diagram for ZMQConfirmedInput:

Public Types

using ReactorFunction = std::function< void(void)>
 Typedef of a function which will be called if a connection has a message.
 

Public Member Functions

 ZMQConfirmedInput (const std::string &inputAddress, const std::shared_ptr< ZMQParent > &parent)
 Create a new confirmed output by binding to the address.
 
std::unique_ptr< ZMQIdMessagehandleIncomingData ()
 Block until a message can be received from one of the inputs. More...
 
void clear ()
 Reset the counters for all received stop and terminate messages. Should be called on run start.
 
std::unique_ptr< ZMQIdMessageoverwriteStopMessage ()
 Manually overwrite the stop message counter and set it to have all stop messages received.
 
std::vector< zmq::socket_t * > getSockets () const final
 The socket used for polling is just the stored socket.
 
virtual bool isReady () const
 Return true of this connection is able to send messages right now. Can be overloaded in derived classes.
 
virtual std::string getMonitoringJSON () const
 Convert the stored monitoring values to a JSON string ready for sending out via a message.
 
template<class AClass >
void log (const std::string &key, const AClass &value)
 Store a value under a certain key. Different types of values can be stored, namely long, double or string. Mixtures are not allowed for a given key.
 
void increment (const std::string &key)
 Increment the value with the given key (only numerical values). If not present, set to 1.
 
void decrement (const std::string &key)
 Decrement the value with the given key (only numerical values). If not present, set to -1.
 
template<size_t MAX_SIZE = 100>
void average (const std::string &key, double value)
 Instead of storeing the double value directly under the given key, store the average of the last MAX_SIZE values.
 
template<size_t AVERAGE_SIZE = 2000>
void timeit (const std::string &key)
 Measure the rate of calls with the same key every AVERAGE_SIZE calls (and also display the last time AVERAGE_SIZE was reached under <key>_last_measurement)
 
void logTime (const std::string &key)
 Store the current time as a string under the given key.
 

Static Public Member Functions

static bool poll (const std::map< const ZMQConnection *, ReactorFunction > &connectionList, int timeout)
 Poll on the given connections and call the attached function if a messages comes in. More...
 
static bool hasMessage (const ZMQConnection *connection)
 Check if the given connection as an incoming message (right now, no waiting).
 

Protected Attributes

std::shared_ptr< ZMQParentm_parent
 The shared ZMQParent instance.
 
std::unique_ptr< zmq::socket_t > m_socket
 The memory of the socket. Needs to be initialized in a derived class.
 

Private Attributes

std::set< std::string > m_receivedStopMessages
 The set of input identities which have already sent a stop message.
 
bool m_allStopMessages = false
 Have we received all stop messages?
 
std::set< std::string > m_receivedTerminateMessages
 The set of input identities which have already sent a terminate message.
 
bool m_allTerminateMessages = false
 Have we received all terminante messages?
 
std::set< std::string > m_registeredWorkersInput
 The set of all registered inputs.
 
std::map< std::string, std::variant< long, double, std::string > > m_monitoring
 Internal storage of all stored values.
 
std::unordered_map< std::string, std::tuple< std::vector< double >, size_t > > m_averages
 Internal storage of the previous values when calculating averages.
 
std::unordered_map< std::string, std::tuple< unsigned long, std::chrono::system_clock::time_point > > m_timeCounters
 Internal storage how often the timeit function for a given key was called and when it has last reached MAX_SIZE.
 

Detailed Description

Input part of a confirmed connection.

In a confirmed connection every message sent by the input to the output is confirmed by a confirmation message by the output. The output can handle multiple inputs, each input can only be connected to a single output.

The input part keeps track of the registered workers and if it has received all stop and/or terminate messages. Stop/Terminate messages are only passed on if received from all registered workers.

If the input receives a message from one of the outputs, it sends back a confirmation message. Depending on the message type, it does several things:

  • if the message is a hello message (the input registered itself), it adds the input identity to the registered workers. Nothing is returned to the caller in this case.
  • if the message is a delete message (someone unregistered a worker), it removes the specified input identity in the message from the registered workers. Nothing is returned to the caller in this case. (corner case: if it turns out the worker to be unregistered was the last one missing for a full stop or terminate message from all workers, this message is passed on)
  • if the message is a stop message, add it to the received stop messages. Only if all registered workers have send a stop message pass it on.
  • same for terminate messages
  • in all other cases just pass on the message.

Internally, a ZMQ_ROUTER is used in bind-mode. The order of starting output and input does not play any role.

Definition at line 65 of file ZMQConfirmedConnection.h.

Member Function Documentation

◆ handleIncomingData()

std::unique_ptr< ZMQIdMessage > handleIncomingData ( )

Block until a message can be received from one of the inputs.

React as described in the general description of this class. Only if a message is to be passed on actually returns a message (in all other cases a nullptr).

Definition at line 50 of file ZMQConfirmedConnection.cc.

51 {
52  auto message = ZMQMessageFactory::fromSocket<ZMQIdMessage>(m_socket);
53  const auto fromIdentity = message->getIdentity();
54 
55  logTime("last_received_message");
56  increment("total_number_messages");
57  increment("total_number_messages_from[" + fromIdentity + "]");
58 
59  auto confirmMessage = ZMQMessageFactory::createMessage(fromIdentity, EMessageTypes::c_confirmMessage);
60  ZMQParent::send(m_socket, std::move(confirmMessage));
61 
62  if (message->isMessage(EMessageTypes::c_helloMessage)) {
63  // a hello message makes us register the worker identity - which is the identity of the sender of the message
64  m_registeredWorkersInput.emplace(fromIdentity);
65  log("registered_workers", static_cast<long>(m_registeredWorkersInput.size()));
66  increment("hello_messages");
67  increment("hello_messages_from[" + fromIdentity + "]");
68  return {};
69  } else if (message->isMessage(EMessageTypes::c_deleteWorkerMessage)) {
70  // a delete message makes us forget about the worker identity. The identity is taken from the message data
71  // making it possible to delete other workers.
72  B2DEBUG(10, "Got message from " << message->getIdentity() << " to kill " << message->getMessagePartAsString<2>());
73  const std::string& killedIdentity = message->getMessagePartAsString<2>();
74  m_registeredWorkersInput.erase(killedIdentity);
75 
76  log("registered_workers", static_cast<long>(m_registeredWorkersInput.size()));
77  increment("dead_workers");
78  increment("dead_worker_messaged_from[" + fromIdentity + "]");
79 
80  if (m_registeredWorkersInput.empty()) {
81  B2ERROR("There is not a single worker registered anymore!");
82  return {};
83  }
84 
85  // Corner case: could be that this was the one we were waiting for
87  m_allStopMessages = true;
88  log("all_stop_messages", static_cast<long>(m_allStopMessages));
89  increment("sent_stop_messages");
90  logTime("last_stop_sent");
91 
92  return ZMQMessageFactory::createMessage(killedIdentity, EMessageTypes::c_lastEventMessage);
93  }
94  // Corner case: could be that this was the one we were waiting for
97  log("all_terminate_messages", static_cast<long>(m_allTerminateMessages));
98  increment("sent_terminate_messages");
99  logTime("last_terminate_sent");
100 
101  return ZMQMessageFactory::createMessage(killedIdentity, EMessageTypes::c_terminateMessage);
102  }
103 
104  return {};
105  }
106 
107  B2ASSERT("Worker without proper registration!",
108  m_registeredWorkersInput.find(fromIdentity) != m_registeredWorkersInput.end());
109 
110  if (message->isMessage(EMessageTypes::c_lastEventMessage)) {
111  // Increment the stop messages
112  m_receivedStopMessages.emplace(fromIdentity);
113  log("received_stop_messages", static_cast<long>(m_receivedStopMessages.size()));
114  increment("total_received_stop_messages");
115 
117  // But only return this if everyone has sent a stop message already
118  m_allStopMessages = true;
119  log("all_stop_messages", static_cast<long>(m_allStopMessages));
120  increment("sent_stop_messages");
121  logTime("last_stop_sent");
122 
123  return ZMQMessageFactory::createMessage(fromIdentity, EMessageTypes::c_lastEventMessage);
124  }
125 
126  // Whatever we return here will be carried on to the application and eventually also to the output.
127  // This means as we are not passing the stop message now, we return nothing.
128  return {};
129  } else if (message->isMessage(EMessageTypes::c_terminateMessage)) {
130  // Increment the terminate messages
131  m_receivedTerminateMessages.emplace(fromIdentity);
132  log("received_terminate_messages", static_cast<long>(m_receivedTerminateMessages.size()));
133  increment("total_received_terminate_messages");
134 
136  // But only return this if everyone has sent a terminate message already
137  m_allTerminateMessages = true;
138  log("all_terminate_messages", static_cast<long>(m_allTerminateMessages));
139  increment("sent_terminate_messages");
140  logTime("last_terminate_sent");
141 
142  return ZMQMessageFactory::createMessage(fromIdentity, EMessageTypes::c_terminateMessage);
143  }
144 
145  // Whatever we return here will be carried on to the application and eventually also to the output.
146  // This means as we are not passing the stop message now, we return nothing.
147  return {};
148  }
149 
150  if (m_allStopMessages) {
151  B2ERROR("Received an event after having received stop messages from every worker. This is not a good sign! I will dismiss this event!");
152  increment("received_messages_after_stop");
153  return {};
154  }
155 
156  // Now it can only be a plain normal data message, so just pass it on
157  const auto dataSize = message->getDataMessage().size();
158 
159  average("data_size", dataSize);
160  average("data_size_from[" + fromIdentity + "]", dataSize);
161 
162  increment("received_events");
163  increment("received_events[" + fromIdentity + "]");
164 
165  timeit("event_rate");
166  timeit<200>("event_rate_from[" + fromIdentity + "]");
167 
168  logTime("last_received_event_message");
169 
170  return message;
171 }

◆ poll()

bool poll ( const std::map< const ZMQConnection *, ReactorFunction > &  connectionList,
int  timeout 
)
staticinherited

Poll on the given connections and call the attached function if a messages comes in.

If after timeout milliseconds still no message is received, return anyways. If timeout is 0, do not wait. If timeout is -1, wait infinitely.

Returns true if a message was received on any socket, false otherwise. Attention: in case of an interrupted system call (e.g. because a signal was received) the function might return anyways with a negative result even before the timeout!

Definition at line 29 of file ZMQConnection.cc.

30 {
31  std::vector<const ReactorFunction*> socketMapping;
32  std::vector<zmq::pollitem_t> pollItems;
33 
34  // zmq needs a special format for its polling, so create it here.
35  for (const auto& [connection, function] : connectionList) {
36  auto sockets = connection->getSockets();
37  for (zmq::socket_t* socket : sockets) {
38  zmq::pollitem_t pollItem;
39  pollItem.socket = static_cast<void*>(*socket);
40  pollItem.events = ZMQ_POLLIN;
41  pollItem.revents = 0;
42  pollItems.push_back(std::move(pollItem));
43 
44  // but keep reference to the original function, so we can call the correct one later
45  socketMapping.push_back(&function);
46  }
47  }
48 
49  if (pollItems.empty()) {
50  return false;
51  }
52 
53  try {
54  zmq::poll(&pollItems[0], pollItems.size(), timeout);
55 
56  bool anySocket = false;
57  unsigned int counter = 0;
58  for (const auto& pollItem : pollItems) {
59  if (pollItem.revents & ZMQ_POLLIN) {
60  anySocket = true;
61  const auto* functionPtr = socketMapping.at(counter);
62  const auto function = *functionPtr;
63  function();
64  }
65  counter++;
66  }
67 
68  return anySocket;
69  } catch (zmq::error_t& error) {
70  if (error.num() == EINTR) {
71  // Could happen if there was an interrupt, return false so the caller knows the time did not pass already
72  return false;
73  } else {
74  // cannot handle, rethrow exception
75  throw;
76  }
77  }
78 }

The documentation for this class was generated from the following files:
Belle2::ZMQConfirmedInput::m_receivedStopMessages
std::set< std::string > m_receivedStopMessages
The set of input identities which have already sent a stop message.
Definition: ZMQConfirmedConnection.h:86
Belle2::ZMQLogger::timeit
void timeit(const std::string &key)
Measure the rate of calls with the same key every AVERAGE_SIZE calls (and also display the last time ...
Definition: ZMQLogger.h:127
Belle2::ZMQParent::send
static void send(std::unique_ptr< zmq::socket_t > &socket, AZMQMessage message)
Send a given message over the given created socket. You need to move in the message for zero-copy.
Definition: ZMQParent.h:163
Belle2::ZMQLogger::logTime
void logTime(const std::string &key)
Store the current time as a string under the given key.
Definition: ZMQLogger.cc:44
Belle2::ZMQConfirmedInput::m_registeredWorkersInput
std::set< std::string > m_registeredWorkersInput
The set of all registered inputs.
Definition: ZMQConfirmedConnection.h:94
Belle2::ZMQConfirmedInput::m_allTerminateMessages
bool m_allTerminateMessages
Have we received all terminante messages?
Definition: ZMQConfirmedConnection.h:92
Belle2::ZMQConfirmedInput::m_receivedTerminateMessages
std::set< std::string > m_receivedTerminateMessages
The set of input identities which have already sent a terminate message.
Definition: ZMQConfirmedConnection.h:90
Belle2::ZMQConfirmedInput::m_allStopMessages
bool m_allStopMessages
Have we received all stop messages?
Definition: ZMQConfirmedConnection.h:88
Belle2::ZMQLogger::log
void log(const std::string &key, const AClass &value)
Store a value under a certain key. Different types of values can be stored, namely long,...
Definition: ZMQLogger.h:106
Belle2::ZMQLogger::increment
void increment(const std::string &key)
Increment the value with the given key (only numerical values). If not present, set to 1.
Definition: ZMQLogger.cc:34
Belle2::ZMQMessageFactory::createMessage
static auto createMessage(const std::string &msgIdentity, const EMessageTypes msgType, const std::unique_ptr< EvtMessage > &eventMessage)
Create an ID Message out of an identity, the type and an event message.
Definition: ZMQMessageFactory.h:37
Belle2::ZMQLogger::average
void average(const std::string &key, double value)
Instead of storeing the double value directly under the given key, store the average of the last MAX_...
Definition: ZMQLogger.h:112
Belle2::ZMQConnectionOverSocket::m_socket
std::unique_ptr< zmq::socket_t > m_socket
The memory of the socket. Needs to be initialized in a derived class.
Definition: ZMQConnection.h:84