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