blob: bf11cba6370faac2efe45de1087cef755c4b46d2 [file] [log] [blame]
Matthew Barth4f0d3b72020-08-27 14:32:15 -05001/**
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 */
Matthew Bartha0dd1352021-03-09 11:10:49 -060016#include "config.h"
17
Matthew Barth4f0d3b72020-08-27 14:32:15 -050018#include "zone.hpp"
19
Matthew Barthde90fb42021-03-04 16:34:28 -060020#include "fan.hpp"
Matthew Barth9403a212021-05-17 09:31:50 -050021#include "sdbusplus.hpp"
Matthew Barth216229c2020-09-24 13:47:33 -050022
Matthew Bartha0dd1352021-03-09 11:10:49 -060023#include <cereal/archives/json.hpp>
24#include <cereal/cereal.hpp>
Matthew Barth4f0d3b72020-08-27 14:32:15 -050025#include <nlohmann/json.hpp>
26#include <phosphor-logging/log.hpp>
Matthew Barthacd737c2021-03-04 11:04:01 -060027#include <sdbusplus/bus.hpp>
Matthew Barth603ef162021-03-24 15:34:53 -050028#include <sdeventplus/event.hpp>
Matthew Barth4f0d3b72020-08-27 14:32:15 -050029
Matthew Bartha0dd1352021-03-09 11:10:49 -060030#include <algorithm>
Matthew Barth007de092021-03-25 13:56:04 -050031#include <chrono>
Matthew Bartha0dd1352021-03-09 11:10:49 -060032#include <filesystem>
33#include <fstream>
Matthew Barth651f03a2020-08-27 16:15:11 -050034#include <iterator>
35#include <map>
36#include <numeric>
Matthew Barth651f03a2020-08-27 16:15:11 -050037#include <utility>
Matthew Barth216229c2020-09-24 13:47:33 -050038#include <vector>
Matthew Barth651f03a2020-08-27 16:15:11 -050039
Matthew Barth4f0d3b72020-08-27 14:32:15 -050040namespace phosphor::fan::control::json
41{
42
43using json = nlohmann::json;
44using namespace phosphor::logging;
Matthew Bartha0dd1352021-03-09 11:10:49 -060045namespace fs = std::filesystem;
Matthew Barth4f0d3b72020-08-27 14:32:15 -050046
Matthew Barthb584d812021-03-11 15:55:04 -060047const std::map<std::string,
48 std::map<std::string, std::function<std::function<void(Zone*)>(
49 const json&, bool)>>>
Matthew Barth216229c2020-09-24 13:47:33 -050050 Zone::_intfPropHandlers = {{thermModeIntf,
51 {{supportedProp, zone::property::supported},
52 {currentProp, zone::property::current}}}};
Matthew Barth651f03a2020-08-27 16:15:11 -050053
Matthew Barth9403a212021-05-17 09:31:50 -050054Zone::Zone(const json& jsonObj, const sdeventplus::Event& event, Manager* mgr) :
Matthew Bartha0dd1352021-03-09 11:10:49 -060055 ConfigBase(jsonObj),
Matthew Barth9403a212021-05-17 09:31:50 -050056 ThermalObject(util::SDBusPlus::getBus(),
57 (fs::path{CONTROL_OBJPATH} /= getName()).c_str(), true),
Matthew Barth603ef162021-03-24 15:34:53 -050058 _manager(mgr), _incDelay(0), _floor(0), _target(0), _incDelta(0),
Matthew Barth007de092021-03-25 13:56:04 -050059 _decDelta(0), _requestTargetBase(0), _isActive(true),
60 _incTimer(event, std::bind(&Zone::incTimerExpired, this)),
61 _decTimer(event, std::bind(&Zone::decTimerExpired, this))
Matthew Barth4f0d3b72020-08-27 14:32:15 -050062{
Matthew Barthe47c9582021-03-09 14:24:02 -060063 // Increase delay is optional, defaults to 0
Matthew Barth4f0d3b72020-08-27 14:32:15 -050064 if (jsonObj.contains("increase_delay"))
65 {
Matthew Barth007de092021-03-25 13:56:04 -050066 _incDelay =
67 std::chrono::seconds(jsonObj["increase_delay"].get<uint64_t>());
Matthew Barth4f0d3b72020-08-27 14:32:15 -050068 }
Matthew Barthe47c9582021-03-09 14:24:02 -060069 setDefaultCeiling(jsonObj);
Matthew Barth4f0d3b72020-08-27 14:32:15 -050070 setDefaultFloor(jsonObj);
71 setDecInterval(jsonObj);
Matthew Barth651f03a2020-08-27 16:15:11 -050072 // Setting properties on interfaces to be served are optional
73 if (jsonObj.contains("interfaces"))
74 {
75 setInterfaces(jsonObj);
76 }
Matthew Barth007de092021-03-25 13:56:04 -050077
Matthew Bartha4483742021-03-25 14:09:01 -050078 // Restore thermal control current mode state
79 restoreCurrentMode();
80
81 // Emit object added for this zone dbus object
82 this->emit_object_added();
83
Matthew Barth007de092021-03-25 13:56:04 -050084 // Start timer for fan target decreases
85 _decTimer.restart(_decInterval);
Matthew Barth4f0d3b72020-08-27 14:32:15 -050086}
87
Matthew Barthde90fb42021-03-04 16:34:28 -060088void Zone::addFan(std::unique_ptr<Fan> fan)
89{
90 _fans.emplace_back(std::move(fan));
91}
92
Matthew Barth8ba715e2021-03-05 09:00:05 -060093void Zone::setTarget(uint64_t target)
94{
Matthew Barth6f787302021-03-25 15:01:01 -050095 if (_isActive && _target != target)
Matthew Barth8ba715e2021-03-05 09:00:05 -060096 {
97 _target = target;
98 for (auto& fan : _fans)
99 {
100 fan->setTarget(_target);
101 }
102 }
103}
104
105void Zone::setActiveAllow(const std::string& ident, bool isActiveAllow)
106{
107 _active[ident] = isActiveAllow;
108 if (!isActiveAllow)
109 {
110 _isActive = false;
111 }
112 else
113 {
114 // Check all entries are set to allow active fan control
115 auto actPred = [](const auto& entry) { return entry.second; };
116 _isActive = std::all_of(_active.begin(), _active.end(), actPred);
117 }
118}
119
Matthew Barth12cb1252021-03-08 16:47:30 -0600120void Zone::setFloor(uint64_t target)
121{
122 // Check all entries are set to allow floor to be set
Matthew Barth8ba715e2021-03-05 09:00:05 -0600123 auto pred = [](const auto& entry) { return entry.second; };
Matthew Barth12cb1252021-03-08 16:47:30 -0600124 if (std::all_of(_floorChange.begin(), _floorChange.end(), pred))
125 {
126 _floor = target;
127 // Floor above target, update target to floor
128 if (_target < _floor)
129 {
130 requestIncrease(_floor - _target);
131 }
132 }
133}
134
135void Zone::requestIncrease(uint64_t targetDelta)
136{
Matthew Barth2b3253e2021-03-09 14:51:16 -0600137 // Only increase when delta is higher than the current increase delta for
138 // the zone and currently under ceiling
139 if (targetDelta > _incDelta && _target < _ceiling)
140 {
141 auto requestTarget = getRequestTargetBase();
142 requestTarget = (targetDelta - _incDelta) + requestTarget;
143 _incDelta = targetDelta;
144 // Target can not go above a current ceiling
145 if (requestTarget > _ceiling)
146 {
147 requestTarget = _ceiling;
148 }
Matthew Barth8ba715e2021-03-05 09:00:05 -0600149 setTarget(requestTarget);
Matthew Barth007de092021-03-25 13:56:04 -0500150 // Restart timer countdown for fan target increase
151 _incTimer.restartOnce(_incDelay);
Matthew Barth2b3253e2021-03-09 14:51:16 -0600152 }
Matthew Barth12cb1252021-03-08 16:47:30 -0600153}
154
Matthew Barth007de092021-03-25 13:56:04 -0500155void Zone::incTimerExpired()
156{
157 // Clear increase delta when timer expires allowing additional target
158 // increase requests or target decreases to occur
159 _incDelta = 0;
160}
161
Matthew Barth45c44ea2021-03-03 13:16:14 -0600162void Zone::requestDecrease(uint64_t targetDelta)
163{
164 // Only decrease the lowest target delta requested
165 if (_decDelta == 0 || targetDelta < _decDelta)
166 {
167 _decDelta = targetDelta;
168 }
169}
170
Matthew Barth007de092021-03-25 13:56:04 -0500171void Zone::decTimerExpired()
172{
173 // Check all entries are set to allow a decrease
174 auto pred = [](auto const& entry) { return entry.second; };
175 auto decAllowed = std::all_of(_decAllowed.begin(), _decAllowed.end(), pred);
176
177 // Only decrease targets when allowed, a requested decrease target delta
178 // exists, where no requested increases exist and the increase timer is not
179 // running (i.e. not in the middle of increasing)
180 if (decAllowed && _decDelta != 0 && _incDelta == 0 &&
181 !_incTimer.isEnabled())
182 {
183 auto requestTarget = getRequestTargetBase();
184 // Request target should not start above ceiling
185 if (requestTarget > _ceiling)
186 {
187 requestTarget = _ceiling;
188 }
189 // Target can not go below the defined floor
190 if ((requestTarget < _decDelta) || (requestTarget - _decDelta < _floor))
191 {
192 requestTarget = _floor;
193 }
194 else
195 {
196 requestTarget = requestTarget - _decDelta;
197 }
198 setTarget(requestTarget);
199 }
200 // Clear decrease delta when timer expires
201 _decDelta = 0;
202 // Decrease timer is restarted since its repeating
203}
204
Matthew Bartha0dd1352021-03-09 11:10:49 -0600205void Zone::setPersisted(const std::string& intf, const std::string& prop)
206{
207 if (std::find_if(_propsPersisted[intf].begin(), _propsPersisted[intf].end(),
208 [&prop](const auto& p) { return prop == p; }) !=
209 _propsPersisted[intf].end())
210 {
211 _propsPersisted[intf].emplace_back(prop);
212 }
213}
214
215std::string Zone::current(std::string value)
216{
217 auto current = ThermalObject::current();
218 std::transform(value.begin(), value.end(), value.begin(), toupper);
219
220 auto supported = ThermalObject::supported();
221 auto isSupported =
222 std::any_of(supported.begin(), supported.end(), [&value](auto& s) {
223 std::transform(s.begin(), s.end(), s.begin(), toupper);
224 return value == s;
225 });
226
227 if (value != current && isSupported)
228 {
229 current = ThermalObject::current(value);
Matthew Barth50219f52021-05-18 11:20:36 -0500230 if (isPersisted(thermModeIntf, currentProp))
Matthew Bartha0dd1352021-03-09 11:10:49 -0600231 {
232 saveCurrentMode();
233 }
Matthew Bartha0dd1352021-03-09 11:10:49 -0600234 }
235
236 return current;
237}
238
Matthew Barthe47c9582021-03-09 14:24:02 -0600239void Zone::setDefaultCeiling(const json& jsonObj)
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500240{
Matthew Barth5606ec82021-05-17 12:08:52 -0500241 // TODO Remove "full_speed" after configs replaced with "default_ceiling"
242 if (!jsonObj.contains("full_speed") && !jsonObj.contains("default_ceiling"))
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500243 {
Matthew Barth5606ec82021-05-17 12:08:52 -0500244 log<level::ERR>("Missing required zone's default ceiling",
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500245 entry("JSON=%s", jsonObj.dump().c_str()));
Matthew Barth5606ec82021-05-17 12:08:52 -0500246 throw std::runtime_error("Missing required zone's default ceiling");
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500247 }
Matthew Barth5606ec82021-05-17 12:08:52 -0500248 if (jsonObj.contains("full_speed"))
249 {
250 _defaultCeiling = jsonObj["full_speed"].get<uint64_t>();
251 }
252 else
253 {
254 _defaultCeiling = jsonObj["default_ceiling"].get<uint64_t>();
255 }
Matthew Barth12cb1252021-03-08 16:47:30 -0600256 // Start with the current target set as the default
Matthew Barthe47c9582021-03-09 14:24:02 -0600257 _target = _defaultCeiling;
Matthew Barth2b3253e2021-03-09 14:51:16 -0600258 // Start with the current ceiling set as the default
259 _ceiling = _defaultCeiling;
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500260}
261
262void Zone::setDefaultFloor(const json& jsonObj)
263{
264 if (!jsonObj.contains("default_floor"))
265 {
Matthew Barthe47c9582021-03-09 14:24:02 -0600266 log<level::ERR>("Missing required zone's default floor",
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500267 entry("JSON=%s", jsonObj.dump().c_str()));
Matthew Barthe47c9582021-03-09 14:24:02 -0600268 throw std::runtime_error("Missing required zone's default floor");
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500269 }
270 _defaultFloor = jsonObj["default_floor"].get<uint64_t>();
Matthew Barth12cb1252021-03-08 16:47:30 -0600271 // Start with the current floor set as the default
272 _floor = _defaultFloor;
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500273}
274
275void Zone::setDecInterval(const json& jsonObj)
276{
277 if (!jsonObj.contains("decrease_interval"))
278 {
279 log<level::ERR>("Missing required zone's decrease interval",
280 entry("JSON=%s", jsonObj.dump().c_str()));
281 throw std::runtime_error("Missing required zone's decrease interval");
282 }
Matthew Barth007de092021-03-25 13:56:04 -0500283 _decInterval =
284 std::chrono::seconds(jsonObj["decrease_interval"].get<uint64_t>());
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500285}
286
Matthew Barth651f03a2020-08-27 16:15:11 -0500287void Zone::setInterfaces(const json& jsonObj)
288{
289 for (const auto& interface : jsonObj["interfaces"])
290 {
291 if (!interface.contains("name") || !interface.contains("properties"))
292 {
293 log<level::ERR>("Missing required zone interface attributes",
294 entry("JSON=%s", interface.dump().c_str()));
295 throw std::runtime_error(
296 "Missing required zone interface attributes");
297 }
Matthew Barth216229c2020-09-24 13:47:33 -0500298 auto propFuncs =
299 _intfPropHandlers.find(interface["name"].get<std::string>());
300 if (propFuncs == _intfPropHandlers.end())
301 {
302 // Construct list of available configurable interfaces
303 auto intfs = std::accumulate(
304 std::next(_intfPropHandlers.begin()), _intfPropHandlers.end(),
305 _intfPropHandlers.begin()->first, [](auto list, auto intf) {
306 return std::move(list) + ", " + intf.first;
307 });
308 log<level::ERR>("Configured interface not available",
309 entry("JSON=%s", interface.dump().c_str()),
310 entry("AVAILABLE_INTFS=%s", intfs.c_str()));
311 throw std::runtime_error("Configured interface not available");
312 }
313
Matthew Barth651f03a2020-08-27 16:15:11 -0500314 for (const auto& property : interface["properties"])
315 {
316 if (!property.contains("name"))
317 {
318 log<level::ERR>(
319 "Missing required interface property attributes",
320 entry("JSON=%s", property.dump().c_str()));
321 throw std::runtime_error(
322 "Missing required interface property attributes");
323 }
324 // Attribute "persist" is optional, defaults to `false`
325 auto persist = false;
326 if (property.contains("persist"))
327 {
328 persist = property["persist"].get<bool>();
329 }
330 // Property name from JSON must exactly match supported
331 // index names to functions in property namespace
Matthew Barth216229c2020-09-24 13:47:33 -0500332 auto propFunc =
333 propFuncs->second.find(property["name"].get<std::string>());
334 if (propFunc == propFuncs->second.end())
Matthew Barth651f03a2020-08-27 16:15:11 -0500335 {
Matthew Barth216229c2020-09-24 13:47:33 -0500336 // Construct list of available configurable properties
Matthew Barth651f03a2020-08-27 16:15:11 -0500337 auto props = std::accumulate(
Matthew Barth216229c2020-09-24 13:47:33 -0500338 std::next(propFuncs->second.begin()),
339 propFuncs->second.end(), propFuncs->second.begin()->first,
340 [](auto list, auto prop) {
Matthew Barth651f03a2020-08-27 16:15:11 -0500341 return std::move(list) + ", " + prop.first;
342 });
Matthew Barth216229c2020-09-24 13:47:33 -0500343 log<level::ERR>("Configured property not available",
Matthew Barth651f03a2020-08-27 16:15:11 -0500344 entry("JSON=%s", property.dump().c_str()),
345 entry("AVAILABLE_PROPS=%s", props.c_str()));
346 throw std::runtime_error(
347 "Configured property function not available");
348 }
Matthew Barthb584d812021-03-11 15:55:04 -0600349 auto propHandler = propFunc->second(property, persist);
350 // Only call non-null set property handler functions
351 if (propHandler)
352 {
353 propHandler(this);
354 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500355 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500356 }
357}
358
Matthew Bartha0dd1352021-03-09 11:10:49 -0600359bool Zone::isPersisted(const std::string& intf, const std::string& prop)
360{
361 auto it = _propsPersisted.find(intf);
362 if (it == _propsPersisted.end())
363 {
364 return false;
365 }
366
367 return std::any_of(it->second.begin(), it->second.end(),
368 [&prop](const auto& p) { return prop == p; });
369}
370
371void Zone::saveCurrentMode()
372{
373 fs::path path{CONTROL_PERSIST_ROOT_PATH};
374 // Append zone name and property description
375 path /= getName();
376 path /= "CurrentMode";
377 std::ofstream ofs(path.c_str(), std::ios::binary);
378 cereal::JSONOutputArchive oArch(ofs);
379 oArch(ThermalObject::current());
380}
381
Matthew Bartha4483742021-03-25 14:09:01 -0500382void Zone::restoreCurrentMode()
383{
384 auto current = ThermalObject::current();
385 fs::path path{CONTROL_PERSIST_ROOT_PATH};
386 path /= getName();
387 path /= "CurrentMode";
388 fs::create_directories(path.parent_path());
389
390 try
391 {
392 if (fs::exists(path))
393 {
394 std::ifstream ifs(path.c_str(), std::ios::in | std::ios::binary);
395 cereal::JSONInputArchive iArch(ifs);
396 iArch(current);
397 }
398 }
399 catch (std::exception& e)
400 {
401 log<level::ERR>(e.what());
402 fs::remove(path);
403 current = ThermalObject::current();
404 }
405
406 this->current(current);
407}
408
Matthew Barth651f03a2020-08-27 16:15:11 -0500409/**
Matthew Barth216229c2020-09-24 13:47:33 -0500410 * Properties of interfaces supported by the zone configuration that return
Matthew Barthb584d812021-03-11 15:55:04 -0600411 * a handler function that sets the zone's property value(s) and persist state.
Matthew Barth651f03a2020-08-27 16:15:11 -0500412 */
413namespace zone::property
414{
Matthew Barthb584d812021-03-11 15:55:04 -0600415// Get a set property handler function for the configured values of the
416// "Supported" property
417std::function<void(Zone*)> supported(const json& jsonObj, bool persist)
Matthew Barth651f03a2020-08-27 16:15:11 -0500418{
419 std::vector<std::string> values;
Matthew Barth216229c2020-09-24 13:47:33 -0500420 if (!jsonObj.contains("values"))
Matthew Barth651f03a2020-08-27 16:15:11 -0500421 {
Matthew Barth216229c2020-09-24 13:47:33 -0500422 log<level::ERR>(
423 "No 'values' found for \"Supported\" property, using an empty list",
424 entry("JSON=%s", jsonObj.dump().c_str()));
425 }
426 else
427 {
428 for (const auto& value : jsonObj["values"])
429 {
430 if (!value.contains("value"))
431 {
432 log<level::ERR>("No 'value' found for \"Supported\" property "
433 "entry, skipping",
434 entry("JSON=%s", value.dump().c_str()));
435 }
436 else
437 {
438 values.emplace_back(value["value"].get<std::string>());
439 }
440 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500441 }
442
Matthew Barthb584d812021-03-11 15:55:04 -0600443 return Zone::setProperty<std::vector<std::string>>(
444 Zone::thermModeIntf, Zone::supportedProp, &Zone::supported,
445 std::move(values), persist);
Matthew Barth651f03a2020-08-27 16:15:11 -0500446}
447
Matthew Barthb584d812021-03-11 15:55:04 -0600448// Get a set property handler function for a configured value of the "Current"
Matthew Barth216229c2020-09-24 13:47:33 -0500449// property
Matthew Barthb584d812021-03-11 15:55:04 -0600450std::function<void(Zone*)> current(const json& jsonObj, bool persist)
Matthew Barth651f03a2020-08-27 16:15:11 -0500451{
Matthew Barth216229c2020-09-24 13:47:33 -0500452 // Use default value for "Current" property if no "value" entry given
453 if (!jsonObj.contains("value"))
454 {
Matthew Barthb584d812021-03-11 15:55:04 -0600455 log<level::INFO>("No 'value' found for \"Current\" property, "
456 "using default",
457 entry("JSON=%s", jsonObj.dump().c_str()));
458 // Set persist state of property
459 return Zone::setPropertyPersist(Zone::thermModeIntf, Zone::currentProp,
460 persist);
Matthew Barth216229c2020-09-24 13:47:33 -0500461 }
462
Matthew Barthb584d812021-03-11 15:55:04 -0600463 return Zone::setProperty<std::string>(
464 Zone::thermModeIntf, Zone::currentProp, &Zone::current,
465 jsonObj["value"].get<std::string>(), persist);
Matthew Barth651f03a2020-08-27 16:15:11 -0500466}
Matthew Barthb584d812021-03-11 15:55:04 -0600467
Matthew Barth651f03a2020-08-27 16:15:11 -0500468} // namespace zone::property
469
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500470} // namespace phosphor::fan::control::json