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 == messageEntry.first; 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 return obj != subscriptionsMap.end(); 925 } 926 927 void deleteSubscription(const std::string& id) 928 { 929 auto obj = subscriptionsMap.find(id); 930 if (obj != subscriptionsMap.end()) 931 { 932 subscriptionsMap.erase(obj); 933 auto obj2 = persistent_data::EventServiceStore::getInstance() 934 .subscriptionsConfigMap.find(id); 935 persistent_data::EventServiceStore::getInstance() 936 .subscriptionsConfigMap.erase(obj2); 937 updateNoOfSubscribersCount(); 938 updateSubscriptionData(); 939 } 940 } 941 942 size_t getNumberOfSubscriptions() 943 { 944 return subscriptionsMap.size(); 945 } 946 947 std::vector<std::string> getAllIDs() 948 { 949 std::vector<std::string> idList; 950 for (const auto& it : subscriptionsMap) 951 { 952 idList.emplace_back(it.first); 953 } 954 return idList; 955 } 956 957 bool isDestinationExist(const std::string& destUrl) 958 { 959 for (const auto& it : subscriptionsMap) 960 { 961 std::shared_ptr<Subscription> entry = it.second; 962 if (entry->destinationUrl == destUrl) 963 { 964 BMCWEB_LOG_ERROR << "Destination exist already" << destUrl; 965 return true; 966 } 967 } 968 return false; 969 } 970 971 bool sendTestEventLog() 972 { 973 for (const auto& it : this->subscriptionsMap) 974 { 975 std::shared_ptr<Subscription> entry = it.second; 976 if (!entry->sendTestEventLog()) 977 { 978 return false; 979 } 980 } 981 return true; 982 } 983 984 void sendEvent(const nlohmann::json& eventMessageIn, 985 const std::string& origin, const std::string& resType) 986 { 987 if (!serviceEnabled || (noOfEventLogSubscribers == 0U)) 988 { 989 BMCWEB_LOG_DEBUG << "EventService disabled or no Subscriptions."; 990 return; 991 } 992 nlohmann::json eventRecord = nlohmann::json::array(); 993 nlohmann::json eventMessage = eventMessageIn; 994 // MemberId is 0 : since we are sending one event record. 995 uint64_t memberId = 0; 996 997 nlohmann::json event = { 998 {"EventId", eventId}, 999 {"MemberId", memberId}, 1000 {"EventTimestamp", crow::utility::getDateTimeOffsetNow().first}, 1001 {"OriginOfCondition", origin}}; 1002 for (nlohmann::json::iterator it = event.begin(); it != event.end(); 1003 ++it) 1004 { 1005 eventMessage[it.key()] = it.value(); 1006 } 1007 eventRecord.push_back(eventMessage); 1008 1009 for (const auto& it : this->subscriptionsMap) 1010 { 1011 std::shared_ptr<Subscription> entry = it.second; 1012 bool isSubscribed = false; 1013 // Search the resourceTypes list for the subscription. 1014 // If resourceTypes list is empty, don't filter events 1015 // send everything. 1016 if (!entry->resourceTypes.empty()) 1017 { 1018 for (const auto& resource : entry->resourceTypes) 1019 { 1020 if (resType == resource) 1021 { 1022 BMCWEB_LOG_INFO << "ResourceType " << resource 1023 << " found in the subscribed list"; 1024 isSubscribed = true; 1025 break; 1026 } 1027 } 1028 } 1029 else // resourceTypes list is empty. 1030 { 1031 isSubscribed = true; 1032 } 1033 if (isSubscribed) 1034 { 1035 nlohmann::json msgJson = { 1036 {"@odata.type", "#Event.v1_4_0.Event"}, 1037 {"Name", "Event Log"}, 1038 {"Id", eventId}, 1039 {"Events", eventRecord}}; 1040 entry->sendEvent(msgJson.dump( 1041 2, ' ', true, nlohmann::json::error_handler_t::replace)); 1042 eventId++; // increament the eventId 1043 } 1044 else 1045 { 1046 BMCWEB_LOG_INFO << "Not subscribed to this resource"; 1047 } 1048 } 1049 } 1050 void sendBroadcastMsg(const std::string& broadcastMsg) 1051 { 1052 for (const auto& it : this->subscriptionsMap) 1053 { 1054 std::shared_ptr<Subscription> entry = it.second; 1055 nlohmann::json msgJson = { 1056 {"Timestamp", crow::utility::getDateTimeOffsetNow().first}, 1057 {"OriginOfCondition", "/ibm/v1/HMC/BroadcastService"}, 1058 {"Name", "Broadcast Message"}, 1059 {"Message", broadcastMsg}}; 1060 entry->sendEvent(msgJson.dump( 1061 2, ' ', true, nlohmann::json::error_handler_t::replace)); 1062 } 1063 } 1064 1065 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES 1066 1067 void resetRedfishFilePosition() 1068 { 1069 // Control would be here when Redfish file is created. 1070 // Reset File Position as new file is created 1071 redfishLogFilePosition = 0; 1072 } 1073 1074 void cacheRedfishLogFile() 1075 { 1076 // Open the redfish file and read till the last record. 1077 1078 std::ifstream logStream(redfishEventLogFile); 1079 if (!logStream.good()) 1080 { 1081 BMCWEB_LOG_ERROR << " Redfish log file open failed \n"; 1082 return; 1083 } 1084 std::string logEntry; 1085 while (std::getline(logStream, logEntry)) 1086 { 1087 redfishLogFilePosition = logStream.tellg(); 1088 } 1089 1090 BMCWEB_LOG_DEBUG << "Next Log Position : " << redfishLogFilePosition; 1091 } 1092 1093 void readEventLogsFromFile() 1094 { 1095 std::ifstream logStream(redfishEventLogFile); 1096 if (!logStream.good()) 1097 { 1098 BMCWEB_LOG_ERROR << " Redfish log file open failed"; 1099 return; 1100 } 1101 1102 std::vector<EventLogObjectsType> eventRecords; 1103 1104 std::string logEntry; 1105 1106 // Get the read pointer to the next log to be read. 1107 logStream.seekg(redfishLogFilePosition); 1108 1109 while (std::getline(logStream, logEntry)) 1110 { 1111 // Update Pointer position 1112 redfishLogFilePosition = logStream.tellg(); 1113 1114 std::string idStr; 1115 if (!event_log::getUniqueEntryID(logEntry, idStr)) 1116 { 1117 continue; 1118 } 1119 1120 if (!serviceEnabled || noOfEventLogSubscribers == 0) 1121 { 1122 // If Service is not enabled, no need to compute 1123 // the remaining items below. 1124 // But, Loop must continue to keep track of Timestamp 1125 continue; 1126 } 1127 1128 std::string timestamp; 1129 std::string messageID; 1130 std::vector<std::string> messageArgs; 1131 if (event_log::getEventLogParams(logEntry, timestamp, messageID, 1132 messageArgs) != 0) 1133 { 1134 BMCWEB_LOG_DEBUG << "Read eventLog entry params failed"; 1135 continue; 1136 } 1137 1138 std::string registryName; 1139 std::string messageKey; 1140 event_log::getRegistryAndMessageKey(messageID, registryName, 1141 messageKey); 1142 if (registryName.empty() || messageKey.empty()) 1143 { 1144 continue; 1145 } 1146 1147 eventRecords.emplace_back(idStr, timestamp, messageID, registryName, 1148 messageKey, messageArgs); 1149 } 1150 1151 if (!serviceEnabled || noOfEventLogSubscribers == 0) 1152 { 1153 BMCWEB_LOG_DEBUG << "EventService disabled or no Subscriptions."; 1154 return; 1155 } 1156 1157 if (eventRecords.empty()) 1158 { 1159 // No Records to send 1160 BMCWEB_LOG_DEBUG << "No log entries available to be transferred."; 1161 return; 1162 } 1163 1164 for (const auto& it : this->subscriptionsMap) 1165 { 1166 std::shared_ptr<Subscription> entry = it.second; 1167 if (entry->eventFormatType == "Event") 1168 { 1169 entry->filterAndSendEventLogs(eventRecords); 1170 } 1171 } 1172 } 1173 1174 static void watchRedfishEventLogFile() 1175 { 1176 if (!inotifyConn) 1177 { 1178 return; 1179 } 1180 1181 static std::array<char, 1024> readBuffer; 1182 1183 inotifyConn->async_read_some( 1184 boost::asio::buffer(readBuffer), 1185 [&](const boost::system::error_code& ec, 1186 const std::size_t& bytesTransferred) { 1187 if (ec) 1188 { 1189 BMCWEB_LOG_ERROR << "Callback Error: " << ec.message(); 1190 return; 1191 } 1192 std::size_t index = 0; 1193 while ((index + iEventSize) <= bytesTransferred) 1194 { 1195 struct inotify_event event 1196 {}; 1197 std::memcpy(&event, &readBuffer[index], iEventSize); 1198 if (event.wd == dirWatchDesc) 1199 { 1200 if ((event.len == 0) || 1201 (index + iEventSize + event.len > bytesTransferred)) 1202 { 1203 index += (iEventSize + event.len); 1204 continue; 1205 } 1206 1207 std::string fileName(&readBuffer[index + iEventSize], 1208 event.len); 1209 if (std::strcmp(fileName.c_str(), "redfish") != 0) 1210 { 1211 index += (iEventSize + event.len); 1212 continue; 1213 } 1214 1215 BMCWEB_LOG_DEBUG 1216 << "Redfish log file created/deleted. event.name: " 1217 << fileName; 1218 if (event.mask == IN_CREATE) 1219 { 1220 if (fileWatchDesc != -1) 1221 { 1222 BMCWEB_LOG_DEBUG 1223 << "Remove and Add inotify watcher on " 1224 "redfish event log file"; 1225 // Remove existing inotify watcher and add 1226 // with new redfish event log file. 1227 inotify_rm_watch(inotifyFd, fileWatchDesc); 1228 fileWatchDesc = -1; 1229 } 1230 1231 fileWatchDesc = inotify_add_watch( 1232 inotifyFd, redfishEventLogFile, IN_MODIFY); 1233 if (fileWatchDesc == -1) 1234 { 1235 BMCWEB_LOG_ERROR 1236 << "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 std::vector<std::pair<std::string, dbus::utility::DbusVariantType>> 1329 props; 1330 std::vector<std::string> invalidProps; 1331 msg.read(interface, props, invalidProps); 1332 1333 auto found = 1334 std::find_if(props.begin(), props.end(), 1335 [](const auto& x) { return x.first == "Readings"; }); 1336 if (found == props.end()) 1337 { 1338 BMCWEB_LOG_INFO << "Failed to get Readings from Report properties"; 1339 return; 1340 } 1341 1342 const telemetry::TimestampReadings* readings = 1343 std::get_if<telemetry::TimestampReadings>(&found->second); 1344 if (readings == nullptr) 1345 { 1346 BMCWEB_LOG_INFO << "Failed to get Readings from Report properties"; 1347 return; 1348 } 1349 1350 for (const auto& it : 1351 EventServiceManager::getInstance().subscriptionsMap) 1352 { 1353 Subscription& entry = *it.second; 1354 if (entry.eventFormatType == metricReportFormatType) 1355 { 1356 entry.filterAndSendReports(id, *readings); 1357 } 1358 } 1359 } 1360 1361 void unregisterMetricReportSignal() 1362 { 1363 if (matchTelemetryMonitor) 1364 { 1365 BMCWEB_LOG_DEBUG << "Metrics report signal - Unregister"; 1366 matchTelemetryMonitor.reset(); 1367 matchTelemetryMonitor = nullptr; 1368 } 1369 } 1370 1371 void registerMetricReportSignal() 1372 { 1373 if (!serviceEnabled || matchTelemetryMonitor) 1374 { 1375 BMCWEB_LOG_DEBUG << "Not registering metric report signal."; 1376 return; 1377 } 1378 1379 BMCWEB_LOG_DEBUG << "Metrics report signal - Register"; 1380 std::string matchStr = "type='signal',member='PropertiesChanged'," 1381 "interface='org.freedesktop.DBus.Properties'," 1382 "arg0=xyz.openbmc_project.Telemetry.Report"; 1383 1384 matchTelemetryMonitor = std::make_shared<sdbusplus::bus::match::match>( 1385 *crow::connections::systemBus, matchStr, getReadingsForReport); 1386 } 1387 }; 1388 1389 } // namespace redfish 1390