xref: /openbmc/phosphor-pid-control/main.cpp (revision e39bbe9f)
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 "build/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/steady_timer.hpp>
36 #include <sdbusplus/asio/connection.hpp>
37 #include <sdbusplus/bus.hpp>
38 
39 #include <chrono>
40 #include <filesystem>
41 #include <iostream>
42 #include <list>
43 #include <map>
44 #include <memory>
45 #include <thread>
46 #include <unordered_map>
47 #include <utility>
48 #include <vector>
49 
50 namespace pid_control
51 {
52 
53 /* The configuration converted sensor list. */
54 std::map<std::string, conf::SensorConfig> sensorConfig = {};
55 /* The configuration converted PID list. */
56 std::map<int64_t, conf::PIDConf> zoneConfig = {};
57 /* The configuration converted Zone configuration. */
58 std::map<int64_t, conf::ZoneConfig> zoneDetailsConfig = {};
59 
60 } // namespace pid_control
61 
62 /** the swampd daemon will check for the existence of this file. */
63 constexpr auto jsonConfigurationPath = "/usr/share/swampd/config.json";
64 std::string configPath = "";
65 
66 /* async io context for operation */
67 boost::asio::io_context io;
68 
69 /* buses for system control */
70 static sdbusplus::asio::connection modeControlBus(io);
71 static sdbusplus::asio::connection
72     hostBus(io, sdbusplus::bus::new_system().release());
73 static sdbusplus::asio::connection
74     passiveBus(io, sdbusplus::bus::new_system().release());
75 
76 namespace pid_control
77 {
78 
79 void restartControlLoops()
80 {
81     static SensorManager mgmr;
82     static std::unordered_map<int64_t, std::shared_ptr<ZoneInterface>> zones;
83     static std::vector<std::shared_ptr<boost::asio::steady_timer>> timers;
84     static bool isCanceling = false;
85 
86     for (const auto timer : timers)
87     {
88         timer->cancel();
89     }
90     isCanceling = true;
91     timers.clear();
92 
93     if (zones.size() > 0 && zones.begin()->second.use_count() > 1)
94     {
95         throw std::runtime_error("wait for count back to 1");
96     }
97     zones.clear();
98     isCanceling = false;
99 
100     const std::string& path =
101         (configPath.length() > 0) ? configPath : jsonConfigurationPath;
102 
103     if (std::filesystem::exists(path))
104     {
105         /*
106          * When building the sensors, if any of the dbus passive ones aren't on
107          * the bus, it'll fail immediately.
108          */
109         try
110         {
111             auto jsonData = parseValidateJson(path);
112             sensorConfig = buildSensorsFromJson(jsonData);
113             std::tie(zoneConfig, zoneDetailsConfig) =
114                 buildPIDsFromJson(jsonData);
115         }
116         catch (const std::exception& e)
117         {
118             std::cerr << "Failed during building: " << e.what() << "\n";
119             exit(EXIT_FAILURE); /* fatal error. */
120         }
121     }
122     else
123     {
124         static boost::asio::steady_timer reloadTimer(io);
125         if (!dbus_configuration::init(modeControlBus, reloadTimer, sensorConfig,
126                                       zoneConfig, zoneDetailsConfig))
127         {
128             return; // configuration not ready
129         }
130     }
131 
132     mgmr = buildSensors(sensorConfig, passiveBus, hostBus);
133     zones = buildZones(zoneConfig, zoneDetailsConfig, mgmr, modeControlBus);
134 
135     if (0 == zones.size())
136     {
137         std::cerr << "No zones defined, exiting.\n";
138         std::exit(EXIT_FAILURE);
139     }
140 
141     for (const auto& i : zones)
142     {
143         std::shared_ptr<boost::asio::steady_timer> timer = timers.emplace_back(
144             std::make_shared<boost::asio::steady_timer>(io));
145         std::cerr << "pushing zone " << i.first << "\n";
146         pidControlLoop(i.second, timer, &isCanceling);
147     }
148 }
149 
150 void tryRestartControlLoops(bool first)
151 {
152     static int count = 0;
153     static const auto delayTime = std::chrono::seconds(10);
154     static boost::asio::steady_timer timer(io);
155     // try to start a control loop while the loop has been scheduled.
156     if (first && count != 0)
157     {
158         std::cerr
159             << "ControlLoops has been scheduled, refresh the loop count\n";
160         count = 1;
161         return;
162     }
163 
164     auto restartLbd = [](const boost::system::error_code& error) {
165         if (error == boost::asio::error::operation_aborted)
166         {
167             return;
168         }
169 
170         // for the last loop, don't elminate the failure of restartControlLoops.
171         if (count >= 5)
172         {
173             restartControlLoops();
174             // reset count after succesful restartControlLoops()
175             count = 0;
176             return;
177         }
178 
179         // retry when restartControlLoops() has some failure.
180         try
181         {
182             restartControlLoops();
183             // reset count after succesful restartControlLoops()
184             count = 0;
185         }
186         catch (const std::exception& e)
187         {
188             std::cerr << count
189                       << " Failed during restartControlLoops, try again: "
190                       << e.what() << "\n";
191             tryRestartControlLoops(false);
192         }
193     };
194     count++;
195     // first time of trying to restart the control loop without a delay
196     if (first)
197     {
198         boost::asio::post(io,
199                           std::bind(restartLbd, boost::system::error_code()));
200     }
201     // re-try control loop, set up a delay.
202     else
203     {
204         timer.expires_after(delayTime);
205         timer.async_wait(restartLbd);
206     }
207 
208     return;
209 }
210 
211 } // namespace pid_control
212 
213 int main(int argc, char* argv[])
214 {
215     loggingPath = "";
216     loggingEnabled = false;
217     tuningEnabled = false;
218 
219     CLI::App app{"OpenBMC Fan Control Daemon"};
220 
221     app.add_option("-c,--conf", configPath,
222                    "Optional parameter to specify configuration at run-time")
223         ->check(CLI::ExistingFile);
224     app.add_option("-l,--log", loggingPath,
225                    "Optional parameter to specify logging folder")
226         ->check(CLI::ExistingDirectory);
227     app.add_flag("-t,--tuning", tuningEnabled, "Enable or disable tuning");
228 
229     CLI11_PARSE(app, argc, argv);
230 
231     static constexpr auto loggingEnablePath = "/etc/thermal.d/logging";
232     static constexpr auto tuningEnablePath = "/etc/thermal.d/tuning";
233 
234     // If this file exists, enable logging at runtime
235     std::ifstream fsLogging(loggingEnablePath);
236     if (fsLogging)
237     {
238         // Unless file contents are a valid directory path, use system default
239         std::getline(fsLogging, loggingPath);
240         if (!(std::filesystem::exists(loggingPath)))
241         {
242             loggingPath = std::filesystem::temp_directory_path();
243         }
244         fsLogging.close();
245 
246         loggingEnabled = true;
247         std::cerr << "Logging enabled: " << loggingPath << "\n";
248     }
249 
250     // If this file exists, enable tuning at runtime
251     if (std::filesystem::exists(tuningEnablePath))
252     {
253         tuningEnabled = true;
254         std::cerr << "Tuning enabled\n";
255     }
256 
257     static constexpr auto modeRoot = "/xyz/openbmc_project/settings/fanctrl";
258     // Create a manager for the ModeBus because we own it.
259     sdbusplus::server::manager::manager(
260         static_cast<sdbusplus::bus::bus&>(modeControlBus), modeRoot);
261     hostBus.request_name("xyz.openbmc_project.Hwmon.external");
262     modeControlBus.request_name("xyz.openbmc_project.State.FanCtrl");
263 
264     /*
265      * All sensors are managed by one manager, but each zone has a pointer to
266      * it.
267      */
268 
269     pid_control::tryRestartControlLoops();
270 
271     io.run();
272     return 0;
273 }
274