summaryrefslogtreecommitdiff
path: root/redfish-core/lib/hypervisor_system.hpp
blob: 1a3d6cbb546aa99b3b0a93ad41a8a5c1530d402d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
#pragma once

#include "app.hpp"
#include "dbus_singleton.hpp"
#include "dbus_utility.hpp"
#include "error_messages.hpp"
#include "ethernet.hpp"
#include "query.hpp"
#include "registries/privilege_registry.hpp"
#include "utils/ip_utils.hpp"
#include "utils/json_utils.hpp"

#include <boost/url/format.hpp>
#include <sdbusplus/asio/property.hpp>

#include <array>
#include <optional>
#include <string_view>
#include <utility>

namespace redfish
{

/**
 * @brief Retrieves hypervisor state properties over dbus
 *
 * The hypervisor state object is optional so this function will only set the
 * state variables if the object is found
 *
 * @param[in] asyncResp     Shared pointer for completing asynchronous calls.
 *
 * @return None.
 */
inline void
    getHypervisorState(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    BMCWEB_LOG_DEBUG("Get hypervisor state information.");
    sdbusplus::asio::getProperty<std::string>(
        *crow::connections::systemBus, "xyz.openbmc_project.State.Hypervisor",
        "/xyz/openbmc_project/state/hypervisor0",
        "xyz.openbmc_project.State.Host", "CurrentHostState",
        [asyncResp](const boost::system::error_code& ec,
                    const std::string& hostState) {
        if (ec)
        {
            BMCWEB_LOG_DEBUG("DBUS response error {}", ec);
            // This is an optional D-Bus object so just return if
            // error occurs
            return;
        }

        BMCWEB_LOG_DEBUG("Hypervisor state: {}", hostState);
        // Verify Host State
        if (hostState == "xyz.openbmc_project.State.Host.HostState.Running")
        {
            asyncResp->res.jsonValue["PowerState"] = "On";
            asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
        }
        else if (hostState == "xyz.openbmc_project.State.Host.HostState."
                              "Quiesced")
        {
            asyncResp->res.jsonValue["PowerState"] = "On";
            asyncResp->res.jsonValue["Status"]["State"] = "Quiesced";
        }
        else if (hostState == "xyz.openbmc_project.State.Host.HostState."
                              "Standby")
        {
            asyncResp->res.jsonValue["PowerState"] = "On";
            asyncResp->res.jsonValue["Status"]["State"] = "StandbyOffline";
        }
        else if (hostState == "xyz.openbmc_project.State.Host.HostState."
                              "TransitioningToRunning")
        {
            asyncResp->res.jsonValue["PowerState"] = "PoweringOn";
            asyncResp->res.jsonValue["Status"]["State"] = "Starting";
        }
        else if (hostState == "xyz.openbmc_project.State.Host.HostState."
                              "TransitioningToOff")
        {
            asyncResp->res.jsonValue["PowerState"] = "PoweringOff";
            asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
        }
        else if (hostState == "xyz.openbmc_project.State.Host.HostState.Off")
        {
            asyncResp->res.jsonValue["PowerState"] = "Off";
            asyncResp->res.jsonValue["Status"]["State"] = "Disabled";
        }
        else
        {
            messages::internalError(asyncResp->res);
            return;
        }
    });
}

/**
 * @brief Populate Actions if any are valid for hypervisor object
 *
 * The hypervisor state object is optional so this function will only set the
 * Action if the object is found
 *
 * @param[in] asyncResp     Shared pointer for completing asynchronous calls.
 *
 * @return None.
 */
inline void
    getHypervisorActions(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    BMCWEB_LOG_DEBUG("Get hypervisor actions.");
    constexpr std::array<std::string_view, 1> interfaces = {
        "xyz.openbmc_project.State.Host"};
    dbus::utility::getDbusObject(
        "/xyz/openbmc_project/state/hypervisor0", interfaces,
        [asyncResp](
            const boost::system::error_code& ec,
            const std::vector<std::pair<std::string, std::vector<std::string>>>&
                objInfo) {
        if (ec)
        {
            BMCWEB_LOG_DEBUG("DBUS response error {}", ec);
            // This is an optional D-Bus object so just return if
            // error occurs
            return;
        }

        if (objInfo.empty())
        {
            // As noted above, this is an optional interface so just return
            // if there is no instance found
            return;
        }

        if (objInfo.size() > 1)
        {
            // More then one hypervisor object is not supported and is an
            // error
            messages::internalError(asyncResp->res);
            return;
        }

        // Object present so system support limited ComputerSystem Action
        nlohmann::json& reset =
            asyncResp->res.jsonValue["Actions"]["#ComputerSystem.Reset"];
        reset["target"] =
            "/redfish/v1/Systems/hypervisor/Actions/ComputerSystem.Reset";
        reset["@Redfish.ActionInfo"] =
            "/redfish/v1/Systems/hypervisor/ResetActionInfo";
    });
}

inline bool extractHypervisorInterfaceData(
    const std::string& ethIfaceId,
    const dbus::utility::ManagedObjectType& dbusData,
    EthernetInterfaceData& ethData, std::vector<IPv4AddressData>& ipv4Config)
{
    bool idFound = false;
    for (const auto& objpath : dbusData)
    {
        for (const auto& ifacePair : objpath.second)
        {
            if (objpath.first ==
                "/xyz/openbmc_project/network/hypervisor/" + ethIfaceId)
            {
                idFound = true;
                if (ifacePair.first == "xyz.openbmc_project.Network.MACAddress")
                {
                    for (const auto& propertyPair : ifacePair.second)
                    {
                        if (propertyPair.first == "MACAddress")
                        {
                            const std::string* mac =
                                std::get_if<std::string>(&propertyPair.second);
                            if (mac != nullptr)
                            {
                                ethData.macAddress = *mac;
                            }
                        }
                    }
                }
                else if (ifacePair.first ==
                         "xyz.openbmc_project.Network.EthernetInterface")
                {
                    for (const auto& propertyPair : ifacePair.second)
                    {
                        if (propertyPair.first == "DHCPEnabled")
                        {
                            const std::string* dhcp =
                                std::get_if<std::string>(&propertyPair.second);
                            if (dhcp != nullptr)
                            {
                                ethData.dhcpEnabled = *dhcp;
                                break; // Interested on only "DHCPEnabled".
                                       // Stop parsing since we got the
                                       // "DHCPEnabled" value.
                            }
                        }
                    }
                }
            }
            if (objpath.first == "/xyz/openbmc_project/network/hypervisor/" +
                                     ethIfaceId + "/ipv4/addr0")
            {
                IPv4AddressData& ipv4Address = ipv4Config.emplace_back();
                if (ifacePair.first == "xyz.openbmc_project.Object.Enable")
                {
                    for (const auto& property : ifacePair.second)
                    {
                        if (property.first == "Enabled")
                        {
                            const bool* intfEnable =
                                std::get_if<bool>(&property.second);
                            if (intfEnable != nullptr)
                            {
                                ipv4Address.isActive = *intfEnable;
                                break;
                            }
                        }
                    }
                }
                if (ifacePair.first == "xyz.openbmc_project.Network.IP")
                {
                    for (const auto& property : ifacePair.second)
                    {
                        if (property.first == "Address")
                        {
                            const std::string* address =
                                std::get_if<std::string>(&property.second);
                            if (address != nullptr)
                            {
                                ipv4Address.address = *address;
                            }
                        }
                        else if (property.first == "Origin")
                        {
                            const std::string* origin =
                                std::get_if<std::string>(&property.second);
                            if (origin != nullptr)
                            {
                                ipv4Address.origin =
                                    translateAddressOriginDbusToRedfish(*origin,
                                                                        true);
                            }
                        }
                        else if (property.first == "PrefixLength")
                        {
                            const uint8_t* mask =
                                std::get_if<uint8_t>(&property.second);
                            if (mask != nullptr)
                            {
                                // convert it to the string
                                ipv4Address.netmask = getNetmask(*mask);
                            }
                        }
                        else if (property.first == "Type" ||
                                 property.first == "Gateway")
                        {
                            // Type & Gateway is not used
                            continue;
                        }
                        else
                        {
                            BMCWEB_LOG_ERROR(
                                "Got extra property: {} on the {} object",
                                property.first, objpath.first.str);
                        }
                    }
                }
            }
            if (objpath.first == "/xyz/openbmc_project/network/hypervisor")
            {
                // System configuration shows up in the global namespace, so no
                // need to check eth number
                if (ifacePair.first ==
                    "xyz.openbmc_project.Network.SystemConfiguration")
                {
                    for (const auto& propertyPair : ifacePair.second)
                    {
                        if (propertyPair.first == "HostName")
                        {
                            const std::string* hostName =
                                std::get_if<std::string>(&propertyPair.second);
                            if (hostName != nullptr)
                            {
                                ethData.hostName = *hostName;
                            }
                        }
                        else if (propertyPair.first == "DefaultGateway")
                        {
                            const std::string* defaultGateway =
                                std::get_if<std::string>(&propertyPair.second);
                            if (defaultGateway != nullptr)
                            {
                                ethData.defaultGateway = *defaultGateway;
                            }
                        }
                    }
                }
            }
        }
    }
    return idFound;
}
/**
 * Function that retrieves all properties for given Hypervisor Ethernet
 * Interface Object from Settings Manager
 * @param ethIfaceId Hypervisor ethernet interface id to query on DBus
 * @param callback a function that shall be called to convert Dbus output
 * into JSON
 */
template <typename CallbackFunc>
void getHypervisorIfaceData(const std::string& ethIfaceId,
                            CallbackFunc&& callback)
{
    sdbusplus::message::object_path path("/");
    dbus::utility::getManagedObjects(
        "xyz.openbmc_project.Settings", path,
        [ethIfaceId{std::string{ethIfaceId}},
         callback{std::forward<CallbackFunc>(callback)}](
            const boost::system::error_code& ec,
            const dbus::utility::ManagedObjectType& resp) mutable {
        EthernetInterfaceData ethData{};
        std::vector<IPv4AddressData> ipv4Data;
        if (ec)
        {
            callback(false, ethData, ipv4Data);
            return;
        }

        bool found = extractHypervisorInterfaceData(ethIfaceId, resp, ethData,
                                                    ipv4Data);
        if (!found)
        {
            BMCWEB_LOG_INFO("Hypervisor Interface not found");
        }
        callback(found, ethData, ipv4Data);
    });
}

/**
 * @brief Sets the Hypervisor Interface IPAddress DBUS
 *
 * @param[in] asyncResp          Shared pointer for generating response message.
 * @param[in] ipv4Address    Address from the incoming request
 * @param[in] ethIfaceId     Hypervisor Interface Id
 *
 * @return None.
 */
inline void setHypervisorIPv4Address(
    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
    const std::string& ethIfaceId, const std::string& ipv4Address)
{
    BMCWEB_LOG_DEBUG("Setting the Hypervisor IPaddress : {} on Iface: {}",
                     ipv4Address, ethIfaceId);

    setDbusProperty(asyncResp, "xyz.openbmc_project.Settings",
                    "/xyz/openbmc_project/network/hypervisor/" + ethIfaceId +
                        "/ipv4/addr0",
                    "xyz.openbmc_project.Network.IP", "Address",
                    "IPv4StaticAddresses/1/Address", ipv4Address);
}

/**
 * @brief Sets the Hypervisor Interface SubnetMask DBUS
 *
 * @param[in] asyncResp     Shared pointer for generating response message.
 * @param[in] subnet    SubnetMask from the incoming request
 * @param[in] ethIfaceId Hypervisor Interface Id
 *
 * @return None.
 */
inline void
    setHypervisorIPv4Subnet(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
                            const std::string& ethIfaceId, const uint8_t subnet)
{
    BMCWEB_LOG_DEBUG("Setting the Hypervisor subnet : {} on Iface: {}", subnet,
                     ethIfaceId);

    setDbusProperty(asyncResp, "xyz.openbmc_project.Settings",
                    "/xyz/openbmc_project/network/hypervisor/" + ethIfaceId +
                        "/ipv4/addr0",
                    "xyz.openbmc_project.Network.IP", "PrefixLength",
                    "IPv4StaticAddresses/1/SubnetMask", subnet);
}

/**
 * @brief Sets the Hypervisor Interface Gateway DBUS
 *
 * @param[in] asyncResp          Shared pointer for generating response message.
 * @param[in] gateway        Gateway from the incoming request
 * @param[in] ethIfaceId     Hypervisor Interface Id
 *
 * @return None.
 */
inline void setHypervisorIPv4Gateway(
    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
    const std::string& gateway)
{
    BMCWEB_LOG_DEBUG(
        "Setting the DefaultGateway to the last configured gateway");

    setDbusProperty(asyncResp, "xyz.openbmc_project.Settings",
                    sdbusplus::message::object_path(
                        "/xyz/openbmc_project/network/hypervisor"),
                    "xyz.openbmc_project.Network.SystemConfiguration",
                    "DefaultGateway", "IPv4StaticAddresses/1/Gateway", gateway);
}

/**
 * @brief Creates a static IPv4 entry
 *
 * @param[in] ifaceId      Id of interface upon which to create the IPv4 entry
 * @param[in] prefixLength IPv4 prefix syntax for the subnet mask
 * @param[in] gateway      IPv4 address of this interfaces gateway
 * @param[in] address      IPv4 address to assign to this interface
 * @param[io] asyncResp    Response object that will be returned to client
 *
 * @return None
 */
inline void
    createHypervisorIPv4(const std::string& ifaceId, uint8_t prefixLength,
                         const std::string& gateway, const std::string& address,
                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    setHypervisorIPv4Address(asyncResp, ifaceId, address);
    setHypervisorIPv4Gateway(asyncResp, gateway);
    setHypervisorIPv4Subnet(asyncResp, ifaceId, prefixLength);
}

/**
 * @brief Deletes given IPv4 interface
 *
 * @param[in] ifaceId     Id of interface whose IP should be deleted
 * @param[io] asyncResp   Response object that will be returned to client
 *
 * @return None
 */
inline void
    deleteHypervisorIPv4(const std::string& ifaceId,
                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    std::string address = "0.0.0.0";
    std::string gateway = "0.0.0.0";
    const uint8_t prefixLength = 0;
    setHypervisorIPv4Address(asyncResp, ifaceId, address);
    setHypervisorIPv4Gateway(asyncResp, gateway);
    setHypervisorIPv4Subnet(asyncResp, ifaceId, prefixLength);
}

inline void parseInterfaceData(nlohmann::json& jsonResponse,
                               const std::string& ifaceId,
                               const EthernetInterfaceData& ethData,
                               const std::vector<IPv4AddressData>& ipv4Data)
{
    jsonResponse["Id"] = ifaceId;
    jsonResponse["@odata.id"] = boost::urls::format(
        "/redfish/v1/Systems/hypervisor/EthernetInterfaces/{}", ifaceId);
    jsonResponse["InterfaceEnabled"] = true;
    jsonResponse["MACAddress"] = ethData.macAddress;

    jsonResponse["HostName"] = ethData.hostName;
    jsonResponse["DHCPv4"]["DHCPEnabled"] =
        translateDhcpEnabledToBool(ethData.dhcpEnabled, true);

    nlohmann::json& ipv4Array = jsonResponse["IPv4Addresses"];
    nlohmann::json& ipv4StaticArray = jsonResponse["IPv4StaticAddresses"];
    ipv4Array = nlohmann::json::array();
    ipv4StaticArray = nlohmann::json::array();
    for (const auto& ipv4Config : ipv4Data)
    {
        if (ipv4Config.isActive)
        {
            nlohmann::json::object_t ipv4;
            ipv4["AddressOrigin"] = ipv4Config.origin;
            ipv4["SubnetMask"] = ipv4Config.netmask;
            ipv4["Address"] = ipv4Config.address;
            ipv4["Gateway"] = ethData.defaultGateway;

            if (ipv4Config.origin == "Static")
            {
                ipv4StaticArray.push_back(ipv4);
            }
            ipv4Array.emplace_back(std::move(ipv4));
        }
    }
}

inline void setDHCPEnabled(const std::string& ifaceId, bool ipv4DHCPEnabled,
                           const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    const std::string dhcp = getDhcpEnabledEnumeration(ipv4DHCPEnabled, false);

    setDbusProperty(asyncResp, "xyz.openbmc_project.Settings",
                    sdbusplus::message::object_path(
                        "/xyz/openbmc_project/network/hypervisor") /
                        ifaceId,
                    "xyz.openbmc_project.Network.EthernetInterface",
                    "DHCPEnabled", "DHCPv4/DHCPEnabled", dhcp);

    // Set the IPv4 address origin to the DHCP / Static as per the new value
    // of the DHCPEnabled property
    std::string origin;
    if (!ipv4DHCPEnabled)
    {
        origin = "xyz.openbmc_project.Network.IP.AddressOrigin.Static";
    }
    else
    {
        // DHCPEnabled is set to true. Delete the current IPv4 settings
        // to receive the new values from DHCP server.
        deleteHypervisorIPv4(ifaceId, asyncResp);
        origin = "xyz.openbmc_project.Network.IP.AddressOrigin.DHCP";
    }

    setDbusProperty(asyncResp, "xyz.openbmc_project.Settings",
                    "/xyz/openbmc_project/network/hypervisor/" + ifaceId +
                        "/ipv4/addr0",
                    "xyz.openbmc_project.Network.IP", "Origin",
                    "IPv4StaticAddresses/1/AddressOrigin", origin);
}

inline void handleHypervisorIPv4StaticPatch(
    const std::string& ifaceId,
    std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>& input,
    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    // Hypervisor considers the first IP address in the array list
    // as the Hypervisor's virtual management interface supports single IPv4
    // address
    std::variant<nlohmann::json::object_t, std::nullptr_t>& thisJson = input[0];
    nlohmann::json::object_t* obj =
        std::get_if<nlohmann::json::object_t>(&thisJson);
    if (obj == nullptr)
    {
        deleteHypervisorIPv4(ifaceId, asyncResp);
        return;
    }
    if (obj->empty())
    {
        return;
    }
    // For the error string
    std::string pathString = "IPv4StaticAddresses/1";
    std::string address;
    std::string subnetMask;
    std::string gateway;
    if (!json_util::readJsonObject(*obj, asyncResp->res, "Address", address,
                                   "SubnetMask", subnetMask, "Gateway",
                                   gateway))
    {
        return;
    }

    uint8_t prefixLength = 0;
    if (!ip_util::ipv4VerifyIpAndGetBitcount(address))
    {
        messages::propertyValueFormatError(asyncResp->res, address,
                                           pathString + "/Address");
        return;
    }

    if (!ip_util::ipv4VerifyIpAndGetBitcount(subnetMask, &prefixLength))
    {
        messages::propertyValueFormatError(asyncResp->res, subnetMask,
                                           pathString + "/SubnetMask");
        return;
    }

    if (!ip_util::ipv4VerifyIpAndGetBitcount(gateway))
    {
        messages::propertyValueFormatError(asyncResp->res, gateway,
                                           pathString + "/Gateway");
        return;
    }

    BMCWEB_LOG_DEBUG("Calling createHypervisorIPv4 on : {},{}", ifaceId,
                     address);
    createHypervisorIPv4(ifaceId, prefixLength, gateway, address, asyncResp);
    // Set the DHCPEnabled to false since the Static IPv4 is set
    setDHCPEnabled(ifaceId, false, asyncResp);
}

inline void handleHypervisorHostnamePatch(
    const std::string& hostName,
    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    if (!isHostnameValid(hostName))
    {
        messages::propertyValueFormatError(asyncResp->res, hostName,
                                           "HostName");
        return;
    }

    asyncResp->res.jsonValue["HostName"] = hostName;
    setDbusProperty(asyncResp, "xyz.openbmc_project.Settings",
                    sdbusplus::message::object_path(
                        "/xyz/openbmc_project/network/hypervisor"),
                    "xyz.openbmc_project.Network.SystemConfiguration",
                    "HostName", "HostName", hostName);
}

inline void
    setIPv4InterfaceEnabled(const std::string& ifaceId, bool isActive,
                            const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    setDbusProperty(asyncResp, "xyz.openbmc_project.Settings",
                    "/xyz/openbmc_project/network/hypervisor/" + ifaceId +
                        "/ipv4/addr0",
                    "xyz.openbmc_project.Object.Enable", "Enabled",
                    "InterfaceEnabled", isActive);
}

inline void handleHypervisorEthernetInterfaceCollectionGet(
    App& app, const crow::Request& req,
    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    if (!redfish::setUpRedfishRoute(app, req, asyncResp))
    {
        return;
    }
    constexpr std::array<std::string_view, 1> interfaces = {
        "xyz.openbmc_project.Network.EthernetInterface"};

    dbus::utility::getSubTreePaths(
        "/xyz/openbmc_project/network/hypervisor", 0, interfaces,
        [asyncResp](
            const boost::system::error_code& ec,
            const dbus::utility::MapperGetSubTreePathsResponse& ifaceList) {
        if (ec)
        {
            messages::resourceNotFound(asyncResp->res, "System", "hypervisor");
            return;
        }
        asyncResp->res.jsonValue["@odata.type"] =
            "#EthernetInterfaceCollection."
            "EthernetInterfaceCollection";
        asyncResp->res.jsonValue["@odata.id"] =
            "/redfish/v1/Systems/hypervisor/EthernetInterfaces";
        asyncResp->res.jsonValue["Name"] = "Hypervisor Ethernet "
                                           "Interface Collection";
        asyncResp->res.jsonValue["Description"] =
            "Collection of Virtual Management "
            "Interfaces for the hypervisor";

        nlohmann::json& ifaceArray = asyncResp->res.jsonValue["Members"];
        ifaceArray = nlohmann::json::array();
        for (const std::string& iface : ifaceList)
        {
            sdbusplus::message::object_path path(iface);
            std::string name = path.filename();
            if (name.empty())
            {
                continue;
            }
            nlohmann::json::object_t ethIface;
            ethIface["@odata.id"] = boost::urls::format(
                "/redfish/v1/Systems/hypervisor/EthernetInterfaces/{}", name);
            ifaceArray.emplace_back(std::move(ethIface));
        }
        asyncResp->res.jsonValue["Members@odata.count"] = ifaceArray.size();
    });
}

inline void handleHypervisorEthernetInterfaceGet(
    App& app, const crow::Request& req,
    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const std::string& id)
{
    if (!redfish::setUpRedfishRoute(app, req, asyncResp))
    {
        return;
    }
    getHypervisorIfaceData(
        id, [asyncResp, ifaceId{std::string(id)}](
                bool success, const EthernetInterfaceData& ethData,
                const std::vector<IPv4AddressData>& ipv4Data) {
        if (!success)
        {
            messages::resourceNotFound(asyncResp->res, "EthernetInterface",
                                       ifaceId);
            return;
        }
        asyncResp->res.jsonValue["@odata.type"] =
            "#EthernetInterface.v1_9_0.EthernetInterface";
        asyncResp->res.jsonValue["Name"] = "Hypervisor Ethernet Interface";
        asyncResp->res.jsonValue["Description"] =
            "Hypervisor's Virtual Management Ethernet Interface";
        parseInterfaceData(asyncResp->res.jsonValue, ifaceId, ethData,
                           ipv4Data);
    });
}

inline void handleHypervisorSystemGet(
    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    sdbusplus::asio::getProperty<std::string>(
        *crow::connections::systemBus, "xyz.openbmc_project.Settings",
        "/xyz/openbmc_project/network/hypervisor",
        "xyz.openbmc_project.Network.SystemConfiguration", "HostName",
        [asyncResp](const boost::system::error_code& ec,
                    const std::string& /*hostName*/) {
        if (ec)
        {
            messages::resourceNotFound(asyncResp->res, "System", "hypervisor");
            return;
        }
        BMCWEB_LOG_DEBUG("Hypervisor is available");

        asyncResp->res.jsonValue["@odata.type"] =
            "#ComputerSystem.v1_6_0.ComputerSystem";
        asyncResp->res.jsonValue["@odata.id"] =
            "/redfish/v1/Systems/hypervisor";
        asyncResp->res.jsonValue["Description"] = "Hypervisor";
        asyncResp->res.jsonValue["Name"] = "Hypervisor";
        asyncResp->res.jsonValue["Id"] = "hypervisor";
        asyncResp->res.jsonValue["SystemType"] = "OS";
        nlohmann::json::array_t managedBy;
        nlohmann::json::object_t manager;
        manager["@odata.id"] = "/redfish/v1/Managers/bmc";
        managedBy.emplace_back(std::move(manager));
        asyncResp->res.jsonValue["Links"]["ManagedBy"] = std::move(managedBy);
        asyncResp->res.jsonValue["EthernetInterfaces"]["@odata.id"] =
            "/redfish/v1/Systems/hypervisor/EthernetInterfaces";
        getHypervisorState(asyncResp);
        getHypervisorActions(asyncResp);
        // TODO: Add "SystemType" : "hypervisor"
    });
}

inline void handleHypervisorEthernetInterfacePatch(
    App& app, const crow::Request& req,
    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
    const std::string& ifaceId)
{
    if (!redfish::setUpRedfishRoute(app, req, asyncResp))
    {
        return;
    }
    std::optional<std::string> hostName;
    std::optional<
        std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>>
        ipv4StaticAddresses;
    std::optional<std::vector<nlohmann::json::object_t>> ipv4Addresses;
    std::optional<bool> ipv4DHCPEnabled;

    if (!json_util::readJsonPatch(req, asyncResp->res, "HostName", hostName,
                                  "IPv4StaticAddresses", ipv4StaticAddresses,
                                  "IPv4Addresses", ipv4Addresses,
                                  "DHCPv4/DHCPEnabled", ipv4DHCPEnabled))
    {
        return;
    }

    if (ipv4Addresses)
    {
        messages::propertyNotWritable(asyncResp->res, "IPv4Addresses");
        return;
    }

    getHypervisorIfaceData(
        ifaceId,
        [asyncResp, ifaceId, hostName = std::move(hostName),
         ipv4StaticAddresses = std::move(ipv4StaticAddresses),
         ipv4DHCPEnabled](bool success, const EthernetInterfaceData& ethData,
                          const std::vector<IPv4AddressData>&) mutable {
        if (!success)
        {
            messages::resourceNotFound(asyncResp->res, "EthernetInterface",
                                       ifaceId);
            return;
        }

        if (ipv4StaticAddresses)
        {
            std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>&
                ipv4Static = *ipv4StaticAddresses;
            if (ipv4Static.begin() == ipv4Static.end())
            {
                messages::propertyValueTypeError(asyncResp->res,
                                                 std::vector<std::string>(),
                                                 "IPv4StaticAddresses");
                return;
            }

            // One and only one hypervisor instance supported
            if (ipv4Static.size() != 1)
            {
                messages::propertyValueFormatError(asyncResp->res, "[]",
                                                   "IPv4StaticAddresses");
                return;
            }

            std::variant<nlohmann::json::object_t, std::nullptr_t>& ipv4Json =
                ipv4Static[0];
            // Check if the param is 'null'. If its null, it means
            // that user wants to delete the IP address. Deleting
            // the IP address is allowed only if its statically
            // configured. Deleting the address originated from DHCP
            // is not allowed.
            if (std::holds_alternative<std::nullptr_t>(ipv4Json) &&
                translateDhcpEnabledToBool(ethData.dhcpEnabled, true))
            {
                BMCWEB_LOG_INFO("Ignoring the delete on ipv4StaticAddresses "
                                "as the interface is DHCP enabled");
            }
            else
            {
                handleHypervisorIPv4StaticPatch(ifaceId, ipv4Static, asyncResp);
            }
        }

        if (hostName)
        {
            handleHypervisorHostnamePatch(*hostName, asyncResp);
        }

        if (ipv4DHCPEnabled)
        {
            setDHCPEnabled(ifaceId, *ipv4DHCPEnabled, asyncResp);
        }

        // Set this interface to disabled/inactive. This will be set
        // to enabled/active by the pldm once the hypervisor
        // consumes the updated settings from the user.
        setIPv4InterfaceEnabled(ifaceId, false, asyncResp);
    });
    asyncResp->res.result(boost::beast::http::status::accepted);
}

inline void handleHypervisorResetActionGet(
    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    // Only return action info if hypervisor D-Bus object present
    constexpr std::array<std::string_view, 1> interfaces = {
        "xyz.openbmc_project.State.Host"};
    dbus::utility::getDbusObject(
        "/xyz/openbmc_project/state/hypervisor0", interfaces,
        [asyncResp](
            const boost::system::error_code& ec,
            const std::vector<std::pair<std::string, std::vector<std::string>>>&
                objInfo) {
        if (ec)
        {
            BMCWEB_LOG_DEBUG("DBUS response error {}", ec);

            // No hypervisor objects found by mapper
            if (ec.value() == boost::system::errc::io_error)
            {
                messages::resourceNotFound(asyncResp->res, "hypervisor",
                                           "ResetActionInfo");
                return;
            }

            messages::internalError(asyncResp->res);
            return;
        }

        // One and only one hypervisor instance supported
        if (objInfo.size() != 1)
        {
            messages::internalError(asyncResp->res);
            return;
        }

        // The hypervisor object only support the ability to
        // turn On The system object Action should be utilized
        // for other operations

        asyncResp->res.jsonValue["@odata.type"] =
            "#ActionInfo.v1_1_2.ActionInfo";
        asyncResp->res.jsonValue["@odata.id"] =
            "/redfish/v1/Systems/hypervisor/ResetActionInfo";
        asyncResp->res.jsonValue["Name"] = "Reset Action Info";
        asyncResp->res.jsonValue["Id"] = "ResetActionInfo";
        nlohmann::json::array_t parameters;
        nlohmann::json::object_t parameter;
        parameter["Name"] = "ResetType";
        parameter["Required"] = true;
        parameter["DataType"] = "String";
        nlohmann::json::array_t allowed;
        allowed.emplace_back("On");
        parameter["AllowableValues"] = std::move(allowed);
        parameters.emplace_back(std::move(parameter));
        asyncResp->res.jsonValue["Parameters"] = std::move(parameters);
    });
}

inline void handleHypervisorSystemResetPost(
    App& app, const crow::Request& req,
    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
{
    if (!redfish::setUpRedfishRoute(app, req, asyncResp))
    {
        return;
    }
    std::optional<std::string> resetType;
    if (!json_util::readJsonAction(req, asyncResp->res, "ResetType", resetType))
    {
        // readJson adds appropriate error to response
        return;
    }

    if (!resetType)
    {
        messages::actionParameterMissing(asyncResp->res, "ComputerSystem.Reset",
                                         "ResetType");
        return;
    }

    // Hypervisor object only support On operation
    if (resetType != "On")
    {
        messages::propertyValueNotInList(asyncResp->res, *resetType,
                                         "ResetType");
        return;
    }

    std::string command = "xyz.openbmc_project.State.Host.Transition.On";

    sdbusplus::asio::setProperty(
        *crow::connections::systemBus, "xyz.openbmc_project.State.Hypervisor",
        "/xyz/openbmc_project/state/hypervisor0",
        "xyz.openbmc_project.State.Host", "RequestedHostTransition", command,
        [asyncResp, resetType](const boost::system::error_code& ec) {
        if (ec)
        {
            BMCWEB_LOG_ERROR("D-Bus responses error: {}", ec);
            if (ec.value() == boost::asio::error::invalid_argument)
            {
                messages::actionParameterNotSupported(asyncResp->res,
                                                      *resetType, "Reset");
                return;
            }

            if (ec.value() == boost::asio::error::host_unreachable)
            {
                messages::resourceNotFound(asyncResp->res, "Actions", "Reset");
                return;
            }

            messages::internalError(asyncResp->res);
            return;
        }
        messages::success(asyncResp->res);
    });
}

inline void requestRoutesHypervisorSystems(App& app)
{
    /**
     * HypervisorInterfaceCollection class to handle the GET and PATCH on
     * Hypervisor Interface
     */

    BMCWEB_ROUTE(app, "/redfish/v1/Systems/hypervisor/EthernetInterfaces/")
        .privileges(redfish::privileges::getEthernetInterfaceCollection)
        .methods(boost::beast::http::verb::get)(std::bind_front(
            handleHypervisorEthernetInterfaceCollectionGet, std::ref(app)));

    BMCWEB_ROUTE(app,
                 "/redfish/v1/Systems/hypervisor/EthernetInterfaces/<str>/")
        .privileges(redfish::privileges::getEthernetInterface)
        .methods(boost::beast::http::verb::get)(std::bind_front(
            handleHypervisorEthernetInterfaceGet, std::ref(app)));

    BMCWEB_ROUTE(app,
                 "/redfish/v1/Systems/hypervisor/EthernetInterfaces/<str>/")
        .privileges(redfish::privileges::patchEthernetInterface)
        .methods(boost::beast::http::verb::patch)(std::bind_front(
            handleHypervisorEthernetInterfacePatch, std::ref(app)));

    BMCWEB_ROUTE(app,
                 "/redfish/v1/Systems/hypervisor/Actions/ComputerSystem.Reset/")
        .privileges(redfish::privileges::postComputerSystem)
        .methods(boost::beast::http::verb::post)(
            std::bind_front(handleHypervisorSystemResetPost, std::ref(app)));
}
} // namespace redfish