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