xref: /openbmc/bmcweb/features/redfish/include/event_service_manager.hpp (revision 19bb362b5b45e36db3c4d2db2fafdf191259972b)
1b52664e2SAppaRao Puli /*
2b52664e2SAppaRao Puli // Copyright (c) 2020 Intel Corporation
3b52664e2SAppaRao Puli //
4b52664e2SAppaRao Puli // Licensed under the Apache License, Version 2.0 (the "License");
5b52664e2SAppaRao Puli // you may not use this file except in compliance with the License.
6b52664e2SAppaRao Puli // You may obtain a copy of the License at
7b52664e2SAppaRao Puli //
8b52664e2SAppaRao Puli //      http://www.apache.org/licenses/LICENSE-2.0
9b52664e2SAppaRao Puli //
10b52664e2SAppaRao Puli // Unless required by applicable law or agreed to in writing, software
11b52664e2SAppaRao Puli // distributed under the License is distributed on an "AS IS" BASIS,
12b52664e2SAppaRao Puli // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13b52664e2SAppaRao Puli // See the License for the specific language governing permissions and
14b52664e2SAppaRao Puli // limitations under the License.
15b52664e2SAppaRao Puli */
16b52664e2SAppaRao Puli #pragma once
173ccb3adbSEd Tanous #include "dbus_utility.hpp"
183ccb3adbSEd Tanous #include "error_messages.hpp"
193ccb3adbSEd Tanous #include "event_service_store.hpp"
203ccb3adbSEd Tanous #include "http_client.hpp"
21c0353249SWludzik, Jozef #include "metric_report.hpp"
222c6ffdb0SEd Tanous #include "ossl_random.hpp"
233ccb3adbSEd Tanous #include "persistent_data.hpp"
247f4eb588SAppaRao Puli #include "registries.hpp"
258dab0f58SEd Tanous #include "registries_selector.hpp"
2650ebd4afSEd Tanous #include "str_utility.hpp"
2777665bdaSNan Zhou #include "utility.hpp"
283ccb3adbSEd Tanous #include "utils/json_utils.hpp"
295b90429aSEd Tanous #include "utils/time_utils.hpp"
307f4eb588SAppaRao Puli 
317f4eb588SAppaRao Puli #include <sys/inotify.h>
32b52664e2SAppaRao Puli 
33fb4fd5d4SZhenfei Tai #include <boost/asio/io_context.hpp>
34b52664e2SAppaRao Puli #include <boost/container/flat_map.hpp>
35ef4c65b7SEd Tanous #include <boost/url/format.hpp>
364a7fbefdSEd Tanous #include <boost/url/url_view_base.hpp>
37b5b40605Snitroglycerine #include <sdbusplus/bus/match.hpp>
381214b7e7SGunnar Mills 
395e44e3d8SAppaRao Puli #include <algorithm>
40b52664e2SAppaRao Puli #include <cstdlib>
41b52664e2SAppaRao Puli #include <ctime>
421bf712bcSAyushi Smriti #include <fstream>
43b52664e2SAppaRao Puli #include <memory>
443544d2a7SEd Tanous #include <ranges>
4526702d01SEd Tanous #include <span>
46b52664e2SAppaRao Puli 
47b52664e2SAppaRao Puli namespace redfish
48b52664e2SAppaRao Puli {
49156d6b00SAppaRao Puli 
50156d6b00SAppaRao Puli static constexpr const char* eventFormatType = "Event";
51156d6b00SAppaRao Puli static constexpr const char* metricReportFormatType = "MetricReport";
52156d6b00SAppaRao Puli 
535e44e3d8SAppaRao Puli static constexpr const char* subscriptionTypeSSE = "SSE";
541bf712bcSAyushi Smriti static constexpr const char* eventServiceFile =
551bf712bcSAyushi Smriti     "/var/lib/bmcweb/eventservice_config.json";
561bf712bcSAyushi Smriti 
575e44e3d8SAppaRao Puli static constexpr const uint8_t maxNoOfSubscriptions = 20;
585e44e3d8SAppaRao Puli static constexpr const uint8_t maxNoOfSSESubscriptions = 10;
595e44e3d8SAppaRao Puli 
60cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
614642bf8fSGeorge Liu static std::optional<boost::asio::posix::stream_descriptor> inotifyConn;
624642bf8fSGeorge Liu static constexpr const char* redfishEventLogDir = "/var/log";
634642bf8fSGeorge Liu static constexpr const char* redfishEventLogFile = "/var/log/redfish";
644642bf8fSGeorge Liu static constexpr const size_t iEventSize = sizeof(inotify_event);
65cf9e417dSEd Tanous 
66cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
674642bf8fSGeorge Liu static int inotifyFd = -1;
68cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
694642bf8fSGeorge Liu static int dirWatchDesc = -1;
70cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
714642bf8fSGeorge Liu static int fileWatchDesc = -1;
724642bf8fSGeorge Liu 
734642bf8fSGeorge Liu // <ID, timestamp, RedfishLogId, registryPrefix, MessageId, MessageArgs>
744642bf8fSGeorge Liu using EventLogObjectsType =
754642bf8fSGeorge Liu     std::tuple<std::string, std::string, std::string, std::string, std::string,
764642bf8fSGeorge Liu                std::vector<std::string>>;
774642bf8fSGeorge Liu 
78fffb8c1fSEd Tanous namespace registries
794642bf8fSGeorge Liu {
807f4eb588SAppaRao Puli static const Message*
817f4eb588SAppaRao Puli     getMsgFromRegistry(const std::string& messageKey,
8226702d01SEd Tanous                        const std::span<const MessageEntry>& registry)
837f4eb588SAppaRao Puli {
843544d2a7SEd Tanous     std::span<const MessageEntry>::iterator messageIt = std::ranges::find_if(
853544d2a7SEd Tanous         registry, [&messageKey](const MessageEntry& messageEntry) {
8655f79e6fSEd Tanous         return messageKey == messageEntry.first;
877f4eb588SAppaRao Puli     });
8826702d01SEd Tanous     if (messageIt != registry.end())
897f4eb588SAppaRao Puli     {
907f4eb588SAppaRao Puli         return &messageIt->second;
917f4eb588SAppaRao Puli     }
927f4eb588SAppaRao Puli 
937f4eb588SAppaRao Puli     return nullptr;
947f4eb588SAppaRao Puli }
957f4eb588SAppaRao Puli 
9626ccae32SEd Tanous static const Message* formatMessage(std::string_view messageID)
977f4eb588SAppaRao Puli {
987f4eb588SAppaRao Puli     // Redfish MessageIds are in the form
997f4eb588SAppaRao Puli     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
1007f4eb588SAppaRao Puli     // the right Message
1017f4eb588SAppaRao Puli     std::vector<std::string> fields;
1027f4eb588SAppaRao Puli     fields.reserve(4);
10350ebd4afSEd Tanous 
10450ebd4afSEd Tanous     bmcweb::split(fields, messageID, '.');
1057f4eb588SAppaRao Puli     if (fields.size() != 4)
1067f4eb588SAppaRao Puli     {
1077f4eb588SAppaRao Puli         return nullptr;
1087f4eb588SAppaRao Puli     }
10902cad96eSEd Tanous     const std::string& registryName = fields[0];
11002cad96eSEd Tanous     const std::string& messageKey = fields[3];
1117f4eb588SAppaRao Puli 
1127f4eb588SAppaRao Puli     // Find the right registry and check it for the MessageKey
113b304bd79SP Dheeraj Srujan Kumar     return getMsgFromRegistry(messageKey, getRegistryFromPrefix(registryName));
1147f4eb588SAppaRao Puli }
115fffb8c1fSEd Tanous } // namespace registries
1167f4eb588SAppaRao Puli 
1177f4eb588SAppaRao Puli namespace event_log
1187f4eb588SAppaRao Puli {
1192558979cSP Dheeraj Srujan Kumar inline bool getUniqueEntryID(const std::string& logEntry, std::string& entryID)
1207f4eb588SAppaRao Puli {
1217f4eb588SAppaRao Puli     static time_t prevTs = 0;
1227f4eb588SAppaRao Puli     static int index = 0;
1237f4eb588SAppaRao Puli 
1247f4eb588SAppaRao Puli     // Get the entry timestamp
1257f4eb588SAppaRao Puli     std::time_t curTs = 0;
1267f4eb588SAppaRao Puli     std::tm timeStruct = {};
1277f4eb588SAppaRao Puli     std::istringstream entryStream(logEntry);
1287f4eb588SAppaRao Puli     if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1297f4eb588SAppaRao Puli     {
1307f4eb588SAppaRao Puli         curTs = std::mktime(&timeStruct);
1317f4eb588SAppaRao Puli         if (curTs == -1)
1327f4eb588SAppaRao Puli         {
1337f4eb588SAppaRao Puli             return false;
1347f4eb588SAppaRao Puli         }
1357f4eb588SAppaRao Puli     }
1367f4eb588SAppaRao Puli     // If the timestamp isn't unique, increment the index
1377f4eb588SAppaRao Puli     index = (curTs == prevTs) ? index + 1 : 0;
1387f4eb588SAppaRao Puli 
1397f4eb588SAppaRao Puli     // Save the timestamp
1407f4eb588SAppaRao Puli     prevTs = curTs;
1417f4eb588SAppaRao Puli 
1427f4eb588SAppaRao Puli     entryID = std::to_string(curTs);
1437f4eb588SAppaRao Puli     if (index > 0)
1447f4eb588SAppaRao Puli     {
1457f4eb588SAppaRao Puli         entryID += "_" + std::to_string(index);
1467f4eb588SAppaRao Puli     }
1477f4eb588SAppaRao Puli     return true;
1487f4eb588SAppaRao Puli }
1497f4eb588SAppaRao Puli 
15023a21a1cSEd Tanous inline int getEventLogParams(const std::string& logEntry,
15123a21a1cSEd Tanous                              std::string& timestamp, std::string& messageID,
1525e715de6SAppaRao Puli                              std::vector<std::string>& messageArgs)
1537f4eb588SAppaRao Puli {
1547f4eb588SAppaRao Puli     // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
1557f4eb588SAppaRao Puli     // First get the Timestamp
156f23b7296SEd Tanous     size_t space = logEntry.find_first_of(' ');
1577f4eb588SAppaRao Puli     if (space == std::string::npos)
1587f4eb588SAppaRao Puli     {
1597f4eb588SAppaRao Puli         return -EINVAL;
1607f4eb588SAppaRao Puli     }
1617f4eb588SAppaRao Puli     timestamp = logEntry.substr(0, space);
1627f4eb588SAppaRao Puli     // Then get the log contents
163f23b7296SEd Tanous     size_t entryStart = logEntry.find_first_not_of(' ', space);
1647f4eb588SAppaRao Puli     if (entryStart == std::string::npos)
1657f4eb588SAppaRao Puli     {
1667f4eb588SAppaRao Puli         return -EINVAL;
1677f4eb588SAppaRao Puli     }
1687f4eb588SAppaRao Puli     std::string_view entry(logEntry);
1697f4eb588SAppaRao Puli     entry.remove_prefix(entryStart);
1707f4eb588SAppaRao Puli     // Use split to separate the entry into its fields
1717f4eb588SAppaRao Puli     std::vector<std::string> logEntryFields;
17250ebd4afSEd Tanous     bmcweb::split(logEntryFields, entry, ',');
1737f4eb588SAppaRao Puli     // We need at least a MessageId to be valid
17426f6976fSEd Tanous     if (logEntryFields.empty())
1757f4eb588SAppaRao Puli     {
1767f4eb588SAppaRao Puli         return -EINVAL;
1777f4eb588SAppaRao Puli     }
1787f4eb588SAppaRao Puli     messageID = logEntryFields[0];
1797f4eb588SAppaRao Puli 
1807f4eb588SAppaRao Puli     // Get the MessageArgs from the log if there are any
1817f4eb588SAppaRao Puli     if (logEntryFields.size() > 1)
1827f4eb588SAppaRao Puli     {
18302cad96eSEd Tanous         const std::string& messageArgsStart = logEntryFields[1];
1847f4eb588SAppaRao Puli         // If the first string is empty, assume there are no MessageArgs
1857f4eb588SAppaRao Puli         if (!messageArgsStart.empty())
1867f4eb588SAppaRao Puli         {
1875e715de6SAppaRao Puli             messageArgs.assign(logEntryFields.begin() + 1,
1885e715de6SAppaRao Puli                                logEntryFields.end());
1897f4eb588SAppaRao Puli         }
1907f4eb588SAppaRao Puli     }
1917f4eb588SAppaRao Puli 
1927f4eb588SAppaRao Puli     return 0;
1937f4eb588SAppaRao Puli }
1947f4eb588SAppaRao Puli 
19523a21a1cSEd Tanous inline void getRegistryAndMessageKey(const std::string& messageID,
1967f4eb588SAppaRao Puli                                      std::string& registryName,
1977f4eb588SAppaRao Puli                                      std::string& messageKey)
1987f4eb588SAppaRao Puli {
1997f4eb588SAppaRao Puli     // Redfish MessageIds are in the form
2007f4eb588SAppaRao Puli     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
2017f4eb588SAppaRao Puli     // the right Message
2027f4eb588SAppaRao Puli     std::vector<std::string> fields;
2037f4eb588SAppaRao Puli     fields.reserve(4);
20450ebd4afSEd Tanous     bmcweb::split(fields, messageID, '.');
2057f4eb588SAppaRao Puli     if (fields.size() == 4)
2067f4eb588SAppaRao Puli     {
2077f4eb588SAppaRao Puli         registryName = fields[0];
2087f4eb588SAppaRao Puli         messageKey = fields[3];
2097f4eb588SAppaRao Puli     }
2107f4eb588SAppaRao Puli }
2117f4eb588SAppaRao Puli 
21223a21a1cSEd Tanous inline int formatEventLogEntry(const std::string& logEntryID,
2137f4eb588SAppaRao Puli                                const std::string& messageID,
214c5ba4c27SEd Tanous                                const std::span<std::string_view> messageArgs,
21523a21a1cSEd Tanous                                std::string timestamp,
216b5a76932SEd Tanous                                const std::string& customText,
2177f4eb588SAppaRao Puli                                nlohmann::json& logEntryJson)
2187f4eb588SAppaRao Puli {
2197f4eb588SAppaRao Puli     // Get the Message from the MessageRegistry
220fffb8c1fSEd Tanous     const registries::Message* message = registries::formatMessage(messageID);
2217f4eb588SAppaRao Puli 
22280f595e7SEd Tanous     if (message == nullptr)
2237f4eb588SAppaRao Puli     {
22480f595e7SEd Tanous         return -1;
2257f4eb588SAppaRao Puli     }
2267f4eb588SAppaRao Puli 
22789492a15SPatrick Williams     std::string msg = redfish::registries::fillMessageArgs(messageArgs,
22889492a15SPatrick Williams                                                            message->message);
22980f595e7SEd Tanous     if (msg.empty())
23080f595e7SEd Tanous     {
23180f595e7SEd Tanous         return -1;
23280f595e7SEd Tanous     }
2337f4eb588SAppaRao Puli 
2347f4eb588SAppaRao Puli     // Get the Created time from the timestamp. The log timestamp is in
2357f4eb588SAppaRao Puli     // RFC3339 format which matches the Redfish format except for the
2367f4eb588SAppaRao Puli     // fractional seconds between the '.' and the '+', so just remove them.
237f23b7296SEd Tanous     std::size_t dot = timestamp.find_first_of('.');
238b2f7609bSEd Tanous     std::size_t plus = timestamp.find_first_of('+', dot);
2397f4eb588SAppaRao Puli     if (dot != std::string::npos && plus != std::string::npos)
2407f4eb588SAppaRao Puli     {
2417f4eb588SAppaRao Puli         timestamp.erase(dot, plus - dot);
2427f4eb588SAppaRao Puli     }
2437f4eb588SAppaRao Puli 
2447f4eb588SAppaRao Puli     // Fill in the log entry with the gathered data
2451476687dSEd Tanous     logEntryJson["EventId"] = logEntryID;
2461476687dSEd Tanous     logEntryJson["EventType"] = "Event";
24780f595e7SEd Tanous     logEntryJson["Severity"] = message->messageSeverity;
2481476687dSEd Tanous     logEntryJson["Message"] = std::move(msg);
2491476687dSEd Tanous     logEntryJson["MessageId"] = messageID;
2501476687dSEd Tanous     logEntryJson["MessageArgs"] = messageArgs;
2511476687dSEd Tanous     logEntryJson["EventTimestamp"] = std::move(timestamp);
2521476687dSEd Tanous     logEntryJson["Context"] = customText;
2537f4eb588SAppaRao Puli     return 0;
2547f4eb588SAppaRao Puli }
2557f4eb588SAppaRao Puli 
2567f4eb588SAppaRao Puli } // namespace event_log
2577f4eb588SAppaRao Puli 
25828afb49cSJunLin Chen class Subscription : public persistent_data::UserSubscription
259b52664e2SAppaRao Puli {
260b52664e2SAppaRao Puli   public:
261b52664e2SAppaRao Puli     Subscription(const Subscription&) = delete;
262b52664e2SAppaRao Puli     Subscription& operator=(const Subscription&) = delete;
263b52664e2SAppaRao Puli     Subscription(Subscription&&) = delete;
264b52664e2SAppaRao Puli     Subscription& operator=(Subscription&&) = delete;
265b52664e2SAppaRao Puli 
2664a7fbefdSEd Tanous     Subscription(const boost::urls::url_view_base& url,
2674a7fbefdSEd Tanous                  boost::asio::io_context& ioc) :
268a716aa74SEd Tanous         policy(std::make_shared<crow::ConnectionPolicy>())
269b52664e2SAppaRao Puli     {
270a716aa74SEd Tanous         destinationUrl = url;
2715e44e3d8SAppaRao Puli         client.emplace(ioc, policy);
2727adb85acSSunitha Harish         // Subscription constructor
273d14a48ffSCarson Labrado         policy->invalidResp = retryRespHandler;
274b52664e2SAppaRao Puli     }
2754bbf237fSAppaRao Puli 
2765e44e3d8SAppaRao Puli     explicit Subscription(crow::sse_socket::Connection& connIn) :
2775e44e3d8SAppaRao Puli         sseConn(&connIn)
2785e44e3d8SAppaRao Puli     {}
2795e44e3d8SAppaRao Puli 
2809f616dd1SEd Tanous     ~Subscription() = default;
281b52664e2SAppaRao Puli 
2825e44e3d8SAppaRao Puli     bool sendEvent(std::string&& msg)
283b52664e2SAppaRao Puli     {
2846ba8c82eSsunharis_in         persistent_data::EventServiceConfig eventServiceConfig =
2856ba8c82eSsunharis_in             persistent_data::EventServiceStore::getInstance()
2866ba8c82eSsunharis_in                 .getEventServiceConfig();
2876ba8c82eSsunharis_in         if (!eventServiceConfig.enabled)
2886ba8c82eSsunharis_in         {
2896ba8c82eSsunharis_in             return false;
2906ba8c82eSsunharis_in         }
2916ba8c82eSsunharis_in 
292f52c03c1SCarson Labrado         // A connection pool will be created if one does not already exist
2935e44e3d8SAppaRao Puli         if (client)
2945e44e3d8SAppaRao Puli         {
295*19bb362bSEd Tanous             client->sendData(
296*19bb362bSEd Tanous                 std::move(msg), destinationUrl,
297*19bb362bSEd Tanous                 static_cast<ensuressl::VerifyCertificate>(verifyCertificate),
298*19bb362bSEd Tanous                 httpHeaders, boost::beast::http::verb::post);
2995e44e3d8SAppaRao Puli             return true;
3005e44e3d8SAppaRao Puli         }
3017adb85acSSunitha Harish 
3024bbf237fSAppaRao Puli         if (sseConn != nullptr)
3034bbf237fSAppaRao Puli         {
3045e44e3d8SAppaRao Puli             eventSeqNum++;
3055e44e3d8SAppaRao Puli             sseConn->sendEvent(std::to_string(eventSeqNum), msg);
3064bbf237fSAppaRao Puli         }
3076ba8c82eSsunharis_in         return true;
3084bbf237fSAppaRao Puli     }
3094bbf237fSAppaRao Puli 
3106ba8c82eSsunharis_in     bool sendTestEventLog()
3110b4bdd93SAppaRao Puli     {
3120b4bdd93SAppaRao Puli         nlohmann::json logEntryArray;
3130b4bdd93SAppaRao Puli         logEntryArray.push_back({});
3140b4bdd93SAppaRao Puli         nlohmann::json& logEntryJson = logEntryArray.back();
3150b4bdd93SAppaRao Puli 
316613dabeaSEd Tanous         logEntryJson["EventId"] = "TestID";
317613dabeaSEd Tanous         logEntryJson["EventType"] = "Event";
318613dabeaSEd Tanous         logEntryJson["Severity"] = "OK";
319613dabeaSEd Tanous         logEntryJson["Message"] = "Generated test event";
320613dabeaSEd Tanous         logEntryJson["MessageId"] = "OpenBMC.0.2.TestEventLog";
321613dabeaSEd Tanous         logEntryJson["MessageArgs"] = nlohmann::json::array();
322613dabeaSEd Tanous         logEntryJson["EventTimestamp"] =
323613dabeaSEd Tanous             redfish::time_utils::getDateTimeOffsetNow().first;
324613dabeaSEd Tanous         logEntryJson["Context"] = customText;
3250b4bdd93SAppaRao Puli 
3261476687dSEd Tanous         nlohmann::json msg;
3271476687dSEd Tanous         msg["@odata.type"] = "#Event.v1_4_0.Event";
3281476687dSEd Tanous         msg["Id"] = std::to_string(eventSeqNum);
3291476687dSEd Tanous         msg["Name"] = "Event Log";
3301476687dSEd Tanous         msg["Events"] = logEntryArray;
3310b4bdd93SAppaRao Puli 
33289492a15SPatrick Williams         std::string strMsg = msg.dump(2, ' ', true,
33389492a15SPatrick Williams                                       nlohmann::json::error_handler_t::replace);
3345e44e3d8SAppaRao Puli         return sendEvent(std::move(strMsg));
3350b4bdd93SAppaRao Puli     }
3360b4bdd93SAppaRao Puli 
3377f4eb588SAppaRao Puli     void filterAndSendEventLogs(
3387f4eb588SAppaRao Puli         const std::vector<EventLogObjectsType>& eventRecords)
3397f4eb588SAppaRao Puli     {
3407f4eb588SAppaRao Puli         nlohmann::json logEntryArray;
3417f4eb588SAppaRao Puli         for (const EventLogObjectsType& logEntry : eventRecords)
3427f4eb588SAppaRao Puli         {
3437f4eb588SAppaRao Puli             const std::string& idStr = std::get<0>(logEntry);
3447f4eb588SAppaRao Puli             const std::string& timestamp = std::get<1>(logEntry);
3457f4eb588SAppaRao Puli             const std::string& messageID = std::get<2>(logEntry);
3467f4eb588SAppaRao Puli             const std::string& registryName = std::get<3>(logEntry);
3477f4eb588SAppaRao Puli             const std::string& messageKey = std::get<4>(logEntry);
3485e715de6SAppaRao Puli             const std::vector<std::string>& messageArgs = std::get<5>(logEntry);
3497f4eb588SAppaRao Puli 
3507f4eb588SAppaRao Puli             // If registryPrefixes list is empty, don't filter events
3517f4eb588SAppaRao Puli             // send everything.
35226f6976fSEd Tanous             if (!registryPrefixes.empty())
3537f4eb588SAppaRao Puli             {
3543544d2a7SEd Tanous                 auto obj = std::ranges::find(registryPrefixes, registryName);
3557f4eb588SAppaRao Puli                 if (obj == registryPrefixes.end())
3567f4eb588SAppaRao Puli                 {
3577f4eb588SAppaRao Puli                     continue;
3587f4eb588SAppaRao Puli                 }
3597f4eb588SAppaRao Puli             }
3607f4eb588SAppaRao Puli 
3617f4eb588SAppaRao Puli             // If registryMsgIds list is empty, don't filter events
3627f4eb588SAppaRao Puli             // send everything.
36326f6976fSEd Tanous             if (!registryMsgIds.empty())
3647f4eb588SAppaRao Puli             {
3653544d2a7SEd Tanous                 auto obj = std::ranges::find(registryMsgIds, messageKey);
3667f4eb588SAppaRao Puli                 if (obj == registryMsgIds.end())
3677f4eb588SAppaRao Puli                 {
3687f4eb588SAppaRao Puli                     continue;
3697f4eb588SAppaRao Puli                 }
3707f4eb588SAppaRao Puli             }
3717f4eb588SAppaRao Puli 
372c5ba4c27SEd Tanous             std::vector<std::string_view> messageArgsView(messageArgs.begin(),
373c5ba4c27SEd Tanous                                                           messageArgs.end());
374c5ba4c27SEd Tanous 
3757f4eb588SAppaRao Puli             logEntryArray.push_back({});
3767f4eb588SAppaRao Puli             nlohmann::json& bmcLogEntry = logEntryArray.back();
377c5ba4c27SEd Tanous             if (event_log::formatEventLogEntry(idStr, messageID,
378c5ba4c27SEd Tanous                                                messageArgsView, timestamp,
379c5ba4c27SEd Tanous                                                customText, bmcLogEntry) != 0)
3807f4eb588SAppaRao Puli             {
38162598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Read eventLog entry failed");
3827f4eb588SAppaRao Puli                 continue;
3837f4eb588SAppaRao Puli             }
3847f4eb588SAppaRao Puli         }
3857f4eb588SAppaRao Puli 
38626f6976fSEd Tanous         if (logEntryArray.empty())
3877f4eb588SAppaRao Puli         {
38862598e31SEd Tanous             BMCWEB_LOG_DEBUG("No log entries available to be transferred.");
3897f4eb588SAppaRao Puli             return;
3907f4eb588SAppaRao Puli         }
3917f4eb588SAppaRao Puli 
3921476687dSEd Tanous         nlohmann::json msg;
3931476687dSEd Tanous         msg["@odata.type"] = "#Event.v1_4_0.Event";
3941476687dSEd Tanous         msg["Id"] = std::to_string(eventSeqNum);
3951476687dSEd Tanous         msg["Name"] = "Event Log";
3961476687dSEd Tanous         msg["Events"] = logEntryArray;
39789492a15SPatrick Williams         std::string strMsg = msg.dump(2, ' ', true,
39889492a15SPatrick Williams                                       nlohmann::json::error_handler_t::replace);
3995e44e3d8SAppaRao Puli         sendEvent(std::move(strMsg));
4005e44e3d8SAppaRao Puli         eventSeqNum++;
4017f4eb588SAppaRao Puli     }
4027f4eb588SAppaRao Puli 
403248d0230SEd Tanous     void filterAndSendReports(const std::string& reportId,
4041e1e598dSJonathan Doman                               const telemetry::TimestampReadings& var)
405156d6b00SAppaRao Puli     {
406ef4c65b7SEd Tanous         boost::urls::url mrdUri = boost::urls::format(
407ef4c65b7SEd Tanous             "/redfish/v1/TelemetryService/MetricReportDefinitions/{}",
408ef4c65b7SEd Tanous             reportId);
409156d6b00SAppaRao Puli 
410156d6b00SAppaRao Puli         // Empty list means no filter. Send everything.
41126f6976fSEd Tanous         if (!metricReportDefinitions.empty())
412156d6b00SAppaRao Puli         {
4133544d2a7SEd Tanous             if (std::ranges::find(metricReportDefinitions, mrdUri.buffer()) ==
4143544d2a7SEd Tanous                 metricReportDefinitions.end())
415156d6b00SAppaRao Puli             {
416156d6b00SAppaRao Puli                 return;
417156d6b00SAppaRao Puli             }
418156d6b00SAppaRao Puli         }
419156d6b00SAppaRao Puli 
420c0353249SWludzik, Jozef         nlohmann::json msg;
421248d0230SEd Tanous         if (!telemetry::fillReport(msg, reportId, var))
422156d6b00SAppaRao Puli         {
42362598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to fill the MetricReport for DBus "
42462598e31SEd Tanous                              "Report with id {}",
42562598e31SEd Tanous                              reportId);
426c0353249SWludzik, Jozef             return;
427156d6b00SAppaRao Puli         }
428156d6b00SAppaRao Puli 
42922daffd7SAppaRao Puli         // Context is set by user during Event subscription and it must be
43022daffd7SAppaRao Puli         // set for MetricReport response.
43122daffd7SAppaRao Puli         if (!customText.empty())
43222daffd7SAppaRao Puli         {
43322daffd7SAppaRao Puli             msg["Context"] = customText;
43422daffd7SAppaRao Puli         }
43522daffd7SAppaRao Puli 
43689492a15SPatrick Williams         std::string strMsg = msg.dump(2, ' ', true,
43789492a15SPatrick Williams                                       nlohmann::json::error_handler_t::replace);
4385e44e3d8SAppaRao Puli         sendEvent(std::move(strMsg));
439156d6b00SAppaRao Puli     }
440156d6b00SAppaRao Puli 
441d14a48ffSCarson Labrado     void updateRetryConfig(uint32_t retryAttempts,
442d14a48ffSCarson Labrado                            uint32_t retryTimeoutInterval)
443fe44eb0bSAyushi Smriti     {
44493cf0ac2SEd Tanous         if (policy == nullptr)
44593cf0ac2SEd Tanous         {
44693cf0ac2SEd Tanous             BMCWEB_LOG_DEBUG("Retry policy was nullptr, ignoring set");
44793cf0ac2SEd Tanous             return;
44893cf0ac2SEd Tanous         }
449d14a48ffSCarson Labrado         policy->maxRetryAttempts = retryAttempts;
450d14a48ffSCarson Labrado         policy->retryIntervalSecs = std::chrono::seconds(retryTimeoutInterval);
45162de0c68SAppaRao Puli     }
452fe44eb0bSAyushi Smriti 
4539eb808c1SEd Tanous     uint64_t getEventSeqNum() const
45496330b99SSunitha Harish     {
45596330b99SSunitha Harish         return eventSeqNum;
45696330b99SSunitha Harish     }
45796330b99SSunitha Harish 
4585e44e3d8SAppaRao Puli     void setSubscriptionId(const std::string& id2)
4595e44e3d8SAppaRao Puli     {
46062598e31SEd Tanous         BMCWEB_LOG_DEBUG("Subscription ID: {}", id2);
4615e44e3d8SAppaRao Puli         subId = id2;
4625e44e3d8SAppaRao Puli     }
4635e44e3d8SAppaRao Puli 
4645e44e3d8SAppaRao Puli     std::string getSubscriptionId()
4655e44e3d8SAppaRao Puli     {
4665e44e3d8SAppaRao Puli         return subId;
4675e44e3d8SAppaRao Puli     }
4685e44e3d8SAppaRao Puli 
4695e44e3d8SAppaRao Puli     bool matchSseId(const crow::sse_socket::Connection& thisConn)
4705e44e3d8SAppaRao Puli     {
4715e44e3d8SAppaRao Puli         return &thisConn == sseConn;
4725e44e3d8SAppaRao Puli     }
4735e44e3d8SAppaRao Puli 
474b52664e2SAppaRao Puli   private:
4755e44e3d8SAppaRao Puli     std::string subId;
476d14a48ffSCarson Labrado     uint64_t eventSeqNum = 1;
477a716aa74SEd Tanous     boost::urls::url host;
478d14a48ffSCarson Labrado     std::shared_ptr<crow::ConnectionPolicy> policy;
4795e44e3d8SAppaRao Puli     crow::sse_socket::Connection* sseConn = nullptr;
4805e44e3d8SAppaRao Puli     std::optional<crow::HttpClient> client;
481b52664e2SAppaRao Puli     std::string path;
482b52664e2SAppaRao Puli     std::string uriProto;
483a7a80296SCarson Labrado 
484a7a80296SCarson Labrado     // Check used to indicate what response codes are valid as part of our retry
485a7a80296SCarson Labrado     // policy.  2XX is considered acceptable
486a7a80296SCarson Labrado     static boost::system::error_code retryRespHandler(unsigned int respCode)
487a7a80296SCarson Labrado     {
48862598e31SEd Tanous         BMCWEB_LOG_DEBUG(
48962598e31SEd Tanous             "Checking response code validity for SubscriptionEvent");
490a7a80296SCarson Labrado         if ((respCode < 200) || (respCode >= 300))
491a7a80296SCarson Labrado         {
492a7a80296SCarson Labrado             return boost::system::errc::make_error_code(
493a7a80296SCarson Labrado                 boost::system::errc::result_out_of_range);
494a7a80296SCarson Labrado         }
495a7a80296SCarson Labrado 
496a7a80296SCarson Labrado         // Return 0 if the response code is valid
497a7a80296SCarson Labrado         return boost::system::errc::make_error_code(
498a7a80296SCarson Labrado             boost::system::errc::success);
4999fa6d147SNan Zhou     }
500b52664e2SAppaRao Puli };
501b52664e2SAppaRao Puli 
502b52664e2SAppaRao Puli class EventServiceManager
503b52664e2SAppaRao Puli {
504b52664e2SAppaRao Puli   private:
505d3a9e084SEd Tanous     bool serviceEnabled = false;
506d3a9e084SEd Tanous     uint32_t retryAttempts = 0;
507d3a9e084SEd Tanous     uint32_t retryTimeoutInterval = 0;
5087d1cc387SAppaRao Puli 
5092558979cSP Dheeraj Srujan Kumar     std::streampos redfishLogFilePosition{0};
5109f616dd1SEd Tanous     size_t noOfEventLogSubscribers{0};
5119f616dd1SEd Tanous     size_t noOfMetricReportSubscribers{0};
51259d494eeSPatrick Williams     std::shared_ptr<sdbusplus::bus::match_t> matchTelemetryMonitor;
513b52664e2SAppaRao Puli     boost::container::flat_map<std::string, std::shared_ptr<Subscription>>
514b52664e2SAppaRao Puli         subscriptionsMap;
515b52664e2SAppaRao Puli 
5169f616dd1SEd Tanous     uint64_t eventId{1};
51796330b99SSunitha Harish 
518f8ca6d79SEd Tanous     boost::asio::io_context& ioc;
519f8ca6d79SEd Tanous 
520b52664e2SAppaRao Puli   public:
5219f616dd1SEd Tanous     EventServiceManager(const EventServiceManager&) = delete;
5229f616dd1SEd Tanous     EventServiceManager& operator=(const EventServiceManager&) = delete;
5239f616dd1SEd Tanous     EventServiceManager(EventServiceManager&&) = delete;
5249f616dd1SEd Tanous     EventServiceManager& operator=(EventServiceManager&&) = delete;
525ecd6a3a2SEd Tanous     ~EventServiceManager() = default;
5269f616dd1SEd Tanous 
527f8ca6d79SEd Tanous     explicit EventServiceManager(boost::asio::io_context& iocIn) : ioc(iocIn)
528b52664e2SAppaRao Puli     {
529f8ca6d79SEd Tanous         // Load config from persist store.
530f8ca6d79SEd Tanous         initConfig();
531f8ca6d79SEd Tanous     }
532f8ca6d79SEd Tanous 
533f8ca6d79SEd Tanous     static EventServiceManager&
534f8ca6d79SEd Tanous         getInstance(boost::asio::io_context* ioc = nullptr)
535f8ca6d79SEd Tanous     {
536f8ca6d79SEd Tanous         static EventServiceManager handler(*ioc);
537b52664e2SAppaRao Puli         return handler;
538b52664e2SAppaRao Puli     }
539b52664e2SAppaRao Puli 
5401bf712bcSAyushi Smriti     void initConfig()
5411bf712bcSAyushi Smriti     {
54228afb49cSJunLin Chen         loadOldBehavior();
5431bf712bcSAyushi Smriti 
54428afb49cSJunLin Chen         persistent_data::EventServiceConfig eventServiceConfig =
54528afb49cSJunLin Chen             persistent_data::EventServiceStore::getInstance()
54628afb49cSJunLin Chen                 .getEventServiceConfig();
5471bf712bcSAyushi Smriti 
54828afb49cSJunLin Chen         serviceEnabled = eventServiceConfig.enabled;
54928afb49cSJunLin Chen         retryAttempts = eventServiceConfig.retryAttempts;
55028afb49cSJunLin Chen         retryTimeoutInterval = eventServiceConfig.retryTimeoutInterval;
5511bf712bcSAyushi Smriti 
55228afb49cSJunLin Chen         for (const auto& it : persistent_data::EventServiceStore::getInstance()
55328afb49cSJunLin Chen                                   .subscriptionsConfigMap)
5541bf712bcSAyushi Smriti         {
55528afb49cSJunLin Chen             std::shared_ptr<persistent_data::UserSubscription> newSub =
55628afb49cSJunLin Chen                 it.second;
5574bbf237fSAppaRao Puli 
5586fd29553SEd Tanous             boost::system::result<boost::urls::url> url =
559a716aa74SEd Tanous                 boost::urls::parse_absolute_uri(newSub->destinationUrl);
5601bf712bcSAyushi Smriti 
561a716aa74SEd Tanous             if (!url)
5621bf712bcSAyushi Smriti             {
56362598e31SEd Tanous                 BMCWEB_LOG_ERROR(
56462598e31SEd Tanous                     "Failed to validate and split destination url");
5651bf712bcSAyushi Smriti                 continue;
5661bf712bcSAyushi Smriti             }
5671bf712bcSAyushi Smriti             std::shared_ptr<Subscription> subValue =
568a716aa74SEd Tanous                 std::make_shared<Subscription>(*url, ioc);
5691bf712bcSAyushi Smriti 
57028afb49cSJunLin Chen             subValue->id = newSub->id;
57128afb49cSJunLin Chen             subValue->destinationUrl = newSub->destinationUrl;
57228afb49cSJunLin Chen             subValue->protocol = newSub->protocol;
573*19bb362bSEd Tanous             subValue->verifyCertificate = newSub->verifyCertificate;
57428afb49cSJunLin Chen             subValue->retryPolicy = newSub->retryPolicy;
57528afb49cSJunLin Chen             subValue->customText = newSub->customText;
57628afb49cSJunLin Chen             subValue->eventFormatType = newSub->eventFormatType;
57728afb49cSJunLin Chen             subValue->subscriptionType = newSub->subscriptionType;
57828afb49cSJunLin Chen             subValue->registryMsgIds = newSub->registryMsgIds;
57928afb49cSJunLin Chen             subValue->registryPrefixes = newSub->registryPrefixes;
58028afb49cSJunLin Chen             subValue->resourceTypes = newSub->resourceTypes;
58128afb49cSJunLin Chen             subValue->httpHeaders = newSub->httpHeaders;
58228afb49cSJunLin Chen             subValue->metricReportDefinitions = newSub->metricReportDefinitions;
5831bf712bcSAyushi Smriti 
58428afb49cSJunLin Chen             if (subValue->id.empty())
5851bf712bcSAyushi Smriti             {
58662598e31SEd Tanous                 BMCWEB_LOG_ERROR("Failed to add subscription");
5871bf712bcSAyushi Smriti             }
58828afb49cSJunLin Chen             subscriptionsMap.insert(std::pair(subValue->id, subValue));
58928afb49cSJunLin Chen 
59028afb49cSJunLin Chen             updateNoOfSubscribersCount();
59128afb49cSJunLin Chen 
59283328316SEd Tanous             if constexpr (!BMCWEB_REDFISH_DBUS_LOG)
59383328316SEd Tanous             {
5942558979cSP Dheeraj Srujan Kumar                 cacheRedfishLogFile();
59583328316SEd Tanous             }
5962558979cSP Dheeraj Srujan Kumar 
59728afb49cSJunLin Chen             // Update retry configuration.
59828afb49cSJunLin Chen             subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
5991bf712bcSAyushi Smriti         }
6001bf712bcSAyushi Smriti     }
6011bf712bcSAyushi Smriti 
60256d2396dSEd Tanous     static void loadOldBehavior()
603b52664e2SAppaRao Puli     {
60428afb49cSJunLin Chen         std::ifstream eventConfigFile(eventServiceFile);
60528afb49cSJunLin Chen         if (!eventConfigFile.good())
6061bf712bcSAyushi Smriti         {
60762598e31SEd Tanous             BMCWEB_LOG_DEBUG("Old eventService config not exist");
60828afb49cSJunLin Chen             return;
60928afb49cSJunLin Chen         }
61028afb49cSJunLin Chen         auto jsonData = nlohmann::json::parse(eventConfigFile, nullptr, false);
61128afb49cSJunLin Chen         if (jsonData.is_discarded())
6124bbf237fSAppaRao Puli         {
61362598e31SEd Tanous             BMCWEB_LOG_ERROR("Old eventService config parse error.");
61428afb49cSJunLin Chen             return;
61528afb49cSJunLin Chen         }
61628afb49cSJunLin Chen 
6170bdda665SEd Tanous         const nlohmann::json::object_t* obj =
6180bdda665SEd Tanous             jsonData.get_ptr<const nlohmann::json::object_t*>();
6190bdda665SEd Tanous         for (const auto& item : *obj)
62028afb49cSJunLin Chen         {
6210bdda665SEd Tanous             if (item.first == "Configuration")
62228afb49cSJunLin Chen             {
62328afb49cSJunLin Chen                 persistent_data::EventServiceStore::getInstance()
62428afb49cSJunLin Chen                     .getEventServiceConfig()
6250bdda665SEd Tanous                     .fromJson(item.second);
62628afb49cSJunLin Chen             }
6270bdda665SEd Tanous             else if (item.first == "Subscriptions")
62828afb49cSJunLin Chen             {
6290bdda665SEd Tanous                 for (const auto& elem : item.second)
63028afb49cSJunLin Chen                 {
63128afb49cSJunLin Chen                     std::shared_ptr<persistent_data::UserSubscription>
63228afb49cSJunLin Chen                         newSubscription =
63328afb49cSJunLin Chen                             persistent_data::UserSubscription::fromJson(elem,
63428afb49cSJunLin Chen                                                                         true);
63528afb49cSJunLin Chen                     if (newSubscription == nullptr)
63628afb49cSJunLin Chen                     {
63762598e31SEd Tanous                         BMCWEB_LOG_ERROR("Problem reading subscription "
63862598e31SEd Tanous                                          "from old persistent store");
6394bbf237fSAppaRao Puli                         continue;
6404bbf237fSAppaRao Puli                     }
6411bf712bcSAyushi Smriti 
64228afb49cSJunLin Chen                     std::uniform_int_distribution<uint32_t> dist(0);
64328afb49cSJunLin Chen                     bmcweb::OpenSSLGenerator gen;
6441bf712bcSAyushi Smriti 
64528afb49cSJunLin Chen                     std::string id;
6461bf712bcSAyushi Smriti 
64728afb49cSJunLin Chen                     int retry = 3;
648e662eae8SEd Tanous                     while (retry != 0)
6491bf712bcSAyushi Smriti                     {
65028afb49cSJunLin Chen                         id = std::to_string(dist(gen));
65128afb49cSJunLin Chen                         if (gen.error())
6527d1cc387SAppaRao Puli                         {
65328afb49cSJunLin Chen                             retry = 0;
65428afb49cSJunLin Chen                             break;
65528afb49cSJunLin Chen                         }
65628afb49cSJunLin Chen                         newSubscription->id = id;
65728afb49cSJunLin Chen                         auto inserted =
65828afb49cSJunLin Chen                             persistent_data::EventServiceStore::getInstance()
65928afb49cSJunLin Chen                                 .subscriptionsConfigMap.insert(
66028afb49cSJunLin Chen                                     std::pair(id, newSubscription));
66128afb49cSJunLin Chen                         if (inserted.second)
66228afb49cSJunLin Chen                         {
66328afb49cSJunLin Chen                             break;
66428afb49cSJunLin Chen                         }
66528afb49cSJunLin Chen                         --retry;
6667d1cc387SAppaRao Puli                     }
6677d1cc387SAppaRao Puli 
66828afb49cSJunLin Chen                     if (retry <= 0)
66928afb49cSJunLin Chen                     {
67062598e31SEd Tanous                         BMCWEB_LOG_ERROR(
67162598e31SEd Tanous                             "Failed to generate random number from old "
67262598e31SEd Tanous                             "persistent store");
67328afb49cSJunLin Chen                         continue;
67428afb49cSJunLin Chen                     }
67528afb49cSJunLin Chen                 }
67628afb49cSJunLin Chen             }
67728afb49cSJunLin Chen 
67828afb49cSJunLin Chen             persistent_data::getConfig().writeData();
6794c521c3cSEd Tanous             std::error_code ec;
6804c521c3cSEd Tanous             std::filesystem::remove(eventServiceFile, ec);
6814c521c3cSEd Tanous             if (ec)
6824c521c3cSEd Tanous             {
6834c521c3cSEd Tanous                 BMCWEB_LOG_DEBUG(
6844c521c3cSEd Tanous                     "Failed to remove old event service file.  Ignoring");
6854c521c3cSEd Tanous             }
6864c521c3cSEd Tanous             else
6874c521c3cSEd Tanous             {
68862598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Remove old eventservice config");
68928afb49cSJunLin Chen             }
69028afb49cSJunLin Chen         }
6914c521c3cSEd Tanous     }
69228afb49cSJunLin Chen 
6939eb808c1SEd Tanous     void updateSubscriptionData() const
69428afb49cSJunLin Chen     {
69528afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
69628afb49cSJunLin Chen             .eventServiceConfig.enabled = serviceEnabled;
69728afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
69828afb49cSJunLin Chen             .eventServiceConfig.retryAttempts = retryAttempts;
69928afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
70028afb49cSJunLin Chen             .eventServiceConfig.retryTimeoutInterval = retryTimeoutInterval;
70128afb49cSJunLin Chen 
70228afb49cSJunLin Chen         persistent_data::getConfig().writeData();
70328afb49cSJunLin Chen     }
70428afb49cSJunLin Chen 
70528afb49cSJunLin Chen     void setEventServiceConfig(const persistent_data::EventServiceConfig& cfg)
7067d1cc387SAppaRao Puli     {
7077d1cc387SAppaRao Puli         bool updateConfig = false;
708fe44eb0bSAyushi Smriti         bool updateRetryCfg = false;
7097d1cc387SAppaRao Puli 
71028afb49cSJunLin Chen         if (serviceEnabled != cfg.enabled)
7117d1cc387SAppaRao Puli         {
71228afb49cSJunLin Chen             serviceEnabled = cfg.enabled;
713e662eae8SEd Tanous             if (serviceEnabled && noOfMetricReportSubscribers != 0U)
7147d1cc387SAppaRao Puli             {
7157d1cc387SAppaRao Puli                 registerMetricReportSignal();
7167d1cc387SAppaRao Puli             }
7177d1cc387SAppaRao Puli             else
7187d1cc387SAppaRao Puli             {
7197d1cc387SAppaRao Puli                 unregisterMetricReportSignal();
7207d1cc387SAppaRao Puli             }
7217d1cc387SAppaRao Puli             updateConfig = true;
7227d1cc387SAppaRao Puli         }
7237d1cc387SAppaRao Puli 
72428afb49cSJunLin Chen         if (retryAttempts != cfg.retryAttempts)
7257d1cc387SAppaRao Puli         {
72628afb49cSJunLin Chen             retryAttempts = cfg.retryAttempts;
7277d1cc387SAppaRao Puli             updateConfig = true;
728fe44eb0bSAyushi Smriti             updateRetryCfg = true;
7297d1cc387SAppaRao Puli         }
7307d1cc387SAppaRao Puli 
73128afb49cSJunLin Chen         if (retryTimeoutInterval != cfg.retryTimeoutInterval)
7327d1cc387SAppaRao Puli         {
73328afb49cSJunLin Chen             retryTimeoutInterval = cfg.retryTimeoutInterval;
7347d1cc387SAppaRao Puli             updateConfig = true;
735fe44eb0bSAyushi Smriti             updateRetryCfg = true;
7367d1cc387SAppaRao Puli         }
7377d1cc387SAppaRao Puli 
7387d1cc387SAppaRao Puli         if (updateConfig)
7397d1cc387SAppaRao Puli         {
7407d1cc387SAppaRao Puli             updateSubscriptionData();
7417d1cc387SAppaRao Puli         }
742fe44eb0bSAyushi Smriti 
743fe44eb0bSAyushi Smriti         if (updateRetryCfg)
744fe44eb0bSAyushi Smriti         {
745fe44eb0bSAyushi Smriti             // Update the changed retry config to all subscriptions
746fe44eb0bSAyushi Smriti             for (const auto& it :
747fe44eb0bSAyushi Smriti                  EventServiceManager::getInstance().subscriptionsMap)
748fe44eb0bSAyushi Smriti             {
7495e44e3d8SAppaRao Puli                 Subscription& entry = *it.second;
7505e44e3d8SAppaRao Puli                 entry.updateRetryConfig(retryAttempts, retryTimeoutInterval);
751fe44eb0bSAyushi Smriti             }
752fe44eb0bSAyushi Smriti         }
7537d1cc387SAppaRao Puli     }
7547d1cc387SAppaRao Puli 
7557d1cc387SAppaRao Puli     void updateNoOfSubscribersCount()
7567d1cc387SAppaRao Puli     {
7577d1cc387SAppaRao Puli         size_t eventLogSubCount = 0;
7587d1cc387SAppaRao Puli         size_t metricReportSubCount = 0;
7597d1cc387SAppaRao Puli         for (const auto& it : subscriptionsMap)
7607d1cc387SAppaRao Puli         {
7617d1cc387SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
7627d1cc387SAppaRao Puli             if (entry->eventFormatType == eventFormatType)
7637d1cc387SAppaRao Puli             {
7647d1cc387SAppaRao Puli                 eventLogSubCount++;
7657d1cc387SAppaRao Puli             }
7667d1cc387SAppaRao Puli             else if (entry->eventFormatType == metricReportFormatType)
7677d1cc387SAppaRao Puli             {
7687d1cc387SAppaRao Puli                 metricReportSubCount++;
7697d1cc387SAppaRao Puli             }
7707d1cc387SAppaRao Puli         }
7717d1cc387SAppaRao Puli 
7727d1cc387SAppaRao Puli         noOfEventLogSubscribers = eventLogSubCount;
7737d1cc387SAppaRao Puli         if (noOfMetricReportSubscribers != metricReportSubCount)
7747d1cc387SAppaRao Puli         {
7757d1cc387SAppaRao Puli             noOfMetricReportSubscribers = metricReportSubCount;
776e662eae8SEd Tanous             if (noOfMetricReportSubscribers != 0U)
7777d1cc387SAppaRao Puli             {
7787d1cc387SAppaRao Puli                 registerMetricReportSignal();
7797d1cc387SAppaRao Puli             }
7807d1cc387SAppaRao Puli             else
7817d1cc387SAppaRao Puli             {
7827d1cc387SAppaRao Puli                 unregisterMetricReportSignal();
7837d1cc387SAppaRao Puli             }
7847d1cc387SAppaRao Puli         }
7857d1cc387SAppaRao Puli     }
7867d1cc387SAppaRao Puli 
787b52664e2SAppaRao Puli     std::shared_ptr<Subscription> getSubscription(const std::string& id)
788b52664e2SAppaRao Puli     {
789b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
790b52664e2SAppaRao Puli         if (obj == subscriptionsMap.end())
791b52664e2SAppaRao Puli         {
79262598e31SEd Tanous             BMCWEB_LOG_ERROR("No subscription exist with ID:{}", id);
793b52664e2SAppaRao Puli             return nullptr;
794b52664e2SAppaRao Puli         }
795b52664e2SAppaRao Puli         std::shared_ptr<Subscription> subValue = obj->second;
796b52664e2SAppaRao Puli         return subValue;
797b52664e2SAppaRao Puli     }
798b52664e2SAppaRao Puli 
799b5a76932SEd Tanous     std::string addSubscription(const std::shared_ptr<Subscription>& subValue,
8001bf712bcSAyushi Smriti                                 const bool updateFile = true)
801b52664e2SAppaRao Puli     {
802fc76b8acSEd Tanous         std::uniform_int_distribution<uint32_t> dist(0);
803fc76b8acSEd Tanous         bmcweb::OpenSSLGenerator gen;
804fc76b8acSEd Tanous 
805b52664e2SAppaRao Puli         std::string id;
806b52664e2SAppaRao Puli 
807b52664e2SAppaRao Puli         int retry = 3;
808e662eae8SEd Tanous         while (retry != 0)
809b52664e2SAppaRao Puli         {
810fc76b8acSEd Tanous             id = std::to_string(dist(gen));
811fc76b8acSEd Tanous             if (gen.error())
812fc76b8acSEd Tanous             {
813fc76b8acSEd Tanous                 retry = 0;
814fc76b8acSEd Tanous                 break;
815fc76b8acSEd Tanous             }
816b52664e2SAppaRao Puli             auto inserted = subscriptionsMap.insert(std::pair(id, subValue));
817b52664e2SAppaRao Puli             if (inserted.second)
818b52664e2SAppaRao Puli             {
819b52664e2SAppaRao Puli                 break;
820b52664e2SAppaRao Puli             }
821b52664e2SAppaRao Puli             --retry;
82223a21a1cSEd Tanous         }
823b52664e2SAppaRao Puli 
824b52664e2SAppaRao Puli         if (retry <= 0)
825b52664e2SAppaRao Puli         {
82662598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to generate random number");
827abb93cddSEd Tanous             return "";
828b52664e2SAppaRao Puli         }
829b52664e2SAppaRao Puli 
83028afb49cSJunLin Chen         std::shared_ptr<persistent_data::UserSubscription> newSub =
83128afb49cSJunLin Chen             std::make_shared<persistent_data::UserSubscription>();
83228afb49cSJunLin Chen         newSub->id = id;
83328afb49cSJunLin Chen         newSub->destinationUrl = subValue->destinationUrl;
83428afb49cSJunLin Chen         newSub->protocol = subValue->protocol;
83528afb49cSJunLin Chen         newSub->retryPolicy = subValue->retryPolicy;
83628afb49cSJunLin Chen         newSub->customText = subValue->customText;
83728afb49cSJunLin Chen         newSub->eventFormatType = subValue->eventFormatType;
83828afb49cSJunLin Chen         newSub->subscriptionType = subValue->subscriptionType;
83928afb49cSJunLin Chen         newSub->registryMsgIds = subValue->registryMsgIds;
84028afb49cSJunLin Chen         newSub->registryPrefixes = subValue->registryPrefixes;
84128afb49cSJunLin Chen         newSub->resourceTypes = subValue->resourceTypes;
84228afb49cSJunLin Chen         newSub->httpHeaders = subValue->httpHeaders;
84328afb49cSJunLin Chen         newSub->metricReportDefinitions = subValue->metricReportDefinitions;
84428afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
84528afb49cSJunLin Chen             .subscriptionsConfigMap.emplace(newSub->id, newSub);
84628afb49cSJunLin Chen 
8477d1cc387SAppaRao Puli         updateNoOfSubscribersCount();
8481bf712bcSAyushi Smriti 
8491bf712bcSAyushi Smriti         if (updateFile)
8501bf712bcSAyushi Smriti         {
851b52664e2SAppaRao Puli             updateSubscriptionData();
8521bf712bcSAyushi Smriti         }
8537f4eb588SAppaRao Puli 
85483328316SEd Tanous         if constexpr (!BMCWEB_REDFISH_DBUS_LOG)
85583328316SEd Tanous         {
8562558979cSP Dheeraj Srujan Kumar             if (redfishLogFilePosition != 0)
8577f4eb588SAppaRao Puli             {
8582558979cSP Dheeraj Srujan Kumar                 cacheRedfishLogFile();
8597f4eb588SAppaRao Puli             }
86083328316SEd Tanous         }
861fe44eb0bSAyushi Smriti         // Update retry configuration.
862fe44eb0bSAyushi Smriti         subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
863fe44eb0bSAyushi Smriti 
8645e44e3d8SAppaRao Puli         // Set Subscription ID for back trace
8655e44e3d8SAppaRao Puli         subValue->setSubscriptionId(id);
866b52664e2SAppaRao Puli         return id;
867b52664e2SAppaRao Puli     }
868b52664e2SAppaRao Puli 
869b52664e2SAppaRao Puli     bool isSubscriptionExist(const std::string& id)
870b52664e2SAppaRao Puli     {
871b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
87255f79e6fSEd Tanous         return obj != subscriptionsMap.end();
873b52664e2SAppaRao Puli     }
874b52664e2SAppaRao Puli 
875b52664e2SAppaRao Puli     void deleteSubscription(const std::string& id)
876b52664e2SAppaRao Puli     {
877b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
878b52664e2SAppaRao Puli         if (obj != subscriptionsMap.end())
879b52664e2SAppaRao Puli         {
880b52664e2SAppaRao Puli             subscriptionsMap.erase(obj);
88128afb49cSJunLin Chen             auto obj2 = persistent_data::EventServiceStore::getInstance()
88228afb49cSJunLin Chen                             .subscriptionsConfigMap.find(id);
88328afb49cSJunLin Chen             persistent_data::EventServiceStore::getInstance()
88428afb49cSJunLin Chen                 .subscriptionsConfigMap.erase(obj2);
8857d1cc387SAppaRao Puli             updateNoOfSubscribersCount();
886b52664e2SAppaRao Puli             updateSubscriptionData();
887b52664e2SAppaRao Puli         }
888b52664e2SAppaRao Puli     }
889b52664e2SAppaRao Puli 
8905e44e3d8SAppaRao Puli     void deleteSseSubscription(const crow::sse_socket::Connection& thisConn)
8915e44e3d8SAppaRao Puli     {
892bdbfae2aSEd Tanous         for (auto it = subscriptionsMap.begin(); it != subscriptionsMap.end();)
8935e44e3d8SAppaRao Puli         {
894bdbfae2aSEd Tanous             std::shared_ptr<Subscription> entry = it->second;
8955e44e3d8SAppaRao Puli             bool entryIsThisConn = entry->matchSseId(thisConn);
8965e44e3d8SAppaRao Puli             if (entryIsThisConn)
8975e44e3d8SAppaRao Puli             {
8985e44e3d8SAppaRao Puli                 persistent_data::EventServiceStore::getInstance()
8995e44e3d8SAppaRao Puli                     .subscriptionsConfigMap.erase(
900bdbfae2aSEd Tanous                         it->second->getSubscriptionId());
901bdbfae2aSEd Tanous                 it = subscriptionsMap.erase(it);
9025e44e3d8SAppaRao Puli                 return;
9035e44e3d8SAppaRao Puli             }
904bdbfae2aSEd Tanous             it++;
9055e44e3d8SAppaRao Puli         }
9065e44e3d8SAppaRao Puli     }
9075e44e3d8SAppaRao Puli 
9085e44e3d8SAppaRao Puli     size_t getNumberOfSubscriptions() const
909b52664e2SAppaRao Puli     {
910b52664e2SAppaRao Puli         return subscriptionsMap.size();
911b52664e2SAppaRao Puli     }
912b52664e2SAppaRao Puli 
9135e44e3d8SAppaRao Puli     size_t getNumberOfSSESubscriptions() const
9145e44e3d8SAppaRao Puli     {
9153544d2a7SEd Tanous         auto size = std::ranges::count_if(
9163544d2a7SEd Tanous             subscriptionsMap,
9175e44e3d8SAppaRao Puli             [](const std::pair<std::string, std::shared_ptr<Subscription>>&
9185e44e3d8SAppaRao Puli                    entry) {
9195e44e3d8SAppaRao Puli             return (entry.second->subscriptionType == subscriptionTypeSSE);
9205e44e3d8SAppaRao Puli         });
9215e44e3d8SAppaRao Puli         return static_cast<size_t>(size);
9225e44e3d8SAppaRao Puli     }
9235e44e3d8SAppaRao Puli 
924b52664e2SAppaRao Puli     std::vector<std::string> getAllIDs()
925b52664e2SAppaRao Puli     {
926b52664e2SAppaRao Puli         std::vector<std::string> idList;
927b52664e2SAppaRao Puli         for (const auto& it : subscriptionsMap)
928b52664e2SAppaRao Puli         {
929b52664e2SAppaRao Puli             idList.emplace_back(it.first);
930b52664e2SAppaRao Puli         }
931b52664e2SAppaRao Puli         return idList;
932b52664e2SAppaRao Puli     }
933b52664e2SAppaRao Puli 
9346ba8c82eSsunharis_in     bool sendTestEventLog()
9350b4bdd93SAppaRao Puli     {
9365e44e3d8SAppaRao Puli         for (const auto& it : subscriptionsMap)
9370b4bdd93SAppaRao Puli         {
9380b4bdd93SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
9396ba8c82eSsunharis_in             if (!entry->sendTestEventLog())
9406ba8c82eSsunharis_in             {
9416ba8c82eSsunharis_in                 return false;
9420b4bdd93SAppaRao Puli             }
9430b4bdd93SAppaRao Puli         }
9446ba8c82eSsunharis_in         return true;
9456ba8c82eSsunharis_in     }
946e9a14131SAppaRao Puli 
947613dabeaSEd Tanous     void sendEvent(nlohmann::json eventMessage, const std::string& origin,
948613dabeaSEd Tanous                    const std::string& resType)
94996330b99SSunitha Harish     {
950dbb59d4dSEd Tanous         if (!serviceEnabled || (noOfEventLogSubscribers == 0U))
9516ba8c82eSsunharis_in         {
95262598e31SEd Tanous             BMCWEB_LOG_DEBUG("EventService disabled or no Subscriptions.");
9536ba8c82eSsunharis_in             return;
9546ba8c82eSsunharis_in         }
95596330b99SSunitha Harish         nlohmann::json eventRecord = nlohmann::json::array();
95696330b99SSunitha Harish 
957613dabeaSEd Tanous         eventMessage["EventId"] = eventId;
958613dabeaSEd Tanous         // MemberId is 0 : since we are sending one event record.
959613dabeaSEd Tanous         eventMessage["MemberId"] = 0;
960613dabeaSEd Tanous         eventMessage["EventTimestamp"] =
961613dabeaSEd Tanous             redfish::time_utils::getDateTimeOffsetNow().first;
962613dabeaSEd Tanous         eventMessage["OriginOfCondition"] = origin;
963613dabeaSEd Tanous 
964613dabeaSEd Tanous         eventRecord.emplace_back(std::move(eventMessage));
96596330b99SSunitha Harish 
9665e44e3d8SAppaRao Puli         for (const auto& it : subscriptionsMap)
96796330b99SSunitha Harish         {
96896330b99SSunitha Harish             std::shared_ptr<Subscription> entry = it.second;
96996330b99SSunitha Harish             bool isSubscribed = false;
97096330b99SSunitha Harish             // Search the resourceTypes list for the subscription.
97196330b99SSunitha Harish             // If resourceTypes list is empty, don't filter events
97296330b99SSunitha Harish             // send everything.
97326f6976fSEd Tanous             if (!entry->resourceTypes.empty())
97496330b99SSunitha Harish             {
9753174e4dfSEd Tanous                 for (const auto& resource : entry->resourceTypes)
97696330b99SSunitha Harish                 {
97796330b99SSunitha Harish                     if (resType == resource)
97896330b99SSunitha Harish                     {
97962598e31SEd Tanous                         BMCWEB_LOG_INFO(
98062598e31SEd Tanous                             "ResourceType {} found in the subscribed list",
98162598e31SEd Tanous                             resource);
98296330b99SSunitha Harish                         isSubscribed = true;
98396330b99SSunitha Harish                         break;
98496330b99SSunitha Harish                     }
98596330b99SSunitha Harish                 }
98696330b99SSunitha Harish             }
98796330b99SSunitha Harish             else // resourceTypes list is empty.
98896330b99SSunitha Harish             {
98996330b99SSunitha Harish                 isSubscribed = true;
99096330b99SSunitha Harish             }
99196330b99SSunitha Harish             if (isSubscribed)
99296330b99SSunitha Harish             {
993613dabeaSEd Tanous                 nlohmann::json msgJson;
994613dabeaSEd Tanous 
995613dabeaSEd Tanous                 msgJson["@odata.type"] = "#Event.v1_4_0.Event";
996613dabeaSEd Tanous                 msgJson["Name"] = "Event Log";
997613dabeaSEd Tanous                 msgJson["Id"] = eventId;
998613dabeaSEd Tanous                 msgJson["Events"] = eventRecord;
999f52c03c1SCarson Labrado 
1000f52c03c1SCarson Labrado                 std::string strMsg = msgJson.dump(
1001f52c03c1SCarson Labrado                     2, ' ', true, nlohmann::json::error_handler_t::replace);
10025e44e3d8SAppaRao Puli                 entry->sendEvent(std::move(strMsg));
10038ece0e45SEd Tanous                 eventId++; // increment the eventId
100496330b99SSunitha Harish             }
100596330b99SSunitha Harish             else
100696330b99SSunitha Harish             {
100762598e31SEd Tanous                 BMCWEB_LOG_INFO("Not subscribed to this resource");
100896330b99SSunitha Harish             }
100996330b99SSunitha Harish         }
101096330b99SSunitha Harish     }
101196330b99SSunitha Harish 
10122558979cSP Dheeraj Srujan Kumar     void resetRedfishFilePosition()
10137f4eb588SAppaRao Puli     {
10142558979cSP Dheeraj Srujan Kumar         // Control would be here when Redfish file is created.
10152558979cSP Dheeraj Srujan Kumar         // Reset File Position as new file is created
10162558979cSP Dheeraj Srujan Kumar         redfishLogFilePosition = 0;
10172558979cSP Dheeraj Srujan Kumar     }
10182558979cSP Dheeraj Srujan Kumar 
10192558979cSP Dheeraj Srujan Kumar     void cacheRedfishLogFile()
10202558979cSP Dheeraj Srujan Kumar     {
10212558979cSP Dheeraj Srujan Kumar         // Open the redfish file and read till the last record.
10222558979cSP Dheeraj Srujan Kumar 
10237f4eb588SAppaRao Puli         std::ifstream logStream(redfishEventLogFile);
10247f4eb588SAppaRao Puli         if (!logStream.good())
10257f4eb588SAppaRao Puli         {
102662598e31SEd Tanous             BMCWEB_LOG_ERROR(" Redfish log file open failed ");
10277f4eb588SAppaRao Puli             return;
10287f4eb588SAppaRao Puli         }
10297f4eb588SAppaRao Puli         std::string logEntry;
10307f4eb588SAppaRao Puli         while (std::getline(logStream, logEntry))
10317f4eb588SAppaRao Puli         {
10322558979cSP Dheeraj Srujan Kumar             redfishLogFilePosition = logStream.tellg();
10337f4eb588SAppaRao Puli         }
10347f4eb588SAppaRao Puli     }
10357f4eb588SAppaRao Puli 
10367f4eb588SAppaRao Puli     void readEventLogsFromFile()
10377f4eb588SAppaRao Puli     {
10387f4eb588SAppaRao Puli         std::ifstream logStream(redfishEventLogFile);
10397f4eb588SAppaRao Puli         if (!logStream.good())
10407f4eb588SAppaRao Puli         {
104162598e31SEd Tanous             BMCWEB_LOG_ERROR(" Redfish log file open failed");
10427f4eb588SAppaRao Puli             return;
10437f4eb588SAppaRao Puli         }
10447f4eb588SAppaRao Puli 
10457f4eb588SAppaRao Puli         std::vector<EventLogObjectsType> eventRecords;
10467f4eb588SAppaRao Puli 
10477f4eb588SAppaRao Puli         std::string logEntry;
10482558979cSP Dheeraj Srujan Kumar 
10492558979cSP Dheeraj Srujan Kumar         // Get the read pointer to the next log to be read.
10502558979cSP Dheeraj Srujan Kumar         logStream.seekg(redfishLogFilePosition);
10512558979cSP Dheeraj Srujan Kumar 
10527f4eb588SAppaRao Puli         while (std::getline(logStream, logEntry))
10537f4eb588SAppaRao Puli         {
10542558979cSP Dheeraj Srujan Kumar             // Update Pointer position
10552558979cSP Dheeraj Srujan Kumar             redfishLogFilePosition = logStream.tellg();
10562558979cSP Dheeraj Srujan Kumar 
10572558979cSP Dheeraj Srujan Kumar             std::string idStr;
10582558979cSP Dheeraj Srujan Kumar             if (!event_log::getUniqueEntryID(logEntry, idStr))
10597f4eb588SAppaRao Puli             {
10607f4eb588SAppaRao Puli                 continue;
10617f4eb588SAppaRao Puli             }
10627f4eb588SAppaRao Puli 
1063e662eae8SEd Tanous             if (!serviceEnabled || noOfEventLogSubscribers == 0)
10647f4eb588SAppaRao Puli             {
10652558979cSP Dheeraj Srujan Kumar                 // If Service is not enabled, no need to compute
10662558979cSP Dheeraj Srujan Kumar                 // the remaining items below.
10672558979cSP Dheeraj Srujan Kumar                 // But, Loop must continue to keep track of Timestamp
10687f4eb588SAppaRao Puli                 continue;
10697f4eb588SAppaRao Puli             }
10707f4eb588SAppaRao Puli 
10717f4eb588SAppaRao Puli             std::string timestamp;
10727f4eb588SAppaRao Puli             std::string messageID;
10735e715de6SAppaRao Puli             std::vector<std::string> messageArgs;
10747f4eb588SAppaRao Puli             if (event_log::getEventLogParams(logEntry, timestamp, messageID,
10757f4eb588SAppaRao Puli                                              messageArgs) != 0)
10767f4eb588SAppaRao Puli             {
107762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Read eventLog entry params failed");
10787f4eb588SAppaRao Puli                 continue;
10797f4eb588SAppaRao Puli             }
10807f4eb588SAppaRao Puli 
10817f4eb588SAppaRao Puli             std::string registryName;
10827f4eb588SAppaRao Puli             std::string messageKey;
10837f4eb588SAppaRao Puli             event_log::getRegistryAndMessageKey(messageID, registryName,
10847f4eb588SAppaRao Puli                                                 messageKey);
10857f4eb588SAppaRao Puli             if (registryName.empty() || messageKey.empty())
10867f4eb588SAppaRao Puli             {
10877f4eb588SAppaRao Puli                 continue;
10887f4eb588SAppaRao Puli             }
10897f4eb588SAppaRao Puli 
10907f4eb588SAppaRao Puli             eventRecords.emplace_back(idStr, timestamp, messageID, registryName,
10917f4eb588SAppaRao Puli                                       messageKey, messageArgs);
10927f4eb588SAppaRao Puli         }
10937f4eb588SAppaRao Puli 
1094e662eae8SEd Tanous         if (!serviceEnabled || noOfEventLogSubscribers == 0)
10952558979cSP Dheeraj Srujan Kumar         {
109662598e31SEd Tanous             BMCWEB_LOG_DEBUG("EventService disabled or no Subscriptions.");
10972558979cSP Dheeraj Srujan Kumar             return;
10982558979cSP Dheeraj Srujan Kumar         }
10992558979cSP Dheeraj Srujan Kumar 
11002558979cSP Dheeraj Srujan Kumar         if (eventRecords.empty())
11012558979cSP Dheeraj Srujan Kumar         {
11022558979cSP Dheeraj Srujan Kumar             // No Records to send
110362598e31SEd Tanous             BMCWEB_LOG_DEBUG("No log entries available to be transferred.");
11042558979cSP Dheeraj Srujan Kumar             return;
11052558979cSP Dheeraj Srujan Kumar         }
11062558979cSP Dheeraj Srujan Kumar 
11075e44e3d8SAppaRao Puli         for (const auto& it : subscriptionsMap)
11087f4eb588SAppaRao Puli         {
11097f4eb588SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
11107f4eb588SAppaRao Puli             if (entry->eventFormatType == "Event")
11117f4eb588SAppaRao Puli             {
11127f4eb588SAppaRao Puli                 entry->filterAndSendEventLogs(eventRecords);
11137f4eb588SAppaRao Puli             }
11147f4eb588SAppaRao Puli         }
11157f4eb588SAppaRao Puli     }
11167f4eb588SAppaRao Puli 
11177f4eb588SAppaRao Puli     static void watchRedfishEventLogFile()
11187f4eb588SAppaRao Puli     {
11196a9f85f9SAppaRao Puli         if (!inotifyConn)
11207f4eb588SAppaRao Puli         {
11217f4eb588SAppaRao Puli             return;
11227f4eb588SAppaRao Puli         }
11237f4eb588SAppaRao Puli 
11247f4eb588SAppaRao Puli         static std::array<char, 1024> readBuffer;
11257f4eb588SAppaRao Puli 
1126002d39b4SEd Tanous         inotifyConn->async_read_some(boost::asio::buffer(readBuffer),
11277f4eb588SAppaRao Puli                                      [&](const boost::system::error_code& ec,
11287f4eb588SAppaRao Puli                                          const std::size_t& bytesTransferred) {
11299ed3f90aSEd Tanous             if (ec == boost::asio::error::operation_aborted)
11309ed3f90aSEd Tanous             {
11319ed3f90aSEd Tanous                 BMCWEB_LOG_DEBUG("Inotify was canceled (shutdown?)");
11329ed3f90aSEd Tanous                 return;
11339ed3f90aSEd Tanous             }
11347f4eb588SAppaRao Puli             if (ec)
11357f4eb588SAppaRao Puli             {
113662598e31SEd Tanous                 BMCWEB_LOG_ERROR("Callback Error: {}", ec.message());
11377f4eb588SAppaRao Puli                 return;
11387f4eb588SAppaRao Puli             }
11397f4eb588SAppaRao Puli             std::size_t index = 0;
1140b792cc56SAppaRao Puli             while ((index + iEventSize) <= bytesTransferred)
11417f4eb588SAppaRao Puli             {
1142d3a9e084SEd Tanous                 struct inotify_event event
1143d3a9e084SEd Tanous                 {};
1144b792cc56SAppaRao Puli                 std::memcpy(&event, &readBuffer[index], iEventSize);
1145b792cc56SAppaRao Puli                 if (event.wd == dirWatchDesc)
1146b792cc56SAppaRao Puli                 {
1147b792cc56SAppaRao Puli                     if ((event.len == 0) ||
1148b792cc56SAppaRao Puli                         (index + iEventSize + event.len > bytesTransferred))
1149b792cc56SAppaRao Puli                     {
1150b792cc56SAppaRao Puli                         index += (iEventSize + event.len);
1151b792cc56SAppaRao Puli                         continue;
1152b792cc56SAppaRao Puli                     }
1153b792cc56SAppaRao Puli 
11544f568f74SJiaqing Zhao                     std::string fileName(&readBuffer[index + iEventSize]);
11554f568f74SJiaqing Zhao                     if (fileName != "redfish")
1156b792cc56SAppaRao Puli                     {
1157b792cc56SAppaRao Puli                         index += (iEventSize + event.len);
1158b792cc56SAppaRao Puli                         continue;
1159b792cc56SAppaRao Puli                     }
1160b792cc56SAppaRao Puli 
116162598e31SEd Tanous                     BMCWEB_LOG_DEBUG(
116262598e31SEd Tanous                         "Redfish log file created/deleted. event.name: {}",
116362598e31SEd Tanous                         fileName);
1164b792cc56SAppaRao Puli                     if (event.mask == IN_CREATE)
1165b792cc56SAppaRao Puli                     {
1166b792cc56SAppaRao Puli                         if (fileWatchDesc != -1)
1167b792cc56SAppaRao Puli                         {
116862598e31SEd Tanous                             BMCWEB_LOG_DEBUG(
116962598e31SEd Tanous                                 "Remove and Add inotify watcher on "
117062598e31SEd Tanous                                 "redfish event log file");
1171016761afSAppaRao Puli                             // Remove existing inotify watcher and add
1172016761afSAppaRao Puli                             // with new redfish event log file.
1173016761afSAppaRao Puli                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1174016761afSAppaRao Puli                             fileWatchDesc = -1;
1175b792cc56SAppaRao Puli                         }
1176b792cc56SAppaRao Puli 
1177b792cc56SAppaRao Puli                         fileWatchDesc = inotify_add_watch(
1178b792cc56SAppaRao Puli                             inotifyFd, redfishEventLogFile, IN_MODIFY);
1179b792cc56SAppaRao Puli                         if (fileWatchDesc == -1)
1180b792cc56SAppaRao Puli                         {
118162598e31SEd Tanous                             BMCWEB_LOG_ERROR("inotify_add_watch failed for "
118262598e31SEd Tanous                                              "redfish log file.");
1183b792cc56SAppaRao Puli                             return;
1184b792cc56SAppaRao Puli                         }
1185b792cc56SAppaRao Puli 
1186b792cc56SAppaRao Puli                         EventServiceManager::getInstance()
11872558979cSP Dheeraj Srujan Kumar                             .resetRedfishFilePosition();
1188b792cc56SAppaRao Puli                         EventServiceManager::getInstance()
1189b792cc56SAppaRao Puli                             .readEventLogsFromFile();
1190b792cc56SAppaRao Puli                     }
1191b792cc56SAppaRao Puli                     else if ((event.mask == IN_DELETE) ||
1192b792cc56SAppaRao Puli                              (event.mask == IN_MOVED_TO))
1193b792cc56SAppaRao Puli                     {
1194b792cc56SAppaRao Puli                         if (fileWatchDesc != -1)
1195b792cc56SAppaRao Puli                         {
1196b792cc56SAppaRao Puli                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1197b792cc56SAppaRao Puli                             fileWatchDesc = -1;
1198b792cc56SAppaRao Puli                         }
1199b792cc56SAppaRao Puli                     }
1200b792cc56SAppaRao Puli                 }
1201b792cc56SAppaRao Puli                 else if (event.wd == fileWatchDesc)
1202b792cc56SAppaRao Puli                 {
1203b792cc56SAppaRao Puli                     if (event.mask == IN_MODIFY)
12047f4eb588SAppaRao Puli                     {
12057f4eb588SAppaRao Puli                         EventServiceManager::getInstance()
12067f4eb588SAppaRao Puli                             .readEventLogsFromFile();
12077f4eb588SAppaRao Puli                     }
1208b792cc56SAppaRao Puli                 }
1209b792cc56SAppaRao Puli                 index += (iEventSize + event.len);
12107f4eb588SAppaRao Puli             }
12117f4eb588SAppaRao Puli 
12127f4eb588SAppaRao Puli             watchRedfishEventLogFile();
12137f4eb588SAppaRao Puli         });
12147f4eb588SAppaRao Puli     }
12157f4eb588SAppaRao Puli 
12167f4eb588SAppaRao Puli     static int startEventLogMonitor(boost::asio::io_context& ioc)
12177f4eb588SAppaRao Puli     {
121823a21a1cSEd Tanous         inotifyConn.emplace(ioc);
1219b792cc56SAppaRao Puli         inotifyFd = inotify_init1(IN_NONBLOCK);
1220b792cc56SAppaRao Puli         if (inotifyFd == -1)
12217f4eb588SAppaRao Puli         {
122262598e31SEd Tanous             BMCWEB_LOG_ERROR("inotify_init1 failed.");
12237f4eb588SAppaRao Puli             return -1;
12247f4eb588SAppaRao Puli         }
1225b792cc56SAppaRao Puli 
1226b792cc56SAppaRao Puli         // Add watch on directory to handle redfish event log file
1227b792cc56SAppaRao Puli         // create/delete.
1228b792cc56SAppaRao Puli         dirWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogDir,
1229b792cc56SAppaRao Puli                                          IN_CREATE | IN_MOVED_TO | IN_DELETE);
1230b792cc56SAppaRao Puli         if (dirWatchDesc == -1)
12317f4eb588SAppaRao Puli         {
123262598e31SEd Tanous             BMCWEB_LOG_ERROR(
123362598e31SEd Tanous                 "inotify_add_watch failed for event log directory.");
12347f4eb588SAppaRao Puli             return -1;
12357f4eb588SAppaRao Puli         }
12367f4eb588SAppaRao Puli 
1237b792cc56SAppaRao Puli         // Watch redfish event log file for modifications.
123889492a15SPatrick Williams         fileWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogFile,
123989492a15SPatrick Williams                                           IN_MODIFY);
1240b792cc56SAppaRao Puli         if (fileWatchDesc == -1)
1241b792cc56SAppaRao Puli         {
124262598e31SEd Tanous             BMCWEB_LOG_ERROR("inotify_add_watch failed for redfish log file.");
1243b792cc56SAppaRao Puli             // Don't return error if file not exist.
1244b792cc56SAppaRao Puli             // Watch on directory will handle create/delete of file.
1245b792cc56SAppaRao Puli         }
1246b792cc56SAppaRao Puli 
12477f4eb588SAppaRao Puli         // monitor redfish event log file
1248b792cc56SAppaRao Puli         inotifyConn->assign(inotifyFd);
12497f4eb588SAppaRao Puli         watchRedfishEventLogFile();
12507f4eb588SAppaRao Puli 
12517f4eb588SAppaRao Puli         return 0;
12527f4eb588SAppaRao Puli     }
12537f4eb588SAppaRao Puli 
12549ed3f90aSEd Tanous     static void stopEventLogMonitor()
12559ed3f90aSEd Tanous     {
12569ed3f90aSEd Tanous         inotifyConn.reset();
12579ed3f90aSEd Tanous     }
12589ed3f90aSEd Tanous 
125959d494eeSPatrick Williams     static void getReadingsForReport(sdbusplus::message_t& msg)
1260156d6b00SAppaRao Puli     {
126156d2396dSEd Tanous         if (msg.is_method_error())
126256d2396dSEd Tanous         {
126362598e31SEd Tanous             BMCWEB_LOG_ERROR("TelemetryMonitor Signal error");
126456d2396dSEd Tanous             return;
126556d2396dSEd Tanous         }
126656d2396dSEd Tanous 
1267c0353249SWludzik, Jozef         sdbusplus::message::object_path path(msg.get_path());
1268c0353249SWludzik, Jozef         std::string id = path.filename();
1269c0353249SWludzik, Jozef         if (id.empty())
1270156d6b00SAppaRao Puli         {
127162598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to get Id from path");
1272156d6b00SAppaRao Puli             return;
1273156d6b00SAppaRao Puli         }
1274156d6b00SAppaRao Puli 
1275c0353249SWludzik, Jozef         std::string interface;
1276b9d36b47SEd Tanous         dbus::utility::DBusPropertiesMap props;
1277c0353249SWludzik, Jozef         std::vector<std::string> invalidProps;
1278c0353249SWludzik, Jozef         msg.read(interface, props, invalidProps);
1279c0353249SWludzik, Jozef 
12803544d2a7SEd Tanous         auto found = std::ranges::find_if(
12813544d2a7SEd Tanous             props, [](const auto& x) { return x.first == "Readings"; });
1282c0353249SWludzik, Jozef         if (found == props.end())
1283156d6b00SAppaRao Puli         {
128462598e31SEd Tanous             BMCWEB_LOG_INFO("Failed to get Readings from Report properties");
1285156d6b00SAppaRao Puli             return;
1286156d6b00SAppaRao Puli         }
1287156d6b00SAppaRao Puli 
12881e1e598dSJonathan Doman         const telemetry::TimestampReadings* readings =
12891e1e598dSJonathan Doman             std::get_if<telemetry::TimestampReadings>(&found->second);
1290e662eae8SEd Tanous         if (readings == nullptr)
12911e1e598dSJonathan Doman         {
129262598e31SEd Tanous             BMCWEB_LOG_INFO("Failed to get Readings from Report properties");
12931e1e598dSJonathan Doman             return;
12941e1e598dSJonathan Doman         }
12951e1e598dSJonathan Doman 
1296156d6b00SAppaRao Puli         for (const auto& it :
1297156d6b00SAppaRao Puli              EventServiceManager::getInstance().subscriptionsMap)
1298156d6b00SAppaRao Puli         {
1299e05aec50SEd Tanous             Subscription& entry = *it.second;
1300c0353249SWludzik, Jozef             if (entry.eventFormatType == metricReportFormatType)
1301156d6b00SAppaRao Puli             {
13021e1e598dSJonathan Doman                 entry.filterAndSendReports(id, *readings);
1303156d6b00SAppaRao Puli             }
1304156d6b00SAppaRao Puli         }
1305156d6b00SAppaRao Puli     }
1306156d6b00SAppaRao Puli 
1307156d6b00SAppaRao Puli     void unregisterMetricReportSignal()
1308156d6b00SAppaRao Puli     {
13097d1cc387SAppaRao Puli         if (matchTelemetryMonitor)
13107d1cc387SAppaRao Puli         {
131162598e31SEd Tanous             BMCWEB_LOG_DEBUG("Metrics report signal - Unregister");
1312156d6b00SAppaRao Puli             matchTelemetryMonitor.reset();
1313156d6b00SAppaRao Puli             matchTelemetryMonitor = nullptr;
1314156d6b00SAppaRao Puli         }
13157d1cc387SAppaRao Puli     }
1316156d6b00SAppaRao Puli 
1317156d6b00SAppaRao Puli     void registerMetricReportSignal()
1318156d6b00SAppaRao Puli     {
13197d1cc387SAppaRao Puli         if (!serviceEnabled || matchTelemetryMonitor)
1320156d6b00SAppaRao Puli         {
132162598e31SEd Tanous             BMCWEB_LOG_DEBUG("Not registering metric report signal.");
1322156d6b00SAppaRao Puli             return;
1323156d6b00SAppaRao Puli         }
1324156d6b00SAppaRao Puli 
132562598e31SEd Tanous         BMCWEB_LOG_DEBUG("Metrics report signal - Register");
1326c0353249SWludzik, Jozef         std::string matchStr = "type='signal',member='PropertiesChanged',"
1327c0353249SWludzik, Jozef                                "interface='org.freedesktop.DBus.Properties',"
1328c0353249SWludzik, Jozef                                "arg0=xyz.openbmc_project.Telemetry.Report";
1329156d6b00SAppaRao Puli 
133059d494eeSPatrick Williams         matchTelemetryMonitor = std::make_shared<sdbusplus::bus::match_t>(
133156d2396dSEd Tanous             *crow::connections::systemBus, matchStr, getReadingsForReport);
1332156d6b00SAppaRao Puli     }
133323a21a1cSEd Tanous };
1334b52664e2SAppaRao Puli 
1335b52664e2SAppaRao Puli } // namespace redfish
1336