1 /**
2  * Copyright © 2021 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 "init.hpp"
17 
18 #include "../manager.hpp"
19 #include "action.hpp"
20 #include "group.hpp"
21 #include "sdbusplus.hpp"
22 #include "trigger_aliases.hpp"
23 
24 #include <nlohmann/json.hpp>
25 #include <phosphor-logging/log.hpp>
26 
27 #include <algorithm>
28 #include <format>
29 #include <iterator>
30 #include <memory>
31 #include <numeric>
32 #include <utility>
33 #include <vector>
34 
35 namespace phosphor::fan::control::json::trigger::init
36 {
37 
38 using json = nlohmann::json;
39 using namespace phosphor::logging;
40 
getProperties(Manager * mgr,const Group & group)41 void getProperties(Manager* mgr, const Group& group)
42 {
43     for (const auto& member : group.getMembers())
44     {
45         try
46         {
47             // Check if property already cached
48             auto value = mgr->getProperty(member, group.getInterface(),
49                                           group.getProperty());
50             if (value == std::nullopt)
51             {
52                 // Property not in cache, attempt to add it
53                 mgr->addObjects(member, group.getInterface(),
54                                 group.getProperty(), group.getService());
55 
56                 // If the service was predefined for the group, then we know
57                 // all members are in the same service so the above addObjects
58                 // call would have already added every present member in the
59                 // group (assuming the service has an ObjectManager iface
60                 // which it should). So no need to continue.
61                 if (!group.getService().empty())
62                 {
63                     break;
64                 }
65             }
66         }
67         catch (const std::exception& e)
68         {
69             // Configured dbus object does not exist on dbus yet?
70             // TODO How to handle this? Create timer to keep checking for
71             // object/service to appear? When to stop checking?
72         }
73     }
74 }
75 
nameHasOwner(Manager * mgr,const Group & group)76 void nameHasOwner(Manager* mgr, const Group& group)
77 {
78     bool hasOwner = false;
79     std::string lastName = "";
80     for (const auto& member : group.getMembers())
81     {
82         std::string servName = "";
83         auto intf = group.getInterface();
84         try
85         {
86             servName = group.getService();
87             if (servName.empty())
88             {
89                 servName = mgr->getService(member, intf);
90             }
91             if (!servName.empty())
92             {
93                 if (lastName != servName)
94                 {
95                     // Member not provided by same service as last group member
96                     lastName = servName;
97                     hasOwner = util::SDBusPlus::callMethodAndRead<bool>(
98                         mgr->getBus(), "org.freedesktop.DBus",
99                         "/org/freedesktop/DBus", "org.freedesktop.DBus",
100                         "NameHasOwner", servName);
101                 }
102                 // Update service name owner state of group object
103                 mgr->setOwner(member, servName, intf, hasOwner);
104             }
105             else
106             {
107                 // Path and/or interface configured does not exist on dbus?
108                 // TODO How to handle this? Create timer to keep checking for
109                 // object/service to appear? When to stop checking?
110                 log<level::ERR>(
111                     std::format(
112                         "Unable to get service name for path {}, interface {}",
113                         member, intf)
114                         .c_str());
115             }
116         }
117         catch (const util::DBusMethodError& dme)
118         {
119             if (!servName.empty())
120             {
121                 // Failed to get service name owner state
122                 hasOwner = false;
123                 mgr->setOwner(member, servName, intf, hasOwner);
124             }
125             else
126             {
127                 // Path and/or interface configured does not exist on dbus?
128                 // TODO How to handle this? Create timer to keep checking for
129                 // object/service to appear? When to stop checking?
130                 log<level::ERR>(std::format("Unable to get service({}) owner "
131                                             "state for path {}, interface {}",
132                                             servName, member, intf)
133                                     .c_str());
134                 throw dme;
135             }
136         }
137     }
138 }
139 
triggerInit(const json & jsonObj,const std::string &,std::vector<std::unique_ptr<ActionBase>> &)140 enableTrigger triggerInit(const json& jsonObj, const std::string& /*eventName*/,
141                           std::vector<std::unique_ptr<ActionBase>>& /*actions*/)
142 {
143     // Get the method handler if configured
144     auto handler = methods.end();
145     if (jsonObj.contains("method"))
146     {
147         auto method = jsonObj["method"].get<std::string>();
148         std::transform(method.begin(), method.end(), method.begin(), tolower);
149         handler = methods.find(method);
150     }
151 
152     return [handler = std::move(handler)](
153                const std::string& eventName, Manager* mgr,
154                const std::vector<Group>& groups,
155                std::vector<std::unique_ptr<ActionBase>>& actions) {
156         // Event groups are optional, so a method is only required if there
157         // are event groups i.e.) An init triggered event without any event
158         // groups results in just running the actions
159         if (!groups.empty() && handler == methods.end())
160         {
161             // Construct list of available methods
162             auto availMethods = std::accumulate(
163                 std::next(methods.begin()), methods.end(),
164                 methods.begin()->first, [](auto list, auto method) {
165                     return std::move(list) + ", " + method.first;
166                 });
167             auto msg =
168                 std::format("Event '{}' requires a supported method given to "
169                             "be init driven, available methods: {}",
170                             eventName, availMethods);
171             log<level::ERR>(msg.c_str());
172             throw std::runtime_error(msg.c_str());
173         }
174 
175         for (const auto& group : groups)
176         {
177             // Call method handler for each group to populate cache
178             handler->second(mgr, group);
179         }
180         for (auto& action : actions)
181         {
182             // Run each action after initializing all the groups
183             action->run();
184         }
185     };
186 }
187 
188 } // namespace phosphor::fan::control::json::trigger::init
189