artdaq_mfextensions  v1_03_06
UDP_mfPlugin.cc
1 #include "cetlib/PluginTypeDeducer.h"
2 #include "fhiclcpp/ParameterSet.h"
3 
4 #include "messagefacility/MessageService/ELdestination.h"
5 #include "messagefacility/Utilities/ELseverityLevel.h"
6 #if MESSAGEFACILITY_HEX_VERSION < 0x20201 // v2_02_01 is s67
7 #include "messagefacility/MessageService/MessageDrop.h"
8 #else
9 #include "messagefacility/MessageLogger/MessageLogger.h"
10 #endif
11 #include "cetlib/compiler_macros.h"
12 #include "messagefacility/Utilities/exception.h"
13 
14 // C/C++ includes
15 #include <arpa/inet.h>
16 #include <ifaddrs.h>
17 #include <netdb.h>
18 #include <netinet/in.h>
19 #include <algorithm>
20 #include <fstream>
21 #include <iostream>
22 #include <memory>
24 
25 #define TRACE_NAME "UDP_mfPlugin"
26 #include "trace.h"
27 
28 // Boost includes
29 #include <boost/algorithm/string.hpp>
30 
31 #if MESSAGEFACILITY_HEX_VERSION < 0x20201 // format changed to format_ for s67
32 #define format_ format
33 #endif
34 
35 namespace mfplugins {
36 using mf::ELseverityLevel;
37 using mf::ErrorObj;
38 using mf::service::ELdestination;
39 
44 class ELUDP : public ELdestination {
45  public:
49  struct Config {
51  fhicl::TableFragment<ELdestination::Config> elDestConfig;
54  fhicl::Atom<int> error_max = fhicl::Atom<int>{
55  fhicl::Name{"error_turnoff_threshold"},
56  fhicl::Comment{"Number of errors before turning off destination (default: 0, don't turn off)"}, 0};
58  fhicl::Atom<int> error_report = fhicl::Atom<int>{fhicl::Name{"error_report_backoff_factor"},
59  fhicl::Comment{"Print an error message every N errors"}, 100};
61  fhicl::Atom<std::string> host =
62  fhicl::Atom<std::string>{fhicl::Name{"host"}, fhicl::Comment{"Address to send messages to"}, "227.128.12.27"};
64  fhicl::Atom<int> port = fhicl::Atom<int>{fhicl::Name{"port"}, fhicl::Comment{"Port to send messages to"}, 5140};
66  fhicl::Atom<bool> multicast_enabled = fhicl::Atom<bool>{
67  fhicl::Name{"multicast_enabled"}, fhicl::Comment{"Whether messages should be sent via multicast"}, false};
70  fhicl::Atom<std::string> output_address = fhicl::Atom<std::string>{
71  fhicl::Name{"multicast_interface_ip"},
72  fhicl::Comment{"Use this hostname for multicast output(to assign to the proper NIC)"}, "0.0.0.0"};
73  };
75  using Parameters = fhicl::WrappedTable<Config>;
76 
77  public:
82  ELUDP(Parameters const& pset);
83 
89  virtual void fillPrefix(std::ostringstream& o, const ErrorObj& e) override;
90 
96  virtual void fillUsrMsg(std::ostringstream& o, const ErrorObj& e) override;
97 
101  virtual void fillSuffix(std::ostringstream&, const ErrorObj&) override {}
102 
108  virtual void routePayload(const std::ostringstream& o, const ErrorObj& e) override;
109 
110  private:
111  void reconnect_();
112 
113  // Parameters
114  int error_report_backoff_factor_;
115  int error_max_;
116  std::string host_;
117  int port_;
118  bool multicast_enabled_;
119  std::string multicast_out_addr_;
120 
121  int message_socket_;
122  struct sockaddr_in message_addr_;
123 
124  // Other stuff
125  int consecutive_success_count_;
126  int error_count_;
127  int next_error_report_;
128  int seqNum_;
129 
130  long pid_;
131  std::string hostname_;
132  std::string hostaddr_;
133  std::string app_;
134 };
135 
136 // END DECLARATION
137 //======================================================================
138 // BEGIN IMPLEMENTATION
139 
140 //======================================================================
141 // ELUDP c'tor
142 //======================================================================
143 
145  : ELdestination(pset().elDestConfig()),
146  error_report_backoff_factor_(pset().error_report()),
147  error_max_(pset().error_max()),
148  host_(pset().host()),
149  port_(pset().port()),
150  multicast_enabled_(pset().multicast_enabled()),
151  multicast_out_addr_(pset().output_address()),
152  message_socket_(-1),
153  consecutive_success_count_(0),
154  error_count_(0),
155  next_error_report_(1),
156  seqNum_(0),
157  pid_(static_cast<long>(getpid())) {
158  // hostname
159  char hostname_c[1024];
160  hostname_ = (gethostname(hostname_c, 1023) == 0) ? hostname_c : "Unkonwn Host";
161 
162  // host ip address
163  hostent* host = nullptr;
164  host = gethostbyname(hostname_c);
165 
166  if (host != nullptr) {
167  // ip address from hostname if the entry exists in /etc/hosts
168  char* ip = inet_ntoa(*(struct in_addr*)host->h_addr);
169  hostaddr_ = ip;
170  } else {
171  // enumerate all network interfaces
172  struct ifaddrs* ifAddrStruct = nullptr;
173  struct ifaddrs* ifa = nullptr;
174  void* tmpAddrPtr = nullptr;
175 
176  if (getifaddrs(&ifAddrStruct)) {
177  // failed to get addr struct
178  hostaddr_ = "127.0.0.1";
179  } else {
180  // iterate through all interfaces
181  for (ifa = ifAddrStruct; ifa != nullptr; ifa = ifa->ifa_next) {
182  if (ifa->ifa_addr->sa_family == AF_INET) {
183  // a valid IPv4 addres
184  tmpAddrPtr = &((struct sockaddr_in*)ifa->ifa_addr)->sin_addr;
185  char addressBuffer[INET_ADDRSTRLEN];
186  inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
187  hostaddr_ = addressBuffer;
188  }
189 
190  else if (ifa->ifa_addr->sa_family == AF_INET6) {
191  // a valid IPv6 address
192  tmpAddrPtr = &((struct sockaddr_in6*)ifa->ifa_addr)->sin6_addr;
193  char addressBuffer[INET6_ADDRSTRLEN];
194  inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
195  hostaddr_ = addressBuffer;
196  }
197 
198  // find first non-local address
199  if (!hostaddr_.empty() && hostaddr_.compare("127.0.0.1") && hostaddr_.compare("::1")) break;
200  }
201 
202  if (hostaddr_.empty()) // failed to find anything
203  hostaddr_ = "127.0.0.1";
204  }
205  }
206 
207 #if 0
208  // get process name from '/proc/pid/exe'
209  std::string exe;
210  std::ostringstream pid_ostr;
211  pid_ostr << "/proc/" << pid_ << "/exe";
212  exe = realpath(pid_ostr.str().c_str(), NULL);
213 
214  size_t end = exe.find('\0');
215  size_t start = exe.find_last_of('/', end);
216 
217  app_ = exe.substr(start + 1, end - start - 1);
218 #else
219  // get process name from '/proc/pid/cmdline'
220  std::stringstream ss;
221  ss << "//proc//" << pid_ << "//cmdline";
222  std::ifstream procfile{ss.str().c_str()};
223 
224  std::string procinfo;
225 
226  if (procfile.is_open()) {
227  procfile >> procinfo;
228  procfile.close();
229  }
230 
231  size_t end = procinfo.find('\0');
232  size_t start = procinfo.find_last_of('/', end);
233 
234  app_ = procinfo.substr(start + 1, end - start - 1);
235 #endif
236 }
237 
238 void ELUDP::reconnect_() {
239  message_socket_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
240  if (message_socket_ < 0) {
241  TLOG(TLVL_ERROR) << "I failed to create the socket for sending Data messages! err=" << strerror(errno);
242  exit(1);
243  }
244  int sts = ResolveHost(host_.c_str(), port_, message_addr_);
245  if (sts == -1) {
246  TLOG(TLVL_ERROR) << "Unable to resolve Data message address, err=" << strerror(errno);
247  exit(1);
248  }
249 
250  if (multicast_out_addr_ == "0.0.0.0") {
251  multicast_out_addr_.reserve(HOST_NAME_MAX);
252  sts = gethostname(&multicast_out_addr_[0], HOST_NAME_MAX);
253  if (sts < 0) {
254  TLOG(TLVL_ERROR) << "Could not get current hostname, err=" << strerror(errno);
255  exit(1);
256  }
257  }
258 
259  if (multicast_out_addr_ != "localhost") {
260  struct in_addr addr;
261  sts = GetInterfaceForNetwork(multicast_out_addr_.c_str(), addr);
262  // sts = ResolveHost(multicast_out_addr_.c_str(), addr);
263  if (sts == -1) {
264  TLOG(TLVL_ERROR) << "Unable to resolve multicast interface address, err=" << strerror(errno);
265  exit(1);
266  }
267 
268  if (setsockopt(message_socket_, IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr)) == -1) {
269  TLOG(TLVL_ERROR) << "Cannot set outgoing interface, err=" << strerror(errno);
270  exit(1);
271  }
272  }
273  int yes = 1;
274  if (setsockopt(message_socket_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0) {
275  TLOG(TLVL_ERROR) << "Unable to enable port reuse on message socket, err=" << strerror(errno);
276  exit(1);
277  }
278  if (setsockopt(message_socket_, IPPROTO_IP, IP_MULTICAST_LOOP, &yes, sizeof(yes)) < 0) {
279  TLOG(TLVL_ERROR) << "Unable to enable multicast loopback on message socket, err=" << strerror(errno);
280  exit(1);
281  }
282  if (setsockopt(message_socket_, SOL_SOCKET, SO_BROADCAST, (void*)&yes, sizeof(int)) == -1) {
283  TLOG(TLVL_ERROR) << "Cannot set message socket to broadcast, err=" << strerror(errno);
284  exit(1);
285  }
286 }
287 
288 //======================================================================
289 // Message prefix filler ( overriddes ELdestination::fillPrefix )
290 //======================================================================
291 void ELUDP::fillPrefix(std::ostringstream& oss, const ErrorObj& msg) {
292  const auto& xid = msg.xid();
293 
294  auto id = xid.id();
295  auto module = xid.module();
296  auto app = app_;
297  std::replace(id.begin(), id.end(), '|', '!');
298  std::replace(app.begin(), app.end(), '|', '!');
299  std::replace(module.begin(), module.end(), '|', '!');
300 
301  oss << format_.timestamp(msg.timestamp()) << "|"; // timestamp
302  oss << std::to_string(++seqNum_) << "|"; // sequence number
303  oss << hostname_ << "|"; // host name
304  oss << hostaddr_ << "|"; // host address
305  oss << xid.severity().getName() << "|"; // severity
306  oss << id << "|"; // category
307  oss << app << "|"; // application
308 #if MESSAGEFACILITY_HEX_VERSION >= 0x20201 // an indication of s67
309  oss << pid_ << "|";
310  oss << mf::GetIteration() << "|"; // run/event no
311 #else
312  oss << pid_ << "|"; // process id
313  oss << mf::MessageDrop::instance()->iteration << "|"; // run/event no
314 #endif
315  oss << module << "|"; // module name
316 #if MESSAGEFACILITY_HEX_VERSION >= 0x20201
317  oss << msg.filename() << "|" << std::to_string(msg.lineNumber()) << "|";
318 #endif
319 }
320 
321 //======================================================================
322 // Message filler ( overriddes ELdestination::fillUsrMsg )
323 //======================================================================
324 void ELUDP::fillUsrMsg(std::ostringstream& oss, const ErrorObj& msg) {
325  std::ostringstream tmposs;
326  // Print the contents.
327  for (auto const& val : msg.items()) {
328  tmposs << val;
329  }
330 
331  // remove leading "\n" if present
332  const std::string& usrMsg = !tmposs.str().compare(0, 1, "\n") ? tmposs.str().erase(0, 1) : tmposs.str();
333 
334  oss << usrMsg;
335 }
336 
337 //======================================================================
338 // Message router ( overriddes ELdestination::routePayload )
339 //======================================================================
340 void ELUDP::routePayload(const std::ostringstream& oss, const ErrorObj&) {
341  if (message_socket_ == -1) reconnect_();
342  if (error_count_ < error_max_ || error_max_ == 0) {
343  char str[INET_ADDRSTRLEN];
344  inet_ntop(AF_INET, &(message_addr_.sin_addr), str, INET_ADDRSTRLEN);
345 
346  auto string = "UDPMFMESSAGE" + std::to_string(pid_) + "|" + oss.str();
347  auto sts = sendto(message_socket_, string.c_str(), string.size(), 0, (struct sockaddr*)&message_addr_,
348  sizeof(message_addr_));
349 
350  if (sts < 0) {
351  consecutive_success_count_ = 0;
352  ++error_count_;
353  if (error_count_ == next_error_report_) {
354  TLOG(TLVL_ERROR) << "Error sending message " << seqNum_ << " to " << host_ << ", errno=" << errno << " ("
355  << strerror(errno) << ")";
356  next_error_report_ *= error_report_backoff_factor_;
357  }
358  } else {
359  ++consecutive_success_count_;
360  if (consecutive_success_count_ >= 5) {
361  error_count_ = 0;
362  next_error_report_ = 1;
363  }
364  }
365  }
366 }
367 } // end namespace mfplugins
368 
369 //======================================================================
370 //
371 // makePlugin function
372 //
373 //======================================================================
374 
375 #ifndef EXTERN_C_FUNC_DECLARE_START
376 #define EXTERN_C_FUNC_DECLARE_START extern "C" {
377 #endif
378 
379 EXTERN_C_FUNC_DECLARE_START
380 auto makePlugin(const std::string&, const fhicl::ParameterSet& pset) {
381  return std::make_unique<mfplugins::ELUDP>(pset);
382 }
383 }
384 
385 DEFINE_BASIC_PLUGINTYPE_FUNC(mf::service::ELdestination)
ELUDP(Parameters const &pset)
ELUDP Constructor
int ResolveHost(char const *host_in, in_addr &addr)
Convert a string hostname to a in_addr suitable for socket communication.
Definition: TCPConnect.hh:42
Message Facility UDP Streamer Destination Formats messages into a delimited string and sends via UDP ...
Definition: UDP_mfPlugin.cc:44
int GetInterfaceForNetwork(char const *host_in, in_addr &addr)
Convert an IP address to the network address of the interface sharing the subnet mask.
Definition: TCPConnect.hh:80
fhicl::Atom< int > error_report
&quot;error_report_backoff_factor&quot; (Default: 100): Print an error message every N errors ...
Definition: UDP_mfPlugin.cc:58
fhicl::Atom< int > port
&quot;port&quot; (Default: 5140): Port to send messages to
Definition: UDP_mfPlugin.cc:64
fhicl::Atom< std::string > host
&quot;host&quot; (Default: &quot;227.128.12.27&quot;): Address to send messages to
Definition: UDP_mfPlugin.cc:61
fhicl::Atom< std::string > output_address
Definition: UDP_mfPlugin.cc:70
Configuration Parameters for ELUDP.
Definition: UDP_mfPlugin.cc:49
virtual void routePayload(const std::ostringstream &o, const ErrorObj &e) override
Serialize a MessageFacility message to the output.
fhicl::WrappedTable< Config > Parameters
Used for ParameterSet validation.
Definition: UDP_mfPlugin.cc:75
fhicl::Atom< int > error_max
Definition: UDP_mfPlugin.cc:54
virtual void fillUsrMsg(std::ostringstream &o, const ErrorObj &e) override
Fill the &quot;User Message&quot; portion of the message.
virtual void fillPrefix(std::ostringstream &o, const ErrorObj &e) override
Fill the &quot;Prefix&quot; portion of the message.
fhicl::TableFragment< ELdestination::Config > elDestConfig
ELDestination common config parameters.
Definition: UDP_mfPlugin.cc:51
virtual void fillSuffix(std::ostringstream &, const ErrorObj &) override
Fill the &quot;Suffix&quot; portion of the message (Unused)
fhicl::Atom< bool > multicast_enabled
&quot;multicast_enabled&quot; (Default: false): Whether messages should be sent via multicast ...
Definition: UDP_mfPlugin.cc:66