xref: /openbmc/phosphor-pid-control/main.cpp (revision 217a827d)
1 /**
2  * Copyright 2017 Google Inc.
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 "config.h"
18 
19 #include "buildjson/buildjson.hpp"
20 #include "conf.hpp"
21 #include "dbus/dbusconfiguration.hpp"
22 #include "interfaces.hpp"
23 #include "pid/builder.hpp"
24 #include "pid/buildjson.hpp"
25 #include "pid/pidloop.hpp"
26 #include "pid/tuning.hpp"
27 #include "pid/zone.hpp"
28 #include "sensors/builder.hpp"
29 #include "sensors/buildjson.hpp"
30 #include "sensors/manager.hpp"
31 #include "util.hpp"
32 
33 #include <CLI/CLI.hpp>
34 #include <boost/asio/io_context.hpp>
35 #include <boost/asio/signal_set.hpp>
36 #include <boost/asio/steady_timer.hpp>
37 #include <sdbusplus/asio/connection.hpp>
38 #include <sdbusplus/bus.hpp>
39 #include <sdbusplus/server/manager.hpp>
40 
41 #include <chrono>
42 #include <filesystem>
43 #include <iostream>
44 #include <list>
45 #include <map>
46 #include <memory>
47 #include <thread>
48 #include <unordered_map>
49 #include <utility>
50 #include <vector>
51 
52 namespace pid_control
53 {
54 
55 /* The configuration converted sensor list. */
56 std::map<std::string, conf::SensorConfig> sensorConfig = {};
57 /* The configuration converted PID list. */
58 std::map<int64_t, conf::PIDConf> zoneConfig = {};
59 /* The configuration converted Zone configuration. */
60 std::map<int64_t, conf::ZoneConfig> zoneDetailsConfig = {};
61 
62 } // namespace pid_control
63 
64 /** the swampd daemon will check for the existence of this file. */
65 constexpr auto jsonConfigurationPath = "/usr/share/swampd/config.json";
66 std::string configPath = "";
67 
68 /* async io context for operation */
69 boost::asio::io_context io;
70 /* async signal_set for signal handling */
71 boost::asio::signal_set signals(io, SIGHUP);
72 
73 /* buses for system control */
74 static sdbusplus::asio::connection modeControlBus(io);
75 static sdbusplus::asio::connection
76     hostBus(io, sdbusplus::bus::new_system().release());
77 static sdbusplus::asio::connection
78     passiveBus(io, sdbusplus::bus::new_system().release());
79 
80 namespace pid_control
81 {
82 
83 void restartControlLoops()
84 {
85     static SensorManager mgmr;
86     static std::unordered_map<int64_t, std::shared_ptr<ZoneInterface>> zones;
87     static std::vector<std::shared_ptr<boost::asio::steady_timer>> timers;
88     static bool isCanceling = false;
89 
90     for (const auto& timer : timers)
91     {
92         timer->cancel();
93     }
94     isCanceling = true;
95     timers.clear();
96 
97     if (zones.size() > 0 && zones.begin()->second.use_count() > 1)
98     {
99         throw std::runtime_error("wait for count back to 1");
100     }
101     zones.clear();
102     isCanceling = false;
103 
104     const std::string& path =
105         (configPath.length() > 0) ? configPath : jsonConfigurationPath;
106 
107     if (std::filesystem::exists(path))
108     {
109         /*
110          * When building the sensors, if any of the dbus passive ones aren't on
111          * the bus, it'll fail immediately.
112          */
113         try
114         {
115             auto jsonData = parseValidateJson(path);
116             sensorConfig = buildSensorsFromJson(jsonData);
117             std::tie(zoneConfig, zoneDetailsConfig) =
118                 buildPIDsFromJson(jsonData);
119         }
120         catch (const std::exception& e)
121         {
122             std::cerr << "Failed during building: " << e.what() << "\n";
123             exit(EXIT_FAILURE); /* fatal error. */
124         }
125     }
126     else
127     {
128         static boost::asio::steady_timer reloadTimer(io);
129         if (!dbus_configuration::init(modeControlBus, reloadTimer, sensorConfig,
130                                       zoneConfig, zoneDetailsConfig))
131         {
132             return; // configuration not ready
133         }
134     }
135 
136     mgmr = buildSensors(sensorConfig, passiveBus, hostBus);
137     zones = buildZones(zoneConfig, zoneDetailsConfig, mgmr, modeControlBus);
138 
139     if (0 == zones.size())
140     {
141         std::cerr << "No zones defined, exiting.\n";
142         std::exit(EXIT_FAILURE);
143     }
144 
145     for (const auto& i : zones)
146     {
147         std::shared_ptr<boost::asio::steady_timer> timer = timers.emplace_back(
148             std::make_shared<boost::asio::steady_timer>(io));
149         std::cerr << "pushing zone " << i.first << "\n";
150         pidControlLoop(i.second, timer, &isCanceling);
151     }
152 }
153 
154 void tryRestartControlLoops(bool first)
155 {
156     static int count = 0;
157     static const auto delayTime = std::chrono::seconds(10);
158     static boost::asio::steady_timer timer(io);
159     // try to start a control loop while the loop has been scheduled.
160     if (first && count != 0)
161     {
162         std::cerr
163             << "ControlLoops has been scheduled, refresh the loop count\n";
164         count = 1;
165         return;
166     }
167 
168     auto restartLbd = [](const boost::system::error_code& error) {
169         if (error == boost::asio::error::operation_aborted)
170         {
171             return;
172         }
173 
174         // for the last loop, don't elminate the failure of restartControlLoops.
175         if (count >= 5)
176         {
177             restartControlLoops();
178             // reset count after succesful restartControlLoops()
179             count = 0;
180             return;
181         }
182 
183         // retry when restartControlLoops() has some failure.
184         try
185         {
186             restartControlLoops();
187             // reset count after succesful restartControlLoops()
188             count = 0;
189         }
190         catch (const std::exception& e)
191         {
192             std::cerr << count
193                       << " Failed during restartControlLoops, try again: "
194                       << e.what() << "\n";
195             tryRestartControlLoops(false);
196         }
197     };
198     count++;
199     // first time of trying to restart the control loop without a delay
200     if (first)
201     {
202         boost::asio::post(io,
203                           std::bind(restartLbd, boost::system::error_code()));
204     }
205     // re-try control loop, set up a delay.
206     else
207     {
208         timer.expires_after(delayTime);
209         timer.async_wait(restartLbd);
210     }
211 
212     return;
213 }
214 
215 } // namespace pid_control
216 
217 void sighupHandler(const boost::system::error_code& error, int signal_number)
218 {
219     static boost::asio::steady_timer timer(io);
220 
221     if (error)
222     {
223         std::cout << "Signal " << signal_number
224                   << " handler error: " << error.message() << "\n";
225         return;
226     }
227 
228     timer.expires_after(std::chrono::seconds(1));
229     timer.async_wait([](const boost::system::error_code ec) {
230         if (ec)
231         {
232             std::cout << "Signal timer error: " << ec.message() << "\n";
233             return;
234         }
235 
236         std::cout << "reloading configuration\n";
237         pid_control::tryRestartControlLoops();
238     });
239     signals.async_wait(sighupHandler);
240 }
241 
242 int main(int argc, char* argv[])
243 {
244     loggingPath = "";
245     loggingEnabled = false;
246     tuningEnabled = false;
247     debugEnabled = false;
248     coreLoggingEnabled = false;
249 
250     CLI::App app{"OpenBMC Fan Control Daemon"};
251 
252     app.add_option("-c,--conf", configPath,
253                    "Optional parameter to specify configuration at run-time")
254         ->check(CLI::ExistingFile);
255     app.add_option("-l,--log", loggingPath,
256                    "Optional parameter to specify logging folder")
257         ->check(CLI::ExistingDirectory);
258     app.add_flag("-t,--tuning", tuningEnabled, "Enable or disable tuning");
259     app.add_flag("-d,--debug", debugEnabled, "Enable or disable debug mode");
260     app.add_flag("-g,--corelogging", coreLoggingEnabled,
261                  "Enable or disable logging of core PID loop computations");
262 
263     CLI11_PARSE(app, argc, argv);
264 
265     static constexpr auto loggingEnablePath = "/etc/thermal.d/logging";
266     static constexpr auto tuningEnablePath = "/etc/thermal.d/tuning";
267     static constexpr auto debugEnablePath = "/etc/thermal.d/debugging";
268     static constexpr auto coreLoggingEnablePath = "/etc/thermal.d/corelogging";
269 
270     // Set up default logging path, preferring command line if it was given
271     std::string defLoggingPath(loggingPath);
272     if (defLoggingPath.empty())
273     {
274         defLoggingPath = std::filesystem::temp_directory_path();
275     }
276     else
277     {
278         // Enable logging, if user explicitly gave path on command line
279         loggingEnabled = true;
280     }
281 
282     // If this file exists, enable logging at runtime
283     std::ifstream fsLogging(loggingEnablePath);
284     if (fsLogging)
285     {
286         // Allow logging path to be changed by file content
287         std::string altPath;
288         std::getline(fsLogging, altPath);
289         fsLogging.close();
290 
291         if (std::filesystem::exists(altPath))
292         {
293             loggingPath = altPath;
294         }
295 
296         loggingEnabled = true;
297     }
298     if (loggingEnabled)
299     {
300         std::cerr << "Logging enabled: " << loggingPath << "\n";
301     }
302 
303     // If this file exists, enable tuning at runtime
304     if (std::filesystem::exists(tuningEnablePath))
305     {
306         tuningEnabled = true;
307     }
308     if (tuningEnabled)
309     {
310         std::cerr << "Tuning enabled\n";
311     }
312 
313     // If this file exists, enable debug mode at runtime
314     if (std::filesystem::exists(debugEnablePath))
315     {
316         debugEnabled = true;
317     }
318 
319     if (debugEnabled)
320     {
321         std::cerr << "Debug mode enabled\n";
322     }
323 
324     // If this file exists, enable core logging at runtime
325     if (std::filesystem::exists(coreLoggingEnablePath))
326     {
327         coreLoggingEnabled = true;
328     }
329     if (coreLoggingEnabled)
330     {
331         std::cerr << "Core logging enabled\n";
332     }
333 
334     static constexpr auto modeRoot = "/xyz/openbmc_project/settings/fanctrl";
335     // Create a manager for the ModeBus because we own it.
336     sdbusplus::server::manager_t(static_cast<sdbusplus::bus_t&>(modeControlBus),
337                                  modeRoot);
338     hostBus.request_name("xyz.openbmc_project.Hwmon.external");
339     modeControlBus.request_name("xyz.openbmc_project.State.FanCtrl");
340     sdbusplus::server::manager_t objManager(modeControlBus, modeRoot);
341 
342     // Enable SIGHUP handling to reload JSON config
343     signals.async_wait(sighupHandler);
344 
345     /*
346      * All sensors are managed by one manager, but each zone has a pointer to
347      * it.
348      */
349 
350     pid_control::tryRestartControlLoops();
351 
352     io.run();
353     return 0;
354 }
355