xref: /openbmc/phosphor-pid-control/main.cpp (revision 0e8fc398)
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 
248     CLI::App app{"OpenBMC Fan Control Daemon"};
249 
250     app.add_option("-c,--conf", configPath,
251                    "Optional parameter to specify configuration at run-time")
252         ->check(CLI::ExistingFile);
253     app.add_option("-l,--log", loggingPath,
254                    "Optional parameter to specify logging folder")
255         ->check(CLI::ExistingDirectory);
256     app.add_flag("-t,--tuning", tuningEnabled, "Enable or disable tuning");
257 
258     CLI11_PARSE(app, argc, argv);
259 
260     static constexpr auto loggingEnablePath = "/etc/thermal.d/logging";
261     static constexpr auto tuningEnablePath = "/etc/thermal.d/tuning";
262 
263     // Set up default logging path, preferring command line if it was given
264     std::string defLoggingPath(loggingPath);
265     if (defLoggingPath.empty())
266     {
267         defLoggingPath = std::filesystem::temp_directory_path();
268     }
269     else
270     {
271         // Enable logging, if user explicitly gave path on command line
272         loggingEnabled = true;
273     }
274 
275     // If this file exists, enable logging at runtime
276     std::ifstream fsLogging(loggingEnablePath);
277     if (fsLogging)
278     {
279         // The first line of file might be a valid directory path
280         std::getline(fsLogging, loggingPath);
281         fsLogging.close();
282 
283         // If so, use it, otherwise use default logging path instead
284         if (!(std::filesystem::exists(loggingPath)))
285         {
286             loggingPath = defLoggingPath;
287         }
288 
289         loggingEnabled = true;
290     }
291 
292     if (loggingEnabled)
293     {
294         std::cerr << "Logging enabled: " << loggingPath << "\n";
295     }
296 
297     // If this file exists, enable tuning at runtime
298     if (std::filesystem::exists(tuningEnablePath))
299     {
300         tuningEnabled = true;
301     }
302 
303     // This can also be enabled from the command line
304     if (tuningEnabled)
305     {
306         std::cerr << "Tuning enabled\n";
307     }
308 
309     static constexpr auto modeRoot = "/xyz/openbmc_project/settings/fanctrl";
310     // Create a manager for the ModeBus because we own it.
311     sdbusplus::server::manager_t(static_cast<sdbusplus::bus_t&>(modeControlBus),
312                                  modeRoot);
313     hostBus.request_name("xyz.openbmc_project.Hwmon.external");
314     modeControlBus.request_name("xyz.openbmc_project.State.FanCtrl");
315     sdbusplus::server::manager_t objManager(modeControlBus, modeRoot);
316 
317     // Enable SIGHUP handling to reload JSON config
318     signals.async_wait(sighupHandler);
319 
320     /*
321      * All sensors are managed by one manager, but each zone has a pointer to
322      * it.
323      */
324 
325     pid_control::tryRestartControlLoops();
326 
327     io.run();
328     return 0;
329 }
330