nv-redfish 0.7.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
// 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::bmc_quirks::BmcQuirks;
use crate::entity_link::FromLink;
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::JsonValue;
use crate::patch_support::Payload;
use crate::patch_support::ReadPatchFn;
use crate::schema::chassis::Chassis as ChassisSchema;
use crate::Error;
use crate::NvBmc;
use crate::Resource;
use crate::ResourceSchema;
use nv_redfish_core::bmc::Bmc;
use nv_redfish_core::NavProperty;
use std::future::Future;
use std::sync::Arc;

#[cfg(feature = "assembly")]
use crate::assembly::Assembly;
#[cfg(feature = "network-adapters")]
use crate::chassis::NetworkAdapter;
#[cfg(feature = "network-adapters")]
use crate::chassis::NetworkAdapterCollection;
#[cfg(feature = "power")]
use crate::chassis::Power;
#[cfg(feature = "power-supplies")]
use crate::chassis::PowerSupply;
#[cfg(feature = "thermal")]
use crate::chassis::Thermal;
#[cfg(feature = "log-services")]
use crate::log_service::LogService;
#[cfg(all(feature = "oem-liteon", feature = "power-supplies"))]
use crate::oem::liteon;
#[cfg(feature = "oem-nvidia-baseboard")]
use crate::oem::nvidia::baseboard::NvidiaCbcChassis;
#[cfg(feature = "pcie-devices")]
use crate::pcie_device::PcieDeviceCollection;
#[cfg(feature = "sensors")]
use crate::schema::sensor::Sensor as SchemaSensor;
#[cfg(feature = "sensors")]
use crate::sensor::extract_environment_sensors;
#[cfg(feature = "sensors")]
use crate::sensor::SensorLink;
#[cfg(feature = "oem-nvidia-baseboard")]
use std::convert::identity;

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

/// Chassis manufacturer.
pub type Manufacturer<T> = HardwareIdManufacturer<T, ChassisTag>;

/// Chassis model.
pub type Model<T> = HardwareIdModel<T, ChassisTag>;

/// Chassis part number.
pub type PartNumber<T> = HardwareIdPartNumber<T, ChassisTag>;

/// Chassis serial number.
pub type SerialNumber<T> = HardwareIdSerialNumber<T, ChassisTag>;

pub struct Config {
    pub read_patch_fn: Option<ReadPatchFn>,
}

impl Config {
    pub fn new(quirks: &BmcQuirks) -> Self {
        let mut patches = Vec::new();
        if quirks.bug_invalid_contained_by_fields() {
            patches.push(remove_invalid_contained_by_fields as fn(JsonValue) -> JsonValue);
        }
        if quirks.bug_missing_chassis_type_field() {
            patches.push(add_default_chassis_type);
        }
        if quirks.bug_missing_chassis_name_field() {
            patches.push(add_default_chassis_name);
        }
        let read_patch_fn = (!patches.is_empty())
            .then(|| Arc::new(move |v| patches.iter().fold(v, |acc, f| f(acc))) as ReadPatchFn);
        Self { read_patch_fn }
    }
}

/// Represents a chassis in the BMC.
///
/// Provides access to chassis information and sub-resources such as power supplies.
pub struct Chassis<B: Bmc> {
    #[allow(dead_code)] // used if any feature enabled.
    bmc: NvBmc<B>,
    data: Arc<ChassisSchema>,
    #[allow(dead_code)] // used when assembly feature enabled.
    config: Arc<Config>,
}

impl<B: Bmc> Chassis<B> {
    /// Create a new chassis handle.
    pub(crate) async fn new(
        bmc: &NvBmc<B>,
        nav: &NavProperty<ChassisSchema>,
    ) -> Result<Self, Error<B>> {
        let config = Config::new(&bmc.quirks);
        if let Some(read_patch_fn) = &config.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,
            config: config.into(),
        })
    }

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

    /// Get hardware identifier of the network adpater.
    #[must_use]
    pub fn hardware_id(&self) -> HardwareIdRef<'_, ChassisTag> {
        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),
        }
    }

    /// Get assembly of this chassis
    ///
    /// Returns `Ok(None)` when the assembly link is absent.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching assembly data fails.
    #[cfg(feature = "assembly")]
    pub async fn assembly(&self) -> Result<Option<Assembly<B>>, Error<B>> {
        if let Some(assembly_ref) = &self.data.assembly {
            Assembly::new(&self.bmc, assembly_ref).await.map(Some)
        } else {
            Ok(None)
        }
    }

    /// Get power supplies from this chassis.
    ///
    /// Attempts to fetch power supplies from `PowerSubsystem` (modern API)
    /// with fallback to Power resource (deprecated API).
    ///
    /// # Errors
    ///
    /// Returns an error if fetching power supply data fails.
    #[cfg(feature = "power-supplies")]
    pub async fn power_supplies(&self) -> Result<Vec<PowerSupply<B>>, Error<B>> {
        if let Some(ps) = &self.data.power_subsystem {
            let ps = ps.get(self.bmc.as_ref()).await.map_err(Error::Bmc)?;
            if let Some(supplies) = &ps.power_supplies {
                let supplies = &self.bmc.expand_property(supplies).await?.members;
                let mut power_supplies = Vec::with_capacity(supplies.len());
                for power_supply in supplies {
                    power_supplies.push(PowerSupply::new(&self.bmc, power_supply).await?);
                }
                return Ok(power_supplies);
            }
        }

        Ok(Vec::new())
    }

    /// Get LiteOn OEM power supplies from this chassis.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching power supply data fails.
    #[cfg(all(feature = "oem-liteon", feature = "power-supplies"))]
    pub async fn oem_liteon_power_supply_links(
        &self,
    ) -> Result<Option<Vec<liteon::power_supply::LiteonPowerSupplyLink<B>>>, Error<B>> {
        liteon::power_supply::chassis_fetch_links(&self.bmc, self).await
    }

    /// Get legacy Power resource (for older BMCs).
    ///
    /// Returns the deprecated `Chassis/Power` resource if available.
    /// For modern BMCs, prefer using direct sensor links via `HasSensors`
    /// or the modern `PowerSubsystem` API.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching power data fails.
    #[cfg(feature = "power")]
    pub async fn power(&self) -> Result<Option<Power<B>>, Error<B>> {
        if let Some(power_ref) = &self.data.power {
            Ok(Some(Power::new(&self.bmc, power_ref).await?))
        } else {
            Ok(None)
        }
    }

    /// Get legacy Thermal resource (for older BMCs).
    ///
    /// Returns the deprecated `Chassis/Thermal` resource if available.
    /// For modern BMCs, prefer using direct sensor links via `HasSensors`
    /// or the modern `ThermalSubsystem` API.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching thermal data fails.
    #[cfg(feature = "thermal")]
    pub async fn thermal(&self) -> Result<Option<Thermal<B>>, Error<B>> {
        if let Some(thermal_ref) = &self.data.thermal {
            Thermal::new(&self.bmc, thermal_ref).await.map(Some)
        } else {
            Ok(None)
        }
    }

    /// Get network adapter resources
    ///
    /// Returns the `Chassis/NetworkAdapter` resources if available, and `Ok(None)` when
    /// the network adapters link is absent.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching network adapters data fails.
    #[cfg(feature = "network-adapters")]
    pub async fn network_adapters(&self) -> Result<Option<Vec<NetworkAdapter<B>>>, Error<B>> {
        if let Some(network_adapters_collection_ref) = &self.data.network_adapters {
            NetworkAdapterCollection::new(&self.bmc, network_adapters_collection_ref)
                .await?
                .members()
                .await
                .map(Some)
        } else {
            Ok(None)
        }
    }

    /// Get log services for this chassis.
    ///
    /// 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 the environment sensors for this chassis.
    ///
    /// Returns a vector of `Sensor<B>` obtained from environment metrics, if available.
    ///
    /// # Errors
    ///
    /// Returns an error if get of environment metrics failed.
    #[cfg(feature = "sensors")]
    pub async fn environment_sensor_links(&self) -> Result<Vec<SensorLink<B>>, Error<B>> {
        let sensor_refs = if let Some(env_ref) = &self.data.environment_metrics {
            extract_environment_sensors(env_ref, self.bmc.as_ref()).await?
        } else {
            Vec::new()
        };

        Ok(sensor_refs
            .into_iter()
            .map(|r| SensorLink::new(&self.bmc, r))
            .collect())
    }

    /// Get the sensors collection for this chassis.
    ///
    /// Returns all available sensors associated with the chassis, and `Ok(None)`
    /// when the sensors link is absent.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching sensors data fails.
    #[cfg(feature = "sensors")]
    pub async fn sensor_links(&self) -> Result<Option<Vec<SensorLink<B>>>, Error<B>> {
        if let Some(sensors_collection) = &self.data.sensors {
            let sc = sensors_collection
                .get(self.bmc.as_ref())
                .await
                .map_err(Error::Bmc)?;
            let mut sensor_data = Vec::with_capacity(sc.members.len());
            for sensor in &sc.members {
                sensor_data.push(SensorLink::new(
                    &self.bmc,
                    NavProperty::<SchemaSensor>::new_reference(sensor.id().clone()),
                ));
            }
            Ok(Some(sensor_data))
        } else {
            Ok(None)
        }
    }

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

    /// NVIDIA Bluefield OEM extension
    ///
    /// Returns `Ok(None)` when the chassis does not include NVIDIA OEM extension data.
    ///
    /// # Errors
    ///
    /// Returns an error if NVIDIA OEM data parsing fails.
    #[cfg(feature = "oem-nvidia-baseboard")]
    pub fn oem_nvidia_baseboard_cbc(&self) -> Result<Option<NvidiaCbcChassis<B>>, Error<B>> {
        self.data
            .base
            .base
            .oem
            .as_ref()
            .map(NvidiaCbcChassis::new)
            .transpose()
            .map(|v| v.and_then(identity))
    }
}

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

impl<B: Bmc> FromLink<B> for Chassis<B> {
    type Schema = ChassisSchema;

    fn from_link(
        bmc: &NvBmc<B>,
        nav: &NavProperty<Self::Schema>,
    ) -> impl Future<Output = Result<Self, Error<B>>> + Send {
        Self::new(bmc, nav)
    }
}

fn remove_invalid_contained_by_fields(mut v: JsonValue) -> JsonValue {
    if let JsonValue::Object(ref mut obj) = v {
        if let Some(JsonValue::Object(ref mut links_obj)) = obj.get_mut("Links") {
            if let Some(JsonValue::Object(ref mut contained_by_obj)) =
                links_obj.get_mut("ContainedBy")
            {
                contained_by_obj.retain(|k, _| k == "@odata.id");
            }
        }
    }
    v
}

fn add_default_chassis_type(v: JsonValue) -> JsonValue {
    if let JsonValue::Object(mut obj) = v {
        obj.entry("ChassisType")
            .or_insert(JsonValue::String("Other".into()));
        JsonValue::Object(obj)
    } else {
        v
    }
}

fn add_default_chassis_name(v: JsonValue) -> JsonValue {
    if let JsonValue::Object(mut obj) = v {
        obj.entry("Name")
            .or_insert(JsonValue::String("Unnamed chassis".into()));
        JsonValue::Object(obj)
    } else {
        v
    }
}