1 /* 2 // Copyright (c) 2018 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 18 #include "gzfile.hpp" 19 #include "http_utility.hpp" 20 #include "human_sort.hpp" 21 #include "registries.hpp" 22 #include "registries/base_message_registry.hpp" 23 #include "registries/openbmc_message_registry.hpp" 24 #include "task.hpp" 25 26 #include <systemd/sd-journal.h> 27 #include <unistd.h> 28 29 #include <app.hpp> 30 #include <boost/algorithm/string/replace.hpp> 31 #include <boost/algorithm/string/split.hpp> 32 #include <boost/beast/http.hpp> 33 #include <boost/container/flat_map.hpp> 34 #include <boost/system/linux_error.hpp> 35 #include <dbus_utility.hpp> 36 #include <error_messages.hpp> 37 #include <registries/privilege_registry.hpp> 38 39 #include <charconv> 40 #include <filesystem> 41 #include <optional> 42 #include <span> 43 #include <string_view> 44 #include <variant> 45 46 namespace redfish 47 { 48 49 constexpr char const* crashdumpObject = "com.intel.crashdump"; 50 constexpr char const* crashdumpPath = "/com/intel/crashdump"; 51 constexpr char const* crashdumpInterface = "com.intel.crashdump"; 52 constexpr char const* deleteAllInterface = 53 "xyz.openbmc_project.Collection.DeleteAll"; 54 constexpr char const* crashdumpOnDemandInterface = 55 "com.intel.crashdump.OnDemand"; 56 constexpr char const* crashdumpTelemetryInterface = 57 "com.intel.crashdump.Telemetry"; 58 59 namespace message_registries 60 { 61 static const Message* 62 getMessageFromRegistry(const std::string& messageKey, 63 const std::span<const MessageEntry> registry) 64 { 65 std::span<const MessageEntry>::iterator messageIt = std::find_if( 66 registry.begin(), registry.end(), 67 [&messageKey](const MessageEntry& messageEntry) { 68 return std::strcmp(messageEntry.first, messageKey.c_str()) == 0; 69 }); 70 if (messageIt != registry.end()) 71 { 72 return &messageIt->second; 73 } 74 75 return nullptr; 76 } 77 78 static const Message* getMessage(const std::string_view& messageID) 79 { 80 // Redfish MessageIds are in the form 81 // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find 82 // the right Message 83 std::vector<std::string> fields; 84 fields.reserve(4); 85 boost::split(fields, messageID, boost::is_any_of(".")); 86 std::string& registryName = fields[0]; 87 std::string& messageKey = fields[3]; 88 89 // Find the right registry and check it for the MessageKey 90 if (std::string(base::header.registryPrefix) == registryName) 91 { 92 return getMessageFromRegistry( 93 messageKey, std::span<const MessageEntry>(base::registry)); 94 } 95 if (std::string(openbmc::header.registryPrefix) == registryName) 96 { 97 return getMessageFromRegistry( 98 messageKey, std::span<const MessageEntry>(openbmc::registry)); 99 } 100 return nullptr; 101 } 102 } // namespace message_registries 103 104 namespace fs = std::filesystem; 105 106 using GetManagedPropertyType = 107 boost::container::flat_map<std::string, dbus::utility::DbusVariantType>; 108 109 inline std::string translateSeverityDbusToRedfish(const std::string& s) 110 { 111 if ((s == "xyz.openbmc_project.Logging.Entry.Level.Alert") || 112 (s == "xyz.openbmc_project.Logging.Entry.Level.Critical") || 113 (s == "xyz.openbmc_project.Logging.Entry.Level.Emergency") || 114 (s == "xyz.openbmc_project.Logging.Entry.Level.Error")) 115 { 116 return "Critical"; 117 } 118 if ((s == "xyz.openbmc_project.Logging.Entry.Level.Debug") || 119 (s == "xyz.openbmc_project.Logging.Entry.Level.Informational") || 120 (s == "xyz.openbmc_project.Logging.Entry.Level.Notice")) 121 { 122 return "OK"; 123 } 124 if (s == "xyz.openbmc_project.Logging.Entry.Level.Warning") 125 { 126 return "Warning"; 127 } 128 return ""; 129 } 130 131 inline static int getJournalMetadata(sd_journal* journal, 132 const std::string_view& field, 133 std::string_view& contents) 134 { 135 const char* data = nullptr; 136 size_t length = 0; 137 int ret = 0; 138 // Get the metadata from the requested field of the journal entry 139 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) 140 const void** dataVoid = reinterpret_cast<const void**>(&data); 141 142 ret = sd_journal_get_data(journal, field.data(), dataVoid, &length); 143 if (ret < 0) 144 { 145 return ret; 146 } 147 contents = std::string_view(data, length); 148 // Only use the content after the "=" character. 149 contents.remove_prefix(std::min(contents.find('=') + 1, contents.size())); 150 return ret; 151 } 152 153 inline static int getJournalMetadata(sd_journal* journal, 154 const std::string_view& field, 155 const int& base, long int& contents) 156 { 157 int ret = 0; 158 std::string_view metadata; 159 // Get the metadata from the requested field of the journal entry 160 ret = getJournalMetadata(journal, field, metadata); 161 if (ret < 0) 162 { 163 return ret; 164 } 165 contents = strtol(metadata.data(), nullptr, base); 166 return ret; 167 } 168 169 inline static bool getEntryTimestamp(sd_journal* journal, 170 std::string& entryTimestamp) 171 { 172 int ret = 0; 173 uint64_t timestamp = 0; 174 ret = sd_journal_get_realtime_usec(journal, ×tamp); 175 if (ret < 0) 176 { 177 BMCWEB_LOG_ERROR << "Failed to read entry timestamp: " 178 << strerror(-ret); 179 return false; 180 } 181 entryTimestamp = crow::utility::getDateTimeUint(timestamp / 1000 / 1000); 182 return true; 183 } 184 185 static bool getSkipParam(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 186 const crow::Request& req, uint64_t& skip) 187 { 188 boost::urls::params_view::iterator it = req.urlView.params().find("$skip"); 189 if (it != req.urlView.params().end()) 190 { 191 std::from_chars_result r = std::from_chars( 192 (*it).value.data(), (*it).value.data() + (*it).value.size(), skip); 193 if (r.ec != std::errc()) 194 { 195 messages::queryParameterValueTypeError(asyncResp->res, "", "$skip"); 196 return false; 197 } 198 } 199 return true; 200 } 201 202 static constexpr const uint64_t maxEntriesPerPage = 1000; 203 static bool getTopParam(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 204 const crow::Request& req, uint64_t& top) 205 { 206 boost::urls::params_view::iterator it = req.urlView.params().find("$top"); 207 if (it != req.urlView.params().end()) 208 { 209 std::from_chars_result r = std::from_chars( 210 (*it).value.data(), (*it).value.data() + (*it).value.size(), top); 211 if (r.ec != std::errc()) 212 { 213 messages::queryParameterValueTypeError(asyncResp->res, "", "$top"); 214 return false; 215 } 216 if (top < 1U || top > maxEntriesPerPage) 217 { 218 219 messages::queryParameterOutOfRange( 220 asyncResp->res, std::to_string(top), "$top", 221 "1-" + std::to_string(maxEntriesPerPage)); 222 return false; 223 } 224 } 225 return true; 226 } 227 228 inline static bool getUniqueEntryID(sd_journal* journal, std::string& entryID, 229 const bool firstEntry = true) 230 { 231 int ret = 0; 232 static uint64_t prevTs = 0; 233 static int index = 0; 234 if (firstEntry) 235 { 236 prevTs = 0; 237 } 238 239 // Get the entry timestamp 240 uint64_t curTs = 0; 241 ret = sd_journal_get_realtime_usec(journal, &curTs); 242 if (ret < 0) 243 { 244 BMCWEB_LOG_ERROR << "Failed to read entry timestamp: " 245 << strerror(-ret); 246 return false; 247 } 248 // If the timestamp isn't unique, increment the index 249 if (curTs == prevTs) 250 { 251 index++; 252 } 253 else 254 { 255 // Otherwise, reset it 256 index = 0; 257 } 258 // Save the timestamp 259 prevTs = curTs; 260 261 entryID = std::to_string(curTs); 262 if (index > 0) 263 { 264 entryID += "_" + std::to_string(index); 265 } 266 return true; 267 } 268 269 static bool getUniqueEntryID(const std::string& logEntry, std::string& entryID, 270 const bool firstEntry = true) 271 { 272 static time_t prevTs = 0; 273 static int index = 0; 274 if (firstEntry) 275 { 276 prevTs = 0; 277 } 278 279 // Get the entry timestamp 280 std::time_t curTs = 0; 281 std::tm timeStruct = {}; 282 std::istringstream entryStream(logEntry); 283 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S")) 284 { 285 curTs = std::mktime(&timeStruct); 286 } 287 // If the timestamp isn't unique, increment the index 288 if (curTs == prevTs) 289 { 290 index++; 291 } 292 else 293 { 294 // Otherwise, reset it 295 index = 0; 296 } 297 // Save the timestamp 298 prevTs = curTs; 299 300 entryID = std::to_string(curTs); 301 if (index > 0) 302 { 303 entryID += "_" + std::to_string(index); 304 } 305 return true; 306 } 307 308 inline static bool 309 getTimestampFromID(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 310 const std::string& entryID, uint64_t& timestamp, 311 uint64_t& index) 312 { 313 if (entryID.empty()) 314 { 315 return false; 316 } 317 // Convert the unique ID back to a timestamp to find the entry 318 std::string_view tsStr(entryID); 319 320 auto underscorePos = tsStr.find('_'); 321 if (underscorePos != std::string_view::npos) 322 { 323 // Timestamp has an index 324 tsStr.remove_suffix(tsStr.size() - underscorePos); 325 std::string_view indexStr(entryID); 326 indexStr.remove_prefix(underscorePos + 1); 327 auto [ptr, ec] = std::from_chars( 328 indexStr.data(), indexStr.data() + indexStr.size(), index); 329 if (ec != std::errc()) 330 { 331 messages::resourceMissingAtURI(asyncResp->res, entryID); 332 return false; 333 } 334 } 335 // Timestamp has no index 336 auto [ptr, ec] = 337 std::from_chars(tsStr.data(), tsStr.data() + tsStr.size(), timestamp); 338 if (ec != std::errc()) 339 { 340 messages::resourceMissingAtURI(asyncResp->res, entryID); 341 return false; 342 } 343 return true; 344 } 345 346 static bool 347 getRedfishLogFiles(std::vector<std::filesystem::path>& redfishLogFiles) 348 { 349 static const std::filesystem::path redfishLogDir = "/var/log"; 350 static const std::string redfishLogFilename = "redfish"; 351 352 // Loop through the directory looking for redfish log files 353 for (const std::filesystem::directory_entry& dirEnt : 354 std::filesystem::directory_iterator(redfishLogDir)) 355 { 356 // If we find a redfish log file, save the path 357 std::string filename = dirEnt.path().filename(); 358 if (boost::starts_with(filename, redfishLogFilename)) 359 { 360 redfishLogFiles.emplace_back(redfishLogDir / filename); 361 } 362 } 363 // As the log files rotate, they are appended with a ".#" that is higher for 364 // the older logs. Since we don't expect more than 10 log files, we 365 // can just sort the list to get them in order from newest to oldest 366 std::sort(redfishLogFiles.begin(), redfishLogFiles.end()); 367 368 return !redfishLogFiles.empty(); 369 } 370 371 inline void 372 getDumpEntryCollection(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 373 const std::string& dumpType) 374 { 375 std::string dumpPath; 376 if (dumpType == "BMC") 377 { 378 dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/"; 379 } 380 else if (dumpType == "System") 381 { 382 dumpPath = "/redfish/v1/Systems/system/LogServices/Dump/Entries/"; 383 } 384 else 385 { 386 BMCWEB_LOG_ERROR << "Invalid dump type" << dumpType; 387 messages::internalError(asyncResp->res); 388 return; 389 } 390 391 crow::connections::systemBus->async_method_call( 392 [asyncResp, dumpPath, 393 dumpType](const boost::system::error_code ec, 394 dbus::utility::ManagedObjectType& resp) { 395 if (ec) 396 { 397 BMCWEB_LOG_ERROR << "DumpEntry resp_handler got error " << ec; 398 messages::internalError(asyncResp->res); 399 return; 400 } 401 402 nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"]; 403 entriesArray = nlohmann::json::array(); 404 std::string dumpEntryPath = 405 "/xyz/openbmc_project/dump/" + 406 std::string(boost::algorithm::to_lower_copy(dumpType)) + 407 "/entry/"; 408 409 for (auto& object : resp) 410 { 411 if (object.first.str.find(dumpEntryPath) == std::string::npos) 412 { 413 continue; 414 } 415 uint64_t timestamp = 0; 416 uint64_t size = 0; 417 std::string dumpStatus; 418 nlohmann::json thisEntry; 419 420 std::string entryID = object.first.filename(); 421 if (entryID.empty()) 422 { 423 continue; 424 } 425 426 for (auto& interfaceMap : object.second) 427 { 428 if (interfaceMap.first == 429 "xyz.openbmc_project.Common.Progress") 430 { 431 for (const auto& propertyMap : interfaceMap.second) 432 { 433 if (propertyMap.first == "Status") 434 { 435 auto status = std::get_if<std::string>( 436 &propertyMap.second); 437 if (status == nullptr) 438 { 439 messages::internalError(asyncResp->res); 440 break; 441 } 442 dumpStatus = *status; 443 } 444 } 445 } 446 else if (interfaceMap.first == 447 "xyz.openbmc_project.Dump.Entry") 448 { 449 450 for (auto& propertyMap : interfaceMap.second) 451 { 452 if (propertyMap.first == "Size") 453 { 454 auto sizePtr = 455 std::get_if<uint64_t>(&propertyMap.second); 456 if (sizePtr == nullptr) 457 { 458 messages::internalError(asyncResp->res); 459 break; 460 } 461 size = *sizePtr; 462 break; 463 } 464 } 465 } 466 else if (interfaceMap.first == 467 "xyz.openbmc_project.Time.EpochTime") 468 { 469 470 for (const auto& propertyMap : interfaceMap.second) 471 { 472 if (propertyMap.first == "Elapsed") 473 { 474 const uint64_t* usecsTimeStamp = 475 std::get_if<uint64_t>(&propertyMap.second); 476 if (usecsTimeStamp == nullptr) 477 { 478 messages::internalError(asyncResp->res); 479 break; 480 } 481 timestamp = (*usecsTimeStamp / 1000 / 1000); 482 break; 483 } 484 } 485 } 486 } 487 488 if (dumpStatus != 489 "xyz.openbmc_project.Common.Progress.OperationStatus.Completed" && 490 !dumpStatus.empty()) 491 { 492 // Dump status is not Complete, no need to enumerate 493 continue; 494 } 495 496 thisEntry["@odata.type"] = "#LogEntry.v1_8_0.LogEntry"; 497 thisEntry["@odata.id"] = dumpPath + entryID; 498 thisEntry["Id"] = entryID; 499 thisEntry["EntryType"] = "Event"; 500 thisEntry["Created"] = 501 crow::utility::getDateTimeUint(timestamp); 502 thisEntry["Name"] = dumpType + " Dump Entry"; 503 504 thisEntry["AdditionalDataSizeBytes"] = size; 505 506 if (dumpType == "BMC") 507 { 508 thisEntry["DiagnosticDataType"] = "Manager"; 509 thisEntry["AdditionalDataURI"] = 510 "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/" + 511 entryID + "/attachment"; 512 } 513 else if (dumpType == "System") 514 { 515 thisEntry["DiagnosticDataType"] = "OEM"; 516 thisEntry["OEMDiagnosticDataType"] = "System"; 517 thisEntry["AdditionalDataURI"] = 518 "/redfish/v1/Systems/system/LogServices/Dump/Entries/" + 519 entryID + "/attachment"; 520 } 521 entriesArray.push_back(std::move(thisEntry)); 522 } 523 asyncResp->res.jsonValue["Members@odata.count"] = 524 entriesArray.size(); 525 }, 526 "xyz.openbmc_project.Dump.Manager", "/xyz/openbmc_project/dump", 527 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); 528 } 529 530 inline void 531 getDumpEntryById(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 532 const std::string& entryID, const std::string& dumpType) 533 { 534 std::string dumpPath; 535 if (dumpType == "BMC") 536 { 537 dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/"; 538 } 539 else if (dumpType == "System") 540 { 541 dumpPath = "/redfish/v1/Systems/system/LogServices/Dump/Entries/"; 542 } 543 else 544 { 545 BMCWEB_LOG_ERROR << "Invalid dump type" << dumpType; 546 messages::internalError(asyncResp->res); 547 return; 548 } 549 550 crow::connections::systemBus->async_method_call( 551 [asyncResp, entryID, dumpPath, 552 dumpType](const boost::system::error_code ec, 553 dbus::utility::ManagedObjectType& resp) { 554 if (ec) 555 { 556 BMCWEB_LOG_ERROR << "DumpEntry resp_handler got error " << ec; 557 messages::internalError(asyncResp->res); 558 return; 559 } 560 561 bool foundDumpEntry = false; 562 std::string dumpEntryPath = 563 "/xyz/openbmc_project/dump/" + 564 std::string(boost::algorithm::to_lower_copy(dumpType)) + 565 "/entry/"; 566 567 for (const auto& objectPath : resp) 568 { 569 if (objectPath.first.str != dumpEntryPath + entryID) 570 { 571 continue; 572 } 573 574 foundDumpEntry = true; 575 uint64_t timestamp = 0; 576 uint64_t size = 0; 577 std::string dumpStatus; 578 579 for (const auto& interfaceMap : objectPath.second) 580 { 581 if (interfaceMap.first == 582 "xyz.openbmc_project.Common.Progress") 583 { 584 for (const auto& propertyMap : interfaceMap.second) 585 { 586 if (propertyMap.first == "Status") 587 { 588 const std::string* status = 589 std::get_if<std::string>( 590 &propertyMap.second); 591 if (status == nullptr) 592 { 593 messages::internalError(asyncResp->res); 594 break; 595 } 596 dumpStatus = *status; 597 } 598 } 599 } 600 else if (interfaceMap.first == 601 "xyz.openbmc_project.Dump.Entry") 602 { 603 for (const auto& propertyMap : interfaceMap.second) 604 { 605 if (propertyMap.first == "Size") 606 { 607 const uint64_t* sizePtr = 608 std::get_if<uint64_t>(&propertyMap.second); 609 if (sizePtr == nullptr) 610 { 611 messages::internalError(asyncResp->res); 612 break; 613 } 614 size = *sizePtr; 615 break; 616 } 617 } 618 } 619 else if (interfaceMap.first == 620 "xyz.openbmc_project.Time.EpochTime") 621 { 622 for (const auto& propertyMap : interfaceMap.second) 623 { 624 if (propertyMap.first == "Elapsed") 625 { 626 const uint64_t* usecsTimeStamp = 627 std::get_if<uint64_t>(&propertyMap.second); 628 if (usecsTimeStamp == nullptr) 629 { 630 messages::internalError(asyncResp->res); 631 break; 632 } 633 timestamp = *usecsTimeStamp / 1000 / 1000; 634 break; 635 } 636 } 637 } 638 } 639 640 if (dumpStatus != 641 "xyz.openbmc_project.Common.Progress.OperationStatus.Completed" && 642 !dumpStatus.empty()) 643 { 644 // Dump status is not Complete 645 // return not found until status is changed to Completed 646 messages::resourceNotFound(asyncResp->res, 647 dumpType + " dump", entryID); 648 return; 649 } 650 651 asyncResp->res.jsonValue["@odata.type"] = 652 "#LogEntry.v1_8_0.LogEntry"; 653 asyncResp->res.jsonValue["@odata.id"] = dumpPath + entryID; 654 asyncResp->res.jsonValue["Id"] = entryID; 655 asyncResp->res.jsonValue["EntryType"] = "Event"; 656 asyncResp->res.jsonValue["Created"] = 657 crow::utility::getDateTimeUint(timestamp); 658 asyncResp->res.jsonValue["Name"] = dumpType + " Dump Entry"; 659 660 asyncResp->res.jsonValue["AdditionalDataSizeBytes"] = size; 661 662 if (dumpType == "BMC") 663 { 664 asyncResp->res.jsonValue["DiagnosticDataType"] = "Manager"; 665 asyncResp->res.jsonValue["AdditionalDataURI"] = 666 "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/" + 667 entryID + "/attachment"; 668 } 669 else if (dumpType == "System") 670 { 671 asyncResp->res.jsonValue["DiagnosticDataType"] = "OEM"; 672 asyncResp->res.jsonValue["OEMDiagnosticDataType"] = 673 "System"; 674 asyncResp->res.jsonValue["AdditionalDataURI"] = 675 "/redfish/v1/Systems/system/LogServices/Dump/Entries/" + 676 entryID + "/attachment"; 677 } 678 } 679 if (!foundDumpEntry) 680 { 681 BMCWEB_LOG_ERROR << "Can't find Dump Entry"; 682 messages::internalError(asyncResp->res); 683 return; 684 } 685 }, 686 "xyz.openbmc_project.Dump.Manager", "/xyz/openbmc_project/dump", 687 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); 688 } 689 690 inline void deleteDumpEntry(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 691 const std::string& entryID, 692 const std::string& dumpType) 693 { 694 auto respHandler = [asyncResp, 695 entryID](const boost::system::error_code ec) { 696 BMCWEB_LOG_DEBUG << "Dump Entry doDelete callback: Done"; 697 if (ec) 698 { 699 if (ec.value() == EBADR) 700 { 701 messages::resourceNotFound(asyncResp->res, "LogEntry", entryID); 702 return; 703 } 704 BMCWEB_LOG_ERROR << "Dump (DBus) doDelete respHandler got error " 705 << ec; 706 messages::internalError(asyncResp->res); 707 return; 708 } 709 }; 710 crow::connections::systemBus->async_method_call( 711 respHandler, "xyz.openbmc_project.Dump.Manager", 712 "/xyz/openbmc_project/dump/" + 713 std::string(boost::algorithm::to_lower_copy(dumpType)) + "/entry/" + 714 entryID, 715 "xyz.openbmc_project.Object.Delete", "Delete"); 716 } 717 718 inline void 719 createDumpTaskCallback(task::Payload&& payload, 720 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 721 const uint32_t& dumpId, const std::string& dumpPath, 722 const std::string& dumpType) 723 { 724 std::shared_ptr<task::TaskData> task = task::TaskData::createTask( 725 [dumpId, dumpPath, dumpType]( 726 boost::system::error_code err, sdbusplus::message::message& m, 727 const std::shared_ptr<task::TaskData>& taskData) { 728 if (err) 729 { 730 BMCWEB_LOG_ERROR << "Error in creating a dump"; 731 taskData->state = "Cancelled"; 732 return task::completed; 733 } 734 std::vector<std::pair< 735 std::string, std::vector<std::pair< 736 std::string, dbus::utility::DbusVariantType>>>> 737 interfacesList; 738 739 sdbusplus::message::object_path objPath; 740 741 m.read(objPath, interfacesList); 742 743 if (objPath.str == 744 "/xyz/openbmc_project/dump/" + 745 std::string(boost::algorithm::to_lower_copy(dumpType)) + 746 "/entry/" + std::to_string(dumpId)) 747 { 748 nlohmann::json retMessage = messages::success(); 749 taskData->messages.emplace_back(retMessage); 750 751 std::string headerLoc = 752 "Location: " + dumpPath + std::to_string(dumpId); 753 taskData->payload->httpHeaders.emplace_back( 754 std::move(headerLoc)); 755 756 taskData->state = "Completed"; 757 return task::completed; 758 } 759 return task::completed; 760 }, 761 "type='signal',interface='org.freedesktop.DBus.ObjectManager'," 762 "member='InterfacesAdded', " 763 "path='/xyz/openbmc_project/dump'"); 764 765 task->startTimer(std::chrono::minutes(3)); 766 task->populateResp(asyncResp->res); 767 task->payload.emplace(std::move(payload)); 768 } 769 770 inline void createDump(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 771 const crow::Request& req, const std::string& dumpType) 772 { 773 774 std::string dumpPath; 775 if (dumpType == "BMC") 776 { 777 dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/"; 778 } 779 else if (dumpType == "System") 780 { 781 dumpPath = "/redfish/v1/Systems/system/LogServices/Dump/Entries/"; 782 } 783 else 784 { 785 BMCWEB_LOG_ERROR << "Invalid dump type: " << dumpType; 786 messages::internalError(asyncResp->res); 787 return; 788 } 789 790 std::optional<std::string> diagnosticDataType; 791 std::optional<std::string> oemDiagnosticDataType; 792 793 if (!redfish::json_util::readJsonAction( 794 req, asyncResp->res, "DiagnosticDataType", diagnosticDataType, 795 "OEMDiagnosticDataType", oemDiagnosticDataType)) 796 { 797 return; 798 } 799 800 if (dumpType == "System") 801 { 802 if (!oemDiagnosticDataType || !diagnosticDataType) 803 { 804 BMCWEB_LOG_ERROR 805 << "CreateDump action parameter 'DiagnosticDataType'/'OEMDiagnosticDataType' value not found!"; 806 messages::actionParameterMissing( 807 asyncResp->res, "CollectDiagnosticData", 808 "DiagnosticDataType & OEMDiagnosticDataType"); 809 return; 810 } 811 if ((*oemDiagnosticDataType != "System") || 812 (*diagnosticDataType != "OEM")) 813 { 814 BMCWEB_LOG_ERROR << "Wrong parameter values passed"; 815 messages::invalidObject(asyncResp->res, 816 "System Dump creation parameters"); 817 return; 818 } 819 } 820 else if (dumpType == "BMC") 821 { 822 if (!diagnosticDataType) 823 { 824 BMCWEB_LOG_ERROR 825 << "CreateDump action parameter 'DiagnosticDataType' not found!"; 826 messages::actionParameterMissing( 827 asyncResp->res, "CollectDiagnosticData", "DiagnosticDataType"); 828 return; 829 } 830 if (*diagnosticDataType != "Manager") 831 { 832 BMCWEB_LOG_ERROR 833 << "Wrong parameter value passed for 'DiagnosticDataType'"; 834 messages::invalidObject(asyncResp->res, 835 "BMC Dump creation parameters"); 836 return; 837 } 838 } 839 840 crow::connections::systemBus->async_method_call( 841 [asyncResp, payload(task::Payload(req)), dumpPath, 842 dumpType](const boost::system::error_code ec, 843 const uint32_t& dumpId) mutable { 844 if (ec) 845 { 846 BMCWEB_LOG_ERROR << "CreateDump resp_handler got error " << ec; 847 messages::internalError(asyncResp->res); 848 return; 849 } 850 BMCWEB_LOG_DEBUG << "Dump Created. Id: " << dumpId; 851 852 createDumpTaskCallback(std::move(payload), asyncResp, dumpId, 853 dumpPath, dumpType); 854 }, 855 "xyz.openbmc_project.Dump.Manager", 856 "/xyz/openbmc_project/dump/" + 857 std::string(boost::algorithm::to_lower_copy(dumpType)), 858 "xyz.openbmc_project.Dump.Create", "CreateDump"); 859 } 860 861 inline void clearDump(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 862 const std::string& dumpType) 863 { 864 std::string dumpTypeLowerCopy = 865 std::string(boost::algorithm::to_lower_copy(dumpType)); 866 867 crow::connections::systemBus->async_method_call( 868 [asyncResp, dumpType](const boost::system::error_code ec, 869 const std::vector<std::string>& subTreePaths) { 870 if (ec) 871 { 872 BMCWEB_LOG_ERROR << "resp_handler got error " << ec; 873 messages::internalError(asyncResp->res); 874 return; 875 } 876 877 for (const std::string& path : subTreePaths) 878 { 879 sdbusplus::message::object_path objPath(path); 880 std::string logID = objPath.filename(); 881 if (logID.empty()) 882 { 883 continue; 884 } 885 deleteDumpEntry(asyncResp, logID, dumpType); 886 } 887 }, 888 "xyz.openbmc_project.ObjectMapper", 889 "/xyz/openbmc_project/object_mapper", 890 "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", 891 "/xyz/openbmc_project/dump/" + dumpTypeLowerCopy, 0, 892 std::array<std::string, 1>{"xyz.openbmc_project.Dump.Entry." + 893 dumpType}); 894 } 895 896 inline static void parseCrashdumpParameters( 897 const std::vector<std::pair<std::string, dbus::utility::DbusVariantType>>& 898 params, 899 std::string& filename, std::string& timestamp, std::string& logfile) 900 { 901 for (auto property : params) 902 { 903 if (property.first == "Timestamp") 904 { 905 const std::string* value = 906 std::get_if<std::string>(&property.second); 907 if (value != nullptr) 908 { 909 timestamp = *value; 910 } 911 } 912 else if (property.first == "Filename") 913 { 914 const std::string* value = 915 std::get_if<std::string>(&property.second); 916 if (value != nullptr) 917 { 918 filename = *value; 919 } 920 } 921 else if (property.first == "Log") 922 { 923 const std::string* value = 924 std::get_if<std::string>(&property.second); 925 if (value != nullptr) 926 { 927 logfile = *value; 928 } 929 } 930 } 931 } 932 933 constexpr char const* postCodeIface = "xyz.openbmc_project.State.Boot.PostCode"; 934 inline void requestRoutesSystemLogServiceCollection(App& app) 935 { 936 /** 937 * Functions triggers appropriate requests on DBus 938 */ 939 BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/") 940 .privileges(redfish::privileges::getLogServiceCollection) 941 .methods(boost::beast::http::verb::get)( 942 [](const crow::Request&, 943 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) 944 945 { 946 // Collections don't include the static data added by SubRoute 947 // because it has a duplicate entry for members 948 asyncResp->res.jsonValue["@odata.type"] = 949 "#LogServiceCollection.LogServiceCollection"; 950 asyncResp->res.jsonValue["@odata.id"] = 951 "/redfish/v1/Systems/system/LogServices"; 952 asyncResp->res.jsonValue["Name"] = 953 "System Log Services Collection"; 954 asyncResp->res.jsonValue["Description"] = 955 "Collection of LogServices for this Computer System"; 956 nlohmann::json& logServiceArray = 957 asyncResp->res.jsonValue["Members"]; 958 logServiceArray = nlohmann::json::array(); 959 logServiceArray.push_back( 960 {{"@odata.id", 961 "/redfish/v1/Systems/system/LogServices/EventLog"}}); 962 #ifdef BMCWEB_ENABLE_REDFISH_DUMP_LOG 963 logServiceArray.push_back( 964 {{"@odata.id", 965 "/redfish/v1/Systems/system/LogServices/Dump"}}); 966 #endif 967 968 #ifdef BMCWEB_ENABLE_REDFISH_CPU_LOG 969 logServiceArray.push_back( 970 {{"@odata.id", 971 "/redfish/v1/Systems/system/LogServices/Crashdump"}}); 972 #endif 973 974 #ifdef BMCWEB_ENABLE_REDFISH_HOST_LOGGER 975 logServiceArray.push_back( 976 {{"@odata.id", 977 "/redfish/v1/Systems/system/LogServices/HostLogger"}}); 978 #endif 979 asyncResp->res.jsonValue["Members@odata.count"] = 980 logServiceArray.size(); 981 982 crow::connections::systemBus->async_method_call( 983 [asyncResp](const boost::system::error_code ec, 984 const std::vector<std::string>& subtreePath) { 985 if (ec) 986 { 987 BMCWEB_LOG_ERROR << ec; 988 return; 989 } 990 991 for (auto& pathStr : subtreePath) 992 { 993 if (pathStr.find("PostCode") != std::string::npos) 994 { 995 nlohmann::json& logServiceArrayLocal = 996 asyncResp->res.jsonValue["Members"]; 997 logServiceArrayLocal.push_back( 998 {{"@odata.id", 999 "/redfish/v1/Systems/system/LogServices/PostCodes"}}); 1000 asyncResp->res 1001 .jsonValue["Members@odata.count"] = 1002 logServiceArrayLocal.size(); 1003 return; 1004 } 1005 } 1006 }, 1007 "xyz.openbmc_project.ObjectMapper", 1008 "/xyz/openbmc_project/object_mapper", 1009 "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", "/", 1010 0, std::array<const char*, 1>{postCodeIface}); 1011 }); 1012 } 1013 1014 inline void requestRoutesEventLogService(App& app) 1015 { 1016 BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/EventLog/") 1017 .privileges(redfish::privileges::getLogService) 1018 .methods( 1019 boost::beast::http::verb:: 1020 get)([](const crow::Request&, 1021 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 1022 asyncResp->res.jsonValue["@odata.id"] = 1023 "/redfish/v1/Systems/system/LogServices/EventLog"; 1024 asyncResp->res.jsonValue["@odata.type"] = 1025 "#LogService.v1_1_0.LogService"; 1026 asyncResp->res.jsonValue["Name"] = "Event Log Service"; 1027 asyncResp->res.jsonValue["Description"] = 1028 "System Event Log Service"; 1029 asyncResp->res.jsonValue["Id"] = "EventLog"; 1030 asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull"; 1031 1032 std::pair<std::string, std::string> redfishDateTimeOffset = 1033 crow::utility::getDateTimeOffsetNow(); 1034 1035 asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first; 1036 asyncResp->res.jsonValue["DateTimeLocalOffset"] = 1037 redfishDateTimeOffset.second; 1038 1039 asyncResp->res.jsonValue["Entries"] = { 1040 {"@odata.id", 1041 "/redfish/v1/Systems/system/LogServices/EventLog/Entries"}}; 1042 asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"] = { 1043 1044 {"target", 1045 "/redfish/v1/Systems/system/LogServices/EventLog/Actions/LogService.ClearLog"}}; 1046 }); 1047 } 1048 1049 inline void requestRoutesJournalEventLogClear(App& app) 1050 { 1051 BMCWEB_ROUTE( 1052 app, 1053 "/redfish/v1/Systems/system/LogServices/EventLog/Actions/LogService.ClearLog/") 1054 .privileges({{"ConfigureComponents"}}) 1055 .methods(boost::beast::http::verb::post)( 1056 [](const crow::Request&, 1057 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 1058 // Clear the EventLog by deleting the log files 1059 std::vector<std::filesystem::path> redfishLogFiles; 1060 if (getRedfishLogFiles(redfishLogFiles)) 1061 { 1062 for (const std::filesystem::path& file : redfishLogFiles) 1063 { 1064 std::error_code ec; 1065 std::filesystem::remove(file, ec); 1066 } 1067 } 1068 1069 // Reload rsyslog so it knows to start new log files 1070 crow::connections::systemBus->async_method_call( 1071 [asyncResp](const boost::system::error_code ec) { 1072 if (ec) 1073 { 1074 BMCWEB_LOG_ERROR << "Failed to reload rsyslog: " 1075 << ec; 1076 messages::internalError(asyncResp->res); 1077 return; 1078 } 1079 1080 messages::success(asyncResp->res); 1081 }, 1082 "org.freedesktop.systemd1", "/org/freedesktop/systemd1", 1083 "org.freedesktop.systemd1.Manager", "ReloadUnit", 1084 "rsyslog.service", "replace"); 1085 }); 1086 } 1087 1088 static int fillEventLogEntryJson(const std::string& logEntryID, 1089 const std::string& logEntry, 1090 nlohmann::json& logEntryJson) 1091 { 1092 // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>" 1093 // First get the Timestamp 1094 size_t space = logEntry.find_first_of(' '); 1095 if (space == std::string::npos) 1096 { 1097 return 1; 1098 } 1099 std::string timestamp = logEntry.substr(0, space); 1100 // Then get the log contents 1101 size_t entryStart = logEntry.find_first_not_of(' ', space); 1102 if (entryStart == std::string::npos) 1103 { 1104 return 1; 1105 } 1106 std::string_view entry(logEntry); 1107 entry.remove_prefix(entryStart); 1108 // Use split to separate the entry into its fields 1109 std::vector<std::string> logEntryFields; 1110 boost::split(logEntryFields, entry, boost::is_any_of(","), 1111 boost::token_compress_on); 1112 // We need at least a MessageId to be valid 1113 if (logEntryFields.empty()) 1114 { 1115 return 1; 1116 } 1117 std::string& messageID = logEntryFields[0]; 1118 1119 // Get the Message from the MessageRegistry 1120 const message_registries::Message* message = 1121 message_registries::getMessage(messageID); 1122 1123 std::string msg; 1124 std::string severity; 1125 if (message != nullptr) 1126 { 1127 msg = message->message; 1128 severity = message->severity; 1129 } 1130 1131 // Get the MessageArgs from the log if there are any 1132 std::span<std::string> messageArgs; 1133 if (logEntryFields.size() > 1) 1134 { 1135 std::string& messageArgsStart = logEntryFields[1]; 1136 // If the first string is empty, assume there are no MessageArgs 1137 std::size_t messageArgsSize = 0; 1138 if (!messageArgsStart.empty()) 1139 { 1140 messageArgsSize = logEntryFields.size() - 1; 1141 } 1142 1143 messageArgs = {&messageArgsStart, messageArgsSize}; 1144 1145 // Fill the MessageArgs into the Message 1146 int i = 0; 1147 for (const std::string& messageArg : messageArgs) 1148 { 1149 std::string argStr = "%" + std::to_string(++i); 1150 size_t argPos = msg.find(argStr); 1151 if (argPos != std::string::npos) 1152 { 1153 msg.replace(argPos, argStr.length(), messageArg); 1154 } 1155 } 1156 } 1157 1158 // Get the Created time from the timestamp. The log timestamp is in RFC3339 1159 // format which matches the Redfish format except for the fractional seconds 1160 // between the '.' and the '+', so just remove them. 1161 std::size_t dot = timestamp.find_first_of('.'); 1162 std::size_t plus = timestamp.find_first_of('+'); 1163 if (dot != std::string::npos && plus != std::string::npos) 1164 { 1165 timestamp.erase(dot, plus - dot); 1166 } 1167 1168 // Fill in the log entry with the gathered data 1169 logEntryJson = { 1170 {"@odata.type", "#LogEntry.v1_8_0.LogEntry"}, 1171 {"@odata.id", 1172 "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" + 1173 logEntryID}, 1174 {"Name", "System Event Log Entry"}, 1175 {"Id", logEntryID}, 1176 {"Message", std::move(msg)}, 1177 {"MessageId", std::move(messageID)}, 1178 {"MessageArgs", messageArgs}, 1179 {"EntryType", "Event"}, 1180 {"Severity", std::move(severity)}, 1181 {"Created", std::move(timestamp)}}; 1182 return 0; 1183 } 1184 1185 inline void requestRoutesJournalEventLogEntryCollection(App& app) 1186 { 1187 BMCWEB_ROUTE(app, 1188 "/redfish/v1/Systems/system/LogServices/EventLog/Entries/") 1189 .privileges(redfish::privileges::getLogEntryCollection) 1190 .methods( 1191 boost::beast::http::verb:: 1192 get)([](const crow::Request& req, 1193 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 1194 uint64_t skip = 0; 1195 uint64_t top = maxEntriesPerPage; // Show max entries by default 1196 if (!getSkipParam(asyncResp, req, skip)) 1197 { 1198 return; 1199 } 1200 if (!getTopParam(asyncResp, req, top)) 1201 { 1202 return; 1203 } 1204 // Collections don't include the static data added by SubRoute 1205 // because it has a duplicate entry for members 1206 asyncResp->res.jsonValue["@odata.type"] = 1207 "#LogEntryCollection.LogEntryCollection"; 1208 asyncResp->res.jsonValue["@odata.id"] = 1209 "/redfish/v1/Systems/system/LogServices/EventLog/Entries"; 1210 asyncResp->res.jsonValue["Name"] = "System Event Log Entries"; 1211 asyncResp->res.jsonValue["Description"] = 1212 "Collection of System Event Log Entries"; 1213 1214 nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"]; 1215 logEntryArray = nlohmann::json::array(); 1216 // Go through the log files and create a unique ID for each 1217 // entry 1218 std::vector<std::filesystem::path> redfishLogFiles; 1219 getRedfishLogFiles(redfishLogFiles); 1220 uint64_t entryCount = 0; 1221 std::string logEntry; 1222 1223 // Oldest logs are in the last file, so start there and loop 1224 // backwards 1225 for (auto it = redfishLogFiles.rbegin(); 1226 it < redfishLogFiles.rend(); it++) 1227 { 1228 std::ifstream logStream(*it); 1229 if (!logStream.is_open()) 1230 { 1231 continue; 1232 } 1233 1234 // Reset the unique ID on the first entry 1235 bool firstEntry = true; 1236 while (std::getline(logStream, logEntry)) 1237 { 1238 entryCount++; 1239 // Handle paging using skip (number of entries to skip 1240 // from the start) and top (number of entries to 1241 // display) 1242 if (entryCount <= skip || entryCount > skip + top) 1243 { 1244 continue; 1245 } 1246 1247 std::string idStr; 1248 if (!getUniqueEntryID(logEntry, idStr, firstEntry)) 1249 { 1250 continue; 1251 } 1252 1253 if (firstEntry) 1254 { 1255 firstEntry = false; 1256 } 1257 1258 logEntryArray.push_back({}); 1259 nlohmann::json& bmcLogEntry = logEntryArray.back(); 1260 if (fillEventLogEntryJson(idStr, logEntry, bmcLogEntry) != 1261 0) 1262 { 1263 messages::internalError(asyncResp->res); 1264 return; 1265 } 1266 } 1267 } 1268 asyncResp->res.jsonValue["Members@odata.count"] = entryCount; 1269 if (skip + top < entryCount) 1270 { 1271 asyncResp->res.jsonValue["Members@odata.nextLink"] = 1272 "/redfish/v1/Systems/system/LogServices/EventLog/Entries?$skip=" + 1273 std::to_string(skip + top); 1274 } 1275 }); 1276 } 1277 1278 inline void requestRoutesJournalEventLogEntry(App& app) 1279 { 1280 BMCWEB_ROUTE( 1281 app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/") 1282 .privileges(redfish::privileges::getLogEntry) 1283 .methods(boost::beast::http::verb::get)( 1284 [](const crow::Request&, 1285 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 1286 const std::string& param) { 1287 const std::string& targetID = param; 1288 1289 // Go through the log files and check the unique ID for each 1290 // entry to find the target entry 1291 std::vector<std::filesystem::path> redfishLogFiles; 1292 getRedfishLogFiles(redfishLogFiles); 1293 std::string logEntry; 1294 1295 // Oldest logs are in the last file, so start there and loop 1296 // backwards 1297 for (auto it = redfishLogFiles.rbegin(); 1298 it < redfishLogFiles.rend(); it++) 1299 { 1300 std::ifstream logStream(*it); 1301 if (!logStream.is_open()) 1302 { 1303 continue; 1304 } 1305 1306 // Reset the unique ID on the first entry 1307 bool firstEntry = true; 1308 while (std::getline(logStream, logEntry)) 1309 { 1310 std::string idStr; 1311 if (!getUniqueEntryID(logEntry, idStr, firstEntry)) 1312 { 1313 continue; 1314 } 1315 1316 if (firstEntry) 1317 { 1318 firstEntry = false; 1319 } 1320 1321 if (idStr == targetID) 1322 { 1323 if (fillEventLogEntryJson( 1324 idStr, logEntry, 1325 asyncResp->res.jsonValue) != 0) 1326 { 1327 messages::internalError(asyncResp->res); 1328 return; 1329 } 1330 return; 1331 } 1332 } 1333 } 1334 // Requested ID was not found 1335 messages::resourceMissingAtURI(asyncResp->res, targetID); 1336 }); 1337 } 1338 1339 inline void requestRoutesDBusEventLogEntryCollection(App& app) 1340 { 1341 BMCWEB_ROUTE(app, 1342 "/redfish/v1/Systems/system/LogServices/EventLog/Entries/") 1343 .privileges(redfish::privileges::getLogEntryCollection) 1344 .methods( 1345 boost::beast::http::verb:: 1346 get)([](const crow::Request&, 1347 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 1348 // Collections don't include the static data added by SubRoute 1349 // because it has a duplicate entry for members 1350 asyncResp->res.jsonValue["@odata.type"] = 1351 "#LogEntryCollection.LogEntryCollection"; 1352 asyncResp->res.jsonValue["@odata.id"] = 1353 "/redfish/v1/Systems/system/LogServices/EventLog/Entries"; 1354 asyncResp->res.jsonValue["Name"] = "System Event Log Entries"; 1355 asyncResp->res.jsonValue["Description"] = 1356 "Collection of System Event Log Entries"; 1357 1358 // DBus implementation of EventLog/Entries 1359 // Make call to Logging Service to find all log entry objects 1360 crow::connections::systemBus->async_method_call( 1361 [asyncResp](const boost::system::error_code ec, 1362 const dbus::utility::ManagedObjectType& resp) { 1363 if (ec) 1364 { 1365 // TODO Handle for specific error code 1366 BMCWEB_LOG_ERROR 1367 << "getLogEntriesIfaceData resp_handler got error " 1368 << ec; 1369 messages::internalError(asyncResp->res); 1370 return; 1371 } 1372 nlohmann::json& entriesArray = 1373 asyncResp->res.jsonValue["Members"]; 1374 entriesArray = nlohmann::json::array(); 1375 for (const auto& objectPath : resp) 1376 { 1377 const uint32_t* id = nullptr; 1378 const uint64_t* timestamp = nullptr; 1379 const uint64_t* updateTimestamp = nullptr; 1380 const std::string* severity = nullptr; 1381 const std::string* message = nullptr; 1382 const std::string* filePath = nullptr; 1383 bool resolved = false; 1384 for (const auto& interfaceMap : objectPath.second) 1385 { 1386 if (interfaceMap.first == 1387 "xyz.openbmc_project.Logging.Entry") 1388 { 1389 for (const auto& propertyMap : 1390 interfaceMap.second) 1391 { 1392 if (propertyMap.first == "Id") 1393 { 1394 id = std::get_if<uint32_t>( 1395 &propertyMap.second); 1396 } 1397 else if (propertyMap.first == "Timestamp") 1398 { 1399 timestamp = std::get_if<uint64_t>( 1400 &propertyMap.second); 1401 } 1402 else if (propertyMap.first == 1403 "UpdateTimestamp") 1404 { 1405 updateTimestamp = std::get_if<uint64_t>( 1406 &propertyMap.second); 1407 } 1408 else if (propertyMap.first == "Severity") 1409 { 1410 severity = std::get_if<std::string>( 1411 &propertyMap.second); 1412 } 1413 else if (propertyMap.first == "Message") 1414 { 1415 message = std::get_if<std::string>( 1416 &propertyMap.second); 1417 } 1418 else if (propertyMap.first == "Resolved") 1419 { 1420 const bool* resolveptr = 1421 std::get_if<bool>( 1422 &propertyMap.second); 1423 if (resolveptr == nullptr) 1424 { 1425 messages::internalError( 1426 asyncResp->res); 1427 return; 1428 } 1429 resolved = *resolveptr; 1430 } 1431 } 1432 if (id == nullptr || message == nullptr || 1433 severity == nullptr) 1434 { 1435 messages::internalError(asyncResp->res); 1436 return; 1437 } 1438 } 1439 else if (interfaceMap.first == 1440 "xyz.openbmc_project.Common.FilePath") 1441 { 1442 for (const auto& propertyMap : 1443 interfaceMap.second) 1444 { 1445 if (propertyMap.first == "Path") 1446 { 1447 filePath = std::get_if<std::string>( 1448 &propertyMap.second); 1449 } 1450 } 1451 } 1452 } 1453 // Object path without the 1454 // xyz.openbmc_project.Logging.Entry interface, ignore 1455 // and continue. 1456 if (id == nullptr || message == nullptr || 1457 severity == nullptr || timestamp == nullptr || 1458 updateTimestamp == nullptr) 1459 { 1460 continue; 1461 } 1462 entriesArray.push_back({}); 1463 nlohmann::json& thisEntry = entriesArray.back(); 1464 thisEntry["@odata.type"] = "#LogEntry.v1_8_0.LogEntry"; 1465 thisEntry["@odata.id"] = 1466 "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" + 1467 std::to_string(*id); 1468 thisEntry["Name"] = "System Event Log Entry"; 1469 thisEntry["Id"] = std::to_string(*id); 1470 thisEntry["Message"] = *message; 1471 thisEntry["Resolved"] = resolved; 1472 thisEntry["EntryType"] = "Event"; 1473 thisEntry["Severity"] = 1474 translateSeverityDbusToRedfish(*severity); 1475 thisEntry["Created"] = 1476 crow::utility::getDateTimeUintMs(*timestamp); 1477 thisEntry["Modified"] = 1478 crow::utility::getDateTimeUintMs(*updateTimestamp); 1479 if (filePath != nullptr) 1480 { 1481 thisEntry["AdditionalDataURI"] = 1482 "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" + 1483 std::to_string(*id) + "/attachment"; 1484 } 1485 } 1486 std::sort(entriesArray.begin(), entriesArray.end(), 1487 [](const nlohmann::json& left, 1488 const nlohmann::json& right) { 1489 return (left["Id"] <= right["Id"]); 1490 }); 1491 asyncResp->res.jsonValue["Members@odata.count"] = 1492 entriesArray.size(); 1493 }, 1494 "xyz.openbmc_project.Logging", "/xyz/openbmc_project/logging", 1495 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); 1496 }); 1497 } 1498 1499 inline void requestRoutesDBusEventLogEntry(App& app) 1500 { 1501 BMCWEB_ROUTE( 1502 app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/") 1503 .privileges(redfish::privileges::getLogEntry) 1504 .methods(boost::beast::http::verb::get)( 1505 [](const crow::Request&, 1506 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 1507 const std::string& param) 1508 1509 { 1510 std::string entryID = param; 1511 dbus::utility::escapePathForDbus(entryID); 1512 1513 // DBus implementation of EventLog/Entries 1514 // Make call to Logging Service to find all log entry objects 1515 crow::connections::systemBus->async_method_call( 1516 [asyncResp, entryID](const boost::system::error_code ec, 1517 const GetManagedPropertyType& resp) { 1518 if (ec.value() == EBADR) 1519 { 1520 messages::resourceNotFound( 1521 asyncResp->res, "EventLogEntry", entryID); 1522 return; 1523 } 1524 if (ec) 1525 { 1526 BMCWEB_LOG_ERROR 1527 << "EventLogEntry (DBus) resp_handler got error " 1528 << ec; 1529 messages::internalError(asyncResp->res); 1530 return; 1531 } 1532 const uint32_t* id = nullptr; 1533 const uint64_t* timestamp = nullptr; 1534 const uint64_t* updateTimestamp = nullptr; 1535 const std::string* severity = nullptr; 1536 const std::string* message = nullptr; 1537 const std::string* filePath = nullptr; 1538 bool resolved = false; 1539 1540 for (const auto& propertyMap : resp) 1541 { 1542 if (propertyMap.first == "Id") 1543 { 1544 id = std::get_if<uint32_t>(&propertyMap.second); 1545 } 1546 else if (propertyMap.first == "Timestamp") 1547 { 1548 timestamp = 1549 std::get_if<uint64_t>(&propertyMap.second); 1550 } 1551 else if (propertyMap.first == "UpdateTimestamp") 1552 { 1553 updateTimestamp = 1554 std::get_if<uint64_t>(&propertyMap.second); 1555 } 1556 else if (propertyMap.first == "Severity") 1557 { 1558 severity = std::get_if<std::string>( 1559 &propertyMap.second); 1560 } 1561 else if (propertyMap.first == "Message") 1562 { 1563 message = std::get_if<std::string>( 1564 &propertyMap.second); 1565 } 1566 else if (propertyMap.first == "Resolved") 1567 { 1568 const bool* resolveptr = 1569 std::get_if<bool>(&propertyMap.second); 1570 if (resolveptr == nullptr) 1571 { 1572 messages::internalError(asyncResp->res); 1573 return; 1574 } 1575 resolved = *resolveptr; 1576 } 1577 else if (propertyMap.first == "Path") 1578 { 1579 filePath = std::get_if<std::string>( 1580 &propertyMap.second); 1581 } 1582 } 1583 if (id == nullptr || message == nullptr || 1584 severity == nullptr || timestamp == nullptr || 1585 updateTimestamp == nullptr) 1586 { 1587 messages::internalError(asyncResp->res); 1588 return; 1589 } 1590 asyncResp->res.jsonValue["@odata.type"] = 1591 "#LogEntry.v1_8_0.LogEntry"; 1592 asyncResp->res.jsonValue["@odata.id"] = 1593 "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" + 1594 std::to_string(*id); 1595 asyncResp->res.jsonValue["Name"] = 1596 "System Event Log Entry"; 1597 asyncResp->res.jsonValue["Id"] = std::to_string(*id); 1598 asyncResp->res.jsonValue["Message"] = *message; 1599 asyncResp->res.jsonValue["Resolved"] = resolved; 1600 asyncResp->res.jsonValue["EntryType"] = "Event"; 1601 asyncResp->res.jsonValue["Severity"] = 1602 translateSeverityDbusToRedfish(*severity); 1603 asyncResp->res.jsonValue["Created"] = 1604 crow::utility::getDateTimeUintMs(*timestamp); 1605 asyncResp->res.jsonValue["Modified"] = 1606 crow::utility::getDateTimeUintMs(*updateTimestamp); 1607 if (filePath != nullptr) 1608 { 1609 asyncResp->res.jsonValue["AdditionalDataURI"] = 1610 "/redfish/v1/Systems/system/LogServices/EventLog/attachment/" + 1611 std::to_string(*id); 1612 } 1613 }, 1614 "xyz.openbmc_project.Logging", 1615 "/xyz/openbmc_project/logging/entry/" + entryID, 1616 "org.freedesktop.DBus.Properties", "GetAll", ""); 1617 }); 1618 1619 BMCWEB_ROUTE( 1620 app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/") 1621 .privileges(redfish::privileges::patchLogEntry) 1622 .methods(boost::beast::http::verb::patch)( 1623 [](const crow::Request& req, 1624 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 1625 const std::string& entryId) { 1626 std::optional<bool> resolved; 1627 1628 if (!json_util::readJsonPatch(req, asyncResp->res, "Resolved", 1629 resolved)) 1630 { 1631 return; 1632 } 1633 BMCWEB_LOG_DEBUG << "Set Resolved"; 1634 1635 crow::connections::systemBus->async_method_call( 1636 [asyncResp, entryId](const boost::system::error_code ec) { 1637 if (ec) 1638 { 1639 BMCWEB_LOG_DEBUG << "DBUS response error " << ec; 1640 messages::internalError(asyncResp->res); 1641 return; 1642 } 1643 }, 1644 "xyz.openbmc_project.Logging", 1645 "/xyz/openbmc_project/logging/entry/" + entryId, 1646 "org.freedesktop.DBus.Properties", "Set", 1647 "xyz.openbmc_project.Logging.Entry", "Resolved", 1648 dbus::utility::DbusVariantType(*resolved)); 1649 }); 1650 1651 BMCWEB_ROUTE( 1652 app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/") 1653 .privileges(redfish::privileges::deleteLogEntry) 1654 1655 .methods(boost::beast::http::verb::delete_)( 1656 [](const crow::Request&, 1657 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 1658 const std::string& param) 1659 1660 { 1661 BMCWEB_LOG_DEBUG << "Do delete single event entries."; 1662 1663 std::string entryID = param; 1664 1665 dbus::utility::escapePathForDbus(entryID); 1666 1667 // Process response from Logging service. 1668 auto respHandler = [asyncResp, entryID]( 1669 const boost::system::error_code ec) { 1670 BMCWEB_LOG_DEBUG 1671 << "EventLogEntry (DBus) doDelete callback: Done"; 1672 if (ec) 1673 { 1674 if (ec.value() == EBADR) 1675 { 1676 messages::resourceNotFound(asyncResp->res, 1677 "LogEntry", entryID); 1678 return; 1679 } 1680 // TODO Handle for specific error code 1681 BMCWEB_LOG_ERROR 1682 << "EventLogEntry (DBus) doDelete respHandler got error " 1683 << ec; 1684 asyncResp->res.result( 1685 boost::beast::http::status::internal_server_error); 1686 return; 1687 } 1688 1689 asyncResp->res.result(boost::beast::http::status::ok); 1690 }; 1691 1692 // Make call to Logging service to request Delete Log 1693 crow::connections::systemBus->async_method_call( 1694 respHandler, "xyz.openbmc_project.Logging", 1695 "/xyz/openbmc_project/logging/entry/" + entryID, 1696 "xyz.openbmc_project.Object.Delete", "Delete"); 1697 }); 1698 } 1699 1700 inline void requestRoutesDBusEventLogEntryDownload(App& app) 1701 { 1702 BMCWEB_ROUTE( 1703 app, 1704 "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/attachment") 1705 .privileges(redfish::privileges::getLogEntry) 1706 .methods(boost::beast::http::verb::get)( 1707 [](const crow::Request& req, 1708 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 1709 const std::string& param) 1710 1711 { 1712 if (!http_helpers::isOctetAccepted( 1713 req.getHeaderValue("Accept"))) 1714 { 1715 asyncResp->res.result( 1716 boost::beast::http::status::bad_request); 1717 return; 1718 } 1719 1720 std::string entryID = param; 1721 dbus::utility::escapePathForDbus(entryID); 1722 1723 crow::connections::systemBus->async_method_call( 1724 [asyncResp, 1725 entryID](const boost::system::error_code ec, 1726 const sdbusplus::message::unix_fd& unixfd) { 1727 if (ec.value() == EBADR) 1728 { 1729 messages::resourceNotFound( 1730 asyncResp->res, "EventLogAttachment", entryID); 1731 return; 1732 } 1733 if (ec) 1734 { 1735 BMCWEB_LOG_DEBUG << "DBUS response error " << ec; 1736 messages::internalError(asyncResp->res); 1737 return; 1738 } 1739 1740 int fd = -1; 1741 fd = dup(unixfd); 1742 if (fd == -1) 1743 { 1744 messages::internalError(asyncResp->res); 1745 return; 1746 } 1747 1748 long long int size = lseek(fd, 0, SEEK_END); 1749 if (size == -1) 1750 { 1751 messages::internalError(asyncResp->res); 1752 return; 1753 } 1754 1755 // Arbitrary max size of 64kb 1756 constexpr int maxFileSize = 65536; 1757 if (size > maxFileSize) 1758 { 1759 BMCWEB_LOG_ERROR 1760 << "File size exceeds maximum allowed size of " 1761 << maxFileSize; 1762 messages::internalError(asyncResp->res); 1763 return; 1764 } 1765 std::vector<char> data(static_cast<size_t>(size)); 1766 long long int rc = lseek(fd, 0, SEEK_SET); 1767 if (rc == -1) 1768 { 1769 messages::internalError(asyncResp->res); 1770 return; 1771 } 1772 rc = read(fd, data.data(), data.size()); 1773 if ((rc == -1) || (rc != size)) 1774 { 1775 messages::internalError(asyncResp->res); 1776 return; 1777 } 1778 close(fd); 1779 1780 std::string_view strData(data.data(), data.size()); 1781 std::string output = 1782 crow::utility::base64encode(strData); 1783 1784 asyncResp->res.addHeader("Content-Type", 1785 "application/octet-stream"); 1786 asyncResp->res.addHeader("Content-Transfer-Encoding", 1787 "Base64"); 1788 asyncResp->res.body() = std::move(output); 1789 }, 1790 "xyz.openbmc_project.Logging", 1791 "/xyz/openbmc_project/logging/entry/" + entryID, 1792 "xyz.openbmc_project.Logging.Entry", "GetEntry"); 1793 }); 1794 } 1795 1796 constexpr const char* hostLoggerFolderPath = "/var/log/console"; 1797 1798 inline bool 1799 getHostLoggerFiles(const std::string& hostLoggerFilePath, 1800 std::vector<std::filesystem::path>& hostLoggerFiles) 1801 { 1802 std::error_code ec; 1803 std::filesystem::directory_iterator logPath(hostLoggerFilePath, ec); 1804 if (ec) 1805 { 1806 BMCWEB_LOG_ERROR << ec.message(); 1807 return false; 1808 } 1809 for (const std::filesystem::directory_entry& it : logPath) 1810 { 1811 std::string filename = it.path().filename(); 1812 // Prefix of each log files is "log". Find the file and save the 1813 // path 1814 if (boost::starts_with(filename, "log")) 1815 { 1816 hostLoggerFiles.emplace_back(it.path()); 1817 } 1818 } 1819 // As the log files rotate, they are appended with a ".#" that is higher for 1820 // the older logs. Since we start from oldest logs, sort the name in 1821 // descending order. 1822 std::sort(hostLoggerFiles.rbegin(), hostLoggerFiles.rend(), 1823 AlphanumLess<std::string>()); 1824 1825 return true; 1826 } 1827 1828 inline bool 1829 getHostLoggerEntries(std::vector<std::filesystem::path>& hostLoggerFiles, 1830 uint64_t& skip, uint64_t& top, 1831 std::vector<std::string>& logEntries, size_t& logCount) 1832 { 1833 GzFileReader logFile; 1834 1835 // Go though all log files and expose host logs. 1836 for (const std::filesystem::path& it : hostLoggerFiles) 1837 { 1838 if (!logFile.gzGetLines(it.string(), skip, top, logEntries, logCount)) 1839 { 1840 BMCWEB_LOG_ERROR << "fail to expose host logs"; 1841 return false; 1842 } 1843 } 1844 // Get lastMessage from constructor by getter 1845 std::string lastMessage = logFile.getLastMessage(); 1846 if (!lastMessage.empty()) 1847 { 1848 logCount++; 1849 if (logCount > skip && logCount <= (skip + top)) 1850 { 1851 logEntries.push_back(lastMessage); 1852 } 1853 } 1854 return true; 1855 } 1856 1857 inline void fillHostLoggerEntryJson(const std::string& logEntryID, 1858 const std::string& msg, 1859 nlohmann::json& logEntryJson) 1860 { 1861 // Fill in the log entry with the gathered data. 1862 logEntryJson = { 1863 {"@odata.type", "#LogEntry.v1_4_0.LogEntry"}, 1864 {"@odata.id", 1865 "/redfish/v1/Systems/system/LogServices/HostLogger/Entries/" + 1866 logEntryID}, 1867 {"Name", "Host Logger Entry"}, 1868 {"Id", logEntryID}, 1869 {"Message", msg}, 1870 {"EntryType", "Oem"}, 1871 {"Severity", "OK"}, 1872 {"OemRecordFormat", "Host Logger Entry"}}; 1873 } 1874 1875 inline void requestRoutesSystemHostLogger(App& app) 1876 { 1877 BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/HostLogger/") 1878 .privileges(redfish::privileges::getLogService) 1879 .methods( 1880 boost::beast::http::verb:: 1881 get)([](const crow::Request&, 1882 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 1883 asyncResp->res.jsonValue["@odata.id"] = 1884 "/redfish/v1/Systems/system/LogServices/HostLogger"; 1885 asyncResp->res.jsonValue["@odata.type"] = 1886 "#LogService.v1_1_0.LogService"; 1887 asyncResp->res.jsonValue["Name"] = "Host Logger Service"; 1888 asyncResp->res.jsonValue["Description"] = "Host Logger Service"; 1889 asyncResp->res.jsonValue["Id"] = "HostLogger"; 1890 asyncResp->res.jsonValue["Entries"] = { 1891 {"@odata.id", 1892 "/redfish/v1/Systems/system/LogServices/HostLogger/Entries"}}; 1893 }); 1894 } 1895 1896 inline void requestRoutesSystemHostLoggerCollection(App& app) 1897 { 1898 BMCWEB_ROUTE(app, 1899 "/redfish/v1/Systems/system/LogServices/HostLogger/Entries/") 1900 .privileges(redfish::privileges::getLogEntry) 1901 .methods( 1902 boost::beast::http::verb:: 1903 get)([](const crow::Request& req, 1904 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 1905 uint64_t skip = 0; 1906 uint64_t top = maxEntriesPerPage; // Show max 1000 entries by 1907 // default, allow range 1 to 1908 // 1000 entries per page. 1909 if (!getSkipParam(asyncResp, req, skip)) 1910 { 1911 return; 1912 } 1913 if (!getTopParam(asyncResp, req, top)) 1914 { 1915 return; 1916 } 1917 asyncResp->res.jsonValue["@odata.id"] = 1918 "/redfish/v1/Systems/system/LogServices/HostLogger/Entries"; 1919 asyncResp->res.jsonValue["@odata.type"] = 1920 "#LogEntryCollection.LogEntryCollection"; 1921 asyncResp->res.jsonValue["Name"] = "HostLogger Entries"; 1922 asyncResp->res.jsonValue["Description"] = 1923 "Collection of HostLogger Entries"; 1924 nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"]; 1925 logEntryArray = nlohmann::json::array(); 1926 asyncResp->res.jsonValue["Members@odata.count"] = 0; 1927 1928 std::vector<std::filesystem::path> hostLoggerFiles; 1929 if (!getHostLoggerFiles(hostLoggerFolderPath, hostLoggerFiles)) 1930 { 1931 BMCWEB_LOG_ERROR << "fail to get host log file path"; 1932 return; 1933 } 1934 1935 size_t logCount = 0; 1936 // This vector only store the entries we want to expose that 1937 // control by skip and top. 1938 std::vector<std::string> logEntries; 1939 if (!getHostLoggerEntries(hostLoggerFiles, skip, top, logEntries, 1940 logCount)) 1941 { 1942 messages::internalError(asyncResp->res); 1943 return; 1944 } 1945 // If vector is empty, that means skip value larger than total 1946 // log count 1947 if (logEntries.empty()) 1948 { 1949 asyncResp->res.jsonValue["Members@odata.count"] = logCount; 1950 return; 1951 } 1952 if (!logEntries.empty()) 1953 { 1954 for (size_t i = 0; i < logEntries.size(); i++) 1955 { 1956 logEntryArray.push_back({}); 1957 nlohmann::json& hostLogEntry = logEntryArray.back(); 1958 fillHostLoggerEntryJson(std::to_string(skip + i), 1959 logEntries[i], hostLogEntry); 1960 } 1961 1962 asyncResp->res.jsonValue["Members@odata.count"] = logCount; 1963 if (skip + top < logCount) 1964 { 1965 asyncResp->res.jsonValue["Members@odata.nextLink"] = 1966 "/redfish/v1/Systems/system/LogServices/HostLogger/Entries?$skip=" + 1967 std::to_string(skip + top); 1968 } 1969 } 1970 }); 1971 } 1972 1973 inline void requestRoutesSystemHostLoggerLogEntry(App& app) 1974 { 1975 BMCWEB_ROUTE( 1976 app, "/redfish/v1/Systems/system/LogServices/HostLogger/Entries/<str>/") 1977 .privileges(redfish::privileges::getLogEntry) 1978 .methods(boost::beast::http::verb::get)( 1979 [](const crow::Request&, 1980 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 1981 const std::string& param) { 1982 const std::string& targetID = param; 1983 1984 uint64_t idInt = 0; 1985 1986 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) 1987 const char* end = targetID.data() + targetID.size(); 1988 1989 auto [ptr, ec] = std::from_chars(targetID.data(), end, idInt); 1990 if (ec == std::errc::invalid_argument) 1991 { 1992 messages::resourceMissingAtURI(asyncResp->res, targetID); 1993 return; 1994 } 1995 if (ec == std::errc::result_out_of_range) 1996 { 1997 messages::resourceMissingAtURI(asyncResp->res, targetID); 1998 return; 1999 } 2000 2001 std::vector<std::filesystem::path> hostLoggerFiles; 2002 if (!getHostLoggerFiles(hostLoggerFolderPath, hostLoggerFiles)) 2003 { 2004 BMCWEB_LOG_ERROR << "fail to get host log file path"; 2005 return; 2006 } 2007 2008 size_t logCount = 0; 2009 uint64_t top = 1; 2010 std::vector<std::string> logEntries; 2011 // We can get specific entry by skip and top. For example, if we 2012 // want to get nth entry, we can set skip = n-1 and top = 1 to 2013 // get that entry 2014 if (!getHostLoggerEntries(hostLoggerFiles, idInt, top, 2015 logEntries, logCount)) 2016 { 2017 messages::internalError(asyncResp->res); 2018 return; 2019 } 2020 2021 if (!logEntries.empty()) 2022 { 2023 fillHostLoggerEntryJson(targetID, logEntries[0], 2024 asyncResp->res.jsonValue); 2025 return; 2026 } 2027 2028 // Requested ID was not found 2029 messages::resourceMissingAtURI(asyncResp->res, targetID); 2030 }); 2031 } 2032 2033 inline void requestRoutesBMCLogServiceCollection(App& app) 2034 { 2035 BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/") 2036 .privileges(redfish::privileges::getLogServiceCollection) 2037 .methods(boost::beast::http::verb::get)( 2038 [](const crow::Request&, 2039 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2040 // Collections don't include the static data added by SubRoute 2041 // because it has a duplicate entry for members 2042 asyncResp->res.jsonValue["@odata.type"] = 2043 "#LogServiceCollection.LogServiceCollection"; 2044 asyncResp->res.jsonValue["@odata.id"] = 2045 "/redfish/v1/Managers/bmc/LogServices"; 2046 asyncResp->res.jsonValue["Name"] = 2047 "Open BMC Log Services Collection"; 2048 asyncResp->res.jsonValue["Description"] = 2049 "Collection of LogServices for this Manager"; 2050 nlohmann::json& logServiceArray = 2051 asyncResp->res.jsonValue["Members"]; 2052 logServiceArray = nlohmann::json::array(); 2053 #ifdef BMCWEB_ENABLE_REDFISH_DUMP_LOG 2054 logServiceArray.push_back( 2055 {{"@odata.id", 2056 "/redfish/v1/Managers/bmc/LogServices/Dump"}}); 2057 #endif 2058 #ifdef BMCWEB_ENABLE_REDFISH_BMC_JOURNAL 2059 logServiceArray.push_back( 2060 {{"@odata.id", 2061 "/redfish/v1/Managers/bmc/LogServices/Journal"}}); 2062 #endif 2063 asyncResp->res.jsonValue["Members@odata.count"] = 2064 logServiceArray.size(); 2065 }); 2066 } 2067 2068 inline void requestRoutesBMCJournalLogService(App& app) 2069 { 2070 BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Journal/") 2071 .privileges(redfish::privileges::getLogService) 2072 .methods(boost::beast::http::verb::get)( 2073 [](const crow::Request&, 2074 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) 2075 2076 { 2077 asyncResp->res.jsonValue["@odata.type"] = 2078 "#LogService.v1_1_0.LogService"; 2079 asyncResp->res.jsonValue["@odata.id"] = 2080 "/redfish/v1/Managers/bmc/LogServices/Journal"; 2081 asyncResp->res.jsonValue["Name"] = 2082 "Open BMC Journal Log Service"; 2083 asyncResp->res.jsonValue["Description"] = 2084 "BMC Journal Log Service"; 2085 asyncResp->res.jsonValue["Id"] = "BMC Journal"; 2086 asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull"; 2087 2088 std::pair<std::string, std::string> redfishDateTimeOffset = 2089 crow::utility::getDateTimeOffsetNow(); 2090 asyncResp->res.jsonValue["DateTime"] = 2091 redfishDateTimeOffset.first; 2092 asyncResp->res.jsonValue["DateTimeLocalOffset"] = 2093 redfishDateTimeOffset.second; 2094 2095 asyncResp->res.jsonValue["Entries"] = { 2096 {"@odata.id", 2097 "/redfish/v1/Managers/bmc/LogServices/Journal/Entries"}}; 2098 }); 2099 } 2100 2101 static int fillBMCJournalLogEntryJson(const std::string& bmcJournalLogEntryID, 2102 sd_journal* journal, 2103 nlohmann::json& bmcJournalLogEntryJson) 2104 { 2105 // Get the Log Entry contents 2106 int ret = 0; 2107 2108 std::string message; 2109 std::string_view syslogID; 2110 ret = getJournalMetadata(journal, "SYSLOG_IDENTIFIER", syslogID); 2111 if (ret < 0) 2112 { 2113 BMCWEB_LOG_ERROR << "Failed to read SYSLOG_IDENTIFIER field: " 2114 << strerror(-ret); 2115 } 2116 if (!syslogID.empty()) 2117 { 2118 message += std::string(syslogID) + ": "; 2119 } 2120 2121 std::string_view msg; 2122 ret = getJournalMetadata(journal, "MESSAGE", msg); 2123 if (ret < 0) 2124 { 2125 BMCWEB_LOG_ERROR << "Failed to read MESSAGE field: " << strerror(-ret); 2126 return 1; 2127 } 2128 message += std::string(msg); 2129 2130 // Get the severity from the PRIORITY field 2131 long int severity = 8; // Default to an invalid priority 2132 ret = getJournalMetadata(journal, "PRIORITY", 10, severity); 2133 if (ret < 0) 2134 { 2135 BMCWEB_LOG_ERROR << "Failed to read PRIORITY field: " << strerror(-ret); 2136 } 2137 2138 // Get the Created time from the timestamp 2139 std::string entryTimeStr; 2140 if (!getEntryTimestamp(journal, entryTimeStr)) 2141 { 2142 return 1; 2143 } 2144 2145 // Fill in the log entry with the gathered data 2146 bmcJournalLogEntryJson = { 2147 {"@odata.type", "#LogEntry.v1_8_0.LogEntry"}, 2148 {"@odata.id", "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/" + 2149 bmcJournalLogEntryID}, 2150 {"Name", "BMC Journal Entry"}, 2151 {"Id", bmcJournalLogEntryID}, 2152 {"Message", std::move(message)}, 2153 {"EntryType", "Oem"}, 2154 {"Severity", severity <= 2 ? "Critical" 2155 : severity <= 4 ? "Warning" 2156 : "OK"}, 2157 {"OemRecordFormat", "BMC Journal Entry"}, 2158 {"Created", std::move(entryTimeStr)}}; 2159 return 0; 2160 } 2161 2162 inline void requestRoutesBMCJournalLogEntryCollection(App& app) 2163 { 2164 BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/") 2165 .privileges(redfish::privileges::getLogEntryCollection) 2166 .methods( 2167 boost::beast::http::verb:: 2168 get)([](const crow::Request& req, 2169 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2170 static constexpr const long maxEntriesPerPage = 1000; 2171 uint64_t skip = 0; 2172 uint64_t top = maxEntriesPerPage; // Show max entries by default 2173 if (!getSkipParam(asyncResp, req, skip)) 2174 { 2175 return; 2176 } 2177 if (!getTopParam(asyncResp, req, top)) 2178 { 2179 return; 2180 } 2181 // Collections don't include the static data added by SubRoute 2182 // because it has a duplicate entry for members 2183 asyncResp->res.jsonValue["@odata.type"] = 2184 "#LogEntryCollection.LogEntryCollection"; 2185 asyncResp->res.jsonValue["@odata.id"] = 2186 "/redfish/v1/Managers/bmc/LogServices/Journal/Entries"; 2187 asyncResp->res.jsonValue["Name"] = "Open BMC Journal Entries"; 2188 asyncResp->res.jsonValue["Description"] = 2189 "Collection of BMC Journal Entries"; 2190 nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"]; 2191 logEntryArray = nlohmann::json::array(); 2192 2193 // Go through the journal and use the timestamp to create a 2194 // unique ID for each entry 2195 sd_journal* journalTmp = nullptr; 2196 int ret = sd_journal_open(&journalTmp, SD_JOURNAL_LOCAL_ONLY); 2197 if (ret < 0) 2198 { 2199 BMCWEB_LOG_ERROR << "failed to open journal: " 2200 << strerror(-ret); 2201 messages::internalError(asyncResp->res); 2202 return; 2203 } 2204 std::unique_ptr<sd_journal, decltype(&sd_journal_close)> journal( 2205 journalTmp, sd_journal_close); 2206 journalTmp = nullptr; 2207 uint64_t entryCount = 0; 2208 // Reset the unique ID on the first entry 2209 bool firstEntry = true; 2210 SD_JOURNAL_FOREACH(journal.get()) 2211 { 2212 entryCount++; 2213 // Handle paging using skip (number of entries to skip from 2214 // the start) and top (number of entries to display) 2215 if (entryCount <= skip || entryCount > skip + top) 2216 { 2217 continue; 2218 } 2219 2220 std::string idStr; 2221 if (!getUniqueEntryID(journal.get(), idStr, firstEntry)) 2222 { 2223 continue; 2224 } 2225 2226 if (firstEntry) 2227 { 2228 firstEntry = false; 2229 } 2230 2231 logEntryArray.push_back({}); 2232 nlohmann::json& bmcJournalLogEntry = logEntryArray.back(); 2233 if (fillBMCJournalLogEntryJson(idStr, journal.get(), 2234 bmcJournalLogEntry) != 0) 2235 { 2236 messages::internalError(asyncResp->res); 2237 return; 2238 } 2239 } 2240 asyncResp->res.jsonValue["Members@odata.count"] = entryCount; 2241 if (skip + top < entryCount) 2242 { 2243 asyncResp->res.jsonValue["Members@odata.nextLink"] = 2244 "/redfish/v1/Managers/bmc/LogServices/Journal/Entries?$skip=" + 2245 std::to_string(skip + top); 2246 } 2247 }); 2248 } 2249 2250 inline void requestRoutesBMCJournalLogEntry(App& app) 2251 { 2252 BMCWEB_ROUTE(app, 2253 "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/<str>/") 2254 .privileges(redfish::privileges::getLogEntry) 2255 .methods(boost::beast::http::verb::get)( 2256 [](const crow::Request&, 2257 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 2258 const std::string& entryID) { 2259 // Convert the unique ID back to a timestamp to find the entry 2260 uint64_t ts = 0; 2261 uint64_t index = 0; 2262 if (!getTimestampFromID(asyncResp, entryID, ts, index)) 2263 { 2264 return; 2265 } 2266 2267 sd_journal* journalTmp = nullptr; 2268 int ret = sd_journal_open(&journalTmp, SD_JOURNAL_LOCAL_ONLY); 2269 if (ret < 0) 2270 { 2271 BMCWEB_LOG_ERROR << "failed to open journal: " 2272 << strerror(-ret); 2273 messages::internalError(asyncResp->res); 2274 return; 2275 } 2276 std::unique_ptr<sd_journal, decltype(&sd_journal_close)> 2277 journal(journalTmp, sd_journal_close); 2278 journalTmp = nullptr; 2279 // Go to the timestamp in the log and move to the entry at the 2280 // index tracking the unique ID 2281 std::string idStr; 2282 bool firstEntry = true; 2283 ret = sd_journal_seek_realtime_usec(journal.get(), ts); 2284 if (ret < 0) 2285 { 2286 BMCWEB_LOG_ERROR << "failed to seek to an entry in journal" 2287 << strerror(-ret); 2288 messages::internalError(asyncResp->res); 2289 return; 2290 } 2291 for (uint64_t i = 0; i <= index; i++) 2292 { 2293 sd_journal_next(journal.get()); 2294 if (!getUniqueEntryID(journal.get(), idStr, firstEntry)) 2295 { 2296 messages::internalError(asyncResp->res); 2297 return; 2298 } 2299 if (firstEntry) 2300 { 2301 firstEntry = false; 2302 } 2303 } 2304 // Confirm that the entry ID matches what was requested 2305 if (idStr != entryID) 2306 { 2307 messages::resourceMissingAtURI(asyncResp->res, entryID); 2308 return; 2309 } 2310 2311 if (fillBMCJournalLogEntryJson(entryID, journal.get(), 2312 asyncResp->res.jsonValue) != 0) 2313 { 2314 messages::internalError(asyncResp->res); 2315 return; 2316 } 2317 }); 2318 } 2319 2320 inline void requestRoutesBMCDumpService(App& app) 2321 { 2322 BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Dump/") 2323 .privileges(redfish::privileges::getLogService) 2324 .methods( 2325 boost::beast::http::verb:: 2326 get)([](const crow::Request&, 2327 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2328 asyncResp->res.jsonValue["@odata.id"] = 2329 "/redfish/v1/Managers/bmc/LogServices/Dump"; 2330 asyncResp->res.jsonValue["@odata.type"] = 2331 "#LogService.v1_2_0.LogService"; 2332 asyncResp->res.jsonValue["Name"] = "Dump LogService"; 2333 asyncResp->res.jsonValue["Description"] = "BMC Dump LogService"; 2334 asyncResp->res.jsonValue["Id"] = "Dump"; 2335 asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull"; 2336 2337 std::pair<std::string, std::string> redfishDateTimeOffset = 2338 crow::utility::getDateTimeOffsetNow(); 2339 asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first; 2340 asyncResp->res.jsonValue["DateTimeLocalOffset"] = 2341 redfishDateTimeOffset.second; 2342 2343 asyncResp->res.jsonValue["Entries"] = { 2344 {"@odata.id", 2345 "/redfish/v1/Managers/bmc/LogServices/Dump/Entries"}}; 2346 asyncResp->res.jsonValue["Actions"] = { 2347 {"#LogService.ClearLog", 2348 {{"target", 2349 "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.ClearLog"}}}, 2350 {"#LogService.CollectDiagnosticData", 2351 {{"target", 2352 "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.CollectDiagnosticData"}}}}; 2353 }); 2354 } 2355 2356 inline void requestRoutesBMCDumpEntryCollection(App& app) 2357 { 2358 2359 /** 2360 * Functions triggers appropriate requests on DBus 2361 */ 2362 BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/") 2363 .privileges(redfish::privileges::getLogEntryCollection) 2364 .methods(boost::beast::http::verb::get)( 2365 [](const crow::Request&, 2366 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2367 asyncResp->res.jsonValue["@odata.type"] = 2368 "#LogEntryCollection.LogEntryCollection"; 2369 asyncResp->res.jsonValue["@odata.id"] = 2370 "/redfish/v1/Managers/bmc/LogServices/Dump/Entries"; 2371 asyncResp->res.jsonValue["Name"] = "BMC Dump Entries"; 2372 asyncResp->res.jsonValue["Description"] = 2373 "Collection of BMC Dump Entries"; 2374 2375 getDumpEntryCollection(asyncResp, "BMC"); 2376 }); 2377 } 2378 2379 inline void requestRoutesBMCDumpEntry(App& app) 2380 { 2381 BMCWEB_ROUTE(app, 2382 "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/<str>/") 2383 .privileges(redfish::privileges::getLogEntry) 2384 .methods(boost::beast::http::verb::get)( 2385 [](const crow::Request&, 2386 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 2387 const std::string& param) { 2388 getDumpEntryById(asyncResp, param, "BMC"); 2389 }); 2390 BMCWEB_ROUTE(app, 2391 "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/<str>/") 2392 .privileges(redfish::privileges::deleteLogEntry) 2393 .methods(boost::beast::http::verb::delete_)( 2394 [](const crow::Request&, 2395 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 2396 const std::string& param) { 2397 deleteDumpEntry(asyncResp, param, "bmc"); 2398 }); 2399 } 2400 2401 inline void requestRoutesBMCDumpCreate(App& app) 2402 { 2403 2404 BMCWEB_ROUTE( 2405 app, 2406 "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.CollectDiagnosticData/") 2407 .privileges(redfish::privileges::postLogService) 2408 .methods(boost::beast::http::verb::post)( 2409 [](const crow::Request& req, 2410 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2411 createDump(asyncResp, req, "BMC"); 2412 }); 2413 } 2414 2415 inline void requestRoutesBMCDumpClear(App& app) 2416 { 2417 BMCWEB_ROUTE( 2418 app, 2419 "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.ClearLog/") 2420 .privileges(redfish::privileges::postLogService) 2421 .methods(boost::beast::http::verb::post)( 2422 [](const crow::Request&, 2423 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2424 clearDump(asyncResp, "BMC"); 2425 }); 2426 } 2427 2428 inline void requestRoutesSystemDumpService(App& app) 2429 { 2430 BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/Dump/") 2431 .privileges(redfish::privileges::getLogService) 2432 .methods(boost::beast::http::verb::get)( 2433 [](const crow::Request&, 2434 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) 2435 2436 { 2437 asyncResp->res.jsonValue["@odata.id"] = 2438 "/redfish/v1/Systems/system/LogServices/Dump"; 2439 asyncResp->res.jsonValue["@odata.type"] = 2440 "#LogService.v1_2_0.LogService"; 2441 asyncResp->res.jsonValue["Name"] = "Dump LogService"; 2442 asyncResp->res.jsonValue["Description"] = 2443 "System Dump LogService"; 2444 asyncResp->res.jsonValue["Id"] = "Dump"; 2445 asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull"; 2446 2447 std::pair<std::string, std::string> redfishDateTimeOffset = 2448 crow::utility::getDateTimeOffsetNow(); 2449 asyncResp->res.jsonValue["DateTime"] = 2450 redfishDateTimeOffset.first; 2451 asyncResp->res.jsonValue["DateTimeLocalOffset"] = 2452 redfishDateTimeOffset.second; 2453 2454 asyncResp->res.jsonValue["Entries"] = { 2455 {"@odata.id", 2456 "/redfish/v1/Systems/system/LogServices/Dump/Entries"}}; 2457 asyncResp->res.jsonValue["Actions"] = { 2458 {"#LogService.ClearLog", 2459 {{"target", 2460 "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.ClearLog"}}}, 2461 {"#LogService.CollectDiagnosticData", 2462 {{"target", 2463 "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.CollectDiagnosticData"}}}}; 2464 }); 2465 } 2466 2467 inline void requestRoutesSystemDumpEntryCollection(App& app) 2468 { 2469 2470 /** 2471 * Functions triggers appropriate requests on DBus 2472 */ 2473 BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/Dump/Entries/") 2474 .privileges(redfish::privileges::getLogEntryCollection) 2475 .methods(boost::beast::http::verb::get)( 2476 [](const crow::Request&, 2477 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2478 asyncResp->res.jsonValue["@odata.type"] = 2479 "#LogEntryCollection.LogEntryCollection"; 2480 asyncResp->res.jsonValue["@odata.id"] = 2481 "/redfish/v1/Systems/system/LogServices/Dump/Entries"; 2482 asyncResp->res.jsonValue["Name"] = "System Dump Entries"; 2483 asyncResp->res.jsonValue["Description"] = 2484 "Collection of System Dump Entries"; 2485 2486 getDumpEntryCollection(asyncResp, "System"); 2487 }); 2488 } 2489 2490 inline void requestRoutesSystemDumpEntry(App& app) 2491 { 2492 BMCWEB_ROUTE(app, 2493 "/redfish/v1/Systems/system/LogServices/Dump/Entries/<str>/") 2494 .privileges(redfish::privileges::getLogEntry) 2495 2496 .methods(boost::beast::http::verb::get)( 2497 [](const crow::Request&, 2498 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 2499 const std::string& param) { 2500 getDumpEntryById(asyncResp, param, "System"); 2501 }); 2502 2503 BMCWEB_ROUTE(app, 2504 "/redfish/v1/Systems/system/LogServices/Dump/Entries/<str>/") 2505 .privileges(redfish::privileges::deleteLogEntry) 2506 .methods(boost::beast::http::verb::delete_)( 2507 [](const crow::Request&, 2508 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 2509 const std::string& param) { 2510 deleteDumpEntry(asyncResp, param, "system"); 2511 }); 2512 } 2513 2514 inline void requestRoutesSystemDumpCreate(App& app) 2515 { 2516 BMCWEB_ROUTE( 2517 app, 2518 "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.CollectDiagnosticData/") 2519 .privileges(redfish::privileges::postLogService) 2520 .methods(boost::beast::http::verb::post)( 2521 [](const crow::Request& req, 2522 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) 2523 2524 { createDump(asyncResp, req, "System"); }); 2525 } 2526 2527 inline void requestRoutesSystemDumpClear(App& app) 2528 { 2529 BMCWEB_ROUTE( 2530 app, 2531 "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.ClearLog/") 2532 .privileges(redfish::privileges::postLogService) 2533 .methods(boost::beast::http::verb::post)( 2534 [](const crow::Request&, 2535 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) 2536 2537 { clearDump(asyncResp, "System"); }); 2538 } 2539 2540 inline void requestRoutesCrashdumpService(App& app) 2541 { 2542 // Note: Deviated from redfish privilege registry for GET & HEAD 2543 // method for security reasons. 2544 /** 2545 * Functions triggers appropriate requests on DBus 2546 */ 2547 BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/Crashdump/") 2548 // This is incorrect, should be: 2549 //.privileges(redfish::privileges::getLogService) 2550 .privileges({{"ConfigureManager"}}) 2551 .methods( 2552 boost::beast::http::verb:: 2553 get)([](const crow::Request&, 2554 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2555 // Copy over the static data to include the entries added by 2556 // SubRoute 2557 asyncResp->res.jsonValue["@odata.id"] = 2558 "/redfish/v1/Systems/system/LogServices/Crashdump"; 2559 asyncResp->res.jsonValue["@odata.type"] = 2560 "#LogService.v1_2_0.LogService"; 2561 asyncResp->res.jsonValue["Name"] = "Open BMC Oem Crashdump Service"; 2562 asyncResp->res.jsonValue["Description"] = "Oem Crashdump Service"; 2563 asyncResp->res.jsonValue["Id"] = "Oem Crashdump"; 2564 asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull"; 2565 asyncResp->res.jsonValue["MaxNumberOfRecords"] = 3; 2566 2567 std::pair<std::string, std::string> redfishDateTimeOffset = 2568 crow::utility::getDateTimeOffsetNow(); 2569 asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first; 2570 asyncResp->res.jsonValue["DateTimeLocalOffset"] = 2571 redfishDateTimeOffset.second; 2572 2573 asyncResp->res.jsonValue["Entries"] = { 2574 {"@odata.id", 2575 "/redfish/v1/Systems/system/LogServices/Crashdump/Entries"}}; 2576 asyncResp->res.jsonValue["Actions"] = { 2577 {"#LogService.ClearLog", 2578 {{"target", 2579 "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.ClearLog"}}}, 2580 {"#LogService.CollectDiagnosticData", 2581 {{"target", 2582 "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.CollectDiagnosticData"}}}}; 2583 }); 2584 } 2585 2586 void inline requestRoutesCrashdumpClear(App& app) 2587 { 2588 BMCWEB_ROUTE( 2589 app, 2590 "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.ClearLog/") 2591 // This is incorrect, should be: 2592 //.privileges(redfish::privileges::postLogService) 2593 .privileges({{"ConfigureComponents"}}) 2594 .methods(boost::beast::http::verb::post)( 2595 [](const crow::Request&, 2596 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2597 crow::connections::systemBus->async_method_call( 2598 [asyncResp](const boost::system::error_code ec, 2599 const std::string&) { 2600 if (ec) 2601 { 2602 messages::internalError(asyncResp->res); 2603 return; 2604 } 2605 messages::success(asyncResp->res); 2606 }, 2607 crashdumpObject, crashdumpPath, deleteAllInterface, 2608 "DeleteAll"); 2609 }); 2610 } 2611 2612 static void 2613 logCrashdumpEntry(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 2614 const std::string& logID, nlohmann::json& logEntryJson) 2615 { 2616 auto getStoredLogCallback = 2617 [asyncResp, logID, &logEntryJson]( 2618 const boost::system::error_code ec, 2619 const std::vector< 2620 std::pair<std::string, dbus::utility::DbusVariantType>>& 2621 params) { 2622 if (ec) 2623 { 2624 BMCWEB_LOG_DEBUG << "failed to get log ec: " << ec.message(); 2625 if (ec.value() == 2626 boost::system::linux_error::bad_request_descriptor) 2627 { 2628 messages::resourceNotFound(asyncResp->res, "LogEntry", 2629 logID); 2630 } 2631 else 2632 { 2633 messages::internalError(asyncResp->res); 2634 } 2635 return; 2636 } 2637 2638 std::string timestamp{}; 2639 std::string filename{}; 2640 std::string logfile{}; 2641 parseCrashdumpParameters(params, filename, timestamp, logfile); 2642 2643 if (filename.empty() || timestamp.empty()) 2644 { 2645 messages::resourceMissingAtURI(asyncResp->res, logID); 2646 return; 2647 } 2648 2649 std::string crashdumpURI = 2650 "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/" + 2651 logID + "/" + filename; 2652 logEntryJson = { 2653 {"@odata.type", "#LogEntry.v1_7_0.LogEntry"}, 2654 {"@odata.id", 2655 "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/" + 2656 logID}, 2657 {"Name", "CPU Crashdump"}, 2658 {"Id", logID}, 2659 {"EntryType", "Oem"}, 2660 {"AdditionalDataURI", std::move(crashdumpURI)}, 2661 {"DiagnosticDataType", "OEM"}, 2662 {"OEMDiagnosticDataType", "PECICrashdump"}, 2663 {"Created", std::move(timestamp)}}; 2664 }; 2665 crow::connections::systemBus->async_method_call( 2666 std::move(getStoredLogCallback), crashdumpObject, 2667 crashdumpPath + std::string("/") + logID, 2668 "org.freedesktop.DBus.Properties", "GetAll", crashdumpInterface); 2669 } 2670 2671 inline void requestRoutesCrashdumpEntryCollection(App& app) 2672 { 2673 // Note: Deviated from redfish privilege registry for GET & HEAD 2674 // method for security reasons. 2675 /** 2676 * Functions triggers appropriate requests on DBus 2677 */ 2678 BMCWEB_ROUTE(app, 2679 "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/") 2680 // This is incorrect, should be. 2681 //.privileges(redfish::privileges::postLogEntryCollection) 2682 .privileges({{"ConfigureComponents"}}) 2683 .methods( 2684 boost::beast::http::verb:: 2685 get)([](const crow::Request&, 2686 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2687 // Collections don't include the static data added by SubRoute 2688 // because it has a duplicate entry for members 2689 auto getLogEntriesCallback = [asyncResp]( 2690 const boost::system::error_code ec, 2691 const std::vector<std::string>& 2692 resp) { 2693 if (ec) 2694 { 2695 if (ec.value() != 2696 boost::system::errc::no_such_file_or_directory) 2697 { 2698 BMCWEB_LOG_DEBUG << "failed to get entries ec: " 2699 << ec.message(); 2700 messages::internalError(asyncResp->res); 2701 return; 2702 } 2703 } 2704 asyncResp->res.jsonValue["@odata.type"] = 2705 "#LogEntryCollection.LogEntryCollection"; 2706 asyncResp->res.jsonValue["@odata.id"] = 2707 "/redfish/v1/Systems/system/LogServices/Crashdump/Entries"; 2708 asyncResp->res.jsonValue["Name"] = "Open BMC Crashdump Entries"; 2709 asyncResp->res.jsonValue["Description"] = 2710 "Collection of Crashdump Entries"; 2711 nlohmann::json& logEntryArray = 2712 asyncResp->res.jsonValue["Members"]; 2713 logEntryArray = nlohmann::json::array(); 2714 std::vector<std::string> logIDs; 2715 // Get the list of log entries and build up an empty array big 2716 // enough to hold them 2717 for (const std::string& objpath : resp) 2718 { 2719 // Get the log ID 2720 std::size_t lastPos = objpath.rfind('/'); 2721 if (lastPos == std::string::npos) 2722 { 2723 continue; 2724 } 2725 logIDs.emplace_back(objpath.substr(lastPos + 1)); 2726 2727 // Add a space for the log entry to the array 2728 logEntryArray.push_back({}); 2729 } 2730 // Now go through and set up async calls to fill in the entries 2731 size_t index = 0; 2732 for (const std::string& logID : logIDs) 2733 { 2734 // Add the log entry to the array 2735 logCrashdumpEntry(asyncResp, logID, logEntryArray[index++]); 2736 } 2737 asyncResp->res.jsonValue["Members@odata.count"] = 2738 logEntryArray.size(); 2739 }; 2740 crow::connections::systemBus->async_method_call( 2741 std::move(getLogEntriesCallback), 2742 "xyz.openbmc_project.ObjectMapper", 2743 "/xyz/openbmc_project/object_mapper", 2744 "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", "", 0, 2745 std::array<const char*, 1>{crashdumpInterface}); 2746 }); 2747 } 2748 2749 inline void requestRoutesCrashdumpEntry(App& app) 2750 { 2751 // Note: Deviated from redfish privilege registry for GET & HEAD 2752 // method for security reasons. 2753 2754 BMCWEB_ROUTE( 2755 app, "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/<str>/") 2756 // this is incorrect, should be 2757 // .privileges(redfish::privileges::getLogEntry) 2758 .privileges({{"ConfigureComponents"}}) 2759 .methods(boost::beast::http::verb::get)( 2760 [](const crow::Request&, 2761 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 2762 const std::string& param) { 2763 const std::string& logID = param; 2764 logCrashdumpEntry(asyncResp, logID, asyncResp->res.jsonValue); 2765 }); 2766 } 2767 2768 inline void requestRoutesCrashdumpFile(App& app) 2769 { 2770 // Note: Deviated from redfish privilege registry for GET & HEAD 2771 // method for security reasons. 2772 BMCWEB_ROUTE( 2773 app, 2774 "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/<str>/<str>/") 2775 .privileges(redfish::privileges::getLogEntry) 2776 .methods(boost::beast::http::verb::get)( 2777 [](const crow::Request&, 2778 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 2779 const std::string& logID, const std::string& fileName) { 2780 auto getStoredLogCallback = 2781 [asyncResp, logID, fileName]( 2782 const boost::system::error_code ec, 2783 const std::vector<std::pair< 2784 std::string, dbus::utility::DbusVariantType>>& 2785 resp) { 2786 if (ec) 2787 { 2788 BMCWEB_LOG_DEBUG << "failed to get log ec: " 2789 << ec.message(); 2790 messages::internalError(asyncResp->res); 2791 return; 2792 } 2793 2794 std::string dbusFilename{}; 2795 std::string dbusTimestamp{}; 2796 std::string dbusFilepath{}; 2797 2798 parseCrashdumpParameters(resp, dbusFilename, 2799 dbusTimestamp, dbusFilepath); 2800 2801 if (dbusFilename.empty() || dbusTimestamp.empty() || 2802 dbusFilepath.empty()) 2803 { 2804 messages::resourceMissingAtURI(asyncResp->res, 2805 fileName); 2806 return; 2807 } 2808 2809 // Verify the file name parameter is correct 2810 if (fileName != dbusFilename) 2811 { 2812 messages::resourceMissingAtURI(asyncResp->res, 2813 fileName); 2814 return; 2815 } 2816 2817 if (!std::filesystem::exists(dbusFilepath)) 2818 { 2819 messages::resourceMissingAtURI(asyncResp->res, 2820 fileName); 2821 return; 2822 } 2823 std::ifstream ifs(dbusFilepath, 2824 std::ios::in | std::ios::binary); 2825 asyncResp->res.body() = std::string( 2826 std::istreambuf_iterator<char>{ifs}, {}); 2827 2828 // Configure this to be a file download when accessed 2829 // from a browser 2830 asyncResp->res.addHeader("Content-Disposition", 2831 "attachment"); 2832 }; 2833 crow::connections::systemBus->async_method_call( 2834 std::move(getStoredLogCallback), crashdumpObject, 2835 crashdumpPath + std::string("/") + logID, 2836 "org.freedesktop.DBus.Properties", "GetAll", 2837 crashdumpInterface); 2838 }); 2839 } 2840 2841 inline void requestRoutesCrashdumpCollect(App& app) 2842 { 2843 // Note: Deviated from redfish privilege registry for GET & HEAD 2844 // method for security reasons. 2845 BMCWEB_ROUTE( 2846 app, 2847 "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.CollectDiagnosticData/") 2848 // The below is incorrect; Should be ConfigureManager 2849 //.privileges(redfish::privileges::postLogService) 2850 .privileges({{"ConfigureComponents"}}) 2851 .methods( 2852 boost::beast::http::verb:: 2853 post)([](const crow::Request& req, 2854 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2855 std::string diagnosticDataType; 2856 std::string oemDiagnosticDataType; 2857 if (!redfish::json_util::readJsonAction( 2858 req, asyncResp->res, "DiagnosticDataType", 2859 diagnosticDataType, "OEMDiagnosticDataType", 2860 oemDiagnosticDataType)) 2861 { 2862 return; 2863 } 2864 2865 if (diagnosticDataType != "OEM") 2866 { 2867 BMCWEB_LOG_ERROR 2868 << "Only OEM DiagnosticDataType supported for Crashdump"; 2869 messages::actionParameterValueFormatError( 2870 asyncResp->res, diagnosticDataType, "DiagnosticDataType", 2871 "CollectDiagnosticData"); 2872 return; 2873 } 2874 2875 auto collectCrashdumpCallback = [asyncResp, 2876 payload(task::Payload(req))]( 2877 const boost::system::error_code 2878 ec, 2879 const std::string&) mutable { 2880 if (ec) 2881 { 2882 if (ec.value() == 2883 boost::system::errc::operation_not_supported) 2884 { 2885 messages::resourceInStandby(asyncResp->res); 2886 } 2887 else if (ec.value() == 2888 boost::system::errc::device_or_resource_busy) 2889 { 2890 messages::serviceTemporarilyUnavailable(asyncResp->res, 2891 "60"); 2892 } 2893 else 2894 { 2895 messages::internalError(asyncResp->res); 2896 } 2897 return; 2898 } 2899 std::shared_ptr<task::TaskData> task = task::TaskData::createTask( 2900 [](boost::system::error_code err, 2901 sdbusplus::message::message&, 2902 const std::shared_ptr<task::TaskData>& taskData) { 2903 if (!err) 2904 { 2905 taskData->messages.emplace_back( 2906 messages::taskCompletedOK( 2907 std::to_string(taskData->index))); 2908 taskData->state = "Completed"; 2909 } 2910 return task::completed; 2911 }, 2912 "type='signal',interface='org.freedesktop.DBus.Properties'," 2913 "member='PropertiesChanged',arg0namespace='com.intel.crashdump'"); 2914 task->startTimer(std::chrono::minutes(5)); 2915 task->populateResp(asyncResp->res); 2916 task->payload.emplace(std::move(payload)); 2917 }; 2918 2919 if (oemDiagnosticDataType == "OnDemand") 2920 { 2921 crow::connections::systemBus->async_method_call( 2922 std::move(collectCrashdumpCallback), crashdumpObject, 2923 crashdumpPath, crashdumpOnDemandInterface, 2924 "GenerateOnDemandLog"); 2925 } 2926 else if (oemDiagnosticDataType == "Telemetry") 2927 { 2928 crow::connections::systemBus->async_method_call( 2929 std::move(collectCrashdumpCallback), crashdumpObject, 2930 crashdumpPath, crashdumpTelemetryInterface, 2931 "GenerateTelemetryLog"); 2932 } 2933 else 2934 { 2935 BMCWEB_LOG_ERROR << "Unsupported OEMDiagnosticDataType: " 2936 << oemDiagnosticDataType; 2937 messages::actionParameterValueFormatError( 2938 asyncResp->res, oemDiagnosticDataType, 2939 "OEMDiagnosticDataType", "CollectDiagnosticData"); 2940 return; 2941 } 2942 }); 2943 } 2944 2945 /** 2946 * DBusLogServiceActionsClear class supports POST method for ClearLog action. 2947 */ 2948 inline void requestRoutesDBusLogServiceActionsClear(App& app) 2949 { 2950 /** 2951 * Function handles POST method request. 2952 * The Clear Log actions does not require any parameter.The action deletes 2953 * all entries found in the Entries collection for this Log Service. 2954 */ 2955 2956 BMCWEB_ROUTE( 2957 app, 2958 "/redfish/v1/Systems/system/LogServices/EventLog/Actions/LogService.ClearLog/") 2959 .privileges(redfish::privileges::postLogService) 2960 .methods(boost::beast::http::verb::post)( 2961 [](const crow::Request&, 2962 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 2963 BMCWEB_LOG_DEBUG << "Do delete all entries."; 2964 2965 // Process response from Logging service. 2966 auto respHandler = [asyncResp]( 2967 const boost::system::error_code ec) { 2968 BMCWEB_LOG_DEBUG 2969 << "doClearLog resp_handler callback: Done"; 2970 if (ec) 2971 { 2972 // TODO Handle for specific error code 2973 BMCWEB_LOG_ERROR << "doClearLog resp_handler got error " 2974 << ec; 2975 asyncResp->res.result( 2976 boost::beast::http::status::internal_server_error); 2977 return; 2978 } 2979 2980 asyncResp->res.result( 2981 boost::beast::http::status::no_content); 2982 }; 2983 2984 // Make call to Logging service to request Clear Log 2985 crow::connections::systemBus->async_method_call( 2986 respHandler, "xyz.openbmc_project.Logging", 2987 "/xyz/openbmc_project/logging", 2988 "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll"); 2989 }); 2990 } 2991 2992 /**************************************************** 2993 * Redfish PostCode interfaces 2994 * using DBUS interface: getPostCodesTS 2995 ******************************************************/ 2996 inline void requestRoutesPostCodesLogService(App& app) 2997 { 2998 BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/PostCodes/") 2999 .privileges(redfish::privileges::getLogService) 3000 .methods( 3001 boost::beast::http::verb:: 3002 get)([](const crow::Request&, 3003 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 3004 asyncResp->res.jsonValue = { 3005 {"@odata.id", 3006 "/redfish/v1/Systems/system/LogServices/PostCodes"}, 3007 {"@odata.type", "#LogService.v1_1_0.LogService"}, 3008 {"Name", "POST Code Log Service"}, 3009 {"Description", "POST Code Log Service"}, 3010 {"Id", "BIOS POST Code Log"}, 3011 {"OverWritePolicy", "WrapsWhenFull"}, 3012 {"Entries", 3013 {{"@odata.id", 3014 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries"}}}}; 3015 3016 std::pair<std::string, std::string> redfishDateTimeOffset = 3017 crow::utility::getDateTimeOffsetNow(); 3018 asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first; 3019 asyncResp->res.jsonValue["DateTimeLocalOffset"] = 3020 redfishDateTimeOffset.second; 3021 3022 asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"] = { 3023 {"target", 3024 "/redfish/v1/Systems/system/LogServices/PostCodes/Actions/LogService.ClearLog"}}; 3025 }); 3026 } 3027 3028 inline void requestRoutesPostCodesClear(App& app) 3029 { 3030 BMCWEB_ROUTE( 3031 app, 3032 "/redfish/v1/Systems/system/LogServices/PostCodes/Actions/LogService.ClearLog/") 3033 // The following privilege is incorrect; It should be ConfigureManager 3034 //.privileges(redfish::privileges::postLogService) 3035 .privileges({{"ConfigureComponents"}}) 3036 .methods(boost::beast::http::verb::post)( 3037 [](const crow::Request&, 3038 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 3039 BMCWEB_LOG_DEBUG << "Do delete all postcodes entries."; 3040 3041 // Make call to post-code service to request clear all 3042 crow::connections::systemBus->async_method_call( 3043 [asyncResp](const boost::system::error_code ec) { 3044 if (ec) 3045 { 3046 // TODO Handle for specific error code 3047 BMCWEB_LOG_ERROR 3048 << "doClearPostCodes resp_handler got error " 3049 << ec; 3050 asyncResp->res.result(boost::beast::http::status:: 3051 internal_server_error); 3052 messages::internalError(asyncResp->res); 3053 return; 3054 } 3055 }, 3056 "xyz.openbmc_project.State.Boot.PostCode0", 3057 "/xyz/openbmc_project/State/Boot/PostCode0", 3058 "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll"); 3059 }); 3060 } 3061 3062 static void fillPostCodeEntry( 3063 const std::shared_ptr<bmcweb::AsyncResp>& aResp, 3064 const boost::container::flat_map< 3065 uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>& postcode, 3066 const uint16_t bootIndex, const uint64_t codeIndex = 0, 3067 const uint64_t skip = 0, const uint64_t top = 0) 3068 { 3069 // Get the Message from the MessageRegistry 3070 const message_registries::Message* message = 3071 message_registries::getMessage("OpenBMC.0.2.BIOSPOSTCode"); 3072 3073 uint64_t currentCodeIndex = 0; 3074 nlohmann::json& logEntryArray = aResp->res.jsonValue["Members"]; 3075 3076 uint64_t firstCodeTimeUs = 0; 3077 for (const std::pair<uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>& 3078 code : postcode) 3079 { 3080 currentCodeIndex++; 3081 std::string postcodeEntryID = 3082 "B" + std::to_string(bootIndex) + "-" + 3083 std::to_string(currentCodeIndex); // 1 based index in EntryID string 3084 3085 uint64_t usecSinceEpoch = code.first; 3086 uint64_t usTimeOffset = 0; 3087 3088 if (1 == currentCodeIndex) 3089 { // already incremented 3090 firstCodeTimeUs = code.first; 3091 } 3092 else 3093 { 3094 usTimeOffset = code.first - firstCodeTimeUs; 3095 } 3096 3097 // skip if no specific codeIndex is specified and currentCodeIndex does 3098 // not fall between top and skip 3099 if ((codeIndex == 0) && 3100 (currentCodeIndex <= skip || currentCodeIndex > top)) 3101 { 3102 continue; 3103 } 3104 3105 // skip if a specific codeIndex is specified and does not match the 3106 // currentIndex 3107 if ((codeIndex > 0) && (currentCodeIndex != codeIndex)) 3108 { 3109 // This is done for simplicity. 1st entry is needed to calculate 3110 // time offset. To improve efficiency, one can get to the entry 3111 // directly (possibly with flatmap's nth method) 3112 continue; 3113 } 3114 3115 // currentCodeIndex is within top and skip or equal to specified code 3116 // index 3117 3118 // Get the Created time from the timestamp 3119 std::string entryTimeStr; 3120 entryTimeStr = 3121 crow::utility::getDateTimeUint(usecSinceEpoch / 1000 / 1000); 3122 3123 // assemble messageArgs: BootIndex, TimeOffset(100us), PostCode(hex) 3124 std::ostringstream hexCode; 3125 hexCode << "0x" << std::setfill('0') << std::setw(2) << std::hex 3126 << std::get<0>(code.second); 3127 std::ostringstream timeOffsetStr; 3128 // Set Fixed -Point Notation 3129 timeOffsetStr << std::fixed; 3130 // Set precision to 4 digits 3131 timeOffsetStr << std::setprecision(4); 3132 // Add double to stream 3133 timeOffsetStr << static_cast<double>(usTimeOffset) / 1000 / 1000; 3134 std::vector<std::string> messageArgs = { 3135 std::to_string(bootIndex), timeOffsetStr.str(), hexCode.str()}; 3136 3137 // Get MessageArgs template from message registry 3138 std::string msg; 3139 if (message != nullptr) 3140 { 3141 msg = message->message; 3142 3143 // fill in this post code value 3144 int i = 0; 3145 for (const std::string& messageArg : messageArgs) 3146 { 3147 std::string argStr = "%" + std::to_string(++i); 3148 size_t argPos = msg.find(argStr); 3149 if (argPos != std::string::npos) 3150 { 3151 msg.replace(argPos, argStr.length(), messageArg); 3152 } 3153 } 3154 } 3155 3156 // Get Severity template from message registry 3157 std::string severity; 3158 if (message != nullptr) 3159 { 3160 severity = message->severity; 3161 } 3162 3163 // add to AsyncResp 3164 logEntryArray.push_back({}); 3165 nlohmann::json& bmcLogEntry = logEntryArray.back(); 3166 bmcLogEntry = { 3167 {"@odata.type", "#LogEntry.v1_8_0.LogEntry"}, 3168 {"@odata.id", 3169 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/" + 3170 postcodeEntryID}, 3171 {"Name", "POST Code Log Entry"}, 3172 {"Id", postcodeEntryID}, 3173 {"Message", std::move(msg)}, 3174 {"MessageId", "OpenBMC.0.2.BIOSPOSTCode"}, 3175 {"MessageArgs", std::move(messageArgs)}, 3176 {"EntryType", "Event"}, 3177 {"Severity", std::move(severity)}, 3178 {"Created", entryTimeStr}}; 3179 if (!std::get<std::vector<uint8_t>>(code.second).empty()) 3180 { 3181 bmcLogEntry["AdditionalDataURI"] = 3182 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/" + 3183 postcodeEntryID + "/attachment"; 3184 } 3185 } 3186 } 3187 3188 static void getPostCodeForEntry(const std::shared_ptr<bmcweb::AsyncResp>& aResp, 3189 const uint16_t bootIndex, 3190 const uint64_t codeIndex) 3191 { 3192 crow::connections::systemBus->async_method_call( 3193 [aResp, bootIndex, 3194 codeIndex](const boost::system::error_code ec, 3195 const boost::container::flat_map< 3196 uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>& 3197 postcode) { 3198 if (ec) 3199 { 3200 BMCWEB_LOG_DEBUG << "DBUS POST CODE PostCode response error"; 3201 messages::internalError(aResp->res); 3202 return; 3203 } 3204 3205 // skip the empty postcode boots 3206 if (postcode.empty()) 3207 { 3208 return; 3209 } 3210 3211 fillPostCodeEntry(aResp, postcode, bootIndex, codeIndex); 3212 3213 aResp->res.jsonValue["Members@odata.count"] = 3214 aResp->res.jsonValue["Members"].size(); 3215 }, 3216 "xyz.openbmc_project.State.Boot.PostCode0", 3217 "/xyz/openbmc_project/State/Boot/PostCode0", 3218 "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodesWithTimeStamp", 3219 bootIndex); 3220 } 3221 3222 static void getPostCodeForBoot(const std::shared_ptr<bmcweb::AsyncResp>& aResp, 3223 const uint16_t bootIndex, 3224 const uint16_t bootCount, 3225 const uint64_t entryCount, const uint64_t skip, 3226 const uint64_t top) 3227 { 3228 crow::connections::systemBus->async_method_call( 3229 [aResp, bootIndex, bootCount, entryCount, skip, 3230 top](const boost::system::error_code ec, 3231 const boost::container::flat_map< 3232 uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>& 3233 postcode) { 3234 if (ec) 3235 { 3236 BMCWEB_LOG_DEBUG << "DBUS POST CODE PostCode response error"; 3237 messages::internalError(aResp->res); 3238 return; 3239 } 3240 3241 uint64_t endCount = entryCount; 3242 if (!postcode.empty()) 3243 { 3244 endCount = entryCount + postcode.size(); 3245 3246 if ((skip < endCount) && ((top + skip) > entryCount)) 3247 { 3248 uint64_t thisBootSkip = 3249 std::max(skip, entryCount) - entryCount; 3250 uint64_t thisBootTop = 3251 std::min(top + skip, endCount) - entryCount; 3252 3253 fillPostCodeEntry(aResp, postcode, bootIndex, 0, 3254 thisBootSkip, thisBootTop); 3255 } 3256 aResp->res.jsonValue["Members@odata.count"] = endCount; 3257 } 3258 3259 // continue to previous bootIndex 3260 if (bootIndex < bootCount) 3261 { 3262 getPostCodeForBoot(aResp, static_cast<uint16_t>(bootIndex + 1), 3263 bootCount, endCount, skip, top); 3264 } 3265 else 3266 { 3267 aResp->res.jsonValue["Members@odata.nextLink"] = 3268 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries?$skip=" + 3269 std::to_string(skip + top); 3270 } 3271 }, 3272 "xyz.openbmc_project.State.Boot.PostCode0", 3273 "/xyz/openbmc_project/State/Boot/PostCode0", 3274 "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodesWithTimeStamp", 3275 bootIndex); 3276 } 3277 3278 static void 3279 getCurrentBootNumber(const std::shared_ptr<bmcweb::AsyncResp>& aResp, 3280 const uint64_t skip, const uint64_t top) 3281 { 3282 uint64_t entryCount = 0; 3283 sdbusplus::asio::getProperty<uint16_t>( 3284 *crow::connections::systemBus, 3285 "xyz.openbmc_project.State.Boot.PostCode0", 3286 "/xyz/openbmc_project/State/Boot/PostCode0", 3287 "xyz.openbmc_project.State.Boot.PostCode", "CurrentBootCycleCount", 3288 [aResp, entryCount, skip, top](const boost::system::error_code ec, 3289 const uint16_t bootCount) { 3290 if (ec) 3291 { 3292 BMCWEB_LOG_DEBUG << "DBUS response error " << ec; 3293 messages::internalError(aResp->res); 3294 return; 3295 } 3296 getPostCodeForBoot(aResp, 1, bootCount, entryCount, skip, top); 3297 }); 3298 } 3299 3300 inline void requestRoutesPostCodesEntryCollection(App& app) 3301 { 3302 BMCWEB_ROUTE(app, 3303 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/") 3304 .privileges(redfish::privileges::getLogEntryCollection) 3305 .methods(boost::beast::http::verb::get)( 3306 [](const crow::Request& req, 3307 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 3308 asyncResp->res.jsonValue["@odata.type"] = 3309 "#LogEntryCollection.LogEntryCollection"; 3310 asyncResp->res.jsonValue["@odata.id"] = 3311 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries"; 3312 asyncResp->res.jsonValue["Name"] = "BIOS POST Code Log Entries"; 3313 asyncResp->res.jsonValue["Description"] = 3314 "Collection of POST Code Log Entries"; 3315 asyncResp->res.jsonValue["Members"] = nlohmann::json::array(); 3316 asyncResp->res.jsonValue["Members@odata.count"] = 0; 3317 3318 uint64_t skip = 0; 3319 uint64_t top = maxEntriesPerPage; // Show max entries by default 3320 if (!getSkipParam(asyncResp, req, skip)) 3321 { 3322 return; 3323 } 3324 if (!getTopParam(asyncResp, req, top)) 3325 { 3326 return; 3327 } 3328 getCurrentBootNumber(asyncResp, skip, top); 3329 }); 3330 } 3331 3332 /** 3333 * @brief Parse post code ID and get the current value and index value 3334 * eg: postCodeID=B1-2, currentValue=1, index=2 3335 * 3336 * @param[in] postCodeID Post Code ID 3337 * @param[out] currentValue Current value 3338 * @param[out] index Index value 3339 * 3340 * @return bool true if the parsing is successful, false the parsing fails 3341 */ 3342 inline static bool parsePostCode(const std::string& postCodeID, 3343 uint64_t& currentValue, uint16_t& index) 3344 { 3345 std::vector<std::string> split; 3346 boost::algorithm::split(split, postCodeID, boost::is_any_of("-")); 3347 if (split.size() != 2 || split[0].length() < 2 || split[0].front() != 'B') 3348 { 3349 return false; 3350 } 3351 3352 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) 3353 const char* start = split[0].data() + 1; 3354 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) 3355 const char* end = split[0].data() + split[0].size(); 3356 auto [ptrIndex, ecIndex] = std::from_chars(start, end, index); 3357 3358 if (ptrIndex != end || ecIndex != std::errc()) 3359 { 3360 return false; 3361 } 3362 3363 start = split[1].data(); 3364 3365 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) 3366 end = split[1].data() + split[1].size(); 3367 auto [ptrValue, ecValue] = std::from_chars(start, end, currentValue); 3368 3369 return ptrValue == end && ecValue != std::errc(); 3370 } 3371 3372 inline void requestRoutesPostCodesEntryAdditionalData(App& app) 3373 { 3374 BMCWEB_ROUTE( 3375 app, 3376 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/<str>/attachment/") 3377 .privileges(redfish::privileges::getLogEntry) 3378 .methods(boost::beast::http::verb::get)( 3379 [](const crow::Request& req, 3380 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 3381 const std::string& postCodeID) { 3382 if (!http_helpers::isOctetAccepted( 3383 req.getHeaderValue("Accept"))) 3384 { 3385 asyncResp->res.result( 3386 boost::beast::http::status::bad_request); 3387 return; 3388 } 3389 3390 uint64_t currentValue = 0; 3391 uint16_t index = 0; 3392 if (!parsePostCode(postCodeID, currentValue, index)) 3393 { 3394 messages::resourceNotFound(asyncResp->res, "LogEntry", 3395 postCodeID); 3396 return; 3397 } 3398 3399 crow::connections::systemBus->async_method_call( 3400 [asyncResp, postCodeID, currentValue]( 3401 const boost::system::error_code ec, 3402 const std::vector<std::tuple< 3403 uint64_t, std::vector<uint8_t>>>& postcodes) { 3404 if (ec.value() == EBADR) 3405 { 3406 messages::resourceNotFound(asyncResp->res, 3407 "LogEntry", postCodeID); 3408 return; 3409 } 3410 if (ec) 3411 { 3412 BMCWEB_LOG_DEBUG << "DBUS response error " << ec; 3413 messages::internalError(asyncResp->res); 3414 return; 3415 } 3416 3417 size_t value = static_cast<size_t>(currentValue) - 1; 3418 if (value == std::string::npos || 3419 postcodes.size() < currentValue) 3420 { 3421 BMCWEB_LOG_ERROR << "Wrong currentValue value"; 3422 messages::resourceNotFound(asyncResp->res, 3423 "LogEntry", postCodeID); 3424 return; 3425 } 3426 3427 const auto& [tID, c] = postcodes[value]; 3428 if (c.empty()) 3429 { 3430 BMCWEB_LOG_INFO << "No found post code data"; 3431 messages::resourceNotFound(asyncResp->res, 3432 "LogEntry", postCodeID); 3433 return; 3434 } 3435 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) 3436 const char* d = reinterpret_cast<const char*>(c.data()); 3437 std::string_view strData(d, c.size()); 3438 3439 asyncResp->res.addHeader("Content-Type", 3440 "application/octet-stream"); 3441 asyncResp->res.addHeader("Content-Transfer-Encoding", 3442 "Base64"); 3443 asyncResp->res.body() = 3444 crow::utility::base64encode(strData); 3445 }, 3446 "xyz.openbmc_project.State.Boot.PostCode0", 3447 "/xyz/openbmc_project/State/Boot/PostCode0", 3448 "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodes", 3449 index); 3450 }); 3451 } 3452 3453 inline void requestRoutesPostCodesEntry(App& app) 3454 { 3455 BMCWEB_ROUTE( 3456 app, "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/<str>/") 3457 .privileges(redfish::privileges::getLogEntry) 3458 .methods(boost::beast::http::verb::get)( 3459 [](const crow::Request&, 3460 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 3461 const std::string& targetID) { 3462 uint16_t bootIndex = 0; 3463 uint64_t codeIndex = 0; 3464 if (!parsePostCode(targetID, codeIndex, bootIndex)) 3465 { 3466 // Requested ID was not found 3467 messages::resourceMissingAtURI(asyncResp->res, targetID); 3468 return; 3469 } 3470 if (bootIndex == 0 || codeIndex == 0) 3471 { 3472 BMCWEB_LOG_DEBUG << "Get Post Code invalid entry string " 3473 << targetID; 3474 } 3475 3476 asyncResp->res.jsonValue["@odata.type"] = 3477 "#LogEntry.v1_4_0.LogEntry"; 3478 asyncResp->res.jsonValue["@odata.id"] = 3479 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries"; 3480 asyncResp->res.jsonValue["Name"] = "BIOS POST Code Log Entries"; 3481 asyncResp->res.jsonValue["Description"] = 3482 "Collection of POST Code Log Entries"; 3483 asyncResp->res.jsonValue["Members"] = nlohmann::json::array(); 3484 asyncResp->res.jsonValue["Members@odata.count"] = 0; 3485 3486 getPostCodeForEntry(asyncResp, bootIndex, codeIndex); 3487 }); 3488 } 3489 3490 } // namespace redfish 3491