11a568650SJolie Ku /**
21a568650SJolie Ku  * Copyright © 2019 IBM Corporation
31a568650SJolie Ku  *
41a568650SJolie Ku  * Licensed under the Apache License, Version 2.0 (the "License");
51a568650SJolie Ku  * you may not use this file except in compliance with the License.
61a568650SJolie Ku  * You may obtain a copy of the License at
71a568650SJolie Ku  *
81a568650SJolie Ku  *     http://www.apache.org/licenses/LICENSE-2.0
91a568650SJolie Ku  *
101a568650SJolie Ku  * Unless required by applicable law or agreed to in writing, software
111a568650SJolie Ku  * distributed under the License is distributed on an "AS IS" BASIS,
121a568650SJolie Ku  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
131a568650SJolie Ku  * See the License for the specific language governing permissions and
141a568650SJolie Ku  * limitations under the License.
151a568650SJolie Ku  */
161a568650SJolie Ku #include "json_parser.hpp"
171a568650SJolie Ku 
181a568650SJolie Ku #include "anyof.hpp"
191a568650SJolie Ku #include "fallback.hpp"
201a568650SJolie Ku #include "gpio.hpp"
211a568650SJolie Ku #include "json_config.hpp"
221a568650SJolie Ku #include "sdbusplus.hpp"
231a568650SJolie Ku #include "tach.hpp"
241a568650SJolie Ku 
251a568650SJolie Ku #include <nlohmann/json.hpp>
261a568650SJolie Ku #include <phosphor-logging/log.hpp>
271a568650SJolie Ku #include <sdbusplus/bus.hpp>
28a35a890bSMike Capps #include <xyz/openbmc_project/Logging/Create/server.hpp>
29a35a890bSMike Capps #include <xyz/openbmc_project/Logging/Entry/server.hpp>
301a568650SJolie Ku 
311a568650SJolie Ku #include <filesystem>
321a568650SJolie Ku #include <fstream>
331a568650SJolie Ku #include <string>
341a568650SJolie Ku 
351a568650SJolie Ku namespace phosphor
361a568650SJolie Ku {
371a568650SJolie Ku namespace fan
381a568650SJolie Ku {
391a568650SJolie Ku namespace presence
401a568650SJolie Ku {
411a568650SJolie Ku 
421a568650SJolie Ku using json = nlohmann::json;
431a568650SJolie Ku namespace fs = std::filesystem;
441a568650SJolie Ku using namespace phosphor::logging;
451a568650SJolie Ku 
461a568650SJolie Ku policies JsonConfig::_policies;
471a568650SJolie Ku const std::map<std::string, methodHandler> JsonConfig::_methods = {
481a568650SJolie Ku     {"tach", method::getTach}, {"gpio", method::getGpio}};
491a568650SJolie Ku const std::map<std::string, rpolicyHandler> JsonConfig::_rpolicies = {
501a568650SJolie Ku     {"anyof", rpolicy::getAnyof}, {"fallback", rpolicy::getFallback}};
511a568650SJolie Ku 
52a35a890bSMike Capps const auto loggingPath = "/xyz/openbmc_project/logging";
53a35a890bSMike Capps const auto loggingCreateIface = "xyz.openbmc_project.Logging.Create";
54a35a890bSMike Capps 
55cb356d48SPatrick Williams JsonConfig::JsonConfig(sdbusplus::bus_t& bus) : _bus(bus)
560daedd18SMatt Spinler {}
571a568650SJolie Ku 
585b839919SMatthew Barth void JsonConfig::start()
590daedd18SMatt Spinler {
605b839919SMatthew Barth     using config = fan::JsonConfig;
615b839919SMatthew Barth 
62dfc8c4d0SMatt Spinler     if (!_loaded)
63dfc8c4d0SMatt Spinler     {
64808d7fe8SMike Capps         process(config::load(config::getConfFile(confAppName, confFileName)));
65dfc8c4d0SMatt Spinler 
66dfc8c4d0SMatt Spinler         _loaded = true;
670daedd18SMatt Spinler 
680daedd18SMatt Spinler         for (auto& p : _policies)
690daedd18SMatt Spinler         {
700daedd18SMatt Spinler             p->monitor();
710daedd18SMatt Spinler         }
721a568650SJolie Ku     }
73dfc8c4d0SMatt Spinler }
741a568650SJolie Ku 
751a568650SJolie Ku const policies& JsonConfig::get()
761a568650SJolie Ku {
771a568650SJolie Ku     return _policies;
781a568650SJolie Ku }
791a568650SJolie Ku 
80808d7fe8SMike Capps void JsonConfig::sighupHandler(sdeventplus::source::Signal& /*sigSrc*/,
81808d7fe8SMike Capps                                const struct signalfd_siginfo* /*sigInfo*/)
821a568650SJolie Ku {
831a568650SJolie Ku     try
841a568650SJolie Ku     {
851a568650SJolie Ku         using config = fan::JsonConfig;
861a568650SJolie Ku 
879e9f599cSMatt Spinler         _reporter.reset();
889e9f599cSMatt Spinler 
891a568650SJolie Ku         // Load and process the json configuration
90808d7fe8SMike Capps         process(config::load(config::getConfFile(confAppName, confFileName)));
911a568650SJolie Ku 
921a568650SJolie Ku         for (auto& p : _policies)
931a568650SJolie Ku         {
941a568650SJolie Ku             p->monitor();
951a568650SJolie Ku         }
961a568650SJolie Ku         log<level::INFO>("Configuration loaded successfully");
971a568650SJolie Ku     }
98ddb773b2SPatrick Williams     catch (const std::runtime_error& re)
991a568650SJolie Ku     {
1001a568650SJolie Ku         log<level::ERR>("Error loading config, no config changes made",
1011a568650SJolie Ku                         entry("LOAD_ERROR=%s", re.what()));
1021a568650SJolie Ku     }
1031a568650SJolie Ku }
1041a568650SJolie Ku 
1051a568650SJolie Ku void JsonConfig::process(const json& jsonConf)
1061a568650SJolie Ku {
1071a568650SJolie Ku     policies policies;
1081a568650SJolie Ku     std::vector<fanPolicy> fans;
1091a568650SJolie Ku     // Set the expected number of fan entries
1101a568650SJolie Ku     // to be size of the list of fan json config entries
1111a568650SJolie Ku     // (Must be done to eliminate vector reallocation of fan references)
1129e9f599cSMatt Spinler     fans.reserve(jsonConf.size());
1139e9f599cSMatt Spinler     for (auto& member : jsonConf)
1141a568650SJolie Ku     {
1151a568650SJolie Ku         if (!member.contains("name") || !member.contains("path") ||
1161a568650SJolie Ku             !member.contains("methods") || !member.contains("rpolicy"))
1171a568650SJolie Ku         {
1181a568650SJolie Ku             log<level::ERR>("Missing required fan presence properties",
1191a568650SJolie Ku                             entry("REQUIRED_PROPERTIES=%s",
1201a568650SJolie Ku                                   "{name, path, methods, rpolicy}"));
1211a568650SJolie Ku             throw std::runtime_error(
1221a568650SJolie Ku                 "Missing required fan presence properties");
1231a568650SJolie Ku         }
1241a568650SJolie Ku 
1251a568650SJolie Ku         // Loop thru the configured methods of presence detection
1261a568650SJolie Ku         std::vector<std::unique_ptr<PresenceSensor>> sensors;
1271a568650SJolie Ku         for (auto& method : member["methods"].items())
1281a568650SJolie Ku         {
1291a568650SJolie Ku             if (!method.value().contains("type"))
1301a568650SJolie Ku             {
1311a568650SJolie Ku                 log<level::ERR>(
1321a568650SJolie Ku                     "Missing required fan presence method type",
1331a568650SJolie Ku                     entry("FAN_NAME=%s",
1341a568650SJolie Ku                           member["name"].get<std::string>().c_str()));
1351a568650SJolie Ku                 throw std::runtime_error(
1361a568650SJolie Ku                     "Missing required fan presence method type");
1371a568650SJolie Ku             }
1381a568650SJolie Ku             // The method type of fan presence detection
1391a568650SJolie Ku             // (Must have a supported function within the method namespace)
1401a568650SJolie Ku             auto type = method.value()["type"].get<std::string>();
1411a568650SJolie Ku             std::transform(type.begin(), type.end(), type.begin(), tolower);
1421a568650SJolie Ku             auto func = _methods.find(type);
1431a568650SJolie Ku             if (func != _methods.end())
1441a568650SJolie Ku             {
1451a568650SJolie Ku                 // Call function for method type
1461a568650SJolie Ku                 auto sensor = func->second(fans.size(), method.value());
1471a568650SJolie Ku                 if (sensor)
1481a568650SJolie Ku                 {
1491a568650SJolie Ku                     sensors.emplace_back(std::move(sensor));
1501a568650SJolie Ku                 }
1511a568650SJolie Ku             }
1521a568650SJolie Ku             else
1531a568650SJolie Ku             {
1541a568650SJolie Ku                 log<level::ERR>(
1551a568650SJolie Ku                     "Invalid fan presence method type",
1561a568650SJolie Ku                     entry("FAN_NAME=%s",
1571a568650SJolie Ku                           member["name"].get<std::string>().c_str()),
1581a568650SJolie Ku                     entry("METHOD_TYPE=%s", type.c_str()));
1591a568650SJolie Ku                 throw std::runtime_error("Invalid fan presence method type");
1601a568650SJolie Ku             }
1611a568650SJolie Ku         }
1629e9f599cSMatt Spinler 
1639e9f599cSMatt Spinler         // Get the amount of time a fan must be not present before
1649e9f599cSMatt Spinler         // creating an error.
1659e9f599cSMatt Spinler         std::optional<size_t> timeUntilError;
1669e9f599cSMatt Spinler         if (member.contains("fan_missing_error_time"))
1679e9f599cSMatt Spinler         {
1689e9f599cSMatt Spinler             timeUntilError = member["fan_missing_error_time"].get<size_t>();
1699e9f599cSMatt Spinler         }
1709e9f599cSMatt Spinler 
171*bc4179e9SMatt Spinler         std::unique_ptr<EEPROMDevice> eepromDevice;
172*bc4179e9SMatt Spinler         if (member.contains("eeprom"))
173*bc4179e9SMatt Spinler         {
174*bc4179e9SMatt Spinler             const auto& eeprom = member.at("eeprom");
175*bc4179e9SMatt Spinler             if (!eeprom.contains("bus_address") ||
176*bc4179e9SMatt Spinler                 !eeprom.contains("driver_name") ||
177*bc4179e9SMatt Spinler                 !eeprom.contains("bind_delay_ms"))
178*bc4179e9SMatt Spinler             {
179*bc4179e9SMatt Spinler                 log<level::ERR>(
180*bc4179e9SMatt Spinler                     "Missing address, driver_name, or bind_delay_ms in eeprom "
181*bc4179e9SMatt Spinler                     "section",
182*bc4179e9SMatt Spinler                     entry("FAN_NAME=%s",
183*bc4179e9SMatt Spinler                           member["name"].get<std::string>().c_str()));
184*bc4179e9SMatt Spinler 
185*bc4179e9SMatt Spinler                 throw std::runtime_error("Missing address, driver_name, or "
186*bc4179e9SMatt Spinler                                          "bind_delay_ms in eeprom section");
187*bc4179e9SMatt Spinler             }
188*bc4179e9SMatt Spinler             eepromDevice = std::make_unique<EEPROMDevice>(
189*bc4179e9SMatt Spinler                 eeprom["bus_address"].get<std::string>(),
190*bc4179e9SMatt Spinler                 eeprom["driver_name"].get<std::string>(),
191*bc4179e9SMatt Spinler                 eeprom["bind_delay_ms"].get<size_t>());
192*bc4179e9SMatt Spinler         }
193*bc4179e9SMatt Spinler 
1949e9f599cSMatt Spinler         auto fan =
1959e9f599cSMatt Spinler             std::make_tuple(member["name"], member["path"], timeUntilError);
1961a568650SJolie Ku         // Create a fan object
1971a568650SJolie Ku         fans.emplace_back(std::make_tuple(fan, std::move(sensors)));
1981a568650SJolie Ku 
1991a568650SJolie Ku         // Add fan presence policy
200*bc4179e9SMatt Spinler         auto policy =
201*bc4179e9SMatt Spinler             getPolicy(member["rpolicy"], fans.back(), std::move(eepromDevice));
2021a568650SJolie Ku         if (policy)
2031a568650SJolie Ku         {
2041a568650SJolie Ku             policies.emplace_back(std::move(policy));
2051a568650SJolie Ku         }
2061a568650SJolie Ku     }
2071a568650SJolie Ku 
2081a568650SJolie Ku     // Success, refresh fans and policies lists
2091a568650SJolie Ku     _fans.clear();
2101a568650SJolie Ku     _fans.swap(fans);
2111a568650SJolie Ku 
2121a568650SJolie Ku     _policies.clear();
2131a568650SJolie Ku     _policies.swap(policies);
214e8122390SMatt Spinler 
215e8122390SMatt Spinler     // Create the error reporter class if necessary
2169e9f599cSMatt Spinler     if (std::any_of(_fans.begin(), _fans.end(), [](const auto& fan) {
2179e9f599cSMatt Spinler             return std::get<std::optional<size_t>>(std::get<Fan>(fan)) !=
2189e9f599cSMatt Spinler                    std::nullopt;
2199e9f599cSMatt Spinler         }))
220e8122390SMatt Spinler     {
2219e9f599cSMatt Spinler         _reporter = std::make_unique<ErrorReporter>(_bus, _fans);
222e8122390SMatt Spinler     }
2231a568650SJolie Ku }
2241a568650SJolie Ku 
2251a568650SJolie Ku std::unique_ptr<RedundancyPolicy>
226*bc4179e9SMatt Spinler     JsonConfig::getPolicy(const json& rpolicy, const fanPolicy& fpolicy,
227*bc4179e9SMatt Spinler                           std::unique_ptr<EEPROMDevice> eepromDevice)
2281a568650SJolie Ku {
2291a568650SJolie Ku     if (!rpolicy.contains("type"))
2301a568650SJolie Ku     {
2311a568650SJolie Ku         log<level::ERR>(
2321a568650SJolie Ku             "Missing required fan presence policy type",
2331a568650SJolie Ku             entry("FAN_NAME=%s",
2341a568650SJolie Ku                   std::get<fanPolicyFanPos>(std::get<Fan>(fpolicy)).c_str()),
2351a568650SJolie Ku             entry("REQUIRED_PROPERTIES=%s", "{type}"));
2361a568650SJolie Ku         throw std::runtime_error("Missing required fan presence policy type");
2371a568650SJolie Ku     }
2381a568650SJolie Ku 
2391a568650SJolie Ku     // The redundancy policy type for fan presence detection
2401a568650SJolie Ku     // (Must have a supported function within the rpolicy namespace)
2411a568650SJolie Ku     auto type = rpolicy["type"].get<std::string>();
2421a568650SJolie Ku     std::transform(type.begin(), type.end(), type.begin(), tolower);
2431a568650SJolie Ku     auto func = _rpolicies.find(type);
2441a568650SJolie Ku     if (func != _rpolicies.end())
2451a568650SJolie Ku     {
2461a568650SJolie Ku         // Call function for redundancy policy type and return the policy
247*bc4179e9SMatt Spinler         return func->second(fpolicy, std::move(eepromDevice));
2481a568650SJolie Ku     }
2491a568650SJolie Ku     else
2501a568650SJolie Ku     {
2511a568650SJolie Ku         log<level::ERR>(
2521a568650SJolie Ku             "Invalid fan presence policy type",
2531a568650SJolie Ku             entry("FAN_NAME=%s",
2541a568650SJolie Ku                   std::get<fanPolicyFanPos>(std::get<Fan>(fpolicy)).c_str()),
2551a568650SJolie Ku             entry("RPOLICY_TYPE=%s", type.c_str()));
2561a568650SJolie Ku         throw std::runtime_error("Invalid fan presence methods policy type");
2571a568650SJolie Ku     }
2581a568650SJolie Ku }
2591a568650SJolie Ku 
2601a568650SJolie Ku /**
2611a568650SJolie Ku  * Methods of fan presence detection function definitions
2621a568650SJolie Ku  */
2631a568650SJolie Ku namespace method
2641a568650SJolie Ku {
2651a568650SJolie Ku // Get a constructed presence sensor for fan presence detection by tach
2661a568650SJolie Ku std::unique_ptr<PresenceSensor> getTach(size_t fanIndex, const json& method)
2671a568650SJolie Ku {
2681a568650SJolie Ku     if (!method.contains("sensors") || method["sensors"].size() == 0)
2691a568650SJolie Ku     {
2701a568650SJolie Ku         log<level::ERR>("Missing required tach method properties",
2711a568650SJolie Ku                         entry("FAN_ENTRY=%d", fanIndex),
2721a568650SJolie Ku                         entry("REQUIRED_PROPERTIES=%s", "{sensors}"));
2731a568650SJolie Ku         throw std::runtime_error("Missing required tach method properties");
2741a568650SJolie Ku     }
2751a568650SJolie Ku 
2761a568650SJolie Ku     std::vector<std::string> sensors;
2771a568650SJolie Ku     for (auto& sensor : method["sensors"])
2781a568650SJolie Ku     {
2791a568650SJolie Ku         sensors.emplace_back(sensor.get<std::string>());
2801a568650SJolie Ku     }
2811a568650SJolie Ku 
2821a568650SJolie Ku     return std::make_unique<PolicyAccess<Tach, JsonConfig>>(fanIndex,
2831a568650SJolie Ku                                                             std::move(sensors));
2841a568650SJolie Ku }
2851a568650SJolie Ku 
2861a568650SJolie Ku // Get a constructed presence sensor for fan presence detection by gpio
2871a568650SJolie Ku std::unique_ptr<PresenceSensor> getGpio(size_t fanIndex, const json& method)
2881a568650SJolie Ku {
2891a568650SJolie Ku     if (!method.contains("physpath") || !method.contains("devpath") ||
2901a568650SJolie Ku         !method.contains("key"))
2911a568650SJolie Ku     {
2921a568650SJolie Ku         log<level::ERR>(
2931a568650SJolie Ku             "Missing required gpio method properties",
2941a568650SJolie Ku             entry("FAN_ENTRY=%d", fanIndex),
2951a568650SJolie Ku             entry("REQUIRED_PROPERTIES=%s", "{physpath, devpath, key}"));
2961a568650SJolie Ku         throw std::runtime_error("Missing required gpio method properties");
2971a568650SJolie Ku     }
2981a568650SJolie Ku 
2991a568650SJolie Ku     auto physpath = method["physpath"].get<std::string>();
3001a568650SJolie Ku     auto devpath = method["devpath"].get<std::string>();
3011a568650SJolie Ku     auto key = method["key"].get<unsigned int>();
3021a568650SJolie Ku 
303a35a890bSMike Capps     try
304a35a890bSMike Capps     {
305a35a890bSMike Capps         return std::make_unique<PolicyAccess<Gpio, JsonConfig>>(
306a35a890bSMike Capps             fanIndex, physpath, devpath, key);
307a35a890bSMike Capps     }
308a35a890bSMike Capps     catch (const sdbusplus::exception_t& e)
309a35a890bSMike Capps     {
310a35a890bSMike Capps         namespace sdlogging = sdbusplus::xyz::openbmc_project::Logging::server;
311a35a890bSMike Capps 
312a35a890bSMike Capps         log<level::ERR>(
313a35a890bSMike Capps             fmt::format(
314a35a890bSMike Capps                 "Error creating Gpio device bridge, hardware not detected: {}",
315a35a890bSMike Capps                 e.what())
316a35a890bSMike Capps                 .c_str());
317a35a890bSMike Capps 
318a35a890bSMike Capps         auto severity =
319a35a890bSMike Capps             sdlogging::convertForMessage(sdlogging::Entry::Level::Error);
320a35a890bSMike Capps 
321a35a890bSMike Capps         std::map<std::string, std::string> additionalData{
322a35a890bSMike Capps             {"PHYSPATH", physpath},
323a35a890bSMike Capps             {"DEVPATH", devpath},
324a35a890bSMike Capps             {"FANINDEX", std::to_string(fanIndex)}};
325a35a890bSMike Capps 
326a35a890bSMike Capps         try
327a35a890bSMike Capps         {
328a35a890bSMike Capps 
329a35a890bSMike Capps             util::SDBusPlus::lookupAndCallMethod(
330a35a890bSMike Capps                 loggingPath, loggingCreateIface, "Create",
331a35a890bSMike Capps                 "xyz.openbmc_project.Fan.Presence.Error.GPIODeviceUnavailable",
332a35a890bSMike Capps                 severity, additionalData);
333a35a890bSMike Capps         }
334a35a890bSMike Capps         catch (const util::DBusError& e)
335a35a890bSMike Capps         {
336a35a890bSMike Capps             log<level::ERR>(fmt::format("Call to create an error log for "
337a35a890bSMike Capps                                         "presence-sensor failure failed: {}",
338a35a890bSMike Capps                                         e.what())
339a35a890bSMike Capps                                 .c_str());
340a35a890bSMike Capps         }
341a35a890bSMike Capps 
342a35a890bSMike Capps         return std::make_unique<PolicyAccess<NullGpio, JsonConfig>>();
343a35a890bSMike Capps     }
3441a568650SJolie Ku }
3451a568650SJolie Ku 
3461a568650SJolie Ku } // namespace method
3471a568650SJolie Ku 
3481a568650SJolie Ku /**
3491a568650SJolie Ku  * Redundancy policies for fan presence detection function definitions
3501a568650SJolie Ku  */
3511a568650SJolie Ku namespace rpolicy
3521a568650SJolie Ku {
3531a568650SJolie Ku // Get an `Anyof` redundancy policy for the fan
354*bc4179e9SMatt Spinler std::unique_ptr<RedundancyPolicy>
355*bc4179e9SMatt Spinler     getAnyof(const fanPolicy& fan, std::unique_ptr<EEPROMDevice> eepromDevice)
3561a568650SJolie Ku {
3571a568650SJolie Ku     std::vector<std::reference_wrapper<PresenceSensor>> pSensors;
3581a568650SJolie Ku     for (auto& fanSensor : std::get<fanPolicySensorListPos>(fan))
3591a568650SJolie Ku     {
3601a568650SJolie Ku         pSensors.emplace_back(*fanSensor);
3611a568650SJolie Ku     }
3621a568650SJolie Ku 
363*bc4179e9SMatt Spinler     return std::make_unique<AnyOf>(std::get<fanPolicyFanPos>(fan), pSensors,
364*bc4179e9SMatt Spinler                                    std::move(eepromDevice));
3651a568650SJolie Ku }
3661a568650SJolie Ku 
3671a568650SJolie Ku // Get a `Fallback` redundancy policy for the fan
368*bc4179e9SMatt Spinler std::unique_ptr<RedundancyPolicy>
369*bc4179e9SMatt Spinler     getFallback(const fanPolicy& fan,
370*bc4179e9SMatt Spinler                 std::unique_ptr<EEPROMDevice> eepromDevice)
3711a568650SJolie Ku {
3721a568650SJolie Ku     std::vector<std::reference_wrapper<PresenceSensor>> pSensors;
3731a568650SJolie Ku     for (auto& fanSensor : std::get<fanPolicySensorListPos>(fan))
3741a568650SJolie Ku     {
3751a568650SJolie Ku         // Place in the order given to fallback correctly
3761a568650SJolie Ku         pSensors.emplace_back(*fanSensor);
3771a568650SJolie Ku     }
3781a568650SJolie Ku 
379*bc4179e9SMatt Spinler     return std::make_unique<Fallback>(std::get<fanPolicyFanPos>(fan), pSensors,
380*bc4179e9SMatt Spinler                                       std::move(eepromDevice));
3811a568650SJolie Ku }
3821a568650SJolie Ku 
3831a568650SJolie Ku } // namespace rpolicy
3841a568650SJolie Ku 
3851a568650SJolie Ku } // namespace presence
3861a568650SJolie Ku } // namespace fan
3871a568650SJolie Ku } // namespace phosphor
388