-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshutdown_alarm_monitor.cpp
464 lines (396 loc) · 15.3 KB
/
shutdown_alarm_monitor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
/**
* Copyright © 2021 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "shutdown_alarm_monitor.hpp"
#include <fmt/format.h>
#include <unistd.h>
#include <phosphor-logging/log.hpp>
#include <xyz/openbmc_project/Logging/Entry/server.hpp>
namespace sensor::monitor
{
using namespace phosphor::logging;
using namespace phosphor::fan::util;
using namespace phosphor::fan;
namespace fs = std::filesystem;
const std::map<ShutdownType, std::string> shutdownInterfaces{
{ShutdownType::hard, "xyz.openbmc_project.Sensor.Threshold.HardShutdown"},
{ShutdownType::soft, "xyz.openbmc_project.Sensor.Threshold.SoftShutdown"}};
const std::map<ShutdownType, std::map<AlarmType, std::string>> alarmProperties{
{ShutdownType::hard,
{{AlarmType::low, "HardShutdownAlarmLow"},
{AlarmType::high, "HardShutdownAlarmHigh"}}},
{ShutdownType::soft,
{{AlarmType::low, "SoftShutdownAlarmLow"},
{AlarmType::high, "SoftShutdownAlarmHigh"}}}};
const std::map<ShutdownType, std::chrono::milliseconds> shutdownDelays{
{ShutdownType::hard,
std::chrono::milliseconds{SHUTDOWN_ALARM_HARD_SHUTDOWN_DELAY_MS}},
{ShutdownType::soft,
std::chrono::milliseconds{SHUTDOWN_ALARM_SOFT_SHUTDOWN_DELAY_MS}}};
const std::map<ShutdownType, std::map<AlarmType, std::string>> alarmEventLogs{
{ShutdownType::hard,
{{AlarmType::high,
"xyz.openbmc_project.Sensor.Threshold.Error.HardShutdownAlarmHigh"},
{AlarmType::low, "xyz.openbmc_project.Sensor.Threshold.Error."
"HardShutdownAlarmLow"}}},
{ShutdownType::soft,
{{AlarmType::high,
"xyz.openbmc_project.Sensor.Threshold.Error.SoftShutdownAlarmHigh"},
{AlarmType::low, "xyz.openbmc_project.Sensor.Threshold.Error."
"SoftShutdownAlarmLow"}}}};
const std::map<ShutdownType, std::map<AlarmType, std::string>>
alarmClearEventLogs{
{ShutdownType::hard,
{{AlarmType::high, "xyz.openbmc_project.Sensor.Threshold.Error."
"HardShutdownAlarmHighClear"},
{AlarmType::low, "xyz.openbmc_project.Sensor.Threshold.Error."
"HardShutdownAlarmLowClear"}}},
{ShutdownType::soft,
{{AlarmType::high, "xyz.openbmc_project.Sensor.Threshold.Error."
"SoftShutdownAlarmHighClear"},
{AlarmType::low, "xyz.openbmc_project.Sensor.Threshold.Error."
"SoftShutdownAlarmLowClear"}}}};
constexpr auto systemdService = "org.freedesktop.systemd1";
constexpr auto systemdPath = "/org/freedesktop/systemd1";
constexpr auto systemdMgrIface = "org.freedesktop.systemd1.Manager";
constexpr auto valueInterface = "xyz.openbmc_project.Sensor.Value";
constexpr auto valueProperty = "Value";
const auto loggingService = "xyz.openbmc_project.Logging";
const auto loggingPath = "/xyz/openbmc_project/logging";
const auto loggingCreateIface = "xyz.openbmc_project.Logging.Create";
using namespace sdbusplus::bus::match;
ShutdownAlarmMonitor::ShutdownAlarmMonitor(
sdbusplus::bus::bus& bus, sdeventplus::Event& event,
std::shared_ptr<PowerState> powerState) :
bus(bus),
event(event), _powerState(std::move(powerState)),
hardShutdownMatch(bus,
"type='signal',member='PropertiesChanged',"
"path_namespace='/xyz/openbmc_project/sensors',"
"arg0='" +
shutdownInterfaces.at(ShutdownType::soft) + "'",
std::bind(&ShutdownAlarmMonitor::propertiesChanged, this,
std::placeholders::_1)),
softShutdownMatch(bus,
"type='signal',member='PropertiesChanged',"
"path_namespace='/xyz/openbmc_project/sensors',"
"arg0='" +
shutdownInterfaces.at(ShutdownType::hard) + "'",
std::bind(&ShutdownAlarmMonitor::propertiesChanged, this,
std::placeholders::_1))
{
_powerState->addCallback("shutdownMon",
std::bind(&ShutdownAlarmMonitor::powerStateChanged,
this, std::placeholders::_1));
findAlarms();
if (_powerState->isPowerOn())
{
checkAlarms();
// Get rid of any previous saved timestamps that don't
// apply anymore.
timestamps.prune(alarms);
}
else
{
timestamps.clear();
}
}
void ShutdownAlarmMonitor::findAlarms()
{
// Find all shutdown threshold ifaces currently on D-Bus.
for (const auto& [shutdownType, interface] : shutdownInterfaces)
{
auto paths = SDBusPlus::getSubTreePathsRaw(bus, "/", interface, 0);
std::for_each(
paths.begin(), paths.end(), [this, shutdownType](const auto& path) {
alarms.emplace(AlarmKey{path, shutdownType, AlarmType::high},
nullptr);
alarms.emplace(AlarmKey{path, shutdownType, AlarmType::low},
nullptr);
});
}
}
void ShutdownAlarmMonitor::checkAlarms()
{
for (auto& [alarmKey, timer] : alarms)
{
const auto& [sensorPath, shutdownType, alarmType] = alarmKey;
const auto& interface = shutdownInterfaces.at(shutdownType);
auto propertyName = alarmProperties.at(shutdownType).at(alarmType);
bool value;
try
{
value = SDBusPlus::getProperty<bool>(bus, sensorPath, interface,
propertyName);
}
catch (const DBusServiceError& e)
{
// The sensor isn't on D-Bus anymore
log<level::INFO>(fmt::format("No {} interface on {} anymore.",
interface, sensorPath)
.c_str());
continue;
}
checkAlarm(value, alarmKey);
}
}
void ShutdownAlarmMonitor::propertiesChanged(
sdbusplus::message::message& message)
{
std::map<std::string, std::variant<bool>> properties;
std::string interface;
if (!_powerState->isPowerOn())
{
return;
}
message.read(interface, properties);
auto type = getShutdownType(interface);
if (!type)
{
return;
}
std::string sensorPath = message.get_path();
const auto& lowAlarmName = alarmProperties.at(*type).at(AlarmType::low);
if (properties.count(lowAlarmName) > 0)
{
AlarmKey alarmKey{sensorPath, *type, AlarmType::low};
auto alarm = alarms.find(alarmKey);
if (alarm == alarms.end())
{
alarms.emplace(alarmKey, nullptr);
}
checkAlarm(std::get<bool>(properties.at(lowAlarmName)), alarmKey);
}
const auto& highAlarmName = alarmProperties.at(*type).at(AlarmType::high);
if (properties.count(highAlarmName) > 0)
{
AlarmKey alarmKey{sensorPath, *type, AlarmType::high};
auto alarm = alarms.find(alarmKey);
if (alarm == alarms.end())
{
alarms.emplace(alarmKey, nullptr);
}
checkAlarm(std::get<bool>(properties.at(highAlarmName)), alarmKey);
}
}
void ShutdownAlarmMonitor::checkAlarm(bool value, const AlarmKey& alarmKey)
{
auto alarm = alarms.find(alarmKey);
if (alarm == alarms.end())
{
return;
}
// Start or stop the timer if necessary.
auto& timer = alarm->second;
if (value)
{
if (!timer)
{
startTimer(alarmKey);
}
}
else
{
if (timer)
{
stopTimer(alarmKey);
}
}
}
void ShutdownAlarmMonitor::startTimer(const AlarmKey& alarmKey)
{
const auto& [sensorPath, shutdownType, alarmType] = alarmKey;
const auto& propertyName = alarmProperties.at(shutdownType).at(alarmType);
std::chrono::milliseconds shutdownDelay{shutdownDelays.at(shutdownType)};
std::optional<double> value;
auto alarm = alarms.find(alarmKey);
if (alarm == alarms.end())
{
throw std::runtime_error("Couldn't find alarm inside startTimer");
}
try
{
value = SDBusPlus::getProperty<double>(bus, sensorPath, valueInterface,
valueProperty);
}
catch (const DBusServiceError& e)
{
// If the sensor was just added, the Value interface for it may
// not be in the mapper yet. This could only happen if the sensor
// application was started with power up and the value exceeded the
// threshold immediately.
}
createEventLog(alarmKey, true, value);
uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
// If there is a saved timestamp for this timer, then we were restarted
// while the timer was running. Calculate the remaining time to use
// for the timer.
auto previousStartTime = timestamps.get().find(alarmKey);
if (previousStartTime != timestamps.get().end())
{
const uint64_t& original = previousStartTime->second;
log<level::INFO>(fmt::format("Found previously running {} timer "
"for {} with start time {}",
propertyName, sensorPath, original)
.c_str());
// Sanity check it isn't total garbage.
if (now > original)
{
uint64_t remainingTime = 0;
auto elapsedTime = now - original;
if (elapsedTime < static_cast<uint64_t>(shutdownDelay.count()))
{
remainingTime =
static_cast<uint64_t>(shutdownDelay.count()) - elapsedTime;
}
shutdownDelay = std::chrono::milliseconds{remainingTime};
}
else
{
log<level::WARNING>(
fmt::format(
"Restarting {} shutdown timer for {} for full "
"time because saved time {} is after current time {}",
propertyName, original, now)
.c_str());
}
}
log<level::INFO>(
fmt::format("Starting {}ms {} shutdown timer due to sensor {} value {}",
shutdownDelay.count(), propertyName, sensorPath, *value)
.c_str());
auto& timer = alarm->second;
timer = std::make_unique<
sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>(
event, std::bind(&ShutdownAlarmMonitor::timerExpired, this, alarmKey));
timer->restartOnce(shutdownDelay);
// Note that if this key is already in the timestamps map because
// the timer was already running the timestamp wil not be updated.
timestamps.add(alarmKey, now);
}
void ShutdownAlarmMonitor::stopTimer(const AlarmKey& alarmKey)
{
const auto& [sensorPath, shutdownType, alarmType] = alarmKey;
const auto& propertyName = alarmProperties.at(shutdownType).at(alarmType);
auto value = SDBusPlus::getProperty<double>(bus, sensorPath, valueInterface,
valueProperty);
auto alarm = alarms.find(alarmKey);
if (alarm == alarms.end())
{
throw std::runtime_error("Couldn't find alarm inside stopTimer");
}
createEventLog(alarmKey, false, value);
log<level::INFO>(
fmt::format("Stopping {} shutdown timer due to sensor {} value {}",
propertyName, sensorPath, value)
.c_str());
auto& timer = alarm->second;
timer->setEnabled(false);
timer.reset();
timestamps.erase(alarmKey);
}
void ShutdownAlarmMonitor::timerExpired(const AlarmKey& alarmKey)
{
const auto& [sensorPath, shutdownType, alarmType] = alarmKey;
const auto& propertyName = alarmProperties.at(shutdownType).at(alarmType);
auto value = SDBusPlus::getProperty<double>(bus, sensorPath, valueInterface,
valueProperty);
log<level::ERR>(
fmt::format(
"The {} shutdown timer expired for sensor {}, shutting down",
propertyName, sensorPath)
.c_str());
// Re-send the event log. If someone didn't want this it could be
// wrapped by a compile option.
createEventLog(alarmKey, true, value, true);
SDBusPlus::callMethod(systemdService, systemdPath, systemdMgrIface,
"StartUnit", "[email protected]",
"replace");
timestamps.erase(alarmKey);
}
void ShutdownAlarmMonitor::powerStateChanged(bool powerStateOn)
{
if (powerStateOn)
{
checkAlarms();
}
else
{
timestamps.clear();
// Cancel and delete all timers
std::for_each(alarms.begin(), alarms.end(), [](auto& alarm) {
auto& timer = alarm.second;
if (timer)
{
timer->setEnabled(false);
timer.reset();
}
});
}
}
void ShutdownAlarmMonitor::createEventLog(
const AlarmKey& alarmKey, bool alarmValue,
const std::optional<double>& sensorValue, bool isPowerOffError)
{
using namespace sdbusplus::xyz::openbmc_project::Logging::server;
const auto& [sensorPath, shutdownType, alarmType] = alarmKey;
std::map<std::string, std::string> ad{{"SENSOR_NAME", sensorPath},
{"_PID", std::to_string(getpid())}};
std::string errorName =
(alarmValue) ? alarmEventLogs.at(shutdownType).at(alarmType)
: alarmClearEventLogs.at(shutdownType).at(alarmType);
// severity = Critical if a power off
// severity = Error if alarm was asserted
// severity = Informational if alarm was deasserted
Entry::Level severity = Entry::Level::Error;
if (isPowerOffError)
{
severity = Entry::Level::Critical;
}
else if (!alarmValue)
{
severity = Entry::Level::Informational;
}
if (sensorValue)
{
ad.emplace("SENSOR_VALUE", std::to_string(*sensorValue));
}
// If this is a power off, specify that it's a power
// fault and a system termination. This is used by some
// implementations for service reasons.
if (isPowerOffError)
{
ad.emplace("POWER_THERMAL_CRITICAL_FAULT", "TRUE");
ad.emplace("SEVERITY_DETAIL", "SYSTEM_TERM");
}
SDBusPlus::callMethod(loggingService, loggingPath, loggingCreateIface,
"Create", errorName, convertForMessage(severity), ad);
}
std::optional<ShutdownType>
ShutdownAlarmMonitor::getShutdownType(const std::string& interface) const
{
auto it = std::find_if(
shutdownInterfaces.begin(), shutdownInterfaces.end(),
[interface](const auto& a) { return a.second == interface; });
if (it == shutdownInterfaces.end())
{
return std::nullopt;
}
return it->first;
}
} // namespace sensor::monitor