libredfish 0.2.0

A redfish library. Useful for querying server hardware from a BMC.
Documentation
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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
/*
 * SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 * SPDX-License-Identifier: MIT
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

use std::{collections::HashMap, path::Path, time::Duration};

use crate::{
    model::{
        account_service::ManagerAccount,
        boot::{BootSourceOverrideEnabled, BootSourceOverrideTarget},
        certificate::Certificate,
        chassis::{Assembly, Chassis, NetworkAdapter},
        storage::Drives,
        component_integrity::ComponentIntegrities,
        network_device_function::NetworkDeviceFunction,
        oem::nvidia_dpu::{HostPrivilegeLevel, NicMode},
        power::Power,
        secure_boot::SecureBoot,
        sel::LogEntry,
        sensor::GPUSensors,
        service_root::{RedfishVendor, ServiceRoot},
        software_inventory::SoftwareInventory,
        task::Task,
        thermal::Thermal,
        update_service::{ComponentType, TransferProtocolType, UpdateService},
        BootOption, ComputerSystem, Manager, ManagerResetType,
    },
    jsonmap,
    standard::RedfishStandard,
    BiosProfileType, Boot, BootOptions, Collection, EnabledDisabled, JobState,
    MachineSetupStatus, MachineSetupDiff, ODataId, PCIeDevice, PowerState, Redfish, RedfishError,
    Resource, RoleId, Status, StatusInternal, SystemPowerControl,
};

/// AMI uses BIOS attribute SETUP001 for Administrator Password (UEFI password)
const UEFI_PASSWORD_NAME: &str = "SETUP001";

pub struct Bmc {
    s: RedfishStandard,
}

impl Bmc {
    pub fn new(s: RedfishStandard) -> Result<Bmc, RedfishError> {
        Ok(Bmc { s })
    }
}

#[async_trait::async_trait]
impl Redfish for Bmc {
    async fn change_username(&self, old_name: &str, new_name: &str) -> Result<(), RedfishError> {
        self.s.change_username(old_name, new_name).await
    }

    async fn change_password(&self, user: &str, new: &str) -> Result<(), RedfishError> {
        self.s.change_password(user, new).await
    }

    /// AMI BMC requires If-Match header for password changes
    async fn change_password_by_id(
        &self,
        account_id: &str,
        new_pass: &str,
    ) -> Result<(), RedfishError> {
        let url = format!("AccountService/Accounts/{}", account_id);
        let mut data = HashMap::new();
        data.insert("Password", new_pass);
        self.s.client.patch_with_if_match(&url, data).await
    }

    async fn get_accounts(&self) -> Result<Vec<ManagerAccount>, RedfishError> {
        self.s.get_accounts().await
    }

    async fn create_user(
        &self,
        username: &str,
        password: &str,
        role_id: RoleId,
    ) -> Result<(), RedfishError> {
        self.s.create_user(username, password, role_id).await
    }

    async fn delete_user(&self, username: &str) -> Result<(), RedfishError> {
        self.s.delete_user(username).await
    }

    async fn get_firmware(&self, id: &str) -> Result<SoftwareInventory, RedfishError> {
        self.s.get_firmware(id).await
    }

    async fn get_software_inventories(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_software_inventories().await
    }

    async fn get_tasks(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_tasks().await
    }

    async fn get_task(&self, id: &str) -> Result<Task, RedfishError> {
        self.s.get_task(id).await
    }

    async fn get_power_state(&self) -> Result<PowerState, RedfishError> {
        self.s.get_power_state().await
    }

    async fn get_service_root(&self) -> Result<ServiceRoot, RedfishError> {
        self.s.get_service_root().await
    }

    async fn get_systems(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_systems().await
    }

    async fn get_system(&self) -> Result<ComputerSystem, RedfishError> {
        self.s.get_system().await
    }

    async fn get_managers(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_managers().await
    }

    async fn get_manager(&self) -> Result<Manager, RedfishError> {
        self.s.get_manager().await
    }

    async fn get_secure_boot(&self) -> Result<SecureBoot, RedfishError> {
        self.s.get_secure_boot().await
    }

    /// AMI BMC requires If-Match header for secure boot changes
    async fn disable_secure_boot(&self) -> Result<(), RedfishError> {
        let mut data = HashMap::new();
        data.insert("SecureBootEnable", false);
        let url = format!("Systems/{}/SecureBoot", self.s.system_id());
        self.s.client.patch_with_if_match(&url, data).await
    }

    /// AMI BMC requires If-Match header for secure boot changes
    async fn enable_secure_boot(&self) -> Result<(), RedfishError> {
        let mut data = HashMap::new();
        data.insert("SecureBootEnable", true);
        let url = format!("Systems/{}/SecureBoot", self.s.system_id());
        self.s.client.patch_with_if_match(&url, data).await
    }

    async fn get_secure_boot_certificate(
        &self,
        database_id: &str,
        certificate_id: &str,
    ) -> Result<Certificate, RedfishError> {
        self.s
            .get_secure_boot_certificate(database_id, certificate_id)
            .await
    }

    async fn get_secure_boot_certificates(
        &self,
        database_id: &str,
    ) -> Result<Vec<String>, RedfishError> {
        self.s.get_secure_boot_certificates(database_id).await
    }

    async fn add_secure_boot_certificate(
        &self,
        pem_cert: &str,
        database_id: &str,
    ) -> Result<Task, RedfishError> {
        self.s
            .add_secure_boot_certificate(pem_cert, database_id)
            .await
    }

    async fn get_power_metrics(&self) -> Result<Power, RedfishError> {
        self.s.get_power_metrics().await
    }

    async fn power(&self, action: SystemPowerControl) -> Result<(), RedfishError> {
        self.s.power(action).await
    }

    /// AMI BMC only supports ForceRestart
    async fn bmc_reset(&self) -> Result<(), RedfishError> {
        self.s
            .reset_manager(ManagerResetType::ForceRestart, None)
            .await
    }

    async fn chassis_reset(
        &self,
        chassis_id: &str,
        reset_type: SystemPowerControl,
    ) -> Result<(), RedfishError> {
        self.s.chassis_reset(chassis_id, reset_type).await
    }

    async fn bmc_reset_to_defaults(&self) -> Result<(), RedfishError> {
        self.s.bmc_reset_to_defaults().await
    }

    async fn get_thermal_metrics(&self) -> Result<Thermal, RedfishError> {
        self.s.get_thermal_metrics().await
    }

    async fn get_gpu_sensors(&self) -> Result<Vec<GPUSensors>, RedfishError> {
        self.s.get_gpu_sensors().await
    }

    async fn get_system_event_log(&self) -> Result<Vec<LogEntry>, RedfishError> {
        self.s.get_system_event_log().await
    }

    async fn get_bmc_event_log(
        &self,
        from: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Vec<LogEntry>, RedfishError> {
        self.s.get_bmc_event_log(from).await
    }

    async fn get_drives_metrics(&self) -> Result<Vec<Drives>, RedfishError> {
        self.s.get_drives_metrics().await
    }

    /// Machine setup for AMI BMC.
    ///
    /// Sets up:
    /// 1. Serial console
    /// 2. Clears TPM
    /// 3. BIOS settings
    async fn machine_setup(
        &self,
        _boot_interface_mac: Option<&str>,
        _bios_profiles: &HashMap<
            RedfishVendor,
            HashMap<String, HashMap<BiosProfileType, HashMap<String, serde_json::Value>>>,
        >,
        _selected_profile: BiosProfileType,
    ) -> Result<(), RedfishError> {
        self.setup_serial_console().await?;
        self.clear_tpm().await?;
        let attrs = self.machine_setup_attrs();
        self.set_bios(attrs).await?;
        Ok(())
    }

    /// Check machine setup status for AMI BMC.
    async fn machine_setup_status(
        &self,
        boot_interface_mac: Option<&str>,
    ) -> Result<MachineSetupStatus, RedfishError> {
        let mut diffs = self.diff_bios_bmc_attr().await?;

        if let Some(mac) = boot_interface_mac {
            let (expected, actual) = self.get_expected_and_actual_first_boot_option(mac).await?;
            if expected.is_none() || expected != actual {
                diffs.push(MachineSetupDiff {
                    key: "boot_first".to_string(),
                    expected: expected.unwrap_or_else(|| "Not found".to_string()),
                    actual: actual.unwrap_or_else(|| "Not found".to_string()),
                });
            }
        }

        let lockdown = self.lockdown_status().await?;
        if !lockdown.is_fully_enabled() {
            diffs.push(MachineSetupDiff {
                key: "lockdown".to_string(),
                expected: "Enabled".to_string(),
                actual: lockdown.status.to_string(),
            });
        }

        Ok(MachineSetupStatus {
            is_done: diffs.is_empty(),
            diffs,
        })
    }

    async fn is_bios_setup(&self, _boot_interface_mac: Option<&str>) -> Result<bool, RedfishError> {
        let diffs = self.diff_bios_bmc_attr().await?;
        Ok(diffs.is_empty())
    }

    /// AMI BMC requires If-Match header for password policy changes
    async fn set_machine_password_policy(&self) -> Result<(), RedfishError> {
        use serde_json::Value;
        let body = HashMap::from([
            ("AccountLockoutThreshold", Value::Number(0.into())),
            ("AccountLockoutDuration", Value::Number(0.into())),
            ("AccountLockoutCounterResetAfter", Value::Number(0.into())),
        ]);
        self.s
            .client
            .patch_with_if_match("AccountService", body)
            .await
    }

    /// AMI lockdown - controls KCS access, USB support, and Host Interface
    async fn lockdown(&self, target: EnabledDisabled) -> Result<(), RedfishError> {
        use EnabledDisabled::*;
        // (KCSACP, USB000, HostInterface enabled)
        let (kcsacp, usb, hi_enabled) = match target {
            Enabled => ("Deny All", "Disabled", false),
            Disabled => ("Allow All", "Enabled", true),
        };

        // Set BIOS attributes
        self.set_bios(HashMap::from([
            ("KCSACP".to_string(), kcsacp.into()),
            ("USB000".to_string(), usb.into()),
        ]))
        .await?;

        // Set Host Interface
        let hi_body = HashMap::from([("InterfaceEnabled", hi_enabled)]);
        self.s
            .client
            .patch_with_if_match("Managers/Self/HostInterfaces/Self", hi_body)
            .await
    }

    /// AMI lockdown_status - checks KCS access, USB support, and Host Interface
    async fn lockdown_status(&self) -> Result<Status, RedfishError> {
        let bios = self.s.bios().await?;
        let url = format!("Systems/{}/Bios", self.s.system_id());
        let attrs = jsonmap::get_object(&bios, "Attributes", &url)?;
        let kcsacp = jsonmap::get_str(attrs, "KCSACP", "Bios Attributes")?;
        let usb000 = jsonmap::get_str(attrs, "USB000", "Bios Attributes")?;

        let hi_url = "Managers/Self/HostInterfaces/Self";
        let (_status, hi): (_, serde_json::Value) = self.s.client.get(hi_url).await?;
        let hi_enabled = hi
            .get("InterfaceEnabled")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let message = format!(
            "kcs_access={}, usb_support={}, host_interface={}",
            kcsacp, usb000, hi_enabled
        );

        let is_locked = kcsacp == "Deny All" && usb000 == "Disabled" && !hi_enabled;
        let is_unlocked = kcsacp == "Allow All" && usb000 == "Enabled" && hi_enabled;

        Ok(Status {
            message,
            status: if is_locked {
                StatusInternal::Enabled
            } else if is_unlocked {
                StatusInternal::Disabled
            } else {
                StatusInternal::Partial
            },
        })
    }

    /// Setup serial console for AMI BMC via BIOS attributes.
    async fn setup_serial_console(&self) -> Result<(), RedfishError> {
        use serde_json::Value;

        let attributes: HashMap<String, Value> = HashMap::from([
            ("TER001".to_string(), "Enabled".into()),   // Console Redirection
            ("TER010".to_string(), "Enabled".into()),   // Console Redirection EMS
            ("TER06B".to_string(), "COM1".into()),      // Out-of-Band Mgmt Port
            ("TER0021".to_string(), "115200".into()),   // Bits per second
            ("TER0020".to_string(), "115200".into()),   // Bits per second EMS
            ("TER012".to_string(), "VT100Plus".into()), // Terminal Type
            ("TER011".to_string(), "VT-UTF8".into()),   // Terminal Type EMS
            ("TER05D".to_string(), "None".into()),      // Flow Control
        ]);

        self.set_bios(attributes).await
    }

    /// Check serial console status for AMI BMC.
    async fn serial_console_status(&self) -> Result<Status, RedfishError> {
        let bios = self.bios().await?;
        let url = format!("Systems/{}/Bios", self.s.system_id());
        let attrs = jsonmap::get_object(&bios, "Attributes", &url)?;

        let expected = vec![
            ("TER001", "Enabled", "Disabled"),
            ("TER010", "Enabled", "Disabled"),
            ("TER06B", "COM1", "any"),
            ("TER0021", "115200", "any"),
            ("TER0020", "115200", "any"),
            ("TER012", "VT100Plus", "any"),
            ("TER011", "VT-UTF8", "any"),
            ("TER05D", "None", "any"),
        ];

        let mut message = String::new();
        let mut enabled = true;
        let mut disabled = true;

        for (key, val_enabled, val_disabled) in expected {
            if let Some(val_current) = attrs.get(key).and_then(|v| v.as_str()) {
                message.push_str(&format!("{key}={val_current} "));
                if val_current != val_enabled {
                    enabled = false;
                }
                if val_current != val_disabled && val_disabled != "any" {
                    disabled = false;
                }
            }
        }

        Ok(Status {
            message,
            status: match (enabled, disabled) {
                (true, _) => StatusInternal::Enabled,
                (_, true) => StatusInternal::Disabled,
                _ => StatusInternal::Partial,
            },
        })
    }

    async fn get_boot_options(&self) -> Result<BootOptions, RedfishError> {
        self.s.get_boot_options().await
    }

    async fn get_boot_option(&self, option_id: &str) -> Result<BootOption, RedfishError> {
        self.s.get_boot_option(option_id).await
    }

    async fn boot_once(&self, target: Boot) -> Result<(), RedfishError> {
        let override_target = match target {
            Boot::Pxe => BootSourceOverrideTarget::Pxe,
            Boot::HardDisk => BootSourceOverrideTarget::Hdd,
            Boot::UefiHttp => BootSourceOverrideTarget::UefiHttp,
        };
        self.set_boot_override(override_target, BootSourceOverrideEnabled::Once)
            .await
    }

    async fn boot_first(&self, target: Boot) -> Result<(), RedfishError> {
        self.s.boot_first(target).await
    }

    /// AMI BMC requires If-Match header for boot order changes
    async fn change_boot_order(&self, boot_array: Vec<String>) -> Result<(), RedfishError> {
        let body = HashMap::from([("Boot", HashMap::from([("BootOrder", boot_array)]))]);
        let url = format!("Systems/{}/SD", self.s.system_id());
        self.s.client.patch_with_if_match(&url, body).await
    }

    async fn clear_tpm(&self) -> Result<(), RedfishError> {
        self.set_bios(HashMap::from([("TCG006".to_string(), "TPM Clear".into())]))
            .await
    }

    async fn pcie_devices(&self) -> Result<Vec<PCIeDevice>, RedfishError> {
        self.s.pcie_devices().await
    }

    async fn update_firmware(&self, firmware: tokio::fs::File) -> Result<Task, RedfishError> {
        self.s.update_firmware(firmware).await
    }

    async fn update_firmware_multipart(
        &self,
        filename: &Path,
        reboot: bool,
        timeout: Duration,
        component_type: ComponentType,
    ) -> Result<String, RedfishError> {
        self.s
            .update_firmware_multipart(filename, reboot, timeout, component_type)
            .await
    }

    async fn update_firmware_simple_update(
        &self,
        image_uri: &str,
        targets: Vec<String>,
        transfer_protocol: TransferProtocolType,
    ) -> Result<Task, RedfishError> {
        self.s
            .update_firmware_simple_update(image_uri, targets, transfer_protocol)
            .await
    }

    async fn bios(&self) -> Result<HashMap<String, serde_json::Value>, RedfishError> {
        self.s.bios().await
    }

    /// AMI BMC requires If-Match header for BIOS changes
    async fn set_bios(
        &self,
        values: HashMap<String, serde_json::Value>,
    ) -> Result<(), RedfishError> {
        let url = format!("Systems/{}/Bios/SD", self.s.system_id());
        let body = HashMap::from([("Attributes", values)]);
        self.s.client.patch_with_if_match(&url, body).await
    }

    async fn reset_bios(&self) -> Result<(), RedfishError> {
        self.s.factory_reset_bios().await
    }

    /// AMI uses /Bios/SD for pending settings
    async fn pending(&self) -> Result<HashMap<String, serde_json::Value>, RedfishError> {
        let url = format!("Systems/{}/Bios/SD", self.s.system_id());
        self.s.pending_with_url(&url).await
    }

    /// AMI clear_pending - uses /Bios/SD instead of /Bios/Settings
    async fn clear_pending(&self) -> Result<(), RedfishError> {
        let pending_url = format!("Systems/{}/Bios/SD", self.s.system_id());
        let pending_attrs = self.s.pending_attributes(&pending_url).await?;
        let current_attrs = self.s.bios_attributes().await?;

        let reset_attrs: HashMap<_, _> = pending_attrs
            .iter()
            .filter(|(k, v)| current_attrs.get(*k) != Some(v))
            .map(|(k, _)| (k.clone(), current_attrs.get(k).cloned()))
            .collect();

        if reset_attrs.is_empty() {
            return Ok(());
        }

        let body = HashMap::from([("Attributes", reset_attrs)]);
        self.s
            .client
            .patch_with_if_match(&pending_url, body)
            .await
    }

    async fn get_network_device_functions(
        &self,
        chassis_id: &str,
    ) -> Result<Vec<String>, RedfishError> {
        self.s.get_network_device_functions(chassis_id).await
    }

    async fn get_network_device_function(
        &self,
        chassis_id: &str,
        id: &str,
        port: Option<&str>,
    ) -> Result<NetworkDeviceFunction, RedfishError> {
        self.s
            .get_network_device_function(chassis_id, id, port)
            .await
    }

    async fn get_chassis_all(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_chassis_all().await
    }

    async fn get_chassis(&self, id: &str) -> Result<Chassis, RedfishError> {
        self.s.get_chassis(id).await
    }

    async fn get_chassis_assembly(&self, chassis_id: &str) -> Result<Assembly, RedfishError> {
        self.s.get_chassis_assembly(chassis_id).await
    }

    async fn get_chassis_network_adapters(
        &self,
        chassis_id: &str,
    ) -> Result<Vec<String>, RedfishError> {
        self.s.get_chassis_network_adapters(chassis_id).await
    }

    async fn get_chassis_network_adapter(
        &self,
        chassis_id: &str,
        id: &str,
    ) -> Result<NetworkAdapter, RedfishError> {
        self.s.get_chassis_network_adapter(chassis_id, id).await
    }

    async fn get_base_network_adapters(
        &self,
        system_id: &str,
    ) -> Result<Vec<String>, RedfishError> {
        self.s.get_base_network_adapters(system_id).await
    }

    async fn get_base_network_adapter(
        &self,
        system_id: &str,
        id: &str,
    ) -> Result<NetworkAdapter, RedfishError> {
        self.s.get_base_network_adapter(system_id, id).await
    }

    async fn get_ports(
        &self,
        chassis_id: &str,
        network_adapter: &str,
    ) -> Result<Vec<String>, RedfishError> {
        self.s.get_ports(chassis_id, network_adapter).await
    }

    async fn get_port(
        &self,
        chassis_id: &str,
        network_adapter: &str,
        id: &str,
    ) -> Result<crate::NetworkPort, RedfishError> {
        self.s.get_port(chassis_id, network_adapter, id).await
    }

    async fn get_manager_ethernet_interfaces(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_manager_ethernet_interfaces().await
    }

    async fn get_manager_ethernet_interface(
        &self,
        id: &str,
    ) -> Result<crate::EthernetInterface, RedfishError> {
        self.s.get_manager_ethernet_interface(id).await
    }

    async fn get_system_ethernet_interfaces(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_system_ethernet_interfaces().await
    }

    async fn get_system_ethernet_interface(
        &self,
        id: &str,
    ) -> Result<crate::EthernetInterface, RedfishError> {
        self.s.get_system_ethernet_interface(id).await
    }

    /// AMI uses BIOS attribute SETUP001 for Administrator Password
    async fn change_uefi_password(
        &self,
        current_uefi_password: &str,
        new_uefi_password: &str,
    ) -> Result<Option<String>, RedfishError> {
        self.s
            .change_bios_password(UEFI_PASSWORD_NAME, current_uefi_password, new_uefi_password)
            .await
    }

    async fn clear_uefi_password(
        &self,
        current_uefi_password: &str,
    ) -> Result<Option<String>, RedfishError> {
        self.change_uefi_password(current_uefi_password, "").await
    }

    async fn get_job_state(&self, job_id: &str) -> Result<JobState, RedfishError> {
        self.s.get_job_state(job_id).await
    }

    async fn get_resource(&self, id: ODataId) -> Result<Resource, RedfishError> {
        self.s.get_resource(id).await
    }

    async fn get_collection(&self, id: ODataId) -> Result<Collection, RedfishError> {
        self.s.get_collection(id).await
    }

    /// Set the DPU (identified by MAC address) as the first boot option.
    async fn set_boot_order_dpu_first(
        &self,
        mac_address: &str,
    ) -> Result<Option<String>, RedfishError> {
        let mac = mac_address.to_uppercase();
        let system = self.get_system().await?;

        let boot_options_id =
            system
                .boot
                .boot_options
                .clone()
                .ok_or_else(|| RedfishError::MissingKey {
                    key: "boot.boot_options".to_string(),
                    url: system.odata.odata_id.clone(),
                })?;

        let all_boot_options: Vec<BootOption> = self
            .get_collection(boot_options_id)
            .await
            .and_then(|c| c.try_get::<BootOption>())?
            .members;

        let target = all_boot_options.iter().find(|opt| {
            let display = opt.display_name.to_uppercase();
            display.contains("HTTP") && display.contains("IPV4") && display.contains(&mac)
        });

        let Some(target) = target else {
            let all_names: Vec<_> = all_boot_options
                .iter()
                .map(|b| format!("{}: {}", b.id, b.display_name))
                .collect();
            return Err(RedfishError::MissingBootOption(format!(
                "No HTTP IPv4 boot option found for MAC {mac_address}; available: {:#?}",
                all_names
            )));
        };

        let target_id = target.boot_option_reference.clone();
        let mut boot_order = system.boot.boot_order;

        if boot_order.first() == Some(&target_id) {
            tracing::info!(
                "NO-OP: DPU ({mac_address}) is already first in boot order ({target_id})"
            );
            return Ok(None);
        }

        boot_order.retain(|id| id != &target_id);
        boot_order.insert(0, target_id);
        self.change_boot_order(boot_order).await?;
        Ok(None)
    }

    /// Check if boot order is setup correctly
    async fn is_boot_order_setup(&self, boot_interface_mac: &str) -> Result<bool, RedfishError> {
        let (expected, actual) = self
            .get_expected_and_actual_first_boot_option(boot_interface_mac)
            .await?;
        Ok(expected.is_some() && expected == actual)
    }

    async fn get_update_service(&self) -> Result<UpdateService, RedfishError> {
        self.s.get_update_service().await
    }

    async fn get_base_mac_address(&self) -> Result<Option<String>, RedfishError> {
        self.s.get_base_mac_address().await
    }

    /// AMI lockdown_bmc - BMC-only lockdown (Host Interface only)
    async fn lockdown_bmc(&self, target: EnabledDisabled) -> Result<(), RedfishError> {
        let interface_enabled = target == EnabledDisabled::Disabled;
        let hi_body = HashMap::from([("InterfaceEnabled", interface_enabled)]);
        let hi_url = "Managers/Self/HostInterfaces/Self";
        self.s.client.patch_with_if_match(hi_url, hi_body).await
    }

    async fn is_ipmi_over_lan_enabled(&self) -> Result<bool, RedfishError> {
        self.s.is_ipmi_over_lan_enabled().await
    }

    /// AMI BMC requires If-Match header for network protocol changes
    async fn enable_ipmi_over_lan(&self, target: EnabledDisabled) -> Result<(), RedfishError> {
        let url = format!("Managers/{}/NetworkProtocol", self.s.manager_id());
        let ipmi_data = HashMap::from([("ProtocolEnabled", target.is_enabled())]);
        let data = HashMap::from([("IPMI", ipmi_data)]);
        self.s.client.patch_with_if_match(&url, data).await
    }

    async fn enable_rshim_bmc(&self) -> Result<(), RedfishError> {
        self.s.enable_rshim_bmc().await
    }

    /// AMI clear_nvram - sets RECV000 (Reset NVRAM) to "Enabled"
    async fn clear_nvram(&self) -> Result<(), RedfishError> {
        self.set_bios(HashMap::from([("RECV000".to_string(), "Enabled".into())]))
            .await
    }

    async fn get_nic_mode(&self) -> Result<Option<NicMode>, RedfishError> {
        self.s.get_nic_mode().await
    }

    async fn set_nic_mode(&self, mode: NicMode) -> Result<(), RedfishError> {
        self.s.set_nic_mode(mode).await
    }

    async fn enable_infinite_boot(&self) -> Result<(), RedfishError> {
        self.set_bios(HashMap::from([("EndlessBoot".to_string(), "Enabled".into())]))
            .await
    }

    async fn is_infinite_boot_enabled(&self) -> Result<Option<bool>, RedfishError> {
        let bios = self.s.bios().await?;
        let url = format!("Systems/{}/Bios", self.s.system_id());
        let attrs = jsonmap::get_object(&bios, "Attributes", &url)?;
        let endless_boot = jsonmap::get_str(attrs, "EndlessBoot", "Bios Attributes")?;
        Ok(Some(endless_boot == "Enabled"))
    }

    async fn set_host_rshim(&self, enabled: EnabledDisabled) -> Result<(), RedfishError> {
        self.s.set_host_rshim(enabled).await
    }

    async fn get_host_rshim(&self) -> Result<Option<EnabledDisabled>, RedfishError> {
        self.s.get_host_rshim().await
    }

    async fn set_idrac_lockdown(&self, enabled: EnabledDisabled) -> Result<(), RedfishError> {
        self.s.set_idrac_lockdown(enabled).await
    }

    async fn get_boss_controller(&self) -> Result<Option<String>, RedfishError> {
        self.s.get_boss_controller().await
    }

    async fn decommission_storage_controller(
        &self,
        controller_id: &str,
    ) -> Result<Option<String>, RedfishError> {
        self.s.decommission_storage_controller(controller_id).await
    }

    async fn create_storage_volume(
        &self,
        controller_id: &str,
        volume_name: &str,
        raid_type: &str,
    ) -> Result<Option<String>, RedfishError> {
        self.s
            .create_storage_volume(controller_id, volume_name, raid_type)
            .await
    }

    async fn get_component_integrities(&self) -> Result<ComponentIntegrities, RedfishError> {
        self.s.get_component_integrities().await
    }

    async fn get_firmware_for_component(
        &self,
        component_integrity_id: &str,
    ) -> Result<SoftwareInventory, RedfishError> {
        self.s
            .get_firmware_for_component(component_integrity_id)
            .await
    }

    async fn get_component_ca_certificate(
        &self,
        url: &str,
    ) -> Result<crate::model::component_integrity::CaCertificate, RedfishError> {
        self.s.get_component_ca_certificate(url).await
    }

    async fn trigger_evidence_collection(
        &self,
        url: &str,
        nonce: &str,
    ) -> Result<Task, RedfishError> {
        self.s.trigger_evidence_collection(url, nonce).await
    }

    async fn get_evidence(
        &self,
        url: &str,
    ) -> Result<crate::model::component_integrity::Evidence, RedfishError> {
        self.s.get_evidence(url).await
    }

    async fn set_host_privilege_level(&self, level: HostPrivilegeLevel) -> Result<(), RedfishError> {
        self.s.set_host_privilege_level(level).await
    }

    /// AMI doesn't support AC power cycle through standard power action
    fn ac_powercycle_supported_by_power(&self) -> bool {
        false
    }

    async fn set_utc_timezone(&self) -> Result<(), RedfishError> {
        self.s.set_utc_timezone().await
    }
}

impl Bmc {
    /// AMI requires patching to /Systems/{id} (NOT /SD) with If-Match header
    async fn set_boot_override(
        &self,
        override_target: BootSourceOverrideTarget,
        override_enabled: BootSourceOverrideEnabled,
    ) -> Result<(), RedfishError> {
        let boot_data = HashMap::from([
            ("BootSourceOverrideMode".to_string(), "UEFI".to_string()),
            (
                "BootSourceOverrideEnabled".to_string(),
                override_enabled.to_string(),
            ),
            (
                "BootSourceOverrideTarget".to_string(),
                override_target.to_string(),
            ),
        ]);
        let data = HashMap::from([("Boot", boot_data)]);
        let url = format!("Systems/{}", self.s.system_id());
        self.s.client.patch_with_if_match(&url, data).await
    }

    /// Get expected and actual first boot option for checking boot order setup.
    ///
    /// AMI boot option format example:
    /// DisplayName: "[Slot2]UEFI: HTTP IPv4 Nvidia Network Adapter - B8:E9:24:17:6D:72 P1"
    /// BootOptionReference: "Boot0001"
    ///
    async fn get_expected_and_actual_first_boot_option(
        &self,
        boot_interface_mac: &str,
    ) -> Result<(Option<String>, Option<String>), RedfishError> {
        let mac = boot_interface_mac.to_uppercase();
        let system = self.get_system().await?;

        let boot_options_id =
            system
                .boot
                .boot_options
                .clone()
                .ok_or_else(|| RedfishError::MissingKey {
                    key: "boot.boot_options".to_string(),
                    url: system.odata.odata_id.clone(),
                })?;

        let all_boot_options: Vec<BootOption> = self
            .get_collection(boot_options_id)
            .await
            .and_then(|c| c.try_get::<BootOption>())?
            .members;

        // Find expected boot option display name (HTTP IPv4 with matching MAC)
        let expected_first_boot_option = all_boot_options
            .iter()
            .find(|opt| {
                let display = opt.display_name.to_uppercase();
                display.contains("HTTP") && display.contains("IPV4") && display.contains(&mac)
            })
            .map(|opt| opt.display_name.clone());

        let actual_first_boot_option = system
            .boot
            .boot_order
            .first()
            .and_then(|first_ref| {
                all_boot_options
                    .iter()
                    .find(|opt| &opt.boot_option_reference == first_ref)
                    .map(|opt| opt.display_name.clone())
            });

        Ok((expected_first_boot_option, actual_first_boot_option))
    }

    /// Get the BIOS attributes for machine setup.
    fn machine_setup_attrs(&self) -> HashMap<String, serde_json::Value> {
        HashMap::from([
            ("VMXEN".to_string(), "Enable".into()),        // VMX (Intel Virtualization)
            ("PCIS007".to_string(), "Enabled".into()),     // SR-IOV Support
            ("NWSK000".to_string(), "Enabled".into()),     // Network Stack
            ("NWSK001".to_string(), "Disabled".into()),    // IPv4 PXE Support
            ("NWSK006".to_string(), "Enabled".into()),     // IPv4 HTTP Support
            ("NWSK002".to_string(), "Disabled".into()),    // IPv6 PXE Support
            ("NWSK007".to_string(), "Disabled".into()),    // IPv6 HTTP Support
            ("FBO001".to_string(), "UEFI".into()),         // Boot Mode Select
            ("EndlessBoot".to_string(), "Enabled".into()), // Infinite Boot
        ])
    }

    /// Check BIOS/BMC attributes against expected values for machine setup status.
    async fn diff_bios_bmc_attr(&self) -> Result<Vec<MachineSetupDiff>, RedfishError> {
        let mut diffs = vec![];

        // Check serial console status
        let sc = self.serial_console_status().await?;
        if !sc.is_fully_enabled() {
            diffs.push(MachineSetupDiff {
                key: "serial_console".to_string(),
                expected: "Enabled".to_string(),
                actual: sc.status.to_string(),
            });
        }

        // Check BIOS attributes
        let bios = self.s.bios_attributes().await?;
        let expected_attrs = self.machine_setup_attrs();

        for (key, expected) in expected_attrs {
            let Some(actual) = bios.get(&key) else {
                diffs.push(MachineSetupDiff {
                    key: key.to_string(),
                    expected: expected.to_string(),
                    actual: "_missing_".to_string(),
                });
                continue;
            };
            let act = actual.as_str().unwrap_or(&actual.to_string()).to_string();
            let exp = expected.as_str().unwrap_or(&expected.to_string()).to_string();
            if act != exp {
                diffs.push(MachineSetupDiff {
                    key: key.to_string(),
                    expected: exp,
                    actual: act,
                });
            }
        }

        Ok(diffs)
    }
}