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