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