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