blob: 5cf3683d0d8d1fda7b8b45a291c4c15eff8e4359 [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
20#include <nlohmann/json.hpp>
Anwaar Hadi32c4fef2025-04-02 16:08:27 +000021#include <phosphor-logging/lg2.hpp>
Matthew Barth11547c92020-05-05 10:34:27 -050022#include <sdbusplus/bus.hpp>
23#include <sdeventplus/source/signal.hpp>
24
25#include <filesystem>
Patrick Williamsfbf47032023-07-17 12:27:34 -050026#include <format>
Matthew Barth11547c92020-05-05 10:34:27 -050027#include <fstream>
28
29namespace phosphor::fan
30{
31
32namespace fs = std::filesystem;
33using json = nlohmann::json;
Matthew Barth11547c92020-05-05 10:34:27 -050034
35constexpr auto confOverridePath = "/etc/phosphor-fan-presence";
36constexpr auto confBasePath = "/usr/share/phosphor-fan-presence";
Matthew Barthb370ab32021-06-10 14:38:02 -050037constexpr auto confCompatServ = "xyz.openbmc_project.EntityManager";
Matthew Barthfcbdc0e2020-10-28 14:11:07 -050038constexpr auto confCompatIntf =
Chau Lyb99ce0e2023-11-30 08:06:00 +000039 "xyz.openbmc_project.Inventory.Decorator.Compatible";
Matthew Barthfcbdc0e2020-10-28 14:11:07 -050040constexpr auto confCompatProp = "Names";
Matthew Barth11547c92020-05-05 10:34:27 -050041
Matthew Barth6eb603e2021-09-01 09:01:57 -050042/**
43 * @class NoConfigFound - A no JSON configuration found exception
44 *
45 * A no JSON configuration found exception that is used to denote that a JSON
46 * configuration has not been found yet.
47 */
48class NoConfigFound : public std::runtime_error
49{
50 public:
51 NoConfigFound() = delete;
52 NoConfigFound(const NoConfigFound&) = delete;
53 NoConfigFound(NoConfigFound&&) = delete;
54 NoConfigFound& operator=(const NoConfigFound&) = delete;
55 NoConfigFound& operator=(NoConfigFound&&) = delete;
56 ~NoConfigFound() = default;
57
58 /**
59 * @brief No JSON configuration found exception object
60 *
61 * When attempting to find the JSON configuration file(s), a NoConfigFound
62 * exception can be thrown to denote that at that time finding/loading the
63 * JSON configuration file(s) for a fan application failed. Details on what
64 * application and JSON configuration file that failed to be found will be
65 * logged resulting in the application being terminated.
66 *
67 * @param[in] details - Additional details
68 */
69 NoConfigFound(const std::string& appName, const std::string& fileName) :
Patrick Williamsfbf47032023-07-17 12:27:34 -050070 std::runtime_error(std::format("JSON configuration not found [Could "
Matthew Barth6eb603e2021-09-01 09:01:57 -050071 "not find fan {} conf file {}]",
72 appName, fileName)
73 .c_str())
74 {}
75};
76
Matthew Barth11547c92020-05-05 10:34:27 -050077class JsonConfig
78{
79 public:
Matt Spinler59850df2021-01-06 16:56:06 -060080 /**
Matthew Barthd80c8752021-06-01 14:46:02 -050081 * @brief Get the object paths with the compatible interface
82 *
83 * Retrieve all the object paths implementing the compatible interface for
84 * configuration file loading.
85 */
Chau Lyb99ce0e2023-11-30 08:06:00 +000086 std::vector<std::string>& getCompatObjPaths()
Matthew Barthd80c8752021-06-01 14:46:02 -050087 {
Chau Lyb99ce0e2023-11-30 08:06:00 +000088 using SubTreeMap =
89 std::map<std::string,
90 std::map<std::string, std::vector<std::string>>>;
91 SubTreeMap subTreeObjs = util::SDBusPlus::getSubTreeRaw(
Matthew Barthd80c8752021-06-01 14:46:02 -050092 util::SDBusPlus::getBus(), "/", confCompatIntf, 0);
Chau Lyb99ce0e2023-11-30 08:06:00 +000093
94 static std::vector<std::string> paths;
95 for (auto& [path, serviceMap] : subTreeObjs)
96 {
97 // Only save objects under confCompatServ
98 if (serviceMap.find(confCompatServ) != serviceMap.end())
99 {
100 paths.emplace_back(path);
101 }
102 }
Matthew Barthd80c8752021-06-01 14:46:02 -0500103 return paths;
104 }
105
106 /**
Matt Spinler59850df2021-01-06 16:56:06 -0600107 * @brief Constructor
108 *
Matthew Barthb370ab32021-06-10 14:38:02 -0500109 * Attempts to set the list of compatible values from the compatible
110 * interface and call the fan app's function to load its config file(s). If
111 * the compatible interface is not found, it subscribes to the
112 * interfacesAdded signal for that interface on the compatible service
113 * defined above.
114 *
115 * @param[in] func - Fan app function to call to load its config file(s)
116 */
117 JsonConfig(std::function<void()> func) : _loadFunc(func)
118 {
Matthew Barth8d1193c2021-09-14 10:36:06 -0500119 std::vector<std::string> compatObjPaths;
120
Patrick Williams3ea9ec22021-11-19 12:21:08 -0600121 _match = std::make_unique<sdbusplus::bus::match_t>(
Matthew Barthb370ab32021-06-10 14:38:02 -0500122 util::SDBusPlus::getBus(),
123 sdbusplus::bus::match::rules::interfacesAdded() +
124 sdbusplus::bus::match::rules::sender(confCompatServ),
125 std::bind(&JsonConfig::compatIntfAdded, this,
126 std::placeholders::_1));
Matthew Barth1689cb62021-08-27 12:34:36 -0500127
Matthew Barth8d1193c2021-09-14 10:36:06 -0500128 try
129 {
130 compatObjPaths = getCompatObjPaths();
131 }
132 catch (const util::DBusMethodError&)
133 {
134 // Compatible interface does not exist on any dbus object yet
135 }
136
Matthew Barth1689cb62021-08-27 12:34:36 -0500137 if (!compatObjPaths.empty())
Matthew Barthb370ab32021-06-10 14:38:02 -0500138 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500139 for (auto& path : compatObjPaths)
Matthew Barthb370ab32021-06-10 14:38:02 -0500140 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500141 try
Matthew Barthb370ab32021-06-10 14:38:02 -0500142 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500143 // Retrieve json config compatible relative path
144 // locations (last one found will be what's used if more
Chau Lyb99ce0e2023-11-30 08:06:00 +0000145 // than one dbus object implementing the compatible
Matthew Barth1689cb62021-08-27 12:34:36 -0500146 // interface exists).
147 _confCompatValues =
148 util::SDBusPlus::getProperty<std::vector<std::string>>(
149 util::SDBusPlus::getBus(), path, confCompatIntf,
150 confCompatProp);
Matthew Barthb370ab32021-06-10 14:38:02 -0500151 }
Matthew Barth1689cb62021-08-27 12:34:36 -0500152 catch (const util::DBusError&)
153 {
154 // Compatible property unavailable on this dbus object
155 // path's compatible interface, ignore
156 }
157 }
Chau Lyb99ce0e2023-11-30 08:06:00 +0000158 try
159 {
160 _loadFunc();
161 }
162 catch (const NoConfigFound&)
163 {
164 // The Decorator.Compatible interface is not unique to one
165 // single object on DBus so this should not be treated as a
166 // failure, wait for interfacesAdded signal.
167 }
Matthew Barth1689cb62021-08-27 12:34:36 -0500168 }
169 else
170 {
171 // Check if required config(s) are found not needing the
172 // compatible interface, otherwise this is intended to catch the
173 // exception thrown by the getConfFile function when the
174 // required config file was not found. This would then result in
175 // waiting for the compatible interfacesAdded signal
176 try
177 {
Matthew Barthb370ab32021-06-10 14:38:02 -0500178 _loadFunc();
Matthew Barthb370ab32021-06-10 14:38:02 -0500179 }
Matthew Barth6eb603e2021-09-01 09:01:57 -0500180 catch (const NoConfigFound&)
Matthew Barthb370ab32021-06-10 14:38:02 -0500181 {
Matthew Barth1689cb62021-08-27 12:34:36 -0500182 // Wait for compatible interfacesAdded signal
Matthew Barthb370ab32021-06-10 14:38:02 -0500183 }
184 }
Matthew Barthb370ab32021-06-10 14:38:02 -0500185 }
186
187 /**
Matthew Barthb370ab32021-06-10 14:38:02 -0500188 * @brief InterfacesAdded callback function for the compatible interface.
189 *
190 * @param[in] msg - The D-Bus message contents
191 *
192 * If the compatible interface is found, it uses the compatible property on
193 * the interface to set the list of compatible values to be used when
194 * attempting to get a configuration file. Once the list of compatible
195 * values has been updated, it calls the load function.
196 */
Patrick Williamscb356d42022-07-22 19:26:53 -0500197 void compatIntfAdded(sdbusplus::message_t& msg)
Matthew Barthb370ab32021-06-10 14:38:02 -0500198 {
Chau Lyb99ce0e2023-11-30 08:06:00 +0000199 if (!_compatibleName.empty())
200 {
201 // Do not process the interfaceAdded signal if one compatible name
202 // has been successfully used to get config files
203 return;
204 }
Matthew Barthb370ab32021-06-10 14:38:02 -0500205 sdbusplus::message::object_path op;
206 std::map<std::string,
207 std::map<std::string, std::variant<std::vector<std::string>>>>
208 intfProps;
209
210 msg.read(op, intfProps);
211
212 if (intfProps.find(confCompatIntf) == intfProps.end())
213 {
214 return;
215 }
216
217 const auto& props = intfProps.at(confCompatIntf);
218 // Only one dbus object with the compatible interface is used at a time
219 _confCompatValues =
220 std::get<std::vector<std::string>>(props.at(confCompatProp));
221 _loadFunc();
222 }
223
224 /**
Matthew Barth11547c92020-05-05 10:34:27 -0500225 * Get the json configuration file. The first location found to contain
226 * the json config file for the given fan application is used from the
227 * following locations in order.
228 * 1.) From the confOverridePath location
Matthew Barthb67089b2021-06-10 14:32:00 -0500229 * 2.) From the default confBasePath location
230 * 3.) From config file found using an entry from a list obtained from an
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500231 * interface's property as a relative path extension on the base path where:
232 * interface = Interface set in confCompatIntf with the property
233 * property = Property set in confCompatProp containing a list of
234 * subdirectories in priority order to find a config
Matthew Barth11547c92020-05-05 10:34:27 -0500235 *
236 * @brief Get the configuration file to be used
237 *
Matthew Barth11547c92020-05-05 10:34:27 -0500238 * @param[in] appName - The phosphor-fan-presence application name
239 * @param[in] fileName - Application's configuration file's name
Matthew Barthb5991022020-08-05 11:08:50 -0500240 * @param[in] isOptional - Config file is optional, default to 'false'
Matthew Barth11547c92020-05-05 10:34:27 -0500241 *
242 * @return filesystem path
243 * The filesystem path to the configuration file to use
244 */
Mike Capps808d7fe2022-06-13 10:12:16 -0400245 static const fs::path getConfFile(const std::string& appName,
Matthew Barthb5991022020-08-05 11:08:50 -0500246 const std::string& fileName,
247 bool isOptional = false)
Matthew Barth11547c92020-05-05 10:34:27 -0500248 {
249 // Check override location
250 fs::path confFile = fs::path{confOverridePath} / appName / fileName;
251 if (fs::exists(confFile))
252 {
253 return confFile;
254 }
255
Matt Spinler59850df2021-01-06 16:56:06 -0600256 // If the default file is there, use it
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500257 confFile = fs::path{confBasePath} / appName / fileName;
Matt Spinler59850df2021-01-06 16:56:06 -0600258 if (fs::exists(confFile))
259 {
260 return confFile;
261 }
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500262
Matthew Barthb67089b2021-06-10 14:32:00 -0500263 // Look for a config file at each entry relative to the base
264 // path and use the first one found
Patrick Williamsdfddd642024-08-16 15:21:51 -0400265 auto it = std::find_if(
266 _confCompatValues.begin(), _confCompatValues.end(),
267 [&confFile, &appName, &fileName](const auto& value) {
268 confFile = fs::path{confBasePath} / appName / value / fileName;
269 _compatibleName = value;
270 return fs::exists(confFile);
271 });
Matthew Barthb67089b2021-06-10 14:32:00 -0500272 if (it == _confCompatValues.end())
273 {
274 confFile.clear();
Chau Lyb99ce0e2023-11-30 08:06:00 +0000275 _compatibleName.clear();
Matthew Barthb67089b2021-06-10 14:32:00 -0500276 }
277
Matt Spinler59850df2021-01-06 16:56:06 -0600278 if (confFile.empty() && !isOptional)
Matthew Barth11547c92020-05-05 10:34:27 -0500279 {
Matthew Barth6eb603e2021-09-01 09:01:57 -0500280 throw NoConfigFound(appName, fileName);
Matthew Barthb5991022020-08-05 11:08:50 -0500281 }
Matthew Barth11547c92020-05-05 10:34:27 -0500282
283 return confFile;
284 }
285
286 /**
287 * @brief Load the JSON config file
288 *
289 * @param[in] confFile - File system path of the configuration file to load
290 *
291 * @return Parsed JSON object
292 * The parsed JSON configuration file object
293 */
294 static const json load(const fs::path& confFile)
295 {
296 std::ifstream file;
297 json jsonConf;
298
Matthew Barthb5991022020-08-05 11:08:50 -0500299 if (!confFile.empty() && fs::exists(confFile))
Matthew Barth11547c92020-05-05 10:34:27 -0500300 {
Anwaar Hadi32c4fef2025-04-02 16:08:27 +0000301 lg2::info("Loading configuration from {CONFFILE}", "CONFFILE",
302 confFile);
Matthew Barth11547c92020-05-05 10:34:27 -0500303 file.open(confFile);
304 try
305 {
Matthew Barthde72d5d2021-07-16 10:39:42 -0500306 // Enable ignoring `//` or `/* */` comments
307 jsonConf = json::parse(file, nullptr, true, true);
Matthew Barth11547c92020-05-05 10:34:27 -0500308 }
Patrick Williamsddb773b2021-10-06 11:24:49 -0500309 catch (const std::exception& e)
Matthew Barth11547c92020-05-05 10:34:27 -0500310 {
Anwaar Hadi32c4fef2025-04-02 16:08:27 +0000311 lg2::error(
312 "Failed to parse JSON config file: {CONFFILE}, error: {ERROR}",
313 "CONFFILE", confFile, "ERROR", e);
Matthew Barth1826c732020-08-28 08:40:59 -0500314 throw std::runtime_error(
Patrick Williamsfbf47032023-07-17 12:27:34 -0500315 std::format(
Matthew Barth1826c732020-08-28 08:40:59 -0500316 "Failed to parse JSON config file: {}, error: {}",
317 confFile.string(), e.what())
318 .c_str());
Matthew Barth11547c92020-05-05 10:34:27 -0500319 }
320 }
321 else
322 {
Anwaar Hadi32c4fef2025-04-02 16:08:27 +0000323 lg2::error("Unable to open JSON config file: {CONFFILE}",
324 "CONFFILE", confFile);
Matthew Barth1826c732020-08-28 08:40:59 -0500325 throw std::runtime_error(
Patrick Williamsfbf47032023-07-17 12:27:34 -0500326 std::format("Unable to open JSON config file: {}",
Matthew Barth1826c732020-08-28 08:40:59 -0500327 confFile.string())
328 .c_str());
Matthew Barth11547c92020-05-05 10:34:27 -0500329 }
330
331 return jsonConf;
332 }
Matt Spinler59850df2021-01-06 16:56:06 -0600333
Matt Spinlerd4c7fb72021-11-09 16:03:50 -0600334 /**
335 * @brief Return the compatible values property
336 *
337 * @return const std::vector<std::string>& - The values
338 */
339 static const std::vector<std::string>& getCompatValues()
340 {
341 return _confCompatValues;
342 }
343
Matt Spinler59850df2021-01-06 16:56:06 -0600344 private:
Matthew Barthb370ab32021-06-10 14:38:02 -0500345 /* Load function to call for a fan app to load its config file(s). */
346 std::function<void()> _loadFunc;
347
Matt Spinler59850df2021-01-06 16:56:06 -0600348 /**
Matt Spinler59850df2021-01-06 16:56:06 -0600349 * @brief The interfacesAdded match that is used to wait
Chau Lyb99ce0e2023-11-30 08:06:00 +0000350 * for the Inventory.Decorator.Compatible interface to show up.
Matt Spinler59850df2021-01-06 16:56:06 -0600351 */
Patrick Williams3ea9ec22021-11-19 12:21:08 -0600352 std::unique_ptr<sdbusplus::bus::match_t> _match;
Matthew Barthb67089b2021-06-10 14:32:00 -0500353
354 /**
355 * @brief List of compatible values from the compatible interface
356 *
357 * Only supports a single instance of the compatible interface on a dbus
358 * object. If more than one dbus object exists with the compatible
359 * interface, the last one found will be the list of compatible values used.
360 */
361 inline static std::vector<std::string> _confCompatValues;
Chau Lyb99ce0e2023-11-30 08:06:00 +0000362
363 /**
364 * @brief The compatible value that is currently used to load configuration
365 *
366 * The value extracted from the achieved property value list that is used
367 * as a sub-folder to append to the configuration location and really
368 * contains the configruation files
369 */
370
371 inline static std::string _compatibleName;
Matthew Barth11547c92020-05-05 10:34:27 -0500372};
373
374} // namespace phosphor::fan