1 /*
2 // Copyright (c) 2020 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 #pragma once
17 #include "metric_report.hpp"
18 #include "registries.hpp"
19 #include "registries/base_message_registry.hpp"
20 #include "registries/openbmc_message_registry.hpp"
21 #include "registries/task_event_message_registry.hpp"
22 
23 #include <sys/inotify.h>
24 
25 #include <boost/asio/io_context.hpp>
26 #include <boost/container/flat_map.hpp>
27 #include <dbus_utility.hpp>
28 #include <error_messages.hpp>
29 #include <event_service_store.hpp>
30 #include <http/utility.hpp>
31 #include <http_client.hpp>
32 #include <persistent_data.hpp>
33 #include <random.hpp>
34 #include <server_sent_events.hpp>
35 #include <utils/json_utils.hpp>
36 
37 #include <cstdlib>
38 #include <ctime>
39 #include <fstream>
40 #include <memory>
41 #include <span>
42 
43 namespace redfish
44 {
45 
46 using ReadingsObjType =
47     std::vector<std::tuple<std::string, std::string, double, int32_t>>;
48 
49 static constexpr const char* eventFormatType = "Event";
50 static constexpr const char* metricReportFormatType = "MetricReport";
51 
52 static constexpr const char* eventServiceFile =
53     "/var/lib/bmcweb/eventservice_config.json";
54 
55 namespace registries
56 {
57 inline std::span<const MessageEntry>
58     getRegistryFromPrefix(const std::string& registryName)
59 {
60     if (task_event::header.registryPrefix == registryName)
61     {
62         return {task_event::registry};
63     }
64     if (openbmc::header.registryPrefix == registryName)
65     {
66         return {openbmc::registry};
67     }
68     if (base::header.registryPrefix == registryName)
69     {
70         return {base::registry};
71     }
72     return {openbmc::registry};
73 }
74 } // namespace registries
75 
76 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
77 static std::optional<boost::asio::posix::stream_descriptor> inotifyConn;
78 static constexpr const char* redfishEventLogDir = "/var/log";
79 static constexpr const char* redfishEventLogFile = "/var/log/redfish";
80 static constexpr const size_t iEventSize = sizeof(inotify_event);
81 static int inotifyFd = -1;
82 static int dirWatchDesc = -1;
83 static int fileWatchDesc = -1;
84 
85 // <ID, timestamp, RedfishLogId, registryPrefix, MessageId, MessageArgs>
86 using EventLogObjectsType =
87     std::tuple<std::string, std::string, std::string, std::string, std::string,
88                std::vector<std::string>>;
89 
90 namespace registries
91 {
92 static const Message*
93     getMsgFromRegistry(const std::string& messageKey,
94                        const std::span<const MessageEntry>& registry)
95 {
96     std::span<const MessageEntry>::iterator messageIt =
97         std::find_if(registry.begin(), registry.end(),
98                      [&messageKey](const MessageEntry& messageEntry) {
99         return messageKey == messageEntry.first;
100         });
101     if (messageIt != registry.end())
102     {
103         return &messageIt->second;
104     }
105 
106     return nullptr;
107 }
108 
109 static const Message* formatMessage(const std::string_view& messageID)
110 {
111     // Redfish MessageIds are in the form
112     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
113     // the right Message
114     std::vector<std::string> fields;
115     fields.reserve(4);
116     boost::split(fields, messageID, boost::is_any_of("."));
117     if (fields.size() != 4)
118     {
119         return nullptr;
120     }
121     std::string& registryName = fields[0];
122     std::string& messageKey = fields[3];
123 
124     // Find the right registry and check it for the MessageKey
125     return getMsgFromRegistry(messageKey, getRegistryFromPrefix(registryName));
126 }
127 } // namespace registries
128 
129 namespace event_log
130 {
131 inline bool getUniqueEntryID(const std::string& logEntry, std::string& entryID)
132 {
133     static time_t prevTs = 0;
134     static int index = 0;
135 
136     // Get the entry timestamp
137     std::time_t curTs = 0;
138     std::tm timeStruct = {};
139     std::istringstream entryStream(logEntry);
140     if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
141     {
142         curTs = std::mktime(&timeStruct);
143         if (curTs == -1)
144         {
145             return false;
146         }
147     }
148     // If the timestamp isn't unique, increment the index
149     index = (curTs == prevTs) ? index + 1 : 0;
150 
151     // Save the timestamp
152     prevTs = curTs;
153 
154     entryID = std::to_string(curTs);
155     if (index > 0)
156     {
157         entryID += "_" + std::to_string(index);
158     }
159     return true;
160 }
161 
162 inline int getEventLogParams(const std::string& logEntry,
163                              std::string& timestamp, std::string& messageID,
164                              std::vector<std::string>& messageArgs)
165 {
166     // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
167     // First get the Timestamp
168     size_t space = logEntry.find_first_of(' ');
169     if (space == std::string::npos)
170     {
171         return -EINVAL;
172     }
173     timestamp = logEntry.substr(0, space);
174     // Then get the log contents
175     size_t entryStart = logEntry.find_first_not_of(' ', space);
176     if (entryStart == std::string::npos)
177     {
178         return -EINVAL;
179     }
180     std::string_view entry(logEntry);
181     entry.remove_prefix(entryStart);
182     // Use split to separate the entry into its fields
183     std::vector<std::string> logEntryFields;
184     boost::split(logEntryFields, entry, boost::is_any_of(","),
185                  boost::token_compress_on);
186     // We need at least a MessageId to be valid
187     if (logEntryFields.empty())
188     {
189         return -EINVAL;
190     }
191     messageID = logEntryFields[0];
192 
193     // Get the MessageArgs from the log if there are any
194     if (logEntryFields.size() > 1)
195     {
196         std::string& messageArgsStart = logEntryFields[1];
197         // If the first string is empty, assume there are no MessageArgs
198         if (!messageArgsStart.empty())
199         {
200             messageArgs.assign(logEntryFields.begin() + 1,
201                                logEntryFields.end());
202         }
203     }
204 
205     return 0;
206 }
207 
208 inline void getRegistryAndMessageKey(const std::string& messageID,
209                                      std::string& registryName,
210                                      std::string& messageKey)
211 {
212     // Redfish MessageIds are in the form
213     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
214     // the right Message
215     std::vector<std::string> fields;
216     fields.reserve(4);
217     boost::split(fields, messageID, boost::is_any_of("."));
218     if (fields.size() == 4)
219     {
220         registryName = fields[0];
221         messageKey = fields[3];
222     }
223 }
224 
225 inline int formatEventLogEntry(const std::string& logEntryID,
226                                const std::string& messageID,
227                                const std::span<std::string_view> messageArgs,
228                                std::string timestamp,
229                                const std::string& customText,
230                                nlohmann::json& logEntryJson)
231 {
232     // Get the Message from the MessageRegistry
233     const registries::Message* message = registries::formatMessage(messageID);
234 
235     std::string msg;
236     std::string severity;
237     if (message != nullptr)
238     {
239         msg = message->message;
240         severity = message->messageSeverity;
241     }
242 
243     redfish::registries::fillMessageArgs(messageArgs, msg);
244 
245     // Get the Created time from the timestamp. The log timestamp is in
246     // RFC3339 format which matches the Redfish format except for the
247     // fractional seconds between the '.' and the '+', so just remove them.
248     std::size_t dot = timestamp.find_first_of('.');
249     std::size_t plus = timestamp.find_first_of('+');
250     if (dot != std::string::npos && plus != std::string::npos)
251     {
252         timestamp.erase(dot, plus - dot);
253     }
254 
255     // Fill in the log entry with the gathered data
256     logEntryJson["EventId"] = logEntryID;
257     logEntryJson["EventType"] = "Event";
258     logEntryJson["Severity"] = std::move(severity);
259     logEntryJson["Message"] = std::move(msg);
260     logEntryJson["MessageId"] = messageID;
261     logEntryJson["MessageArgs"] = messageArgs;
262     logEntryJson["EventTimestamp"] = std::move(timestamp);
263     logEntryJson["Context"] = customText;
264     return 0;
265 }
266 
267 } // namespace event_log
268 #endif
269 
270 inline bool isFilterQuerySpecialChar(char c)
271 {
272     switch (c)
273     {
274         case '(':
275         case ')':
276         case '\'':
277             return true;
278         default:
279             return false;
280     }
281 }
282 
283 inline bool
284     readSSEQueryParams(std::string sseFilter, std::string& formatType,
285                        std::vector<std::string>& messageIds,
286                        std::vector<std::string>& registryPrefixes,
287                        std::vector<std::string>& metricReportDefinitions)
288 {
289     sseFilter.erase(std::remove_if(sseFilter.begin(), sseFilter.end(),
290                                    isFilterQuerySpecialChar),
291                     sseFilter.end());
292 
293     std::vector<std::string> result;
294     boost::split(result, sseFilter, boost::is_any_of(" "),
295                  boost::token_compress_on);
296 
297     BMCWEB_LOG_DEBUG << "No of tokens in SEE query: " << result.size();
298 
299     constexpr uint8_t divisor = 4;
300     constexpr uint8_t minTokenSize = 3;
301     if (result.size() % divisor != minTokenSize)
302     {
303         BMCWEB_LOG_ERROR << "Invalid SSE filter specified.";
304         return false;
305     }
306 
307     for (std::size_t i = 0; i < result.size(); i += divisor)
308     {
309         std::string& key = result[i];
310         std::string& op = result[i + 1];
311         std::string& value = result[i + 2];
312 
313         if ((i + minTokenSize) < result.size())
314         {
315             std::string& separator = result[i + minTokenSize];
316             // SSE supports only "or" and "and" in query params.
317             if ((separator != "or") && (separator != "and"))
318             {
319                 BMCWEB_LOG_ERROR
320                     << "Invalid group operator in SSE query parameters";
321                 return false;
322             }
323         }
324 
325         // SSE supports only "eq" as per spec.
326         if (op != "eq")
327         {
328             BMCWEB_LOG_ERROR
329                 << "Invalid assignment operator in SSE query parameters";
330             return false;
331         }
332 
333         BMCWEB_LOG_DEBUG << key << " : " << value;
334         if (key == "EventFormatType")
335         {
336             formatType = value;
337         }
338         else if (key == "MessageId")
339         {
340             messageIds.push_back(value);
341         }
342         else if (key == "RegistryPrefix")
343         {
344             registryPrefixes.push_back(value);
345         }
346         else if (key == "MetricReportDefinition")
347         {
348             metricReportDefinitions.push_back(value);
349         }
350         else
351         {
352             BMCWEB_LOG_ERROR << "Invalid property(" << key
353                              << ")in SSE filter query.";
354             return false;
355         }
356     }
357     return true;
358 }
359 
360 class Subscription : public persistent_data::UserSubscription
361 {
362   public:
363     Subscription(const Subscription&) = delete;
364     Subscription& operator=(const Subscription&) = delete;
365     Subscription(Subscription&&) = delete;
366     Subscription& operator=(Subscription&&) = delete;
367 
368     Subscription(const std::string& inHost, uint16_t inPort,
369                  const std::string& inPath, const std::string& inUriProto) :
370         eventSeqNum(1),
371         host(inHost), port(inPort), path(inPath), uriProto(inUriProto)
372     {
373         // Subscription constructor
374     }
375 
376     Subscription(const std::shared_ptr<boost::beast::tcp_stream>& adaptor) :
377         eventSeqNum(1)
378     {
379         sseConn = std::make_shared<crow::ServerSentEvents>(adaptor);
380     }
381 
382     ~Subscription() = default;
383 
384     bool sendEvent(std::string& msg)
385     {
386         persistent_data::EventServiceConfig eventServiceConfig =
387             persistent_data::EventServiceStore::getInstance()
388                 .getEventServiceConfig();
389         if (!eventServiceConfig.enabled)
390         {
391             return false;
392         }
393 
394         // A connection pool will be created if one does not already exist
395         crow::HttpClient::getInstance().sendData(
396             msg, id, host, port, path, httpHeaders,
397             boost::beast::http::verb::post, retryPolicyName);
398         eventSeqNum++;
399 
400         if (sseConn != nullptr)
401         {
402             sseConn->sendData(eventSeqNum, msg);
403         }
404         return true;
405     }
406 
407     bool sendTestEventLog()
408     {
409         nlohmann::json logEntryArray;
410         logEntryArray.push_back({});
411         nlohmann::json& logEntryJson = logEntryArray.back();
412 
413         logEntryJson = {
414             {"EventId", "TestID"},
415             {"EventType", "Event"},
416             {"Severity", "OK"},
417             {"Message", "Generated test event"},
418             {"MessageId", "OpenBMC.0.2.TestEventLog"},
419             {"MessageArgs", nlohmann::json::array()},
420             {"EventTimestamp", crow::utility::getDateTimeOffsetNow().first},
421             {"Context", customText}};
422 
423         nlohmann::json msg;
424         msg["@odata.type"] = "#Event.v1_4_0.Event";
425         msg["Id"] = std::to_string(eventSeqNum);
426         msg["Name"] = "Event Log";
427         msg["Events"] = logEntryArray;
428 
429         std::string strMsg =
430             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace);
431         return this->sendEvent(strMsg);
432     }
433 
434 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
435     void filterAndSendEventLogs(
436         const std::vector<EventLogObjectsType>& eventRecords)
437     {
438         nlohmann::json logEntryArray;
439         for (const EventLogObjectsType& logEntry : eventRecords)
440         {
441             const std::string& idStr = std::get<0>(logEntry);
442             const std::string& timestamp = std::get<1>(logEntry);
443             const std::string& messageID = std::get<2>(logEntry);
444             const std::string& registryName = std::get<3>(logEntry);
445             const std::string& messageKey = std::get<4>(logEntry);
446             const std::vector<std::string>& messageArgs = std::get<5>(logEntry);
447 
448             // If registryPrefixes list is empty, don't filter events
449             // send everything.
450             if (!registryPrefixes.empty())
451             {
452                 auto obj = std::find(registryPrefixes.begin(),
453                                      registryPrefixes.end(), registryName);
454                 if (obj == registryPrefixes.end())
455                 {
456                     continue;
457                 }
458             }
459 
460             // If registryMsgIds list is empty, don't filter events
461             // send everything.
462             if (!registryMsgIds.empty())
463             {
464                 auto obj = std::find(registryMsgIds.begin(),
465                                      registryMsgIds.end(), messageKey);
466                 if (obj == registryMsgIds.end())
467                 {
468                     continue;
469                 }
470             }
471 
472             std::vector<std::string_view> messageArgsView(messageArgs.begin(),
473                                                           messageArgs.end());
474 
475             logEntryArray.push_back({});
476             nlohmann::json& bmcLogEntry = logEntryArray.back();
477             if (event_log::formatEventLogEntry(idStr, messageID,
478                                                messageArgsView, timestamp,
479                                                customText, bmcLogEntry) != 0)
480             {
481                 BMCWEB_LOG_DEBUG << "Read eventLog entry failed";
482                 continue;
483             }
484         }
485 
486         if (logEntryArray.empty())
487         {
488             BMCWEB_LOG_DEBUG << "No log entries available to be transferred.";
489             return;
490         }
491 
492         nlohmann::json msg;
493         msg["@odata.type"] = "#Event.v1_4_0.Event";
494         msg["Id"] = std::to_string(eventSeqNum);
495         msg["Name"] = "Event Log";
496         msg["Events"] = logEntryArray;
497 
498         std::string strMsg =
499             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace);
500         this->sendEvent(strMsg);
501     }
502 #endif
503 
504     void filterAndSendReports(const std::string& reportId,
505                               const telemetry::TimestampReadings& var)
506     {
507         boost::urls::url mrdUri =
508             crow::utility::urlFromPieces("redfish", "v1", "TelemetryService",
509                                          "MetricReportDefinitions", reportId);
510 
511         // Empty list means no filter. Send everything.
512         if (!metricReportDefinitions.empty())
513         {
514             if (std::find(metricReportDefinitions.begin(),
515                           metricReportDefinitions.end(),
516                           mrdUri.string()) == metricReportDefinitions.end())
517             {
518                 return;
519             }
520         }
521 
522         nlohmann::json msg;
523         if (!telemetry::fillReport(msg, reportId, var))
524         {
525             BMCWEB_LOG_ERROR << "Failed to fill the MetricReport for DBus "
526                                 "Report with id "
527                              << reportId;
528             return;
529         }
530 
531         std::string strMsg =
532             msg.dump(2, ' ', true, nlohmann::json::error_handler_t::replace);
533         this->sendEvent(strMsg);
534     }
535 
536     void updateRetryConfig(const uint32_t retryAttempts,
537                            const uint32_t retryTimeoutInterval)
538     {
539         crow::HttpClient::getInstance().setRetryConfig(
540             retryAttempts, retryTimeoutInterval, retryPolicyName);
541     }
542 
543     void updateRetryPolicy()
544     {
545         crow::HttpClient::getInstance().setRetryPolicy(retryPolicy,
546                                                        retryPolicyName);
547     }
548 
549     uint64_t getEventSeqNum() const
550     {
551         return eventSeqNum;
552     }
553 
554   private:
555     uint64_t eventSeqNum;
556     std::string host;
557     uint16_t port = 0;
558     std::string path;
559     std::string uriProto;
560     std::shared_ptr<crow::ServerSentEvents> sseConn = nullptr;
561     std::string retryPolicyName = "SubscriptionEvent";
562 };
563 
564 class EventServiceManager
565 {
566   private:
567     bool serviceEnabled = false;
568     uint32_t retryAttempts = 0;
569     uint32_t retryTimeoutInterval = 0;
570 
571     EventServiceManager()
572     {
573         // Load config from persist store.
574         initConfig();
575     }
576 
577     std::streampos redfishLogFilePosition{0};
578     size_t noOfEventLogSubscribers{0};
579     size_t noOfMetricReportSubscribers{0};
580     std::shared_ptr<sdbusplus::bus::match::match> matchTelemetryMonitor;
581     boost::container::flat_map<std::string, std::shared_ptr<Subscription>>
582         subscriptionsMap;
583 
584     uint64_t eventId{1};
585 
586   public:
587     EventServiceManager(const EventServiceManager&) = delete;
588     EventServiceManager& operator=(const EventServiceManager&) = delete;
589     EventServiceManager(EventServiceManager&&) = delete;
590     EventServiceManager& operator=(EventServiceManager&&) = delete;
591     ~EventServiceManager() = default;
592 
593     static EventServiceManager& getInstance()
594     {
595         static EventServiceManager handler;
596         return handler;
597     }
598 
599     void initConfig()
600     {
601         loadOldBehavior();
602 
603         persistent_data::EventServiceConfig eventServiceConfig =
604             persistent_data::EventServiceStore::getInstance()
605                 .getEventServiceConfig();
606 
607         serviceEnabled = eventServiceConfig.enabled;
608         retryAttempts = eventServiceConfig.retryAttempts;
609         retryTimeoutInterval = eventServiceConfig.retryTimeoutInterval;
610 
611         for (const auto& it : persistent_data::EventServiceStore::getInstance()
612                                   .subscriptionsConfigMap)
613         {
614             std::shared_ptr<persistent_data::UserSubscription> newSub =
615                 it.second;
616 
617             std::string host;
618             std::string urlProto;
619             uint16_t port = 0;
620             std::string path;
621             bool status = crow::utility::validateAndSplitUrl(
622                 newSub->destinationUrl, urlProto, host, port, path);
623 
624             if (!status)
625             {
626                 BMCWEB_LOG_ERROR
627                     << "Failed to validate and split destination url";
628                 continue;
629             }
630             std::shared_ptr<Subscription> subValue =
631                 std::make_shared<Subscription>(host, port, path, urlProto);
632 
633             subValue->id = newSub->id;
634             subValue->destinationUrl = newSub->destinationUrl;
635             subValue->protocol = newSub->protocol;
636             subValue->retryPolicy = newSub->retryPolicy;
637             subValue->customText = newSub->customText;
638             subValue->eventFormatType = newSub->eventFormatType;
639             subValue->subscriptionType = newSub->subscriptionType;
640             subValue->registryMsgIds = newSub->registryMsgIds;
641             subValue->registryPrefixes = newSub->registryPrefixes;
642             subValue->resourceTypes = newSub->resourceTypes;
643             subValue->httpHeaders = newSub->httpHeaders;
644             subValue->metricReportDefinitions = newSub->metricReportDefinitions;
645 
646             if (subValue->id.empty())
647             {
648                 BMCWEB_LOG_ERROR << "Failed to add subscription";
649             }
650             subscriptionsMap.insert(std::pair(subValue->id, subValue));
651 
652             updateNoOfSubscribersCount();
653 
654 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
655 
656             cacheRedfishLogFile();
657 
658 #endif
659             // Update retry configuration.
660             subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
661             subValue->updateRetryPolicy();
662         }
663     }
664 
665     static void loadOldBehavior()
666     {
667         std::ifstream eventConfigFile(eventServiceFile);
668         if (!eventConfigFile.good())
669         {
670             BMCWEB_LOG_DEBUG << "Old eventService config not exist";
671             return;
672         }
673         auto jsonData = nlohmann::json::parse(eventConfigFile, nullptr, false);
674         if (jsonData.is_discarded())
675         {
676             BMCWEB_LOG_ERROR << "Old eventService config parse error.";
677             return;
678         }
679 
680         for (const auto& item : jsonData.items())
681         {
682             if (item.key() == "Configuration")
683             {
684                 persistent_data::EventServiceStore::getInstance()
685                     .getEventServiceConfig()
686                     .fromJson(item.value());
687             }
688             else if (item.key() == "Subscriptions")
689             {
690                 for (const auto& elem : item.value())
691                 {
692                     std::shared_ptr<persistent_data::UserSubscription>
693                         newSubscription =
694                             persistent_data::UserSubscription::fromJson(elem,
695                                                                         true);
696                     if (newSubscription == nullptr)
697                     {
698                         BMCWEB_LOG_ERROR << "Problem reading subscription "
699                                             "from old persistent store";
700                         continue;
701                     }
702 
703                     std::uniform_int_distribution<uint32_t> dist(0);
704                     bmcweb::OpenSSLGenerator gen;
705 
706                     std::string id;
707 
708                     int retry = 3;
709                     while (retry != 0)
710                     {
711                         id = std::to_string(dist(gen));
712                         if (gen.error())
713                         {
714                             retry = 0;
715                             break;
716                         }
717                         newSubscription->id = id;
718                         auto inserted =
719                             persistent_data::EventServiceStore::getInstance()
720                                 .subscriptionsConfigMap.insert(
721                                     std::pair(id, newSubscription));
722                         if (inserted.second)
723                         {
724                             break;
725                         }
726                         --retry;
727                     }
728 
729                     if (retry <= 0)
730                     {
731                         BMCWEB_LOG_ERROR
732                             << "Failed to generate random number from old "
733                                "persistent store";
734                         continue;
735                     }
736                 }
737             }
738 
739             persistent_data::getConfig().writeData();
740             std::remove(eventServiceFile);
741             BMCWEB_LOG_DEBUG << "Remove old eventservice config";
742         }
743     }
744 
745     void updateSubscriptionData() const
746     {
747         persistent_data::EventServiceStore::getInstance()
748             .eventServiceConfig.enabled = serviceEnabled;
749         persistent_data::EventServiceStore::getInstance()
750             .eventServiceConfig.retryAttempts = retryAttempts;
751         persistent_data::EventServiceStore::getInstance()
752             .eventServiceConfig.retryTimeoutInterval = retryTimeoutInterval;
753 
754         persistent_data::getConfig().writeData();
755     }
756 
757     void setEventServiceConfig(const persistent_data::EventServiceConfig& cfg)
758     {
759         bool updateConfig = false;
760         bool updateRetryCfg = false;
761 
762         if (serviceEnabled != cfg.enabled)
763         {
764             serviceEnabled = cfg.enabled;
765             if (serviceEnabled && noOfMetricReportSubscribers != 0U)
766             {
767                 registerMetricReportSignal();
768             }
769             else
770             {
771                 unregisterMetricReportSignal();
772             }
773             updateConfig = true;
774         }
775 
776         if (retryAttempts != cfg.retryAttempts)
777         {
778             retryAttempts = cfg.retryAttempts;
779             updateConfig = true;
780             updateRetryCfg = true;
781         }
782 
783         if (retryTimeoutInterval != cfg.retryTimeoutInterval)
784         {
785             retryTimeoutInterval = cfg.retryTimeoutInterval;
786             updateConfig = true;
787             updateRetryCfg = true;
788         }
789 
790         if (updateConfig)
791         {
792             updateSubscriptionData();
793         }
794 
795         if (updateRetryCfg)
796         {
797             // Update the changed retry config to all subscriptions
798             for (const auto& it :
799                  EventServiceManager::getInstance().subscriptionsMap)
800             {
801                 std::shared_ptr<Subscription> entry = it.second;
802                 entry->updateRetryConfig(retryAttempts, retryTimeoutInterval);
803             }
804         }
805     }
806 
807     void updateNoOfSubscribersCount()
808     {
809         size_t eventLogSubCount = 0;
810         size_t metricReportSubCount = 0;
811         for (const auto& it : subscriptionsMap)
812         {
813             std::shared_ptr<Subscription> entry = it.second;
814             if (entry->eventFormatType == eventFormatType)
815             {
816                 eventLogSubCount++;
817             }
818             else if (entry->eventFormatType == metricReportFormatType)
819             {
820                 metricReportSubCount++;
821             }
822         }
823 
824         noOfEventLogSubscribers = eventLogSubCount;
825         if (noOfMetricReportSubscribers != metricReportSubCount)
826         {
827             noOfMetricReportSubscribers = metricReportSubCount;
828             if (noOfMetricReportSubscribers != 0U)
829             {
830                 registerMetricReportSignal();
831             }
832             else
833             {
834                 unregisterMetricReportSignal();
835             }
836         }
837     }
838 
839     std::shared_ptr<Subscription> getSubscription(const std::string& id)
840     {
841         auto obj = subscriptionsMap.find(id);
842         if (obj == subscriptionsMap.end())
843         {
844             BMCWEB_LOG_ERROR << "No subscription exist with ID:" << id;
845             return nullptr;
846         }
847         std::shared_ptr<Subscription> subValue = obj->second;
848         return subValue;
849     }
850 
851     std::string addSubscription(const std::shared_ptr<Subscription>& subValue,
852                                 const bool updateFile = true)
853     {
854 
855         std::uniform_int_distribution<uint32_t> dist(0);
856         bmcweb::OpenSSLGenerator gen;
857 
858         std::string id;
859 
860         int retry = 3;
861         while (retry != 0)
862         {
863             id = std::to_string(dist(gen));
864             if (gen.error())
865             {
866                 retry = 0;
867                 break;
868             }
869             auto inserted = subscriptionsMap.insert(std::pair(id, subValue));
870             if (inserted.second)
871             {
872                 break;
873             }
874             --retry;
875         }
876 
877         if (retry <= 0)
878         {
879             BMCWEB_LOG_ERROR << "Failed to generate random number";
880             return "";
881         }
882 
883         std::shared_ptr<persistent_data::UserSubscription> newSub =
884             std::make_shared<persistent_data::UserSubscription>();
885         newSub->id = id;
886         newSub->destinationUrl = subValue->destinationUrl;
887         newSub->protocol = subValue->protocol;
888         newSub->retryPolicy = subValue->retryPolicy;
889         newSub->customText = subValue->customText;
890         newSub->eventFormatType = subValue->eventFormatType;
891         newSub->subscriptionType = subValue->subscriptionType;
892         newSub->registryMsgIds = subValue->registryMsgIds;
893         newSub->registryPrefixes = subValue->registryPrefixes;
894         newSub->resourceTypes = subValue->resourceTypes;
895         newSub->httpHeaders = subValue->httpHeaders;
896         newSub->metricReportDefinitions = subValue->metricReportDefinitions;
897         persistent_data::EventServiceStore::getInstance()
898             .subscriptionsConfigMap.emplace(newSub->id, newSub);
899 
900         updateNoOfSubscribersCount();
901 
902         if (updateFile)
903         {
904             updateSubscriptionData();
905         }
906 
907 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
908         if (redfishLogFilePosition != 0)
909         {
910             cacheRedfishLogFile();
911         }
912 #endif
913         // Update retry configuration.
914         subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval);
915         subValue->updateRetryPolicy();
916 
917         return id;
918     }
919 
920     bool isSubscriptionExist(const std::string& id)
921     {
922         auto obj = subscriptionsMap.find(id);
923         return obj != subscriptionsMap.end();
924     }
925 
926     void deleteSubscription(const std::string& id)
927     {
928         auto obj = subscriptionsMap.find(id);
929         if (obj != subscriptionsMap.end())
930         {
931             subscriptionsMap.erase(obj);
932             auto obj2 = persistent_data::EventServiceStore::getInstance()
933                             .subscriptionsConfigMap.find(id);
934             persistent_data::EventServiceStore::getInstance()
935                 .subscriptionsConfigMap.erase(obj2);
936             updateNoOfSubscribersCount();
937             updateSubscriptionData();
938         }
939     }
940 
941     size_t getNumberOfSubscriptions()
942     {
943         return subscriptionsMap.size();
944     }
945 
946     std::vector<std::string> getAllIDs()
947     {
948         std::vector<std::string> idList;
949         for (const auto& it : subscriptionsMap)
950         {
951             idList.emplace_back(it.first);
952         }
953         return idList;
954     }
955 
956     bool isDestinationExist(const std::string& destUrl)
957     {
958         for (const auto& it : subscriptionsMap)
959         {
960             std::shared_ptr<Subscription> entry = it.second;
961             if (entry->destinationUrl == destUrl)
962             {
963                 BMCWEB_LOG_ERROR << "Destination exist already" << destUrl;
964                 return true;
965             }
966         }
967         return false;
968     }
969 
970     bool sendTestEventLog()
971     {
972         for (const auto& it : this->subscriptionsMap)
973         {
974             std::shared_ptr<Subscription> entry = it.second;
975             if (!entry->sendTestEventLog())
976             {
977                 return false;
978             }
979         }
980         return true;
981     }
982 
983     void sendEvent(const nlohmann::json& eventMessageIn,
984                    const std::string& origin, const std::string& resType)
985     {
986         if (!serviceEnabled || (noOfEventLogSubscribers == 0U))
987         {
988             BMCWEB_LOG_DEBUG << "EventService disabled or no Subscriptions.";
989             return;
990         }
991         nlohmann::json eventRecord = nlohmann::json::array();
992         nlohmann::json eventMessage = eventMessageIn;
993         // MemberId is 0 : since we are sending one event record.
994         uint64_t memberId = 0;
995 
996         nlohmann::json event = {
997             {"EventId", eventId},
998             {"MemberId", memberId},
999             {"EventTimestamp", crow::utility::getDateTimeOffsetNow().first},
1000             {"OriginOfCondition", origin}};
1001         for (nlohmann::json::iterator it = event.begin(); it != event.end();
1002              ++it)
1003         {
1004             eventMessage[it.key()] = it.value();
1005         }
1006         eventRecord.push_back(eventMessage);
1007 
1008         for (const auto& it : this->subscriptionsMap)
1009         {
1010             std::shared_ptr<Subscription> entry = it.second;
1011             bool isSubscribed = false;
1012             // Search the resourceTypes list for the subscription.
1013             // If resourceTypes list is empty, don't filter events
1014             // send everything.
1015             if (!entry->resourceTypes.empty())
1016             {
1017                 for (const auto& resource : entry->resourceTypes)
1018                 {
1019                     if (resType == resource)
1020                     {
1021                         BMCWEB_LOG_INFO << "ResourceType " << resource
1022                                         << " found in the subscribed list";
1023                         isSubscribed = true;
1024                         break;
1025                     }
1026                 }
1027             }
1028             else // resourceTypes list is empty.
1029             {
1030                 isSubscribed = true;
1031             }
1032             if (isSubscribed)
1033             {
1034                 nlohmann::json msgJson = {
1035                     {"@odata.type", "#Event.v1_4_0.Event"},
1036                     {"Name", "Event Log"},
1037                     {"Id", eventId},
1038                     {"Events", eventRecord}};
1039 
1040                 std::string strMsg = msgJson.dump(
1041                     2, ' ', true, nlohmann::json::error_handler_t::replace);
1042                 entry->sendEvent(strMsg);
1043                 eventId++; // increament the eventId
1044             }
1045             else
1046             {
1047                 BMCWEB_LOG_INFO << "Not subscribed to this resource";
1048             }
1049         }
1050     }
1051     void sendBroadcastMsg(const std::string& broadcastMsg)
1052     {
1053         for (const auto& it : this->subscriptionsMap)
1054         {
1055             std::shared_ptr<Subscription> entry = it.second;
1056             nlohmann::json msgJson = {
1057                 {"Timestamp", crow::utility::getDateTimeOffsetNow().first},
1058                 {"OriginOfCondition", "/ibm/v1/HMC/BroadcastService"},
1059                 {"Name", "Broadcast Message"},
1060                 {"Message", broadcastMsg}};
1061 
1062             std::string strMsg = msgJson.dump(
1063                 2, ' ', true, nlohmann::json::error_handler_t::replace);
1064             entry->sendEvent(strMsg);
1065         }
1066     }
1067 
1068 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES
1069 
1070     void resetRedfishFilePosition()
1071     {
1072         // Control would be here when Redfish file is created.
1073         // Reset File Position as new file is created
1074         redfishLogFilePosition = 0;
1075     }
1076 
1077     void cacheRedfishLogFile()
1078     {
1079         // Open the redfish file and read till the last record.
1080 
1081         std::ifstream logStream(redfishEventLogFile);
1082         if (!logStream.good())
1083         {
1084             BMCWEB_LOG_ERROR << " Redfish log file open failed \n";
1085             return;
1086         }
1087         std::string logEntry;
1088         while (std::getline(logStream, logEntry))
1089         {
1090             redfishLogFilePosition = logStream.tellg();
1091         }
1092 
1093         BMCWEB_LOG_DEBUG << "Next Log Position : " << redfishLogFilePosition;
1094     }
1095 
1096     void readEventLogsFromFile()
1097     {
1098         std::ifstream logStream(redfishEventLogFile);
1099         if (!logStream.good())
1100         {
1101             BMCWEB_LOG_ERROR << " Redfish log file open failed";
1102             return;
1103         }
1104 
1105         std::vector<EventLogObjectsType> eventRecords;
1106 
1107         std::string logEntry;
1108 
1109         // Get the read pointer to the next log to be read.
1110         logStream.seekg(redfishLogFilePosition);
1111 
1112         while (std::getline(logStream, logEntry))
1113         {
1114             // Update Pointer position
1115             redfishLogFilePosition = logStream.tellg();
1116 
1117             std::string idStr;
1118             if (!event_log::getUniqueEntryID(logEntry, idStr))
1119             {
1120                 continue;
1121             }
1122 
1123             if (!serviceEnabled || noOfEventLogSubscribers == 0)
1124             {
1125                 // If Service is not enabled, no need to compute
1126                 // the remaining items below.
1127                 // But, Loop must continue to keep track of Timestamp
1128                 continue;
1129             }
1130 
1131             std::string timestamp;
1132             std::string messageID;
1133             std::vector<std::string> messageArgs;
1134             if (event_log::getEventLogParams(logEntry, timestamp, messageID,
1135                                              messageArgs) != 0)
1136             {
1137                 BMCWEB_LOG_DEBUG << "Read eventLog entry params failed";
1138                 continue;
1139             }
1140 
1141             std::string registryName;
1142             std::string messageKey;
1143             event_log::getRegistryAndMessageKey(messageID, registryName,
1144                                                 messageKey);
1145             if (registryName.empty() || messageKey.empty())
1146             {
1147                 continue;
1148             }
1149 
1150             eventRecords.emplace_back(idStr, timestamp, messageID, registryName,
1151                                       messageKey, messageArgs);
1152         }
1153 
1154         if (!serviceEnabled || noOfEventLogSubscribers == 0)
1155         {
1156             BMCWEB_LOG_DEBUG << "EventService disabled or no Subscriptions.";
1157             return;
1158         }
1159 
1160         if (eventRecords.empty())
1161         {
1162             // No Records to send
1163             BMCWEB_LOG_DEBUG << "No log entries available to be transferred.";
1164             return;
1165         }
1166 
1167         for (const auto& it : this->subscriptionsMap)
1168         {
1169             std::shared_ptr<Subscription> entry = it.second;
1170             if (entry->eventFormatType == "Event")
1171             {
1172                 entry->filterAndSendEventLogs(eventRecords);
1173             }
1174         }
1175     }
1176 
1177     static void watchRedfishEventLogFile()
1178     {
1179         if (!inotifyConn)
1180         {
1181             return;
1182         }
1183 
1184         static std::array<char, 1024> readBuffer;
1185 
1186         inotifyConn->async_read_some(boost::asio::buffer(readBuffer),
1187                                      [&](const boost::system::error_code& ec,
1188                                          const std::size_t& bytesTransferred) {
1189             if (ec)
1190             {
1191                 BMCWEB_LOG_ERROR << "Callback Error: " << ec.message();
1192                 return;
1193             }
1194             std::size_t index = 0;
1195             while ((index + iEventSize) <= bytesTransferred)
1196             {
1197                 struct inotify_event event
1198                 {};
1199                 std::memcpy(&event, &readBuffer[index], iEventSize);
1200                 if (event.wd == dirWatchDesc)
1201                 {
1202                     if ((event.len == 0) ||
1203                         (index + iEventSize + event.len > bytesTransferred))
1204                     {
1205                         index += (iEventSize + event.len);
1206                         continue;
1207                     }
1208 
1209                     std::string fileName(&readBuffer[index + iEventSize]);
1210                     if (fileName != "redfish")
1211                     {
1212                         index += (iEventSize + event.len);
1213                         continue;
1214                     }
1215 
1216                     BMCWEB_LOG_DEBUG
1217                         << "Redfish log file created/deleted. event.name: "
1218                         << fileName;
1219                     if (event.mask == IN_CREATE)
1220                     {
1221                         if (fileWatchDesc != -1)
1222                         {
1223                             BMCWEB_LOG_DEBUG
1224                                 << "Remove and Add inotify watcher on "
1225                                    "redfish event log file";
1226                             // Remove existing inotify watcher and add
1227                             // with new redfish event log file.
1228                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1229                             fileWatchDesc = -1;
1230                         }
1231 
1232                         fileWatchDesc = inotify_add_watch(
1233                             inotifyFd, redfishEventLogFile, IN_MODIFY);
1234                         if (fileWatchDesc == -1)
1235                         {
1236                             BMCWEB_LOG_ERROR << "inotify_add_watch failed for "
1237                                                 "redfish log file.";
1238                             return;
1239                         }
1240 
1241                         EventServiceManager::getInstance()
1242                             .resetRedfishFilePosition();
1243                         EventServiceManager::getInstance()
1244                             .readEventLogsFromFile();
1245                     }
1246                     else if ((event.mask == IN_DELETE) ||
1247                              (event.mask == IN_MOVED_TO))
1248                     {
1249                         if (fileWatchDesc != -1)
1250                         {
1251                             inotify_rm_watch(inotifyFd, fileWatchDesc);
1252                             fileWatchDesc = -1;
1253                         }
1254                     }
1255                 }
1256                 else if (event.wd == fileWatchDesc)
1257                 {
1258                     if (event.mask == IN_MODIFY)
1259                     {
1260                         EventServiceManager::getInstance()
1261                             .readEventLogsFromFile();
1262                     }
1263                 }
1264                 index += (iEventSize + event.len);
1265             }
1266 
1267             watchRedfishEventLogFile();
1268         });
1269     }
1270 
1271     static int startEventLogMonitor(boost::asio::io_context& ioc)
1272     {
1273         inotifyConn.emplace(ioc);
1274         inotifyFd = inotify_init1(IN_NONBLOCK);
1275         if (inotifyFd == -1)
1276         {
1277             BMCWEB_LOG_ERROR << "inotify_init1 failed.";
1278             return -1;
1279         }
1280 
1281         // Add watch on directory to handle redfish event log file
1282         // create/delete.
1283         dirWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogDir,
1284                                          IN_CREATE | IN_MOVED_TO | IN_DELETE);
1285         if (dirWatchDesc == -1)
1286         {
1287             BMCWEB_LOG_ERROR
1288                 << "inotify_add_watch failed for event log directory.";
1289             return -1;
1290         }
1291 
1292         // Watch redfish event log file for modifications.
1293         fileWatchDesc =
1294             inotify_add_watch(inotifyFd, redfishEventLogFile, IN_MODIFY);
1295         if (fileWatchDesc == -1)
1296         {
1297             BMCWEB_LOG_ERROR
1298                 << "inotify_add_watch failed for redfish log file.";
1299             // Don't return error if file not exist.
1300             // Watch on directory will handle create/delete of file.
1301         }
1302 
1303         // monitor redfish event log file
1304         inotifyConn->assign(inotifyFd);
1305         watchRedfishEventLogFile();
1306 
1307         return 0;
1308     }
1309 
1310 #endif
1311     static void getReadingsForReport(sdbusplus::message::message& msg)
1312     {
1313         if (msg.is_method_error())
1314         {
1315             BMCWEB_LOG_ERROR << "TelemetryMonitor Signal error";
1316             return;
1317         }
1318 
1319         sdbusplus::message::object_path path(msg.get_path());
1320         std::string id = path.filename();
1321         if (id.empty())
1322         {
1323             BMCWEB_LOG_ERROR << "Failed to get Id from path";
1324             return;
1325         }
1326 
1327         std::string interface;
1328         dbus::utility::DBusPropertiesMap props;
1329         std::vector<std::string> invalidProps;
1330         msg.read(interface, props, invalidProps);
1331 
1332         auto found =
1333             std::find_if(props.begin(), props.end(),
1334                          [](const auto& x) { return x.first == "Readings"; });
1335         if (found == props.end())
1336         {
1337             BMCWEB_LOG_INFO << "Failed to get Readings from Report properties";
1338             return;
1339         }
1340 
1341         const telemetry::TimestampReadings* readings =
1342             std::get_if<telemetry::TimestampReadings>(&found->second);
1343         if (readings == nullptr)
1344         {
1345             BMCWEB_LOG_INFO << "Failed to get Readings from Report properties";
1346             return;
1347         }
1348 
1349         for (const auto& it :
1350              EventServiceManager::getInstance().subscriptionsMap)
1351         {
1352             Subscription& entry = *it.second;
1353             if (entry.eventFormatType == metricReportFormatType)
1354             {
1355                 entry.filterAndSendReports(id, *readings);
1356             }
1357         }
1358     }
1359 
1360     void unregisterMetricReportSignal()
1361     {
1362         if (matchTelemetryMonitor)
1363         {
1364             BMCWEB_LOG_DEBUG << "Metrics report signal - Unregister";
1365             matchTelemetryMonitor.reset();
1366             matchTelemetryMonitor = nullptr;
1367         }
1368     }
1369 
1370     void registerMetricReportSignal()
1371     {
1372         if (!serviceEnabled || matchTelemetryMonitor)
1373         {
1374             BMCWEB_LOG_DEBUG << "Not registering metric report signal.";
1375             return;
1376         }
1377 
1378         BMCWEB_LOG_DEBUG << "Metrics report signal - Register";
1379         std::string matchStr = "type='signal',member='PropertiesChanged',"
1380                                "interface='org.freedesktop.DBus.Properties',"
1381                                "arg0=xyz.openbmc_project.Telemetry.Report";
1382 
1383         matchTelemetryMonitor = std::make_shared<sdbusplus::bus::match::match>(
1384             *crow::connections::systemBus, matchStr, getReadingsForReport);
1385     }
1386 };
1387 
1388 } // namespace redfish
1389