blob: 3fd53b18d074947909a3d4684ec49eb88613dc01 [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 Barthfcbdc0e2020-10-28 14:11:07 -050039constexpr auto confCompatIntf =
40 "xyz.openbmc_project.Configuration.IBMCompatibleSystem";
41constexpr auto confCompatProp = "Names";
Matthew Barth11547c92020-05-05 10:34:27 -050042
43class JsonConfig
44{
45 public:
Matt Spinler59850df2021-01-06 16:56:06 -060046 using ConfFileReadyFunc = std::function<void(const std::string&)>;
47
48 /**
Matthew Barthd80c8752021-06-01 14:46:02 -050049 * @brief Get the object paths with the compatible interface
50 *
51 * Retrieve all the object paths implementing the compatible interface for
52 * configuration file loading.
53 */
54 static auto& getCompatObjPaths() __attribute__((pure))
55 {
56 static auto paths = util::SDBusPlus::getSubTreePathsRaw(
57 util::SDBusPlus::getBus(), "/", confCompatIntf, 0);
58 return paths;
59 }
60
61 /**
Matt Spinler59850df2021-01-06 16:56:06 -060062 * @brief Constructor
63 *
64 * Looks for the JSON config file. If it can't find one, then it
65 * will watch entity-manager for the IBMCompatibleSystem interface
66 * to show up and then use that data to try again. If the config
67 * file is initially present, the callback function is executed
68 * with the path to the file.
69 *
70 * @param[in] bus - The dbus bus object
71 * @param[in] appName - The appName portion of the config file path
72 * @param[in] fileName - Application's configuration file's name
73 * @param[in] func - The function to call when the config file
74 * is found.
75 */
76 JsonConfig(sdbusplus::bus::bus& bus, const std::string& appName,
77 const std::string& fileName, ConfFileReadyFunc func) :
78 _appName(appName),
79 _fileName(fileName), _readyFunc(func)
80 {
81 _match = std::make_unique<sdbusplus::server::match::match>(
82 bus,
83 sdbusplus::bus::match::rules::interfacesAdded() +
84 sdbusplus::bus::match::rules::sender(
85 "xyz.openbmc_project.EntityManager"),
86 std::bind(&JsonConfig::ifacesAddedCallback, this,
87 std::placeholders::_1));
88 try
89 {
Matthew Barthb67089b2021-06-10 14:32:00 -050090 auto compatObjPaths = getCompatObjPaths();
91 if (!compatObjPaths.empty())
92 {
93 for (auto& path : compatObjPaths)
94 {
95 try
96 {
97 // Retrieve json config compatible relative path
98 // locations (last one found will be what's used if more
99 // than one dbus object implementing the comptaible
100 // interface exists).
101 _confCompatValues = util::SDBusPlus::getProperty<
102 std::vector<std::string>>(bus, path, confCompatIntf,
103 confCompatProp);
104 }
105 catch (const util::DBusError&)
106 {
107 // Property unavailable on this dbus object path.
108 }
109 }
110 }
Matt Spinler59850df2021-01-06 16:56:06 -0600111 _confFile = getConfFile(bus, _appName, _fileName);
112 }
113 catch (const std::runtime_error& e)
114 {
115 // No conf file found, so let the interfacesAdded
116 // match callback handle finding it.
117 }
118
119 if (!_confFile.empty())
120 {
121 _match.reset();
122 _readyFunc(_confFile);
123 }
124 }
125
126 /**
127 * @brief The interfacesAdded callback function that looks for
128 * the IBMCompatibleSystem interface. If it finds it,
129 * it uses the Names property in the interface to find
130 * the JSON config file to use. If it finds one, it calls
131 * the _readyFunc function with the config file path.
132 *
133 * @param[in] msg - The D-Bus message contents
134 */
135 void ifacesAddedCallback(sdbusplus::message::message& msg)
136 {
137 sdbusplus::message::object_path path;
138 std::map<std::string,
139 std::map<std::string, std::variant<std::vector<std::string>>>>
140 interfaces;
141
142 msg.read(path, interfaces);
143
144 if (interfaces.find(confCompatIntf) == interfaces.end())
145 {
146 return;
147 }
148
149 const auto& properties = interfaces.at(confCompatIntf);
150 auto names =
151 std::get<std::vector<std::string>>(properties.at(confCompatProp));
152
153 auto it =
154 std::find_if(names.begin(), names.end(), [this](auto const& name) {
155 auto confFile =
156 fs::path{confBasePath} / _appName / name / _fileName;
157 if (fs::exists(confFile))
158 {
159 _confFile = confFile;
160 return true;
161 }
162 return false;
163 });
164
165 if (it != names.end())
166 {
167 _readyFunc(_confFile);
168 _match.reset();
169 }
Matt Spinler4031f102021-04-22 16:42:20 -0500170 else
171 {
172 log<level::ERR>(fmt::format("Could not find fan {} conf file {} "
173 "even after {} iface became available",
174 _appName, _fileName, confCompatIntf)
175 .c_str());
176 }
Matt Spinler59850df2021-01-06 16:56:06 -0600177 }
178
Matthew Barth11547c92020-05-05 10:34:27 -0500179 /**
180 * Get the json configuration file. The first location found to contain
181 * the json config file for the given fan application is used from the
182 * following locations in order.
183 * 1.) From the confOverridePath location
Matthew Barthb67089b2021-06-10 14:32:00 -0500184 * 2.) From the default confBasePath location
185 * 3.) From config file found using an entry from a list obtained from an
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500186 * interface's property as a relative path extension on the base path where:
187 * interface = Interface set in confCompatIntf with the property
188 * property = Property set in confCompatProp containing a list of
189 * subdirectories in priority order to find a config
Matthew Barth11547c92020-05-05 10:34:27 -0500190 *
191 * @brief Get the configuration file to be used
192 *
193 * @param[in] bus - The dbus bus object
194 * @param[in] appName - The phosphor-fan-presence application name
195 * @param[in] fileName - Application's configuration file's name
Matthew Barthb5991022020-08-05 11:08:50 -0500196 * @param[in] isOptional - Config file is optional, default to 'false'
Matthew Barth11547c92020-05-05 10:34:27 -0500197 *
198 * @return filesystem path
199 * The filesystem path to the configuration file to use
200 */
201 static const fs::path getConfFile(sdbusplus::bus::bus& bus,
202 const std::string& appName,
Matthew Barthb5991022020-08-05 11:08:50 -0500203 const std::string& fileName,
204 bool isOptional = false)
Matthew Barth11547c92020-05-05 10:34:27 -0500205 {
206 // Check override location
207 fs::path confFile = fs::path{confOverridePath} / appName / fileName;
208 if (fs::exists(confFile))
209 {
210 return confFile;
211 }
212
Matt Spinler59850df2021-01-06 16:56:06 -0600213 // If the default file is there, use it
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500214 confFile = fs::path{confBasePath} / appName / fileName;
Matt Spinler59850df2021-01-06 16:56:06 -0600215 if (fs::exists(confFile))
216 {
217 return confFile;
218 }
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500219
Matthew Barthb67089b2021-06-10 14:32:00 -0500220 // TODO - Will be removed in a following commit in place of using a
221 // constructor to populate the compatible values
222 auto compatObjPaths = getCompatObjPaths();
223 if (!compatObjPaths.empty())
Matthew Barth11547c92020-05-05 10:34:27 -0500224 {
Matthew Barthb67089b2021-06-10 14:32:00 -0500225 for (auto& path : compatObjPaths)
Matthew Barth11547c92020-05-05 10:34:27 -0500226 {
Matthew Barthb67089b2021-06-10 14:32:00 -0500227 try
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500228 {
Matthew Barthb67089b2021-06-10 14:32:00 -0500229 // Retrieve json config compatible relative path
230 // locations (last one found will be what's used if more
231 // than one dbus object implementing the comptaible
232 // interface exists).
233 _confCompatValues =
234 util::SDBusPlus::getProperty<std::vector<std::string>>(
235 bus, path, confCompatIntf, confCompatProp);
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500236 }
Matthew Barthb67089b2021-06-10 14:32:00 -0500237 catch (const util::DBusError&)
238 {
239 // Property unavailable on this dbus object path.
240 }
Matthew Barthfcbdc0e2020-10-28 14:11:07 -0500241 }
Matthew Barth11547c92020-05-05 10:34:27 -0500242 }
243
Matthew Barthb67089b2021-06-10 14:32:00 -0500244 // Look for a config file at each entry relative to the base
245 // path and use the first one found
246 auto it = std::find_if(
247 _confCompatValues.begin(), _confCompatValues.end(),
248 [&confFile, &appName, &fileName](const auto& value) {
249 confFile = fs::path{confBasePath} / appName / value / fileName;
250 return fs::exists(confFile);
251 });
252 if (it == _confCompatValues.end())
253 {
254 confFile.clear();
255 }
256
257 if (!isOptional && confFile.empty() && !_confCompatValues.empty())
Matt Spinler4031f102021-04-22 16:42:20 -0500258 {
259 log<level::ERR>(fmt::format("Could not find fan {} conf file {}",
260 appName, fileName)
261 .c_str());
262 }
263
Matt Spinler59850df2021-01-06 16:56:06 -0600264 if (confFile.empty() && !isOptional)
Matthew Barth11547c92020-05-05 10:34:27 -0500265 {
Matt Spinler59850df2021-01-06 16:56:06 -0600266 throw std::runtime_error("No JSON config file found");
Matthew Barthb5991022020-08-05 11:08:50 -0500267 }
Matthew Barth11547c92020-05-05 10:34:27 -0500268
269 return confFile;
270 }
271
272 /**
273 * @brief Load the JSON config file
274 *
275 * @param[in] confFile - File system path of the configuration file to load
276 *
277 * @return Parsed JSON object
278 * The parsed JSON configuration file object
279 */
280 static const json load(const fs::path& confFile)
281 {
282 std::ifstream file;
283 json jsonConf;
284
Matthew Barthb5991022020-08-05 11:08:50 -0500285 if (!confFile.empty() && fs::exists(confFile))
Matthew Barth11547c92020-05-05 10:34:27 -0500286 {
Matthew Barth1826c732020-08-28 08:40:59 -0500287 log<level::INFO>(
288 fmt::format("Loading configuration from {}", confFile.string())
289 .c_str());
Matthew Barth11547c92020-05-05 10:34:27 -0500290 file.open(confFile);
291 try
292 {
293 jsonConf = json::parse(file);
294 }
295 catch (std::exception& e)
296 {
Matthew Barth1826c732020-08-28 08:40:59 -0500297 log<level::ERR>(
298 fmt::format(
299 "Failed to parse JSON config file: {}, error: {}",
300 confFile.string(), e.what())
301 .c_str());
302 throw std::runtime_error(
303 fmt::format(
304 "Failed to parse JSON config file: {}, error: {}",
305 confFile.string(), e.what())
306 .c_str());
Matthew Barth11547c92020-05-05 10:34:27 -0500307 }
308 }
309 else
310 {
Matthew Barth1826c732020-08-28 08:40:59 -0500311 log<level::ERR>(fmt::format("Unable to open JSON config file: {}",
312 confFile.string())
313 .c_str());
314 throw std::runtime_error(
315 fmt::format("Unable to open JSON config file: {}",
316 confFile.string())
317 .c_str());
Matthew Barth11547c92020-05-05 10:34:27 -0500318 }
319
320 return jsonConf;
321 }
Matt Spinler59850df2021-01-06 16:56:06 -0600322
323 private:
324 /**
325 * @brief The 'appName' portion of the config file path.
326 */
327 const std::string _appName;
328
329 /**
330 * @brief The config file name.
331 */
332 const std::string _fileName;
333
334 /**
335 * @brief The function to call when the config file is available.
336 */
337 ConfFileReadyFunc _readyFunc;
338
339 /**
340 * @brief The JSON config file
341 */
342 fs::path _confFile;
343
344 /**
345 * @brief The interfacesAdded match that is used to wait
346 * for the IBMCompatibleSystem interface to show up.
347 */
348 std::unique_ptr<sdbusplus::server::match::match> _match;
Matthew Barthb67089b2021-06-10 14:32:00 -0500349
350 /**
351 * @brief List of compatible values from the compatible interface
352 *
353 * Only supports a single instance of the compatible interface on a dbus
354 * object. If more than one dbus object exists with the compatible
355 * interface, the last one found will be the list of compatible values used.
356 */
357 inline static std::vector<std::string> _confCompatValues;
Matthew Barth11547c92020-05-05 10:34:27 -0500358};
359
360} // namespace phosphor::fan