1 /**
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 
17 #include "manager.hpp"
18 
19 #include "chassis.hpp"
20 #include "config_file_parser.hpp"
21 #include "exception_utils.hpp"
22 #include "rule.hpp"
23 #include "utility.hpp"
24 
25 #include <xyz/openbmc_project/Common/error.hpp>
26 
27 #include <algorithm>
28 #include <chrono>
29 #include <exception>
30 #include <functional>
31 #include <map>
32 #include <thread>
33 #include <tuple>
34 #include <utility>
35 #include <variant>
36 
37 namespace phosphor::power::regulators
38 {
39 
40 namespace fs = std::filesystem;
41 
42 constexpr auto busName = "xyz.openbmc_project.Power.Regulators";
43 constexpr auto managerObjPath = "/xyz/openbmc_project/power/regulators/manager";
44 constexpr auto compatibleIntf =
45     "xyz.openbmc_project.Configuration.IBMCompatibleSystem";
46 constexpr auto compatibleNamesProp = "Names";
47 constexpr std::chrono::minutes maxTimeToWaitForCompatTypes{5};
48 
49 /**
50  * Default configuration file name.  This is used when the system does not
51  * implement the D-Bus compatible interface.
52  */
53 constexpr auto defaultConfigFileName = "config.json";
54 
55 /**
56  * Standard configuration file directory.  This directory is part of the
57  * firmware install image.  It contains the standard version of the config file.
58  */
59 const fs::path standardConfigFileDir{"/usr/share/phosphor-regulators"};
60 
61 /**
62  * Test configuration file directory.  This directory can contain a test version
63  * of the config file.  The test version will override the standard version.
64  */
65 const fs::path testConfigFileDir{"/etc/phosphor-regulators"};
66 
67 Manager::Manager(sdbusplus::bus::bus& bus, const sdeventplus::Event& event) :
68     ManagerObject{bus, managerObjPath, true}, bus{bus}, eventLoop{event},
69     services{bus}
70 {
71     // Subscribe to D-Bus interfacesAdded signal from Entity Manager.  This
72     // notifies us if the compatible interface becomes available later.
73     std::string matchStr = sdbusplus::bus::match::rules::interfacesAdded() +
74                            sdbusplus::bus::match::rules::sender(
75                                "xyz.openbmc_project.EntityManager");
76     std::unique_ptr<sdbusplus::server::match::match> matchPtr =
77         std::make_unique<sdbusplus::server::match::match>(
78             bus, matchStr,
79             std::bind(&Manager::interfacesAddedHandler, this,
80                       std::placeholders::_1));
81     signals.emplace_back(std::move(matchPtr));
82 
83     // Try to find compatible system types using D-Bus compatible interface.
84     // Note that it might not be supported on this system, or the service that
85     // provides the interface might not be running yet.
86     findCompatibleSystemTypes();
87 
88     // Try to find and load the JSON configuration file
89     loadConfigFile();
90 
91     // Obtain dbus service name
92     bus.request_name(busName);
93 }
94 
95 void Manager::configure()
96 {
97     // Clear any cached data or error history related to hardware devices
98     clearHardwareData();
99 
100     // Wait until the config file has been loaded or hit max wait time
101     waitUntilConfigFileLoaded();
102 
103     // Verify config file has been loaded and System object is valid
104     if (isConfigFileLoaded())
105     {
106         // Configure the regulator devices in the system
107         system->configure(services);
108     }
109     else
110     {
111         // Write error message to journal
112         services.getJournal().logError("Unable to configure regulator devices: "
113                                        "Configuration file not loaded");
114 
115         // Log critical error since regulators could not be configured.  Could
116         // cause hardware damage if default regulator settings are very wrong.
117         services.getErrorLogging().logConfigFileError(Entry::Level::Critical,
118                                                       services.getJournal());
119 
120         // Throw InternalFailure to propogate error status to D-Bus client
121         throw sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure{};
122     }
123 }
124 
125 void Manager::interfacesAddedHandler(sdbusplus::message::message& msg)
126 {
127     // Verify message is valid
128     if (!msg)
129     {
130         return;
131     }
132 
133     try
134     {
135         // Read object path for object that was created or had interface added
136         sdbusplus::message::object_path objPath;
137         msg.read(objPath);
138 
139         // Read the dictionary whose keys are interface names and whose values
140         // are dictionaries containing the interface property names and values
141         std::map<std::string,
142                  std::map<std::string, std::variant<std::vector<std::string>>>>
143             intfProp;
144         msg.read(intfProp);
145 
146         // Find the compatible interface, if present
147         auto itIntf = intfProp.find(compatibleIntf);
148         if (itIntf != intfProp.cend())
149         {
150             // Find the Names property of the compatible interface, if present
151             auto itProp = itIntf->second.find(compatibleNamesProp);
152             if (itProp != itIntf->second.cend())
153             {
154                 // Get value of Names property
155                 auto propValue = std::get<0>(itProp->second);
156                 if (!propValue.empty())
157                 {
158                     // Store list of compatible system types
159                     compatibleSystemTypes = propValue;
160 
161                     // Find and load JSON config file based on system types
162                     loadConfigFile();
163                 }
164             }
165         }
166     }
167     catch (const std::exception&)
168     {
169         // Error trying to read interfacesAdded message.  One possible cause
170         // could be a property whose value is not a std::vector<std::string>.
171     }
172 }
173 
174 void Manager::monitor(bool enable)
175 {
176     if (enable)
177     {
178         /* Temporarily comment out until monitoring is supported.
179             Timer timer(eventLoop, std::bind(&Manager::timerExpired, this));
180             // Set timer as a repeating 1sec timer
181             timer.restart(std::chrono::milliseconds(1000));
182             timers.emplace_back(std::move(timer));
183         */
184     }
185     else
186     {
187         /* Temporarily comment out until monitoring is supported.
188             // Delete all timers to disable monitoring
189             timers.clear();
190         */
191 
192         // Verify config file has been loaded and System object is valid
193         if (isConfigFileLoaded())
194         {
195             // Close the regulator devices in the system.  Monitoring is
196             // normally disabled because the system is being powered off.  The
197             // devices should be closed in case hardware is removed or replaced
198             // while the system is powered off.
199             system->closeDevices(services);
200         }
201     }
202 }
203 
204 void Manager::sighupHandler(sdeventplus::source::Signal& /*sigSrc*/,
205                             const struct signalfd_siginfo* /*sigInfo*/)
206 {
207     // Reload the JSON configuration file
208     loadConfigFile();
209 }
210 
211 void Manager::timerExpired()
212 {
213     // TODO Analyze, refresh sensor status, and
214     // collect/update telemetry for each regulator
215 }
216 
217 void Manager::clearHardwareData()
218 {
219     // Clear any cached hardware presence data and VPD values
220     services.getPresenceService().clearCache();
221     services.getVPD().clearCache();
222 
223     // Verify config file has been loaded and System object is valid
224     if (isConfigFileLoaded())
225     {
226         // Clear any cached hardware data in the System object
227         system->clearCache();
228     }
229 
230     // TODO: Clear error history related to hardware devices
231 }
232 
233 void Manager::findCompatibleSystemTypes()
234 {
235     using namespace phosphor::power::util;
236 
237     try
238     {
239         // Query object mapper for object paths that implement the compatible
240         // interface.  Returns a map of object paths to a map of services names
241         // to their interfaces.
242         DbusSubtree subTree = getSubTree(bus, "/xyz/openbmc_project/inventory",
243                                          compatibleIntf, 0);
244 
245         // Get the first object path
246         auto objectIt = subTree.cbegin();
247         if (objectIt != subTree.cend())
248         {
249             std::string objPath = objectIt->first;
250 
251             // Get the first service name
252             auto serviceIt = objectIt->second.cbegin();
253             if (serviceIt != objectIt->second.cend())
254             {
255                 std::string service = serviceIt->first;
256                 if (!service.empty())
257                 {
258                     // Get compatible system types property value
259                     getProperty(compatibleIntf, compatibleNamesProp, objPath,
260                                 service, bus, compatibleSystemTypes);
261                 }
262             }
263         }
264     }
265     catch (const std::exception&)
266     {
267         // Compatible system types information is not available.  The current
268         // system might not support the interface, or the service that
269         // implements the interface might not be running yet.
270     }
271 }
272 
273 fs::path Manager::findConfigFile()
274 {
275     // Build list of possible base file names
276     std::vector<std::string> fileNames{};
277 
278     // Add possible file names based on compatible system types (if any)
279     for (const std::string& systemType : compatibleSystemTypes)
280     {
281         // Replace all spaces and commas in system type name with underscores
282         std::string fileName{systemType};
283         std::replace(fileName.begin(), fileName.end(), ' ', '_');
284         std::replace(fileName.begin(), fileName.end(), ',', '_');
285 
286         // Append .json suffix and add to list
287         fileName.append(".json");
288         fileNames.emplace_back(fileName);
289     }
290 
291     // Add default file name for systems that don't use compatible interface
292     fileNames.emplace_back(defaultConfigFileName);
293 
294     // Look for a config file with one of the possible base names
295     for (const std::string& fileName : fileNames)
296     {
297         // Check if file exists in test directory
298         fs::path pathName{testConfigFileDir / fileName};
299         if (fs::exists(pathName))
300         {
301             return pathName;
302         }
303 
304         // Check if file exists in standard directory
305         pathName = standardConfigFileDir / fileName;
306         if (fs::exists(pathName))
307         {
308             return pathName;
309         }
310     }
311 
312     // No config file found; return empty path
313     return fs::path{};
314 }
315 
316 void Manager::loadConfigFile()
317 {
318     try
319     {
320         // Find the absolute path to the config file
321         fs::path pathName = findConfigFile();
322         if (!pathName.empty())
323         {
324             // Log info message in journal; config file path is important
325             services.getJournal().logInfo("Loading configuration file " +
326                                           pathName.string());
327 
328             // Parse the config file
329             std::vector<std::unique_ptr<Rule>> rules{};
330             std::vector<std::unique_ptr<Chassis>> chassis{};
331             std::tie(rules, chassis) = config_file_parser::parse(pathName);
332 
333             // Store config file information in a new System object.  The old
334             // System object, if any, is automatically deleted.
335             system =
336                 std::make_unique<System>(std::move(rules), std::move(chassis));
337         }
338     }
339     catch (const std::exception& e)
340     {
341         // Log error messages in journal
342         services.getJournal().logError(exception_utils::getMessages(e));
343         services.getJournal().logError("Unable to load configuration file");
344 
345         // Log error
346         services.getErrorLogging().logConfigFileError(Entry::Level::Error,
347                                                       services.getJournal());
348     }
349 }
350 
351 void Manager::waitUntilConfigFileLoaded()
352 {
353     // If config file not loaded and list of compatible system types is empty
354     if (!isConfigFileLoaded() && compatibleSystemTypes.empty())
355     {
356         // Loop until compatible system types found or waited max amount of time
357         auto start = std::chrono::system_clock::now();
358         std::chrono::system_clock::duration timeWaited{0};
359         while (compatibleSystemTypes.empty() &&
360                (timeWaited <= maxTimeToWaitForCompatTypes))
361         {
362             // Try to find list of compatible system types
363             findCompatibleSystemTypes();
364             if (!compatibleSystemTypes.empty())
365             {
366                 // Compatible system types found; try to load config file
367                 loadConfigFile();
368             }
369             else
370             {
371                 // Sleep 5 seconds
372                 using namespace std::chrono_literals;
373                 std::this_thread::sleep_for(5s);
374             }
375             timeWaited = std::chrono::system_clock::now() - start;
376         }
377     }
378 }
379 
380 } // namespace phosphor::power::regulators
381