xref: /openbmc/phosphor-fan-presence/monitor/json_parser.cpp (revision 61b7329603e737b76b04b98746d69c1f410761b8)
1 /**
2  * Copyright © 2020 IBM 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 #include "json_parser.hpp"
17 
18 #include "conditions.hpp"
19 #include "json_config.hpp"
20 #include "nonzero_speed_trust.hpp"
21 #include "power_interface.hpp"
22 #include "power_off_rule.hpp"
23 #include "tach_sensor.hpp"
24 #include "types.hpp"
25 
26 #include <fmt/format.h>
27 
28 #include <nlohmann/json.hpp>
29 #include <phosphor-logging/log.hpp>
30 
31 #include <algorithm>
32 #include <map>
33 #include <memory>
34 #include <optional>
35 #include <vector>
36 
37 namespace phosphor::fan::monitor
38 {
39 
40 using json = nlohmann::json;
41 using namespace phosphor::logging;
42 
43 namespace tClass
44 {
45 
46 // Get a constructed trust group class for a non-zero speed group
47 CreateGroupFunction
48     getNonZeroSpeed(const std::vector<trust::GroupDefinition>& group)
49 {
50     return [group]() {
51         return std::make_unique<trust::NonzeroSpeed>(std::move(group));
52     };
53 }
54 
55 } // namespace tClass
56 
57 const std::map<std::string, trustHandler> trusts = {
58     {"nonzerospeed", tClass::getNonZeroSpeed}};
59 const std::map<std::string, condHandler> conditions = {
60     {"propertiesmatch", condition::getPropertiesMatch}};
61 const std::map<std::string, size_t> methods = {
62     {"timebased", MethodMode::timebased}, {"count", MethodMode::count}};
63 
64 const std::vector<CreateGroupFunction> getTrustGrps(const json& obj)
65 {
66     std::vector<CreateGroupFunction> grpFuncs;
67 
68     if (obj.contains("sensor_trust_groups"))
69     {
70         for (auto& stg : obj["sensor_trust_groups"])
71         {
72             if (!stg.contains("class") || !stg.contains("group"))
73             {
74                 // Log error on missing required parameters
75                 log<level::ERR>(
76                     "Missing required fan monitor trust group parameters",
77                     entry("REQUIRED_PARAMETERS=%s", "{class, group}"));
78                 throw std::runtime_error(
79                     "Missing required fan trust group parameters");
80             }
81             auto tgClass = stg["class"].get<std::string>();
82             std::vector<trust::GroupDefinition> group;
83             for (auto& member : stg["group"])
84             {
85                 // Construct list of group members
86                 if (!member.contains("name"))
87                 {
88                     // Log error on missing required parameter
89                     log<level::ERR>(
90                         "Missing required fan monitor trust group member name",
91                         entry("CLASS=%s", tgClass.c_str()));
92                     throw std::runtime_error(
93                         "Missing required fan monitor trust group member name");
94                 }
95                 auto in_trust = true;
96                 if (member.contains("in_trust"))
97                 {
98                     in_trust = member["in_trust"].get<bool>();
99                 }
100                 group.emplace_back(trust::GroupDefinition{
101                     member["name"].get<std::string>(), in_trust});
102             }
103             // The class for fan sensor trust groups
104             // (Must have a supported function within the tClass namespace)
105             std::transform(tgClass.begin(), tgClass.end(), tgClass.begin(),
106                            tolower);
107             auto handler = trusts.find(tgClass);
108             if (handler != trusts.end())
109             {
110                 // Call function for trust group class
111                 grpFuncs.emplace_back(handler->second(group));
112             }
113             else
114             {
115                 // Log error on unsupported trust group class
116                 log<level::ERR>("Invalid fan monitor trust group class",
117                                 entry("CLASS=%s", tgClass.c_str()));
118                 throw std::runtime_error(
119                     "Invalid fan monitor trust group class");
120             }
121         }
122     }
123 
124     return grpFuncs;
125 }
126 
127 const std::vector<SensorDefinition> getSensorDefs(const json& sensors)
128 {
129     std::vector<SensorDefinition> sensorDefs;
130 
131     for (const auto& sensor : sensors)
132     {
133         if (!sensor.contains("name") || !sensor.contains("has_target"))
134         {
135             // Log error on missing required parameters
136             log<level::ERR>(
137                 "Missing required fan sensor definition parameters",
138                 entry("REQUIRED_PARAMETERS=%s", "{name, has_target}"));
139             throw std::runtime_error(
140                 "Missing required fan sensor definition parameters");
141         }
142         // Target interface is optional and defaults to
143         // 'xyz.openbmc_project.Control.FanSpeed'
144         std::string targetIntf = "xyz.openbmc_project.Control.FanSpeed";
145         if (sensor.contains("target_interface"))
146         {
147             targetIntf = sensor["target_interface"].get<std::string>();
148         }
149         // Target path is optional
150         std::string targetPath;
151         if (sensor.contains("target_path"))
152         {
153             targetPath = sensor["target_path"].get<std::string>();
154         }
155         // Factor is optional and defaults to 1
156         auto factor = 1.0;
157         if (sensor.contains("factor"))
158         {
159             factor = sensor["factor"].get<double>();
160         }
161         // Offset is optional and defaults to 0
162         auto offset = 0;
163         if (sensor.contains("offset"))
164         {
165             offset = sensor["offset"].get<int64_t>();
166         }
167         // Threshold is optional and defaults to 1
168         auto threshold = 1;
169         if (sensor.contains("threshold"))
170         {
171             threshold = sensor["threshold"].get<size_t>();
172         }
173         // Ignore being above the allowed max is optional, defaults to not
174         bool ignoreAboveMax = false;
175         if (sensor.contains("ignore_above_max"))
176         {
177             ignoreAboveMax = sensor["ignore_above_max"].get<bool>();
178         }
179 
180         sensorDefs.emplace_back(std::tuple(
181             sensor["name"].get<std::string>(), sensor["has_target"].get<bool>(),
182             targetIntf, targetPath, factor, offset, threshold, ignoreAboveMax));
183     }
184 
185     return sensorDefs;
186 }
187 
188 const std::vector<FanDefinition> getFanDefs(const json& obj)
189 {
190     std::vector<FanDefinition> fanDefs;
191 
192     for (const auto& fan : obj["fans"])
193     {
194         if (!fan.contains("inventory") || !fan.contains("deviation") ||
195             !fan.contains("sensors"))
196         {
197             // Log error on missing required parameters
198             log<level::ERR>(
199                 "Missing required fan monitor definition parameters",
200                 entry("REQUIRED_PARAMETERS=%s",
201                       "{inventory, deviation, sensors}"));
202             throw std::runtime_error(
203                 "Missing required fan monitor definition parameters");
204         }
205         // Valid deviation range is 0 - 100%
206         auto deviation = fan["deviation"].get<size_t>();
207         if (100 < deviation)
208         {
209             auto msg = fmt::format(
210                 "Invalid deviation of {} found, must be between 0 and 100",
211                 deviation);
212 
213             log<level::ERR>(msg.c_str());
214             throw std::runtime_error(msg.c_str());
215         }
216 
217         // Construct the sensor definitions for this fan
218         auto sensorDefs = getSensorDefs(fan["sensors"]);
219 
220         // Functional delay is optional and defaults to 0
221         size_t funcDelay = 0;
222         if (fan.contains("functional_delay"))
223         {
224             funcDelay = fan["functional_delay"].get<size_t>();
225         }
226 
227         // Method is optional and defaults to time based functional
228         // determination
229         size_t method = MethodMode::timebased;
230         size_t countInterval = 1;
231         if (fan.contains("method"))
232         {
233             auto methodConf = fan["method"].get<std::string>();
234             auto methodFunc = methods.find(methodConf);
235             if (methodFunc != methods.end())
236             {
237                 method = methodFunc->second;
238             }
239             else
240             {
241                 // Log error on unsupported method parameter
242                 log<level::ERR>("Invalid fan method");
243                 throw std::runtime_error("Invalid fan method");
244             }
245 
246             // Read the count interval value used with the count method.
247             if (method == MethodMode::count)
248             {
249                 if (fan.contains("count_interval"))
250                 {
251                     countInterval = fan["count_interval"].get<size_t>();
252                 }
253             }
254         }
255 
256         // Timeout defaults to 0
257         size_t timeout = 0;
258         if (method == MethodMode::timebased)
259         {
260             if (!fan.contains("allowed_out_of_range_time"))
261             {
262                 // Log error on missing required parameter
263                 log<level::ERR>(
264                     "Missing required fan monitor definition parameters",
265                     entry("REQUIRED_PARAMETER=%s",
266                           "{allowed_out_of_range_time}"));
267                 throw std::runtime_error(
268                     "Missing required fan monitor definition parameters");
269             }
270             else
271             {
272                 timeout = fan["allowed_out_of_range_time"].get<size_t>();
273             }
274         }
275 
276         // Monitor start delay is optional and defaults to 0
277         size_t monitorDelay = 0;
278         if (fan.contains("monitor_start_delay"))
279         {
280             monitorDelay = fan["monitor_start_delay"].get<size_t>();
281         }
282 
283         // num_sensors_nonfunc_for_fan_nonfunc is optional and defaults
284         // to zero if not present, meaning the code will not set the
285         // parent fan to nonfunctional based on sensors.
286         size_t nonfuncSensorsCount = 0;
287         if (fan.contains("num_sensors_nonfunc_for_fan_nonfunc"))
288         {
289             nonfuncSensorsCount =
290                 fan["num_sensors_nonfunc_for_fan_nonfunc"].get<size_t>();
291         }
292 
293         // nonfunc_rotor_error_delay is optional, though it will
294         // default to zero if 'fault_handling' is present.
295         std::optional<size_t> nonfuncRotorErrorDelay;
296         if (fan.contains("nonfunc_rotor_error_delay"))
297         {
298             nonfuncRotorErrorDelay =
299                 fan["nonfunc_rotor_error_delay"].get<size_t>();
300         }
301         else if (obj.contains("fault_handling"))
302         {
303             nonfuncRotorErrorDelay = 0;
304         }
305 
306         // fan_missing_error_delay is optional.
307         std::optional<size_t> fanMissingErrorDelay;
308         if (fan.contains("fan_missing_error_delay"))
309         {
310             fanMissingErrorDelay =
311                 fan.at("fan_missing_error_delay").get<size_t>();
312         }
313 
314         // Handle optional conditions
315         auto cond = std::optional<Condition>();
316         if (fan.contains("condition"))
317         {
318             if (!fan["condition"].contains("name"))
319             {
320                 // Log error on missing required parameter
321                 log<level::ERR>(
322                     "Missing required fan monitor condition parameter",
323                     entry("REQUIRED_PARAMETER=%s", "{name}"));
324                 throw std::runtime_error(
325                     "Missing required fan monitor condition parameter");
326             }
327             auto name = fan["condition"]["name"].get<std::string>();
328             // The function for fan monitoring condition
329             // (Must have a supported function within the condition namespace)
330             std::transform(name.begin(), name.end(), name.begin(), tolower);
331             auto handler = conditions.find(name);
332             if (handler != conditions.end())
333             {
334                 cond = handler->second(fan["condition"]);
335             }
336             else
337             {
338                 log<level::INFO>(
339                     "No handler found for configured condition",
340                     entry("CONDITION_NAME=%s", name.c_str()),
341                     entry("JSON_DUMP=%s", fan["condition"].dump().c_str()));
342             }
343         }
344 
345         // if the fan should be set to functional when plugged in
346         bool setFuncOnPresent = false;
347         if (fan.contains("set_func_on_present"))
348         {
349             setFuncOnPresent = fan["set_func_on_present"].get<bool>();
350         }
351 
352         fanDefs.emplace_back(std::tuple(
353             fan["inventory"].get<std::string>(), method, funcDelay, timeout,
354             deviation, nonfuncSensorsCount, monitorDelay, countInterval,
355             nonfuncRotorErrorDelay, fanMissingErrorDelay, sensorDefs, cond,
356             setFuncOnPresent));
357     }
358 
359     return fanDefs;
360 }
361 
362 PowerRuleState getPowerOffPowerRuleState(const json& powerOffConfig)
363 {
364     // The state is optional and defaults to runtime
365     PowerRuleState ruleState{PowerRuleState::runtime};
366 
367     if (powerOffConfig.contains("state"))
368     {
369         auto state = powerOffConfig.at("state").get<std::string>();
370         if (state == "at_pgood")
371         {
372             ruleState = PowerRuleState::atPgood;
373         }
374         else if (state != "runtime")
375         {
376             auto msg = fmt::format("Invalid power off state entry {}", state);
377             log<level::ERR>(msg.c_str());
378             throw std::runtime_error(msg.c_str());
379         }
380     }
381 
382     return ruleState;
383 }
384 
385 std::unique_ptr<PowerOffCause> getPowerOffCause(const json& powerOffConfig)
386 {
387     std::unique_ptr<PowerOffCause> cause;
388 
389     if (!powerOffConfig.contains("count") || !powerOffConfig.contains("cause"))
390     {
391         const auto msg =
392             "Missing 'count' or 'cause' entries in power off config";
393         log<level::ERR>(msg);
394         throw std::runtime_error(msg);
395     }
396 
397     auto count = powerOffConfig.at("count").get<size_t>();
398     auto powerOffCause = powerOffConfig.at("cause").get<std::string>();
399 
400     const std::map<std::string, std::function<std::unique_ptr<PowerOffCause>()>>
401         causes{
402             {"missing_fan_frus",
403              [count]() { return std::make_unique<MissingFanFRUCause>(count); }},
404             {"nonfunc_fan_rotors", [count]() {
405                  return std::make_unique<NonfuncFanRotorCause>(count);
406              }}};
407 
408     auto it = causes.find(powerOffCause);
409     if (it != causes.end())
410     {
411         cause = it->second();
412     }
413     else
414     {
415         auto msg =
416             fmt::format("Invalid power off cause {} in power off config JSON",
417                         powerOffCause);
418         log<level::ERR>(msg.c_str());
419         throw std::runtime_error(msg.c_str());
420     }
421 
422     return cause;
423 }
424 
425 std::unique_ptr<PowerOffAction>
426     getPowerOffAction(const json& powerOffConfig,
427                       std::shared_ptr<PowerInterfaceBase>& powerInterface,
428                       PowerOffAction::PrePowerOffFunc& func)
429 {
430     std::unique_ptr<PowerOffAction> action;
431     if (!powerOffConfig.contains("type"))
432     {
433         const auto msg = "Missing 'type' entry in power off config";
434         log<level::ERR>(msg);
435         throw std::runtime_error(msg);
436     }
437 
438     auto type = powerOffConfig.at("type").get<std::string>();
439 
440     if (((type == "hard") || (type == "soft")) &&
441         !powerOffConfig.contains("delay"))
442     {
443         const auto msg = "Missing 'delay' entry in power off config";
444         log<level::ERR>(msg);
445         throw std::runtime_error(msg);
446     }
447     else if ((type == "epow") &&
448              (!powerOffConfig.contains("service_mode_delay") ||
449               !powerOffConfig.contains("meltdown_delay")))
450     {
451         const auto msg = "Missing 'service_mode_delay' or 'meltdown_delay' "
452                          "entry in power off config";
453         log<level::ERR>(msg);
454         throw std::runtime_error(msg);
455     }
456 
457     if (type == "hard")
458     {
459         action = std::make_unique<HardPowerOff>(
460             powerOffConfig.at("delay").get<uint32_t>(), powerInterface, func);
461     }
462     else if (type == "soft")
463     {
464         action = std::make_unique<SoftPowerOff>(
465             powerOffConfig.at("delay").get<uint32_t>(), powerInterface, func);
466     }
467     else if (type == "epow")
468     {
469         action = std::make_unique<EpowPowerOff>(
470             powerOffConfig.at("service_mode_delay").get<uint32_t>(),
471             powerOffConfig.at("meltdown_delay").get<uint32_t>(), powerInterface,
472             func);
473     }
474     else
475     {
476         auto msg = fmt::format("Invalid 'type' entry {} in power off config",
477                                type);
478         log<level::ERR>(msg.c_str());
479         throw std::runtime_error(msg.c_str());
480     }
481 
482     return action;
483 }
484 
485 std::vector<std::unique_ptr<PowerOffRule>>
486     getPowerOffRules(const json& obj,
487                      std::shared_ptr<PowerInterfaceBase>& powerInterface,
488                      PowerOffAction::PrePowerOffFunc& func)
489 {
490     std::vector<std::unique_ptr<PowerOffRule>> rules;
491 
492     if (!(obj.contains("fault_handling") &&
493           obj.at("fault_handling").contains("power_off_config")))
494     {
495         return rules;
496     }
497 
498     for (const auto& config : obj.at("fault_handling").at("power_off_config"))
499     {
500         auto state = getPowerOffPowerRuleState(config);
501         auto cause = getPowerOffCause(config);
502         auto action = getPowerOffAction(config, powerInterface, func);
503 
504         auto rule = std::make_unique<PowerOffRule>(
505             std::move(state), std::move(cause), std::move(action));
506         rules.push_back(std::move(rule));
507     }
508 
509     return rules;
510 }
511 
512 std::optional<size_t> getNumNonfuncRotorsBeforeError(const json& obj)
513 {
514     std::optional<size_t> num;
515 
516     if (obj.contains("fault_handling"))
517     {
518         // Defaults to 1 if not present inside of 'fault_handling'.
519         num = obj.at("fault_handling")
520                   .value("num_nonfunc_rotors_before_error", 1);
521     }
522 
523     return num;
524 }
525 
526 } // namespace phosphor::fan::monitor
527