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