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