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