xref: /openbmc/bmcweb/features/redfish/include/event_service_manager.hpp (revision 62598e31d0988d589506d5091bd38f72d61faf5e)
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 
3211ba3979SEd Tanous #include <boost/algorithm/string/classification.hpp>
33fb4fd5d4SZhenfei Tai #include <boost/asio/io_context.hpp>
34b52664e2SAppaRao Puli #include <boost/container/flat_map.hpp>
35ef4c65b7SEd Tanous #include <boost/url/format.hpp>
36b5b40605Snitroglycerine #include <sdbusplus/bus/match.hpp>
371214b7e7SGunnar Mills 
385e44e3d8SAppaRao Puli #include <algorithm>
39b52664e2SAppaRao Puli #include <cstdlib>
40b52664e2SAppaRao Puli #include <ctime>
411bf712bcSAyushi Smriti #include <fstream>
42b52664e2SAppaRao Puli #include <memory>
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 {
8626702d01SEd Tanous     std::span<const MessageEntry>::iterator messageIt =
8726702d01SEd Tanous         std::find_if(registry.begin(), registry.end(),
887f4eb588SAppaRao Puli                      [&messageKey](const MessageEntry& messageEntry) {
8955f79e6fSEd Tanous         return messageKey == messageEntry.first;
907f4eb588SAppaRao Puli         });
9126702d01SEd Tanous     if (messageIt != registry.end())
927f4eb588SAppaRao Puli     {
937f4eb588SAppaRao Puli         return &messageIt->second;
947f4eb588SAppaRao Puli     }
957f4eb588SAppaRao Puli 
967f4eb588SAppaRao Puli     return nullptr;
977f4eb588SAppaRao Puli }
987f4eb588SAppaRao Puli 
9926ccae32SEd Tanous static const Message* formatMessage(std::string_view messageID)
1007f4eb588SAppaRao Puli {
1017f4eb588SAppaRao Puli     // Redfish MessageIds are in the form
1027f4eb588SAppaRao Puli     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
1037f4eb588SAppaRao Puli     // the right Message
1047f4eb588SAppaRao Puli     std::vector<std::string> fields;
1057f4eb588SAppaRao Puli     fields.reserve(4);
10650ebd4afSEd Tanous 
10750ebd4afSEd Tanous     bmcweb::split(fields, messageID, '.');
1087f4eb588SAppaRao Puli     if (fields.size() != 4)
1097f4eb588SAppaRao Puli     {
1107f4eb588SAppaRao Puli         return nullptr;
1117f4eb588SAppaRao Puli     }
11202cad96eSEd Tanous     const std::string& registryName = fields[0];
11302cad96eSEd Tanous     const std::string& messageKey = fields[3];
1147f4eb588SAppaRao Puli 
1157f4eb588SAppaRao Puli     // Find the right registry and check it for the MessageKey
116b304bd79SP Dheeraj Srujan Kumar     return getMsgFromRegistry(messageKey, getRegistryFromPrefix(registryName));
1177f4eb588SAppaRao Puli }
118fffb8c1fSEd Tanous } // namespace registries
1197f4eb588SAppaRao Puli 
1207f4eb588SAppaRao Puli namespace event_log
1217f4eb588SAppaRao Puli {
1222558979cSP Dheeraj Srujan Kumar inline bool getUniqueEntryID(const std::string& logEntry, std::string& entryID)
1237f4eb588SAppaRao Puli {
1247f4eb588SAppaRao Puli     static time_t prevTs = 0;
1257f4eb588SAppaRao Puli     static int index = 0;
1267f4eb588SAppaRao Puli 
1277f4eb588SAppaRao Puli     // Get the entry timestamp
1287f4eb588SAppaRao Puli     std::time_t curTs = 0;
1297f4eb588SAppaRao Puli     std::tm timeStruct = {};
1307f4eb588SAppaRao Puli     std::istringstream entryStream(logEntry);
1317f4eb588SAppaRao Puli     if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1327f4eb588SAppaRao Puli     {
1337f4eb588SAppaRao Puli         curTs = std::mktime(&timeStruct);
1347f4eb588SAppaRao Puli         if (curTs == -1)
1357f4eb588SAppaRao Puli         {
1367f4eb588SAppaRao Puli             return false;
1377f4eb588SAppaRao Puli         }
1387f4eb588SAppaRao Puli     }
1397f4eb588SAppaRao Puli     // If the timestamp isn't unique, increment the index
1407f4eb588SAppaRao Puli     index = (curTs == prevTs) ? index + 1 : 0;
1417f4eb588SAppaRao Puli 
1427f4eb588SAppaRao Puli     // Save the timestamp
1437f4eb588SAppaRao Puli     prevTs = curTs;
1447f4eb588SAppaRao Puli 
1457f4eb588SAppaRao Puli     entryID = std::to_string(curTs);
1467f4eb588SAppaRao Puli     if (index > 0)
1477f4eb588SAppaRao Puli     {
1487f4eb588SAppaRao Puli         entryID += "_" + std::to_string(index);
1497f4eb588SAppaRao Puli     }
1507f4eb588SAppaRao Puli     return true;
1517f4eb588SAppaRao Puli }
1527f4eb588SAppaRao Puli 
15323a21a1cSEd Tanous inline int getEventLogParams(const std::string& logEntry,
15423a21a1cSEd Tanous                              std::string& timestamp, std::string& messageID,
1555e715de6SAppaRao Puli                              std::vector<std::string>& messageArgs)
1567f4eb588SAppaRao Puli {
1577f4eb588SAppaRao Puli     // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
1587f4eb588SAppaRao Puli     // First get the Timestamp
159f23b7296SEd Tanous     size_t space = logEntry.find_first_of(' ');
1607f4eb588SAppaRao Puli     if (space == std::string::npos)
1617f4eb588SAppaRao Puli     {
1627f4eb588SAppaRao Puli         return -EINVAL;
1637f4eb588SAppaRao Puli     }
1647f4eb588SAppaRao Puli     timestamp = logEntry.substr(0, space);
1657f4eb588SAppaRao Puli     // Then get the log contents
166f23b7296SEd Tanous     size_t entryStart = logEntry.find_first_not_of(' ', space);
1677f4eb588SAppaRao Puli     if (entryStart == std::string::npos)
1687f4eb588SAppaRao Puli     {
1697f4eb588SAppaRao Puli         return -EINVAL;
1707f4eb588SAppaRao Puli     }
1717f4eb588SAppaRao Puli     std::string_view entry(logEntry);
1727f4eb588SAppaRao Puli     entry.remove_prefix(entryStart);
1737f4eb588SAppaRao Puli     // Use split to separate the entry into its fields
1747f4eb588SAppaRao Puli     std::vector<std::string> logEntryFields;
17550ebd4afSEd Tanous     bmcweb::split(logEntryFields, entry, ',');
1767f4eb588SAppaRao Puli     // We need at least a MessageId to be valid
17726f6976fSEd Tanous     if (logEntryFields.empty())
1787f4eb588SAppaRao Puli     {
1797f4eb588SAppaRao Puli         return -EINVAL;
1807f4eb588SAppaRao Puli     }
1817f4eb588SAppaRao Puli     messageID = logEntryFields[0];
1827f4eb588SAppaRao Puli 
1837f4eb588SAppaRao Puli     // Get the MessageArgs from the log if there are any
1847f4eb588SAppaRao Puli     if (logEntryFields.size() > 1)
1857f4eb588SAppaRao Puli     {
18602cad96eSEd Tanous         const std::string& messageArgsStart = logEntryFields[1];
1877f4eb588SAppaRao Puli         // If the first string is empty, assume there are no MessageArgs
1887f4eb588SAppaRao Puli         if (!messageArgsStart.empty())
1897f4eb588SAppaRao Puli         {
1905e715de6SAppaRao Puli             messageArgs.assign(logEntryFields.begin() + 1,
1915e715de6SAppaRao Puli                                logEntryFields.end());
1927f4eb588SAppaRao Puli         }
1937f4eb588SAppaRao Puli     }
1947f4eb588SAppaRao Puli 
1957f4eb588SAppaRao Puli     return 0;
1967f4eb588SAppaRao Puli }
1977f4eb588SAppaRao Puli 
19823a21a1cSEd Tanous inline void getRegistryAndMessageKey(const std::string& messageID,
1997f4eb588SAppaRao Puli                                      std::string& registryName,
2007f4eb588SAppaRao Puli                                      std::string& messageKey)
2017f4eb588SAppaRao Puli {
2027f4eb588SAppaRao Puli     // Redfish MessageIds are in the form
2037f4eb588SAppaRao Puli     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
2047f4eb588SAppaRao Puli     // the right Message
2057f4eb588SAppaRao Puli     std::vector<std::string> fields;
2067f4eb588SAppaRao Puli     fields.reserve(4);
20750ebd4afSEd Tanous     bmcweb::split(fields, messageID, '.');
2087f4eb588SAppaRao Puli     if (fields.size() == 4)
2097f4eb588SAppaRao Puli     {
2107f4eb588SAppaRao Puli         registryName = fields[0];
2117f4eb588SAppaRao Puli         messageKey = fields[3];
2127f4eb588SAppaRao Puli     }
2137f4eb588SAppaRao Puli }
2147f4eb588SAppaRao Puli 
21523a21a1cSEd Tanous inline int formatEventLogEntry(const std::string& logEntryID,
2167f4eb588SAppaRao Puli                                const std::string& messageID,
217c5ba4c27SEd Tanous                                const std::span<std::string_view> messageArgs,
21823a21a1cSEd Tanous                                std::string timestamp,
219b5a76932SEd Tanous                                const std::string& customText,
2207f4eb588SAppaRao Puli                                nlohmann::json& logEntryJson)
2217f4eb588SAppaRao Puli {
2227f4eb588SAppaRao Puli     // Get the Message from the MessageRegistry
223fffb8c1fSEd Tanous     const registries::Message* message = registries::formatMessage(messageID);
2247f4eb588SAppaRao Puli 
22580f595e7SEd Tanous     if (message == nullptr)
2267f4eb588SAppaRao Puli     {
22780f595e7SEd Tanous         return -1;
2287f4eb588SAppaRao Puli     }
2297f4eb588SAppaRao Puli 
23089492a15SPatrick Williams     std::string msg = redfish::registries::fillMessageArgs(messageArgs,
23189492a15SPatrick Williams                                                            message->message);
23280f595e7SEd Tanous     if (msg.empty())
23380f595e7SEd Tanous     {
23480f595e7SEd Tanous         return -1;
23580f595e7SEd Tanous     }
2367f4eb588SAppaRao Puli 
2377f4eb588SAppaRao Puli     // Get the Created time from the timestamp. The log timestamp is in
2387f4eb588SAppaRao Puli     // RFC3339 format which matches the Redfish format except for the
2397f4eb588SAppaRao Puli     // fractional seconds between the '.' and the '+', so just remove them.
240f23b7296SEd Tanous     std::size_t dot = timestamp.find_first_of('.');
241b2f7609bSEd Tanous     std::size_t plus = timestamp.find_first_of('+', dot);
2427f4eb588SAppaRao Puli     if (dot != std::string::npos && plus != std::string::npos)
2437f4eb588SAppaRao Puli     {
2447f4eb588SAppaRao Puli         timestamp.erase(dot, plus - dot);
2457f4eb588SAppaRao Puli     }
2467f4eb588SAppaRao Puli 
2477f4eb588SAppaRao Puli     // Fill in the log entry with the gathered data
2481476687dSEd Tanous     logEntryJson["EventId"] = logEntryID;
2491476687dSEd Tanous     logEntryJson["EventType"] = "Event";
25080f595e7SEd Tanous     logEntryJson["Severity"] = message->messageSeverity;
2511476687dSEd Tanous     logEntryJson["Message"] = std::move(msg);
2521476687dSEd Tanous     logEntryJson["MessageId"] = messageID;
2531476687dSEd Tanous     logEntryJson["MessageArgs"] = messageArgs;
2541476687dSEd Tanous     logEntryJson["EventTimestamp"] = std::move(timestamp);
2551476687dSEd Tanous     logEntryJson["Context"] = customText;
2567f4eb588SAppaRao Puli     return 0;
2577f4eb588SAppaRao Puli }
2587f4eb588SAppaRao Puli 
2597f4eb588SAppaRao Puli } // namespace event_log
2607f4eb588SAppaRao Puli #endif
2617f4eb588SAppaRao Puli 
26223a21a1cSEd Tanous inline bool isFilterQuerySpecialChar(char c)
26307941a88SAyushi Smriti {
26407941a88SAyushi Smriti     switch (c)
26507941a88SAyushi Smriti     {
26607941a88SAyushi Smriti         case '(':
26707941a88SAyushi Smriti         case ')':
26807941a88SAyushi Smriti         case '\'':
26907941a88SAyushi Smriti             return true;
27007941a88SAyushi Smriti         default:
27107941a88SAyushi Smriti             return false;
27207941a88SAyushi Smriti     }
27307941a88SAyushi Smriti }
27407941a88SAyushi Smriti 
27523a21a1cSEd Tanous inline bool
27623a21a1cSEd Tanous     readSSEQueryParams(std::string sseFilter, std::string& formatType,
27707941a88SAyushi Smriti                        std::vector<std::string>& messageIds,
27807941a88SAyushi Smriti                        std::vector<std::string>& registryPrefixes,
279144b6318SAppaRao Puli                        std::vector<std::string>& metricReportDefinitions)
28007941a88SAyushi Smriti {
28107941a88SAyushi Smriti     sseFilter.erase(std::remove_if(sseFilter.begin(), sseFilter.end(),
28207941a88SAyushi Smriti                                    isFilterQuerySpecialChar),
28307941a88SAyushi Smriti                     sseFilter.end());
28407941a88SAyushi Smriti 
28507941a88SAyushi Smriti     std::vector<std::string> result;
28650ebd4afSEd Tanous 
28750ebd4afSEd Tanous     // NOLINTNEXTLINE
28850ebd4afSEd Tanous     bmcweb::split(result, sseFilter, ' ');
28907941a88SAyushi Smriti 
290*62598e31SEd Tanous     BMCWEB_LOG_DEBUG("No of tokens in SEE query: {}", result.size());
29107941a88SAyushi Smriti 
29207941a88SAyushi Smriti     constexpr uint8_t divisor = 4;
29307941a88SAyushi Smriti     constexpr uint8_t minTokenSize = 3;
29407941a88SAyushi Smriti     if (result.size() % divisor != minTokenSize)
29507941a88SAyushi Smriti     {
296*62598e31SEd Tanous         BMCWEB_LOG_ERROR("Invalid SSE filter specified.");
29707941a88SAyushi Smriti         return false;
29807941a88SAyushi Smriti     }
29907941a88SAyushi Smriti 
30007941a88SAyushi Smriti     for (std::size_t i = 0; i < result.size(); i += divisor)
30107941a88SAyushi Smriti     {
30202cad96eSEd Tanous         const std::string& key = result[i];
30302cad96eSEd Tanous         const std::string& op = result[i + 1];
30402cad96eSEd Tanous         const std::string& value = result[i + 2];
30507941a88SAyushi Smriti 
30607941a88SAyushi Smriti         if ((i + minTokenSize) < result.size())
30707941a88SAyushi Smriti         {
30802cad96eSEd Tanous             const std::string& separator = result[i + minTokenSize];
30907941a88SAyushi Smriti             // SSE supports only "or" and "and" in query params.
3104e0453b1SGunnar Mills             if ((separator != "or") && (separator != "and"))
31107941a88SAyushi Smriti             {
312*62598e31SEd Tanous                 BMCWEB_LOG_ERROR(
313*62598e31SEd Tanous                     "Invalid group operator in SSE query parameters");
31407941a88SAyushi Smriti                 return false;
31507941a88SAyushi Smriti             }
31607941a88SAyushi Smriti         }
31707941a88SAyushi Smriti 
31807941a88SAyushi Smriti         // SSE supports only "eq" as per spec.
31907941a88SAyushi Smriti         if (op != "eq")
32007941a88SAyushi Smriti         {
321*62598e31SEd Tanous             BMCWEB_LOG_ERROR(
322*62598e31SEd Tanous                 "Invalid assignment operator in SSE query parameters");
32307941a88SAyushi Smriti             return false;
32407941a88SAyushi Smriti         }
32507941a88SAyushi Smriti 
326*62598e31SEd Tanous         BMCWEB_LOG_DEBUG("{} : {}", key, value);
32707941a88SAyushi Smriti         if (key == "EventFormatType")
32807941a88SAyushi Smriti         {
32907941a88SAyushi Smriti             formatType = value;
33007941a88SAyushi Smriti         }
33107941a88SAyushi Smriti         else if (key == "MessageId")
33207941a88SAyushi Smriti         {
33307941a88SAyushi Smriti             messageIds.push_back(value);
33407941a88SAyushi Smriti         }
33507941a88SAyushi Smriti         else if (key == "RegistryPrefix")
33607941a88SAyushi Smriti         {
33707941a88SAyushi Smriti             registryPrefixes.push_back(value);
33807941a88SAyushi Smriti         }
33907941a88SAyushi Smriti         else if (key == "MetricReportDefinition")
34007941a88SAyushi Smriti         {
34107941a88SAyushi Smriti             metricReportDefinitions.push_back(value);
34207941a88SAyushi Smriti         }
34307941a88SAyushi Smriti         else
34407941a88SAyushi Smriti         {
345*62598e31SEd Tanous             BMCWEB_LOG_ERROR("Invalid property({})in SSE filter query.", key);
34607941a88SAyushi Smriti             return false;
34707941a88SAyushi Smriti         }
34807941a88SAyushi Smriti     }
34907941a88SAyushi Smriti     return true;
35007941a88SAyushi Smriti }
35107941a88SAyushi Smriti 
35228afb49cSJunLin Chen class Subscription : public persistent_data::UserSubscription
353b52664e2SAppaRao Puli {
354b52664e2SAppaRao Puli   public:
355b52664e2SAppaRao Puli     Subscription(const Subscription&) = delete;
356b52664e2SAppaRao Puli     Subscription& operator=(const Subscription&) = delete;
357b52664e2SAppaRao Puli     Subscription(Subscription&&) = delete;
358b52664e2SAppaRao Puli     Subscription& operator=(Subscription&&) = delete;
359b52664e2SAppaRao Puli 
360eb1c47d3SEd Tanous     Subscription(const std::string& inHost, uint16_t inPort,
361f8ca6d79SEd Tanous                  const std::string& inPath, const std::string& inUriProto,
362f8ca6d79SEd Tanous                  boost::asio::io_context& ioc) :
363d14a48ffSCarson Labrado         host(inHost),
364d14a48ffSCarson Labrado         port(inPort), policy(std::make_shared<crow::ConnectionPolicy>()),
3655e44e3d8SAppaRao Puli         path(inPath), uriProto(inUriProto)
366b52664e2SAppaRao Puli     {
3675e44e3d8SAppaRao Puli         client.emplace(ioc, policy);
3687adb85acSSunitha Harish         // Subscription constructor
369d14a48ffSCarson Labrado         policy->invalidResp = retryRespHandler;
370b52664e2SAppaRao Puli     }
3714bbf237fSAppaRao Puli 
3725e44e3d8SAppaRao Puli     explicit Subscription(crow::sse_socket::Connection& connIn) :
3735e44e3d8SAppaRao Puli         sseConn(&connIn)
3745e44e3d8SAppaRao Puli     {}
3755e44e3d8SAppaRao Puli 
3769f616dd1SEd Tanous     ~Subscription() = default;
377b52664e2SAppaRao Puli 
3785e44e3d8SAppaRao Puli     bool sendEvent(std::string&& msg)
379b52664e2SAppaRao Puli     {
3806ba8c82eSsunharis_in         persistent_data::EventServiceConfig eventServiceConfig =
3816ba8c82eSsunharis_in             persistent_data::EventServiceStore::getInstance()
3826ba8c82eSsunharis_in                 .getEventServiceConfig();
3836ba8c82eSsunharis_in         if (!eventServiceConfig.enabled)
3846ba8c82eSsunharis_in         {
3856ba8c82eSsunharis_in             return false;
3866ba8c82eSsunharis_in         }
3876ba8c82eSsunharis_in 
388e38778a5SAppaRao Puli         bool useSSL = (uriProto == "https");
389f52c03c1SCarson Labrado         // A connection pool will be created if one does not already exist
3905e44e3d8SAppaRao Puli         if (client)
3915e44e3d8SAppaRao Puli         {
3925e44e3d8SAppaRao Puli             client->sendData(std::move(msg), host, port, path, useSSL,
3935e44e3d8SAppaRao Puli                              httpHeaders, boost::beast::http::verb::post);
3945e44e3d8SAppaRao Puli             return true;
3955e44e3d8SAppaRao Puli         }
3967adb85acSSunitha Harish 
3974bbf237fSAppaRao Puli         if (sseConn != nullptr)
3984bbf237fSAppaRao Puli         {
3995e44e3d8SAppaRao Puli             eventSeqNum++;
4005e44e3d8SAppaRao Puli             sseConn->sendEvent(std::to_string(eventSeqNum), msg);
4014bbf237fSAppaRao Puli         }
4026ba8c82eSsunharis_in         return true;
4034bbf237fSAppaRao Puli     }
4044bbf237fSAppaRao Puli 
4056ba8c82eSsunharis_in     bool sendTestEventLog()
4060b4bdd93SAppaRao Puli     {
4070b4bdd93SAppaRao Puli         nlohmann::json logEntryArray;
4080b4bdd93SAppaRao Puli         logEntryArray.push_back({});
4090b4bdd93SAppaRao Puli         nlohmann::json& logEntryJson = logEntryArray.back();
4100b4bdd93SAppaRao Puli 
411613dabeaSEd Tanous         logEntryJson["EventId"] = "TestID";
412613dabeaSEd Tanous         logEntryJson["EventType"] = "Event";
413613dabeaSEd Tanous         logEntryJson["Severity"] = "OK";
414613dabeaSEd Tanous         logEntryJson["Message"] = "Generated test event";
415613dabeaSEd Tanous         logEntryJson["MessageId"] = "OpenBMC.0.2.TestEventLog";
416613dabeaSEd Tanous         logEntryJson["MessageArgs"] = nlohmann::json::array();
417613dabeaSEd Tanous         logEntryJson["EventTimestamp"] =
418613dabeaSEd Tanous             redfish::time_utils::getDateTimeOffsetNow().first;
419613dabeaSEd Tanous         logEntryJson["Context"] = customText;
4200b4bdd93SAppaRao Puli 
4211476687dSEd Tanous         nlohmann::json msg;
4221476687dSEd Tanous         msg["@odata.type"] = "#Event.v1_4_0.Event";
4231476687dSEd Tanous         msg["Id"] = std::to_string(eventSeqNum);
4241476687dSEd Tanous         msg["Name"] = "Event Log";
4251476687dSEd Tanous         msg["Events"] = logEntryArray;
4260b4bdd93SAppaRao Puli 
42789492a15SPatrick Williams         std::string strMsg = msg.dump(2, ' ', true,
42889492a15SPatrick Williams                                       nlohmann::json::error_handler_t::replace);
4295e44e3d8SAppaRao Puli         return sendEvent(std::move(strMsg));
4300b4bdd93SAppaRao Puli     }
4310b4bdd93SAppaRao Puli 
4327f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
4337f4eb588SAppaRao Puli     void filterAndSendEventLogs(
4347f4eb588SAppaRao Puli         const std::vector<EventLogObjectsType>& eventRecords)
4357f4eb588SAppaRao Puli     {
4367f4eb588SAppaRao Puli         nlohmann::json logEntryArray;
4377f4eb588SAppaRao Puli         for (const EventLogObjectsType& logEntry : eventRecords)
4387f4eb588SAppaRao Puli         {
4397f4eb588SAppaRao Puli             const std::string& idStr = std::get<0>(logEntry);
4407f4eb588SAppaRao Puli             const std::string& timestamp = std::get<1>(logEntry);
4417f4eb588SAppaRao Puli             const std::string& messageID = std::get<2>(logEntry);
4427f4eb588SAppaRao Puli             const std::string& registryName = std::get<3>(logEntry);
4437f4eb588SAppaRao Puli             const std::string& messageKey = std::get<4>(logEntry);
4445e715de6SAppaRao Puli             const std::vector<std::string>& messageArgs = std::get<5>(logEntry);
4457f4eb588SAppaRao Puli 
4467f4eb588SAppaRao Puli             // If registryPrefixes list is empty, don't filter events
4477f4eb588SAppaRao Puli             // send everything.
44826f6976fSEd Tanous             if (!registryPrefixes.empty())
4497f4eb588SAppaRao Puli             {
4507f4eb588SAppaRao Puli                 auto obj = std::find(registryPrefixes.begin(),
4517f4eb588SAppaRao Puli                                      registryPrefixes.end(), registryName);
4527f4eb588SAppaRao Puli                 if (obj == registryPrefixes.end())
4537f4eb588SAppaRao Puli                 {
4547f4eb588SAppaRao Puli                     continue;
4557f4eb588SAppaRao Puli                 }
4567f4eb588SAppaRao Puli             }
4577f4eb588SAppaRao Puli 
4587f4eb588SAppaRao Puli             // If registryMsgIds list is empty, don't filter events
4597f4eb588SAppaRao Puli             // send everything.
46026f6976fSEd Tanous             if (!registryMsgIds.empty())
4617f4eb588SAppaRao Puli             {
4627f4eb588SAppaRao Puli                 auto obj = std::find(registryMsgIds.begin(),
4637f4eb588SAppaRao Puli                                      registryMsgIds.end(), messageKey);
4647f4eb588SAppaRao Puli                 if (obj == registryMsgIds.end())
4657f4eb588SAppaRao Puli                 {
4667f4eb588SAppaRao Puli                     continue;
4677f4eb588SAppaRao Puli                 }
4687f4eb588SAppaRao Puli             }
4697f4eb588SAppaRao Puli 
470c5ba4c27SEd Tanous             std::vector<std::string_view> messageArgsView(messageArgs.begin(),
471c5ba4c27SEd Tanous                                                           messageArgs.end());
472c5ba4c27SEd Tanous 
4737f4eb588SAppaRao Puli             logEntryArray.push_back({});
4747f4eb588SAppaRao Puli             nlohmann::json& bmcLogEntry = logEntryArray.back();
475c5ba4c27SEd Tanous             if (event_log::formatEventLogEntry(idStr, messageID,
476c5ba4c27SEd Tanous                                                messageArgsView, timestamp,
477c5ba4c27SEd Tanous                                                customText, bmcLogEntry) != 0)
4787f4eb588SAppaRao Puli             {
479*62598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Read eventLog entry failed");
4807f4eb588SAppaRao Puli                 continue;
4817f4eb588SAppaRao Puli             }
4827f4eb588SAppaRao Puli         }
4837f4eb588SAppaRao Puli 
48426f6976fSEd Tanous         if (logEntryArray.empty())
4857f4eb588SAppaRao Puli         {
486*62598e31SEd Tanous             BMCWEB_LOG_DEBUG("No log entries available to be transferred.");
4877f4eb588SAppaRao Puli             return;
4887f4eb588SAppaRao Puli         }
4897f4eb588SAppaRao Puli 
4901476687dSEd Tanous         nlohmann::json msg;
4911476687dSEd Tanous         msg["@odata.type"] = "#Event.v1_4_0.Event";
4921476687dSEd Tanous         msg["Id"] = std::to_string(eventSeqNum);
4931476687dSEd Tanous         msg["Name"] = "Event Log";
4941476687dSEd Tanous         msg["Events"] = logEntryArray;
49589492a15SPatrick Williams         std::string strMsg = msg.dump(2, ' ', true,
49689492a15SPatrick Williams                                       nlohmann::json::error_handler_t::replace);
4975e44e3d8SAppaRao Puli         sendEvent(std::move(strMsg));
4985e44e3d8SAppaRao Puli         eventSeqNum++;
4997f4eb588SAppaRao Puli     }
5007f4eb588SAppaRao Puli #endif
5017f4eb588SAppaRao Puli 
502248d0230SEd Tanous     void filterAndSendReports(const std::string& reportId,
5031e1e598dSJonathan Doman                               const telemetry::TimestampReadings& var)
504156d6b00SAppaRao Puli     {
505ef4c65b7SEd Tanous         boost::urls::url mrdUri = boost::urls::format(
506ef4c65b7SEd Tanous             "/redfish/v1/TelemetryService/MetricReportDefinitions/{}",
507ef4c65b7SEd Tanous             reportId);
508156d6b00SAppaRao Puli 
509156d6b00SAppaRao Puli         // Empty list means no filter. Send everything.
51026f6976fSEd Tanous         if (!metricReportDefinitions.empty())
511156d6b00SAppaRao Puli         {
512156d6b00SAppaRao Puli             if (std::find(metricReportDefinitions.begin(),
513156d6b00SAppaRao Puli                           metricReportDefinitions.end(),
514079360aeSEd Tanous                           mrdUri.buffer()) == metricReportDefinitions.end())
515156d6b00SAppaRao Puli             {
516156d6b00SAppaRao Puli                 return;
517156d6b00SAppaRao Puli             }
518156d6b00SAppaRao Puli         }
519156d6b00SAppaRao Puli 
520c0353249SWludzik, Jozef         nlohmann::json msg;
521248d0230SEd Tanous         if (!telemetry::fillReport(msg, reportId, var))
522156d6b00SAppaRao Puli         {
523*62598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to fill the MetricReport for DBus "
524*62598e31SEd Tanous                              "Report with id {}",
525*62598e31SEd Tanous                              reportId);
526c0353249SWludzik, Jozef             return;
527156d6b00SAppaRao Puli         }
528156d6b00SAppaRao Puli 
52922daffd7SAppaRao Puli         // Context is set by user during Event subscription and it must be
53022daffd7SAppaRao Puli         // set for MetricReport response.
53122daffd7SAppaRao Puli         if (!customText.empty())
53222daffd7SAppaRao Puli         {
53322daffd7SAppaRao Puli             msg["Context"] = customText;
53422daffd7SAppaRao Puli         }
53522daffd7SAppaRao Puli 
53689492a15SPatrick Williams         std::string strMsg = msg.dump(2, ' ', true,
53789492a15SPatrick Williams                                       nlohmann::json::error_handler_t::replace);
5385e44e3d8SAppaRao Puli         sendEvent(std::move(strMsg));
539156d6b00SAppaRao Puli     }
540156d6b00SAppaRao Puli 
541d14a48ffSCarson Labrado     void updateRetryConfig(uint32_t retryAttempts,
542d14a48ffSCarson Labrado                            uint32_t retryTimeoutInterval)
543fe44eb0bSAyushi Smriti     {
544d14a48ffSCarson Labrado         policy->maxRetryAttempts = retryAttempts;
545d14a48ffSCarson Labrado         policy->retryIntervalSecs = std::chrono::seconds(retryTimeoutInterval);
54662de0c68SAppaRao Puli     }
547fe44eb0bSAyushi Smriti 
5489eb808c1SEd Tanous     uint64_t getEventSeqNum() const
54996330b99SSunitha Harish     {
55096330b99SSunitha Harish         return eventSeqNum;
55196330b99SSunitha Harish     }
55296330b99SSunitha Harish 
5535e44e3d8SAppaRao Puli     void setSubscriptionId(const std::string& id2)
5545e44e3d8SAppaRao Puli     {
555*62598e31SEd Tanous         BMCWEB_LOG_DEBUG("Subscription ID: {}", id2);
5565e44e3d8SAppaRao Puli         subId = id2;
5575e44e3d8SAppaRao Puli     }
5585e44e3d8SAppaRao Puli 
5595e44e3d8SAppaRao Puli     std::string getSubscriptionId()
5605e44e3d8SAppaRao Puli     {
5615e44e3d8SAppaRao Puli         return subId;
5625e44e3d8SAppaRao Puli     }
5635e44e3d8SAppaRao Puli 
5645e44e3d8SAppaRao Puli     bool matchSseId(const crow::sse_socket::Connection& thisConn)
5655e44e3d8SAppaRao Puli     {
5665e44e3d8SAppaRao Puli         return &thisConn == sseConn;
5675e44e3d8SAppaRao Puli     }
5685e44e3d8SAppaRao Puli 
569b52664e2SAppaRao Puli   private:
5705e44e3d8SAppaRao Puli     std::string subId;
571d14a48ffSCarson Labrado     uint64_t eventSeqNum = 1;
572b52664e2SAppaRao Puli     std::string host;
573eb1c47d3SEd Tanous     uint16_t port = 0;
574d14a48ffSCarson Labrado     std::shared_ptr<crow::ConnectionPolicy> policy;
5755e44e3d8SAppaRao Puli     crow::sse_socket::Connection* sseConn = nullptr;
5765e44e3d8SAppaRao Puli     std::optional<crow::HttpClient> client;
577b52664e2SAppaRao Puli     std::string path;
578b52664e2SAppaRao Puli     std::string uriProto;
579a7a80296SCarson Labrado 
580a7a80296SCarson Labrado     // Check used to indicate what response codes are valid as part of our retry
581a7a80296SCarson Labrado     // policy.  2XX is considered acceptable
582a7a80296SCarson Labrado     static boost::system::error_code retryRespHandler(unsigned int respCode)
583a7a80296SCarson Labrado     {
584*62598e31SEd Tanous         BMCWEB_LOG_DEBUG(
585*62598e31SEd Tanous             "Checking response code validity for SubscriptionEvent");
586a7a80296SCarson Labrado         if ((respCode < 200) || (respCode >= 300))
587a7a80296SCarson Labrado         {
588a7a80296SCarson Labrado             return boost::system::errc::make_error_code(
589a7a80296SCarson Labrado                 boost::system::errc::result_out_of_range);
590a7a80296SCarson Labrado         }
591a7a80296SCarson Labrado 
592a7a80296SCarson Labrado         // Return 0 if the response code is valid
593a7a80296SCarson Labrado         return boost::system::errc::make_error_code(
594a7a80296SCarson Labrado             boost::system::errc::success);
5959fa6d147SNan Zhou     }
596b52664e2SAppaRao Puli };
597b52664e2SAppaRao Puli 
598b52664e2SAppaRao Puli class EventServiceManager
599b52664e2SAppaRao Puli {
600b52664e2SAppaRao Puli   private:
601d3a9e084SEd Tanous     bool serviceEnabled = false;
602d3a9e084SEd Tanous     uint32_t retryAttempts = 0;
603d3a9e084SEd Tanous     uint32_t retryTimeoutInterval = 0;
6047d1cc387SAppaRao Puli 
6052558979cSP Dheeraj Srujan Kumar     std::streampos redfishLogFilePosition{0};
6069f616dd1SEd Tanous     size_t noOfEventLogSubscribers{0};
6079f616dd1SEd Tanous     size_t noOfMetricReportSubscribers{0};
60859d494eeSPatrick Williams     std::shared_ptr<sdbusplus::bus::match_t> matchTelemetryMonitor;
609b52664e2SAppaRao Puli     boost::container::flat_map<std::string, std::shared_ptr<Subscription>>
610b52664e2SAppaRao Puli         subscriptionsMap;
611b52664e2SAppaRao Puli 
6129f616dd1SEd Tanous     uint64_t eventId{1};
61396330b99SSunitha Harish 
614f8ca6d79SEd Tanous     boost::asio::io_context& ioc;
615f8ca6d79SEd Tanous 
616b52664e2SAppaRao Puli   public:
6179f616dd1SEd Tanous     EventServiceManager(const EventServiceManager&) = delete;
6189f616dd1SEd Tanous     EventServiceManager& operator=(const EventServiceManager&) = delete;
6199f616dd1SEd Tanous     EventServiceManager(EventServiceManager&&) = delete;
6209f616dd1SEd Tanous     EventServiceManager& operator=(EventServiceManager&&) = delete;
621ecd6a3a2SEd Tanous     ~EventServiceManager() = default;
6229f616dd1SEd Tanous 
623f8ca6d79SEd Tanous     explicit EventServiceManager(boost::asio::io_context& iocIn) : ioc(iocIn)
624b52664e2SAppaRao Puli     {
625f8ca6d79SEd Tanous         // Load config from persist store.
626f8ca6d79SEd Tanous         initConfig();
627f8ca6d79SEd Tanous     }
628f8ca6d79SEd Tanous 
629f8ca6d79SEd Tanous     static EventServiceManager&
630f8ca6d79SEd Tanous         getInstance(boost::asio::io_context* ioc = nullptr)
631f8ca6d79SEd Tanous     {
632f8ca6d79SEd Tanous         static EventServiceManager handler(*ioc);
633b52664e2SAppaRao Puli         return handler;
634b52664e2SAppaRao Puli     }
635b52664e2SAppaRao Puli 
6361bf712bcSAyushi Smriti     void initConfig()
6371bf712bcSAyushi Smriti     {
63828afb49cSJunLin Chen         loadOldBehavior();
6391bf712bcSAyushi Smriti 
64028afb49cSJunLin Chen         persistent_data::EventServiceConfig eventServiceConfig =
64128afb49cSJunLin Chen             persistent_data::EventServiceStore::getInstance()
64228afb49cSJunLin Chen                 .getEventServiceConfig();
6431bf712bcSAyushi Smriti 
64428afb49cSJunLin Chen         serviceEnabled = eventServiceConfig.enabled;
64528afb49cSJunLin Chen         retryAttempts = eventServiceConfig.retryAttempts;
64628afb49cSJunLin Chen         retryTimeoutInterval = eventServiceConfig.retryTimeoutInterval;
6471bf712bcSAyushi Smriti 
64828afb49cSJunLin Chen         for (const auto& it : persistent_data::EventServiceStore::getInstance()
64928afb49cSJunLin Chen                                   .subscriptionsConfigMap)
6501bf712bcSAyushi Smriti         {
65128afb49cSJunLin Chen             std::shared_ptr<persistent_data::UserSubscription> newSub =
65228afb49cSJunLin Chen                 it.second;
6534bbf237fSAppaRao Puli 
6541bf712bcSAyushi Smriti             std::string host;
6551bf712bcSAyushi Smriti             std::string urlProto;
656eb1c47d3SEd Tanous             uint16_t port = 0;
6571bf712bcSAyushi Smriti             std::string path;
65811baefe4SEd Tanous             bool status = crow::utility::validateAndSplitUrl(
65911baefe4SEd Tanous                 newSub->destinationUrl, urlProto, host, port, path);
6601bf712bcSAyushi Smriti 
6611bf712bcSAyushi Smriti             if (!status)
6621bf712bcSAyushi Smriti             {
663*62598e31SEd Tanous                 BMCWEB_LOG_ERROR(
664*62598e31SEd Tanous                     "Failed to validate and split destination url");
6651bf712bcSAyushi Smriti                 continue;
6661bf712bcSAyushi Smriti             }
6671bf712bcSAyushi Smriti             std::shared_ptr<Subscription> subValue =
668f8ca6d79SEd Tanous                 std::make_shared<Subscription>(host, port, path, urlProto, ioc);
6691bf712bcSAyushi Smriti 
67028afb49cSJunLin Chen             subValue->id = newSub->id;
67128afb49cSJunLin Chen             subValue->destinationUrl = newSub->destinationUrl;
67228afb49cSJunLin Chen             subValue->protocol = newSub->protocol;
67328afb49cSJunLin Chen             subValue->retryPolicy = newSub->retryPolicy;
67428afb49cSJunLin Chen             subValue->customText = newSub->customText;
67528afb49cSJunLin Chen             subValue->eventFormatType = newSub->eventFormatType;
67628afb49cSJunLin Chen             subValue->subscriptionType = newSub->subscriptionType;
67728afb49cSJunLin Chen             subValue->registryMsgIds = newSub->registryMsgIds;
67828afb49cSJunLin Chen             subValue->registryPrefixes = newSub->registryPrefixes;
67928afb49cSJunLin Chen             subValue->resourceTypes = newSub->resourceTypes;
68028afb49cSJunLin Chen             subValue->httpHeaders = newSub->httpHeaders;
68128afb49cSJunLin Chen             subValue->metricReportDefinitions = newSub->metricReportDefinitions;
6821bf712bcSAyushi Smriti 
68328afb49cSJunLin Chen             if (subValue->id.empty())
6841bf712bcSAyushi Smriti             {
685*62598e31SEd Tanous                 BMCWEB_LOG_ERROR("Failed to add subscription");
6861bf712bcSAyushi Smriti             }
68728afb49cSJunLin Chen             subscriptionsMap.insert(std::pair(subValue->id, subValue));
68828afb49cSJunLin Chen 
68928afb49cSJunLin Chen             updateNoOfSubscribersCount();
69028afb49cSJunLin Chen 
69128afb49cSJunLin Chen #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
6922558979cSP Dheeraj Srujan Kumar 
6932558979cSP Dheeraj Srujan Kumar             cacheRedfishLogFile();
6942558979cSP Dheeraj Srujan Kumar 
69528afb49cSJunLin Chen #endif
69628afb49cSJunLin Chen             // Update retry configuration.
69728afb49cSJunLin Chen             subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
6981bf712bcSAyushi Smriti         }
6991bf712bcSAyushi Smriti     }
7001bf712bcSAyushi Smriti 
70156d2396dSEd Tanous     static void loadOldBehavior()
702b52664e2SAppaRao Puli     {
70328afb49cSJunLin Chen         std::ifstream eventConfigFile(eventServiceFile);
70428afb49cSJunLin Chen         if (!eventConfigFile.good())
7051bf712bcSAyushi Smriti         {
706*62598e31SEd Tanous             BMCWEB_LOG_DEBUG("Old eventService config not exist");
70728afb49cSJunLin Chen             return;
70828afb49cSJunLin Chen         }
70928afb49cSJunLin Chen         auto jsonData = nlohmann::json::parse(eventConfigFile, nullptr, false);
71028afb49cSJunLin Chen         if (jsonData.is_discarded())
7114bbf237fSAppaRao Puli         {
712*62598e31SEd Tanous             BMCWEB_LOG_ERROR("Old eventService config parse error.");
71328afb49cSJunLin Chen             return;
71428afb49cSJunLin Chen         }
71528afb49cSJunLin Chen 
71628afb49cSJunLin Chen         for (const auto& item : jsonData.items())
71728afb49cSJunLin Chen         {
71828afb49cSJunLin Chen             if (item.key() == "Configuration")
71928afb49cSJunLin Chen             {
72028afb49cSJunLin Chen                 persistent_data::EventServiceStore::getInstance()
72128afb49cSJunLin Chen                     .getEventServiceConfig()
72228afb49cSJunLin Chen                     .fromJson(item.value());
72328afb49cSJunLin Chen             }
72428afb49cSJunLin Chen             else if (item.key() == "Subscriptions")
72528afb49cSJunLin Chen             {
72628afb49cSJunLin Chen                 for (const auto& elem : item.value())
72728afb49cSJunLin Chen                 {
72828afb49cSJunLin Chen                     std::shared_ptr<persistent_data::UserSubscription>
72928afb49cSJunLin Chen                         newSubscription =
73028afb49cSJunLin Chen                             persistent_data::UserSubscription::fromJson(elem,
73128afb49cSJunLin Chen                                                                         true);
73228afb49cSJunLin Chen                     if (newSubscription == nullptr)
73328afb49cSJunLin Chen                     {
734*62598e31SEd Tanous                         BMCWEB_LOG_ERROR("Problem reading subscription "
735*62598e31SEd Tanous                                          "from old persistent store");
7364bbf237fSAppaRao Puli                         continue;
7374bbf237fSAppaRao Puli                     }
7381bf712bcSAyushi Smriti 
73928afb49cSJunLin Chen                     std::uniform_int_distribution<uint32_t> dist(0);
74028afb49cSJunLin Chen                     bmcweb::OpenSSLGenerator gen;
7411bf712bcSAyushi Smriti 
74228afb49cSJunLin Chen                     std::string id;
7431bf712bcSAyushi Smriti 
74428afb49cSJunLin Chen                     int retry = 3;
745e662eae8SEd Tanous                     while (retry != 0)
7461bf712bcSAyushi Smriti                     {
74728afb49cSJunLin Chen                         id = std::to_string(dist(gen));
74828afb49cSJunLin Chen                         if (gen.error())
7497d1cc387SAppaRao Puli                         {
75028afb49cSJunLin Chen                             retry = 0;
75128afb49cSJunLin Chen                             break;
75228afb49cSJunLin Chen                         }
75328afb49cSJunLin Chen                         newSubscription->id = id;
75428afb49cSJunLin Chen                         auto inserted =
75528afb49cSJunLin Chen                             persistent_data::EventServiceStore::getInstance()
75628afb49cSJunLin Chen                                 .subscriptionsConfigMap.insert(
75728afb49cSJunLin Chen                                     std::pair(id, newSubscription));
75828afb49cSJunLin Chen                         if (inserted.second)
75928afb49cSJunLin Chen                         {
76028afb49cSJunLin Chen                             break;
76128afb49cSJunLin Chen                         }
76228afb49cSJunLin Chen                         --retry;
7637d1cc387SAppaRao Puli                     }
7647d1cc387SAppaRao Puli 
76528afb49cSJunLin Chen                     if (retry <= 0)
76628afb49cSJunLin Chen                     {
767*62598e31SEd Tanous                         BMCWEB_LOG_ERROR(
768*62598e31SEd Tanous                             "Failed to generate random number from old "
769*62598e31SEd Tanous                             "persistent store");
77028afb49cSJunLin Chen                         continue;
77128afb49cSJunLin Chen                     }
77228afb49cSJunLin Chen                 }
77328afb49cSJunLin Chen             }
77428afb49cSJunLin Chen 
77528afb49cSJunLin Chen             persistent_data::getConfig().writeData();
77628afb49cSJunLin Chen             std::remove(eventServiceFile);
777*62598e31SEd Tanous             BMCWEB_LOG_DEBUG("Remove old eventservice config");
77828afb49cSJunLin Chen         }
77928afb49cSJunLin Chen     }
78028afb49cSJunLin Chen 
7819eb808c1SEd Tanous     void updateSubscriptionData() const
78228afb49cSJunLin Chen     {
78328afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
78428afb49cSJunLin Chen             .eventServiceConfig.enabled = serviceEnabled;
78528afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
78628afb49cSJunLin Chen             .eventServiceConfig.retryAttempts = retryAttempts;
78728afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
78828afb49cSJunLin Chen             .eventServiceConfig.retryTimeoutInterval = retryTimeoutInterval;
78928afb49cSJunLin Chen 
79028afb49cSJunLin Chen         persistent_data::getConfig().writeData();
79128afb49cSJunLin Chen     }
79228afb49cSJunLin Chen 
79328afb49cSJunLin Chen     void setEventServiceConfig(const persistent_data::EventServiceConfig& cfg)
7947d1cc387SAppaRao Puli     {
7957d1cc387SAppaRao Puli         bool updateConfig = false;
796fe44eb0bSAyushi Smriti         bool updateRetryCfg = false;
7977d1cc387SAppaRao Puli 
79828afb49cSJunLin Chen         if (serviceEnabled != cfg.enabled)
7997d1cc387SAppaRao Puli         {
80028afb49cSJunLin Chen             serviceEnabled = cfg.enabled;
801e662eae8SEd Tanous             if (serviceEnabled && noOfMetricReportSubscribers != 0U)
8027d1cc387SAppaRao Puli             {
8037d1cc387SAppaRao Puli                 registerMetricReportSignal();
8047d1cc387SAppaRao Puli             }
8057d1cc387SAppaRao Puli             else
8067d1cc387SAppaRao Puli             {
8077d1cc387SAppaRao Puli                 unregisterMetricReportSignal();
8087d1cc387SAppaRao Puli             }
8097d1cc387SAppaRao Puli             updateConfig = true;
8107d1cc387SAppaRao Puli         }
8117d1cc387SAppaRao Puli 
81228afb49cSJunLin Chen         if (retryAttempts != cfg.retryAttempts)
8137d1cc387SAppaRao Puli         {
81428afb49cSJunLin Chen             retryAttempts = cfg.retryAttempts;
8157d1cc387SAppaRao Puli             updateConfig = true;
816fe44eb0bSAyushi Smriti             updateRetryCfg = true;
8177d1cc387SAppaRao Puli         }
8187d1cc387SAppaRao Puli 
81928afb49cSJunLin Chen         if (retryTimeoutInterval != cfg.retryTimeoutInterval)
8207d1cc387SAppaRao Puli         {
82128afb49cSJunLin Chen             retryTimeoutInterval = cfg.retryTimeoutInterval;
8227d1cc387SAppaRao Puli             updateConfig = true;
823fe44eb0bSAyushi Smriti             updateRetryCfg = true;
8247d1cc387SAppaRao Puli         }
8257d1cc387SAppaRao Puli 
8267d1cc387SAppaRao Puli         if (updateConfig)
8277d1cc387SAppaRao Puli         {
8287d1cc387SAppaRao Puli             updateSubscriptionData();
8297d1cc387SAppaRao Puli         }
830fe44eb0bSAyushi Smriti 
831fe44eb0bSAyushi Smriti         if (updateRetryCfg)
832fe44eb0bSAyushi Smriti         {
833fe44eb0bSAyushi Smriti             // Update the changed retry config to all subscriptions
834fe44eb0bSAyushi Smriti             for (const auto& it :
835fe44eb0bSAyushi Smriti                  EventServiceManager::getInstance().subscriptionsMap)
836fe44eb0bSAyushi Smriti             {
8375e44e3d8SAppaRao Puli                 Subscription& entry = *it.second;
8385e44e3d8SAppaRao Puli                 entry.updateRetryConfig(retryAttempts, retryTimeoutInterval);
839fe44eb0bSAyushi Smriti             }
840fe44eb0bSAyushi Smriti         }
8417d1cc387SAppaRao Puli     }
8427d1cc387SAppaRao Puli 
8437d1cc387SAppaRao Puli     void updateNoOfSubscribersCount()
8447d1cc387SAppaRao Puli     {
8457d1cc387SAppaRao Puli         size_t eventLogSubCount = 0;
8467d1cc387SAppaRao Puli         size_t metricReportSubCount = 0;
8477d1cc387SAppaRao Puli         for (const auto& it : subscriptionsMap)
8487d1cc387SAppaRao Puli         {
8497d1cc387SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
8507d1cc387SAppaRao Puli             if (entry->eventFormatType == eventFormatType)
8517d1cc387SAppaRao Puli             {
8527d1cc387SAppaRao Puli                 eventLogSubCount++;
8537d1cc387SAppaRao Puli             }
8547d1cc387SAppaRao Puli             else if (entry->eventFormatType == metricReportFormatType)
8557d1cc387SAppaRao Puli             {
8567d1cc387SAppaRao Puli                 metricReportSubCount++;
8577d1cc387SAppaRao Puli             }
8587d1cc387SAppaRao Puli         }
8597d1cc387SAppaRao Puli 
8607d1cc387SAppaRao Puli         noOfEventLogSubscribers = eventLogSubCount;
8617d1cc387SAppaRao Puli         if (noOfMetricReportSubscribers != metricReportSubCount)
8627d1cc387SAppaRao Puli         {
8637d1cc387SAppaRao Puli             noOfMetricReportSubscribers = metricReportSubCount;
864e662eae8SEd Tanous             if (noOfMetricReportSubscribers != 0U)
8657d1cc387SAppaRao Puli             {
8667d1cc387SAppaRao Puli                 registerMetricReportSignal();
8677d1cc387SAppaRao Puli             }
8687d1cc387SAppaRao Puli             else
8697d1cc387SAppaRao Puli             {
8707d1cc387SAppaRao Puli                 unregisterMetricReportSignal();
8717d1cc387SAppaRao Puli             }
8727d1cc387SAppaRao Puli         }
8737d1cc387SAppaRao Puli     }
8747d1cc387SAppaRao Puli 
875b52664e2SAppaRao Puli     std::shared_ptr<Subscription> getSubscription(const std::string& id)
876b52664e2SAppaRao Puli     {
877b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
878b52664e2SAppaRao Puli         if (obj == subscriptionsMap.end())
879b52664e2SAppaRao Puli         {
880*62598e31SEd Tanous             BMCWEB_LOG_ERROR("No subscription exist with ID:{}", id);
881b52664e2SAppaRao Puli             return nullptr;
882b52664e2SAppaRao Puli         }
883b52664e2SAppaRao Puli         std::shared_ptr<Subscription> subValue = obj->second;
884b52664e2SAppaRao Puli         return subValue;
885b52664e2SAppaRao Puli     }
886b52664e2SAppaRao Puli 
887b5a76932SEd Tanous     std::string addSubscription(const std::shared_ptr<Subscription>& subValue,
8881bf712bcSAyushi Smriti                                 const bool updateFile = true)
889b52664e2SAppaRao Puli     {
890fc76b8acSEd Tanous         std::uniform_int_distribution<uint32_t> dist(0);
891fc76b8acSEd Tanous         bmcweb::OpenSSLGenerator gen;
892fc76b8acSEd Tanous 
893b52664e2SAppaRao Puli         std::string id;
894b52664e2SAppaRao Puli 
895b52664e2SAppaRao Puli         int retry = 3;
896e662eae8SEd Tanous         while (retry != 0)
897b52664e2SAppaRao Puli         {
898fc76b8acSEd Tanous             id = std::to_string(dist(gen));
899fc76b8acSEd Tanous             if (gen.error())
900fc76b8acSEd Tanous             {
901fc76b8acSEd Tanous                 retry = 0;
902fc76b8acSEd Tanous                 break;
903fc76b8acSEd Tanous             }
904b52664e2SAppaRao Puli             auto inserted = subscriptionsMap.insert(std::pair(id, subValue));
905b52664e2SAppaRao Puli             if (inserted.second)
906b52664e2SAppaRao Puli             {
907b52664e2SAppaRao Puli                 break;
908b52664e2SAppaRao Puli             }
909b52664e2SAppaRao Puli             --retry;
91023a21a1cSEd Tanous         }
911b52664e2SAppaRao Puli 
912b52664e2SAppaRao Puli         if (retry <= 0)
913b52664e2SAppaRao Puli         {
914*62598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to generate random number");
915abb93cddSEd Tanous             return "";
916b52664e2SAppaRao Puli         }
917b52664e2SAppaRao Puli 
91828afb49cSJunLin Chen         std::shared_ptr<persistent_data::UserSubscription> newSub =
91928afb49cSJunLin Chen             std::make_shared<persistent_data::UserSubscription>();
92028afb49cSJunLin Chen         newSub->id = id;
92128afb49cSJunLin Chen         newSub->destinationUrl = subValue->destinationUrl;
92228afb49cSJunLin Chen         newSub->protocol = subValue->protocol;
92328afb49cSJunLin Chen         newSub->retryPolicy = subValue->retryPolicy;
92428afb49cSJunLin Chen         newSub->customText = subValue->customText;
92528afb49cSJunLin Chen         newSub->eventFormatType = subValue->eventFormatType;
92628afb49cSJunLin Chen         newSub->subscriptionType = subValue->subscriptionType;
92728afb49cSJunLin Chen         newSub->registryMsgIds = subValue->registryMsgIds;
92828afb49cSJunLin Chen         newSub->registryPrefixes = subValue->registryPrefixes;
92928afb49cSJunLin Chen         newSub->resourceTypes = subValue->resourceTypes;
93028afb49cSJunLin Chen         newSub->httpHeaders = subValue->httpHeaders;
93128afb49cSJunLin Chen         newSub->metricReportDefinitions = subValue->metricReportDefinitions;
93228afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
93328afb49cSJunLin Chen             .subscriptionsConfigMap.emplace(newSub->id, newSub);
93428afb49cSJunLin Chen 
9357d1cc387SAppaRao Puli         updateNoOfSubscribersCount();
9361bf712bcSAyushi Smriti 
9371bf712bcSAyushi Smriti         if (updateFile)
9381bf712bcSAyushi Smriti         {
939b52664e2SAppaRao Puli             updateSubscriptionData();
9401bf712bcSAyushi Smriti         }
9417f4eb588SAppaRao Puli 
9427f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
9432558979cSP Dheeraj Srujan Kumar         if (redfishLogFilePosition != 0)
9447f4eb588SAppaRao Puli         {
9452558979cSP Dheeraj Srujan Kumar             cacheRedfishLogFile();
9467f4eb588SAppaRao Puli         }
9477f4eb588SAppaRao Puli #endif
948fe44eb0bSAyushi Smriti         // Update retry configuration.
949fe44eb0bSAyushi Smriti         subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
950fe44eb0bSAyushi Smriti 
9515e44e3d8SAppaRao Puli         // Set Subscription ID for back trace
9525e44e3d8SAppaRao Puli         subValue->setSubscriptionId(id);
953b52664e2SAppaRao Puli         return id;
954b52664e2SAppaRao Puli     }
955b52664e2SAppaRao Puli 
956b52664e2SAppaRao Puli     bool isSubscriptionExist(const std::string& id)
957b52664e2SAppaRao Puli     {
958b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
95955f79e6fSEd Tanous         return obj != subscriptionsMap.end();
960b52664e2SAppaRao Puli     }
961b52664e2SAppaRao Puli 
962b52664e2SAppaRao Puli     void deleteSubscription(const std::string& id)
963b52664e2SAppaRao Puli     {
964b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
965b52664e2SAppaRao Puli         if (obj != subscriptionsMap.end())
966b52664e2SAppaRao Puli         {
967b52664e2SAppaRao Puli             subscriptionsMap.erase(obj);
96828afb49cSJunLin Chen             auto obj2 = persistent_data::EventServiceStore::getInstance()
96928afb49cSJunLin Chen                             .subscriptionsConfigMap.find(id);
97028afb49cSJunLin Chen             persistent_data::EventServiceStore::getInstance()
97128afb49cSJunLin Chen                 .subscriptionsConfigMap.erase(obj2);
9727d1cc387SAppaRao Puli             updateNoOfSubscribersCount();
973b52664e2SAppaRao Puli             updateSubscriptionData();
974b52664e2SAppaRao Puli         }
975b52664e2SAppaRao Puli     }
976b52664e2SAppaRao Puli 
9775e44e3d8SAppaRao Puli     void deleteSseSubscription(const crow::sse_socket::Connection& thisConn)
9785e44e3d8SAppaRao Puli     {
9795e44e3d8SAppaRao Puli         for (const auto& it : subscriptionsMap)
9805e44e3d8SAppaRao Puli         {
9815e44e3d8SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
9825e44e3d8SAppaRao Puli             bool entryIsThisConn = entry->matchSseId(thisConn);
9835e44e3d8SAppaRao Puli             if (entryIsThisConn)
9845e44e3d8SAppaRao Puli             {
9855e44e3d8SAppaRao Puli                 persistent_data::EventServiceStore::getInstance()
9865e44e3d8SAppaRao Puli                     .subscriptionsConfigMap.erase(
9875e44e3d8SAppaRao Puli                         it.second->getSubscriptionId());
9885e44e3d8SAppaRao Puli                 return;
9895e44e3d8SAppaRao Puli             }
9905e44e3d8SAppaRao Puli         }
9915e44e3d8SAppaRao Puli     }
9925e44e3d8SAppaRao Puli 
9935e44e3d8SAppaRao Puli     size_t getNumberOfSubscriptions() const
994b52664e2SAppaRao Puli     {
995b52664e2SAppaRao Puli         return subscriptionsMap.size();
996b52664e2SAppaRao Puli     }
997b52664e2SAppaRao Puli 
9985e44e3d8SAppaRao Puli     size_t getNumberOfSSESubscriptions() const
9995e44e3d8SAppaRao Puli     {
10005e44e3d8SAppaRao Puli         auto size = std::count_if(
10015e44e3d8SAppaRao Puli             subscriptionsMap.begin(), subscriptionsMap.end(),
10025e44e3d8SAppaRao Puli             [](const std::pair<std::string, std::shared_ptr<Subscription>>&
10035e44e3d8SAppaRao Puli                    entry) {
10045e44e3d8SAppaRao Puli             return (entry.second->subscriptionType == subscriptionTypeSSE);
10055e44e3d8SAppaRao Puli             });
10065e44e3d8SAppaRao Puli         return static_cast<size_t>(size);
10075e44e3d8SAppaRao Puli     }
10085e44e3d8SAppaRao Puli 
1009b52664e2SAppaRao Puli     std::vector<std::string> getAllIDs()
1010b52664e2SAppaRao Puli     {
1011b52664e2SAppaRao Puli         std::vector<std::string> idList;
1012b52664e2SAppaRao Puli         for (const auto& it : subscriptionsMap)
1013b52664e2SAppaRao Puli         {
1014b52664e2SAppaRao Puli             idList.emplace_back(it.first);
1015b52664e2SAppaRao Puli         }
1016b52664e2SAppaRao Puli         return idList;
1017b52664e2SAppaRao Puli     }
1018b52664e2SAppaRao Puli 
10195e44e3d8SAppaRao Puli     bool isDestinationExist(const std::string& destUrl) const
1020b52664e2SAppaRao Puli     {
1021b52664e2SAppaRao Puli         for (const auto& it : subscriptionsMap)
1022b52664e2SAppaRao Puli         {
1023b52664e2SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
1024b52664e2SAppaRao Puli             if (entry->destinationUrl == destUrl)
1025b52664e2SAppaRao Puli             {
1026*62598e31SEd Tanous                 BMCWEB_LOG_ERROR("Destination exist already{}", destUrl);
1027b52664e2SAppaRao Puli                 return true;
1028b52664e2SAppaRao Puli             }
1029b52664e2SAppaRao Puli         }
1030b52664e2SAppaRao Puli         return false;
1031b52664e2SAppaRao Puli     }
10320b4bdd93SAppaRao Puli 
10336ba8c82eSsunharis_in     bool sendTestEventLog()
10340b4bdd93SAppaRao Puli     {
10355e44e3d8SAppaRao Puli         for (const auto& it : subscriptionsMap)
10360b4bdd93SAppaRao Puli         {
10370b4bdd93SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
10386ba8c82eSsunharis_in             if (!entry->sendTestEventLog())
10396ba8c82eSsunharis_in             {
10406ba8c82eSsunharis_in                 return false;
10410b4bdd93SAppaRao Puli             }
10420b4bdd93SAppaRao Puli         }
10436ba8c82eSsunharis_in         return true;
10446ba8c82eSsunharis_in     }
1045e9a14131SAppaRao Puli 
1046613dabeaSEd Tanous     void sendEvent(nlohmann::json eventMessage, const std::string& origin,
1047613dabeaSEd Tanous                    const std::string& resType)
104896330b99SSunitha Harish     {
1049dbb59d4dSEd Tanous         if (!serviceEnabled || (noOfEventLogSubscribers == 0U))
10506ba8c82eSsunharis_in         {
1051*62598e31SEd Tanous             BMCWEB_LOG_DEBUG("EventService disabled or no Subscriptions.");
10526ba8c82eSsunharis_in             return;
10536ba8c82eSsunharis_in         }
105496330b99SSunitha Harish         nlohmann::json eventRecord = nlohmann::json::array();
105596330b99SSunitha Harish 
1056613dabeaSEd Tanous         eventMessage["EventId"] = eventId;
1057613dabeaSEd Tanous         // MemberId is 0 : since we are sending one event record.
1058613dabeaSEd Tanous         eventMessage["MemberId"] = 0;
1059613dabeaSEd Tanous         eventMessage["EventTimestamp"] =
1060613dabeaSEd Tanous             redfish::time_utils::getDateTimeOffsetNow().first;
1061613dabeaSEd Tanous         eventMessage["OriginOfCondition"] = origin;
1062613dabeaSEd Tanous 
1063613dabeaSEd Tanous         eventRecord.emplace_back(std::move(eventMessage));
106496330b99SSunitha Harish 
10655e44e3d8SAppaRao Puli         for (const auto& it : subscriptionsMap)
106696330b99SSunitha Harish         {
106796330b99SSunitha Harish             std::shared_ptr<Subscription> entry = it.second;
106896330b99SSunitha Harish             bool isSubscribed = false;
106996330b99SSunitha Harish             // Search the resourceTypes list for the subscription.
107096330b99SSunitha Harish             // If resourceTypes list is empty, don't filter events
107196330b99SSunitha Harish             // send everything.
107226f6976fSEd Tanous             if (!entry->resourceTypes.empty())
107396330b99SSunitha Harish             {
10743174e4dfSEd Tanous                 for (const auto& resource : entry->resourceTypes)
107596330b99SSunitha Harish                 {
107696330b99SSunitha Harish                     if (resType == resource)
107796330b99SSunitha Harish                     {
1078*62598e31SEd Tanous                         BMCWEB_LOG_INFO(
1079*62598e31SEd Tanous                             "ResourceType {} found in the subscribed list",
1080*62598e31SEd Tanous                             resource);
108196330b99SSunitha Harish                         isSubscribed = true;
108296330b99SSunitha Harish                         break;
108396330b99SSunitha Harish                     }
108496330b99SSunitha Harish                 }
108596330b99SSunitha Harish             }
108696330b99SSunitha Harish             else // resourceTypes list is empty.
108796330b99SSunitha Harish             {
108896330b99SSunitha Harish                 isSubscribed = true;
108996330b99SSunitha Harish             }
109096330b99SSunitha Harish             if (isSubscribed)
109196330b99SSunitha Harish             {
1092613dabeaSEd Tanous                 nlohmann::json msgJson;
1093613dabeaSEd Tanous 
1094613dabeaSEd Tanous                 msgJson["@odata.type"] = "#Event.v1_4_0.Event";
1095613dabeaSEd Tanous                 msgJson["Name"] = "Event Log";
1096613dabeaSEd Tanous                 msgJson["Id"] = eventId;
1097613dabeaSEd Tanous                 msgJson["Events"] = eventRecord;
1098f52c03c1SCarson Labrado 
1099f52c03c1SCarson Labrado                 std::string strMsg = msgJson.dump(
1100f52c03c1SCarson Labrado                     2, ' ', true, nlohmann::json::error_handler_t::replace);
11015e44e3d8SAppaRao Puli                 entry->sendEvent(std::move(strMsg));
110296330b99SSunitha Harish                 eventId++; // increament the eventId
110396330b99SSunitha Harish             }
110496330b99SSunitha Harish             else
110596330b99SSunitha Harish             {
1106*62598e31SEd Tanous                 BMCWEB_LOG_INFO("Not subscribed to this resource");
110796330b99SSunitha Harish             }
110896330b99SSunitha Harish         }
110996330b99SSunitha Harish     }
111096330b99SSunitha Harish 
11117f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
11122558979cSP Dheeraj Srujan Kumar 
11132558979cSP Dheeraj Srujan Kumar     void resetRedfishFilePosition()
11147f4eb588SAppaRao Puli     {
11152558979cSP Dheeraj Srujan Kumar         // Control would be here when Redfish file is created.
11162558979cSP Dheeraj Srujan Kumar         // Reset File Position as new file is created
11172558979cSP Dheeraj Srujan Kumar         redfishLogFilePosition = 0;
11182558979cSP Dheeraj Srujan Kumar     }
11192558979cSP Dheeraj Srujan Kumar 
11202558979cSP Dheeraj Srujan Kumar     void cacheRedfishLogFile()
11212558979cSP Dheeraj Srujan Kumar     {
11222558979cSP Dheeraj Srujan Kumar         // Open the redfish file and read till the last record.
11232558979cSP Dheeraj Srujan Kumar 
11247f4eb588SAppaRao Puli         std::ifstream logStream(redfishEventLogFile);
11257f4eb588SAppaRao Puli         if (!logStream.good())
11267f4eb588SAppaRao Puli         {
1127*62598e31SEd Tanous             BMCWEB_LOG_ERROR(" Redfish log file open failed ");
11287f4eb588SAppaRao Puli             return;
11297f4eb588SAppaRao Puli         }
11307f4eb588SAppaRao Puli         std::string logEntry;
11317f4eb588SAppaRao Puli         while (std::getline(logStream, logEntry))
11327f4eb588SAppaRao Puli         {
11332558979cSP Dheeraj Srujan Kumar             redfishLogFilePosition = logStream.tellg();
11347f4eb588SAppaRao Puli         }
11357f4eb588SAppaRao Puli     }
11367f4eb588SAppaRao Puli 
11377f4eb588SAppaRao Puli     void readEventLogsFromFile()
11387f4eb588SAppaRao Puli     {
11397f4eb588SAppaRao Puli         std::ifstream logStream(redfishEventLogFile);
11407f4eb588SAppaRao Puli         if (!logStream.good())
11417f4eb588SAppaRao Puli         {
1142*62598e31SEd Tanous             BMCWEB_LOG_ERROR(" Redfish log file open failed");
11437f4eb588SAppaRao Puli             return;
11447f4eb588SAppaRao Puli         }
11457f4eb588SAppaRao Puli 
11467f4eb588SAppaRao Puli         std::vector<EventLogObjectsType> eventRecords;
11477f4eb588SAppaRao Puli 
11487f4eb588SAppaRao Puli         std::string logEntry;
11492558979cSP Dheeraj Srujan Kumar 
11502558979cSP Dheeraj Srujan Kumar         // Get the read pointer to the next log to be read.
11512558979cSP Dheeraj Srujan Kumar         logStream.seekg(redfishLogFilePosition);
11522558979cSP Dheeraj Srujan Kumar 
11537f4eb588SAppaRao Puli         while (std::getline(logStream, logEntry))
11547f4eb588SAppaRao Puli         {
11552558979cSP Dheeraj Srujan Kumar             // Update Pointer position
11562558979cSP Dheeraj Srujan Kumar             redfishLogFilePosition = logStream.tellg();
11572558979cSP Dheeraj Srujan Kumar 
11582558979cSP Dheeraj Srujan Kumar             std::string idStr;
11592558979cSP Dheeraj Srujan Kumar             if (!event_log::getUniqueEntryID(logEntry, idStr))
11607f4eb588SAppaRao Puli             {
11617f4eb588SAppaRao Puli                 continue;
11627f4eb588SAppaRao Puli             }
11637f4eb588SAppaRao Puli 
1164e662eae8SEd Tanous             if (!serviceEnabled || noOfEventLogSubscribers == 0)
11657f4eb588SAppaRao Puli             {
11662558979cSP Dheeraj Srujan Kumar                 // If Service is not enabled, no need to compute
11672558979cSP Dheeraj Srujan Kumar                 // the remaining items below.
11682558979cSP Dheeraj Srujan Kumar                 // But, Loop must continue to keep track of Timestamp
11697f4eb588SAppaRao Puli                 continue;
11707f4eb588SAppaRao Puli             }
11717f4eb588SAppaRao Puli 
11727f4eb588SAppaRao Puli             std::string timestamp;
11737f4eb588SAppaRao Puli             std::string messageID;
11745e715de6SAppaRao Puli             std::vector<std::string> messageArgs;
11757f4eb588SAppaRao Puli             if (event_log::getEventLogParams(logEntry, timestamp, messageID,
11767f4eb588SAppaRao Puli                                              messageArgs) != 0)
11777f4eb588SAppaRao Puli             {
1178*62598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Read eventLog entry params failed");
11797f4eb588SAppaRao Puli                 continue;
11807f4eb588SAppaRao Puli             }
11817f4eb588SAppaRao Puli 
11827f4eb588SAppaRao Puli             std::string registryName;
11837f4eb588SAppaRao Puli             std::string messageKey;
11847f4eb588SAppaRao Puli             event_log::getRegistryAndMessageKey(messageID, registryName,
11857f4eb588SAppaRao Puli                                                 messageKey);
11867f4eb588SAppaRao Puli             if (registryName.empty() || messageKey.empty())
11877f4eb588SAppaRao Puli             {
11887f4eb588SAppaRao Puli                 continue;
11897f4eb588SAppaRao Puli             }
11907f4eb588SAppaRao Puli 
11917f4eb588SAppaRao Puli             eventRecords.emplace_back(idStr, timestamp, messageID, registryName,
11927f4eb588SAppaRao Puli                                       messageKey, messageArgs);
11937f4eb588SAppaRao Puli         }
11947f4eb588SAppaRao Puli 
1195e662eae8SEd Tanous         if (!serviceEnabled || noOfEventLogSubscribers == 0)
11962558979cSP Dheeraj Srujan Kumar         {
1197*62598e31SEd Tanous             BMCWEB_LOG_DEBUG("EventService disabled or no Subscriptions.");
11982558979cSP Dheeraj Srujan Kumar             return;
11992558979cSP Dheeraj Srujan Kumar         }
12002558979cSP Dheeraj Srujan Kumar 
12012558979cSP Dheeraj Srujan Kumar         if (eventRecords.empty())
12022558979cSP Dheeraj Srujan Kumar         {
12032558979cSP Dheeraj Srujan Kumar             // No Records to send
1204*62598e31SEd Tanous             BMCWEB_LOG_DEBUG("No log entries available to be transferred.");
12052558979cSP Dheeraj Srujan Kumar             return;
12062558979cSP Dheeraj Srujan Kumar         }
12072558979cSP Dheeraj Srujan Kumar 
12085e44e3d8SAppaRao Puli         for (const auto& it : subscriptionsMap)
12097f4eb588SAppaRao Puli         {
12107f4eb588SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
12117f4eb588SAppaRao Puli             if (entry->eventFormatType == "Event")
12127f4eb588SAppaRao Puli             {
12137f4eb588SAppaRao Puli                 entry->filterAndSendEventLogs(eventRecords);
12147f4eb588SAppaRao Puli             }
12157f4eb588SAppaRao Puli         }
12167f4eb588SAppaRao Puli     }
12177f4eb588SAppaRao Puli 
12187f4eb588SAppaRao Puli     static void watchRedfishEventLogFile()
12197f4eb588SAppaRao Puli     {
12206a9f85f9SAppaRao Puli         if (!inotifyConn)
12217f4eb588SAppaRao Puli         {
12227f4eb588SAppaRao Puli             return;
12237f4eb588SAppaRao Puli         }
12247f4eb588SAppaRao Puli 
12257f4eb588SAppaRao Puli         static std::array<char, 1024> readBuffer;
12267f4eb588SAppaRao Puli 
1227002d39b4SEd Tanous         inotifyConn->async_read_some(boost::asio::buffer(readBuffer),
12287f4eb588SAppaRao Puli                                      [&](const boost::system::error_code& ec,
12297f4eb588SAppaRao Puli                                          const std::size_t& bytesTransferred) {
12307f4eb588SAppaRao Puli             if (ec)
12317f4eb588SAppaRao Puli             {
1232*62598e31SEd Tanous                 BMCWEB_LOG_ERROR("Callback Error: {}", ec.message());
12337f4eb588SAppaRao Puli                 return;
12347f4eb588SAppaRao Puli             }
12357f4eb588SAppaRao Puli             std::size_t index = 0;
1236b792cc56SAppaRao Puli             while ((index + iEventSize) <= bytesTransferred)
12377f4eb588SAppaRao Puli             {
1238d3a9e084SEd Tanous                 struct inotify_event event
1239d3a9e084SEd Tanous                 {};
1240b792cc56SAppaRao Puli                 std::memcpy(&event, &readBuffer[index], iEventSize);
1241b792cc56SAppaRao Puli                 if (event.wd == dirWatchDesc)
1242b792cc56SAppaRao Puli                 {
1243b792cc56SAppaRao Puli                     if ((event.len == 0) ||
1244b792cc56SAppaRao Puli                         (index + iEventSize + event.len > bytesTransferred))
1245b792cc56SAppaRao Puli                     {
1246b792cc56SAppaRao Puli                         index += (iEventSize + event.len);
1247b792cc56SAppaRao Puli                         continue;
1248b792cc56SAppaRao Puli                     }
1249b792cc56SAppaRao Puli 
12504f568f74SJiaqing Zhao                     std::string fileName(&readBuffer[index + iEventSize]);
12514f568f74SJiaqing Zhao                     if (fileName != "redfish")
1252b792cc56SAppaRao Puli                     {
1253b792cc56SAppaRao Puli                         index += (iEventSize + event.len);
1254b792cc56SAppaRao Puli                         continue;
1255b792cc56SAppaRao Puli                     }
1256b792cc56SAppaRao Puli 
1257*62598e31SEd Tanous                     BMCWEB_LOG_DEBUG(
1258*62598e31SEd Tanous                         "Redfish log file created/deleted. event.name: {}",
1259*62598e31SEd Tanous                         fileName);
1260b792cc56SAppaRao Puli                     if (event.mask == IN_CREATE)
1261b792cc56SAppaRao Puli                     {
1262b792cc56SAppaRao Puli                         if (fileWatchDesc != -1)
1263b792cc56SAppaRao Puli                         {
1264*62598e31SEd Tanous                             BMCWEB_LOG_DEBUG(
1265*62598e31SEd Tanous                                 "Remove and Add inotify watcher on "
1266*62598e31SEd Tanous                                 "redfish event log file");
1267016761afSAppaRao Puli                             // Remove existing inotify watcher and add
1268016761afSAppaRao Puli                             // with new redfish event log file.
1269016761afSAppaRao Puli                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1270016761afSAppaRao Puli                             fileWatchDesc = -1;
1271b792cc56SAppaRao Puli                         }
1272b792cc56SAppaRao Puli 
1273b792cc56SAppaRao Puli                         fileWatchDesc = inotify_add_watch(
1274b792cc56SAppaRao Puli                             inotifyFd, redfishEventLogFile, IN_MODIFY);
1275b792cc56SAppaRao Puli                         if (fileWatchDesc == -1)
1276b792cc56SAppaRao Puli                         {
1277*62598e31SEd Tanous                             BMCWEB_LOG_ERROR("inotify_add_watch failed for "
1278*62598e31SEd Tanous                                              "redfish log file.");
1279b792cc56SAppaRao Puli                             return;
1280b792cc56SAppaRao Puli                         }
1281b792cc56SAppaRao Puli 
1282b792cc56SAppaRao Puli                         EventServiceManager::getInstance()
12832558979cSP Dheeraj Srujan Kumar                             .resetRedfishFilePosition();
1284b792cc56SAppaRao Puli                         EventServiceManager::getInstance()
1285b792cc56SAppaRao Puli                             .readEventLogsFromFile();
1286b792cc56SAppaRao Puli                     }
1287b792cc56SAppaRao Puli                     else if ((event.mask == IN_DELETE) ||
1288b792cc56SAppaRao Puli                              (event.mask == IN_MOVED_TO))
1289b792cc56SAppaRao Puli                     {
1290b792cc56SAppaRao Puli                         if (fileWatchDesc != -1)
1291b792cc56SAppaRao Puli                         {
1292b792cc56SAppaRao Puli                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1293b792cc56SAppaRao Puli                             fileWatchDesc = -1;
1294b792cc56SAppaRao Puli                         }
1295b792cc56SAppaRao Puli                     }
1296b792cc56SAppaRao Puli                 }
1297b792cc56SAppaRao Puli                 else if (event.wd == fileWatchDesc)
1298b792cc56SAppaRao Puli                 {
1299b792cc56SAppaRao Puli                     if (event.mask == IN_MODIFY)
13007f4eb588SAppaRao Puli                     {
13017f4eb588SAppaRao Puli                         EventServiceManager::getInstance()
13027f4eb588SAppaRao Puli                             .readEventLogsFromFile();
13037f4eb588SAppaRao Puli                     }
1304b792cc56SAppaRao Puli                 }
1305b792cc56SAppaRao Puli                 index += (iEventSize + event.len);
13067f4eb588SAppaRao Puli             }
13077f4eb588SAppaRao Puli 
13087f4eb588SAppaRao Puli             watchRedfishEventLogFile();
13097f4eb588SAppaRao Puli         });
13107f4eb588SAppaRao Puli     }
13117f4eb588SAppaRao Puli 
13127f4eb588SAppaRao Puli     static int startEventLogMonitor(boost::asio::io_context& ioc)
13137f4eb588SAppaRao Puli     {
131423a21a1cSEd Tanous         inotifyConn.emplace(ioc);
1315b792cc56SAppaRao Puli         inotifyFd = inotify_init1(IN_NONBLOCK);
1316b792cc56SAppaRao Puli         if (inotifyFd == -1)
13177f4eb588SAppaRao Puli         {
1318*62598e31SEd Tanous             BMCWEB_LOG_ERROR("inotify_init1 failed.");
13197f4eb588SAppaRao Puli             return -1;
13207f4eb588SAppaRao Puli         }
1321b792cc56SAppaRao Puli 
1322b792cc56SAppaRao Puli         // Add watch on directory to handle redfish event log file
1323b792cc56SAppaRao Puli         // create/delete.
1324b792cc56SAppaRao Puli         dirWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogDir,
1325b792cc56SAppaRao Puli                                          IN_CREATE | IN_MOVED_TO | IN_DELETE);
1326b792cc56SAppaRao Puli         if (dirWatchDesc == -1)
13277f4eb588SAppaRao Puli         {
1328*62598e31SEd Tanous             BMCWEB_LOG_ERROR(
1329*62598e31SEd Tanous                 "inotify_add_watch failed for event log directory.");
13307f4eb588SAppaRao Puli             return -1;
13317f4eb588SAppaRao Puli         }
13327f4eb588SAppaRao Puli 
1333b792cc56SAppaRao Puli         // Watch redfish event log file for modifications.
133489492a15SPatrick Williams         fileWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogFile,
133589492a15SPatrick Williams                                           IN_MODIFY);
1336b792cc56SAppaRao Puli         if (fileWatchDesc == -1)
1337b792cc56SAppaRao Puli         {
1338*62598e31SEd Tanous             BMCWEB_LOG_ERROR("inotify_add_watch failed for redfish log file.");
1339b792cc56SAppaRao Puli             // Don't return error if file not exist.
1340b792cc56SAppaRao Puli             // Watch on directory will handle create/delete of file.
1341b792cc56SAppaRao Puli         }
1342b792cc56SAppaRao Puli 
13437f4eb588SAppaRao Puli         // monitor redfish event log file
1344b792cc56SAppaRao Puli         inotifyConn->assign(inotifyFd);
13457f4eb588SAppaRao Puli         watchRedfishEventLogFile();
13467f4eb588SAppaRao Puli 
13477f4eb588SAppaRao Puli         return 0;
13487f4eb588SAppaRao Puli     }
13497f4eb588SAppaRao Puli 
13507f4eb588SAppaRao Puli #endif
135159d494eeSPatrick Williams     static void getReadingsForReport(sdbusplus::message_t& msg)
1352156d6b00SAppaRao Puli     {
135356d2396dSEd Tanous         if (msg.is_method_error())
135456d2396dSEd Tanous         {
1355*62598e31SEd Tanous             BMCWEB_LOG_ERROR("TelemetryMonitor Signal error");
135656d2396dSEd Tanous             return;
135756d2396dSEd Tanous         }
135856d2396dSEd Tanous 
1359c0353249SWludzik, Jozef         sdbusplus::message::object_path path(msg.get_path());
1360c0353249SWludzik, Jozef         std::string id = path.filename();
1361c0353249SWludzik, Jozef         if (id.empty())
1362156d6b00SAppaRao Puli         {
1363*62598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to get Id from path");
1364156d6b00SAppaRao Puli             return;
1365156d6b00SAppaRao Puli         }
1366156d6b00SAppaRao Puli 
1367c0353249SWludzik, Jozef         std::string interface;
1368b9d36b47SEd Tanous         dbus::utility::DBusPropertiesMap props;
1369c0353249SWludzik, Jozef         std::vector<std::string> invalidProps;
1370c0353249SWludzik, Jozef         msg.read(interface, props, invalidProps);
1371c0353249SWludzik, Jozef 
1372c0353249SWludzik, Jozef         auto found =
1373c0353249SWludzik, Jozef             std::find_if(props.begin(), props.end(),
1374c0353249SWludzik, Jozef                          [](const auto& x) { return x.first == "Readings"; });
1375c0353249SWludzik, Jozef         if (found == props.end())
1376156d6b00SAppaRao Puli         {
1377*62598e31SEd Tanous             BMCWEB_LOG_INFO("Failed to get Readings from Report properties");
1378156d6b00SAppaRao Puli             return;
1379156d6b00SAppaRao Puli         }
1380156d6b00SAppaRao Puli 
13811e1e598dSJonathan Doman         const telemetry::TimestampReadings* readings =
13821e1e598dSJonathan Doman             std::get_if<telemetry::TimestampReadings>(&found->second);
1383e662eae8SEd Tanous         if (readings == nullptr)
13841e1e598dSJonathan Doman         {
1385*62598e31SEd Tanous             BMCWEB_LOG_INFO("Failed to get Readings from Report properties");
13861e1e598dSJonathan Doman             return;
13871e1e598dSJonathan Doman         }
13881e1e598dSJonathan Doman 
1389156d6b00SAppaRao Puli         for (const auto& it :
1390156d6b00SAppaRao Puli              EventServiceManager::getInstance().subscriptionsMap)
1391156d6b00SAppaRao Puli         {
1392e05aec50SEd Tanous             Subscription& entry = *it.second;
1393c0353249SWludzik, Jozef             if (entry.eventFormatType == metricReportFormatType)
1394156d6b00SAppaRao Puli             {
13951e1e598dSJonathan Doman                 entry.filterAndSendReports(id, *readings);
1396156d6b00SAppaRao Puli             }
1397156d6b00SAppaRao Puli         }
1398156d6b00SAppaRao Puli     }
1399156d6b00SAppaRao Puli 
1400156d6b00SAppaRao Puli     void unregisterMetricReportSignal()
1401156d6b00SAppaRao Puli     {
14027d1cc387SAppaRao Puli         if (matchTelemetryMonitor)
14037d1cc387SAppaRao Puli         {
1404*62598e31SEd Tanous             BMCWEB_LOG_DEBUG("Metrics report signal - Unregister");
1405156d6b00SAppaRao Puli             matchTelemetryMonitor.reset();
1406156d6b00SAppaRao Puli             matchTelemetryMonitor = nullptr;
1407156d6b00SAppaRao Puli         }
14087d1cc387SAppaRao Puli     }
1409156d6b00SAppaRao Puli 
1410156d6b00SAppaRao Puli     void registerMetricReportSignal()
1411156d6b00SAppaRao Puli     {
14127d1cc387SAppaRao Puli         if (!serviceEnabled || matchTelemetryMonitor)
1413156d6b00SAppaRao Puli         {
1414*62598e31SEd Tanous             BMCWEB_LOG_DEBUG("Not registering metric report signal.");
1415156d6b00SAppaRao Puli             return;
1416156d6b00SAppaRao Puli         }
1417156d6b00SAppaRao Puli 
1418*62598e31SEd Tanous         BMCWEB_LOG_DEBUG("Metrics report signal - Register");
1419c0353249SWludzik, Jozef         std::string matchStr = "type='signal',member='PropertiesChanged',"
1420c0353249SWludzik, Jozef                                "interface='org.freedesktop.DBus.Properties',"
1421c0353249SWludzik, Jozef                                "arg0=xyz.openbmc_project.Telemetry.Report";
1422156d6b00SAppaRao Puli 
142359d494eeSPatrick Williams         matchTelemetryMonitor = std::make_shared<sdbusplus::bus::match_t>(
142456d2396dSEd Tanous             *crow::connections::systemBus, matchStr, getReadingsForReport);
1425156d6b00SAppaRao Puli     }
142623a21a1cSEd Tanous };
1427b52664e2SAppaRao Puli 
1428b52664e2SAppaRao Puli } // namespace redfish
1429