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         // Clear error history related to hardware devices in the System object
230         system->clearErrorHistory();
231     }
232 }
233 
234 void Manager::findCompatibleSystemTypes()
235 {
236     using namespace phosphor::power::util;
237 
238     try
239     {
240         // Query object mapper for object paths that implement the compatible
241         // interface.  Returns a map of object paths to a map of services names
242         // to their interfaces.
243         DbusSubtree subTree = getSubTree(bus, "/xyz/openbmc_project/inventory",
244                                          compatibleIntf, 0);
245 
246         // Get the first object path
247         auto objectIt = subTree.cbegin();
248         if (objectIt != subTree.cend())
249         {
250             std::string objPath = objectIt->first;
251 
252             // Get the first service name
253             auto serviceIt = objectIt->second.cbegin();
254             if (serviceIt != objectIt->second.cend())
255             {
256                 std::string service = serviceIt->first;
257                 if (!service.empty())
258                 {
259                     // Get compatible system types property value
260                     getProperty(compatibleIntf, compatibleNamesProp, objPath,
261                                 service, bus, compatibleSystemTypes);
262                 }
263             }
264         }
265     }
266     catch (const std::exception&)
267     {
268         // Compatible system types information is not available.  The current
269         // system might not support the interface, or the service that
270         // implements the interface might not be running yet.
271     }
272 }
273 
274 fs::path Manager::findConfigFile()
275 {
276     // Build list of possible base file names
277     std::vector<std::string> fileNames{};
278 
279     // Add possible file names based on compatible system types (if any)
280     for (const std::string& systemType : compatibleSystemTypes)
281     {
282         // Replace all spaces and commas in system type name with underscores
283         std::string fileName{systemType};
284         std::replace(fileName.begin(), fileName.end(), ' ', '_');
285         std::replace(fileName.begin(), fileName.end(), ',', '_');
286 
287         // Append .json suffix and add to list
288         fileName.append(".json");
289         fileNames.emplace_back(fileName);
290     }
291 
292     // Add default file name for systems that don't use compatible interface
293     fileNames.emplace_back(defaultConfigFileName);
294 
295     // Look for a config file with one of the possible base names
296     for (const std::string& fileName : fileNames)
297     {
298         // Check if file exists in test directory
299         fs::path pathName{testConfigFileDir / fileName};
300         if (fs::exists(pathName))
301         {
302             return pathName;
303         }
304 
305         // Check if file exists in standard directory
306         pathName = standardConfigFileDir / fileName;
307         if (fs::exists(pathName))
308         {
309             return pathName;
310         }
311     }
312 
313     // No config file found; return empty path
314     return fs::path{};
315 }
316 
317 void Manager::loadConfigFile()
318 {
319     try
320     {
321         // Find the absolute path to the config file
322         fs::path pathName = findConfigFile();
323         if (!pathName.empty())
324         {
325             // Log info message in journal; config file path is important
326             services.getJournal().logInfo("Loading configuration file " +
327                                           pathName.string());
328 
329             // Parse the config file
330             std::vector<std::unique_ptr<Rule>> rules{};
331             std::vector<std::unique_ptr<Chassis>> chassis{};
332             std::tie(rules, chassis) = config_file_parser::parse(pathName);
333 
334             // Store config file information in a new System object.  The old
335             // System object, if any, is automatically deleted.
336             system =
337                 std::make_unique<System>(std::move(rules), std::move(chassis));
338         }
339     }
340     catch (const std::exception& e)
341     {
342         // Log error messages in journal
343         services.getJournal().logError(exception_utils::getMessages(e));
344         services.getJournal().logError("Unable to load configuration file");
345 
346         // Log error
347         services.getErrorLogging().logConfigFileError(Entry::Level::Error,
348                                                       services.getJournal());
349     }
350 }
351 
352 void Manager::waitUntilConfigFileLoaded()
353 {
354     // If config file not loaded and list of compatible system types is empty
355     if (!isConfigFileLoaded() && compatibleSystemTypes.empty())
356     {
357         // Loop until compatible system types found or waited max amount of time
358         auto start = std::chrono::system_clock::now();
359         std::chrono::system_clock::duration timeWaited{0};
360         while (compatibleSystemTypes.empty() &&
361                (timeWaited <= maxTimeToWaitForCompatTypes))
362         {
363             // Try to find list of compatible system types
364             findCompatibleSystemTypes();
365             if (!compatibleSystemTypes.empty())
366             {
367                 // Compatible system types found; try to load config file
368                 loadConfigFile();
369             }
370             else
371             {
372                 // Sleep 5 seconds
373                 using namespace std::chrono_literals;
374                 std::this_thread::sleep_for(5s);
375             }
376             timeWaited = std::chrono::system_clock::now() - start;
377         }
378     }
379 }
380 
381 } // namespace phosphor::power::regulators
382