xref: /openbmc/bmcweb/features/redfish/include/utils/sw_utils.hpp (revision d1bde9e590f165f28d948fda93e48d51b30bb463)
1 #pragma once
2 #include <async_resp.hpp>
3 #include <dbus_utility.hpp>
4 #include <sdbusplus/asio/property.hpp>
5 #include <sdbusplus/unpack_properties.hpp>
6 #include <utils/dbus_utils.hpp>
7 
8 #include <algorithm>
9 #include <string>
10 #include <vector>
11 
12 namespace redfish
13 {
14 namespace sw_util
15 {
16 /* @brief String that indicates a bios software instance */
17 constexpr const char* biosPurpose =
18     "xyz.openbmc_project.Software.Version.VersionPurpose.Host";
19 
20 /* @brief String that indicates a BMC software instance */
21 constexpr const char* bmcPurpose =
22     "xyz.openbmc_project.Software.Version.VersionPurpose.BMC";
23 
24 /**
25  * @brief Populate the running software version and image links
26  *
27  * @param[i,o] aResp             Async response object
28  * @param[i]   swVersionPurpose  Indicates what target to look for
29  * @param[i]   activeVersionPropName  Index in aResp->res.jsonValue to write
30  * the running software version to
31  * @param[i]   populateLinkToImages  Populate aResp->res "Links"
32  * "ActiveSoftwareImage" with a link to the running software image and
33  * "SoftwareImages" with a link to the all its software images
34  *
35  * @return void
36  */
37 inline void
38     populateSoftwareInformation(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
39                                 const std::string& swVersionPurpose,
40                                 const std::string& activeVersionPropName,
41                                 const bool populateLinkToImages)
42 {
43     // Used later to determine running (known on Redfish as active) Sw images
44     sdbusplus::asio::getProperty<std::vector<std::string>>(
45         *crow::connections::systemBus, "xyz.openbmc_project.ObjectMapper",
46         "/xyz/openbmc_project/software/functional",
47         "xyz.openbmc_project.Association", "endpoints",
48         [aResp, swVersionPurpose, activeVersionPropName,
49          populateLinkToImages](const boost::system::error_code ec,
50                                const std::vector<std::string>& functionalSw) {
51         BMCWEB_LOG_DEBUG << "populateSoftwareInformation enter";
52         if (ec)
53         {
54             BMCWEB_LOG_ERROR << "error_code = " << ec;
55             BMCWEB_LOG_ERROR << "error msg = " << ec.message();
56             messages::internalError(aResp->res);
57             return;
58         }
59 
60         if (functionalSw.empty())
61         {
62             // Could keep going and try to populate SoftwareImages but
63             // something is seriously wrong, so just fail
64             BMCWEB_LOG_ERROR << "Zero functional software in system";
65             messages::internalError(aResp->res);
66             return;
67         }
68 
69         std::vector<std::string> functionalSwIds;
70         // example functionalSw:
71         // v as 2 "/xyz/openbmc_project/software/ace821ef"
72         //        "/xyz/openbmc_project/software/230fb078"
73         for (const auto& sw : functionalSw)
74         {
75             sdbusplus::message::object_path path(sw);
76             std::string leaf = path.filename();
77             if (leaf.empty())
78             {
79                 continue;
80             }
81 
82             functionalSwIds.push_back(leaf);
83         }
84 
85         crow::connections::systemBus->async_method_call(
86             [aResp, swVersionPurpose, activeVersionPropName,
87              populateLinkToImages, functionalSwIds](
88                 const boost::system::error_code ec2,
89                 const dbus::utility::MapperGetSubTreeResponse& subtree) {
90             if (ec2)
91             {
92                 BMCWEB_LOG_ERROR << "error_code = " << ec2;
93                 BMCWEB_LOG_ERROR << "error msg = " << ec2.message();
94                 messages::internalError(aResp->res);
95                 return;
96             }
97 
98             BMCWEB_LOG_DEBUG << "Found " << subtree.size() << " images";
99 
100             for (const std::pair<std::string,
101                                  std::vector<std::pair<
102                                      std::string, std::vector<std::string>>>>&
103                      obj : subtree)
104             {
105 
106                 sdbusplus::message::object_path path(obj.first);
107                 std::string swId = path.filename();
108                 if (swId.empty())
109                 {
110                     messages::internalError(aResp->res);
111                     BMCWEB_LOG_ERROR << "Invalid software ID";
112 
113                     return;
114                 }
115 
116                 bool runningImage = false;
117                 // Look at Ids from
118                 // /xyz/openbmc_project/software/functional
119                 // to determine if this is a running image
120                 if (std::find(functionalSwIds.begin(), functionalSwIds.end(),
121                               swId) != functionalSwIds.end())
122                 {
123                     runningImage = true;
124                 }
125 
126                 // Now grab its version info
127                 sdbusplus::asio::getAllProperties(
128                     *crow::connections::systemBus, obj.second[0].first,
129                     obj.first, "xyz.openbmc_project.Software.Version",
130                     [aResp, swId, runningImage, swVersionPurpose,
131                      activeVersionPropName, populateLinkToImages](
132                         const boost::system::error_code ec3,
133                         const dbus::utility::DBusPropertiesMap&
134                             propertiesList) {
135                     if (ec3)
136                     {
137                         BMCWEB_LOG_ERROR << "error_code = " << ec3;
138                         BMCWEB_LOG_ERROR << "error msg = " << ec3.message();
139                         // Have seen the code update app delete the D-Bus
140                         // object, during code update, between the call to
141                         // mapper and here. Just leave these properties off if
142                         // resource not found.
143                         if (ec3.value() == EBADR)
144                         {
145                             return;
146                         }
147                         messages::internalError(aResp->res);
148                         return;
149                     }
150                     // example propertiesList
151                     // a{sv} 2 "Version" s
152                     // "IBM-witherspoon-OP9-v2.0.10-2.22" "Purpose"
153                     // s
154                     // "xyz.openbmc_project.Software.Version.VersionPurpose.Host"
155                     const std::string* version = nullptr;
156                     const std::string* swInvPurpose = nullptr;
157 
158                     const bool success = sdbusplus::unpackPropertiesNoThrow(
159                         dbus_utils::UnpackErrorPrinter(), propertiesList,
160                         "Purpose", swInvPurpose, "Version", version);
161 
162                     if (!success)
163                     {
164                         messages::internalError(aResp->res);
165                         return;
166                     }
167 
168                     if (version == nullptr || version->empty())
169                     {
170                         messages::internalError(aResp->res);
171                         return;
172                     }
173                     if (swInvPurpose == nullptr ||
174                         *swInvPurpose != swVersionPurpose)
175                     {
176                         // Not purpose we're looking for
177                         return;
178                     }
179 
180                     BMCWEB_LOG_DEBUG << "Image ID: " << swId;
181                     BMCWEB_LOG_DEBUG << "Running image: " << runningImage;
182                     BMCWEB_LOG_DEBUG << "Image purpose: " << *swInvPurpose;
183 
184                     if (populateLinkToImages)
185                     {
186                         nlohmann::json& softwareImageMembers =
187                             aResp->res.jsonValue["Links"]["SoftwareImages"];
188                         // Firmware images are at
189                         // /redfish/v1/UpdateService/FirmwareInventory/<Id>
190                         // e.g. .../FirmwareInventory/82d3ec86
191                         softwareImageMembers.push_back(
192                             {{"@odata.id", "/redfish/v1/UpdateService/"
193                                            "FirmwareInventory/" +
194                                                swId}});
195                         aResp->res
196                             .jsonValue["Links"]["SoftwareImages@odata.count"] =
197                             softwareImageMembers.size();
198 
199                         if (runningImage)
200                         {
201                             // Create the link to the running image
202                             aResp->res
203                                 .jsonValue["Links"]["ActiveSoftwareImage"] = {
204                                 {"@odata.id", "/redfish/v1/UpdateService/"
205                                               "FirmwareInventory/" +
206                                                   swId}};
207                         }
208                     }
209                     if (!activeVersionPropName.empty() && runningImage)
210                     {
211                         aResp->res.jsonValue[activeVersionPropName] = *version;
212                     }
213                     });
214             }
215             },
216             "xyz.openbmc_project.ObjectMapper",
217             "/xyz/openbmc_project/object_mapper",
218             "xyz.openbmc_project.ObjectMapper", "GetSubTree",
219             "/xyz/openbmc_project/software", static_cast<int32_t>(0),
220             std::array<const char*, 1>{"xyz.openbmc_project.Software.Version"});
221         });
222 }
223 
224 /**
225  * @brief Translate input swState to Redfish state
226  *
227  * This function will return the corresponding Redfish state
228  *
229  * @param[i]   swState  The OpenBMC software state
230  *
231  * @return The corresponding Redfish state
232  */
233 inline std::string getRedfishSwState(const std::string& swState)
234 {
235     if (swState == "xyz.openbmc_project.Software.Activation.Activations.Active")
236     {
237         return "Enabled";
238     }
239     if (swState == "xyz.openbmc_project.Software.Activation."
240                    "Activations.Activating")
241     {
242         return "Updating";
243     }
244     if (swState == "xyz.openbmc_project.Software.Activation."
245                    "Activations.StandbySpare")
246     {
247         return "StandbySpare";
248     }
249     BMCWEB_LOG_DEBUG << "Default sw state " << swState << " to Disabled";
250     return "Disabled";
251 }
252 
253 /**
254  * @brief Translate input swState to Redfish health state
255  *
256  * This function will return the corresponding Redfish health state
257  *
258  * @param[i]   swState  The OpenBMC software state
259  *
260  * @return The corresponding Redfish health state
261  */
262 inline std::string getRedfishSwHealth(const std::string& swState)
263 {
264     if ((swState ==
265          "xyz.openbmc_project.Software.Activation.Activations.Active") ||
266         (swState == "xyz.openbmc_project.Software.Activation.Activations."
267                     "Activating") ||
268         (swState ==
269          "xyz.openbmc_project.Software.Activation.Activations.Ready"))
270     {
271         return "OK";
272     }
273     BMCWEB_LOG_DEBUG << "Sw state " << swState << " to Warning";
274     return "Warning";
275 }
276 
277 /**
278  * @brief Put status of input swId into json response
279  *
280  * This function will put the appropriate Redfish state of the input
281  * software id to ["Status"]["State"] within the json response
282  *
283  * @param[i,o] aResp    Async response object
284  * @param[i]   swId     The software ID to get status for
285  * @param[i]   dbusSvc  The dbus service implementing the software object
286  *
287  * @return void
288  */
289 inline void getSwStatus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
290                         const std::shared_ptr<std::string>& swId,
291                         const std::string& dbusSvc)
292 {
293     BMCWEB_LOG_DEBUG << "getSwStatus: swId " << *swId << " svc " << dbusSvc;
294 
295     sdbusplus::asio::getAllProperties(
296         *crow::connections::systemBus, dbusSvc,
297         "/xyz/openbmc_project/software/" + *swId,
298         "xyz.openbmc_project.Software.Activation",
299         [asyncResp,
300          swId](const boost::system::error_code errorCode,
301                const dbus::utility::DBusPropertiesMap& propertiesList) {
302         if (errorCode)
303         {
304             // not all swtypes are updateable, this is ok
305             asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
306             return;
307         }
308 
309         const std::string* swInvActivation = nullptr;
310 
311         const bool success = sdbusplus::unpackPropertiesNoThrow(
312             dbus_utils::UnpackErrorPrinter(), propertiesList, "Activation",
313             swInvActivation);
314 
315         if (!success)
316         {
317             messages::internalError(asyncResp->res);
318             return;
319         }
320 
321         if (swInvActivation == nullptr)
322         {
323             messages::internalError(asyncResp->res);
324             return;
325         }
326 
327         BMCWEB_LOG_DEBUG << "getSwStatus: Activation " << *swInvActivation;
328         asyncResp->res.jsonValue["Status"]["State"] =
329             getRedfishSwState(*swInvActivation);
330         asyncResp->res.jsonValue["Status"]["Health"] =
331             getRedfishSwHealth(*swInvActivation);
332         });
333 }
334 
335 /**
336  * @brief Updates programmable status of input swId into json response
337  *
338  * This function checks whether software inventory component
339  * can be programmable or not and fill's the "Updatable"
340  * Property.
341  *
342  * @param[i,o] asyncResp  Async response object
343  * @param[i]   swId       The software ID
344  */
345 inline void
346     getSwUpdatableStatus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
347                          const std::shared_ptr<std::string>& swId)
348 {
349     sdbusplus::asio::getProperty<std::vector<std::string>>(
350         *crow::connections::systemBus, "xyz.openbmc_project.ObjectMapper",
351         "/xyz/openbmc_project/software/updateable",
352         "xyz.openbmc_project.Association", "endpoints",
353         [asyncResp, swId](const boost::system::error_code ec,
354                           const std::vector<std::string>& objPaths) {
355         if (ec)
356         {
357             BMCWEB_LOG_DEBUG << " error_code = " << ec
358                              << " error msg =  " << ec.message();
359             // System can exist with no updateable software,
360             // so don't throw error here.
361             return;
362         }
363         std::string reqSwObjPath = "/xyz/openbmc_project/software/" + *swId;
364 
365         if (std::find(objPaths.begin(), objPaths.end(), reqSwObjPath) !=
366             objPaths.end())
367         {
368             asyncResp->res.jsonValue["Updateable"] = true;
369             return;
370         }
371         });
372 }
373 
374 } // namespace sw_util
375 } // namespace redfish
376