artdaq_mfextensions  v1_04_00
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 {
46 public:
50  struct Config
51  {
53  fhicl::TableFragment<ELdestination::Config> elDestConfig;
56  fhicl::Atom<int> error_max = fhicl::Atom<int>{
57  fhicl::Name{"error_turnoff_threshold"},
58  fhicl::Comment{"Number of errors before turning off destination (default: 0, don't turn off)"}, 0};
60  fhicl::Atom<int> error_report = fhicl::Atom<int>{fhicl::Name{"error_report_backoff_factor"},
61  fhicl::Comment{"Print an error message every N errors"}, 100};
63  fhicl::Atom<std::string> host =
64  fhicl::Atom<std::string>{fhicl::Name{"host"}, fhicl::Comment{"Address to send messages to"}, "227.128.12.27"};
66  fhicl::Atom<int> port = fhicl::Atom<int>{fhicl::Name{"port"}, fhicl::Comment{"Port to send messages to"}, 5140};
68  fhicl::Atom<bool> multicast_enabled = fhicl::Atom<bool>{
69  fhicl::Name{"multicast_enabled"}, fhicl::Comment{"Whether messages should be sent via multicast"}, false};
72  fhicl::Atom<std::string> output_address = fhicl::Atom<std::string>{
73  fhicl::Name{"multicast_interface_ip"},
74  fhicl::Comment{"Use this hostname for multicast output(to assign to the proper NIC)"}, "0.0.0.0"};
75  };
77  using Parameters = fhicl::WrappedTable<Config>;
78 
79 public:
84  ELUDP(Parameters const& pset);
85 
91  virtual void fillPrefix(std::ostringstream& o, const ErrorObj& e) override;
92 
98  virtual void fillUsrMsg(std::ostringstream& o, const ErrorObj& e) override;
99 
103  virtual void fillSuffix(std::ostringstream&, const ErrorObj&) override {}
104 
110  virtual void routePayload(const std::ostringstream& o, const ErrorObj& e) override;
111 
112 private:
113  void reconnect_();
114 
115  // Parameters
116  int error_report_backoff_factor_;
117  int error_max_;
118  std::string host_;
119  int port_;
120  bool multicast_enabled_;
121  std::string multicast_out_addr_;
122 
123  int message_socket_;
124  struct sockaddr_in message_addr_;
125 
126  // Other stuff
127  int consecutive_success_count_;
128  int error_count_;
129  int next_error_report_;
130  int seqNum_;
131 
132  long pid_;
133  std::string hostname_;
134  std::string hostaddr_;
135  std::string app_;
136 };
137 
138 // END DECLARATION
139 //======================================================================
140 // BEGIN IMPLEMENTATION
141 
142 //======================================================================
143 // ELUDP c'tor
144 //======================================================================
145 
147  : ELdestination(pset().elDestConfig()), error_report_backoff_factor_(pset().error_report()), error_max_(pset().error_max()), host_(pset().host()), port_(pset().port()), multicast_enabled_(pset().multicast_enabled()), multicast_out_addr_(pset().output_address()), message_socket_(-1), consecutive_success_count_(0), error_count_(0), next_error_report_(1), seqNum_(0), pid_(static_cast<long>(getpid()))
148 {
149  // hostname
150  char hostname_c[1024];
151  hostname_ = (gethostname(hostname_c, 1023) == 0) ? hostname_c : "Unkonwn Host";
152 
153  // host ip address
154  hostent* host = nullptr;
155  host = gethostbyname(hostname_c);
156 
157  if (host != nullptr)
158  {
159  // ip address from hostname if the entry exists in /etc/hosts
160  char* ip = inet_ntoa(*(struct in_addr*)host->h_addr);
161  hostaddr_ = ip;
162  }
163  else
164  {
165  // enumerate all network interfaces
166  struct ifaddrs* ifAddrStruct = nullptr;
167  struct ifaddrs* ifa = nullptr;
168  void* tmpAddrPtr = nullptr;
169 
170  if (getifaddrs(&ifAddrStruct))
171  {
172  // failed to get addr struct
173  hostaddr_ = "127.0.0.1";
174  }
175  else
176  {
177  // iterate through all interfaces
178  for (ifa = ifAddrStruct; ifa != nullptr; ifa = ifa->ifa_next)
179  {
180  if (ifa->ifa_addr->sa_family == AF_INET)
181  {
182  // a valid IPv4 addres
183  tmpAddrPtr = &((struct sockaddr_in*)ifa->ifa_addr)->sin_addr;
184  char addressBuffer[INET_ADDRSTRLEN];
185  inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
186  hostaddr_ = addressBuffer;
187  }
188 
189  else if (ifa->ifa_addr->sa_family == AF_INET6)
190  {
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  {
228  procfile >> procinfo;
229  procfile.close();
230  }
231 
232  size_t end = procinfo.find('\0');
233  size_t start = procinfo.find_last_of('/', end);
234 
235  app_ = procinfo.substr(start + 1, end - start - 1);
236 #endif
237 }
238 
239 void ELUDP::reconnect_()
240 {
241  message_socket_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
242  if (message_socket_ < 0)
243  {
244  TLOG(TLVL_ERROR) << "I failed to create the socket for sending Data messages! err=" << strerror(errno);
245  exit(1);
246  }
247  int sts = ResolveHost(host_.c_str(), port_, message_addr_);
248  if (sts == -1)
249  {
250  TLOG(TLVL_ERROR) << "Unable to resolve Data message address, err=" << strerror(errno);
251  exit(1);
252  }
253 
254  if (multicast_out_addr_ == "0.0.0.0")
255  {
256  multicast_out_addr_.reserve(HOST_NAME_MAX);
257  sts = gethostname(&multicast_out_addr_[0], HOST_NAME_MAX);
258  if (sts < 0)
259  {
260  TLOG(TLVL_ERROR) << "Could not get current hostname, err=" << strerror(errno);
261  exit(1);
262  }
263  }
264 
265  if (multicast_out_addr_ != "localhost")
266  {
267  struct in_addr addr;
268  sts = GetInterfaceForNetwork(multicast_out_addr_.c_str(), addr);
269  // sts = ResolveHost(multicast_out_addr_.c_str(), addr);
270  if (sts == -1)
271  {
272  TLOG(TLVL_ERROR) << "Unable to resolve multicast interface address, err=" << strerror(errno);
273  exit(1);
274  }
275 
276  if (setsockopt(message_socket_, IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr)) == -1)
277  {
278  TLOG(TLVL_ERROR) << "Cannot set outgoing interface, err=" << strerror(errno);
279  exit(1);
280  }
281  }
282  int yes = 1;
283  if (setsockopt(message_socket_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0)
284  {
285  TLOG(TLVL_ERROR) << "Unable to enable port reuse on message socket, err=" << strerror(errno);
286  exit(1);
287  }
288  if (setsockopt(message_socket_, IPPROTO_IP, IP_MULTICAST_LOOP, &yes, sizeof(yes)) < 0)
289  {
290  TLOG(TLVL_ERROR) << "Unable to enable multicast loopback on message socket, err=" << strerror(errno);
291  exit(1);
292  }
293  if (setsockopt(message_socket_, SOL_SOCKET, SO_BROADCAST, (void*)&yes, sizeof(int)) == -1)
294  {
295  TLOG(TLVL_ERROR) << "Cannot set message socket to broadcast, err=" << strerror(errno);
296  exit(1);
297  }
298 }
299 
300 //======================================================================
301 // Message prefix filler ( overriddes ELdestination::fillPrefix )
302 //======================================================================
303 void ELUDP::fillPrefix(std::ostringstream& oss, const ErrorObj& msg)
304 {
305  const auto& xid = msg.xid();
306 
307  auto id = xid.id();
308  auto module = xid.module();
309  auto app = app_;
310  std::replace(id.begin(), id.end(), '|', '!');
311  std::replace(app.begin(), app.end(), '|', '!');
312  std::replace(module.begin(), module.end(), '|', '!');
313 
314  oss << format_.timestamp(msg.timestamp()) << "|"; // timestamp
315  oss << std::to_string(++seqNum_) << "|"; // sequence number
316  oss << hostname_ << "|"; // host name
317  oss << hostaddr_ << "|"; // host address
318  oss << xid.severity().getName() << "|"; // severity
319  oss << id << "|"; // category
320  oss << app << "|"; // application
321 #if MESSAGEFACILITY_HEX_VERSION >= 0x20201 // an indication of s67
322  oss << pid_ << "|";
323  oss << mf::GetIteration() << "|"; // run/event no
324 #else
325  oss << pid_ << "|"; // process id
326  oss << mf::MessageDrop::instance()->iteration << "|"; // run/event no
327 #endif
328  oss << module << "|"; // module name
329 #if MESSAGEFACILITY_HEX_VERSION >= 0x20201
330  oss << msg.filename() << "|" << std::to_string(msg.lineNumber()) << "|";
331 #endif
332 }
333 
334 //======================================================================
335 // Message filler ( overriddes ELdestination::fillUsrMsg )
336 //======================================================================
337 void ELUDP::fillUsrMsg(std::ostringstream& oss, const ErrorObj& msg)
338 {
339  std::ostringstream tmposs;
340  // Print the contents.
341  for (auto const& val : msg.items())
342  {
343  tmposs << val;
344  }
345 
346  // remove leading "\n" if present
347  const std::string& usrMsg = !tmposs.str().compare(0, 1, "\n") ? tmposs.str().erase(0, 1) : tmposs.str();
348 
349  oss << usrMsg;
350 }
351 
352 //======================================================================
353 // Message router ( overriddes ELdestination::routePayload )
354 //======================================================================
355 void ELUDP::routePayload(const std::ostringstream& oss, const ErrorObj&)
356 {
357  if (message_socket_ == -1) reconnect_();
358  if (error_count_ < error_max_ || error_max_ == 0)
359  {
360  char str[INET_ADDRSTRLEN];
361  inet_ntop(AF_INET, &(message_addr_.sin_addr), str, INET_ADDRSTRLEN);
362 
363  auto string = "UDPMFMESSAGE" + std::to_string(pid_) + "|" + oss.str();
364  auto sts = sendto(message_socket_, string.c_str(), string.size(), 0, (struct sockaddr*)&message_addr_,
365  sizeof(message_addr_));
366 
367  if (sts < 0)
368  {
369  consecutive_success_count_ = 0;
370  ++error_count_;
371  if (error_count_ == next_error_report_)
372  {
373  TLOG(TLVL_ERROR) << "Error sending message " << seqNum_ << " to " << host_ << ", errno=" << errno << " ("
374  << strerror(errno) << ")";
375  next_error_report_ *= error_report_backoff_factor_;
376  }
377  }
378  else
379  {
380  ++consecutive_success_count_;
381  if (consecutive_success_count_ >= 5)
382  {
383  error_count_ = 0;
384  next_error_report_ = 1;
385  }
386  }
387  }
388 }
389 } // end namespace mfplugins
390 
391 //======================================================================
392 //
393 // makePlugin function
394 //
395 //======================================================================
396 
397 #ifndef EXTERN_C_FUNC_DECLARE_START
398 #define EXTERN_C_FUNC_DECLARE_START extern "C" {
399 #endif
400 
401 EXTERN_C_FUNC_DECLARE_START
402 auto makePlugin(const std::string&, const fhicl::ParameterSet& pset)
403 {
404  return std::make_unique<mfplugins::ELUDP>(pset);
405 }
406 }
407 
408 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:90
fhicl::Atom< int > error_report
&quot;error_report_backoff_factor&quot; (Default: 100): Print an error message every N errors ...
Definition: UDP_mfPlugin.cc:60
fhicl::Atom< int > port
&quot;port&quot; (Default: 5140): Port to send messages to
Definition: UDP_mfPlugin.cc:66
fhicl::Atom< std::string > host
&quot;host&quot; (Default: &quot;227.128.12.27&quot;): Address to send messages to
Definition: UDP_mfPlugin.cc:63
fhicl::Atom< std::string > output_address
Definition: UDP_mfPlugin.cc:72
Configuration Parameters for ELUDP.
Definition: UDP_mfPlugin.cc:50
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:77
fhicl::Atom< int > error_max
Definition: UDP_mfPlugin.cc:56
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:53
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:68