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