artdaq_mfextensions  v1_06_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 #include "messagefacility/MessageLogger/MessageLogger.h"
7 #include "cetlib/compiler_macros.h"
8 #include "messagefacility/Utilities/exception.h"
9 
10 // C/C++ includes
11 #include <arpa/inet.h>
12 #include <ifaddrs.h>
13 #include <netdb.h>
14 #include <netinet/in.h>
15 #include <algorithm>
16 #include <fstream>
17 #include <mutex>
18 #include <iostream>
19 #include <memory>
21 
22 #define TRACE_NAME "UDP_mfPlugin"
23 #include "trace.h"
24 
25 // Boost includes
26 #include <boost/algorithm/string.hpp>
27 
28 namespace mfplugins {
29 using mf::ErrorObj;
30 using mf::service::ELdestination;
31 
36 class ELUDP : public ELdestination
37 {
38 public:
42  struct Config
43  {
45  fhicl::TableFragment<ELdestination::Config> elDestConfig;
48  fhicl::Atom<int> error_max = fhicl::Atom<int>{
49  fhicl::Name{"error_turnoff_threshold"},
50  fhicl::Comment{"Number of errors before turning off destination (default: 0, don't turn off)"}, 0};
52  fhicl::Atom<int> error_report = fhicl::Atom<int>{fhicl::Name{"error_report_backoff_factor"},
53  fhicl::Comment{"Print an error message every N errors"}, 100};
55  fhicl::Atom<std::string> host =
56  fhicl::Atom<std::string>{fhicl::Name{"host"}, fhicl::Comment{"Address to send messages to"}, "227.128.12.27"};
58  fhicl::Atom<int> port = fhicl::Atom<int>{fhicl::Name{"port"}, fhicl::Comment{"Port to send messages to"}, 5140};
60  fhicl::Atom<bool> multicast_enabled = fhicl::Atom<bool>{
61  fhicl::Name{"multicast_enabled"}, fhicl::Comment{"Whether messages should be sent via multicast"}, false};
64  fhicl::Atom<std::string> output_address = fhicl::Atom<std::string>{
65  fhicl::Name{"multicast_interface_ip"},
66  fhicl::Comment{"Use this hostname for multicast output(to assign to the proper NIC)"}, "0.0.0.0"};
68  fhicl::Atom<std::string> filename_delimit =
69  fhicl::Atom<std::string>{fhicl::Name{"filename_delimit"},
70  fhicl::Comment{"Grab path after this. \"/srcs/\" /x/srcs/y/z.cc => y/z.cc. NOTE: only works if full filename is given to this plugin (based on which mf::<method> is used)."}, "/"};
71  };
73  using Parameters = fhicl::WrappedTable<Config>;
74 
75 public:
80  ELUDP(Parameters const& pset);
81 
87  void fillPrefix(std::ostringstream& o, const ErrorObj& msg) override;
88 
94  void fillUsrMsg(std::ostringstream& o, const ErrorObj& msg) override;
95 
99  void fillSuffix(std::ostringstream& /*unused*/, const ErrorObj& /*msg*/) override {}
100 
106  void routePayload(const std::ostringstream& o, const ErrorObj& e) override;
107 
108 private:
109  void reconnect_();
110 
111  // Parameters
112  int error_report_backoff_factor_;
113  int error_max_;
114  std::string host_;
115  int port_;
116  bool multicast_enabled_;
117  std::string multicast_out_addr_;
118 
119  int message_socket_;
120  struct sockaddr_in message_addr_;
121 
122  // Other stuff
123  int consecutive_success_count_;
124  int error_count_;
125  int next_error_report_;
126  int seqNum_;
127 
128  int64_t pid_;
129  std::string hostname_;
130  std::string hostaddr_;
131  std::string app_;
132  std::string filename_delimit_;
133 };
134 
135 // END DECLARATION
136 //======================================================================
137 // BEGIN IMPLEMENTATION
138 
139 //======================================================================
140 // ELUDP c'tor
141 //======================================================================
142 
144  : ELdestination(pset().elDestConfig()), error_report_backoff_factor_(pset().error_report()), error_max_(pset().error_max())
145  , host_(pset().host()), port_(pset().port()), multicast_enabled_(pset().multicast_enabled()), multicast_out_addr_(pset().output_address())
146  , message_socket_(-1), consecutive_success_count_(0), error_count_(0), next_error_report_(1), seqNum_(0), pid_(static_cast<int64_t>(getpid()))
147  , filename_delimit_(pset().filename_delimit())
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(*reinterpret_cast<struct in_addr*>(host->h_addr)); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-bounds-pointer-arithmetic)
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) != 0)
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 = &(reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr)->sin_addr); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
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 = &(reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr)->sin6_addr); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
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_ != "127.0.0.1") && (hostaddr_ != "::1"))
200  {
201  break;
202  }
203  }
204 
205  if (hostaddr_.empty())
206  { // failed to find anything
207  hostaddr_ = "127.0.0.1";
208  }
209  }
210  }
211 
212 #if 0
213  // get process name from '/proc/pid/exe'
214  std::string exe;
215  std::ostringstream pid_ostr;
216  pid_ostr << "/proc/" << pid_ << "/exe";
217  exe = realpath(pid_ostr.str().c_str(), NULL);
218 
219  size_t end = exe.find('\0');
220  size_t start = exe.find_last_of('/', end);
221 
222  app_ = exe.substr(start + 1, end - start - 1);
223 #else
224  // get process name from '/proc/pid/cmdline'
225  std::stringstream ss;
226  ss << "//proc//" << pid_ << "//cmdline";
227  std::ifstream procfile{ss.str().c_str()};
228 
229  std::string procinfo;
230 
231  if (procfile.is_open())
232  {
233  procfile >> procinfo;
234  procfile.close();
235  }
236 
237  size_t end = procinfo.find('\0');
238  size_t start = procinfo.find_last_of('/', end);
239 
240  app_ = procinfo.substr(start + 1, end - start - 1);
241 #endif
242 }
243 
244 void ELUDP::reconnect_()
245 {
246  static std::mutex mutex;
247  std::lock_guard<std::mutex> lk(mutex);
248  if (message_socket_ == -1)
249  {
250  message_socket_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
251  if (message_socket_ < 0)
252  {
253  TLOG(TLVL_ERROR) << "I failed to create the socket for sending Data messages! err=" << strerror(errno);
254  exit(1);
255  }
256  int sts = ResolveHost(host_.c_str(), port_, message_addr_);
257  if (sts == -1)
258  {
259  TLOG(TLVL_ERROR) << "Unable to resolve Data message address, err=" << strerror(errno);
260  exit(1);
261  }
262 
263  if (multicast_out_addr_ == "0.0.0.0")
264  {
265  multicast_out_addr_.reserve(HOST_NAME_MAX);
266  sts = gethostname(&multicast_out_addr_[0], HOST_NAME_MAX);
267  if (sts < 0)
268  {
269  TLOG(TLVL_ERROR) << "Could not get current hostname, err=" << strerror(errno);
270  exit(1);
271  }
272  }
273 
274  if (multicast_out_addr_ != "localhost")
275  {
276  struct in_addr addr;
277  sts = GetInterfaceForNetwork(multicast_out_addr_.c_str(), addr);
278  // sts = ResolveHost(multicast_out_addr_.c_str(), addr);
279  if (sts == -1)
280  {
281  TLOG(TLVL_ERROR) << "Unable to resolve multicast interface address, err=" << strerror(errno);
282  exit(1);
283  }
284 
285  if (setsockopt(message_socket_, IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr)) == -1)
286  {
287  TLOG(TLVL_ERROR) << "Cannot set outgoing interface, err=" << strerror(errno);
288  exit(1);
289  }
290  }
291  int yes = 1;
292  if (setsockopt(message_socket_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0)
293  {
294  TLOG(TLVL_ERROR) << "Unable to enable port reuse on message socket, err=" << strerror(errno);
295  exit(1);
296  }
297  if (setsockopt(message_socket_, IPPROTO_IP, IP_MULTICAST_LOOP, &yes, sizeof(yes)) < 0)
298  {
299  TLOG(TLVL_ERROR) << "Unable to enable multicast loopback on message socket, err=" << strerror(errno);
300  exit(1);
301  }
302  if (setsockopt(message_socket_, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes)) == -1)
303  {
304  TLOG(TLVL_ERROR) << "Cannot set message socket to broadcast, err=" << strerror(errno);
305  exit(1);
306  }
307  }
308 }
309 
310 //======================================================================
311 // Message prefix filler ( overriddes ELdestination::fillPrefix )
312 //======================================================================
313 void ELUDP::fillPrefix(std::ostringstream& oss, const ErrorObj& msg)
314 {
315  const auto& xid = msg.xid();
316 
317  auto id = xid.id();
318  auto module = xid.module();
319  auto app = app_;
320  std::replace(id.begin(), id.end(), '|', '!');
321  std::replace(app.begin(), app.end(), '|', '!');
322  std::replace(module.begin(), module.end(), '|', '!');
323 
324  oss << format_.timestamp(msg.timestamp()) << "|"; // timestamp
325  oss << std::to_string(++seqNum_) << "|"; // sequence number
326  oss << hostname_ << "|"; // host name
327  oss << hostaddr_ << "|"; // host address
328  oss << xid.severity().getName() << "|"; // severity
329  oss << id << "|"; // category
330  oss << app << "|"; // application
331  oss << pid_ << "|";
332  oss << mf::GetIteration() << "|"; // run/event no
333 
334  oss << module << "|"; // module name
335  if (filename_delimit_.empty())
336  {
337  oss << msg.filename();
338  }
339  else if (filename_delimit_.size() == 1) // for a single character (i.e '/'), search in reverse.
340  {
341  oss << (strrchr(&msg.filename()[0], filename_delimit_[0]) != nullptr // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
342  ? strrchr(&msg.filename()[0], filename_delimit_[0]) + 1 // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
343  : msg.filename());
344  }
345  else
346  {
347  const char* cp = strstr(&msg.filename()[0], &filename_delimit_[0]); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
348  if (cp != nullptr)
349  {
350  // make sure to remove a part that ends with '/'
351  cp += filename_delimit_.size() - 1; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
352  while (*cp && *cp != '/') ++cp;
353  ++cp; // increment past '/'
354  oss << cp;
355  }
356  else
357  oss << msg.filename();
358  }
359  oss << "|" << std::to_string(msg.lineNumber()) << "|";
360 }
361 
362 //======================================================================
363 // Message filler ( overriddes ELdestination::fillUsrMsg )
364 //======================================================================
365 void ELUDP::fillUsrMsg(std::ostringstream& oss, const ErrorObj& msg)
366 {
367  std::ostringstream tmposs;
368  // Print the contents.
369  for (auto const& val : msg.items())
370  {
371  tmposs << val;
372  }
373 
374  // remove leading "\n" if present
375  const std::string& usrMsg = tmposs.str().compare(0, 1, "\n") == 0 ? tmposs.str().erase(0, 1) : tmposs.str();
376 
377  oss << usrMsg;
378 }
379 
380 //======================================================================
381 // Message router ( overriddes ELdestination::routePayload )
382 //======================================================================
383 void ELUDP::routePayload(const std::ostringstream& oss, const ErrorObj& /*msg*/)
384 {
385  if (message_socket_ == -1)
386  {
387  reconnect_();
388  }
389  if (error_count_ < error_max_ || error_max_ == 0)
390  {
391  char str[INET_ADDRSTRLEN];
392  inet_ntop(AF_INET, &(message_addr_.sin_addr), str, INET_ADDRSTRLEN);
393 
394  auto string = "UDPMFMESSAGE" + std::to_string(pid_) + "|" + oss.str();
395  auto sts = sendto(message_socket_, string.c_str(), string.size(), 0, reinterpret_cast<struct sockaddr*>(&message_addr_), // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
396  sizeof(message_addr_));
397 
398  if (sts < 0)
399  {
400  consecutive_success_count_ = 0;
401  ++error_count_;
402  if (error_count_ == next_error_report_)
403  {
404  TLOG(TLVL_ERROR) << "Error sending message " << seqNum_ << " to " << host_ << ", errno=" << errno << " ("
405  << strerror(errno) << ")";
406  next_error_report_ *= error_report_backoff_factor_;
407  }
408  }
409  else
410  {
411  ++consecutive_success_count_;
412  if (consecutive_success_count_ >= 5)
413  {
414  error_count_ = 0;
415  next_error_report_ = 1;
416  }
417  }
418  }
419 }
420 } // end namespace mfplugins
421 
422 //======================================================================
423 //
424 // makePlugin function
425 //
426 //======================================================================
427 
428 #ifndef EXTERN_C_FUNC_DECLARE_START
429 #define EXTERN_C_FUNC_DECLARE_START extern "C" {
430 #endif
431 
432 EXTERN_C_FUNC_DECLARE_START
433 auto makePlugin(const std::string& /*unused*/, const fhicl::ParameterSet& pset)
434 {
435  return std::make_unique<mfplugins::ELUDP>(pset);
436 }
437 }
438 
439 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:36
void fillPrefix(std::ostringstream &o, const ErrorObj &msg) override
Fill the &quot;Prefix&quot; portion of the message.
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:52
fhicl::Atom< int > port
&quot;port&quot; (Default: 5140): Port to send messages to
Definition: UDP_mfPlugin.cc:58
fhicl::Atom< std::string > host
&quot;host&quot; (Default: &quot;227.128.12.27&quot;): Address to send messages to
Definition: UDP_mfPlugin.cc:55
fhicl::Atom< std::string > output_address
Definition: UDP_mfPlugin.cc:64
Configuration Parameters for ELUDP.
Definition: UDP_mfPlugin.cc:42
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:73
fhicl::Atom< int > error_max
Definition: UDP_mfPlugin.cc:48
fhicl::TableFragment< ELdestination::Config > elDestConfig
ELDestination common config parameters.
Definition: UDP_mfPlugin.cc:45
void fillUsrMsg(std::ostringstream &o, const ErrorObj &msg) override
Fill the &quot;User Message&quot; portion of the message.
fhicl::Atom< std::string > filename_delimit
filename_delimit (Default: &quot;/&quot;): Grab path after this. &quot;/srcs/&quot; /x/srcs/y/z.cc =&gt; y/z...
Definition: UDP_mfPlugin.cc:68
void fillSuffix(std::ostringstream &, const ErrorObj &) override
Fill the &quot;Suffix&quot; portion of the message (Unused)
Definition: UDP_mfPlugin.cc:99
fhicl::Atom< bool > multicast_enabled
&quot;multicast_enabled&quot; (Default: false): Whether messages should be sent via multicast ...
Definition: UDP_mfPlugin.cc:60