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 "redfish_util.hpp"
20 
21 #include <app.hpp>
22 #include <boost/algorithm/string/replace.hpp>
23 #include <boost/date_time.hpp>
24 #include <dbus_utility.hpp>
25 #include <registries/privilege_registry.hpp>
26 #include <utils/fw_utils.hpp>
27 #include <utils/systemd_utils.hpp>
28 
29 #include <cstdint>
30 #include <memory>
31 #include <sstream>
32 #include <variant>
33 
34 namespace redfish
35 {
36 
37 /**
38  * Function reboots the BMC.
39  *
40  * @param[in] asyncResp - Shared pointer for completing asynchronous calls
41  */
42 inline void
43     doBMCGracefulRestart(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
44 {
45     const char* processName = "xyz.openbmc_project.State.BMC";
46     const char* objectPath = "/xyz/openbmc_project/state/bmc0";
47     const char* interfaceName = "xyz.openbmc_project.State.BMC";
48     const std::string& propertyValue =
49         "xyz.openbmc_project.State.BMC.Transition.Reboot";
50     const char* destProperty = "RequestedBMCTransition";
51 
52     // Create the D-Bus variant for D-Bus call.
53     dbus::utility::DbusVariantType dbusPropertyValue(propertyValue);
54 
55     crow::connections::systemBus->async_method_call(
56         [asyncResp](const boost::system::error_code ec) {
57             // Use "Set" method to set the property value.
58             if (ec)
59             {
60                 BMCWEB_LOG_DEBUG << "[Set] Bad D-Bus request error: " << ec;
61                 messages::internalError(asyncResp->res);
62                 return;
63             }
64 
65             messages::success(asyncResp->res);
66         },
67         processName, objectPath, "org.freedesktop.DBus.Properties", "Set",
68         interfaceName, destProperty, dbusPropertyValue);
69 }
70 
71 inline void
72     doBMCForceRestart(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
73 {
74     const char* processName = "xyz.openbmc_project.State.BMC";
75     const char* objectPath = "/xyz/openbmc_project/state/bmc0";
76     const char* interfaceName = "xyz.openbmc_project.State.BMC";
77     const std::string& propertyValue =
78         "xyz.openbmc_project.State.BMC.Transition.HardReboot";
79     const char* destProperty = "RequestedBMCTransition";
80 
81     // Create the D-Bus variant for D-Bus call.
82     dbus::utility::DbusVariantType dbusPropertyValue(propertyValue);
83 
84     crow::connections::systemBus->async_method_call(
85         [asyncResp](const boost::system::error_code ec) {
86             // Use "Set" method to set the property value.
87             if (ec)
88             {
89                 BMCWEB_LOG_DEBUG << "[Set] Bad D-Bus request error: " << ec;
90                 messages::internalError(asyncResp->res);
91                 return;
92             }
93 
94             messages::success(asyncResp->res);
95         },
96         processName, objectPath, "org.freedesktop.DBus.Properties", "Set",
97         interfaceName, destProperty, dbusPropertyValue);
98 }
99 
100 /**
101  * ManagerResetAction class supports the POST method for the Reset (reboot)
102  * action.
103  */
104 inline void requestRoutesManagerResetAction(App& app)
105 {
106     /**
107      * Function handles POST method request.
108      * Analyzes POST body before sending Reset (Reboot) request data to D-Bus.
109      * OpenBMC supports ResetType "GracefulRestart" and "ForceRestart".
110      */
111 
112     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/Actions/Manager.Reset/")
113         .privileges(redfish::privileges::postManager)
114         .methods(boost::beast::http::verb::post)(
115             [](const crow::Request& req,
116                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
117                 BMCWEB_LOG_DEBUG << "Post Manager Reset.";
118 
119                 std::string resetType;
120 
121                 if (!json_util::readJson(req, asyncResp->res, "ResetType",
122                                          resetType))
123                 {
124                     return;
125                 }
126 
127                 if (resetType == "GracefulRestart")
128                 {
129                     BMCWEB_LOG_DEBUG << "Proceeding with " << resetType;
130                     doBMCGracefulRestart(asyncResp);
131                     return;
132                 }
133                 if (resetType == "ForceRestart")
134                 {
135                     BMCWEB_LOG_DEBUG << "Proceeding with " << resetType;
136                     doBMCForceRestart(asyncResp);
137                     return;
138                 }
139                 BMCWEB_LOG_DEBUG << "Invalid property value for ResetType: "
140                                  << resetType;
141                 messages::actionParameterNotSupported(asyncResp->res, resetType,
142                                                       "ResetType");
143 
144                 return;
145             });
146 }
147 
148 /**
149  * ManagerResetToDefaultsAction class supports POST method for factory reset
150  * action.
151  */
152 inline void requestRoutesManagerResetToDefaultsAction(App& app)
153 {
154 
155     /**
156      * Function handles ResetToDefaults POST method request.
157      *
158      * Analyzes POST body message and factory resets BMC by calling
159      * BMC code updater factory reset followed by a BMC reboot.
160      *
161      * BMC code updater factory reset wipes the whole BMC read-write
162      * filesystem which includes things like the network settings.
163      *
164      * OpenBMC only supports ResetToDefaultsType "ResetAll".
165      */
166 
167     BMCWEB_ROUTE(app,
168                  "/redfish/v1/Managers/bmc/Actions/Manager.ResetToDefaults/")
169         .privileges(redfish::privileges::postManager)
170         .methods(boost::beast::http::verb::post)(
171             [](const crow::Request& req,
172                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
173                 BMCWEB_LOG_DEBUG << "Post ResetToDefaults.";
174 
175                 std::string resetType;
176 
177                 if (!json_util::readJson(req, asyncResp->res,
178                                          "ResetToDefaultsType", resetType))
179                 {
180                     BMCWEB_LOG_DEBUG << "Missing property ResetToDefaultsType.";
181 
182                     messages::actionParameterMissing(asyncResp->res,
183                                                      "ResetToDefaults",
184                                                      "ResetToDefaultsType");
185                     return;
186                 }
187 
188                 if (resetType != "ResetAll")
189                 {
190                     BMCWEB_LOG_DEBUG
191                         << "Invalid property value for ResetToDefaultsType: "
192                         << resetType;
193                     messages::actionParameterNotSupported(
194                         asyncResp->res, resetType, "ResetToDefaultsType");
195                     return;
196                 }
197 
198                 crow::connections::systemBus->async_method_call(
199                     [asyncResp](const boost::system::error_code ec) {
200                         if (ec)
201                         {
202                             BMCWEB_LOG_DEBUG << "Failed to ResetToDefaults: "
203                                              << ec;
204                             messages::internalError(asyncResp->res);
205                             return;
206                         }
207                         // Factory Reset doesn't actually happen until a reboot
208                         // Can't erase what the BMC is running on
209                         doBMCGracefulRestart(asyncResp);
210                     },
211                     "xyz.openbmc_project.Software.BMC.Updater",
212                     "/xyz/openbmc_project/software",
213                     "xyz.openbmc_project.Common.FactoryReset", "Reset");
214             });
215 }
216 
217 /**
218  * ManagerResetActionInfo derived class for delivering Manager
219  * ResetType AllowableValues using ResetInfo schema.
220  */
221 inline void requestRoutesManagerResetActionInfo(App& app)
222 {
223     /**
224      * Functions triggers appropriate requests on DBus
225      */
226 
227     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/ResetActionInfo/")
228         .privileges(redfish::privileges::getActionInfo)
229         .methods(boost::beast::http::verb::get)(
230             [](const crow::Request&,
231                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
232                 asyncResp->res.jsonValue = {
233                     {"@odata.type", "#ActionInfo.v1_1_2.ActionInfo"},
234                     {"@odata.id", "/redfish/v1/Managers/bmc/ResetActionInfo"},
235                     {"Name", "Reset Action Info"},
236                     {"Id", "ResetActionInfo"},
237                     {"Parameters",
238                      {{{"Name", "ResetType"},
239                        {"Required", true},
240                        {"DataType", "String"},
241                        {"AllowableValues",
242                         {"GracefulRestart", "ForceRestart"}}}}}};
243             });
244 }
245 
246 static constexpr const char* objectManagerIface =
247     "org.freedesktop.DBus.ObjectManager";
248 static constexpr const char* pidConfigurationIface =
249     "xyz.openbmc_project.Configuration.Pid";
250 static constexpr const char* pidZoneConfigurationIface =
251     "xyz.openbmc_project.Configuration.Pid.Zone";
252 static constexpr const char* stepwiseConfigurationIface =
253     "xyz.openbmc_project.Configuration.Stepwise";
254 static constexpr const char* thermalModeIface =
255     "xyz.openbmc_project.Control.ThermalMode";
256 
257 inline void
258     asyncPopulatePid(const std::string& connection, const std::string& path,
259                      const std::string& currentProfile,
260                      const std::vector<std::string>& supportedProfiles,
261                      const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
262 {
263 
264     crow::connections::systemBus->async_method_call(
265         [asyncResp, currentProfile, supportedProfiles](
266             const boost::system::error_code ec,
267             const dbus::utility::ManagedObjectType& managedObj) {
268             if (ec)
269             {
270                 BMCWEB_LOG_ERROR << ec;
271                 asyncResp->res.jsonValue.clear();
272                 messages::internalError(asyncResp->res);
273                 return;
274             }
275             nlohmann::json& configRoot =
276                 asyncResp->res.jsonValue["Oem"]["OpenBmc"]["Fan"];
277             nlohmann::json& fans = configRoot["FanControllers"];
278             fans["@odata.type"] = "#OemManager.FanControllers";
279             fans["@odata.id"] =
280                 "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/FanControllers";
281 
282             nlohmann::json& pids = configRoot["PidControllers"];
283             pids["@odata.type"] = "#OemManager.PidControllers";
284             pids["@odata.id"] =
285                 "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/PidControllers";
286 
287             nlohmann::json& stepwise = configRoot["StepwiseControllers"];
288             stepwise["@odata.type"] = "#OemManager.StepwiseControllers";
289             stepwise["@odata.id"] =
290                 "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/StepwiseControllers";
291 
292             nlohmann::json& zones = configRoot["FanZones"];
293             zones["@odata.id"] =
294                 "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/FanZones";
295             zones["@odata.type"] = "#OemManager.FanZones";
296             configRoot["@odata.id"] =
297                 "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan";
298             configRoot["@odata.type"] = "#OemManager.Fan";
299             configRoot["Profile@Redfish.AllowableValues"] = supportedProfiles;
300 
301             if (!currentProfile.empty())
302             {
303                 configRoot["Profile"] = currentProfile;
304             }
305             BMCWEB_LOG_ERROR << "profile = " << currentProfile << " !";
306 
307             for (const auto& pathPair : managedObj)
308             {
309                 for (const auto& intfPair : pathPair.second)
310                 {
311                     if (intfPair.first != pidConfigurationIface &&
312                         intfPair.first != pidZoneConfigurationIface &&
313                         intfPair.first != stepwiseConfigurationIface)
314                     {
315                         continue;
316                     }
317 
318                     std::string name;
319 
320                     for (const std::pair<std::string,
321                                          dbus::utility::DbusVariantType>&
322                              propPair : intfPair.second)
323                     {
324                         if (propPair.first == "Name")
325                         {
326                             const std::string* namePtr =
327                                 std::get_if<std::string>(&propPair.second);
328                             if (namePtr == nullptr)
329                             {
330                                 BMCWEB_LOG_ERROR << "Pid Name Field illegal";
331                                 messages::internalError(asyncResp->res);
332                                 return;
333                             }
334                             std::string name = *namePtr;
335                             dbus::utility::escapePathForDbus(name);
336                         }
337                         else if (propPair.first == "Profiles")
338                         {
339                             const std::vector<std::string>* profiles =
340                                 std::get_if<std::vector<std::string>>(
341                                     &propPair.second);
342                             if (profiles == nullptr)
343                             {
344                                 BMCWEB_LOG_ERROR
345                                     << "Pid Profiles Field illegal";
346                                 messages::internalError(asyncResp->res);
347                                 return;
348                             }
349                             if (std::find(profiles->begin(), profiles->end(),
350                                           currentProfile) == profiles->end())
351                             {
352                                 BMCWEB_LOG_INFO
353                                     << name
354                                     << " not supported in current profile";
355                                 continue;
356                             }
357                         }
358                     }
359                     nlohmann::json* config = nullptr;
360                     const std::string* classPtr = nullptr;
361 
362                     for (const std::pair<std::string,
363                                          dbus::utility::DbusVariantType>&
364                              propPair : intfPair.second)
365                     {
366                         if (intfPair.first == "Class")
367                         {
368                             classPtr =
369                                 std::get_if<std::string>(&propPair.second);
370                         }
371                     }
372 
373                     if (intfPair.first == pidZoneConfigurationIface)
374                     {
375                         std::string chassis;
376                         if (!dbus::utility::getNthStringFromPath(
377                                 pathPair.first.str, 5, chassis))
378                         {
379                             chassis = "#IllegalValue";
380                         }
381                         nlohmann::json& zone = zones[name];
382                         zone["Chassis"] = {
383                             {"@odata.id", "/redfish/v1/Chassis/" + chassis}};
384                         zone["@odata.id"] =
385                             "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/FanZones/" +
386                             name;
387                         zone["@odata.type"] = "#OemManager.FanZone";
388                         config = &zone;
389                     }
390 
391                     else if (intfPair.first == stepwiseConfigurationIface)
392                     {
393                         if (classPtr == nullptr)
394                         {
395                             BMCWEB_LOG_ERROR << "Pid Class Field illegal";
396                             messages::internalError(asyncResp->res);
397                             return;
398                         }
399 
400                         nlohmann::json& controller = stepwise[name];
401                         config = &controller;
402 
403                         controller["@odata.id"] =
404                             "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/StepwiseControllers/" +
405                             name;
406                         controller["@odata.type"] =
407                             "#OemManager.StepwiseController";
408 
409                         controller["Direction"] = *classPtr;
410                     }
411 
412                     // pid and fans are off the same configuration
413                     else if (intfPair.first == pidConfigurationIface)
414                     {
415 
416                         if (classPtr == nullptr)
417                         {
418                             BMCWEB_LOG_ERROR << "Pid Class Field illegal";
419                             messages::internalError(asyncResp->res);
420                             return;
421                         }
422                         bool isFan = *classPtr == "fan";
423                         nlohmann::json& element =
424                             isFan ? fans[name] : pids[name];
425                         config = &element;
426                         if (isFan)
427                         {
428                             element["@odata.id"] =
429                                 "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/FanControllers/" +
430                                 name;
431                             element["@odata.type"] =
432                                 "#OemManager.FanController";
433                         }
434                         else
435                         {
436                             element["@odata.id"] =
437                                 "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/PidControllers/" +
438                                 name;
439                             element["@odata.type"] =
440                                 "#OemManager.PidController";
441                         }
442                     }
443                     else
444                     {
445                         BMCWEB_LOG_ERROR << "Unexpected configuration";
446                         messages::internalError(asyncResp->res);
447                         return;
448                     }
449 
450                     // used for making maps out of 2 vectors
451                     const std::vector<double>* keys = nullptr;
452                     const std::vector<double>* values = nullptr;
453 
454                     for (const auto& propertyPair : intfPair.second)
455                     {
456                         if (propertyPair.first == "Type" ||
457                             propertyPair.first == "Class" ||
458                             propertyPair.first == "Name")
459                         {
460                             continue;
461                         }
462 
463                         // zones
464                         if (intfPair.first == pidZoneConfigurationIface)
465                         {
466                             const double* ptr =
467                                 std::get_if<double>(&propertyPair.second);
468                             if (ptr == nullptr)
469                             {
470                                 BMCWEB_LOG_ERROR << "Field Illegal "
471                                                  << propertyPair.first;
472                                 messages::internalError(asyncResp->res);
473                                 return;
474                             }
475                             (*config)[propertyPair.first] = *ptr;
476                         }
477 
478                         if (intfPair.first == stepwiseConfigurationIface)
479                         {
480                             if (propertyPair.first == "Reading" ||
481                                 propertyPair.first == "Output")
482                             {
483                                 const std::vector<double>* ptr =
484                                     std::get_if<std::vector<double>>(
485                                         &propertyPair.second);
486 
487                                 if (ptr == nullptr)
488                                 {
489                                     BMCWEB_LOG_ERROR << "Field Illegal "
490                                                      << propertyPair.first;
491                                     messages::internalError(asyncResp->res);
492                                     return;
493                                 }
494 
495                                 if (propertyPair.first == "Reading")
496                                 {
497                                     keys = ptr;
498                                 }
499                                 else
500                                 {
501                                     values = ptr;
502                                 }
503                                 if (keys && values)
504                                 {
505                                     if (keys->size() != values->size())
506                                     {
507                                         BMCWEB_LOG_ERROR
508                                             << "Reading and Output size don't match ";
509                                         messages::internalError(asyncResp->res);
510                                         return;
511                                     }
512                                     nlohmann::json& steps = (*config)["Steps"];
513                                     steps = nlohmann::json::array();
514                                     for (size_t ii = 0; ii < keys->size(); ii++)
515                                     {
516                                         steps.push_back(
517                                             {{"Target", (*keys)[ii]},
518                                              {"Output", (*values)[ii]}});
519                                     }
520                                 }
521                             }
522                             if (propertyPair.first == "NegativeHysteresis" ||
523                                 propertyPair.first == "PositiveHysteresis")
524                             {
525                                 const double* ptr =
526                                     std::get_if<double>(&propertyPair.second);
527                                 if (ptr == nullptr)
528                                 {
529                                     BMCWEB_LOG_ERROR << "Field Illegal "
530                                                      << propertyPair.first;
531                                     messages::internalError(asyncResp->res);
532                                     return;
533                                 }
534                                 (*config)[propertyPair.first] = *ptr;
535                             }
536                         }
537 
538                         // pid and fans are off the same configuration
539                         if (intfPair.first == pidConfigurationIface ||
540                             intfPair.first == stepwiseConfigurationIface)
541                         {
542 
543                             if (propertyPair.first == "Zones")
544                             {
545                                 const std::vector<std::string>* inputs =
546                                     std::get_if<std::vector<std::string>>(
547                                         &propertyPair.second);
548 
549                                 if (inputs == nullptr)
550                                 {
551                                     BMCWEB_LOG_ERROR
552                                         << "Zones Pid Field Illegal";
553                                     messages::internalError(asyncResp->res);
554                                     return;
555                                 }
556                                 auto& data = (*config)[propertyPair.first];
557                                 data = nlohmann::json::array();
558                                 for (std::string itemCopy : *inputs)
559                                 {
560                                     dbus::utility::escapePathForDbus(itemCopy);
561                                     data.push_back(
562                                         {{"@odata.id",
563                                           "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/FanZones/" +
564                                               itemCopy}});
565                                 }
566                             }
567                             // todo(james): may never happen, but this
568                             // assumes configuration data referenced in the
569                             // PID config is provided by the same daemon, we
570                             // could add another loop to cover all cases,
571                             // but I'm okay kicking this can down the road a
572                             // bit
573 
574                             else if (propertyPair.first == "Inputs" ||
575                                      propertyPair.first == "Outputs")
576                             {
577                                 auto& data = (*config)[propertyPair.first];
578                                 const std::vector<std::string>* inputs =
579                                     std::get_if<std::vector<std::string>>(
580                                         &propertyPair.second);
581 
582                                 if (inputs == nullptr)
583                                 {
584                                     BMCWEB_LOG_ERROR << "Field Illegal "
585                                                      << propertyPair.first;
586                                     messages::internalError(asyncResp->res);
587                                     return;
588                                 }
589                                 data = *inputs;
590                             }
591                             else if (propertyPair.first == "SetPointOffset")
592                             {
593                                 const std::string* ptr =
594                                     std::get_if<std::string>(
595                                         &propertyPair.second);
596 
597                                 if (ptr == nullptr)
598                                 {
599                                     BMCWEB_LOG_ERROR << "Field Illegal "
600                                                      << propertyPair.first;
601                                     messages::internalError(asyncResp->res);
602                                     return;
603                                 }
604                                 // translate from dbus to redfish
605                                 if (*ptr == "WarningHigh")
606                                 {
607                                     (*config)["SetPointOffset"] =
608                                         "UpperThresholdNonCritical";
609                                 }
610                                 else if (*ptr == "WarningLow")
611                                 {
612                                     (*config)["SetPointOffset"] =
613                                         "LowerThresholdNonCritical";
614                                 }
615                                 else if (*ptr == "CriticalHigh")
616                                 {
617                                     (*config)["SetPointOffset"] =
618                                         "UpperThresholdCritical";
619                                 }
620                                 else if (*ptr == "CriticalLow")
621                                 {
622                                     (*config)["SetPointOffset"] =
623                                         "LowerThresholdCritical";
624                                 }
625                                 else
626                                 {
627                                     BMCWEB_LOG_ERROR << "Value Illegal "
628                                                      << *ptr;
629                                     messages::internalError(asyncResp->res);
630                                     return;
631                                 }
632                             }
633                             // doubles
634                             else if (propertyPair.first ==
635                                          "FFGainCoefficient" ||
636                                      propertyPair.first == "FFOffCoefficient" ||
637                                      propertyPair.first == "ICoefficient" ||
638                                      propertyPair.first == "ILimitMax" ||
639                                      propertyPair.first == "ILimitMin" ||
640                                      propertyPair.first ==
641                                          "PositiveHysteresis" ||
642                                      propertyPair.first ==
643                                          "NegativeHysteresis" ||
644                                      propertyPair.first == "OutLimitMax" ||
645                                      propertyPair.first == "OutLimitMin" ||
646                                      propertyPair.first == "PCoefficient" ||
647                                      propertyPair.first == "SetPoint" ||
648                                      propertyPair.first == "SlewNeg" ||
649                                      propertyPair.first == "SlewPos")
650                             {
651                                 const double* ptr =
652                                     std::get_if<double>(&propertyPair.second);
653                                 if (ptr == nullptr)
654                                 {
655                                     BMCWEB_LOG_ERROR << "Field Illegal "
656                                                      << propertyPair.first;
657                                     messages::internalError(asyncResp->res);
658                                     return;
659                                 }
660                                 (*config)[propertyPair.first] = *ptr;
661                             }
662                         }
663                     }
664                 }
665             }
666         },
667         connection, path, objectManagerIface, "GetManagedObjects");
668 }
669 
670 enum class CreatePIDRet
671 {
672     fail,
673     del,
674     patch
675 };
676 
677 inline bool
678     getZonesFromJsonReq(const std::shared_ptr<bmcweb::AsyncResp>& response,
679                         std::vector<nlohmann::json>& config,
680                         std::vector<std::string>& zones)
681 {
682     if (config.empty())
683     {
684         BMCWEB_LOG_ERROR << "Empty Zones";
685         messages::propertyValueFormatError(response->res,
686                                            nlohmann::json::array(), "Zones");
687         return false;
688     }
689     for (auto& odata : config)
690     {
691         std::string path;
692         if (!redfish::json_util::readJson(odata, response->res, "@odata.id",
693                                           path))
694         {
695             return false;
696         }
697         std::string input;
698 
699         // 8 below comes from
700         // /redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/FanZones/Left
701         //     0    1     2      3    4    5      6     7      8
702         if (!dbus::utility::getNthStringFromPath(path, 8, input))
703         {
704             BMCWEB_LOG_ERROR << "Got invalid path " << path;
705             BMCWEB_LOG_ERROR << "Illegal Type Zones";
706             messages::propertyValueFormatError(response->res, odata.dump(),
707                                                "Zones");
708             return false;
709         }
710         boost::replace_all(input, "_", " ");
711         zones.emplace_back(std::move(input));
712     }
713     return true;
714 }
715 
716 inline const dbus::utility::ManagedObjectType::value_type*
717     findChassis(const dbus::utility::ManagedObjectType& managedObj,
718                 const std::string& value, std::string& chassis)
719 {
720     BMCWEB_LOG_DEBUG << "Find Chassis: " << value << "\n";
721 
722     std::string escaped = boost::replace_all_copy(value, " ", "_");
723     escaped = "/" + escaped;
724     auto it = std::find_if(
725         managedObj.begin(), managedObj.end(), [&escaped](const auto& obj) {
726             if (boost::algorithm::ends_with(obj.first.str, escaped))
727             {
728                 BMCWEB_LOG_DEBUG << "Matched " << obj.first.str << "\n";
729                 return true;
730             }
731             return false;
732         });
733 
734     if (it == managedObj.end())
735     {
736         return nullptr;
737     }
738     // 5 comes from <chassis-name> being the 5th element
739     // /xyz/openbmc_project/inventory/system/chassis/<chassis-name>
740     if (dbus::utility::getNthStringFromPath(it->first.str, 5, chassis))
741     {
742         return &(*it);
743     }
744 
745     return nullptr;
746 }
747 
748 inline CreatePIDRet createPidInterface(
749     const std::shared_ptr<bmcweb::AsyncResp>& response, const std::string& type,
750     const nlohmann::json::iterator& it, const std::string& path,
751     const dbus::utility::ManagedObjectType& managedObj, bool createNewObject,
752     boost::container::flat_map<std::string, dbus::utility::DbusVariantType>&
753         output,
754     std::string& chassis, const std::string& profile)
755 {
756 
757     // common deleter
758     if (it.value() == nullptr)
759     {
760         std::string iface;
761         if (type == "PidControllers" || type == "FanControllers")
762         {
763             iface = pidConfigurationIface;
764         }
765         else if (type == "FanZones")
766         {
767             iface = pidZoneConfigurationIface;
768         }
769         else if (type == "StepwiseControllers")
770         {
771             iface = stepwiseConfigurationIface;
772         }
773         else
774         {
775             BMCWEB_LOG_ERROR << "Illegal Type " << type;
776             messages::propertyUnknown(response->res, type);
777             return CreatePIDRet::fail;
778         }
779 
780         BMCWEB_LOG_DEBUG << "del " << path << " " << iface << "\n";
781         // delete interface
782         crow::connections::systemBus->async_method_call(
783             [response, path](const boost::system::error_code ec) {
784                 if (ec)
785                 {
786                     BMCWEB_LOG_ERROR << "Error patching " << path << ": " << ec;
787                     messages::internalError(response->res);
788                     return;
789                 }
790                 messages::success(response->res);
791             },
792             "xyz.openbmc_project.EntityManager", path, iface, "Delete");
793         return CreatePIDRet::del;
794     }
795 
796     const dbus::utility::ManagedObjectType::value_type* managedItem = nullptr;
797     if (!createNewObject)
798     {
799         // if we aren't creating a new object, we should be able to find it on
800         // d-bus
801         managedItem = findChassis(managedObj, it.key(), chassis);
802         if (managedItem == nullptr)
803         {
804             BMCWEB_LOG_ERROR << "Failed to get chassis from config patch";
805             messages::invalidObject(response->res, it.key());
806             return CreatePIDRet::fail;
807         }
808     }
809 
810     if (profile.size() &&
811         (type == "PidControllers" || type == "FanControllers" ||
812          type == "StepwiseControllers"))
813     {
814         if (managedItem == nullptr)
815         {
816             output["Profiles"] = std::vector<std::string>{profile};
817         }
818         else
819         {
820             std::string interface;
821             if (type == "StepwiseControllers")
822             {
823                 interface = stepwiseConfigurationIface;
824             }
825             else
826             {
827                 interface = pidConfigurationIface;
828             }
829             bool ifaceFound = false;
830             for (const auto& iface : managedItem->second)
831             {
832                 if (iface.first == interface)
833                 {
834                     ifaceFound = true;
835                     for (const auto& prop : iface.second)
836                     {
837                         if (prop.first == "Profiles")
838                         {
839                             const std::vector<std::string>* curProfiles =
840                                 std::get_if<std::vector<std::string>>(
841                                     &(prop.second));
842                             if (curProfiles == nullptr)
843                             {
844                                 BMCWEB_LOG_ERROR
845                                     << "Illegal profiles in managed object";
846                                 messages::internalError(response->res);
847                                 return CreatePIDRet::fail;
848                             }
849                             if (std::find(curProfiles->begin(),
850                                           curProfiles->end(),
851                                           profile) == curProfiles->end())
852                             {
853                                 std::vector<std::string> newProfiles =
854                                     *curProfiles;
855                                 newProfiles.push_back(profile);
856                                 output["Profiles"] = newProfiles;
857                             }
858                         }
859                     }
860                 }
861             }
862 
863             if (!ifaceFound)
864             {
865                 BMCWEB_LOG_ERROR
866                     << "Failed to find interface in managed object";
867                 messages::internalError(response->res);
868                 return CreatePIDRet::fail;
869             }
870         }
871     }
872 
873     if (type == "PidControllers" || type == "FanControllers")
874     {
875         if (createNewObject)
876         {
877             output["Class"] = type == "PidControllers" ? std::string("temp")
878                                                        : std::string("fan");
879             output["Type"] = std::string("Pid");
880         }
881 
882         std::optional<std::vector<nlohmann::json>> zones;
883         std::optional<std::vector<std::string>> inputs;
884         std::optional<std::vector<std::string>> outputs;
885         std::map<std::string, std::optional<double>> doubles;
886         std::optional<std::string> setpointOffset;
887         if (!redfish::json_util::readJson(
888                 it.value(), response->res, "Inputs", inputs, "Outputs", outputs,
889                 "Zones", zones, "FFGainCoefficient",
890                 doubles["FFGainCoefficient"], "FFOffCoefficient",
891                 doubles["FFOffCoefficient"], "ICoefficient",
892                 doubles["ICoefficient"], "ILimitMax", doubles["ILimitMax"],
893                 "ILimitMin", doubles["ILimitMin"], "OutLimitMax",
894                 doubles["OutLimitMax"], "OutLimitMin", doubles["OutLimitMin"],
895                 "PCoefficient", doubles["PCoefficient"], "SetPoint",
896                 doubles["SetPoint"], "SetPointOffset", setpointOffset,
897                 "SlewNeg", doubles["SlewNeg"], "SlewPos", doubles["SlewPos"],
898                 "PositiveHysteresis", doubles["PositiveHysteresis"],
899                 "NegativeHysteresis", doubles["NegativeHysteresis"]))
900         {
901             BMCWEB_LOG_ERROR
902                 << "Illegal Property "
903                 << it.value().dump(2, ' ', true,
904                                    nlohmann::json::error_handler_t::replace);
905             return CreatePIDRet::fail;
906         }
907         if (zones)
908         {
909             std::vector<std::string> zonesStr;
910             if (!getZonesFromJsonReq(response, *zones, zonesStr))
911             {
912                 BMCWEB_LOG_ERROR << "Illegal Zones";
913                 return CreatePIDRet::fail;
914             }
915             if (chassis.empty() &&
916                 !findChassis(managedObj, zonesStr[0], chassis))
917             {
918                 BMCWEB_LOG_ERROR << "Failed to get chassis from config patch";
919                 messages::invalidObject(response->res, it.key());
920                 return CreatePIDRet::fail;
921             }
922 
923             output["Zones"] = std::move(zonesStr);
924         }
925         if (inputs || outputs)
926         {
927             std::array<std::optional<std::vector<std::string>>*, 2> containers =
928                 {&inputs, &outputs};
929             size_t index = 0;
930             for (const auto& containerPtr : containers)
931             {
932                 std::optional<std::vector<std::string>>& container =
933                     *containerPtr;
934                 if (!container)
935                 {
936                     index++;
937                     continue;
938                 }
939 
940                 for (std::string& value : *container)
941                 {
942                     boost::replace_all(value, "_", " ");
943                 }
944                 std::string key;
945                 if (index == 0)
946                 {
947                     key = "Inputs";
948                 }
949                 else
950                 {
951                     key = "Outputs";
952                 }
953                 output[key] = *container;
954                 index++;
955             }
956         }
957 
958         if (setpointOffset)
959         {
960             // translate between redfish and dbus names
961             if (*setpointOffset == "UpperThresholdNonCritical")
962             {
963                 output["SetPointOffset"] = std::string("WarningLow");
964             }
965             else if (*setpointOffset == "LowerThresholdNonCritical")
966             {
967                 output["SetPointOffset"] = std::string("WarningHigh");
968             }
969             else if (*setpointOffset == "LowerThresholdCritical")
970             {
971                 output["SetPointOffset"] = std::string("CriticalLow");
972             }
973             else if (*setpointOffset == "UpperThresholdCritical")
974             {
975                 output["SetPointOffset"] = std::string("CriticalHigh");
976             }
977             else
978             {
979                 BMCWEB_LOG_ERROR << "Invalid setpointoffset "
980                                  << *setpointOffset;
981                 messages::invalidObject(response->res, it.key());
982                 return CreatePIDRet::fail;
983             }
984         }
985 
986         // doubles
987         for (const auto& pairs : doubles)
988         {
989             if (!pairs.second)
990             {
991                 continue;
992             }
993             BMCWEB_LOG_DEBUG << pairs.first << " = " << *pairs.second;
994             output[pairs.first] = *(pairs.second);
995         }
996     }
997 
998     else if (type == "FanZones")
999     {
1000         output["Type"] = std::string("Pid.Zone");
1001 
1002         std::optional<nlohmann::json> chassisContainer;
1003         std::optional<double> failSafePercent;
1004         std::optional<double> minThermalOutput;
1005         if (!redfish::json_util::readJson(it.value(), response->res, "Chassis",
1006                                           chassisContainer, "FailSafePercent",
1007                                           failSafePercent, "MinThermalOutput",
1008                                           minThermalOutput))
1009         {
1010             BMCWEB_LOG_ERROR
1011                 << "Illegal Property "
1012                 << it.value().dump(2, ' ', true,
1013                                    nlohmann::json::error_handler_t::replace);
1014             return CreatePIDRet::fail;
1015         }
1016 
1017         if (chassisContainer)
1018         {
1019 
1020             std::string chassisId;
1021             if (!redfish::json_util::readJson(*chassisContainer, response->res,
1022                                               "@odata.id", chassisId))
1023             {
1024                 BMCWEB_LOG_ERROR
1025                     << "Illegal Property "
1026                     << chassisContainer->dump(
1027                            2, ' ', true,
1028                            nlohmann::json::error_handler_t::replace);
1029                 return CreatePIDRet::fail;
1030             }
1031 
1032             // /redfish/v1/chassis/chassis_name/
1033             if (!dbus::utility::getNthStringFromPath(chassisId, 3, chassis))
1034             {
1035                 BMCWEB_LOG_ERROR << "Got invalid path " << chassisId;
1036                 messages::invalidObject(response->res, chassisId);
1037                 return CreatePIDRet::fail;
1038             }
1039         }
1040         if (minThermalOutput)
1041         {
1042             output["MinThermalOutput"] = *minThermalOutput;
1043         }
1044         if (failSafePercent)
1045         {
1046             output["FailSafePercent"] = *failSafePercent;
1047         }
1048     }
1049     else if (type == "StepwiseControllers")
1050     {
1051         output["Type"] = std::string("Stepwise");
1052 
1053         std::optional<std::vector<nlohmann::json>> zones;
1054         std::optional<std::vector<nlohmann::json>> steps;
1055         std::optional<std::vector<std::string>> inputs;
1056         std::optional<double> positiveHysteresis;
1057         std::optional<double> negativeHysteresis;
1058         std::optional<std::string> direction; // upper clipping curve vs lower
1059         if (!redfish::json_util::readJson(
1060                 it.value(), response->res, "Zones", zones, "Steps", steps,
1061                 "Inputs", inputs, "PositiveHysteresis", positiveHysteresis,
1062                 "NegativeHysteresis", negativeHysteresis, "Direction",
1063                 direction))
1064         {
1065             BMCWEB_LOG_ERROR
1066                 << "Illegal Property "
1067                 << it.value().dump(2, ' ', true,
1068                                    nlohmann::json::error_handler_t::replace);
1069             return CreatePIDRet::fail;
1070         }
1071 
1072         if (zones)
1073         {
1074             std::vector<std::string> zonesStrs;
1075             if (!getZonesFromJsonReq(response, *zones, zonesStrs))
1076             {
1077                 BMCWEB_LOG_ERROR << "Illegal Zones";
1078                 return CreatePIDRet::fail;
1079             }
1080             if (chassis.empty() &&
1081                 !findChassis(managedObj, zonesStrs[0], chassis))
1082             {
1083                 BMCWEB_LOG_ERROR << "Failed to get chassis from config patch";
1084                 messages::invalidObject(response->res, it.key());
1085                 return CreatePIDRet::fail;
1086             }
1087             output["Zones"] = std::move(zonesStrs);
1088         }
1089         if (steps)
1090         {
1091             std::vector<double> readings;
1092             std::vector<double> outputs;
1093             for (auto& step : *steps)
1094             {
1095                 double target = 0.0;
1096                 double out = 0.0;
1097 
1098                 if (!redfish::json_util::readJson(step, response->res, "Target",
1099                                                   target, "Output", out))
1100                 {
1101                     BMCWEB_LOG_ERROR
1102                         << "Illegal Property "
1103                         << it.value().dump(
1104                                2, ' ', true,
1105                                nlohmann::json::error_handler_t::replace);
1106                     return CreatePIDRet::fail;
1107                 }
1108                 readings.emplace_back(target);
1109                 outputs.emplace_back(out);
1110             }
1111             output["Reading"] = std::move(readings);
1112             output["Output"] = std::move(outputs);
1113         }
1114         if (inputs)
1115         {
1116             for (std::string& value : *inputs)
1117             {
1118                 boost::replace_all(value, "_", " ");
1119             }
1120             output["Inputs"] = std::move(*inputs);
1121         }
1122         if (negativeHysteresis)
1123         {
1124             output["NegativeHysteresis"] = *negativeHysteresis;
1125         }
1126         if (positiveHysteresis)
1127         {
1128             output["PositiveHysteresis"] = *positiveHysteresis;
1129         }
1130         if (direction)
1131         {
1132             constexpr const std::array<const char*, 2> allowedDirections = {
1133                 "Ceiling", "Floor"};
1134             if (std::find(allowedDirections.begin(), allowedDirections.end(),
1135                           *direction) == allowedDirections.end())
1136             {
1137                 messages::propertyValueTypeError(response->res, "Direction",
1138                                                  *direction);
1139                 return CreatePIDRet::fail;
1140             }
1141             output["Class"] = *direction;
1142         }
1143     }
1144     else
1145     {
1146         BMCWEB_LOG_ERROR << "Illegal Type " << type;
1147         messages::propertyUnknown(response->res, type);
1148         return CreatePIDRet::fail;
1149     }
1150     return CreatePIDRet::patch;
1151 }
1152 struct GetPIDValues : std::enable_shared_from_this<GetPIDValues>
1153 {
1154 
1155     GetPIDValues(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn) :
1156         asyncResp(asyncRespIn)
1157 
1158     {}
1159 
1160     void run()
1161     {
1162         std::shared_ptr<GetPIDValues> self = shared_from_this();
1163 
1164         // get all configurations
1165         crow::connections::systemBus->async_method_call(
1166             [self](const boost::system::error_code ec,
1167                    const crow::openbmc_mapper::GetSubTreeType& subtreeLocal) {
1168                 if (ec)
1169                 {
1170                     BMCWEB_LOG_ERROR << ec;
1171                     messages::internalError(self->asyncResp->res);
1172                     return;
1173                 }
1174                 self->subtree = subtreeLocal;
1175             },
1176             "xyz.openbmc_project.ObjectMapper",
1177             "/xyz/openbmc_project/object_mapper",
1178             "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", 0,
1179             std::array<const char*, 4>{
1180                 pidConfigurationIface, pidZoneConfigurationIface,
1181                 objectManagerIface, stepwiseConfigurationIface});
1182 
1183         // at the same time get the selected profile
1184         crow::connections::systemBus->async_method_call(
1185             [self](const boost::system::error_code ec,
1186                    const crow::openbmc_mapper::GetSubTreeType& subtreeLocal) {
1187                 if (ec || subtreeLocal.empty())
1188                 {
1189                     return;
1190                 }
1191                 if (subtreeLocal[0].second.size() != 1)
1192                 {
1193                     // invalid mapper response, should never happen
1194                     BMCWEB_LOG_ERROR << "GetPIDValues: Mapper Error";
1195                     messages::internalError(self->asyncResp->res);
1196                     return;
1197                 }
1198 
1199                 const std::string& path = subtreeLocal[0].first;
1200                 const std::string& owner = subtreeLocal[0].second[0].first;
1201                 crow::connections::systemBus->async_method_call(
1202                     [path, owner,
1203                      self](const boost::system::error_code ec2,
1204                            const boost::container::flat_map<
1205                                std::string, dbus::utility::DbusVariantType>&
1206                                resp) {
1207                         if (ec2)
1208                         {
1209                             BMCWEB_LOG_ERROR
1210                                 << "GetPIDValues: Can't get thermalModeIface "
1211                                 << path;
1212                             messages::internalError(self->asyncResp->res);
1213                             return;
1214                         }
1215                         const std::string* current = nullptr;
1216                         const std::vector<std::string>* supported = nullptr;
1217                         for (auto& [key, value] : resp)
1218                         {
1219                             if (key == "Current")
1220                             {
1221                                 current = std::get_if<std::string>(&value);
1222                                 if (current == nullptr)
1223                                 {
1224                                     BMCWEB_LOG_ERROR
1225                                         << "GetPIDValues: thermal mode iface invalid "
1226                                         << path;
1227                                     messages::internalError(
1228                                         self->asyncResp->res);
1229                                     return;
1230                                 }
1231                             }
1232                             if (key == "Supported")
1233                             {
1234                                 supported =
1235                                     std::get_if<std::vector<std::string>>(
1236                                         &value);
1237                                 if (supported == nullptr)
1238                                 {
1239                                     BMCWEB_LOG_ERROR
1240                                         << "GetPIDValues: thermal mode iface invalid"
1241                                         << path;
1242                                     messages::internalError(
1243                                         self->asyncResp->res);
1244                                     return;
1245                                 }
1246                             }
1247                         }
1248                         if (current == nullptr || supported == nullptr)
1249                         {
1250                             BMCWEB_LOG_ERROR
1251                                 << "GetPIDValues: thermal mode iface invalid "
1252                                 << path;
1253                             messages::internalError(self->asyncResp->res);
1254                             return;
1255                         }
1256                         self->currentProfile = *current;
1257                         self->supportedProfiles = *supported;
1258                     },
1259                     owner, path, "org.freedesktop.DBus.Properties", "GetAll",
1260                     thermalModeIface);
1261             },
1262             "xyz.openbmc_project.ObjectMapper",
1263             "/xyz/openbmc_project/object_mapper",
1264             "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", 0,
1265             std::array<const char*, 1>{thermalModeIface});
1266     }
1267 
1268     ~GetPIDValues()
1269     {
1270         if (asyncResp->res.result() != boost::beast::http::status::ok)
1271         {
1272             return;
1273         }
1274         // create map of <connection, path to objMgr>>
1275         boost::container::flat_map<std::string, std::string> objectMgrPaths;
1276         boost::container::flat_set<std::string> calledConnections;
1277         for (const auto& pathGroup : subtree)
1278         {
1279             for (const auto& connectionGroup : pathGroup.second)
1280             {
1281                 auto findConnection =
1282                     calledConnections.find(connectionGroup.first);
1283                 if (findConnection != calledConnections.end())
1284                 {
1285                     break;
1286                 }
1287                 for (const std::string& interface : connectionGroup.second)
1288                 {
1289                     if (interface == objectManagerIface)
1290                     {
1291                         objectMgrPaths[connectionGroup.first] = pathGroup.first;
1292                     }
1293                     // this list is alphabetical, so we
1294                     // should have found the objMgr by now
1295                     if (interface == pidConfigurationIface ||
1296                         interface == pidZoneConfigurationIface ||
1297                         interface == stepwiseConfigurationIface)
1298                     {
1299                         auto findObjMgr =
1300                             objectMgrPaths.find(connectionGroup.first);
1301                         if (findObjMgr == objectMgrPaths.end())
1302                         {
1303                             BMCWEB_LOG_DEBUG << connectionGroup.first
1304                                              << "Has no Object Manager";
1305                             continue;
1306                         }
1307 
1308                         calledConnections.insert(connectionGroup.first);
1309 
1310                         asyncPopulatePid(findObjMgr->first, findObjMgr->second,
1311                                          currentProfile, supportedProfiles,
1312                                          asyncResp);
1313                         break;
1314                     }
1315                 }
1316             }
1317         }
1318     }
1319 
1320     std::vector<std::string> supportedProfiles;
1321     std::string currentProfile;
1322     crow::openbmc_mapper::GetSubTreeType subtree;
1323     std::shared_ptr<bmcweb::AsyncResp> asyncResp;
1324 };
1325 
1326 struct SetPIDValues : std::enable_shared_from_this<SetPIDValues>
1327 {
1328 
1329     SetPIDValues(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
1330                  nlohmann::json& data) :
1331         asyncResp(asyncRespIn)
1332     {
1333 
1334         std::optional<nlohmann::json> pidControllers;
1335         std::optional<nlohmann::json> fanControllers;
1336         std::optional<nlohmann::json> fanZones;
1337         std::optional<nlohmann::json> stepwiseControllers;
1338 
1339         if (!redfish::json_util::readJson(
1340                 data, asyncResp->res, "PidControllers", pidControllers,
1341                 "FanControllers", fanControllers, "FanZones", fanZones,
1342                 "StepwiseControllers", stepwiseControllers, "Profile", profile))
1343         {
1344             BMCWEB_LOG_ERROR
1345                 << "Illegal Property "
1346                 << data.dump(2, ' ', true,
1347                              nlohmann::json::error_handler_t::replace);
1348             return;
1349         }
1350         configuration.emplace_back("PidControllers", std::move(pidControllers));
1351         configuration.emplace_back("FanControllers", std::move(fanControllers));
1352         configuration.emplace_back("FanZones", std::move(fanZones));
1353         configuration.emplace_back("StepwiseControllers",
1354                                    std::move(stepwiseControllers));
1355     }
1356     void run()
1357     {
1358         if (asyncResp->res.result() != boost::beast::http::status::ok)
1359         {
1360             return;
1361         }
1362 
1363         std::shared_ptr<SetPIDValues> self = shared_from_this();
1364 
1365         // todo(james): might make sense to do a mapper call here if this
1366         // interface gets more traction
1367         crow::connections::systemBus->async_method_call(
1368             [self](const boost::system::error_code ec,
1369                    const dbus::utility::ManagedObjectType& mObj) {
1370                 if (ec)
1371                 {
1372                     BMCWEB_LOG_ERROR << "Error communicating to Entity Manager";
1373                     messages::internalError(self->asyncResp->res);
1374                     return;
1375                 }
1376                 const std::array<const char*, 3> configurations = {
1377                     pidConfigurationIface, pidZoneConfigurationIface,
1378                     stepwiseConfigurationIface};
1379 
1380                 for (const auto& [path, object] : mObj)
1381                 {
1382                     for (const auto& [interface, _] : object)
1383                     {
1384                         if (std::find(configurations.begin(),
1385                                       configurations.end(),
1386                                       interface) != configurations.end())
1387                         {
1388                             self->objectCount++;
1389                             break;
1390                         }
1391                     }
1392                 }
1393                 self->managedObj = mObj;
1394             },
1395             "xyz.openbmc_project.EntityManager", "/", objectManagerIface,
1396             "GetManagedObjects");
1397 
1398         // at the same time get the profile information
1399         crow::connections::systemBus->async_method_call(
1400             [self](const boost::system::error_code ec,
1401                    const crow::openbmc_mapper::GetSubTreeType& subtree) {
1402                 if (ec || subtree.empty())
1403                 {
1404                     return;
1405                 }
1406                 if (subtree[0].second.empty())
1407                 {
1408                     // invalid mapper response, should never happen
1409                     BMCWEB_LOG_ERROR << "SetPIDValues: Mapper Error";
1410                     messages::internalError(self->asyncResp->res);
1411                     return;
1412                 }
1413 
1414                 const std::string& path = subtree[0].first;
1415                 const std::string& owner = subtree[0].second[0].first;
1416                 crow::connections::systemBus->async_method_call(
1417                     [self, path, owner](
1418                         const boost::system::error_code ec2,
1419                         const boost::container::flat_map<
1420                             std::string, dbus::utility::DbusVariantType>& r) {
1421                         if (ec2)
1422                         {
1423                             BMCWEB_LOG_ERROR
1424                                 << "SetPIDValues: Can't get thermalModeIface "
1425                                 << path;
1426                             messages::internalError(self->asyncResp->res);
1427                             return;
1428                         }
1429                         const std::string* current = nullptr;
1430                         const std::vector<std::string>* supported = nullptr;
1431                         for (auto& [key, value] : r)
1432                         {
1433                             if (key == "Current")
1434                             {
1435                                 current = std::get_if<std::string>(&value);
1436                                 if (current == nullptr)
1437                                 {
1438                                     BMCWEB_LOG_ERROR
1439                                         << "SetPIDValues: thermal mode iface invalid "
1440                                         << path;
1441                                     messages::internalError(
1442                                         self->asyncResp->res);
1443                                     return;
1444                                 }
1445                             }
1446                             if (key == "Supported")
1447                             {
1448                                 supported =
1449                                     std::get_if<std::vector<std::string>>(
1450                                         &value);
1451                                 if (supported == nullptr)
1452                                 {
1453                                     BMCWEB_LOG_ERROR
1454                                         << "SetPIDValues: thermal mode iface invalid"
1455                                         << path;
1456                                     messages::internalError(
1457                                         self->asyncResp->res);
1458                                     return;
1459                                 }
1460                             }
1461                         }
1462                         if (current == nullptr || supported == nullptr)
1463                         {
1464                             BMCWEB_LOG_ERROR
1465                                 << "SetPIDValues: thermal mode iface invalid "
1466                                 << path;
1467                             messages::internalError(self->asyncResp->res);
1468                             return;
1469                         }
1470                         self->currentProfile = *current;
1471                         self->supportedProfiles = *supported;
1472                         self->profileConnection = owner;
1473                         self->profilePath = path;
1474                     },
1475                     owner, path, "org.freedesktop.DBus.Properties", "GetAll",
1476                     thermalModeIface);
1477             },
1478             "xyz.openbmc_project.ObjectMapper",
1479             "/xyz/openbmc_project/object_mapper",
1480             "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", 0,
1481             std::array<const char*, 1>{thermalModeIface});
1482     }
1483     void pidSetDone()
1484     {
1485         if (asyncResp->res.result() != boost::beast::http::status::ok)
1486         {
1487             return;
1488         }
1489         std::shared_ptr<bmcweb::AsyncResp> response = asyncResp;
1490         if (profile)
1491         {
1492             if (std::find(supportedProfiles.begin(), supportedProfiles.end(),
1493                           *profile) == supportedProfiles.end())
1494             {
1495                 messages::actionParameterUnknown(response->res, "Profile",
1496                                                  *profile);
1497                 return;
1498             }
1499             currentProfile = *profile;
1500             crow::connections::systemBus->async_method_call(
1501                 [response](const boost::system::error_code ec) {
1502                     if (ec)
1503                     {
1504                         BMCWEB_LOG_ERROR << "Error patching profile" << ec;
1505                         messages::internalError(response->res);
1506                     }
1507                 },
1508                 profileConnection, profilePath,
1509                 "org.freedesktop.DBus.Properties", "Set", thermalModeIface,
1510                 "Current", dbus::utility::DbusVariantType(*profile));
1511         }
1512 
1513         for (auto& containerPair : configuration)
1514         {
1515             auto& container = containerPair.second;
1516             if (!container)
1517             {
1518                 continue;
1519             }
1520             BMCWEB_LOG_DEBUG << *container;
1521 
1522             std::string& type = containerPair.first;
1523 
1524             for (nlohmann::json::iterator it = container->begin();
1525                  it != container->end(); ++it)
1526             {
1527                 const auto& name = it.key();
1528                 BMCWEB_LOG_DEBUG << "looking for " << name;
1529 
1530                 auto pathItr =
1531                     std::find_if(managedObj.begin(), managedObj.end(),
1532                                  [&name](const auto& obj) {
1533                                      return boost::algorithm::ends_with(
1534                                          obj.first.str, "/" + name);
1535                                  });
1536                 boost::container::flat_map<std::string,
1537                                            dbus::utility::DbusVariantType>
1538                     output;
1539 
1540                 output.reserve(16); // The pid interface length
1541 
1542                 // determines if we're patching entity-manager or
1543                 // creating a new object
1544                 bool createNewObject = (pathItr == managedObj.end());
1545                 BMCWEB_LOG_DEBUG << "Found = " << !createNewObject;
1546 
1547                 std::string iface;
1548                 /*
1549                 if (type == "PidControllers" || type == "FanControllers")
1550                 {
1551                     iface = pidConfigurationIface;
1552                     if (!createNewObject &&
1553                         pathItr->second.find(pidConfigurationIface) ==
1554                             pathItr->second.end())
1555                     {
1556                         createNewObject = true;
1557                     }
1558                 }
1559                 else if (type == "FanZones")
1560                 {
1561                     iface = pidZoneConfigurationIface;
1562                     if (!createNewObject &&
1563                         pathItr->second.find(pidZoneConfigurationIface) ==
1564                             pathItr->second.end())
1565                     {
1566 
1567                         createNewObject = true;
1568                     }
1569                 }
1570                 else if (type == "StepwiseControllers")
1571                 {
1572                     iface = stepwiseConfigurationIface;
1573                     if (!createNewObject &&
1574                         pathItr->second.find(stepwiseConfigurationIface) ==
1575                             pathItr->second.end())
1576                     {
1577                         createNewObject = true;
1578                     }
1579                 }*/
1580 
1581                 if (createNewObject && it.value() == nullptr)
1582                 {
1583                     // can't delete a non-existent object
1584                     messages::invalidObject(response->res, name);
1585                     continue;
1586                 }
1587 
1588                 std::string path;
1589                 if (pathItr != managedObj.end())
1590                 {
1591                     path = pathItr->first.str;
1592                 }
1593 
1594                 BMCWEB_LOG_DEBUG << "Create new = " << createNewObject << "\n";
1595 
1596                 // arbitrary limit to avoid attacks
1597                 constexpr const size_t controllerLimit = 500;
1598                 if (createNewObject && objectCount >= controllerLimit)
1599                 {
1600                     messages::resourceExhaustion(response->res, type);
1601                     continue;
1602                 }
1603 
1604                 output["Name"] = boost::replace_all_copy(name, "_", " ");
1605 
1606                 std::string chassis;
1607                 CreatePIDRet ret = createPidInterface(
1608                     response, type, it, path, managedObj, createNewObject,
1609                     output, chassis, currentProfile);
1610                 if (ret == CreatePIDRet::fail)
1611                 {
1612                     return;
1613                 }
1614                 if (ret == CreatePIDRet::del)
1615                 {
1616                     continue;
1617                 }
1618 
1619                 if (!createNewObject)
1620                 {
1621                     for (const auto& property : output)
1622                     {
1623                         crow::connections::systemBus->async_method_call(
1624                             [response,
1625                              propertyName{std::string(property.first)}](
1626                                 const boost::system::error_code ec) {
1627                                 if (ec)
1628                                 {
1629                                     BMCWEB_LOG_ERROR << "Error patching "
1630                                                      << propertyName << ": "
1631                                                      << ec;
1632                                     messages::internalError(response->res);
1633                                     return;
1634                                 }
1635                                 messages::success(response->res);
1636                             },
1637                             "xyz.openbmc_project.EntityManager", path,
1638                             "org.freedesktop.DBus.Properties", "Set", iface,
1639                             property.first, property.second);
1640                     }
1641                 }
1642                 else
1643                 {
1644                     if (chassis.empty())
1645                     {
1646                         BMCWEB_LOG_ERROR << "Failed to get chassis from config";
1647                         messages::invalidObject(response->res, name);
1648                         return;
1649                     }
1650 
1651                     bool foundChassis = false;
1652                     for (const auto& obj : managedObj)
1653                     {
1654                         if (boost::algorithm::ends_with(obj.first.str, chassis))
1655                         {
1656                             chassis = obj.first.str;
1657                             foundChassis = true;
1658                             break;
1659                         }
1660                     }
1661                     if (!foundChassis)
1662                     {
1663                         BMCWEB_LOG_ERROR << "Failed to find chassis on dbus";
1664                         messages::resourceMissingAtURI(
1665                             response->res, "/redfish/v1/Chassis/" + chassis);
1666                         return;
1667                     }
1668 
1669                     crow::connections::systemBus->async_method_call(
1670                         [response](const boost::system::error_code ec) {
1671                             if (ec)
1672                             {
1673                                 BMCWEB_LOG_ERROR << "Error Adding Pid Object "
1674                                                  << ec;
1675                                 messages::internalError(response->res);
1676                                 return;
1677                             }
1678                             messages::success(response->res);
1679                         },
1680                         "xyz.openbmc_project.EntityManager", chassis,
1681                         "xyz.openbmc_project.AddObject", "AddObject", output);
1682                 }
1683             }
1684         }
1685     }
1686 
1687     ~SetPIDValues()
1688     {
1689         try
1690         {
1691             pidSetDone();
1692         }
1693         catch (...)
1694         {
1695             BMCWEB_LOG_CRITICAL << "pidSetDone threw exception";
1696         }
1697     }
1698 
1699     std::shared_ptr<bmcweb::AsyncResp> asyncResp;
1700     std::vector<std::pair<std::string, std::optional<nlohmann::json>>>
1701         configuration;
1702     std::optional<std::string> profile;
1703     dbus::utility::ManagedObjectType managedObj;
1704     std::vector<std::string> supportedProfiles;
1705     std::string currentProfile;
1706     std::string profileConnection;
1707     std::string profilePath;
1708     size_t objectCount = 0;
1709 };
1710 
1711 /**
1712  * @brief Retrieves BMC manager location data over DBus
1713  *
1714  * @param[in] aResp Shared pointer for completing asynchronous calls
1715  * @param[in] connectionName - service name
1716  * @param[in] path - object path
1717  * @return none
1718  */
1719 inline void getLocation(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
1720                         const std::string& connectionName,
1721                         const std::string& path)
1722 {
1723     BMCWEB_LOG_DEBUG << "Get BMC manager Location data.";
1724 
1725     sdbusplus::asio::getProperty<std::string>(
1726         *crow::connections::systemBus, connectionName, path,
1727         "xyz.openbmc_project.Inventory.Decorator.LocationCode", "LocationCode",
1728         [aResp](const boost::system::error_code ec,
1729                 const std::string& property) {
1730             if (ec)
1731             {
1732                 BMCWEB_LOG_DEBUG << "DBUS response error for "
1733                                     "Location";
1734                 messages::internalError(aResp->res);
1735                 return;
1736             }
1737 
1738             aResp->res.jsonValue["Location"]["PartLocation"]["ServiceLabel"] =
1739                 property;
1740         });
1741 }
1742 // avoid name collision systems.hpp
1743 inline void
1744     managerGetLastResetTime(const std::shared_ptr<bmcweb::AsyncResp>& aResp)
1745 {
1746     BMCWEB_LOG_DEBUG << "Getting Manager Last Reset Time";
1747 
1748     sdbusplus::asio::getProperty<uint64_t>(
1749         *crow::connections::systemBus, "xyz.openbmc_project.State.BMC",
1750         "/xyz/openbmc_project/state/bmc0", "xyz.openbmc_project.State.BMC",
1751         "LastRebootTime",
1752         [aResp](const boost::system::error_code ec,
1753                 const uint64_t lastResetTime) {
1754             if (ec)
1755             {
1756                 BMCWEB_LOG_DEBUG << "D-BUS response error " << ec;
1757                 return;
1758             }
1759 
1760             // LastRebootTime is epoch time, in milliseconds
1761             // https://github.com/openbmc/phosphor-dbus-interfaces/blob/7f9a128eb9296e926422ddc312c148b625890bb6/xyz/openbmc_project/State/BMC.interface.yaml#L19
1762             uint64_t lastResetTimeStamp = lastResetTime / 1000;
1763 
1764             // Convert to ISO 8601 standard
1765             aResp->res.jsonValue["LastResetTime"] =
1766                 crow::utility::getDateTimeUint(lastResetTimeStamp);
1767         });
1768 }
1769 
1770 /**
1771  * @brief Set the running firmware image
1772  *
1773  * @param[i,o] aResp - Async response object
1774  * @param[i] runningFirmwareTarget - Image to make the running image
1775  *
1776  * @return void
1777  */
1778 inline void
1779     setActiveFirmwareImage(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
1780                            const std::string& runningFirmwareTarget)
1781 {
1782     // Get the Id from /redfish/v1/UpdateService/FirmwareInventory/<Id>
1783     std::string::size_type idPos = runningFirmwareTarget.rfind('/');
1784     if (idPos == std::string::npos)
1785     {
1786         messages::propertyValueNotInList(aResp->res, runningFirmwareTarget,
1787                                          "@odata.id");
1788         BMCWEB_LOG_DEBUG << "Can't parse firmware ID!";
1789         return;
1790     }
1791     idPos++;
1792     if (idPos >= runningFirmwareTarget.size())
1793     {
1794         messages::propertyValueNotInList(aResp->res, runningFirmwareTarget,
1795                                          "@odata.id");
1796         BMCWEB_LOG_DEBUG << "Invalid firmware ID.";
1797         return;
1798     }
1799     std::string firmwareId = runningFirmwareTarget.substr(idPos);
1800 
1801     // Make sure the image is valid before setting priority
1802     crow::connections::systemBus->async_method_call(
1803         [aResp, firmwareId,
1804          runningFirmwareTarget](const boost::system::error_code ec,
1805                                 dbus::utility::ManagedObjectType& subtree) {
1806             if (ec)
1807             {
1808                 BMCWEB_LOG_DEBUG << "D-Bus response error getting objects.";
1809                 messages::internalError(aResp->res);
1810                 return;
1811             }
1812 
1813             if (subtree.size() == 0)
1814             {
1815                 BMCWEB_LOG_DEBUG << "Can't find image!";
1816                 messages::internalError(aResp->res);
1817                 return;
1818             }
1819 
1820             bool foundImage = false;
1821             for (auto& object : subtree)
1822             {
1823                 const std::string& path =
1824                     static_cast<const std::string&>(object.first);
1825                 std::size_t idPos2 = path.rfind('/');
1826 
1827                 if (idPos2 == std::string::npos)
1828                 {
1829                     continue;
1830                 }
1831 
1832                 idPos2++;
1833                 if (idPos2 >= path.size())
1834                 {
1835                     continue;
1836                 }
1837 
1838                 if (path.substr(idPos2) == firmwareId)
1839                 {
1840                     foundImage = true;
1841                     break;
1842                 }
1843             }
1844 
1845             if (!foundImage)
1846             {
1847                 messages::propertyValueNotInList(
1848                     aResp->res, runningFirmwareTarget, "@odata.id");
1849                 BMCWEB_LOG_DEBUG << "Invalid firmware ID.";
1850                 return;
1851             }
1852 
1853             BMCWEB_LOG_DEBUG
1854                 << "Setting firmware version " + firmwareId + " to priority 0.";
1855 
1856             // Only support Immediate
1857             // An addition could be a Redfish Setting like
1858             // ActiveSoftwareImageApplyTime and support OnReset
1859             crow::connections::systemBus->async_method_call(
1860                 [aResp](const boost::system::error_code ec) {
1861                     if (ec)
1862                     {
1863                         BMCWEB_LOG_DEBUG << "D-Bus response error setting.";
1864                         messages::internalError(aResp->res);
1865                         return;
1866                     }
1867                     doBMCGracefulRestart(aResp);
1868                 },
1869 
1870                 "xyz.openbmc_project.Software.BMC.Updater",
1871                 "/xyz/openbmc_project/software/" + firmwareId,
1872                 "org.freedesktop.DBus.Properties", "Set",
1873                 "xyz.openbmc_project.Software.RedundancyPriority", "Priority",
1874                 dbus::utility::DbusVariantType(static_cast<uint8_t>(0)));
1875         },
1876         "xyz.openbmc_project.Software.BMC.Updater",
1877         "/xyz/openbmc_project/software", "org.freedesktop.DBus.ObjectManager",
1878         "GetManagedObjects");
1879 }
1880 
1881 inline void setDateTime(std::shared_ptr<bmcweb::AsyncResp> aResp,
1882                         std::string datetime)
1883 {
1884     BMCWEB_LOG_DEBUG << "Set date time: " << datetime;
1885 
1886     std::stringstream stream(datetime);
1887     // Convert from ISO 8601 to boost local_time
1888     // (BMC only has time in UTC)
1889     boost::posix_time::ptime posixTime;
1890     boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
1891     // Facet gets deleted with the stringsteam
1892     auto ifc = std::make_unique<boost::local_time::local_time_input_facet>(
1893         "%Y-%m-%d %H:%M:%S%F %ZP");
1894     stream.imbue(std::locale(stream.getloc(), ifc.release()));
1895 
1896     boost::local_time::local_date_time ldt(boost::local_time::not_a_date_time);
1897 
1898     if (stream >> ldt)
1899     {
1900         posixTime = ldt.utc_time();
1901         boost::posix_time::time_duration dur = posixTime - epoch;
1902         uint64_t durMicroSecs = static_cast<uint64_t>(dur.total_microseconds());
1903         crow::connections::systemBus->async_method_call(
1904             [aResp{std::move(aResp)}, datetime{std::move(datetime)}](
1905                 const boost::system::error_code ec) {
1906                 if (ec)
1907                 {
1908                     BMCWEB_LOG_DEBUG << "Failed to set elapsed time. "
1909                                         "DBUS response error "
1910                                      << ec;
1911                     messages::internalError(aResp->res);
1912                     return;
1913                 }
1914                 aResp->res.jsonValue["DateTime"] = datetime;
1915             },
1916             "xyz.openbmc_project.Time.Manager", "/xyz/openbmc_project/time/bmc",
1917             "org.freedesktop.DBus.Properties", "Set",
1918             "xyz.openbmc_project.Time.EpochTime", "Elapsed",
1919             dbus::utility::DbusVariantType(durMicroSecs));
1920     }
1921     else
1922     {
1923         messages::propertyValueFormatError(aResp->res, datetime, "DateTime");
1924         return;
1925     }
1926 }
1927 
1928 inline void requestRoutesManager(App& app)
1929 {
1930     std::string uuid = persistent_data::getConfig().systemUuid;
1931 
1932     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/")
1933         .privileges(redfish::privileges::getManager)
1934         .methods(boost::beast::http::verb::get)([uuid](const crow::Request&,
1935                                                        const std::shared_ptr<
1936                                                            bmcweb::AsyncResp>&
1937                                                            asyncResp) {
1938             asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/Managers/bmc";
1939             asyncResp->res.jsonValue["@odata.type"] =
1940                 "#Manager.v1_11_0.Manager";
1941             asyncResp->res.jsonValue["Id"] = "bmc";
1942             asyncResp->res.jsonValue["Name"] = "OpenBmc Manager";
1943             asyncResp->res.jsonValue["Description"] =
1944                 "Baseboard Management Controller";
1945             asyncResp->res.jsonValue["PowerState"] = "On";
1946             asyncResp->res.jsonValue["Status"] = {{"State", "Enabled"},
1947                                                   {"Health", "OK"}};
1948             asyncResp->res.jsonValue["ManagerType"] = "BMC";
1949             asyncResp->res.jsonValue["UUID"] = systemd_utils::getUuid();
1950             asyncResp->res.jsonValue["ServiceEntryPointUUID"] = uuid;
1951             asyncResp->res.jsonValue["Model"] =
1952                 "OpenBmc"; // TODO(ed), get model
1953 
1954             asyncResp->res.jsonValue["LogServices"] = {
1955                 {"@odata.id", "/redfish/v1/Managers/bmc/LogServices"}};
1956 
1957             asyncResp->res.jsonValue["NetworkProtocol"] = {
1958                 {"@odata.id", "/redfish/v1/Managers/bmc/NetworkProtocol"}};
1959 
1960             asyncResp->res.jsonValue["EthernetInterfaces"] = {
1961                 {"@odata.id", "/redfish/v1/Managers/bmc/EthernetInterfaces"}};
1962 
1963 #ifdef BMCWEB_ENABLE_VM_NBDPROXY
1964             asyncResp->res.jsonValue["VirtualMedia"] = {
1965                 {"@odata.id", "/redfish/v1/Managers/bmc/VirtualMedia"}};
1966 #endif // BMCWEB_ENABLE_VM_NBDPROXY
1967 
1968             // default oem data
1969             nlohmann::json& oem = asyncResp->res.jsonValue["Oem"];
1970             nlohmann::json& oemOpenbmc = oem["OpenBmc"];
1971             oem["@odata.type"] = "#OemManager.Oem";
1972             oem["@odata.id"] = "/redfish/v1/Managers/bmc#/Oem";
1973             oemOpenbmc["@odata.type"] = "#OemManager.OpenBmc";
1974             oemOpenbmc["@odata.id"] = "/redfish/v1/Managers/bmc#/Oem/OpenBmc";
1975             oemOpenbmc["Certificates"] = {
1976                 {"@odata.id",
1977                  "/redfish/v1/Managers/bmc/Truststore/Certificates"}};
1978 
1979             // Manager.Reset (an action) can be many values, OpenBMC only
1980             // supports BMC reboot.
1981             nlohmann::json& managerReset =
1982                 asyncResp->res.jsonValue["Actions"]["#Manager.Reset"];
1983             managerReset["target"] =
1984                 "/redfish/v1/Managers/bmc/Actions/Manager.Reset";
1985             managerReset["@Redfish.ActionInfo"] =
1986                 "/redfish/v1/Managers/bmc/ResetActionInfo";
1987 
1988             // ResetToDefaults (Factory Reset) has values like
1989             // PreserveNetworkAndUsers and PreserveNetwork that aren't supported
1990             // on OpenBMC
1991             nlohmann::json& resetToDefaults =
1992                 asyncResp->res.jsonValue["Actions"]["#Manager.ResetToDefaults"];
1993             resetToDefaults["target"] =
1994                 "/redfish/v1/Managers/bmc/Actions/Manager.ResetToDefaults";
1995             resetToDefaults["ResetType@Redfish.AllowableValues"] = {"ResetAll"};
1996 
1997             std::pair<std::string, std::string> redfishDateTimeOffset =
1998                 crow::utility::getDateTimeOffsetNow();
1999 
2000             asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
2001             asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2002                 redfishDateTimeOffset.second;
2003 
2004             // TODO (Gunnar): Remove these one day since moved to ComputerSystem
2005             // Still used by OCP profiles
2006             // https://github.com/opencomputeproject/OCP-Profiles/issues/23
2007             // Fill in SerialConsole info
2008             asyncResp->res.jsonValue["SerialConsole"]["ServiceEnabled"] = true;
2009             asyncResp->res.jsonValue["SerialConsole"]["MaxConcurrentSessions"] =
2010                 15;
2011             asyncResp->res.jsonValue["SerialConsole"]["ConnectTypesSupported"] =
2012                 {"IPMI", "SSH"};
2013 #ifdef BMCWEB_ENABLE_KVM
2014             // Fill in GraphicalConsole info
2015             asyncResp->res.jsonValue["GraphicalConsole"]["ServiceEnabled"] =
2016                 true;
2017             asyncResp->res
2018                 .jsonValue["GraphicalConsole"]["MaxConcurrentSessions"] = 4;
2019             asyncResp->res.jsonValue["GraphicalConsole"]
2020                                     ["ConnectTypesSupported"] = {"KVMIP"};
2021 #endif // BMCWEB_ENABLE_KVM
2022 
2023             asyncResp->res.jsonValue["Links"]["ManagerForServers@odata.count"] =
2024                 1;
2025             asyncResp->res.jsonValue["Links"]["ManagerForServers"] = {
2026                 {{"@odata.id", "/redfish/v1/Systems/system"}}};
2027 
2028             auto health = std::make_shared<HealthPopulate>(asyncResp);
2029             health->isManagersHealth = true;
2030             health->populate();
2031 
2032             fw_util::populateFirmwareInformation(asyncResp, fw_util::bmcPurpose,
2033                                                  "FirmwareVersion", true);
2034 
2035             managerGetLastResetTime(asyncResp);
2036 
2037             auto pids = std::make_shared<GetPIDValues>(asyncResp);
2038             pids->run();
2039 
2040             getMainChassisId(
2041                 asyncResp, [](const std::string& chassisId,
2042                               const std::shared_ptr<bmcweb::AsyncResp>& aRsp) {
2043                     aRsp->res
2044                         .jsonValue["Links"]["ManagerForChassis@odata.count"] =
2045                         1;
2046                     aRsp->res.jsonValue["Links"]["ManagerForChassis"] = {
2047                         {{"@odata.id", "/redfish/v1/Chassis/" + chassisId}}};
2048                     aRsp->res.jsonValue["Links"]["ManagerInChassis"] = {
2049                         {"@odata.id", "/redfish/v1/Chassis/" + chassisId}};
2050                 });
2051 
2052             static bool started = false;
2053 
2054             if (!started)
2055             {
2056                 sdbusplus::asio::getProperty<double>(
2057                     *crow::connections::systemBus, "org.freedesktop.systemd1",
2058                     "/org/freedesktop/systemd1",
2059                     "org.freedesktop.systemd1.Manager", "Progress",
2060                     [asyncResp](const boost::system::error_code ec,
2061                                 const double& val) {
2062                         if (ec)
2063                         {
2064                             BMCWEB_LOG_ERROR << "Error while getting progress";
2065                             messages::internalError(asyncResp->res);
2066                             return;
2067                         }
2068                         if (val < 1.0)
2069                         {
2070                             asyncResp->res.jsonValue["Status"]["State"] =
2071                                 "Starting";
2072                             started = true;
2073                         }
2074                     });
2075             }
2076 
2077             crow::connections::systemBus->async_method_call(
2078                 [asyncResp](
2079                     const boost::system::error_code ec,
2080                     const std::vector<
2081                         std::pair<std::string,
2082                                   std::vector<std::pair<
2083                                       std::string, std::vector<std::string>>>>>&
2084                         subtree) {
2085                     if (ec)
2086                     {
2087                         BMCWEB_LOG_DEBUG
2088                             << "D-Bus response error on GetSubTree " << ec;
2089                         return;
2090                     }
2091                     if (subtree.size() == 0)
2092                     {
2093                         BMCWEB_LOG_DEBUG << "Can't find bmc D-Bus object!";
2094                         return;
2095                     }
2096                     // Assume only 1 bmc D-Bus object
2097                     // Throw an error if there is more than 1
2098                     if (subtree.size() > 1)
2099                     {
2100                         BMCWEB_LOG_DEBUG
2101                             << "Found more than 1 bmc D-Bus object!";
2102                         messages::internalError(asyncResp->res);
2103                         return;
2104                     }
2105 
2106                     if (subtree[0].first.empty() ||
2107                         subtree[0].second.size() != 1)
2108                     {
2109                         BMCWEB_LOG_DEBUG << "Error getting bmc D-Bus object!";
2110                         messages::internalError(asyncResp->res);
2111                         return;
2112                     }
2113 
2114                     const std::string& path = subtree[0].first;
2115                     const std::string& connectionName =
2116                         subtree[0].second[0].first;
2117 
2118                     for (const auto& interfaceName :
2119                          subtree[0].second[0].second)
2120                     {
2121                         if (interfaceName ==
2122                             "xyz.openbmc_project.Inventory.Decorator.Asset")
2123                         {
2124                             crow::connections::systemBus->async_method_call(
2125                                 [asyncResp](
2126                                     const boost::system::error_code ec,
2127                                     const std::vector<std::pair<
2128                                         std::string,
2129                                         dbus::utility::DbusVariantType>>&
2130                                         propertiesList) {
2131                                     if (ec)
2132                                     {
2133                                         BMCWEB_LOG_DEBUG
2134                                             << "Can't get bmc asset!";
2135                                         return;
2136                                     }
2137                                     for (const std::pair<
2138                                              std::string,
2139                                              dbus::utility::DbusVariantType>&
2140                                              property : propertiesList)
2141                                     {
2142                                         const std::string& propertyName =
2143                                             property.first;
2144 
2145                                         if ((propertyName == "PartNumber") ||
2146                                             (propertyName == "SerialNumber") ||
2147                                             (propertyName == "Manufacturer") ||
2148                                             (propertyName == "Model") ||
2149                                             (propertyName == "SparePartNumber"))
2150                                         {
2151                                             const std::string* value =
2152                                                 std::get_if<std::string>(
2153                                                     &property.second);
2154                                             if (value == nullptr)
2155                                             {
2156                                                 // illegal property
2157                                                 messages::internalError(
2158                                                     asyncResp->res);
2159                                                 return;
2160                                             }
2161                                             asyncResp->res
2162                                                 .jsonValue[propertyName] =
2163                                                 *value;
2164                                         }
2165                                     }
2166                                 },
2167                                 connectionName, path,
2168                                 "org.freedesktop.DBus.Properties", "GetAll",
2169                                 "xyz.openbmc_project.Inventory.Decorator.Asset");
2170                         }
2171                         else if (
2172                             interfaceName ==
2173                             "xyz.openbmc_project.Inventory.Decorator.LocationCode")
2174                         {
2175                             getLocation(asyncResp, connectionName, path);
2176                         }
2177                     }
2178                 },
2179                 "xyz.openbmc_project.ObjectMapper",
2180                 "/xyz/openbmc_project/object_mapper",
2181                 "xyz.openbmc_project.ObjectMapper", "GetSubTree",
2182                 "/xyz/openbmc_project/inventory", int32_t(0),
2183                 std::array<const char*, 1>{
2184                     "xyz.openbmc_project.Inventory.Item.Bmc"});
2185         });
2186 
2187     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/")
2188         .privileges(redfish::privileges::patchManager)
2189         .methods(
2190             boost::beast::http::verb::
2191                 patch)([](const crow::Request& req,
2192                           const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2193             std::optional<nlohmann::json> oem;
2194             std::optional<nlohmann::json> links;
2195             std::optional<std::string> datetime;
2196 
2197             if (!json_util::readJson(req, asyncResp->res, "Oem", oem,
2198                                      "DateTime", datetime, "Links", links))
2199             {
2200                 return;
2201             }
2202 
2203             if (oem)
2204             {
2205                 std::optional<nlohmann::json> openbmc;
2206                 if (!redfish::json_util::readJson(*oem, asyncResp->res,
2207                                                   "OpenBmc", openbmc))
2208                 {
2209                     BMCWEB_LOG_ERROR
2210                         << "Illegal Property "
2211                         << oem->dump(2, ' ', true,
2212                                      nlohmann::json::error_handler_t::replace);
2213                     return;
2214                 }
2215                 if (openbmc)
2216                 {
2217                     std::optional<nlohmann::json> fan;
2218                     if (!redfish::json_util::readJson(*openbmc, asyncResp->res,
2219                                                       "Fan", fan))
2220                     {
2221                         BMCWEB_LOG_ERROR
2222                             << "Illegal Property "
2223                             << openbmc->dump(
2224                                    2, ' ', true,
2225                                    nlohmann::json::error_handler_t::replace);
2226                         return;
2227                     }
2228                     if (fan)
2229                     {
2230                         auto pid =
2231                             std::make_shared<SetPIDValues>(asyncResp, *fan);
2232                         pid->run();
2233                     }
2234                 }
2235             }
2236             if (links)
2237             {
2238                 std::optional<nlohmann::json> activeSoftwareImage;
2239                 if (!redfish::json_util::readJson(*links, asyncResp->res,
2240                                                   "ActiveSoftwareImage",
2241                                                   activeSoftwareImage))
2242                 {
2243                     return;
2244                 }
2245                 if (activeSoftwareImage)
2246                 {
2247                     std::optional<std::string> odataId;
2248                     if (!json_util::readJson(*activeSoftwareImage,
2249                                              asyncResp->res, "@odata.id",
2250                                              odataId))
2251                     {
2252                         return;
2253                     }
2254 
2255                     if (odataId)
2256                     {
2257                         setActiveFirmwareImage(asyncResp, *odataId);
2258                     }
2259                 }
2260             }
2261             if (datetime)
2262             {
2263                 setDateTime(asyncResp, std::move(*datetime));
2264             }
2265         });
2266 }
2267 
2268 inline void requestRoutesManagerCollection(App& app)
2269 {
2270     BMCWEB_ROUTE(app, "/redfish/v1/Managers/")
2271         .privileges(redfish::privileges::getManagerCollection)
2272         .methods(boost::beast::http::verb::get)(
2273             [](const crow::Request&,
2274                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2275                 // Collections don't include the static data added by SubRoute
2276                 // because it has a duplicate entry for members
2277                 asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/Managers";
2278                 asyncResp->res.jsonValue["@odata.type"] =
2279                     "#ManagerCollection.ManagerCollection";
2280                 asyncResp->res.jsonValue["Name"] = "Manager Collection";
2281                 asyncResp->res.jsonValue["Members@odata.count"] = 1;
2282                 asyncResp->res.jsonValue["Members"] = {
2283                     {{"@odata.id", "/redfish/v1/Managers/bmc"}}};
2284             });
2285 }
2286 } // namespace redfish
2287