xref: /openbmc/bmcweb/features/redfish/include/event_service_manager.hpp (revision d14a48ff5e539633f2e3180525f3779f90ad3e78)
1 /*
2 // Copyright (c) 2020 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 #pragma once
17 #include "dbus_utility.hpp"
18 #include "error_messages.hpp"
19 #include "event_service_store.hpp"
20 #include "http_client.hpp"
21 #include "metric_report.hpp"
22 #include "persistent_data.hpp"
23 #include "random.hpp"
24 #include "registries.hpp"
25 #include "registries/base_message_registry.hpp"
26 #include "registries/openbmc_message_registry.hpp"
27 #include "registries/task_event_message_registry.hpp"
28 #include "server_sent_events.hpp"
29 #include "str_utility.hpp"
30 #include "utility.hpp"
31 #include "utils/json_utils.hpp"
32 
33 #include <sys/inotify.h>
34 
35 #include <boost/algorithm/string/classification.hpp>
36 #include <boost/asio/io_context.hpp>
37 #include <boost/container/flat_map.hpp>
38 #include <sdbusplus/bus/match.hpp>
39 
40 #include <cstdlib>
41 #include <ctime>
42 #include <fstream>
43 #include <memory>
44 #include <span>
45 
46 namespace redfish
47 {
48 
49 using ReadingsObjType =
50     std::vector<std::tuple<std::string, std::string, double, int32_t>>;
51 
52 static constexpr const char* eventFormatType = "Event";
53 static constexpr const char* metricReportFormatType = "MetricReport";
54 
55 static constexpr const char* eventServiceFile =
56     "/var/lib/bmcweb/eventservice_config.json";
57 
58 namespace registries
59 {
60 inline std::span<const MessageEntry>
61     getRegistryFromPrefix(const std::string& registryName)
62 {
63     if (task_event::header.registryPrefix == registryName)
64     {
65         return {task_event::registry};
66     }
67     if (openbmc::header.registryPrefix == registryName)
68     {
69         return {openbmc::registry};
70     }
71     if (base::header.registryPrefix == registryName)
72     {
73         return {base::registry};
74     }
75     return {openbmc::registry};
76 }
77 } // namespace registries
78 
79 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
80 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
81 static std::optional<boost::asio::posix::stream_descriptor> inotifyConn;
82 static constexpr const char* redfishEventLogDir = "/var/log";
83 static constexpr const char* redfishEventLogFile = "/var/log/redfish";
84 static constexpr const size_t iEventSize = sizeof(inotify_event);
85 
86 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
87 static int inotifyFd = -1;
88 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
89 static int dirWatchDesc = -1;
90 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
91 static int fileWatchDesc = -1;
92 
93 // <ID, timestamp, RedfishLogId, registryPrefix, MessageId, MessageArgs>
94 using EventLogObjectsType =
95     std::tuple<std::string, std::string, std::string, std::string, std::string,
96                std::vector<std::string>>;
97 
98 namespace registries
99 {
100 static const Message*
101     getMsgFromRegistry(const std::string& messageKey,
102                        const std::span<const MessageEntry>& registry)
103 {
104     std::span<const MessageEntry>::iterator messageIt =
105         std::find_if(registry.begin(), registry.end(),
106                      [&messageKey](const MessageEntry& messageEntry) {
107         return messageKey == messageEntry.first;
108         });
109     if (messageIt != registry.end())
110     {
111         return &messageIt->second;
112     }
113 
114     return nullptr;
115 }
116 
117 static const Message* formatMessage(std::string_view messageID)
118 {
119     // Redfish MessageIds are in the form
120     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
121     // the right Message
122     std::vector<std::string> fields;
123     fields.reserve(4);
124 
125     bmcweb::split(fields, messageID, '.');
126     if (fields.size() != 4)
127     {
128         return nullptr;
129     }
130     const std::string& registryName = fields[0];
131     const std::string& messageKey = fields[3];
132 
133     // Find the right registry and check it for the MessageKey
134     return getMsgFromRegistry(messageKey, getRegistryFromPrefix(registryName));
135 }
136 } // namespace registries
137 
138 namespace event_log
139 {
140 inline bool getUniqueEntryID(const std::string& logEntry, std::string& entryID)
141 {
142     static time_t prevTs = 0;
143     static int index = 0;
144 
145     // Get the entry timestamp
146     std::time_t curTs = 0;
147     std::tm timeStruct = {};
148     std::istringstream entryStream(logEntry);
149     if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
150     {
151         curTs = std::mktime(&timeStruct);
152         if (curTs == -1)
153         {
154             return false;
155         }
156     }
157     // If the timestamp isn't unique, increment the index
158     index = (curTs == prevTs) ? index + 1 : 0;
159 
160     // Save the timestamp
161     prevTs = curTs;
162 
163     entryID = std::to_string(curTs);
164     if (index > 0)
165     {
166         entryID += "_" + std::to_string(index);
167     }
168     return true;
169 }
170 
171 inline int getEventLogParams(const std::string& logEntry,
172                              std::string& timestamp, std::string& messageID,
173                              std::vector<std::string>& messageArgs)
174 {
175     // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
176     // First get the Timestamp
177     size_t space = logEntry.find_first_of(' ');
178     if (space == std::string::npos)
179     {
180         return -EINVAL;
181     }
182     timestamp = logEntry.substr(0, space);
183     // Then get the log contents
184     size_t entryStart = logEntry.find_first_not_of(' ', space);
185     if (entryStart == std::string::npos)
186     {
187         return -EINVAL;
188     }
189     std::string_view entry(logEntry);
190     entry.remove_prefix(entryStart);
191     // Use split to separate the entry into its fields
192     std::vector<std::string> logEntryFields;
193     bmcweb::split(logEntryFields, entry, ',');
194     // We need at least a MessageId to be valid
195     if (logEntryFields.empty())
196     {
197         return -EINVAL;
198     }
199     messageID = logEntryFields[0];
200 
201     // Get the MessageArgs from the log if there are any
202     if (logEntryFields.size() > 1)
203     {
204         const std::string& messageArgsStart = logEntryFields[1];
205         // If the first string is empty, assume there are no MessageArgs
206         if (!messageArgsStart.empty())
207         {
208             messageArgs.assign(logEntryFields.begin() + 1,
209                                logEntryFields.end());
210         }
211     }
212 
213     return 0;
214 }
215 
216 inline void getRegistryAndMessageKey(const std::string& messageID,
217                                      std::string& registryName,
218                                      std::string& messageKey)
219 {
220     // Redfish MessageIds are in the form
221     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
222     // the right Message
223     std::vector<std::string> fields;
224     fields.reserve(4);
225     bmcweb::split(fields, messageID, '.');
226     if (fields.size() == 4)
227     {
228         registryName = fields[0];
229         messageKey = fields[3];
230     }
231 }
232 
233 inline int formatEventLogEntry(const std::string& logEntryID,
234                                const std::string& messageID,
235                                const std::span<std::string_view> messageArgs,
236                                std::string timestamp,
237                                const std::string& customText,
238                                nlohmann::json& logEntryJson)
239 {
240     // Get the Message from the MessageRegistry
241     const registries::Message* message = registries::formatMessage(messageID);
242 
243     if (message == nullptr)
244     {
245         return -1;
246     }
247 
248     std::string msg =
249         redfish::registries::fillMessageArgs(messageArgs, message->message);
250     if (msg.empty())
251     {
252         return -1;
253     }
254 
255     // Get the Created time from the timestamp. The log timestamp is in
256     // RFC3339 format which matches the Redfish format except for the
257     // fractional seconds between the '.' and the '+', so just remove them.
258     std::size_t dot = timestamp.find_first_of('.');
259     std::size_t plus = timestamp.find_first_of('+', dot);
260     if (dot != std::string::npos && plus != std::string::npos)
261     {
262         timestamp.erase(dot, plus - dot);
263     }
264 
265     // Fill in the log entry with the gathered data
266     logEntryJson["EventId"] = logEntryID;
267     logEntryJson["EventType"] = "Event";
268     logEntryJson["Severity"] = message->messageSeverity;
269     logEntryJson["Message"] = std::move(msg);
270     logEntryJson["MessageId"] = messageID;
271     logEntryJson["MessageArgs"] = messageArgs;
272     logEntryJson["EventTimestamp"] = std::move(timestamp);
273     logEntryJson["Context"] = customText;
274     return 0;
275 }
276 
277 } // namespace event_log
278 #endif
279 
280 inline bool isFilterQuerySpecialChar(char c)
281 {
282     switch (c)
283     {
284         case '(':
285         case ')':
286         case '\'':
287             return true;
288         default:
289             return false;
290     }
291 }
292 
293 inline bool
294     readSSEQueryParams(std::string sseFilter, std::string& formatType,
295                        std::vector<std::string>& messageIds,
296                        std::vector<std::string>& registryPrefixes,
297                        std::vector<std::string>& metricReportDefinitions)
298 {
299     sseFilter.erase(std::remove_if(sseFilter.begin(), sseFilter.end(),
300                                    isFilterQuerySpecialChar),
301                     sseFilter.end());
302 
303     std::vector<std::string> result;
304 
305     // NOLINTNEXTLINE
306     bmcweb::split(result, sseFilter, ' ');
307 
308     BMCWEB_LOG_DEBUG << "No of tokens in SEE query: " << result.size();
309 
310     constexpr uint8_t divisor = 4;
311     constexpr uint8_t minTokenSize = 3;
312     if (result.size() % divisor != minTokenSize)
313     {
314         BMCWEB_LOG_ERROR << "Invalid SSE filter specified.";
315         return false;
316     }
317 
318     for (std::size_t i = 0; i < result.size(); i += divisor)
319     {
320         const std::string& key = result[i];
321         const std::string& op = result[i + 1];
322         const std::string& value = result[i + 2];
323 
324         if ((i + minTokenSize) < result.size())
325         {
326             const std::string& separator = result[i + minTokenSize];
327             // SSE supports only "or" and "and" in query params.
328             if ((separator != "or") && (separator != "and"))
329             {
330                 BMCWEB_LOG_ERROR
331                     << "Invalid group operator in SSE query parameters";
332                 return false;
333             }
334         }
335 
336         // SSE supports only "eq" as per spec.
337         if (op != "eq")
338         {
339             BMCWEB_LOG_ERROR
340                 << "Invalid assignment operator in SSE query parameters";
341             return false;
342         }
343 
344         BMCWEB_LOG_DEBUG << key << " : " << value;
345         if (key == "EventFormatType")
346         {
347             formatType = value;
348         }
349         else if (key == "MessageId")
350         {
351             messageIds.push_back(value);
352         }
353         else if (key == "RegistryPrefix")
354         {
355             registryPrefixes.push_back(value);
356         }
357         else if (key == "MetricReportDefinition")
358         {
359             metricReportDefinitions.push_back(value);
360         }
361         else
362         {
363             BMCWEB_LOG_ERROR << "Invalid property(" << key
364                              << ")in SSE filter query.";
365             return false;
366         }
367     }
368     return true;
369 }
370 
371 class Subscription : public persistent_data::UserSubscription
372 {
373   public:
374     Subscription(const Subscription&) = delete;
375     Subscription& operator=(const Subscription&) = delete;
376     Subscription(Subscription&&) = delete;
377     Subscription& operator=(Subscription&&) = delete;
378 
379     Subscription(const std::string& inHost, uint16_t inPort,
380                  const std::string& inPath, const std::string& inUriProto) :
381         host(inHost),
382         port(inPort), policy(std::make_shared<crow::ConnectionPolicy>()),
383         client(policy), path(inPath), uriProto(inUriProto)
384     {
385         // Subscription constructor
386         policy->invalidResp = retryRespHandler;
387     }
388 
389     explicit Subscription(
390         const std::shared_ptr<boost::asio::ip::tcp::socket>& adaptor) :
391         policy(std::make_shared<crow::ConnectionPolicy>()),
392         client(policy),
393         sseConn(std::make_shared<crow::ServerSentEvents>(adaptor))
394     {}
395 
396     ~Subscription() = default;
397 
398     bool sendEvent(std::string& msg)
399     {
400         persistent_data::EventServiceConfig eventServiceConfig =
401             persistent_data::EventServiceStore::getInstance()
402                 .getEventServiceConfig();
403         if (!eventServiceConfig.enabled)
404         {
405             return false;
406         }
407 
408         bool useSSL = (uriProto == "https");
409         // A connection pool will be created if one does not already exist
410         client.sendData(msg, host, port, path, useSSL, httpHeaders,
411                         boost::beast::http::verb::post);
412         eventSeqNum++;
413 
414         if (sseConn != nullptr)
415         {
416             sseConn->sendData(eventSeqNum, msg);
417         }
418         return true;
419     }
420 
421     bool sendTestEventLog()
422     {
423         nlohmann::json logEntryArray;
424         logEntryArray.push_back({});
425         nlohmann::json& logEntryJson = logEntryArray.back();
426 
427         logEntryJson["EventId"] = "TestID";
428         logEntryJson["EventType"] = "Event";
429         logEntryJson["Severity"] = "OK";
430         logEntryJson["Message"] = "Generated test event";
431         logEntryJson["MessageId"] = "OpenBMC.0.2.TestEventLog";
432         logEntryJson["MessageArgs"] = nlohmann::json::array();
433         logEntryJson["EventTimestamp"] =
434             redfish::time_utils::getDateTimeOffsetNow().first;
435         logEntryJson["Context"] = customText;
436 
437         nlohmann::json msg;
438         msg["@odata.type"] = "#Event.v1_4_0.Event";
439         msg["Id"] = std::to_string(eventSeqNum);
440         msg["Name"] = "Event Log";
441         msg["Events"] = logEntryArray;
442 
443         std::string strMsg =
444             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace);
445         return this->sendEvent(strMsg);
446     }
447 
448 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
449     void filterAndSendEventLogs(
450         const std::vector<EventLogObjectsType>& eventRecords)
451     {
452         nlohmann::json logEntryArray;
453         for (const EventLogObjectsType& logEntry : eventRecords)
454         {
455             const std::string& idStr = std::get<0>(logEntry);
456             const std::string& timestamp = std::get<1>(logEntry);
457             const std::string& messageID = std::get<2>(logEntry);
458             const std::string& registryName = std::get<3>(logEntry);
459             const std::string& messageKey = std::get<4>(logEntry);
460             const std::vector<std::string>& messageArgs = std::get<5>(logEntry);
461 
462             // If registryPrefixes list is empty, don't filter events
463             // send everything.
464             if (!registryPrefixes.empty())
465             {
466                 auto obj = std::find(registryPrefixes.begin(),
467                                      registryPrefixes.end(), registryName);
468                 if (obj == registryPrefixes.end())
469                 {
470                     continue;
471                 }
472             }
473 
474             // If registryMsgIds list is empty, don't filter events
475             // send everything.
476             if (!registryMsgIds.empty())
477             {
478                 auto obj = std::find(registryMsgIds.begin(),
479                                      registryMsgIds.end(), messageKey);
480                 if (obj == registryMsgIds.end())
481                 {
482                     continue;
483                 }
484             }
485 
486             std::vector<std::string_view> messageArgsView(messageArgs.begin(),
487                                                           messageArgs.end());
488 
489             logEntryArray.push_back({});
490             nlohmann::json& bmcLogEntry = logEntryArray.back();
491             if (event_log::formatEventLogEntry(idStr, messageID,
492                                                messageArgsView, timestamp,
493                                                customText, bmcLogEntry) != 0)
494             {
495                 BMCWEB_LOG_DEBUG << "Read eventLog entry failed";
496                 continue;
497             }
498         }
499 
500         if (logEntryArray.empty())
501         {
502             BMCWEB_LOG_DEBUG << "No log entries available to be transferred.";
503             return;
504         }
505 
506         nlohmann::json msg;
507         msg["@odata.type"] = "#Event.v1_4_0.Event";
508         msg["Id"] = std::to_string(eventSeqNum);
509         msg["Name"] = "Event Log";
510         msg["Events"] = logEntryArray;
511 
512         std::string strMsg =
513             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace);
514         this->sendEvent(strMsg);
515     }
516 #endif
517 
518     void filterAndSendReports(const std::string& reportId,
519                               const telemetry::TimestampReadings& var)
520     {
521         boost::urls::url mrdUri =
522             crow::utility::urlFromPieces("redfish", "v1", "TelemetryService",
523                                          "MetricReportDefinitions", reportId);
524 
525         // Empty list means no filter. Send everything.
526         if (!metricReportDefinitions.empty())
527         {
528             if (std::find(metricReportDefinitions.begin(),
529                           metricReportDefinitions.end(),
530                           mrdUri.buffer()) == metricReportDefinitions.end())
531             {
532                 return;
533             }
534         }
535 
536         nlohmann::json msg;
537         if (!telemetry::fillReport(msg, reportId, var))
538         {
539             BMCWEB_LOG_ERROR << "Failed to fill the MetricReport for DBus "
540                                 "Report with id "
541                              << reportId;
542             return;
543         }
544 
545         // Context is set by user during Event subscription and it must be
546         // set for MetricReport response.
547         if (!customText.empty())
548         {
549             msg["Context"] = customText;
550         }
551 
552         std::string strMsg =
553             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace);
554         this->sendEvent(strMsg);
555     }
556 
557     void updateRetryConfig(uint32_t retryAttempts,
558                            uint32_t retryTimeoutInterval)
559     {
560         policy->maxRetryAttempts = retryAttempts;
561         policy->retryIntervalSecs = std::chrono::seconds(retryTimeoutInterval);
562     }
563 
564     uint64_t getEventSeqNum() const
565     {
566         return eventSeqNum;
567     }
568 
569   private:
570     uint64_t eventSeqNum = 1;
571     std::string host;
572     uint16_t port = 0;
573     std::shared_ptr<crow::ConnectionPolicy> policy;
574     crow::HttpClient client;
575     std::string path;
576     std::string uriProto;
577     std::shared_ptr<crow::ServerSentEvents> sseConn = nullptr;
578 
579     // Check used to indicate what response codes are valid as part of our retry
580     // policy.  2XX is considered acceptable
581     static boost::system::error_code retryRespHandler(unsigned int respCode)
582     {
583         BMCWEB_LOG_DEBUG
584             << "Checking response code validity for SubscriptionEvent";
585         if ((respCode < 200) || (respCode >= 300))
586         {
587             return boost::system::errc::make_error_code(
588                 boost::system::errc::result_out_of_range);
589         }
590 
591         // Return 0 if the response code is valid
592         return boost::system::errc::make_error_code(
593             boost::system::errc::success);
594     }
595 };
596 
597 class EventServiceManager
598 {
599   private:
600     bool serviceEnabled = false;
601     uint32_t retryAttempts = 0;
602     uint32_t retryTimeoutInterval = 0;
603 
604     EventServiceManager()
605     {
606         // Load config from persist store.
607         initConfig();
608     }
609 
610     std::streampos redfishLogFilePosition{0};
611     size_t noOfEventLogSubscribers{0};
612     size_t noOfMetricReportSubscribers{0};
613     std::shared_ptr<sdbusplus::bus::match_t> matchTelemetryMonitor;
614     boost::container::flat_map<std::string, std::shared_ptr<Subscription>>
615         subscriptionsMap;
616 
617     uint64_t eventId{1};
618 
619   public:
620     EventServiceManager(const EventServiceManager&) = delete;
621     EventServiceManager& operator=(const EventServiceManager&) = delete;
622     EventServiceManager(EventServiceManager&&) = delete;
623     EventServiceManager& operator=(EventServiceManager&&) = delete;
624     ~EventServiceManager() = default;
625 
626     static EventServiceManager& getInstance()
627     {
628         static EventServiceManager handler;
629         return handler;
630     }
631 
632     void initConfig()
633     {
634         loadOldBehavior();
635 
636         persistent_data::EventServiceConfig eventServiceConfig =
637             persistent_data::EventServiceStore::getInstance()
638                 .getEventServiceConfig();
639 
640         serviceEnabled = eventServiceConfig.enabled;
641         retryAttempts = eventServiceConfig.retryAttempts;
642         retryTimeoutInterval = eventServiceConfig.retryTimeoutInterval;
643 
644         for (const auto& it : persistent_data::EventServiceStore::getInstance()
645                                   .subscriptionsConfigMap)
646         {
647             std::shared_ptr<persistent_data::UserSubscription> newSub =
648                 it.second;
649 
650             std::string host;
651             std::string urlProto;
652             uint16_t port = 0;
653             std::string path;
654             bool status = crow::utility::validateAndSplitUrl(
655                 newSub->destinationUrl, urlProto, host, port, path);
656 
657             if (!status)
658             {
659                 BMCWEB_LOG_ERROR
660                     << "Failed to validate and split destination url";
661                 continue;
662             }
663             std::shared_ptr<Subscription> subValue =
664                 std::make_shared<Subscription>(host, port, path, urlProto);
665 
666             subValue->id = newSub->id;
667             subValue->destinationUrl = newSub->destinationUrl;
668             subValue->protocol = newSub->protocol;
669             subValue->retryPolicy = newSub->retryPolicy;
670             subValue->customText = newSub->customText;
671             subValue->eventFormatType = newSub->eventFormatType;
672             subValue->subscriptionType = newSub->subscriptionType;
673             subValue->registryMsgIds = newSub->registryMsgIds;
674             subValue->registryPrefixes = newSub->registryPrefixes;
675             subValue->resourceTypes = newSub->resourceTypes;
676             subValue->httpHeaders = newSub->httpHeaders;
677             subValue->metricReportDefinitions = newSub->metricReportDefinitions;
678 
679             if (subValue->id.empty())
680             {
681                 BMCWEB_LOG_ERROR << "Failed to add subscription";
682             }
683             subscriptionsMap.insert(std::pair(subValue->id, subValue));
684 
685             updateNoOfSubscribersCount();
686 
687 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
688 
689             cacheRedfishLogFile();
690 
691 #endif
692             // Update retry configuration.
693             subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
694         }
695     }
696 
697     static void loadOldBehavior()
698     {
699         std::ifstream eventConfigFile(eventServiceFile);
700         if (!eventConfigFile.good())
701         {
702             BMCWEB_LOG_DEBUG << "Old eventService config not exist";
703             return;
704         }
705         auto jsonData = nlohmann::json::parse(eventConfigFile, nullptr, false);
706         if (jsonData.is_discarded())
707         {
708             BMCWEB_LOG_ERROR << "Old eventService config parse error.";
709             return;
710         }
711 
712         for (const auto& item : jsonData.items())
713         {
714             if (item.key() == "Configuration")
715             {
716                 persistent_data::EventServiceStore::getInstance()
717                     .getEventServiceConfig()
718                     .fromJson(item.value());
719             }
720             else if (item.key() == "Subscriptions")
721             {
722                 for (const auto& elem : item.value())
723                 {
724                     std::shared_ptr<persistent_data::UserSubscription>
725                         newSubscription =
726                             persistent_data::UserSubscription::fromJson(elem,
727                                                                         true);
728                     if (newSubscription == nullptr)
729                     {
730                         BMCWEB_LOG_ERROR << "Problem reading subscription "
731                                             "from old persistent store";
732                         continue;
733                     }
734 
735                     std::uniform_int_distribution<uint32_t> dist(0);
736                     bmcweb::OpenSSLGenerator gen;
737 
738                     std::string id;
739 
740                     int retry = 3;
741                     while (retry != 0)
742                     {
743                         id = std::to_string(dist(gen));
744                         if (gen.error())
745                         {
746                             retry = 0;
747                             break;
748                         }
749                         newSubscription->id = id;
750                         auto inserted =
751                             persistent_data::EventServiceStore::getInstance()
752                                 .subscriptionsConfigMap.insert(
753                                     std::pair(id, newSubscription));
754                         if (inserted.second)
755                         {
756                             break;
757                         }
758                         --retry;
759                     }
760 
761                     if (retry <= 0)
762                     {
763                         BMCWEB_LOG_ERROR
764                             << "Failed to generate random number from old "
765                                "persistent store";
766                         continue;
767                     }
768                 }
769             }
770 
771             persistent_data::getConfig().writeData();
772             std::remove(eventServiceFile);
773             BMCWEB_LOG_DEBUG << "Remove old eventservice config";
774         }
775     }
776 
777     void updateSubscriptionData() const
778     {
779         persistent_data::EventServiceStore::getInstance()
780             .eventServiceConfig.enabled = serviceEnabled;
781         persistent_data::EventServiceStore::getInstance()
782             .eventServiceConfig.retryAttempts = retryAttempts;
783         persistent_data::EventServiceStore::getInstance()
784             .eventServiceConfig.retryTimeoutInterval = retryTimeoutInterval;
785 
786         persistent_data::getConfig().writeData();
787     }
788 
789     void setEventServiceConfig(const persistent_data::EventServiceConfig& cfg)
790     {
791         bool updateConfig = false;
792         bool updateRetryCfg = false;
793 
794         if (serviceEnabled != cfg.enabled)
795         {
796             serviceEnabled = cfg.enabled;
797             if (serviceEnabled && noOfMetricReportSubscribers != 0U)
798             {
799                 registerMetricReportSignal();
800             }
801             else
802             {
803                 unregisterMetricReportSignal();
804             }
805             updateConfig = true;
806         }
807 
808         if (retryAttempts != cfg.retryAttempts)
809         {
810             retryAttempts = cfg.retryAttempts;
811             updateConfig = true;
812             updateRetryCfg = true;
813         }
814 
815         if (retryTimeoutInterval != cfg.retryTimeoutInterval)
816         {
817             retryTimeoutInterval = cfg.retryTimeoutInterval;
818             updateConfig = true;
819             updateRetryCfg = true;
820         }
821 
822         if (updateConfig)
823         {
824             updateSubscriptionData();
825         }
826 
827         if (updateRetryCfg)
828         {
829             // Update the changed retry config to all subscriptions
830             for (const auto& it :
831                  EventServiceManager::getInstance().subscriptionsMap)
832             {
833                 std::shared_ptr<Subscription> entry = it.second;
834                 entry->updateRetryConfig(retryAttempts, retryTimeoutInterval);
835             }
836         }
837     }
838 
839     void updateNoOfSubscribersCount()
840     {
841         size_t eventLogSubCount = 0;
842         size_t metricReportSubCount = 0;
843         for (const auto& it : subscriptionsMap)
844         {
845             std::shared_ptr<Subscription> entry = it.second;
846             if (entry->eventFormatType == eventFormatType)
847             {
848                 eventLogSubCount++;
849             }
850             else if (entry->eventFormatType == metricReportFormatType)
851             {
852                 metricReportSubCount++;
853             }
854         }
855 
856         noOfEventLogSubscribers = eventLogSubCount;
857         if (noOfMetricReportSubscribers != metricReportSubCount)
858         {
859             noOfMetricReportSubscribers = metricReportSubCount;
860             if (noOfMetricReportSubscribers != 0U)
861             {
862                 registerMetricReportSignal();
863             }
864             else
865             {
866                 unregisterMetricReportSignal();
867             }
868         }
869     }
870 
871     std::shared_ptr<Subscription> getSubscription(const std::string& id)
872     {
873         auto obj = subscriptionsMap.find(id);
874         if (obj == subscriptionsMap.end())
875         {
876             BMCWEB_LOG_ERROR << "No subscription exist with ID:" << id;
877             return nullptr;
878         }
879         std::shared_ptr<Subscription> subValue = obj->second;
880         return subValue;
881     }
882 
883     std::string addSubscription(const std::shared_ptr<Subscription>& subValue,
884                                 const bool updateFile = true)
885     {
886 
887         std::uniform_int_distribution<uint32_t> dist(0);
888         bmcweb::OpenSSLGenerator gen;
889 
890         std::string id;
891 
892         int retry = 3;
893         while (retry != 0)
894         {
895             id = std::to_string(dist(gen));
896             if (gen.error())
897             {
898                 retry = 0;
899                 break;
900             }
901             auto inserted = subscriptionsMap.insert(std::pair(id, subValue));
902             if (inserted.second)
903             {
904                 break;
905             }
906             --retry;
907         }
908 
909         if (retry <= 0)
910         {
911             BMCWEB_LOG_ERROR << "Failed to generate random number";
912             return "";
913         }
914 
915         std::shared_ptr<persistent_data::UserSubscription> newSub =
916             std::make_shared<persistent_data::UserSubscription>();
917         newSub->id = id;
918         newSub->destinationUrl = subValue->destinationUrl;
919         newSub->protocol = subValue->protocol;
920         newSub->retryPolicy = subValue->retryPolicy;
921         newSub->customText = subValue->customText;
922         newSub->eventFormatType = subValue->eventFormatType;
923         newSub->subscriptionType = subValue->subscriptionType;
924         newSub->registryMsgIds = subValue->registryMsgIds;
925         newSub->registryPrefixes = subValue->registryPrefixes;
926         newSub->resourceTypes = subValue->resourceTypes;
927         newSub->httpHeaders = subValue->httpHeaders;
928         newSub->metricReportDefinitions = subValue->metricReportDefinitions;
929         persistent_data::EventServiceStore::getInstance()
930             .subscriptionsConfigMap.emplace(newSub->id, newSub);
931 
932         updateNoOfSubscribersCount();
933 
934         if (updateFile)
935         {
936             updateSubscriptionData();
937         }
938 
939 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
940         if (redfishLogFilePosition != 0)
941         {
942             cacheRedfishLogFile();
943         }
944 #endif
945         // Update retry configuration.
946         subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
947 
948         return id;
949     }
950 
951     bool isSubscriptionExist(const std::string& id)
952     {
953         auto obj = subscriptionsMap.find(id);
954         return obj != subscriptionsMap.end();
955     }
956 
957     void deleteSubscription(const std::string& id)
958     {
959         auto obj = subscriptionsMap.find(id);
960         if (obj != subscriptionsMap.end())
961         {
962             subscriptionsMap.erase(obj);
963             auto obj2 = persistent_data::EventServiceStore::getInstance()
964                             .subscriptionsConfigMap.find(id);
965             persistent_data::EventServiceStore::getInstance()
966                 .subscriptionsConfigMap.erase(obj2);
967             updateNoOfSubscribersCount();
968             updateSubscriptionData();
969         }
970     }
971 
972     size_t getNumberOfSubscriptions()
973     {
974         return subscriptionsMap.size();
975     }
976 
977     std::vector<std::string> getAllIDs()
978     {
979         std::vector<std::string> idList;
980         for (const auto& it : subscriptionsMap)
981         {
982             idList.emplace_back(it.first);
983         }
984         return idList;
985     }
986 
987     bool isDestinationExist(const std::string& destUrl)
988     {
989         for (const auto& it : subscriptionsMap)
990         {
991             std::shared_ptr<Subscription> entry = it.second;
992             if (entry->destinationUrl == destUrl)
993             {
994                 BMCWEB_LOG_ERROR << "Destination exist already" << destUrl;
995                 return true;
996             }
997         }
998         return false;
999     }
1000 
1001     bool sendTestEventLog()
1002     {
1003         for (const auto& it : this->subscriptionsMap)
1004         {
1005             std::shared_ptr<Subscription> entry = it.second;
1006             if (!entry->sendTestEventLog())
1007             {
1008                 return false;
1009             }
1010         }
1011         return true;
1012     }
1013 
1014     void sendEvent(nlohmann::json eventMessage, const std::string& origin,
1015                    const std::string& resType)
1016     {
1017         if (!serviceEnabled || (noOfEventLogSubscribers == 0U))
1018         {
1019             BMCWEB_LOG_DEBUG << "EventService disabled or no Subscriptions.";
1020             return;
1021         }
1022         nlohmann::json eventRecord = nlohmann::json::array();
1023 
1024         eventMessage["EventId"] = eventId;
1025         // MemberId is 0 : since we are sending one event record.
1026         eventMessage["MemberId"] = 0;
1027         eventMessage["EventTimestamp"] =
1028             redfish::time_utils::getDateTimeOffsetNow().first;
1029         eventMessage["OriginOfCondition"] = origin;
1030 
1031         eventRecord.emplace_back(std::move(eventMessage));
1032 
1033         for (const auto& it : this->subscriptionsMap)
1034         {
1035             std::shared_ptr<Subscription> entry = it.second;
1036             bool isSubscribed = false;
1037             // Search the resourceTypes list for the subscription.
1038             // If resourceTypes list is empty, don't filter events
1039             // send everything.
1040             if (!entry->resourceTypes.empty())
1041             {
1042                 for (const auto& resource : entry->resourceTypes)
1043                 {
1044                     if (resType == resource)
1045                     {
1046                         BMCWEB_LOG_INFO << "ResourceType " << resource
1047                                         << " found in the subscribed list";
1048                         isSubscribed = true;
1049                         break;
1050                     }
1051                 }
1052             }
1053             else // resourceTypes list is empty.
1054             {
1055                 isSubscribed = true;
1056             }
1057             if (isSubscribed)
1058             {
1059                 nlohmann::json msgJson;
1060 
1061                 msgJson["@odata.type"] = "#Event.v1_4_0.Event";
1062                 msgJson["Name"] = "Event Log";
1063                 msgJson["Id"] = eventId;
1064                 msgJson["Events"] = eventRecord;
1065 
1066                 std::string strMsg = msgJson.dump(
1067                     2, ' ', true, nlohmann::json::error_handler_t::replace);
1068                 entry->sendEvent(strMsg);
1069                 eventId++; // increament the eventId
1070             }
1071             else
1072             {
1073                 BMCWEB_LOG_INFO << "Not subscribed to this resource";
1074             }
1075         }
1076     }
1077     void sendBroadcastMsg(const std::string& broadcastMsg)
1078     {
1079         for (const auto& it : this->subscriptionsMap)
1080         {
1081             std::shared_ptr<Subscription> entry = it.second;
1082             nlohmann::json msgJson;
1083             msgJson["Timestamp"] =
1084                 redfish::time_utils::getDateTimeOffsetNow().first;
1085             msgJson["OriginOfCondition"] = "/ibm/v1/HMC/BroadcastService";
1086             msgJson["Name"] = "Broadcast Message";
1087             msgJson["Message"] = broadcastMsg;
1088 
1089             std::string strMsg = msgJson.dump(
1090                 2, ' ', true, nlohmann::json::error_handler_t::replace);
1091             entry->sendEvent(strMsg);
1092         }
1093     }
1094 
1095 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
1096 
1097     void resetRedfishFilePosition()
1098     {
1099         // Control would be here when Redfish file is created.
1100         // Reset File Position as new file is created
1101         redfishLogFilePosition = 0;
1102     }
1103 
1104     void cacheRedfishLogFile()
1105     {
1106         // Open the redfish file and read till the last record.
1107 
1108         std::ifstream logStream(redfishEventLogFile);
1109         if (!logStream.good())
1110         {
1111             BMCWEB_LOG_ERROR << " Redfish log file open failed \n";
1112             return;
1113         }
1114         std::string logEntry;
1115         while (std::getline(logStream, logEntry))
1116         {
1117             redfishLogFilePosition = logStream.tellg();
1118         }
1119 
1120         BMCWEB_LOG_DEBUG << "Next Log Position : " << redfishLogFilePosition;
1121     }
1122 
1123     void readEventLogsFromFile()
1124     {
1125         std::ifstream logStream(redfishEventLogFile);
1126         if (!logStream.good())
1127         {
1128             BMCWEB_LOG_ERROR << " Redfish log file open failed";
1129             return;
1130         }
1131 
1132         std::vector<EventLogObjectsType> eventRecords;
1133 
1134         std::string logEntry;
1135 
1136         // Get the read pointer to the next log to be read.
1137         logStream.seekg(redfishLogFilePosition);
1138 
1139         while (std::getline(logStream, logEntry))
1140         {
1141             // Update Pointer position
1142             redfishLogFilePosition = logStream.tellg();
1143 
1144             std::string idStr;
1145             if (!event_log::getUniqueEntryID(logEntry, idStr))
1146             {
1147                 continue;
1148             }
1149 
1150             if (!serviceEnabled || noOfEventLogSubscribers == 0)
1151             {
1152                 // If Service is not enabled, no need to compute
1153                 // the remaining items below.
1154                 // But, Loop must continue to keep track of Timestamp
1155                 continue;
1156             }
1157 
1158             std::string timestamp;
1159             std::string messageID;
1160             std::vector<std::string> messageArgs;
1161             if (event_log::getEventLogParams(logEntry, timestamp, messageID,
1162                                              messageArgs) != 0)
1163             {
1164                 BMCWEB_LOG_DEBUG << "Read eventLog entry params failed";
1165                 continue;
1166             }
1167 
1168             std::string registryName;
1169             std::string messageKey;
1170             event_log::getRegistryAndMessageKey(messageID, registryName,
1171                                                 messageKey);
1172             if (registryName.empty() || messageKey.empty())
1173             {
1174                 continue;
1175             }
1176 
1177             eventRecords.emplace_back(idStr, timestamp, messageID, registryName,
1178                                       messageKey, messageArgs);
1179         }
1180 
1181         if (!serviceEnabled || noOfEventLogSubscribers == 0)
1182         {
1183             BMCWEB_LOG_DEBUG << "EventService disabled or no Subscriptions.";
1184             return;
1185         }
1186 
1187         if (eventRecords.empty())
1188         {
1189             // No Records to send
1190             BMCWEB_LOG_DEBUG << "No log entries available to be transferred.";
1191             return;
1192         }
1193 
1194         for (const auto& it : this->subscriptionsMap)
1195         {
1196             std::shared_ptr<Subscription> entry = it.second;
1197             if (entry->eventFormatType == "Event")
1198             {
1199                 entry->filterAndSendEventLogs(eventRecords);
1200             }
1201         }
1202     }
1203 
1204     static void watchRedfishEventLogFile()
1205     {
1206         if (!inotifyConn)
1207         {
1208             return;
1209         }
1210 
1211         static std::array<char, 1024> readBuffer;
1212 
1213         inotifyConn->async_read_some(boost::asio::buffer(readBuffer),
1214                                      [&](const boost::system::error_code& ec,
1215                                          const std::size_t& bytesTransferred) {
1216             if (ec)
1217             {
1218                 BMCWEB_LOG_ERROR << "Callback Error: " << ec.message();
1219                 return;
1220             }
1221             std::size_t index = 0;
1222             while ((index + iEventSize) <= bytesTransferred)
1223             {
1224                 struct inotify_event event
1225                 {};
1226                 std::memcpy(&event, &readBuffer[index], iEventSize);
1227                 if (event.wd == dirWatchDesc)
1228                 {
1229                     if ((event.len == 0) ||
1230                         (index + iEventSize + event.len > bytesTransferred))
1231                     {
1232                         index += (iEventSize + event.len);
1233                         continue;
1234                     }
1235 
1236                     std::string fileName(&readBuffer[index + iEventSize]);
1237                     if (fileName != "redfish")
1238                     {
1239                         index += (iEventSize + event.len);
1240                         continue;
1241                     }
1242 
1243                     BMCWEB_LOG_DEBUG
1244                         << "Redfish log file created/deleted. event.name: "
1245                         << fileName;
1246                     if (event.mask == IN_CREATE)
1247                     {
1248                         if (fileWatchDesc != -1)
1249                         {
1250                             BMCWEB_LOG_DEBUG
1251                                 << "Remove and Add inotify watcher on "
1252                                    "redfish event log file";
1253                             // Remove existing inotify watcher and add
1254                             // with new redfish event log file.
1255                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1256                             fileWatchDesc = -1;
1257                         }
1258 
1259                         fileWatchDesc = inotify_add_watch(
1260                             inotifyFd, redfishEventLogFile, IN_MODIFY);
1261                         if (fileWatchDesc == -1)
1262                         {
1263                             BMCWEB_LOG_ERROR << "inotify_add_watch failed for "
1264                                                 "redfish log file.";
1265                             return;
1266                         }
1267 
1268                         EventServiceManager::getInstance()
1269                             .resetRedfishFilePosition();
1270                         EventServiceManager::getInstance()
1271                             .readEventLogsFromFile();
1272                     }
1273                     else if ((event.mask == IN_DELETE) ||
1274                              (event.mask == IN_MOVED_TO))
1275                     {
1276                         if (fileWatchDesc != -1)
1277                         {
1278                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1279                             fileWatchDesc = -1;
1280                         }
1281                     }
1282                 }
1283                 else if (event.wd == fileWatchDesc)
1284                 {
1285                     if (event.mask == IN_MODIFY)
1286                     {
1287                         EventServiceManager::getInstance()
1288                             .readEventLogsFromFile();
1289                     }
1290                 }
1291                 index += (iEventSize + event.len);
1292             }
1293 
1294             watchRedfishEventLogFile();
1295         });
1296     }
1297 
1298     static int startEventLogMonitor(boost::asio::io_context& ioc)
1299     {
1300         inotifyConn.emplace(ioc);
1301         inotifyFd = inotify_init1(IN_NONBLOCK);
1302         if (inotifyFd == -1)
1303         {
1304             BMCWEB_LOG_ERROR << "inotify_init1 failed.";
1305             return -1;
1306         }
1307 
1308         // Add watch on directory to handle redfish event log file
1309         // create/delete.
1310         dirWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogDir,
1311                                          IN_CREATE | IN_MOVED_TO | IN_DELETE);
1312         if (dirWatchDesc == -1)
1313         {
1314             BMCWEB_LOG_ERROR
1315                 << "inotify_add_watch failed for event log directory.";
1316             return -1;
1317         }
1318 
1319         // Watch redfish event log file for modifications.
1320         fileWatchDesc =
1321             inotify_add_watch(inotifyFd, redfishEventLogFile, IN_MODIFY);
1322         if (fileWatchDesc == -1)
1323         {
1324             BMCWEB_LOG_ERROR
1325                 << "inotify_add_watch failed for redfish log file.";
1326             // Don't return error if file not exist.
1327             // Watch on directory will handle create/delete of file.
1328         }
1329 
1330         // monitor redfish event log file
1331         inotifyConn->assign(inotifyFd);
1332         watchRedfishEventLogFile();
1333 
1334         return 0;
1335     }
1336 
1337 #endif
1338     static void getReadingsForReport(sdbusplus::message_t& msg)
1339     {
1340         if (msg.is_method_error())
1341         {
1342             BMCWEB_LOG_ERROR << "TelemetryMonitor Signal error";
1343             return;
1344         }
1345 
1346         sdbusplus::message::object_path path(msg.get_path());
1347         std::string id = path.filename();
1348         if (id.empty())
1349         {
1350             BMCWEB_LOG_ERROR << "Failed to get Id from path";
1351             return;
1352         }
1353 
1354         std::string interface;
1355         dbus::utility::DBusPropertiesMap props;
1356         std::vector<std::string> invalidProps;
1357         msg.read(interface, props, invalidProps);
1358 
1359         auto found =
1360             std::find_if(props.begin(), props.end(),
1361                          [](const auto& x) { return x.first == "Readings"; });
1362         if (found == props.end())
1363         {
1364             BMCWEB_LOG_INFO << "Failed to get Readings from Report properties";
1365             return;
1366         }
1367 
1368         const telemetry::TimestampReadings* readings =
1369             std::get_if<telemetry::TimestampReadings>(&found->second);
1370         if (readings == nullptr)
1371         {
1372             BMCWEB_LOG_INFO << "Failed to get Readings from Report properties";
1373             return;
1374         }
1375 
1376         for (const auto& it :
1377              EventServiceManager::getInstance().subscriptionsMap)
1378         {
1379             Subscription& entry = *it.second;
1380             if (entry.eventFormatType == metricReportFormatType)
1381             {
1382                 entry.filterAndSendReports(id, *readings);
1383             }
1384         }
1385     }
1386 
1387     void unregisterMetricReportSignal()
1388     {
1389         if (matchTelemetryMonitor)
1390         {
1391             BMCWEB_LOG_DEBUG << "Metrics report signal - Unregister";
1392             matchTelemetryMonitor.reset();
1393             matchTelemetryMonitor = nullptr;
1394         }
1395     }
1396 
1397     void registerMetricReportSignal()
1398     {
1399         if (!serviceEnabled || matchTelemetryMonitor)
1400         {
1401             BMCWEB_LOG_DEBUG << "Not registering metric report signal.";
1402             return;
1403         }
1404 
1405         BMCWEB_LOG_DEBUG << "Metrics report signal - Register";
1406         std::string matchStr = "type='signal',member='PropertiesChanged',"
1407                                "interface='org.freedesktop.DBus.Properties',"
1408                                "arg0=xyz.openbmc_project.Telemetry.Report";
1409 
1410         matchTelemetryMonitor = std::make_shared<sdbusplus::bus::match_t>(
1411             *crow::connections::systemBus, matchStr, getReadingsForReport);
1412     }
1413 };
1414 
1415 } // namespace redfish
1416