blob: fcb603f6d102e4bbe7cbfafbd18cabe8d731aba9 [file] [log] [blame]
Matthew Barth11547c92020-05-05 10:34:27 -05001/**
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#pragma once
17
18#include "sdbusplus.hpp"
19
Matthew Barth1826c732020-08-28 08:40:59 -050020#include <fmt/format.h>
21
Matthew Barth11547c92020-05-05 10:34:27 -050022#include <nlohmann/json.hpp>
23#include <phosphor-logging/log.hpp>
24#include <sdbusplus/bus.hpp>
25#include <sdeventplus/source/signal.hpp>
26
27#include <filesystem>
28#include <fstream>
29
30namespace phosphor::fan
31{
32
33namespace fs = std::filesystem;
34using json = nlohmann::json;
35using namespace phosphor::logging;
36
37constexpr auto confOverridePath = "/etc/phosphor-fan-presence";
38constexpr auto confBasePath = "/usr/share/phosphor-fan-presence";
Matthew Barthb370ab32021-06-10 14:38:02 -050039constexpr auto confCompatServ = "xyz.openbmc_project.EntityManager";
Matthew Barthfcbdc0e2020-10-28 14:11:07 -050040constexpr auto confCompatIntf =
41 "xyz.openbmc_project.Configuration.IBMCompatibleSystem";
42constexpr auto confCompatProp = "Names";
Matthew Barth11547c92020-05-05 10:34:27 -050043
Matthew Barth6eb603e2021-09-01 09:01:57 -050044/**
45 * @class NoConfigFound - A no JSON configuration found exception
46 *
47 * A no JSON configuration found exception that is used to denote that a JSON
48 * configuration has not been found yet.
49 */
50class NoConfigFound : public std::runtime_error
51{
52 public:
53 NoConfigFound() = delete;
54 NoConfigFound(const NoConfigFound&) = delete;
55 NoConfigFound(NoConfigFound&&) = delete;
56 NoConfigFound& operator=(const NoConfigFound&) = delete;
57 NoConfigFound& operator=(NoConfigFound&&) = delete;
58 ~NoConfigFound() = default;
59
60 /**
61 * @brief No JSON configuration found exception object
62 *
63 * When attempting to find the JSON configuration file(s), a NoConfigFound
64 * exception can be thrown to denote that at that time finding/loading the
65 * JSON configuration file(s) for a fan application failed. Details on what
66 * application and JSON configuration file that failed to be found will be
67 * logged resulting in the application being terminated.
68 *
69 * @param[in] details - Additional details
70 */
71 NoConfigFound(const std::string& appName, const std::string& fileName) :
72 std::runtime_error(fmt::format("JSON configuration not found [Could "
73 "not find fan {} conf file {}]",
74 appName, fileName)
75 .c_str())
76 {}
77};
78
Matthew Barth11547c92020-05-05 10:34:27 -050079class JsonConfig
80{
81 public:
Matt Spinler59850df2021-01-06 16:56:06 -060082 /**
Matthew Barthd80c8752021-06-01 14:46:02 -050083 * @brief Get the object paths with the compatible interface
84 *
85 * Retrieve all the object paths implementing the compatible interface for
86 * configuration file loading.
87 */
88 static auto& getCompatObjPaths() __attribute__((pure))
89 {
90 static auto paths = util::SDBusPlus::getSubTreePathsRaw(
91 util::SDBusPlus::getBus(), "/", confCompatIntf, 0);
92 return paths;
93 }
94
95 /**
Matt Spinler59850df2021-01-06 16:56:06 -060096 * @brief Constructor
97 *
Matthew Barthb370ab32021-06-10 14:38:02 -050098 * Attempts to set the list of compatible values from the compatible
99 * interface and call the fan app's function to load its config file(s). If
100 * the compatible interface is not found, it subscribes to the
101 * interfacesAdded signal for that interface on the compatible service
102 * defined above.
103 *
104 * @param[in] func - Fan app function to call to load its config file(s)
105 */
106 JsonConfig(std::function<void()> func) : _loadFunc(func)
107 {
108 _match = std::make_unique<sdbusplus::server::match::match>(
109 util::SDBusPlus::getBus(),
110 sdbusplus::bus::match::rules::interfacesAdded() +
111 sdbusplus::bus::match::rules::sender(confCompatServ),
112 std::bind(&JsonConfig::compatIntfAdded, this,
113 std::placeholders::_1));
Matthew Barth1689cb62021-08-27 12:34:36 -0500114
115 auto compatObjPaths = getCompatObjPaths();
116 if (!compatObjPaths.empty())
Matthew Barthb370ab32021-06-10 14:38:02 -0500117 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500118 for (auto& path : compatObjPaths)
Matthew Barthb370ab32021-06-10 14:38:02 -0500119 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500120 try
Matthew Barthb370ab32021-06-10 14:38:02 -0500121 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500122 // Retrieve json config compatible relative path
123 // locations (last one found will be what's used if more
124 // than one dbus object implementing the comptaible
125 // interface exists).
126 _confCompatValues =
127 util::SDBusPlus::getProperty<std::vector<std::string>>(
128 util::SDBusPlus::getBus(), path, confCompatIntf,
129 confCompatProp);
Matthew Barthb370ab32021-06-10 14:38:02 -0500130 }
Matthew Barth1689cb62021-08-27 12:34:36 -0500131 catch (const util::DBusError&)
132 {
133 // Compatible property unavailable on this dbus object
134 // path's compatible interface, ignore
135 }
136 }
137 _loadFunc();
138 _match.reset();
139 }
140 else
141 {
142 // Check if required config(s) are found not needing the
143 // compatible interface, otherwise this is intended to catch the
144 // exception thrown by the getConfFile function when the
145 // required config file was not found. This would then result in
146 // waiting for the compatible interfacesAdded signal
147 try
148 {
Matthew Barthb370ab32021-06-10 14:38:02 -0500149 _loadFunc();
150 _match.reset();
151 }
Matthew Barth6eb603e2021-09-01 09:01:57 -0500152 catch (const NoConfigFound&)
Matthew Barthb370ab32021-06-10 14:38:02 -0500153 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500154 // Wait for compatible interfacesAdded signal
Matthew Barthb370ab32021-06-10 14:38:02 -0500155 }
156 }
Matthew Barthb370ab32021-06-10 14:38:02 -0500157 }
158
159 /**
Matthew Barthb370ab32021-06-10 14:38:02 -0500160 * @brief InterfacesAdded callback function for the compatible interface.
161 *
162 * @param[in] msg - The D-Bus message contents
163 *
164 * If the compatible interface is found, it uses the compatible property on
165 * the interface to set the list of compatible values to be used when
166 * attempting to get a configuration file. Once the list of compatible
167 * values has been updated, it calls the load function.
168 */
169 void compatIntfAdded(sdbusplus::message::message& msg)
170 {
171 sdbusplus::message::object_path op;
172 std::map<std::string,
173 std::map<std::string, std::variant<std::vector<std::string>>>>
174 intfProps;
175
176 msg.read(op, intfProps);
177
178 if (intfProps.find(confCompatIntf) == intfProps.end())
179 {
180 return;
181 }
182
183 const auto& props = intfProps.at(confCompatIntf);
184 // Only one dbus object with the compatible interface is used at a time
185 _confCompatValues =
186 std::get<std::vector<std::string>>(props.at(confCompatProp));
187 _loadFunc();
188 }
189
190 /**
Matthew Barth11547c92020-05-05 10:34:27 -0500191 * Get the json configuration file. The first location found to contain
192 * the json config file for the given fan application is used from the
193 * following locations in order.
194 * 1.) From the confOverridePath location
Matthew Barthb67089b2021-06-10 14:32:00 -0500195 * 2.) From the default confBasePath location
196 * 3.) From config file found using an entry from a list obtained from an
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500197 * interface's property as a relative path extension on the base path where:
198 * interface = Interface set in confCompatIntf with the property
199 * property = Property set in confCompatProp containing a list of
200 * subdirectories in priority order to find a config
Matthew Barth11547c92020-05-05 10:34:27 -0500201 *
202 * @brief Get the configuration file to be used
203 *
204 * @param[in] bus - The dbus bus object
205 * @param[in] appName - The phosphor-fan-presence application name
206 * @param[in] fileName - Application's configuration file's name
Matthew Barthb5991022020-08-05 11:08:50 -0500207 * @param[in] isOptional - Config file is optional, default to 'false'
Matthew Barth11547c92020-05-05 10:34:27 -0500208 *
209 * @return filesystem path
210 * The filesystem path to the configuration file to use
211 */
212 static const fs::path getConfFile(sdbusplus::bus::bus& bus,
213 const std::string& appName,
Matthew Barthb5991022020-08-05 11:08:50 -0500214 const std::string& fileName,
215 bool isOptional = false)
Matthew Barth11547c92020-05-05 10:34:27 -0500216 {
217 // Check override location
218 fs::path confFile = fs::path{confOverridePath} / appName / fileName;
219 if (fs::exists(confFile))
220 {
221 return confFile;
222 }
223
Matt Spinler59850df2021-01-06 16:56:06 -0600224 // If the default file is there, use it
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500225 confFile = fs::path{confBasePath} / appName / fileName;
Matt Spinler59850df2021-01-06 16:56:06 -0600226 if (fs::exists(confFile))
227 {
228 return confFile;
229 }
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500230
Matthew Barthb67089b2021-06-10 14:32:00 -0500231 // Look for a config file at each entry relative to the base
232 // path and use the first one found
233 auto it = std::find_if(
234 _confCompatValues.begin(), _confCompatValues.end(),
235 [&confFile, &appName, &fileName](const auto& value) {
236 confFile = fs::path{confBasePath} / appName / value / fileName;
237 return fs::exists(confFile);
238 });
239 if (it == _confCompatValues.end())
240 {
241 confFile.clear();
242 }
243
Matt Spinler59850df2021-01-06 16:56:06 -0600244 if (confFile.empty() && !isOptional)
Matthew Barth11547c92020-05-05 10:34:27 -0500245 {
Matthew Barth6eb603e2021-09-01 09:01:57 -0500246 throw NoConfigFound(appName, fileName);
Matthew Barthb5991022020-08-05 11:08:50 -0500247 }
Matthew Barth11547c92020-05-05 10:34:27 -0500248
249 return confFile;
250 }
251
252 /**
253 * @brief Load the JSON config file
254 *
255 * @param[in] confFile - File system path of the configuration file to load
256 *
257 * @return Parsed JSON object
258 * The parsed JSON configuration file object
259 */
260 static const json load(const fs::path& confFile)
261 {
262 std::ifstream file;
263 json jsonConf;
264
Matthew Barthb5991022020-08-05 11:08:50 -0500265 if (!confFile.empty() && fs::exists(confFile))
Matthew Barth11547c92020-05-05 10:34:27 -0500266 {
Matthew Barth1826c732020-08-28 08:40:59 -0500267 log<level::INFO>(
268 fmt::format("Loading configuration from {}", confFile.string())
269 .c_str());
Matthew Barth11547c92020-05-05 10:34:27 -0500270 file.open(confFile);
271 try
272 {
Matthew Barthde72d5d2021-07-16 10:39:42 -0500273 // Enable ignoring `//` or `/* */` comments
274 jsonConf = json::parse(file, nullptr, true, true);
Matthew Barth11547c92020-05-05 10:34:27 -0500275 }
276 catch (std::exception& e)
277 {
Matthew Barth1826c732020-08-28 08:40:59 -0500278 log<level::ERR>(
279 fmt::format(
280 "Failed to parse JSON config file: {}, error: {}",
281 confFile.string(), e.what())
282 .c_str());
283 throw std::runtime_error(
284 fmt::format(
285 "Failed to parse JSON config file: {}, error: {}",
286 confFile.string(), e.what())
287 .c_str());
Matthew Barth11547c92020-05-05 10:34:27 -0500288 }
289 }
290 else
291 {
Matthew Barth1826c732020-08-28 08:40:59 -0500292 log<level::ERR>(fmt::format("Unable to open JSON config file: {}",
293 confFile.string())
294 .c_str());
295 throw std::runtime_error(
296 fmt::format("Unable to open JSON config file: {}",
297 confFile.string())
298 .c_str());
Matthew Barth11547c92020-05-05 10:34:27 -0500299 }
300
301 return jsonConf;
302 }
Matt Spinler59850df2021-01-06 16:56:06 -0600303
304 private:
Matthew Barthb370ab32021-06-10 14:38:02 -0500305 /* Load function to call for a fan app to load its config file(s). */
306 std::function<void()> _loadFunc;
307
Matt Spinler59850df2021-01-06 16:56:06 -0600308 /**
Matt Spinler59850df2021-01-06 16:56:06 -0600309 * @brief The interfacesAdded match that is used to wait
310 * for the IBMCompatibleSystem interface to show up.
311 */
312 std::unique_ptr<sdbusplus::server::match::match> _match;
Matthew Barthb67089b2021-06-10 14:32:00 -0500313
314 /**
315 * @brief List of compatible values from the compatible interface
316 *
317 * Only supports a single instance of the compatible interface on a dbus
318 * object. If more than one dbus object exists with the compatible
319 * interface, the last one found will be the list of compatible values used.
320 */
321 inline static std::vector<std::string> _confCompatValues;
Matthew Barth11547c92020-05-05 10:34:27 -0500322};
323
324} // namespace phosphor::fan