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