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 <math.h> 19 #include <dbus_singleton.hpp> 20 #include <boost/algorithm/string/predicate.hpp> 21 #include <boost/algorithm/string/split.hpp> 22 #include <boost/container/flat_map.hpp> 23 #include <boost/range/algorithm/replace_copy_if.hpp> 24 25 namespace redfish { 26 27 constexpr const char* DBUS_SENSOR_PREFIX = "/xyz/openbmc_project/Sensors/"; 28 29 using GetSubTreeType = std::vector< 30 std::pair<std::string, 31 std::vector<std::pair<std::string, std::vector<std::string>>>>>; 32 33 using SensorVariant = sdbusplus::message::variant<int64_t, double>; 34 35 using ManagedObjectsVectorType = std::vector<std::pair< 36 sdbusplus::message::object_path, 37 boost::container::flat_map< 38 std::string, boost::container::flat_map<std::string, SensorVariant>>>>; 39 40 /** 41 * SensorsAsyncResp 42 * Gathers data needed for response processing after async calls are done 43 */ 44 class SensorsAsyncResp { 45 public: 46 SensorsAsyncResp(crow::response& response, const std::string& chassisId, 47 const std::initializer_list<const char*> types) 48 : res(response), chassisId(chassisId), types(types) { 49 res.json_value["@odata.id"] = 50 "/redfish/v1/Chassis/" + chassisId + "/Thermal"; 51 } 52 53 ~SensorsAsyncResp() { 54 if (res.result() == boost::beast::http::status::internal_server_error) { 55 // Reset the json object to clear out any data that made it in before the 56 // error happened 57 // todo(ed) handle error condition with proper code 58 res.json_value = nlohmann::json::object(); 59 } 60 res.end(); 61 } 62 63 void setErrorStatus() { 64 res.result(boost::beast::http::status::internal_server_error); 65 } 66 67 crow::response& res; 68 std::string chassisId{}; 69 const std::vector<const char*> types; 70 }; 71 72 /** 73 * @brief Creates connections necessary for chassis sensors 74 * @param SensorsAsyncResp Pointer to object holding response data 75 * @param sensorNames Sensors retrieved from chassis 76 * @param callback Callback for processing gathered connections 77 */ 78 template <typename Callback> 79 void getConnections(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp, 80 const boost::container::flat_set<std::string>& sensorNames, 81 Callback&& callback) { 82 CROW_LOG_DEBUG << "getConnections enter"; 83 const std::string path = "/xyz/openbmc_project/Sensors"; 84 const std::array<std::string, 1> interfaces = { 85 "xyz.openbmc_project.Sensor.Value"}; 86 87 // Response handler for parsing objects subtree 88 auto resp_handler = 89 [ callback{std::move(callback)}, SensorsAsyncResp, sensorNames ]( 90 const boost::system::error_code ec, const GetSubTreeType& subtree) { 91 CROW_LOG_DEBUG << "getConnections resp_handler enter"; 92 if (ec) { 93 SensorsAsyncResp->setErrorStatus(); 94 CROW_LOG_ERROR << "getConnections resp_handler: Dbus error " << ec; 95 return; 96 } 97 98 CROW_LOG_DEBUG << "Found " << subtree.size() << " subtrees"; 99 100 // Make unique list of connections only for requested sensor types and 101 // found in the chassis 102 boost::container::flat_set<std::string> connections; 103 // Intrinsic to avoid malloc. Most systems will have < 8 sensor producers 104 connections.reserve(8); 105 106 CROW_LOG_DEBUG << "sensorNames list count: " << sensorNames.size(); 107 for (const std::string& tsensor : sensorNames) { 108 CROW_LOG_DEBUG << "Sensor to find: " << tsensor; 109 } 110 111 for (const std::pair< 112 std::string, 113 std::vector<std::pair<std::string, std::vector<std::string>>>>& 114 object : subtree) { 115 for (const char* type : SensorsAsyncResp->types) { 116 if (boost::starts_with(object.first, type)) { 117 auto lastPos = object.first.rfind('/'); 118 if (lastPos != std::string::npos) { 119 std::string sensorName = object.first.substr(lastPos + 1); 120 121 if (sensorNames.find(sensorName) != sensorNames.end()) { 122 // For each connection name 123 for (const std::pair<std::string, std::vector<std::string>>& 124 objData : object.second) { 125 CROW_LOG_DEBUG << "Adding connection: " << objData.first; 126 connections.insert(objData.first); 127 } 128 } 129 } 130 break; 131 } 132 } 133 } 134 CROW_LOG_DEBUG << "Found " << connections.size() << " connections"; 135 callback(std::move(connections)); 136 CROW_LOG_DEBUG << "getConnections resp_handler exit"; 137 }; 138 139 // Make call to ObjectMapper to find all sensors objects 140 crow::connections::system_bus->async_method_call( 141 std::move(resp_handler), "xyz.openbmc_project.ObjectMapper", 142 "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", 143 "GetSubTree", path, 2, interfaces); 144 CROW_LOG_DEBUG << "getConnections exit"; 145 } 146 147 /** 148 * @brief Retrieves requested chassis sensors and redundancy data from DBus . 149 * @param SensorsAsyncResp Pointer to object holding response data 150 * @param callback Callback for next step in gathered sensor processing 151 */ 152 template <typename Callback> 153 void getChassis(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp, 154 Callback&& callback) { 155 CROW_LOG_DEBUG << "getChassis enter"; 156 // Process response from EntityManager and extract chassis data 157 auto resp_handler = [ callback{std::move(callback)}, SensorsAsyncResp ]( 158 const boost::system::error_code ec, ManagedObjectsVectorType& resp) { 159 CROW_LOG_DEBUG << "getChassis resp_handler enter"; 160 if (ec) { 161 CROW_LOG_ERROR << "getChassis resp_handler DBUS error: " << ec; 162 SensorsAsyncResp->setErrorStatus(); 163 return; 164 } 165 boost::container::flat_set<std::string> sensorNames; 166 167 // SensorsAsyncResp->chassisId 168 bool foundChassis = false; 169 std::vector<std::string> split; 170 // Reserve space for 171 // /xyz/openbmc_project/inventory/<name>/<subname> + 3 subnames 172 split.reserve(8); 173 174 for (const auto& objDictEntry : resp) { 175 const std::string& objectPath = 176 static_cast<const std::string&>(objDictEntry.first); 177 boost::algorithm::split(split, objectPath, boost::is_any_of("/")); 178 if (split.size() < 2) { 179 CROW_LOG_ERROR << "Got path that isn't long enough " << objectPath; 180 split.clear(); 181 continue; 182 } 183 const std::string& sensorName = split.end()[-1]; 184 const std::string& chassisName = split.end()[-2]; 185 186 if (chassisName != SensorsAsyncResp->chassisId) { 187 split.clear(); 188 continue; 189 } 190 CROW_LOG_DEBUG << "New sensor: " << sensorName; 191 foundChassis = true; 192 sensorNames.emplace(sensorName); 193 split.clear(); 194 }; 195 CROW_LOG_DEBUG << "Found " << sensorNames.size() << " Sensor names"; 196 197 if (!foundChassis) { 198 CROW_LOG_INFO << "Unable to find chassis named " 199 << SensorsAsyncResp->chassisId; 200 SensorsAsyncResp->res.result(boost::beast::http::status::not_found); 201 } else { 202 callback(sensorNames); 203 } 204 CROW_LOG_DEBUG << "getChassis resp_handler exit"; 205 }; 206 207 // Make call to EntityManager to find all chassis objects 208 crow::connections::system_bus->async_method_call( 209 resp_handler, "xyz.openbmc_project.EntityManager", "/", 210 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); 211 CROW_LOG_DEBUG << "getChassis exit"; 212 } 213 214 /** 215 * @brief Builds a json sensor representation of a sensor. 216 * @param sensorName The name of the sensor to be built 217 * @param sensorType The type (temperature, fan_tach, etc) of the sensor to 218 * build 219 * @param interfacesDict A dictionary of the interfaces and properties of said 220 * interfaces to be built from 221 * @param sensor_json The json object to fill 222 */ 223 void objectInterfacesToJson( 224 const std::string& sensorName, const std::string& sensorType, 225 const boost::container::flat_map< 226 std::string, boost::container::flat_map<std::string, SensorVariant>>& 227 interfacesDict, 228 nlohmann::json& sensor_json) { 229 // We need a value interface before we can do anything with it 230 auto value_it = interfacesDict.find("xyz.openbmc_project.Sensor.Value"); 231 if (value_it == interfacesDict.end()) { 232 CROW_LOG_ERROR << "Sensor doesn't have a value interface"; 233 return; 234 } 235 236 // Assume values exist as is (10^0 == 1) if no scale exists 237 int64_t scaleMultiplier = 0; 238 239 auto scale_it = value_it->second.find("Scale"); 240 // If a scale exists, pull value as int64, and use the scaling. 241 if (scale_it != value_it->second.end()) { 242 const int64_t* int64Value = 243 mapbox::get_ptr<const int64_t>(scale_it->second); 244 if (int64Value != nullptr) { 245 scaleMultiplier = *int64Value; 246 } 247 } 248 249 sensor_json["MemberId"] = sensorName; 250 sensor_json["Name"] = sensorName; 251 sensor_json["Status"]["State"] = "Enabled"; 252 sensor_json["Status"]["Health"] = "OK"; 253 254 // Parameter to set to override the type we get from dbus, and force it to 255 // int, regardless of what is available. This is used for schemas like fan, 256 // that require integers, not floats. 257 bool forceToInt = false; 258 259 const char* unit = "Reading"; 260 if (sensorType == "temperature") { 261 unit = "ReadingCelsius"; 262 sensor_json["@odata.type"] = "#Thermal.v1_3_0.Temperature"; 263 // TODO(ed) Documentation says that path should be type fan_tach, 264 // implementation seems to implement fan 265 } else if (sensorType == "fan" || sensorType == "fan_type") { 266 unit = "Reading"; 267 sensor_json["ReadingUnits"] = "RPM"; 268 sensor_json["@odata.type"] = "#Thermal.v1_3_0.Fan"; 269 forceToInt = true; 270 } else if (sensorType == "voltage") { 271 unit = "ReadingVolts"; 272 sensor_json["@odata.type"] = "#Power.v1_0_0.Voltage"; 273 } else { 274 CROW_LOG_ERROR << "Redfish cannot map object type for " << sensorName; 275 return; 276 } 277 // Map of dbus interface name, dbus property name and redfish property_name 278 std::vector<std::tuple<const char*, const char*, const char*>> properties; 279 properties.reserve(7); 280 281 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit); 282 properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning", 283 "WarningHigh", "UpperThresholdNonCritical"); 284 properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning", 285 "WarningLow", "LowerThresholdNonCritical"); 286 properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical", 287 "CriticalHigh", "UpperThresholdCritical"); 288 properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical", 289 "CriticalLow", "LowerThresholdCritical"); 290 291 if (sensorType == "temperature") { 292 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue", 293 "MinReadingRangeTemp"); 294 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue", 295 "MaxReadingRangeTemp"); 296 } else { 297 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue", 298 "MinReadingRange"); 299 properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue", 300 "MaxReadingRange"); 301 } 302 303 for (const std::tuple<const char*, const char*, const char*>& p : 304 properties) { 305 auto interfaceProperties = interfacesDict.find(std::get<0>(p)); 306 if (interfaceProperties != interfacesDict.end()) { 307 auto value_it = interfaceProperties->second.find(std::get<1>(p)); 308 if (value_it != interfaceProperties->second.end()) { 309 const SensorVariant& valueVariant = value_it->second; 310 nlohmann::json& value_it = sensor_json[std::get<2>(p)]; 311 312 // Attempt to pull the int64 directly 313 const int64_t* int64Value = 314 mapbox::get_ptr<const int64_t>(valueVariant); 315 316 if (int64Value != nullptr) { 317 if (forceToInt || scaleMultiplier >= 0) { 318 value_it = *int64Value * std::pow(10, scaleMultiplier); 319 } else { 320 value_it = *int64Value * 321 std::pow(10, static_cast<double>(scaleMultiplier)); 322 } 323 } 324 // Attempt to pull the float directly 325 const double* doubleValue = mapbox::get_ptr<const double>(valueVariant); 326 327 if (doubleValue != nullptr) { 328 if (!forceToInt) { 329 value_it = *doubleValue * 330 std::pow(10, static_cast<double>(scaleMultiplier)); 331 } else { 332 value_it = static_cast<int64_t>(*doubleValue * 333 std::pow(10, scaleMultiplier)); 334 } 335 } 336 } 337 } 338 } 339 CROW_LOG_DEBUG << "Added sensor " << sensorName; 340 } 341 342 /** 343 * @brief Entry point for retrieving sensors data related to requested 344 * chassis. 345 * @param SensorsAsyncResp Pointer to object holding response data 346 */ 347 void getChassisData(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp) { 348 CROW_LOG_DEBUG << "getChassisData enter"; 349 auto getChassisCb = [&, SensorsAsyncResp]( 350 boost::container::flat_set<std::string>& 351 sensorNames) { 352 CROW_LOG_DEBUG << "getChassisCb enter"; 353 auto getConnectionCb = 354 [&, SensorsAsyncResp, sensorNames]( 355 const boost::container::flat_set<std::string>& connections) { 356 CROW_LOG_DEBUG << "getConnectionCb enter"; 357 // Get managed objects from all services exposing sensors 358 for (const std::string& connection : connections) { 359 // Response handler to process managed objects 360 auto getManagedObjectsCb = [&, SensorsAsyncResp, sensorNames]( 361 const boost::system::error_code ec, 362 ManagedObjectsVectorType& resp) { 363 CROW_LOG_DEBUG << "getManagedObjectsCb enter"; 364 if (ec) { 365 CROW_LOG_ERROR << "getManagedObjectsCb DBUS error: " << ec; 366 SensorsAsyncResp->setErrorStatus(); 367 return; 368 } 369 // Go through all objects and update response with 370 // sensor data 371 for (const auto& objDictEntry : resp) { 372 const std::string& objPath = 373 static_cast<const std::string&>(objDictEntry.first); 374 CROW_LOG_DEBUG << "getManagedObjectsCb parsing object " 375 << objPath; 376 377 std::vector<std::string> split; 378 // Reserve space for 379 // /xyz/openbmc_project/Sensors/<name>/<subname> 380 split.reserve(6); 381 boost::algorithm::split(split, objPath, boost::is_any_of("/")); 382 if (split.size() < 6) { 383 CROW_LOG_ERROR << "Got path that isn't long enough " 384 << objPath; 385 continue; 386 } 387 // These indexes aren't intuitive, as boost::split puts an empty 388 // string at the beggining 389 const std::string& sensorType = split[4]; 390 const std::string& sensorName = split[5]; 391 CROW_LOG_DEBUG << "sensorName " << sensorName << " sensorType " 392 << sensorType; 393 if (sensorNames.find(sensorName) == sensorNames.end()) { 394 CROW_LOG_ERROR << sensorName << " not in sensor list "; 395 continue; 396 } 397 398 const char* fieldName = nullptr; 399 if (sensorType == "temperature") { 400 fieldName = "Temperatures"; 401 } else if (sensorType == "fan" || sensorType == "fan_tach") { 402 fieldName = "Fans"; 403 } else if (sensorType == "voltage") { 404 fieldName = "Voltages"; 405 } else if (sensorType == "current") { 406 fieldName = "PowerSupply"; 407 } else if (sensorType == "power") { 408 fieldName = "PowerSupply"; 409 } else { 410 CROW_LOG_ERROR << "Unsure how to handle sensorType " 411 << sensorType; 412 continue; 413 } 414 415 nlohmann::json& temp_array = 416 SensorsAsyncResp->res.json_value[fieldName]; 417 418 // Create the array if it doesn't yet exist 419 if (temp_array.is_array() == false) { 420 temp_array = nlohmann::json::array(); 421 } 422 423 temp_array.push_back( 424 {{"@odata.id", "/redfish/v1/Chassis/" + 425 SensorsAsyncResp->chassisId + 426 "/Thermal#/" + sensorName}}); 427 nlohmann::json& sensor_json = temp_array.back(); 428 objectInterfacesToJson(sensorName, sensorType, 429 objDictEntry.second, sensor_json); 430 } 431 CROW_LOG_DEBUG << "getManagedObjectsCb exit"; 432 }; 433 crow::connections::system_bus->async_method_call( 434 getManagedObjectsCb, connection, "/", 435 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); 436 }; 437 CROW_LOG_DEBUG << "getConnectionCb exit"; 438 }; 439 // Get connections and then pass it to get sensors 440 getConnections(SensorsAsyncResp, sensorNames, std::move(getConnectionCb)); 441 CROW_LOG_DEBUG << "getChassisCb exit"; 442 }; 443 444 // Get chassis information related to sensors 445 getChassis(SensorsAsyncResp, std::move(getChassisCb)); 446 CROW_LOG_DEBUG << "getChassisData exit"; 447 }; 448 449 } // namespace redfish 450