xref: /openbmc/phosphor-pid-control/main.cpp (revision 1df9e879)
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 
85     for (const auto timer : timers)
86     {
87         timer->cancel();
88     }
89     timers.clear();
90     zones.clear();
91 
92     const std::string& path =
93         (configPath.length() > 0) ? configPath : jsonConfigurationPath;
94 
95     if (std::filesystem::exists(path))
96     {
97         /*
98          * When building the sensors, if any of the dbus passive ones aren't on
99          * the bus, it'll fail immediately.
100          */
101         try
102         {
103             auto jsonData = parseValidateJson(path);
104             sensorConfig = buildSensorsFromJson(jsonData);
105             std::tie(zoneConfig, zoneDetailsConfig) =
106                 buildPIDsFromJson(jsonData);
107         }
108         catch (const std::exception& e)
109         {
110             std::cerr << "Failed during building: " << e.what() << "\n";
111             exit(EXIT_FAILURE); /* fatal error. */
112         }
113     }
114     else
115     {
116         static boost::asio::steady_timer reloadTimer(io);
117         if (!dbus_configuration::init(modeControlBus, reloadTimer, sensorConfig,
118                                       zoneConfig, zoneDetailsConfig))
119         {
120             return; // configuration not ready
121         }
122     }
123 
124     mgmr = buildSensors(sensorConfig, passiveBus, hostBus);
125     zones = buildZones(zoneConfig, zoneDetailsConfig, mgmr, modeControlBus);
126 
127     if (0 == zones.size())
128     {
129         std::cerr << "No zones defined, exiting.\n";
130         std::exit(EXIT_FAILURE);
131     }
132 
133     for (const auto& i : zones)
134     {
135         std::shared_ptr<boost::asio::steady_timer> timer = timers.emplace_back(
136             std::make_shared<boost::asio::steady_timer>(io));
137         std::cerr << "pushing zone " << i.first << "\n";
138         pidControlLoop(i.second, timer);
139     }
140 }
141 
142 void tryRestartControlLoops()
143 {
144     int count = 0;
145     for (count = 0; count <= 5; count++)
146     {
147         try
148         {
149             restartControlLoops();
150             break;
151         }
152         catch (const std::exception& e)
153         {
154             std::cerr << count
155                       << " Failed during restartControlLoops, try again: "
156                       << e.what() << "\n";
157             if (count >= 5)
158             {
159                 throw std::runtime_error(e.what());
160             }
161         }
162         std::this_thread::sleep_for(std::chrono::seconds(10));
163     }
164 
165     return;
166 }
167 
168 } // namespace pid_control
169 
170 int main(int argc, char* argv[])
171 {
172     loggingPath = "";
173     loggingEnabled = false;
174     tuningEnabled = false;
175 
176     CLI::App app{"OpenBMC Fan Control Daemon"};
177 
178     app.add_option("-c,--conf", configPath,
179                    "Optional parameter to specify configuration at run-time")
180         ->check(CLI::ExistingFile);
181     app.add_option("-l,--log", loggingPath,
182                    "Optional parameter to specify logging folder")
183         ->check(CLI::ExistingDirectory);
184     app.add_flag("-t,--tuning", tuningEnabled, "Enable or disable tuning");
185 
186     CLI11_PARSE(app, argc, argv);
187 
188     static constexpr auto loggingEnablePath = "/etc/thermal.d/logging";
189     static constexpr auto tuningEnablePath = "/etc/thermal.d/tuning";
190 
191     // If this file exists, enable logging at runtime
192     std::ifstream fsLogging(loggingEnablePath);
193     if (fsLogging)
194     {
195         // Unless file contents are a valid directory path, use system default
196         std::getline(fsLogging, loggingPath);
197         if (!(std::filesystem::exists(loggingPath)))
198         {
199             loggingPath = std::filesystem::temp_directory_path();
200         }
201         fsLogging.close();
202 
203         loggingEnabled = true;
204         std::cerr << "Logging enabled: " << loggingPath << "\n";
205     }
206 
207     // If this file exists, enable tuning at runtime
208     if (std::filesystem::exists(tuningEnablePath))
209     {
210         tuningEnabled = true;
211         std::cerr << "Tuning enabled\n";
212     }
213 
214     static constexpr auto modeRoot = "/xyz/openbmc_project/settings/fanctrl";
215     // Create a manager for the ModeBus because we own it.
216     sdbusplus::server::manager::manager(
217         static_cast<sdbusplus::bus::bus&>(modeControlBus), modeRoot);
218     hostBus.request_name("xyz.openbmc_project.Hwmon.external");
219     modeControlBus.request_name("xyz.openbmc_project.State.FanCtrl");
220 
221     /*
222      * All sensors are managed by one manager, but each zone has a pointer to
223      * it.
224      */
225 
226     pid_control::tryRestartControlLoops();
227 
228     io.run();
229     return 0;
230 }
231