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