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