xref: /openbmc/bmcweb/features/redfish/include/event_service_manager.hpp (revision b5b40605fbdbf45b0ec140e02530853595c9b6e5)
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
17c0353249SWludzik, Jozef #include "metric_report.hpp"
187f4eb588SAppaRao Puli #include "registries.hpp"
197f4eb588SAppaRao Puli #include "registries/base_message_registry.hpp"
207f4eb588SAppaRao Puli #include "registries/openbmc_message_registry.hpp"
21b304bd79SP Dheeraj Srujan Kumar #include "registries/task_event_message_registry.hpp"
227f4eb588SAppaRao Puli 
237f4eb588SAppaRao Puli #include <sys/inotify.h>
24b52664e2SAppaRao Puli 
25fb4fd5d4SZhenfei Tai #include <boost/asio/io_context.hpp>
26b52664e2SAppaRao Puli #include <boost/container/flat_map.hpp>
27168e20c1SEd Tanous #include <dbus_utility.hpp>
281214b7e7SGunnar Mills #include <error_messages.hpp>
2928afb49cSJunLin Chen #include <event_service_store.hpp>
30eb1c47d3SEd Tanous #include <http/utility.hpp>
311214b7e7SGunnar Mills #include <http_client.hpp>
3228afb49cSJunLin Chen #include <persistent_data.hpp>
33fc76b8acSEd Tanous #include <random.hpp>
34*b5b40605Snitroglycerine #include <sdbusplus/bus/match.hpp>
354bbf237fSAppaRao Puli #include <server_sent_events.hpp>
361214b7e7SGunnar Mills #include <utils/json_utils.hpp>
371214b7e7SGunnar Mills 
38b52664e2SAppaRao Puli #include <cstdlib>
39b52664e2SAppaRao Puli #include <ctime>
401bf712bcSAyushi Smriti #include <fstream>
41b52664e2SAppaRao Puli #include <memory>
4226702d01SEd Tanous #include <span>
43b52664e2SAppaRao Puli 
44b52664e2SAppaRao Puli namespace redfish
45b52664e2SAppaRao Puli {
46156d6b00SAppaRao Puli 
47156d6b00SAppaRao Puli using ReadingsObjType =
4893f5d7c7SWludzik, Jozef     std::vector<std::tuple<std::string, std::string, double, int32_t>>;
49156d6b00SAppaRao Puli 
50156d6b00SAppaRao Puli static constexpr const char* eventFormatType = "Event";
51156d6b00SAppaRao Puli static constexpr const char* metricReportFormatType = "MetricReport";
52156d6b00SAppaRao Puli 
531bf712bcSAyushi Smriti static constexpr const char* eventServiceFile =
541bf712bcSAyushi Smriti     "/var/lib/bmcweb/eventservice_config.json";
551bf712bcSAyushi Smriti 
56fffb8c1fSEd Tanous namespace registries
577f4eb588SAppaRao Puli {
5826702d01SEd Tanous inline std::span<const MessageEntry>
59b304bd79SP Dheeraj Srujan Kumar     getRegistryFromPrefix(const std::string& registryName)
60b304bd79SP Dheeraj Srujan Kumar {
61b304bd79SP Dheeraj Srujan Kumar     if (task_event::header.registryPrefix == registryName)
62b304bd79SP Dheeraj Srujan Kumar     {
6326702d01SEd Tanous         return {task_event::registry};
64b304bd79SP Dheeraj Srujan Kumar     }
65b304bd79SP Dheeraj Srujan Kumar     if (openbmc::header.registryPrefix == registryName)
66b304bd79SP Dheeraj Srujan Kumar     {
6726702d01SEd Tanous         return {openbmc::registry};
68b304bd79SP Dheeraj Srujan Kumar     }
69b304bd79SP Dheeraj Srujan Kumar     if (base::header.registryPrefix == registryName)
70b304bd79SP Dheeraj Srujan Kumar     {
7126702d01SEd Tanous         return {base::registry};
72b304bd79SP Dheeraj Srujan Kumar     }
7326702d01SEd Tanous     return {openbmc::registry};
74b304bd79SP Dheeraj Srujan Kumar }
75fffb8c1fSEd Tanous } // namespace registries
76b304bd79SP Dheeraj Srujan Kumar 
774642bf8fSGeorge Liu #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
784642bf8fSGeorge Liu static std::optional<boost::asio::posix::stream_descriptor> inotifyConn;
794642bf8fSGeorge Liu static constexpr const char* redfishEventLogDir = "/var/log";
804642bf8fSGeorge Liu static constexpr const char* redfishEventLogFile = "/var/log/redfish";
814642bf8fSGeorge Liu static constexpr const size_t iEventSize = sizeof(inotify_event);
824642bf8fSGeorge Liu static int inotifyFd = -1;
834642bf8fSGeorge Liu static int dirWatchDesc = -1;
844642bf8fSGeorge Liu static int fileWatchDesc = -1;
854642bf8fSGeorge Liu 
864642bf8fSGeorge Liu // <ID, timestamp, RedfishLogId, registryPrefix, MessageId, MessageArgs>
874642bf8fSGeorge Liu using EventLogObjectsType =
884642bf8fSGeorge Liu     std::tuple<std::string, std::string, std::string, std::string, std::string,
894642bf8fSGeorge Liu                std::vector<std::string>>;
904642bf8fSGeorge Liu 
91fffb8c1fSEd Tanous namespace registries
924642bf8fSGeorge Liu {
937f4eb588SAppaRao Puli static const Message*
947f4eb588SAppaRao Puli     getMsgFromRegistry(const std::string& messageKey,
9526702d01SEd Tanous                        const std::span<const MessageEntry>& registry)
967f4eb588SAppaRao Puli {
9726702d01SEd Tanous     std::span<const MessageEntry>::iterator messageIt =
9826702d01SEd Tanous         std::find_if(registry.begin(), registry.end(),
997f4eb588SAppaRao Puli                      [&messageKey](const MessageEntry& messageEntry) {
10055f79e6fSEd Tanous         return messageKey == messageEntry.first;
1017f4eb588SAppaRao Puli         });
10226702d01SEd Tanous     if (messageIt != registry.end())
1037f4eb588SAppaRao Puli     {
1047f4eb588SAppaRao Puli         return &messageIt->second;
1057f4eb588SAppaRao Puli     }
1067f4eb588SAppaRao Puli 
1077f4eb588SAppaRao Puli     return nullptr;
1087f4eb588SAppaRao Puli }
1097f4eb588SAppaRao Puli 
1107f4eb588SAppaRao Puli static const Message* formatMessage(const std::string_view& messageID)
1117f4eb588SAppaRao Puli {
1127f4eb588SAppaRao Puli     // Redfish MessageIds are in the form
1137f4eb588SAppaRao Puli     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
1147f4eb588SAppaRao Puli     // the right Message
1157f4eb588SAppaRao Puli     std::vector<std::string> fields;
1167f4eb588SAppaRao Puli     fields.reserve(4);
1177f4eb588SAppaRao Puli     boost::split(fields, messageID, boost::is_any_of("."));
1187f4eb588SAppaRao Puli     if (fields.size() != 4)
1197f4eb588SAppaRao Puli     {
1207f4eb588SAppaRao Puli         return nullptr;
1217f4eb588SAppaRao Puli     }
1227f4eb588SAppaRao Puli     std::string& registryName = fields[0];
1237f4eb588SAppaRao Puli     std::string& messageKey = fields[3];
1247f4eb588SAppaRao Puli 
1257f4eb588SAppaRao Puli     // Find the right registry and check it for the MessageKey
126b304bd79SP Dheeraj Srujan Kumar     return getMsgFromRegistry(messageKey, getRegistryFromPrefix(registryName));
1277f4eb588SAppaRao Puli }
128fffb8c1fSEd Tanous } // namespace registries
1297f4eb588SAppaRao Puli 
1307f4eb588SAppaRao Puli namespace event_log
1317f4eb588SAppaRao Puli {
1322558979cSP Dheeraj Srujan Kumar inline bool getUniqueEntryID(const std::string& logEntry, std::string& entryID)
1337f4eb588SAppaRao Puli {
1347f4eb588SAppaRao Puli     static time_t prevTs = 0;
1357f4eb588SAppaRao Puli     static int index = 0;
1367f4eb588SAppaRao Puli 
1377f4eb588SAppaRao Puli     // Get the entry timestamp
1387f4eb588SAppaRao Puli     std::time_t curTs = 0;
1397f4eb588SAppaRao Puli     std::tm timeStruct = {};
1407f4eb588SAppaRao Puli     std::istringstream entryStream(logEntry);
1417f4eb588SAppaRao Puli     if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1427f4eb588SAppaRao Puli     {
1437f4eb588SAppaRao Puli         curTs = std::mktime(&timeStruct);
1447f4eb588SAppaRao Puli         if (curTs == -1)
1457f4eb588SAppaRao Puli         {
1467f4eb588SAppaRao Puli             return false;
1477f4eb588SAppaRao Puli         }
1487f4eb588SAppaRao Puli     }
1497f4eb588SAppaRao Puli     // If the timestamp isn't unique, increment the index
1507f4eb588SAppaRao Puli     index = (curTs == prevTs) ? index + 1 : 0;
1517f4eb588SAppaRao Puli 
1527f4eb588SAppaRao Puli     // Save the timestamp
1537f4eb588SAppaRao Puli     prevTs = curTs;
1547f4eb588SAppaRao Puli 
1557f4eb588SAppaRao Puli     entryID = std::to_string(curTs);
1567f4eb588SAppaRao Puli     if (index > 0)
1577f4eb588SAppaRao Puli     {
1587f4eb588SAppaRao Puli         entryID += "_" + std::to_string(index);
1597f4eb588SAppaRao Puli     }
1607f4eb588SAppaRao Puli     return true;
1617f4eb588SAppaRao Puli }
1627f4eb588SAppaRao Puli 
16323a21a1cSEd Tanous inline int getEventLogParams(const std::string& logEntry,
16423a21a1cSEd Tanous                              std::string& timestamp, std::string& messageID,
1655e715de6SAppaRao Puli                              std::vector<std::string>& messageArgs)
1667f4eb588SAppaRao Puli {
1677f4eb588SAppaRao Puli     // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
1687f4eb588SAppaRao Puli     // First get the Timestamp
169f23b7296SEd Tanous     size_t space = logEntry.find_first_of(' ');
1707f4eb588SAppaRao Puli     if (space == std::string::npos)
1717f4eb588SAppaRao Puli     {
1727f4eb588SAppaRao Puli         return -EINVAL;
1737f4eb588SAppaRao Puli     }
1747f4eb588SAppaRao Puli     timestamp = logEntry.substr(0, space);
1757f4eb588SAppaRao Puli     // Then get the log contents
176f23b7296SEd Tanous     size_t entryStart = logEntry.find_first_not_of(' ', space);
1777f4eb588SAppaRao Puli     if (entryStart == std::string::npos)
1787f4eb588SAppaRao Puli     {
1797f4eb588SAppaRao Puli         return -EINVAL;
1807f4eb588SAppaRao Puli     }
1817f4eb588SAppaRao Puli     std::string_view entry(logEntry);
1827f4eb588SAppaRao Puli     entry.remove_prefix(entryStart);
1837f4eb588SAppaRao Puli     // Use split to separate the entry into its fields
1847f4eb588SAppaRao Puli     std::vector<std::string> logEntryFields;
1857f4eb588SAppaRao Puli     boost::split(logEntryFields, entry, boost::is_any_of(","),
1867f4eb588SAppaRao Puli                  boost::token_compress_on);
1877f4eb588SAppaRao Puli     // We need at least a MessageId to be valid
18826f6976fSEd Tanous     if (logEntryFields.empty())
1897f4eb588SAppaRao Puli     {
1907f4eb588SAppaRao Puli         return -EINVAL;
1917f4eb588SAppaRao Puli     }
1927f4eb588SAppaRao Puli     messageID = logEntryFields[0];
1937f4eb588SAppaRao Puli 
1947f4eb588SAppaRao Puli     // Get the MessageArgs from the log if there are any
1957f4eb588SAppaRao Puli     if (logEntryFields.size() > 1)
1967f4eb588SAppaRao Puli     {
1977f4eb588SAppaRao Puli         std::string& messageArgsStart = logEntryFields[1];
1987f4eb588SAppaRao Puli         // If the first string is empty, assume there are no MessageArgs
1997f4eb588SAppaRao Puli         if (!messageArgsStart.empty())
2007f4eb588SAppaRao Puli         {
2015e715de6SAppaRao Puli             messageArgs.assign(logEntryFields.begin() + 1,
2025e715de6SAppaRao Puli                                logEntryFields.end());
2037f4eb588SAppaRao Puli         }
2047f4eb588SAppaRao Puli     }
2057f4eb588SAppaRao Puli 
2067f4eb588SAppaRao Puli     return 0;
2077f4eb588SAppaRao Puli }
2087f4eb588SAppaRao Puli 
20923a21a1cSEd Tanous inline void getRegistryAndMessageKey(const std::string& messageID,
2107f4eb588SAppaRao Puli                                      std::string& registryName,
2117f4eb588SAppaRao Puli                                      std::string& messageKey)
2127f4eb588SAppaRao Puli {
2137f4eb588SAppaRao Puli     // Redfish MessageIds are in the form
2147f4eb588SAppaRao Puli     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
2157f4eb588SAppaRao Puli     // the right Message
2167f4eb588SAppaRao Puli     std::vector<std::string> fields;
2177f4eb588SAppaRao Puli     fields.reserve(4);
2187f4eb588SAppaRao Puli     boost::split(fields, messageID, boost::is_any_of("."));
2197f4eb588SAppaRao Puli     if (fields.size() == 4)
2207f4eb588SAppaRao Puli     {
2217f4eb588SAppaRao Puli         registryName = fields[0];
2227f4eb588SAppaRao Puli         messageKey = fields[3];
2237f4eb588SAppaRao Puli     }
2247f4eb588SAppaRao Puli }
2257f4eb588SAppaRao Puli 
22623a21a1cSEd Tanous inline int formatEventLogEntry(const std::string& logEntryID,
2277f4eb588SAppaRao Puli                                const std::string& messageID,
228c5ba4c27SEd Tanous                                const std::span<std::string_view> messageArgs,
22923a21a1cSEd Tanous                                std::string timestamp,
230b5a76932SEd Tanous                                const std::string& customText,
2317f4eb588SAppaRao Puli                                nlohmann::json& logEntryJson)
2327f4eb588SAppaRao Puli {
2337f4eb588SAppaRao Puli     // Get the Message from the MessageRegistry
234fffb8c1fSEd Tanous     const registries::Message* message = registries::formatMessage(messageID);
2357f4eb588SAppaRao Puli 
2367f4eb588SAppaRao Puli     std::string msg;
2377f4eb588SAppaRao Puli     std::string severity;
2387f4eb588SAppaRao Puli     if (message != nullptr)
2397f4eb588SAppaRao Puli     {
2407f4eb588SAppaRao Puli         msg = message->message;
2415f2b84eeSEd Tanous         severity = message->messageSeverity;
2427f4eb588SAppaRao Puli     }
2437f4eb588SAppaRao Puli 
244fffb8c1fSEd Tanous     redfish::registries::fillMessageArgs(messageArgs, msg);
2457f4eb588SAppaRao Puli 
2467f4eb588SAppaRao Puli     // Get the Created time from the timestamp. The log timestamp is in
2477f4eb588SAppaRao Puli     // RFC3339 format which matches the Redfish format except for the
2487f4eb588SAppaRao Puli     // fractional seconds between the '.' and the '+', so just remove them.
249f23b7296SEd Tanous     std::size_t dot = timestamp.find_first_of('.');
250f23b7296SEd Tanous     std::size_t plus = timestamp.find_first_of('+');
2517f4eb588SAppaRao Puli     if (dot != std::string::npos && plus != std::string::npos)
2527f4eb588SAppaRao Puli     {
2537f4eb588SAppaRao Puli         timestamp.erase(dot, plus - dot);
2547f4eb588SAppaRao Puli     }
2557f4eb588SAppaRao Puli 
2567f4eb588SAppaRao Puli     // Fill in the log entry with the gathered data
2571476687dSEd Tanous     logEntryJson["EventId"] = logEntryID;
2581476687dSEd Tanous     logEntryJson["EventType"] = "Event";
2591476687dSEd Tanous     logEntryJson["Severity"] = std::move(severity);
2601476687dSEd Tanous     logEntryJson["Message"] = std::move(msg);
2611476687dSEd Tanous     logEntryJson["MessageId"] = messageID;
2621476687dSEd Tanous     logEntryJson["MessageArgs"] = messageArgs;
2631476687dSEd Tanous     logEntryJson["EventTimestamp"] = std::move(timestamp);
2641476687dSEd Tanous     logEntryJson["Context"] = customText;
2657f4eb588SAppaRao Puli     return 0;
2667f4eb588SAppaRao Puli }
2677f4eb588SAppaRao Puli 
2687f4eb588SAppaRao Puli } // namespace event_log
2697f4eb588SAppaRao Puli #endif
2707f4eb588SAppaRao Puli 
27123a21a1cSEd Tanous inline bool isFilterQuerySpecialChar(char c)
27207941a88SAyushi Smriti {
27307941a88SAyushi Smriti     switch (c)
27407941a88SAyushi Smriti     {
27507941a88SAyushi Smriti         case '(':
27607941a88SAyushi Smriti         case ')':
27707941a88SAyushi Smriti         case '\'':
27807941a88SAyushi Smriti             return true;
27907941a88SAyushi Smriti         default:
28007941a88SAyushi Smriti             return false;
28107941a88SAyushi Smriti     }
28207941a88SAyushi Smriti }
28307941a88SAyushi Smriti 
28423a21a1cSEd Tanous inline bool
28523a21a1cSEd Tanous     readSSEQueryParams(std::string sseFilter, std::string& formatType,
28607941a88SAyushi Smriti                        std::vector<std::string>& messageIds,
28707941a88SAyushi Smriti                        std::vector<std::string>& registryPrefixes,
288144b6318SAppaRao Puli                        std::vector<std::string>& metricReportDefinitions)
28907941a88SAyushi Smriti {
29007941a88SAyushi Smriti     sseFilter.erase(std::remove_if(sseFilter.begin(), sseFilter.end(),
29107941a88SAyushi Smriti                                    isFilterQuerySpecialChar),
29207941a88SAyushi Smriti                     sseFilter.end());
29307941a88SAyushi Smriti 
29407941a88SAyushi Smriti     std::vector<std::string> result;
29507941a88SAyushi Smriti     boost::split(result, sseFilter, boost::is_any_of(" "),
29607941a88SAyushi Smriti                  boost::token_compress_on);
29707941a88SAyushi Smriti 
29807941a88SAyushi Smriti     BMCWEB_LOG_DEBUG << "No of tokens in SEE query: " << result.size();
29907941a88SAyushi Smriti 
30007941a88SAyushi Smriti     constexpr uint8_t divisor = 4;
30107941a88SAyushi Smriti     constexpr uint8_t minTokenSize = 3;
30207941a88SAyushi Smriti     if (result.size() % divisor != minTokenSize)
30307941a88SAyushi Smriti     {
30407941a88SAyushi Smriti         BMCWEB_LOG_ERROR << "Invalid SSE filter specified.";
30507941a88SAyushi Smriti         return false;
30607941a88SAyushi Smriti     }
30707941a88SAyushi Smriti 
30807941a88SAyushi Smriti     for (std::size_t i = 0; i < result.size(); i += divisor)
30907941a88SAyushi Smriti     {
31007941a88SAyushi Smriti         std::string& key = result[i];
31107941a88SAyushi Smriti         std::string& op = result[i + 1];
31207941a88SAyushi Smriti         std::string& value = result[i + 2];
31307941a88SAyushi Smriti 
31407941a88SAyushi Smriti         if ((i + minTokenSize) < result.size())
31507941a88SAyushi Smriti         {
3164e0453b1SGunnar Mills             std::string& separator = result[i + minTokenSize];
31707941a88SAyushi Smriti             // SSE supports only "or" and "and" in query params.
3184e0453b1SGunnar Mills             if ((separator != "or") && (separator != "and"))
31907941a88SAyushi Smriti             {
32007941a88SAyushi Smriti                 BMCWEB_LOG_ERROR
32107941a88SAyushi Smriti                     << "Invalid group operator in SSE query parameters";
32207941a88SAyushi Smriti                 return false;
32307941a88SAyushi Smriti             }
32407941a88SAyushi Smriti         }
32507941a88SAyushi Smriti 
32607941a88SAyushi Smriti         // SSE supports only "eq" as per spec.
32707941a88SAyushi Smriti         if (op != "eq")
32807941a88SAyushi Smriti         {
32907941a88SAyushi Smriti             BMCWEB_LOG_ERROR
33007941a88SAyushi Smriti                 << "Invalid assignment operator in SSE query parameters";
33107941a88SAyushi Smriti             return false;
33207941a88SAyushi Smriti         }
33307941a88SAyushi Smriti 
33407941a88SAyushi Smriti         BMCWEB_LOG_DEBUG << key << " : " << value;
33507941a88SAyushi Smriti         if (key == "EventFormatType")
33607941a88SAyushi Smriti         {
33707941a88SAyushi Smriti             formatType = value;
33807941a88SAyushi Smriti         }
33907941a88SAyushi Smriti         else if (key == "MessageId")
34007941a88SAyushi Smriti         {
34107941a88SAyushi Smriti             messageIds.push_back(value);
34207941a88SAyushi Smriti         }
34307941a88SAyushi Smriti         else if (key == "RegistryPrefix")
34407941a88SAyushi Smriti         {
34507941a88SAyushi Smriti             registryPrefixes.push_back(value);
34607941a88SAyushi Smriti         }
34707941a88SAyushi Smriti         else if (key == "MetricReportDefinition")
34807941a88SAyushi Smriti         {
34907941a88SAyushi Smriti             metricReportDefinitions.push_back(value);
35007941a88SAyushi Smriti         }
35107941a88SAyushi Smriti         else
35207941a88SAyushi Smriti         {
35307941a88SAyushi Smriti             BMCWEB_LOG_ERROR << "Invalid property(" << key
35407941a88SAyushi Smriti                              << ")in SSE filter query.";
35507941a88SAyushi Smriti             return false;
35607941a88SAyushi Smriti         }
35707941a88SAyushi Smriti     }
35807941a88SAyushi Smriti     return true;
35907941a88SAyushi Smriti }
36007941a88SAyushi Smriti 
36128afb49cSJunLin Chen class Subscription : public persistent_data::UserSubscription
362b52664e2SAppaRao Puli {
363b52664e2SAppaRao Puli   public:
364b52664e2SAppaRao Puli     Subscription(const Subscription&) = delete;
365b52664e2SAppaRao Puli     Subscription& operator=(const Subscription&) = delete;
366b52664e2SAppaRao Puli     Subscription(Subscription&&) = delete;
367b52664e2SAppaRao Puli     Subscription& operator=(Subscription&&) = delete;
368b52664e2SAppaRao Puli 
369eb1c47d3SEd Tanous     Subscription(const std::string& inHost, uint16_t inPort,
370b52664e2SAppaRao Puli                  const std::string& inPath, const std::string& inUriProto) :
3710b4bdd93SAppaRao Puli         eventSeqNum(1),
3720b4bdd93SAppaRao Puli         host(inHost), port(inPort), path(inPath), uriProto(inUriProto)
373b52664e2SAppaRao Puli     {
3747adb85acSSunitha Harish         // Subscription constructor
375b52664e2SAppaRao Puli     }
3764bbf237fSAppaRao Puli 
37723e64207SEd Tanous     Subscription(const std::shared_ptr<boost::beast::tcp_stream>& adaptor) :
3784bbf237fSAppaRao Puli         eventSeqNum(1)
3794bbf237fSAppaRao Puli     {
3804bbf237fSAppaRao Puli         sseConn = std::make_shared<crow::ServerSentEvents>(adaptor);
3814bbf237fSAppaRao Puli     }
3824bbf237fSAppaRao Puli 
3839f616dd1SEd Tanous     ~Subscription() = default;
384b52664e2SAppaRao Puli 
385f52c03c1SCarson Labrado     bool sendEvent(std::string& msg)
386b52664e2SAppaRao Puli     {
3876ba8c82eSsunharis_in         persistent_data::EventServiceConfig eventServiceConfig =
3886ba8c82eSsunharis_in             persistent_data::EventServiceStore::getInstance()
3896ba8c82eSsunharis_in                 .getEventServiceConfig();
3906ba8c82eSsunharis_in         if (!eventServiceConfig.enabled)
3916ba8c82eSsunharis_in         {
3926ba8c82eSsunharis_in             return false;
3936ba8c82eSsunharis_in         }
3946ba8c82eSsunharis_in 
395f52c03c1SCarson Labrado         // A connection pool will be created if one does not already exist
396244256ccSCarson Labrado         crow::HttpClient::getInstance().sendData(
397244256ccSCarson Labrado             msg, id, host, port, path, httpHeaders,
398244256ccSCarson Labrado             boost::beast::http::verb::post, retryPolicyName);
3997adb85acSSunitha Harish         eventSeqNum++;
4007adb85acSSunitha Harish 
4014bbf237fSAppaRao Puli         if (sseConn != nullptr)
4024bbf237fSAppaRao Puli         {
4034bbf237fSAppaRao Puli             sseConn->sendData(eventSeqNum, msg);
4044bbf237fSAppaRao Puli         }
4056ba8c82eSsunharis_in         return true;
4064bbf237fSAppaRao Puli     }
4074bbf237fSAppaRao Puli 
4086ba8c82eSsunharis_in     bool sendTestEventLog()
4090b4bdd93SAppaRao Puli     {
4100b4bdd93SAppaRao Puli         nlohmann::json logEntryArray;
4110b4bdd93SAppaRao Puli         logEntryArray.push_back({});
4120b4bdd93SAppaRao Puli         nlohmann::json& logEntryJson = logEntryArray.back();
4130b4bdd93SAppaRao Puli 
4147c8c4058STejas Patil         logEntryJson = {
4157c8c4058STejas Patil             {"EventId", "TestID"},
4160b4bdd93SAppaRao Puli             {"EventType", "Event"},
4170b4bdd93SAppaRao Puli             {"Severity", "OK"},
4180b4bdd93SAppaRao Puli             {"Message", "Generated test event"},
4194a0bf539SManojkiran Eda             {"MessageId", "OpenBMC.0.2.TestEventLog"},
4200b4bdd93SAppaRao Puli             {"MessageArgs", nlohmann::json::array()},
4217c8c4058STejas Patil             {"EventTimestamp", crow::utility::getDateTimeOffsetNow().first},
4220b4bdd93SAppaRao Puli             {"Context", customText}};
4230b4bdd93SAppaRao Puli 
4241476687dSEd Tanous         nlohmann::json msg;
4251476687dSEd Tanous         msg["@odata.type"] = "#Event.v1_4_0.Event";
4261476687dSEd Tanous         msg["Id"] = std::to_string(eventSeqNum);
4271476687dSEd Tanous         msg["Name"] = "Event Log";
4281476687dSEd Tanous         msg["Events"] = logEntryArray;
4290b4bdd93SAppaRao Puli 
430f52c03c1SCarson Labrado         std::string strMsg =
431f52c03c1SCarson Labrado             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace);
432f52c03c1SCarson Labrado         return this->sendEvent(strMsg);
4330b4bdd93SAppaRao Puli     }
4340b4bdd93SAppaRao Puli 
4357f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
4367f4eb588SAppaRao Puli     void filterAndSendEventLogs(
4377f4eb588SAppaRao Puli         const std::vector<EventLogObjectsType>& eventRecords)
4387f4eb588SAppaRao Puli     {
4397f4eb588SAppaRao Puli         nlohmann::json logEntryArray;
4407f4eb588SAppaRao Puli         for (const EventLogObjectsType& logEntry : eventRecords)
4417f4eb588SAppaRao Puli         {
4427f4eb588SAppaRao Puli             const std::string& idStr = std::get<0>(logEntry);
4437f4eb588SAppaRao Puli             const std::string& timestamp = std::get<1>(logEntry);
4447f4eb588SAppaRao Puli             const std::string& messageID = std::get<2>(logEntry);
4457f4eb588SAppaRao Puli             const std::string& registryName = std::get<3>(logEntry);
4467f4eb588SAppaRao Puli             const std::string& messageKey = std::get<4>(logEntry);
4475e715de6SAppaRao Puli             const std::vector<std::string>& messageArgs = std::get<5>(logEntry);
4487f4eb588SAppaRao Puli 
4497f4eb588SAppaRao Puli             // If registryPrefixes list is empty, don't filter events
4507f4eb588SAppaRao Puli             // send everything.
45126f6976fSEd Tanous             if (!registryPrefixes.empty())
4527f4eb588SAppaRao Puli             {
4537f4eb588SAppaRao Puli                 auto obj = std::find(registryPrefixes.begin(),
4547f4eb588SAppaRao Puli                                      registryPrefixes.end(), registryName);
4557f4eb588SAppaRao Puli                 if (obj == registryPrefixes.end())
4567f4eb588SAppaRao Puli                 {
4577f4eb588SAppaRao Puli                     continue;
4587f4eb588SAppaRao Puli                 }
4597f4eb588SAppaRao Puli             }
4607f4eb588SAppaRao Puli 
4617f4eb588SAppaRao Puli             // If registryMsgIds list is empty, don't filter events
4627f4eb588SAppaRao Puli             // send everything.
46326f6976fSEd Tanous             if (!registryMsgIds.empty())
4647f4eb588SAppaRao Puli             {
4657f4eb588SAppaRao Puli                 auto obj = std::find(registryMsgIds.begin(),
4667f4eb588SAppaRao Puli                                      registryMsgIds.end(), messageKey);
4677f4eb588SAppaRao Puli                 if (obj == registryMsgIds.end())
4687f4eb588SAppaRao Puli                 {
4697f4eb588SAppaRao Puli                     continue;
4707f4eb588SAppaRao Puli                 }
4717f4eb588SAppaRao Puli             }
4727f4eb588SAppaRao Puli 
473c5ba4c27SEd Tanous             std::vector<std::string_view> messageArgsView(messageArgs.begin(),
474c5ba4c27SEd Tanous                                                           messageArgs.end());
475c5ba4c27SEd Tanous 
4767f4eb588SAppaRao Puli             logEntryArray.push_back({});
4777f4eb588SAppaRao Puli             nlohmann::json& bmcLogEntry = logEntryArray.back();
478c5ba4c27SEd Tanous             if (event_log::formatEventLogEntry(idStr, messageID,
479c5ba4c27SEd Tanous                                                messageArgsView, timestamp,
480c5ba4c27SEd Tanous                                                customText, bmcLogEntry) != 0)
4817f4eb588SAppaRao Puli             {
4827f4eb588SAppaRao Puli                 BMCWEB_LOG_DEBUG << "Read eventLog entry failed";
4837f4eb588SAppaRao Puli                 continue;
4847f4eb588SAppaRao Puli             }
4857f4eb588SAppaRao Puli         }
4867f4eb588SAppaRao Puli 
48726f6976fSEd Tanous         if (logEntryArray.empty())
4887f4eb588SAppaRao Puli         {
4897f4eb588SAppaRao Puli             BMCWEB_LOG_DEBUG << "No log entries available to be transferred.";
4907f4eb588SAppaRao Puli             return;
4917f4eb588SAppaRao Puli         }
4927f4eb588SAppaRao Puli 
4931476687dSEd Tanous         nlohmann::json msg;
4941476687dSEd Tanous         msg["@odata.type"] = "#Event.v1_4_0.Event";
4951476687dSEd Tanous         msg["Id"] = std::to_string(eventSeqNum);
4961476687dSEd Tanous         msg["Name"] = "Event Log";
4971476687dSEd Tanous         msg["Events"] = logEntryArray;
4987f4eb588SAppaRao Puli 
499f52c03c1SCarson Labrado         std::string strMsg =
500f52c03c1SCarson Labrado             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace);
501f52c03c1SCarson Labrado         this->sendEvent(strMsg);
5027f4eb588SAppaRao Puli     }
5037f4eb588SAppaRao Puli #endif
5047f4eb588SAppaRao Puli 
505248d0230SEd Tanous     void filterAndSendReports(const std::string& reportId,
5061e1e598dSJonathan Doman                               const telemetry::TimestampReadings& var)
507156d6b00SAppaRao Puli     {
508456cd875SSzymon Dompke         boost::urls::url mrdUri =
509456cd875SSzymon Dompke             crow::utility::urlFromPieces("redfish", "v1", "TelemetryService",
510456cd875SSzymon Dompke                                          "MetricReportDefinitions", reportId);
511156d6b00SAppaRao Puli 
512156d6b00SAppaRao Puli         // Empty list means no filter. Send everything.
51326f6976fSEd Tanous         if (!metricReportDefinitions.empty())
514156d6b00SAppaRao Puli         {
515156d6b00SAppaRao Puli             if (std::find(metricReportDefinitions.begin(),
516156d6b00SAppaRao Puli                           metricReportDefinitions.end(),
517456cd875SSzymon Dompke                           mrdUri.string()) == metricReportDefinitions.end())
518156d6b00SAppaRao Puli             {
519156d6b00SAppaRao Puli                 return;
520156d6b00SAppaRao Puli             }
521156d6b00SAppaRao Puli         }
522156d6b00SAppaRao Puli 
523c0353249SWludzik, Jozef         nlohmann::json msg;
524248d0230SEd Tanous         if (!telemetry::fillReport(msg, reportId, var))
525156d6b00SAppaRao Puli         {
526c0353249SWludzik, Jozef             BMCWEB_LOG_ERROR << "Failed to fill the MetricReport for DBus "
527c0353249SWludzik, Jozef                                 "Report with id "
528248d0230SEd Tanous                              << reportId;
529c0353249SWludzik, Jozef             return;
530156d6b00SAppaRao Puli         }
531156d6b00SAppaRao Puli 
532f52c03c1SCarson Labrado         std::string strMsg =
533f52c03c1SCarson Labrado             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace);
534f52c03c1SCarson Labrado         this->sendEvent(strMsg);
535156d6b00SAppaRao Puli     }
536156d6b00SAppaRao Puli 
537fe44eb0bSAyushi Smriti     void updateRetryConfig(const uint32_t retryAttempts,
538fe44eb0bSAyushi Smriti                            const uint32_t retryTimeoutInterval)
539fe44eb0bSAyushi Smriti     {
540f52c03c1SCarson Labrado         crow::HttpClient::getInstance().setRetryConfig(
541a7a80296SCarson Labrado             retryAttempts, retryTimeoutInterval, retryRespHandler,
542a7a80296SCarson Labrado             retryPolicyName);
54362de0c68SAppaRao Puli     }
544fe44eb0bSAyushi Smriti 
545fe44eb0bSAyushi Smriti     void updateRetryPolicy()
546fe44eb0bSAyushi Smriti     {
547f52c03c1SCarson Labrado         crow::HttpClient::getInstance().setRetryPolicy(retryPolicy,
548f52c03c1SCarson Labrado                                                        retryPolicyName);
54962de0c68SAppaRao Puli     }
550fe44eb0bSAyushi Smriti 
5519eb808c1SEd Tanous     uint64_t getEventSeqNum() const
55296330b99SSunitha Harish     {
55396330b99SSunitha Harish         return eventSeqNum;
55496330b99SSunitha Harish     }
55596330b99SSunitha Harish 
556b52664e2SAppaRao Puli   private:
5570b4bdd93SAppaRao Puli     uint64_t eventSeqNum;
558b52664e2SAppaRao Puli     std::string host;
559eb1c47d3SEd Tanous     uint16_t port = 0;
560b52664e2SAppaRao Puli     std::string path;
561b52664e2SAppaRao Puli     std::string uriProto;
5624bbf237fSAppaRao Puli     std::shared_ptr<crow::ServerSentEvents> sseConn = nullptr;
563f52c03c1SCarson Labrado     std::string retryPolicyName = "SubscriptionEvent";
564a7a80296SCarson Labrado 
565a7a80296SCarson Labrado     // Check used to indicate what response codes are valid as part of our retry
566a7a80296SCarson Labrado     // policy.  2XX is considered acceptable
567a7a80296SCarson Labrado     static boost::system::error_code retryRespHandler(unsigned int respCode)
568a7a80296SCarson Labrado     {
569a7a80296SCarson Labrado         BMCWEB_LOG_DEBUG
570a7a80296SCarson Labrado             << "Checking response code validity for SubscriptionEvent";
571a7a80296SCarson Labrado         if ((respCode < 200) || (respCode >= 300))
572a7a80296SCarson Labrado         {
573a7a80296SCarson Labrado             return boost::system::errc::make_error_code(
574a7a80296SCarson Labrado                 boost::system::errc::result_out_of_range);
575a7a80296SCarson Labrado         }
576a7a80296SCarson Labrado 
577a7a80296SCarson Labrado         // Return 0 if the response code is valid
578a7a80296SCarson Labrado         return boost::system::errc::make_error_code(
579a7a80296SCarson Labrado             boost::system::errc::success);
5809fa6d147SNan Zhou     }
581b52664e2SAppaRao Puli };
582b52664e2SAppaRao Puli 
583b52664e2SAppaRao Puli class EventServiceManager
584b52664e2SAppaRao Puli {
585b52664e2SAppaRao Puli   private:
586d3a9e084SEd Tanous     bool serviceEnabled = false;
587d3a9e084SEd Tanous     uint32_t retryAttempts = 0;
588d3a9e084SEd Tanous     uint32_t retryTimeoutInterval = 0;
5897d1cc387SAppaRao Puli 
5909f616dd1SEd Tanous     EventServiceManager()
591b52664e2SAppaRao Puli     {
5921bf712bcSAyushi Smriti         // Load config from persist store.
5931bf712bcSAyushi Smriti         initConfig();
594b52664e2SAppaRao Puli     }
595b52664e2SAppaRao Puli 
5962558979cSP Dheeraj Srujan Kumar     std::streampos redfishLogFilePosition{0};
5979f616dd1SEd Tanous     size_t noOfEventLogSubscribers{0};
5989f616dd1SEd Tanous     size_t noOfMetricReportSubscribers{0};
599156d6b00SAppaRao Puli     std::shared_ptr<sdbusplus::bus::match::match> matchTelemetryMonitor;
600b52664e2SAppaRao Puli     boost::container::flat_map<std::string, std::shared_ptr<Subscription>>
601b52664e2SAppaRao Puli         subscriptionsMap;
602b52664e2SAppaRao Puli 
6039f616dd1SEd Tanous     uint64_t eventId{1};
60496330b99SSunitha Harish 
605b52664e2SAppaRao Puli   public:
6069f616dd1SEd Tanous     EventServiceManager(const EventServiceManager&) = delete;
6079f616dd1SEd Tanous     EventServiceManager& operator=(const EventServiceManager&) = delete;
6089f616dd1SEd Tanous     EventServiceManager(EventServiceManager&&) = delete;
6099f616dd1SEd Tanous     EventServiceManager& operator=(EventServiceManager&&) = delete;
610ecd6a3a2SEd Tanous     ~EventServiceManager() = default;
6119f616dd1SEd Tanous 
612b52664e2SAppaRao Puli     static EventServiceManager& getInstance()
613b52664e2SAppaRao Puli     {
614b52664e2SAppaRao Puli         static EventServiceManager handler;
615b52664e2SAppaRao Puli         return handler;
616b52664e2SAppaRao Puli     }
617b52664e2SAppaRao Puli 
6181bf712bcSAyushi Smriti     void initConfig()
6191bf712bcSAyushi Smriti     {
62028afb49cSJunLin Chen         loadOldBehavior();
6211bf712bcSAyushi Smriti 
62228afb49cSJunLin Chen         persistent_data::EventServiceConfig eventServiceConfig =
62328afb49cSJunLin Chen             persistent_data::EventServiceStore::getInstance()
62428afb49cSJunLin Chen                 .getEventServiceConfig();
6251bf712bcSAyushi Smriti 
62628afb49cSJunLin Chen         serviceEnabled = eventServiceConfig.enabled;
62728afb49cSJunLin Chen         retryAttempts = eventServiceConfig.retryAttempts;
62828afb49cSJunLin Chen         retryTimeoutInterval = eventServiceConfig.retryTimeoutInterval;
6291bf712bcSAyushi Smriti 
63028afb49cSJunLin Chen         for (const auto& it : persistent_data::EventServiceStore::getInstance()
63128afb49cSJunLin Chen                                   .subscriptionsConfigMap)
6321bf712bcSAyushi Smriti         {
63328afb49cSJunLin Chen             std::shared_ptr<persistent_data::UserSubscription> newSub =
63428afb49cSJunLin Chen                 it.second;
6354bbf237fSAppaRao Puli 
6361bf712bcSAyushi Smriti             std::string host;
6371bf712bcSAyushi Smriti             std::string urlProto;
638eb1c47d3SEd Tanous             uint16_t port = 0;
6391bf712bcSAyushi Smriti             std::string path;
64011baefe4SEd Tanous             bool status = crow::utility::validateAndSplitUrl(
64111baefe4SEd Tanous                 newSub->destinationUrl, urlProto, host, port, path);
6421bf712bcSAyushi Smriti 
6431bf712bcSAyushi Smriti             if (!status)
6441bf712bcSAyushi Smriti             {
6451bf712bcSAyushi Smriti                 BMCWEB_LOG_ERROR
6461bf712bcSAyushi Smriti                     << "Failed to validate and split destination url";
6471bf712bcSAyushi Smriti                 continue;
6481bf712bcSAyushi Smriti             }
6491bf712bcSAyushi Smriti             std::shared_ptr<Subscription> subValue =
6501bf712bcSAyushi Smriti                 std::make_shared<Subscription>(host, port, path, urlProto);
6511bf712bcSAyushi Smriti 
65228afb49cSJunLin Chen             subValue->id = newSub->id;
65328afb49cSJunLin Chen             subValue->destinationUrl = newSub->destinationUrl;
65428afb49cSJunLin Chen             subValue->protocol = newSub->protocol;
65528afb49cSJunLin Chen             subValue->retryPolicy = newSub->retryPolicy;
65628afb49cSJunLin Chen             subValue->customText = newSub->customText;
65728afb49cSJunLin Chen             subValue->eventFormatType = newSub->eventFormatType;
65828afb49cSJunLin Chen             subValue->subscriptionType = newSub->subscriptionType;
65928afb49cSJunLin Chen             subValue->registryMsgIds = newSub->registryMsgIds;
66028afb49cSJunLin Chen             subValue->registryPrefixes = newSub->registryPrefixes;
66128afb49cSJunLin Chen             subValue->resourceTypes = newSub->resourceTypes;
66228afb49cSJunLin Chen             subValue->httpHeaders = newSub->httpHeaders;
66328afb49cSJunLin Chen             subValue->metricReportDefinitions = newSub->metricReportDefinitions;
6641bf712bcSAyushi Smriti 
66528afb49cSJunLin Chen             if (subValue->id.empty())
6661bf712bcSAyushi Smriti             {
6671bf712bcSAyushi Smriti                 BMCWEB_LOG_ERROR << "Failed to add subscription";
6681bf712bcSAyushi Smriti             }
66928afb49cSJunLin Chen             subscriptionsMap.insert(std::pair(subValue->id, subValue));
67028afb49cSJunLin Chen 
67128afb49cSJunLin Chen             updateNoOfSubscribersCount();
67228afb49cSJunLin Chen 
67328afb49cSJunLin Chen #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
6742558979cSP Dheeraj Srujan Kumar 
6752558979cSP Dheeraj Srujan Kumar             cacheRedfishLogFile();
6762558979cSP Dheeraj Srujan Kumar 
67728afb49cSJunLin Chen #endif
67828afb49cSJunLin Chen             // Update retry configuration.
67928afb49cSJunLin Chen             subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
68028afb49cSJunLin Chen             subValue->updateRetryPolicy();
6811bf712bcSAyushi Smriti         }
6821bf712bcSAyushi Smriti     }
6831bf712bcSAyushi Smriti 
68456d2396dSEd Tanous     static void loadOldBehavior()
685b52664e2SAppaRao Puli     {
68628afb49cSJunLin Chen         std::ifstream eventConfigFile(eventServiceFile);
68728afb49cSJunLin Chen         if (!eventConfigFile.good())
6881bf712bcSAyushi Smriti         {
68928afb49cSJunLin Chen             BMCWEB_LOG_DEBUG << "Old eventService config not exist";
69028afb49cSJunLin Chen             return;
69128afb49cSJunLin Chen         }
69228afb49cSJunLin Chen         auto jsonData = nlohmann::json::parse(eventConfigFile, nullptr, false);
69328afb49cSJunLin Chen         if (jsonData.is_discarded())
6944bbf237fSAppaRao Puli         {
69528afb49cSJunLin Chen             BMCWEB_LOG_ERROR << "Old eventService config parse error.";
69628afb49cSJunLin Chen             return;
69728afb49cSJunLin Chen         }
69828afb49cSJunLin Chen 
69928afb49cSJunLin Chen         for (const auto& item : jsonData.items())
70028afb49cSJunLin Chen         {
70128afb49cSJunLin Chen             if (item.key() == "Configuration")
70228afb49cSJunLin Chen             {
70328afb49cSJunLin Chen                 persistent_data::EventServiceStore::getInstance()
70428afb49cSJunLin Chen                     .getEventServiceConfig()
70528afb49cSJunLin Chen                     .fromJson(item.value());
70628afb49cSJunLin Chen             }
70728afb49cSJunLin Chen             else if (item.key() == "Subscriptions")
70828afb49cSJunLin Chen             {
70928afb49cSJunLin Chen                 for (const auto& elem : item.value())
71028afb49cSJunLin Chen                 {
71128afb49cSJunLin Chen                     std::shared_ptr<persistent_data::UserSubscription>
71228afb49cSJunLin Chen                         newSubscription =
71328afb49cSJunLin Chen                             persistent_data::UserSubscription::fromJson(elem,
71428afb49cSJunLin Chen                                                                         true);
71528afb49cSJunLin Chen                     if (newSubscription == nullptr)
71628afb49cSJunLin Chen                     {
71728afb49cSJunLin Chen                         BMCWEB_LOG_ERROR << "Problem reading subscription "
71828afb49cSJunLin Chen                                             "from old persistent store";
7194bbf237fSAppaRao Puli                         continue;
7204bbf237fSAppaRao Puli                     }
7211bf712bcSAyushi Smriti 
72228afb49cSJunLin Chen                     std::uniform_int_distribution<uint32_t> dist(0);
72328afb49cSJunLin Chen                     bmcweb::OpenSSLGenerator gen;
7241bf712bcSAyushi Smriti 
72528afb49cSJunLin Chen                     std::string id;
7261bf712bcSAyushi Smriti 
72728afb49cSJunLin Chen                     int retry = 3;
728e662eae8SEd Tanous                     while (retry != 0)
7291bf712bcSAyushi Smriti                     {
73028afb49cSJunLin Chen                         id = std::to_string(dist(gen));
73128afb49cSJunLin Chen                         if (gen.error())
7327d1cc387SAppaRao Puli                         {
73328afb49cSJunLin Chen                             retry = 0;
73428afb49cSJunLin Chen                             break;
73528afb49cSJunLin Chen                         }
73628afb49cSJunLin Chen                         newSubscription->id = id;
73728afb49cSJunLin Chen                         auto inserted =
73828afb49cSJunLin Chen                             persistent_data::EventServiceStore::getInstance()
73928afb49cSJunLin Chen                                 .subscriptionsConfigMap.insert(
74028afb49cSJunLin Chen                                     std::pair(id, newSubscription));
74128afb49cSJunLin Chen                         if (inserted.second)
74228afb49cSJunLin Chen                         {
74328afb49cSJunLin Chen                             break;
74428afb49cSJunLin Chen                         }
74528afb49cSJunLin Chen                         --retry;
7467d1cc387SAppaRao Puli                     }
7477d1cc387SAppaRao Puli 
74828afb49cSJunLin Chen                     if (retry <= 0)
74928afb49cSJunLin Chen                     {
75028afb49cSJunLin Chen                         BMCWEB_LOG_ERROR
75128afb49cSJunLin Chen                             << "Failed to generate random number from old "
75228afb49cSJunLin Chen                                "persistent store";
75328afb49cSJunLin Chen                         continue;
75428afb49cSJunLin Chen                     }
75528afb49cSJunLin Chen                 }
75628afb49cSJunLin Chen             }
75728afb49cSJunLin Chen 
75828afb49cSJunLin Chen             persistent_data::getConfig().writeData();
75928afb49cSJunLin Chen             std::remove(eventServiceFile);
76028afb49cSJunLin Chen             BMCWEB_LOG_DEBUG << "Remove old eventservice config";
76128afb49cSJunLin Chen         }
76228afb49cSJunLin Chen     }
76328afb49cSJunLin Chen 
7649eb808c1SEd Tanous     void updateSubscriptionData() const
76528afb49cSJunLin Chen     {
76628afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
76728afb49cSJunLin Chen             .eventServiceConfig.enabled = serviceEnabled;
76828afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
76928afb49cSJunLin Chen             .eventServiceConfig.retryAttempts = retryAttempts;
77028afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
77128afb49cSJunLin Chen             .eventServiceConfig.retryTimeoutInterval = retryTimeoutInterval;
77228afb49cSJunLin Chen 
77328afb49cSJunLin Chen         persistent_data::getConfig().writeData();
77428afb49cSJunLin Chen     }
77528afb49cSJunLin Chen 
77628afb49cSJunLin Chen     void setEventServiceConfig(const persistent_data::EventServiceConfig& cfg)
7777d1cc387SAppaRao Puli     {
7787d1cc387SAppaRao Puli         bool updateConfig = false;
779fe44eb0bSAyushi Smriti         bool updateRetryCfg = false;
7807d1cc387SAppaRao Puli 
78128afb49cSJunLin Chen         if (serviceEnabled != cfg.enabled)
7827d1cc387SAppaRao Puli         {
78328afb49cSJunLin Chen             serviceEnabled = cfg.enabled;
784e662eae8SEd Tanous             if (serviceEnabled && noOfMetricReportSubscribers != 0U)
7857d1cc387SAppaRao Puli             {
7867d1cc387SAppaRao Puli                 registerMetricReportSignal();
7877d1cc387SAppaRao Puli             }
7887d1cc387SAppaRao Puli             else
7897d1cc387SAppaRao Puli             {
7907d1cc387SAppaRao Puli                 unregisterMetricReportSignal();
7917d1cc387SAppaRao Puli             }
7927d1cc387SAppaRao Puli             updateConfig = true;
7937d1cc387SAppaRao Puli         }
7947d1cc387SAppaRao Puli 
79528afb49cSJunLin Chen         if (retryAttempts != cfg.retryAttempts)
7967d1cc387SAppaRao Puli         {
79728afb49cSJunLin Chen             retryAttempts = cfg.retryAttempts;
7987d1cc387SAppaRao Puli             updateConfig = true;
799fe44eb0bSAyushi Smriti             updateRetryCfg = true;
8007d1cc387SAppaRao Puli         }
8017d1cc387SAppaRao Puli 
80228afb49cSJunLin Chen         if (retryTimeoutInterval != cfg.retryTimeoutInterval)
8037d1cc387SAppaRao Puli         {
80428afb49cSJunLin Chen             retryTimeoutInterval = cfg.retryTimeoutInterval;
8057d1cc387SAppaRao Puli             updateConfig = true;
806fe44eb0bSAyushi Smriti             updateRetryCfg = true;
8077d1cc387SAppaRao Puli         }
8087d1cc387SAppaRao Puli 
8097d1cc387SAppaRao Puli         if (updateConfig)
8107d1cc387SAppaRao Puli         {
8117d1cc387SAppaRao Puli             updateSubscriptionData();
8127d1cc387SAppaRao Puli         }
813fe44eb0bSAyushi Smriti 
814fe44eb0bSAyushi Smriti         if (updateRetryCfg)
815fe44eb0bSAyushi Smriti         {
816fe44eb0bSAyushi Smriti             // Update the changed retry config to all subscriptions
817fe44eb0bSAyushi Smriti             for (const auto& it :
818fe44eb0bSAyushi Smriti                  EventServiceManager::getInstance().subscriptionsMap)
819fe44eb0bSAyushi Smriti             {
820fe44eb0bSAyushi Smriti                 std::shared_ptr<Subscription> entry = it.second;
821fe44eb0bSAyushi Smriti                 entry->updateRetryConfig(retryAttempts, retryTimeoutInterval);
822fe44eb0bSAyushi Smriti             }
823fe44eb0bSAyushi Smriti         }
8247d1cc387SAppaRao Puli     }
8257d1cc387SAppaRao Puli 
8267d1cc387SAppaRao Puli     void updateNoOfSubscribersCount()
8277d1cc387SAppaRao Puli     {
8287d1cc387SAppaRao Puli         size_t eventLogSubCount = 0;
8297d1cc387SAppaRao Puli         size_t metricReportSubCount = 0;
8307d1cc387SAppaRao Puli         for (const auto& it : subscriptionsMap)
8317d1cc387SAppaRao Puli         {
8327d1cc387SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
8337d1cc387SAppaRao Puli             if (entry->eventFormatType == eventFormatType)
8347d1cc387SAppaRao Puli             {
8357d1cc387SAppaRao Puli                 eventLogSubCount++;
8367d1cc387SAppaRao Puli             }
8377d1cc387SAppaRao Puli             else if (entry->eventFormatType == metricReportFormatType)
8387d1cc387SAppaRao Puli             {
8397d1cc387SAppaRao Puli                 metricReportSubCount++;
8407d1cc387SAppaRao Puli             }
8417d1cc387SAppaRao Puli         }
8427d1cc387SAppaRao Puli 
8437d1cc387SAppaRao Puli         noOfEventLogSubscribers = eventLogSubCount;
8447d1cc387SAppaRao Puli         if (noOfMetricReportSubscribers != metricReportSubCount)
8457d1cc387SAppaRao Puli         {
8467d1cc387SAppaRao Puli             noOfMetricReportSubscribers = metricReportSubCount;
847e662eae8SEd Tanous             if (noOfMetricReportSubscribers != 0U)
8487d1cc387SAppaRao Puli             {
8497d1cc387SAppaRao Puli                 registerMetricReportSignal();
8507d1cc387SAppaRao Puli             }
8517d1cc387SAppaRao Puli             else
8527d1cc387SAppaRao Puli             {
8537d1cc387SAppaRao Puli                 unregisterMetricReportSignal();
8547d1cc387SAppaRao Puli             }
8557d1cc387SAppaRao Puli         }
8567d1cc387SAppaRao Puli     }
8577d1cc387SAppaRao Puli 
858b52664e2SAppaRao Puli     std::shared_ptr<Subscription> getSubscription(const std::string& id)
859b52664e2SAppaRao Puli     {
860b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
861b52664e2SAppaRao Puli         if (obj == subscriptionsMap.end())
862b52664e2SAppaRao Puli         {
863b52664e2SAppaRao Puli             BMCWEB_LOG_ERROR << "No subscription exist with ID:" << id;
864b52664e2SAppaRao Puli             return nullptr;
865b52664e2SAppaRao Puli         }
866b52664e2SAppaRao Puli         std::shared_ptr<Subscription> subValue = obj->second;
867b52664e2SAppaRao Puli         return subValue;
868b52664e2SAppaRao Puli     }
869b52664e2SAppaRao Puli 
870b5a76932SEd Tanous     std::string addSubscription(const std::shared_ptr<Subscription>& subValue,
8711bf712bcSAyushi Smriti                                 const bool updateFile = true)
872b52664e2SAppaRao Puli     {
873fc76b8acSEd Tanous 
874fc76b8acSEd Tanous         std::uniform_int_distribution<uint32_t> dist(0);
875fc76b8acSEd Tanous         bmcweb::OpenSSLGenerator gen;
876fc76b8acSEd Tanous 
877b52664e2SAppaRao Puli         std::string id;
878b52664e2SAppaRao Puli 
879b52664e2SAppaRao Puli         int retry = 3;
880e662eae8SEd Tanous         while (retry != 0)
881b52664e2SAppaRao Puli         {
882fc76b8acSEd Tanous             id = std::to_string(dist(gen));
883fc76b8acSEd Tanous             if (gen.error())
884fc76b8acSEd Tanous             {
885fc76b8acSEd Tanous                 retry = 0;
886fc76b8acSEd Tanous                 break;
887fc76b8acSEd Tanous             }
888b52664e2SAppaRao Puli             auto inserted = subscriptionsMap.insert(std::pair(id, subValue));
889b52664e2SAppaRao Puli             if (inserted.second)
890b52664e2SAppaRao Puli             {
891b52664e2SAppaRao Puli                 break;
892b52664e2SAppaRao Puli             }
893b52664e2SAppaRao Puli             --retry;
89423a21a1cSEd Tanous         }
895b52664e2SAppaRao Puli 
896b52664e2SAppaRao Puli         if (retry <= 0)
897b52664e2SAppaRao Puli         {
898b52664e2SAppaRao Puli             BMCWEB_LOG_ERROR << "Failed to generate random number";
899abb93cddSEd Tanous             return "";
900b52664e2SAppaRao Puli         }
901b52664e2SAppaRao Puli 
90228afb49cSJunLin Chen         std::shared_ptr<persistent_data::UserSubscription> newSub =
90328afb49cSJunLin Chen             std::make_shared<persistent_data::UserSubscription>();
90428afb49cSJunLin Chen         newSub->id = id;
90528afb49cSJunLin Chen         newSub->destinationUrl = subValue->destinationUrl;
90628afb49cSJunLin Chen         newSub->protocol = subValue->protocol;
90728afb49cSJunLin Chen         newSub->retryPolicy = subValue->retryPolicy;
90828afb49cSJunLin Chen         newSub->customText = subValue->customText;
90928afb49cSJunLin Chen         newSub->eventFormatType = subValue->eventFormatType;
91028afb49cSJunLin Chen         newSub->subscriptionType = subValue->subscriptionType;
91128afb49cSJunLin Chen         newSub->registryMsgIds = subValue->registryMsgIds;
91228afb49cSJunLin Chen         newSub->registryPrefixes = subValue->registryPrefixes;
91328afb49cSJunLin Chen         newSub->resourceTypes = subValue->resourceTypes;
91428afb49cSJunLin Chen         newSub->httpHeaders = subValue->httpHeaders;
91528afb49cSJunLin Chen         newSub->metricReportDefinitions = subValue->metricReportDefinitions;
91628afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
91728afb49cSJunLin Chen             .subscriptionsConfigMap.emplace(newSub->id, newSub);
91828afb49cSJunLin Chen 
9197d1cc387SAppaRao Puli         updateNoOfSubscribersCount();
9201bf712bcSAyushi Smriti 
9211bf712bcSAyushi Smriti         if (updateFile)
9221bf712bcSAyushi Smriti         {
923b52664e2SAppaRao Puli             updateSubscriptionData();
9241bf712bcSAyushi Smriti         }
9257f4eb588SAppaRao Puli 
9267f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
9272558979cSP Dheeraj Srujan Kumar         if (redfishLogFilePosition != 0)
9287f4eb588SAppaRao Puli         {
9292558979cSP Dheeraj Srujan Kumar             cacheRedfishLogFile();
9307f4eb588SAppaRao Puli         }
9317f4eb588SAppaRao Puli #endif
932fe44eb0bSAyushi Smriti         // Update retry configuration.
933fe44eb0bSAyushi Smriti         subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
934fe44eb0bSAyushi Smriti         subValue->updateRetryPolicy();
935fe44eb0bSAyushi Smriti 
936b52664e2SAppaRao Puli         return id;
937b52664e2SAppaRao Puli     }
938b52664e2SAppaRao Puli 
939b52664e2SAppaRao Puli     bool isSubscriptionExist(const std::string& id)
940b52664e2SAppaRao Puli     {
941b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
94255f79e6fSEd Tanous         return obj != subscriptionsMap.end();
943b52664e2SAppaRao Puli     }
944b52664e2SAppaRao Puli 
945b52664e2SAppaRao Puli     void deleteSubscription(const std::string& id)
946b52664e2SAppaRao Puli     {
947b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
948b52664e2SAppaRao Puli         if (obj != subscriptionsMap.end())
949b52664e2SAppaRao Puli         {
950b52664e2SAppaRao Puli             subscriptionsMap.erase(obj);
95128afb49cSJunLin Chen             auto obj2 = persistent_data::EventServiceStore::getInstance()
95228afb49cSJunLin Chen                             .subscriptionsConfigMap.find(id);
95328afb49cSJunLin Chen             persistent_data::EventServiceStore::getInstance()
95428afb49cSJunLin Chen                 .subscriptionsConfigMap.erase(obj2);
9557d1cc387SAppaRao Puli             updateNoOfSubscribersCount();
956b52664e2SAppaRao Puli             updateSubscriptionData();
957b52664e2SAppaRao Puli         }
958b52664e2SAppaRao Puli     }
959b52664e2SAppaRao Puli 
960b52664e2SAppaRao Puli     size_t getNumberOfSubscriptions()
961b52664e2SAppaRao Puli     {
962b52664e2SAppaRao Puli         return subscriptionsMap.size();
963b52664e2SAppaRao Puli     }
964b52664e2SAppaRao Puli 
965b52664e2SAppaRao Puli     std::vector<std::string> getAllIDs()
966b52664e2SAppaRao Puli     {
967b52664e2SAppaRao Puli         std::vector<std::string> idList;
968b52664e2SAppaRao Puli         for (const auto& it : subscriptionsMap)
969b52664e2SAppaRao Puli         {
970b52664e2SAppaRao Puli             idList.emplace_back(it.first);
971b52664e2SAppaRao Puli         }
972b52664e2SAppaRao Puli         return idList;
973b52664e2SAppaRao Puli     }
974b52664e2SAppaRao Puli 
975b52664e2SAppaRao Puli     bool isDestinationExist(const std::string& destUrl)
976b52664e2SAppaRao Puli     {
977b52664e2SAppaRao Puli         for (const auto& it : subscriptionsMap)
978b52664e2SAppaRao Puli         {
979b52664e2SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
980b52664e2SAppaRao Puli             if (entry->destinationUrl == destUrl)
981b52664e2SAppaRao Puli             {
982b52664e2SAppaRao Puli                 BMCWEB_LOG_ERROR << "Destination exist already" << destUrl;
983b52664e2SAppaRao Puli                 return true;
984b52664e2SAppaRao Puli             }
985b52664e2SAppaRao Puli         }
986b52664e2SAppaRao Puli         return false;
987b52664e2SAppaRao Puli     }
9880b4bdd93SAppaRao Puli 
9896ba8c82eSsunharis_in     bool sendTestEventLog()
9900b4bdd93SAppaRao Puli     {
9910b4bdd93SAppaRao Puli         for (const auto& it : this->subscriptionsMap)
9920b4bdd93SAppaRao Puli         {
9930b4bdd93SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
9946ba8c82eSsunharis_in             if (!entry->sendTestEventLog())
9956ba8c82eSsunharis_in             {
9966ba8c82eSsunharis_in                 return false;
9970b4bdd93SAppaRao Puli             }
9980b4bdd93SAppaRao Puli         }
9996ba8c82eSsunharis_in         return true;
10006ba8c82eSsunharis_in     }
1001e9a14131SAppaRao Puli 
100296330b99SSunitha Harish     void sendEvent(const nlohmann::json& eventMessageIn,
100396330b99SSunitha Harish                    const std::string& origin, const std::string& resType)
100496330b99SSunitha Harish     {
1005dbb59d4dSEd Tanous         if (!serviceEnabled || (noOfEventLogSubscribers == 0U))
10066ba8c82eSsunharis_in         {
10076ba8c82eSsunharis_in             BMCWEB_LOG_DEBUG << "EventService disabled or no Subscriptions.";
10086ba8c82eSsunharis_in             return;
10096ba8c82eSsunharis_in         }
101096330b99SSunitha Harish         nlohmann::json eventRecord = nlohmann::json::array();
101196330b99SSunitha Harish         nlohmann::json eventMessage = eventMessageIn;
101296330b99SSunitha Harish         // MemberId is 0 : since we are sending one event record.
101396330b99SSunitha Harish         uint64_t memberId = 0;
101496330b99SSunitha Harish 
101596330b99SSunitha Harish         nlohmann::json event = {
101696330b99SSunitha Harish             {"EventId", eventId},
101796330b99SSunitha Harish             {"MemberId", memberId},
10187c8c4058STejas Patil             {"EventTimestamp", crow::utility::getDateTimeOffsetNow().first},
101996330b99SSunitha Harish             {"OriginOfCondition", origin}};
102096330b99SSunitha Harish         for (nlohmann::json::iterator it = event.begin(); it != event.end();
102196330b99SSunitha Harish              ++it)
102296330b99SSunitha Harish         {
102396330b99SSunitha Harish             eventMessage[it.key()] = it.value();
102496330b99SSunitha Harish         }
102596330b99SSunitha Harish         eventRecord.push_back(eventMessage);
102696330b99SSunitha Harish 
102796330b99SSunitha Harish         for (const auto& it : this->subscriptionsMap)
102896330b99SSunitha Harish         {
102996330b99SSunitha Harish             std::shared_ptr<Subscription> entry = it.second;
103096330b99SSunitha Harish             bool isSubscribed = false;
103196330b99SSunitha Harish             // Search the resourceTypes list for the subscription.
103296330b99SSunitha Harish             // If resourceTypes list is empty, don't filter events
103396330b99SSunitha Harish             // send everything.
103426f6976fSEd Tanous             if (!entry->resourceTypes.empty())
103596330b99SSunitha Harish             {
10363174e4dfSEd Tanous                 for (const auto& resource : entry->resourceTypes)
103796330b99SSunitha Harish                 {
103896330b99SSunitha Harish                     if (resType == resource)
103996330b99SSunitha Harish                     {
104096330b99SSunitha Harish                         BMCWEB_LOG_INFO << "ResourceType " << resource
104196330b99SSunitha Harish                                         << " found in the subscribed list";
104296330b99SSunitha Harish                         isSubscribed = true;
104396330b99SSunitha Harish                         break;
104496330b99SSunitha Harish                     }
104596330b99SSunitha Harish                 }
104696330b99SSunitha Harish             }
104796330b99SSunitha Harish             else // resourceTypes list is empty.
104896330b99SSunitha Harish             {
104996330b99SSunitha Harish                 isSubscribed = true;
105096330b99SSunitha Harish             }
105196330b99SSunitha Harish             if (isSubscribed)
105296330b99SSunitha Harish             {
105396330b99SSunitha Harish                 nlohmann::json msgJson = {
105496330b99SSunitha Harish                     {"@odata.type", "#Event.v1_4_0.Event"},
105596330b99SSunitha Harish                     {"Name", "Event Log"},
105696330b99SSunitha Harish                     {"Id", eventId},
105796330b99SSunitha Harish                     {"Events", eventRecord}};
1058f52c03c1SCarson Labrado 
1059f52c03c1SCarson Labrado                 std::string strMsg = msgJson.dump(
1060f52c03c1SCarson Labrado                     2, ' ', true, nlohmann::json::error_handler_t::replace);
1061f52c03c1SCarson Labrado                 entry->sendEvent(strMsg);
106296330b99SSunitha Harish                 eventId++; // increament the eventId
106396330b99SSunitha Harish             }
106496330b99SSunitha Harish             else
106596330b99SSunitha Harish             {
106696330b99SSunitha Harish                 BMCWEB_LOG_INFO << "Not subscribed to this resource";
106796330b99SSunitha Harish             }
106896330b99SSunitha Harish         }
106996330b99SSunitha Harish     }
10705738de59SAsmitha Karunanithi     void sendBroadcastMsg(const std::string& broadcastMsg)
10715738de59SAsmitha Karunanithi     {
10725738de59SAsmitha Karunanithi         for (const auto& it : this->subscriptionsMap)
10735738de59SAsmitha Karunanithi         {
10745738de59SAsmitha Karunanithi             std::shared_ptr<Subscription> entry = it.second;
10755738de59SAsmitha Karunanithi             nlohmann::json msgJson = {
10767c8c4058STejas Patil                 {"Timestamp", crow::utility::getDateTimeOffsetNow().first},
10775738de59SAsmitha Karunanithi                 {"OriginOfCondition", "/ibm/v1/HMC/BroadcastService"},
10785738de59SAsmitha Karunanithi                 {"Name", "Broadcast Message"},
10795738de59SAsmitha Karunanithi                 {"Message", broadcastMsg}};
1080f52c03c1SCarson Labrado 
1081f52c03c1SCarson Labrado             std::string strMsg = msgJson.dump(
1082f52c03c1SCarson Labrado                 2, ' ', true, nlohmann::json::error_handler_t::replace);
1083f52c03c1SCarson Labrado             entry->sendEvent(strMsg);
10845738de59SAsmitha Karunanithi         }
10855738de59SAsmitha Karunanithi     }
108696330b99SSunitha Harish 
10877f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
10882558979cSP Dheeraj Srujan Kumar 
10892558979cSP Dheeraj Srujan Kumar     void resetRedfishFilePosition()
10907f4eb588SAppaRao Puli     {
10912558979cSP Dheeraj Srujan Kumar         // Control would be here when Redfish file is created.
10922558979cSP Dheeraj Srujan Kumar         // Reset File Position as new file is created
10932558979cSP Dheeraj Srujan Kumar         redfishLogFilePosition = 0;
10942558979cSP Dheeraj Srujan Kumar     }
10952558979cSP Dheeraj Srujan Kumar 
10962558979cSP Dheeraj Srujan Kumar     void cacheRedfishLogFile()
10972558979cSP Dheeraj Srujan Kumar     {
10982558979cSP Dheeraj Srujan Kumar         // Open the redfish file and read till the last record.
10992558979cSP Dheeraj Srujan Kumar 
11007f4eb588SAppaRao Puli         std::ifstream logStream(redfishEventLogFile);
11017f4eb588SAppaRao Puli         if (!logStream.good())
11027f4eb588SAppaRao Puli         {
11037f4eb588SAppaRao Puli             BMCWEB_LOG_ERROR << " Redfish log file open failed \n";
11047f4eb588SAppaRao Puli             return;
11057f4eb588SAppaRao Puli         }
11067f4eb588SAppaRao Puli         std::string logEntry;
11077f4eb588SAppaRao Puli         while (std::getline(logStream, logEntry))
11087f4eb588SAppaRao Puli         {
11092558979cSP Dheeraj Srujan Kumar             redfishLogFilePosition = logStream.tellg();
11107f4eb588SAppaRao Puli         }
11112558979cSP Dheeraj Srujan Kumar 
11122558979cSP Dheeraj Srujan Kumar         BMCWEB_LOG_DEBUG << "Next Log Position : " << redfishLogFilePosition;
11137f4eb588SAppaRao Puli     }
11147f4eb588SAppaRao Puli 
11157f4eb588SAppaRao Puli     void readEventLogsFromFile()
11167f4eb588SAppaRao Puli     {
11177f4eb588SAppaRao Puli         std::ifstream logStream(redfishEventLogFile);
11187f4eb588SAppaRao Puli         if (!logStream.good())
11197f4eb588SAppaRao Puli         {
11207f4eb588SAppaRao Puli             BMCWEB_LOG_ERROR << " Redfish log file open failed";
11217f4eb588SAppaRao Puli             return;
11227f4eb588SAppaRao Puli         }
11237f4eb588SAppaRao Puli 
11247f4eb588SAppaRao Puli         std::vector<EventLogObjectsType> eventRecords;
11257f4eb588SAppaRao Puli 
11267f4eb588SAppaRao Puli         std::string logEntry;
11272558979cSP Dheeraj Srujan Kumar 
11282558979cSP Dheeraj Srujan Kumar         // Get the read pointer to the next log to be read.
11292558979cSP Dheeraj Srujan Kumar         logStream.seekg(redfishLogFilePosition);
11302558979cSP Dheeraj Srujan Kumar 
11317f4eb588SAppaRao Puli         while (std::getline(logStream, logEntry))
11327f4eb588SAppaRao Puli         {
11332558979cSP Dheeraj Srujan Kumar             // Update Pointer position
11342558979cSP Dheeraj Srujan Kumar             redfishLogFilePosition = logStream.tellg();
11352558979cSP Dheeraj Srujan Kumar 
11362558979cSP Dheeraj Srujan Kumar             std::string idStr;
11372558979cSP Dheeraj Srujan Kumar             if (!event_log::getUniqueEntryID(logEntry, idStr))
11387f4eb588SAppaRao Puli             {
11397f4eb588SAppaRao Puli                 continue;
11407f4eb588SAppaRao Puli             }
11417f4eb588SAppaRao Puli 
1142e662eae8SEd Tanous             if (!serviceEnabled || noOfEventLogSubscribers == 0)
11437f4eb588SAppaRao Puli             {
11442558979cSP Dheeraj Srujan Kumar                 // If Service is not enabled, no need to compute
11452558979cSP Dheeraj Srujan Kumar                 // the remaining items below.
11462558979cSP Dheeraj Srujan Kumar                 // But, Loop must continue to keep track of Timestamp
11477f4eb588SAppaRao Puli                 continue;
11487f4eb588SAppaRao Puli             }
11497f4eb588SAppaRao Puli 
11507f4eb588SAppaRao Puli             std::string timestamp;
11517f4eb588SAppaRao Puli             std::string messageID;
11525e715de6SAppaRao Puli             std::vector<std::string> messageArgs;
11537f4eb588SAppaRao Puli             if (event_log::getEventLogParams(logEntry, timestamp, messageID,
11547f4eb588SAppaRao Puli                                              messageArgs) != 0)
11557f4eb588SAppaRao Puli             {
11567f4eb588SAppaRao Puli                 BMCWEB_LOG_DEBUG << "Read eventLog entry params failed";
11577f4eb588SAppaRao Puli                 continue;
11587f4eb588SAppaRao Puli             }
11597f4eb588SAppaRao Puli 
11607f4eb588SAppaRao Puli             std::string registryName;
11617f4eb588SAppaRao Puli             std::string messageKey;
11627f4eb588SAppaRao Puli             event_log::getRegistryAndMessageKey(messageID, registryName,
11637f4eb588SAppaRao Puli                                                 messageKey);
11647f4eb588SAppaRao Puli             if (registryName.empty() || messageKey.empty())
11657f4eb588SAppaRao Puli             {
11667f4eb588SAppaRao Puli                 continue;
11677f4eb588SAppaRao Puli             }
11687f4eb588SAppaRao Puli 
11697f4eb588SAppaRao Puli             eventRecords.emplace_back(idStr, timestamp, messageID, registryName,
11707f4eb588SAppaRao Puli                                       messageKey, messageArgs);
11717f4eb588SAppaRao Puli         }
11727f4eb588SAppaRao Puli 
1173e662eae8SEd Tanous         if (!serviceEnabled || noOfEventLogSubscribers == 0)
11742558979cSP Dheeraj Srujan Kumar         {
11752558979cSP Dheeraj Srujan Kumar             BMCWEB_LOG_DEBUG << "EventService disabled or no Subscriptions.";
11762558979cSP Dheeraj Srujan Kumar             return;
11772558979cSP Dheeraj Srujan Kumar         }
11782558979cSP Dheeraj Srujan Kumar 
11792558979cSP Dheeraj Srujan Kumar         if (eventRecords.empty())
11802558979cSP Dheeraj Srujan Kumar         {
11812558979cSP Dheeraj Srujan Kumar             // No Records to send
11822558979cSP Dheeraj Srujan Kumar             BMCWEB_LOG_DEBUG << "No log entries available to be transferred.";
11832558979cSP Dheeraj Srujan Kumar             return;
11842558979cSP Dheeraj Srujan Kumar         }
11852558979cSP Dheeraj Srujan Kumar 
11867f4eb588SAppaRao Puli         for (const auto& it : this->subscriptionsMap)
11877f4eb588SAppaRao Puli         {
11887f4eb588SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
11897f4eb588SAppaRao Puli             if (entry->eventFormatType == "Event")
11907f4eb588SAppaRao Puli             {
11917f4eb588SAppaRao Puli                 entry->filterAndSendEventLogs(eventRecords);
11927f4eb588SAppaRao Puli             }
11937f4eb588SAppaRao Puli         }
11947f4eb588SAppaRao Puli     }
11957f4eb588SAppaRao Puli 
11967f4eb588SAppaRao Puli     static void watchRedfishEventLogFile()
11977f4eb588SAppaRao Puli     {
11986a9f85f9SAppaRao Puli         if (!inotifyConn)
11997f4eb588SAppaRao Puli         {
12007f4eb588SAppaRao Puli             return;
12017f4eb588SAppaRao Puli         }
12027f4eb588SAppaRao Puli 
12037f4eb588SAppaRao Puli         static std::array<char, 1024> readBuffer;
12047f4eb588SAppaRao Puli 
1205002d39b4SEd Tanous         inotifyConn->async_read_some(boost::asio::buffer(readBuffer),
12067f4eb588SAppaRao Puli                                      [&](const boost::system::error_code& ec,
12077f4eb588SAppaRao Puli                                          const std::size_t& bytesTransferred) {
12087f4eb588SAppaRao Puli             if (ec)
12097f4eb588SAppaRao Puli             {
12107f4eb588SAppaRao Puli                 BMCWEB_LOG_ERROR << "Callback Error: " << ec.message();
12117f4eb588SAppaRao Puli                 return;
12127f4eb588SAppaRao Puli             }
12137f4eb588SAppaRao Puli             std::size_t index = 0;
1214b792cc56SAppaRao Puli             while ((index + iEventSize) <= bytesTransferred)
12157f4eb588SAppaRao Puli             {
1216d3a9e084SEd Tanous                 struct inotify_event event
1217d3a9e084SEd Tanous                 {};
1218b792cc56SAppaRao Puli                 std::memcpy(&event, &readBuffer[index], iEventSize);
1219b792cc56SAppaRao Puli                 if (event.wd == dirWatchDesc)
1220b792cc56SAppaRao Puli                 {
1221b792cc56SAppaRao Puli                     if ((event.len == 0) ||
1222b792cc56SAppaRao Puli                         (index + iEventSize + event.len > bytesTransferred))
1223b792cc56SAppaRao Puli                     {
1224b792cc56SAppaRao Puli                         index += (iEventSize + event.len);
1225b792cc56SAppaRao Puli                         continue;
1226b792cc56SAppaRao Puli                     }
1227b792cc56SAppaRao Puli 
12284f568f74SJiaqing Zhao                     std::string fileName(&readBuffer[index + iEventSize]);
12294f568f74SJiaqing Zhao                     if (fileName != "redfish")
1230b792cc56SAppaRao Puli                     {
1231b792cc56SAppaRao Puli                         index += (iEventSize + event.len);
1232b792cc56SAppaRao Puli                         continue;
1233b792cc56SAppaRao Puli                     }
1234b792cc56SAppaRao Puli 
1235b792cc56SAppaRao Puli                     BMCWEB_LOG_DEBUG
1236b792cc56SAppaRao Puli                         << "Redfish log file created/deleted. event.name: "
1237b792cc56SAppaRao Puli                         << fileName;
1238b792cc56SAppaRao Puli                     if (event.mask == IN_CREATE)
1239b792cc56SAppaRao Puli                     {
1240b792cc56SAppaRao Puli                         if (fileWatchDesc != -1)
1241b792cc56SAppaRao Puli                         {
1242b792cc56SAppaRao Puli                             BMCWEB_LOG_DEBUG
1243016761afSAppaRao Puli                                 << "Remove and Add inotify watcher on "
1244016761afSAppaRao Puli                                    "redfish event log file";
1245016761afSAppaRao Puli                             // Remove existing inotify watcher and add
1246016761afSAppaRao Puli                             // with new redfish event log file.
1247016761afSAppaRao Puli                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1248016761afSAppaRao Puli                             fileWatchDesc = -1;
1249b792cc56SAppaRao Puli                         }
1250b792cc56SAppaRao Puli 
1251b792cc56SAppaRao Puli                         fileWatchDesc = inotify_add_watch(
1252b792cc56SAppaRao Puli                             inotifyFd, redfishEventLogFile, IN_MODIFY);
1253b792cc56SAppaRao Puli                         if (fileWatchDesc == -1)
1254b792cc56SAppaRao Puli                         {
1255002d39b4SEd Tanous                             BMCWEB_LOG_ERROR << "inotify_add_watch failed for "
1256b792cc56SAppaRao Puli                                                 "redfish log file.";
1257b792cc56SAppaRao Puli                             return;
1258b792cc56SAppaRao Puli                         }
1259b792cc56SAppaRao Puli 
1260b792cc56SAppaRao Puli                         EventServiceManager::getInstance()
12612558979cSP Dheeraj Srujan Kumar                             .resetRedfishFilePosition();
1262b792cc56SAppaRao Puli                         EventServiceManager::getInstance()
1263b792cc56SAppaRao Puli                             .readEventLogsFromFile();
1264b792cc56SAppaRao Puli                     }
1265b792cc56SAppaRao Puli                     else if ((event.mask == IN_DELETE) ||
1266b792cc56SAppaRao Puli                              (event.mask == IN_MOVED_TO))
1267b792cc56SAppaRao Puli                     {
1268b792cc56SAppaRao Puli                         if (fileWatchDesc != -1)
1269b792cc56SAppaRao Puli                         {
1270b792cc56SAppaRao Puli                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1271b792cc56SAppaRao Puli                             fileWatchDesc = -1;
1272b792cc56SAppaRao Puli                         }
1273b792cc56SAppaRao Puli                     }
1274b792cc56SAppaRao Puli                 }
1275b792cc56SAppaRao Puli                 else if (event.wd == fileWatchDesc)
1276b792cc56SAppaRao Puli                 {
1277b792cc56SAppaRao Puli                     if (event.mask == IN_MODIFY)
12787f4eb588SAppaRao Puli                     {
12797f4eb588SAppaRao Puli                         EventServiceManager::getInstance()
12807f4eb588SAppaRao Puli                             .readEventLogsFromFile();
12817f4eb588SAppaRao Puli                     }
1282b792cc56SAppaRao Puli                 }
1283b792cc56SAppaRao Puli                 index += (iEventSize + event.len);
12847f4eb588SAppaRao Puli             }
12857f4eb588SAppaRao Puli 
12867f4eb588SAppaRao Puli             watchRedfishEventLogFile();
12877f4eb588SAppaRao Puli         });
12887f4eb588SAppaRao Puli     }
12897f4eb588SAppaRao Puli 
12907f4eb588SAppaRao Puli     static int startEventLogMonitor(boost::asio::io_context& ioc)
12917f4eb588SAppaRao Puli     {
129223a21a1cSEd Tanous         inotifyConn.emplace(ioc);
1293b792cc56SAppaRao Puli         inotifyFd = inotify_init1(IN_NONBLOCK);
1294b792cc56SAppaRao Puli         if (inotifyFd == -1)
12957f4eb588SAppaRao Puli         {
12967f4eb588SAppaRao Puli             BMCWEB_LOG_ERROR << "inotify_init1 failed.";
12977f4eb588SAppaRao Puli             return -1;
12987f4eb588SAppaRao Puli         }
1299b792cc56SAppaRao Puli 
1300b792cc56SAppaRao Puli         // Add watch on directory to handle redfish event log file
1301b792cc56SAppaRao Puli         // create/delete.
1302b792cc56SAppaRao Puli         dirWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogDir,
1303b792cc56SAppaRao Puli                                          IN_CREATE | IN_MOVED_TO | IN_DELETE);
1304b792cc56SAppaRao Puli         if (dirWatchDesc == -1)
13057f4eb588SAppaRao Puli         {
13067f4eb588SAppaRao Puli             BMCWEB_LOG_ERROR
1307b792cc56SAppaRao Puli                 << "inotify_add_watch failed for event log directory.";
13087f4eb588SAppaRao Puli             return -1;
13097f4eb588SAppaRao Puli         }
13107f4eb588SAppaRao Puli 
1311b792cc56SAppaRao Puli         // Watch redfish event log file for modifications.
1312b792cc56SAppaRao Puli         fileWatchDesc =
1313b792cc56SAppaRao Puli             inotify_add_watch(inotifyFd, redfishEventLogFile, IN_MODIFY);
1314b792cc56SAppaRao Puli         if (fileWatchDesc == -1)
1315b792cc56SAppaRao Puli         {
1316b792cc56SAppaRao Puli             BMCWEB_LOG_ERROR
1317b792cc56SAppaRao Puli                 << "inotify_add_watch failed for redfish log file.";
1318b792cc56SAppaRao Puli             // Don't return error if file not exist.
1319b792cc56SAppaRao Puli             // Watch on directory will handle create/delete of file.
1320b792cc56SAppaRao Puli         }
1321b792cc56SAppaRao Puli 
13227f4eb588SAppaRao Puli         // monitor redfish event log file
1323b792cc56SAppaRao Puli         inotifyConn->assign(inotifyFd);
13247f4eb588SAppaRao Puli         watchRedfishEventLogFile();
13257f4eb588SAppaRao Puli 
13267f4eb588SAppaRao Puli         return 0;
13277f4eb588SAppaRao Puli     }
13287f4eb588SAppaRao Puli 
13297f4eb588SAppaRao Puli #endif
133056d2396dSEd Tanous     static void getReadingsForReport(sdbusplus::message::message& msg)
1331156d6b00SAppaRao Puli     {
133256d2396dSEd Tanous         if (msg.is_method_error())
133356d2396dSEd Tanous         {
133456d2396dSEd Tanous             BMCWEB_LOG_ERROR << "TelemetryMonitor Signal error";
133556d2396dSEd Tanous             return;
133656d2396dSEd Tanous         }
133756d2396dSEd Tanous 
1338c0353249SWludzik, Jozef         sdbusplus::message::object_path path(msg.get_path());
1339c0353249SWludzik, Jozef         std::string id = path.filename();
1340c0353249SWludzik, Jozef         if (id.empty())
1341156d6b00SAppaRao Puli         {
1342c0353249SWludzik, Jozef             BMCWEB_LOG_ERROR << "Failed to get Id from path";
1343156d6b00SAppaRao Puli             return;
1344156d6b00SAppaRao Puli         }
1345156d6b00SAppaRao Puli 
1346c0353249SWludzik, Jozef         std::string interface;
1347b9d36b47SEd Tanous         dbus::utility::DBusPropertiesMap props;
1348c0353249SWludzik, Jozef         std::vector<std::string> invalidProps;
1349c0353249SWludzik, Jozef         msg.read(interface, props, invalidProps);
1350c0353249SWludzik, Jozef 
1351c0353249SWludzik, Jozef         auto found =
1352c0353249SWludzik, Jozef             std::find_if(props.begin(), props.end(),
1353c0353249SWludzik, Jozef                          [](const auto& x) { return x.first == "Readings"; });
1354c0353249SWludzik, Jozef         if (found == props.end())
1355156d6b00SAppaRao Puli         {
1356c0353249SWludzik, Jozef             BMCWEB_LOG_INFO << "Failed to get Readings from Report properties";
1357156d6b00SAppaRao Puli             return;
1358156d6b00SAppaRao Puli         }
1359156d6b00SAppaRao Puli 
13601e1e598dSJonathan Doman         const telemetry::TimestampReadings* readings =
13611e1e598dSJonathan Doman             std::get_if<telemetry::TimestampReadings>(&found->second);
1362e662eae8SEd Tanous         if (readings == nullptr)
13631e1e598dSJonathan Doman         {
13641e1e598dSJonathan Doman             BMCWEB_LOG_INFO << "Failed to get Readings from Report properties";
13651e1e598dSJonathan Doman             return;
13661e1e598dSJonathan Doman         }
13671e1e598dSJonathan Doman 
1368156d6b00SAppaRao Puli         for (const auto& it :
1369156d6b00SAppaRao Puli              EventServiceManager::getInstance().subscriptionsMap)
1370156d6b00SAppaRao Puli         {
1371e05aec50SEd Tanous             Subscription& entry = *it.second;
1372c0353249SWludzik, Jozef             if (entry.eventFormatType == metricReportFormatType)
1373156d6b00SAppaRao Puli             {
13741e1e598dSJonathan Doman                 entry.filterAndSendReports(id, *readings);
1375156d6b00SAppaRao Puli             }
1376156d6b00SAppaRao Puli         }
1377156d6b00SAppaRao Puli     }
1378156d6b00SAppaRao Puli 
1379156d6b00SAppaRao Puli     void unregisterMetricReportSignal()
1380156d6b00SAppaRao Puli     {
13817d1cc387SAppaRao Puli         if (matchTelemetryMonitor)
13827d1cc387SAppaRao Puli         {
1383156d6b00SAppaRao Puli             BMCWEB_LOG_DEBUG << "Metrics report signal - Unregister";
1384156d6b00SAppaRao Puli             matchTelemetryMonitor.reset();
1385156d6b00SAppaRao Puli             matchTelemetryMonitor = nullptr;
1386156d6b00SAppaRao Puli         }
13877d1cc387SAppaRao Puli     }
1388156d6b00SAppaRao Puli 
1389156d6b00SAppaRao Puli     void registerMetricReportSignal()
1390156d6b00SAppaRao Puli     {
13917d1cc387SAppaRao Puli         if (!serviceEnabled || matchTelemetryMonitor)
1392156d6b00SAppaRao Puli         {
13937d1cc387SAppaRao Puli             BMCWEB_LOG_DEBUG << "Not registering metric report signal.";
1394156d6b00SAppaRao Puli             return;
1395156d6b00SAppaRao Puli         }
1396156d6b00SAppaRao Puli 
1397156d6b00SAppaRao Puli         BMCWEB_LOG_DEBUG << "Metrics report signal - Register";
1398c0353249SWludzik, Jozef         std::string matchStr = "type='signal',member='PropertiesChanged',"
1399c0353249SWludzik, Jozef                                "interface='org.freedesktop.DBus.Properties',"
1400c0353249SWludzik, Jozef                                "arg0=xyz.openbmc_project.Telemetry.Report";
1401156d6b00SAppaRao Puli 
1402156d6b00SAppaRao Puli         matchTelemetryMonitor = std::make_shared<sdbusplus::bus::match::match>(
140356d2396dSEd Tanous             *crow::connections::systemBus, matchStr, getReadingsForReport);
1404156d6b00SAppaRao Puli     }
140523a21a1cSEd Tanous };
1406b52664e2SAppaRao Puli 
1407b52664e2SAppaRao Puli } // namespace redfish
1408