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