blob: b12cdb97a0937ea8bb26638cbd66095907251291 [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 {
Matthew Barth8d1193c2021-09-14 10:36:06 -0500108 std::vector<std::string> compatObjPaths;
109
Patrick Williams3ea9ec22021-11-19 12:21:08 -0600110 _match = std::make_unique<sdbusplus::bus::match_t>(
Matthew Barthb370ab32021-06-10 14:38:02 -0500111 util::SDBusPlus::getBus(),
112 sdbusplus::bus::match::rules::interfacesAdded() +
113 sdbusplus::bus::match::rules::sender(confCompatServ),
114 std::bind(&JsonConfig::compatIntfAdded, this,
115 std::placeholders::_1));
Matthew Barth1689cb62021-08-27 12:34:36 -0500116
Matthew Barth8d1193c2021-09-14 10:36:06 -0500117 try
118 {
119 compatObjPaths = getCompatObjPaths();
120 }
121 catch (const util::DBusMethodError&)
122 {
123 // Compatible interface does not exist on any dbus object yet
124 }
125
Matthew Barth1689cb62021-08-27 12:34:36 -0500126 if (!compatObjPaths.empty())
Matthew Barthb370ab32021-06-10 14:38:02 -0500127 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500128 for (auto& path : compatObjPaths)
Matthew Barthb370ab32021-06-10 14:38:02 -0500129 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500130 try
Matthew Barthb370ab32021-06-10 14:38:02 -0500131 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500132 // Retrieve json config compatible relative path
133 // locations (last one found will be what's used if more
134 // than one dbus object implementing the comptaible
135 // interface exists).
136 _confCompatValues =
137 util::SDBusPlus::getProperty<std::vector<std::string>>(
138 util::SDBusPlus::getBus(), path, confCompatIntf,
139 confCompatProp);
Matthew Barthb370ab32021-06-10 14:38:02 -0500140 }
Matthew Barth1689cb62021-08-27 12:34:36 -0500141 catch (const util::DBusError&)
142 {
143 // Compatible property unavailable on this dbus object
144 // path's compatible interface, ignore
145 }
146 }
147 _loadFunc();
Matthew Barth1689cb62021-08-27 12:34:36 -0500148 }
149 else
150 {
151 // Check if required config(s) are found not needing the
152 // compatible interface, otherwise this is intended to catch the
153 // exception thrown by the getConfFile function when the
154 // required config file was not found. This would then result in
155 // waiting for the compatible interfacesAdded signal
156 try
157 {
Matthew Barthb370ab32021-06-10 14:38:02 -0500158 _loadFunc();
Matthew Barthb370ab32021-06-10 14:38:02 -0500159 }
Matthew Barth6eb603e2021-09-01 09:01:57 -0500160 catch (const NoConfigFound&)
Matthew Barthb370ab32021-06-10 14:38:02 -0500161 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500162 // Wait for compatible interfacesAdded signal
Matthew Barthb370ab32021-06-10 14:38:02 -0500163 }
164 }
Matthew Barthb370ab32021-06-10 14:38:02 -0500165 }
166
167 /**
Matthew Barthb370ab32021-06-10 14:38:02 -0500168 * @brief InterfacesAdded callback function for the compatible interface.
169 *
170 * @param[in] msg - The D-Bus message contents
171 *
172 * If the compatible interface is found, it uses the compatible property on
173 * the interface to set the list of compatible values to be used when
174 * attempting to get a configuration file. Once the list of compatible
175 * values has been updated, it calls the load function.
176 */
Patrick Williamscb356d42022-07-22 19:26:53 -0500177 void compatIntfAdded(sdbusplus::message_t& msg)
Matthew Barthb370ab32021-06-10 14:38:02 -0500178 {
179 sdbusplus::message::object_path op;
180 std::map<std::string,
181 std::map<std::string, std::variant<std::vector<std::string>>>>
182 intfProps;
183
184 msg.read(op, intfProps);
185
186 if (intfProps.find(confCompatIntf) == intfProps.end())
187 {
188 return;
189 }
190
191 const auto& props = intfProps.at(confCompatIntf);
192 // Only one dbus object with the compatible interface is used at a time
193 _confCompatValues =
194 std::get<std::vector<std::string>>(props.at(confCompatProp));
195 _loadFunc();
196 }
197
198 /**
Matthew Barth11547c92020-05-05 10:34:27 -0500199 * Get the json configuration file. The first location found to contain
200 * the json config file for the given fan application is used from the
201 * following locations in order.
202 * 1.) From the confOverridePath location
Matthew Barthb67089b2021-06-10 14:32:00 -0500203 * 2.) From the default confBasePath location
204 * 3.) From config file found using an entry from a list obtained from an
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500205 * interface's property as a relative path extension on the base path where:
206 * interface = Interface set in confCompatIntf with the property
207 * property = Property set in confCompatProp containing a list of
208 * subdirectories in priority order to find a config
Matthew Barth11547c92020-05-05 10:34:27 -0500209 *
210 * @brief Get the configuration file to be used
211 *
Matthew Barth11547c92020-05-05 10:34:27 -0500212 * @param[in] appName - The phosphor-fan-presence application name
213 * @param[in] fileName - Application's configuration file's name
Matthew Barthb5991022020-08-05 11:08:50 -0500214 * @param[in] isOptional - Config file is optional, default to 'false'
Matthew Barth11547c92020-05-05 10:34:27 -0500215 *
216 * @return filesystem path
217 * The filesystem path to the configuration file to use
218 */
Mike Capps808d7fe2022-06-13 10:12:16 -0400219 static const fs::path getConfFile(const std::string& appName,
Matthew Barthb5991022020-08-05 11:08:50 -0500220 const std::string& fileName,
221 bool isOptional = false)
Matthew Barth11547c92020-05-05 10:34:27 -0500222 {
223 // Check override location
224 fs::path confFile = fs::path{confOverridePath} / appName / fileName;
225 if (fs::exists(confFile))
226 {
227 return confFile;
228 }
229
Matt Spinler59850df2021-01-06 16:56:06 -0600230 // If the default file is there, use it
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500231 confFile = fs::path{confBasePath} / appName / fileName;
Matt Spinler59850df2021-01-06 16:56:06 -0600232 if (fs::exists(confFile))
233 {
234 return confFile;
235 }
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500236
Matthew Barthb67089b2021-06-10 14:32:00 -0500237 // Look for a config file at each entry relative to the base
238 // path and use the first one found
Patrick Williams61b73292023-05-10 07:50:12 -0500239 auto it =
240 std::find_if(_confCompatValues.begin(), _confCompatValues.end(),
241 [&confFile, &appName, &fileName](const auto& value) {
242 confFile = fs::path{confBasePath} / appName / value / fileName;
243 return fs::exists(confFile);
Matthew Barthb67089b2021-06-10 14:32:00 -0500244 });
245 if (it == _confCompatValues.end())
246 {
247 confFile.clear();
248 }
249
Matt Spinler59850df2021-01-06 16:56:06 -0600250 if (confFile.empty() && !isOptional)
Matthew Barth11547c92020-05-05 10:34:27 -0500251 {
Matthew Barth6eb603e2021-09-01 09:01:57 -0500252 throw NoConfigFound(appName, fileName);
Matthew Barthb5991022020-08-05 11:08:50 -0500253 }
Matthew Barth11547c92020-05-05 10:34:27 -0500254
255 return confFile;
256 }
257
258 /**
259 * @brief Load the JSON config file
260 *
261 * @param[in] confFile - File system path of the configuration file to load
262 *
263 * @return Parsed JSON object
264 * The parsed JSON configuration file object
265 */
266 static const json load(const fs::path& confFile)
267 {
268 std::ifstream file;
269 json jsonConf;
270
Matthew Barthb5991022020-08-05 11:08:50 -0500271 if (!confFile.empty() && fs::exists(confFile))
Matthew Barth11547c92020-05-05 10:34:27 -0500272 {
Matthew Barth1826c732020-08-28 08:40:59 -0500273 log<level::INFO>(
274 fmt::format("Loading configuration from {}", confFile.string())
275 .c_str());
Matthew Barth11547c92020-05-05 10:34:27 -0500276 file.open(confFile);
277 try
278 {
Matthew Barthde72d5d2021-07-16 10:39:42 -0500279 // Enable ignoring `//` or `/* */` comments
280 jsonConf = json::parse(file, nullptr, true, true);
Matthew Barth11547c92020-05-05 10:34:27 -0500281 }
Patrick Williamsddb773b2021-10-06 11:24:49 -0500282 catch (const std::exception& e)
Matthew Barth11547c92020-05-05 10:34:27 -0500283 {
Matthew Barth1826c732020-08-28 08:40:59 -0500284 log<level::ERR>(
285 fmt::format(
286 "Failed to parse JSON config file: {}, error: {}",
287 confFile.string(), e.what())
288 .c_str());
289 throw std::runtime_error(
290 fmt::format(
291 "Failed to parse JSON config file: {}, error: {}",
292 confFile.string(), e.what())
293 .c_str());
Matthew Barth11547c92020-05-05 10:34:27 -0500294 }
295 }
296 else
297 {
Matthew Barth1826c732020-08-28 08:40:59 -0500298 log<level::ERR>(fmt::format("Unable to open JSON config file: {}",
299 confFile.string())
300 .c_str());
301 throw std::runtime_error(
302 fmt::format("Unable to open JSON config file: {}",
303 confFile.string())
304 .c_str());
Matthew Barth11547c92020-05-05 10:34:27 -0500305 }
306
307 return jsonConf;
308 }
Matt Spinler59850df2021-01-06 16:56:06 -0600309
Matt Spinlerd4c7fb72021-11-09 16:03:50 -0600310 /**
311 * @brief Return the compatible values property
312 *
313 * @return const std::vector<std::string>& - The values
314 */
315 static const std::vector<std::string>& getCompatValues()
316 {
317 return _confCompatValues;
318 }
319
Matt Spinler59850df2021-01-06 16:56:06 -0600320 private:
Matthew Barthb370ab32021-06-10 14:38:02 -0500321 /* Load function to call for a fan app to load its config file(s). */
322 std::function<void()> _loadFunc;
323
Matt Spinler59850df2021-01-06 16:56:06 -0600324 /**
Matt Spinler59850df2021-01-06 16:56:06 -0600325 * @brief The interfacesAdded match that is used to wait
326 * for the IBMCompatibleSystem interface to show up.
327 */
Patrick Williams3ea9ec22021-11-19 12:21:08 -0600328 std::unique_ptr<sdbusplus::bus::match_t> _match;
Matthew Barthb67089b2021-06-10 14:32:00 -0500329
330 /**
331 * @brief List of compatible values from the compatible interface
332 *
333 * Only supports a single instance of the compatible interface on a dbus
334 * object. If more than one dbus object exists with the compatible
335 * interface, the last one found will be the list of compatible values used.
336 */
337 inline static std::vector<std::string> _confCompatValues;
Matthew Barth11547c92020-05-05 10:34:27 -0500338};
339
340} // namespace phosphor::fan