1b52664e2SAppaRao Puli /*
2b52664e2SAppaRao Puli // Copyright (c) 2020 Intel Corporation
3b52664e2SAppaRao Puli //
4b52664e2SAppaRao Puli // Licensed under the Apache License, Version 2.0 (the "License");
5b52664e2SAppaRao Puli // you may not use this file except in compliance with the License.
6b52664e2SAppaRao Puli // You may obtain a copy of the License at
7b52664e2SAppaRao Puli //
8b52664e2SAppaRao Puli // http://www.apache.org/licenses/LICENSE-2.0
9b52664e2SAppaRao Puli //
10b52664e2SAppaRao Puli // Unless required by applicable law or agreed to in writing, software
11b52664e2SAppaRao Puli // distributed under the License is distributed on an "AS IS" BASIS,
12b52664e2SAppaRao Puli // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13b52664e2SAppaRao Puli // See the License for the specific language governing permissions and
14b52664e2SAppaRao Puli // limitations under the License.
15b52664e2SAppaRao Puli */
16b52664e2SAppaRao Puli #pragma once
173ccb3adbSEd Tanous #include "dbus_utility.hpp"
183ccb3adbSEd Tanous #include "error_messages.hpp"
193ccb3adbSEd Tanous #include "event_service_store.hpp"
203ccb3adbSEd Tanous #include "http_client.hpp"
21c0353249SWludzik, Jozef #include "metric_report.hpp"
222c6ffdb0SEd Tanous #include "ossl_random.hpp"
233ccb3adbSEd Tanous #include "persistent_data.hpp"
247f4eb588SAppaRao Puli #include "registries.hpp"
258dab0f58SEd Tanous #include "registries_selector.hpp"
2650ebd4afSEd Tanous #include "str_utility.hpp"
2777665bdaSNan Zhou #include "utility.hpp"
283ccb3adbSEd Tanous #include "utils/json_utils.hpp"
295b90429aSEd Tanous #include "utils/time_utils.hpp"
307f4eb588SAppaRao Puli
317f4eb588SAppaRao Puli #include <sys/inotify.h>
32b52664e2SAppaRao Puli
33fb4fd5d4SZhenfei Tai #include <boost/asio/io_context.hpp>
34b52664e2SAppaRao Puli #include <boost/container/flat_map.hpp>
35ef4c65b7SEd Tanous #include <boost/url/format.hpp>
364a7fbefdSEd Tanous #include <boost/url/url_view_base.hpp>
37b5b40605Snitroglycerine #include <sdbusplus/bus/match.hpp>
381214b7e7SGunnar Mills
395e44e3d8SAppaRao Puli #include <algorithm>
40b52664e2SAppaRao Puli #include <cstdlib>
41b52664e2SAppaRao Puli #include <ctime>
421bf712bcSAyushi Smriti #include <fstream>
43b52664e2SAppaRao Puli #include <memory>
443544d2a7SEd Tanous #include <ranges>
4526702d01SEd Tanous #include <span>
46b52664e2SAppaRao Puli
47b52664e2SAppaRao Puli namespace redfish
48b52664e2SAppaRao Puli {
49156d6b00SAppaRao Puli
50156d6b00SAppaRao Puli using ReadingsObjType =
5193f5d7c7SWludzik, Jozef std::vector<std::tuple<std::string, std::string, double, int32_t>>;
52156d6b00SAppaRao Puli
53156d6b00SAppaRao Puli static constexpr const char* eventFormatType = "Event";
54156d6b00SAppaRao Puli static constexpr const char* metricReportFormatType = "MetricReport";
55156d6b00SAppaRao Puli
565e44e3d8SAppaRao Puli static constexpr const char* subscriptionTypeSSE = "SSE";
571bf712bcSAyushi Smriti static constexpr const char* eventServiceFile =
581bf712bcSAyushi Smriti "/var/lib/bmcweb/eventservice_config.json";
591bf712bcSAyushi Smriti
605e44e3d8SAppaRao Puli static constexpr const uint8_t maxNoOfSubscriptions = 20;
615e44e3d8SAppaRao Puli static constexpr const uint8_t maxNoOfSSESubscriptions = 10;
625e44e3d8SAppaRao Puli
63cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
644642bf8fSGeorge Liu static std::optional<boost::asio::posix::stream_descriptor> inotifyConn;
654642bf8fSGeorge Liu static constexpr const char* redfishEventLogDir = "/var/log";
664642bf8fSGeorge Liu static constexpr const char* redfishEventLogFile = "/var/log/redfish";
674642bf8fSGeorge Liu static constexpr const size_t iEventSize = sizeof(inotify_event);
68cf9e417dSEd Tanous
69cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
704642bf8fSGeorge Liu static int inotifyFd = -1;
71cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
724642bf8fSGeorge Liu static int dirWatchDesc = -1;
73cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
744642bf8fSGeorge Liu static int fileWatchDesc = -1;
754642bf8fSGeorge Liu
764642bf8fSGeorge Liu // <ID, timestamp, RedfishLogId, registryPrefix, MessageId, MessageArgs>
774642bf8fSGeorge Liu using EventLogObjectsType =
784642bf8fSGeorge Liu std::tuple<std::string, std::string, std::string, std::string, std::string,
794642bf8fSGeorge Liu std::vector<std::string>>;
804642bf8fSGeorge Liu
81fffb8c1fSEd Tanous namespace registries
824642bf8fSGeorge Liu {
837f4eb588SAppaRao Puli static const Message*
getMsgFromRegistry(const std::string & messageKey,const std::span<const MessageEntry> & registry)847f4eb588SAppaRao Puli getMsgFromRegistry(const std::string& messageKey,
8526702d01SEd Tanous const std::span<const MessageEntry>& registry)
867f4eb588SAppaRao Puli {
873544d2a7SEd Tanous std::span<const MessageEntry>::iterator messageIt = std::ranges::find_if(
883544d2a7SEd Tanous registry, [&messageKey](const MessageEntry& messageEntry) {
8955f79e6fSEd Tanous return messageKey == messageEntry.first;
907f4eb588SAppaRao Puli });
9126702d01SEd Tanous if (messageIt != registry.end())
927f4eb588SAppaRao Puli {
937f4eb588SAppaRao Puli return &messageIt->second;
947f4eb588SAppaRao Puli }
957f4eb588SAppaRao Puli
967f4eb588SAppaRao Puli return nullptr;
977f4eb588SAppaRao Puli }
987f4eb588SAppaRao Puli
formatMessage(std::string_view messageID)9926ccae32SEd Tanous static const Message* formatMessage(std::string_view messageID)
1007f4eb588SAppaRao Puli {
1017f4eb588SAppaRao Puli // Redfish MessageIds are in the form
1027f4eb588SAppaRao Puli // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
1037f4eb588SAppaRao Puli // the right Message
1047f4eb588SAppaRao Puli std::vector<std::string> fields;
1057f4eb588SAppaRao Puli fields.reserve(4);
10650ebd4afSEd Tanous
10750ebd4afSEd Tanous bmcweb::split(fields, messageID, '.');
1087f4eb588SAppaRao Puli if (fields.size() != 4)
1097f4eb588SAppaRao Puli {
1107f4eb588SAppaRao Puli return nullptr;
1117f4eb588SAppaRao Puli }
11202cad96eSEd Tanous const std::string& registryName = fields[0];
11302cad96eSEd Tanous const std::string& messageKey = fields[3];
1147f4eb588SAppaRao Puli
1157f4eb588SAppaRao Puli // Find the right registry and check it for the MessageKey
116b304bd79SP Dheeraj Srujan Kumar return getMsgFromRegistry(messageKey, getRegistryFromPrefix(registryName));
1177f4eb588SAppaRao Puli }
118fffb8c1fSEd Tanous } // namespace registries
1197f4eb588SAppaRao Puli
1207f4eb588SAppaRao Puli namespace event_log
1217f4eb588SAppaRao Puli {
getUniqueEntryID(const std::string & logEntry,std::string & entryID)1222558979cSP Dheeraj Srujan Kumar inline bool getUniqueEntryID(const std::string& logEntry, std::string& entryID)
1237f4eb588SAppaRao Puli {
1247f4eb588SAppaRao Puli static time_t prevTs = 0;
1257f4eb588SAppaRao Puli static int index = 0;
1267f4eb588SAppaRao Puli
1277f4eb588SAppaRao Puli // Get the entry timestamp
1287f4eb588SAppaRao Puli std::time_t curTs = 0;
1297f4eb588SAppaRao Puli std::tm timeStruct = {};
1307f4eb588SAppaRao Puli std::istringstream entryStream(logEntry);
1317f4eb588SAppaRao Puli if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1327f4eb588SAppaRao Puli {
1337f4eb588SAppaRao Puli curTs = std::mktime(&timeStruct);
1347f4eb588SAppaRao Puli if (curTs == -1)
1357f4eb588SAppaRao Puli {
1367f4eb588SAppaRao Puli return false;
1377f4eb588SAppaRao Puli }
1387f4eb588SAppaRao Puli }
1397f4eb588SAppaRao Puli // If the timestamp isn't unique, increment the index
1407f4eb588SAppaRao Puli index = (curTs == prevTs) ? index + 1 : 0;
1417f4eb588SAppaRao Puli
1427f4eb588SAppaRao Puli // Save the timestamp
1437f4eb588SAppaRao Puli prevTs = curTs;
1447f4eb588SAppaRao Puli
1457f4eb588SAppaRao Puli entryID = std::to_string(curTs);
1467f4eb588SAppaRao Puli if (index > 0)
1477f4eb588SAppaRao Puli {
1487f4eb588SAppaRao Puli entryID += "_" + std::to_string(index);
1497f4eb588SAppaRao Puli }
1507f4eb588SAppaRao Puli return true;
1517f4eb588SAppaRao Puli }
1527f4eb588SAppaRao Puli
getEventLogParams(const std::string & logEntry,std::string & timestamp,std::string & messageID,std::vector<std::string> & messageArgs)15323a21a1cSEd Tanous inline int getEventLogParams(const std::string& logEntry,
15423a21a1cSEd Tanous std::string& timestamp, std::string& messageID,
1555e715de6SAppaRao Puli std::vector<std::string>& messageArgs)
1567f4eb588SAppaRao Puli {
1577f4eb588SAppaRao Puli // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
1587f4eb588SAppaRao Puli // First get the Timestamp
159f23b7296SEd Tanous size_t space = logEntry.find_first_of(' ');
1607f4eb588SAppaRao Puli if (space == std::string::npos)
1617f4eb588SAppaRao Puli {
1627f4eb588SAppaRao Puli return -EINVAL;
1637f4eb588SAppaRao Puli }
1647f4eb588SAppaRao Puli timestamp = logEntry.substr(0, space);
1657f4eb588SAppaRao Puli // Then get the log contents
166f23b7296SEd Tanous size_t entryStart = logEntry.find_first_not_of(' ', space);
1677f4eb588SAppaRao Puli if (entryStart == std::string::npos)
1687f4eb588SAppaRao Puli {
1697f4eb588SAppaRao Puli return -EINVAL;
1707f4eb588SAppaRao Puli }
1717f4eb588SAppaRao Puli std::string_view entry(logEntry);
1727f4eb588SAppaRao Puli entry.remove_prefix(entryStart);
1737f4eb588SAppaRao Puli // Use split to separate the entry into its fields
1747f4eb588SAppaRao Puli std::vector<std::string> logEntryFields;
17550ebd4afSEd Tanous bmcweb::split(logEntryFields, entry, ',');
1767f4eb588SAppaRao Puli // We need at least a MessageId to be valid
17726f6976fSEd Tanous if (logEntryFields.empty())
1787f4eb588SAppaRao Puli {
1797f4eb588SAppaRao Puli return -EINVAL;
1807f4eb588SAppaRao Puli }
1817f4eb588SAppaRao Puli messageID = logEntryFields[0];
1827f4eb588SAppaRao Puli
1837f4eb588SAppaRao Puli // Get the MessageArgs from the log if there are any
1847f4eb588SAppaRao Puli if (logEntryFields.size() > 1)
1857f4eb588SAppaRao Puli {
18602cad96eSEd Tanous const std::string& messageArgsStart = logEntryFields[1];
1877f4eb588SAppaRao Puli // If the first string is empty, assume there are no MessageArgs
1887f4eb588SAppaRao Puli if (!messageArgsStart.empty())
1897f4eb588SAppaRao Puli {
1905e715de6SAppaRao Puli messageArgs.assign(logEntryFields.begin() + 1,
1915e715de6SAppaRao Puli logEntryFields.end());
1927f4eb588SAppaRao Puli }
1937f4eb588SAppaRao Puli }
1947f4eb588SAppaRao Puli
1957f4eb588SAppaRao Puli return 0;
1967f4eb588SAppaRao Puli }
1977f4eb588SAppaRao Puli
getRegistryAndMessageKey(const std::string & messageID,std::string & registryName,std::string & messageKey)19823a21a1cSEd Tanous inline void getRegistryAndMessageKey(const std::string& messageID,
1997f4eb588SAppaRao Puli std::string& registryName,
2007f4eb588SAppaRao Puli std::string& messageKey)
2017f4eb588SAppaRao Puli {
2027f4eb588SAppaRao Puli // Redfish MessageIds are in the form
2037f4eb588SAppaRao Puli // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
2047f4eb588SAppaRao Puli // the right Message
2057f4eb588SAppaRao Puli std::vector<std::string> fields;
2067f4eb588SAppaRao Puli fields.reserve(4);
20750ebd4afSEd Tanous bmcweb::split(fields, messageID, '.');
2087f4eb588SAppaRao Puli if (fields.size() == 4)
2097f4eb588SAppaRao Puli {
2107f4eb588SAppaRao Puli registryName = fields[0];
2117f4eb588SAppaRao Puli messageKey = fields[3];
2127f4eb588SAppaRao Puli }
2137f4eb588SAppaRao Puli }
2147f4eb588SAppaRao Puli
formatEventLogEntry(const std::string & logEntryID,const std::string & messageID,const std::span<std::string_view> messageArgs,std::string timestamp,const std::string & customText,nlohmann::json & logEntryJson)21523a21a1cSEd Tanous inline int formatEventLogEntry(const std::string& logEntryID,
2167f4eb588SAppaRao Puli const std::string& messageID,
217c5ba4c27SEd Tanous const std::span<std::string_view> messageArgs,
21823a21a1cSEd Tanous std::string timestamp,
219b5a76932SEd Tanous const std::string& customText,
2207f4eb588SAppaRao Puli nlohmann::json& logEntryJson)
2217f4eb588SAppaRao Puli {
2227f4eb588SAppaRao Puli // Get the Message from the MessageRegistry
223fffb8c1fSEd Tanous const registries::Message* message = registries::formatMessage(messageID);
2247f4eb588SAppaRao Puli
22580f595e7SEd Tanous if (message == nullptr)
2267f4eb588SAppaRao Puli {
22780f595e7SEd Tanous return -1;
2287f4eb588SAppaRao Puli }
2297f4eb588SAppaRao Puli
23089492a15SPatrick Williams std::string msg = redfish::registries::fillMessageArgs(messageArgs,
23189492a15SPatrick Williams message->message);
23280f595e7SEd Tanous if (msg.empty())
23380f595e7SEd Tanous {
23480f595e7SEd Tanous return -1;
23580f595e7SEd Tanous }
2367f4eb588SAppaRao Puli
2377f4eb588SAppaRao Puli // Get the Created time from the timestamp. The log timestamp is in
2387f4eb588SAppaRao Puli // RFC3339 format which matches the Redfish format except for the
2397f4eb588SAppaRao Puli // fractional seconds between the '.' and the '+', so just remove them.
240f23b7296SEd Tanous std::size_t dot = timestamp.find_first_of('.');
241b2f7609bSEd Tanous std::size_t plus = timestamp.find_first_of('+', dot);
2427f4eb588SAppaRao Puli if (dot != std::string::npos && plus != std::string::npos)
2437f4eb588SAppaRao Puli {
2447f4eb588SAppaRao Puli timestamp.erase(dot, plus - dot);
2457f4eb588SAppaRao Puli }
2467f4eb588SAppaRao Puli
2477f4eb588SAppaRao Puli // Fill in the log entry with the gathered data
2481476687dSEd Tanous logEntryJson["EventId"] = logEntryID;
2491476687dSEd Tanous logEntryJson["EventType"] = "Event";
25080f595e7SEd Tanous logEntryJson["Severity"] = message->messageSeverity;
2511476687dSEd Tanous logEntryJson["Message"] = std::move(msg);
2521476687dSEd Tanous logEntryJson["MessageId"] = messageID;
2531476687dSEd Tanous logEntryJson["MessageArgs"] = messageArgs;
2541476687dSEd Tanous logEntryJson["EventTimestamp"] = std::move(timestamp);
2551476687dSEd Tanous logEntryJson["Context"] = customText;
2567f4eb588SAppaRao Puli return 0;
2577f4eb588SAppaRao Puli }
2587f4eb588SAppaRao Puli
2597f4eb588SAppaRao Puli } // namespace event_log
2607f4eb588SAppaRao Puli
26128afb49cSJunLin Chen class Subscription : public persistent_data::UserSubscription
262b52664e2SAppaRao Puli {
263b52664e2SAppaRao Puli public:
264b52664e2SAppaRao Puli Subscription(const Subscription&) = delete;
265b52664e2SAppaRao Puli Subscription& operator=(const Subscription&) = delete;
266b52664e2SAppaRao Puli Subscription(Subscription&&) = delete;
267b52664e2SAppaRao Puli Subscription& operator=(Subscription&&) = delete;
268b52664e2SAppaRao Puli
Subscription(const boost::urls::url_view_base & url,boost::asio::io_context & ioc)2694a7fbefdSEd Tanous Subscription(const boost::urls::url_view_base& url,
2704a7fbefdSEd Tanous boost::asio::io_context& ioc) :
271a716aa74SEd Tanous policy(std::make_shared<crow::ConnectionPolicy>())
272b52664e2SAppaRao Puli {
273a716aa74SEd Tanous destinationUrl = url;
2745e44e3d8SAppaRao Puli client.emplace(ioc, policy);
2757adb85acSSunitha Harish // Subscription constructor
276d14a48ffSCarson Labrado policy->invalidResp = retryRespHandler;
277b52664e2SAppaRao Puli }
2784bbf237fSAppaRao Puli
Subscription(crow::sse_socket::Connection & connIn)2795e44e3d8SAppaRao Puli explicit Subscription(crow::sse_socket::Connection& connIn) :
2805e44e3d8SAppaRao Puli sseConn(&connIn)
2815e44e3d8SAppaRao Puli {}
2825e44e3d8SAppaRao Puli
2839f616dd1SEd Tanous ~Subscription() = default;
284b52664e2SAppaRao Puli
sendEvent(std::string && msg)2855e44e3d8SAppaRao Puli bool sendEvent(std::string&& msg)
286b52664e2SAppaRao Puli {
2876ba8c82eSsunharis_in persistent_data::EventServiceConfig eventServiceConfig =
2886ba8c82eSsunharis_in persistent_data::EventServiceStore::getInstance()
2896ba8c82eSsunharis_in .getEventServiceConfig();
2906ba8c82eSsunharis_in if (!eventServiceConfig.enabled)
2916ba8c82eSsunharis_in {
2926ba8c82eSsunharis_in return false;
2936ba8c82eSsunharis_in }
2946ba8c82eSsunharis_in
295f52c03c1SCarson Labrado // A connection pool will be created if one does not already exist
2965e44e3d8SAppaRao Puli if (client)
2975e44e3d8SAppaRao Puli {
298a716aa74SEd Tanous client->sendData(std::move(msg), destinationUrl, httpHeaders,
299a716aa74SEd Tanous boost::beast::http::verb::post);
3005e44e3d8SAppaRao Puli return true;
3015e44e3d8SAppaRao Puli }
3027adb85acSSunitha Harish
3034bbf237fSAppaRao Puli if (sseConn != nullptr)
3044bbf237fSAppaRao Puli {
3055e44e3d8SAppaRao Puli eventSeqNum++;
3065e44e3d8SAppaRao Puli sseConn->sendEvent(std::to_string(eventSeqNum), msg);
3074bbf237fSAppaRao Puli }
3086ba8c82eSsunharis_in return true;
3094bbf237fSAppaRao Puli }
3104bbf237fSAppaRao Puli
sendTestEventLog()3116ba8c82eSsunharis_in bool sendTestEventLog()
3120b4bdd93SAppaRao Puli {
3130b4bdd93SAppaRao Puli nlohmann::json logEntryArray;
3140b4bdd93SAppaRao Puli logEntryArray.push_back({});
3150b4bdd93SAppaRao Puli nlohmann::json& logEntryJson = logEntryArray.back();
3160b4bdd93SAppaRao Puli
317613dabeaSEd Tanous logEntryJson["EventId"] = "TestID";
318613dabeaSEd Tanous logEntryJson["EventType"] = "Event";
319613dabeaSEd Tanous logEntryJson["Severity"] = "OK";
320613dabeaSEd Tanous logEntryJson["Message"] = "Generated test event";
321613dabeaSEd Tanous logEntryJson["MessageId"] = "OpenBMC.0.2.TestEventLog";
322613dabeaSEd Tanous logEntryJson["MessageArgs"] = nlohmann::json::array();
323613dabeaSEd Tanous logEntryJson["EventTimestamp"] =
324613dabeaSEd Tanous redfish::time_utils::getDateTimeOffsetNow().first;
325613dabeaSEd Tanous logEntryJson["Context"] = customText;
3260b4bdd93SAppaRao Puli
3271476687dSEd Tanous nlohmann::json msg;
3281476687dSEd Tanous msg["@odata.type"] = "#Event.v1_4_0.Event";
3291476687dSEd Tanous msg["Id"] = std::to_string(eventSeqNum);
3301476687dSEd Tanous msg["Name"] = "Event Log";
3311476687dSEd Tanous msg["Events"] = logEntryArray;
3320b4bdd93SAppaRao Puli
33389492a15SPatrick Williams std::string strMsg = msg.dump(2, ' ', true,
33489492a15SPatrick Williams nlohmann::json::error_handler_t::replace);
3355e44e3d8SAppaRao Puli return sendEvent(std::move(strMsg));
3360b4bdd93SAppaRao Puli }
3370b4bdd93SAppaRao Puli
filterAndSendEventLogs(const std::vector<EventLogObjectsType> & eventRecords)3387f4eb588SAppaRao Puli void filterAndSendEventLogs(
3397f4eb588SAppaRao Puli const std::vector<EventLogObjectsType>& eventRecords)
3407f4eb588SAppaRao Puli {
3417f4eb588SAppaRao Puli nlohmann::json logEntryArray;
3427f4eb588SAppaRao Puli for (const EventLogObjectsType& logEntry : eventRecords)
3437f4eb588SAppaRao Puli {
3447f4eb588SAppaRao Puli const std::string& idStr = std::get<0>(logEntry);
3457f4eb588SAppaRao Puli const std::string& timestamp = std::get<1>(logEntry);
3467f4eb588SAppaRao Puli const std::string& messageID = std::get<2>(logEntry);
3477f4eb588SAppaRao Puli const std::string& registryName = std::get<3>(logEntry);
3487f4eb588SAppaRao Puli const std::string& messageKey = std::get<4>(logEntry);
3495e715de6SAppaRao Puli const std::vector<std::string>& messageArgs = std::get<5>(logEntry);
3507f4eb588SAppaRao Puli
3517f4eb588SAppaRao Puli // If registryPrefixes list is empty, don't filter events
3527f4eb588SAppaRao Puli // send everything.
35326f6976fSEd Tanous if (!registryPrefixes.empty())
3547f4eb588SAppaRao Puli {
3553544d2a7SEd Tanous auto obj = std::ranges::find(registryPrefixes, registryName);
3567f4eb588SAppaRao Puli if (obj == registryPrefixes.end())
3577f4eb588SAppaRao Puli {
3587f4eb588SAppaRao Puli continue;
3597f4eb588SAppaRao Puli }
3607f4eb588SAppaRao Puli }
3617f4eb588SAppaRao Puli
3627f4eb588SAppaRao Puli // If registryMsgIds list is empty, don't filter events
3637f4eb588SAppaRao Puli // send everything.
36426f6976fSEd Tanous if (!registryMsgIds.empty())
3657f4eb588SAppaRao Puli {
3663544d2a7SEd Tanous auto obj = std::ranges::find(registryMsgIds, messageKey);
3677f4eb588SAppaRao Puli if (obj == registryMsgIds.end())
3687f4eb588SAppaRao Puli {
3697f4eb588SAppaRao Puli continue;
3707f4eb588SAppaRao Puli }
3717f4eb588SAppaRao Puli }
3727f4eb588SAppaRao Puli
373c5ba4c27SEd Tanous std::vector<std::string_view> messageArgsView(messageArgs.begin(),
374c5ba4c27SEd Tanous messageArgs.end());
375c5ba4c27SEd Tanous
3767f4eb588SAppaRao Puli logEntryArray.push_back({});
3777f4eb588SAppaRao Puli nlohmann::json& bmcLogEntry = logEntryArray.back();
378c5ba4c27SEd Tanous if (event_log::formatEventLogEntry(idStr, messageID,
379c5ba4c27SEd Tanous messageArgsView, timestamp,
380c5ba4c27SEd Tanous customText, bmcLogEntry) != 0)
3817f4eb588SAppaRao Puli {
38262598e31SEd Tanous BMCWEB_LOG_DEBUG("Read eventLog entry failed");
3837f4eb588SAppaRao Puli continue;
3847f4eb588SAppaRao Puli }
3857f4eb588SAppaRao Puli }
3867f4eb588SAppaRao Puli
38726f6976fSEd Tanous if (logEntryArray.empty())
3887f4eb588SAppaRao Puli {
38962598e31SEd Tanous BMCWEB_LOG_DEBUG("No log entries available to be transferred.");
3907f4eb588SAppaRao Puli return;
3917f4eb588SAppaRao Puli }
3927f4eb588SAppaRao Puli
3931476687dSEd Tanous nlohmann::json msg;
3941476687dSEd Tanous msg["@odata.type"] = "#Event.v1_4_0.Event";
3951476687dSEd Tanous msg["Id"] = std::to_string(eventSeqNum);
3961476687dSEd Tanous msg["Name"] = "Event Log";
3971476687dSEd Tanous msg["Events"] = logEntryArray;
39889492a15SPatrick Williams std::string strMsg = msg.dump(2, ' ', true,
39989492a15SPatrick Williams nlohmann::json::error_handler_t::replace);
4005e44e3d8SAppaRao Puli sendEvent(std::move(strMsg));
4015e44e3d8SAppaRao Puli eventSeqNum++;
4027f4eb588SAppaRao Puli }
4037f4eb588SAppaRao Puli
filterAndSendReports(const std::string & reportId,const telemetry::TimestampReadings & var)404248d0230SEd Tanous void filterAndSendReports(const std::string& reportId,
4051e1e598dSJonathan Doman const telemetry::TimestampReadings& var)
406156d6b00SAppaRao Puli {
407ef4c65b7SEd Tanous boost::urls::url mrdUri = boost::urls::format(
408ef4c65b7SEd Tanous "/redfish/v1/TelemetryService/MetricReportDefinitions/{}",
409ef4c65b7SEd Tanous reportId);
410156d6b00SAppaRao Puli
411156d6b00SAppaRao Puli // Empty list means no filter. Send everything.
41226f6976fSEd Tanous if (!metricReportDefinitions.empty())
413156d6b00SAppaRao Puli {
4143544d2a7SEd Tanous if (std::ranges::find(metricReportDefinitions, mrdUri.buffer()) ==
4153544d2a7SEd Tanous metricReportDefinitions.end())
416156d6b00SAppaRao Puli {
417156d6b00SAppaRao Puli return;
418156d6b00SAppaRao Puli }
419156d6b00SAppaRao Puli }
420156d6b00SAppaRao Puli
421c0353249SWludzik, Jozef nlohmann::json msg;
422248d0230SEd Tanous if (!telemetry::fillReport(msg, reportId, var))
423156d6b00SAppaRao Puli {
42462598e31SEd Tanous BMCWEB_LOG_ERROR("Failed to fill the MetricReport for DBus "
42562598e31SEd Tanous "Report with id {}",
42662598e31SEd Tanous reportId);
427c0353249SWludzik, Jozef return;
428156d6b00SAppaRao Puli }
429156d6b00SAppaRao Puli
43022daffd7SAppaRao Puli // Context is set by user during Event subscription and it must be
43122daffd7SAppaRao Puli // set for MetricReport response.
43222daffd7SAppaRao Puli if (!customText.empty())
43322daffd7SAppaRao Puli {
43422daffd7SAppaRao Puli msg["Context"] = customText;
43522daffd7SAppaRao Puli }
43622daffd7SAppaRao Puli
43789492a15SPatrick Williams std::string strMsg = msg.dump(2, ' ', true,
43889492a15SPatrick Williams nlohmann::json::error_handler_t::replace);
4395e44e3d8SAppaRao Puli sendEvent(std::move(strMsg));
440156d6b00SAppaRao Puli }
441156d6b00SAppaRao Puli
updateRetryConfig(uint32_t retryAttempts,uint32_t retryTimeoutInterval)442d14a48ffSCarson Labrado void updateRetryConfig(uint32_t retryAttempts,
443d14a48ffSCarson Labrado uint32_t retryTimeoutInterval)
444fe44eb0bSAyushi Smriti {
44593cf0ac2SEd Tanous if (policy == nullptr)
44693cf0ac2SEd Tanous {
44793cf0ac2SEd Tanous BMCWEB_LOG_DEBUG("Retry policy was nullptr, ignoring set");
44893cf0ac2SEd Tanous return;
44993cf0ac2SEd Tanous }
450d14a48ffSCarson Labrado policy->maxRetryAttempts = retryAttempts;
451d14a48ffSCarson Labrado policy->retryIntervalSecs = std::chrono::seconds(retryTimeoutInterval);
45262de0c68SAppaRao Puli }
453fe44eb0bSAyushi Smriti
getEventSeqNum() const4549eb808c1SEd Tanous uint64_t getEventSeqNum() const
45596330b99SSunitha Harish {
45696330b99SSunitha Harish return eventSeqNum;
45796330b99SSunitha Harish }
45896330b99SSunitha Harish
setSubscriptionId(const std::string & id2)4595e44e3d8SAppaRao Puli void setSubscriptionId(const std::string& id2)
4605e44e3d8SAppaRao Puli {
46162598e31SEd Tanous BMCWEB_LOG_DEBUG("Subscription ID: {}", id2);
4625e44e3d8SAppaRao Puli subId = id2;
4635e44e3d8SAppaRao Puli }
4645e44e3d8SAppaRao Puli
getSubscriptionId()4655e44e3d8SAppaRao Puli std::string getSubscriptionId()
4665e44e3d8SAppaRao Puli {
4675e44e3d8SAppaRao Puli return subId;
4685e44e3d8SAppaRao Puli }
4695e44e3d8SAppaRao Puli
matchSseId(const crow::sse_socket::Connection & thisConn)4705e44e3d8SAppaRao Puli bool matchSseId(const crow::sse_socket::Connection& thisConn)
4715e44e3d8SAppaRao Puli {
4725e44e3d8SAppaRao Puli return &thisConn == sseConn;
4735e44e3d8SAppaRao Puli }
4745e44e3d8SAppaRao Puli
475b52664e2SAppaRao Puli private:
4765e44e3d8SAppaRao Puli std::string subId;
477d14a48ffSCarson Labrado uint64_t eventSeqNum = 1;
478a716aa74SEd Tanous boost::urls::url host;
479d14a48ffSCarson Labrado std::shared_ptr<crow::ConnectionPolicy> policy;
4805e44e3d8SAppaRao Puli crow::sse_socket::Connection* sseConn = nullptr;
4815e44e3d8SAppaRao Puli std::optional<crow::HttpClient> client;
482b52664e2SAppaRao Puli std::string path;
483b52664e2SAppaRao Puli std::string uriProto;
484a7a80296SCarson Labrado
485a7a80296SCarson Labrado // Check used to indicate what response codes are valid as part of our retry
486a7a80296SCarson Labrado // policy. 2XX is considered acceptable
retryRespHandler(unsigned int respCode)487a7a80296SCarson Labrado static boost::system::error_code retryRespHandler(unsigned int respCode)
488a7a80296SCarson Labrado {
48962598e31SEd Tanous BMCWEB_LOG_DEBUG(
49062598e31SEd Tanous "Checking response code validity for SubscriptionEvent");
491a7a80296SCarson Labrado if ((respCode < 200) || (respCode >= 300))
492a7a80296SCarson Labrado {
493a7a80296SCarson Labrado return boost::system::errc::make_error_code(
494a7a80296SCarson Labrado boost::system::errc::result_out_of_range);
495a7a80296SCarson Labrado }
496a7a80296SCarson Labrado
497a7a80296SCarson Labrado // Return 0 if the response code is valid
498a7a80296SCarson Labrado return boost::system::errc::make_error_code(
499a7a80296SCarson Labrado boost::system::errc::success);
5009fa6d147SNan Zhou }
501b52664e2SAppaRao Puli };
502b52664e2SAppaRao Puli
503b52664e2SAppaRao Puli class EventServiceManager
504b52664e2SAppaRao Puli {
505b52664e2SAppaRao Puli private:
506d3a9e084SEd Tanous bool serviceEnabled = false;
507d3a9e084SEd Tanous uint32_t retryAttempts = 0;
508d3a9e084SEd Tanous uint32_t retryTimeoutInterval = 0;
5097d1cc387SAppaRao Puli
5102558979cSP Dheeraj Srujan Kumar std::streampos redfishLogFilePosition{0};
5119f616dd1SEd Tanous size_t noOfEventLogSubscribers{0};
5129f616dd1SEd Tanous size_t noOfMetricReportSubscribers{0};
51359d494eeSPatrick Williams std::shared_ptr<sdbusplus::bus::match_t> matchTelemetryMonitor;
514b52664e2SAppaRao Puli boost::container::flat_map<std::string, std::shared_ptr<Subscription>>
515b52664e2SAppaRao Puli subscriptionsMap;
516b52664e2SAppaRao Puli
5179f616dd1SEd Tanous uint64_t eventId{1};
51896330b99SSunitha Harish
519f8ca6d79SEd Tanous boost::asio::io_context& ioc;
520f8ca6d79SEd Tanous
521b52664e2SAppaRao Puli public:
5229f616dd1SEd Tanous EventServiceManager(const EventServiceManager&) = delete;
5239f616dd1SEd Tanous EventServiceManager& operator=(const EventServiceManager&) = delete;
5249f616dd1SEd Tanous EventServiceManager(EventServiceManager&&) = delete;
5259f616dd1SEd Tanous EventServiceManager& operator=(EventServiceManager&&) = delete;
526ecd6a3a2SEd Tanous ~EventServiceManager() = default;
5279f616dd1SEd Tanous
EventServiceManager(boost::asio::io_context & iocIn)528f8ca6d79SEd Tanous explicit EventServiceManager(boost::asio::io_context& iocIn) : ioc(iocIn)
529b52664e2SAppaRao Puli {
530f8ca6d79SEd Tanous // Load config from persist store.
531f8ca6d79SEd Tanous initConfig();
532f8ca6d79SEd Tanous }
533f8ca6d79SEd Tanous
534f8ca6d79SEd Tanous static EventServiceManager&
getInstance(boost::asio::io_context * ioc=nullptr)535f8ca6d79SEd Tanous getInstance(boost::asio::io_context* ioc = nullptr)
536f8ca6d79SEd Tanous {
537f8ca6d79SEd Tanous static EventServiceManager handler(*ioc);
538b52664e2SAppaRao Puli return handler;
539b52664e2SAppaRao Puli }
540b52664e2SAppaRao Puli
initConfig()5411bf712bcSAyushi Smriti void initConfig()
5421bf712bcSAyushi Smriti {
54328afb49cSJunLin Chen loadOldBehavior();
5441bf712bcSAyushi Smriti
54528afb49cSJunLin Chen persistent_data::EventServiceConfig eventServiceConfig =
54628afb49cSJunLin Chen persistent_data::EventServiceStore::getInstance()
54728afb49cSJunLin Chen .getEventServiceConfig();
5481bf712bcSAyushi Smriti
54928afb49cSJunLin Chen serviceEnabled = eventServiceConfig.enabled;
55028afb49cSJunLin Chen retryAttempts = eventServiceConfig.retryAttempts;
55128afb49cSJunLin Chen retryTimeoutInterval = eventServiceConfig.retryTimeoutInterval;
5521bf712bcSAyushi Smriti
55328afb49cSJunLin Chen for (const auto& it : persistent_data::EventServiceStore::getInstance()
55428afb49cSJunLin Chen .subscriptionsConfigMap)
5551bf712bcSAyushi Smriti {
55628afb49cSJunLin Chen std::shared_ptr<persistent_data::UserSubscription> newSub =
55728afb49cSJunLin Chen it.second;
5584bbf237fSAppaRao Puli
5596fd29553SEd Tanous boost::system::result<boost::urls::url> url =
560a716aa74SEd Tanous boost::urls::parse_absolute_uri(newSub->destinationUrl);
5611bf712bcSAyushi Smriti
562a716aa74SEd Tanous if (!url)
5631bf712bcSAyushi Smriti {
56462598e31SEd Tanous BMCWEB_LOG_ERROR(
56562598e31SEd Tanous "Failed to validate and split destination url");
5661bf712bcSAyushi Smriti continue;
5671bf712bcSAyushi Smriti }
5681bf712bcSAyushi Smriti std::shared_ptr<Subscription> subValue =
569a716aa74SEd Tanous std::make_shared<Subscription>(*url, ioc);
5701bf712bcSAyushi Smriti
57128afb49cSJunLin Chen subValue->id = newSub->id;
57228afb49cSJunLin Chen subValue->destinationUrl = newSub->destinationUrl;
57328afb49cSJunLin Chen subValue->protocol = newSub->protocol;
57428afb49cSJunLin Chen subValue->retryPolicy = newSub->retryPolicy;
57528afb49cSJunLin Chen subValue->customText = newSub->customText;
57628afb49cSJunLin Chen subValue->eventFormatType = newSub->eventFormatType;
57728afb49cSJunLin Chen subValue->subscriptionType = newSub->subscriptionType;
57828afb49cSJunLin Chen subValue->registryMsgIds = newSub->registryMsgIds;
57928afb49cSJunLin Chen subValue->registryPrefixes = newSub->registryPrefixes;
58028afb49cSJunLin Chen subValue->resourceTypes = newSub->resourceTypes;
58128afb49cSJunLin Chen subValue->httpHeaders = newSub->httpHeaders;
58228afb49cSJunLin Chen subValue->metricReportDefinitions = newSub->metricReportDefinitions;
5831bf712bcSAyushi Smriti
58428afb49cSJunLin Chen if (subValue->id.empty())
5851bf712bcSAyushi Smriti {
58662598e31SEd Tanous BMCWEB_LOG_ERROR("Failed to add subscription");
5871bf712bcSAyushi Smriti }
58828afb49cSJunLin Chen subscriptionsMap.insert(std::pair(subValue->id, subValue));
58928afb49cSJunLin Chen
59028afb49cSJunLin Chen updateNoOfSubscribersCount();
59128afb49cSJunLin Chen
59283328316SEd Tanous if constexpr (!BMCWEB_REDFISH_DBUS_LOG)
59383328316SEd Tanous {
5942558979cSP Dheeraj Srujan Kumar cacheRedfishLogFile();
59583328316SEd Tanous }
5962558979cSP Dheeraj Srujan Kumar
59728afb49cSJunLin Chen // Update retry configuration.
59828afb49cSJunLin Chen subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
5991bf712bcSAyushi Smriti }
6001bf712bcSAyushi Smriti }
6011bf712bcSAyushi Smriti
loadOldBehavior()60256d2396dSEd Tanous static void loadOldBehavior()
603b52664e2SAppaRao Puli {
60428afb49cSJunLin Chen std::ifstream eventConfigFile(eventServiceFile);
60528afb49cSJunLin Chen if (!eventConfigFile.good())
6061bf712bcSAyushi Smriti {
60762598e31SEd Tanous BMCWEB_LOG_DEBUG("Old eventService config not exist");
60828afb49cSJunLin Chen return;
60928afb49cSJunLin Chen }
61028afb49cSJunLin Chen auto jsonData = nlohmann::json::parse(eventConfigFile, nullptr, false);
61128afb49cSJunLin Chen if (jsonData.is_discarded())
6124bbf237fSAppaRao Puli {
61362598e31SEd Tanous BMCWEB_LOG_ERROR("Old eventService config parse error.");
61428afb49cSJunLin Chen return;
61528afb49cSJunLin Chen }
61628afb49cSJunLin Chen
617*0bdda665SEd Tanous const nlohmann::json::object_t* obj =
618*0bdda665SEd Tanous jsonData.get_ptr<const nlohmann::json::object_t*>();
619*0bdda665SEd Tanous for (const auto& item : *obj)
62028afb49cSJunLin Chen {
621*0bdda665SEd Tanous if (item.first == "Configuration")
62228afb49cSJunLin Chen {
62328afb49cSJunLin Chen persistent_data::EventServiceStore::getInstance()
62428afb49cSJunLin Chen .getEventServiceConfig()
625*0bdda665SEd Tanous .fromJson(item.second);
62628afb49cSJunLin Chen }
627*0bdda665SEd Tanous else if (item.first == "Subscriptions")
62828afb49cSJunLin Chen {
629*0bdda665SEd Tanous for (const auto& elem : item.second)
63028afb49cSJunLin Chen {
63128afb49cSJunLin Chen std::shared_ptr<persistent_data::UserSubscription>
63228afb49cSJunLin Chen newSubscription =
63328afb49cSJunLin Chen persistent_data::UserSubscription::fromJson(elem,
63428afb49cSJunLin Chen true);
63528afb49cSJunLin Chen if (newSubscription == nullptr)
63628afb49cSJunLin Chen {
63762598e31SEd Tanous BMCWEB_LOG_ERROR("Problem reading subscription "
63862598e31SEd Tanous "from old persistent store");
6394bbf237fSAppaRao Puli continue;
6404bbf237fSAppaRao Puli }
6411bf712bcSAyushi Smriti
64228afb49cSJunLin Chen std::uniform_int_distribution<uint32_t> dist(0);
64328afb49cSJunLin Chen bmcweb::OpenSSLGenerator gen;
6441bf712bcSAyushi Smriti
64528afb49cSJunLin Chen std::string id;
6461bf712bcSAyushi Smriti
64728afb49cSJunLin Chen int retry = 3;
648e662eae8SEd Tanous while (retry != 0)
6491bf712bcSAyushi Smriti {
65028afb49cSJunLin Chen id = std::to_string(dist(gen));
65128afb49cSJunLin Chen if (gen.error())
6527d1cc387SAppaRao Puli {
65328afb49cSJunLin Chen retry = 0;
65428afb49cSJunLin Chen break;
65528afb49cSJunLin Chen }
65628afb49cSJunLin Chen newSubscription->id = id;
65728afb49cSJunLin Chen auto inserted =
65828afb49cSJunLin Chen persistent_data::EventServiceStore::getInstance()
65928afb49cSJunLin Chen .subscriptionsConfigMap.insert(
66028afb49cSJunLin Chen std::pair(id, newSubscription));
66128afb49cSJunLin Chen if (inserted.second)
66228afb49cSJunLin Chen {
66328afb49cSJunLin Chen break;
66428afb49cSJunLin Chen }
66528afb49cSJunLin Chen --retry;
6667d1cc387SAppaRao Puli }
6677d1cc387SAppaRao Puli
66828afb49cSJunLin Chen if (retry <= 0)
66928afb49cSJunLin Chen {
67062598e31SEd Tanous BMCWEB_LOG_ERROR(
67162598e31SEd Tanous "Failed to generate random number from old "
67262598e31SEd Tanous "persistent store");
67328afb49cSJunLin Chen continue;
67428afb49cSJunLin Chen }
67528afb49cSJunLin Chen }
67628afb49cSJunLin Chen }
67728afb49cSJunLin Chen
67828afb49cSJunLin Chen persistent_data::getConfig().writeData();
6794c521c3cSEd Tanous std::error_code ec;
6804c521c3cSEd Tanous std::filesystem::remove(eventServiceFile, ec);
6814c521c3cSEd Tanous if (ec)
6824c521c3cSEd Tanous {
6834c521c3cSEd Tanous BMCWEB_LOG_DEBUG(
6844c521c3cSEd Tanous "Failed to remove old event service file. Ignoring");
6854c521c3cSEd Tanous }
6864c521c3cSEd Tanous else
6874c521c3cSEd Tanous {
68862598e31SEd Tanous BMCWEB_LOG_DEBUG("Remove old eventservice config");
68928afb49cSJunLin Chen }
69028afb49cSJunLin Chen }
6914c521c3cSEd Tanous }
69228afb49cSJunLin Chen
updateSubscriptionData() const6939eb808c1SEd Tanous void updateSubscriptionData() const
69428afb49cSJunLin Chen {
69528afb49cSJunLin Chen persistent_data::EventServiceStore::getInstance()
69628afb49cSJunLin Chen .eventServiceConfig.enabled = serviceEnabled;
69728afb49cSJunLin Chen persistent_data::EventServiceStore::getInstance()
69828afb49cSJunLin Chen .eventServiceConfig.retryAttempts = retryAttempts;
69928afb49cSJunLin Chen persistent_data::EventServiceStore::getInstance()
70028afb49cSJunLin Chen .eventServiceConfig.retryTimeoutInterval = retryTimeoutInterval;
70128afb49cSJunLin Chen
70228afb49cSJunLin Chen persistent_data::getConfig().writeData();
70328afb49cSJunLin Chen }
70428afb49cSJunLin Chen
setEventServiceConfig(const persistent_data::EventServiceConfig & cfg)70528afb49cSJunLin Chen void setEventServiceConfig(const persistent_data::EventServiceConfig& cfg)
7067d1cc387SAppaRao Puli {
7077d1cc387SAppaRao Puli bool updateConfig = false;
708fe44eb0bSAyushi Smriti bool updateRetryCfg = false;
7097d1cc387SAppaRao Puli
71028afb49cSJunLin Chen if (serviceEnabled != cfg.enabled)
7117d1cc387SAppaRao Puli {
71228afb49cSJunLin Chen serviceEnabled = cfg.enabled;
713e662eae8SEd Tanous if (serviceEnabled && noOfMetricReportSubscribers != 0U)
7147d1cc387SAppaRao Puli {
7157d1cc387SAppaRao Puli registerMetricReportSignal();
7167d1cc387SAppaRao Puli }
7177d1cc387SAppaRao Puli else
7187d1cc387SAppaRao Puli {
7197d1cc387SAppaRao Puli unregisterMetricReportSignal();
7207d1cc387SAppaRao Puli }
7217d1cc387SAppaRao Puli updateConfig = true;
7227d1cc387SAppaRao Puli }
7237d1cc387SAppaRao Puli
72428afb49cSJunLin Chen if (retryAttempts != cfg.retryAttempts)
7257d1cc387SAppaRao Puli {
72628afb49cSJunLin Chen retryAttempts = cfg.retryAttempts;
7277d1cc387SAppaRao Puli updateConfig = true;
728fe44eb0bSAyushi Smriti updateRetryCfg = true;
7297d1cc387SAppaRao Puli }
7307d1cc387SAppaRao Puli
73128afb49cSJunLin Chen if (retryTimeoutInterval != cfg.retryTimeoutInterval)
7327d1cc387SAppaRao Puli {
73328afb49cSJunLin Chen retryTimeoutInterval = cfg.retryTimeoutInterval;
7347d1cc387SAppaRao Puli updateConfig = true;
735fe44eb0bSAyushi Smriti updateRetryCfg = true;
7367d1cc387SAppaRao Puli }
7377d1cc387SAppaRao Puli
7387d1cc387SAppaRao Puli if (updateConfig)
7397d1cc387SAppaRao Puli {
7407d1cc387SAppaRao Puli updateSubscriptionData();
7417d1cc387SAppaRao Puli }
742fe44eb0bSAyushi Smriti
743fe44eb0bSAyushi Smriti if (updateRetryCfg)
744fe44eb0bSAyushi Smriti {
745fe44eb0bSAyushi Smriti // Update the changed retry config to all subscriptions
746fe44eb0bSAyushi Smriti for (const auto& it :
747fe44eb0bSAyushi Smriti EventServiceManager::getInstance().subscriptionsMap)
748fe44eb0bSAyushi Smriti {
7495e44e3d8SAppaRao Puli Subscription& entry = *it.second;
7505e44e3d8SAppaRao Puli entry.updateRetryConfig(retryAttempts, retryTimeoutInterval);
751fe44eb0bSAyushi Smriti }
752fe44eb0bSAyushi Smriti }
7537d1cc387SAppaRao Puli }
7547d1cc387SAppaRao Puli
updateNoOfSubscribersCount()7557d1cc387SAppaRao Puli void updateNoOfSubscribersCount()
7567d1cc387SAppaRao Puli {
7577d1cc387SAppaRao Puli size_t eventLogSubCount = 0;
7587d1cc387SAppaRao Puli size_t metricReportSubCount = 0;
7597d1cc387SAppaRao Puli for (const auto& it : subscriptionsMap)
7607d1cc387SAppaRao Puli {
7617d1cc387SAppaRao Puli std::shared_ptr<Subscription> entry = it.second;
7627d1cc387SAppaRao Puli if (entry->eventFormatType == eventFormatType)
7637d1cc387SAppaRao Puli {
7647d1cc387SAppaRao Puli eventLogSubCount++;
7657d1cc387SAppaRao Puli }
7667d1cc387SAppaRao Puli else if (entry->eventFormatType == metricReportFormatType)
7677d1cc387SAppaRao Puli {
7687d1cc387SAppaRao Puli metricReportSubCount++;
7697d1cc387SAppaRao Puli }
7707d1cc387SAppaRao Puli }
7717d1cc387SAppaRao Puli
7727d1cc387SAppaRao Puli noOfEventLogSubscribers = eventLogSubCount;
7737d1cc387SAppaRao Puli if (noOfMetricReportSubscribers != metricReportSubCount)
7747d1cc387SAppaRao Puli {
7757d1cc387SAppaRao Puli noOfMetricReportSubscribers = metricReportSubCount;
776e662eae8SEd Tanous if (noOfMetricReportSubscribers != 0U)
7777d1cc387SAppaRao Puli {
7787d1cc387SAppaRao Puli registerMetricReportSignal();
7797d1cc387SAppaRao Puli }
7807d1cc387SAppaRao Puli else
7817d1cc387SAppaRao Puli {
7827d1cc387SAppaRao Puli unregisterMetricReportSignal();
7837d1cc387SAppaRao Puli }
7847d1cc387SAppaRao Puli }
7857d1cc387SAppaRao Puli }
7867d1cc387SAppaRao Puli
getSubscription(const std::string & id)787b52664e2SAppaRao Puli std::shared_ptr<Subscription> getSubscription(const std::string& id)
788b52664e2SAppaRao Puli {
789b52664e2SAppaRao Puli auto obj = subscriptionsMap.find(id);
790b52664e2SAppaRao Puli if (obj == subscriptionsMap.end())
791b52664e2SAppaRao Puli {
79262598e31SEd Tanous BMCWEB_LOG_ERROR("No subscription exist with ID:{}", id);
793b52664e2SAppaRao Puli return nullptr;
794b52664e2SAppaRao Puli }
795b52664e2SAppaRao Puli std::shared_ptr<Subscription> subValue = obj->second;
796b52664e2SAppaRao Puli return subValue;
797b52664e2SAppaRao Puli }
798b52664e2SAppaRao Puli
addSubscription(const std::shared_ptr<Subscription> & subValue,const bool updateFile=true)799b5a76932SEd Tanous std::string addSubscription(const std::shared_ptr<Subscription>& subValue,
8001bf712bcSAyushi Smriti const bool updateFile = true)
801b52664e2SAppaRao Puli {
802fc76b8acSEd Tanous std::uniform_int_distribution<uint32_t> dist(0);
803fc76b8acSEd Tanous bmcweb::OpenSSLGenerator gen;
804fc76b8acSEd Tanous
805b52664e2SAppaRao Puli std::string id;
806b52664e2SAppaRao Puli
807b52664e2SAppaRao Puli int retry = 3;
808e662eae8SEd Tanous while (retry != 0)
809b52664e2SAppaRao Puli {
810fc76b8acSEd Tanous id = std::to_string(dist(gen));
811fc76b8acSEd Tanous if (gen.error())
812fc76b8acSEd Tanous {
813fc76b8acSEd Tanous retry = 0;
814fc76b8acSEd Tanous break;
815fc76b8acSEd Tanous }
816b52664e2SAppaRao Puli auto inserted = subscriptionsMap.insert(std::pair(id, subValue));
817b52664e2SAppaRao Puli if (inserted.second)
818b52664e2SAppaRao Puli {
819b52664e2SAppaRao Puli break;
820b52664e2SAppaRao Puli }
821b52664e2SAppaRao Puli --retry;
82223a21a1cSEd Tanous }
823b52664e2SAppaRao Puli
824b52664e2SAppaRao Puli if (retry <= 0)
825b52664e2SAppaRao Puli {
82662598e31SEd Tanous BMCWEB_LOG_ERROR("Failed to generate random number");
827abb93cddSEd Tanous return "";
828b52664e2SAppaRao Puli }
829b52664e2SAppaRao Puli
83028afb49cSJunLin Chen std::shared_ptr<persistent_data::UserSubscription> newSub =
83128afb49cSJunLin Chen std::make_shared<persistent_data::UserSubscription>();
83228afb49cSJunLin Chen newSub->id = id;
83328afb49cSJunLin Chen newSub->destinationUrl = subValue->destinationUrl;
83428afb49cSJunLin Chen newSub->protocol = subValue->protocol;
83528afb49cSJunLin Chen newSub->retryPolicy = subValue->retryPolicy;
83628afb49cSJunLin Chen newSub->customText = subValue->customText;
83728afb49cSJunLin Chen newSub->eventFormatType = subValue->eventFormatType;
83828afb49cSJunLin Chen newSub->subscriptionType = subValue->subscriptionType;
83928afb49cSJunLin Chen newSub->registryMsgIds = subValue->registryMsgIds;
84028afb49cSJunLin Chen newSub->registryPrefixes = subValue->registryPrefixes;
84128afb49cSJunLin Chen newSub->resourceTypes = subValue->resourceTypes;
84228afb49cSJunLin Chen newSub->httpHeaders = subValue->httpHeaders;
84328afb49cSJunLin Chen newSub->metricReportDefinitions = subValue->metricReportDefinitions;
84428afb49cSJunLin Chen persistent_data::EventServiceStore::getInstance()
84528afb49cSJunLin Chen .subscriptionsConfigMap.emplace(newSub->id, newSub);
84628afb49cSJunLin Chen
8477d1cc387SAppaRao Puli updateNoOfSubscribersCount();
8481bf712bcSAyushi Smriti
8491bf712bcSAyushi Smriti if (updateFile)
8501bf712bcSAyushi Smriti {
851b52664e2SAppaRao Puli updateSubscriptionData();
8521bf712bcSAyushi Smriti }
8537f4eb588SAppaRao Puli
85483328316SEd Tanous if constexpr (!BMCWEB_REDFISH_DBUS_LOG)
85583328316SEd Tanous {
8562558979cSP Dheeraj Srujan Kumar if (redfishLogFilePosition != 0)
8577f4eb588SAppaRao Puli {
8582558979cSP Dheeraj Srujan Kumar cacheRedfishLogFile();
8597f4eb588SAppaRao Puli }
86083328316SEd Tanous }
861fe44eb0bSAyushi Smriti // Update retry configuration.
862fe44eb0bSAyushi Smriti subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
863fe44eb0bSAyushi Smriti
8645e44e3d8SAppaRao Puli // Set Subscription ID for back trace
8655e44e3d8SAppaRao Puli subValue->setSubscriptionId(id);
866b52664e2SAppaRao Puli return id;
867b52664e2SAppaRao Puli }
868b52664e2SAppaRao Puli
isSubscriptionExist(const std::string & id)869b52664e2SAppaRao Puli bool isSubscriptionExist(const std::string& id)
870b52664e2SAppaRao Puli {
871b52664e2SAppaRao Puli auto obj = subscriptionsMap.find(id);
87255f79e6fSEd Tanous return obj != subscriptionsMap.end();
873b52664e2SAppaRao Puli }
874b52664e2SAppaRao Puli
deleteSubscription(const std::string & id)875b52664e2SAppaRao Puli void deleteSubscription(const std::string& id)
876b52664e2SAppaRao Puli {
877b52664e2SAppaRao Puli auto obj = subscriptionsMap.find(id);
878b52664e2SAppaRao Puli if (obj != subscriptionsMap.end())
879b52664e2SAppaRao Puli {
880b52664e2SAppaRao Puli subscriptionsMap.erase(obj);
88128afb49cSJunLin Chen auto obj2 = persistent_data::EventServiceStore::getInstance()
88228afb49cSJunLin Chen .subscriptionsConfigMap.find(id);
88328afb49cSJunLin Chen persistent_data::EventServiceStore::getInstance()
88428afb49cSJunLin Chen .subscriptionsConfigMap.erase(obj2);
8857d1cc387SAppaRao Puli updateNoOfSubscribersCount();
886b52664e2SAppaRao Puli updateSubscriptionData();
887b52664e2SAppaRao Puli }
888b52664e2SAppaRao Puli }
889b52664e2SAppaRao Puli
deleteSseSubscription(const crow::sse_socket::Connection & thisConn)8905e44e3d8SAppaRao Puli void deleteSseSubscription(const crow::sse_socket::Connection& thisConn)
8915e44e3d8SAppaRao Puli {
892bdbfae2aSEd Tanous for (auto it = subscriptionsMap.begin(); it != subscriptionsMap.end();)
8935e44e3d8SAppaRao Puli {
894bdbfae2aSEd Tanous std::shared_ptr<Subscription> entry = it->second;
8955e44e3d8SAppaRao Puli bool entryIsThisConn = entry->matchSseId(thisConn);
8965e44e3d8SAppaRao Puli if (entryIsThisConn)
8975e44e3d8SAppaRao Puli {
8985e44e3d8SAppaRao Puli persistent_data::EventServiceStore::getInstance()
8995e44e3d8SAppaRao Puli .subscriptionsConfigMap.erase(
900bdbfae2aSEd Tanous it->second->getSubscriptionId());
901bdbfae2aSEd Tanous it = subscriptionsMap.erase(it);
9025e44e3d8SAppaRao Puli return;
9035e44e3d8SAppaRao Puli }
904bdbfae2aSEd Tanous it++;
9055e44e3d8SAppaRao Puli }
9065e44e3d8SAppaRao Puli }
9075e44e3d8SAppaRao Puli
getNumberOfSubscriptions() const9085e44e3d8SAppaRao Puli size_t getNumberOfSubscriptions() const
909b52664e2SAppaRao Puli {
910b52664e2SAppaRao Puli return subscriptionsMap.size();
911b52664e2SAppaRao Puli }
912b52664e2SAppaRao Puli
getNumberOfSSESubscriptions() const9135e44e3d8SAppaRao Puli size_t getNumberOfSSESubscriptions() const
9145e44e3d8SAppaRao Puli {
9153544d2a7SEd Tanous auto size = std::ranges::count_if(
9163544d2a7SEd Tanous subscriptionsMap,
9175e44e3d8SAppaRao Puli [](const std::pair<std::string, std::shared_ptr<Subscription>>&
9185e44e3d8SAppaRao Puli entry) {
9195e44e3d8SAppaRao Puli return (entry.second->subscriptionType == subscriptionTypeSSE);
9205e44e3d8SAppaRao Puli });
9215e44e3d8SAppaRao Puli return static_cast<size_t>(size);
9225e44e3d8SAppaRao Puli }
9235e44e3d8SAppaRao Puli
getAllIDs()924b52664e2SAppaRao Puli std::vector<std::string> getAllIDs()
925b52664e2SAppaRao Puli {
926b52664e2SAppaRao Puli std::vector<std::string> idList;
927b52664e2SAppaRao Puli for (const auto& it : subscriptionsMap)
928b52664e2SAppaRao Puli {
929b52664e2SAppaRao Puli idList.emplace_back(it.first);
930b52664e2SAppaRao Puli }
931b52664e2SAppaRao Puli return idList;
932b52664e2SAppaRao Puli }
933b52664e2SAppaRao Puli
sendTestEventLog()9346ba8c82eSsunharis_in bool sendTestEventLog()
9350b4bdd93SAppaRao Puli {
9365e44e3d8SAppaRao Puli for (const auto& it : subscriptionsMap)
9370b4bdd93SAppaRao Puli {
9380b4bdd93SAppaRao Puli std::shared_ptr<Subscription> entry = it.second;
9396ba8c82eSsunharis_in if (!entry->sendTestEventLog())
9406ba8c82eSsunharis_in {
9416ba8c82eSsunharis_in return false;
9420b4bdd93SAppaRao Puli }
9430b4bdd93SAppaRao Puli }
9446ba8c82eSsunharis_in return true;
9456ba8c82eSsunharis_in }
946e9a14131SAppaRao Puli
sendEvent(nlohmann::json eventMessage,const std::string & origin,const std::string & resType)947613dabeaSEd Tanous void sendEvent(nlohmann::json eventMessage, const std::string& origin,
948613dabeaSEd Tanous const std::string& resType)
94996330b99SSunitha Harish {
950dbb59d4dSEd Tanous if (!serviceEnabled || (noOfEventLogSubscribers == 0U))
9516ba8c82eSsunharis_in {
95262598e31SEd Tanous BMCWEB_LOG_DEBUG("EventService disabled or no Subscriptions.");
9536ba8c82eSsunharis_in return;
9546ba8c82eSsunharis_in }
95596330b99SSunitha Harish nlohmann::json eventRecord = nlohmann::json::array();
95696330b99SSunitha Harish
957613dabeaSEd Tanous eventMessage["EventId"] = eventId;
958613dabeaSEd Tanous // MemberId is 0 : since we are sending one event record.
959613dabeaSEd Tanous eventMessage["MemberId"] = 0;
960613dabeaSEd Tanous eventMessage["EventTimestamp"] =
961613dabeaSEd Tanous redfish::time_utils::getDateTimeOffsetNow().first;
962613dabeaSEd Tanous eventMessage["OriginOfCondition"] = origin;
963613dabeaSEd Tanous
964613dabeaSEd Tanous eventRecord.emplace_back(std::move(eventMessage));
96596330b99SSunitha Harish
9665e44e3d8SAppaRao Puli for (const auto& it : subscriptionsMap)
96796330b99SSunitha Harish {
96896330b99SSunitha Harish std::shared_ptr<Subscription> entry = it.second;
96996330b99SSunitha Harish bool isSubscribed = false;
97096330b99SSunitha Harish // Search the resourceTypes list for the subscription.
97196330b99SSunitha Harish // If resourceTypes list is empty, don't filter events
97296330b99SSunitha Harish // send everything.
97326f6976fSEd Tanous if (!entry->resourceTypes.empty())
97496330b99SSunitha Harish {
9753174e4dfSEd Tanous for (const auto& resource : entry->resourceTypes)
97696330b99SSunitha Harish {
97796330b99SSunitha Harish if (resType == resource)
97896330b99SSunitha Harish {
97962598e31SEd Tanous BMCWEB_LOG_INFO(
98062598e31SEd Tanous "ResourceType {} found in the subscribed list",
98162598e31SEd Tanous resource);
98296330b99SSunitha Harish isSubscribed = true;
98396330b99SSunitha Harish break;
98496330b99SSunitha Harish }
98596330b99SSunitha Harish }
98696330b99SSunitha Harish }
98796330b99SSunitha Harish else // resourceTypes list is empty.
98896330b99SSunitha Harish {
98996330b99SSunitha Harish isSubscribed = true;
99096330b99SSunitha Harish }
99196330b99SSunitha Harish if (isSubscribed)
99296330b99SSunitha Harish {
993613dabeaSEd Tanous nlohmann::json msgJson;
994613dabeaSEd Tanous
995613dabeaSEd Tanous msgJson["@odata.type"] = "#Event.v1_4_0.Event";
996613dabeaSEd Tanous msgJson["Name"] = "Event Log";
997613dabeaSEd Tanous msgJson["Id"] = eventId;
998613dabeaSEd Tanous msgJson["Events"] = eventRecord;
999f52c03c1SCarson Labrado
1000f52c03c1SCarson Labrado std::string strMsg = msgJson.dump(
1001f52c03c1SCarson Labrado 2, ' ', true, nlohmann::json::error_handler_t::replace);
10025e44e3d8SAppaRao Puli entry->sendEvent(std::move(strMsg));
10038ece0e45SEd Tanous eventId++; // increment the eventId
100496330b99SSunitha Harish }
100596330b99SSunitha Harish else
100696330b99SSunitha Harish {
100762598e31SEd Tanous BMCWEB_LOG_INFO("Not subscribed to this resource");
100896330b99SSunitha Harish }
100996330b99SSunitha Harish }
101096330b99SSunitha Harish }
101196330b99SSunitha Harish
resetRedfishFilePosition()10122558979cSP Dheeraj Srujan Kumar void resetRedfishFilePosition()
10137f4eb588SAppaRao Puli {
10142558979cSP Dheeraj Srujan Kumar // Control would be here when Redfish file is created.
10152558979cSP Dheeraj Srujan Kumar // Reset File Position as new file is created
10162558979cSP Dheeraj Srujan Kumar redfishLogFilePosition = 0;
10172558979cSP Dheeraj Srujan Kumar }
10182558979cSP Dheeraj Srujan Kumar
cacheRedfishLogFile()10192558979cSP Dheeraj Srujan Kumar void cacheRedfishLogFile()
10202558979cSP Dheeraj Srujan Kumar {
10212558979cSP Dheeraj Srujan Kumar // Open the redfish file and read till the last record.
10222558979cSP Dheeraj Srujan Kumar
10237f4eb588SAppaRao Puli std::ifstream logStream(redfishEventLogFile);
10247f4eb588SAppaRao Puli if (!logStream.good())
10257f4eb588SAppaRao Puli {
102662598e31SEd Tanous BMCWEB_LOG_ERROR(" Redfish log file open failed ");
10277f4eb588SAppaRao Puli return;
10287f4eb588SAppaRao Puli }
10297f4eb588SAppaRao Puli std::string logEntry;
10307f4eb588SAppaRao Puli while (std::getline(logStream, logEntry))
10317f4eb588SAppaRao Puli {
10322558979cSP Dheeraj Srujan Kumar redfishLogFilePosition = logStream.tellg();
10337f4eb588SAppaRao Puli }
10347f4eb588SAppaRao Puli }
10357f4eb588SAppaRao Puli
readEventLogsFromFile()10367f4eb588SAppaRao Puli void readEventLogsFromFile()
10377f4eb588SAppaRao Puli {
10387f4eb588SAppaRao Puli std::ifstream logStream(redfishEventLogFile);
10397f4eb588SAppaRao Puli if (!logStream.good())
10407f4eb588SAppaRao Puli {
104162598e31SEd Tanous BMCWEB_LOG_ERROR(" Redfish log file open failed");
10427f4eb588SAppaRao Puli return;
10437f4eb588SAppaRao Puli }
10447f4eb588SAppaRao Puli
10457f4eb588SAppaRao Puli std::vector<EventLogObjectsType> eventRecords;
10467f4eb588SAppaRao Puli
10477f4eb588SAppaRao Puli std::string logEntry;
10482558979cSP Dheeraj Srujan Kumar
10492558979cSP Dheeraj Srujan Kumar // Get the read pointer to the next log to be read.
10502558979cSP Dheeraj Srujan Kumar logStream.seekg(redfishLogFilePosition);
10512558979cSP Dheeraj Srujan Kumar
10527f4eb588SAppaRao Puli while (std::getline(logStream, logEntry))
10537f4eb588SAppaRao Puli {
10542558979cSP Dheeraj Srujan Kumar // Update Pointer position
10552558979cSP Dheeraj Srujan Kumar redfishLogFilePosition = logStream.tellg();
10562558979cSP Dheeraj Srujan Kumar
10572558979cSP Dheeraj Srujan Kumar std::string idStr;
10582558979cSP Dheeraj Srujan Kumar if (!event_log::getUniqueEntryID(logEntry, idStr))
10597f4eb588SAppaRao Puli {
10607f4eb588SAppaRao Puli continue;
10617f4eb588SAppaRao Puli }
10627f4eb588SAppaRao Puli
1063e662eae8SEd Tanous if (!serviceEnabled || noOfEventLogSubscribers == 0)
10647f4eb588SAppaRao Puli {
10652558979cSP Dheeraj Srujan Kumar // If Service is not enabled, no need to compute
10662558979cSP Dheeraj Srujan Kumar // the remaining items below.
10672558979cSP Dheeraj Srujan Kumar // But, Loop must continue to keep track of Timestamp
10687f4eb588SAppaRao Puli continue;
10697f4eb588SAppaRao Puli }
10707f4eb588SAppaRao Puli
10717f4eb588SAppaRao Puli std::string timestamp;
10727f4eb588SAppaRao Puli std::string messageID;
10735e715de6SAppaRao Puli std::vector<std::string> messageArgs;
10747f4eb588SAppaRao Puli if (event_log::getEventLogParams(logEntry, timestamp, messageID,
10757f4eb588SAppaRao Puli messageArgs) != 0)
10767f4eb588SAppaRao Puli {
107762598e31SEd Tanous BMCWEB_LOG_DEBUG("Read eventLog entry params failed");
10787f4eb588SAppaRao Puli continue;
10797f4eb588SAppaRao Puli }
10807f4eb588SAppaRao Puli
10817f4eb588SAppaRao Puli std::string registryName;
10827f4eb588SAppaRao Puli std::string messageKey;
10837f4eb588SAppaRao Puli event_log::getRegistryAndMessageKey(messageID, registryName,
10847f4eb588SAppaRao Puli messageKey);
10857f4eb588SAppaRao Puli if (registryName.empty() || messageKey.empty())
10867f4eb588SAppaRao Puli {
10877f4eb588SAppaRao Puli continue;
10887f4eb588SAppaRao Puli }
10897f4eb588SAppaRao Puli
10907f4eb588SAppaRao Puli eventRecords.emplace_back(idStr, timestamp, messageID, registryName,
10917f4eb588SAppaRao Puli messageKey, messageArgs);
10927f4eb588SAppaRao Puli }
10937f4eb588SAppaRao Puli
1094e662eae8SEd Tanous if (!serviceEnabled || noOfEventLogSubscribers == 0)
10952558979cSP Dheeraj Srujan Kumar {
109662598e31SEd Tanous BMCWEB_LOG_DEBUG("EventService disabled or no Subscriptions.");
10972558979cSP Dheeraj Srujan Kumar return;
10982558979cSP Dheeraj Srujan Kumar }
10992558979cSP Dheeraj Srujan Kumar
11002558979cSP Dheeraj Srujan Kumar if (eventRecords.empty())
11012558979cSP Dheeraj Srujan Kumar {
11022558979cSP Dheeraj Srujan Kumar // No Records to send
110362598e31SEd Tanous BMCWEB_LOG_DEBUG("No log entries available to be transferred.");
11042558979cSP Dheeraj Srujan Kumar return;
11052558979cSP Dheeraj Srujan Kumar }
11062558979cSP Dheeraj Srujan Kumar
11075e44e3d8SAppaRao Puli for (const auto& it : subscriptionsMap)
11087f4eb588SAppaRao Puli {
11097f4eb588SAppaRao Puli std::shared_ptr<Subscription> entry = it.second;
11107f4eb588SAppaRao Puli if (entry->eventFormatType == "Event")
11117f4eb588SAppaRao Puli {
11127f4eb588SAppaRao Puli entry->filterAndSendEventLogs(eventRecords);
11137f4eb588SAppaRao Puli }
11147f4eb588SAppaRao Puli }
11157f4eb588SAppaRao Puli }
11167f4eb588SAppaRao Puli
watchRedfishEventLogFile()11177f4eb588SAppaRao Puli static void watchRedfishEventLogFile()
11187f4eb588SAppaRao Puli {
11196a9f85f9SAppaRao Puli if (!inotifyConn)
11207f4eb588SAppaRao Puli {
11217f4eb588SAppaRao Puli return;
11227f4eb588SAppaRao Puli }
11237f4eb588SAppaRao Puli
11247f4eb588SAppaRao Puli static std::array<char, 1024> readBuffer;
11257f4eb588SAppaRao Puli
1126002d39b4SEd Tanous inotifyConn->async_read_some(boost::asio::buffer(readBuffer),
11277f4eb588SAppaRao Puli [&](const boost::system::error_code& ec,
11287f4eb588SAppaRao Puli const std::size_t& bytesTransferred) {
11297f4eb588SAppaRao Puli if (ec)
11307f4eb588SAppaRao Puli {
113162598e31SEd Tanous BMCWEB_LOG_ERROR("Callback Error: {}", ec.message());
11327f4eb588SAppaRao Puli return;
11337f4eb588SAppaRao Puli }
11347f4eb588SAppaRao Puli std::size_t index = 0;
1135b792cc56SAppaRao Puli while ((index + iEventSize) <= bytesTransferred)
11367f4eb588SAppaRao Puli {
1137d3a9e084SEd Tanous struct inotify_event event
1138d3a9e084SEd Tanous {};
1139b792cc56SAppaRao Puli std::memcpy(&event, &readBuffer[index], iEventSize);
1140b792cc56SAppaRao Puli if (event.wd == dirWatchDesc)
1141b792cc56SAppaRao Puli {
1142b792cc56SAppaRao Puli if ((event.len == 0) ||
1143b792cc56SAppaRao Puli (index + iEventSize + event.len > bytesTransferred))
1144b792cc56SAppaRao Puli {
1145b792cc56SAppaRao Puli index += (iEventSize + event.len);
1146b792cc56SAppaRao Puli continue;
1147b792cc56SAppaRao Puli }
1148b792cc56SAppaRao Puli
11494f568f74SJiaqing Zhao std::string fileName(&readBuffer[index + iEventSize]);
11504f568f74SJiaqing Zhao if (fileName != "redfish")
1151b792cc56SAppaRao Puli {
1152b792cc56SAppaRao Puli index += (iEventSize + event.len);
1153b792cc56SAppaRao Puli continue;
1154b792cc56SAppaRao Puli }
1155b792cc56SAppaRao Puli
115662598e31SEd Tanous BMCWEB_LOG_DEBUG(
115762598e31SEd Tanous "Redfish log file created/deleted. event.name: {}",
115862598e31SEd Tanous fileName);
1159b792cc56SAppaRao Puli if (event.mask == IN_CREATE)
1160b792cc56SAppaRao Puli {
1161b792cc56SAppaRao Puli if (fileWatchDesc != -1)
1162b792cc56SAppaRao Puli {
116362598e31SEd Tanous BMCWEB_LOG_DEBUG(
116462598e31SEd Tanous "Remove and Add inotify watcher on "
116562598e31SEd Tanous "redfish event log file");
1166016761afSAppaRao Puli // Remove existing inotify watcher and add
1167016761afSAppaRao Puli // with new redfish event log file.
1168016761afSAppaRao Puli inotify_rm_watch(inotifyFd, fileWatchDesc);
1169016761afSAppaRao Puli fileWatchDesc = -1;
1170b792cc56SAppaRao Puli }
1171b792cc56SAppaRao Puli
1172b792cc56SAppaRao Puli fileWatchDesc = inotify_add_watch(
1173b792cc56SAppaRao Puli inotifyFd, redfishEventLogFile, IN_MODIFY);
1174b792cc56SAppaRao Puli if (fileWatchDesc == -1)
1175b792cc56SAppaRao Puli {
117662598e31SEd Tanous BMCWEB_LOG_ERROR("inotify_add_watch failed for "
117762598e31SEd Tanous "redfish log file.");
1178b792cc56SAppaRao Puli return;
1179b792cc56SAppaRao Puli }
1180b792cc56SAppaRao Puli
1181b792cc56SAppaRao Puli EventServiceManager::getInstance()
11822558979cSP Dheeraj Srujan Kumar .resetRedfishFilePosition();
1183b792cc56SAppaRao Puli EventServiceManager::getInstance()
1184b792cc56SAppaRao Puli .readEventLogsFromFile();
1185b792cc56SAppaRao Puli }
1186b792cc56SAppaRao Puli else if ((event.mask == IN_DELETE) ||
1187b792cc56SAppaRao Puli (event.mask == IN_MOVED_TO))
1188b792cc56SAppaRao Puli {
1189b792cc56SAppaRao Puli if (fileWatchDesc != -1)
1190b792cc56SAppaRao Puli {
1191b792cc56SAppaRao Puli inotify_rm_watch(inotifyFd, fileWatchDesc);
1192b792cc56SAppaRao Puli fileWatchDesc = -1;
1193b792cc56SAppaRao Puli }
1194b792cc56SAppaRao Puli }
1195b792cc56SAppaRao Puli }
1196b792cc56SAppaRao Puli else if (event.wd == fileWatchDesc)
1197b792cc56SAppaRao Puli {
1198b792cc56SAppaRao Puli if (event.mask == IN_MODIFY)
11997f4eb588SAppaRao Puli {
12007f4eb588SAppaRao Puli EventServiceManager::getInstance()
12017f4eb588SAppaRao Puli .readEventLogsFromFile();
12027f4eb588SAppaRao Puli }
1203b792cc56SAppaRao Puli }
1204b792cc56SAppaRao Puli index += (iEventSize + event.len);
12057f4eb588SAppaRao Puli }
12067f4eb588SAppaRao Puli
12077f4eb588SAppaRao Puli watchRedfishEventLogFile();
12087f4eb588SAppaRao Puli });
12097f4eb588SAppaRao Puli }
12107f4eb588SAppaRao Puli
startEventLogMonitor(boost::asio::io_context & ioc)12117f4eb588SAppaRao Puli static int startEventLogMonitor(boost::asio::io_context& ioc)
12127f4eb588SAppaRao Puli {
121323a21a1cSEd Tanous inotifyConn.emplace(ioc);
1214b792cc56SAppaRao Puli inotifyFd = inotify_init1(IN_NONBLOCK);
1215b792cc56SAppaRao Puli if (inotifyFd == -1)
12167f4eb588SAppaRao Puli {
121762598e31SEd Tanous BMCWEB_LOG_ERROR("inotify_init1 failed.");
12187f4eb588SAppaRao Puli return -1;
12197f4eb588SAppaRao Puli }
1220b792cc56SAppaRao Puli
1221b792cc56SAppaRao Puli // Add watch on directory to handle redfish event log file
1222b792cc56SAppaRao Puli // create/delete.
1223b792cc56SAppaRao Puli dirWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogDir,
1224b792cc56SAppaRao Puli IN_CREATE | IN_MOVED_TO | IN_DELETE);
1225b792cc56SAppaRao Puli if (dirWatchDesc == -1)
12267f4eb588SAppaRao Puli {
122762598e31SEd Tanous BMCWEB_LOG_ERROR(
122862598e31SEd Tanous "inotify_add_watch failed for event log directory.");
12297f4eb588SAppaRao Puli return -1;
12307f4eb588SAppaRao Puli }
12317f4eb588SAppaRao Puli
1232b792cc56SAppaRao Puli // Watch redfish event log file for modifications.
123389492a15SPatrick Williams fileWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogFile,
123489492a15SPatrick Williams IN_MODIFY);
1235b792cc56SAppaRao Puli if (fileWatchDesc == -1)
1236b792cc56SAppaRao Puli {
123762598e31SEd Tanous BMCWEB_LOG_ERROR("inotify_add_watch failed for redfish log file.");
1238b792cc56SAppaRao Puli // Don't return error if file not exist.
1239b792cc56SAppaRao Puli // Watch on directory will handle create/delete of file.
1240b792cc56SAppaRao Puli }
1241b792cc56SAppaRao Puli
12427f4eb588SAppaRao Puli // monitor redfish event log file
1243b792cc56SAppaRao Puli inotifyConn->assign(inotifyFd);
12447f4eb588SAppaRao Puli watchRedfishEventLogFile();
12457f4eb588SAppaRao Puli
12467f4eb588SAppaRao Puli return 0;
12477f4eb588SAppaRao Puli }
12487f4eb588SAppaRao Puli
getReadingsForReport(sdbusplus::message_t & msg)124959d494eeSPatrick Williams static void getReadingsForReport(sdbusplus::message_t& msg)
1250156d6b00SAppaRao Puli {
125156d2396dSEd Tanous if (msg.is_method_error())
125256d2396dSEd Tanous {
125362598e31SEd Tanous BMCWEB_LOG_ERROR("TelemetryMonitor Signal error");
125456d2396dSEd Tanous return;
125556d2396dSEd Tanous }
125656d2396dSEd Tanous
1257c0353249SWludzik, Jozef sdbusplus::message::object_path path(msg.get_path());
1258c0353249SWludzik, Jozef std::string id = path.filename();
1259c0353249SWludzik, Jozef if (id.empty())
1260156d6b00SAppaRao Puli {
126162598e31SEd Tanous BMCWEB_LOG_ERROR("Failed to get Id from path");
1262156d6b00SAppaRao Puli return;
1263156d6b00SAppaRao Puli }
1264156d6b00SAppaRao Puli
1265c0353249SWludzik, Jozef std::string interface;
1266b9d36b47SEd Tanous dbus::utility::DBusPropertiesMap props;
1267c0353249SWludzik, Jozef std::vector<std::string> invalidProps;
1268c0353249SWludzik, Jozef msg.read(interface, props, invalidProps);
1269c0353249SWludzik, Jozef
12703544d2a7SEd Tanous auto found = std::ranges::find_if(
12713544d2a7SEd Tanous props, [](const auto& x) { return x.first == "Readings"; });
1272c0353249SWludzik, Jozef if (found == props.end())
1273156d6b00SAppaRao Puli {
127462598e31SEd Tanous BMCWEB_LOG_INFO("Failed to get Readings from Report properties");
1275156d6b00SAppaRao Puli return;
1276156d6b00SAppaRao Puli }
1277156d6b00SAppaRao Puli
12781e1e598dSJonathan Doman const telemetry::TimestampReadings* readings =
12791e1e598dSJonathan Doman std::get_if<telemetry::TimestampReadings>(&found->second);
1280e662eae8SEd Tanous if (readings == nullptr)
12811e1e598dSJonathan Doman {
128262598e31SEd Tanous BMCWEB_LOG_INFO("Failed to get Readings from Report properties");
12831e1e598dSJonathan Doman return;
12841e1e598dSJonathan Doman }
12851e1e598dSJonathan Doman
1286156d6b00SAppaRao Puli for (const auto& it :
1287156d6b00SAppaRao Puli EventServiceManager::getInstance().subscriptionsMap)
1288156d6b00SAppaRao Puli {
1289e05aec50SEd Tanous Subscription& entry = *it.second;
1290c0353249SWludzik, Jozef if (entry.eventFormatType == metricReportFormatType)
1291156d6b00SAppaRao Puli {
12921e1e598dSJonathan Doman entry.filterAndSendReports(id, *readings);
1293156d6b00SAppaRao Puli }
1294156d6b00SAppaRao Puli }
1295156d6b00SAppaRao Puli }
1296156d6b00SAppaRao Puli
unregisterMetricReportSignal()1297156d6b00SAppaRao Puli void unregisterMetricReportSignal()
1298156d6b00SAppaRao Puli {
12997d1cc387SAppaRao Puli if (matchTelemetryMonitor)
13007d1cc387SAppaRao Puli {
130162598e31SEd Tanous BMCWEB_LOG_DEBUG("Metrics report signal - Unregister");
1302156d6b00SAppaRao Puli matchTelemetryMonitor.reset();
1303156d6b00SAppaRao Puli matchTelemetryMonitor = nullptr;
1304156d6b00SAppaRao Puli }
13057d1cc387SAppaRao Puli }
1306156d6b00SAppaRao Puli
registerMetricReportSignal()1307156d6b00SAppaRao Puli void registerMetricReportSignal()
1308156d6b00SAppaRao Puli {
13097d1cc387SAppaRao Puli if (!serviceEnabled || matchTelemetryMonitor)
1310156d6b00SAppaRao Puli {
131162598e31SEd Tanous BMCWEB_LOG_DEBUG("Not registering metric report signal.");
1312156d6b00SAppaRao Puli return;
1313156d6b00SAppaRao Puli }
1314156d6b00SAppaRao Puli
131562598e31SEd Tanous BMCWEB_LOG_DEBUG("Metrics report signal - Register");
1316c0353249SWludzik, Jozef std::string matchStr = "type='signal',member='PropertiesChanged',"
1317c0353249SWludzik, Jozef "interface='org.freedesktop.DBus.Properties',"
1318c0353249SWludzik, Jozef "arg0=xyz.openbmc_project.Telemetry.Report";
1319156d6b00SAppaRao Puli
132059d494eeSPatrick Williams matchTelemetryMonitor = std::make_shared<sdbusplus::bus::match_t>(
132156d2396dSEd Tanous *crow::connections::systemBus, matchStr, getReadingsForReport);
1322156d6b00SAppaRao Puli }
132323a21a1cSEd Tanous };
1324b52664e2SAppaRao Puli
1325b52664e2SAppaRao Puli } // namespace redfish
1326