xref: /openbmc/bmcweb/features/redfish/include/event_service_manager.hpp (revision c035324925c9c09855e0717ef7af5caae3c296ff)
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
17*c0353249SWludzik, 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>
271214b7e7SGunnar Mills #include <error_messages.hpp>
2828afb49cSJunLin Chen #include <event_service_store.hpp>
291214b7e7SGunnar Mills #include <http_client.hpp>
3028afb49cSJunLin Chen #include <persistent_data.hpp>
31fc76b8acSEd Tanous #include <random.hpp>
324bbf237fSAppaRao Puli #include <server_sent_events.hpp>
331214b7e7SGunnar Mills #include <utils/json_utils.hpp>
341214b7e7SGunnar Mills 
35b52664e2SAppaRao Puli #include <cstdlib>
36b52664e2SAppaRao Puli #include <ctime>
371bf712bcSAyushi Smriti #include <fstream>
38b52664e2SAppaRao Puli #include <memory>
39b52664e2SAppaRao Puli #include <variant>
40b52664e2SAppaRao Puli 
41b52664e2SAppaRao Puli namespace redfish
42b52664e2SAppaRao Puli {
43156d6b00SAppaRao Puli 
44156d6b00SAppaRao Puli using ReadingsObjType =
4593f5d7c7SWludzik, Jozef     std::vector<std::tuple<std::string, std::string, double, int32_t>>;
46156d6b00SAppaRao Puli 
47156d6b00SAppaRao Puli static constexpr const char* eventFormatType = "Event";
48156d6b00SAppaRao Puli static constexpr const char* metricReportFormatType = "MetricReport";
49156d6b00SAppaRao Puli 
501bf712bcSAyushi Smriti static constexpr const char* eventServiceFile =
511bf712bcSAyushi Smriti     "/var/lib/bmcweb/eventservice_config.json";
521bf712bcSAyushi Smriti 
537f4eb588SAppaRao Puli namespace message_registries
547f4eb588SAppaRao Puli {
55b304bd79SP Dheeraj Srujan Kumar inline boost::beast::span<const MessageEntry>
56b304bd79SP Dheeraj Srujan Kumar     getRegistryFromPrefix(const std::string& registryName)
57b304bd79SP Dheeraj Srujan Kumar {
58b304bd79SP Dheeraj Srujan Kumar     if (task_event::header.registryPrefix == registryName)
59b304bd79SP Dheeraj Srujan Kumar     {
60b304bd79SP Dheeraj Srujan Kumar         return boost::beast::span<const MessageEntry>(task_event::registry);
61b304bd79SP Dheeraj Srujan Kumar     }
62b304bd79SP Dheeraj Srujan Kumar     if (openbmc::header.registryPrefix == registryName)
63b304bd79SP Dheeraj Srujan Kumar     {
64b304bd79SP Dheeraj Srujan Kumar         return boost::beast::span<const MessageEntry>(openbmc::registry);
65b304bd79SP Dheeraj Srujan Kumar     }
66b304bd79SP Dheeraj Srujan Kumar     if (base::header.registryPrefix == registryName)
67b304bd79SP Dheeraj Srujan Kumar     {
68b304bd79SP Dheeraj Srujan Kumar         return boost::beast::span<const MessageEntry>(base::registry);
69b304bd79SP Dheeraj Srujan Kumar     }
70b304bd79SP Dheeraj Srujan Kumar     return boost::beast::span<const MessageEntry>(openbmc::registry);
71b304bd79SP Dheeraj Srujan Kumar }
724642bf8fSGeorge Liu } // namespace message_registries
73b304bd79SP Dheeraj Srujan Kumar 
744642bf8fSGeorge Liu #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
754642bf8fSGeorge Liu static std::optional<boost::asio::posix::stream_descriptor> inotifyConn;
764642bf8fSGeorge Liu static constexpr const char* redfishEventLogDir = "/var/log";
774642bf8fSGeorge Liu static constexpr const char* redfishEventLogFile = "/var/log/redfish";
784642bf8fSGeorge Liu static constexpr const size_t iEventSize = sizeof(inotify_event);
794642bf8fSGeorge Liu static int inotifyFd = -1;
804642bf8fSGeorge Liu static int dirWatchDesc = -1;
814642bf8fSGeorge Liu static int fileWatchDesc = -1;
824642bf8fSGeorge Liu 
834642bf8fSGeorge Liu // <ID, timestamp, RedfishLogId, registryPrefix, MessageId, MessageArgs>
844642bf8fSGeorge Liu using EventLogObjectsType =
854642bf8fSGeorge Liu     std::tuple<std::string, std::string, std::string, std::string, std::string,
864642bf8fSGeorge Liu                std::vector<std::string>>;
874642bf8fSGeorge Liu 
884642bf8fSGeorge Liu namespace message_registries
894642bf8fSGeorge Liu {
907f4eb588SAppaRao Puli static const Message*
917f4eb588SAppaRao Puli     getMsgFromRegistry(const std::string& messageKey,
927f4eb588SAppaRao Puli                        const boost::beast::span<const MessageEntry>& registry)
937f4eb588SAppaRao Puli {
947f4eb588SAppaRao Puli     boost::beast::span<const MessageEntry>::const_iterator messageIt =
957f4eb588SAppaRao Puli         std::find_if(registry.cbegin(), registry.cend(),
967f4eb588SAppaRao Puli                      [&messageKey](const MessageEntry& messageEntry) {
977f4eb588SAppaRao Puli                          return !messageKey.compare(messageEntry.first);
987f4eb588SAppaRao Puli                      });
997f4eb588SAppaRao Puli     if (messageIt != registry.cend())
1007f4eb588SAppaRao Puli     {
1017f4eb588SAppaRao Puli         return &messageIt->second;
1027f4eb588SAppaRao Puli     }
1037f4eb588SAppaRao Puli 
1047f4eb588SAppaRao Puli     return nullptr;
1057f4eb588SAppaRao Puli }
1067f4eb588SAppaRao Puli 
1077f4eb588SAppaRao Puli static const Message* formatMessage(const std::string_view& messageID)
1087f4eb588SAppaRao Puli {
1097f4eb588SAppaRao Puli     // Redfish MessageIds are in the form
1107f4eb588SAppaRao Puli     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
1117f4eb588SAppaRao Puli     // the right Message
1127f4eb588SAppaRao Puli     std::vector<std::string> fields;
1137f4eb588SAppaRao Puli     fields.reserve(4);
1147f4eb588SAppaRao Puli     boost::split(fields, messageID, boost::is_any_of("."));
1157f4eb588SAppaRao Puli     if (fields.size() != 4)
1167f4eb588SAppaRao Puli     {
1177f4eb588SAppaRao Puli         return nullptr;
1187f4eb588SAppaRao Puli     }
1197f4eb588SAppaRao Puli     std::string& registryName = fields[0];
1207f4eb588SAppaRao Puli     std::string& messageKey = fields[3];
1217f4eb588SAppaRao Puli 
1227f4eb588SAppaRao Puli     // Find the right registry and check it for the MessageKey
123b304bd79SP Dheeraj Srujan Kumar     return getMsgFromRegistry(messageKey, getRegistryFromPrefix(registryName));
1247f4eb588SAppaRao Puli }
1257f4eb588SAppaRao Puli } // namespace message_registries
1267f4eb588SAppaRao Puli 
1277f4eb588SAppaRao Puli namespace event_log
1287f4eb588SAppaRao Puli {
12923a21a1cSEd Tanous inline bool getUniqueEntryID(const std::string& logEntry, std::string& entryID,
1307f4eb588SAppaRao Puli                              const bool firstEntry = true)
1317f4eb588SAppaRao Puli {
1327f4eb588SAppaRao Puli     static time_t prevTs = 0;
1337f4eb588SAppaRao Puli     static int index = 0;
1347f4eb588SAppaRao Puli     if (firstEntry)
1357f4eb588SAppaRao Puli     {
1367f4eb588SAppaRao Puli         prevTs = 0;
1377f4eb588SAppaRao Puli     }
1387f4eb588SAppaRao Puli 
1397f4eb588SAppaRao Puli     // Get the entry timestamp
1407f4eb588SAppaRao Puli     std::time_t curTs = 0;
1417f4eb588SAppaRao Puli     std::tm timeStruct = {};
1427f4eb588SAppaRao Puli     std::istringstream entryStream(logEntry);
1437f4eb588SAppaRao Puli     if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1447f4eb588SAppaRao Puli     {
1457f4eb588SAppaRao Puli         curTs = std::mktime(&timeStruct);
1467f4eb588SAppaRao Puli         if (curTs == -1)
1477f4eb588SAppaRao Puli         {
1487f4eb588SAppaRao Puli             return false;
1497f4eb588SAppaRao Puli         }
1507f4eb588SAppaRao Puli     }
1517f4eb588SAppaRao Puli     // If the timestamp isn't unique, increment the index
1527f4eb588SAppaRao Puli     index = (curTs == prevTs) ? index + 1 : 0;
1537f4eb588SAppaRao Puli 
1547f4eb588SAppaRao Puli     // Save the timestamp
1557f4eb588SAppaRao Puli     prevTs = curTs;
1567f4eb588SAppaRao Puli 
1577f4eb588SAppaRao Puli     entryID = std::to_string(curTs);
1587f4eb588SAppaRao Puli     if (index > 0)
1597f4eb588SAppaRao Puli     {
1607f4eb588SAppaRao Puli         entryID += "_" + std::to_string(index);
1617f4eb588SAppaRao Puli     }
1627f4eb588SAppaRao Puli     return true;
1637f4eb588SAppaRao Puli }
1647f4eb588SAppaRao Puli 
16523a21a1cSEd Tanous inline int getEventLogParams(const std::string& logEntry,
16623a21a1cSEd Tanous                              std::string& timestamp, std::string& messageID,
1675e715de6SAppaRao Puli                              std::vector<std::string>& messageArgs)
1687f4eb588SAppaRao Puli {
1697f4eb588SAppaRao Puli     // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
1707f4eb588SAppaRao Puli     // First get the Timestamp
171f23b7296SEd Tanous     size_t space = logEntry.find_first_of(' ');
1727f4eb588SAppaRao Puli     if (space == std::string::npos)
1737f4eb588SAppaRao Puli     {
1747f4eb588SAppaRao Puli         return -EINVAL;
1757f4eb588SAppaRao Puli     }
1767f4eb588SAppaRao Puli     timestamp = logEntry.substr(0, space);
1777f4eb588SAppaRao Puli     // Then get the log contents
178f23b7296SEd Tanous     size_t entryStart = logEntry.find_first_not_of(' ', space);
1797f4eb588SAppaRao Puli     if (entryStart == std::string::npos)
1807f4eb588SAppaRao Puli     {
1817f4eb588SAppaRao Puli         return -EINVAL;
1827f4eb588SAppaRao Puli     }
1837f4eb588SAppaRao Puli     std::string_view entry(logEntry);
1847f4eb588SAppaRao Puli     entry.remove_prefix(entryStart);
1857f4eb588SAppaRao Puli     // Use split to separate the entry into its fields
1867f4eb588SAppaRao Puli     std::vector<std::string> logEntryFields;
1877f4eb588SAppaRao Puli     boost::split(logEntryFields, entry, boost::is_any_of(","),
1887f4eb588SAppaRao Puli                  boost::token_compress_on);
1897f4eb588SAppaRao Puli     // We need at least a MessageId to be valid
1907f4eb588SAppaRao Puli     if (logEntryFields.size() < 1)
1917f4eb588SAppaRao Puli     {
1927f4eb588SAppaRao Puli         return -EINVAL;
1937f4eb588SAppaRao Puli     }
1947f4eb588SAppaRao Puli     messageID = logEntryFields[0];
1957f4eb588SAppaRao Puli 
1967f4eb588SAppaRao Puli     // Get the MessageArgs from the log if there are any
1977f4eb588SAppaRao Puli     if (logEntryFields.size() > 1)
1987f4eb588SAppaRao Puli     {
1997f4eb588SAppaRao Puli         std::string& messageArgsStart = logEntryFields[1];
2007f4eb588SAppaRao Puli         // If the first string is empty, assume there are no MessageArgs
2017f4eb588SAppaRao Puli         if (!messageArgsStart.empty())
2027f4eb588SAppaRao Puli         {
2035e715de6SAppaRao Puli             messageArgs.assign(logEntryFields.begin() + 1,
2045e715de6SAppaRao Puli                                logEntryFields.end());
2057f4eb588SAppaRao Puli         }
2067f4eb588SAppaRao Puli     }
2077f4eb588SAppaRao Puli 
2087f4eb588SAppaRao Puli     return 0;
2097f4eb588SAppaRao Puli }
2107f4eb588SAppaRao Puli 
21123a21a1cSEd Tanous inline void getRegistryAndMessageKey(const std::string& messageID,
2127f4eb588SAppaRao Puli                                      std::string& registryName,
2137f4eb588SAppaRao Puli                                      std::string& messageKey)
2147f4eb588SAppaRao Puli {
2157f4eb588SAppaRao Puli     // Redfish MessageIds are in the form
2167f4eb588SAppaRao Puli     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
2177f4eb588SAppaRao Puli     // the right Message
2187f4eb588SAppaRao Puli     std::vector<std::string> fields;
2197f4eb588SAppaRao Puli     fields.reserve(4);
2207f4eb588SAppaRao Puli     boost::split(fields, messageID, boost::is_any_of("."));
2217f4eb588SAppaRao Puli     if (fields.size() == 4)
2227f4eb588SAppaRao Puli     {
2237f4eb588SAppaRao Puli         registryName = fields[0];
2247f4eb588SAppaRao Puli         messageKey = fields[3];
2257f4eb588SAppaRao Puli     }
2267f4eb588SAppaRao Puli }
2277f4eb588SAppaRao Puli 
22823a21a1cSEd Tanous inline int formatEventLogEntry(const std::string& logEntryID,
2297f4eb588SAppaRao Puli                                const std::string& messageID,
2305e715de6SAppaRao Puli                                const std::vector<std::string>& messageArgs,
23123a21a1cSEd Tanous                                std::string timestamp,
232b5a76932SEd Tanous                                const std::string& customText,
2337f4eb588SAppaRao Puli                                nlohmann::json& logEntryJson)
2347f4eb588SAppaRao Puli {
2357f4eb588SAppaRao Puli     // Get the Message from the MessageRegistry
2367f4eb588SAppaRao Puli     const message_registries::Message* message =
2377f4eb588SAppaRao Puli         message_registries::formatMessage(messageID);
2387f4eb588SAppaRao Puli 
2397f4eb588SAppaRao Puli     std::string msg;
2407f4eb588SAppaRao Puli     std::string severity;
2417f4eb588SAppaRao Puli     if (message != nullptr)
2427f4eb588SAppaRao Puli     {
2437f4eb588SAppaRao Puli         msg = message->message;
2447f4eb588SAppaRao Puli         severity = message->severity;
2457f4eb588SAppaRao Puli     }
2467f4eb588SAppaRao Puli 
2477f4eb588SAppaRao Puli     // Fill the MessageArgs into the Message
2487f4eb588SAppaRao Puli     int i = 0;
2497f4eb588SAppaRao Puli     for (const std::string& messageArg : messageArgs)
2507f4eb588SAppaRao Puli     {
2517f4eb588SAppaRao Puli         std::string argStr = "%" + std::to_string(++i);
2527f4eb588SAppaRao Puli         size_t argPos = msg.find(argStr);
2537f4eb588SAppaRao Puli         if (argPos != std::string::npos)
2547f4eb588SAppaRao Puli         {
2557f4eb588SAppaRao Puli             msg.replace(argPos, argStr.length(), messageArg);
2567f4eb588SAppaRao Puli         }
2577f4eb588SAppaRao Puli     }
2587f4eb588SAppaRao Puli 
2597f4eb588SAppaRao Puli     // Get the Created time from the timestamp. The log timestamp is in
2607f4eb588SAppaRao Puli     // RFC3339 format which matches the Redfish format except for the
2617f4eb588SAppaRao Puli     // fractional seconds between the '.' and the '+', so just remove them.
262f23b7296SEd Tanous     std::size_t dot = timestamp.find_first_of('.');
263f23b7296SEd Tanous     std::size_t plus = timestamp.find_first_of('+');
2647f4eb588SAppaRao Puli     if (dot != std::string::npos && plus != std::string::npos)
2657f4eb588SAppaRao Puli     {
2667f4eb588SAppaRao Puli         timestamp.erase(dot, plus - dot);
2677f4eb588SAppaRao Puli     }
2687f4eb588SAppaRao Puli 
2697f4eb588SAppaRao Puli     // Fill in the log entry with the gathered data
2707f4eb588SAppaRao Puli     logEntryJson = {{"EventId", logEntryID},
2717f4eb588SAppaRao Puli                     {"EventType", "Event"},
2727f4eb588SAppaRao Puli                     {"Severity", std::move(severity)},
2737f4eb588SAppaRao Puli                     {"Message", std::move(msg)},
274f23b7296SEd Tanous                     {"MessageId", messageID},
275f23b7296SEd Tanous                     {"MessageArgs", messageArgs},
2767f4eb588SAppaRao Puli                     {"EventTimestamp", std::move(timestamp)},
2777f4eb588SAppaRao Puli                     {"Context", customText}};
2787f4eb588SAppaRao Puli     return 0;
2797f4eb588SAppaRao Puli }
2807f4eb588SAppaRao Puli 
2817f4eb588SAppaRao Puli } // namespace event_log
2827f4eb588SAppaRao Puli #endif
2837f4eb588SAppaRao Puli 
28423a21a1cSEd Tanous inline bool isFilterQuerySpecialChar(char c)
28507941a88SAyushi Smriti {
28607941a88SAyushi Smriti     switch (c)
28707941a88SAyushi Smriti     {
28807941a88SAyushi Smriti         case '(':
28907941a88SAyushi Smriti         case ')':
29007941a88SAyushi Smriti         case '\'':
29107941a88SAyushi Smriti             return true;
29207941a88SAyushi Smriti         default:
29307941a88SAyushi Smriti             return false;
29407941a88SAyushi Smriti     }
29507941a88SAyushi Smriti }
29607941a88SAyushi Smriti 
29723a21a1cSEd Tanous inline bool
29823a21a1cSEd Tanous     readSSEQueryParams(std::string sseFilter, std::string& formatType,
29907941a88SAyushi Smriti                        std::vector<std::string>& messageIds,
30007941a88SAyushi Smriti                        std::vector<std::string>& registryPrefixes,
301144b6318SAppaRao Puli                        std::vector<std::string>& metricReportDefinitions)
30207941a88SAyushi Smriti {
30307941a88SAyushi Smriti     sseFilter.erase(std::remove_if(sseFilter.begin(), sseFilter.end(),
30407941a88SAyushi Smriti                                    isFilterQuerySpecialChar),
30507941a88SAyushi Smriti                     sseFilter.end());
30607941a88SAyushi Smriti 
30707941a88SAyushi Smriti     std::vector<std::string> result;
30807941a88SAyushi Smriti     boost::split(result, sseFilter, boost::is_any_of(" "),
30907941a88SAyushi Smriti                  boost::token_compress_on);
31007941a88SAyushi Smriti 
31107941a88SAyushi Smriti     BMCWEB_LOG_DEBUG << "No of tokens in SEE query: " << result.size();
31207941a88SAyushi Smriti 
31307941a88SAyushi Smriti     constexpr uint8_t divisor = 4;
31407941a88SAyushi Smriti     constexpr uint8_t minTokenSize = 3;
31507941a88SAyushi Smriti     if (result.size() % divisor != minTokenSize)
31607941a88SAyushi Smriti     {
31707941a88SAyushi Smriti         BMCWEB_LOG_ERROR << "Invalid SSE filter specified.";
31807941a88SAyushi Smriti         return false;
31907941a88SAyushi Smriti     }
32007941a88SAyushi Smriti 
32107941a88SAyushi Smriti     for (std::size_t i = 0; i < result.size(); i += divisor)
32207941a88SAyushi Smriti     {
32307941a88SAyushi Smriti         std::string& key = result[i];
32407941a88SAyushi Smriti         std::string& op = result[i + 1];
32507941a88SAyushi Smriti         std::string& value = result[i + 2];
32607941a88SAyushi Smriti 
32707941a88SAyushi Smriti         if ((i + minTokenSize) < result.size())
32807941a88SAyushi Smriti         {
3294e0453b1SGunnar Mills             std::string& separator = result[i + minTokenSize];
33007941a88SAyushi Smriti             // SSE supports only "or" and "and" in query params.
3314e0453b1SGunnar Mills             if ((separator != "or") && (separator != "and"))
33207941a88SAyushi Smriti             {
33307941a88SAyushi Smriti                 BMCWEB_LOG_ERROR
33407941a88SAyushi Smriti                     << "Invalid group operator in SSE query parameters";
33507941a88SAyushi Smriti                 return false;
33607941a88SAyushi Smriti             }
33707941a88SAyushi Smriti         }
33807941a88SAyushi Smriti 
33907941a88SAyushi Smriti         // SSE supports only "eq" as per spec.
34007941a88SAyushi Smriti         if (op != "eq")
34107941a88SAyushi Smriti         {
34207941a88SAyushi Smriti             BMCWEB_LOG_ERROR
34307941a88SAyushi Smriti                 << "Invalid assignment operator in SSE query parameters";
34407941a88SAyushi Smriti             return false;
34507941a88SAyushi Smriti         }
34607941a88SAyushi Smriti 
34707941a88SAyushi Smriti         BMCWEB_LOG_DEBUG << key << " : " << value;
34807941a88SAyushi Smriti         if (key == "EventFormatType")
34907941a88SAyushi Smriti         {
35007941a88SAyushi Smriti             formatType = value;
35107941a88SAyushi Smriti         }
35207941a88SAyushi Smriti         else if (key == "MessageId")
35307941a88SAyushi Smriti         {
35407941a88SAyushi Smriti             messageIds.push_back(value);
35507941a88SAyushi Smriti         }
35607941a88SAyushi Smriti         else if (key == "RegistryPrefix")
35707941a88SAyushi Smriti         {
35807941a88SAyushi Smriti             registryPrefixes.push_back(value);
35907941a88SAyushi Smriti         }
36007941a88SAyushi Smriti         else if (key == "MetricReportDefinition")
36107941a88SAyushi Smriti         {
36207941a88SAyushi Smriti             metricReportDefinitions.push_back(value);
36307941a88SAyushi Smriti         }
36407941a88SAyushi Smriti         else
36507941a88SAyushi Smriti         {
36607941a88SAyushi Smriti             BMCWEB_LOG_ERROR << "Invalid property(" << key
36707941a88SAyushi Smriti                              << ")in SSE filter query.";
36807941a88SAyushi Smriti             return false;
36907941a88SAyushi Smriti         }
37007941a88SAyushi Smriti     }
37107941a88SAyushi Smriti     return true;
37207941a88SAyushi Smriti }
37307941a88SAyushi Smriti 
37428afb49cSJunLin Chen class Subscription : public persistent_data::UserSubscription
375b52664e2SAppaRao Puli {
376b52664e2SAppaRao Puli   public:
377b52664e2SAppaRao Puli     Subscription(const Subscription&) = delete;
378b52664e2SAppaRao Puli     Subscription& operator=(const Subscription&) = delete;
379b52664e2SAppaRao Puli     Subscription(Subscription&&) = delete;
380b52664e2SAppaRao Puli     Subscription& operator=(Subscription&&) = delete;
381b52664e2SAppaRao Puli 
382b52664e2SAppaRao Puli     Subscription(const std::string& inHost, const std::string& inPort,
383b52664e2SAppaRao Puli                  const std::string& inPath, const std::string& inUriProto) :
3840b4bdd93SAppaRao Puli         eventSeqNum(1),
3850b4bdd93SAppaRao Puli         host(inHost), port(inPort), path(inPath), uriProto(inUriProto)
386b52664e2SAppaRao Puli     {
3877adb85acSSunitha Harish         // Subscription constructor
388b52664e2SAppaRao Puli     }
3894bbf237fSAppaRao Puli 
39023e64207SEd Tanous     Subscription(const std::shared_ptr<boost::beast::tcp_stream>& adaptor) :
3914bbf237fSAppaRao Puli         eventSeqNum(1)
3924bbf237fSAppaRao Puli     {
3934bbf237fSAppaRao Puli         sseConn = std::make_shared<crow::ServerSentEvents>(adaptor);
3944bbf237fSAppaRao Puli     }
3954bbf237fSAppaRao Puli 
3969f616dd1SEd Tanous     ~Subscription() = default;
397b52664e2SAppaRao Puli 
398b52664e2SAppaRao Puli     void sendEvent(const std::string& msg)
399b52664e2SAppaRao Puli     {
4007adb85acSSunitha Harish         if (conn == nullptr)
4014bbf237fSAppaRao Puli         {
4027adb85acSSunitha Harish             // create the HttpClient connection
4037adb85acSSunitha Harish             conn = std::make_shared<crow::HttpClient>(
4047adb85acSSunitha Harish                 crow::connections::systemBus->get_io_context(), id, host, port,
4057adb85acSSunitha Harish                 path, httpHeaders);
406b52664e2SAppaRao Puli         }
407b52664e2SAppaRao Puli 
4087adb85acSSunitha Harish         conn->sendData(msg);
4097adb85acSSunitha Harish         eventSeqNum++;
4107adb85acSSunitha Harish 
4114bbf237fSAppaRao Puli         if (sseConn != nullptr)
4124bbf237fSAppaRao Puli         {
4134bbf237fSAppaRao Puli             sseConn->sendData(eventSeqNum, msg);
4144bbf237fSAppaRao Puli         }
4154bbf237fSAppaRao Puli     }
4164bbf237fSAppaRao Puli 
4170b4bdd93SAppaRao Puli     void sendTestEventLog()
4180b4bdd93SAppaRao Puli     {
4190b4bdd93SAppaRao Puli         nlohmann::json logEntryArray;
4200b4bdd93SAppaRao Puli         logEntryArray.push_back({});
4210b4bdd93SAppaRao Puli         nlohmann::json& logEntryJson = logEntryArray.back();
4220b4bdd93SAppaRao Puli 
4237c8c4058STejas Patil         logEntryJson = {
4247c8c4058STejas Patil             {"EventId", "TestID"},
4250b4bdd93SAppaRao Puli             {"EventType", "Event"},
4260b4bdd93SAppaRao Puli             {"Severity", "OK"},
4270b4bdd93SAppaRao Puli             {"Message", "Generated test event"},
4284a0bf539SManojkiran Eda             {"MessageId", "OpenBMC.0.2.TestEventLog"},
4290b4bdd93SAppaRao Puli             {"MessageArgs", nlohmann::json::array()},
4307c8c4058STejas Patil             {"EventTimestamp", crow::utility::getDateTimeOffsetNow().first},
4310b4bdd93SAppaRao Puli             {"Context", customText}};
4320b4bdd93SAppaRao Puli 
4330b4bdd93SAppaRao Puli         nlohmann::json msg = {{"@odata.type", "#Event.v1_4_0.Event"},
4340b4bdd93SAppaRao Puli                               {"Id", std::to_string(eventSeqNum)},
4350b4bdd93SAppaRao Puli                               {"Name", "Event Log"},
4360b4bdd93SAppaRao Puli                               {"Events", logEntryArray}};
4370b4bdd93SAppaRao Puli 
43871f52d96SEd Tanous         this->sendEvent(
43971f52d96SEd Tanous             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace));
4400b4bdd93SAppaRao Puli     }
4410b4bdd93SAppaRao Puli 
4427f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
4437f4eb588SAppaRao Puli     void filterAndSendEventLogs(
4447f4eb588SAppaRao Puli         const std::vector<EventLogObjectsType>& eventRecords)
4457f4eb588SAppaRao Puli     {
4467f4eb588SAppaRao Puli         nlohmann::json logEntryArray;
4477f4eb588SAppaRao Puli         for (const EventLogObjectsType& logEntry : eventRecords)
4487f4eb588SAppaRao Puli         {
4497f4eb588SAppaRao Puli             const std::string& idStr = std::get<0>(logEntry);
4507f4eb588SAppaRao Puli             const std::string& timestamp = std::get<1>(logEntry);
4517f4eb588SAppaRao Puli             const std::string& messageID = std::get<2>(logEntry);
4527f4eb588SAppaRao Puli             const std::string& registryName = std::get<3>(logEntry);
4537f4eb588SAppaRao Puli             const std::string& messageKey = std::get<4>(logEntry);
4545e715de6SAppaRao Puli             const std::vector<std::string>& messageArgs = std::get<5>(logEntry);
4557f4eb588SAppaRao Puli 
4567f4eb588SAppaRao Puli             // If registryPrefixes list is empty, don't filter events
4577f4eb588SAppaRao Puli             // send everything.
4587f4eb588SAppaRao Puli             if (registryPrefixes.size())
4597f4eb588SAppaRao Puli             {
4607f4eb588SAppaRao Puli                 auto obj = std::find(registryPrefixes.begin(),
4617f4eb588SAppaRao Puli                                      registryPrefixes.end(), registryName);
4627f4eb588SAppaRao Puli                 if (obj == registryPrefixes.end())
4637f4eb588SAppaRao Puli                 {
4647f4eb588SAppaRao Puli                     continue;
4657f4eb588SAppaRao Puli                 }
4667f4eb588SAppaRao Puli             }
4677f4eb588SAppaRao Puli 
4687f4eb588SAppaRao Puli             // If registryMsgIds list is empty, don't filter events
4697f4eb588SAppaRao Puli             // send everything.
4707f4eb588SAppaRao Puli             if (registryMsgIds.size())
4717f4eb588SAppaRao Puli             {
4727f4eb588SAppaRao Puli                 auto obj = std::find(registryMsgIds.begin(),
4737f4eb588SAppaRao Puli                                      registryMsgIds.end(), messageKey);
4747f4eb588SAppaRao Puli                 if (obj == registryMsgIds.end())
4757f4eb588SAppaRao Puli                 {
4767f4eb588SAppaRao Puli                     continue;
4777f4eb588SAppaRao Puli                 }
4787f4eb588SAppaRao Puli             }
4797f4eb588SAppaRao Puli 
4807f4eb588SAppaRao Puli             logEntryArray.push_back({});
4817f4eb588SAppaRao Puli             nlohmann::json& bmcLogEntry = logEntryArray.back();
4827f4eb588SAppaRao Puli             if (event_log::formatEventLogEntry(idStr, messageID, messageArgs,
4837f4eb588SAppaRao Puli                                                timestamp, customText,
4847f4eb588SAppaRao Puli                                                bmcLogEntry) != 0)
4857f4eb588SAppaRao Puli             {
4867f4eb588SAppaRao Puli                 BMCWEB_LOG_DEBUG << "Read eventLog entry failed";
4877f4eb588SAppaRao Puli                 continue;
4887f4eb588SAppaRao Puli             }
4897f4eb588SAppaRao Puli         }
4907f4eb588SAppaRao Puli 
4917f4eb588SAppaRao Puli         if (logEntryArray.size() < 1)
4927f4eb588SAppaRao Puli         {
4937f4eb588SAppaRao Puli             BMCWEB_LOG_DEBUG << "No log entries available to be transferred.";
4947f4eb588SAppaRao Puli             return;
4957f4eb588SAppaRao Puli         }
4967f4eb588SAppaRao Puli 
4977f4eb588SAppaRao Puli         nlohmann::json msg = {{"@odata.type", "#Event.v1_4_0.Event"},
4987f4eb588SAppaRao Puli                               {"Id", std::to_string(eventSeqNum)},
4997f4eb588SAppaRao Puli                               {"Name", "Event Log"},
5007f4eb588SAppaRao Puli                               {"Events", logEntryArray}};
5017f4eb588SAppaRao Puli 
50271f52d96SEd Tanous         this->sendEvent(
50371f52d96SEd Tanous             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace));
5047f4eb588SAppaRao Puli     }
5057f4eb588SAppaRao Puli #endif
5067f4eb588SAppaRao Puli 
507*c0353249SWludzik, Jozef     void filterAndSendReports(
508*c0353249SWludzik, Jozef         const std::string& id,
509*c0353249SWludzik, Jozef         const std::variant<telemetry::TimestampReadings>& var)
510156d6b00SAppaRao Puli     {
511*c0353249SWludzik, Jozef         std::string mrdUri = telemetry::metricReportDefinitionUri + ("/" + id);
512156d6b00SAppaRao Puli 
513156d6b00SAppaRao Puli         // Empty list means no filter. Send everything.
514156d6b00SAppaRao Puli         if (metricReportDefinitions.size())
515156d6b00SAppaRao Puli         {
516156d6b00SAppaRao Puli             if (std::find(metricReportDefinitions.begin(),
517156d6b00SAppaRao Puli                           metricReportDefinitions.end(),
518*c0353249SWludzik, Jozef                           mrdUri) == metricReportDefinitions.end())
519156d6b00SAppaRao Puli             {
520156d6b00SAppaRao Puli                 return;
521156d6b00SAppaRao Puli             }
522156d6b00SAppaRao Puli         }
523156d6b00SAppaRao Puli 
524*c0353249SWludzik, Jozef         nlohmann::json msg;
525*c0353249SWludzik, Jozef         if (!telemetry::fillReport(msg, id, var))
526156d6b00SAppaRao Puli         {
527*c0353249SWludzik, Jozef             BMCWEB_LOG_ERROR << "Failed to fill the MetricReport for DBus "
528*c0353249SWludzik, Jozef                                 "Report with id "
529*c0353249SWludzik, Jozef                              << id;
530*c0353249SWludzik, Jozef             return;
531156d6b00SAppaRao Puli         }
532156d6b00SAppaRao Puli 
53371f52d96SEd Tanous         this->sendEvent(
53471f52d96SEd Tanous             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace));
535156d6b00SAppaRao Puli     }
536156d6b00SAppaRao Puli 
537fe44eb0bSAyushi Smriti     void updateRetryConfig(const uint32_t retryAttempts,
538fe44eb0bSAyushi Smriti                            const uint32_t retryTimeoutInterval)
539fe44eb0bSAyushi Smriti     {
54062de0c68SAppaRao Puli         if (conn != nullptr)
54162de0c68SAppaRao Puli         {
542fe44eb0bSAyushi Smriti             conn->setRetryConfig(retryAttempts, retryTimeoutInterval);
543fe44eb0bSAyushi Smriti         }
54462de0c68SAppaRao Puli     }
545fe44eb0bSAyushi Smriti 
546fe44eb0bSAyushi Smriti     void updateRetryPolicy()
547fe44eb0bSAyushi Smriti     {
54862de0c68SAppaRao Puli         if (conn != nullptr)
54962de0c68SAppaRao Puli         {
550fe44eb0bSAyushi Smriti             conn->setRetryPolicy(retryPolicy);
551fe44eb0bSAyushi Smriti         }
55262de0c68SAppaRao Puli     }
553fe44eb0bSAyushi Smriti 
55496330b99SSunitha Harish     uint64_t getEventSeqNum()
55596330b99SSunitha Harish     {
55696330b99SSunitha Harish         return eventSeqNum;
55796330b99SSunitha Harish     }
55896330b99SSunitha Harish 
559b52664e2SAppaRao Puli   private:
5600b4bdd93SAppaRao Puli     uint64_t eventSeqNum;
561b52664e2SAppaRao Puli     std::string host;
562b52664e2SAppaRao Puli     std::string port;
563b52664e2SAppaRao Puli     std::string path;
564b52664e2SAppaRao Puli     std::string uriProto;
5654bbf237fSAppaRao Puli     std::shared_ptr<crow::HttpClient> conn = nullptr;
5664bbf237fSAppaRao Puli     std::shared_ptr<crow::ServerSentEvents> sseConn = nullptr;
567b52664e2SAppaRao Puli };
568b52664e2SAppaRao Puli 
569b52664e2SAppaRao Puli class EventServiceManager
570b52664e2SAppaRao Puli {
571b52664e2SAppaRao Puli   private:
5727d1cc387SAppaRao Puli     bool serviceEnabled;
5737d1cc387SAppaRao Puli     uint32_t retryAttempts;
5747d1cc387SAppaRao Puli     uint32_t retryTimeoutInterval;
5757d1cc387SAppaRao Puli 
5769f616dd1SEd Tanous     EventServiceManager()
577b52664e2SAppaRao Puli     {
5781bf712bcSAyushi Smriti         // Load config from persist store.
5791bf712bcSAyushi Smriti         initConfig();
580b52664e2SAppaRao Puli     }
581b52664e2SAppaRao Puli 
5827f4eb588SAppaRao Puli     std::string lastEventTStr;
5839f616dd1SEd Tanous     size_t noOfEventLogSubscribers{0};
5849f616dd1SEd Tanous     size_t noOfMetricReportSubscribers{0};
585156d6b00SAppaRao Puli     std::shared_ptr<sdbusplus::bus::match::match> matchTelemetryMonitor;
586b52664e2SAppaRao Puli     boost::container::flat_map<std::string, std::shared_ptr<Subscription>>
587b52664e2SAppaRao Puli         subscriptionsMap;
588b52664e2SAppaRao Puli 
5899f616dd1SEd Tanous     uint64_t eventId{1};
59096330b99SSunitha Harish 
591b52664e2SAppaRao Puli   public:
5929f616dd1SEd Tanous     EventServiceManager(const EventServiceManager&) = delete;
5939f616dd1SEd Tanous     EventServiceManager& operator=(const EventServiceManager&) = delete;
5949f616dd1SEd Tanous     EventServiceManager(EventServiceManager&&) = delete;
5959f616dd1SEd Tanous     EventServiceManager& operator=(EventServiceManager&&) = delete;
5969f616dd1SEd Tanous 
597b52664e2SAppaRao Puli     static EventServiceManager& getInstance()
598b52664e2SAppaRao Puli     {
599b52664e2SAppaRao Puli         static EventServiceManager handler;
600b52664e2SAppaRao Puli         return handler;
601b52664e2SAppaRao Puli     }
602b52664e2SAppaRao Puli 
6031bf712bcSAyushi Smriti     void initConfig()
6041bf712bcSAyushi Smriti     {
60528afb49cSJunLin Chen         loadOldBehavior();
6061bf712bcSAyushi Smriti 
60728afb49cSJunLin Chen         persistent_data::EventServiceConfig eventServiceConfig =
60828afb49cSJunLin Chen             persistent_data::EventServiceStore::getInstance()
60928afb49cSJunLin Chen                 .getEventServiceConfig();
6101bf712bcSAyushi Smriti 
61128afb49cSJunLin Chen         serviceEnabled = eventServiceConfig.enabled;
61228afb49cSJunLin Chen         retryAttempts = eventServiceConfig.retryAttempts;
61328afb49cSJunLin Chen         retryTimeoutInterval = eventServiceConfig.retryTimeoutInterval;
6141bf712bcSAyushi Smriti 
61528afb49cSJunLin Chen         for (const auto& it : persistent_data::EventServiceStore::getInstance()
61628afb49cSJunLin Chen                                   .subscriptionsConfigMap)
6171bf712bcSAyushi Smriti         {
61828afb49cSJunLin Chen             std::shared_ptr<persistent_data::UserSubscription> newSub =
61928afb49cSJunLin Chen                 it.second;
6204bbf237fSAppaRao Puli 
6211bf712bcSAyushi Smriti             std::string host;
6221bf712bcSAyushi Smriti             std::string urlProto;
6231bf712bcSAyushi Smriti             std::string port;
6241bf712bcSAyushi Smriti             std::string path;
62528afb49cSJunLin Chen             bool status = validateAndSplitUrl(newSub->destinationUrl, urlProto,
62628afb49cSJunLin Chen                                               host, port, path);
6271bf712bcSAyushi Smriti 
6281bf712bcSAyushi Smriti             if (!status)
6291bf712bcSAyushi Smriti             {
6301bf712bcSAyushi Smriti                 BMCWEB_LOG_ERROR
6311bf712bcSAyushi Smriti                     << "Failed to validate and split destination url";
6321bf712bcSAyushi Smriti                 continue;
6331bf712bcSAyushi Smriti             }
6341bf712bcSAyushi Smriti             std::shared_ptr<Subscription> subValue =
6351bf712bcSAyushi Smriti                 std::make_shared<Subscription>(host, port, path, urlProto);
6361bf712bcSAyushi Smriti 
63728afb49cSJunLin Chen             subValue->id = newSub->id;
63828afb49cSJunLin Chen             subValue->destinationUrl = newSub->destinationUrl;
63928afb49cSJunLin Chen             subValue->protocol = newSub->protocol;
64028afb49cSJunLin Chen             subValue->retryPolicy = newSub->retryPolicy;
64128afb49cSJunLin Chen             subValue->customText = newSub->customText;
64228afb49cSJunLin Chen             subValue->eventFormatType = newSub->eventFormatType;
64328afb49cSJunLin Chen             subValue->subscriptionType = newSub->subscriptionType;
64428afb49cSJunLin Chen             subValue->registryMsgIds = newSub->registryMsgIds;
64528afb49cSJunLin Chen             subValue->registryPrefixes = newSub->registryPrefixes;
64628afb49cSJunLin Chen             subValue->resourceTypes = newSub->resourceTypes;
64728afb49cSJunLin Chen             subValue->httpHeaders = newSub->httpHeaders;
64828afb49cSJunLin Chen             subValue->metricReportDefinitions = newSub->metricReportDefinitions;
6491bf712bcSAyushi Smriti 
65028afb49cSJunLin Chen             if (subValue->id.empty())
6511bf712bcSAyushi Smriti             {
6521bf712bcSAyushi Smriti                 BMCWEB_LOG_ERROR << "Failed to add subscription";
6531bf712bcSAyushi Smriti             }
65428afb49cSJunLin Chen             subscriptionsMap.insert(std::pair(subValue->id, subValue));
65528afb49cSJunLin Chen 
65628afb49cSJunLin Chen             updateNoOfSubscribersCount();
65728afb49cSJunLin Chen 
65828afb49cSJunLin Chen #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
65928afb49cSJunLin Chen             if (lastEventTStr.empty())
66028afb49cSJunLin Chen             {
66128afb49cSJunLin Chen                 cacheLastEventTimestamp();
66228afb49cSJunLin Chen             }
66328afb49cSJunLin Chen #endif
66428afb49cSJunLin Chen             // Update retry configuration.
66528afb49cSJunLin Chen             subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
66628afb49cSJunLin Chen             subValue->updateRetryPolicy();
6671bf712bcSAyushi Smriti         }
6681bf712bcSAyushi Smriti         return;
6691bf712bcSAyushi Smriti     }
6701bf712bcSAyushi Smriti 
67128afb49cSJunLin Chen     void loadOldBehavior()
672b52664e2SAppaRao Puli     {
67328afb49cSJunLin Chen         std::ifstream eventConfigFile(eventServiceFile);
67428afb49cSJunLin Chen         if (!eventConfigFile.good())
6751bf712bcSAyushi Smriti         {
67628afb49cSJunLin Chen             BMCWEB_LOG_DEBUG << "Old eventService config not exist";
67728afb49cSJunLin Chen             return;
67828afb49cSJunLin Chen         }
67928afb49cSJunLin Chen         auto jsonData = nlohmann::json::parse(eventConfigFile, nullptr, false);
68028afb49cSJunLin Chen         if (jsonData.is_discarded())
6814bbf237fSAppaRao Puli         {
68228afb49cSJunLin Chen             BMCWEB_LOG_ERROR << "Old eventService config parse error.";
68328afb49cSJunLin Chen             return;
68428afb49cSJunLin Chen         }
68528afb49cSJunLin Chen 
68628afb49cSJunLin Chen         for (const auto& item : jsonData.items())
68728afb49cSJunLin Chen         {
68828afb49cSJunLin Chen             if (item.key() == "Configuration")
68928afb49cSJunLin Chen             {
69028afb49cSJunLin Chen                 persistent_data::EventServiceStore::getInstance()
69128afb49cSJunLin Chen                     .getEventServiceConfig()
69228afb49cSJunLin Chen                     .fromJson(item.value());
69328afb49cSJunLin Chen             }
69428afb49cSJunLin Chen             else if (item.key() == "Subscriptions")
69528afb49cSJunLin Chen             {
69628afb49cSJunLin Chen                 for (const auto& elem : item.value())
69728afb49cSJunLin Chen                 {
69828afb49cSJunLin Chen                     std::shared_ptr<persistent_data::UserSubscription>
69928afb49cSJunLin Chen                         newSubscription =
70028afb49cSJunLin Chen                             persistent_data::UserSubscription::fromJson(elem,
70128afb49cSJunLin Chen                                                                         true);
70228afb49cSJunLin Chen                     if (newSubscription == nullptr)
70328afb49cSJunLin Chen                     {
70428afb49cSJunLin Chen                         BMCWEB_LOG_ERROR << "Problem reading subscription "
70528afb49cSJunLin Chen                                             "from old persistent store";
7064bbf237fSAppaRao Puli                         continue;
7074bbf237fSAppaRao Puli                     }
7081bf712bcSAyushi Smriti 
70928afb49cSJunLin Chen                     std::uniform_int_distribution<uint32_t> dist(0);
71028afb49cSJunLin Chen                     bmcweb::OpenSSLGenerator gen;
7111bf712bcSAyushi Smriti 
71228afb49cSJunLin Chen                     std::string id;
7131bf712bcSAyushi Smriti 
71428afb49cSJunLin Chen                     int retry = 3;
71528afb49cSJunLin Chen                     while (retry)
7161bf712bcSAyushi Smriti                     {
71728afb49cSJunLin Chen                         id = std::to_string(dist(gen));
71828afb49cSJunLin Chen                         if (gen.error())
7197d1cc387SAppaRao Puli                         {
72028afb49cSJunLin Chen                             retry = 0;
72128afb49cSJunLin Chen                             break;
72228afb49cSJunLin Chen                         }
72328afb49cSJunLin Chen                         newSubscription->id = id;
72428afb49cSJunLin Chen                         auto inserted =
72528afb49cSJunLin Chen                             persistent_data::EventServiceStore::getInstance()
72628afb49cSJunLin Chen                                 .subscriptionsConfigMap.insert(
72728afb49cSJunLin Chen                                     std::pair(id, newSubscription));
72828afb49cSJunLin Chen                         if (inserted.second)
72928afb49cSJunLin Chen                         {
73028afb49cSJunLin Chen                             break;
73128afb49cSJunLin Chen                         }
73228afb49cSJunLin Chen                         --retry;
7337d1cc387SAppaRao Puli                     }
7347d1cc387SAppaRao Puli 
73528afb49cSJunLin Chen                     if (retry <= 0)
73628afb49cSJunLin Chen                     {
73728afb49cSJunLin Chen                         BMCWEB_LOG_ERROR
73828afb49cSJunLin Chen                             << "Failed to generate random number from old "
73928afb49cSJunLin Chen                                "persistent store";
74028afb49cSJunLin Chen                         continue;
74128afb49cSJunLin Chen                     }
74228afb49cSJunLin Chen                 }
74328afb49cSJunLin Chen             }
74428afb49cSJunLin Chen 
74528afb49cSJunLin Chen             persistent_data::getConfig().writeData();
74628afb49cSJunLin Chen             std::remove(eventServiceFile);
74728afb49cSJunLin Chen             BMCWEB_LOG_DEBUG << "Remove old eventservice config";
74828afb49cSJunLin Chen         }
74928afb49cSJunLin Chen     }
75028afb49cSJunLin Chen 
75128afb49cSJunLin Chen     void updateSubscriptionData()
75228afb49cSJunLin Chen     {
75328afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
75428afb49cSJunLin Chen             .eventServiceConfig.enabled = serviceEnabled;
75528afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
75628afb49cSJunLin Chen             .eventServiceConfig.retryAttempts = retryAttempts;
75728afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
75828afb49cSJunLin Chen             .eventServiceConfig.retryTimeoutInterval = retryTimeoutInterval;
75928afb49cSJunLin Chen 
76028afb49cSJunLin Chen         persistent_data::getConfig().writeData();
76128afb49cSJunLin Chen     }
76228afb49cSJunLin Chen 
76328afb49cSJunLin Chen     void setEventServiceConfig(const persistent_data::EventServiceConfig& cfg)
7647d1cc387SAppaRao Puli     {
7657d1cc387SAppaRao Puli         bool updateConfig = false;
766fe44eb0bSAyushi Smriti         bool updateRetryCfg = false;
7677d1cc387SAppaRao Puli 
76828afb49cSJunLin Chen         if (serviceEnabled != cfg.enabled)
7697d1cc387SAppaRao Puli         {
77028afb49cSJunLin Chen             serviceEnabled = cfg.enabled;
7717d1cc387SAppaRao Puli             if (serviceEnabled && noOfMetricReportSubscribers)
7727d1cc387SAppaRao Puli             {
7737d1cc387SAppaRao Puli                 registerMetricReportSignal();
7747d1cc387SAppaRao Puli             }
7757d1cc387SAppaRao Puli             else
7767d1cc387SAppaRao Puli             {
7777d1cc387SAppaRao Puli                 unregisterMetricReportSignal();
7787d1cc387SAppaRao Puli             }
7797d1cc387SAppaRao Puli             updateConfig = true;
7807d1cc387SAppaRao Puli         }
7817d1cc387SAppaRao Puli 
78228afb49cSJunLin Chen         if (retryAttempts != cfg.retryAttempts)
7837d1cc387SAppaRao Puli         {
78428afb49cSJunLin Chen             retryAttempts = cfg.retryAttempts;
7857d1cc387SAppaRao Puli             updateConfig = true;
786fe44eb0bSAyushi Smriti             updateRetryCfg = true;
7877d1cc387SAppaRao Puli         }
7887d1cc387SAppaRao Puli 
78928afb49cSJunLin Chen         if (retryTimeoutInterval != cfg.retryTimeoutInterval)
7907d1cc387SAppaRao Puli         {
79128afb49cSJunLin Chen             retryTimeoutInterval = cfg.retryTimeoutInterval;
7927d1cc387SAppaRao Puli             updateConfig = true;
793fe44eb0bSAyushi Smriti             updateRetryCfg = true;
7947d1cc387SAppaRao Puli         }
7957d1cc387SAppaRao Puli 
7967d1cc387SAppaRao Puli         if (updateConfig)
7977d1cc387SAppaRao Puli         {
7987d1cc387SAppaRao Puli             updateSubscriptionData();
7997d1cc387SAppaRao Puli         }
800fe44eb0bSAyushi Smriti 
801fe44eb0bSAyushi Smriti         if (updateRetryCfg)
802fe44eb0bSAyushi Smriti         {
803fe44eb0bSAyushi Smriti             // Update the changed retry config to all subscriptions
804fe44eb0bSAyushi Smriti             for (const auto& it :
805fe44eb0bSAyushi Smriti                  EventServiceManager::getInstance().subscriptionsMap)
806fe44eb0bSAyushi Smriti             {
807fe44eb0bSAyushi Smriti                 std::shared_ptr<Subscription> entry = it.second;
808fe44eb0bSAyushi Smriti                 entry->updateRetryConfig(retryAttempts, retryTimeoutInterval);
809fe44eb0bSAyushi Smriti             }
810fe44eb0bSAyushi Smriti         }
8117d1cc387SAppaRao Puli     }
8127d1cc387SAppaRao Puli 
8137d1cc387SAppaRao Puli     void updateNoOfSubscribersCount()
8147d1cc387SAppaRao Puli     {
8157d1cc387SAppaRao Puli         size_t eventLogSubCount = 0;
8167d1cc387SAppaRao Puli         size_t metricReportSubCount = 0;
8177d1cc387SAppaRao Puli         for (const auto& it : subscriptionsMap)
8187d1cc387SAppaRao Puli         {
8197d1cc387SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
8207d1cc387SAppaRao Puli             if (entry->eventFormatType == eventFormatType)
8217d1cc387SAppaRao Puli             {
8227d1cc387SAppaRao Puli                 eventLogSubCount++;
8237d1cc387SAppaRao Puli             }
8247d1cc387SAppaRao Puli             else if (entry->eventFormatType == metricReportFormatType)
8257d1cc387SAppaRao Puli             {
8267d1cc387SAppaRao Puli                 metricReportSubCount++;
8277d1cc387SAppaRao Puli             }
8287d1cc387SAppaRao Puli         }
8297d1cc387SAppaRao Puli 
8307d1cc387SAppaRao Puli         noOfEventLogSubscribers = eventLogSubCount;
8317d1cc387SAppaRao Puli         if (noOfMetricReportSubscribers != metricReportSubCount)
8327d1cc387SAppaRao Puli         {
8337d1cc387SAppaRao Puli             noOfMetricReportSubscribers = metricReportSubCount;
8347d1cc387SAppaRao Puli             if (noOfMetricReportSubscribers)
8357d1cc387SAppaRao Puli             {
8367d1cc387SAppaRao Puli                 registerMetricReportSignal();
8377d1cc387SAppaRao Puli             }
8387d1cc387SAppaRao Puli             else
8397d1cc387SAppaRao Puli             {
8407d1cc387SAppaRao Puli                 unregisterMetricReportSignal();
8417d1cc387SAppaRao Puli             }
8427d1cc387SAppaRao Puli         }
8437d1cc387SAppaRao Puli     }
8447d1cc387SAppaRao Puli 
845b52664e2SAppaRao Puli     std::shared_ptr<Subscription> getSubscription(const std::string& id)
846b52664e2SAppaRao Puli     {
847b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
848b52664e2SAppaRao Puli         if (obj == subscriptionsMap.end())
849b52664e2SAppaRao Puli         {
850b52664e2SAppaRao Puli             BMCWEB_LOG_ERROR << "No subscription exist with ID:" << id;
851b52664e2SAppaRao Puli             return nullptr;
852b52664e2SAppaRao Puli         }
853b52664e2SAppaRao Puli         std::shared_ptr<Subscription> subValue = obj->second;
854b52664e2SAppaRao Puli         return subValue;
855b52664e2SAppaRao Puli     }
856b52664e2SAppaRao Puli 
857b5a76932SEd Tanous     std::string addSubscription(const std::shared_ptr<Subscription>& subValue,
8581bf712bcSAyushi Smriti                                 const bool updateFile = true)
859b52664e2SAppaRao Puli     {
860fc76b8acSEd Tanous 
861fc76b8acSEd Tanous         std::uniform_int_distribution<uint32_t> dist(0);
862fc76b8acSEd Tanous         bmcweb::OpenSSLGenerator gen;
863fc76b8acSEd Tanous 
864b52664e2SAppaRao Puli         std::string id;
865b52664e2SAppaRao Puli 
866b52664e2SAppaRao Puli         int retry = 3;
867b52664e2SAppaRao Puli         while (retry)
868b52664e2SAppaRao Puli         {
869fc76b8acSEd Tanous             id = std::to_string(dist(gen));
870fc76b8acSEd Tanous             if (gen.error())
871fc76b8acSEd Tanous             {
872fc76b8acSEd Tanous                 retry = 0;
873fc76b8acSEd Tanous                 break;
874fc76b8acSEd Tanous             }
875b52664e2SAppaRao Puli             auto inserted = subscriptionsMap.insert(std::pair(id, subValue));
876b52664e2SAppaRao Puli             if (inserted.second)
877b52664e2SAppaRao Puli             {
878b52664e2SAppaRao Puli                 break;
879b52664e2SAppaRao Puli             }
880b52664e2SAppaRao Puli             --retry;
88123a21a1cSEd Tanous         }
882b52664e2SAppaRao Puli 
883b52664e2SAppaRao Puli         if (retry <= 0)
884b52664e2SAppaRao Puli         {
885b52664e2SAppaRao Puli             BMCWEB_LOG_ERROR << "Failed to generate random number";
886abb93cddSEd Tanous             return "";
887b52664e2SAppaRao Puli         }
888b52664e2SAppaRao Puli 
88928afb49cSJunLin Chen         std::shared_ptr<persistent_data::UserSubscription> newSub =
89028afb49cSJunLin Chen             std::make_shared<persistent_data::UserSubscription>();
89128afb49cSJunLin Chen         newSub->id = id;
89228afb49cSJunLin Chen         newSub->destinationUrl = subValue->destinationUrl;
89328afb49cSJunLin Chen         newSub->protocol = subValue->protocol;
89428afb49cSJunLin Chen         newSub->retryPolicy = subValue->retryPolicy;
89528afb49cSJunLin Chen         newSub->customText = subValue->customText;
89628afb49cSJunLin Chen         newSub->eventFormatType = subValue->eventFormatType;
89728afb49cSJunLin Chen         newSub->subscriptionType = subValue->subscriptionType;
89828afb49cSJunLin Chen         newSub->registryMsgIds = subValue->registryMsgIds;
89928afb49cSJunLin Chen         newSub->registryPrefixes = subValue->registryPrefixes;
90028afb49cSJunLin Chen         newSub->resourceTypes = subValue->resourceTypes;
90128afb49cSJunLin Chen         newSub->httpHeaders = subValue->httpHeaders;
90228afb49cSJunLin Chen         newSub->metricReportDefinitions = subValue->metricReportDefinitions;
90328afb49cSJunLin Chen         persistent_data::EventServiceStore::getInstance()
90428afb49cSJunLin Chen             .subscriptionsConfigMap.emplace(newSub->id, newSub);
90528afb49cSJunLin Chen 
9067d1cc387SAppaRao Puli         updateNoOfSubscribersCount();
9071bf712bcSAyushi Smriti 
9081bf712bcSAyushi Smriti         if (updateFile)
9091bf712bcSAyushi Smriti         {
910b52664e2SAppaRao Puli             updateSubscriptionData();
9111bf712bcSAyushi Smriti         }
9127f4eb588SAppaRao Puli 
9137f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
9147f4eb588SAppaRao Puli         if (lastEventTStr.empty())
9157f4eb588SAppaRao Puli         {
9167f4eb588SAppaRao Puli             cacheLastEventTimestamp();
9177f4eb588SAppaRao Puli         }
9187f4eb588SAppaRao Puli #endif
919fe44eb0bSAyushi Smriti         // Update retry configuration.
920fe44eb0bSAyushi Smriti         subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
921fe44eb0bSAyushi Smriti         subValue->updateRetryPolicy();
922fe44eb0bSAyushi Smriti 
923b52664e2SAppaRao Puli         return id;
924b52664e2SAppaRao Puli     }
925b52664e2SAppaRao Puli 
926b52664e2SAppaRao Puli     bool isSubscriptionExist(const std::string& id)
927b52664e2SAppaRao Puli     {
928b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
929b52664e2SAppaRao Puli         if (obj == subscriptionsMap.end())
930b52664e2SAppaRao Puli         {
931b52664e2SAppaRao Puli             return false;
932b52664e2SAppaRao Puli         }
933b52664e2SAppaRao Puli         return true;
934b52664e2SAppaRao Puli     }
935b52664e2SAppaRao Puli 
936b52664e2SAppaRao Puli     void deleteSubscription(const std::string& id)
937b52664e2SAppaRao Puli     {
938b52664e2SAppaRao Puli         auto obj = subscriptionsMap.find(id);
939b52664e2SAppaRao Puli         if (obj != subscriptionsMap.end())
940b52664e2SAppaRao Puli         {
941b52664e2SAppaRao Puli             subscriptionsMap.erase(obj);
94228afb49cSJunLin Chen             auto obj2 = persistent_data::EventServiceStore::getInstance()
94328afb49cSJunLin Chen                             .subscriptionsConfigMap.find(id);
94428afb49cSJunLin Chen             persistent_data::EventServiceStore::getInstance()
94528afb49cSJunLin Chen                 .subscriptionsConfigMap.erase(obj2);
9467d1cc387SAppaRao Puli             updateNoOfSubscribersCount();
947b52664e2SAppaRao Puli             updateSubscriptionData();
948b52664e2SAppaRao Puli         }
949b52664e2SAppaRao Puli     }
950b52664e2SAppaRao Puli 
951b52664e2SAppaRao Puli     size_t getNumberOfSubscriptions()
952b52664e2SAppaRao Puli     {
953b52664e2SAppaRao Puli         return subscriptionsMap.size();
954b52664e2SAppaRao Puli     }
955b52664e2SAppaRao Puli 
956b52664e2SAppaRao Puli     std::vector<std::string> getAllIDs()
957b52664e2SAppaRao Puli     {
958b52664e2SAppaRao Puli         std::vector<std::string> idList;
959b52664e2SAppaRao Puli         for (const auto& it : subscriptionsMap)
960b52664e2SAppaRao Puli         {
961b52664e2SAppaRao Puli             idList.emplace_back(it.first);
962b52664e2SAppaRao Puli         }
963b52664e2SAppaRao Puli         return idList;
964b52664e2SAppaRao Puli     }
965b52664e2SAppaRao Puli 
966b52664e2SAppaRao Puli     bool isDestinationExist(const std::string& destUrl)
967b52664e2SAppaRao Puli     {
968b52664e2SAppaRao Puli         for (const auto& it : subscriptionsMap)
969b52664e2SAppaRao Puli         {
970b52664e2SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
971b52664e2SAppaRao Puli             if (entry->destinationUrl == destUrl)
972b52664e2SAppaRao Puli             {
973b52664e2SAppaRao Puli                 BMCWEB_LOG_ERROR << "Destination exist already" << destUrl;
974b52664e2SAppaRao Puli                 return true;
975b52664e2SAppaRao Puli             }
976b52664e2SAppaRao Puli         }
977b52664e2SAppaRao Puli         return false;
978b52664e2SAppaRao Puli     }
9790b4bdd93SAppaRao Puli 
9800b4bdd93SAppaRao Puli     void sendTestEventLog()
9810b4bdd93SAppaRao Puli     {
9820b4bdd93SAppaRao Puli         for (const auto& it : this->subscriptionsMap)
9830b4bdd93SAppaRao Puli         {
9840b4bdd93SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
9850b4bdd93SAppaRao Puli             entry->sendTestEventLog();
9860b4bdd93SAppaRao Puli         }
9870b4bdd93SAppaRao Puli     }
988e9a14131SAppaRao Puli 
98996330b99SSunitha Harish     void sendEvent(const nlohmann::json& eventMessageIn,
99096330b99SSunitha Harish                    const std::string& origin, const std::string& resType)
99196330b99SSunitha Harish     {
99296330b99SSunitha Harish         nlohmann::json eventRecord = nlohmann::json::array();
99396330b99SSunitha Harish         nlohmann::json eventMessage = eventMessageIn;
99496330b99SSunitha Harish         // MemberId is 0 : since we are sending one event record.
99596330b99SSunitha Harish         uint64_t memberId = 0;
99696330b99SSunitha Harish 
99796330b99SSunitha Harish         nlohmann::json event = {
99896330b99SSunitha Harish             {"EventId", eventId},
99996330b99SSunitha Harish             {"MemberId", memberId},
10007c8c4058STejas Patil             {"EventTimestamp", crow::utility::getDateTimeOffsetNow().first},
100196330b99SSunitha Harish             {"OriginOfCondition", origin}};
100296330b99SSunitha Harish         for (nlohmann::json::iterator it = event.begin(); it != event.end();
100396330b99SSunitha Harish              ++it)
100496330b99SSunitha Harish         {
100596330b99SSunitha Harish             eventMessage[it.key()] = it.value();
100696330b99SSunitha Harish         }
100796330b99SSunitha Harish         eventRecord.push_back(eventMessage);
100896330b99SSunitha Harish 
100996330b99SSunitha Harish         for (const auto& it : this->subscriptionsMap)
101096330b99SSunitha Harish         {
101196330b99SSunitha Harish             std::shared_ptr<Subscription> entry = it.second;
101296330b99SSunitha Harish             bool isSubscribed = false;
101396330b99SSunitha Harish             // Search the resourceTypes list for the subscription.
101496330b99SSunitha Harish             // If resourceTypes list is empty, don't filter events
101596330b99SSunitha Harish             // send everything.
101696330b99SSunitha Harish             if (entry->resourceTypes.size())
101796330b99SSunitha Harish             {
10183174e4dfSEd Tanous                 for (const auto& resource : entry->resourceTypes)
101996330b99SSunitha Harish                 {
102096330b99SSunitha Harish                     if (resType == resource)
102196330b99SSunitha Harish                     {
102296330b99SSunitha Harish                         BMCWEB_LOG_INFO << "ResourceType " << resource
102396330b99SSunitha Harish                                         << " found in the subscribed list";
102496330b99SSunitha Harish                         isSubscribed = true;
102596330b99SSunitha Harish                         break;
102696330b99SSunitha Harish                     }
102796330b99SSunitha Harish                 }
102896330b99SSunitha Harish             }
102996330b99SSunitha Harish             else // resourceTypes list is empty.
103096330b99SSunitha Harish             {
103196330b99SSunitha Harish                 isSubscribed = true;
103296330b99SSunitha Harish             }
103396330b99SSunitha Harish             if (isSubscribed)
103496330b99SSunitha Harish             {
103596330b99SSunitha Harish                 nlohmann::json msgJson = {
103696330b99SSunitha Harish                     {"@odata.type", "#Event.v1_4_0.Event"},
103796330b99SSunitha Harish                     {"Name", "Event Log"},
103896330b99SSunitha Harish                     {"Id", eventId},
103996330b99SSunitha Harish                     {"Events", eventRecord}};
104071f52d96SEd Tanous                 entry->sendEvent(msgJson.dump(
104171f52d96SEd Tanous                     2, ' ', true, nlohmann::json::error_handler_t::replace));
104296330b99SSunitha Harish                 eventId++; // increament the eventId
104396330b99SSunitha Harish             }
104496330b99SSunitha Harish             else
104596330b99SSunitha Harish             {
104696330b99SSunitha Harish                 BMCWEB_LOG_INFO << "Not subscribed to this resource";
104796330b99SSunitha Harish             }
104896330b99SSunitha Harish         }
104996330b99SSunitha Harish     }
10505738de59SAsmitha Karunanithi     void sendBroadcastMsg(const std::string& broadcastMsg)
10515738de59SAsmitha Karunanithi     {
10525738de59SAsmitha Karunanithi         for (const auto& it : this->subscriptionsMap)
10535738de59SAsmitha Karunanithi         {
10545738de59SAsmitha Karunanithi             std::shared_ptr<Subscription> entry = it.second;
10555738de59SAsmitha Karunanithi             nlohmann::json msgJson = {
10567c8c4058STejas Patil                 {"Timestamp", crow::utility::getDateTimeOffsetNow().first},
10575738de59SAsmitha Karunanithi                 {"OriginOfCondition", "/ibm/v1/HMC/BroadcastService"},
10585738de59SAsmitha Karunanithi                 {"Name", "Broadcast Message"},
10595738de59SAsmitha Karunanithi                 {"Message", broadcastMsg}};
106071f52d96SEd Tanous             entry->sendEvent(msgJson.dump(
106171f52d96SEd Tanous                 2, ' ', true, nlohmann::json::error_handler_t::replace));
10625738de59SAsmitha Karunanithi         }
10635738de59SAsmitha Karunanithi     }
106496330b99SSunitha Harish 
10657f4eb588SAppaRao Puli #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
10667f4eb588SAppaRao Puli     void cacheLastEventTimestamp()
10677f4eb588SAppaRao Puli     {
1068016761afSAppaRao Puli         lastEventTStr.clear();
10697f4eb588SAppaRao Puli         std::ifstream logStream(redfishEventLogFile);
10707f4eb588SAppaRao Puli         if (!logStream.good())
10717f4eb588SAppaRao Puli         {
10727f4eb588SAppaRao Puli             BMCWEB_LOG_ERROR << " Redfish log file open failed \n";
10737f4eb588SAppaRao Puli             return;
10747f4eb588SAppaRao Puli         }
10757f4eb588SAppaRao Puli         std::string logEntry;
10767f4eb588SAppaRao Puli         while (std::getline(logStream, logEntry))
10777f4eb588SAppaRao Puli         {
1078f23b7296SEd Tanous             size_t space = logEntry.find_first_of(' ');
10797f4eb588SAppaRao Puli             if (space == std::string::npos)
10807f4eb588SAppaRao Puli             {
10817f4eb588SAppaRao Puli                 // Shouldn't enter here but lets skip it.
10827f4eb588SAppaRao Puli                 BMCWEB_LOG_DEBUG << "Invalid log entry found.";
10837f4eb588SAppaRao Puli                 continue;
10847f4eb588SAppaRao Puli             }
10857f4eb588SAppaRao Puli             lastEventTStr = logEntry.substr(0, space);
10867f4eb588SAppaRao Puli         }
10877f4eb588SAppaRao Puli         BMCWEB_LOG_DEBUG << "Last Event time stamp set: " << lastEventTStr;
10887f4eb588SAppaRao Puli     }
10897f4eb588SAppaRao Puli 
10907f4eb588SAppaRao Puli     void readEventLogsFromFile()
10917f4eb588SAppaRao Puli     {
10927f4eb588SAppaRao Puli         if (!serviceEnabled || !noOfEventLogSubscribers)
10937f4eb588SAppaRao Puli         {
10947f4eb588SAppaRao Puli             BMCWEB_LOG_DEBUG << "EventService disabled or no Subscriptions.";
10957f4eb588SAppaRao Puli             return;
10967f4eb588SAppaRao Puli         }
10977f4eb588SAppaRao Puli         std::ifstream logStream(redfishEventLogFile);
10987f4eb588SAppaRao Puli         if (!logStream.good())
10997f4eb588SAppaRao Puli         {
11007f4eb588SAppaRao Puli             BMCWEB_LOG_ERROR << " Redfish log file open failed";
11017f4eb588SAppaRao Puli             return;
11027f4eb588SAppaRao Puli         }
11037f4eb588SAppaRao Puli 
11047f4eb588SAppaRao Puli         std::vector<EventLogObjectsType> eventRecords;
11057f4eb588SAppaRao Puli 
11067f4eb588SAppaRao Puli         bool startLogCollection = false;
11077f4eb588SAppaRao Puli         bool firstEntry = true;
11087f4eb588SAppaRao Puli 
11097f4eb588SAppaRao Puli         std::string logEntry;
11107f4eb588SAppaRao Puli         while (std::getline(logStream, logEntry))
11117f4eb588SAppaRao Puli         {
1112016761afSAppaRao Puli             if (!startLogCollection && !lastEventTStr.empty())
11137f4eb588SAppaRao Puli             {
11147f4eb588SAppaRao Puli                 if (boost::starts_with(logEntry, lastEventTStr))
11157f4eb588SAppaRao Puli                 {
11167f4eb588SAppaRao Puli                     startLogCollection = true;
11177f4eb588SAppaRao Puli                 }
11187f4eb588SAppaRao Puli                 continue;
11197f4eb588SAppaRao Puli             }
11207f4eb588SAppaRao Puli 
11217f4eb588SAppaRao Puli             std::string idStr;
11227f4eb588SAppaRao Puli             if (!event_log::getUniqueEntryID(logEntry, idStr, firstEntry))
11237f4eb588SAppaRao Puli             {
11247f4eb588SAppaRao Puli                 continue;
11257f4eb588SAppaRao Puli             }
11267f4eb588SAppaRao Puli             firstEntry = false;
11277f4eb588SAppaRao Puli 
11287f4eb588SAppaRao Puli             std::string timestamp;
11297f4eb588SAppaRao Puli             std::string messageID;
11305e715de6SAppaRao Puli             std::vector<std::string> messageArgs;
11317f4eb588SAppaRao Puli             if (event_log::getEventLogParams(logEntry, timestamp, messageID,
11327f4eb588SAppaRao Puli                                              messageArgs) != 0)
11337f4eb588SAppaRao Puli             {
11347f4eb588SAppaRao Puli                 BMCWEB_LOG_DEBUG << "Read eventLog entry params failed";
11357f4eb588SAppaRao Puli                 continue;
11367f4eb588SAppaRao Puli             }
11377f4eb588SAppaRao Puli 
11387f4eb588SAppaRao Puli             std::string registryName;
11397f4eb588SAppaRao Puli             std::string messageKey;
11407f4eb588SAppaRao Puli             event_log::getRegistryAndMessageKey(messageID, registryName,
11417f4eb588SAppaRao Puli                                                 messageKey);
11427f4eb588SAppaRao Puli             if (registryName.empty() || messageKey.empty())
11437f4eb588SAppaRao Puli             {
11447f4eb588SAppaRao Puli                 continue;
11457f4eb588SAppaRao Puli             }
11467f4eb588SAppaRao Puli 
11477f4eb588SAppaRao Puli             lastEventTStr = timestamp;
11487f4eb588SAppaRao Puli             eventRecords.emplace_back(idStr, timestamp, messageID, registryName,
11497f4eb588SAppaRao Puli                                       messageKey, messageArgs);
11507f4eb588SAppaRao Puli         }
11517f4eb588SAppaRao Puli 
11527f4eb588SAppaRao Puli         for (const auto& it : this->subscriptionsMap)
11537f4eb588SAppaRao Puli         {
11547f4eb588SAppaRao Puli             std::shared_ptr<Subscription> entry = it.second;
11557f4eb588SAppaRao Puli             if (entry->eventFormatType == "Event")
11567f4eb588SAppaRao Puli             {
11577f4eb588SAppaRao Puli                 entry->filterAndSendEventLogs(eventRecords);
11587f4eb588SAppaRao Puli             }
11597f4eb588SAppaRao Puli         }
11607f4eb588SAppaRao Puli     }
11617f4eb588SAppaRao Puli 
11627f4eb588SAppaRao Puli     static void watchRedfishEventLogFile()
11637f4eb588SAppaRao Puli     {
11646a9f85f9SAppaRao Puli         if (!inotifyConn)
11657f4eb588SAppaRao Puli         {
11667f4eb588SAppaRao Puli             return;
11677f4eb588SAppaRao Puli         }
11687f4eb588SAppaRao Puli 
11697f4eb588SAppaRao Puli         static std::array<char, 1024> readBuffer;
11707f4eb588SAppaRao Puli 
11717f4eb588SAppaRao Puli         inotifyConn->async_read_some(
11727f4eb588SAppaRao Puli             boost::asio::buffer(readBuffer),
11737f4eb588SAppaRao Puli             [&](const boost::system::error_code& ec,
11747f4eb588SAppaRao Puli                 const std::size_t& bytesTransferred) {
11757f4eb588SAppaRao Puli                 if (ec)
11767f4eb588SAppaRao Puli                 {
11777f4eb588SAppaRao Puli                     BMCWEB_LOG_ERROR << "Callback Error: " << ec.message();
11787f4eb588SAppaRao Puli                     return;
11797f4eb588SAppaRao Puli                 }
11807f4eb588SAppaRao Puli                 std::size_t index = 0;
1181b792cc56SAppaRao Puli                 while ((index + iEventSize) <= bytesTransferred)
11827f4eb588SAppaRao Puli                 {
11837f4eb588SAppaRao Puli                     struct inotify_event event;
1184b792cc56SAppaRao Puli                     std::memcpy(&event, &readBuffer[index], iEventSize);
1185b792cc56SAppaRao Puli                     if (event.wd == dirWatchDesc)
1186b792cc56SAppaRao Puli                     {
1187b792cc56SAppaRao Puli                         if ((event.len == 0) ||
1188b792cc56SAppaRao Puli                             (index + iEventSize + event.len > bytesTransferred))
1189b792cc56SAppaRao Puli                         {
1190b792cc56SAppaRao Puli                             index += (iEventSize + event.len);
1191b792cc56SAppaRao Puli                             continue;
1192b792cc56SAppaRao Puli                         }
1193b792cc56SAppaRao Puli 
1194b792cc56SAppaRao Puli                         std::string fileName(&readBuffer[index + iEventSize],
1195b792cc56SAppaRao Puli                                              event.len);
1196b792cc56SAppaRao Puli                         if (std::strcmp(fileName.c_str(), "redfish") != 0)
1197b792cc56SAppaRao Puli                         {
1198b792cc56SAppaRao Puli                             index += (iEventSize + event.len);
1199b792cc56SAppaRao Puli                             continue;
1200b792cc56SAppaRao Puli                         }
1201b792cc56SAppaRao Puli 
1202b792cc56SAppaRao Puli                         BMCWEB_LOG_DEBUG
1203b792cc56SAppaRao Puli                             << "Redfish log file created/deleted. event.name: "
1204b792cc56SAppaRao Puli                             << fileName;
1205b792cc56SAppaRao Puli                         if (event.mask == IN_CREATE)
1206b792cc56SAppaRao Puli                         {
1207b792cc56SAppaRao Puli                             if (fileWatchDesc != -1)
1208b792cc56SAppaRao Puli                             {
1209b792cc56SAppaRao Puli                                 BMCWEB_LOG_DEBUG
1210016761afSAppaRao Puli                                     << "Remove and Add inotify watcher on "
1211016761afSAppaRao Puli                                        "redfish event log file";
1212016761afSAppaRao Puli                                 // Remove existing inotify watcher and add
1213016761afSAppaRao Puli                                 // with new redfish event log file.
1214016761afSAppaRao Puli                                 inotify_rm_watch(inotifyFd, fileWatchDesc);
1215016761afSAppaRao Puli                                 fileWatchDesc = -1;
1216b792cc56SAppaRao Puli                             }
1217b792cc56SAppaRao Puli 
1218b792cc56SAppaRao Puli                             fileWatchDesc = inotify_add_watch(
1219b792cc56SAppaRao Puli                                 inotifyFd, redfishEventLogFile, IN_MODIFY);
1220b792cc56SAppaRao Puli                             if (fileWatchDesc == -1)
1221b792cc56SAppaRao Puli                             {
1222b792cc56SAppaRao Puli                                 BMCWEB_LOG_ERROR
1223b792cc56SAppaRao Puli                                     << "inotify_add_watch failed for "
1224b792cc56SAppaRao Puli                                        "redfish log file.";
1225b792cc56SAppaRao Puli                                 return;
1226b792cc56SAppaRao Puli                             }
1227b792cc56SAppaRao Puli 
1228b792cc56SAppaRao Puli                             EventServiceManager::getInstance()
1229b792cc56SAppaRao Puli                                 .cacheLastEventTimestamp();
1230b792cc56SAppaRao Puli                             EventServiceManager::getInstance()
1231b792cc56SAppaRao Puli                                 .readEventLogsFromFile();
1232b792cc56SAppaRao Puli                         }
1233b792cc56SAppaRao Puli                         else if ((event.mask == IN_DELETE) ||
1234b792cc56SAppaRao Puli                                  (event.mask == IN_MOVED_TO))
1235b792cc56SAppaRao Puli                         {
1236b792cc56SAppaRao Puli                             if (fileWatchDesc != -1)
1237b792cc56SAppaRao Puli                             {
1238b792cc56SAppaRao Puli                                 inotify_rm_watch(inotifyFd, fileWatchDesc);
1239b792cc56SAppaRao Puli                                 fileWatchDesc = -1;
1240b792cc56SAppaRao Puli                             }
1241b792cc56SAppaRao Puli                         }
1242b792cc56SAppaRao Puli                     }
1243b792cc56SAppaRao Puli                     else if (event.wd == fileWatchDesc)
1244b792cc56SAppaRao Puli                     {
1245b792cc56SAppaRao Puli                         if (event.mask == IN_MODIFY)
12467f4eb588SAppaRao Puli                         {
12477f4eb588SAppaRao Puli                             EventServiceManager::getInstance()
12487f4eb588SAppaRao Puli                                 .readEventLogsFromFile();
12497f4eb588SAppaRao Puli                         }
1250b792cc56SAppaRao Puli                     }
1251b792cc56SAppaRao Puli                     index += (iEventSize + event.len);
12527f4eb588SAppaRao Puli                 }
12537f4eb588SAppaRao Puli 
12547f4eb588SAppaRao Puli                 watchRedfishEventLogFile();
12557f4eb588SAppaRao Puli             });
12567f4eb588SAppaRao Puli     }
12577f4eb588SAppaRao Puli 
12587f4eb588SAppaRao Puli     static int startEventLogMonitor(boost::asio::io_context& ioc)
12597f4eb588SAppaRao Puli     {
126023a21a1cSEd Tanous         inotifyConn.emplace(ioc);
1261b792cc56SAppaRao Puli         inotifyFd = inotify_init1(IN_NONBLOCK);
1262b792cc56SAppaRao Puli         if (inotifyFd == -1)
12637f4eb588SAppaRao Puli         {
12647f4eb588SAppaRao Puli             BMCWEB_LOG_ERROR << "inotify_init1 failed.";
12657f4eb588SAppaRao Puli             return -1;
12667f4eb588SAppaRao Puli         }
1267b792cc56SAppaRao Puli 
1268b792cc56SAppaRao Puli         // Add watch on directory to handle redfish event log file
1269b792cc56SAppaRao Puli         // create/delete.
1270b792cc56SAppaRao Puli         dirWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogDir,
1271b792cc56SAppaRao Puli                                          IN_CREATE | IN_MOVED_TO | IN_DELETE);
1272b792cc56SAppaRao Puli         if (dirWatchDesc == -1)
12737f4eb588SAppaRao Puli         {
12747f4eb588SAppaRao Puli             BMCWEB_LOG_ERROR
1275b792cc56SAppaRao Puli                 << "inotify_add_watch failed for event log directory.";
12767f4eb588SAppaRao Puli             return -1;
12777f4eb588SAppaRao Puli         }
12787f4eb588SAppaRao Puli 
1279b792cc56SAppaRao Puli         // Watch redfish event log file for modifications.
1280b792cc56SAppaRao Puli         fileWatchDesc =
1281b792cc56SAppaRao Puli             inotify_add_watch(inotifyFd, redfishEventLogFile, IN_MODIFY);
1282b792cc56SAppaRao Puli         if (fileWatchDesc == -1)
1283b792cc56SAppaRao Puli         {
1284b792cc56SAppaRao Puli             BMCWEB_LOG_ERROR
1285b792cc56SAppaRao Puli                 << "inotify_add_watch failed for redfish log file.";
1286b792cc56SAppaRao Puli             // Don't return error if file not exist.
1287b792cc56SAppaRao Puli             // Watch on directory will handle create/delete of file.
1288b792cc56SAppaRao Puli         }
1289b792cc56SAppaRao Puli 
12907f4eb588SAppaRao Puli         // monitor redfish event log file
1291b792cc56SAppaRao Puli         inotifyConn->assign(inotifyFd);
12927f4eb588SAppaRao Puli         watchRedfishEventLogFile();
12937f4eb588SAppaRao Puli 
12947f4eb588SAppaRao Puli         return 0;
12957f4eb588SAppaRao Puli     }
12967f4eb588SAppaRao Puli 
12977f4eb588SAppaRao Puli #endif
1298*c0353249SWludzik, Jozef     void getReadingsForReport(sdbusplus::message::message& msg)
1299156d6b00SAppaRao Puli     {
1300*c0353249SWludzik, Jozef         sdbusplus::message::object_path path(msg.get_path());
1301*c0353249SWludzik, Jozef         std::string id = path.filename();
1302*c0353249SWludzik, Jozef         if (id.empty())
1303156d6b00SAppaRao Puli         {
1304*c0353249SWludzik, Jozef             BMCWEB_LOG_ERROR << "Failed to get Id from path";
1305156d6b00SAppaRao Puli             return;
1306156d6b00SAppaRao Puli         }
1307156d6b00SAppaRao Puli 
1308*c0353249SWludzik, Jozef         std::string interface;
1309*c0353249SWludzik, Jozef         std::vector<
1310*c0353249SWludzik, Jozef             std::pair<std::string, std::variant<telemetry::TimestampReadings>>>
1311*c0353249SWludzik, Jozef             props;
1312*c0353249SWludzik, Jozef         std::vector<std::string> invalidProps;
1313*c0353249SWludzik, Jozef         msg.read(interface, props, invalidProps);
1314*c0353249SWludzik, Jozef 
1315*c0353249SWludzik, Jozef         auto found =
1316*c0353249SWludzik, Jozef             std::find_if(props.begin(), props.end(),
1317*c0353249SWludzik, Jozef                          [](const auto& x) { return x.first == "Readings"; });
1318*c0353249SWludzik, Jozef         if (found == props.end())
1319156d6b00SAppaRao Puli         {
1320*c0353249SWludzik, Jozef             BMCWEB_LOG_INFO << "Failed to get Readings from Report properties";
1321156d6b00SAppaRao Puli             return;
1322156d6b00SAppaRao Puli         }
1323156d6b00SAppaRao Puli 
1324*c0353249SWludzik, Jozef         const std::variant<telemetry::TimestampReadings>& readings =
1325*c0353249SWludzik, Jozef             found->second;
1326156d6b00SAppaRao Puli         for (const auto& it :
1327156d6b00SAppaRao Puli              EventServiceManager::getInstance().subscriptionsMap)
1328156d6b00SAppaRao Puli         {
1329*c0353249SWludzik, Jozef             Subscription& entry = *it.second.get();
1330*c0353249SWludzik, Jozef             if (entry.eventFormatType == metricReportFormatType)
1331156d6b00SAppaRao Puli             {
1332*c0353249SWludzik, Jozef                 entry.filterAndSendReports(id, readings);
1333156d6b00SAppaRao Puli             }
1334156d6b00SAppaRao Puli         }
1335156d6b00SAppaRao Puli     }
1336156d6b00SAppaRao Puli 
1337156d6b00SAppaRao Puli     void unregisterMetricReportSignal()
1338156d6b00SAppaRao Puli     {
13397d1cc387SAppaRao Puli         if (matchTelemetryMonitor)
13407d1cc387SAppaRao Puli         {
1341156d6b00SAppaRao Puli             BMCWEB_LOG_DEBUG << "Metrics report signal - Unregister";
1342156d6b00SAppaRao Puli             matchTelemetryMonitor.reset();
1343156d6b00SAppaRao Puli             matchTelemetryMonitor = nullptr;
1344156d6b00SAppaRao Puli         }
13457d1cc387SAppaRao Puli     }
1346156d6b00SAppaRao Puli 
1347156d6b00SAppaRao Puli     void registerMetricReportSignal()
1348156d6b00SAppaRao Puli     {
13497d1cc387SAppaRao Puli         if (!serviceEnabled || matchTelemetryMonitor)
1350156d6b00SAppaRao Puli         {
13517d1cc387SAppaRao Puli             BMCWEB_LOG_DEBUG << "Not registering metric report signal.";
1352156d6b00SAppaRao Puli             return;
1353156d6b00SAppaRao Puli         }
1354156d6b00SAppaRao Puli 
1355156d6b00SAppaRao Puli         BMCWEB_LOG_DEBUG << "Metrics report signal - Register";
1356*c0353249SWludzik, Jozef         std::string matchStr = "type='signal',member='PropertiesChanged',"
1357*c0353249SWludzik, Jozef                                "interface='org.freedesktop.DBus.Properties',"
1358*c0353249SWludzik, Jozef                                "arg0=xyz.openbmc_project.Telemetry.Report";
1359156d6b00SAppaRao Puli 
1360156d6b00SAppaRao Puli         matchTelemetryMonitor = std::make_shared<sdbusplus::bus::match::match>(
1361156d6b00SAppaRao Puli             *crow::connections::systemBus, matchStr,
1362156d6b00SAppaRao Puli             [this](sdbusplus::message::message& msg) {
1363156d6b00SAppaRao Puli                 if (msg.is_method_error())
1364156d6b00SAppaRao Puli                 {
1365156d6b00SAppaRao Puli                     BMCWEB_LOG_ERROR << "TelemetryMonitor Signal error";
1366156d6b00SAppaRao Puli                     return;
1367156d6b00SAppaRao Puli                 }
1368156d6b00SAppaRao Puli 
1369*c0353249SWludzik, Jozef                 getReadingsForReport(msg);
1370156d6b00SAppaRao Puli             });
1371156d6b00SAppaRao Puli     }
13721bf712bcSAyushi Smriti 
13731bf712bcSAyushi Smriti     bool validateAndSplitUrl(const std::string& destUrl, std::string& urlProto,
13741bf712bcSAyushi Smriti                              std::string& host, std::string& port,
13751bf712bcSAyushi Smriti                              std::string& path)
13761bf712bcSAyushi Smriti     {
13771bf712bcSAyushi Smriti         // Validate URL using regex expression
13781bf712bcSAyushi Smriti         // Format: <protocol>://<host>:<port>/<path>
13791bf712bcSAyushi Smriti         // protocol: http/https
13801bf712bcSAyushi Smriti         const std::regex urlRegex(
13811bf712bcSAyushi Smriti             "(http|https)://([^/\\x20\\x3f\\x23\\x3a]+):?([0-9]*)(/"
13821bf712bcSAyushi Smriti             "([^\\x20\\x23\\x3f]*\\x3f?([^\\x20\\x23\\x3f])*)?)");
13831bf712bcSAyushi Smriti         std::cmatch match;
13841bf712bcSAyushi Smriti         if (!std::regex_match(destUrl.c_str(), match, urlRegex))
13851bf712bcSAyushi Smriti         {
13861bf712bcSAyushi Smriti             BMCWEB_LOG_INFO << "Dest. url did not match ";
13871bf712bcSAyushi Smriti             return false;
13881bf712bcSAyushi Smriti         }
13891bf712bcSAyushi Smriti 
13901bf712bcSAyushi Smriti         urlProto = std::string(match[1].first, match[1].second);
13911bf712bcSAyushi Smriti         if (urlProto == "http")
13921bf712bcSAyushi Smriti         {
13931bf712bcSAyushi Smriti #ifndef BMCWEB_INSECURE_ENABLE_HTTP_PUSH_STYLE_EVENTING
13941bf712bcSAyushi Smriti             return false;
13951bf712bcSAyushi Smriti #endif
13961bf712bcSAyushi Smriti         }
13971bf712bcSAyushi Smriti 
13981bf712bcSAyushi Smriti         host = std::string(match[2].first, match[2].second);
13991bf712bcSAyushi Smriti         port = std::string(match[3].first, match[3].second);
14001bf712bcSAyushi Smriti         path = std::string(match[4].first, match[4].second);
14011bf712bcSAyushi Smriti         if (port.empty())
14021bf712bcSAyushi Smriti         {
14031bf712bcSAyushi Smriti             if (urlProto == "http")
14041bf712bcSAyushi Smriti             {
14051bf712bcSAyushi Smriti                 port = "80";
14061bf712bcSAyushi Smriti             }
14071bf712bcSAyushi Smriti             else
14081bf712bcSAyushi Smriti             {
14091bf712bcSAyushi Smriti                 port = "443";
14101bf712bcSAyushi Smriti             }
14111bf712bcSAyushi Smriti         }
14121bf712bcSAyushi Smriti         if (path.empty())
14131bf712bcSAyushi Smriti         {
14141bf712bcSAyushi Smriti             path = "/";
14151bf712bcSAyushi Smriti         }
14161bf712bcSAyushi Smriti         return true;
14171bf712bcSAyushi Smriti     }
141823a21a1cSEd Tanous };
1419b52664e2SAppaRao Puli 
1420b52664e2SAppaRao Puli } // namespace redfish
1421