xref: /openbmc/bmcweb/features/redfish/lib/update_service.hpp (revision e195977836ef5135d9362f40e8755da8c34dc0d7)
1 /*
2 // Copyright (c) 2018 Intel 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 #pragma once
17 
18 #include "node.hpp"
19 
20 #include <boost/container/flat_map.hpp>
21 #include <utils/fw_utils.hpp>
22 #include <variant>
23 
24 namespace redfish
25 {
26 
27 // Match signals added on software path
28 static std::unique_ptr<sdbusplus::bus::match::match> fwUpdateMatcher;
29 // Only allow one update at a time
30 static bool fwUpdateInProgress = false;
31 // Timer for software available
32 static std::unique_ptr<boost::asio::steady_timer> fwAvailableTimer;
33 
34 static void cleanUp()
35 {
36     fwUpdateInProgress = false;
37     fwUpdateMatcher = nullptr;
38 }
39 static void activateImage(const std::string &objPath,
40                           const std::string &service)
41 {
42     BMCWEB_LOG_DEBUG << "Activate image for " << objPath << " " << service;
43     crow::connections::systemBus->async_method_call(
44         [](const boost::system::error_code error_code) {
45             if (error_code)
46             {
47                 BMCWEB_LOG_DEBUG << "error_code = " << error_code;
48                 BMCWEB_LOG_DEBUG << "error msg = " << error_code.message();
49             }
50         },
51         service, objPath, "org.freedesktop.DBus.Properties", "Set",
52         "xyz.openbmc_project.Software.Activation", "RequestedActivation",
53         std::variant<std::string>(
54             "xyz.openbmc_project.Software.Activation.RequestedActivations."
55             "Active"));
56 }
57 
58 // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
59 // then no asyncResp updates will occur
60 static void softwareInterfaceAdded(std::shared_ptr<AsyncResp> asyncResp,
61                                    sdbusplus::message::message &m)
62 {
63     std::vector<std::pair<
64         std::string,
65         std::vector<std::pair<std::string, std::variant<std::string>>>>>
66         interfacesProperties;
67 
68     sdbusplus::message::object_path objPath;
69 
70     m.read(objPath, interfacesProperties);
71 
72     BMCWEB_LOG_DEBUG << "obj path = " << objPath.str;
73     for (auto &interface : interfacesProperties)
74     {
75         BMCWEB_LOG_DEBUG << "interface = " << interface.first;
76 
77         if (interface.first == "xyz.openbmc_project.Software.Activation")
78         {
79             // Found our interface, disable callbacks
80             fwUpdateMatcher = nullptr;
81 
82             // Retrieve service and activate
83             crow::connections::systemBus->async_method_call(
84                 [objPath, asyncResp](
85                     const boost::system::error_code error_code,
86                     const std::vector<std::pair<
87                         std::string, std::vector<std::string>>> &objInfo) {
88                     if (error_code)
89                     {
90                         BMCWEB_LOG_DEBUG << "error_code = " << error_code;
91                         BMCWEB_LOG_DEBUG << "error msg = "
92                                          << error_code.message();
93                         if (asyncResp)
94                         {
95                             messages::internalError(asyncResp->res);
96                         }
97                         cleanUp();
98                         return;
99                     }
100                     // Ensure we only got one service back
101                     if (objInfo.size() != 1)
102                     {
103                         BMCWEB_LOG_ERROR << "Invalid Object Size "
104                                          << objInfo.size();
105                         if (asyncResp)
106                         {
107                             messages::internalError(asyncResp->res);
108                         }
109                         cleanUp();
110                         return;
111                     }
112                     // cancel timer only when
113                     // xyz.openbmc_project.Software.Activation interface
114                     // is added
115                     fwAvailableTimer = nullptr;
116 
117                     activateImage(objPath.str, objInfo[0].first);
118                     if (asyncResp)
119                     {
120                         redfish::messages::success(asyncResp->res);
121                     }
122                     fwUpdateInProgress = false;
123                 },
124                 "xyz.openbmc_project.ObjectMapper",
125                 "/xyz/openbmc_project/object_mapper",
126                 "xyz.openbmc_project.ObjectMapper", "GetObject", objPath.str,
127                 std::array<const char *, 1>{
128                     "xyz.openbmc_project.Software.Activation"});
129         }
130     }
131 }
132 
133 // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
134 // then no asyncResp updates will occur
135 static void monitorForSoftwareAvailable(std::shared_ptr<AsyncResp> asyncResp,
136                                         const crow::Request &req,
137                                         int timeoutTimeSeconds = 5)
138 {
139     // Only allow one FW update at a time
140     if (fwUpdateInProgress != false)
141     {
142         if (asyncResp)
143         {
144             messages::serviceTemporarilyUnavailable(asyncResp->res, "30");
145         }
146         return;
147     }
148 
149     fwAvailableTimer =
150         std::make_unique<boost::asio::steady_timer>(*req.ioService);
151 
152     fwAvailableTimer->expires_after(std::chrono::seconds(timeoutTimeSeconds));
153 
154     fwAvailableTimer->async_wait(
155         [asyncResp](const boost::system::error_code &ec) {
156             cleanUp();
157             if (ec == boost::asio::error::operation_aborted)
158             {
159                 // expected, we were canceled before the timer completed.
160                 return;
161             }
162             BMCWEB_LOG_ERROR
163                 << "Timed out waiting for firmware object being created";
164             BMCWEB_LOG_ERROR
165                 << "FW image may has already been uploaded to server";
166             if (ec)
167             {
168                 BMCWEB_LOG_ERROR << "Async_wait failed" << ec;
169                 return;
170             }
171             if (asyncResp)
172             {
173                 redfish::messages::internalError(asyncResp->res);
174             }
175         });
176 
177     auto callback = [asyncResp](sdbusplus::message::message &m) {
178         BMCWEB_LOG_DEBUG << "Match fired";
179         softwareInterfaceAdded(asyncResp, m);
180     };
181 
182     fwUpdateInProgress = true;
183 
184     fwUpdateMatcher = std::make_unique<sdbusplus::bus::match::match>(
185         *crow::connections::systemBus,
186         "interface='org.freedesktop.DBus.ObjectManager',type='signal',"
187         "member='InterfacesAdded',path='/xyz/openbmc_project/software'",
188         callback);
189 }
190 
191 /**
192  * UpdateServiceActionsSimpleUpdate class supports handle POST method for
193  * SimpleUpdate action.
194  */
195 class UpdateServiceActionsSimpleUpdate : public Node
196 {
197   public:
198     UpdateServiceActionsSimpleUpdate(CrowApp &app) :
199         Node(app,
200              "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate/")
201     {
202         entityPrivileges = {
203             {boost::beast::http::verb::get, {{"Login"}}},
204             {boost::beast::http::verb::head, {{"Login"}}},
205             {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
206             {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
207             {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
208             {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
209     }
210 
211   private:
212     void doPost(crow::Response &res, const crow::Request &req,
213                 const std::vector<std::string> &params) override
214     {
215         std::optional<std::string> transferProtocol;
216         std::string imageURI;
217         std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
218 
219         BMCWEB_LOG_DEBUG << "Enter UpdateService.SimpleUpdate doPost";
220 
221         // User can pass in both TransferProtocol and ImageURI parameters or
222         // they can pass in just the ImageURI with the transfer protocl embedded
223         // within it.
224         // 1) TransferProtocol:TFTP ImageURI:1.1.1.1/myfile.bin
225         // 2) ImageURI:tftp://1.1.1.1/myfile.bin
226 
227         if (!json_util::readJson(req, asyncResp->res, "TransferProtocol",
228                                  transferProtocol, "ImageURI", imageURI))
229         {
230             BMCWEB_LOG_DEBUG
231                 << "Missing TransferProtocol or ImageURI parameter";
232             return;
233         }
234         if (!transferProtocol)
235         {
236             // Must be option 2
237             // Verify ImageURI has transfer protocol in it
238             size_t separator = imageURI.find(":");
239             if ((separator == std::string::npos) ||
240                 ((separator + 1) > imageURI.size()))
241             {
242                 messages::actionParameterValueTypeError(
243                     asyncResp->res, imageURI, "ImageURI",
244                     "UpdateService.SimpleUpdate");
245                 BMCWEB_LOG_ERROR << "ImageURI missing transfer protocol: "
246                                  << imageURI;
247                 return;
248             }
249             transferProtocol = imageURI.substr(0, separator);
250             // Ensure protocol is upper case for a common comparison path below
251             boost::to_upper(*transferProtocol);
252             BMCWEB_LOG_DEBUG << "Encoded transfer protocol "
253                              << *transferProtocol;
254 
255             // Adjust imageURI to not have the protocol on it for parsing
256             // below
257             // ex. tftp://1.1.1.1/myfile.bin -> 1.1.1.1/myfile.bin
258             imageURI = imageURI.substr(separator + 3);
259             BMCWEB_LOG_DEBUG << "Adjusted imageUri " << imageURI;
260         }
261 
262         // OpenBMC currently only supports TFTP
263         if (*transferProtocol != "TFTP")
264         {
265             messages::actionParameterNotSupported(asyncResp->res,
266                                                   "TransferProtocol",
267                                                   "UpdateService.SimpleUpdate");
268             BMCWEB_LOG_ERROR << "Request incorrect protocol parameter: "
269                              << *transferProtocol;
270             return;
271         }
272 
273         // Format should be <IP or Hostname>/<file> for imageURI
274         size_t separator = imageURI.find("/");
275         if ((separator == std::string::npos) ||
276             ((separator + 1) > imageURI.size()))
277         {
278             messages::actionParameterValueTypeError(
279                 asyncResp->res, imageURI, "ImageURI",
280                 "UpdateService.SimpleUpdate");
281             BMCWEB_LOG_ERROR << "Invalid ImageURI: " << imageURI;
282             return;
283         }
284 
285         std::string tftpServer = imageURI.substr(0, separator);
286         std::string fwFile = imageURI.substr(separator + 1);
287         BMCWEB_LOG_DEBUG << "Server: " << tftpServer + " File: " << fwFile;
288 
289         // Setup callback for when new software detected
290         // Give TFTP 2 minutes to complete
291         monitorForSoftwareAvailable(nullptr, req, 120);
292 
293         // TFTP can take up to 2 minutes depending on image size and
294         // connection speed. Return to caller as soon as the TFTP operation
295         // has been started. The callback above will ensure the activate
296         // is started once the download has completed
297         redfish::messages::success(asyncResp->res);
298 
299         // Call TFTP service
300         crow::connections::systemBus->async_method_call(
301             [](const boost::system::error_code ec) {
302                 if (ec)
303                 {
304                     // messages::internalError(asyncResp->res);
305                     cleanUp();
306                     BMCWEB_LOG_DEBUG << "error_code = " << ec;
307                     BMCWEB_LOG_DEBUG << "error msg = " << ec.message();
308                 }
309                 else
310                 {
311                     BMCWEB_LOG_DEBUG << "Call to DownloaViaTFTP Success";
312                 }
313             },
314             "xyz.openbmc_project.Software.Download",
315             "/xyz/openbmc_project/software", "xyz.openbmc_project.Common.TFTP",
316             "DownloadViaTFTP", fwFile, tftpServer);
317 
318         BMCWEB_LOG_DEBUG << "Exit UpdateService.SimpleUpdate doPost";
319     }
320 };
321 
322 class UpdateService : public Node
323 {
324   public:
325     UpdateService(CrowApp &app) : Node(app, "/redfish/v1/UpdateService/")
326     {
327         entityPrivileges = {
328             {boost::beast::http::verb::get, {{"Login"}}},
329             {boost::beast::http::verb::head, {{"Login"}}},
330             {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
331             {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
332             {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
333             {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
334     }
335 
336   private:
337     void doGet(crow::Response &res, const crow::Request &req,
338                const std::vector<std::string> &params) override
339     {
340         res.jsonValue["@odata.type"] = "#UpdateService.v1_2_0.UpdateService";
341         res.jsonValue["@odata.id"] = "/redfish/v1/UpdateService";
342         res.jsonValue["@odata.context"] =
343             "/redfish/v1/$metadata#UpdateService.UpdateService";
344         res.jsonValue["Id"] = "UpdateService";
345         res.jsonValue["Description"] = "Service for Software Update";
346         res.jsonValue["Name"] = "Update Service";
347         res.jsonValue["HttpPushUri"] = "/redfish/v1/UpdateService";
348         // UpdateService cannot be disabled
349         res.jsonValue["ServiceEnabled"] = true;
350         res.jsonValue["FirmwareInventory"] = {
351             {"@odata.id", "/redfish/v1/UpdateService/FirmwareInventory"}};
352 #ifdef BMCWEB_INSECURE_ENABLE_REDFISH_FW_TFTP_UPDATE
353         // Update Actions object.
354         nlohmann::json &updateSvcSimpleUpdate =
355             res.jsonValue["Actions"]["#UpdateService.SimpleUpdate"];
356         updateSvcSimpleUpdate["target"] =
357             "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate";
358         updateSvcSimpleUpdate["TransferProtocol@Redfish.AllowableValues"] = {
359             "TFTP"};
360 #endif
361         res.end();
362     }
363 
364     void doPatch(crow::Response &res, const crow::Request &req,
365                  const std::vector<std::string> &params) override
366     {
367         BMCWEB_LOG_DEBUG << "doPatch...";
368 
369         std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
370         std::string applyTime;
371 
372         if (!json_util::readJson(req, res, "ApplyTime", applyTime))
373         {
374             return;
375         }
376 
377         if ((applyTime == "Immediate") || (applyTime == "OnReset"))
378         {
379             std::string applyTimeNewVal;
380             if (applyTime == "Immediate")
381             {
382                 applyTimeNewVal = "xyz.openbmc_project.Software.ApplyTime."
383                                   "RequestedApplyTimes.Immediate";
384             }
385             else
386             {
387                 applyTimeNewVal = "xyz.openbmc_project.Software.ApplyTime."
388                                   "RequestedApplyTimes.OnReset";
389             }
390 
391             // Set the requested image apply time value
392             crow::connections::systemBus->async_method_call(
393                 [asyncResp](const boost::system::error_code ec) {
394                     if (ec)
395                     {
396                         BMCWEB_LOG_ERROR << "D-Bus responses error: " << ec;
397                         messages::internalError(asyncResp->res);
398                         return;
399                     }
400                     messages::success(asyncResp->res);
401                 },
402                 "xyz.openbmc_project.Settings",
403                 "/xyz/openbmc_project/software/apply_time",
404                 "org.freedesktop.DBus.Properties", "Set",
405                 "xyz.openbmc_project.Software.ApplyTime", "RequestedApplyTime",
406                 std::variant<std::string>{applyTimeNewVal});
407         }
408         else
409         {
410             BMCWEB_LOG_INFO << "ApplyTime value is not in the list of "
411                                "acceptable values";
412             messages::propertyValueNotInList(asyncResp->res, applyTime,
413                                              "ApplyTime");
414         }
415     }
416 
417     void doPost(crow::Response &res, const crow::Request &req,
418                 const std::vector<std::string> &params) override
419     {
420         BMCWEB_LOG_DEBUG << "doPost...";
421 
422         std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
423 
424         // Setup callback for when new software detected
425         monitorForSoftwareAvailable(asyncResp, req);
426 
427         std::string filepath(
428             "/tmp/images/" +
429             boost::uuids::to_string(boost::uuids::random_generator()()));
430         BMCWEB_LOG_DEBUG << "Writing file to " << filepath;
431         std::ofstream out(filepath, std::ofstream::out | std::ofstream::binary |
432                                         std::ofstream::trunc);
433         out << req.body;
434         out.close();
435         BMCWEB_LOG_DEBUG << "file upload complete!!";
436     }
437 };
438 
439 class SoftwareInventoryCollection : public Node
440 {
441   public:
442     template <typename CrowApp>
443     SoftwareInventoryCollection(CrowApp &app) :
444         Node(app, "/redfish/v1/UpdateService/FirmwareInventory/")
445     {
446         entityPrivileges = {
447             {boost::beast::http::verb::get, {{"Login"}}},
448             {boost::beast::http::verb::head, {{"Login"}}},
449             {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
450             {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
451             {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
452             {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
453     }
454 
455   private:
456     void doGet(crow::Response &res, const crow::Request &req,
457                const std::vector<std::string> &params) override
458     {
459         std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
460         res.jsonValue["@odata.type"] =
461             "#SoftwareInventoryCollection.SoftwareInventoryCollection";
462         res.jsonValue["@odata.id"] =
463             "/redfish/v1/UpdateService/FirmwareInventory";
464         res.jsonValue["@odata.context"] =
465             "/redfish/v1/"
466             "$metadata#SoftwareInventoryCollection.SoftwareInventoryCollection";
467         res.jsonValue["Name"] = "Software Inventory Collection";
468 
469         crow::connections::systemBus->async_method_call(
470             [asyncResp](
471                 const boost::system::error_code ec,
472                 const std::vector<std::pair<
473                     std::string, std::vector<std::pair<
474                                      std::string, std::vector<std::string>>>>>
475                     &subtree) {
476                 if (ec)
477                 {
478                     messages::internalError(asyncResp->res);
479                     return;
480                 }
481                 asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
482                 asyncResp->res.jsonValue["Members@odata.count"] = 0;
483 
484                 for (auto &obj : subtree)
485                 {
486                     // if can't parse fw id then return
487                     std::size_t idPos;
488                     if ((idPos = obj.first.rfind("/")) == std::string::npos)
489                     {
490                         messages::internalError(asyncResp->res);
491                         BMCWEB_LOG_DEBUG << "Can't parse firmware ID!!";
492                         return;
493                     }
494                     std::string swId = obj.first.substr(idPos + 1);
495 
496                     nlohmann::json &members =
497                         asyncResp->res.jsonValue["Members"];
498                     members.push_back(
499                         {{"@odata.id", "/redfish/v1/UpdateService/"
500                                        "FirmwareInventory/" +
501                                            swId}});
502                     asyncResp->res.jsonValue["Members@odata.count"] =
503                         members.size();
504                 }
505             },
506             "xyz.openbmc_project.ObjectMapper",
507             "/xyz/openbmc_project/object_mapper",
508             "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/",
509             static_cast<int32_t>(0),
510             std::array<const char *, 1>{
511                 "xyz.openbmc_project.Software.Version"});
512     }
513 };
514 
515 class SoftwareInventory : public Node
516 {
517   public:
518     template <typename CrowApp>
519     SoftwareInventory(CrowApp &app) :
520         Node(app, "/redfish/v1/UpdateService/FirmwareInventory/<str>/",
521              std::string())
522     {
523         entityPrivileges = {
524             {boost::beast::http::verb::get, {{"Login"}}},
525             {boost::beast::http::verb::head, {{"Login"}}},
526             {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
527             {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
528             {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
529             {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
530     }
531 
532   private:
533     /* Fill related item links (i.e. bmc, bios) in for inventory */
534     static void getRelatedItems(std::shared_ptr<AsyncResp> aResp,
535                                 const std::string &purpose)
536     {
537         if (purpose == fw_util::bmcPurpose)
538         {
539             nlohmann::json &members = aResp->res.jsonValue["RelatedItem"];
540             members.push_back({{"@odata.id", "/redfish/v1/Managers/bmc"}});
541             aResp->res.jsonValue["Members@odata.count"] = members.size();
542         }
543         else if (purpose == fw_util::biosPurpose)
544         {
545             // TODO(geissonator) Need BIOS schema support added for this
546             //                   to be valid
547             // nlohmann::json &members = aResp->res.jsonValue["RelatedItem"];
548             // members.push_back(
549             //    {{"@odata.id", "/redfish/v1/Systems/system/BIOS"}});
550             // aResp->res.jsonValue["Members@odata.count"] = members.size();
551         }
552         else
553         {
554             BMCWEB_LOG_ERROR << "Unknown software purpose " << purpose;
555         }
556     }
557 
558     void doGet(crow::Response &res, const crow::Request &req,
559                const std::vector<std::string> &params) override
560     {
561         std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
562 
563         if (params.size() != 1)
564         {
565             messages::internalError(res);
566             res.end();
567             return;
568         }
569 
570         std::shared_ptr<std::string> swId =
571             std::make_shared<std::string>(params[0]);
572 
573         res.jsonValue["@odata.id"] =
574             "/redfish/v1/UpdateService/FirmwareInventory/" + *swId;
575 
576         crow::connections::systemBus->async_method_call(
577             [asyncResp, swId](
578                 const boost::system::error_code ec,
579                 const std::vector<std::pair<
580                     std::string, std::vector<std::pair<
581                                      std::string, std::vector<std::string>>>>>
582                     &subtree) {
583                 BMCWEB_LOG_DEBUG << "doGet callback...";
584                 if (ec)
585                 {
586                     messages::internalError(asyncResp->res);
587                     return;
588                 }
589 
590                 // Ensure we find our input swId, otherwise return an error
591                 bool found = false;
592                 for (const std::pair<
593                          std::string,
594                          std::vector<
595                              std::pair<std::string, std::vector<std::string>>>>
596                          &obj : subtree)
597                 {
598                     if (boost::ends_with(obj.first, *swId) != true)
599                     {
600                         continue;
601                     }
602 
603                     if (obj.second.size() < 1)
604                     {
605                         continue;
606                     }
607 
608                     found = true;
609                     fw_util::getFwStatus(asyncResp, swId, obj.second[0].first);
610 
611                     crow::connections::systemBus->async_method_call(
612                         [asyncResp,
613                          swId](const boost::system::error_code error_code,
614                                const boost::container::flat_map<
615                                    std::string, VariantType> &propertiesList) {
616                             if (error_code)
617                             {
618                                 messages::internalError(asyncResp->res);
619                                 return;
620                             }
621                             boost::container::flat_map<
622                                 std::string, VariantType>::const_iterator it =
623                                 propertiesList.find("Purpose");
624                             if (it == propertiesList.end())
625                             {
626                                 BMCWEB_LOG_DEBUG
627                                     << "Can't find property \"Purpose\"!";
628                                 messages::propertyMissing(asyncResp->res,
629                                                           "Purpose");
630                                 return;
631                             }
632                             const std::string *swInvPurpose =
633                                 std::get_if<std::string>(&it->second);
634                             if (swInvPurpose == nullptr)
635                             {
636                                 BMCWEB_LOG_DEBUG
637                                     << "wrong types for property\"Purpose\"!";
638                                 messages::propertyValueTypeError(asyncResp->res,
639                                                                  "", "Purpose");
640                                 return;
641                             }
642 
643                             BMCWEB_LOG_DEBUG << "swInvPurpose = "
644                                              << *swInvPurpose;
645                             it = propertiesList.find("Version");
646                             if (it == propertiesList.end())
647                             {
648                                 BMCWEB_LOG_DEBUG
649                                     << "Can't find property \"Version\"!";
650                                 messages::propertyMissing(asyncResp->res,
651                                                           "Version");
652                                 return;
653                             }
654 
655                             BMCWEB_LOG_DEBUG << "Version found!";
656 
657                             const std::string *version =
658                                 std::get_if<std::string>(&it->second);
659 
660                             if (version == nullptr)
661                             {
662                                 BMCWEB_LOG_DEBUG
663                                     << "Can't find property \"Version\"!";
664 
665                                 messages::propertyValueTypeError(asyncResp->res,
666                                                                  "", "Version");
667                                 return;
668                             }
669                             asyncResp->res.jsonValue["Version"] = *version;
670                             asyncResp->res.jsonValue["Id"] = *swId;
671 
672                             // swInvPurpose is of format:
673                             // xyz.openbmc_project.Software.Version.VersionPurpose.ABC
674                             // Translate this to "ABC image"
675                             size_t endDesc = swInvPurpose->rfind(".");
676                             if (endDesc == std::string::npos)
677                             {
678                                 messages::internalError(asyncResp->res);
679                                 return;
680                             }
681                             endDesc++;
682                             if (endDesc >= swInvPurpose->size())
683                             {
684                                 messages::internalError(asyncResp->res);
685                                 return;
686                             }
687 
688                             std::string formatDesc =
689                                 swInvPurpose->substr(endDesc);
690                             asyncResp->res.jsonValue["Description"] =
691                                 formatDesc + " image";
692                             getRelatedItems(asyncResp, *swInvPurpose);
693                         },
694                         obj.second[0].first, obj.first,
695                         "org.freedesktop.DBus.Properties", "GetAll",
696                         "xyz.openbmc_project.Software.Version");
697                 }
698                 if (!found)
699                 {
700                     BMCWEB_LOG_ERROR << "Input swID " + *swId + " not found!";
701                     messages::resourceMissingAtURI(
702                         asyncResp->res,
703                         "/redfish/v1/UpdateService/FirmwareInventory/" + *swId);
704                     return;
705                 }
706                 asyncResp->res.jsonValue["@odata.type"] =
707                     "#SoftwareInventory.v1_1_0.SoftwareInventory";
708                 asyncResp->res.jsonValue["@odata.context"] =
709                     "/redfish/v1/$metadata#SoftwareInventory.SoftwareInventory";
710                 asyncResp->res.jsonValue["Name"] = "Software Inventory";
711                 asyncResp->res.jsonValue["Updateable"] = false;
712                 asyncResp->res.jsonValue["Status"]["Health"] = "OK";
713                 asyncResp->res.jsonValue["Status"]["HealthRollup"] = "OK";
714             },
715             "xyz.openbmc_project.ObjectMapper",
716             "/xyz/openbmc_project/object_mapper",
717             "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/",
718             static_cast<int32_t>(0),
719             std::array<const char *, 1>{
720                 "xyz.openbmc_project.Software.Version"});
721     }
722 };
723 
724 } // namespace redfish
725