1 /**
2  * Copyright © 2022 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  */
16 #include "config.h"
17 
18 #include "manager.hpp"
19 
20 #include "action.hpp"
21 #include "dbus_paths.hpp"
22 #include "event.hpp"
23 #include "fan.hpp"
24 #include "group.hpp"
25 #include "json_config.hpp"
26 #include "power_state.hpp"
27 #include "profile.hpp"
28 #include "sdbusplus.hpp"
29 #include "utils/flight_recorder.hpp"
30 #include "zone.hpp"
31 
32 #include <systemd/sd-bus.h>
33 
34 #include <nlohmann/json.hpp>
35 #include <sdbusplus/bus.hpp>
36 #include <sdbusplus/server/manager.hpp>
37 #include <sdeventplus/event.hpp>
38 #include <sdeventplus/utility/timer.hpp>
39 
40 #include <algorithm>
41 #include <chrono>
42 #include <filesystem>
43 #include <functional>
44 #include <map>
45 #include <memory>
46 #include <tuple>
47 #include <utility>
48 #include <vector>
49 
50 namespace phosphor::fan::control::json
51 {
52 
53 using json = nlohmann::json;
54 
55 std::vector<std::string> Manager::_activeProfiles;
56 std::map<std::string,
57          std::map<std::string, std::pair<bool, std::vector<std::string>>>>
58     Manager::_servTree;
59 std::map<std::string,
60          std::map<std::string, std::map<std::string, PropertyVariantType>>>
61     Manager::_objects;
62 std::unordered_map<std::string, PropertyVariantType> Manager::_parameters;
63 std::unordered_map<std::string, TriggerActions> Manager::_parameterTriggers;
64 
65 const std::string Manager::dumpFile = "/tmp/fan_control_dump.json";
66 
Manager(const sdeventplus::Event & event)67 Manager::Manager(const sdeventplus::Event& event) :
68     _bus(util::SDBusPlus::getBus()), _event(event),
69     _mgr(util::SDBusPlus::getBus(), CONTROL_OBJPATH), _loadAllowed(true),
70     _powerState(std::make_unique<PGoodState>(
71         util::SDBusPlus::getBus(),
72         std::bind(std::mem_fn(&Manager::powerStateChanged), this,
73                   std::placeholders::_1)))
74 {}
75 
sighupHandler(sdeventplus::source::Signal &,const struct signalfd_siginfo *)76 void Manager::sighupHandler(sdeventplus::source::Signal&,
77                             const struct signalfd_siginfo*)
78 {
79     FlightRecorder::instance().log("main", "SIGHUP received");
80     // Save current set of available and active profiles
81     std::map<configKey, std::unique_ptr<Profile>> profiles;
82     profiles.swap(_profiles);
83     std::vector<std::string> activeProfiles;
84     activeProfiles.swap(_activeProfiles);
85 
86     try
87     {
88         _loadAllowed = true;
89         load();
90     }
91     catch (const std::runtime_error& re)
92     {
93         // Restore saved available and active profiles
94         _loadAllowed = false;
95         _profiles.swap(profiles);
96         _activeProfiles.swap(activeProfiles);
97         log<level::ERR>("Error reloading configs, no changes made",
98                         entry("LOAD_ERROR=%s", re.what()));
99         FlightRecorder::instance().log(
100             "main", std::format("Error reloading configs, no changes made: {}",
101                                 re.what()));
102     }
103 }
104 
dumpDebugData(sdeventplus::source::Signal &,const struct signalfd_siginfo *)105 void Manager::dumpDebugData(sdeventplus::source::Signal&,
106                             const struct signalfd_siginfo*)
107 {
108     json data;
109     FlightRecorder::instance().dump(data);
110     dumpCache(data);
111 
112     std::for_each(_zones.begin(), _zones.end(), [&data](const auto& zone) {
113         data["zones"][zone.second->getName()] = zone.second->dump();
114     });
115 
116     std::ofstream file{Manager::dumpFile};
117     if (!file)
118     {
119         log<level::ERR>("Could not open file for fan dump");
120         return;
121     }
122 
123     file << std::setw(4) << data;
124 }
125 
dumpCache(json & data)126 void Manager::dumpCache(json& data)
127 {
128     auto& objects = data["objects"];
129     for (const auto& [path, interfaces] : _objects)
130     {
131         auto& interfaceJSON = objects[path];
132 
133         for (const auto& [interface, properties] : interfaces)
134         {
135             auto& propertyJSON = interfaceJSON[interface];
136             for (const auto& [propName, propValue] : properties)
137             {
138                 std::visit(
139                     [&obj = propertyJSON[propName]](auto&& val) { obj = val; },
140                     propValue);
141             }
142         }
143     }
144 
145     auto& parameters = data["parameters"];
146     for (const auto& [name, value] : _parameters)
147     {
148         std::visit([&obj = parameters[name]](auto&& val) { obj = val; }, value);
149     }
150 
151     std::for_each(_events.begin(), _events.end(), [&data](const auto& event) {
152         data["events"][event.second->getName()] = event.second->dump();
153     });
154 
155     data["services"] = _servTree;
156 }
157 
load()158 void Manager::load()
159 {
160     if (_loadAllowed)
161     {
162         // Load the available profiles and which are active
163         setProfiles();
164 
165         // Load the zone configurations
166         auto zones = getConfig<Zone>(false, _event, this);
167         // Load the fan configurations and move each fan into its zone
168         auto fans = getConfig<Fan>(false);
169         for (auto& fan : fans)
170         {
171             configKey fanProfile =
172                 std::make_pair(fan.second->getZone(), fan.first.second);
173             auto itZone = std::find_if(
174                 zones.begin(), zones.end(), [&fanProfile](const auto& zone) {
175                     return Manager::inConfig(fanProfile, zone.first);
176                 });
177             if (itZone != zones.end())
178             {
179                 if (itZone->second->getTarget() != fan.second->getTarget() &&
180                     fan.second->getTarget() != 0)
181                 {
182                     // Update zone target to current target of the fan in the
183                     // zone
184                     itZone->second->setTarget(fan.second->getTarget());
185                 }
186                 itZone->second->addFan(std::move(fan.second));
187             }
188         }
189 
190         // Save all currently available groups, if any, then clear for reloading
191         auto groups = std::move(Event::getAllGroups(false));
192         Event::clearAllGroups();
193 
194         std::map<configKey, std::unique_ptr<Event>> events;
195         try
196         {
197             // Load any events configured, including all the groups
198             events = getConfig<Event>(true, this, zones);
199         }
200         catch (const std::runtime_error& re)
201         {
202             // Restore saved set of all available groups for current events
203             Event::setAllGroups(std::move(groups));
204             throw re;
205         }
206 
207         // Enable zones
208         _zones = std::move(zones);
209         std::for_each(_zones.begin(), _zones.end(),
210                       [](const auto& entry) { entry.second->enable(); });
211 
212         // Clear current timers and signal subscriptions before enabling events
213         // To save reloading services and/or objects into cache, do not clear
214         // cache
215         _timers.clear();
216         _signals.clear();
217 
218         // Enable events
219         _events = std::move(events);
220         FlightRecorder::instance().log("main", "Enabling events");
221         std::for_each(_events.begin(), _events.end(),
222                       [](const auto& entry) { entry.second->enable(); });
223         FlightRecorder::instance().log("main", "Done enabling events");
224 
225         _loadAllowed = false;
226     }
227 }
228 
powerStateChanged(bool powerStateOn)229 void Manager::powerStateChanged(bool powerStateOn)
230 {
231     if (powerStateOn)
232     {
233         FlightRecorder::instance().log("power", "Power on");
234         if (_zones.empty())
235         {
236             throw std::runtime_error("No configured zones found at poweron");
237         }
238         std::for_each(_zones.begin(), _zones.end(), [](const auto& entry) {
239             entry.second->setTarget(entry.second->getPoweronTarget());
240         });
241 
242         // Tell events to run their power on triggers
243         std::for_each(_events.begin(), _events.end(),
244                       [](const auto& entry) { entry.second->powerOn(); });
245     }
246     else
247     {
248         FlightRecorder::instance().log("power", "Power off");
249         // Tell events to run their power off triggers
250         std::for_each(_events.begin(), _events.end(),
251                       [](const auto& entry) { entry.second->powerOff(); });
252     }
253 }
254 
getActiveProfiles()255 const std::vector<std::string>& Manager::getActiveProfiles()
256 {
257     return _activeProfiles;
258 }
259 
inConfig(const configKey & input,const configKey & comp)260 bool Manager::inConfig(const configKey& input, const configKey& comp)
261 {
262     // Config names dont match, do not include in config
263     if (input.first != comp.first)
264     {
265         return false;
266     }
267     // No profiles specified by input config, can be used in any config
268     if (input.second.empty())
269     {
270         return true;
271     }
272     else
273     {
274         // Profiles must have one match in the other's profiles(and they must be
275         // an active profile) to be used in the config
276         return std::any_of(
277             input.second.begin(), input.second.end(),
278             [&comp](const auto& lProfile) {
279                 return std::any_of(
280                     comp.second.begin(), comp.second.end(),
281                     [&lProfile](const auto& rProfile) {
282                         if (lProfile != rProfile)
283                         {
284                             return false;
285                         }
286                         auto activeProfs = getActiveProfiles();
287                         return std::find(activeProfs.begin(), activeProfs.end(),
288                                          lProfile) != activeProfs.end();
289                     });
290             });
291     }
292 }
293 
hasOwner(const std::string & path,const std::string & intf)294 bool Manager::hasOwner(const std::string& path, const std::string& intf)
295 {
296     auto itServ = _servTree.find(path);
297     if (itServ == _servTree.end())
298     {
299         // Path not found in cache, therefore owner missing
300         return false;
301     }
302     for (const auto& service : itServ->second)
303     {
304         auto itIntf = std::find_if(
305             service.second.second.begin(), service.second.second.end(),
306             [&intf](const auto& interface) { return intf == interface; });
307         if (itIntf != std::end(service.second.second))
308         {
309             // Service found, return owner state
310             return service.second.first;
311         }
312     }
313     // Interface not found in cache, therefore owner missing
314     return false;
315 }
316 
setOwner(const std::string & serv,bool hasOwner)317 void Manager::setOwner(const std::string& serv, bool hasOwner)
318 {
319     // Update owner state on all entries of `serv`
320     for (auto& itPath : _servTree)
321     {
322         auto itServ = itPath.second.find(serv);
323         if (itServ != itPath.second.end())
324         {
325             itServ->second.first = hasOwner;
326 
327             // Remove associated interfaces from object cache when service no
328             // longer has an owner
329             if (!hasOwner && _objects.find(itPath.first) != _objects.end())
330             {
331                 for (auto& intf : itServ->second.second)
332                 {
333                     _objects[itPath.first].erase(intf);
334                 }
335             }
336         }
337     }
338 }
339 
setOwner(const std::string & path,const std::string & serv,const std::string & intf,bool isOwned)340 void Manager::setOwner(const std::string& path, const std::string& serv,
341                        const std::string& intf, bool isOwned)
342 {
343     // Set owner state for specific object given
344     auto& ownIntf = _servTree[path][serv];
345     ownIntf.first = isOwned;
346     auto itIntf = std::find_if(
347         ownIntf.second.begin(), ownIntf.second.end(),
348         [&intf](const auto& interface) { return intf == interface; });
349     if (itIntf == std::end(ownIntf.second))
350     {
351         ownIntf.second.emplace_back(intf);
352     }
353 
354     // Update owner state on all entries of the same `serv` & `intf`
355     for (auto& itPath : _servTree)
356     {
357         if (itPath.first == path)
358         {
359             // Already set/updated owner on this path for `serv` & `intf`
360             continue;
361         }
362         for (auto& itServ : itPath.second)
363         {
364             if (itServ.first != serv)
365             {
366                 continue;
367             }
368             auto itIntf = std::find_if(
369                 itServ.second.second.begin(), itServ.second.second.end(),
370                 [&intf](const auto& interface) { return intf == interface; });
371             if (itIntf != std::end(itServ.second.second))
372             {
373                 itServ.second.first = isOwned;
374             }
375         }
376     }
377 }
378 
findService(const std::string & path,const std::string & intf)379 const std::string& Manager::findService(const std::string& path,
380                                         const std::string& intf)
381 {
382     static const std::string empty = "";
383 
384     auto itServ = _servTree.find(path);
385     if (itServ != _servTree.end())
386     {
387         for (const auto& service : itServ->second)
388         {
389             auto itIntf = std::find_if(
390                 service.second.second.begin(), service.second.second.end(),
391                 [&intf](const auto& interface) { return intf == interface; });
392             if (itIntf != std::end(service.second.second))
393             {
394                 // Service found, return service name
395                 return service.first;
396             }
397         }
398     }
399 
400     return empty;
401 }
402 
addServices(const std::string & intf,int32_t depth)403 void Manager::addServices(const std::string& intf, int32_t depth)
404 {
405     // Get all subtree objects for the given interface
406     auto objects = util::SDBusPlus::getSubTreeRaw(util::SDBusPlus::getBus(),
407                                                   "/", intf, depth);
408     // Add what's returned to the cache of path->services
409     for (auto& itPath : objects)
410     {
411         auto pathIter = _servTree.find(itPath.first);
412         if (pathIter != _servTree.end())
413         {
414             // Path found in cache
415             for (auto& itServ : itPath.second)
416             {
417                 auto servIter = pathIter->second.find(itServ.first);
418                 if (servIter != pathIter->second.end())
419                 {
420                     if (std::find(servIter->second.second.begin(),
421                                   servIter->second.second.end(), intf) ==
422                         servIter->second.second.end())
423                     {
424                         // Add interface to cache
425                         servIter->second.second.emplace_back(intf);
426                     }
427                 }
428                 else
429                 {
430                     // Service not found in cache
431                     auto intfs = {intf};
432                     pathIter->second[itServ.first] =
433                         std::make_pair(true, intfs);
434                 }
435             }
436         }
437         else
438         {
439             // Path not found in cache
440             auto intfs = {intf};
441             for (const auto& [servName, servIntfs] : itPath.second)
442             {
443                 _servTree[itPath.first][servName] = std::make_pair(true, intfs);
444             }
445         }
446     }
447 }
448 
getService(const std::string & path,const std::string & intf)449 const std::string& Manager::getService(const std::string& path,
450                                        const std::string& intf)
451 {
452     // Retrieve service from cache
453     const auto& serviceName = findService(path, intf);
454     if (serviceName.empty())
455     {
456         addServices(intf, 0);
457         return findService(path, intf);
458     }
459 
460     return serviceName;
461 }
462 
463 std::vector<std::string>
findPaths(const std::string & serv,const std::string & intf)464     Manager::findPaths(const std::string& serv, const std::string& intf)
465 {
466     std::vector<std::string> paths;
467 
468     for (const auto& path : _servTree)
469     {
470         auto itServ = path.second.find(serv);
471         if (itServ != path.second.end())
472         {
473             if (std::find(itServ->second.second.begin(),
474                           itServ->second.second.end(), intf) !=
475                 itServ->second.second.end())
476             {
477                 if (std::find(paths.begin(), paths.end(), path.first) ==
478                     paths.end())
479                 {
480                     paths.push_back(path.first);
481                 }
482             }
483         }
484     }
485 
486     return paths;
487 }
488 
getPaths(const std::string & serv,const std::string & intf)489 std::vector<std::string> Manager::getPaths(const std::string& serv,
490                                            const std::string& intf)
491 {
492     auto paths = findPaths(serv, intf);
493     if (paths.empty())
494     {
495         addServices(intf, 0);
496         return findPaths(serv, intf);
497     }
498 
499     return paths;
500 }
501 
insertFilteredObjects(ManagedObjects & ref)502 void Manager::insertFilteredObjects(ManagedObjects& ref)
503 {
504     // Filter out objects that aren't part of a group
505     const auto& allGroupMembers = Group::getAllMembers();
506     auto it = ref.begin();
507 
508     while (it != ref.end())
509     {
510         if (allGroupMembers.find(it->first) == allGroupMembers.end())
511         {
512             it = ref.erase(it);
513         }
514         else
515         {
516             it++;
517         }
518     }
519 
520     for (auto& [path, pathMap] : ref)
521     {
522         for (auto& [intf, intfMap] : pathMap)
523         {
524             // for each property on this path+interface
525             for (auto& [prop, value] : intfMap)
526             {
527                 setProperty(path, intf, prop, value);
528             }
529         }
530     }
531 }
532 
addObjects(const std::string & path,const std::string & intf,const std::string & prop,const std::string & serviceName)533 void Manager::addObjects(const std::string& path, const std::string& intf,
534                          const std::string& prop,
535                          const std::string& serviceName)
536 {
537     auto service = serviceName;
538     if (service.empty())
539     {
540         service = getService(path, intf);
541         if (service.empty())
542         {
543             // Log service not found for object
544             log<level::DEBUG>(
545                 std::format(
546                     "Unable to get service name for path {}, interface {}",
547                     path, intf)
548                     .c_str());
549             return;
550         }
551     }
552     else
553     {
554         // The service is known, so the service cache can be
555         // populated even if the path itself isn't present.
556         const auto& s = findService(path, intf);
557         if (s.empty())
558         {
559             addServices(intf, 0);
560         }
561     }
562 
563     auto objMgrPaths = getPaths(service, "org.freedesktop.DBus.ObjectManager");
564 
565     bool useManagedObj = false;
566 
567     if (!objMgrPaths.empty())
568     {
569         for (const auto& objMgrPath : objMgrPaths)
570         {
571             // Get all managed objects of service
572             auto objects =
573                 util::SDBusPlus::getManagedObjects<PropertyVariantType>(
574                     _bus, service, objMgrPath);
575             if (objects.size() > 0)
576             {
577                 useManagedObj = true;
578             }
579             // insert all objects that are in groups but remove any NaN values
580             insertFilteredObjects(objects);
581         }
582     }
583 
584     if (!useManagedObj)
585     {
586         // No object manager interface provided by service?
587         // Or no object is managed?
588         // Attempt to retrieve property directly
589         try
590         {
591             auto value =
592                 util::SDBusPlus::getPropertyVariant<PropertyVariantType>(
593                     _bus, service, path, intf, prop);
594 
595             setProperty(path, intf, prop, value);
596         }
597         catch (const std::exception& e)
598         {}
599         return;
600     }
601 }
602 
getProperty(const std::string & path,const std::string & intf,const std::string & prop)603 const std::optional<PropertyVariantType> Manager::getProperty(
604     const std::string& path, const std::string& intf, const std::string& prop)
605 {
606     // TODO Objects hosted by fan control (i.e. ThermalMode) are required to
607     // update the cache upon being set/updated
608     auto itPath = _objects.find(path);
609     if (itPath != _objects.end())
610     {
611         auto itIntf = itPath->second.find(intf);
612         if (itIntf != itPath->second.end())
613         {
614             auto itProp = itIntf->second.find(prop);
615             if (itProp != itIntf->second.end())
616             {
617                 return itProp->second;
618             }
619         }
620     }
621 
622     return std::nullopt;
623 }
624 
setProperty(const std::string & path,const std::string & intf,const std::string & prop,PropertyVariantType value)625 void Manager::setProperty(const std::string& path, const std::string& intf,
626                           const std::string& prop, PropertyVariantType value)
627 {
628     // filter NaNs out of the cache
629     if (PropertyContainsNan(value))
630     {
631         // dont use operator [] if paths dont exist
632         if (_objects.find(path) != _objects.end() &&
633             _objects[path].find(intf) != _objects[path].end())
634         {
635             _objects[path][intf].erase(prop);
636         }
637     }
638     else
639     {
640         _objects[path][intf][prop] = std::move(value);
641     }
642 }
643 
addTimer(const TimerType type,const std::chrono::microseconds interval,std::unique_ptr<TimerPkg> pkg)644 void Manager::addTimer(const TimerType type,
645                        const std::chrono::microseconds interval,
646                        std::unique_ptr<TimerPkg> pkg)
647 {
648     auto dataPtr =
649         std::make_unique<TimerData>(std::make_pair(type, std::move(*pkg)));
650     Timer timer(_event,
651                 std::bind(&Manager::timerExpired, this, std::ref(*dataPtr)));
652     if (type == TimerType::repeating)
653     {
654         timer.restart(interval);
655     }
656     else if (type == TimerType::oneshot)
657     {
658         timer.restartOnce(interval);
659     }
660     else
661     {
662         throw std::invalid_argument("Invalid Timer Type");
663     }
664     _timers.emplace_back(std::move(dataPtr), std::move(timer));
665 }
666 
addGroups(const std::vector<Group> & groups)667 void Manager::addGroups(const std::vector<Group>& groups)
668 {
669     std::string lastServ;
670     std::vector<std::string> objMgrPaths;
671     std::set<std::string> services;
672     for (const auto& group : groups)
673     {
674         for (const auto& member : group.getMembers())
675         {
676             try
677             {
678                 auto service = group.getService();
679                 if (service.empty())
680                 {
681                     service = getService(member, group.getInterface());
682                 }
683 
684                 if (!service.empty())
685                 {
686                     if (lastServ != service)
687                     {
688                         objMgrPaths = getPaths(
689                             service, "org.freedesktop.DBus.ObjectManager");
690                         lastServ = service;
691                     }
692 
693                     // Look for the ObjectManager as an ancestor from the
694                     // member.
695                     auto hasObjMgr = std::any_of(
696                         objMgrPaths.begin(), objMgrPaths.end(),
697                         [&member](const auto& path) {
698                             return member.find(path) != std::string::npos;
699                         });
700 
701                     if (!hasObjMgr)
702                     {
703                         // No object manager interface provided for group member
704                         // Attempt to retrieve group member property directly
705                         try
706                         {
707                             auto value = util::SDBusPlus::getPropertyVariant<
708                                 PropertyVariantType>(_bus, service, member,
709                                                      group.getInterface(),
710                                                      group.getProperty());
711                             setProperty(member, group.getInterface(),
712                                         group.getProperty(), value);
713                         }
714                         catch (const std::exception& e)
715                         {}
716                         continue;
717                     }
718 
719                     if (services.find(service) == services.end())
720                     {
721                         services.insert(service);
722                         for (const auto& objMgrPath : objMgrPaths)
723                         {
724                             // Get all managed objects from the service
725                             auto objects = util::SDBusPlus::getManagedObjects<
726                                 PropertyVariantType>(_bus, service, objMgrPath);
727 
728                             // Insert objects into cache
729                             insertFilteredObjects(objects);
730                         }
731                     }
732                 }
733             }
734             catch (const util::DBusError&)
735             {
736                 // No service or property found for group member with the
737                 // group's configured interface
738                 continue;
739             }
740         }
741     }
742 }
743 
timerExpired(TimerData & data)744 void Manager::timerExpired(TimerData& data)
745 {
746     if (std::get<bool>(data.second))
747     {
748         addGroups(std::get<const std::vector<Group>&>(data.second));
749     }
750 
751     auto& actions =
752         std::get<std::vector<std::unique_ptr<ActionBase>>&>(data.second);
753     // Perform the actions in the timer data
754     std::for_each(actions.begin(), actions.end(),
755                   [](auto& action) { action->run(); });
756 
757     // Remove oneshot timers after they expired
758     if (data.first == TimerType::oneshot)
759     {
760         auto itTimer = std::find_if(
761             _timers.begin(), _timers.end(), [&data](const auto& timer) {
762                 return (data.first == timer.first->first &&
763                         (std::get<std::string>(data.second) ==
764                          std::get<std::string>(timer.first->second)));
765             });
766         if (itTimer != std::end(_timers))
767         {
768             _timers.erase(itTimer);
769         }
770     }
771 }
772 
handleSignal(sdbusplus::message_t & msg,const std::vector<SignalPkg> * pkgs)773 void Manager::handleSignal(sdbusplus::message_t& msg,
774                            const std::vector<SignalPkg>* pkgs)
775 {
776     for (auto& pkg : *pkgs)
777     {
778         // Handle the signal callback and only run the actions if the handler
779         // updated the cache for the given SignalObject
780         if (std::get<SignalHandler>(
781                 pkg)(msg, std::get<SignalObject>(pkg), *this))
782         {
783             // Perform the actions in the handler package
784             auto& actions = std::get<TriggerActions>(pkg);
785             std::for_each(actions.begin(), actions.end(), [](auto& action) {
786                 if (action.get())
787                 {
788                     action.get()->run();
789                 }
790             });
791         }
792         // Only rewind message when not last package
793         if (&pkg != &pkgs->back())
794         {
795             sd_bus_message_rewind(msg.get(), true);
796         }
797     }
798 }
799 
setProfiles()800 void Manager::setProfiles()
801 {
802     // Profiles JSON config file is optional
803     auto confFile =
804         fan::JsonConfig::getConfFile(confAppName, Profile::confFileName, true);
805 
806     _profiles.clear();
807     if (!confFile.empty())
808     {
809         for (const auto& entry : fan::JsonConfig::load(confFile))
810         {
811             auto obj = std::make_unique<Profile>(entry);
812             _profiles.emplace(
813                 std::make_pair(obj->getName(), obj->getProfiles()),
814                 std::move(obj));
815         }
816     }
817 
818     // Ensure all configurations use the same set of active profiles
819     // (In case a profile's active state changes during configuration)
820     _activeProfiles.clear();
821     for (const auto& profile : _profiles)
822     {
823         if (profile.second->isActive())
824         {
825             _activeProfiles.emplace_back(profile.first.first);
826         }
827     }
828 }
829 
addParameterTrigger(const std::string & name,std::vector<std::unique_ptr<ActionBase>> & actions)830 void Manager::addParameterTrigger(
831     const std::string& name, std::vector<std::unique_ptr<ActionBase>>& actions)
832 {
833     auto it = _parameterTriggers.find(name);
834     if (it != _parameterTriggers.end())
835     {
836         std::for_each(actions.begin(), actions.end(),
837                       [&actList = it->second](auto& action) {
838                           actList.emplace_back(std::ref(action));
839                       });
840     }
841     else
842     {
843         TriggerActions triggerActions;
844         std::for_each(actions.begin(), actions.end(),
845                       [&triggerActions](auto& action) {
846                           triggerActions.emplace_back(std::ref(action));
847                       });
848         _parameterTriggers[name] = std::move(triggerActions);
849     }
850 }
851 
runParameterActions(const std::string & name)852 void Manager::runParameterActions(const std::string& name)
853 {
854     auto it = _parameterTriggers.find(name);
855     if (it != _parameterTriggers.end())
856     {
857         std::for_each(it->second.begin(), it->second.end(),
858                       [](auto& action) { action.get()->run(); });
859     }
860 }
861 
862 } // namespace phosphor::fan::control::json
863