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