1 #pragma once 2 3 #include "VariantVisitors.hpp" 4 5 #include <boost/algorithm/string/replace.hpp> 6 #include <boost/asio/steady_timer.hpp> 7 #include <boost/container/flat_map.hpp> 8 #include <sdbusplus/asio/connection.hpp> 9 #include <sdbusplus/asio/object_server.hpp> 10 #include <sdbusplus/message/types.hpp> 11 12 #include <filesystem> 13 #include <functional> 14 #include <iostream> 15 #include <memory> 16 #include <optional> 17 #include <regex> 18 #include <span> 19 #include <string> 20 #include <tuple> 21 #include <utility> 22 #include <variant> 23 #include <vector> 24 25 const constexpr char* jsonStore = "/var/configuration/flattened.json"; 26 const constexpr char* inventoryPath = "/xyz/openbmc_project/inventory"; 27 const constexpr char* entityManagerName = "xyz.openbmc_project.EntityManager"; 28 29 constexpr const char* cpuInventoryPath = 30 "/xyz/openbmc_project/inventory/system/chassis/motherboard"; 31 const std::regex illegalDbusRegex("[^A-Za-z0-9_]"); 32 33 using BasicVariantType = 34 std::variant<std::vector<std::string>, std::string, int64_t, uint64_t, 35 double, int32_t, uint32_t, int16_t, uint16_t, uint8_t, bool>; 36 using SensorBaseConfigMap = 37 boost::container::flat_map<std::string, BasicVariantType>; 38 using SensorBaseConfiguration = std::pair<std::string, SensorBaseConfigMap>; 39 using SensorData = boost::container::flat_map<std::string, SensorBaseConfigMap>; 40 using ManagedObjectType = 41 boost::container::flat_map<sdbusplus::message::object_path, SensorData>; 42 43 using GetSubTreeType = std::vector< 44 std::pair<std::string, 45 std::vector<std::pair<std::string, std::vector<std::string>>>>>; 46 using Association = std::tuple<std::string, std::string, std::string>; 47 48 inline std::string escapeName(const std::string& sensorName) 49 { 50 return boost::replace_all_copy(sensorName, " ", "_"); 51 } 52 53 enum class PowerState 54 { 55 on, 56 biosPost, 57 always, 58 chassisOn 59 }; 60 61 std::optional<std::string> openAndRead(const std::string& hwmonFile); 62 std::optional<std::string> 63 getFullHwmonFilePath(const std::string& directory, 64 const std::string& hwmonBaseName, 65 const std::set<std::string>& permitSet); 66 std::set<std::string> getPermitSet(const SensorBaseConfigMap& config); 67 bool findFiles(const std::filesystem::path& dirPath, 68 std::string_view matchString, 69 std::vector<std::filesystem::path>& foundPaths, 70 int symlinkDepth = 1); 71 bool isPowerOn(void); 72 bool hasBiosPost(void); 73 bool isChassisOn(void); 74 void setupPowerMatchCallback( 75 const std::shared_ptr<sdbusplus::asio::connection>& conn, 76 std::function<void(PowerState type, bool state)>&& callback); 77 void setupPowerMatch(const std::shared_ptr<sdbusplus::asio::connection>& conn); 78 bool getSensorConfiguration( 79 const std::string& type, 80 const std::shared_ptr<sdbusplus::asio::connection>& dbusConnection, 81 ManagedObjectType& resp, bool useCache); 82 83 bool getSensorConfiguration( 84 const std::string& type, 85 const std::shared_ptr<sdbusplus::asio::connection>& dbusConnection, 86 ManagedObjectType& resp); 87 88 void createAssociation( 89 std::shared_ptr<sdbusplus::asio::dbus_interface>& association, 90 const std::string& path); 91 92 // replaces limits if MinReading and MaxReading are found. 93 void findLimits(std::pair<double, double>& limits, 94 const SensorBaseConfiguration* data); 95 96 bool readingStateGood(const PowerState& powerState); 97 98 constexpr const char* configInterfacePrefix = 99 "xyz.openbmc_project.Configuration."; 100 101 inline std::string configInterfaceName(const std::string& type) 102 { 103 return std::string(configInterfacePrefix) + type; 104 } 105 106 namespace mapper 107 { 108 constexpr const char* busName = "xyz.openbmc_project.ObjectMapper"; 109 constexpr const char* path = "/xyz/openbmc_project/object_mapper"; 110 constexpr const char* interface = "xyz.openbmc_project.ObjectMapper"; 111 constexpr const char* subtree = "GetSubTree"; 112 } // namespace mapper 113 114 namespace properties 115 { 116 constexpr const char* interface = "org.freedesktop.DBus.Properties"; 117 constexpr const char* get = "Get"; 118 constexpr const char* set = "Set"; 119 } // namespace properties 120 121 namespace power 122 { 123 const static constexpr char* busname = "xyz.openbmc_project.State.Host"; 124 const static constexpr char* interface = "xyz.openbmc_project.State.Host"; 125 const static constexpr char* path = "/xyz/openbmc_project/state/host0"; 126 const static constexpr char* property = "CurrentHostState"; 127 } // namespace power 128 129 namespace chassis 130 { 131 const static constexpr char* busname = "xyz.openbmc_project.State.Chassis"; 132 const static constexpr char* interface = "xyz.openbmc_project.State.Chassis"; 133 const static constexpr char* path = "/xyz/openbmc_project/state/chassis0"; 134 const static constexpr char* property = "CurrentPowerState"; 135 const static constexpr char* sOn = ".On"; 136 } // namespace chassis 137 138 namespace post 139 { 140 const static constexpr char* busname = 141 "xyz.openbmc_project.State.OperatingSystem"; 142 const static constexpr char* interface = 143 "xyz.openbmc_project.State.OperatingSystem.Status"; 144 const static constexpr char* path = "/xyz/openbmc_project/state/os"; 145 const static constexpr char* property = "OperatingSystemState"; 146 } // namespace post 147 148 namespace association 149 { 150 const static constexpr char* interface = 151 "xyz.openbmc_project.Association.Definitions"; 152 } // namespace association 153 154 template <typename T> 155 inline T loadVariant(const SensorBaseConfigMap& data, const std::string& key) 156 { 157 auto it = data.find(key); 158 if (it == data.end()) 159 { 160 std::cerr << "Configuration missing " << key << "\n"; 161 throw std::invalid_argument("Key Missing"); 162 } 163 if constexpr (std::is_same_v<T, double>) 164 { 165 return std::visit(VariantToDoubleVisitor(), it->second); 166 } 167 else if constexpr (std::is_unsigned_v<T>) 168 { 169 return std::visit(VariantToUnsignedIntVisitor(), it->second); 170 } 171 else if constexpr (std::is_same_v<T, std::string>) 172 { 173 return std::visit(VariantToStringVisitor(), it->second); 174 } 175 else 176 { 177 static_assert(!std::is_same_v<T, T>, "Type Not Implemented"); 178 } 179 } 180 181 inline void setReadState(const std::string& str, PowerState& val) 182 { 183 if (str == "On") 184 { 185 val = PowerState::on; 186 } 187 else if (str == "BiosPost") 188 { 189 val = PowerState::biosPost; 190 } 191 else if (str == "Always") 192 { 193 val = PowerState::always; 194 } 195 else if (str == "ChassisOn") 196 { 197 val = PowerState::chassisOn; 198 } 199 } 200 201 inline PowerState getPowerState(const SensorBaseConfigMap& cfg) 202 { 203 PowerState state = PowerState::always; 204 auto findPowerState = cfg.find("PowerState"); 205 if (findPowerState != cfg.end()) 206 { 207 std::string powerState = std::visit(VariantToStringVisitor(), 208 findPowerState->second); 209 setReadState(powerState, state); 210 } 211 return state; 212 } 213 214 inline float getPollRate(const SensorBaseConfigMap& cfg, float dflt) 215 { 216 float pollRate = dflt; 217 auto findPollRate = cfg.find("PollRate"); 218 if (findPollRate != cfg.end()) 219 { 220 pollRate = std::visit(VariantToFloatVisitor(), findPollRate->second); 221 if (!std::isfinite(pollRate) || pollRate <= 0.0F) 222 { 223 pollRate = dflt; // poll time invalid, fall back to default 224 } 225 } 226 return pollRate; 227 } 228 229 inline void setLed(const std::shared_ptr<sdbusplus::asio::connection>& conn, 230 const std::string& name, bool on) 231 { 232 conn->async_method_call( 233 [name](const boost::system::error_code ec) { 234 if (ec) 235 { 236 std::cerr << "Failed to set LED " << name << "\n"; 237 } 238 }, 239 "xyz.openbmc_project.LED.GroupManager", 240 "/xyz/openbmc_project/led/groups/" + name, properties::interface, 241 properties::set, "xyz.openbmc_project.Led.Group", "Asserted", 242 std::variant<bool>(on)); 243 } 244 245 void createInventoryAssoc( 246 const std::shared_ptr<sdbusplus::asio::connection>& conn, 247 const std::shared_ptr<sdbusplus::asio::dbus_interface>& association, 248 const std::string& path); 249 250 struct GetSensorConfiguration : 251 std::enable_shared_from_this<GetSensorConfiguration> 252 { 253 GetSensorConfiguration( 254 std::shared_ptr<sdbusplus::asio::connection> connection, 255 std::function<void(ManagedObjectType& resp)>&& callbackFunc) : 256 dbusConnection(std::move(connection)), 257 callback(std::move(callbackFunc)) 258 {} 259 260 void getPath(const std::string& path, const std::string& interface, 261 const std::string& owner, size_t retries = 5) 262 { 263 if (retries > 5) 264 { 265 retries = 5; 266 } 267 std::shared_ptr<GetSensorConfiguration> self = shared_from_this(); 268 269 self->dbusConnection->async_method_call( 270 [self, path, interface, owner, retries]( 271 const boost::system::error_code ec, SensorBaseConfigMap& data) { 272 if (ec) 273 { 274 std::cerr << "Error getting " << path << ": retries left" 275 << retries - 1 << "\n"; 276 if (retries == 0U) 277 { 278 return; 279 } 280 auto timer = std::make_shared<boost::asio::steady_timer>( 281 self->dbusConnection->get_io_context()); 282 timer->expires_after(std::chrono::seconds(10)); 283 timer->async_wait([self, timer, path, interface, owner, 284 retries](boost::system::error_code ec) { 285 if (ec) 286 { 287 std::cerr << "Timer error!\n"; 288 return; 289 } 290 self->getPath(path, interface, owner, retries - 1); 291 }); 292 return; 293 } 294 295 self->respData[path][interface] = std::move(data); 296 }, 297 owner, path, "org.freedesktop.DBus.Properties", "GetAll", 298 interface); 299 } 300 301 void getConfiguration(const std::vector<std::string>& types, 302 size_t retries = 0) 303 { 304 if (retries > 5) 305 { 306 retries = 5; 307 } 308 309 std::vector<std::string> interfaces(types.size()); 310 for (const auto& type : types) 311 { 312 interfaces.push_back(configInterfaceName(type)); 313 } 314 315 std::shared_ptr<GetSensorConfiguration> self = shared_from_this(); 316 dbusConnection->async_method_call( 317 [self, interfaces, retries](const boost::system::error_code ec, 318 const GetSubTreeType& ret) { 319 if (ec) 320 { 321 std::cerr << "Error calling mapper\n"; 322 if (retries == 0U) 323 { 324 return; 325 } 326 auto timer = std::make_shared<boost::asio::steady_timer>( 327 self->dbusConnection->get_io_context()); 328 timer->expires_after(std::chrono::seconds(10)); 329 timer->async_wait([self, timer, interfaces, 330 retries](boost::system::error_code ec) { 331 if (ec) 332 { 333 std::cerr << "Timer error!\n"; 334 return; 335 } 336 self->getConfiguration(interfaces, retries - 1); 337 }); 338 339 return; 340 } 341 for (const auto& [path, objDict] : ret) 342 { 343 if (objDict.empty()) 344 { 345 return; 346 } 347 const std::string& owner = objDict.begin()->first; 348 349 for (const std::string& interface : objDict.begin()->second) 350 { 351 // anything that starts with a requested configuration 352 // is good 353 if (std::find_if(interfaces.begin(), interfaces.end(), 354 [interface](const std::string& possible) { 355 return interface.starts_with(possible); 356 }) == interfaces.end()) 357 { 358 continue; 359 } 360 self->getPath(path, interface, owner); 361 } 362 } 363 }, 364 mapper::busName, mapper::path, mapper::interface, mapper::subtree, 365 "/", 0, interfaces); 366 } 367 368 ~GetSensorConfiguration() 369 { 370 callback(respData); 371 } 372 373 std::shared_ptr<sdbusplus::asio::connection> dbusConnection; 374 std::function<void(ManagedObjectType& resp)> callback; 375 ManagedObjectType respData; 376 }; 377 378 // The common scheme for sysfs files naming is: <type><number>_<item>. 379 // This function returns optionally these 3 elements as a tuple. 380 std::optional<std::tuple<std::string, std::string, std::string>> 381 splitFileName(const std::filesystem::path& filePath); 382 std::optional<double> readFile(const std::string& thresholdFile, 383 const double& scaleFactor); 384 void setupManufacturingModeMatch(sdbusplus::asio::connection& conn); 385 bool getManufacturingMode(); 386 std::vector<std::unique_ptr<sdbusplus::bus::match_t>> 387 setupPropertiesChangedMatches( 388 sdbusplus::asio::connection& bus, std::span<const char* const> types, 389 const std::function<void(sdbusplus::message_t&)>& handler); 390 391 template <typename T> 392 bool getDeviceBusAddr(const std::string& deviceName, T& bus, T& addr) 393 { 394 auto findHyphen = deviceName.find('-'); 395 if (findHyphen == std::string::npos) 396 { 397 std::cerr << "found bad device " << deviceName << "\n"; 398 return false; 399 } 400 std::string busStr = deviceName.substr(0, findHyphen); 401 std::string addrStr = deviceName.substr(findHyphen + 1); 402 403 std::from_chars_result res{}; 404 res = std::from_chars(&*busStr.begin(), &*busStr.end(), bus); 405 if (res.ec != std::errc{} || res.ptr != &*busStr.end()) 406 { 407 std::cerr << "Error finding bus for " << deviceName << "\n"; 408 return false; 409 } 410 res = std::from_chars(&*addrStr.begin(), &*addrStr.end(), addr, 16); 411 if (res.ec != std::errc{} || res.ptr != &*addrStr.end()) 412 { 413 std::cerr << "Error finding addr for " << deviceName << "\n"; 414 return false; 415 } 416 417 return true; 418 } 419