forked from NVIDIA/ncx-infra-controller-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
2904 lines (2618 loc) · 105 KB
/
mod.rs
File metadata and controls
2904 lines (2618 loc) · 105 KB
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
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 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 std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::fmt::Display;
use std::net::{IpAddr, SocketAddr};
use std::ops::Deref;
use ::rpc::errors::RpcDataConversionError;
use base64::prelude::*;
use carbide_uuid::domain::DomainId;
use carbide_uuid::instance_type::InstanceTypeId;
use carbide_uuid::machine::{MachineId, MachineInterfaceId, MachineType};
use carbide_uuid::network::NetworkSegmentId;
use carbide_uuid::power_shelf::PowerShelfId;
use carbide_uuid::switch::SwitchId;
use chrono::{DateTime, Duration, Utc};
use config_version::{ConfigVersion, Versioned};
use duration_str::deserialize_duration_chrono;
use health_report::HealthReport;
use json::MachineSnapshotPgJson;
use libredfish::{PowerState, SystemPowerControl};
use mac_address::MacAddress;
use rpc::forge::HealthOverrideOrigin;
use rpc::forge_agent_control_response::{Action, ForgeAgentControlExtraInfo};
use serde::{Deserialize, Serialize, Serializer};
use sqlx::postgres::PgRow;
use sqlx::{Column, FromRow, Row};
use strum_macros::EnumIter;
use self::infiniband::MachineInfinibandStatusObservation;
use self::network::{MachineNetworkStatusObservation, ManagedHostNetworkConfig};
use self::nvlink::MachineNvLinkStatusObservation;
use super::StateSla;
use super::bmc_info::BmcInfo;
use super::hardware_info::MachineInventory;
use super::instance::snapshot::InstanceSnapshot;
use super::instance::status::extension_service::InstanceExtensionServiceStatusObservation;
use super::instance::status::network::InstanceNetworkStatusObservation;
use super::metadata::Metadata;
use super::sku::SkuStatus;
use crate::controller_outcome::PersistentStateHandlerOutcome;
use crate::dpa_interface::DpaInterface;
use crate::errors::{ModelError, ModelResult};
use crate::firmware::FirmwareComponentType;
use crate::hardware_info::{HardwareInfo, MachineNvLinkInfo};
use crate::instance::config::network::DeviceLocator;
use crate::instance::snapshot::InstanceSnapshotPgJson;
use crate::machine::capabilities::MachineCapabilitiesSet;
use crate::machine::health_override::HealthReportOverrides;
use crate::machine_interface_address::InterfaceAssociationType;
use crate::network_segment::NetworkSegmentType;
use crate::power_manager::PowerOptions;
mod slas;
pub mod capabilities;
pub mod health_override;
pub mod infiniband;
pub mod json;
pub mod machine_id;
pub mod machine_search_config;
pub mod network;
pub mod nvlink;
pub mod topology;
pub mod upgrade_policy;
type DpuDeviceMappings = (HashMap<MachineId, String>, HashMap<String, Vec<MachineId>>);
pub fn get_display_ids(machines: &[Machine]) -> String {
machines
.iter()
.map(|x| x.id.to_string())
.collect::<Vec<String>>()
.join("/")
}
fn default_true() -> bool {
true
}
/// Represents the current state of `Machine`
#[derive(Debug, Clone)]
pub struct ManagedHostStateSnapshot {
pub host_snapshot: Machine,
pub dpu_snapshots: Vec<Machine>,
pub dpa_interface_snapshots: Vec<DpaInterface>,
/// If there is an instance provisioned on top of the machine, this holds
/// its state
pub instance: Option<InstanceSnapshot>,
pub managed_state: ManagedHostState,
/// Aggregated health. This is calculated based on the health of Hosts and DPUs
pub aggregate_health: health_report::HealthReport,
/// Health overrides inherited from the rack this host belongs to (if any).
/// Populated at read time; not stored on the machines table.
pub rack_health_overrides: Option<HealthReportOverrides>,
}
impl<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow> for ManagedHostStateSnapshot {
fn from_row(row: &'r sqlx::postgres::PgRow) -> Result<Self, sqlx::Error> {
#[derive(Deserialize)]
struct RackHealthOverrides {
json: HealthReportOverrides,
}
let host_snapshot: sqlx::types::Json<MachineSnapshotPgJson> =
row.try_get("host_snapshot")?;
let dpu_snapshots: sqlx::types::Json<Vec<Option<MachineSnapshotPgJson>>> =
row.try_get("dpu_snapshots")?;
let rack_health_overrides: sqlx::types::Json<Vec<Option<RackHealthOverrides>>> =
row.try_get("rack_health_overrides")?;
// We are setting dpa_interface_snapshots to an emtpy vector here.
// This will be filled by load_object_state later.
let dpa_interface_snapshots: Vec<DpaInterface> = Vec::new();
let mut instance: Option<InstanceSnapshot> =
if let Some(column) = row.columns().iter().find(|c| c.name() == "instance") {
let json: sqlx::types::Json<Option<InstanceSnapshotPgJson>> =
row.try_get(column.ordinal())?;
json.0.map(TryInto::try_into).transpose()?
} else {
None
};
let host_snapshot: Machine = host_snapshot.0.try_into()?;
let dpu_snapshots: Vec<Machine> = dpu_snapshots
.0
.into_iter()
.flatten()
.map(TryInto::try_into)
.collect::<Result<Vec<_>, _>>()?;
let rack_health_overrides = rack_health_overrides
.0
.into_iter()
.next()
.flatten()
.and_then(|overrides| {
let overrides = overrides.json;
if overrides.replace.is_some() || !overrides.merges.is_empty() {
Some(overrides)
} else {
None
}
});
// Instance network observation is fetched from dpu_snapshots.
if let Some(instance) = &mut instance {
instance.observations.network =
InstanceNetworkStatusObservation::aggregate_instance_observation(&dpu_snapshots);
instance.observations.extension_services =
InstanceExtensionServiceStatusObservation::aggregate_instance_observation(
&dpu_snapshots,
);
}
// TODO: consider dropping this field from ManagedHostStateSnapshot
let managed_state = host_snapshot.state.value.clone();
let mut result = Self {
host_snapshot,
dpu_snapshots,
dpa_interface_snapshots,
managed_state,
instance,
rack_health_overrides,
// This will need to be modified by callers, as its value depends on a
// HardwareHealthReportsConfig being specified.
aggregate_health: health_report::HealthReport::empty("".to_string()),
};
result.sort_dpu_snapshots()?;
Ok(result)
}
}
/// Reasons why a Machine is not allocatable
#[derive(thiserror::Error, Clone, PartialEq, Eq, Debug)]
pub enum NotAllocatableReason {
#[error("The Machine is in a state other than `Ready`: {0:?}")]
InvalidState(Box<ManagedHostState>),
#[error(
"The Machine has a pending instance creation request, that has not yet been processed by the state handler"
)]
PendingInstanceCreation,
#[error("There are no dpu_snapshots, but associated_dpu_machine_ids is non-empty")]
NoDpuSnapshots,
#[error("The Machine is in Maintenance Mode")]
MaintenanceMode,
#[error("A Health Alert prevents the Machine from being allocated: {0:?}")]
HealthAlert(Box<health_report::HealthProbeAlert>),
}
#[derive(Debug, thiserror::Error)]
pub enum ManagedHostStateSnapshotError {
#[error("Missing attached dpu id in primary interface. Machine id: {0}")]
AttachedDpuIdMissing(MachineId),
#[error("Missing dpu with primary dpu id. Machine id: {0}, DPU ID: {1}")]
MissingPrimaryDpu(MachineId, MachineId),
}
impl From<ManagedHostStateSnapshotError> for sqlx::Error {
fn from(value: ManagedHostStateSnapshotError) -> Self {
Self::Decode(Box::new(value))
}
}
impl ManagedHostStateSnapshot {
/// Returns `true` if override report is hw_health, `false` otherwise
fn merge_override_report_with_hw_health(
output: &mut HealthReport,
source: &str,
report: &mut HealthReport,
hardware_health_config: HardwareHealthReportsConfig,
) -> bool {
if HealthReportOverrides::is_hardware_health_override_source(source) {
match hardware_health_config {
HardwareHealthReportsConfig::Disabled => {}
HardwareHealthReportsConfig::MonitorOnly => {
for alert in &mut report.alerts {
alert.classifications.clear();
}
output.merge(report)
}
HardwareHealthReportsConfig::Enabled => output.merge(report),
}
true
} else {
output.merge(report);
false
}
}
/// Returns `Ok` if the Host can be used as an instance
///
/// This requires
/// - the Machine to be in `Ready` state
/// - the Machine has not yet been target of an instance creation request
/// - no health alerts which classification `PreventAllocations` to be set
/// - the machine not to be in Maintenance Mode
pub fn is_usable_as_instance(&self, allow_unhealthy: bool) -> Result<(), NotAllocatableReason> {
// TODO: allow other states than Ready when allow_unhealthy=true. Will require changes to state machine (see Matthias).
if !matches!(self.managed_state, ManagedHostState::Ready) {
return Err(NotAllocatableReason::InvalidState(Box::new(
self.managed_state.clone(),
)));
}
// A new instance can be created only in Ready state.
// This is possible that a instance is created by user, but still not picked by state machine.
// To avoid that race condition, need to check if db has any entry with given machine id.
if self.instance.is_some() {
return Err(NotAllocatableReason::PendingInstanceCreation);
}
if self.dpu_snapshots.is_empty()
&& !self.host_snapshot.associated_dpu_machine_ids().is_empty()
{
return Err(NotAllocatableReason::NoDpuSnapshots);
}
if !allow_unhealthy
&& let Some(alert) = self.aggregate_health.find_alert_by_classification(
&health_report::HealthAlertClassification::prevent_allocations(),
)
{
return Err(NotAllocatableReason::HealthAlert(Box::new(alert.clone())));
}
Ok(())
}
/// Derives the aggregate health of the Managed Host based on individual
/// health reports
pub fn derive_aggregate_health(&mut self, host_health_config: HostHealthConfig) {
// TODO: In the future we will also take machine-validation results into consideration
let source = "aggregate-host-health".to_string();
let observed_at = Some(chrono::Utc::now());
// If there is an [`OverrideMode::Replace`] health report override on
// the host, then use that. A host-level Replace takes full precedence,
// including over any rack-level overrides.
if let Some(mut over) = self.host_snapshot.health_report_overrides.replace.clone() {
over.source = source;
over.observed_at = observed_at;
self.aggregate_health = over;
return;
}
let mut output = health_report::HealthReport::empty("".to_string());
output.merge(&self.host_snapshot.machine_validation_health_report);
if let Some(sku_validation_health_report) =
self.host_snapshot.sku_validation_health_report.as_ref()
{
output.merge(sku_validation_health_report);
}
if let Some(report) = self.host_snapshot.site_explorer_health_report.as_ref() {
output.merge(report);
}
let merge_or_timeout =
|output: &mut HealthReport, input: &Option<HealthReport>, target: String| {
if let Some(input) = input {
output.merge(input);
} else {
output.merge(&HealthReport::heartbeat_timeout(
"".to_string(),
target,
"".to_string(),
));
}
};
let mut has_hardware_health = false;
// Merge DPU's alerts. If DPU alerts should be suppressed, than remove the classification from the
// alert so that metrics won't show a critical issue.
let suppress_dpu_alerts = self.managed_state.suppress_dpu_alerts();
for snapshot in self.dpu_snapshots.iter_mut() {
let health_report = if suppress_dpu_alerts {
let mut health_report = snapshot.dpu_agent_health_report.clone();
if let Some(health_report) = &mut health_report {
for alert in &mut health_report.alerts {
alert.classifications.clear();
}
}
health_report
} else {
snapshot.dpu_agent_health_report.clone()
};
if let Some(network_status_observation) = snapshot.network_status_observation.as_ref()
&& let Some(health_report) = network_status_observation
.expired_version_health_report(
host_health_config.dpu_agent_version_staleness_threshold,
host_health_config.prevent_allocations_on_stale_dpu_agent_version,
)
{
output.merge(&health_report);
}
merge_or_timeout(&mut output, &health_report, "forge-dpu-agent".to_string());
if let Some(report) = snapshot.site_explorer_health_report.as_ref() {
output.merge(report);
}
for (source, over) in snapshot.health_report_overrides.merges.iter_mut() {
let merged_hardware = Self::merge_override_report_with_hw_health(
&mut output,
source,
over,
host_health_config.hardware_health_reports,
);
has_hardware_health |= merged_hardware;
}
}
for (source, over) in self.host_snapshot.health_report_overrides.merges.iter_mut() {
let merged_hardware = Self::merge_override_report_with_hw_health(
&mut output,
source,
over,
host_health_config.hardware_health_reports,
);
has_hardware_health |= merged_hardware;
}
if host_health_config.hardware_health_reports == HardwareHealthReportsConfig::Enabled
&& !has_hardware_health
{
merge_or_timeout(&mut output, &None, "hardware-health".to_string());
}
if let Some(rack_overrides) = &self.rack_health_overrides {
if let Some(rack_replace) = &rack_overrides.replace {
output.merge(rack_replace);
}
for rack_merge in rack_overrides.merges.values() {
output.merge(rack_merge);
}
}
output.source = source;
output.observed_at = observed_at;
self.aggregate_health = output;
}
/// Creates an RPC Machine representation for either the Host or one of the DPUs
pub fn rpc_machine_state(
&self,
dpu_machine_id: Option<&MachineId>,
) -> Option<rpc::forge::Machine> {
match dpu_machine_id {
None => {
let mut rpc_machine: rpc::forge::Machine = self.host_snapshot.clone().into();
rpc_machine.health = Some(self.aggregate_health.clone().into());
Some(rpc_machine)
}
Some(dpu_machine_id) => {
let dpu_snapshot = self
.dpu_snapshots
.iter()
.find(|dpu| dpu.id == *dpu_machine_id)?;
let mut rpc_machine: rpc::forge::Machine = dpu_snapshot.clone().into();
// In case the DPU does not know the associated Host - we can backfill the data here
rpc_machine.associated_host_machine_id = Some(self.host_snapshot.id);
Some(rpc_machine)
}
}
}
/// Returns true if the desired managedhost networking configuration had been synced
/// to **all** DPUs.
pub fn managed_host_network_config_version_synced(&self) -> bool {
for dpu_snapshot in self.dpu_snapshots.iter() {
if !dpu_snapshot.managed_host_network_config_version_synced() {
return false;
}
}
true
}
/// Sort the DPUs by pci address and then make sure the primary DPU is the first.
pub fn sort_dpu_snapshots(&mut self) -> Result<(), ManagedHostStateSnapshotError> {
let mac_pci_map: HashMap<MacAddress, Option<&str>> = self
.host_snapshot
.hardware_info
.iter()
.flat_map(|hi| &hi.network_interfaces)
.map(|interface| {
(
interface.mac_address,
interface
.pci_properties
.as_ref()
.and_then(|pci| pci.slot.as_deref()),
)
})
.collect();
self.dpu_snapshots.sort_by(|lhs, rhs| {
let Some(lhs_dpu_mac) = lhs
.hardware_info
.as_ref()
.and_then(|hi| hi.dpu_info.as_ref())
.and_then(|di| di.factory_mac_address.parse().ok())
else {
return Ordering::Greater;
};
let Some(rhs_dpu_mac) = rhs
.hardware_info
.as_ref()
.and_then(|hi| hi.dpu_info.as_ref())
.and_then(|di| di.factory_mac_address.parse().ok())
else {
return Ordering::Less;
};
let lhs_pci_slot = mac_pci_map.get(&lhs_dpu_mac).unwrap_or(&None);
let rhs_pci_slot = mac_pci_map.get(&rhs_dpu_mac).unwrap_or(&None);
match (lhs_pci_slot, rhs_pci_slot) {
(Some(lhs_pci_slot), Some(rhs_pci_slot)) => lhs_pci_slot.cmp(rhs_pci_slot),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
}
});
let primary_dpu_id = self
.host_snapshot
.interfaces
.iter()
.find_map(|x| {
if x.primary_interface {
Some(x.attached_dpu_machine_id)
} else {
None
}
})
.flatten();
if let Some(primary_dpu_id) = primary_dpu_id {
let index = self
.dpu_snapshots
.iter()
.position(|x| x.id == primary_dpu_id)
.ok_or({
ManagedHostStateSnapshotError::MissingPrimaryDpu(
self.host_snapshot.id,
primary_dpu_id,
)
})?;
if index != 0 {
let snapshot = self.dpu_snapshots.remove(index);
self.dpu_snapshots.insert(0, snapshot);
}
} else if !self.dpu_snapshots.is_empty() {
// If it is not Zero-DPU case, return failure.
return Err(ManagedHostStateSnapshotError::AttachedDpuIdMissing(
self.host_snapshot.id,
));
};
Ok(())
}
}
impl TryFrom<ManagedHostStateSnapshot> for Option<rpc::Instance> {
type Error = RpcDataConversionError;
fn try_from(mut snapshot: ManagedHostStateSnapshot) -> Result<Self, Self::Error> {
let Some(instance) = snapshot.instance.take() else {
return Ok(None);
};
// TODO: If multiple DPUs have reprovisioning requested, we might not get
// the expected response
let mut reprovision_request = snapshot.host_snapshot.reprovision_requested.clone();
for dpu in &snapshot.dpu_snapshots {
if let Some(reprovision_requested) = dpu.reprovision_requested.as_ref() {
reprovision_request = Some(reprovision_requested.clone());
}
}
let (_, dpu_id_to_device_map) = snapshot
.host_snapshot
.get_dpu_device_and_id_mappings()
.map_err(|e| {
RpcDataConversionError::InvalidValue(
"dpu_id_to_device_map".to_string(),
e.to_string(),
)
})?;
let status = instance.derive_status(
dpu_id_to_device_map,
snapshot.managed_state.clone(),
reprovision_request,
snapshot
.host_snapshot
.infiniband_status_observation
.as_ref(),
snapshot.host_snapshot.nvlink_status_observation.as_ref(),
)?;
Ok(Some(rpc::Instance {
id: Some(instance.id),
machine_id: Some(instance.machine_id),
config: Some(instance.config.try_into()?),
status: Some(status.try_into()?),
config_version: instance.config_version.version_string(),
network_config_version: instance.network_config_version.version_string(),
ib_config_version: instance.ib_config_version.version_string(),
dpu_extension_service_version: instance
.extension_services_config_version
.version_string(),
instance_type_id: instance.instance_type_id.map(|i| i.to_string()),
metadata: Some(instance.metadata.into()),
tpm_ek_certificate: snapshot.host_snapshot.hardware_info.and_then(|hi| {
hi.tpm_ek_certificate
.map(|cert| BASE64_STANDARD.encode(cert.into_bytes()))
}),
nvlink_config_version: instance.nvlink_config_version.version_string(),
}))
}
}
/// Represents the last_reboot_requested data
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Eq, PartialEq)]
pub enum MachineLastRebootRequestedMode {
Reboot,
PowerOff,
PowerOn,
GracefulShutdown,
}
impl From<SystemPowerControl> for MachineLastRebootRequestedMode {
fn from(value: SystemPowerControl) -> Self {
match value {
SystemPowerControl::On => Self::PowerOn,
SystemPowerControl::GracefulShutdown => Self::PowerOff,
SystemPowerControl::ForceOff => Self::PowerOff,
SystemPowerControl::GracefulRestart => Self::Reboot,
SystemPowerControl::ForceRestart => Self::Reboot,
SystemPowerControl::ACPowercycle => Self::Reboot,
SystemPowerControl::PowerCycle => Self::Reboot,
}
}
}
impl Display for MachineLastRebootRequestedMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self, f)
}
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub struct MachineLastRebootRequested {
pub time: DateTime<Utc>,
pub mode: MachineLastRebootRequestedMode,
pub restart_verified: Option<bool>,
pub verification_attempts: Option<i32>,
}
impl Default for MachineLastRebootRequested {
fn default() -> Self {
MachineLastRebootRequested {
time: Default::default(),
mode: MachineLastRebootRequestedMode::Reboot,
restart_verified: None,
verification_attempts: None,
}
}
}
///
/// A machine is a standalone system that performs network booting via normal DHCP processes.
///
#[derive(Debug, Clone)]
pub struct Machine {
/// The ID of the machine, this is an internal identifier in the database that's unique for
/// all machines managed by this instance of carbide.
pub id: MachineId,
/// The current state of the machine.
pub state: Versioned<ManagedHostState>,
/// The current network state of the machine, excluding the tenant related
/// configuration. The latter will be tracked as part of the InstanceNetworkConfig.
pub network_config: Versioned<ManagedHostNetworkConfig>,
/// The most recent status forge-dpu-agent observed. Tells us if network_config has been
/// applied yet, and other useful things.
pub network_status_observation: Option<MachineNetworkStatusObservation>,
/// The most recent status of infiniband interfaces.
pub infiniband_status_observation: Option<MachineInfinibandStatusObservation>,
// The most recent status of the nvlink GPUs.
pub nvlink_status_observation: Option<MachineNvLinkStatusObservation>,
/// A list of [MachineStateHistory] that this machine has experienced
pub history: Vec<MachineStateHistory>,
/// A list of [MachineInterfaceSnapshot]s that this machine owns
pub interfaces: Vec<MachineInterfaceSnapshot>,
/// The Hardware information that was discovered for this machine
pub hardware_info: Option<HardwareInfo>,
/// The BMC info for this machine
pub bmc_info: BmcInfo,
/// Last time when machine came up.
pub last_reboot_time: Option<DateTime<Utc>>,
/// Last time when cleanup was performed successfully.
pub last_cleanup_time: Option<DateTime<Utc>>,
/// Last time when discovery finished.
pub last_discovery_time: Option<DateTime<Utc>>,
/// Last time when scout contacted the machine.
pub last_scout_contact_time: Option<DateTime<Utc>>,
/// Failure cause. If failure cause is critical, machine will move into Failed state.
pub failure_details: FailureDetails,
/// Last time when machine reprovision requested.
pub reprovision_requested: Option<ReprovisionRequest>,
/// Last time when host reprovision requested
pub host_reprovision_requested: Option<HostReprovisionRequest>,
/// Does the forge-dpu-agent on this DPU need upgrading?
pub dpu_agent_upgrade_requested: Option<UpgradeDecision>,
/// Latest health report received by forge-dpu-agent
pub dpu_agent_health_report: Option<HealthReport>,
/// Latest health report generated by validation tests
pub machine_validation_health_report: HealthReport,
/// Latest health report submitted by site-explorer
pub site_explorer_health_report: Option<HealthReport>,
/// All health report overrides
pub health_report_overrides: HealthReportOverrides,
// Inventory related to a DPU machine as reported by the agent there.
// Software and versions installed on the machine.
pub inventory: Option<MachineInventory>,
/// Last time when machine reboot was requested.
/// This field takes care of reboot requested from state machine only.
pub last_reboot_requested: Option<MachineLastRebootRequested>,
/// The result of the last attempt to change state
pub controller_state_outcome: Option<PersistentStateHandlerOutcome>,
// Is the bios password set on the machine
pub bios_password_set_time: Option<DateTime<Utc>>,
/// Last host validation finished.
pub last_machine_validation_time: Option<DateTime<Utc>>,
/// current discovery validation id.
pub discovery_machine_validation_id: Option<uuid::Uuid>,
/// current cleanup validation id.
pub cleanup_machine_validation_id: Option<uuid::Uuid>,
/// Override to enable or disable firmware auto update
pub firmware_autoupdate: Option<bool>,
/// current on demand validation id.
pub on_demand_machine_validation_id: Option<uuid::Uuid>,
pub on_demand_machine_validation_request: Option<bool>,
/// The InstanceType with which a machine is associated if any
pub instance_type_id: Option<InstanceTypeId>,
pub asn: Option<u32>,
/// Machine metadata
pub metadata: Metadata,
/// Version field that tracks changes to
/// - Metadata
pub version: ConfigVersion,
// Columns for these exist, but are unused in rust code
// /// When this machine record was created
// pub created: DateTime<Utc>,
// /// When the machine record was last modified
// pub updated: DateTime<Utc>,
// /// When the machine was last deployed
// pub deployed: Option<DateTime<Utc>>,
pub hw_sku: Option<String>,
pub hw_sku_status: Option<SkuStatus>,
pub sku_validation_health_report: Option<HealthReport>,
/// Host's power options.
pub power_options: Option<PowerOptions>,
/// The hardware SKU's device type
pub hw_sku_device_type: Option<String>,
/// If host upgrades have been completed since the last start explicit start request or actual start
pub update_complete: bool,
/// The NMX-M GPU info for this machine.
pub nvlink_info: Option<MachineNvLinkInfo>,
/// Whether the DPF is enabled for this machine
pub dpf: Dpf,
/// Timestamp when manual firmware upgrade was marked as completed
/// TEMPORARY: Used for workflow where manual upgrades are required before automatic ones
/// TODO: Remove after upgrade-through-scout is complete
pub manual_firmware_upgrade_completed: Option<DateTime<Utc>>,
}
// Dpf status field.
#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct Dpf {
// This field is copied from expected_machines.
pub enabled: bool,
// If dpf is used for ingestion.
pub used_for_ingestion: bool,
}
impl From<Machine> for ::rpc::forge::dpf_state_response::DpfState {
fn from(value: Machine) -> Self {
Self {
machine_id: value.id.into(),
enabled: value.dpf.enabled,
used_for_ingestion: value.dpf.used_for_ingestion,
}
}
}
// We need to implement FromRow because we can't associate dependent tables with the default derive
// (i.e. it can't default unknown fields)
impl<'r> FromRow<'r, PgRow> for Machine {
fn from_row(row: &'r PgRow) -> Result<Self, sqlx::Error> {
let json: serde_json::value::Value = row.try_get(0)?;
MachineSnapshotPgJson::deserialize(json)
.map_err(|err| sqlx::Error::Decode(err.into()))?
.try_into()
}
}
impl Machine {
/// Returns whether the Machine is a DPU, based on the HardwareInfo that
/// was available when the Machine was discovered
pub fn is_dpu(&self) -> bool {
self.id.machine_type().is_dpu()
}
pub fn bmc_vendor(&self) -> bmc_vendor::BMCVendor {
match self.hardware_info.as_ref() {
Some(hw) => hw.bmc_vendor(),
None => bmc_vendor::BMCVendor::Unknown,
}
}
pub fn use_admin_network(&self) -> bool {
self.network_config.use_admin_network.unwrap_or(true)
}
/// Does the forge-dpu-agent on this DPU need upgrading?
pub fn needs_agent_upgrade(&self) -> bool {
self.dpu_agent_upgrade_requested
.as_ref()
.map(|d| d.should_upgrade)
.unwrap_or(false)
}
/// Return the current state of the machine.
pub fn current_state(&self) -> &ManagedHostState {
&self.state.value
}
/// Return the current version of state of the machine.
pub fn current_version(&self) -> ConfigVersion {
self.state.version
}
pub fn loopback_ip(&self) -> Option<IpAddr> {
self.network_config.loopback_ip
}
/// Returns all associated DPU Machine IDs if this is Host Machine
pub fn associated_dpu_machine_ids(&self) -> Vec<MachineId> {
if self.is_dpu() {
return Vec::new();
}
self.interfaces
.iter()
.filter_map(|i| i.attached_dpu_machine_id)
.collect::<Vec<MachineId>>()
}
pub fn bmc_addr(&self) -> Option<SocketAddr> {
self.bmc_info
.ip
.as_ref()
.and_then(|ip| ip.parse().ok())
.map(|ip| SocketAddr::new(ip, self.bmc_info.port.unwrap_or(443)))
}
/// If this machine is a DPU, then this returns whether the desired ManagedHost
/// network configuration had been applied by forge-dpu-agent
pub fn managed_host_network_config_version_synced(&self) -> bool {
let dpu_expected_version = self.network_config.version;
let dpu_observation = self.network_status_observation.as_ref();
let dpu_observed_version: ConfigVersion = match dpu_observation {
None => {
return false;
}
Some(network_status) => match network_status.network_config_version {
None => {
return false;
}
Some(version) => version,
},
};
if dpu_expected_version != dpu_observed_version {
return false;
}
true
}
pub fn instance_network_restrictions(&self) -> rpc::forge::InstanceNetworkRestrictions {
let inband_interfaces = self
.interfaces
.iter()
.filter(|i| matches!(i.network_segment_type, Some(NetworkSegmentType::HostInband)))
.collect::<Vec<_>>();
// If there are no HostInband interfaces, this currently means this machine has DPUs and is
// not restricted to being in particular network segments
if inband_interfaces.is_empty() {
return rpc::forge::InstanceNetworkRestrictions {
network_segment_membership_type:
rpc::forge::InstanceNetworkSegmentMembershipType::TenantConfigurable as i32,
network_segment_ids: vec![],
};
}
// The machine has interfaces on HostInband segments, meaning its network segment
// memebership is static (cannot be configured at instance allocation time.)
// Get unique segment ID's and VPC ID's from each HostInband interface
let inband_network_segment_ids = inband_interfaces
.iter()
.map(|iface| iface.segment_id)
.collect::<HashSet<_>>();
rpc::forge::InstanceNetworkRestrictions {
network_segment_membership_type:
rpc::forge::InstanceNetworkSegmentMembershipType::Static as i32,
network_segment_ids: inband_network_segment_ids.into_iter().collect(),
}
}
pub fn to_capabilities(&self) -> Option<MachineCapabilitiesSet> {
self.hardware_info.clone().map(|info| {
MachineCapabilitiesSet::from_hardware_info(
info,
self.infiniband_status_observation.as_ref(),
self.associated_dpu_machine_ids(),
self.interfaces.clone(),
)
})
}
pub fn get_device_locator_for_dpu_id(
&self,
dpu_machine_id: &MachineId,
) -> ModelResult<DeviceLocator> {
let (id_to_device_map, device_to_id_map) = self.get_dpu_device_and_id_mappings()?;
if let Some(device) = id_to_device_map.get(dpu_machine_id)
&& let Some(id_vec) = device_to_id_map.get(device)
&& let Some(instance) = id_vec.iter().position(|id| id == dpu_machine_id)
{
return Ok(DeviceLocator {
device: device.clone(),
device_instance: instance,
});
}
Err(ModelError::DpuMappingError(format!(
"No device instance found for dpu {} in machine {}",
dpu_machine_id, self.id
)))
}
pub fn get_dpu_device_and_id_mappings(&self) -> ModelResult<DpuDeviceMappings> {
if self.is_dpu() {
return Err(ModelError::DpuMappingError(
"get_device_instance_and_dpu_id_mapping called on dpu".to_string(),
));
}
let hardware_info = self
.hardware_info
.as_ref()
.ok_or(ModelError::DpuMappingError(format!(
"Missing hardware information for machine {}",
self.id
)))?;
let mut id_to_device_map: HashMap<MachineId, String> = HashMap::default();
let mut device_to_id_map: HashMap<String, Vec<MachineId>> = HashMap::default();
// in order to ensure that the primary dpu is assigned a network config, it is configured first.
// hardware_interfaces has the primary dpu as the first interface, self.interfaces may not.
// iterate over hardware_interfaces and match it to self.interfaces using the mac address
for hardware_iface in &hardware_info.network_interfaces {
if let Some(pci) = &hardware_iface.pci_properties
&& let Some(iface) = self
.interfaces
.iter()
.find(|i| i.mac_address == hardware_iface.mac_address)
&& let Some(dpu_machine_id) = iface.attached_dpu_machine_id
{
id_to_device_map.insert(dpu_machine_id, pci.device.clone());
let id_vec = device_to_id_map.entry(pci.device.clone()).or_default();
id_vec.push(dpu_machine_id);
}
}