1 #include "cetlib/PluginTypeDeducer.h"
2 #include "fhiclcpp/ParameterSet.h"
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"
9 #include "messagefacility/MessageLogger/MessageLogger.h"
11 #include "cetlib/compiler_macros.h"
12 #include "messagefacility/Utilities/exception.h"
15 #include <arpa/inet.h>
18 #include <netinet/in.h>
25 #define TRACE_NAME "UDP_mfPlugin"
29 #include <boost/algorithm/string.hpp>
31 #if MESSAGEFACILITY_HEX_VERSION < 0x20201 // format changed to format_ for s67
32 #define format_ format
36 using mf::ELseverityLevel;
38 using mf::service::ELdestination;
44 class ELUDP :
public ELdestination
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};
69 fhicl::Name{
"multicast_enabled"}, fhicl::Comment{
"Whether messages should be sent via multicast"},
false};
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"};
91 virtual void fillPrefix(std::ostringstream& o,
const ErrorObj& e)
override;
98 virtual void fillUsrMsg(std::ostringstream& o,
const ErrorObj& e)
override;
103 virtual void fillSuffix(std::ostringstream&,
const ErrorObj&)
override {}
110 virtual void routePayload(
const std::ostringstream& o,
const ErrorObj& e)
override;
116 int error_report_backoff_factor_;
120 bool multicast_enabled_;
121 std::string multicast_out_addr_;
124 struct sockaddr_in message_addr_;
127 int consecutive_success_count_;
129 int next_error_report_;
133 std::string hostname_;
134 std::string hostaddr_;
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()))
150 char hostname_c[1024];
151 hostname_ = (gethostname(hostname_c, 1023) == 0) ? hostname_c :
"Unkonwn Host";
154 hostent* host =
nullptr;
155 host = gethostbyname(hostname_c);
160 char* ip = inet_ntoa(*(
struct in_addr*)host->h_addr);
166 struct ifaddrs* ifAddrStruct =
nullptr;
167 struct ifaddrs* ifa =
nullptr;
168 void* tmpAddrPtr =
nullptr;
170 if (getifaddrs(&ifAddrStruct))
173 hostaddr_ =
"127.0.0.1";
178 for (ifa = ifAddrStruct; ifa !=
nullptr; ifa = ifa->ifa_next)
180 if (ifa->ifa_addr->sa_family == AF_INET)
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;
189 else if (ifa->ifa_addr->sa_family == AF_INET6)
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;
199 if (!hostaddr_.empty() && hostaddr_.compare(
"127.0.0.1") && hostaddr_.compare(
"::1"))
break;
202 if (hostaddr_.empty())
203 hostaddr_ =
"127.0.0.1";
210 std::ostringstream pid_ostr;
211 pid_ostr <<
"/proc/" << pid_ <<
"/exe";
212 exe = realpath(pid_ostr.str().c_str(), NULL);
214 size_t end = exe.find(
'\0');
215 size_t start = exe.find_last_of(
'/', end);
217 app_ = exe.substr(start + 1, end - start - 1);
220 std::stringstream ss;
221 ss <<
"//proc//" << pid_ <<
"//cmdline";
222 std::ifstream procfile{ss.str().c_str()};
224 std::string procinfo;
226 if (procfile.is_open())
228 procfile >> procinfo;
232 size_t end = procinfo.find(
'\0');
233 size_t start = procinfo.find_last_of(
'/', end);
235 app_ = procinfo.substr(start + 1, end - start - 1);
239 void ELUDP::reconnect_()
241 message_socket_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
242 if (message_socket_ < 0)
244 TLOG(TLVL_ERROR) <<
"I failed to create the socket for sending Data messages! err=" << strerror(errno);
247 int sts =
ResolveHost(host_.c_str(), port_, message_addr_);
250 TLOG(TLVL_ERROR) <<
"Unable to resolve Data message address, err=" << strerror(errno);
254 if (multicast_out_addr_ ==
"0.0.0.0")
256 multicast_out_addr_.reserve(HOST_NAME_MAX);
257 sts = gethostname(&multicast_out_addr_[0], HOST_NAME_MAX);
260 TLOG(TLVL_ERROR) <<
"Could not get current hostname, err=" << strerror(errno);
265 if (multicast_out_addr_ !=
"localhost")
272 TLOG(TLVL_ERROR) <<
"Unable to resolve multicast interface address, err=" << strerror(errno);
276 if (setsockopt(message_socket_, IPPROTO_IP, IP_MULTICAST_IF, &addr,
sizeof(addr)) == -1)
278 TLOG(TLVL_ERROR) <<
"Cannot set outgoing interface, err=" << strerror(errno);
283 if (setsockopt(message_socket_, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(yes)) < 0)
285 TLOG(TLVL_ERROR) <<
"Unable to enable port reuse on message socket, err=" << strerror(errno);
288 if (setsockopt(message_socket_, IPPROTO_IP, IP_MULTICAST_LOOP, &yes,
sizeof(yes)) < 0)
290 TLOG(TLVL_ERROR) <<
"Unable to enable multicast loopback on message socket, err=" << strerror(errno);
293 if (setsockopt(message_socket_, SOL_SOCKET, SO_BROADCAST, (
void*)&yes,
sizeof(
int)) == -1)
295 TLOG(TLVL_ERROR) <<
"Cannot set message socket to broadcast, err=" << strerror(errno);
305 const auto& xid = msg.xid();
308 auto module = xid.module();
310 std::replace(
id.begin(),
id.end(),
'|',
'!');
311 std::replace(app.begin(), app.end(),
'|',
'!');
312 std::replace(module.begin(), module.end(),
'|',
'!');
314 oss << format_.timestamp(msg.timestamp()) <<
"|";
315 oss << std::to_string(++seqNum_) <<
"|";
316 oss << hostname_ <<
"|";
317 oss << hostaddr_ <<
"|";
318 oss << xid.severity().getName() <<
"|";
321 #if MESSAGEFACILITY_HEX_VERSION >= 0x20201 // an indication of s67
323 oss << mf::GetIteration() <<
"|";
326 oss << mf::MessageDrop::instance()->iteration <<
"|";
328 oss << module <<
"|";
329 #if MESSAGEFACILITY_HEX_VERSION >= 0x20201
330 oss << msg.filename() <<
"|" << std::to_string(msg.lineNumber()) <<
"|";
339 std::ostringstream tmposs;
341 for (
auto const& val : msg.items())
347 const std::string& usrMsg = !tmposs.str().compare(0, 1,
"\n") ? tmposs.str().erase(0, 1) : tmposs.str();
357 if (message_socket_ == -1) reconnect_();
358 if (error_count_ < error_max_ || error_max_ == 0)
360 char str[INET_ADDRSTRLEN];
361 inet_ntop(AF_INET, &(message_addr_.sin_addr), str, INET_ADDRSTRLEN);
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_));
369 consecutive_success_count_ = 0;
371 if (error_count_ == next_error_report_)
373 TLOG(TLVL_ERROR) <<
"Error sending message " << seqNum_ <<
" to " << host_ <<
", errno=" << errno <<
" ("
374 << strerror(errno) <<
")";
375 next_error_report_ *= error_report_backoff_factor_;
380 ++consecutive_success_count_;
381 if (consecutive_success_count_ >= 5)
384 next_error_report_ = 1;
397 #ifndef EXTERN_C_FUNC_DECLARE_START
398 #define EXTERN_C_FUNC_DECLARE_START extern "C" {
401 EXTERN_C_FUNC_DECLARE_START
402 auto makePlugin(
const std::string&,
const fhicl::ParameterSet& pset)
404 return std::make_unique<mfplugins::ELUDP>(pset);
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.
Message Facility UDP Streamer Destination Formats messages into a delimited string and sends via UDP ...
int GetInterfaceForNetwork(char const *host_in, in_addr &addr)
Convert an IP address to the network address of the interface sharing the subnet mask.
fhicl::Atom< int > error_report
"error_report_backoff_factor" (Default: 100): Print an error message every N errors ...
fhicl::Atom< int > port
"port" (Default: 5140): Port to send messages to
fhicl::Atom< std::string > host
"host" (Default: "227.128.12.27"): Address to send messages to
fhicl::Atom< std::string > output_address
Configuration Parameters for ELUDP.
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.
fhicl::Atom< int > error_max
virtual void fillUsrMsg(std::ostringstream &o, const ErrorObj &e) override
Fill the "User Message" portion of the message.
virtual void fillPrefix(std::ostringstream &o, const ErrorObj &e) override
Fill the "Prefix" portion of the message.
fhicl::TableFragment< ELdestination::Config > elDestConfig
ELDestination common config parameters.
virtual void fillSuffix(std::ostringstream &, const ErrorObj &) override
Fill the "Suffix" portion of the message (Unused)
fhicl::Atom< bool > multicast_enabled
"multicast_enabled" (Default: false): Whether messages should be sent via multicast ...