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