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 <app.hpp> 19 #include <boost/algorithm/string/classification.hpp> 20 #include <boost/algorithm/string/split.hpp> 21 #include <boost/range/algorithm/replace_copy_if.hpp> 22 #include <dbus_singleton.hpp> 23 #include <dbus_utility.hpp> 24 #include <query.hpp> 25 #include <registries/privilege_registry.hpp> 26 #include <sdbusplus/asio/property.hpp> 27 #include <utils/json_utils.hpp> 28 #include <utils/query_param.hpp> 29 30 #include <cmath> 31 #include <iterator> 32 #include <map> 33 #include <set> 34 #include <utility> 35 #include <variant> 36 37 namespace redfish 38 { 39 40 namespace sensors 41 { 42 namespace node 43 { 44 static constexpr std::string_view power = "Power"; 45 static constexpr std::string_view sensors = "Sensors"; 46 static constexpr std::string_view thermal = "Thermal"; 47 } // namespace node 48 49 // clang-format off 50 namespace dbus 51 { 52 static auto powerPaths = std::to_array<std::string_view>({ 53 "/xyz/openbmc_project/sensors/voltage", 54 "/xyz/openbmc_project/sensors/power" 55 }); 56 57 static auto sensorPaths = std::to_array<std::string_view>({ 58 "/xyz/openbmc_project/sensors/power", 59 "/xyz/openbmc_project/sensors/current", 60 "/xyz/openbmc_project/sensors/airflow", 61 "/xyz/openbmc_project/sensors/humidity", 62 #ifdef BMCWEB_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM 63 "/xyz/openbmc_project/sensors/voltage", 64 "/xyz/openbmc_project/sensors/fan_tach", 65 "/xyz/openbmc_project/sensors/temperature", 66 "/xyz/openbmc_project/sensors/fan_pwm", 67 "/xyz/openbmc_project/sensors/altitude", 68 "/xyz/openbmc_project/sensors/energy", 69 #endif 70 "/xyz/openbmc_project/sensors/utilization" 71 }); 72 73 static auto thermalPaths = std::to_array<std::string_view>({ 74 "/xyz/openbmc_project/sensors/fan_tach", 75 "/xyz/openbmc_project/sensors/temperature", 76 "/xyz/openbmc_project/sensors/fan_pwm" 77 }); 78 79 } // namespace dbus 80 // clang-format on 81 82 using sensorPair = std::pair<std::string_view, std::span<std::string_view>>; 83 static constexpr std::array<sensorPair, 3> paths = { 84 {{node::power, std::span<std::string_view>(dbus::powerPaths)}, 85 {node::sensors, std::span<std::string_view>(dbus::sensorPaths)}, 86 {node::thermal, std::span<std::string_view>(dbus::thermalPaths)}}}; 87 88 inline const char* toReadingType(const std::string& sensorType) 89 { 90 if (sensorType == "voltage") 91 { 92 return "Voltage"; 93 } 94 if (sensorType == "power") 95 { 96 return "Power"; 97 } 98 if (sensorType == "current") 99 { 100 return "Current"; 101 } 102 if (sensorType == "fan_tach") 103 { 104 return "Rotational"; 105 } 106 if (sensorType == "temperature") 107 { 108 return "Temperature"; 109 } 110 if (sensorType == "fan_pwm" || sensorType == "utilization") 111 { 112 return "Percent"; 113 } 114 if (sensorType == "humidity") 115 { 116 return "Humidity"; 117 } 118 if (sensorType == "altitude") 119 { 120 return "Altitude"; 121 } 122 if (sensorType == "airflow") 123 { 124 return "AirFlow"; 125 } 126 if (sensorType == "energy") 127 { 128 return "EnergyJoules"; 129 } 130 return ""; 131 } 132 133 inline const char* toReadingUnits(const std::string& sensorType) 134 { 135 if (sensorType == "voltage") 136 { 137 return "V"; 138 } 139 if (sensorType == "power") 140 { 141 return "W"; 142 } 143 if (sensorType == "current") 144 { 145 return "A"; 146 } 147 if (sensorType == "fan_tach") 148 { 149 return "RPM"; 150 } 151 if (sensorType == "temperature") 152 { 153 return "Cel"; 154 } 155 if (sensorType == "fan_pwm" || sensorType == "utilization" || 156 sensorType == "humidity") 157 { 158 return "%"; 159 } 160 if (sensorType == "altitude") 161 { 162 return "m"; 163 } 164 if (sensorType == "airflow") 165 { 166 return "cft_i/min"; 167 } 168 if (sensorType == "energy") 169 { 170 return "J"; 171 } 172 return ""; 173 } 174 } // namespace sensors 175 176 /** 177 * SensorsAsyncResp 178 * Gathers data needed for response processing after async calls are done 179 */ 180 class SensorsAsyncResp 181 { 182 public: 183 using DataCompleteCb = std::function<void( 184 const boost::beast::http::status status, 185 const std::map<std::string, std::string>& uriToDbus)>; 186 187 struct SensorData 188 { 189 const std::string name; 190 std::string uri; 191 const std::string valueKey; 192 const std::string dbusPath; 193 }; 194 195 SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn, 196 const std::string& chassisIdIn, 197 std::span<std::string_view> typesIn, 198 std::string_view subNode) : 199 asyncResp(asyncRespIn), 200 chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode), 201 efficientExpand(false) 202 {} 203 204 // Store extra data about sensor mapping and return it in callback 205 SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn, 206 const std::string& chassisIdIn, 207 std::span<std::string_view> typesIn, 208 std::string_view subNode, 209 DataCompleteCb&& creationComplete) : 210 asyncResp(asyncRespIn), 211 chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode), 212 efficientExpand(false), metadata{std::vector<SensorData>()}, 213 dataComplete{std::move(creationComplete)} 214 {} 215 216 // sensor collections expand 217 SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn, 218 const std::string& chassisIdIn, 219 const std::span<std::string_view> typesIn, 220 const std::string_view& subNode, bool efficientExpandIn) : 221 asyncResp(asyncRespIn), 222 chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode), 223 efficientExpand(efficientExpandIn) 224 {} 225 226 ~SensorsAsyncResp() 227 { 228 if (asyncResp->res.result() == 229 boost::beast::http::status::internal_server_error) 230 { 231 // Reset the json object to clear out any data that made it in 232 // before the error happened todo(ed) handle error condition with 233 // proper code 234 asyncResp->res.jsonValue = nlohmann::json::object(); 235 } 236 237 if (dataComplete && metadata) 238 { 239 std::map<std::string, std::string> map; 240 if (asyncResp->res.result() == boost::beast::http::status::ok) 241 { 242 for (auto& sensor : *metadata) 243 { 244 map.insert(std::make_pair(sensor.uri + sensor.valueKey, 245 sensor.dbusPath)); 246 } 247 } 248 dataComplete(asyncResp->res.result(), map); 249 } 250 } 251 252 SensorsAsyncResp(const SensorsAsyncResp&) = delete; 253 SensorsAsyncResp(SensorsAsyncResp&&) = delete; 254 SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete; 255 SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete; 256 257 void addMetadata(const nlohmann::json& sensorObject, 258 const std::string& valueKey, const std::string& dbusPath) 259 { 260 if (metadata) 261 { 262 metadata->emplace_back(SensorData{sensorObject["Name"], 263 sensorObject["@odata.id"], 264 valueKey, dbusPath}); 265 } 266 } 267 268 void updateUri(const std::string& name, const std::string& uri) 269 { 270 if (metadata) 271 { 272 for (auto& sensor : *metadata) 273 { 274 if (sensor.name == name) 275 { 276 sensor.uri = uri; 277 } 278 } 279 } 280 } 281 282 const std::shared_ptr<bmcweb::AsyncResp> asyncResp; 283 const std::string chassisId; 284 const std::span<std::string_view> types; 285 const std::string chassisSubNode; 286 const bool efficientExpand; 287 288 private: 289 std::optional<std::vector<SensorData>> metadata; 290 DataCompleteCb dataComplete; 291 }; 292 293 /** 294 * Possible states for physical inventory leds 295 */ 296 enum class LedState 297 { 298 OFF, 299 ON, 300 BLINK, 301 UNKNOWN 302 }; 303 304 /** 305 * D-Bus inventory item associated with one or more sensors. 306 */ 307 class InventoryItem 308 { 309 public: 310 explicit InventoryItem(const std::string& objPath) : objectPath(objPath) 311 { 312 // Set inventory item name to last node of object path 313 sdbusplus::message::object_path path(objectPath); 314 name = path.filename(); 315 if (name.empty()) 316 { 317 BMCWEB_LOG_ERROR << "Failed to find '/' in " << objectPath; 318 } 319 } 320 321 std::string objectPath; 322 std::string name; 323 bool isPresent = true; 324 bool isFunctional = true; 325 bool isPowerSupply = false; 326 int powerSupplyEfficiencyPercent = -1; 327 std::string manufacturer; 328 std::string model; 329 std::string partNumber; 330 std::string serialNumber; 331 std::set<std::string> sensors; 332 std::string ledObjectPath; 333 LedState ledState = LedState::UNKNOWN; 334 }; 335 336 /** 337 * @brief Get objects with connection necessary for sensors 338 * @param SensorsAsyncResp Pointer to object holding response data 339 * @param sensorNames Sensors retrieved from chassis 340 * @param callback Callback for processing gathered connections 341 */ 342 template <typename Callback> 343 void getObjectsWithConnection( 344 const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp, 345 const std::shared_ptr<std::set<std::string>>& sensorNames, 346 Callback&& callback) 347 { 348 BMCWEB_LOG_DEBUG << "getObjectsWithConnection enter"; 349 const std::string path = "/xyz/openbmc_project/sensors"; 350 const std::array<std::string, 1> interfaces = { 351 "xyz.openbmc_project.Sensor.Value"}; 352 353 // Response handler for parsing objects subtree 354 auto respHandler = 355 [callback{std::forward<Callback>(callback)}, sensorsAsyncResp, 356 sensorNames](const boost::system::error_code ec, 357 const dbus::utility::MapperGetSubTreeResponse& subtree) { 358 BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler enter"; 359 if (ec) 360 { 361 messages::internalError(sensorsAsyncResp->asyncResp->res); 362 BMCWEB_LOG_ERROR 363 << "getObjectsWithConnection resp_handler: Dbus error " << ec; 364 return; 365 } 366 367 BMCWEB_LOG_DEBUG << "Found " << subtree.size() << " subtrees"; 368 369 // Make unique list of connections only for requested sensor types and 370 // found in the chassis 371 std::set<std::string> connections; 372 std::set<std::pair<std::string, std::string>> objectsWithConnection; 373 374 BMCWEB_LOG_DEBUG << "sensorNames list count: " << sensorNames->size(); 375 for (const std::string& tsensor : *sensorNames) 376 { 377 BMCWEB_LOG_DEBUG << "Sensor to find: " << tsensor; 378 } 379 380 for (const std::pair< 381 std::string, 382 std::vector<std::pair<std::string, std::vector<std::string>>>>& 383 object : subtree) 384 { 385 if (sensorNames->find(object.first) != sensorNames->end()) 386 { 387 for (const std::pair<std::string, std::vector<std::string>>& 388 objData : object.second) 389 { 390 BMCWEB_LOG_DEBUG << "Adding connection: " << objData.first; 391 connections.insert(objData.first); 392 objectsWithConnection.insert( 393 std::make_pair(object.first, objData.first)); 394 } 395 } 396 } 397 BMCWEB_LOG_DEBUG << "Found " << connections.size() << " connections"; 398 callback(std::move(connections), std::move(objectsWithConnection)); 399 BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler exit"; 400 }; 401 // Make call to ObjectMapper to find all sensors objects 402 crow::connections::systemBus->async_method_call( 403 std::move(respHandler), "xyz.openbmc_project.ObjectMapper", 404 "/xyz/openbmc_project/object_mapper", 405 "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 2, interfaces); 406 BMCWEB_LOG_DEBUG << "getObjectsWithConnection exit"; 407 } 408 409 /** 410 * @brief Create connections necessary for sensors 411 * @param SensorsAsyncResp Pointer to object holding response data 412 * @param sensorNames Sensors retrieved from chassis 413 * @param callback Callback for processing gathered connections 414 */ 415 template <typename Callback> 416 void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp, 417 const std::shared_ptr<std::set<std::string>> sensorNames, 418 Callback&& callback) 419 { 420 auto objectsWithConnectionCb = 421 [callback](const std::set<std::string>& connections, 422 const std::set<std::pair<std::string, std::string>>& 423 /*objectsWithConnection*/) { callback(connections); }; 424 getObjectsWithConnection(sensorsAsyncResp, sensorNames, 425 std::move(objectsWithConnectionCb)); 426 } 427 428 /** 429 * @brief Shrinks the list of sensors for processing 430 * @param SensorsAysncResp The class holding the Redfish response 431 * @param allSensors A list of all the sensors associated to the 432 * chassis element (i.e. baseboard, front panel, etc...) 433 * @param activeSensors A list that is a reduction of the incoming 434 * allSensors list. Eliminate Thermal sensors when a Power request is 435 * made, and eliminate Power sensors when a Thermal request is made. 436 */ 437 inline void reduceSensorList( 438 const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp, 439 const std::vector<std::string>* allSensors, 440 const std::shared_ptr<std::set<std::string>>& activeSensors) 441 { 442 if (sensorsAsyncResp == nullptr) 443 { 444 return; 445 } 446 if ((allSensors == nullptr) || (activeSensors == nullptr)) 447 { 448 messages::resourceNotFound( 449 sensorsAsyncResp->asyncResp->res, sensorsAsyncResp->chassisSubNode, 450 sensorsAsyncResp->chassisSubNode == sensors::node::thermal 451 ? "Temperatures" 452 : "Voltages"); 453 454 return; 455 } 456 if (allSensors->empty()) 457 { 458 // Nothing to do, the activeSensors object is also empty 459 return; 460 } 461 462 for (std::string_view type : sensorsAsyncResp->types) 463 { 464 for (const std::string& sensor : *allSensors) 465 { 466 if (sensor.starts_with(type)) 467 { 468 activeSensors->emplace(sensor); 469 } 470 } 471 } 472 } 473 474 /** 475 * @brief Retrieves requested chassis sensors and redundancy data from DBus . 476 * @param SensorsAsyncResp Pointer to object holding response data 477 * @param callback Callback for next step in gathered sensor processing 478 */ 479 template <typename Callback> 480 void getChassis(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp, 481 Callback&& callback) 482 { 483 BMCWEB_LOG_DEBUG << "getChassis enter"; 484 const std::array<const char*, 2> interfaces = { 485 "xyz.openbmc_project.Inventory.Item.Board", 486 "xyz.openbmc_project.Inventory.Item.Chassis"}; 487 auto respHandler = 488 [callback{std::forward<Callback>(callback)}, sensorsAsyncResp]( 489 const boost::system::error_code ec, 490 const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) { 491 BMCWEB_LOG_DEBUG << "getChassis respHandler enter"; 492 if (ec) 493 { 494 BMCWEB_LOG_ERROR << "getChassis respHandler DBUS error: " << ec; 495 messages::internalError(sensorsAsyncResp->asyncResp->res); 496 return; 497 } 498 499 const std::string* chassisPath = nullptr; 500 std::string chassisName; 501 for (const std::string& chassis : chassisPaths) 502 { 503 sdbusplus::message::object_path path(chassis); 504 chassisName = path.filename(); 505 if (chassisName.empty()) 506 { 507 BMCWEB_LOG_ERROR << "Failed to find '/' in " << chassis; 508 continue; 509 } 510 if (chassisName == sensorsAsyncResp->chassisId) 511 { 512 chassisPath = &chassis; 513 break; 514 } 515 } 516 if (chassisPath == nullptr) 517 { 518 messages::resourceNotFound(sensorsAsyncResp->asyncResp->res, 519 "Chassis", sensorsAsyncResp->chassisId); 520 return; 521 } 522 523 const std::string& chassisSubNode = sensorsAsyncResp->chassisSubNode; 524 if (chassisSubNode == sensors::node::power) 525 { 526 sensorsAsyncResp->asyncResp->res.jsonValue["@odata.type"] = 527 "#Power.v1_5_2.Power"; 528 } 529 else if (chassisSubNode == sensors::node::thermal) 530 { 531 sensorsAsyncResp->asyncResp->res.jsonValue["@odata.type"] = 532 "#Thermal.v1_4_0.Thermal"; 533 sensorsAsyncResp->asyncResp->res.jsonValue["Fans"] = 534 nlohmann::json::array(); 535 sensorsAsyncResp->asyncResp->res.jsonValue["Temperatures"] = 536 nlohmann::json::array(); 537 } 538 else if (chassisSubNode == sensors::node::sensors) 539 { 540 sensorsAsyncResp->asyncResp->res.jsonValue["@odata.type"] = 541 "#SensorCollection.SensorCollection"; 542 sensorsAsyncResp->asyncResp->res.jsonValue["Description"] = 543 "Collection of Sensors for this Chassis"; 544 sensorsAsyncResp->asyncResp->res.jsonValue["Members"] = 545 nlohmann::json::array(); 546 sensorsAsyncResp->asyncResp->res.jsonValue["Members@odata.count"] = 547 0; 548 } 549 550 if (chassisSubNode != sensors::node::sensors) 551 { 552 sensorsAsyncResp->asyncResp->res.jsonValue["Id"] = chassisSubNode; 553 } 554 555 sensorsAsyncResp->asyncResp->res.jsonValue["@odata.id"] = 556 "/redfish/v1/Chassis/" + sensorsAsyncResp->chassisId + "/" + 557 chassisSubNode; 558 sensorsAsyncResp->asyncResp->res.jsonValue["Name"] = chassisSubNode; 559 // Get the list of all sensors for this Chassis element 560 std::string sensorPath = *chassisPath + "/all_sensors"; 561 sdbusplus::asio::getProperty<std::vector<std::string>>( 562 *crow::connections::systemBus, "xyz.openbmc_project.ObjectMapper", 563 sensorPath, "xyz.openbmc_project.Association", "endpoints", 564 [sensorsAsyncResp, 565 callback{std::forward<const Callback>(callback)}]( 566 const boost::system::error_code& e, 567 const std::vector<std::string>& nodeSensorList) { 568 if (e) 569 { 570 if (e.value() != EBADR) 571 { 572 messages::internalError(sensorsAsyncResp->asyncResp->res); 573 return; 574 } 575 } 576 const std::shared_ptr<std::set<std::string>> culledSensorList = 577 std::make_shared<std::set<std::string>>(); 578 reduceSensorList(sensorsAsyncResp, &nodeSensorList, 579 culledSensorList); 580 callback(culledSensorList); 581 }); 582 }; 583 584 // Get the Chassis Collection 585 crow::connections::systemBus->async_method_call( 586 respHandler, "xyz.openbmc_project.ObjectMapper", 587 "/xyz/openbmc_project/object_mapper", 588 "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", 589 "/xyz/openbmc_project/inventory", 0, interfaces); 590 BMCWEB_LOG_DEBUG << "getChassis exit"; 591 } 592 593 /** 594 * @brief Finds all DBus object paths that implement ObjectManager. 595 * 596 * Creates a mapping from the associated connection name to the object path. 597 * 598 * Finds the object paths asynchronously. Invokes callback when information has 599 * been obtained. 600 * 601 * The callback must have the following signature: 602 * @code 603 * callback(std::shared_ptr<std::map<std::string,std::string>> objectMgrPaths) 604 * @endcode 605 * 606 * @param sensorsAsyncResp Pointer to object holding response data. 607 * @param callback Callback to invoke when object paths obtained. 608 */ 609 template <typename Callback> 610 void getObjectManagerPaths( 611 const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp, 612 Callback&& callback) 613 { 614 BMCWEB_LOG_DEBUG << "getObjectManagerPaths enter"; 615 const std::array<std::string, 1> interfaces = { 616 "org.freedesktop.DBus.ObjectManager"}; 617 618 // Response handler for GetSubTree DBus method 619 auto respHandler = 620 [callback{std::forward<Callback>(callback)}, sensorsAsyncResp]( 621 const boost::system::error_code ec, 622 const dbus::utility::MapperGetSubTreeResponse& subtree) { 623 BMCWEB_LOG_DEBUG << "getObjectManagerPaths respHandler enter"; 624 if (ec) 625 { 626 messages::internalError(sensorsAsyncResp->asyncResp->res); 627 BMCWEB_LOG_ERROR << "getObjectManagerPaths respHandler: DBus error " 628 << ec; 629 return; 630 } 631 632 // Loop over returned object paths 633 std::shared_ptr<std::map<std::string, std::string>> objectMgrPaths = 634 std::make_shared<std::map<std::string, std::string>>(); 635 for (const std::pair< 636 std::string, 637 std::vector<std::pair<std::string, std::vector<std::string>>>>& 638 object : subtree) 639 { 640 // Loop over connections for current object path 641 const std::string& objectPath = object.first; 642 for (const std::pair<std::string, std::vector<std::string>>& 643 objData : object.second) 644 { 645 // Add mapping from connection to object path 646 const std::string& connection = objData.first; 647 (*objectMgrPaths)[connection] = objectPath; 648 BMCWEB_LOG_DEBUG << "Added mapping " << connection << " -> " 649 << objectPath; 650 } 651 } 652 callback(objectMgrPaths); 653 BMCWEB_LOG_DEBUG << "getObjectManagerPaths respHandler exit"; 654 }; 655 656 // Query mapper for all DBus object paths that implement ObjectManager 657 crow::connections::systemBus->async_method_call( 658 std::move(respHandler), "xyz.openbmc_project.ObjectMapper", 659 "/xyz/openbmc_project/object_mapper", 660 "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", 0, interfaces); 661 BMCWEB_LOG_DEBUG << "getObjectManagerPaths exit"; 662 } 663 664 /** 665 * @brief Returns the Redfish State value for the specified inventory item. 666 * @param inventoryItem D-Bus inventory item associated with a sensor. 667 * @return State value for inventory item. 668 */ 669 inline std::string getState(const InventoryItem* inventoryItem) 670 { 671 if ((inventoryItem != nullptr) && !(inventoryItem->isPresent)) 672 { 673 return "Absent"; 674 } 675 676 return "Enabled"; 677 } 678 679 /** 680 * @brief Returns the Redfish Health value for the specified sensor. 681 * @param sensorJson Sensor JSON object. 682 * @param interfacesDict Map of all sensor interfaces. 683 * @param inventoryItem D-Bus inventory item associated with the sensor. Will 684 * be nullptr if no associated inventory item was found. 685 * @return Health value for sensor. 686 */ 687 inline std::string 688 getHealth(nlohmann::json& sensorJson, 689 const dbus::utility::DBusInteracesMap& interfacesDict, 690 const InventoryItem* inventoryItem) 691 { 692 // Get current health value (if any) in the sensor JSON object. Some JSON 693 // objects contain multiple sensors (such as PowerSupplies). We want to set 694 // the overall health to be the most severe of any of the sensors. 695 std::string currentHealth; 696 auto statusIt = sensorJson.find("Status"); 697 if (statusIt != sensorJson.end()) 698 { 699 auto healthIt = statusIt->find("Health"); 700 if (healthIt != statusIt->end()) 701 { 702 std::string* health = healthIt->get_ptr<std::string*>(); 703 if (health != nullptr) 704 { 705 currentHealth = *health; 706 } 707 } 708 } 709 710 // If current health in JSON object is already Critical, return that. This 711 // should override the sensor health, which might be less severe. 712 if (currentHealth == "Critical") 713 { 714 return "Critical"; 715 } 716 717 // Check if sensor has critical threshold alarm 718 719 for (const auto& [interface, values] : interfacesDict) 720 { 721 if (interface == "xyz.openbmc_project.Sensor.Threshold.Critical") 722 { 723 for (const auto& [valueName, value] : values) 724 { 725 if (valueName == "CriticalAlarmHigh" || 726 valueName == "CriticalAlarmLow") 727 { 728 const bool* asserted = std::get_if<bool>(&value); 729 if (asserted == nullptr) 730 { 731 BMCWEB_LOG_ERROR << "Illegal sensor threshold"; 732 } 733 else if (*asserted) 734 { 735 return "Critical"; 736 } 737 } 738 } 739 } 740 } 741 742 // Check if associated inventory item is not functional 743 if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional)) 744 { 745 return "Critical"; 746 } 747 748 // If current health in JSON object is already Warning, return that. This 749 // should override the sensor status, which might be less severe. 750 if (currentHealth == "Warning") 751 { 752 return "Warning"; 753 } 754 755 // Check if sensor has warning threshold alarm 756 for (const auto& [interface, values] : interfacesDict) 757 { 758 if (interface == "xyz.openbmc_project.Sensor.Threshold.Warning") 759 { 760 for (const auto& [valueName, value] : values) 761 { 762 if (valueName == "WarningAlarmHigh" || 763 valueName == "WarningAlarmLow") 764 { 765 const bool* asserted = std::get_if<bool>(&value); 766 if (asserted == nullptr) 767 { 768 BMCWEB_LOG_ERROR << "Illegal sensor threshold"; 769 } 770 else if (*asserted) 771 { 772 return "Warning"; 773 } 774 } 775 } 776 } 777 } 778 779 return "OK"; 780 } 781 782 inline void setLedState(nlohmann::json& sensorJson, 783 const InventoryItem* inventoryItem) 784 { 785 if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty()) 786 { 787 switch (inventoryItem->ledState) 788 { 789 case LedState::OFF: 790 sensorJson["IndicatorLED"] = "Off"; 791 break; 792 case LedState::ON: 793 sensorJson["IndicatorLED"] = "Lit"; 794 break; 795 case LedState::BLINK: 796 sensorJson["IndicatorLED"] = "Blinking"; 797 break; 798 case LedState::UNKNOWN: 799 break; 800 } 801 } 802 } 803 804 /** 805 * @brief Builds a json sensor representation of a sensor. 806 * @param sensorName The name of the sensor to be built 807 * @param sensorType The type (temperature, fan_tach, etc) of the sensor to 808 * build 809 * @param sensorsAsyncResp Sensor metadata 810 * @param interfacesDict A dictionary of the interfaces and properties of said 811 * interfaces to be built from 812 * @param sensor_json The json object to fill 813 * @param inventoryItem D-Bus inventory item associated with the sensor. Will 814 * be nullptr if no associated inventory item was found. 815 */ 816 inline void objectInterfacesToJson( 817 const std::string& sensorName, const std::string& sensorType, 818 const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp, 819 const dbus::utility::DBusInteracesMap& interfacesDict, 820 nlohmann::json& sensorJson, InventoryItem* inventoryItem) 821 { 822 // Assume values exist as is (10^0 == 1) if no scale exists 823 int64_t scaleMultiplier = 0; 824 for (const auto& [interface, values] : interfacesDict) 825 { 826 if (interface == "xyz.openbmc_project.Sensor.Value") 827 { 828 for (const auto& [valueName, value] : values) 829 { 830 if (valueName == "Scale") 831 { 832 const int64_t* int64Value = std::get_if<int64_t>(&value); 833 if (int64Value != nullptr) 834 { 835 scaleMultiplier = *int64Value; 836 } 837 } 838 } 839 } 840 } 841 842 if (sensorsAsyncResp->chassisSubNode == sensors::node::sensors) 843 { 844 // For sensors in SensorCollection we set Id instead of MemberId, 845 // including power sensors. 846 sensorJson["Id"] = sensorName; 847 sensorJson["Name"] = boost::replace_all_copy(sensorName, "_", " "); 848 } 849 else if (sensorType != "power") 850 { 851 // Set MemberId and Name for non-power sensors. For PowerSupplies and 852 // PowerControl, those properties have more general values because 853 // multiple sensors can be stored in the same JSON object. 854 sensorJson["MemberId"] = sensorName; 855 sensorJson["Name"] = boost::replace_all_copy(sensorName, "_", " "); 856 } 857 858 sensorJson["Status"]["State"] = getState(inventoryItem); 859 sensorJson["Status"]["Health"] = 860 getHealth(sensorJson, interfacesDict, inventoryItem); 861 862 // Parameter to set to override the type we get from dbus, and force it to 863 // int, regardless of what is available. This is used for schemas like fan, 864 // that require integers, not floats. 865 bool forceToInt = false; 866 867 nlohmann::json::json_pointer unit("/Reading"); 868 if (sensorsAsyncResp->chassisSubNode == sensors::node::sensors) 869 { 870 sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor"; 871 872 const std::string& readingType = sensors::toReadingType(sensorType); 873 if (readingType.empty()) 874 { 875 BMCWEB_LOG_ERROR << "Redfish cannot map reading type for " 876 << sensorType; 877 } 878 else 879 { 880 sensorJson["ReadingType"] = readingType; 881 } 882 883 const std::string& readingUnits = sensors::toReadingUnits(sensorType); 884 if (readingUnits.empty()) 885 { 886 BMCWEB_LOG_ERROR << "Redfish cannot map reading unit for " 887 << sensorType; 888 } 889 else 890 { 891 sensorJson["ReadingUnits"] = readingUnits; 892 } 893 } 894 else if (sensorType == "temperature") 895 { 896 unit = "/ReadingCelsius"_json_pointer; 897 sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature"; 898 // TODO(ed) Documentation says that path should be type fan_tach, 899 // implementation seems to implement fan 900 } 901 else if (sensorType == "fan" || sensorType == "fan_tach") 902 { 903 unit = "/Reading"_json_pointer; 904 sensorJson["ReadingUnits"] = "RPM"; 905 sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan"; 906 setLedState(sensorJson, inventoryItem); 907 forceToInt = true; 908 } 909 else if (sensorType == "fan_pwm") 910 { 911 unit = "/Reading"_json_pointer; 912 sensorJson["ReadingUnits"] = "Percent"; 913 sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan"; 914 setLedState(sensorJson, inventoryItem); 915 forceToInt = true; 916 } 917 else if (sensorType == "voltage") 918 { 919 unit = "/ReadingVolts"_json_pointer; 920 sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage"; 921 } 922 else if (sensorType == "power") 923 { 924 std::string sensorNameLower = 925 boost::algorithm::to_lower_copy(sensorName); 926 927 if (sensorName == "total_power") 928 { 929 sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl"; 930 // Put multiple "sensors" into a single PowerControl, so have 931 // generic names for MemberId and Name. Follows Redfish mockup. 932 sensorJson["MemberId"] = "0"; 933 sensorJson["Name"] = "Chassis Power Control"; 934 unit = "/PowerConsumedWatts"_json_pointer; 935 } 936 else if (sensorNameLower.find("input") != std::string::npos) 937 { 938 unit = "/PowerInputWatts"_json_pointer; 939 } 940 else 941 { 942 unit = "/PowerOutputWatts"_json_pointer; 943 } 944 } 945 else 946 { 947 BMCWEB_LOG_ERROR << "Redfish cannot map object type for " << sensorName; 948 return; 949 } 950 // Map of dbus interface name, dbus property name and redfish property_name 951 std::vector< 952 std::tuple<const char*, const char*, nlohmann::json::json_pointer>> 953 properties; 954 properties.reserve(7); 955 956 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit); 957 958 if (sensorsAsyncResp->chassisSubNode == sensors::node::sensors) 959 { 960 properties.emplace_back( 961 "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh", 962 "/Thresholds/UpperCaution/Reading"_json_pointer); 963 properties.emplace_back( 964 "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow", 965 "/Thresholds/LowerCaution/Reading"_json_pointer); 966 properties.emplace_back( 967 "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh", 968 "/Thresholds/UpperCritical/Reading"_json_pointer); 969 properties.emplace_back( 970 "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow", 971 "/Thresholds/LowerCritical/Reading"_json_pointer); 972 } 973 else if (sensorType != "power") 974 { 975 properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning", 976 "WarningHigh", 977 "/UpperThresholdNonCritical"_json_pointer); 978 properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning", 979 "WarningLow", 980 "/LowerThresholdNonCritical"_json_pointer); 981 properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical", 982 "CriticalHigh", 983 "/UpperThresholdCritical"_json_pointer); 984 properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical", 985 "CriticalLow", 986 "/LowerThresholdCritical"_json_pointer); 987 } 988 989 // TODO Need to get UpperThresholdFatal and LowerThresholdFatal 990 991 if (sensorsAsyncResp->chassisSubNode == sensors::node::sensors) 992 { 993 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue", 994 "/ReadingRangeMin"_json_pointer); 995 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue", 996 "/ReadingRangeMax"_json_pointer); 997 } 998 else if (sensorType == "temperature") 999 { 1000 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue", 1001 "/MinReadingRangeTemp"_json_pointer); 1002 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue", 1003 "/MaxReadingRangeTemp"_json_pointer); 1004 } 1005 else if (sensorType != "power") 1006 { 1007 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue", 1008 "/MinReadingRange"_json_pointer); 1009 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue", 1010 "/MaxReadingRange"_json_pointer); 1011 } 1012 1013 for (const std::tuple<const char*, const char*, 1014 nlohmann::json::json_pointer>& p : properties) 1015 { 1016 for (const auto& [interface, values] : interfacesDict) 1017 { 1018 if (interface != std::get<0>(p)) 1019 { 1020 continue; 1021 } 1022 for (const auto& [valueName, valueVariant] : values) 1023 { 1024 if (valueName != std::get<1>(p)) 1025 { 1026 continue; 1027 } 1028 1029 // The property we want to set may be nested json, so use 1030 // a json_pointer for easy indexing into the json structure. 1031 const nlohmann::json::json_pointer& key = std::get<2>(p); 1032 1033 // Attempt to pull the int64 directly 1034 const int64_t* int64Value = std::get_if<int64_t>(&valueVariant); 1035 1036 const double* doubleValue = std::get_if<double>(&valueVariant); 1037 const uint32_t* uValue = std::get_if<uint32_t>(&valueVariant); 1038 double temp = 0.0; 1039 if (int64Value != nullptr) 1040 { 1041 temp = static_cast<double>(*int64Value); 1042 } 1043 else if (doubleValue != nullptr) 1044 { 1045 temp = *doubleValue; 1046 } 1047 else if (uValue != nullptr) 1048 { 1049 temp = *uValue; 1050 } 1051 else 1052 { 1053 BMCWEB_LOG_ERROR 1054 << "Got value interface that wasn't int or double"; 1055 continue; 1056 } 1057 temp = temp * std::pow(10, scaleMultiplier); 1058 if (forceToInt) 1059 { 1060 sensorJson[key] = static_cast<int64_t>(temp); 1061 } 1062 else 1063 { 1064 sensorJson[key] = temp; 1065 } 1066 } 1067 } 1068 } 1069 1070 sensorsAsyncResp->addMetadata(sensorJson, unit.to_string(), 1071 "/xyz/openbmc_project/sensors/" + sensorType + 1072 "/" + sensorName); 1073 1074 BMCWEB_LOG_DEBUG << "Added sensor " << sensorName; 1075 } 1076 1077 inline void populateFanRedundancy( 1078 const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp) 1079 { 1080 crow::connections::systemBus->async_method_call( 1081 [sensorsAsyncResp]( 1082 const boost::system::error_code ec, 1083 const dbus::utility::MapperGetSubTreeResponse& resp) { 1084 if (ec) 1085 { 1086 return; // don't have to have this interface 1087 } 1088 for (const std::pair< 1089 std::string, 1090 std::vector<std::pair<std::string, std::vector<std::string>>>>& 1091 pathPair : resp) 1092 { 1093 const std::string& path = pathPair.first; 1094 const std::vector<std::pair<std::string, std::vector<std::string>>>& 1095 objDict = pathPair.second; 1096 if (objDict.empty()) 1097 { 1098 continue; // this should be impossible 1099 } 1100 1101 const std::string& owner = objDict.begin()->first; 1102 sdbusplus::asio::getProperty<std::vector<std::string>>( 1103 *crow::connections::systemBus, 1104 "xyz.openbmc_project.ObjectMapper", path + "/chassis", 1105 "xyz.openbmc_project.Association", "endpoints", 1106 [path, owner, 1107 sensorsAsyncResp](const boost::system::error_code e, 1108 const std::vector<std::string>& endpoints) { 1109 if (e) 1110 { 1111 return; // if they don't have an association we 1112 // can't tell what chassis is 1113 } 1114 auto found = 1115 std::find_if(endpoints.begin(), endpoints.end(), 1116 [sensorsAsyncResp](const std::string& entry) { 1117 return entry.find(sensorsAsyncResp->chassisId) != 1118 std::string::npos; 1119 }); 1120 1121 if (found == endpoints.end()) 1122 { 1123 return; 1124 } 1125 crow::connections::systemBus->async_method_call( 1126 [path, sensorsAsyncResp]( 1127 const boost::system::error_code& err, 1128 const std::map<std::string, 1129 dbus::utility::DbusVariantType>& ret) { 1130 if (err) 1131 { 1132 return; // don't have to have this 1133 // interface 1134 } 1135 auto findFailures = ret.find("AllowedFailures"); 1136 auto findCollection = ret.find("Collection"); 1137 auto findStatus = ret.find("Status"); 1138 1139 if (findFailures == ret.end() || 1140 findCollection == ret.end() || findStatus == ret.end()) 1141 { 1142 BMCWEB_LOG_ERROR << "Invalid redundancy interface"; 1143 messages::internalError( 1144 sensorsAsyncResp->asyncResp->res); 1145 return; 1146 } 1147 1148 const uint8_t* allowedFailures = 1149 std::get_if<uint8_t>(&(findFailures->second)); 1150 const std::vector<std::string>* collection = 1151 std::get_if<std::vector<std::string>>( 1152 &(findCollection->second)); 1153 const std::string* status = 1154 std::get_if<std::string>(&(findStatus->second)); 1155 1156 if (allowedFailures == nullptr || collection == nullptr || 1157 status == nullptr) 1158 { 1159 1160 BMCWEB_LOG_ERROR 1161 << "Invalid redundancy interface types"; 1162 messages::internalError( 1163 sensorsAsyncResp->asyncResp->res); 1164 return; 1165 } 1166 sdbusplus::message::object_path objectPath(path); 1167 std::string name = objectPath.filename(); 1168 if (name.empty()) 1169 { 1170 // this should be impossible 1171 messages::internalError( 1172 sensorsAsyncResp->asyncResp->res); 1173 return; 1174 } 1175 std::replace(name.begin(), name.end(), '_', ' '); 1176 1177 std::string health; 1178 1179 if (status->ends_with("Full")) 1180 { 1181 health = "OK"; 1182 } 1183 else if (status->ends_with("Degraded")) 1184 { 1185 health = "Warning"; 1186 } 1187 else 1188 { 1189 health = "Critical"; 1190 } 1191 nlohmann::json::array_t redfishCollection; 1192 const auto& fanRedfish = 1193 sensorsAsyncResp->asyncResp->res.jsonValue["Fans"]; 1194 for (const std::string& item : *collection) 1195 { 1196 sdbusplus::message::object_path itemPath(item); 1197 std::string itemName = itemPath.filename(); 1198 if (itemName.empty()) 1199 { 1200 continue; 1201 } 1202 /* 1203 todo(ed): merge patch that fixes the names 1204 std::replace(itemName.begin(), 1205 itemName.end(), '_', ' ');*/ 1206 auto schemaItem = 1207 std::find_if(fanRedfish.begin(), fanRedfish.end(), 1208 [itemName](const nlohmann::json& fan) { 1209 return fan["MemberId"] == itemName; 1210 }); 1211 if (schemaItem != fanRedfish.end()) 1212 { 1213 nlohmann::json::object_t collectionId; 1214 collectionId["@odata.id"] = 1215 (*schemaItem)["@odata.id"]; 1216 redfishCollection.emplace_back( 1217 std::move(collectionId)); 1218 } 1219 else 1220 { 1221 BMCWEB_LOG_ERROR << "failed to find fan in schema"; 1222 messages::internalError( 1223 sensorsAsyncResp->asyncResp->res); 1224 return; 1225 } 1226 } 1227 1228 size_t minNumNeeded = 1229 collection->empty() 1230 ? 0 1231 : collection->size() - *allowedFailures; 1232 nlohmann::json& jResp = sensorsAsyncResp->asyncResp->res 1233 .jsonValue["Redundancy"]; 1234 1235 nlohmann::json::object_t redundancy; 1236 redundancy["@odata.id"] = 1237 "/redfish/v1/Chassis/" + sensorsAsyncResp->chassisId + 1238 "/" + sensorsAsyncResp->chassisSubNode + 1239 "#/Redundancy/" + std::to_string(jResp.size()); 1240 redundancy["@odata.type"] = "#Redundancy.v1_3_2.Redundancy"; 1241 redundancy["MinNumNeeded"] = minNumNeeded; 1242 redundancy["MemberId"] = name; 1243 redundancy["Mode"] = "N+m"; 1244 redundancy["Name"] = name; 1245 redundancy["RedundancySet"] = redfishCollection; 1246 redundancy["Status"]["Health"] = health; 1247 redundancy["Status"]["State"] = "Enabled"; 1248 1249 jResp.push_back(std::move(redundancy)); 1250 }, 1251 owner, path, "org.freedesktop.DBus.Properties", "GetAll", 1252 "xyz.openbmc_project.Control.FanRedundancy"); 1253 }); 1254 } 1255 }, 1256 "xyz.openbmc_project.ObjectMapper", 1257 "/xyz/openbmc_project/object_mapper", 1258 "xyz.openbmc_project.ObjectMapper", "GetSubTree", 1259 "/xyz/openbmc_project/control", 2, 1260 std::array<const char*, 1>{ 1261 "xyz.openbmc_project.Control.FanRedundancy"}); 1262 } 1263 1264 inline void 1265 sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp) 1266 { 1267 nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue; 1268 std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"}; 1269 if (sensorsAsyncResp->chassisSubNode == sensors::node::power) 1270 { 1271 sensorHeaders = {"Voltages", "PowerSupplies"}; 1272 } 1273 for (const std::string& sensorGroup : sensorHeaders) 1274 { 1275 nlohmann::json::iterator entry = response.find(sensorGroup); 1276 if (entry != response.end()) 1277 { 1278 std::sort(entry->begin(), entry->end(), 1279 [](const nlohmann::json& c1, const nlohmann::json& c2) { 1280 return c1["Name"] < c2["Name"]; 1281 }); 1282 1283 // add the index counts to the end of each entry 1284 size_t count = 0; 1285 for (nlohmann::json& sensorJson : *entry) 1286 { 1287 nlohmann::json::iterator odata = sensorJson.find("@odata.id"); 1288 if (odata == sensorJson.end()) 1289 { 1290 continue; 1291 } 1292 std::string* value = odata->get_ptr<std::string*>(); 1293 if (value != nullptr) 1294 { 1295 *value += std::to_string(count); 1296 count++; 1297 sensorsAsyncResp->updateUri(sensorJson["Name"], *value); 1298 } 1299 } 1300 } 1301 } 1302 } 1303 1304 /** 1305 * @brief Finds the inventory item with the specified object path. 1306 * @param inventoryItems D-Bus inventory items associated with sensors. 1307 * @param invItemObjPath D-Bus object path of inventory item. 1308 * @return Inventory item within vector, or nullptr if no match found. 1309 */ 1310 inline InventoryItem* findInventoryItem( 1311 const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems, 1312 const std::string& invItemObjPath) 1313 { 1314 for (InventoryItem& inventoryItem : *inventoryItems) 1315 { 1316 if (inventoryItem.objectPath == invItemObjPath) 1317 { 1318 return &inventoryItem; 1319 } 1320 } 1321 return nullptr; 1322 } 1323 1324 /** 1325 * @brief Finds the inventory item associated with the specified sensor. 1326 * @param inventoryItems D-Bus inventory items associated with sensors. 1327 * @param sensorObjPath D-Bus object path of sensor. 1328 * @return Inventory item within vector, or nullptr if no match found. 1329 */ 1330 inline InventoryItem* findInventoryItemForSensor( 1331 const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems, 1332 const std::string& sensorObjPath) 1333 { 1334 for (InventoryItem& inventoryItem : *inventoryItems) 1335 { 1336 if (inventoryItem.sensors.count(sensorObjPath) > 0) 1337 { 1338 return &inventoryItem; 1339 } 1340 } 1341 return nullptr; 1342 } 1343 1344 /** 1345 * @brief Finds the inventory item associated with the specified led path. 1346 * @param inventoryItems D-Bus inventory items associated with sensors. 1347 * @param ledObjPath D-Bus object path of led. 1348 * @return Inventory item within vector, or nullptr if no match found. 1349 */ 1350 inline InventoryItem* 1351 findInventoryItemForLed(std::vector<InventoryItem>& inventoryItems, 1352 const std::string& ledObjPath) 1353 { 1354 for (InventoryItem& inventoryItem : inventoryItems) 1355 { 1356 if (inventoryItem.ledObjectPath == ledObjPath) 1357 { 1358 return &inventoryItem; 1359 } 1360 } 1361 return nullptr; 1362 } 1363 1364 /** 1365 * @brief Adds inventory item and associated sensor to specified vector. 1366 * 1367 * Adds a new InventoryItem to the vector if necessary. Searches for an 1368 * existing InventoryItem with the specified object path. If not found, one is 1369 * added to the vector. 1370 * 1371 * Next, the specified sensor is added to the set of sensors associated with the 1372 * InventoryItem. 1373 * 1374 * @param inventoryItems D-Bus inventory items associated with sensors. 1375 * @param invItemObjPath D-Bus object path of inventory item. 1376 * @param sensorObjPath D-Bus object path of sensor 1377 */ 1378 inline void addInventoryItem( 1379 const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems, 1380 const std::string& invItemObjPath, const std::string& sensorObjPath) 1381 { 1382 // Look for inventory item in vector 1383 InventoryItem* inventoryItem = 1384 findInventoryItem(inventoryItems, invItemObjPath); 1385 1386 // If inventory item doesn't exist in vector, add it 1387 if (inventoryItem == nullptr) 1388 { 1389 inventoryItems->emplace_back(invItemObjPath); 1390 inventoryItem = &(inventoryItems->back()); 1391 } 1392 1393 // Add sensor to set of sensors associated with inventory item 1394 inventoryItem->sensors.emplace(sensorObjPath); 1395 } 1396 1397 /** 1398 * @brief Stores D-Bus data in the specified inventory item. 1399 * 1400 * Finds D-Bus data in the specified map of interfaces. Stores the data in the 1401 * specified InventoryItem. 1402 * 1403 * This data is later used to provide sensor property values in the JSON 1404 * response. 1405 * 1406 * @param inventoryItem Inventory item where data will be stored. 1407 * @param interfacesDict Map containing D-Bus interfaces and their properties 1408 * for the specified inventory item. 1409 */ 1410 inline void storeInventoryItemData( 1411 InventoryItem& inventoryItem, 1412 const dbus::utility::DBusInteracesMap& interfacesDict) 1413 { 1414 // Get properties from Inventory.Item interface 1415 1416 for (const auto& [interface, values] : interfacesDict) 1417 { 1418 if (interface == "xyz.openbmc_project.Inventory.Item") 1419 { 1420 for (const auto& [name, dbusValue] : values) 1421 { 1422 if (name == "Present") 1423 { 1424 const bool* value = std::get_if<bool>(&dbusValue); 1425 if (value != nullptr) 1426 { 1427 inventoryItem.isPresent = *value; 1428 } 1429 } 1430 } 1431 } 1432 // Check if Inventory.Item.PowerSupply interface is present 1433 1434 if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply") 1435 { 1436 inventoryItem.isPowerSupply = true; 1437 } 1438 1439 // Get properties from Inventory.Decorator.Asset interface 1440 if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset") 1441 { 1442 for (const auto& [name, dbusValue] : values) 1443 { 1444 if (name == "Manufacturer") 1445 { 1446 const std::string* value = 1447 std::get_if<std::string>(&dbusValue); 1448 if (value != nullptr) 1449 { 1450 inventoryItem.manufacturer = *value; 1451 } 1452 } 1453 if (name == "Model") 1454 { 1455 const std::string* value = 1456 std::get_if<std::string>(&dbusValue); 1457 if (value != nullptr) 1458 { 1459 inventoryItem.model = *value; 1460 } 1461 } 1462 if (name == "SerialNumber") 1463 { 1464 const std::string* value = 1465 std::get_if<std::string>(&dbusValue); 1466 if (value != nullptr) 1467 { 1468 inventoryItem.serialNumber = *value; 1469 } 1470 } 1471 if (name == "PartNumber") 1472 { 1473 const std::string* value = 1474 std::get_if<std::string>(&dbusValue); 1475 if (value != nullptr) 1476 { 1477 inventoryItem.partNumber = *value; 1478 } 1479 } 1480 } 1481 } 1482 1483 if (interface == 1484 "xyz.openbmc_project.State.Decorator.OperationalStatus") 1485 { 1486 for (const auto& [name, dbusValue] : values) 1487 { 1488 if (name == "Functional") 1489 { 1490 const bool* value = std::get_if<bool>(&dbusValue); 1491 if (value != nullptr) 1492 { 1493 inventoryItem.isFunctional = *value; 1494 } 1495 } 1496 } 1497 } 1498 } 1499 } 1500 1501 /** 1502 * @brief Gets D-Bus data for inventory items associated with sensors. 1503 * 1504 * Uses the specified connections (services) to obtain D-Bus data for inventory 1505 * items associated with sensors. Stores the resulting data in the 1506 * inventoryItems vector. 1507 * 1508 * This data is later used to provide sensor property values in the JSON 1509 * response. 1510 * 1511 * Finds the inventory item data asynchronously. Invokes callback when data has 1512 * been obtained. 1513 * 1514 * The callback must have the following signature: 1515 * @code 1516 * callback(void) 1517 * @endcode 1518 * 1519 * This function is called recursively, obtaining data asynchronously from one 1520 * connection in each call. This ensures the callback is not invoked until the 1521 * last asynchronous function has completed. 1522 * 1523 * @param sensorsAsyncResp Pointer to object holding response data. 1524 * @param inventoryItems D-Bus inventory items associated with sensors. 1525 * @param invConnections Connections that provide data for the inventory items. 1526 * @param objectMgrPaths Mappings from connection name to DBus object path that 1527 * implements ObjectManager. 1528 * @param callback Callback to invoke when inventory data has been obtained. 1529 * @param invConnectionsIndex Current index in invConnections. Only specified 1530 * in recursive calls to this function. 1531 */ 1532 template <typename Callback> 1533 static void getInventoryItemsData( 1534 std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp, 1535 std::shared_ptr<std::vector<InventoryItem>> inventoryItems, 1536 std::shared_ptr<std::set<std::string>> invConnections, 1537 std::shared_ptr<std::map<std::string, std::string>> objectMgrPaths, 1538 Callback&& callback, size_t invConnectionsIndex = 0) 1539 { 1540 BMCWEB_LOG_DEBUG << "getInventoryItemsData enter"; 1541 1542 // If no more connections left, call callback 1543 if (invConnectionsIndex >= invConnections->size()) 1544 { 1545 callback(); 1546 BMCWEB_LOG_DEBUG << "getInventoryItemsData exit"; 1547 return; 1548 } 1549 1550 // Get inventory item data from current connection 1551 auto it = invConnections->begin(); 1552 std::advance(it, invConnectionsIndex); 1553 if (it != invConnections->end()) 1554 { 1555 const std::string& invConnection = *it; 1556 1557 // Response handler for GetManagedObjects 1558 auto respHandler = 1559 [sensorsAsyncResp, inventoryItems, invConnections, objectMgrPaths, 1560 callback{std::forward<Callback>(callback)}, invConnectionsIndex]( 1561 const boost::system::error_code ec, 1562 const dbus::utility::ManagedObjectType& resp) { 1563 BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler enter"; 1564 if (ec) 1565 { 1566 BMCWEB_LOG_ERROR 1567 << "getInventoryItemsData respHandler DBus error " << ec; 1568 messages::internalError(sensorsAsyncResp->asyncResp->res); 1569 return; 1570 } 1571 1572 // Loop through returned object paths 1573 for (const auto& objDictEntry : resp) 1574 { 1575 const std::string& objPath = 1576 static_cast<const std::string&>(objDictEntry.first); 1577 1578 // If this object path is one of the specified inventory items 1579 InventoryItem* inventoryItem = 1580 findInventoryItem(inventoryItems, objPath); 1581 if (inventoryItem != nullptr) 1582 { 1583 // Store inventory data in InventoryItem 1584 storeInventoryItemData(*inventoryItem, objDictEntry.second); 1585 } 1586 } 1587 1588 // Recurse to get inventory item data from next connection 1589 getInventoryItemsData(sensorsAsyncResp, inventoryItems, 1590 invConnections, objectMgrPaths, 1591 std::move(callback), invConnectionsIndex + 1); 1592 1593 BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler exit"; 1594 }; 1595 1596 // Find DBus object path that implements ObjectManager for the current 1597 // connection. If no mapping found, default to "/". 1598 auto iter = objectMgrPaths->find(invConnection); 1599 const std::string& objectMgrPath = 1600 (iter != objectMgrPaths->end()) ? iter->second : "/"; 1601 BMCWEB_LOG_DEBUG << "ObjectManager path for " << invConnection << " is " 1602 << objectMgrPath; 1603 1604 // Get all object paths and their interfaces for current connection 1605 crow::connections::systemBus->async_method_call( 1606 std::move(respHandler), invConnection, objectMgrPath, 1607 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); 1608 } 1609 1610 BMCWEB_LOG_DEBUG << "getInventoryItemsData exit"; 1611 } 1612 1613 /** 1614 * @brief Gets connections that provide D-Bus data for inventory items. 1615 * 1616 * Gets the D-Bus connections (services) that provide data for the inventory 1617 * items that are associated with sensors. 1618 * 1619 * Finds the connections asynchronously. Invokes callback when information has 1620 * been obtained. 1621 * 1622 * The callback must have the following signature: 1623 * @code 1624 * callback(std::shared_ptr<std::set<std::string>> invConnections) 1625 * @endcode 1626 * 1627 * @param sensorsAsyncResp Pointer to object holding response data. 1628 * @param inventoryItems D-Bus inventory items associated with sensors. 1629 * @param callback Callback to invoke when connections have been obtained. 1630 */ 1631 template <typename Callback> 1632 static void getInventoryItemsConnections( 1633 const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp, 1634 const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems, 1635 Callback&& callback) 1636 { 1637 BMCWEB_LOG_DEBUG << "getInventoryItemsConnections enter"; 1638 1639 const std::string path = "/xyz/openbmc_project/inventory"; 1640 const std::array<std::string, 4> interfaces = { 1641 "xyz.openbmc_project.Inventory.Item", 1642 "xyz.openbmc_project.Inventory.Item.PowerSupply", 1643 "xyz.openbmc_project.Inventory.Decorator.Asset", 1644 "xyz.openbmc_project.State.Decorator.OperationalStatus"}; 1645 1646 // Response handler for parsing output from GetSubTree 1647 auto respHandler = 1648 [callback{std::forward<Callback>(callback)}, sensorsAsyncResp, 1649 inventoryItems]( 1650 const boost::system::error_code ec, 1651 const dbus::utility::MapperGetSubTreeResponse& subtree) { 1652 BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler enter"; 1653 if (ec) 1654 { 1655 messages::internalError(sensorsAsyncResp->asyncResp->res); 1656 BMCWEB_LOG_ERROR 1657 << "getInventoryItemsConnections respHandler DBus error " << ec; 1658 return; 1659 } 1660 1661 // Make unique list of connections for desired inventory items 1662 std::shared_ptr<std::set<std::string>> invConnections = 1663 std::make_shared<std::set<std::string>>(); 1664 1665 // Loop through objects from GetSubTree 1666 for (const std::pair< 1667 std::string, 1668 std::vector<std::pair<std::string, std::vector<std::string>>>>& 1669 object : subtree) 1670 { 1671 // Check if object path is one of the specified inventory items 1672 const std::string& objPath = object.first; 1673 if (findInventoryItem(inventoryItems, objPath) != nullptr) 1674 { 1675 // Store all connections to inventory item 1676 for (const std::pair<std::string, std::vector<std::string>>& 1677 objData : object.second) 1678 { 1679 const std::string& invConnection = objData.first; 1680 invConnections->insert(invConnection); 1681 } 1682 } 1683 } 1684 1685 callback(invConnections); 1686 BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler exit"; 1687 }; 1688 1689 // Make call to ObjectMapper to find all inventory items 1690 crow::connections::systemBus->async_method_call( 1691 std::move(respHandler), "xyz.openbmc_project.ObjectMapper", 1692 "/xyz/openbmc_project/object_mapper", 1693 "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 0, interfaces); 1694 BMCWEB_LOG_DEBUG << "getInventoryItemsConnections exit"; 1695 } 1696 1697 /** 1698 * @brief Gets associations from sensors to inventory items. 1699 * 1700 * Looks for ObjectMapper associations from the specified sensors to related 1701 * inventory items. Then finds the associations from those inventory items to 1702 * their LEDs, if any. 1703 * 1704 * Finds the inventory items asynchronously. Invokes callback when information 1705 * has been obtained. 1706 * 1707 * The callback must have the following signature: 1708 * @code 1709 * callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems) 1710 * @endcode 1711 * 1712 * @param sensorsAsyncResp Pointer to object holding response data. 1713 * @param sensorNames All sensors within the current chassis. 1714 * @param objectMgrPaths Mappings from connection name to DBus object path that 1715 * implements ObjectManager. 1716 * @param callback Callback to invoke when inventory items have been obtained. 1717 */ 1718 template <typename Callback> 1719 static void getInventoryItemAssociations( 1720 const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp, 1721 const std::shared_ptr<std::set<std::string>>& sensorNames, 1722 const std::shared_ptr<std::map<std::string, std::string>>& objectMgrPaths, 1723 Callback&& callback) 1724 { 1725 BMCWEB_LOG_DEBUG << "getInventoryItemAssociations enter"; 1726 1727 // Response handler for GetManagedObjects 1728 auto respHandler = 1729 [callback{std::forward<Callback>(callback)}, sensorsAsyncResp, 1730 sensorNames](const boost::system::error_code ec, 1731 const dbus::utility::ManagedObjectType& resp) { 1732 BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler enter"; 1733 if (ec) 1734 { 1735 BMCWEB_LOG_ERROR 1736 << "getInventoryItemAssociations respHandler DBus error " << ec; 1737 messages::internalError(sensorsAsyncResp->asyncResp->res); 1738 return; 1739 } 1740 1741 // Create vector to hold list of inventory items 1742 std::shared_ptr<std::vector<InventoryItem>> inventoryItems = 1743 std::make_shared<std::vector<InventoryItem>>(); 1744 1745 // Loop through returned object paths 1746 std::string sensorAssocPath; 1747 sensorAssocPath.reserve(128); // avoid memory allocations 1748 for (const auto& objDictEntry : resp) 1749 { 1750 const std::string& objPath = 1751 static_cast<const std::string&>(objDictEntry.first); 1752 1753 // If path is inventory association for one of the specified sensors 1754 for (const std::string& sensorName : *sensorNames) 1755 { 1756 sensorAssocPath = sensorName; 1757 sensorAssocPath += "/inventory"; 1758 if (objPath == sensorAssocPath) 1759 { 1760 // Get Association interface for object path 1761 for (const auto& [interface, values] : objDictEntry.second) 1762 { 1763 if (interface == "xyz.openbmc_project.Association") 1764 { 1765 for (const auto& [valueName, value] : values) 1766 { 1767 if (valueName == "endpoints") 1768 { 1769 const std::vector<std::string>* endpoints = 1770 std::get_if<std::vector<std::string>>( 1771 &value); 1772 if ((endpoints != nullptr) && 1773 !endpoints->empty()) 1774 { 1775 // Add inventory item to vector 1776 const std::string& invItemPath = 1777 endpoints->front(); 1778 addInventoryItem(inventoryItems, 1779 invItemPath, 1780 sensorName); 1781 } 1782 } 1783 } 1784 } 1785 } 1786 break; 1787 } 1788 } 1789 } 1790 1791 // Now loop through the returned object paths again, this time to 1792 // find the leds associated with the inventory items we just found 1793 std::string inventoryAssocPath; 1794 inventoryAssocPath.reserve(128); // avoid memory allocations 1795 for (const auto& objDictEntry : resp) 1796 { 1797 const std::string& objPath = 1798 static_cast<const std::string&>(objDictEntry.first); 1799 1800 for (InventoryItem& inventoryItem : *inventoryItems) 1801 { 1802 inventoryAssocPath = inventoryItem.objectPath; 1803 inventoryAssocPath += "/leds"; 1804 if (objPath == inventoryAssocPath) 1805 { 1806 for (const auto& [interface, values] : objDictEntry.second) 1807 { 1808 if (interface == "xyz.openbmc_project.Association") 1809 { 1810 for (const auto& [valueName, value] : values) 1811 { 1812 if (valueName == "endpoints") 1813 { 1814 const std::vector<std::string>* endpoints = 1815 std::get_if<std::vector<std::string>>( 1816 &value); 1817 if ((endpoints != nullptr) && 1818 !endpoints->empty()) 1819 { 1820 // Add inventory item to vector 1821 // Store LED path in inventory item 1822 const std::string& ledPath = 1823 endpoints->front(); 1824 inventoryItem.ledObjectPath = ledPath; 1825 } 1826 } 1827 } 1828 } 1829 } 1830 1831 break; 1832 } 1833 } 1834 } 1835 callback(inventoryItems); 1836 BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler exit"; 1837 }; 1838 1839 // Find DBus object path that implements ObjectManager for ObjectMapper 1840 std::string connection = "xyz.openbmc_project.ObjectMapper"; 1841 auto iter = objectMgrPaths->find(connection); 1842 const std::string& objectMgrPath = 1843 (iter != objectMgrPaths->end()) ? iter->second : "/"; 1844 BMCWEB_LOG_DEBUG << "ObjectManager path for " << connection << " is " 1845 << objectMgrPath; 1846 1847 // Call GetManagedObjects on the ObjectMapper to get all associations 1848 crow::connections::systemBus->async_method_call( 1849 std::move(respHandler), connection, objectMgrPath, 1850 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); 1851 1852 BMCWEB_LOG_DEBUG << "getInventoryItemAssociations exit"; 1853 } 1854 1855 /** 1856 * @brief Gets D-Bus data for inventory item leds associated with sensors. 1857 * 1858 * Uses the specified connections (services) to obtain D-Bus data for inventory 1859 * item leds associated with sensors. Stores the resulting data in the 1860 * inventoryItems vector. 1861 * 1862 * This data is later used to provide sensor property values in the JSON 1863 * response. 1864 * 1865 * Finds the inventory item led data asynchronously. Invokes callback when data 1866 * has been obtained. 1867 * 1868 * The callback must have the following signature: 1869 * @code 1870 * callback() 1871 * @endcode 1872 * 1873 * This function is called recursively, obtaining data asynchronously from one 1874 * connection in each call. This ensures the callback is not invoked until the 1875 * last asynchronous function has completed. 1876 * 1877 * @param sensorsAsyncResp Pointer to object holding response data. 1878 * @param inventoryItems D-Bus inventory items associated with sensors. 1879 * @param ledConnections Connections that provide data for the inventory leds. 1880 * @param callback Callback to invoke when inventory data has been obtained. 1881 * @param ledConnectionsIndex Current index in ledConnections. Only specified 1882 * in recursive calls to this function. 1883 */ 1884 template <typename Callback> 1885 void getInventoryLedData( 1886 std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp, 1887 std::shared_ptr<std::vector<InventoryItem>> inventoryItems, 1888 std::shared_ptr<std::map<std::string, std::string>> ledConnections, 1889 Callback&& callback, size_t ledConnectionsIndex = 0) 1890 { 1891 BMCWEB_LOG_DEBUG << "getInventoryLedData enter"; 1892 1893 // If no more connections left, call callback 1894 if (ledConnectionsIndex >= ledConnections->size()) 1895 { 1896 callback(); 1897 BMCWEB_LOG_DEBUG << "getInventoryLedData exit"; 1898 return; 1899 } 1900 1901 // Get inventory item data from current connection 1902 auto it = ledConnections->begin(); 1903 std::advance(it, ledConnectionsIndex); 1904 if (it != ledConnections->end()) 1905 { 1906 const std::string& ledPath = (*it).first; 1907 const std::string& ledConnection = (*it).second; 1908 // Response handler for Get State property 1909 auto respHandler = 1910 [sensorsAsyncResp, inventoryItems, ledConnections, ledPath, 1911 callback{std::forward<Callback>(callback)}, ledConnectionsIndex]( 1912 const boost::system::error_code ec, const std::string& state) { 1913 BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler enter"; 1914 if (ec) 1915 { 1916 BMCWEB_LOG_ERROR 1917 << "getInventoryLedData respHandler DBus error " << ec; 1918 messages::internalError(sensorsAsyncResp->asyncResp->res); 1919 return; 1920 } 1921 1922 BMCWEB_LOG_DEBUG << "Led state: " << state; 1923 // Find inventory item with this LED object path 1924 InventoryItem* inventoryItem = 1925 findInventoryItemForLed(*inventoryItems, ledPath); 1926 if (inventoryItem != nullptr) 1927 { 1928 // Store LED state in InventoryItem 1929 if (state.ends_with("On")) 1930 { 1931 inventoryItem->ledState = LedState::ON; 1932 } 1933 else if (state.ends_with("Blink")) 1934 { 1935 inventoryItem->ledState = LedState::BLINK; 1936 } 1937 else if (state.ends_with("Off")) 1938 { 1939 inventoryItem->ledState = LedState::OFF; 1940 } 1941 else 1942 { 1943 inventoryItem->ledState = LedState::UNKNOWN; 1944 } 1945 } 1946 1947 // Recurse to get LED data from next connection 1948 getInventoryLedData(sensorsAsyncResp, inventoryItems, 1949 ledConnections, std::move(callback), 1950 ledConnectionsIndex + 1); 1951 1952 BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler exit"; 1953 }; 1954 1955 // Get the State property for the current LED 1956 sdbusplus::asio::getProperty<std::string>( 1957 *crow::connections::systemBus, ledConnection, ledPath, 1958 "xyz.openbmc_project.Led.Physical", "State", 1959 std::move(respHandler)); 1960 } 1961 1962 BMCWEB_LOG_DEBUG << "getInventoryLedData exit"; 1963 } 1964 1965 /** 1966 * @brief Gets LED data for LEDs associated with given inventory items. 1967 * 1968 * Gets the D-Bus connections (services) that provide LED data for the LEDs 1969 * associated with the specified inventory items. Then gets the LED data from 1970 * each connection and stores it in the inventory item. 1971 * 1972 * This data is later used to provide sensor property values in the JSON 1973 * response. 1974 * 1975 * Finds the LED data asynchronously. Invokes callback when information has 1976 * been obtained. 1977 * 1978 * The callback must have the following signature: 1979 * @code 1980 * callback() 1981 * @endcode 1982 * 1983 * @param sensorsAsyncResp Pointer to object holding response data. 1984 * @param inventoryItems D-Bus inventory items associated with sensors. 1985 * @param callback Callback to invoke when inventory items have been obtained. 1986 */ 1987 template <typename Callback> 1988 void getInventoryLeds( 1989 std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp, 1990 std::shared_ptr<std::vector<InventoryItem>> inventoryItems, 1991 Callback&& callback) 1992 { 1993 BMCWEB_LOG_DEBUG << "getInventoryLeds enter"; 1994 1995 const std::string path = "/xyz/openbmc_project"; 1996 const std::array<std::string, 1> interfaces = { 1997 "xyz.openbmc_project.Led.Physical"}; 1998 1999 // Response handler for parsing output from GetSubTree 2000 auto respHandler = 2001 [callback{std::forward<Callback>(callback)}, sensorsAsyncResp, 2002 inventoryItems]( 2003 const boost::system::error_code ec, 2004 const dbus::utility::MapperGetSubTreeResponse& subtree) { 2005 BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler enter"; 2006 if (ec) 2007 { 2008 messages::internalError(sensorsAsyncResp->asyncResp->res); 2009 BMCWEB_LOG_ERROR << "getInventoryLeds respHandler DBus error " 2010 << ec; 2011 return; 2012 } 2013 2014 // Build map of LED object paths to connections 2015 std::shared_ptr<std::map<std::string, std::string>> ledConnections = 2016 std::make_shared<std::map<std::string, std::string>>(); 2017 2018 // Loop through objects from GetSubTree 2019 for (const std::pair< 2020 std::string, 2021 std::vector<std::pair<std::string, std::vector<std::string>>>>& 2022 object : subtree) 2023 { 2024 // Check if object path is LED for one of the specified inventory 2025 // items 2026 const std::string& ledPath = object.first; 2027 if (findInventoryItemForLed(*inventoryItems, ledPath) != nullptr) 2028 { 2029 // Add mapping from ledPath to connection 2030 const std::string& connection = object.second.begin()->first; 2031 (*ledConnections)[ledPath] = connection; 2032 BMCWEB_LOG_DEBUG << "Added mapping " << ledPath << " -> " 2033 << connection; 2034 } 2035 } 2036 2037 getInventoryLedData(sensorsAsyncResp, inventoryItems, ledConnections, 2038 std::move(callback)); 2039 BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler exit"; 2040 }; 2041 // Make call to ObjectMapper to find all inventory items 2042 crow::connections::systemBus->async_method_call( 2043 std::move(respHandler), "xyz.openbmc_project.ObjectMapper", 2044 "/xyz/openbmc_project/object_mapper", 2045 "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 0, interfaces); 2046 BMCWEB_LOG_DEBUG << "getInventoryLeds exit"; 2047 } 2048 2049 /** 2050 * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent 2051 * 2052 * Uses the specified connections (services) (currently assumes just one) to 2053 * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in 2054 * the inventoryItems vector. Only stores data in Power Supply inventoryItems. 2055 * 2056 * This data is later used to provide sensor property values in the JSON 2057 * response. 2058 * 2059 * Finds the Power Supply Attributes data asynchronously. Invokes callback 2060 * when data has been obtained. 2061 * 2062 * The callback must have the following signature: 2063 * @code 2064 * callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems) 2065 * @endcode 2066 * 2067 * @param sensorsAsyncResp Pointer to object holding response data. 2068 * @param inventoryItems D-Bus inventory items associated with sensors. 2069 * @param psAttributesConnections Connections that provide data for the Power 2070 * Supply Attributes 2071 * @param callback Callback to invoke when data has been obtained. 2072 */ 2073 template <typename Callback> 2074 void getPowerSupplyAttributesData( 2075 const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp, 2076 std::shared_ptr<std::vector<InventoryItem>> inventoryItems, 2077 const std::map<std::string, std::string>& psAttributesConnections, 2078 Callback&& callback) 2079 { 2080 BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData enter"; 2081 2082 if (psAttributesConnections.empty()) 2083 { 2084 BMCWEB_LOG_DEBUG << "Can't find PowerSupplyAttributes, no connections!"; 2085 callback(inventoryItems); 2086 return; 2087 } 2088 2089 // Assuming just one connection (service) for now 2090 auto it = psAttributesConnections.begin(); 2091 2092 const std::string& psAttributesPath = (*it).first; 2093 const std::string& psAttributesConnection = (*it).second; 2094 2095 // Response handler for Get DeratingFactor property 2096 auto respHandler = 2097 [sensorsAsyncResp, inventoryItems, 2098 callback{std::forward<Callback>(callback)}]( 2099 const boost::system::error_code ec, const uint32_t value) { 2100 BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler enter"; 2101 if (ec) 2102 { 2103 BMCWEB_LOG_ERROR 2104 << "getPowerSupplyAttributesData respHandler DBus error " << ec; 2105 messages::internalError(sensorsAsyncResp->asyncResp->res); 2106 return; 2107 } 2108 2109 BMCWEB_LOG_DEBUG << "PS EfficiencyPercent value: " << value; 2110 // Store value in Power Supply Inventory Items 2111 for (InventoryItem& inventoryItem : *inventoryItems) 2112 { 2113 if (inventoryItem.isPowerSupply) 2114 { 2115 inventoryItem.powerSupplyEfficiencyPercent = 2116 static_cast<int>(value); 2117 } 2118 } 2119 2120 BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler exit"; 2121 callback(inventoryItems); 2122 }; 2123 2124 // Get the DeratingFactor property for the PowerSupplyAttributes 2125 // Currently only property on the interface/only one we care about 2126 sdbusplus::asio::getProperty<uint32_t>( 2127 *crow::connections::systemBus, psAttributesConnection, psAttributesPath, 2128 "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor", 2129 std::move(respHandler)); 2130 2131 BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData exit"; 2132 } 2133 2134 /** 2135 * @brief Gets the Power Supply Attributes such as EfficiencyPercent 2136 * 2137 * Gets the D-Bus connection (service) that provides Power Supply Attributes 2138 * data. Then gets the Power Supply Attributes data from the connection 2139 * (currently just assumes 1 connection) and stores the data in the inventory 2140 * item. 2141 * 2142 * This data is later used to provide sensor property values in the JSON 2143 * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish. 2144 * 2145 * Finds the Power Supply Attributes data asynchronously. Invokes callback 2146 * when information has been obtained. 2147 * 2148 * The callback must have the following signature: 2149 * @code 2150 * callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems) 2151 * @endcode 2152 * 2153 * @param sensorsAsyncResp Pointer to object holding response data. 2154 * @param inventoryItems D-Bus inventory items associated with sensors. 2155 * @param callback Callback to invoke when data has been obtained. 2156 */ 2157 template <typename Callback> 2158 void getPowerSupplyAttributes( 2159 std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp, 2160 std::shared_ptr<std::vector<InventoryItem>> inventoryItems, 2161 Callback&& callback) 2162 { 2163 BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes enter"; 2164 2165 // Only need the power supply attributes when the Power Schema 2166 if (sensorsAsyncResp->chassisSubNode != sensors::node::power) 2167 { 2168 BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit since not Power"; 2169 callback(inventoryItems); 2170 return; 2171 } 2172 2173 const std::array<std::string, 1> interfaces = { 2174 "xyz.openbmc_project.Control.PowerSupplyAttributes"}; 2175 2176 // Response handler for parsing output from GetSubTree 2177 auto respHandler = 2178 [callback{std::forward<Callback>(callback)}, sensorsAsyncResp, 2179 inventoryItems]( 2180 const boost::system::error_code ec, 2181 const dbus::utility::MapperGetSubTreeResponse& subtree) { 2182 BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler enter"; 2183 if (ec) 2184 { 2185 messages::internalError(sensorsAsyncResp->asyncResp->res); 2186 BMCWEB_LOG_ERROR 2187 << "getPowerSupplyAttributes respHandler DBus error " << ec; 2188 return; 2189 } 2190 if (subtree.empty()) 2191 { 2192 BMCWEB_LOG_DEBUG << "Can't find Power Supply Attributes!"; 2193 callback(inventoryItems); 2194 return; 2195 } 2196 2197 // Currently we only support 1 power supply attribute, use this for 2198 // all the power supplies. Build map of object path to connection. 2199 // Assume just 1 connection and 1 path for now. 2200 std::map<std::string, std::string> psAttributesConnections; 2201 2202 if (subtree[0].first.empty() || subtree[0].second.empty()) 2203 { 2204 BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!"; 2205 callback(inventoryItems); 2206 return; 2207 } 2208 2209 const std::string& psAttributesPath = subtree[0].first; 2210 const std::string& connection = subtree[0].second.begin()->first; 2211 2212 if (connection.empty()) 2213 { 2214 BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!"; 2215 callback(inventoryItems); 2216 return; 2217 } 2218 2219 psAttributesConnections[psAttributesPath] = connection; 2220 BMCWEB_LOG_DEBUG << "Added mapping " << psAttributesPath << " -> " 2221 << connection; 2222 2223 getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems, 2224 psAttributesConnections, 2225 std::move(callback)); 2226 BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler exit"; 2227 }; 2228 // Make call to ObjectMapper to find the PowerSupplyAttributes service 2229 crow::connections::systemBus->async_method_call( 2230 std::move(respHandler), "xyz.openbmc_project.ObjectMapper", 2231 "/xyz/openbmc_project/object_mapper", 2232 "xyz.openbmc_project.ObjectMapper", "GetSubTree", 2233 "/xyz/openbmc_project", 0, interfaces); 2234 BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit"; 2235 } 2236 2237 /** 2238 * @brief Gets inventory items associated with sensors. 2239 * 2240 * Finds the inventory items that are associated with the specified sensors. 2241 * Then gets D-Bus data for the inventory items, such as presence and VPD. 2242 * 2243 * This data is later used to provide sensor property values in the JSON 2244 * response. 2245 * 2246 * Finds the inventory items asynchronously. Invokes callback when the 2247 * inventory items have been obtained. 2248 * 2249 * The callback must have the following signature: 2250 * @code 2251 * callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems) 2252 * @endcode 2253 * 2254 * @param sensorsAsyncResp Pointer to object holding response data. 2255 * @param sensorNames All sensors within the current chassis. 2256 * @param objectMgrPaths Mappings from connection name to DBus object path that 2257 * implements ObjectManager. 2258 * @param callback Callback to invoke when inventory items have been obtained. 2259 */ 2260 template <typename Callback> 2261 static void getInventoryItems( 2262 std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp, 2263 const std::shared_ptr<std::set<std::string>> sensorNames, 2264 std::shared_ptr<std::map<std::string, std::string>> objectMgrPaths, 2265 Callback&& callback) 2266 { 2267 BMCWEB_LOG_DEBUG << "getInventoryItems enter"; 2268 auto getInventoryItemAssociationsCb = 2269 [sensorsAsyncResp, objectMgrPaths, 2270 callback{std::forward<Callback>(callback)}]( 2271 std::shared_ptr<std::vector<InventoryItem>> inventoryItems) { 2272 BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb enter"; 2273 auto getInventoryItemsConnectionsCb = 2274 [sensorsAsyncResp, inventoryItems, objectMgrPaths, 2275 callback{std::forward<const Callback>(callback)}]( 2276 std::shared_ptr<std::set<std::string>> invConnections) { 2277 BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb enter"; 2278 auto getInventoryItemsDataCb = [sensorsAsyncResp, inventoryItems, 2279 callback{std::move(callback)}]() { 2280 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb enter"; 2281 2282 auto getInventoryLedsCb = [sensorsAsyncResp, inventoryItems, 2283 callback{std::move(callback)}]() { 2284 BMCWEB_LOG_DEBUG << "getInventoryLedsCb enter"; 2285 // Find Power Supply Attributes and get the data 2286 getPowerSupplyAttributes(sensorsAsyncResp, inventoryItems, 2287 std::move(callback)); 2288 BMCWEB_LOG_DEBUG << "getInventoryLedsCb exit"; 2289 }; 2290 2291 // Find led connections and get the data 2292 getInventoryLeds(sensorsAsyncResp, inventoryItems, 2293 std::move(getInventoryLedsCb)); 2294 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb exit"; 2295 }; 2296 2297 // Get inventory item data from connections 2298 getInventoryItemsData(sensorsAsyncResp, inventoryItems, 2299 invConnections, objectMgrPaths, 2300 std::move(getInventoryItemsDataCb)); 2301 BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb exit"; 2302 }; 2303 2304 // Get connections that provide inventory item data 2305 getInventoryItemsConnections(sensorsAsyncResp, inventoryItems, 2306 std::move(getInventoryItemsConnectionsCb)); 2307 BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb exit"; 2308 }; 2309 2310 // Get associations from sensors to inventory items 2311 getInventoryItemAssociations(sensorsAsyncResp, sensorNames, objectMgrPaths, 2312 std::move(getInventoryItemAssociationsCb)); 2313 BMCWEB_LOG_DEBUG << "getInventoryItems exit"; 2314 } 2315 2316 /** 2317 * @brief Returns JSON PowerSupply object for the specified inventory item. 2318 * 2319 * Searches for a JSON PowerSupply object that matches the specified inventory 2320 * item. If one is not found, a new PowerSupply object is added to the JSON 2321 * array. 2322 * 2323 * Multiple sensors are often associated with one power supply inventory item. 2324 * As a result, multiple sensor values are stored in one JSON PowerSupply 2325 * object. 2326 * 2327 * @param powerSupplyArray JSON array containing Redfish PowerSupply objects. 2328 * @param inventoryItem Inventory item for the power supply. 2329 * @param chassisId Chassis that contains the power supply. 2330 * @return JSON PowerSupply object for the specified inventory item. 2331 */ 2332 inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray, 2333 const InventoryItem& inventoryItem, 2334 const std::string& chassisId) 2335 { 2336 // Check if matching PowerSupply object already exists in JSON array 2337 for (nlohmann::json& powerSupply : powerSupplyArray) 2338 { 2339 if (powerSupply["MemberId"] == inventoryItem.name) 2340 { 2341 return powerSupply; 2342 } 2343 } 2344 2345 // Add new PowerSupply object to JSON array 2346 powerSupplyArray.push_back({}); 2347 nlohmann::json& powerSupply = powerSupplyArray.back(); 2348 powerSupply["@odata.id"] = 2349 "/redfish/v1/Chassis/" + chassisId + "/Power#/PowerSupplies/"; 2350 powerSupply["MemberId"] = inventoryItem.name; 2351 powerSupply["Name"] = boost::replace_all_copy(inventoryItem.name, "_", " "); 2352 powerSupply["Manufacturer"] = inventoryItem.manufacturer; 2353 powerSupply["Model"] = inventoryItem.model; 2354 powerSupply["PartNumber"] = inventoryItem.partNumber; 2355 powerSupply["SerialNumber"] = inventoryItem.serialNumber; 2356 setLedState(powerSupply, &inventoryItem); 2357 2358 if (inventoryItem.powerSupplyEfficiencyPercent >= 0) 2359 { 2360 powerSupply["EfficiencyPercent"] = 2361 inventoryItem.powerSupplyEfficiencyPercent; 2362 } 2363 2364 powerSupply["Status"]["State"] = getState(&inventoryItem); 2365 const char* health = inventoryItem.isFunctional ? "OK" : "Critical"; 2366 powerSupply["Status"]["Health"] = health; 2367 2368 return powerSupply; 2369 } 2370 2371 /** 2372 * @brief Gets the values of the specified sensors. 2373 * 2374 * Stores the results as JSON in the SensorsAsyncResp. 2375 * 2376 * Gets the sensor values asynchronously. Stores the results later when the 2377 * information has been obtained. 2378 * 2379 * The sensorNames set contains all requested sensors for the current chassis. 2380 * 2381 * To minimize the number of DBus calls, the DBus method 2382 * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the 2383 * values of all sensors provided by a connection (service). 2384 * 2385 * The connections set contains all the connections that provide sensor values. 2386 * 2387 * The objectMgrPaths map contains mappings from a connection name to the 2388 * corresponding DBus object path that implements ObjectManager. 2389 * 2390 * The InventoryItem vector contains D-Bus inventory items associated with the 2391 * sensors. Inventory item data is needed for some Redfish sensor properties. 2392 * 2393 * @param SensorsAsyncResp Pointer to object holding response data. 2394 * @param sensorNames All requested sensors within the current chassis. 2395 * @param connections Connections that provide sensor values. 2396 * @param objectMgrPaths Mappings from connection name to DBus object path that 2397 * implements ObjectManager. 2398 * @param inventoryItems Inventory items associated with the sensors. 2399 */ 2400 inline void getSensorData( 2401 const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp, 2402 const std::shared_ptr<std::set<std::string>>& sensorNames, 2403 const std::set<std::string>& connections, 2404 const std::shared_ptr<std::map<std::string, std::string>>& objectMgrPaths, 2405 const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems) 2406 { 2407 BMCWEB_LOG_DEBUG << "getSensorData enter"; 2408 // Get managed objects from all services exposing sensors 2409 for (const std::string& connection : connections) 2410 { 2411 // Response handler to process managed objects 2412 auto getManagedObjectsCb = 2413 [sensorsAsyncResp, sensorNames, 2414 inventoryItems](const boost::system::error_code ec, 2415 const dbus::utility::ManagedObjectType& resp) { 2416 BMCWEB_LOG_DEBUG << "getManagedObjectsCb enter"; 2417 if (ec) 2418 { 2419 BMCWEB_LOG_ERROR << "getManagedObjectsCb DBUS error: " << ec; 2420 messages::internalError(sensorsAsyncResp->asyncResp->res); 2421 return; 2422 } 2423 // Go through all objects and update response with sensor data 2424 for (const auto& objDictEntry : resp) 2425 { 2426 const std::string& objPath = 2427 static_cast<const std::string&>(objDictEntry.first); 2428 BMCWEB_LOG_DEBUG << "getManagedObjectsCb parsing object " 2429 << objPath; 2430 2431 std::vector<std::string> split; 2432 // Reserve space for 2433 // /xyz/openbmc_project/sensors/<name>/<subname> 2434 split.reserve(6); 2435 boost::algorithm::split(split, objPath, boost::is_any_of("/")); 2436 if (split.size() < 6) 2437 { 2438 BMCWEB_LOG_ERROR << "Got path that isn't long enough " 2439 << objPath; 2440 continue; 2441 } 2442 // These indexes aren't intuitive, as boost::split puts an empty 2443 // string at the beginning 2444 const std::string& sensorType = split[4]; 2445 const std::string& sensorName = split[5]; 2446 BMCWEB_LOG_DEBUG << "sensorName " << sensorName 2447 << " sensorType " << sensorType; 2448 if (sensorNames->find(objPath) == sensorNames->end()) 2449 { 2450 BMCWEB_LOG_DEBUG << sensorName << " not in sensor list "; 2451 continue; 2452 } 2453 2454 // Find inventory item (if any) associated with sensor 2455 InventoryItem* inventoryItem = 2456 findInventoryItemForSensor(inventoryItems, objPath); 2457 2458 const std::string& sensorSchema = 2459 sensorsAsyncResp->chassisSubNode; 2460 2461 nlohmann::json* sensorJson = nullptr; 2462 2463 if (sensorSchema == sensors::node::sensors && 2464 !sensorsAsyncResp->efficientExpand) 2465 { 2466 sensorsAsyncResp->asyncResp->res.jsonValue["@odata.id"] = 2467 "/redfish/v1/Chassis/" + sensorsAsyncResp->chassisId + 2468 "/" + sensorsAsyncResp->chassisSubNode + "/" + 2469 sensorName; 2470 sensorJson = &(sensorsAsyncResp->asyncResp->res.jsonValue); 2471 } 2472 else 2473 { 2474 std::string fieldName; 2475 if (sensorsAsyncResp->efficientExpand) 2476 { 2477 fieldName = "Members"; 2478 } 2479 else if (sensorType == "temperature") 2480 { 2481 fieldName = "Temperatures"; 2482 } 2483 else if (sensorType == "fan" || sensorType == "fan_tach" || 2484 sensorType == "fan_pwm") 2485 { 2486 fieldName = "Fans"; 2487 } 2488 else if (sensorType == "voltage") 2489 { 2490 fieldName = "Voltages"; 2491 } 2492 else if (sensorType == "power") 2493 { 2494 if (sensorName == "total_power") 2495 { 2496 fieldName = "PowerControl"; 2497 } 2498 else if ((inventoryItem != nullptr) && 2499 (inventoryItem->isPowerSupply)) 2500 { 2501 fieldName = "PowerSupplies"; 2502 } 2503 else 2504 { 2505 // Other power sensors are in SensorCollection 2506 continue; 2507 } 2508 } 2509 else 2510 { 2511 BMCWEB_LOG_ERROR << "Unsure how to handle sensorType " 2512 << sensorType; 2513 continue; 2514 } 2515 2516 nlohmann::json& tempArray = 2517 sensorsAsyncResp->asyncResp->res.jsonValue[fieldName]; 2518 if (fieldName == "PowerControl") 2519 { 2520 if (tempArray.empty()) 2521 { 2522 // Put multiple "sensors" into a single 2523 // PowerControl. Follows MemberId naming and 2524 // naming in power.hpp. 2525 nlohmann::json::object_t power; 2526 power["@odata.id"] = 2527 "/redfish/v1/Chassis/" + 2528 sensorsAsyncResp->chassisId + "/" + 2529 sensorsAsyncResp->chassisSubNode + "#/" + 2530 fieldName + "/0"; 2531 tempArray.push_back(std::move(power)); 2532 } 2533 sensorJson = &(tempArray.back()); 2534 } 2535 else if (fieldName == "PowerSupplies") 2536 { 2537 if (inventoryItem != nullptr) 2538 { 2539 sensorJson = 2540 &(getPowerSupply(tempArray, *inventoryItem, 2541 sensorsAsyncResp->chassisId)); 2542 } 2543 } 2544 else if (fieldName == "Members") 2545 { 2546 nlohmann::json::object_t member; 2547 member["@odata.id"] = 2548 "/redfish/v1/Chassis/" + 2549 sensorsAsyncResp->chassisId + "/" + 2550 sensorsAsyncResp->chassisSubNode + "/" + sensorName; 2551 tempArray.push_back(std::move(member)); 2552 sensorJson = &(tempArray.back()); 2553 } 2554 else 2555 { 2556 nlohmann::json::object_t member; 2557 member["@odata.id"] = "/redfish/v1/Chassis/" + 2558 sensorsAsyncResp->chassisId + 2559 "/" + 2560 sensorsAsyncResp->chassisSubNode + 2561 "#/" + fieldName + "/"; 2562 tempArray.push_back(std::move(member)); 2563 sensorJson = &(tempArray.back()); 2564 } 2565 } 2566 2567 if (sensorJson != nullptr) 2568 { 2569 objectInterfacesToJson( 2570 sensorName, sensorType, sensorsAsyncResp, 2571 objDictEntry.second, *sensorJson, inventoryItem); 2572 } 2573 } 2574 if (sensorsAsyncResp.use_count() == 1) 2575 { 2576 sortJSONResponse(sensorsAsyncResp); 2577 if (sensorsAsyncResp->chassisSubNode == 2578 sensors::node::sensors && 2579 sensorsAsyncResp->efficientExpand) 2580 { 2581 sensorsAsyncResp->asyncResp->res 2582 .jsonValue["Members@odata.count"] = 2583 sensorsAsyncResp->asyncResp->res.jsonValue["Members"] 2584 .size(); 2585 } 2586 else if (sensorsAsyncResp->chassisSubNode == 2587 sensors::node::thermal) 2588 { 2589 populateFanRedundancy(sensorsAsyncResp); 2590 } 2591 } 2592 BMCWEB_LOG_DEBUG << "getManagedObjectsCb exit"; 2593 }; 2594 2595 // Find DBus object path that implements ObjectManager for the current 2596 // connection. If no mapping found, default to "/". 2597 auto iter = objectMgrPaths->find(connection); 2598 const std::string& objectMgrPath = 2599 (iter != objectMgrPaths->end()) ? iter->second : "/"; 2600 BMCWEB_LOG_DEBUG << "ObjectManager path for " << connection << " is " 2601 << objectMgrPath; 2602 2603 crow::connections::systemBus->async_method_call( 2604 getManagedObjectsCb, connection, objectMgrPath, 2605 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); 2606 } 2607 BMCWEB_LOG_DEBUG << "getSensorData exit"; 2608 } 2609 2610 inline void 2611 processSensorList(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp, 2612 const std::shared_ptr<std::set<std::string>>& sensorNames) 2613 { 2614 auto getConnectionCb = [sensorsAsyncResp, sensorNames]( 2615 const std::set<std::string>& connections) { 2616 BMCWEB_LOG_DEBUG << "getConnectionCb enter"; 2617 auto getObjectManagerPathsCb = 2618 [sensorsAsyncResp, sensorNames, connections]( 2619 const std::shared_ptr<std::map<std::string, std::string>>& 2620 objectMgrPaths) { 2621 BMCWEB_LOG_DEBUG << "getObjectManagerPathsCb enter"; 2622 auto getInventoryItemsCb = 2623 [sensorsAsyncResp, sensorNames, connections, objectMgrPaths]( 2624 const std::shared_ptr<std::vector<InventoryItem>>& 2625 inventoryItems) { 2626 BMCWEB_LOG_DEBUG << "getInventoryItemsCb enter"; 2627 // Get sensor data and store results in JSON 2628 getSensorData(sensorsAsyncResp, sensorNames, connections, 2629 objectMgrPaths, inventoryItems); 2630 BMCWEB_LOG_DEBUG << "getInventoryItemsCb exit"; 2631 }; 2632 2633 // Get inventory items associated with sensors 2634 getInventoryItems(sensorsAsyncResp, sensorNames, objectMgrPaths, 2635 std::move(getInventoryItemsCb)); 2636 2637 BMCWEB_LOG_DEBUG << "getObjectManagerPathsCb exit"; 2638 }; 2639 2640 // Get mapping from connection names to the DBus object 2641 // paths that implement the ObjectManager interface 2642 getObjectManagerPaths(sensorsAsyncResp, 2643 std::move(getObjectManagerPathsCb)); 2644 BMCWEB_LOG_DEBUG << "getConnectionCb exit"; 2645 }; 2646 2647 // Get set of connections that provide sensor values 2648 getConnections(sensorsAsyncResp, sensorNames, std::move(getConnectionCb)); 2649 } 2650 2651 /** 2652 * @brief Entry point for retrieving sensors data related to requested 2653 * chassis. 2654 * @param SensorsAsyncResp Pointer to object holding response data 2655 */ 2656 inline void 2657 getChassisData(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp) 2658 { 2659 BMCWEB_LOG_DEBUG << "getChassisData enter"; 2660 auto getChassisCb = 2661 [sensorsAsyncResp]( 2662 const std::shared_ptr<std::set<std::string>>& sensorNames) { 2663 BMCWEB_LOG_DEBUG << "getChassisCb enter"; 2664 processSensorList(sensorsAsyncResp, sensorNames); 2665 BMCWEB_LOG_DEBUG << "getChassisCb exit"; 2666 }; 2667 // SensorCollection doesn't contain the Redundancy property 2668 if (sensorsAsyncResp->chassisSubNode != sensors::node::sensors) 2669 { 2670 sensorsAsyncResp->asyncResp->res.jsonValue["Redundancy"] = 2671 nlohmann::json::array(); 2672 } 2673 // Get set of sensors in chassis 2674 getChassis(sensorsAsyncResp, std::move(getChassisCb)); 2675 BMCWEB_LOG_DEBUG << "getChassisData exit"; 2676 } 2677 2678 /** 2679 * @brief Find the requested sensorName in the list of all sensors supplied by 2680 * the chassis node 2681 * 2682 * @param sensorName The sensor name supplied in the PATCH request 2683 * @param sensorsList The list of sensors managed by the chassis node 2684 * @param sensorsModified The list of sensors that were found as a result of 2685 * repeated calls to this function 2686 */ 2687 inline bool 2688 findSensorNameUsingSensorPath(std::string_view sensorName, 2689 const std::set<std::string>& sensorsList, 2690 std::set<std::string>& sensorsModified) 2691 { 2692 for (const auto& chassisSensor : sensorsList) 2693 { 2694 sdbusplus::message::object_path path(chassisSensor); 2695 std::string thisSensorName = path.filename(); 2696 if (thisSensorName.empty()) 2697 { 2698 continue; 2699 } 2700 if (thisSensorName == sensorName) 2701 { 2702 sensorsModified.emplace(chassisSensor); 2703 return true; 2704 } 2705 } 2706 return false; 2707 } 2708 2709 /** 2710 * @brief Entry point for overriding sensor values of given sensor 2711 * 2712 * @param sensorAsyncResp response object 2713 * @param allCollections Collections extract from sensors' request patch info 2714 * @param chassisSubNode Chassis Node for which the query has to happen 2715 */ 2716 inline void setSensorsOverride( 2717 const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp, 2718 std::unordered_map<std::string, std::vector<nlohmann::json>>& 2719 allCollections) 2720 { 2721 BMCWEB_LOG_INFO << "setSensorsOverride for subNode" 2722 << sensorAsyncResp->chassisSubNode << "\n"; 2723 2724 const char* propertyValueName = nullptr; 2725 std::unordered_map<std::string, std::pair<double, std::string>> overrideMap; 2726 std::string memberId; 2727 double value = 0.0; 2728 for (auto& collectionItems : allCollections) 2729 { 2730 if (collectionItems.first == "Temperatures") 2731 { 2732 propertyValueName = "ReadingCelsius"; 2733 } 2734 else if (collectionItems.first == "Fans") 2735 { 2736 propertyValueName = "Reading"; 2737 } 2738 else 2739 { 2740 propertyValueName = "ReadingVolts"; 2741 } 2742 for (auto& item : collectionItems.second) 2743 { 2744 if (!json_util::readJson(item, sensorAsyncResp->asyncResp->res, 2745 "MemberId", memberId, propertyValueName, 2746 value)) 2747 { 2748 return; 2749 } 2750 overrideMap.emplace(memberId, 2751 std::make_pair(value, collectionItems.first)); 2752 } 2753 } 2754 2755 auto getChassisSensorListCb = 2756 [sensorAsyncResp, overrideMap]( 2757 const std::shared_ptr<std::set<std::string>>& sensorsList) { 2758 // Match sensor names in the PATCH request to those managed by the 2759 // chassis node 2760 const std::shared_ptr<std::set<std::string>> sensorNames = 2761 std::make_shared<std::set<std::string>>(); 2762 for (const auto& item : overrideMap) 2763 { 2764 const auto& sensor = item.first; 2765 if (!findSensorNameUsingSensorPath(sensor, *sensorsList, 2766 *sensorNames)) 2767 { 2768 BMCWEB_LOG_INFO << "Unable to find memberId " << item.first; 2769 messages::resourceNotFound(sensorAsyncResp->asyncResp->res, 2770 item.second.second, item.first); 2771 return; 2772 } 2773 } 2774 // Get the connection to which the memberId belongs 2775 auto getObjectsWithConnectionCb = 2776 [sensorAsyncResp, 2777 overrideMap](const std::set<std::string>& /*connections*/, 2778 const std::set<std::pair<std::string, std::string>>& 2779 objectsWithConnection) { 2780 if (objectsWithConnection.size() != overrideMap.size()) 2781 { 2782 BMCWEB_LOG_INFO 2783 << "Unable to find all objects with proper connection " 2784 << objectsWithConnection.size() << " requested " 2785 << overrideMap.size() << "\n"; 2786 messages::resourceNotFound(sensorAsyncResp->asyncResp->res, 2787 sensorAsyncResp->chassisSubNode == 2788 sensors::node::thermal 2789 ? "Temperatures" 2790 : "Voltages", 2791 "Count"); 2792 return; 2793 } 2794 for (const auto& item : objectsWithConnection) 2795 { 2796 sdbusplus::message::object_path path(item.first); 2797 std::string sensorName = path.filename(); 2798 if (sensorName.empty()) 2799 { 2800 messages::internalError(sensorAsyncResp->asyncResp->res); 2801 return; 2802 } 2803 2804 const auto& iterator = overrideMap.find(sensorName); 2805 if (iterator == overrideMap.end()) 2806 { 2807 BMCWEB_LOG_INFO << "Unable to find sensor object" 2808 << item.first << "\n"; 2809 messages::internalError(sensorAsyncResp->asyncResp->res); 2810 return; 2811 } 2812 crow::connections::systemBus->async_method_call( 2813 [sensorAsyncResp](const boost::system::error_code ec) { 2814 if (ec) 2815 { 2816 if (ec.value() == 2817 boost::system::errc::permission_denied) 2818 { 2819 BMCWEB_LOG_WARNING 2820 << "Manufacturing mode is not Enabled...can't " 2821 "Override the sensor value. "; 2822 2823 messages::insufficientPrivilege( 2824 sensorAsyncResp->asyncResp->res); 2825 return; 2826 } 2827 BMCWEB_LOG_DEBUG 2828 << "setOverrideValueStatus DBUS error: " << ec; 2829 messages::internalError( 2830 sensorAsyncResp->asyncResp->res); 2831 } 2832 }, 2833 item.second, item.first, "org.freedesktop.DBus.Properties", 2834 "Set", "xyz.openbmc_project.Sensor.Value", "Value", 2835 dbus::utility::DbusVariantType(iterator->second.first)); 2836 } 2837 }; 2838 // Get object with connection for the given sensor name 2839 getObjectsWithConnection(sensorAsyncResp, sensorNames, 2840 std::move(getObjectsWithConnectionCb)); 2841 }; 2842 // get full sensor list for the given chassisId and cross verify the sensor. 2843 getChassis(sensorAsyncResp, std::move(getChassisSensorListCb)); 2844 } 2845 2846 /** 2847 * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus 2848 * path of the sensor. 2849 * 2850 * Function builds valid Redfish response for sensor query of given chassis and 2851 * node. It then builds metadata about Redfish<->D-Bus correlations and provides 2852 * it to caller in a callback. 2853 * 2854 * @param chassis Chassis for which retrieval should be performed 2855 * @param node Node (group) of sensors. See sensors::node for supported values 2856 * @param mapComplete Callback to be called with retrieval result 2857 */ 2858 inline void retrieveUriToDbusMap(const std::string& chassis, 2859 const std::string& node, 2860 SensorsAsyncResp::DataCompleteCb&& mapComplete) 2861 { 2862 decltype(sensors::paths)::const_iterator pathIt = 2863 std::find_if(sensors::paths.cbegin(), sensors::paths.cend(), 2864 [&node](auto&& val) { return val.first == node; }); 2865 if (pathIt == sensors::paths.cend()) 2866 { 2867 BMCWEB_LOG_ERROR << "Wrong node provided : " << node; 2868 mapComplete(boost::beast::http::status::bad_request, {}); 2869 return; 2870 } 2871 2872 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(); 2873 auto callback = [asyncResp, mapCompleteCb{std::move(mapComplete)}]( 2874 const boost::beast::http::status status, 2875 const std::map<std::string, std::string>& uriToDbus) { 2876 mapCompleteCb(status, uriToDbus); 2877 }; 2878 2879 auto resp = std::make_shared<SensorsAsyncResp>( 2880 asyncResp, chassis, pathIt->second, node, std::move(callback)); 2881 getChassisData(resp); 2882 } 2883 2884 namespace sensors 2885 { 2886 2887 inline void getChassisCallback( 2888 const std::shared_ptr<SensorsAsyncResp>& asyncResp, 2889 const std::shared_ptr<std::set<std::string>>& sensorNames) 2890 { 2891 BMCWEB_LOG_DEBUG << "getChassisCallback enter"; 2892 2893 nlohmann::json& entriesArray = 2894 asyncResp->asyncResp->res.jsonValue["Members"]; 2895 for (const auto& sensor : *sensorNames) 2896 { 2897 BMCWEB_LOG_DEBUG << "Adding sensor: " << sensor; 2898 2899 sdbusplus::message::object_path path(sensor); 2900 std::string sensorName = path.filename(); 2901 if (sensorName.empty()) 2902 { 2903 BMCWEB_LOG_ERROR << "Invalid sensor path: " << sensor; 2904 messages::internalError(asyncResp->asyncResp->res); 2905 return; 2906 } 2907 nlohmann::json::object_t member; 2908 member["@odata.id"] = "/redfish/v1/Chassis/" + asyncResp->chassisId + 2909 "/" + asyncResp->chassisSubNode + "/" + 2910 sensorName; 2911 entriesArray.push_back(std::move(member)); 2912 } 2913 2914 asyncResp->asyncResp->res.jsonValue["Members@odata.count"] = 2915 entriesArray.size(); 2916 BMCWEB_LOG_DEBUG << "getChassisCallback exit"; 2917 } 2918 2919 inline void 2920 handleSensorCollectionGet(App& app, const crow::Request& req, 2921 const std::shared_ptr<bmcweb::AsyncResp>& aResp, 2922 const std::string& chassisId) 2923 { 2924 query_param::QueryCapabilities capabilities = { 2925 .canDelegateExpandLevel = 1, 2926 }; 2927 query_param::Query delegatedQuery; 2928 if (!redfish::setUpRedfishRouteWithDelegation(app, req, aResp, 2929 delegatedQuery, capabilities)) 2930 { 2931 return; 2932 } 2933 2934 if (delegatedQuery.expandType != query_param::ExpandType::None) 2935 { 2936 // we perform efficient expand. 2937 auto asyncResp = std::make_shared<SensorsAsyncResp>( 2938 aResp, chassisId, sensors::dbus::sensorPaths, 2939 sensors::node::sensors, 2940 /*efficientExpand=*/true); 2941 getChassisData(asyncResp); 2942 2943 BMCWEB_LOG_DEBUG 2944 << "SensorCollection doGet exit via efficient expand handler"; 2945 return; 2946 } 2947 2948 // if there's no efficient expand available, we use the default 2949 // Query Parameters route 2950 auto asyncResp = std::make_shared<SensorsAsyncResp>( 2951 aResp, chassisId, sensors::dbus::sensorPaths, sensors::node::sensors); 2952 2953 // We get all sensors as hyperlinkes in the chassis (this 2954 // implies we reply on the default query parameters handler) 2955 getChassis(asyncResp, 2956 std::bind_front(sensors::getChassisCallback, asyncResp)); 2957 BMCWEB_LOG_DEBUG << "SensorCollection doGet exit"; 2958 } 2959 2960 inline void handleSensorGet(App& app, const crow::Request& req, 2961 const std::shared_ptr<bmcweb::AsyncResp>& aResp, 2962 const std::string& chassisId, 2963 const std::string& sensorName) 2964 { 2965 if (!redfish::setUpRedfishRoute(app, req, aResp)) 2966 { 2967 return; 2968 } 2969 BMCWEB_LOG_DEBUG << "Sensor doGet enter"; 2970 std::shared_ptr<SensorsAsyncResp> asyncResp = 2971 std::make_shared<SensorsAsyncResp>(aResp, chassisId, 2972 std::span<std::string_view>(), 2973 sensors::node::sensors); 2974 2975 const std::array<const char*, 1> interfaces = { 2976 "xyz.openbmc_project.Sensor.Value"}; 2977 2978 // Get a list of all of the sensors that implement Sensor.Value 2979 // and get the path and service name associated with the sensor 2980 crow::connections::systemBus->async_method_call( 2981 [asyncResp, 2982 sensorName](const boost::system::error_code ec, 2983 const ::dbus::utility::MapperGetSubTreeResponse& subtree) { 2984 BMCWEB_LOG_DEBUG << "respHandler1 enter"; 2985 if (ec) 2986 { 2987 messages::internalError(asyncResp->asyncResp->res); 2988 BMCWEB_LOG_ERROR << "Sensor getSensorPaths resp_handler: " 2989 << "Dbus error " << ec; 2990 return; 2991 } 2992 2993 ::dbus::utility::MapperGetSubTreeResponse::const_iterator it = 2994 std::find_if( 2995 subtree.begin(), subtree.end(), 2996 [sensorName]( 2997 const std::pair< 2998 std::string, 2999 std::vector<std::pair< 3000 std::string, std::vector<std::string>>>>& object) { 3001 sdbusplus::message::object_path path(object.first); 3002 std::string name = path.filename(); 3003 if (name.empty()) 3004 { 3005 BMCWEB_LOG_ERROR << "Invalid sensor path: " << object.first; 3006 return false; 3007 } 3008 3009 return name == sensorName; 3010 }); 3011 3012 if (it == subtree.end()) 3013 { 3014 BMCWEB_LOG_ERROR << "Could not find path for sensor: " 3015 << sensorName; 3016 messages::resourceNotFound(asyncResp->asyncResp->res, "Sensor", 3017 sensorName); 3018 return; 3019 } 3020 std::string_view sensorPath = (*it).first; 3021 BMCWEB_LOG_DEBUG << "Found sensor path for sensor '" << sensorName 3022 << "': " << sensorPath; 3023 3024 const std::shared_ptr<std::set<std::string>> sensorList = 3025 std::make_shared<std::set<std::string>>(); 3026 3027 sensorList->emplace(sensorPath); 3028 processSensorList(asyncResp, sensorList); 3029 BMCWEB_LOG_DEBUG << "respHandler1 exit"; 3030 }, 3031 "xyz.openbmc_project.ObjectMapper", 3032 "/xyz/openbmc_project/object_mapper", 3033 "xyz.openbmc_project.ObjectMapper", "GetSubTree", 3034 "/xyz/openbmc_project/sensors", 2, interfaces); 3035 } 3036 3037 } // namespace sensors 3038 3039 inline void requestRoutesSensorCollection(App& app) 3040 { 3041 BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/") 3042 .privileges(redfish::privileges::getSensorCollection) 3043 .methods(boost::beast::http::verb::get)( 3044 std::bind_front(sensors::handleSensorCollectionGet, std::ref(app))); 3045 } 3046 3047 inline void requestRoutesSensor(App& app) 3048 { 3049 BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/") 3050 .privileges(redfish::privileges::getSensor) 3051 .methods(boost::beast::http::verb::get)( 3052 std::bind_front(sensors::handleSensorGet, std::ref(app))); 3053 } 3054 3055 } // namespace redfish 3056