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