xref: /openbmc/bmcweb/features/redfish/include/event_service_manager.hpp (revision 93cf0ac2c7921d3344fa112f667c47a838e3b7d6)
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"
297f4eb588SAppaRao Puli 
307f4eb588SAppaRao Puli #include <sys/inotify.h>
31b52664e2SAppaRao Puli 
32fb4fd5d4SZhenfei Tai #include <boost/asio/io_context.hpp>
33b52664e2SAppaRao Puli #include <boost/container/flat_map.hpp>
34ef4c65b7SEd Tanous #include <boost/url/format.hpp>
35b5b40605Snitroglycerine #include <sdbusplus/bus/match.hpp>
361214b7e7SGunnar Mills 
375e44e3d8SAppaRao Puli #include <algorithm>
38b52664e2SAppaRao Puli #include <cstdlib>
39b52664e2SAppaRao Puli #include <ctime>
401bf712bcSAyushi Smriti #include <fstream>
41b52664e2SAppaRao Puli #include <memory>
423544d2a7SEd Tanous #include <ranges>
4326702d01SEd Tanous #include <span>
44b52664e2SAppaRao Puli 
45b52664e2SAppaRao Puli namespace redfish
46b52664e2SAppaRao Puli {
47156d6b00SAppaRao Puli 
48156d6b00SAppaRao Puli using ReadingsObjType =
4993f5d7c7SWludzik, Jozef     std::vector<std::tuple<std::string, std::string, double, int32_t>>;
50156d6b00SAppaRao Puli 
51156d6b00SAppaRao Puli static constexpr const char* eventFormatType = "Event";
52156d6b00SAppaRao Puli static constexpr const char* metricReportFormatType = "MetricReport";
53156d6b00SAppaRao Puli 
545e44e3d8SAppaRao Puli static constexpr const char* subscriptionTypeSSE = "SSE";
551bf712bcSAyushi Smriti static constexpr const char* eventServiceFile =
561bf712bcSAyushi Smriti     "/var/lib/bmcweb/eventservice_config.json";
571bf712bcSAyushi Smriti 
585e44e3d8SAppaRao Puli static constexpr const uint8_t maxNoOfSubscriptions = 20;
595e44e3d8SAppaRao Puli static constexpr const uint8_t maxNoOfSSESubscriptions = 10;
605e44e3d8SAppaRao Puli 
614642bf8fSGeorge Liu #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
62cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
634642bf8fSGeorge Liu static std::optional<boost::asio::posix::stream_descriptor> inotifyConn;
644642bf8fSGeorge Liu static constexpr const char* redfishEventLogDir = "/var/log";
654642bf8fSGeorge Liu static constexpr const char* redfishEventLogFile = "/var/log/redfish";
664642bf8fSGeorge Liu static constexpr const size_t iEventSize = sizeof(inotify_event);
67cf9e417dSEd Tanous 
68cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
694642bf8fSGeorge Liu static int inotifyFd = -1;
70cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
714642bf8fSGeorge Liu static int dirWatchDesc = -1;
72cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
734642bf8fSGeorge Liu static int fileWatchDesc = -1;
744642bf8fSGeorge Liu 
754642bf8fSGeorge Liu // <ID, timestamp, RedfishLogId, registryPrefix, MessageId, MessageArgs>
764642bf8fSGeorge Liu using EventLogObjectsType =
774642bf8fSGeorge Liu     std::tuple<std::string, std::string, std::string, std::string, std::string,
784642bf8fSGeorge Liu                std::vector<std::string>>;
794642bf8fSGeorge Liu 
80fffb8c1fSEd Tanous namespace registries
814642bf8fSGeorge Liu {
827f4eb588SAppaRao Puli static const Message*
837f4eb588SAppaRao Puli     getMsgFromRegistry(const std::string& messageKey,
8426702d01SEd Tanous                        const std::span<const MessageEntry>& registry)
857f4eb588SAppaRao Puli {
863544d2a7SEd Tanous     std::span<const MessageEntry>::iterator messageIt = std::ranges::find_if(
873544d2a7SEd Tanous         registry, [&messageKey](const MessageEntry& messageEntry) {
8855f79e6fSEd Tanous         return messageKey == messageEntry.first;
897f4eb588SAppaRao Puli     });
9026702d01SEd Tanous     if (messageIt != registry.end())
917f4eb588SAppaRao Puli     {
927f4eb588SAppaRao Puli         return &messageIt->second;
937f4eb588SAppaRao Puli     }
947f4eb588SAppaRao Puli 
957f4eb588SAppaRao Puli     return nullptr;
967f4eb588SAppaRao Puli }
977f4eb588SAppaRao Puli 
9826ccae32SEd Tanous static const Message* formatMessage(std::string_view messageID)
997f4eb588SAppaRao Puli {
1007f4eb588SAppaRao Puli     // Redfish MessageIds are in the form
1017f4eb588SAppaRao Puli     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
1027f4eb588SAppaRao Puli     // the right Message
1037f4eb588SAppaRao Puli     std::vector<std::string> fields;
1047f4eb588SAppaRao Puli     fields.reserve(4);
10550ebd4afSEd Tanous 
10650ebd4afSEd Tanous     bmcweb::split(fields, messageID, '.');
1077f4eb588SAppaRao Puli     if (fields.size() != 4)
1087f4eb588SAppaRao Puli     {
1097f4eb588SAppaRao Puli         return nullptr;
1107f4eb588SAppaRao Puli     }
11102cad96eSEd Tanous     const std::string& registryName = fields[0];
11202cad96eSEd Tanous     const std::string& messageKey = fields[3];
1137f4eb588SAppaRao Puli 
1147f4eb588SAppaRao Puli     // Find the right registry and check it for the MessageKey
115b304bd79SP Dheeraj Srujan Kumar     return getMsgFromRegistry(messageKey, getRegistryFromPrefix(registryName));
1167f4eb588SAppaRao Puli }
117fffb8c1fSEd Tanous } // namespace registries
1187f4eb588SAppaRao Puli 
1197f4eb588SAppaRao Puli namespace event_log
1207f4eb588SAppaRao Puli {
1212558979cSP Dheeraj Srujan Kumar inline bool getUniqueEntryID(const std::string& logEntry, std::string& entryID)
1227f4eb588SAppaRao Puli {
1237f4eb588SAppaRao Puli     static time_t prevTs = 0;
1247f4eb588SAppaRao Puli     static int index = 0;
1257f4eb588SAppaRao Puli 
1267f4eb588SAppaRao Puli     // Get the entry timestamp
1277f4eb588SAppaRao Puli     std::time_t curTs = 0;
1287f4eb588SAppaRao Puli     std::tm timeStruct = {};
1297f4eb588SAppaRao Puli     std::istringstream entryStream(logEntry);
1307f4eb588SAppaRao Puli     if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1317f4eb588SAppaRao Puli     {
1327f4eb588SAppaRao Puli         curTs = std::mktime(&timeStruct);
1337f4eb588SAppaRao Puli         if (curTs == -1)
1347f4eb588SAppaRao Puli         {
1357f4eb588SAppaRao Puli             return false;
1367f4eb588SAppaRao Puli         }
1377f4eb588SAppaRao Puli     }
1387f4eb588SAppaRao Puli     // If the timestamp isn't unique, increment the index
1397f4eb588SAppaRao Puli     index = (curTs == prevTs) ? index + 1 : 0;
1407f4eb588SAppaRao Puli 
1417f4eb588SAppaRao Puli     // Save the timestamp
1427f4eb588SAppaRao Puli     prevTs = curTs;
1437f4eb588SAppaRao Puli 
1447f4eb588SAppaRao Puli     entryID = std::to_string(curTs);
1457f4eb588SAppaRao Puli     if (index > 0)
1467f4eb588SAppaRao Puli     {
1477f4eb588SAppaRao Puli         entryID += "_" + std::to_string(index);
1487f4eb588SAppaRao Puli     }
1497f4eb588SAppaRao Puli     return true;
1507f4eb588SAppaRao Puli }
1517f4eb588SAppaRao Puli 
15223a21a1cSEd Tanous inline int getEventLogParams(const std::string& logEntry,
15323a21a1cSEd Tanous                              std::string& timestamp, std::string& messageID,
1545e715de6SAppaRao Puli                              std::vector<std::string>& messageArgs)
1557f4eb588SAppaRao Puli {
1567f4eb588SAppaRao Puli     // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
1577f4eb588SAppaRao Puli     // First get the Timestamp
158f23b7296SEd Tanous     size_t space = logEntry.find_first_of(' ');
1597f4eb588SAppaRao Puli     if (space == std::string::npos)
1607f4eb588SAppaRao Puli     {
1617f4eb588SAppaRao Puli         return -EINVAL;
1627f4eb588SAppaRao Puli     }
1637f4eb588SAppaRao Puli     timestamp = logEntry.substr(0, space);
1647f4eb588SAppaRao Puli     // Then get the log contents
165f23b7296SEd Tanous     size_t entryStart = logEntry.find_first_not_of(' ', space);
1667f4eb588SAppaRao Puli     if (entryStart == std::string::npos)
1677f4eb588SAppaRao Puli     {
1687f4eb588SAppaRao Puli         return -EINVAL;
1697f4eb588SAppaRao Puli     }
1707f4eb588SAppaRao Puli     std::string_view entry(logEntry);
1717f4eb588SAppaRao Puli     entry.remove_prefix(entryStart);
1727f4eb588SAppaRao Puli     // Use split to separate the entry into its fields
1737f4eb588SAppaRao Puli     std::vector<std::string> logEntryFields;
17450ebd4afSEd Tanous     bmcweb::split(logEntryFields, entry, ',');
1757f4eb588SAppaRao Puli     // We need at least a MessageId to be valid
17626f6976fSEd Tanous     if (logEntryFields.empty())
1777f4eb588SAppaRao Puli     {
1787f4eb588SAppaRao Puli         return -EINVAL;
1797f4eb588SAppaRao Puli     }
1807f4eb588SAppaRao Puli     messageID = logEntryFields[0];
1817f4eb588SAppaRao Puli 
1827f4eb588SAppaRao Puli     // Get the MessageArgs from the log if there are any
1837f4eb588SAppaRao Puli     if (logEntryFields.size() > 1)
1847f4eb588SAppaRao Puli     {
18502cad96eSEd Tanous         const std::string& messageArgsStart = logEntryFields[1];
1867f4eb588SAppaRao Puli         // If the first string is empty, assume there are no MessageArgs
1877f4eb588SAppaRao Puli         if (!messageArgsStart.empty())
1887f4eb588SAppaRao Puli         {
1895e715de6SAppaRao Puli             messageArgs.assign(logEntryFields.begin() + 1,
1905e715de6SAppaRao Puli                                logEntryFields.end());
1917f4eb588SAppaRao Puli         }
1927f4eb588SAppaRao Puli     }
1937f4eb588SAppaRao Puli 
1947f4eb588SAppaRao Puli     return 0;
1957f4eb588SAppaRao Puli }
1967f4eb588SAppaRao Puli 
19723a21a1cSEd Tanous inline void getRegistryAndMessageKey(const std::string& messageID,
1987f4eb588SAppaRao Puli                                      std::string& registryName,
1997f4eb588SAppaRao Puli                                      std::string& messageKey)
2007f4eb588SAppaRao Puli {
2017f4eb588SAppaRao Puli     // Redfish MessageIds are in the form
2027f4eb588SAppaRao Puli     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
2037f4eb588SAppaRao Puli     // the right Message
2047f4eb588SAppaRao Puli     std::vector<std::string> fields;
2057f4eb588SAppaRao Puli     fields.reserve(4);
20650ebd4afSEd Tanous     bmcweb::split(fields, messageID, '.');
2077f4eb588SAppaRao Puli     if (fields.size() == 4)
2087f4eb588SAppaRao Puli     {
2097f4eb588SAppaRao Puli         registryName = fields[0];
2107f4eb588SAppaRao Puli         messageKey = fields[3];
2117f4eb588SAppaRao Puli     }
2127f4eb588SAppaRao Puli }
2137f4eb588SAppaRao Puli 
21423a21a1cSEd Tanous inline int formatEventLogEntry(const std::string& logEntryID,
2157f4eb588SAppaRao Puli                                const std::string& messageID,
216c5ba4c27SEd Tanous                                const std::span<std::string_view> messageArgs,
21723a21a1cSEd Tanous                                std::string timestamp,
218b5a76932SEd Tanous                                const std::string& customText,
2197f4eb588SAppaRao Puli                                nlohmann::json& logEntryJson)
2207f4eb588SAppaRao Puli {
2217f4eb588SAppaRao Puli     // Get the Message from the MessageRegistry
222fffb8c1fSEd Tanous     const registries::Message* message = registries::formatMessage(messageID);
2237f4eb588SAppaRao Puli 
22480f595e7SEd Tanous     if (message == nullptr)
2257f4eb588SAppaRao Puli     {
22680f595e7SEd Tanous         return -1;
2277f4eb588SAppaRao Puli     }
2287f4eb588SAppaRao Puli 
22989492a15SPatrick Williams     std::string msg = redfish::registries::fillMessageArgs(messageArgs,
23089492a15SPatrick Williams                                                            message->message);
23180f595e7SEd Tanous     if (msg.empty())
23280f595e7SEd Tanous     {
23380f595e7SEd Tanous         return -1;
23480f595e7SEd Tanous     }
2357f4eb588SAppaRao Puli 
2367f4eb588SAppaRao Puli     // Get the Created time from the timestamp. The log timestamp is in
2377f4eb588SAppaRao Puli     // RFC3339 format which matches the Redfish format except for the
2387f4eb588SAppaRao Puli     // fractional seconds between the '.' and the '+', so just remove them.
239f23b7296SEd Tanous     std::size_t dot = timestamp.find_first_of('.');
240b2f7609bSEd Tanous     std::size_t plus = timestamp.find_first_of('+', dot);
2417f4eb588SAppaRao Puli     if (dot != std::string::npos && plus != std::string::npos)
2427f4eb588SAppaRao Puli     {
2437f4eb588SAppaRao Puli         timestamp.erase(dot, plus - dot);
2447f4eb588SAppaRao Puli     }
2457f4eb588SAppaRao Puli 
2467f4eb588SAppaRao Puli     // Fill in the log entry with the gathered data
2471476687dSEd Tanous     logEntryJson["EventId"] = logEntryID;
2481476687dSEd Tanous     logEntryJson["EventType"] = "Event";
24980f595e7SEd Tanous     logEntryJson["Severity"] = message->messageSeverity;
2501476687dSEd Tanous     logEntryJson["Message"] = std::move(msg);
2511476687dSEd Tanous     logEntryJson["MessageId"] = messageID;
2521476687dSEd Tanous     logEntryJson["MessageArgs"] = messageArgs;
2531476687dSEd Tanous     logEntryJson["EventTimestamp"] = std::move(timestamp);
2541476687dSEd Tanous     logEntryJson["Context"] = customText;
2557f4eb588SAppaRao Puli     return 0;
2567f4eb588SAppaRao Puli }
2577f4eb588SAppaRao Puli 
2587f4eb588SAppaRao Puli } // namespace event_log
2597f4eb588SAppaRao Puli #endif
2607f4eb588SAppaRao Puli 
26123a21a1cSEd Tanous inline bool isFilterQuerySpecialChar(char c)
26207941a88SAyushi Smriti {
26307941a88SAyushi Smriti     switch (c)
26407941a88SAyushi Smriti     {
26507941a88SAyushi Smriti         case '(':
26607941a88SAyushi Smriti         case ')':
26707941a88SAyushi Smriti         case '\'':
26807941a88SAyushi Smriti             return true;
26907941a88SAyushi Smriti         default:
27007941a88SAyushi Smriti             return false;
27107941a88SAyushi Smriti     }
27207941a88SAyushi Smriti }
27307941a88SAyushi Smriti 
27423a21a1cSEd Tanous inline bool
27523a21a1cSEd Tanous     readSSEQueryParams(std::string sseFilter, std::string& formatType,
27607941a88SAyushi Smriti                        std::vector<std::string>& messageIds,
27707941a88SAyushi Smriti                        std::vector<std::string>& registryPrefixes,
278144b6318SAppaRao Puli                        std::vector<std::string>& metricReportDefinitions)
27907941a88SAyushi Smriti {
2803544d2a7SEd Tanous     auto remove = std::ranges::remove_if(sseFilter, isFilterQuerySpecialChar);
2813544d2a7SEd Tanous     sseFilter.erase(std::ranges::begin(remove), sseFilter.end());
28207941a88SAyushi Smriti 
28307941a88SAyushi Smriti     std::vector<std::string> result;
28450ebd4afSEd Tanous 
28550ebd4afSEd Tanous     // NOLINTNEXTLINE
28650ebd4afSEd Tanous     bmcweb::split(result, sseFilter, ' ');
28707941a88SAyushi Smriti 
28862598e31SEd Tanous     BMCWEB_LOG_DEBUG("No of tokens in SEE query: {}", result.size());
28907941a88SAyushi Smriti 
29007941a88SAyushi Smriti     constexpr uint8_t divisor = 4;
29107941a88SAyushi Smriti     constexpr uint8_t minTokenSize = 3;
29207941a88SAyushi Smriti     if (result.size() % divisor != minTokenSize)
29307941a88SAyushi Smriti     {
29462598e31SEd Tanous         BMCWEB_LOG_ERROR("Invalid SSE filter specified.");
29507941a88SAyushi Smriti         return false;
29607941a88SAyushi Smriti     }
29707941a88SAyushi Smriti 
29807941a88SAyushi Smriti     for (std::size_t i = 0; i < result.size(); i += divisor)
29907941a88SAyushi Smriti     {
30002cad96eSEd Tanous         const std::string& key = result[i];
30102cad96eSEd Tanous         const std::string& op = result[i + 1];
30202cad96eSEd Tanous         const std::string& value = result[i + 2];
30307941a88SAyushi Smriti 
30407941a88SAyushi Smriti         if ((i + minTokenSize) < result.size())
30507941a88SAyushi Smriti         {
30602cad96eSEd Tanous             const std::string& separator = result[i + minTokenSize];
30707941a88SAyushi Smriti             // SSE supports only "or" and "and" in query params.
3084e0453b1SGunnar Mills             if ((separator != "or") && (separator != "and"))
30907941a88SAyushi Smriti             {
31062598e31SEd Tanous                 BMCWEB_LOG_ERROR(
31162598e31SEd Tanous                     "Invalid group operator in SSE query parameters");
31207941a88SAyushi Smriti                 return false;
31307941a88SAyushi Smriti             }
31407941a88SAyushi Smriti         }
31507941a88SAyushi Smriti 
31607941a88SAyushi Smriti         // SSE supports only "eq" as per spec.
31707941a88SAyushi Smriti         if (op != "eq")
31807941a88SAyushi Smriti         {
31962598e31SEd Tanous             BMCWEB_LOG_ERROR(
32062598e31SEd Tanous                 "Invalid assignment operator in SSE query parameters");
32107941a88SAyushi Smriti             return false;
32207941a88SAyushi Smriti         }
32307941a88SAyushi Smriti 
32462598e31SEd Tanous         BMCWEB_LOG_DEBUG("{} : {}", key, value);
32507941a88SAyushi Smriti         if (key == "EventFormatType")
32607941a88SAyushi Smriti         {
32707941a88SAyushi Smriti             formatType = value;
32807941a88SAyushi Smriti         }
32907941a88SAyushi Smriti         else if (key == "MessageId")
33007941a88SAyushi Smriti         {
33107941a88SAyushi Smriti             messageIds.push_back(value);
33207941a88SAyushi Smriti         }
33307941a88SAyushi Smriti         else if (key == "RegistryPrefix")
33407941a88SAyushi Smriti         {
33507941a88SAyushi Smriti             registryPrefixes.push_back(value);
33607941a88SAyushi Smriti         }
33707941a88SAyushi Smriti         else if (key == "MetricReportDefinition")
33807941a88SAyushi Smriti         {
33907941a88SAyushi Smriti             metricReportDefinitions.push_back(value);
34007941a88SAyushi Smriti         }
34107941a88SAyushi Smriti         else
34207941a88SAyushi Smriti         {
34362598e31SEd Tanous             BMCWEB_LOG_ERROR("Invalid property({})in SSE filter query.", key);
34407941a88SAyushi Smriti             return false;
34507941a88SAyushi Smriti         }
34607941a88SAyushi Smriti     }
34707941a88SAyushi Smriti     return true;
34807941a88SAyushi Smriti }
34907941a88SAyushi Smriti 
35028afb49cSJunLin Chen class Subscription : public persistent_data::UserSubscription
351b52664e2SAppaRao Puli {
352b52664e2SAppaRao Puli   public:
353b52664e2SAppaRao Puli     Subscription(const Subscription&) = delete;
354b52664e2SAppaRao Puli     Subscription& operator=(const Subscription&) = delete;
355b52664e2SAppaRao Puli     Subscription(Subscription&&) = delete;
356b52664e2SAppaRao Puli     Subscription& operator=(Subscription&&) = delete;
357b52664e2SAppaRao Puli 
358a716aa74SEd Tanous     Subscription(boost::urls::url_view url, boost::asio::io_context& ioc) :
359a716aa74SEd Tanous         policy(std::make_shared<crow::ConnectionPolicy>())
360b52664e2SAppaRao Puli     {
361a716aa74SEd Tanous         destinationUrl = url;
3625e44e3d8SAppaRao Puli         client.emplace(ioc, policy);
3637adb85acSSunitha Harish         // Subscription constructor
364d14a48ffSCarson Labrado         policy->invalidResp = retryRespHandler;
365b52664e2SAppaRao Puli     }
3664bbf237fSAppaRao Puli 
3675e44e3d8SAppaRao Puli     explicit Subscription(crow::sse_socket::Connection& connIn) :
3685e44e3d8SAppaRao Puli         sseConn(&connIn)
3695e44e3d8SAppaRao Puli     {}
3705e44e3d8SAppaRao Puli 
3719f616dd1SEd Tanous     ~Subscription() = default;
372b52664e2SAppaRao Puli 
3735e44e3d8SAppaRao Puli     bool sendEvent(std::string&& msg)
374b52664e2SAppaRao Puli     {
3756ba8c82eSsunharis_in         persistent_data::EventServiceConfig eventServiceConfig =
3766ba8c82eSsunharis_in             persistent_data::EventServiceStore::getInstance()
3776ba8c82eSsunharis_in                 .getEventServiceConfig();
3786ba8c82eSsunharis_in         if (!eventServiceConfig.enabled)
3796ba8c82eSsunharis_in         {
3806ba8c82eSsunharis_in             return false;
3816ba8c82eSsunharis_in         }
3826ba8c82eSsunharis_in 
383f52c03c1SCarson Labrado         // A connection pool will be created if one does not already exist
3845e44e3d8SAppaRao Puli         if (client)
3855e44e3d8SAppaRao Puli         {
386a716aa74SEd Tanous             client->sendData(std::move(msg), destinationUrl, httpHeaders,
387a716aa74SEd Tanous                              boost::beast::http::verb::post);
3885e44e3d8SAppaRao Puli             return true;
3895e44e3d8SAppaRao Puli         }
3907adb85acSSunitha Harish 
3914bbf237fSAppaRao Puli         if (sseConn != nullptr)
3924bbf237fSAppaRao Puli         {
3935e44e3d8SAppaRao Puli             eventSeqNum++;
3945e44e3d8SAppaRao Puli             sseConn->sendEvent(std::to_string(eventSeqNum), msg);
3954bbf237fSAppaRao Puli         }
3966ba8c82eSsunharis_in         return true;
3974bbf237fSAppaRao Puli     }
3984bbf237fSAppaRao Puli 
3996ba8c82eSsunharis_in     bool sendTestEventLog()
4000b4bdd93SAppaRao Puli     {
4010b4bdd93SAppaRao Puli         nlohmann::json logEntryArray;
4020b4bdd93SAppaRao Puli         logEntryArray.push_back({});
4030b4bdd93SAppaRao Puli         nlohmann::json& logEntryJson = logEntryArray.back();
4040b4bdd93SAppaRao Puli 
405613dabeaSEd Tanous         logEntryJson["EventId"] = "TestID";
406613dabeaSEd Tanous         logEntryJson["EventType"] = "Event";
407613dabeaSEd Tanous         logEntryJson["Severity"] = "OK";
408613dabeaSEd Tanous         logEntryJson["Message"] = "Generated test event";
409613dabeaSEd Tanous         logEntryJson["MessageId"] = "OpenBMC.0.2.TestEventLog";
410613dabeaSEd Tanous         logEntryJson["MessageArgs"] = nlohmann::json::array();
411613dabeaSEd Tanous         logEntryJson["EventTimestamp"] =
412613dabeaSEd Tanous             redfish::time_utils::getDateTimeOffsetNow().first;
413613dabeaSEd Tanous         logEntryJson["Context"] = customText;
4140b4bdd93SAppaRao Puli 
4151476687dSEd Tanous         nlohmann::json msg;
4161476687dSEd Tanous         msg["@odata.type"] = "#Event.v1_4_0.Event";
4171476687dSEd Tanous         msg["Id"] = std::to_string(eventSeqNum);
4181476687dSEd Tanous         msg["Name"] = "Event Log";
4191476687dSEd Tanous         msg["Events"] = logEntryArray;
4200b4bdd93SAppaRao Puli 
42189492a15SPatrick Williams         std::string strMsg = msg.dump(2, ' ', true,
42289492a15SPatrick Williams                                       nlohmann::json::error_handler_t::replace);
4235e44e3d8SAppaRao Puli         return sendEvent(std::move(strMsg));
4240b4bdd93SAppaRao Puli     }
4250b4bdd93SAppaRao Puli 
4267f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
4277f4eb588SAppaRao Puli     void filterAndSendEventLogs(
4287f4eb588SAppaRao Puli         const std::vector<EventLogObjectsType>& eventRecords)
4297f4eb588SAppaRao Puli     {
4307f4eb588SAppaRao Puli         nlohmann::json logEntryArray;
4317f4eb588SAppaRao Puli         for (const EventLogObjectsType& logEntry : eventRecords)
4327f4eb588SAppaRao Puli         {
4337f4eb588SAppaRao Puli             const std::string& idStr = std::get<0>(logEntry);
4347f4eb588SAppaRao Puli             const std::string& timestamp = std::get<1>(logEntry);
4357f4eb588SAppaRao Puli             const std::string& messageID = std::get<2>(logEntry);
4367f4eb588SAppaRao Puli             const std::string& registryName = std::get<3>(logEntry);
4377f4eb588SAppaRao Puli             const std::string& messageKey = std::get<4>(logEntry);
4385e715de6SAppaRao Puli             const std::vector<std::string>& messageArgs = std::get<5>(logEntry);
4397f4eb588SAppaRao Puli 
4407f4eb588SAppaRao Puli             // If registryPrefixes list is empty, don't filter events
4417f4eb588SAppaRao Puli             // send everything.
44226f6976fSEd Tanous             if (!registryPrefixes.empty())
4437f4eb588SAppaRao Puli             {
4443544d2a7SEd Tanous                 auto obj = std::ranges::find(registryPrefixes, registryName);
4457f4eb588SAppaRao Puli                 if (obj == registryPrefixes.end())
4467f4eb588SAppaRao Puli                 {
4477f4eb588SAppaRao Puli                     continue;
4487f4eb588SAppaRao Puli                 }
4497f4eb588SAppaRao Puli             }
4507f4eb588SAppaRao Puli 
4517f4eb588SAppaRao Puli             // If registryMsgIds list is empty, don't filter events
4527f4eb588SAppaRao Puli             // send everything.
45326f6976fSEd Tanous             if (!registryMsgIds.empty())
4547f4eb588SAppaRao Puli             {
4553544d2a7SEd Tanous                 auto obj = std::ranges::find(registryMsgIds, messageKey);
4567f4eb588SAppaRao Puli                 if (obj == registryMsgIds.end())
4577f4eb588SAppaRao Puli                 {
4587f4eb588SAppaRao Puli                     continue;
4597f4eb588SAppaRao Puli                 }
4607f4eb588SAppaRao Puli             }
4617f4eb588SAppaRao Puli 
462c5ba4c27SEd Tanous             std::vector<std::string_view> messageArgsView(messageArgs.begin(),
463c5ba4c27SEd Tanous                                                           messageArgs.end());
464c5ba4c27SEd Tanous 
4657f4eb588SAppaRao Puli             logEntryArray.push_back({});
4667f4eb588SAppaRao Puli             nlohmann::json& bmcLogEntry = logEntryArray.back();
467c5ba4c27SEd Tanous             if (event_log::formatEventLogEntry(idStr, messageID,
468c5ba4c27SEd Tanous                                                messageArgsView, timestamp,
469c5ba4c27SEd Tanous                                                customText, bmcLogEntry) != 0)
4707f4eb588SAppaRao Puli             {
47162598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Read eventLog entry failed");
4727f4eb588SAppaRao Puli                 continue;
4737f4eb588SAppaRao Puli             }
4747f4eb588SAppaRao Puli         }
4757f4eb588SAppaRao Puli 
47626f6976fSEd Tanous         if (logEntryArray.empty())
4777f4eb588SAppaRao Puli         {
47862598e31SEd Tanous             BMCWEB_LOG_DEBUG("No log entries available to be transferred.");
4797f4eb588SAppaRao Puli             return;
4807f4eb588SAppaRao Puli         }
4817f4eb588SAppaRao Puli 
4821476687dSEd Tanous         nlohmann::json msg;
4831476687dSEd Tanous         msg["@odata.type"] = "#Event.v1_4_0.Event";
4841476687dSEd Tanous         msg["Id"] = std::to_string(eventSeqNum);
4851476687dSEd Tanous         msg["Name"] = "Event Log";
4861476687dSEd Tanous         msg["Events"] = logEntryArray;
48789492a15SPatrick Williams         std::string strMsg = msg.dump(2, ' ', true,
48889492a15SPatrick Williams                                       nlohmann::json::error_handler_t::replace);
4895e44e3d8SAppaRao Puli         sendEvent(std::move(strMsg));
4905e44e3d8SAppaRao Puli         eventSeqNum++;
4917f4eb588SAppaRao Puli     }
4927f4eb588SAppaRao Puli #endif
4937f4eb588SAppaRao Puli 
494248d0230SEd Tanous     void filterAndSendReports(const std::string& reportId,
4951e1e598dSJonathan Doman                               const telemetry::TimestampReadings& var)
496156d6b00SAppaRao Puli     {
497ef4c65b7SEd Tanous         boost::urls::url mrdUri = boost::urls::format(
498ef4c65b7SEd Tanous             "/redfish/v1/TelemetryService/MetricReportDefinitions/{}",
499ef4c65b7SEd Tanous             reportId);
500156d6b00SAppaRao Puli 
501156d6b00SAppaRao Puli         // Empty list means no filter. Send everything.
50226f6976fSEd Tanous         if (!metricReportDefinitions.empty())
503156d6b00SAppaRao Puli         {
5043544d2a7SEd Tanous             if (std::ranges::find(metricReportDefinitions, mrdUri.buffer()) ==
5053544d2a7SEd Tanous                 metricReportDefinitions.end())
506156d6b00SAppaRao Puli             {
507156d6b00SAppaRao Puli                 return;
508156d6b00SAppaRao Puli             }
509156d6b00SAppaRao Puli         }
510156d6b00SAppaRao Puli 
511c0353249SWludzik, Jozef         nlohmann::json msg;
512248d0230SEd Tanous         if (!telemetry::fillReport(msg, reportId, var))
513156d6b00SAppaRao Puli         {
51462598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to fill the MetricReport for DBus "
51562598e31SEd Tanous                              "Report with id {}",
51662598e31SEd Tanous                              reportId);
517c0353249SWludzik, Jozef             return;
518156d6b00SAppaRao Puli         }
519156d6b00SAppaRao Puli 
52022daffd7SAppaRao Puli         // Context is set by user during Event subscription and it must be
52122daffd7SAppaRao Puli         // set for MetricReport response.
52222daffd7SAppaRao Puli         if (!customText.empty())
52322daffd7SAppaRao Puli         {
52422daffd7SAppaRao Puli             msg["Context"] = customText;
52522daffd7SAppaRao Puli         }
52622daffd7SAppaRao Puli 
52789492a15SPatrick Williams         std::string strMsg = msg.dump(2, ' ', true,
52889492a15SPatrick Williams                                       nlohmann::json::error_handler_t::replace);
5295e44e3d8SAppaRao Puli         sendEvent(std::move(strMsg));
530156d6b00SAppaRao Puli     }
531156d6b00SAppaRao Puli 
532d14a48ffSCarson Labrado     void updateRetryConfig(uint32_t retryAttempts,
533d14a48ffSCarson Labrado                            uint32_t retryTimeoutInterval)
534fe44eb0bSAyushi Smriti     {
535*93cf0ac2SEd Tanous         if (policy == nullptr)
536*93cf0ac2SEd Tanous         {
537*93cf0ac2SEd Tanous             BMCWEB_LOG_DEBUG("Retry policy was nullptr, ignoring set");
538*93cf0ac2SEd Tanous             return;
539*93cf0ac2SEd Tanous         }
540d14a48ffSCarson Labrado         policy->maxRetryAttempts = retryAttempts;
541d14a48ffSCarson Labrado         policy->retryIntervalSecs = std::chrono::seconds(retryTimeoutInterval);
54262de0c68SAppaRao Puli     }
543fe44eb0bSAyushi Smriti 
5449eb808c1SEd Tanous     uint64_t getEventSeqNum() const
54596330b99SSunitha Harish     {
54696330b99SSunitha Harish         return eventSeqNum;
54796330b99SSunitha Harish     }
54896330b99SSunitha Harish 
5495e44e3d8SAppaRao Puli     void setSubscriptionId(const std::string& id2)
5505e44e3d8SAppaRao Puli     {
55162598e31SEd Tanous         BMCWEB_LOG_DEBUG("Subscription ID: {}", id2);
5525e44e3d8SAppaRao Puli         subId = id2;
5535e44e3d8SAppaRao Puli     }
5545e44e3d8SAppaRao Puli 
5555e44e3d8SAppaRao Puli     std::string getSubscriptionId()
5565e44e3d8SAppaRao Puli     {
5575e44e3d8SAppaRao Puli         return subId;
5585e44e3d8SAppaRao Puli     }
5595e44e3d8SAppaRao Puli 
5605e44e3d8SAppaRao Puli     bool matchSseId(const crow::sse_socket::Connection& thisConn)
5615e44e3d8SAppaRao Puli     {
5625e44e3d8SAppaRao Puli         return &thisConn == sseConn;
5635e44e3d8SAppaRao Puli     }
5645e44e3d8SAppaRao Puli 
565b52664e2SAppaRao Puli   private:
5665e44e3d8SAppaRao Puli     std::string subId;
567d14a48ffSCarson Labrado     uint64_t eventSeqNum = 1;
568a716aa74SEd Tanous     boost::urls::url host;
569d14a48ffSCarson Labrado     std::shared_ptr<crow::ConnectionPolicy> policy;
5705e44e3d8SAppaRao Puli     crow::sse_socket::Connection* sseConn = nullptr;
5715e44e3d8SAppaRao Puli     std::optional<crow::HttpClient> client;
572b52664e2SAppaRao Puli     std::string path;
573b52664e2SAppaRao Puli     std::string uriProto;
574a7a80296SCarson Labrado 
575a7a80296SCarson Labrado     // Check used to indicate what response codes are valid as part of our retry
576a7a80296SCarson Labrado     // policy.  2XX is considered acceptable
577a7a80296SCarson Labrado     static boost::system::error_code retryRespHandler(unsigned int respCode)
578a7a80296SCarson Labrado     {
57962598e31SEd Tanous         BMCWEB_LOG_DEBUG(
58062598e31SEd Tanous             "Checking response code validity for SubscriptionEvent");
581a7a80296SCarson Labrado         if ((respCode < 200) || (respCode >= 300))
582a7a80296SCarson Labrado         {
583a7a80296SCarson Labrado             return boost::system::errc::make_error_code(
584a7a80296SCarson Labrado                 boost::system::errc::result_out_of_range);
585a7a80296SCarson Labrado         }
586a7a80296SCarson Labrado 
587a7a80296SCarson Labrado         // Return 0 if the response code is valid
588a7a80296SCarson Labrado         return boost::system::errc::make_error_code(
589a7a80296SCarson Labrado             boost::system::errc::success);
5909fa6d147SNan Zhou     }
591b52664e2SAppaRao Puli };
592b52664e2SAppaRao Puli 
593b52664e2SAppaRao Puli class EventServiceManager
594b52664e2SAppaRao Puli {
595b52664e2SAppaRao Puli   private:
596d3a9e084SEd Tanous     bool serviceEnabled = false;
597d3a9e084SEd Tanous     uint32_t retryAttempts = 0;
598d3a9e084SEd Tanous     uint32_t retryTimeoutInterval = 0;
5997d1cc387SAppaRao Puli 
6002558979cSP Dheeraj Srujan Kumar     std::streampos redfishLogFilePosition{0};
6019f616dd1SEd Tanous     size_t noOfEventLogSubscribers{0};
6029f616dd1SEd Tanous     size_t noOfMetricReportSubscribers{0};
60359d494eeSPatrick Williams     std::shared_ptr<sdbusplus::bus::match_t> matchTelemetryMonitor;
604b52664e2SAppaRao Puli     boost::container::flat_map<std::string, std::shared_ptr<Subscription>>
605b52664e2SAppaRao Puli         subscriptionsMap;
606b52664e2SAppaRao Puli 
6079f616dd1SEd Tanous     uint64_t eventId{1};
60896330b99SSunitha Harish 
609f8ca6d79SEd Tanous     boost::asio::io_context& ioc;
610f8ca6d79SEd Tanous 
611b52664e2SAppaRao Puli   public:
6129f616dd1SEd Tanous     EventServiceManager(const EventServiceManager&) = delete;
6139f616dd1SEd Tanous     EventServiceManager& operator=(const EventServiceManager&) = delete;
6149f616dd1SEd Tanous     EventServiceManager(EventServiceManager&&) = delete;
6159f616dd1SEd Tanous     EventServiceManager& operator=(EventServiceManager&&) = delete;
616ecd6a3a2SEd Tanous     ~EventServiceManager() = default;
6179f616dd1SEd Tanous 
618f8ca6d79SEd Tanous     explicit EventServiceManager(boost::asio::io_context& iocIn) : ioc(iocIn)
619b52664e2SAppaRao Puli     {
620f8ca6d79SEd Tanous         // Load config from persist store.
621f8ca6d79SEd Tanous         initConfig();
622f8ca6d79SEd Tanous     }
623f8ca6d79SEd Tanous 
624f8ca6d79SEd Tanous     static EventServiceManager&
625f8ca6d79SEd Tanous         getInstance(boost::asio::io_context* ioc = nullptr)
626f8ca6d79SEd Tanous     {
627f8ca6d79SEd Tanous         static EventServiceManager handler(*ioc);
628b52664e2SAppaRao Puli         return handler;
629b52664e2SAppaRao Puli     }
630b52664e2SAppaRao Puli 
6311bf712bcSAyushi Smriti     void initConfig()
6321bf712bcSAyushi Smriti     {
63328afb49cSJunLin Chen         loadOldBehavior();
6341bf712bcSAyushi Smriti 
63528afb49cSJunLin Chen         persistent_data::EventServiceConfig eventServiceConfig =
63628afb49cSJunLin Chen             persistent_data::EventServiceStore::getInstance()
63728afb49cSJunLin Chen                 .getEventServiceConfig();
6381bf712bcSAyushi Smriti 
63928afb49cSJunLin Chen         serviceEnabled = eventServiceConfig.enabled;
64028afb49cSJunLin Chen         retryAttempts = eventServiceConfig.retryAttempts;
64128afb49cSJunLin Chen         retryTimeoutInterval = eventServiceConfig.retryTimeoutInterval;
6421bf712bcSAyushi Smriti 
64328afb49cSJunLin Chen         for (const auto& it : persistent_data::EventServiceStore::getInstance()
64428afb49cSJunLin Chen                                   .subscriptionsConfigMap)
6451bf712bcSAyushi Smriti         {
64628afb49cSJunLin Chen             std::shared_ptr<persistent_data::UserSubscription> newSub =
64728afb49cSJunLin Chen                 it.second;
6484bbf237fSAppaRao Puli 
6496fd29553SEd Tanous             boost::system::result<boost::urls::url> url =
650a716aa74SEd Tanous                 boost::urls::parse_absolute_uri(newSub->destinationUrl);
6511bf712bcSAyushi Smriti 
652a716aa74SEd Tanous             if (!url)
6531bf712bcSAyushi Smriti             {
65462598e31SEd Tanous                 BMCWEB_LOG_ERROR(
65562598e31SEd Tanous                     "Failed to validate and split destination url");
6561bf712bcSAyushi Smriti                 continue;
6571bf712bcSAyushi Smriti             }
6581bf712bcSAyushi Smriti             std::shared_ptr<Subscription> subValue =
659a716aa74SEd Tanous                 std::make_shared<Subscription>(*url, ioc);
6601bf712bcSAyushi Smriti 
66128afb49cSJunLin Chen             subValue->id = newSub->id;
66228afb49cSJunLin Chen             subValue->destinationUrl = newSub->destinationUrl;
66328afb49cSJunLin Chen             subValue->protocol = newSub->protocol;
66428afb49cSJunLin Chen             subValue->retryPolicy = newSub->retryPolicy;
66528afb49cSJunLin Chen             subValue->customText = newSub->customText;
66628afb49cSJunLin Chen             subValue->eventFormatType = newSub->eventFormatType;
66728afb49cSJunLin Chen             subValue->subscriptionType = newSub->subscriptionType;
66828afb49cSJunLin Chen             subValue->registryMsgIds = newSub->registryMsgIds;
66928afb49cSJunLin Chen             subValue->registryPrefixes = newSub->registryPrefixes;
67028afb49cSJunLin Chen             subValue->resourceTypes = newSub->resourceTypes;
67128afb49cSJunLin Chen             subValue->httpHeaders = newSub->httpHeaders;
67228afb49cSJunLin Chen             subValue->metricReportDefinitions = newSub->metricReportDefinitions;
6731bf712bcSAyushi Smriti 
67428afb49cSJunLin Chen             if (subValue->id.empty())
6751bf712bcSAyushi Smriti             {
67662598e31SEd Tanous                 BMCWEB_LOG_ERROR("Failed to add subscription");
6771bf712bcSAyushi Smriti             }
67828afb49cSJunLin Chen             subscriptionsMap.insert(std::pair(subValue->id, subValue));
67928afb49cSJunLin Chen 
68028afb49cSJunLin Chen             updateNoOfSubscribersCount();
68128afb49cSJunLin Chen 
68228afb49cSJunLin Chen #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
6832558979cSP Dheeraj Srujan Kumar 
6842558979cSP Dheeraj Srujan Kumar             cacheRedfishLogFile();
6852558979cSP Dheeraj Srujan Kumar 
68628afb49cSJunLin Chen #endif
68728afb49cSJunLin Chen             // Update retry configuration.
68828afb49cSJunLin Chen             subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
6891bf712bcSAyushi Smriti         }
6901bf712bcSAyushi Smriti     }
6911bf712bcSAyushi Smriti 
69256d2396dSEd Tanous     static void loadOldBehavior()
693b52664e2SAppaRao Puli     {
69428afb49cSJunLin Chen         std::ifstream eventConfigFile(eventServiceFile);
69528afb49cSJunLin Chen         if (!eventConfigFile.good())
6961bf712bcSAyushi Smriti         {
69762598e31SEd Tanous             BMCWEB_LOG_DEBUG("Old eventService config not exist");
69828afb49cSJunLin Chen             return;
69928afb49cSJunLin Chen         }
70028afb49cSJunLin Chen         auto jsonData = nlohmann::json::parse(eventConfigFile, nullptr, false);
70128afb49cSJunLin Chen         if (jsonData.is_discarded())
7024bbf237fSAppaRao Puli         {
70362598e31SEd Tanous             BMCWEB_LOG_ERROR("Old eventService config parse error.");
70428afb49cSJunLin Chen             return;
70528afb49cSJunLin Chen         }
70628afb49cSJunLin Chen 
70728afb49cSJunLin Chen         for (const auto& item : jsonData.items())
70828afb49cSJunLin Chen         {
70928afb49cSJunLin Chen             if (item.key() == "Configuration")
71028afb49cSJunLin Chen             {
71128afb49cSJunLin Chen                 persistent_data::EventServiceStore::getInstance()
71228afb49cSJunLin Chen                     .getEventServiceConfig()
71328afb49cSJunLin Chen                     .fromJson(item.value());
71428afb49cSJunLin Chen             }
71528afb49cSJunLin Chen             else if (item.key() == "Subscriptions")
71628afb49cSJunLin Chen             {
71728afb49cSJunLin Chen                 for (const auto& elem : item.value())
71828afb49cSJunLin Chen                 {
71928afb49cSJunLin Chen                     std::shared_ptr<persistent_data::UserSubscription>
72028afb49cSJunLin Chen                         newSubscription =
72128afb49cSJunLin Chen                             persistent_data::UserSubscription::fromJson(elem,
72228afb49cSJunLin Chen                                                                         true);
72328afb49cSJunLin Chen                     if (newSubscription == nullptr)
72428afb49cSJunLin Chen                     {
72562598e31SEd Tanous                         BMCWEB_LOG_ERROR("Problem reading subscription "
72662598e31SEd Tanous                                          "from old persistent store");
7274bbf237fSAppaRao Puli                         continue;
7284bbf237fSAppaRao Puli                     }
7291bf712bcSAyushi Smriti 
73028afb49cSJunLin Chen                     std::uniform_int_distribution<uint32_t> dist(0);
73128afb49cSJunLin Chen                     bmcweb::OpenSSLGenerator gen;
7321bf712bcSAyushi Smriti 
73328afb49cSJunLin Chen                     std::string id;
7341bf712bcSAyushi Smriti 
73528afb49cSJunLin Chen                     int retry = 3;
736e662eae8SEd Tanous                     while (retry != 0)
7371bf712bcSAyushi Smriti                     {
73828afb49cSJunLin Chen                         id = std::to_string(dist(gen));
73928afb49cSJunLin Chen                         if (gen.error())
7407d1cc387SAppaRao Puli                         {
74128afb49cSJunLin Chen                             retry = 0;
74228afb49cSJunLin Chen                             break;
74328afb49cSJunLin Chen                         }
74428afb49cSJunLin Chen                         newSubscription->id = id;
74528afb49cSJunLin Chen                         auto inserted =
74628afb49cSJunLin Chen                             persistent_data::EventServiceStore::getInstance()
74728afb49cSJunLin Chen                                 .subscriptionsConfigMap.insert(
74828afb49cSJunLin Chen                                     std::pair(id, newSubscription));
74928afb49cSJunLin Chen                         if (inserted.second)
75028afb49cSJunLin Chen                         {
75128afb49cSJunLin Chen                             break;
75228afb49cSJunLin Chen                         }
75328afb49cSJunLin Chen                         --retry;
7547d1cc387SAppaRao Puli                     }
7557d1cc387SAppaRao Puli 
75628afb49cSJunLin Chen                     if (retry <= 0)
75728afb49cSJunLin Chen                     {
75862598e31SEd Tanous                         BMCWEB_LOG_ERROR(
75962598e31SEd Tanous                             "Failed to generate random number from old "
76062598e31SEd Tanous                             "persistent store");
76128afb49cSJunLin Chen                         continue;
76228afb49cSJunLin Chen                     }
76328afb49cSJunLin Chen                 }
76428afb49cSJunLin Chen             }
76528afb49cSJunLin Chen 
76628afb49cSJunLin Chen             persistent_data::getConfig().writeData();
76728afb49cSJunLin Chen             std::remove(eventServiceFile);
76862598e31SEd Tanous             BMCWEB_LOG_DEBUG("Remove old eventservice config");
76928afb49cSJunLin Chen         }
77028afb49cSJunLin Chen     }
77128afb49cSJunLin Chen 
7729eb808c1SEd Tanous     void updateSubscriptionData() const
77328afb49cSJunLin Chen     {
77428afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
77528afb49cSJunLin Chen             .eventServiceConfig.enabled = serviceEnabled;
77628afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
77728afb49cSJunLin Chen             .eventServiceConfig.retryAttempts = retryAttempts;
77828afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
77928afb49cSJunLin Chen             .eventServiceConfig.retryTimeoutInterval = retryTimeoutInterval;
78028afb49cSJunLin Chen 
78128afb49cSJunLin Chen         persistent_data::getConfig().writeData();
78228afb49cSJunLin Chen     }
78328afb49cSJunLin Chen 
78428afb49cSJunLin Chen     void setEventServiceConfig(const persistent_data::EventServiceConfig& cfg)
7857d1cc387SAppaRao Puli     {
7867d1cc387SAppaRao Puli         bool updateConfig = false;
787fe44eb0bSAyushi Smriti         bool updateRetryCfg = false;
7887d1cc387SAppaRao Puli 
78928afb49cSJunLin Chen         if (serviceEnabled != cfg.enabled)
7907d1cc387SAppaRao Puli         {
79128afb49cSJunLin Chen             serviceEnabled = cfg.enabled;
792e662eae8SEd Tanous             if (serviceEnabled && noOfMetricReportSubscribers != 0U)
7937d1cc387SAppaRao Puli             {
7947d1cc387SAppaRao Puli                 registerMetricReportSignal();
7957d1cc387SAppaRao Puli             }
7967d1cc387SAppaRao Puli             else
7977d1cc387SAppaRao Puli             {
7987d1cc387SAppaRao Puli                 unregisterMetricReportSignal();
7997d1cc387SAppaRao Puli             }
8007d1cc387SAppaRao Puli             updateConfig = true;
8017d1cc387SAppaRao Puli         }
8027d1cc387SAppaRao Puli 
80328afb49cSJunLin Chen         if (retryAttempts != cfg.retryAttempts)
8047d1cc387SAppaRao Puli         {
80528afb49cSJunLin Chen             retryAttempts = cfg.retryAttempts;
8067d1cc387SAppaRao Puli             updateConfig = true;
807fe44eb0bSAyushi Smriti             updateRetryCfg = true;
8087d1cc387SAppaRao Puli         }
8097d1cc387SAppaRao Puli 
81028afb49cSJunLin Chen         if (retryTimeoutInterval != cfg.retryTimeoutInterval)
8117d1cc387SAppaRao Puli         {
81228afb49cSJunLin Chen             retryTimeoutInterval = cfg.retryTimeoutInterval;
8137d1cc387SAppaRao Puli             updateConfig = true;
814fe44eb0bSAyushi Smriti             updateRetryCfg = true;
8157d1cc387SAppaRao Puli         }
8167d1cc387SAppaRao Puli 
8177d1cc387SAppaRao Puli         if (updateConfig)
8187d1cc387SAppaRao Puli         {
8197d1cc387SAppaRao Puli             updateSubscriptionData();
8207d1cc387SAppaRao Puli         }
821fe44eb0bSAyushi Smriti 
822fe44eb0bSAyushi Smriti         if (updateRetryCfg)
823fe44eb0bSAyushi Smriti         {
824fe44eb0bSAyushi Smriti             // Update the changed retry config to all subscriptions
825fe44eb0bSAyushi Smriti             for (const auto& it :
826fe44eb0bSAyushi Smriti                  EventServiceManager::getInstance().subscriptionsMap)
827fe44eb0bSAyushi Smriti             {
8285e44e3d8SAppaRao Puli                 Subscription& entry = *it.second;
8295e44e3d8SAppaRao Puli                 entry.updateRetryConfig(retryAttempts, retryTimeoutInterval);
830fe44eb0bSAyushi Smriti             }
831fe44eb0bSAyushi Smriti         }
8327d1cc387SAppaRao Puli     }
8337d1cc387SAppaRao Puli 
8347d1cc387SAppaRao Puli     void updateNoOfSubscribersCount()
8357d1cc387SAppaRao Puli     {
8367d1cc387SAppaRao Puli         size_t eventLogSubCount = 0;
8377d1cc387SAppaRao Puli         size_t metricReportSubCount = 0;
8387d1cc387SAppaRao Puli         for (const auto& it : subscriptionsMap)
8397d1cc387SAppaRao Puli         {
8407d1cc387SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
8417d1cc387SAppaRao Puli             if (entry->eventFormatType == eventFormatType)
8427d1cc387SAppaRao Puli             {
8437d1cc387SAppaRao Puli                 eventLogSubCount++;
8447d1cc387SAppaRao Puli             }
8457d1cc387SAppaRao Puli             else if (entry->eventFormatType == metricReportFormatType)
8467d1cc387SAppaRao Puli             {
8477d1cc387SAppaRao Puli                 metricReportSubCount++;
8487d1cc387SAppaRao Puli             }
8497d1cc387SAppaRao Puli         }
8507d1cc387SAppaRao Puli 
8517d1cc387SAppaRao Puli         noOfEventLogSubscribers = eventLogSubCount;
8527d1cc387SAppaRao Puli         if (noOfMetricReportSubscribers != metricReportSubCount)
8537d1cc387SAppaRao Puli         {
8547d1cc387SAppaRao Puli             noOfMetricReportSubscribers = metricReportSubCount;
855e662eae8SEd Tanous             if (noOfMetricReportSubscribers != 0U)
8567d1cc387SAppaRao Puli             {
8577d1cc387SAppaRao Puli                 registerMetricReportSignal();
8587d1cc387SAppaRao Puli             }
8597d1cc387SAppaRao Puli             else
8607d1cc387SAppaRao Puli             {
8617d1cc387SAppaRao Puli                 unregisterMetricReportSignal();
8627d1cc387SAppaRao Puli             }
8637d1cc387SAppaRao Puli         }
8647d1cc387SAppaRao Puli     }
8657d1cc387SAppaRao Puli 
866b52664e2SAppaRao Puli     std::shared_ptr<Subscription> getSubscription(const std::string& id)
867b52664e2SAppaRao Puli     {
868b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
869b52664e2SAppaRao Puli         if (obj == subscriptionsMap.end())
870b52664e2SAppaRao Puli         {
87162598e31SEd Tanous             BMCWEB_LOG_ERROR("No subscription exist with ID:{}", id);
872b52664e2SAppaRao Puli             return nullptr;
873b52664e2SAppaRao Puli         }
874b52664e2SAppaRao Puli         std::shared_ptr<Subscription> subValue = obj->second;
875b52664e2SAppaRao Puli         return subValue;
876b52664e2SAppaRao Puli     }
877b52664e2SAppaRao Puli 
878b5a76932SEd Tanous     std::string addSubscription(const std::shared_ptr<Subscription>& subValue,
8791bf712bcSAyushi Smriti                                 const bool updateFile = true)
880b52664e2SAppaRao Puli     {
881fc76b8acSEd Tanous         std::uniform_int_distribution<uint32_t> dist(0);
882fc76b8acSEd Tanous         bmcweb::OpenSSLGenerator gen;
883fc76b8acSEd Tanous 
884b52664e2SAppaRao Puli         std::string id;
885b52664e2SAppaRao Puli 
886b52664e2SAppaRao Puli         int retry = 3;
887e662eae8SEd Tanous         while (retry != 0)
888b52664e2SAppaRao Puli         {
889fc76b8acSEd Tanous             id = std::to_string(dist(gen));
890fc76b8acSEd Tanous             if (gen.error())
891fc76b8acSEd Tanous             {
892fc76b8acSEd Tanous                 retry = 0;
893fc76b8acSEd Tanous                 break;
894fc76b8acSEd Tanous             }
895b52664e2SAppaRao Puli             auto inserted = subscriptionsMap.insert(std::pair(id, subValue));
896b52664e2SAppaRao Puli             if (inserted.second)
897b52664e2SAppaRao Puli             {
898b52664e2SAppaRao Puli                 break;
899b52664e2SAppaRao Puli             }
900b52664e2SAppaRao Puli             --retry;
90123a21a1cSEd Tanous         }
902b52664e2SAppaRao Puli 
903b52664e2SAppaRao Puli         if (retry <= 0)
904b52664e2SAppaRao Puli         {
90562598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to generate random number");
906abb93cddSEd Tanous             return "";
907b52664e2SAppaRao Puli         }
908b52664e2SAppaRao Puli 
90928afb49cSJunLin Chen         std::shared_ptr<persistent_data::UserSubscription> newSub =
91028afb49cSJunLin Chen             std::make_shared<persistent_data::UserSubscription>();
91128afb49cSJunLin Chen         newSub->id = id;
91228afb49cSJunLin Chen         newSub->destinationUrl = subValue->destinationUrl;
91328afb49cSJunLin Chen         newSub->protocol = subValue->protocol;
91428afb49cSJunLin Chen         newSub->retryPolicy = subValue->retryPolicy;
91528afb49cSJunLin Chen         newSub->customText = subValue->customText;
91628afb49cSJunLin Chen         newSub->eventFormatType = subValue->eventFormatType;
91728afb49cSJunLin Chen         newSub->subscriptionType = subValue->subscriptionType;
91828afb49cSJunLin Chen         newSub->registryMsgIds = subValue->registryMsgIds;
91928afb49cSJunLin Chen         newSub->registryPrefixes = subValue->registryPrefixes;
92028afb49cSJunLin Chen         newSub->resourceTypes = subValue->resourceTypes;
92128afb49cSJunLin Chen         newSub->httpHeaders = subValue->httpHeaders;
92228afb49cSJunLin Chen         newSub->metricReportDefinitions = subValue->metricReportDefinitions;
92328afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
92428afb49cSJunLin Chen             .subscriptionsConfigMap.emplace(newSub->id, newSub);
92528afb49cSJunLin Chen 
9267d1cc387SAppaRao Puli         updateNoOfSubscribersCount();
9271bf712bcSAyushi Smriti 
9281bf712bcSAyushi Smriti         if (updateFile)
9291bf712bcSAyushi Smriti         {
930b52664e2SAppaRao Puli             updateSubscriptionData();
9311bf712bcSAyushi Smriti         }
9327f4eb588SAppaRao Puli 
9337f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
9342558979cSP Dheeraj Srujan Kumar         if (redfishLogFilePosition != 0)
9357f4eb588SAppaRao Puli         {
9362558979cSP Dheeraj Srujan Kumar             cacheRedfishLogFile();
9377f4eb588SAppaRao Puli         }
9387f4eb588SAppaRao Puli #endif
939fe44eb0bSAyushi Smriti         // Update retry configuration.
940fe44eb0bSAyushi Smriti         subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
941fe44eb0bSAyushi Smriti 
9425e44e3d8SAppaRao Puli         // Set Subscription ID for back trace
9435e44e3d8SAppaRao Puli         subValue->setSubscriptionId(id);
944b52664e2SAppaRao Puli         return id;
945b52664e2SAppaRao Puli     }
946b52664e2SAppaRao Puli 
947b52664e2SAppaRao Puli     bool isSubscriptionExist(const std::string& id)
948b52664e2SAppaRao Puli     {
949b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
95055f79e6fSEd Tanous         return obj != subscriptionsMap.end();
951b52664e2SAppaRao Puli     }
952b52664e2SAppaRao Puli 
953b52664e2SAppaRao Puli     void deleteSubscription(const std::string& id)
954b52664e2SAppaRao Puli     {
955b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
956b52664e2SAppaRao Puli         if (obj != subscriptionsMap.end())
957b52664e2SAppaRao Puli         {
958b52664e2SAppaRao Puli             subscriptionsMap.erase(obj);
95928afb49cSJunLin Chen             auto obj2 = persistent_data::EventServiceStore::getInstance()
96028afb49cSJunLin Chen                             .subscriptionsConfigMap.find(id);
96128afb49cSJunLin Chen             persistent_data::EventServiceStore::getInstance()
96228afb49cSJunLin Chen                 .subscriptionsConfigMap.erase(obj2);
9637d1cc387SAppaRao Puli             updateNoOfSubscribersCount();
964b52664e2SAppaRao Puli             updateSubscriptionData();
965b52664e2SAppaRao Puli         }
966b52664e2SAppaRao Puli     }
967b52664e2SAppaRao Puli 
9685e44e3d8SAppaRao Puli     void deleteSseSubscription(const crow::sse_socket::Connection& thisConn)
9695e44e3d8SAppaRao Puli     {
9705e44e3d8SAppaRao Puli         for (const auto& it : subscriptionsMap)
9715e44e3d8SAppaRao Puli         {
9725e44e3d8SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
9735e44e3d8SAppaRao Puli             bool entryIsThisConn = entry->matchSseId(thisConn);
9745e44e3d8SAppaRao Puli             if (entryIsThisConn)
9755e44e3d8SAppaRao Puli             {
9765e44e3d8SAppaRao Puli                 persistent_data::EventServiceStore::getInstance()
9775e44e3d8SAppaRao Puli                     .subscriptionsConfigMap.erase(
9785e44e3d8SAppaRao Puli                         it.second->getSubscriptionId());
9795e44e3d8SAppaRao Puli                 return;
9805e44e3d8SAppaRao Puli             }
9815e44e3d8SAppaRao Puli         }
9825e44e3d8SAppaRao Puli     }
9835e44e3d8SAppaRao Puli 
9845e44e3d8SAppaRao Puli     size_t getNumberOfSubscriptions() const
985b52664e2SAppaRao Puli     {
986b52664e2SAppaRao Puli         return subscriptionsMap.size();
987b52664e2SAppaRao Puli     }
988b52664e2SAppaRao Puli 
9895e44e3d8SAppaRao Puli     size_t getNumberOfSSESubscriptions() const
9905e44e3d8SAppaRao Puli     {
9913544d2a7SEd Tanous         auto size = std::ranges::count_if(
9923544d2a7SEd Tanous             subscriptionsMap,
9935e44e3d8SAppaRao Puli             [](const std::pair<std::string, std::shared_ptr<Subscription>>&
9945e44e3d8SAppaRao Puli                    entry) {
9955e44e3d8SAppaRao Puli             return (entry.second->subscriptionType == subscriptionTypeSSE);
9965e44e3d8SAppaRao Puli         });
9975e44e3d8SAppaRao Puli         return static_cast<size_t>(size);
9985e44e3d8SAppaRao Puli     }
9995e44e3d8SAppaRao Puli 
1000b52664e2SAppaRao Puli     std::vector<std::string> getAllIDs()
1001b52664e2SAppaRao Puli     {
1002b52664e2SAppaRao Puli         std::vector<std::string> idList;
1003b52664e2SAppaRao Puli         for (const auto& it : subscriptionsMap)
1004b52664e2SAppaRao Puli         {
1005b52664e2SAppaRao Puli             idList.emplace_back(it.first);
1006b52664e2SAppaRao Puli         }
1007b52664e2SAppaRao Puli         return idList;
1008b52664e2SAppaRao Puli     }
1009b52664e2SAppaRao Puli 
10106ba8c82eSsunharis_in     bool sendTestEventLog()
10110b4bdd93SAppaRao Puli     {
10125e44e3d8SAppaRao Puli         for (const auto& it : subscriptionsMap)
10130b4bdd93SAppaRao Puli         {
10140b4bdd93SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
10156ba8c82eSsunharis_in             if (!entry->sendTestEventLog())
10166ba8c82eSsunharis_in             {
10176ba8c82eSsunharis_in                 return false;
10180b4bdd93SAppaRao Puli             }
10190b4bdd93SAppaRao Puli         }
10206ba8c82eSsunharis_in         return true;
10216ba8c82eSsunharis_in     }
1022e9a14131SAppaRao Puli 
1023613dabeaSEd Tanous     void sendEvent(nlohmann::json eventMessage, const std::string& origin,
1024613dabeaSEd Tanous                    const std::string& resType)
102596330b99SSunitha Harish     {
1026dbb59d4dSEd Tanous         if (!serviceEnabled || (noOfEventLogSubscribers == 0U))
10276ba8c82eSsunharis_in         {
102862598e31SEd Tanous             BMCWEB_LOG_DEBUG("EventService disabled or no Subscriptions.");
10296ba8c82eSsunharis_in             return;
10306ba8c82eSsunharis_in         }
103196330b99SSunitha Harish         nlohmann::json eventRecord = nlohmann::json::array();
103296330b99SSunitha Harish 
1033613dabeaSEd Tanous         eventMessage["EventId"] = eventId;
1034613dabeaSEd Tanous         // MemberId is 0 : since we are sending one event record.
1035613dabeaSEd Tanous         eventMessage["MemberId"] = 0;
1036613dabeaSEd Tanous         eventMessage["EventTimestamp"] =
1037613dabeaSEd Tanous             redfish::time_utils::getDateTimeOffsetNow().first;
1038613dabeaSEd Tanous         eventMessage["OriginOfCondition"] = origin;
1039613dabeaSEd Tanous 
1040613dabeaSEd Tanous         eventRecord.emplace_back(std::move(eventMessage));
104196330b99SSunitha Harish 
10425e44e3d8SAppaRao Puli         for (const auto& it : subscriptionsMap)
104396330b99SSunitha Harish         {
104496330b99SSunitha Harish             std::shared_ptr<Subscription> entry = it.second;
104596330b99SSunitha Harish             bool isSubscribed = false;
104696330b99SSunitha Harish             // Search the resourceTypes list for the subscription.
104796330b99SSunitha Harish             // If resourceTypes list is empty, don't filter events
104896330b99SSunitha Harish             // send everything.
104926f6976fSEd Tanous             if (!entry->resourceTypes.empty())
105096330b99SSunitha Harish             {
10513174e4dfSEd Tanous                 for (const auto& resource : entry->resourceTypes)
105296330b99SSunitha Harish                 {
105396330b99SSunitha Harish                     if (resType == resource)
105496330b99SSunitha Harish                     {
105562598e31SEd Tanous                         BMCWEB_LOG_INFO(
105662598e31SEd Tanous                             "ResourceType {} found in the subscribed list",
105762598e31SEd Tanous                             resource);
105896330b99SSunitha Harish                         isSubscribed = true;
105996330b99SSunitha Harish                         break;
106096330b99SSunitha Harish                     }
106196330b99SSunitha Harish                 }
106296330b99SSunitha Harish             }
106396330b99SSunitha Harish             else // resourceTypes list is empty.
106496330b99SSunitha Harish             {
106596330b99SSunitha Harish                 isSubscribed = true;
106696330b99SSunitha Harish             }
106796330b99SSunitha Harish             if (isSubscribed)
106896330b99SSunitha Harish             {
1069613dabeaSEd Tanous                 nlohmann::json msgJson;
1070613dabeaSEd Tanous 
1071613dabeaSEd Tanous                 msgJson["@odata.type"] = "#Event.v1_4_0.Event";
1072613dabeaSEd Tanous                 msgJson["Name"] = "Event Log";
1073613dabeaSEd Tanous                 msgJson["Id"] = eventId;
1074613dabeaSEd Tanous                 msgJson["Events"] = eventRecord;
1075f52c03c1SCarson Labrado 
1076f52c03c1SCarson Labrado                 std::string strMsg = msgJson.dump(
1077f52c03c1SCarson Labrado                     2, ' ', true, nlohmann::json::error_handler_t::replace);
10785e44e3d8SAppaRao Puli                 entry->sendEvent(std::move(strMsg));
10798ece0e45SEd Tanous                 eventId++; // increment the eventId
108096330b99SSunitha Harish             }
108196330b99SSunitha Harish             else
108296330b99SSunitha Harish             {
108362598e31SEd Tanous                 BMCWEB_LOG_INFO("Not subscribed to this resource");
108496330b99SSunitha Harish             }
108596330b99SSunitha Harish         }
108696330b99SSunitha Harish     }
108796330b99SSunitha Harish 
10887f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
10892558979cSP Dheeraj Srujan Kumar 
10902558979cSP Dheeraj Srujan Kumar     void resetRedfishFilePosition()
10917f4eb588SAppaRao Puli     {
10922558979cSP Dheeraj Srujan Kumar         // Control would be here when Redfish file is created.
10932558979cSP Dheeraj Srujan Kumar         // Reset File Position as new file is created
10942558979cSP Dheeraj Srujan Kumar         redfishLogFilePosition = 0;
10952558979cSP Dheeraj Srujan Kumar     }
10962558979cSP Dheeraj Srujan Kumar 
10972558979cSP Dheeraj Srujan Kumar     void cacheRedfishLogFile()
10982558979cSP Dheeraj Srujan Kumar     {
10992558979cSP Dheeraj Srujan Kumar         // Open the redfish file and read till the last record.
11002558979cSP Dheeraj Srujan Kumar 
11017f4eb588SAppaRao Puli         std::ifstream logStream(redfishEventLogFile);
11027f4eb588SAppaRao Puli         if (!logStream.good())
11037f4eb588SAppaRao Puli         {
110462598e31SEd Tanous             BMCWEB_LOG_ERROR(" Redfish log file open failed ");
11057f4eb588SAppaRao Puli             return;
11067f4eb588SAppaRao Puli         }
11077f4eb588SAppaRao Puli         std::string logEntry;
11087f4eb588SAppaRao Puli         while (std::getline(logStream, logEntry))
11097f4eb588SAppaRao Puli         {
11102558979cSP Dheeraj Srujan Kumar             redfishLogFilePosition = logStream.tellg();
11117f4eb588SAppaRao Puli         }
11127f4eb588SAppaRao Puli     }
11137f4eb588SAppaRao Puli 
11147f4eb588SAppaRao Puli     void readEventLogsFromFile()
11157f4eb588SAppaRao Puli     {
11167f4eb588SAppaRao Puli         std::ifstream logStream(redfishEventLogFile);
11177f4eb588SAppaRao Puli         if (!logStream.good())
11187f4eb588SAppaRao Puli         {
111962598e31SEd Tanous             BMCWEB_LOG_ERROR(" Redfish log file open failed");
11207f4eb588SAppaRao Puli             return;
11217f4eb588SAppaRao Puli         }
11227f4eb588SAppaRao Puli 
11237f4eb588SAppaRao Puli         std::vector<EventLogObjectsType> eventRecords;
11247f4eb588SAppaRao Puli 
11257f4eb588SAppaRao Puli         std::string logEntry;
11262558979cSP Dheeraj Srujan Kumar 
11272558979cSP Dheeraj Srujan Kumar         // Get the read pointer to the next log to be read.
11282558979cSP Dheeraj Srujan Kumar         logStream.seekg(redfishLogFilePosition);
11292558979cSP Dheeraj Srujan Kumar 
11307f4eb588SAppaRao Puli         while (std::getline(logStream, logEntry))
11317f4eb588SAppaRao Puli         {
11322558979cSP Dheeraj Srujan Kumar             // Update Pointer position
11332558979cSP Dheeraj Srujan Kumar             redfishLogFilePosition = logStream.tellg();
11342558979cSP Dheeraj Srujan Kumar 
11352558979cSP Dheeraj Srujan Kumar             std::string idStr;
11362558979cSP Dheeraj Srujan Kumar             if (!event_log::getUniqueEntryID(logEntry, idStr))
11377f4eb588SAppaRao Puli             {
11387f4eb588SAppaRao Puli                 continue;
11397f4eb588SAppaRao Puli             }
11407f4eb588SAppaRao Puli 
1141e662eae8SEd Tanous             if (!serviceEnabled || noOfEventLogSubscribers == 0)
11427f4eb588SAppaRao Puli             {
11432558979cSP Dheeraj Srujan Kumar                 // If Service is not enabled, no need to compute
11442558979cSP Dheeraj Srujan Kumar                 // the remaining items below.
11452558979cSP Dheeraj Srujan Kumar                 // But, Loop must continue to keep track of Timestamp
11467f4eb588SAppaRao Puli                 continue;
11477f4eb588SAppaRao Puli             }
11487f4eb588SAppaRao Puli 
11497f4eb588SAppaRao Puli             std::string timestamp;
11507f4eb588SAppaRao Puli             std::string messageID;
11515e715de6SAppaRao Puli             std::vector<std::string> messageArgs;
11527f4eb588SAppaRao Puli             if (event_log::getEventLogParams(logEntry, timestamp, messageID,
11537f4eb588SAppaRao Puli                                              messageArgs) != 0)
11547f4eb588SAppaRao Puli             {
115562598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Read eventLog entry params failed");
11567f4eb588SAppaRao Puli                 continue;
11577f4eb588SAppaRao Puli             }
11587f4eb588SAppaRao Puli 
11597f4eb588SAppaRao Puli             std::string registryName;
11607f4eb588SAppaRao Puli             std::string messageKey;
11617f4eb588SAppaRao Puli             event_log::getRegistryAndMessageKey(messageID, registryName,
11627f4eb588SAppaRao Puli                                                 messageKey);
11637f4eb588SAppaRao Puli             if (registryName.empty() || messageKey.empty())
11647f4eb588SAppaRao Puli             {
11657f4eb588SAppaRao Puli                 continue;
11667f4eb588SAppaRao Puli             }
11677f4eb588SAppaRao Puli 
11687f4eb588SAppaRao Puli             eventRecords.emplace_back(idStr, timestamp, messageID, registryName,
11697f4eb588SAppaRao Puli                                       messageKey, messageArgs);
11707f4eb588SAppaRao Puli         }
11717f4eb588SAppaRao Puli 
1172e662eae8SEd Tanous         if (!serviceEnabled || noOfEventLogSubscribers == 0)
11732558979cSP Dheeraj Srujan Kumar         {
117462598e31SEd Tanous             BMCWEB_LOG_DEBUG("EventService disabled or no Subscriptions.");
11752558979cSP Dheeraj Srujan Kumar             return;
11762558979cSP Dheeraj Srujan Kumar         }
11772558979cSP Dheeraj Srujan Kumar 
11782558979cSP Dheeraj Srujan Kumar         if (eventRecords.empty())
11792558979cSP Dheeraj Srujan Kumar         {
11802558979cSP Dheeraj Srujan Kumar             // No Records to send
118162598e31SEd Tanous             BMCWEB_LOG_DEBUG("No log entries available to be transferred.");
11822558979cSP Dheeraj Srujan Kumar             return;
11832558979cSP Dheeraj Srujan Kumar         }
11842558979cSP Dheeraj Srujan Kumar 
11855e44e3d8SAppaRao Puli         for (const auto& it : subscriptionsMap)
11867f4eb588SAppaRao Puli         {
11877f4eb588SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
11887f4eb588SAppaRao Puli             if (entry->eventFormatType == "Event")
11897f4eb588SAppaRao Puli             {
11907f4eb588SAppaRao Puli                 entry->filterAndSendEventLogs(eventRecords);
11917f4eb588SAppaRao Puli             }
11927f4eb588SAppaRao Puli         }
11937f4eb588SAppaRao Puli     }
11947f4eb588SAppaRao Puli 
11957f4eb588SAppaRao Puli     static void watchRedfishEventLogFile()
11967f4eb588SAppaRao Puli     {
11976a9f85f9SAppaRao Puli         if (!inotifyConn)
11987f4eb588SAppaRao Puli         {
11997f4eb588SAppaRao Puli             return;
12007f4eb588SAppaRao Puli         }
12017f4eb588SAppaRao Puli 
12027f4eb588SAppaRao Puli         static std::array<char, 1024> readBuffer;
12037f4eb588SAppaRao Puli 
1204002d39b4SEd Tanous         inotifyConn->async_read_some(boost::asio::buffer(readBuffer),
12057f4eb588SAppaRao Puli                                      [&](const boost::system::error_code& ec,
12067f4eb588SAppaRao Puli                                          const std::size_t& bytesTransferred) {
12077f4eb588SAppaRao Puli             if (ec)
12087f4eb588SAppaRao Puli             {
120962598e31SEd Tanous                 BMCWEB_LOG_ERROR("Callback Error: {}", ec.message());
12107f4eb588SAppaRao Puli                 return;
12117f4eb588SAppaRao Puli             }
12127f4eb588SAppaRao Puli             std::size_t index = 0;
1213b792cc56SAppaRao Puli             while ((index + iEventSize) <= bytesTransferred)
12147f4eb588SAppaRao Puli             {
1215d3a9e084SEd Tanous                 struct inotify_event event
1216d3a9e084SEd Tanous                 {};
1217b792cc56SAppaRao Puli                 std::memcpy(&event, &readBuffer[index], iEventSize);
1218b792cc56SAppaRao Puli                 if (event.wd == dirWatchDesc)
1219b792cc56SAppaRao Puli                 {
1220b792cc56SAppaRao Puli                     if ((event.len == 0) ||
1221b792cc56SAppaRao Puli                         (index + iEventSize + event.len > bytesTransferred))
1222b792cc56SAppaRao Puli                     {
1223b792cc56SAppaRao Puli                         index += (iEventSize + event.len);
1224b792cc56SAppaRao Puli                         continue;
1225b792cc56SAppaRao Puli                     }
1226b792cc56SAppaRao Puli 
12274f568f74SJiaqing Zhao                     std::string fileName(&readBuffer[index + iEventSize]);
12284f568f74SJiaqing Zhao                     if (fileName != "redfish")
1229b792cc56SAppaRao Puli                     {
1230b792cc56SAppaRao Puli                         index += (iEventSize + event.len);
1231b792cc56SAppaRao Puli                         continue;
1232b792cc56SAppaRao Puli                     }
1233b792cc56SAppaRao Puli 
123462598e31SEd Tanous                     BMCWEB_LOG_DEBUG(
123562598e31SEd Tanous                         "Redfish log file created/deleted. event.name: {}",
123662598e31SEd Tanous                         fileName);
1237b792cc56SAppaRao Puli                     if (event.mask == IN_CREATE)
1238b792cc56SAppaRao Puli                     {
1239b792cc56SAppaRao Puli                         if (fileWatchDesc != -1)
1240b792cc56SAppaRao Puli                         {
124162598e31SEd Tanous                             BMCWEB_LOG_DEBUG(
124262598e31SEd Tanous                                 "Remove and Add inotify watcher on "
124362598e31SEd Tanous                                 "redfish event log file");
1244016761afSAppaRao Puli                             // Remove existing inotify watcher and add
1245016761afSAppaRao Puli                             // with new redfish event log file.
1246016761afSAppaRao Puli                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1247016761afSAppaRao Puli                             fileWatchDesc = -1;
1248b792cc56SAppaRao Puli                         }
1249b792cc56SAppaRao Puli 
1250b792cc56SAppaRao Puli                         fileWatchDesc = inotify_add_watch(
1251b792cc56SAppaRao Puli                             inotifyFd, redfishEventLogFile, IN_MODIFY);
1252b792cc56SAppaRao Puli                         if (fileWatchDesc == -1)
1253b792cc56SAppaRao Puli                         {
125462598e31SEd Tanous                             BMCWEB_LOG_ERROR("inotify_add_watch failed for "
125562598e31SEd Tanous                                              "redfish log file.");
1256b792cc56SAppaRao Puli                             return;
1257b792cc56SAppaRao Puli                         }
1258b792cc56SAppaRao Puli 
1259b792cc56SAppaRao Puli                         EventServiceManager::getInstance()
12602558979cSP Dheeraj Srujan Kumar                             .resetRedfishFilePosition();
1261b792cc56SAppaRao Puli                         EventServiceManager::getInstance()
1262b792cc56SAppaRao Puli                             .readEventLogsFromFile();
1263b792cc56SAppaRao Puli                     }
1264b792cc56SAppaRao Puli                     else if ((event.mask == IN_DELETE) ||
1265b792cc56SAppaRao Puli                              (event.mask == IN_MOVED_TO))
1266b792cc56SAppaRao Puli                     {
1267b792cc56SAppaRao Puli                         if (fileWatchDesc != -1)
1268b792cc56SAppaRao Puli                         {
1269b792cc56SAppaRao Puli                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1270b792cc56SAppaRao Puli                             fileWatchDesc = -1;
1271b792cc56SAppaRao Puli                         }
1272b792cc56SAppaRao Puli                     }
1273b792cc56SAppaRao Puli                 }
1274b792cc56SAppaRao Puli                 else if (event.wd == fileWatchDesc)
1275b792cc56SAppaRao Puli                 {
1276b792cc56SAppaRao Puli                     if (event.mask == IN_MODIFY)
12777f4eb588SAppaRao Puli                     {
12787f4eb588SAppaRao Puli                         EventServiceManager::getInstance()
12797f4eb588SAppaRao Puli                             .readEventLogsFromFile();
12807f4eb588SAppaRao Puli                     }
1281b792cc56SAppaRao Puli                 }
1282b792cc56SAppaRao Puli                 index += (iEventSize + event.len);
12837f4eb588SAppaRao Puli             }
12847f4eb588SAppaRao Puli 
12857f4eb588SAppaRao Puli             watchRedfishEventLogFile();
12867f4eb588SAppaRao Puli         });
12877f4eb588SAppaRao Puli     }
12887f4eb588SAppaRao Puli 
12897f4eb588SAppaRao Puli     static int startEventLogMonitor(boost::asio::io_context& ioc)
12907f4eb588SAppaRao Puli     {
129123a21a1cSEd Tanous         inotifyConn.emplace(ioc);
1292b792cc56SAppaRao Puli         inotifyFd = inotify_init1(IN_NONBLOCK);
1293b792cc56SAppaRao Puli         if (inotifyFd == -1)
12947f4eb588SAppaRao Puli         {
129562598e31SEd Tanous             BMCWEB_LOG_ERROR("inotify_init1 failed.");
12967f4eb588SAppaRao Puli             return -1;
12977f4eb588SAppaRao Puli         }
1298b792cc56SAppaRao Puli 
1299b792cc56SAppaRao Puli         // Add watch on directory to handle redfish event log file
1300b792cc56SAppaRao Puli         // create/delete.
1301b792cc56SAppaRao Puli         dirWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogDir,
1302b792cc56SAppaRao Puli                                          IN_CREATE | IN_MOVED_TO | IN_DELETE);
1303b792cc56SAppaRao Puli         if (dirWatchDesc == -1)
13047f4eb588SAppaRao Puli         {
130562598e31SEd Tanous             BMCWEB_LOG_ERROR(
130662598e31SEd Tanous                 "inotify_add_watch failed for event log directory.");
13077f4eb588SAppaRao Puli             return -1;
13087f4eb588SAppaRao Puli         }
13097f4eb588SAppaRao Puli 
1310b792cc56SAppaRao Puli         // Watch redfish event log file for modifications.
131189492a15SPatrick Williams         fileWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogFile,
131289492a15SPatrick Williams                                           IN_MODIFY);
1313b792cc56SAppaRao Puli         if (fileWatchDesc == -1)
1314b792cc56SAppaRao Puli         {
131562598e31SEd Tanous             BMCWEB_LOG_ERROR("inotify_add_watch failed for redfish log file.");
1316b792cc56SAppaRao Puli             // Don't return error if file not exist.
1317b792cc56SAppaRao Puli             // Watch on directory will handle create/delete of file.
1318b792cc56SAppaRao Puli         }
1319b792cc56SAppaRao Puli 
13207f4eb588SAppaRao Puli         // monitor redfish event log file
1321b792cc56SAppaRao Puli         inotifyConn->assign(inotifyFd);
13227f4eb588SAppaRao Puli         watchRedfishEventLogFile();
13237f4eb588SAppaRao Puli 
13247f4eb588SAppaRao Puli         return 0;
13257f4eb588SAppaRao Puli     }
13267f4eb588SAppaRao Puli 
13277f4eb588SAppaRao Puli #endif
132859d494eeSPatrick Williams     static void getReadingsForReport(sdbusplus::message_t& msg)
1329156d6b00SAppaRao Puli     {
133056d2396dSEd Tanous         if (msg.is_method_error())
133156d2396dSEd Tanous         {
133262598e31SEd Tanous             BMCWEB_LOG_ERROR("TelemetryMonitor Signal error");
133356d2396dSEd Tanous             return;
133456d2396dSEd Tanous         }
133556d2396dSEd Tanous 
1336c0353249SWludzik, Jozef         sdbusplus::message::object_path path(msg.get_path());
1337c0353249SWludzik, Jozef         std::string id = path.filename();
1338c0353249SWludzik, Jozef         if (id.empty())
1339156d6b00SAppaRao Puli         {
134062598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to get Id from path");
1341156d6b00SAppaRao Puli             return;
1342156d6b00SAppaRao Puli         }
1343156d6b00SAppaRao Puli 
1344c0353249SWludzik, Jozef         std::string interface;
1345b9d36b47SEd Tanous         dbus::utility::DBusPropertiesMap props;
1346c0353249SWludzik, Jozef         std::vector<std::string> invalidProps;
1347c0353249SWludzik, Jozef         msg.read(interface, props, invalidProps);
1348c0353249SWludzik, Jozef 
13493544d2a7SEd Tanous         auto found = std::ranges::find_if(
13503544d2a7SEd Tanous             props, [](const auto& x) { return x.first == "Readings"; });
1351c0353249SWludzik, Jozef         if (found == props.end())
1352156d6b00SAppaRao Puli         {
135362598e31SEd Tanous             BMCWEB_LOG_INFO("Failed to get Readings from Report properties");
1354156d6b00SAppaRao Puli             return;
1355156d6b00SAppaRao Puli         }
1356156d6b00SAppaRao Puli 
13571e1e598dSJonathan Doman         const telemetry::TimestampReadings* readings =
13581e1e598dSJonathan Doman             std::get_if<telemetry::TimestampReadings>(&found->second);
1359e662eae8SEd Tanous         if (readings == nullptr)
13601e1e598dSJonathan Doman         {
136162598e31SEd Tanous             BMCWEB_LOG_INFO("Failed to get Readings from Report properties");
13621e1e598dSJonathan Doman             return;
13631e1e598dSJonathan Doman         }
13641e1e598dSJonathan Doman 
1365156d6b00SAppaRao Puli         for (const auto& it :
1366156d6b00SAppaRao Puli              EventServiceManager::getInstance().subscriptionsMap)
1367156d6b00SAppaRao Puli         {
1368e05aec50SEd Tanous             Subscription& entry = *it.second;
1369c0353249SWludzik, Jozef             if (entry.eventFormatType == metricReportFormatType)
1370156d6b00SAppaRao Puli             {
13711e1e598dSJonathan Doman                 entry.filterAndSendReports(id, *readings);
1372156d6b00SAppaRao Puli             }
1373156d6b00SAppaRao Puli         }
1374156d6b00SAppaRao Puli     }
1375156d6b00SAppaRao Puli 
1376156d6b00SAppaRao Puli     void unregisterMetricReportSignal()
1377156d6b00SAppaRao Puli     {
13787d1cc387SAppaRao Puli         if (matchTelemetryMonitor)
13797d1cc387SAppaRao Puli         {
138062598e31SEd Tanous             BMCWEB_LOG_DEBUG("Metrics report signal - Unregister");
1381156d6b00SAppaRao Puli             matchTelemetryMonitor.reset();
1382156d6b00SAppaRao Puli             matchTelemetryMonitor = nullptr;
1383156d6b00SAppaRao Puli         }
13847d1cc387SAppaRao Puli     }
1385156d6b00SAppaRao Puli 
1386156d6b00SAppaRao Puli     void registerMetricReportSignal()
1387156d6b00SAppaRao Puli     {
13887d1cc387SAppaRao Puli         if (!serviceEnabled || matchTelemetryMonitor)
1389156d6b00SAppaRao Puli         {
139062598e31SEd Tanous             BMCWEB_LOG_DEBUG("Not registering metric report signal.");
1391156d6b00SAppaRao Puli             return;
1392156d6b00SAppaRao Puli         }
1393156d6b00SAppaRao Puli 
139462598e31SEd Tanous         BMCWEB_LOG_DEBUG("Metrics report signal - Register");
1395c0353249SWludzik, Jozef         std::string matchStr = "type='signal',member='PropertiesChanged',"
1396c0353249SWludzik, Jozef                                "interface='org.freedesktop.DBus.Properties',"
1397c0353249SWludzik, Jozef                                "arg0=xyz.openbmc_project.Telemetry.Report";
1398156d6b00SAppaRao Puli 
139959d494eeSPatrick Williams         matchTelemetryMonitor = std::make_shared<sdbusplus::bus::match_t>(
140056d2396dSEd Tanous             *crow::connections::systemBus, matchStr, getReadingsForReport);
1401156d6b00SAppaRao Puli     }
140223a21a1cSEd Tanous };
1403b52664e2SAppaRao Puli 
1404b52664e2SAppaRao Puli } // namespace redfish
1405