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