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 if (conn != nullptr) 557 { 558 conn->setRetryConfig(retryAttempts, retryTimeoutInterval); 559 } 560 } 561 562 void updateRetryPolicy() 563 { 564 if (conn != nullptr) 565 { 566 conn->setRetryPolicy(retryPolicy); 567 } 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 static constexpr const bool defaultEnabledState = true; 581 static constexpr const uint32_t defaultRetryAttempts = 3; 582 static constexpr const uint32_t defaultRetryInterval = 30; 583 static constexpr const char* defaulEventFormatType = "Event"; 584 static constexpr const char* defaulSubscriptionType = "RedfishEvent"; 585 static constexpr const char* defaulRetryPolicy = "TerminateAfterRetries"; 586 587 class EventServiceManager 588 { 589 private: 590 bool serviceEnabled; 591 uint32_t retryAttempts; 592 uint32_t retryTimeoutInterval; 593 594 EventServiceManager(const EventServiceManager&) = delete; 595 EventServiceManager& operator=(const EventServiceManager&) = delete; 596 EventServiceManager(EventServiceManager&&) = delete; 597 EventServiceManager& operator=(EventServiceManager&&) = delete; 598 599 EventServiceManager() : 600 noOfEventLogSubscribers(0), noOfMetricReportSubscribers(0) 601 { 602 // Load config from persist store. 603 initConfig(); 604 } 605 606 std::string lastEventTStr; 607 size_t noOfEventLogSubscribers; 608 size_t noOfMetricReportSubscribers; 609 std::shared_ptr<sdbusplus::bus::match::match> matchTelemetryMonitor; 610 boost::container::flat_map<std::string, std::shared_ptr<Subscription>> 611 subscriptionsMap; 612 613 public: 614 static EventServiceManager& getInstance() 615 { 616 static EventServiceManager handler; 617 return handler; 618 } 619 620 void loadDefaultConfig() 621 { 622 serviceEnabled = defaultEnabledState; 623 retryAttempts = defaultRetryAttempts; 624 retryTimeoutInterval = defaultRetryInterval; 625 } 626 627 void initConfig() 628 { 629 std::ifstream eventConfigFile(eventServiceFile); 630 if (!eventConfigFile.good()) 631 { 632 BMCWEB_LOG_DEBUG << "EventService config not exist"; 633 loadDefaultConfig(); 634 return; 635 } 636 auto jsonData = nlohmann::json::parse(eventConfigFile, nullptr, false); 637 if (jsonData.is_discarded()) 638 { 639 BMCWEB_LOG_ERROR << "EventService config parse error."; 640 loadDefaultConfig(); 641 return; 642 } 643 644 nlohmann::json jsonConfig; 645 if (json_util::getValueFromJsonObject(jsonData, "Configuration", 646 jsonConfig)) 647 { 648 if (!json_util::getValueFromJsonObject(jsonConfig, "ServiceEnabled", 649 serviceEnabled)) 650 { 651 serviceEnabled = defaultEnabledState; 652 } 653 if (!json_util::getValueFromJsonObject( 654 jsonConfig, "DeliveryRetryAttempts", retryAttempts)) 655 { 656 retryAttempts = defaultRetryAttempts; 657 } 658 if (!json_util::getValueFromJsonObject( 659 jsonConfig, "DeliveryRetryIntervalSeconds", 660 retryTimeoutInterval)) 661 { 662 retryTimeoutInterval = defaultRetryInterval; 663 } 664 } 665 else 666 { 667 loadDefaultConfig(); 668 } 669 670 nlohmann::json subscriptionsList; 671 if (!json_util::getValueFromJsonObject(jsonData, "Subscriptions", 672 subscriptionsList)) 673 { 674 BMCWEB_LOG_DEBUG << "EventService: Subscriptions not exist."; 675 return; 676 } 677 678 for (nlohmann::json& jsonObj : subscriptionsList) 679 { 680 std::string protocol; 681 if (!json_util::getValueFromJsonObject(jsonObj, "Protocol", 682 protocol)) 683 { 684 BMCWEB_LOG_DEBUG << "Invalid subscription Protocol exist."; 685 continue; 686 } 687 688 std::string subscriptionType; 689 if (!json_util::getValueFromJsonObject(jsonObj, "SubscriptionType", 690 subscriptionType)) 691 { 692 subscriptionType = defaulSubscriptionType; 693 } 694 // SSE connections are initiated from client 695 // and can't be re-established from server. 696 if (subscriptionType == "SSE") 697 { 698 BMCWEB_LOG_DEBUG 699 << "The subscription type is SSE, so skipping."; 700 continue; 701 } 702 703 std::string destination; 704 if (!json_util::getValueFromJsonObject(jsonObj, "Destination", 705 destination)) 706 { 707 BMCWEB_LOG_DEBUG << "Invalid subscription destination exist."; 708 continue; 709 } 710 std::string host; 711 std::string urlProto; 712 std::string port; 713 std::string path; 714 bool status = 715 validateAndSplitUrl(destination, urlProto, host, port, path); 716 717 if (!status) 718 { 719 BMCWEB_LOG_ERROR 720 << "Failed to validate and split destination url"; 721 continue; 722 } 723 std::shared_ptr<Subscription> subValue = 724 std::make_shared<Subscription>(host, port, path, urlProto); 725 726 subValue->destinationUrl = destination; 727 subValue->protocol = protocol; 728 subValue->subscriptionType = subscriptionType; 729 if (!json_util::getValueFromJsonObject( 730 jsonObj, "DeliveryRetryPolicy", subValue->retryPolicy)) 731 { 732 subValue->retryPolicy = defaulRetryPolicy; 733 } 734 if (!json_util::getValueFromJsonObject(jsonObj, "EventFormatType", 735 subValue->eventFormatType)) 736 { 737 subValue->eventFormatType = defaulEventFormatType; 738 } 739 json_util::getValueFromJsonObject(jsonObj, "Context", 740 subValue->customText); 741 json_util::getValueFromJsonObject(jsonObj, "MessageIds", 742 subValue->registryMsgIds); 743 json_util::getValueFromJsonObject(jsonObj, "RegistryPrefixes", 744 subValue->registryPrefixes); 745 json_util::getValueFromJsonObject(jsonObj, "HttpHeaders", 746 subValue->httpHeaders); 747 json_util::getValueFromJsonObject( 748 jsonObj, "MetricReportDefinitions", 749 subValue->metricReportDefinitions); 750 751 std::string id = addSubscription(subValue, false); 752 if (id.empty()) 753 { 754 BMCWEB_LOG_ERROR << "Failed to add subscription"; 755 } 756 } 757 return; 758 } 759 760 void updateSubscriptionData() 761 { 762 // Persist the config and subscription data. 763 nlohmann::json jsonData; 764 765 nlohmann::json& configObj = jsonData["Configuration"]; 766 configObj["ServiceEnabled"] = serviceEnabled; 767 configObj["DeliveryRetryAttempts"] = retryAttempts; 768 configObj["DeliveryRetryIntervalSeconds"] = retryTimeoutInterval; 769 770 nlohmann::json& subListArray = jsonData["Subscriptions"]; 771 subListArray = nlohmann::json::array(); 772 773 for (const auto& it : subscriptionsMap) 774 { 775 std::shared_ptr<Subscription> subValue = it.second; 776 // Don't preserve SSE connections. Its initiated from 777 // client side and can't be re-established from server. 778 if (subValue->subscriptionType == "SSE") 779 { 780 BMCWEB_LOG_DEBUG 781 << "The subscription type is SSE, so skipping."; 782 continue; 783 } 784 785 nlohmann::json entry; 786 entry["Context"] = subValue->customText; 787 entry["DeliveryRetryPolicy"] = subValue->retryPolicy; 788 entry["Destination"] = subValue->destinationUrl; 789 entry["EventFormatType"] = subValue->eventFormatType; 790 entry["HttpHeaders"] = subValue->httpHeaders; 791 entry["MessageIds"] = subValue->registryMsgIds; 792 entry["Protocol"] = subValue->protocol; 793 entry["RegistryPrefixes"] = subValue->registryPrefixes; 794 entry["SubscriptionType"] = subValue->subscriptionType; 795 entry["MetricReportDefinitions"] = 796 subValue->metricReportDefinitions; 797 798 subListArray.push_back(entry); 799 } 800 801 const std::string tmpFile(std::string(eventServiceFile) + "_tmp"); 802 std::ofstream ofs(tmpFile, std::ios::out); 803 const auto& writeData = jsonData.dump(); 804 ofs << writeData; 805 ofs.close(); 806 807 BMCWEB_LOG_DEBUG << "EventService config updated to file."; 808 if (std::rename(tmpFile.c_str(), eventServiceFile) != 0) 809 { 810 BMCWEB_LOG_ERROR << "Error in renaming temporary file: " 811 << tmpFile.c_str(); 812 } 813 } 814 815 EventServiceConfig getEventServiceConfig() 816 { 817 return {serviceEnabled, retryAttempts, retryTimeoutInterval}; 818 } 819 820 void setEventServiceConfig(const EventServiceConfig& cfg) 821 { 822 bool updateConfig = false; 823 bool updateRetryCfg = false; 824 825 if (serviceEnabled != std::get<0>(cfg)) 826 { 827 serviceEnabled = std::get<0>(cfg); 828 if (serviceEnabled && noOfMetricReportSubscribers) 829 { 830 registerMetricReportSignal(); 831 } 832 else 833 { 834 unregisterMetricReportSignal(); 835 } 836 updateConfig = true; 837 } 838 839 if (retryAttempts != std::get<1>(cfg)) 840 { 841 retryAttempts = std::get<1>(cfg); 842 updateConfig = true; 843 updateRetryCfg = true; 844 } 845 846 if (retryTimeoutInterval != std::get<2>(cfg)) 847 { 848 retryTimeoutInterval = std::get<2>(cfg); 849 updateConfig = true; 850 updateRetryCfg = true; 851 } 852 853 if (updateConfig) 854 { 855 updateSubscriptionData(); 856 } 857 858 if (updateRetryCfg) 859 { 860 // Update the changed retry config to all subscriptions 861 for (const auto& it : 862 EventServiceManager::getInstance().subscriptionsMap) 863 { 864 std::shared_ptr<Subscription> entry = it.second; 865 entry->updateRetryConfig(retryAttempts, retryTimeoutInterval); 866 } 867 } 868 } 869 870 void updateNoOfSubscribersCount() 871 { 872 size_t eventLogSubCount = 0; 873 size_t metricReportSubCount = 0; 874 for (const auto& it : subscriptionsMap) 875 { 876 std::shared_ptr<Subscription> entry = it.second; 877 if (entry->eventFormatType == eventFormatType) 878 { 879 eventLogSubCount++; 880 } 881 else if (entry->eventFormatType == metricReportFormatType) 882 { 883 metricReportSubCount++; 884 } 885 } 886 887 noOfEventLogSubscribers = eventLogSubCount; 888 if (noOfMetricReportSubscribers != metricReportSubCount) 889 { 890 noOfMetricReportSubscribers = metricReportSubCount; 891 if (noOfMetricReportSubscribers) 892 { 893 registerMetricReportSignal(); 894 } 895 else 896 { 897 unregisterMetricReportSignal(); 898 } 899 } 900 } 901 902 std::shared_ptr<Subscription> getSubscription(const std::string& id) 903 { 904 auto obj = subscriptionsMap.find(id); 905 if (obj == subscriptionsMap.end()) 906 { 907 BMCWEB_LOG_ERROR << "No subscription exist with ID:" << id; 908 return nullptr; 909 } 910 std::shared_ptr<Subscription> subValue = obj->second; 911 return subValue; 912 } 913 914 std::string addSubscription(const std::shared_ptr<Subscription> subValue, 915 const bool updateFile = true) 916 { 917 std::srand(static_cast<uint32_t>(std::time(0))); 918 std::string id; 919 920 int retry = 3; 921 while (retry) 922 { 923 id = std::to_string(std::rand()); 924 auto inserted = subscriptionsMap.insert(std::pair(id, subValue)); 925 if (inserted.second) 926 { 927 break; 928 } 929 --retry; 930 }; 931 932 if (retry <= 0) 933 { 934 BMCWEB_LOG_ERROR << "Failed to generate random number"; 935 return std::string(""); 936 } 937 938 updateNoOfSubscribersCount(); 939 940 if (updateFile) 941 { 942 updateSubscriptionData(); 943 } 944 945 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES 946 if (lastEventTStr.empty()) 947 { 948 cacheLastEventTimestamp(); 949 } 950 #endif 951 // Update retry configuration. 952 subValue->updateRetryConfig(retryAttempts, retryTimeoutInterval); 953 subValue->updateRetryPolicy(); 954 955 return id; 956 } 957 958 bool isSubscriptionExist(const std::string& id) 959 { 960 auto obj = subscriptionsMap.find(id); 961 if (obj == subscriptionsMap.end()) 962 { 963 return false; 964 } 965 return true; 966 } 967 968 void deleteSubscription(const std::string& id) 969 { 970 auto obj = subscriptionsMap.find(id); 971 if (obj != subscriptionsMap.end()) 972 { 973 subscriptionsMap.erase(obj); 974 updateNoOfSubscribersCount(); 975 updateSubscriptionData(); 976 } 977 } 978 979 size_t getNumberOfSubscriptions() 980 { 981 return subscriptionsMap.size(); 982 } 983 984 std::vector<std::string> getAllIDs() 985 { 986 std::vector<std::string> idList; 987 for (const auto& it : subscriptionsMap) 988 { 989 idList.emplace_back(it.first); 990 } 991 return idList; 992 } 993 994 bool isDestinationExist(const std::string& destUrl) 995 { 996 for (const auto& it : subscriptionsMap) 997 { 998 std::shared_ptr<Subscription> entry = it.second; 999 if (entry->destinationUrl == destUrl) 1000 { 1001 BMCWEB_LOG_ERROR << "Destination exist already" << destUrl; 1002 return true; 1003 } 1004 } 1005 return false; 1006 } 1007 1008 void sendTestEventLog() 1009 { 1010 for (const auto& it : this->subscriptionsMap) 1011 { 1012 std::shared_ptr<Subscription> entry = it.second; 1013 entry->sendTestEventLog(); 1014 } 1015 } 1016 1017 #ifndef BMCWEB_ENABLE_REDFISH_DBUS_LOG_ENTRIES 1018 void cacheLastEventTimestamp() 1019 { 1020 std::ifstream logStream(redfishEventLogFile); 1021 if (!logStream.good()) 1022 { 1023 BMCWEB_LOG_ERROR << " Redfish log file open failed \n"; 1024 return; 1025 } 1026 std::string logEntry; 1027 while (std::getline(logStream, logEntry)) 1028 { 1029 size_t space = logEntry.find_first_of(" "); 1030 if (space == std::string::npos) 1031 { 1032 // Shouldn't enter here but lets skip it. 1033 BMCWEB_LOG_DEBUG << "Invalid log entry found."; 1034 continue; 1035 } 1036 lastEventTStr = logEntry.substr(0, space); 1037 } 1038 BMCWEB_LOG_DEBUG << "Last Event time stamp set: " << lastEventTStr; 1039 } 1040 1041 void readEventLogsFromFile() 1042 { 1043 if (!serviceEnabled || !noOfEventLogSubscribers) 1044 { 1045 BMCWEB_LOG_DEBUG << "EventService disabled or no Subscriptions."; 1046 return; 1047 } 1048 std::ifstream logStream(redfishEventLogFile); 1049 if (!logStream.good()) 1050 { 1051 BMCWEB_LOG_ERROR << " Redfish log file open failed"; 1052 return; 1053 } 1054 1055 std::vector<EventLogObjectsType> eventRecords; 1056 1057 bool startLogCollection = false; 1058 bool firstEntry = true; 1059 1060 std::string logEntry; 1061 while (std::getline(logStream, logEntry)) 1062 { 1063 if (!startLogCollection) 1064 { 1065 if (boost::starts_with(logEntry, lastEventTStr)) 1066 { 1067 startLogCollection = true; 1068 } 1069 continue; 1070 } 1071 1072 std::string idStr; 1073 if (!event_log::getUniqueEntryID(logEntry, idStr, firstEntry)) 1074 { 1075 continue; 1076 } 1077 firstEntry = false; 1078 1079 std::string timestamp; 1080 std::string messageID; 1081 std::vector<std::string> messageArgs; 1082 if (event_log::getEventLogParams(logEntry, timestamp, messageID, 1083 messageArgs) != 0) 1084 { 1085 BMCWEB_LOG_DEBUG << "Read eventLog entry params failed"; 1086 continue; 1087 } 1088 1089 std::string registryName; 1090 std::string messageKey; 1091 event_log::getRegistryAndMessageKey(messageID, registryName, 1092 messageKey); 1093 if (registryName.empty() || messageKey.empty()) 1094 { 1095 continue; 1096 } 1097 1098 lastEventTStr = timestamp; 1099 eventRecords.emplace_back(idStr, timestamp, messageID, registryName, 1100 messageKey, messageArgs); 1101 } 1102 1103 for (const auto& it : this->subscriptionsMap) 1104 { 1105 std::shared_ptr<Subscription> entry = it.second; 1106 if (entry->eventFormatType == "Event") 1107 { 1108 entry->filterAndSendEventLogs(eventRecords); 1109 } 1110 } 1111 } 1112 1113 static void watchRedfishEventLogFile() 1114 { 1115 if (inotifyConn == nullptr) 1116 { 1117 return; 1118 } 1119 1120 static std::array<char, 1024> readBuffer; 1121 1122 inotifyConn->async_read_some( 1123 boost::asio::buffer(readBuffer), 1124 [&](const boost::system::error_code& ec, 1125 const std::size_t& bytesTransferred) { 1126 if (ec) 1127 { 1128 BMCWEB_LOG_ERROR << "Callback Error: " << ec.message(); 1129 return; 1130 } 1131 std::size_t index = 0; 1132 while ((index + iEventSize) <= bytesTransferred) 1133 { 1134 struct inotify_event event; 1135 std::memcpy(&event, &readBuffer[index], iEventSize); 1136 if (event.wd == dirWatchDesc) 1137 { 1138 if ((event.len == 0) || 1139 (index + iEventSize + event.len > bytesTransferred)) 1140 { 1141 index += (iEventSize + event.len); 1142 continue; 1143 } 1144 1145 std::string fileName(&readBuffer[index + iEventSize], 1146 event.len); 1147 if (std::strcmp(fileName.c_str(), "redfish") != 0) 1148 { 1149 index += (iEventSize + event.len); 1150 continue; 1151 } 1152 1153 BMCWEB_LOG_DEBUG 1154 << "Redfish log file created/deleted. event.name: " 1155 << fileName; 1156 if (event.mask == IN_CREATE) 1157 { 1158 if (fileWatchDesc != -1) 1159 { 1160 BMCWEB_LOG_DEBUG 1161 << "Redfish log file is already on " 1162 "inotify_add_watch."; 1163 return; 1164 } 1165 1166 fileWatchDesc = inotify_add_watch( 1167 inotifyFd, redfishEventLogFile, IN_MODIFY); 1168 if (fileWatchDesc == -1) 1169 { 1170 BMCWEB_LOG_ERROR 1171 << "inotify_add_watch failed for " 1172 "redfish log file."; 1173 return; 1174 } 1175 1176 EventServiceManager::getInstance() 1177 .cacheLastEventTimestamp(); 1178 EventServiceManager::getInstance() 1179 .readEventLogsFromFile(); 1180 } 1181 else if ((event.mask == IN_DELETE) || 1182 (event.mask == IN_MOVED_TO)) 1183 { 1184 if (fileWatchDesc != -1) 1185 { 1186 inotify_rm_watch(inotifyFd, fileWatchDesc); 1187 fileWatchDesc = -1; 1188 } 1189 } 1190 } 1191 else if (event.wd == fileWatchDesc) 1192 { 1193 if (event.mask == IN_MODIFY) 1194 { 1195 EventServiceManager::getInstance() 1196 .readEventLogsFromFile(); 1197 } 1198 } 1199 index += (iEventSize + event.len); 1200 } 1201 1202 watchRedfishEventLogFile(); 1203 }); 1204 } 1205 1206 static int startEventLogMonitor(boost::asio::io_context& ioc) 1207 { 1208 inotifyConn = 1209 std::make_shared<boost::asio::posix::stream_descriptor>(ioc); 1210 inotifyFd = inotify_init1(IN_NONBLOCK); 1211 if (inotifyFd == -1) 1212 { 1213 BMCWEB_LOG_ERROR << "inotify_init1 failed."; 1214 return -1; 1215 } 1216 1217 // Add watch on directory to handle redfish event log file 1218 // create/delete. 1219 dirWatchDesc = inotify_add_watch(inotifyFd, redfishEventLogDir, 1220 IN_CREATE | IN_MOVED_TO | IN_DELETE); 1221 if (dirWatchDesc == -1) 1222 { 1223 BMCWEB_LOG_ERROR 1224 << "inotify_add_watch failed for event log directory."; 1225 return -1; 1226 } 1227 1228 // Watch redfish event log file for modifications. 1229 fileWatchDesc = 1230 inotify_add_watch(inotifyFd, redfishEventLogFile, IN_MODIFY); 1231 if (fileWatchDesc == -1) 1232 { 1233 BMCWEB_LOG_ERROR 1234 << "inotify_add_watch failed for redfish log file."; 1235 // Don't return error if file not exist. 1236 // Watch on directory will handle create/delete of file. 1237 } 1238 1239 // monitor redfish event log file 1240 inotifyConn->assign(inotifyFd); 1241 watchRedfishEventLogFile(); 1242 1243 return 0; 1244 } 1245 1246 #endif 1247 1248 void getMetricReading(const std::string& service, 1249 const std::string& objPath, const std::string& intf) 1250 { 1251 std::size_t found = objPath.find_last_of("/"); 1252 if (found == std::string::npos) 1253 { 1254 BMCWEB_LOG_DEBUG << "Invalid objPath received"; 1255 return; 1256 } 1257 1258 std::string idStr = objPath.substr(found + 1); 1259 if (idStr.empty()) 1260 { 1261 BMCWEB_LOG_DEBUG << "Invalid ID in objPath"; 1262 return; 1263 } 1264 1265 crow::connections::systemBus->async_method_call( 1266 [idStr{std::move(idStr)}]( 1267 const boost::system::error_code ec, 1268 boost::container::flat_map< 1269 std::string, std::variant<std::string, ReadingsObjType>>& 1270 resp) { 1271 if (ec) 1272 { 1273 BMCWEB_LOG_DEBUG 1274 << "D-Bus call failed to GetAll metric readings."; 1275 return; 1276 } 1277 1278 const std::string* timestampPtr = 1279 std::get_if<std::string>(&resp["Timestamp"]); 1280 if (!timestampPtr) 1281 { 1282 BMCWEB_LOG_DEBUG << "Failed to Get timestamp."; 1283 return; 1284 } 1285 1286 ReadingsObjType* readingsPtr = 1287 std::get_if<ReadingsObjType>(&resp["Readings"]); 1288 if (!readingsPtr) 1289 { 1290 BMCWEB_LOG_DEBUG << "Failed to Get Readings property."; 1291 return; 1292 } 1293 1294 if (!readingsPtr->size()) 1295 { 1296 BMCWEB_LOG_DEBUG << "No metrics report to be transferred"; 1297 return; 1298 } 1299 1300 for (const auto& it : 1301 EventServiceManager::getInstance().subscriptionsMap) 1302 { 1303 std::shared_ptr<Subscription> entry = it.second; 1304 if (entry->eventFormatType == metricReportFormatType) 1305 { 1306 entry->filterAndSendReports(idStr, *timestampPtr, 1307 *readingsPtr); 1308 } 1309 } 1310 }, 1311 service, objPath, "org.freedesktop.DBus.Properties", "GetAll", 1312 intf); 1313 } 1314 1315 void unregisterMetricReportSignal() 1316 { 1317 if (matchTelemetryMonitor) 1318 { 1319 BMCWEB_LOG_DEBUG << "Metrics report signal - Unregister"; 1320 matchTelemetryMonitor.reset(); 1321 matchTelemetryMonitor = nullptr; 1322 } 1323 } 1324 1325 void registerMetricReportSignal() 1326 { 1327 if (!serviceEnabled || matchTelemetryMonitor) 1328 { 1329 BMCWEB_LOG_DEBUG << "Not registering metric report signal."; 1330 return; 1331 } 1332 1333 BMCWEB_LOG_DEBUG << "Metrics report signal - Register"; 1334 std::string matchStr( 1335 "type='signal',member='ReportUpdate', " 1336 "interface='xyz.openbmc_project.MonitoringService.Report'"); 1337 1338 matchTelemetryMonitor = std::make_shared<sdbusplus::bus::match::match>( 1339 *crow::connections::systemBus, matchStr, 1340 [this](sdbusplus::message::message& msg) { 1341 if (msg.is_method_error()) 1342 { 1343 BMCWEB_LOG_ERROR << "TelemetryMonitor Signal error"; 1344 return; 1345 } 1346 1347 std::string service = msg.get_sender(); 1348 std::string objPath = msg.get_path(); 1349 std::string intf = msg.get_interface(); 1350 getMetricReading(service, objPath, intf); 1351 }); 1352 } 1353 1354 bool validateAndSplitUrl(const std::string& destUrl, std::string& urlProto, 1355 std::string& host, std::string& port, 1356 std::string& path) 1357 { 1358 // Validate URL using regex expression 1359 // Format: <protocol>://<host>:<port>/<path> 1360 // protocol: http/https 1361 const std::regex urlRegex( 1362 "(http|https)://([^/\\x20\\x3f\\x23\\x3a]+):?([0-9]*)(/" 1363 "([^\\x20\\x23\\x3f]*\\x3f?([^\\x20\\x23\\x3f])*)?)"); 1364 std::cmatch match; 1365 if (!std::regex_match(destUrl.c_str(), match, urlRegex)) 1366 { 1367 BMCWEB_LOG_INFO << "Dest. url did not match "; 1368 return false; 1369 } 1370 1371 urlProto = std::string(match[1].first, match[1].second); 1372 if (urlProto == "http") 1373 { 1374 #ifndef BMCWEB_INSECURE_ENABLE_HTTP_PUSH_STYLE_EVENTING 1375 return false; 1376 #endif 1377 } 1378 1379 host = std::string(match[2].first, match[2].second); 1380 port = std::string(match[3].first, match[3].second); 1381 path = std::string(match[4].first, match[4].second); 1382 if (port.empty()) 1383 { 1384 if (urlProto == "http") 1385 { 1386 port = "80"; 1387 } 1388 else 1389 { 1390 port = "443"; 1391 } 1392 } 1393 if (path.empty()) 1394 { 1395 path = "/"; 1396 } 1397 return true; 1398 } 1399 }; // namespace redfish 1400 1401 } // namespace redfish 1402