xref: /openbmc/dbus-sensors/src/Utils.hpp (revision ea14f14a)
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 void createAssociation(
84     std::shared_ptr<sdbusplus::asio::dbus_interface>& association,
85     const std::string& path);
86 
87 // replaces limits if MinReading and MaxReading are found.
88 void findLimits(std::pair<double, double>& limits,
89                 const SensorBaseConfiguration* data);
90 
91 bool readingStateGood(const PowerState& powerState);
92 
93 constexpr const char* configInterfacePrefix =
94     "xyz.openbmc_project.Configuration.";
95 
96 inline std::string configInterfaceName(const std::string& type)
97 {
98     return std::string(configInterfacePrefix) + type;
99 }
100 
101 namespace mapper
102 {
103 constexpr const char* busName = "xyz.openbmc_project.ObjectMapper";
104 constexpr const char* path = "/xyz/openbmc_project/object_mapper";
105 constexpr const char* interface = "xyz.openbmc_project.ObjectMapper";
106 constexpr const char* subtree = "GetSubTree";
107 } // namespace mapper
108 
109 namespace properties
110 {
111 constexpr const char* interface = "org.freedesktop.DBus.Properties";
112 constexpr const char* get = "Get";
113 constexpr const char* set = "Set";
114 } // namespace properties
115 
116 namespace power
117 {
118 const static constexpr char* busname = "xyz.openbmc_project.State.Host";
119 const static constexpr char* interface = "xyz.openbmc_project.State.Host";
120 const static constexpr char* path = "/xyz/openbmc_project/state/host0";
121 const static constexpr char* property = "CurrentHostState";
122 } // namespace power
123 
124 namespace chassis
125 {
126 const static constexpr char* busname = "xyz.openbmc_project.State.Chassis0";
127 const static constexpr char* interface = "xyz.openbmc_project.State.Chassis";
128 const static constexpr char* path = "/xyz/openbmc_project/state/chassis0";
129 const static constexpr char* property = "CurrentPowerState";
130 const static constexpr char* sOn = ".On";
131 } // namespace chassis
132 
133 namespace post
134 {
135 const static constexpr char* busname =
136     "xyz.openbmc_project.State.OperatingSystem";
137 const static constexpr char* interface =
138     "xyz.openbmc_project.State.OperatingSystem.Status";
139 const static constexpr char* path = "/xyz/openbmc_project/state/os";
140 const static constexpr char* property = "OperatingSystemState";
141 } // namespace post
142 
143 namespace association
144 {
145 const static constexpr char* interface =
146     "xyz.openbmc_project.Association.Definitions";
147 } // namespace association
148 
149 template <typename T>
150 inline T loadVariant(const SensorBaseConfigMap& data, const std::string& key)
151 {
152     auto it = data.find(key);
153     if (it == data.end())
154     {
155         std::cerr << "Configuration missing " << key << "\n";
156         throw std::invalid_argument("Key Missing");
157     }
158     if constexpr (std::is_same_v<T, double>)
159     {
160         return std::visit(VariantToDoubleVisitor(), it->second);
161     }
162     else if constexpr (std::is_unsigned_v<T>)
163     {
164         return std::visit(VariantToUnsignedIntVisitor(), it->second);
165     }
166     else if constexpr (std::is_same_v<T, std::string>)
167     {
168         return std::visit(VariantToStringVisitor(), it->second);
169     }
170     else
171     {
172         static_assert(!std::is_same_v<T, T>, "Type Not Implemented");
173     }
174 }
175 
176 inline void setReadState(const std::string& str, PowerState& val)
177 {
178     if (str == "On")
179     {
180         val = PowerState::on;
181     }
182     else if (str == "BiosPost")
183     {
184         val = PowerState::biosPost;
185     }
186     else if (str == "Always")
187     {
188         val = PowerState::always;
189     }
190     else if (str == "ChassisOn")
191     {
192         val = PowerState::chassisOn;
193     }
194 }
195 
196 inline PowerState getPowerState(const SensorBaseConfigMap& cfg)
197 {
198     PowerState state = PowerState::always;
199     auto findPowerState = cfg.find("PowerState");
200     if (findPowerState != cfg.end())
201     {
202         std::string powerState = std::visit(VariantToStringVisitor(),
203                                             findPowerState->second);
204         setReadState(powerState, state);
205     }
206     return state;
207 }
208 
209 inline float getPollRate(const SensorBaseConfigMap& cfg, float dflt)
210 {
211     float pollRate = dflt;
212     auto findPollRate = cfg.find("PollRate");
213     if (findPollRate != cfg.end())
214     {
215         pollRate = std::visit(VariantToFloatVisitor(), findPollRate->second);
216         if (!std::isfinite(pollRate) || pollRate <= 0.0F)
217         {
218             pollRate = dflt; // poll time invalid, fall back to default
219         }
220     }
221     return pollRate;
222 }
223 
224 inline void setLed(const std::shared_ptr<sdbusplus::asio::connection>& conn,
225                    const std::string& name, bool on)
226 {
227     conn->async_method_call(
228         [name](const boost::system::error_code ec) {
229         if (ec)
230         {
231             std::cerr << "Failed to set LED " << name << "\n";
232         }
233     },
234         "xyz.openbmc_project.LED.GroupManager",
235         "/xyz/openbmc_project/led/groups/" + name, properties::interface,
236         properties::set, "xyz.openbmc_project.Led.Group", "Asserted",
237         std::variant<bool>(on));
238 }
239 
240 void createInventoryAssoc(
241     const std::shared_ptr<sdbusplus::asio::connection>& conn,
242     const std::shared_ptr<sdbusplus::asio::dbus_interface>& association,
243     const std::string& path);
244 
245 struct GetSensorConfiguration :
246     std::enable_shared_from_this<GetSensorConfiguration>
247 {
248     GetSensorConfiguration(
249         std::shared_ptr<sdbusplus::asio::connection> connection,
250         std::function<void(ManagedObjectType& resp)>&& callbackFunc) :
251         dbusConnection(std::move(connection)),
252         callback(std::move(callbackFunc))
253     {}
254 
255     void getPath(const std::string& path, const std::string& interface,
256                  const std::string& owner, size_t retries = 5)
257     {
258         if (retries > 5)
259         {
260             retries = 5;
261         }
262         std::shared_ptr<GetSensorConfiguration> self = shared_from_this();
263 
264         self->dbusConnection->async_method_call(
265             [self, path, interface, owner, retries](
266                 const boost::system::error_code ec, SensorBaseConfigMap& data) {
267             if (ec)
268             {
269                 std::cerr << "Error getting " << path << ": retries left"
270                           << retries - 1 << "\n";
271                 if (retries == 0U)
272                 {
273                     return;
274                 }
275                 auto timer = std::make_shared<boost::asio::steady_timer>(
276                     self->dbusConnection->get_io_context());
277                 timer->expires_after(std::chrono::seconds(10));
278                 timer->async_wait([self, timer, path, interface, owner,
279                                    retries](boost::system::error_code ec) {
280                     if (ec)
281                     {
282                         std::cerr << "Timer error!\n";
283                         return;
284                     }
285                     self->getPath(path, interface, owner, retries - 1);
286                 });
287                 return;
288             }
289 
290             self->respData[path][interface] = std::move(data);
291         },
292             owner, path, "org.freedesktop.DBus.Properties", "GetAll",
293             interface);
294     }
295 
296     void getConfiguration(const std::vector<std::string>& types,
297                           size_t retries = 0)
298     {
299         if (retries > 5)
300         {
301             retries = 5;
302         }
303 
304         std::vector<std::string> interfaces(types.size());
305         for (const auto& type : types)
306         {
307             interfaces.push_back(configInterfaceName(type));
308         }
309 
310         std::shared_ptr<GetSensorConfiguration> self = shared_from_this();
311         dbusConnection->async_method_call(
312             [self, interfaces, retries](const boost::system::error_code ec,
313                                         const GetSubTreeType& ret) {
314             if (ec)
315             {
316                 std::cerr << "Error calling mapper\n";
317                 if (retries == 0U)
318                 {
319                     return;
320                 }
321                 auto timer = std::make_shared<boost::asio::steady_timer>(
322                     self->dbusConnection->get_io_context());
323                 timer->expires_after(std::chrono::seconds(10));
324                 timer->async_wait([self, timer, interfaces,
325                                    retries](boost::system::error_code ec) {
326                     if (ec)
327                     {
328                         std::cerr << "Timer error!\n";
329                         return;
330                     }
331                     self->getConfiguration(interfaces, retries - 1);
332                 });
333 
334                 return;
335             }
336             for (const auto& [path, objDict] : ret)
337             {
338                 if (objDict.empty())
339                 {
340                     return;
341                 }
342                 const std::string& owner = objDict.begin()->first;
343 
344                 for (const std::string& interface : objDict.begin()->second)
345                 {
346                     // anything that starts with a requested configuration
347                     // is good
348                     if (std::find_if(interfaces.begin(), interfaces.end(),
349                                      [interface](const std::string& possible) {
350                         return interface.starts_with(possible);
351                     }) == interfaces.end())
352                     {
353                         continue;
354                     }
355                     self->getPath(path, interface, owner);
356                 }
357             }
358         },
359             mapper::busName, mapper::path, mapper::interface, mapper::subtree,
360             "/", 0, interfaces);
361     }
362 
363     ~GetSensorConfiguration()
364     {
365         callback(respData);
366     }
367 
368     std::shared_ptr<sdbusplus::asio::connection> dbusConnection;
369     std::function<void(ManagedObjectType& resp)> callback;
370     ManagedObjectType respData;
371 };
372 
373 // The common scheme for sysfs files naming is: <type><number>_<item>.
374 // This function returns optionally these 3 elements as a tuple.
375 std::optional<std::tuple<std::string, std::string, std::string>>
376     splitFileName(const std::filesystem::path& filePath);
377 std::optional<double> readFile(const std::string& thresholdFile,
378                                const double& scaleFactor);
379 void setupManufacturingModeMatch(sdbusplus::asio::connection& conn);
380 bool getManufacturingMode();
381 std::vector<std::unique_ptr<sdbusplus::bus::match_t>>
382     setupPropertiesChangedMatches(
383         sdbusplus::asio::connection& bus, std::span<const char* const> types,
384         const std::function<void(sdbusplus::message_t&)>& handler);
385 
386 template <typename T>
387 bool getDeviceBusAddr(const std::string& deviceName, T& bus, T& addr)
388 {
389     auto findHyphen = deviceName.find('-');
390     if (findHyphen == std::string::npos)
391     {
392         std::cerr << "found bad device " << deviceName << "\n";
393         return false;
394     }
395     std::string busStr = deviceName.substr(0, findHyphen);
396     std::string addrStr = deviceName.substr(findHyphen + 1);
397 
398     std::from_chars_result res{};
399     res = std::from_chars(&*busStr.begin(), &*busStr.end(), bus);
400     if (res.ec != std::errc{} || res.ptr != &*busStr.end())
401     {
402         std::cerr << "Error finding bus for " << deviceName << "\n";
403         return false;
404     }
405     res = std::from_chars(&*addrStr.begin(), &*addrStr.end(), addr, 16);
406     if (res.ec != std::errc{} || res.ptr != &*addrStr.end())
407     {
408         std::cerr << "Error finding addr for " << deviceName << "\n";
409         return false;
410     }
411 
412     return true;
413 }
414