1 #pragma once
2 
3 #include "app.hpp"
4 #include "dbus_singleton.hpp"
5 #include "dbus_utility.hpp"
6 #include "error_messages.hpp"
7 #include "ethernet.hpp"
8 #include "query.hpp"
9 #include "registries/privilege_registry.hpp"
10 #include "utils/ip_utils.hpp"
11 #include "utils/json_utils.hpp"
12 
13 #include <boost/container/flat_set.hpp>
14 #include <sdbusplus/asio/property.hpp>
15 
16 #include <array>
17 #include <optional>
18 #include <string_view>
19 #include <utility>
20 
21 // TODO(ed) requestRoutesHypervisorSystems seems to have copy-pasted a
22 // lot of code, and has a number of methods that have name conflicts with the
23 // normal ethernet internfaces in ethernet.hpp.  For the moment, we'll put
24 // hypervisor in a namespace to isolate it, but these methods eventually need
25 // deduplicated
26 namespace redfish::hypervisor
27 {
28 
29 /**
30  * @brief Retrieves hypervisor state properties over dbus
31  *
32  * The hypervisor state object is optional so this function will only set the
33  * state variables if the object is found
34  *
35  * @param[in] aResp     Shared pointer for completing asynchronous calls.
36  *
37  * @return None.
38  */
39 inline void getHypervisorState(const std::shared_ptr<bmcweb::AsyncResp>& aResp)
40 {
41     BMCWEB_LOG_DEBUG << "Get hypervisor state information.";
42     sdbusplus::asio::getProperty<std::string>(
43         *crow::connections::systemBus, "xyz.openbmc_project.State.Hypervisor",
44         "/xyz/openbmc_project/state/hypervisor0",
45         "xyz.openbmc_project.State.Host", "CurrentHostState",
46         [aResp](const boost::system::error_code ec,
47                 const std::string& hostState) {
48         if (ec)
49         {
50             BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
51             // This is an optional D-Bus object so just return if
52             // error occurs
53             return;
54         }
55 
56         BMCWEB_LOG_DEBUG << "Hypervisor state: " << hostState;
57         // Verify Host State
58         if (hostState == "xyz.openbmc_project.State.Host.HostState.Running")
59         {
60             aResp->res.jsonValue["PowerState"] = "On";
61             aResp->res.jsonValue["Status"]["State"] = "Enabled";
62         }
63         else if (hostState == "xyz.openbmc_project.State.Host.HostState."
64                               "Quiesced")
65         {
66             aResp->res.jsonValue["PowerState"] = "On";
67             aResp->res.jsonValue["Status"]["State"] = "Quiesced";
68         }
69         else if (hostState == "xyz.openbmc_project.State.Host.HostState."
70                               "Standby")
71         {
72             aResp->res.jsonValue["PowerState"] = "On";
73             aResp->res.jsonValue["Status"]["State"] = "StandbyOffline";
74         }
75         else if (hostState == "xyz.openbmc_project.State.Host.HostState."
76                               "TransitioningToRunning")
77         {
78             aResp->res.jsonValue["PowerState"] = "PoweringOn";
79             aResp->res.jsonValue["Status"]["State"] = "Starting";
80         }
81         else if (hostState == "xyz.openbmc_project.State.Host.HostState."
82                               "TransitioningToOff")
83         {
84             aResp->res.jsonValue["PowerState"] = "PoweringOff";
85             aResp->res.jsonValue["Status"]["State"] = "Enabled";
86         }
87         else if (hostState == "xyz.openbmc_project.State.Host.HostState.Off")
88         {
89             aResp->res.jsonValue["PowerState"] = "Off";
90             aResp->res.jsonValue["Status"]["State"] = "Disabled";
91         }
92         else
93         {
94             messages::internalError(aResp->res);
95             return;
96         }
97         });
98 }
99 
100 /**
101  * @brief Populate Actions if any are valid for hypervisor object
102  *
103  * The hypervisor state object is optional so this function will only set the
104  * Action if the object is found
105  *
106  * @param[in] aResp     Shared pointer for completing asynchronous calls.
107  *
108  * @return None.
109  */
110 inline void
111     getHypervisorActions(const std::shared_ptr<bmcweb::AsyncResp>& aResp)
112 {
113     BMCWEB_LOG_DEBUG << "Get hypervisor actions.";
114     constexpr std::array<std::string_view, 1> interfaces = {
115         "xyz.openbmc_project.State.Host"};
116     dbus::utility::getDbusObject(
117         "/xyz/openbmc_project/state/hypervisor0", interfaces,
118         [aResp](
119             const boost::system::error_code& ec,
120             const std::vector<std::pair<std::string, std::vector<std::string>>>&
121                 objInfo) {
122         if (ec)
123         {
124             BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
125             // This is an optional D-Bus object so just return if
126             // error occurs
127             return;
128         }
129 
130         if (objInfo.empty())
131         {
132             // As noted above, this is an optional interface so just return
133             // if there is no instance found
134             return;
135         }
136 
137         if (objInfo.size() > 1)
138         {
139             // More then one hypervisor object is not supported and is an
140             // error
141             messages::internalError(aResp->res);
142             return;
143         }
144 
145         // Object present so system support limited ComputerSystem Action
146         nlohmann::json& reset =
147             aResp->res.jsonValue["Actions"]["#ComputerSystem.Reset"];
148         reset["target"] =
149             "/redfish/v1/Systems/hypervisor/Actions/ComputerSystem.Reset";
150         reset["@Redfish.ActionInfo"] =
151             "/redfish/v1/Systems/hypervisor/ResetActionInfo";
152         });
153 }
154 
155 inline bool extractHypervisorInterfaceData(
156     const std::string& ethIfaceId,
157     const dbus::utility::ManagedObjectType& dbusData,
158     EthernetInterfaceData& ethData,
159     boost::container::flat_set<IPv4AddressData>& ipv4Config)
160 {
161     bool idFound = false;
162     for (const auto& objpath : dbusData)
163     {
164         for (const auto& ifacePair : objpath.second)
165         {
166             if (objpath.first ==
167                 "/xyz/openbmc_project/network/hypervisor/" + ethIfaceId)
168             {
169                 idFound = true;
170                 if (ifacePair.first == "xyz.openbmc_project.Network.MACAddress")
171                 {
172                     for (const auto& propertyPair : ifacePair.second)
173                     {
174                         if (propertyPair.first == "MACAddress")
175                         {
176                             const std::string* mac =
177                                 std::get_if<std::string>(&propertyPair.second);
178                             if (mac != nullptr)
179                             {
180                                 ethData.macAddress = *mac;
181                             }
182                         }
183                     }
184                 }
185                 else if (ifacePair.first ==
186                          "xyz.openbmc_project.Network.EthernetInterface")
187                 {
188                     for (const auto& propertyPair : ifacePair.second)
189                     {
190                         if (propertyPair.first == "DHCPEnabled")
191                         {
192                             const std::string* dhcp =
193                                 std::get_if<std::string>(&propertyPair.second);
194                             if (dhcp != nullptr)
195                             {
196                                 ethData.dhcpEnabled = *dhcp;
197                                 break; // Interested on only "DHCPEnabled".
198                                        // Stop parsing since we got the
199                                        // "DHCPEnabled" value.
200                             }
201                         }
202                     }
203                 }
204             }
205             if (objpath.first == "/xyz/openbmc_project/network/hypervisor/" +
206                                      ethIfaceId + "/ipv4/addr0")
207             {
208                 std::pair<boost::container::flat_set<IPv4AddressData>::iterator,
209                           bool>
210                     it = ipv4Config.insert(IPv4AddressData{});
211                 IPv4AddressData& ipv4Address = *it.first;
212                 if (ifacePair.first == "xyz.openbmc_project.Object.Enable")
213                 {
214                     for (const auto& property : ifacePair.second)
215                     {
216                         if (property.first == "Enabled")
217                         {
218                             const bool* intfEnable =
219                                 std::get_if<bool>(&property.second);
220                             if (intfEnable != nullptr)
221                             {
222                                 ipv4Address.isActive = *intfEnable;
223                                 break;
224                             }
225                         }
226                     }
227                 }
228                 if (ifacePair.first == "xyz.openbmc_project.Network.IP")
229                 {
230                     for (const auto& property : ifacePair.second)
231                     {
232                         if (property.first == "Address")
233                         {
234                             const std::string* address =
235                                 std::get_if<std::string>(&property.second);
236                             if (address != nullptr)
237                             {
238                                 ipv4Address.address = *address;
239                             }
240                         }
241                         else if (property.first == "Origin")
242                         {
243                             const std::string* origin =
244                                 std::get_if<std::string>(&property.second);
245                             if (origin != nullptr)
246                             {
247                                 ipv4Address.origin =
248                                     translateAddressOriginDbusToRedfish(*origin,
249                                                                         true);
250                             }
251                         }
252                         else if (property.first == "PrefixLength")
253                         {
254                             const uint8_t* mask =
255                                 std::get_if<uint8_t>(&property.second);
256                             if (mask != nullptr)
257                             {
258                                 // convert it to the string
259                                 ipv4Address.netmask = getNetmask(*mask);
260                             }
261                         }
262                         else if (property.first == "Type" ||
263                                  property.first == "Gateway")
264                         {
265                             // Type & Gateway is not used
266                             continue;
267                         }
268                         else
269                         {
270                             BMCWEB_LOG_ERROR
271                                 << "Got extra property: " << property.first
272                                 << " on the " << objpath.first.str << " object";
273                         }
274                     }
275                 }
276             }
277             if (objpath.first == "/xyz/openbmc_project/network/hypervisor")
278             {
279                 // System configuration shows up in the global namespace, so no
280                 // need to check eth number
281                 if (ifacePair.first ==
282                     "xyz.openbmc_project.Network.SystemConfiguration")
283                 {
284                     for (const auto& propertyPair : ifacePair.second)
285                     {
286                         if (propertyPair.first == "HostName")
287                         {
288                             const std::string* hostName =
289                                 std::get_if<std::string>(&propertyPair.second);
290                             if (hostName != nullptr)
291                             {
292                                 ethData.hostName = *hostName;
293                             }
294                         }
295                         else if (propertyPair.first == "DefaultGateway")
296                         {
297                             const std::string* defaultGateway =
298                                 std::get_if<std::string>(&propertyPair.second);
299                             if (defaultGateway != nullptr)
300                             {
301                                 ethData.defaultGateway = *defaultGateway;
302                             }
303                         }
304                     }
305                 }
306             }
307         }
308     }
309     return idFound;
310 }
311 /**
312  * Function that retrieves all properties for given Hypervisor Ethernet
313  * Interface Object from Settings Manager
314  * @param ethIfaceId Hypervisor ethernet interface id to query on DBus
315  * @param callback a function that shall be called to convert Dbus output
316  * into JSON
317  */
318 template <typename CallbackFunc>
319 void getHypervisorIfaceData(const std::string& ethIfaceId,
320                             CallbackFunc&& callback)
321 {
322     crow::connections::systemBus->async_method_call(
323         [ethIfaceId{std::string{ethIfaceId}},
324          callback{std::forward<CallbackFunc>(callback)}](
325             const boost::system::error_code error,
326             const dbus::utility::ManagedObjectType& resp) {
327         EthernetInterfaceData ethData{};
328         boost::container::flat_set<IPv4AddressData> ipv4Data;
329         if (error)
330         {
331             callback(false, ethData, ipv4Data);
332             return;
333         }
334 
335         bool found =
336             extractHypervisorInterfaceData(ethIfaceId, resp, ethData, ipv4Data);
337         if (!found)
338         {
339             BMCWEB_LOG_INFO << "Hypervisor Interface not found";
340         }
341         callback(found, ethData, ipv4Data);
342         },
343         "xyz.openbmc_project.Settings", "/",
344         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
345 }
346 
347 /**
348  * @brief Sets the Hypervisor Interface IPAddress DBUS
349  *
350  * @param[in] aResp          Shared pointer for generating response message.
351  * @param[in] ipv4Address    Address from the incoming request
352  * @param[in] ethIfaceId     Hypervisor Interface Id
353  *
354  * @return None.
355  */
356 inline void
357     setHypervisorIPv4Address(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
358                              const std::string& ethIfaceId,
359                              const std::string& ipv4Address)
360 {
361     BMCWEB_LOG_DEBUG << "Setting the Hypervisor IPaddress : " << ipv4Address
362                      << " on Iface: " << ethIfaceId;
363     crow::connections::systemBus->async_method_call(
364         [aResp](const boost::system::error_code ec) {
365         if (ec)
366         {
367             BMCWEB_LOG_ERROR << "DBUS response error " << ec;
368             return;
369         }
370         BMCWEB_LOG_DEBUG << "Hypervisor IPaddress is Set";
371         },
372         "xyz.openbmc_project.Settings",
373         "/xyz/openbmc_project/network/hypervisor/" + ethIfaceId + "/ipv4/addr0",
374         "org.freedesktop.DBus.Properties", "Set",
375         "xyz.openbmc_project.Network.IP", "Address",
376         dbus::utility::DbusVariantType(ipv4Address));
377 }
378 
379 /**
380  * @brief Sets the Hypervisor Interface SubnetMask DBUS
381  *
382  * @param[in] aResp     Shared pointer for generating response message.
383  * @param[in] subnet    SubnetMask from the incoming request
384  * @param[in] ethIfaceId Hypervisor Interface Id
385  *
386  * @return None.
387  */
388 inline void
389     setHypervisorIPv4Subnet(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
390                             const std::string& ethIfaceId, const uint8_t subnet)
391 {
392     BMCWEB_LOG_DEBUG << "Setting the Hypervisor subnet : " << subnet
393                      << " on Iface: " << ethIfaceId;
394 
395     crow::connections::systemBus->async_method_call(
396         [aResp](const boost::system::error_code ec) {
397         if (ec)
398         {
399             BMCWEB_LOG_ERROR << "DBUS response error " << ec;
400             return;
401         }
402         BMCWEB_LOG_DEBUG << "SubnetMask is Set";
403         },
404         "xyz.openbmc_project.Settings",
405         "/xyz/openbmc_project/network/hypervisor/" + ethIfaceId + "/ipv4/addr0",
406         "org.freedesktop.DBus.Properties", "Set",
407         "xyz.openbmc_project.Network.IP", "PrefixLength",
408         dbus::utility::DbusVariantType(subnet));
409 }
410 
411 /**
412  * @brief Sets the Hypervisor Interface Gateway DBUS
413  *
414  * @param[in] aResp          Shared pointer for generating response message.
415  * @param[in] gateway        Gateway from the incoming request
416  * @param[in] ethIfaceId     Hypervisor Interface Id
417  *
418  * @return None.
419  */
420 inline void
421     setHypervisorIPv4Gateway(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
422                              const std::string& gateway)
423 {
424     BMCWEB_LOG_DEBUG
425         << "Setting the DefaultGateway to the last configured gateway";
426 
427     crow::connections::systemBus->async_method_call(
428         [aResp](const boost::system::error_code ec) {
429         if (ec)
430         {
431             BMCWEB_LOG_ERROR << "DBUS response error " << ec;
432             return;
433         }
434         BMCWEB_LOG_DEBUG << "Default Gateway is Set";
435         },
436         "xyz.openbmc_project.Settings",
437         "/xyz/openbmc_project/network/hypervisor",
438         "org.freedesktop.DBus.Properties", "Set",
439         "xyz.openbmc_project.Network.SystemConfiguration", "DefaultGateway",
440         dbus::utility::DbusVariantType(gateway));
441 }
442 
443 /**
444  * @brief Creates a static IPv4 entry
445  *
446  * @param[in] ifaceId      Id of interface upon which to create the IPv4 entry
447  * @param[in] prefixLength IPv4 prefix syntax for the subnet mask
448  * @param[in] gateway      IPv4 address of this interfaces gateway
449  * @param[in] address      IPv4 address to assign to this interface
450  * @param[io] asyncResp    Response object that will be returned to client
451  *
452  * @return None
453  */
454 inline void
455     createHypervisorIPv4(const std::string& ifaceId, uint8_t prefixLength,
456                          const std::string& gateway, const std::string& address,
457                          const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
458 {
459     setHypervisorIPv4Address(asyncResp, ifaceId, address);
460     setHypervisorIPv4Gateway(asyncResp, gateway);
461     setHypervisorIPv4Subnet(asyncResp, ifaceId, prefixLength);
462 }
463 
464 /**
465  * @brief Deletes given IPv4 interface
466  *
467  * @param[in] ifaceId     Id of interface whose IP should be deleted
468  * @param[io] asyncResp   Response object that will be returned to client
469  *
470  * @return None
471  */
472 inline void
473     deleteHypervisorIPv4(const std::string& ifaceId,
474                          const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
475 {
476     std::string address = "0.0.0.0";
477     std::string gateway = "0.0.0.0";
478     const uint8_t prefixLength = 0;
479     setHypervisorIPv4Address(asyncResp, ifaceId, address);
480     setHypervisorIPv4Gateway(asyncResp, gateway);
481     setHypervisorIPv4Subnet(asyncResp, ifaceId, prefixLength);
482 }
483 
484 inline void parseInterfaceData(
485     nlohmann::json& jsonResponse, const std::string& ifaceId,
486     const EthernetInterfaceData& ethData,
487     const boost::container::flat_set<IPv4AddressData>& ipv4Data)
488 {
489     jsonResponse["Id"] = ifaceId;
490     jsonResponse["@odata.id"] =
491         "/redfish/v1/Systems/hypervisor/EthernetInterfaces/" + ifaceId;
492     jsonResponse["InterfaceEnabled"] = true;
493     jsonResponse["MACAddress"] = ethData.macAddress;
494 
495     jsonResponse["HostName"] = ethData.hostName;
496     jsonResponse["DHCPv4"]["DHCPEnabled"] =
497         translateDhcpEnabledToBool(ethData.dhcpEnabled, true);
498 
499     nlohmann::json& ipv4Array = jsonResponse["IPv4Addresses"];
500     nlohmann::json& ipv4StaticArray = jsonResponse["IPv4StaticAddresses"];
501     ipv4Array = nlohmann::json::array();
502     ipv4StaticArray = nlohmann::json::array();
503     for (const auto& ipv4Config : ipv4Data)
504     {
505         if (ipv4Config.isActive)
506         {
507             nlohmann::json::object_t ipv4;
508             ipv4["AddressOrigin"] = ipv4Config.origin;
509             ipv4["SubnetMask"] = ipv4Config.netmask;
510             ipv4["Address"] = ipv4Config.address;
511             ipv4["Gateway"] = ethData.defaultGateway;
512 
513             if (ipv4Config.origin == "Static")
514             {
515                 ipv4StaticArray.push_back(ipv4);
516             }
517             ipv4Array.push_back(std::move(ipv4));
518         }
519     }
520 }
521 
522 inline void setDHCPEnabled(const std::string& ifaceId,
523                            const bool& ipv4DHCPEnabled,
524                            const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
525 {
526     const std::string dhcp = getDhcpEnabledEnumeration(ipv4DHCPEnabled, false);
527     crow::connections::systemBus->async_method_call(
528         [asyncResp](const boost::system::error_code ec) {
529         if (ec)
530         {
531             BMCWEB_LOG_ERROR << "D-Bus responses error: " << ec;
532             messages::internalError(asyncResp->res);
533             return;
534         }
535         },
536         "xyz.openbmc_project.Settings",
537         "/xyz/openbmc_project/network/hypervisor/" + ifaceId,
538         "org.freedesktop.DBus.Properties", "Set",
539         "xyz.openbmc_project.Network.EthernetInterface", "DHCPEnabled",
540         dbus::utility::DbusVariantType{dhcp});
541 
542     // Set the IPv4 address origin to the DHCP / Static as per the new value
543     // of the DHCPEnabled property
544     std::string origin;
545     if (!ipv4DHCPEnabled)
546     {
547         origin = "xyz.openbmc_project.Network.IP.AddressOrigin.Static";
548     }
549     else
550     {
551         // DHCPEnabled is set to true. Delete the current IPv4 settings
552         // to receive the new values from DHCP server.
553         deleteHypervisorIPv4(ifaceId, asyncResp);
554         origin = "xyz.openbmc_project.Network.IP.AddressOrigin.DHCP";
555     }
556     crow::connections::systemBus->async_method_call(
557         [asyncResp](const boost::system::error_code ec) {
558         if (ec)
559         {
560             BMCWEB_LOG_ERROR << "DBUS response error " << ec;
561             messages::internalError(asyncResp->res);
562             return;
563         }
564         BMCWEB_LOG_DEBUG << "Hypervisor IPaddress Origin is Set";
565         },
566         "xyz.openbmc_project.Settings",
567         "/xyz/openbmc_project/network/hypervisor/" + ifaceId + "/ipv4/addr0",
568         "org.freedesktop.DBus.Properties", "Set",
569         "xyz.openbmc_project.Network.IP", "Origin",
570         dbus::utility::DbusVariantType(origin));
571 }
572 
573 inline void handleHypervisorIPv4StaticPatch(
574     const std::string& ifaceId, const nlohmann::json& input,
575     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
576 {
577     if ((!input.is_array()) || input.empty())
578     {
579         messages::propertyValueTypeError(asyncResp->res, input.dump(),
580                                          "IPv4StaticAddresses");
581         return;
582     }
583 
584     // Hypervisor considers the first IP address in the array list
585     // as the Hypervisor's virtual management interface supports single IPv4
586     // address
587     const nlohmann::json& thisJson = input[0];
588 
589     if (!thisJson.is_null() && !thisJson.empty())
590     {
591         // For the error string
592         std::string pathString = "IPv4StaticAddresses/1";
593         std::optional<std::string> address;
594         std::optional<std::string> subnetMask;
595         std::optional<std::string> gateway;
596         nlohmann::json thisJsonCopy = thisJson;
597         if (!json_util::readJson(thisJsonCopy, asyncResp->res, "Address",
598                                  address, "SubnetMask", subnetMask, "Gateway",
599                                  gateway))
600         {
601             messages::propertyValueFormatError(
602                 asyncResp->res,
603                 thisJson.dump(2, ' ', true,
604                               nlohmann::json::error_handler_t::replace),
605                 pathString);
606             return;
607         }
608 
609         uint8_t prefixLength = 0;
610         bool errorInEntry = false;
611         if (address)
612         {
613             if (!ip_util::ipv4VerifyIpAndGetBitcount(*address))
614             {
615                 messages::propertyValueFormatError(asyncResp->res, *address,
616                                                    pathString + "/Address");
617                 errorInEntry = true;
618             }
619         }
620         else
621         {
622             messages::propertyMissing(asyncResp->res, pathString + "/Address");
623             errorInEntry = true;
624         }
625 
626         if (subnetMask)
627         {
628             if (!ip_util::ipv4VerifyIpAndGetBitcount(*subnetMask,
629                                                      &prefixLength))
630             {
631                 messages::propertyValueFormatError(asyncResp->res, *subnetMask,
632                                                    pathString + "/SubnetMask");
633                 errorInEntry = true;
634             }
635         }
636         else
637         {
638             messages::propertyMissing(asyncResp->res,
639                                       pathString + "/SubnetMask");
640             errorInEntry = true;
641         }
642 
643         if (gateway)
644         {
645             if (!ip_util::ipv4VerifyIpAndGetBitcount(*gateway))
646             {
647                 messages::propertyValueFormatError(asyncResp->res, *gateway,
648                                                    pathString + "/Gateway");
649                 errorInEntry = true;
650             }
651         }
652         else
653         {
654             messages::propertyMissing(asyncResp->res, pathString + "/Gateway");
655             errorInEntry = true;
656         }
657 
658         if (errorInEntry)
659         {
660             return;
661         }
662 
663         BMCWEB_LOG_DEBUG << "Calling createHypervisorIPv4 on : " << ifaceId
664                          << "," << *address;
665         createHypervisorIPv4(ifaceId, prefixLength, *gateway, *address,
666                              asyncResp);
667         // Set the DHCPEnabled to false since the Static IPv4 is set
668         setDHCPEnabled(ifaceId, false, asyncResp);
669     }
670     else
671     {
672         if (thisJson.is_null())
673         {
674             deleteHypervisorIPv4(ifaceId, asyncResp);
675         }
676     }
677 }
678 
679 inline void
680     handleHostnamePatch(const std::string& hostName,
681                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
682 {
683     if (!isHostnameValid(hostName))
684     {
685         messages::propertyValueFormatError(asyncResp->res, hostName,
686                                            "HostName");
687         return;
688     }
689 
690     asyncResp->res.jsonValue["HostName"] = hostName;
691     crow::connections::systemBus->async_method_call(
692         [asyncResp](const boost::system::error_code ec) {
693         if (ec)
694         {
695             messages::internalError(asyncResp->res);
696         }
697         },
698         "xyz.openbmc_project.Settings",
699         "/xyz/openbmc_project/network/hypervisor",
700         "org.freedesktop.DBus.Properties", "Set",
701         "xyz.openbmc_project.Network.SystemConfiguration", "HostName",
702         dbus::utility::DbusVariantType(hostName));
703 }
704 
705 inline void
706     setIPv4InterfaceEnabled(const std::string& ifaceId, const bool& isActive,
707                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
708 {
709     crow::connections::systemBus->async_method_call(
710         [asyncResp](const boost::system::error_code ec) {
711         if (ec)
712         {
713             BMCWEB_LOG_ERROR << "D-Bus responses error: " << ec;
714             messages::internalError(asyncResp->res);
715             return;
716         }
717         },
718         "xyz.openbmc_project.Settings",
719         "/xyz/openbmc_project/network/hypervisor/" + ifaceId + "/ipv4/addr0",
720         "org.freedesktop.DBus.Properties", "Set",
721         "xyz.openbmc_project.Object.Enable", "Enabled",
722         dbus::utility::DbusVariantType(isActive));
723 }
724 
725 inline void requestRoutesHypervisorSystems(App& app)
726 {
727     /**
728      * Hypervisor Systems derived class for delivering Computer Systems Schema.
729      */
730 
731     BMCWEB_ROUTE(app, "/redfish/v1/Systems/hypervisor/")
732         .privileges(redfish::privileges::getComputerSystem)
733         .methods(boost::beast::http::verb::get)(
734             [&app](const crow::Request& req,
735                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
736         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
737         {
738             return;
739         }
740         sdbusplus::asio::getProperty<std::string>(
741             *crow::connections::systemBus, "xyz.openbmc_project.Settings",
742             "/xyz/openbmc_project/network/hypervisor",
743             "xyz.openbmc_project.Network.SystemConfiguration", "HostName",
744             [asyncResp](const boost::system::error_code ec,
745                         const std::string& /*hostName*/) {
746             if (ec)
747             {
748                 messages::resourceNotFound(asyncResp->res, "System",
749                                            "hypervisor");
750                 return;
751             }
752             BMCWEB_LOG_DEBUG << "Hypervisor is available";
753 
754             asyncResp->res.jsonValue["@odata.type"] =
755                 "#ComputerSystem.v1_6_0.ComputerSystem";
756             asyncResp->res.jsonValue["@odata.id"] =
757                 "/redfish/v1/Systems/hypervisor";
758             asyncResp->res.jsonValue["Description"] = "Hypervisor";
759             asyncResp->res.jsonValue["Name"] = "Hypervisor";
760             asyncResp->res.jsonValue["Id"] = "hypervisor";
761             asyncResp->res.jsonValue["SystemType"] = "OS";
762             nlohmann::json::array_t managedBy;
763             nlohmann::json::object_t manager;
764             manager["@odata.id"] = "/redfish/v1/Managers/bmc";
765             managedBy.push_back(std::move(manager));
766             asyncResp->res.jsonValue["Links"]["ManagedBy"] =
767                 std::move(managedBy);
768             asyncResp->res.jsonValue["EthernetInterfaces"]["@odata.id"] =
769                 "/redfish/v1/Systems/hypervisor/EthernetInterfaces";
770             getHypervisorState(asyncResp);
771             getHypervisorActions(asyncResp);
772             // TODO: Add "SystemType" : "hypervisor"
773             });
774         });
775 
776     /**
777      * HypervisorInterfaceCollection class to handle the GET and PATCH on
778      * Hypervisor Interface
779      */
780 
781     BMCWEB_ROUTE(app, "/redfish/v1/Systems/hypervisor/EthernetInterfaces/")
782         .privileges(redfish::privileges::getEthernetInterfaceCollection)
783         .methods(boost::beast::http::verb::get)(
784             [&app](const crow::Request& req,
785                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
786         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
787         {
788             return;
789         }
790         constexpr std::array<std::string_view, 1> interfaces = {
791             "xyz.openbmc_project.Network.EthernetInterface"};
792 
793         dbus::utility::getSubTreePaths(
794             "/xyz/openbmc_project/network/hypervisor", 0, interfaces,
795             [asyncResp](
796                 const boost::system::error_code& error,
797                 const dbus::utility::MapperGetSubTreePathsResponse& ifaceList) {
798             if (error)
799             {
800                 messages::resourceNotFound(asyncResp->res, "System",
801                                            "hypervisor");
802                 return;
803             }
804             asyncResp->res.jsonValue["@odata.type"] =
805                 "#EthernetInterfaceCollection."
806                 "EthernetInterfaceCollection";
807             asyncResp->res.jsonValue["@odata.id"] =
808                 "/redfish/v1/Systems/hypervisor/EthernetInterfaces";
809             asyncResp->res.jsonValue["Name"] = "Hypervisor Ethernet "
810                                                "Interface Collection";
811             asyncResp->res.jsonValue["Description"] =
812                 "Collection of Virtual Management "
813                 "Interfaces for the hypervisor";
814 
815             nlohmann::json& ifaceArray = asyncResp->res.jsonValue["Members"];
816             ifaceArray = nlohmann::json::array();
817             for (const std::string& iface : ifaceList)
818             {
819                 sdbusplus::message::object_path path(iface);
820                 std::string name = path.filename();
821                 if (name.empty())
822                 {
823                     continue;
824                 }
825                 nlohmann::json::object_t ethIface;
826                 ethIface["@odata.id"] =
827                     "/redfish/v1/Systems/hypervisor/EthernetInterfaces/" + name;
828                 ifaceArray.push_back(std::move(ethIface));
829             }
830             asyncResp->res.jsonValue["Members@odata.count"] = ifaceArray.size();
831             });
832         });
833 
834     BMCWEB_ROUTE(app,
835                  "/redfish/v1/Systems/hypervisor/EthernetInterfaces/<str>/")
836         .privileges(redfish::privileges::getEthernetInterface)
837         .methods(boost::beast::http::verb::get)(
838             [&app](const crow::Request& req,
839                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
840                    const std::string& id) {
841         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
842         {
843             return;
844         }
845         getHypervisorIfaceData(
846             id,
847             [asyncResp, ifaceId{std::string(id)}](
848                 const bool& success, const EthernetInterfaceData& ethData,
849                 const boost::container::flat_set<IPv4AddressData>& ipv4Data) {
850             if (!success)
851             {
852                 messages::resourceNotFound(asyncResp->res, "EthernetInterface",
853                                            ifaceId);
854                 return;
855             }
856             asyncResp->res.jsonValue["@odata.type"] =
857                 "#EthernetInterface.v1_6_0.EthernetInterface";
858             asyncResp->res.jsonValue["Name"] = "Hypervisor Ethernet Interface";
859             asyncResp->res.jsonValue["Description"] =
860                 "Hypervisor's Virtual Management Ethernet Interface";
861             parseInterfaceData(asyncResp->res.jsonValue, ifaceId, ethData,
862                                ipv4Data);
863             });
864         });
865 
866     BMCWEB_ROUTE(app,
867                  "/redfish/v1/Systems/hypervisor/EthernetInterfaces/<str>/")
868         .privileges(redfish::privileges::patchEthernetInterface)
869         .methods(boost::beast::http::verb::patch)(
870             [&app](const crow::Request& req,
871                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
872                    const std::string& ifaceId) {
873         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
874         {
875             return;
876         }
877         std::optional<std::string> hostName;
878         std::optional<std::vector<nlohmann::json>> ipv4StaticAddresses;
879         std::optional<nlohmann::json> ipv4Addresses;
880         std::optional<nlohmann::json> dhcpv4;
881         std::optional<bool> ipv4DHCPEnabled;
882 
883         if (!json_util::readJsonPatch(req, asyncResp->res, "HostName", hostName,
884                                       "IPv4StaticAddresses",
885                                       ipv4StaticAddresses, "IPv4Addresses",
886                                       ipv4Addresses, "DHCPv4", dhcpv4))
887         {
888             return;
889         }
890 
891         if (ipv4Addresses)
892         {
893             messages::propertyNotWritable(asyncResp->res, "IPv4Addresses");
894             return;
895         }
896 
897         if (dhcpv4)
898         {
899             if (!json_util::readJson(*dhcpv4, asyncResp->res, "DHCPEnabled",
900                                      ipv4DHCPEnabled))
901             {
902                 return;
903             }
904         }
905 
906         getHypervisorIfaceData(
907             ifaceId,
908             [asyncResp, ifaceId, hostName = std::move(hostName),
909              ipv4StaticAddresses = std::move(ipv4StaticAddresses),
910              ipv4DHCPEnabled, dhcpv4 = std::move(dhcpv4)](
911                 const bool& success, const EthernetInterfaceData& ethData,
912                 const boost::container::flat_set<IPv4AddressData>&) {
913             if (!success)
914             {
915                 messages::resourceNotFound(asyncResp->res, "EthernetInterface",
916                                            ifaceId);
917                 return;
918             }
919 
920             if (ipv4StaticAddresses)
921             {
922                 const nlohmann::json& ipv4Static = *ipv4StaticAddresses;
923                 if (ipv4Static.begin() == ipv4Static.end())
924                 {
925                     messages::propertyValueTypeError(
926                         asyncResp->res,
927                         ipv4Static.dump(
928                             2, ' ', true,
929                             nlohmann::json::error_handler_t::replace),
930                         "IPv4StaticAddresses");
931                     return;
932                 }
933 
934                 // One and only one hypervisor instance supported
935                 if (ipv4Static.size() != 1)
936                 {
937                     messages::propertyValueFormatError(
938                         asyncResp->res,
939                         ipv4Static.dump(
940                             2, ' ', true,
941                             nlohmann::json::error_handler_t::replace),
942                         "IPv4StaticAddresses");
943                     return;
944                 }
945 
946                 const nlohmann::json& ipv4Json = ipv4Static[0];
947                 // Check if the param is 'null'. If its null, it means
948                 // that user wants to delete the IP address. Deleting
949                 // the IP address is allowed only if its statically
950                 // configured. Deleting the address originated from DHCP
951                 // is not allowed.
952                 if ((ipv4Json.is_null()) &&
953                     (translateDhcpEnabledToBool(ethData.dhcpEnabled, true)))
954                 {
955                     BMCWEB_LOG_INFO
956                         << "Ignoring the delete on ipv4StaticAddresses "
957                            "as the interface is DHCP enabled";
958                 }
959                 else
960                 {
961                     handleHypervisorIPv4StaticPatch(ifaceId, ipv4Static,
962                                                     asyncResp);
963                 }
964             }
965 
966             if (hostName)
967             {
968                 handleHostnamePatch(*hostName, asyncResp);
969             }
970 
971             if (dhcpv4)
972             {
973                 setDHCPEnabled(ifaceId, *ipv4DHCPEnabled, asyncResp);
974             }
975 
976             // Set this interface to disabled/inactive. This will be set
977             // to enabled/active by the pldm once the hypervisor
978             // consumes the updated settings from the user.
979             setIPv4InterfaceEnabled(ifaceId, false, asyncResp);
980             });
981         asyncResp->res.result(boost::beast::http::status::accepted);
982         });
983 
984     BMCWEB_ROUTE(app, "/redfish/v1/Systems/hypervisor/ResetActionInfo/")
985         .privileges(redfish::privileges::getActionInfo)
986         .methods(boost::beast::http::verb::get)(
987             [&app](const crow::Request& req,
988                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
989         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
990         {
991             return;
992         }
993         // Only return action info if hypervisor D-Bus object present
994         constexpr std::array<std::string_view, 1> interfaces = {
995             "xyz.openbmc_project.State.Host"};
996         dbus::utility::getDbusObject(
997             "/xyz/openbmc_project/state/hypervisor0", interfaces,
998             [asyncResp](const boost::system::error_code& ec,
999                         const std::vector<std::pair<
1000                             std::string, std::vector<std::string>>>& objInfo) {
1001             if (ec)
1002             {
1003                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
1004 
1005                 // No hypervisor objects found by mapper
1006                 if (ec.value() == boost::system::errc::io_error)
1007                 {
1008                     messages::resourceNotFound(asyncResp->res, "hypervisor",
1009                                                "ResetActionInfo");
1010                     return;
1011                 }
1012 
1013                 messages::internalError(asyncResp->res);
1014                 return;
1015             }
1016 
1017             // One and only one hypervisor instance supported
1018             if (objInfo.size() != 1)
1019             {
1020                 messages::internalError(asyncResp->res);
1021                 return;
1022             }
1023 
1024             // The hypervisor object only support the ability to
1025             // turn On The system object Action should be utilized
1026             // for other operations
1027 
1028             asyncResp->res.jsonValue["@odata.type"] =
1029                 "#ActionInfo.v1_1_2.ActionInfo";
1030             asyncResp->res.jsonValue["@odata.id"] =
1031                 "/redfish/v1/Systems/hypervisor/ResetActionInfo";
1032             asyncResp->res.jsonValue["Name"] = "Reset Action Info";
1033             asyncResp->res.jsonValue["Id"] = "ResetActionInfo";
1034             nlohmann::json::array_t parameters;
1035             nlohmann::json::object_t parameter;
1036             parameter["Name"] = "ResetType";
1037             parameter["Required"] = true;
1038             parameter["DataType"] = "String";
1039             nlohmann::json::array_t allowed;
1040             allowed.push_back("On");
1041             parameter["AllowableValues"] = std::move(allowed);
1042             parameters.push_back(std::move(parameter));
1043             asyncResp->res.jsonValue["Parameters"] = std::move(parameters);
1044             });
1045         });
1046 
1047     BMCWEB_ROUTE(app,
1048                  "/redfish/v1/Systems/hypervisor/Actions/ComputerSystem.Reset/")
1049         .privileges(redfish::privileges::postComputerSystem)
1050         .methods(boost::beast::http::verb::post)(
1051             [&app](const crow::Request& req,
1052                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1053         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1054         {
1055             return;
1056         }
1057         std::optional<std::string> resetType;
1058         if (!json_util::readJsonAction(req, asyncResp->res, "ResetType",
1059                                        resetType))
1060         {
1061             // readJson adds appropriate error to response
1062             return;
1063         }
1064 
1065         if (!resetType)
1066         {
1067             messages::actionParameterMissing(
1068                 asyncResp->res, "ComputerSystem.Reset", "ResetType");
1069             return;
1070         }
1071 
1072         // Hypervisor object only support On operation
1073         if (resetType != "On")
1074         {
1075             messages::propertyValueNotInList(asyncResp->res, *resetType,
1076                                              "ResetType");
1077             return;
1078         }
1079 
1080         std::string command = "xyz.openbmc_project.State.Host.Transition.On";
1081 
1082         crow::connections::systemBus->async_method_call(
1083             [asyncResp, resetType](const boost::system::error_code ec) {
1084             if (ec)
1085             {
1086                 BMCWEB_LOG_ERROR << "D-Bus responses error: " << ec;
1087                 if (ec.value() == boost::asio::error::invalid_argument)
1088                 {
1089                     messages::actionParameterNotSupported(asyncResp->res,
1090                                                           *resetType, "Reset");
1091                     return;
1092                 }
1093 
1094                 if (ec.value() == boost::asio::error::host_unreachable)
1095                 {
1096                     messages::resourceNotFound(asyncResp->res, "Actions",
1097                                                "Reset");
1098                     return;
1099                 }
1100 
1101                 messages::internalError(asyncResp->res);
1102                 return;
1103             }
1104             messages::success(asyncResp->res);
1105             },
1106             "xyz.openbmc_project.State.Hypervisor",
1107             "/xyz/openbmc_project/state/hypervisor0",
1108             "org.freedesktop.DBus.Properties", "Set",
1109             "xyz.openbmc_project.State.Host", "RequestedHostTransition",
1110             dbus::utility::DbusVariantType{std::move(command)});
1111         });
1112 }
1113 } // namespace redfish::hypervisor
1114