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