blob: 477a4c6ff98fdee186acc3cc05efd7af4e23d89e [file] [log] [blame]
Josh Lehan2a40e932020-09-02 11:48:14 -07001#include "ExternalSensor.hpp"
2#include "Utils.hpp"
3#include "VariantVisitors.hpp"
4
5#include <boost/algorithm/string/predicate.hpp>
6#include <boost/algorithm/string/replace.hpp>
7#include <boost/container/flat_map.hpp>
8#include <boost/container/flat_set.hpp>
9#include <sdbusplus/asio/connection.hpp>
10#include <sdbusplus/asio/object_server.hpp>
11#include <sdbusplus/bus/match.hpp>
12
13#include <array>
14#include <filesystem>
15#include <fstream>
16#include <functional>
17#include <memory>
18#include <regex>
19#include <stdexcept>
20#include <string>
21#include <utility>
22#include <variant>
23#include <vector>
24
25// Copied from HwmonTempSensor and inspired by
26// https://gerrit.openbmc-project.xyz/c/openbmc/dbus-sensors/+/35476
27
28// The ExternalSensor is a sensor whose value is intended to be writable
29// by something external to the BMC, so that the host (or something else)
Josh Lehan72432172021-03-17 13:35:43 -070030// can write to it, perhaps by using an IPMI or Redfish connection.
Josh Lehan2a40e932020-09-02 11:48:14 -070031
32// Unlike most other sensors, an external sensor does not correspond
Josh Lehan72432172021-03-17 13:35:43 -070033// to a hwmon file or any other kernel/hardware interface,
Josh Lehan2a40e932020-09-02 11:48:14 -070034// so, after initialization, this module does not have much to do,
35// but it handles reinitialization and thresholds, similar to the others.
Josh Lehan72432172021-03-17 13:35:43 -070036// The main work of this module is to provide backing storage for a
37// sensor that exists only virtually, and to provide an optional
38// timeout service for detecting loss of timely updates.
Josh Lehan2a40e932020-09-02 11:48:14 -070039
40// As there is no corresponding driver or hardware to support,
41// all configuration of this sensor comes from the JSON parameters:
Josh Lehan72432172021-03-17 13:35:43 -070042// MinValue, MaxValue, Timeout, PowerState, Units, Name
Josh Lehan2a40e932020-09-02 11:48:14 -070043
Josh Lehan72432172021-03-17 13:35:43 -070044// The purpose of "Units" is to specify the physical characteristic
Josh Lehan2a40e932020-09-02 11:48:14 -070045// the external sensor is measuring, because with an external sensor
46// there is no other way to tell, and it will be used for the object path
Josh Lehan72432172021-03-17 13:35:43 -070047// here: /xyz/openbmc_project/sensors/<Units>/<Name>
48
49// For more information, see external-sensor.md design document:
50// https://gerrit.openbmc-project.xyz/c/openbmc/docs/+/41452
51// https://github.com/openbmc/docs/tree/master/designs/
Josh Lehan2a40e932020-09-02 11:48:14 -070052
Ed Tanous8a57ec02020-10-09 12:46:52 -070053static constexpr bool debug = false;
Josh Lehan2a40e932020-09-02 11:48:14 -070054
55static const char* sensorType =
56 "xyz.openbmc_project.Configuration.ExternalSensor";
57
Josh Lehan72432172021-03-17 13:35:43 -070058void updateReaper(boost::container::flat_map<
59 std::string, std::shared_ptr<ExternalSensor>>& sensors,
60 boost::asio::steady_timer& timer,
61 const std::chrono::steady_clock::time_point& now)
62{
63 // First pass, reap all stale sensors
64 for (auto& sensor : sensors)
65 {
66 if (!sensor.second)
67 {
68 continue;
69 }
70
71 if (!sensor.second->isAliveAndPerishable())
72 {
73 continue;
74 }
75
76 if (!sensor.second->isAliveAndFresh(now))
77 {
78 // Mark sensor as dead, no longer alive
79 sensor.second->writeInvalidate();
80 }
81 }
82
83 std::chrono::steady_clock::duration nextCheck;
84 bool needCheck = false;
85
86 // Second pass, determine timer interval to next check
87 for (auto& sensor : sensors)
88 {
89 if (!sensor.second)
90 {
91 continue;
92 }
93
94 if (!sensor.second->isAliveAndPerishable())
95 {
96 continue;
97 }
98
99 auto expiration = sensor.second->ageRemaining(now);
100
101 if (needCheck)
102 {
103 nextCheck = std::min(nextCheck, expiration);
104 }
105 else
106 {
107 // Initialization
108 nextCheck = expiration;
109 needCheck = true;
110 }
111 }
112
113 if (!needCheck)
114 {
115 if constexpr (debug)
116 {
117 std::cerr << "Next ExternalSensor timer idle\n";
118 }
119
120 return;
121 }
122
123 timer.expires_at(now + nextCheck);
124
125 timer.async_wait([&sensors, &timer](const boost::system::error_code& err) {
126 if (err != boost::system::errc::success)
127 {
128 // Cancellation is normal, as timer is dynamically rescheduled
Josh Lehan03627382021-03-17 13:35:43 -0700129 if (err != boost::asio::error::operation_aborted)
Josh Lehan72432172021-03-17 13:35:43 -0700130 {
131 std::cerr << "ExternalSensor timer scheduling problem: "
132 << err.message() << "\n";
133 }
134 return;
135 }
Josh Lehan03627382021-03-17 13:35:43 -0700136
Josh Lehan72432172021-03-17 13:35:43 -0700137 updateReaper(sensors, timer, std::chrono::steady_clock::now());
138 });
139
140 if constexpr (debug)
141 {
142 std::cerr << "Next ExternalSensor timer "
143 << std::chrono::duration_cast<std::chrono::microseconds>(
144 nextCheck)
145 .count()
146 << " us\n";
147 }
148}
149
Josh Lehan2a40e932020-09-02 11:48:14 -0700150void createSensors(
Ed Tanous8a17c302021-09-02 15:07:11 -0700151 sdbusplus::asio::object_server& objectServer,
Josh Lehan2a40e932020-09-02 11:48:14 -0700152 boost::container::flat_map<std::string, std::shared_ptr<ExternalSensor>>&
153 sensors,
154 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
155 const std::shared_ptr<boost::container::flat_set<std::string>>&
Josh Lehan72432172021-03-17 13:35:43 -0700156 sensorsChanged,
157 boost::asio::steady_timer& reaperTimer)
Josh Lehan2a40e932020-09-02 11:48:14 -0700158{
Josh Lehan03627382021-03-17 13:35:43 -0700159 if constexpr (debug)
160 {
161 std::cerr << "ExternalSensor considering creating sensors\n";
162 }
163
Josh Lehan2a40e932020-09-02 11:48:14 -0700164 auto getter = std::make_shared<GetSensorConfiguration>(
165 dbusConnection,
Ed Tanous8a17c302021-09-02 15:07:11 -0700166 [&objectServer, &sensors, &dbusConnection, sensorsChanged,
Josh Lehan72432172021-03-17 13:35:43 -0700167 &reaperTimer](const ManagedObjectType& sensorConfigurations) {
Josh Lehan2a40e932020-09-02 11:48:14 -0700168 bool firstScan = (sensorsChanged == nullptr);
169
170 for (const std::pair<sdbusplus::message::object_path, SensorData>&
171 sensor : sensorConfigurations)
172 {
173 const std::string& interfacePath = sensor.first.str;
174 const SensorData& sensorData = sensor.second;
175
176 auto sensorBase = sensorData.find(sensorType);
177 if (sensorBase == sensorData.end())
178 {
179 std::cerr << "Base configuration not found for "
180 << interfacePath << "\n";
181 continue;
182 }
183
184 const SensorBaseConfiguration& baseConfiguration = *sensorBase;
185 const SensorBaseConfigMap& baseConfigMap =
186 baseConfiguration.second;
187
Josh Lehan2a40e932020-09-02 11:48:14 -0700188 // MinValue and MinValue are mandatory numeric parameters
189 auto minFound = baseConfigMap.find("MinValue");
190 if (minFound == baseConfigMap.end())
191 {
192 std::cerr << "MinValue parameter not found for "
193 << interfacePath << "\n";
194 continue;
195 }
Ed Tanousa771f6a2022-01-14 09:36:51 -0800196 double minValue =
Josh Lehan2a40e932020-09-02 11:48:14 -0700197 std::visit(VariantToDoubleVisitor(), minFound->second);
198 if (!std::isfinite(minValue))
199 {
200 std::cerr << "MinValue parameter not parsed for "
201 << interfacePath << "\n";
202 continue;
203 }
204
205 auto maxFound = baseConfigMap.find("MaxValue");
206 if (maxFound == baseConfigMap.end())
207 {
208 std::cerr << "MaxValue parameter not found for "
209 << interfacePath << "\n";
210 continue;
211 }
Ed Tanousa771f6a2022-01-14 09:36:51 -0800212 double maxValue =
Josh Lehan2a40e932020-09-02 11:48:14 -0700213 std::visit(VariantToDoubleVisitor(), maxFound->second);
214 if (!std::isfinite(maxValue))
215 {
216 std::cerr << "MaxValue parameter not parsed for "
217 << interfacePath << "\n";
218 continue;
219 }
220
Josh Lehan72432172021-03-17 13:35:43 -0700221 double timeoutSecs = 0.0;
Josh Lehan2a40e932020-09-02 11:48:14 -0700222
Josh Lehan72432172021-03-17 13:35:43 -0700223 // Timeout is an optional numeric parameter
224 auto timeoutFound = baseConfigMap.find("Timeout");
225 if (timeoutFound != baseConfigMap.end())
226 {
227 timeoutSecs = std::visit(VariantToDoubleVisitor(),
228 timeoutFound->second);
229 }
230 if (!(std::isfinite(timeoutSecs) && (timeoutSecs >= 0.0)))
231 {
232 std::cerr << "Timeout parameter not parsed for "
233 << interfacePath << "\n";
234 continue;
235 }
236
237 std::string sensorName;
238 std::string sensorUnits;
239
240 // Name and Units are mandatory string parameters
Josh Lehan2a40e932020-09-02 11:48:14 -0700241 auto nameFound = baseConfigMap.find("Name");
242 if (nameFound == baseConfigMap.end())
243 {
244 std::cerr << "Name parameter not found for "
245 << interfacePath << "\n";
246 continue;
247 }
248 sensorName =
249 std::visit(VariantToStringVisitor(), nameFound->second);
250 if (sensorName.empty())
251 {
252 std::cerr << "Name parameter not parsed for "
253 << interfacePath << "\n";
254 continue;
255 }
256
Josh Lehan72432172021-03-17 13:35:43 -0700257 auto unitsFound = baseConfigMap.find("Units");
258 if (unitsFound == baseConfigMap.end())
Josh Lehan2a40e932020-09-02 11:48:14 -0700259 {
260 std::cerr << "Units parameter not found for "
261 << interfacePath << "\n";
262 continue;
263 }
Josh Lehan72432172021-03-17 13:35:43 -0700264 sensorUnits =
265 std::visit(VariantToStringVisitor(), unitsFound->second);
266 if (sensorUnits.empty())
Josh Lehan2a40e932020-09-02 11:48:14 -0700267 {
Josh Lehan72432172021-03-17 13:35:43 -0700268 std::cerr << "Units parameter not parsed for "
Josh Lehan2a40e932020-09-02 11:48:14 -0700269 << interfacePath << "\n";
270 continue;
271 }
272
273 // on rescans, only update sensors we were signaled by
274 auto findSensor = sensors.find(sensorName);
275 if (!firstScan && (findSensor != sensors.end()))
276 {
277 std::string suffixName = "/";
278 suffixName += findSensor->second->name;
279 bool found = false;
280 for (auto it = sensorsChanged->begin();
281 it != sensorsChanged->end(); it++)
282 {
283 std::string suffixIt = "/";
284 suffixIt += *it;
285 if (boost::ends_with(suffixIt, suffixName))
286 {
287 sensorsChanged->erase(it);
288 findSensor->second = nullptr;
289 found = true;
Josh Lehan03627382021-03-17 13:35:43 -0700290 if constexpr (debug)
291 {
292 std::cerr << "ExternalSensor " << sensorName
293 << " change found\n";
294 }
Josh Lehan2a40e932020-09-02 11:48:14 -0700295 break;
296 }
297 }
298 if (!found)
299 {
300 continue;
301 }
302 }
303
304 std::vector<thresholds::Threshold> sensorThresholds;
305 if (!parseThresholdsFromConfig(sensorData, sensorThresholds))
306 {
307 std::cerr << "error populating thresholds for "
308 << sensorName << "\n";
309 }
310
311 auto findPowerOn = baseConfiguration.second.find("PowerState");
312 PowerState readState = PowerState::always;
313 if (findPowerOn != baseConfiguration.second.end())
314 {
315 std::string powerState = std::visit(
316 VariantToStringVisitor(), findPowerOn->second);
317 setReadState(powerState, readState);
318 }
319
320 auto& sensorEntry = sensors[sensorName];
321 sensorEntry = nullptr;
322
323 sensorEntry = std::make_shared<ExternalSensor>(
324 sensorType, objectServer, dbusConnection, sensorName,
Josh Lehan72432172021-03-17 13:35:43 -0700325 sensorUnits, std::move(sensorThresholds), interfacePath,
Josh Lehan03627382021-03-17 13:35:43 -0700326 maxValue, minValue, timeoutSecs, readState);
327 sensorEntry->initWriteHook(
Josh Lehan72432172021-03-17 13:35:43 -0700328 [&sensors, &reaperTimer](
329 const std::chrono::steady_clock::time_point& now) {
330 updateReaper(sensors, reaperTimer, now);
331 });
332
333 if constexpr (debug)
334 {
335 std::cerr << "ExternalSensor " << sensorName
336 << " created\n";
337 }
Josh Lehan2a40e932020-09-02 11:48:14 -0700338 }
339 });
340
341 getter->getConfiguration(std::vector<std::string>{sensorType});
342}
343
344int main()
345{
Josh Lehan72432172021-03-17 13:35:43 -0700346 if constexpr (debug)
347 {
348 std::cerr << "ExternalSensor service starting up\n";
349 }
350
Josh Lehan2a40e932020-09-02 11:48:14 -0700351 boost::asio::io_service io;
352 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
353 systemBus->request_name("xyz.openbmc_project.ExternalSensor");
354 sdbusplus::asio::object_server objectServer(systemBus);
355 boost::container::flat_map<std::string, std::shared_ptr<ExternalSensor>>
356 sensors;
357 std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
358 auto sensorsChanged =
359 std::make_shared<boost::container::flat_set<std::string>>();
Josh Lehan72432172021-03-17 13:35:43 -0700360 boost::asio::steady_timer reaperTimer(io);
Josh Lehan2a40e932020-09-02 11:48:14 -0700361
Ed Tanous8a17c302021-09-02 15:07:11 -0700362 io.post([&objectServer, &sensors, &systemBus, &reaperTimer]() {
363 createSensors(objectServer, sensors, systemBus, nullptr, reaperTimer);
Josh Lehan2a40e932020-09-02 11:48:14 -0700364 });
365
366 boost::asio::deadline_timer filterTimer(io);
367 std::function<void(sdbusplus::message::message&)> eventHandler =
Ed Tanous8a17c302021-09-02 15:07:11 -0700368 [&objectServer, &sensors, &systemBus, &sensorsChanged, &filterTimer,
369 &reaperTimer](sdbusplus::message::message& message) mutable {
Josh Lehan2a40e932020-09-02 11:48:14 -0700370 if (message.is_method_error())
371 {
372 std::cerr << "callback method error\n";
373 return;
374 }
Josh Lehan03627382021-03-17 13:35:43 -0700375
376 auto messagePath = message.get_path();
377 sensorsChanged->insert(messagePath);
378 if constexpr (debug)
379 {
380 std::cerr << "ExternalSensor change event received: "
381 << messagePath << "\n";
382 }
383
Josh Lehan2a40e932020-09-02 11:48:14 -0700384 // this implicitly cancels the timer
385 filterTimer.expires_from_now(boost::posix_time::seconds(1));
386
Ed Tanous8a17c302021-09-02 15:07:11 -0700387 filterTimer.async_wait(
388 [&objectServer, &sensors, &systemBus, &sensorsChanged,
389 &reaperTimer](const boost::system::error_code& ec) mutable {
390 if (ec != boost::system::errc::success)
Josh Lehan2a40e932020-09-02 11:48:14 -0700391 {
Ed Tanous8a17c302021-09-02 15:07:11 -0700392 if (ec != boost::asio::error::operation_aborted)
393 {
394 std::cerr << "callback error: " << ec.message()
395 << "\n";
396 }
397 return;
Josh Lehan2a40e932020-09-02 11:48:14 -0700398 }
Josh Lehan03627382021-03-17 13:35:43 -0700399
Ed Tanous8a17c302021-09-02 15:07:11 -0700400 createSensors(objectServer, sensors, systemBus,
401 sensorsChanged, reaperTimer);
402 });
Josh Lehan2a40e932020-09-02 11:48:14 -0700403 };
404
405 auto match = std::make_unique<sdbusplus::bus::match::match>(
406 static_cast<sdbusplus::bus::bus&>(*systemBus),
407 "type='signal',member='PropertiesChanged',path_namespace='" +
408 std::string(inventoryPath) + "',arg0namespace='" + sensorType + "'",
409 eventHandler);
410 matches.emplace_back(std::move(match));
411
Josh Lehan72432172021-03-17 13:35:43 -0700412 if constexpr (debug)
413 {
414 std::cerr << "ExternalSensor service entering main loop\n";
415 }
416
Josh Lehan2a40e932020-09-02 11:48:14 -0700417 io.run();
418}