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