nv-redfish 0.5.0

Rust implementation of Redfish API for BMC management
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
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::core::Bmc;
use crate::core::EntityTypeRef as _;
use crate::core::ModificationResponse;
use crate::core::NavProperty;
use crate::core::RedfishSettings as _;
use crate::hardware_id::HardwareIdRef;
use crate::hardware_id::Manufacturer as HardwareIdManufacturer;
use crate::hardware_id::Model as HardwareIdModel;
use crate::hardware_id::PartNumber as HardwareIdPartNumber;
use crate::hardware_id::SerialNumber as HardwareIdSerialNumber;
use crate::patch_support::Payload;
use crate::patch_support::ReadPatchFn;
use crate::resource::PowerState;
use crate::schema::redfish::computer_system::ComputerSystem as ComputerSystemSchema;
use crate::Error;
use crate::NvBmc;
use crate::Resource;
use crate::ResourceSchema;

use serde::Serialize;
use std::convert::identity;
use std::sync::Arc;
use tagged_types::TaggedType;

#[cfg(feature = "bios")]
use crate::computer_system::Bios;
#[cfg(feature = "boot-options")]
use crate::computer_system::BootOptionCollection;
#[cfg(feature = "memory")]
use crate::computer_system::Memory;
#[cfg(feature = "processors")]
use crate::computer_system::Processor;
#[cfg(feature = "secure-boot")]
use crate::computer_system::SecureBoot;
#[cfg(feature = "storages")]
use crate::computer_system::Storage;
#[cfg(feature = "ethernet-interfaces")]
use crate::ethernet_interface::EthernetInterfaceCollection;
#[cfg(feature = "log-services")]
use crate::log_service::LogService;
#[cfg(feature = "oem-lenovo")]
use crate::oem::lenovo::computer_system::LenovoComputerSystem;
#[cfg(feature = "oem-nvidia-bluefield")]
use crate::oem::nvidia::bluefield::nvidia_computer_system::NvidiaComputerSystem;

#[doc(hidden)]
pub enum ComputerSystemTag {}

/// Computer system manufacturer.
pub type Manufacturer<T> = HardwareIdManufacturer<T, ComputerSystemTag>;

/// Computer system model.
pub type Model<T> = HardwareIdModel<T, ComputerSystemTag>;

/// Computer system part number.
pub type PartNumber<T> = HardwareIdPartNumber<T, ComputerSystemTag>;

/// Computer system serial number.
pub type SerialNumber<T> = HardwareIdSerialNumber<T, ComputerSystemTag>;

/// Computer system SKU.
pub type Sku<T> = TaggedType<T, ComputerSystemSkuTag>;
#[doc(hidden)]
#[derive(tagged_types::Tag)]
#[implement(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[transparent(Debug, Display, FromStr, Serialize, Deserialize)]
#[capability(inner_access, cloned)]
pub enum ComputerSystemSkuTag {}

/// `BootOptionReference` type represent boot order of the `ComputerSystem`.
pub type BootOptionReference<T> = TaggedType<T, BootOptionReferenceTag>;
#[doc(hidden)]
#[derive(tagged_types::Tag)]
#[implement(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[transparent(Debug, Display, FromStr, Serialize, Deserialize)]
#[capability(inner_access, cloned)]
pub enum BootOptionReferenceTag {}

#[derive(Serialize)]
struct BootPatch {
    #[serde(rename = "BootOrder")]
    boot_order: Vec<BootOptionReference<String>>,
}

#[derive(Serialize)]
struct ComputerSystemBootOrderUpdate {
    #[serde(rename = "Boot")]
    boot: BootPatch,
}

/// Represents a computer system in the BMC.
///
/// Provides access to system information and sub-resources such as processors.
pub struct ComputerSystem<B: Bmc> {
    #[allow(dead_code)] // feature-enabled...
    bmc: NvBmc<B>,
    data: Arc<ComputerSystemSchema>,
}

impl<B: Bmc> ComputerSystem<B> {
    /// Create a new computer system handle.
    pub(crate) async fn new(
        bmc: &NvBmc<B>,
        nav: &NavProperty<ComputerSystemSchema>,
        read_patch_fn: Option<&ReadPatchFn>,
    ) -> Result<Self, Error<B>> {
        if let Some(read_patch_fn) = read_patch_fn {
            Payload::get(bmc.as_ref(), nav, read_patch_fn.as_ref()).await
        } else {
            nav.get(bmc.as_ref()).await.map_err(Error::Bmc)
        }
        .map(|data| Self {
            bmc: bmc.clone(),
            data,
        })
    }

    /// Get the raw schema data for this computer system.
    ///
    /// Returns an `Arc` to the underlying schema, allowing cheap cloning
    /// and sharing of the data.
    #[must_use]
    pub fn raw(&self) -> Arc<ComputerSystemSchema> {
        self.data.clone()
    }

    /// Get hardware identifier of the network adpater.
    #[must_use]
    pub fn hardware_id(&self) -> HardwareIdRef<'_, ComputerSystemTag> {
        HardwareIdRef {
            manufacturer: self
                .data
                .manufacturer
                .as_ref()
                .and_then(Option::as_deref)
                .map(Manufacturer::new),
            model: self
                .data
                .model
                .as_ref()
                .and_then(Option::as_deref)
                .map(Model::new),
            part_number: self
                .data
                .part_number
                .as_ref()
                .and_then(Option::as_deref)
                .map(PartNumber::new),
            serial_number: self
                .data
                .serial_number
                .as_ref()
                .and_then(Option::as_deref)
                .map(SerialNumber::new),
        }
    }

    /// The manufacturer SKU for this system.
    #[must_use]
    pub fn sku(&self) -> Option<Sku<&str>> {
        self.data
            .sku
            .as_ref()
            .and_then(Option::as_ref)
            .map(String::as_str)
            .map(Sku::new)
    }

    /// Power state of this system.
    #[must_use]
    pub fn power_state(&self) -> Option<PowerState> {
        self.data.power_state.and_then(identity)
    }

    /// An array of `BootOptionReference` strings that represent the persistent boot order for with this
    /// computer system.
    #[must_use]
    pub fn boot_order(&self) -> Option<Vec<BootOptionReference<&str>>> {
        self.data
            .as_ref()
            .boot
            .as_ref()
            .and_then(|boot| boot.boot_order.as_ref().and_then(Option::as_ref))
            .map(|v| {
                v.iter()
                    .map(String::as_str)
                    .map(BootOptionReference::new)
                    .collect::<Vec<_>>()
            })
    }

    /// Update the persistent boot order for this computer system.
    ///
    /// # Errors
    ///
    /// Returns an error if updating the system fails.
    pub async fn set_boot_order(
        &self,
        boot_order: Vec<BootOptionReference<String>>,
    ) -> Result<Option<Self>, Error<B>> {
        let update = ComputerSystemBootOrderUpdate {
            boot: BootPatch { boot_order },
        };

        let settings = self.data.settings_object();

        let update_odata = settings
            .as_ref()
            .map_or_else(|| self.data.odata_id(), |settings| settings.odata_id());

        match self
            .bmc
            .as_ref()
            .update::<_, NavProperty<ComputerSystemSchema>>(update_odata, None, &update)
            .await
            .map_err(Error::Bmc)?
        {
            ModificationResponse::Entity(nav) => {
                let data = nav.get(self.bmc.as_ref()).await.map_err(Error::Bmc)?;
                Ok(Some(Self {
                    bmc: self.bmc.clone(),
                    data,
                }))
            }
            ModificationResponse::Task(_) | ModificationResponse::Empty => Ok(None),
        }
    }

    /// Bios associated with this system.
    ///
    /// Fetches the BIOS settings. Returns `Ok(None)` when the BIOS link is absent.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching BIOS data fails.
    #[cfg(feature = "bios")]
    pub async fn bios(&self) -> Result<Option<Bios<B>>, Error<B>> {
        if let Some(bios_ref) = &self.data.bios {
            Bios::new(&self.bmc, bios_ref).await.map(Some)
        } else {
            Ok(None)
        }
    }

    /// Get processors associated with this system.
    ///
    /// Fetches the processor collection and returns a list of [`Processor`] handles.
    /// Returns `Ok(None)` when the processors link is absent.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching processor data fails.
    #[cfg(feature = "processors")]
    pub async fn processors(&self) -> Result<Option<Vec<Processor<B>>>, Error<B>> {
        if let Some(processors_ref) = &self.data.processors {
            let processors_collection = self.bmc.expand_property(processors_ref).await?;

            let mut processors = Vec::new();
            for m in &processors_collection.members {
                processors.push(Processor::new(&self.bmc, m).await?);
            }

            Ok(Some(processors))
        } else {
            Ok(None)
        }
    }

    /// Get secure boot resource associated with this system.
    ///
    /// Returns `Ok(None)` when the secure boot link is absent.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching secure boot data fails.
    #[cfg(feature = "secure-boot")]
    pub async fn secure_boot(&self) -> Result<Option<SecureBoot<B>>, Error<B>> {
        if let Some(secure_boot_ref) = &self.data.secure_boot {
            SecureBoot::new(&self.bmc, secure_boot_ref).await.map(Some)
        } else {
            Ok(None)
        }
    }

    /// Get storage controllers associated with this system.
    ///
    /// Fetches the storage collection and returns a list of [`Storage`] handles.
    /// Returns `Ok(None)` when the storage link is absent.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching storage data fails.
    #[cfg(feature = "storages")]
    pub async fn storage_controllers(&self) -> Result<Option<Vec<Storage<B>>>, Error<B>> {
        if let Some(storage_ref) = &self.data.storage {
            let storage_collection = self.bmc.expand_property(storage_ref).await?;

            let mut storage_controllers = Vec::new();
            for m in &storage_collection.members {
                storage_controllers.push(Storage::new(&self.bmc, m).await?);
            }

            Ok(Some(storage_controllers))
        } else {
            Ok(None)
        }
    }

    /// Get memory modules associated with this system.
    ///
    /// Fetches the memory collection and returns a list of [`Memory`] handles.
    /// Returns `Ok(None)` when the memory link is absent.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching memory data fails.
    #[cfg(feature = "memory")]
    pub async fn memory_modules(&self) -> Result<Option<Vec<Memory<B>>>, Error<B>> {
        if let Some(memory_ref) = &self.data.memory {
            let memory_collection = self.bmc.expand_property(memory_ref).await?;

            let mut memory_modules = Vec::new();
            for m in &memory_collection.members {
                memory_modules.push(Memory::new(&self.bmc, m).await?);
            }

            Ok(Some(memory_modules))
        } else {
            Ok(None)
        }
    }

    /// Get log services for this computer system.
    ///
    /// Returns `Ok(None)` when the log services link is absent.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching log service data fails.
    #[cfg(feature = "log-services")]
    pub async fn log_services(&self) -> Result<Option<Vec<LogService<B>>>, Error<B>> {
        if let Some(log_services_ref) = &self.data.log_services {
            let log_services_collection = log_services_ref
                .get(self.bmc.as_ref())
                .await
                .map_err(Error::Bmc)?;

            let mut log_services = Vec::new();
            for m in &log_services_collection.members {
                log_services.push(LogService::new(&self.bmc, m).await?);
            }

            Ok(Some(log_services))
        } else {
            Ok(None)
        }
    }

    /// Get ethernet interfaces for this computer system.
    ///
    /// Returns `Ok(None)` when the ethernet interfaces link is absent.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching ethernet interface data fails.
    #[cfg(feature = "ethernet-interfaces")]
    pub async fn ethernet_interfaces(
        &self,
    ) -> Result<Option<EthernetInterfaceCollection<B>>, Error<B>> {
        if let Some(p) = &self.data.ethernet_interfaces {
            EthernetInterfaceCollection::new(&self.bmc, p)
                .await
                .map(Some)
        } else {
            Ok(None)
        }
    }

    /// Get collection of the UEFI boot options associated with this computer system.
    ///
    /// Returns `Ok(None)` when boot options are not exposed.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching boot options data fails.
    #[cfg(feature = "boot-options")]
    pub async fn boot_options(&self) -> Result<Option<BootOptionCollection<B>>, Error<B>> {
        if let Some(p) = &self
            .data
            .boot
            .as_ref()
            .and_then(|v| v.boot_options.as_ref())
        {
            BootOptionCollection::new(&self.bmc, p).await.map(Some)
        } else {
            Ok(None)
        }
    }

    /// NVIDIA Bluefield OEM extension
    ///
    /// Returns `Ok(None)` when the system does not include NVIDIA OEM extension data.
    ///
    /// # Errors
    ///
    /// Returns an error if NVIDIA OEM data parsing/fetching fails.
    #[cfg(feature = "oem-nvidia-bluefield")]
    pub async fn oem_nvidia_bluefield(&self) -> Result<Option<NvidiaComputerSystem<B>>, Error<B>> {
        if let Some(oem) = self.data.base.base.oem.as_ref() {
            NvidiaComputerSystem::new(&self.bmc, oem).await
        } else {
            Ok(None)
        }
    }

    /// Lenovo OEM extension
    ///
    /// Returns `Ok(None)` when the system does not include Lenovo OEM extension data.
    ///
    /// # Errors
    ///
    /// Returns an error if Lenovo OEM data parsing fails.
    #[cfg(feature = "oem-lenovo")]
    pub fn oem_lenovo(&self) -> Result<Option<LenovoComputerSystem<B>>, Error<B>> {
        LenovoComputerSystem::new(&self.bmc, &self.data)
    }
}

impl<B: Bmc> Resource for ComputerSystem<B> {
    fn resource_ref(&self) -> &ResourceSchema {
        &self.data.as_ref().base
    }
}