forked from NVIDIA/ncx-infra-controller-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstance.rs
More file actions
5969 lines (5279 loc) · 199 KB
/
instance.rs
File metadata and controls
5969 lines (5279 loc) · 199 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::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr};
use std::ops::DerefMut;
use std::str::FromStr;
use std::time::{Duration, SystemTime};
use ::rpc::forge::forge_server::Forge;
use carbide_uuid::instance::InstanceId;
use carbide_uuid::machine::MachineId;
use carbide_uuid::network::NetworkSegmentId;
use carbide_uuid::vpc::VpcPrefixId;
use chrono::Utc;
use common::api_fixtures::instance::{
advance_created_instance_into_ready_state, default_os_config, default_tenant_config,
interface_network_config_with_devices, single_interface_network_config,
single_interface_network_config_with_vpc_prefix, update_instance_network_status_observation,
};
use common::api_fixtures::managed_host::ManagedHostConfig;
use common::api_fixtures::tpm_attestation::{CA_CERT_SERIALIZED, EK_CERT_SERIALIZED};
use common::api_fixtures::{
TestEnvOverrides, create_managed_host, create_test_env, create_test_env_with_overrides, dpu,
get_config, get_vpc_fixture_id, inject_machine_measurements, network_configured_with_health,
persist_machine_validation_result, populate_network_security_groups, site_explorer,
};
use config_version::ConfigVersion;
use db::instance_address::UsedOverlayNetworkIpResolver;
use db::ip_allocator::UsedIpResolver;
use db::network_segment::IdColumn;
use db::{self, ObjectColumnFilter};
use ipnetwork::{IpNetwork, Ipv4Network};
use itertools::Itertools;
use mac_address::MacAddress;
use model::dpu_machine_update::DpuMachineUpdate;
use model::instance::config::extension_services::InstanceExtensionServicesConfig;
use model::instance::config::infiniband::InstanceInfinibandConfig;
use model::instance::config::network::{
DeviceLocator, InstanceNetworkConfig, InterfaceFunctionId, NetworkDetails,
};
use model::instance::config::nvlink::InstanceNvLinkConfig;
use model::instance::status::network::{
InstanceInterfaceStatusObservation, InstanceNetworkStatusObservation,
};
use model::machine::{
CleanupState, FailureDetails, InstanceState, MachineState, MachineValidatingState,
ManagedHostState, MeasuringState, NetworkConfigUpdateState, ValidationState,
};
use model::metadata::Metadata;
use model::network_security_group::NetworkSecurityGroupStatusObservation;
use model::network_segment::NetworkSegmentSearchConfig;
use model::vpc::UpdateVpcVirtualization;
use model::vpc_prefix::VpcPrefixConfig;
use rpc::forge::{
DpuExtensionService, Issue, IssueCategory, NetworkSegmentSearchFilter, TpmCaCert, TpmCaCertId,
};
use rpc::{InstanceReleaseRequest, InterfaceFunctionType, Timestamp};
use sqlx::PgPool;
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
use tonic::Request;
use crate::cfg::file::VmaasConfig;
use crate::instance::{allocate_instance, allocate_network};
use crate::network_segment::allocate::PrefixAllocator;
use crate::tests::common;
use crate::tests::common::api_fixtures::instance::{
advance_created_instance_into_state, single_interface_network_config_with_vfs,
};
use crate::tests::common::api_fixtures::{
TestEnv, create_managed_host_multi_dpu, create_managed_host_with_ek, update_time_params,
};
use crate::tests::common::rpc_builder::{
InstanceAllocationRequest, InstanceConfig, VpcCreationRequest,
};
pub async fn find_instances_by_label(
env: &TestEnv,
label: rpc::forge::Label,
) -> rpc::forge::InstanceList {
let instance_ids = env
.api
.find_instance_ids(tonic::Request::new(rpc::forge::InstanceSearchFilter {
label: Some(label),
tenant_org_id: None,
vpc_id: None,
instance_type_id: None,
}))
.await
.unwrap()
.into_inner()
.instance_ids;
env.api
.find_instances_by_ids(tonic::Request::new(rpc::forge::InstancesByIdsRequest {
instance_ids,
}))
.await
.unwrap()
.into_inner()
}
#[crate::sqlx_test]
async fn test_allocate_and_release_instance_one_dpu(
pool_options: PgPoolOptions,
options: PgConnectOptions,
) {
test_allocate_and_release_instance_impl(pool_options, options, 1, 1).await
}
#[crate::sqlx_test]
async fn test_allocate_and_release_instance_one_of_two_dpus(
pool_options: PgPoolOptions,
options: PgConnectOptions,
) {
test_allocate_and_release_instance_impl(pool_options, options, 2, 1).await
}
#[crate::sqlx_test]
async fn test_allocate_and_release_instance_two_of_two_dpus(
pool_options: PgPoolOptions,
options: PgConnectOptions,
) {
test_allocate_and_release_instance_impl(pool_options, options, 2, 2).await
}
#[crate::sqlx_test]
async fn test_allocate_and_release_instance_two_of_three_dpus(
pool_options: PgPoolOptions,
options: PgConnectOptions,
) {
test_allocate_and_release_instance_impl(pool_options, options, 3, 2).await
}
async fn test_allocate_and_release_instance_impl(
_: PgPoolOptions,
options: PgConnectOptions,
dpu_count: usize,
instance_interface_count: usize,
) {
let pool = PgPoolOptions::new().connect_with(options).await.unwrap();
let env = create_test_env(pool).await;
let segment_ids = env.create_vpc_and_tenant_segments(dpu_count).await;
let mh = create_managed_host_multi_dpu(&env, dpu_count).await;
let (used_dpu_ids, _unused_dpu_ids) = mh.dpu_ids.split_at(instance_interface_count);
let mut txn = env.db_txn().await;
for segment_id in &segment_ids {
assert_eq!(
db::instance_address::count_by_segment_id(&mut txn, segment_id)
.await
.unwrap(),
0
);
}
let host_machine = mh.host().db_machine(&mut txn).await;
let mut device_locators = Vec::default();
for dpu_machine_id in used_dpu_ids {
device_locators.push(
host_machine
.get_device_locator_for_dpu_id(dpu_machine_id)
.unwrap(),
);
}
assert!(matches!(
host_machine.current_state(),
ManagedHostState::Ready
));
txn.commit().await.unwrap();
let tinstance = mh
.instance_builer(&env)
.network(interface_network_config_with_devices(
&segment_ids,
&device_locators,
))
.build()
.await;
let instance = tinstance.rpc_instance().await;
assert_eq!(instance.status().tenant(), rpc::forge::TenantState::Ready);
let tenant_config = instance.config().tenant();
let expected_os = default_os_config();
let os = instance.config().os();
assert_eq!(os, &expected_os);
let expected_tenant_config = default_tenant_config();
assert_eq!(tenant_config, &expected_tenant_config);
let mut txn = env.db_txn().await;
let snapshot = mh.snapshot(&mut txn).await;
let fetched_instance = snapshot.instance.unwrap();
assert_eq!(&fetched_instance.machine_id, &mh.host().id);
for (segment_index, segment_id) in segment_ids.iter().enumerate() {
let expected_count = if segment_index < instance_interface_count {
1
} else {
0
};
assert_eq!(
db::instance_address::count_by_segment_id(&mut txn, segment_id)
.await
.unwrap(),
expected_count
);
}
let network_config = fetched_instance.config.network.clone();
assert_eq!(fetched_instance.network_config_version.version_nr(), 1);
let mut network_config_no_addresses = network_config.clone();
for iface in network_config_no_addresses.interfaces.iter_mut() {
assert_eq!(iface.ip_addrs.len(), 1);
assert_eq!(iface.interface_prefixes.len(), 1);
iface.ip_addrs.clear();
iface.interface_prefixes.clear();
iface.network_segment_gateways.clear();
iface.internal_uuid = uuid::Uuid::nil();
}
assert_eq!(
network_config_no_addresses,
InstanceNetworkConfig::for_segment_ids(&segment_ids, &device_locators,)
);
assert!(!fetched_instance.observations.network.is_empty());
assert!(fetched_instance.use_custom_pxe_on_boot);
let _ = db::instance::use_custom_ipxe_on_next_boot(&mh.host().id, false, &mut txn).await;
let snapshot = mh.snapshot(&mut txn).await;
let fetched_instance = snapshot.instance.unwrap();
txn.commit().await.unwrap();
let mut txn = env.db_txn().await;
// TODO: The MAC here doesn't matter. It's not used for lookup
let record = db::instance_address::find_by_instance_id_and_segment_id(
&mut txn,
&fetched_instance.id,
segment_ids.first().unwrap(),
)
.await
.unwrap()
.unwrap();
// This should the first IP. Algo does not look into machine_interface_addresses
// table for used addresses for instance.
assert_eq!(record.address.to_string(), "192.0.4.3");
assert_eq!(
&record.address,
network_config.interfaces[0]
.ip_addrs
.iter()
.next()
.unwrap()
.1
);
assert_eq!(
format!("{}/32", &record.address),
network_config.interfaces[0]
.interface_prefixes
.iter()
.next()
.unwrap()
.1
.to_string()
);
assert!(matches!(
mh.host().db_machine(&mut txn).await.current_state(),
ManagedHostState::Assigned {
instance_state: InstanceState::Ready
}
));
txn.commit().await.unwrap();
tinstance.delete().await;
// Address is freed during delete
let mut txn = env.db_txn().await;
assert!(matches!(
mh.host().db_machine(&mut txn).await.current_state(),
ManagedHostState::Ready
));
for segment_id in &segment_ids {
assert_eq!(
db::instance_address::count_by_segment_id(&mut txn, segment_id)
.await
.unwrap(),
0
);
}
txn.commit().await.unwrap();
}
#[crate::sqlx_test]
async fn test_measurement_assigned_ready_to_waiting_for_measurements_to_ca_failed_to_ready(
_: PgPoolOptions,
options: PgConnectOptions,
) {
let pool = PgPoolOptions::new().connect_with(options).await.unwrap();
let mut config = get_config();
config.attestation_enabled = true;
let env = create_test_env_with_overrides(pool, TestEnvOverrides::with_config(config)).await;
let segment_id = env.create_vpc_and_tenant_segment().await;
// add CA cert to pass attestation process
let add_ca_request = tonic::Request::new(TpmCaCert {
ca_cert: CA_CERT_SERIALIZED.to_vec(),
});
let inserted_cert = env
.api
.tpm_add_ca_cert(add_ca_request)
.await
.expect("Failed to add CA cert")
.into_inner();
let mh = create_managed_host_with_ek(&env, &EK_CERT_SERIALIZED).await;
let mut txn = env.db_txn().await;
//let dpu_loopback_ip = dpu::loopback_ip(&mut txn, &dpu_machine_id).await;
assert_eq!(
db::instance_address::count_by_segment_id(&mut txn, &segment_id)
.await
.unwrap(),
0
);
let host_machine = mh.host().db_machine(&mut txn).await;
assert!(matches!(
host_machine.current_state(),
ManagedHostState::Ready
));
txn.commit().await.unwrap();
let device_locator = host_machine
.get_device_locator_for_dpu_id(&mh.dpu().id)
.unwrap();
let tinstance = mh
.instance_builer(&env)
.network(interface_network_config_with_devices(
&[segment_id],
std::slice::from_ref(&device_locator),
))
.build()
.await;
let instance = tinstance.rpc_instance().await;
assert_eq!(instance.status().tenant(), rpc::forge::TenantState::Ready);
let tenant_config = instance.config().tenant();
let expected_os = default_os_config();
let os = instance.config().os();
assert_eq!(os, &expected_os);
let expected_tenant_config = default_tenant_config();
assert_eq!(tenant_config, &expected_tenant_config);
let mut txn = env.db_txn().await;
let snapshot = mh.snapshot(&mut txn).await;
let fetched_instance = snapshot.instance.unwrap();
assert_eq!(fetched_instance.machine_id, mh.host().id);
assert_eq!(
db::instance_address::count_by_segment_id(&mut txn, &segment_id)
.await
.unwrap(),
1
);
let network_config = fetched_instance.config.network.clone();
assert_eq!(fetched_instance.network_config_version.version_nr(), 1);
let mut network_config_no_addresses = network_config.clone();
for iface in network_config_no_addresses.interfaces.iter_mut() {
assert_eq!(iface.ip_addrs.len(), 1);
assert_eq!(iface.interface_prefixes.len(), 1);
iface.ip_addrs.clear();
iface.interface_prefixes.clear();
iface.network_segment_gateways.clear();
iface.internal_uuid = uuid::Uuid::nil();
}
assert_eq!(
network_config_no_addresses,
InstanceNetworkConfig::for_segment_ids(&[segment_id], &[device_locator],)
);
assert!(!fetched_instance.observations.network.is_empty());
assert!(fetched_instance.use_custom_pxe_on_boot);
let _ = db::instance::use_custom_ipxe_on_next_boot(&mh.host().id, false, &mut txn).await;
let snapshot = mh.snapshot(&mut txn).await;
let fetched_instance = snapshot.instance.unwrap();
assert!(!fetched_instance.use_custom_pxe_on_boot);
txn.commit().await.unwrap();
let mut txn = env.db_txn().await;
// TODO: The MAC here doesn't matter. It's not used for lookup
let segment = db::network_segment::find_by_name(&mut txn, "TENANT")
.await
.unwrap();
let record = db::instance_address::find_by_instance_id_and_segment_id(
&mut txn,
&fetched_instance.id,
&segment.id,
)
.await
.unwrap()
.unwrap();
// This should the first IP. Algo does not look into machine_interface_addresses
// table for used addresses for instance.
assert_eq!(record.address.to_string(), "192.0.4.3");
assert_eq!(
&record.address,
network_config.interfaces[0]
.ip_addrs
.iter()
.next()
.unwrap()
.1
);
assert_eq!(
format!("{}/32", &record.address),
network_config.interfaces[0]
.interface_prefixes
.iter()
.next()
.unwrap()
.1
.to_string()
);
assert!(matches!(
mh.host().db_machine(&mut txn).await.current_state(),
ManagedHostState::Assigned {
instance_state: InstanceState::Ready
}
));
txn.commit().await.unwrap();
// from delete_instance()
env.api
.release_instance(tonic::Request::new(InstanceReleaseRequest {
id: Some(tinstance.id),
issue: None,
is_repair_tenant: None,
}))
.await
.expect("Delete instance failed.");
// The instance should show up immediatly as terminating - even if the state handler didn't yet run
let instance = tinstance.rpc_instance().await;
assert_eq!(instance.status().tenant(), rpc::TenantState::Terminating);
env.run_machine_state_controller_iteration_until_state_matches(
&mh.host().id,
5,
ManagedHostState::Assigned {
instance_state: model::machine::InstanceState::HostPlatformConfiguration {
platform_config_state:
model::machine::HostPlatformConfigurationState::CheckHostConfig,
},
},
)
.await;
mh.network_configured(&env).await;
env.run_machine_state_controller_iteration_until_state_matches(
&mh.host().id,
1,
ManagedHostState::Assigned {
instance_state: model::machine::InstanceState::WaitingForDpusToUp,
},
)
.await;
mh.network_configured(&env).await;
env.run_machine_state_controller_iteration_until_state_matches(
&mh.host().id,
1,
ManagedHostState::Assigned {
instance_state: model::machine::InstanceState::BootingWithDiscoveryImage {
retry: model::machine::RetryInfo { count: 0 },
},
},
)
.await;
// handle_delete_post_bootingwithdiscoveryimage()
let mut txn = env.db_txn().await;
let machine = mh.host().db_machine(&mut txn).await;
db::machine::update_reboot_time(&machine, &mut txn)
.await
.unwrap();
txn.commit().await.unwrap();
// Run state machine twice.
// First DeletingManagedResource updates use_admin_network, transitions to WaitingForNetworkReconfig
// Second to discover we are now in WaitingForNetworkReconfig
env.run_machine_state_controller_iteration_until_state_matches(
&mh.host().id,
2,
ManagedHostState::Assigned {
instance_state: model::machine::InstanceState::WaitingForNetworkReconfig,
},
)
.await;
// Apply switching back to admin network
mh.network_configured(&env).await;
// now we should be in waiting for measurument state
env.run_machine_state_controller_iteration_until_state_matches(
&mh.host().id,
2,
ManagedHostState::PostAssignedMeasuring {
measuring_state: MeasuringState::WaitingForMeasurements,
},
)
.await;
// remove ca cert and inject measurements, now we should go to failed ca
// validation state
let delete_ca_certs_request = tonic::Request::new(TpmCaCertId {
ca_cert_id: inserted_cert.id.unwrap().ca_cert_id,
});
env.api
.tpm_delete_ca_cert(delete_ca_certs_request)
.await
.unwrap();
inject_machine_measurements(&env, mh.host().id).await;
for _ in 0..5 {
env.run_machine_state_controller_iteration().await;
}
// check that it has failed as intended due to the lack of ca cert
let mut txn = env.db_txn().await;
let host = mh.host().db_machine(&mut txn).await;
assert!(matches!(
host.current_state(),
ManagedHostState::Failed {
details: FailureDetails {
cause: model::machine::FailureCause::MeasurementsCAValidationFailed { .. },
..
},
..
}
));
txn.commit().await.unwrap();
// now re-add the ca cert
let add_ca_request = tonic::Request::new(TpmCaCert {
ca_cert: CA_CERT_SERIALIZED.to_vec(),
});
env.api
.tpm_add_ca_cert(add_ca_request)
.await
.expect("Failed to add CA cert");
env.run_machine_state_controller_iteration_until_state_matches(
&mh.host().id,
3,
ManagedHostState::WaitingForCleanup {
cleanup_state: CleanupState::HostCleanup {
boss_controller_id: None,
},
},
)
.await;
let mut txn = env.db_txn().await;
let machine = mh.host().db_machine(&mut txn).await;
db::machine::update_reboot_time(&machine, &mut txn)
.await
.unwrap();
db::machine::update_cleanup_time(&machine, &mut txn)
.await
.unwrap();
txn.commit().await.unwrap();
env.run_machine_state_controller_iteration_until_state_matches(
&mh.host().id,
3,
ManagedHostState::Validation {
validation_state: ValidationState::MachineValidation {
machine_validation: MachineValidatingState::MachineValidating {
context: "Cleanup".to_string(),
id: uuid::Uuid::default(),
completed: 1,
total: 1,
is_enabled: true,
},
},
},
)
.await;
let mut machine_validation_result = rpc::forge::MachineValidationResult {
validation_id: None,
name: "instance".to_string(),
description: "desc".to_string(),
command: "echo".to_string(),
args: "test".to_string(),
std_out: "".to_string(),
std_err: "".to_string(),
context: "Cleanup".to_string(),
exit_code: 0,
start_time: Some(Timestamp::from(SystemTime::now())),
end_time: Some(Timestamp::from(SystemTime::now())),
test_id: Some("test1".to_string()),
};
let response = mh.host().forge_agent_control().await;
let uuid = &response.data.unwrap().pair[1].value;
machine_validation_result.validation_id = Some(rpc::Uuid {
value: uuid.to_owned(),
});
persist_machine_validation_result(&env, machine_validation_result.clone()).await;
let mut txn = env.db_txn().await;
db::machine::update_machine_validation_time(&mh.host().id, &mut txn)
.await
.unwrap();
txn.commit().await.unwrap();
env.run_machine_state_controller_iteration_until_state_matches(
&mh.host().id,
3,
ManagedHostState::HostInit {
machine_state: MachineState::Discovered {
skip_reboot_wait: false,
},
},
)
.await;
let mut txn = env.db_txn().await;
let machine = mh.host().db_machine(&mut txn).await;
db::machine::update_reboot_time(&machine, &mut txn)
.await
.unwrap();
txn.commit().await.unwrap();
env.run_machine_state_controller_iteration_until_state_matches(
&mh.host().id,
3,
ManagedHostState::Ready,
)
.await;
// end of handle_delete_post_bootingwithdiscoveryimage()
assert!(
env.find_instances(vec![tinstance.id])
.await
.instances
.is_empty()
);
// end of delete_instance()
// Address is freed during delete
let mut txn = env.db_txn().await;
assert!(matches!(
mh.host().db_machine(&mut txn).await.current_state(),
ManagedHostState::Ready
));
assert_eq!(
db::instance_address::count_by_segment_id(&mut txn, &segment_id)
.await
.unwrap(),
0
);
txn.commit().await.unwrap();
}
#[crate::sqlx_test]
async fn test_allocate_instance_with_labels(_: PgPoolOptions, options: PgConnectOptions) {
let pool = PgPoolOptions::new().connect_with(options).await.unwrap();
let env = create_test_env(pool).await;
let segment_id = env.create_vpc_and_tenant_segment().await;
let mh = create_managed_host(&env).await;
let txn = env
.pool
.begin()
.await
.expect("Unable to create transaction on database pool");
txn.commit().await.unwrap();
let instance_metadata = rpc::forge::Metadata {
name: "test_instance_with_labels".to_string(),
description: "this instance must have labels.".to_string(),
labels: vec![
rpc::forge::Label {
key: "key1".to_string(),
value: Some("value1".to_string()),
},
rpc::forge::Label {
key: "key2".to_string(),
value: None,
},
],
};
let tinstance = mh
.instance_builer(&env)
.single_interface_network_config(segment_id)
.metadata(instance_metadata.clone())
.build()
.await;
// Test searching based on instance id.
let mut instance_matched_by_id = tinstance.rpc_instance().await.into_inner();
instance_matched_by_id.metadata = instance_matched_by_id.metadata.take().map(|mut metadata| {
metadata.labels.sort_by(|l1, l2| l1.key.cmp(&l2.key));
metadata
});
assert_eq!(
instance_matched_by_id.metadata,
Some(instance_metadata.clone())
);
let mut txn = env.db_txn().await;
let snapshot = mh.snapshot(&mut txn).await;
let fetched_instance = snapshot.instance.unwrap();
assert_eq!(fetched_instance.machine_id, mh.host().id);
assert_eq!(fetched_instance.metadata.name, "test_instance_with_labels");
assert_eq!(
fetched_instance.metadata.description,
"this instance must have labels."
);
assert!(fetched_instance.metadata.labels.len() == 2);
assert_eq!(
fetched_instance.metadata.labels.get("key1").unwrap(),
"value1"
);
assert_eq!(fetched_instance.metadata.labels.get("key2").unwrap(), "");
let mut instance_matched_by_label = find_instances_by_label(
&env,
rpc::forge::Label {
key: "key1".to_string(),
value: None,
},
)
.await
.instances
.remove(0);
instance_matched_by_label.metadata =
instance_matched_by_label
.metadata
.take()
.map(|mut metadata| {
metadata.labels.sort_by(|l1, l2| l1.key.cmp(&l2.key));
metadata
});
assert_eq!(instance_matched_by_label.machine_id.unwrap(), mh.host().id);
assert_eq!(instance_matched_by_label.metadata, Some(instance_metadata));
}
#[crate::sqlx_test]
async fn test_allocate_instance_with_invalid_metadata(_: PgPoolOptions, options: PgConnectOptions) {
let pool = PgPoolOptions::new().connect_with(options).await.unwrap();
let env = create_test_env(pool).await;
let segment_id = env.create_vpc_and_tenant_segment().await;
let (host_machine_id, _dpu_machine_id) = create_managed_host(&env).await.into();
for (invalid_metadata, expected_err) in common::metadata::invalid_metadata_testcases(true) {
let tenant_config = default_tenant_config();
let config = InstanceConfig::builder()
.tenant(tenant_config)
.os(default_os_config())
.network(single_interface_network_config(segment_id))
.rpc();
let result = env
.api
.allocate_instance(
InstanceAllocationRequest::builder(false)
.machine_id(host_machine_id)
.config(config)
.metadata(invalid_metadata.clone())
.tonic_request(),
)
.await;
let err = result.expect_err(&format!(
"Invalid metadata of type should not be accepted: {invalid_metadata:?}"
));
assert_eq!(err.code(), tonic::Code::InvalidArgument);
assert!(
err.message().contains(&expected_err),
"Testcase: {:?}\nMessage is \"{}\".\nMessage should contain: \"{}\"",
invalid_metadata,
err.message(),
expected_err
);
}
}
#[crate::sqlx_test]
async fn test_instance_hostname_creation(_: PgPoolOptions, options: PgConnectOptions) {
let pool = PgPoolOptions::new().connect_with(options).await.unwrap();
let env = create_test_env(pool).await;
let segment_id = env.create_vpc_and_tenant_segment().await;
let mh = create_managed_host(&env).await;
let txn = env
.pool
.begin()
.await
.expect("Unable to create transaction on database pool");
txn.commit().await.unwrap();
let instance_hostname = "test-hostname";
mh.instance_builer(&env)
.single_interface_network_config(segment_id)
.hostname(instance_hostname)
.tenant_org("org-nebulon")
.build()
.await;
let mut txn = env.db_txn().await;
let snapshot = mh.snapshot(&mut txn).await;
let fetched_instance = snapshot.instance.unwrap();
let returned_hostname = fetched_instance.config.tenant.hostname;
assert_eq!(returned_hostname.unwrap(), instance_hostname);
//Check for duplicate hostnames
let txn = env
.pool
.begin()
.await
.expect("Unable to create transaction on database pool");
txn.commit().await.unwrap();
create_managed_host(&env)
.await
.instance_builer(&env)
.single_interface_network_config(segment_id)
.hostname(instance_hostname)
.tenant_org("org-nvidia") // different org, should fail on the same one
.build()
.await;
}
#[crate::sqlx_test]
async fn test_instance_dns_resolution(_: PgPoolOptions, options: PgConnectOptions) {
let pool = PgPoolOptions::new().connect_with(options).await.unwrap();
let env = create_test_env(pool).await;
let (segment_id_1, segment_id_2) = env.create_vpc_and_dual_tenant_segment().await;
let mh = create_managed_host(&env).await;
let network = rpc::InstanceNetworkConfig {
interfaces: vec![
rpc::InstanceInterfaceConfig {
function_type: rpc::InterfaceFunctionType::Physical as i32,
network_segment_id: Some(segment_id_1),
network_details: None,
device: None,
device_instance: 0u32,
virtual_function_id: None,
},
rpc::InstanceInterfaceConfig {
function_type: rpc::InterfaceFunctionType::Virtual as i32,
network_segment_id: Some(segment_id_2),
network_details: None,
device: None,
device_instance: 0u32,
virtual_function_id: None,
},
],
};
// Create instance with hostname
mh.instance_builer(&env)
.network(network)
.hostname("test-hostname")
.tenant_org("nvidia-org")
.build()
.await;
let response = env
.api
.get_managed_host_network_config(tonic::Request::new(
rpc::forge::ManagedHostNetworkConfigRequest {
dpu_machine_id: mh.dpu().id.into(),
},
))
.await
.unwrap()
.into_inner();
//DNS record domain always uses IP Address (for now)
let dns_record = env
.api
.lookup_record(tonic::Request::new(
rpc::protos::dns::DnsResourceRecordLookupRequest {
qname: "192-0-2-3.dwrt1.com.".to_string(),
zone_id: uuid::Uuid::new_v4().to_string(),
local: None,
remote: None,
qtype: "A".to_string(),
real_remote: None,
},
))
.await
.unwrap()
.into_inner();
tracing::info!("dns_record is {:?}: ", dns_record);
assert_eq!(dns_record.records.first().unwrap().content, "192.0.2.3");
//DHCP response uses hostname set during allocation
assert_eq!(
"test-hostname.dwrt1.com",
response.tenant_interfaces[0].fqdn
);
}
#[crate::sqlx_test]
async fn test_instance_null_hostname(_: PgPoolOptions, options: PgConnectOptions) {
let pool = PgPoolOptions::new().connect_with(options).await.unwrap();
let env = create_test_env(pool).await;
let segment_id = env.create_vpc_and_tenant_segment().await;
let mh = create_managed_host(&env).await;
//Create instance with no hostname set
let mut tenant_config = default_tenant_config();
tenant_config.hostname = None;
let instance_config = InstanceConfig::builder()
.tenant(tenant_config)
.os(default_os_config())
.network(single_interface_network_config(segment_id))
.rpc();
mh.instance_builer(&env)
.config(instance_config)
.build()
.await;
let _response = env
.api
.get_managed_host_network_config(tonic::Request::new(
rpc::forge::ManagedHostNetworkConfigRequest {
dpu_machine_id: mh.dpu().id.into(),
},
))
.await
.unwrap()
.into_inner();
//DNS record domain always uses dashed IP (for now)
let dns_record = env
.api
.lookup_record(tonic::Request::new(
rpc::protos::dns::DnsResourceRecordLookupRequest {
qname: "192-0-2-3.dwrt1.com.".to_string(),
zone_id: uuid::Uuid::new_v4().to_string(),
local: None,
remote: None,