xref: /openbmc/bmcweb/redfish-core/lib/chassis.hpp (revision a1ffbb84cf0f7f75ccb84fa6e0752b645b81ebdf)
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 "health.hpp"
19 #include "led.hpp"
20 #include "node.hpp"
21 
22 #include <boost/container/flat_map.hpp>
23 #include <utils/collection.hpp>
24 
25 #include <variant>
26 
27 namespace redfish
28 {
29 
30 /**
31  * @brief Retrieves chassis state properties over dbus
32  *
33  * @param[in] aResp - Shared pointer for completing asynchronous calls.
34  *
35  * @return None.
36  */
37 inline void getChassisState(std::shared_ptr<AsyncResp> aResp)
38 {
39     crow::connections::systemBus->async_method_call(
40         [aResp{std::move(aResp)}](
41             const boost::system::error_code ec,
42             const std::variant<std::string>& chassisState) {
43             if (ec)
44             {
45                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
46                 messages::internalError(aResp->res);
47                 return;
48             }
49 
50             const std::string* s = std::get_if<std::string>(&chassisState);
51             BMCWEB_LOG_DEBUG << "Chassis state: " << *s;
52             if (s != nullptr)
53             {
54                 // Verify Chassis State
55                 if (*s == "xyz.openbmc_project.State.Chassis.PowerState.On")
56                 {
57                     aResp->res.jsonValue["PowerState"] = "On";
58                     aResp->res.jsonValue["Status"]["State"] = "Enabled";
59                 }
60                 else if (*s ==
61                          "xyz.openbmc_project.State.Chassis.PowerState.Off")
62                 {
63                     aResp->res.jsonValue["PowerState"] = "Off";
64                     aResp->res.jsonValue["Status"]["State"] = "StandbyOffline";
65                 }
66             }
67         },
68         "xyz.openbmc_project.State.Chassis",
69         "/xyz/openbmc_project/state/chassis0",
70         "org.freedesktop.DBus.Properties", "Get",
71         "xyz.openbmc_project.State.Chassis", "CurrentPowerState");
72 }
73 
74 /**
75  * DBus types primitives for several generic DBus interfaces
76  * TODO(Pawel) consider move this to separate file into boost::dbus
77  */
78 // Note, this is not a very useful Variant, but because it isn't used to get
79 // values, it should be as simple as possible
80 // TODO(ed) invent a nullvariant type
81 using VariantType = std::variant<bool, std::string, uint64_t, uint32_t>;
82 using ManagedObjectsType = std::vector<std::pair<
83     sdbusplus::message::object_path,
84     std::vector<std::pair<std::string,
85                           std::vector<std::pair<std::string, VariantType>>>>>>;
86 
87 using PropertiesType = boost::container::flat_map<std::string, VariantType>;
88 
89 inline void getIntrusionByService(std::shared_ptr<AsyncResp> aResp,
90                                   const std::string& service,
91                                   const std::string& objPath)
92 {
93     BMCWEB_LOG_DEBUG << "Get intrusion status by service \n";
94 
95     crow::connections::systemBus->async_method_call(
96         [aResp{std::move(aResp)}](const boost::system::error_code ec,
97                                   const std::variant<std::string>& value) {
98             if (ec)
99             {
100                 // do not add err msg in redfish response, because this is not
101                 //     mandatory property
102                 BMCWEB_LOG_ERROR << "DBUS response error " << ec << "\n";
103                 return;
104             }
105 
106             const std::string* status = std::get_if<std::string>(&value);
107 
108             if (status == nullptr)
109             {
110                 BMCWEB_LOG_ERROR << "intrusion status read error \n";
111                 return;
112             }
113 
114             aResp->res.jsonValue["PhysicalSecurity"] = {
115                 {"IntrusionSensorNumber", 1}, {"IntrusionSensor", *status}};
116         },
117         service, objPath, "org.freedesktop.DBus.Properties", "Get",
118         "xyz.openbmc_project.Chassis.Intrusion", "Status");
119 }
120 
121 /**
122  * Retrieves physical security properties over dbus
123  */
124 inline void getPhysicalSecurityData(std::shared_ptr<AsyncResp> aResp)
125 {
126     crow::connections::systemBus->async_method_call(
127         [aResp{std::move(aResp)}](
128             const boost::system::error_code ec,
129             const std::vector<std::pair<
130                 std::string,
131                 std::vector<std::pair<std::string, std::vector<std::string>>>>>&
132                 subtree) {
133             if (ec)
134             {
135                 // do not add err msg in redfish response, because this is not
136                 //     mandatory property
137                 BMCWEB_LOG_ERROR << "DBUS error: no matched iface " << ec
138                                  << "\n";
139                 return;
140             }
141             // Iterate over all retrieved ObjectPaths.
142             for (const auto& object : subtree)
143             {
144                 for (const auto& service : object.second)
145                 {
146                     getIntrusionByService(aResp, service.first, object.first);
147                     return;
148                 }
149             }
150         },
151         "xyz.openbmc_project.ObjectMapper",
152         "/xyz/openbmc_project/object_mapper",
153         "xyz.openbmc_project.ObjectMapper", "GetSubTree",
154         "/xyz/openbmc_project/Intrusion", 1,
155         std::array<const char*, 1>{"xyz.openbmc_project.Chassis.Intrusion"});
156 }
157 
158 /**
159  * ChassisCollection derived class for delivering Chassis Collection Schema
160  */
161 class ChassisCollection : public Node
162 {
163   public:
164     ChassisCollection(App& app) : Node(app, "/redfish/v1/Chassis/")
165     {
166         entityPrivileges = {
167             {boost::beast::http::verb::get, {{"Login"}}},
168             {boost::beast::http::verb::head, {{"Login"}}},
169             {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
170             {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
171             {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
172             {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
173     }
174 
175   private:
176     /**
177      * Functions triggers appropriate requests on DBus
178      */
179     void doGet(crow::Response& res, const crow::Request&,
180                const std::vector<std::string>&) override
181     {
182         res.jsonValue["@odata.type"] = "#ChassisCollection.ChassisCollection";
183         res.jsonValue["@odata.id"] = "/redfish/v1/Chassis";
184         res.jsonValue["Name"] = "Chassis Collection";
185 
186         auto asyncResp = std::make_shared<AsyncResp>(res);
187 
188         collection_util::getCollectionMembers(
189             asyncResp, "/redfish/v1/Chassis",
190             {"xyz.openbmc_project.Inventory.Item.Board",
191              "xyz.openbmc_project.Inventory.Item.Chassis"});
192     }
193 };
194 
195 /**
196  * Chassis override class for delivering Chassis Schema
197  */
198 class Chassis : public Node
199 {
200   public:
201     Chassis(App& app) : Node(app, "/redfish/v1/Chassis/<str>/", std::string())
202     {
203         entityPrivileges = {
204             {boost::beast::http::verb::get, {{"Login"}}},
205             {boost::beast::http::verb::head, {{"Login"}}},
206             {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
207             {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
208             {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
209             {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
210     }
211 
212   private:
213     /**
214      * Functions triggers appropriate requests on DBus
215      */
216     void doGet(crow::Response& res, const crow::Request&,
217                const std::vector<std::string>& params) override
218     {
219         const std::array<const char*, 2> interfaces = {
220             "xyz.openbmc_project.Inventory.Item.Board",
221             "xyz.openbmc_project.Inventory.Item.Chassis"};
222 
223         // Check if there is required param, truly entering this shall be
224         // impossible.
225         if (params.size() != 1)
226         {
227             messages::internalError(res);
228             res.end();
229             return;
230         }
231         const std::string& chassisId = params[0];
232 
233         auto asyncResp = std::make_shared<AsyncResp>(res);
234         crow::connections::systemBus->async_method_call(
235             [asyncResp, chassisId(std::string(chassisId))](
236                 const boost::system::error_code ec,
237                 const crow::openbmc_mapper::GetSubTreeType& subtree) {
238                 if (ec)
239                 {
240                     messages::internalError(asyncResp->res);
241                     return;
242                 }
243                 // Iterate over all retrieved ObjectPaths.
244                 for (const std::pair<
245                          std::string,
246                          std::vector<
247                              std::pair<std::string, std::vector<std::string>>>>&
248                          object : subtree)
249                 {
250                     const std::string& path = object.first;
251                     const std::vector<
252                         std::pair<std::string, std::vector<std::string>>>&
253                         connectionNames = object.second;
254 
255                     if (!boost::ends_with(path, chassisId))
256                     {
257                         continue;
258                     }
259 
260                     auto health = std::make_shared<HealthPopulate>(asyncResp);
261 
262                     crow::connections::systemBus->async_method_call(
263                         [health](const boost::system::error_code ec2,
264                                  std::variant<std::vector<std::string>>& resp) {
265                             if (ec2)
266                             {
267                                 return; // no sensors = no failures
268                             }
269                             std::vector<std::string>* data =
270                                 std::get_if<std::vector<std::string>>(&resp);
271                             if (data == nullptr)
272                             {
273                                 return;
274                             }
275                             health->inventory = std::move(*data);
276                         },
277                         "xyz.openbmc_project.ObjectMapper",
278                         path + "/all_sensors",
279                         "org.freedesktop.DBus.Properties", "Get",
280                         "xyz.openbmc_project.Association", "endpoints");
281 
282                     health->populate();
283 
284                     if (connectionNames.size() < 1)
285                     {
286                         BMCWEB_LOG_ERROR << "Got 0 Connection names";
287                         continue;
288                     }
289 
290                     asyncResp->res.jsonValue["@odata.type"] =
291                         "#Chassis.v1_10_0.Chassis";
292                     asyncResp->res.jsonValue["@odata.id"] =
293                         "/redfish/v1/Chassis/" + chassisId;
294                     asyncResp->res.jsonValue["Name"] = "Chassis Collection";
295                     asyncResp->res.jsonValue["ChassisType"] = "RackMount";
296                     asyncResp->res.jsonValue["Actions"]["#Chassis.Reset"] = {
297                         {"target", "/redfish/v1/Chassis/" + chassisId +
298                                        "/Actions/Chassis.Reset"},
299                         {"@Redfish.ActionInfo", "/redfish/v1/Chassis/" +
300                                                     chassisId +
301                                                     "/ResetActionInfo"}};
302                     asyncResp->res.jsonValue["PCIeDevices"] = {
303                         {"@odata.id",
304                          "/redfish/v1/Systems/system/PCIeDevices"}};
305 
306                     const std::string& connectionName =
307                         connectionNames[0].first;
308 
309                     const std::vector<std::string>& interfaces2 =
310                         connectionNames[0].second;
311                     const std::array<const char*, 2> hasIndicatorLed = {
312                         "xyz.openbmc_project.Inventory.Item.Panel",
313                         "xyz.openbmc_project.Inventory.Item.Board.Motherboard"};
314 
315                     for (const char* interface : hasIndicatorLed)
316                     {
317                         if (std::find(interfaces2.begin(), interfaces2.end(),
318                                       interface) != interfaces2.end())
319                         {
320                             getIndicatorLedState(asyncResp);
321                             break;
322                         }
323                     }
324 
325                     crow::connections::systemBus->async_method_call(
326                         [asyncResp, chassisId(std::string(chassisId))](
327                             const boost::system::error_code /*ec2*/,
328                             const std::vector<std::pair<
329                                 std::string, VariantType>>& propertiesList) {
330                             for (const std::pair<std::string, VariantType>&
331                                      property : propertiesList)
332                             {
333                                 // Store DBus properties that are also Redfish
334                                 // properties with same name and a string value
335                                 const std::string& propertyName =
336                                     property.first;
337                                 if ((propertyName == "PartNumber") ||
338                                     (propertyName == "SerialNumber") ||
339                                     (propertyName == "Manufacturer") ||
340                                     (propertyName == "Model"))
341                                 {
342                                     const std::string* value =
343                                         std::get_if<std::string>(
344                                             &property.second);
345                                     if (value != nullptr)
346                                     {
347                                         asyncResp->res.jsonValue[propertyName] =
348                                             *value;
349                                     }
350                                 }
351                             }
352                             asyncResp->res.jsonValue["Name"] = chassisId;
353                             asyncResp->res.jsonValue["Id"] = chassisId;
354                             asyncResp->res.jsonValue["Thermal"] = {
355                                 {"@odata.id", "/redfish/v1/Chassis/" +
356                                                   chassisId + "/Thermal"}};
357                             // Power object
358                             asyncResp->res.jsonValue["Power"] = {
359                                 {"@odata.id", "/redfish/v1/Chassis/" +
360                                                   chassisId + "/Power"}};
361                             // SensorCollection
362                             asyncResp->res.jsonValue["Sensors"] = {
363                                 {"@odata.id", "/redfish/v1/Chassis/" +
364                                                   chassisId + "/Sensors"}};
365                             asyncResp->res.jsonValue["Status"] = {
366                                 {"State", "Enabled"},
367                             };
368 
369                             asyncResp->res
370                                 .jsonValue["Links"]["ComputerSystems"] = {
371                                 {{"@odata.id", "/redfish/v1/Systems/system"}}};
372                             asyncResp->res.jsonValue["Links"]["ManagedBy"] = {
373                                 {{"@odata.id", "/redfish/v1/Managers/bmc"}}};
374                             getChassisState(asyncResp);
375                         },
376                         connectionName, path, "org.freedesktop.DBus.Properties",
377                         "GetAll",
378                         "xyz.openbmc_project.Inventory.Decorator.Asset");
379                     return;
380                 }
381 
382                 // Couldn't find an object with that name.  return an error
383                 messages::resourceNotFound(
384                     asyncResp->res, "#Chassis.v1_10_0.Chassis", chassisId);
385             },
386             "xyz.openbmc_project.ObjectMapper",
387             "/xyz/openbmc_project/object_mapper",
388             "xyz.openbmc_project.ObjectMapper", "GetSubTree",
389             "/xyz/openbmc_project/inventory", 0, interfaces);
390 
391         getPhysicalSecurityData(asyncResp);
392     }
393 
394     void doPatch(crow::Response& res, const crow::Request& req,
395                  const std::vector<std::string>& params) override
396     {
397         std::optional<std::string> indicatorLed;
398         auto asyncResp = std::make_shared<AsyncResp>(res);
399 
400         if (params.size() != 1)
401         {
402             return;
403         }
404 
405         if (!json_util::readJson(req, res, "IndicatorLED", indicatorLed))
406         {
407             return;
408         }
409 
410         if (!indicatorLed)
411         {
412             return; // delete this when we support more patch properties
413         }
414 
415         const std::array<const char*, 2> interfaces = {
416             "xyz.openbmc_project.Inventory.Item.Board",
417             "xyz.openbmc_project.Inventory.Item.Chassis"};
418 
419         const std::string& chassisId = params[0];
420 
421         crow::connections::systemBus->async_method_call(
422             [asyncResp, chassisId, indicatorLed](
423                 const boost::system::error_code ec,
424                 const crow::openbmc_mapper::GetSubTreeType& subtree) {
425                 if (ec)
426                 {
427                     messages::internalError(asyncResp->res);
428                     return;
429                 }
430 
431                 // Iterate over all retrieved ObjectPaths.
432                 for (const std::pair<
433                          std::string,
434                          std::vector<
435                              std::pair<std::string, std::vector<std::string>>>>&
436                          object : subtree)
437                 {
438                     const std::string& path = object.first;
439                     const std::vector<
440                         std::pair<std::string, std::vector<std::string>>>&
441                         connectionNames = object.second;
442 
443                     if (!boost::ends_with(path, chassisId))
444                     {
445                         continue;
446                     }
447 
448                     if (connectionNames.size() < 1)
449                     {
450                         BMCWEB_LOG_ERROR << "Got 0 Connection names";
451                         continue;
452                     }
453 
454                     const std::vector<std::string>& interfaces3 =
455                         connectionNames[0].second;
456 
457                     if (indicatorLed)
458                     {
459                         const std::array<const char*, 2> hasIndicatorLed = {
460                             "xyz.openbmc_project.Inventory.Item.Panel",
461                             "xyz.openbmc_project.Inventory.Item.Board."
462                             "Motherboard"};
463                         bool indicatorChassis = false;
464                         for (const char* interface : hasIndicatorLed)
465                         {
466                             if (std::find(interfaces3.begin(),
467                                           interfaces3.end(),
468                                           interface) != interfaces3.end())
469                             {
470                                 indicatorChassis = true;
471                                 break;
472                             }
473                         }
474                         if (indicatorChassis)
475                         {
476                             setIndicatorLedState(asyncResp, *indicatorLed);
477                         }
478                         else
479                         {
480                             messages::propertyUnknown(asyncResp->res,
481                                                       "IndicatorLED");
482                         }
483                     }
484                     return;
485                 }
486 
487                 messages::resourceNotFound(
488                     asyncResp->res, "#Chassis.v1_10_0.Chassis", chassisId);
489             },
490             "xyz.openbmc_project.ObjectMapper",
491             "/xyz/openbmc_project/object_mapper",
492             "xyz.openbmc_project.ObjectMapper", "GetSubTree",
493             "/xyz/openbmc_project/inventory", 0, interfaces);
494     }
495 };
496 
497 inline void doChassisPowerCycle(const std::shared_ptr<AsyncResp>& asyncResp)
498 {
499     const char* busName = "xyz.openbmc_project.ObjectMapper";
500     const char* path = "/xyz/openbmc_project/object_mapper";
501     const char* interface = "xyz.openbmc_project.ObjectMapper";
502     const char* method = "GetSubTreePaths";
503 
504     const std::array<const char*, 1> interfaces = {
505         "xyz.openbmc_project.State.Chassis"};
506 
507     // Use mapper to get subtree paths.
508     crow::connections::systemBus->async_method_call(
509         [asyncResp](const boost::system::error_code ec,
510                     const std::vector<std::string>& chassisList) {
511             if (ec)
512             {
513                 BMCWEB_LOG_DEBUG << "[mapper] Bad D-Bus request error: " << ec;
514                 messages::internalError(asyncResp->res);
515                 return;
516             }
517 
518             const char* processName = "xyz.openbmc_project.State.Chassis";
519             const char* interfaceName = "xyz.openbmc_project.State.Chassis";
520             const char* destProperty = "RequestedPowerTransition";
521             const std::string propertyValue =
522                 "xyz.openbmc_project.State.Chassis.Transition.PowerCycle";
523             std::string objectPath =
524                 "/xyz/openbmc_project/state/chassis_system0";
525 
526             /* Look for system reset chassis path */
527             if ((std::find(chassisList.begin(), chassisList.end(),
528                            objectPath)) == chassisList.end())
529             {
530                 /* We prefer to reset the full chassis_system, but if it doesn't
531                  * exist on some platforms, fall back to a host-only power reset
532                  */
533                 objectPath = "/xyz/openbmc_project/state/chassis0";
534             }
535 
536             crow::connections::systemBus->async_method_call(
537                 [asyncResp](const boost::system::error_code ec) {
538                     // Use "Set" method to set the property value.
539                     if (ec)
540                     {
541                         BMCWEB_LOG_DEBUG << "[Set] Bad D-Bus request error: "
542                                          << ec;
543                         messages::internalError(asyncResp->res);
544                         return;
545                     }
546 
547                     messages::success(asyncResp->res);
548                 },
549                 processName, objectPath, "org.freedesktop.DBus.Properties",
550                 "Set", interfaceName, destProperty,
551                 std::variant<std::string>{propertyValue});
552         },
553         busName, path, interface, method, "/", 0, interfaces);
554 }
555 
556 /**
557  * ChassisResetAction class supports the POST method for the Reset
558  * action.
559  */
560 class ChassisResetAction : public Node
561 {
562   public:
563     ChassisResetAction(App& app) :
564         Node(app, "/redfish/v1/Chassis/<str>/Actions/Chassis.Reset/",
565              std::string())
566     {
567         entityPrivileges = {
568             {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
569     }
570 
571   private:
572     /**
573      * Function handles POST method request.
574      * Analyzes POST body before sending Reset request data to D-Bus.
575      */
576     void doPost(crow::Response& res, const crow::Request& req,
577                 const std::vector<std::string>&) override
578     {
579         BMCWEB_LOG_DEBUG << "Post Chassis Reset.";
580 
581         std::string resetType;
582         auto asyncResp = std::make_shared<AsyncResp>(res);
583 
584         if (!json_util::readJson(req, asyncResp->res, "ResetType", resetType))
585         {
586             return;
587         }
588 
589         if (resetType != "PowerCycle")
590         {
591             BMCWEB_LOG_DEBUG << "Invalid property value for ResetType: "
592                              << resetType;
593             messages::actionParameterNotSupported(asyncResp->res, resetType,
594                                                   "ResetType");
595 
596             return;
597         }
598         doChassisPowerCycle(asyncResp);
599     }
600 };
601 
602 /**
603  * ChassisResetActionInfo derived class for delivering Chassis
604  * ResetType AllowableValues using ResetInfo schema.
605  */
606 class ChassisResetActionInfo : public Node
607 {
608   public:
609     /*
610      * Default Constructor
611      */
612     ChassisResetActionInfo(App& app) :
613         Node(app, "/redfish/v1/Chassis/<str>/ResetActionInfo/", std::string())
614     {
615         entityPrivileges = {
616             {boost::beast::http::verb::get, {{"Login"}}},
617             {boost::beast::http::verb::head, {{"Login"}}},
618             {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
619             {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
620             {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
621             {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
622     }
623 
624   private:
625     /**
626      * Functions triggers appropriate requests on DBus
627      */
628     void doGet(crow::Response& res, const crow::Request&,
629                const std::vector<std::string>& params) override
630     {
631         if (params.size() != 1)
632         {
633             messages::internalError(res);
634             res.end();
635             return;
636         }
637         const std::string& chassisId = params[0];
638 
639         res.jsonValue = {{"@odata.type", "#ActionInfo.v1_1_2.ActionInfo"},
640                          {"@odata.id", "/redfish/v1/Chassis/" + chassisId +
641                                            "/ResetActionInfo"},
642                          {"Name", "Reset Action Info"},
643                          {"Id", "ResetActionInfo"},
644                          {"Parameters",
645                           {{{"Name", "ResetType"},
646                             {"Required", true},
647                             {"DataType", "String"},
648                             {"AllowableValues", {"PowerCycle"}}}}}};
649         res.end();
650     }
651 };
652 
653 } // namespace redfish
654