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