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