-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathinstances.rs
More file actions
8111 lines (7280 loc) · 280 KB
/
Copy pathinstances.rs
File metadata and controls
8111 lines (7280 loc) · 280 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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Tests basic instance support in the API
use super::external_ips::floating_ip_get;
use super::external_ips::get_floating_ip_by_id_url;
use super::metrics::{assert_silo_metrics, assert_system_metrics};
use http::StatusCode;
use http::method::Method;
use itertools::Itertools;
use nexus_auth::authz::Action;
use nexus_db_lookup::LookupPath;
use nexus_db_queries::context::OpContext;
use nexus_db_queries::db::DataStore;
use nexus_db_queries::db::fixed_data::silo::DEFAULT_SILO;
use nexus_test_interface::NexusServer;
use nexus_test_utils::http_testing::AuthnMode;
use nexus_test_utils::http_testing::NexusRequest;
use nexus_test_utils::http_testing::RequestBuilder;
use nexus_test_utils::resource_helpers::DiskTest;
use nexus_test_utils::resource_helpers::assert_ip_pool_utilization;
use nexus_test_utils::resource_helpers::create_default_ip_pool;
use nexus_test_utils::resource_helpers::create_disk;
use nexus_test_utils::resource_helpers::create_floating_ip;
use nexus_test_utils::resource_helpers::create_ip_pool;
use nexus_test_utils::resource_helpers::create_local_user;
use nexus_test_utils::resource_helpers::create_silo;
use nexus_test_utils::resource_helpers::grant_iam;
use nexus_test_utils::resource_helpers::link_ip_pool;
use nexus_test_utils::resource_helpers::object_create;
use nexus_test_utils::resource_helpers::object_create_error;
use nexus_test_utils::resource_helpers::object_delete;
use nexus_test_utils::resource_helpers::object_delete_error;
use nexus_test_utils::resource_helpers::object_get;
use nexus_test_utils::resource_helpers::object_put;
use nexus_test_utils::resource_helpers::object_put_error;
use nexus_test_utils::resource_helpers::objects_list_page_authz;
use nexus_test_utils::resource_helpers::test_params;
use nexus_test_utils::start_sled_agent_with_config;
use nexus_test_utils::wait_for_producer;
use nexus_types::external_api::params::SshKeyCreate;
use nexus_types::external_api::shared::IpKind;
use nexus_types::external_api::shared::IpRange;
use nexus_types::external_api::shared::Ipv4Range;
use nexus_types::external_api::shared::SiloIdentityMode;
use nexus_types::external_api::views::Sled;
use nexus_types::external_api::views::SshKey;
use nexus_types::external_api::{params, views};
use nexus_types::identity::Resource;
use nexus_types::internal_api::params::InstanceMigrateRequest;
use nexus_types::silo::DEFAULT_SILO_ID;
use omicron_common::api::external::AffinityPolicy;
use omicron_common::api::external::ByteCount;
use omicron_common::api::external::Disk;
use omicron_common::api::external::DiskState;
use omicron_common::api::external::Error;
use omicron_common::api::external::FailureDomain;
use omicron_common::api::external::IdentityMetadataCreateParams;
use omicron_common::api::external::IdentityMetadataUpdateParams;
use omicron_common::api::external::Instance;
use omicron_common::api::external::InstanceAutoRestartPolicy;
use omicron_common::api::external::InstanceCpuCount;
use omicron_common::api::external::InstanceCpuPlatform;
use omicron_common::api::external::InstanceNetworkInterface;
use omicron_common::api::external::InstanceState;
use omicron_common::api::external::Name;
use omicron_common::api::external::NameOrId;
use omicron_common::api::external::Nullable;
use omicron_common::api::external::Vni;
use omicron_common::api::internal::shared::ResolvedVpcRoute;
use omicron_common::api::internal::shared::RouterId;
use omicron_common::api::internal::shared::RouterKind;
use omicron_nexus::Nexus;
use omicron_nexus::TestInterfaces as _;
use omicron_nexus::app::MAX_MEMORY_BYTES_PER_INSTANCE;
use omicron_nexus::app::MAX_VCPU_PER_INSTANCE;
use omicron_nexus::app::MIN_MEMORY_BYTES_PER_INSTANCE;
use omicron_sled_agent::sim::SledAgent;
use omicron_test_utils::dev::poll::wait_for_condition;
use omicron_uuid_kinds::PropolisUuid;
use omicron_uuid_kinds::SledUuid;
use omicron_uuid_kinds::{GenericUuid, InstanceUuid};
use sled_agent_client::TestInterfaces as _;
use std::collections::HashSet;
use std::convert::TryFrom;
use std::net::Ipv4Addr;
use std::sync::Arc;
use std::time::Duration;
use uuid::Uuid;
use dropshot::test_util::ClientTestContext;
use dropshot::{HttpErrorResponseBody, ResultsPage};
use nexus_test_utils::identity_eq;
use nexus_test_utils::resource_helpers::{
create_instance, create_instance_with, create_instance_with_error,
create_project,
};
use nexus_test_utils_macros::nexus_test;
use nexus_types::external_api::shared::SiloRole;
use omicron_test_utils::dev::poll;
use omicron_test_utils::dev::poll::CondCheckError;
type ControlPlaneTestContext =
nexus_test_utils::ControlPlaneTestContext<omicron_nexus::Server>;
static PROJECT_NAME: &str = "springfield-squidport";
fn get_project_selector() -> String {
format!("project={}", PROJECT_NAME)
}
fn get_instances_url() -> String {
format!("/v1/instances?{}", get_project_selector())
}
fn get_instance_url(instance_name: &str) -> String {
format!("/v1/instances/{}?{}", instance_name, get_project_selector())
}
fn get_instance_start_url(instance_name: &str) -> String {
format!("/v1/instances/{}/start?{}", instance_name, get_project_selector())
}
fn get_instance_stop_url(instance_name: &str) -> String {
format!("/v1/instances/{}/stop?{}", instance_name, get_project_selector())
}
fn get_disks_url() -> String {
format!("/v1/disks?{}", get_project_selector())
}
fn anti_affinity_groups_url() -> String {
format!("/v1/anti-affinity-groups?{}", get_project_selector())
}
fn default_vpc_subnets_url() -> String {
format!("/v1/vpc-subnets?{}&vpc=default", get_project_selector())
}
const SLEDS_URL: &'static str = "/v1/system/hardware/sleds";
pub async fn create_project_and_pool(
client: &ClientTestContext,
) -> views::Project {
create_default_ip_pool(client).await;
create_project(client, PROJECT_NAME).await
}
#[nexus_test]
async fn test_instances_access_before_create_returns_not_found(
cptestctx: &ControlPlaneTestContext,
) {
let client = &cptestctx.external_client;
// Create a project that we'll use for testing.
let _ = create_project(&client, PROJECT_NAME).await;
// List instances. There aren't any yet.
let instances = instances_list(&client, &get_instances_url()).await;
assert_eq!(instances.len(), 0);
// Make sure we get a 404 if we fetch one.
let instance_url = get_instance_url("just-rainsticks");
let error: HttpErrorResponseBody = NexusRequest::expect_failure(
client,
StatusCode::NOT_FOUND,
Method::GET,
&instance_url,
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap()
.parsed_body()
.unwrap();
assert_eq!(
error.message,
"not found: instance with name \"just-rainsticks\""
);
// Ditto if we try to delete one.
let error: HttpErrorResponseBody = NexusRequest::expect_failure(
client,
StatusCode::NOT_FOUND,
Method::DELETE,
&instance_url,
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap()
.parsed_body()
.unwrap();
assert_eq!(
error.message,
"not found: instance with name \"just-rainsticks\""
);
}
// Regression tests for https://github.com/oxidecomputer/omicron/issues/4923.
#[nexus_test]
async fn test_cannot_create_instance_with_bad_hostname(
cptestctx: &ControlPlaneTestContext,
) {
test_create_instance_with_bad_hostname_impl(cptestctx, "bad_hostname")
.await;
}
#[nexus_test]
async fn test_cannot_create_instance_with_empty_hostname(
cptestctx: &ControlPlaneTestContext,
) {
test_create_instance_with_bad_hostname_impl(cptestctx, "").await;
}
async fn test_create_instance_with_bad_hostname_impl(
cptestctx: &ControlPlaneTestContext,
hostname: &str,
) {
let client = &cptestctx.external_client;
let _project = create_project_and_pool(client).await;
// Create an instance, with what should be an invalid hostname.
//
// We'll do this by creating a _valid_ set of parameters, convert it to
// JSON, and then muck with the hostname.
let instance_name = "happy-accident";
let params = params::InstanceCreate {
identity: IdentityMetadataCreateParams {
name: instance_name.parse().unwrap(),
description: format!("instance {:?}", instance_name),
},
ncpus: InstanceCpuCount(4),
memory: ByteCount::from_gibibytes_u32(1),
hostname: "the-host".parse().unwrap(),
user_data:
b"#cloud-config\nsystem_info:\n default_user:\n name: oxide"
.to_vec(),
network_interfaces: Default::default(),
external_ips: vec![],
disks: vec![],
boot_disk: None,
cpu_platform: None,
start: false,
ssh_public_keys: None,
auto_restart_policy: Default::default(),
anti_affinity_groups: Vec::new(),
};
let mut body: serde_json::Value =
serde_json::from_str(&serde_json::to_string(¶ms).unwrap()).unwrap();
body["hostname"] = hostname.into();
let err = create_instance_with_error(
client,
PROJECT_NAME,
&body,
StatusCode::BAD_REQUEST,
)
.await;
assert!(err.message.contains("Hostnames must comply with RFC 1035"));
}
#[nexus_test]
async fn test_instance_access(cptestctx: &ControlPlaneTestContext) {
let client = &cptestctx.external_client;
let project = create_project_and_pool(client).await;
// Create an instance.
let instance_name = "test-instance";
let instance = create_instance(client, PROJECT_NAME, instance_name).await;
// Fetch instance by id
let fetched_instance = instance_get(
&client,
format!("/v1/instances/{}", instance.identity.id).as_str(),
)
.await;
assert_eq!(fetched_instance.identity.id, instance.identity.id);
// Fetch instance by name and project_id
let fetched_instance = instance_get(
&client,
format!(
"/v1/instances/{}?project={}",
instance.identity.name, project.identity.id
)
.as_str(),
)
.await;
assert_eq!(fetched_instance.identity.id, instance.identity.id);
// Fetch instance by name and project_name
let fetched_instance = instance_get(
&client,
format!(
"/v1/instances/{}?project={}",
instance.identity.name, project.identity.name
)
.as_str(),
)
.await;
assert_eq!(fetched_instance.identity.id, instance.identity.id);
}
#[nexus_test]
async fn test_instances_create_reboot_halt(
cptestctx: &ControlPlaneTestContext,
) {
let client = &cptestctx.external_client;
let apictx = &cptestctx.server.server_context();
let nexus = &apictx.nexus;
let instance_name = "just-rainsticks";
create_project_and_pool(&client).await;
// Create an instance.
let instance_url = get_instance_url(instance_name);
let instance = create_instance(client, PROJECT_NAME, instance_name).await;
assert_eq!(instance.identity.name, instance_name);
assert_eq!(
instance.identity.description,
format!("instance \"{}\"", instance_name).as_str()
);
let InstanceCpuCount(nfoundcpus) = instance.ncpus;
// These particulars are hardcoded in create_instance().
assert_eq!(nfoundcpus, 4);
assert_eq!(instance.memory.to_whole_gibibytes(), 1);
assert_eq!(instance.hostname.as_str(), "the-host");
assert_eq!(instance.runtime.run_state, InstanceState::Starting);
// Attempt to create a second instance with a conflicting name.
let error: HttpErrorResponseBody = NexusRequest::new(
RequestBuilder::new(client, Method::POST, &get_instances_url())
.body(Some(¶ms::InstanceCreate {
identity: IdentityMetadataCreateParams {
name: instance.identity.name.clone(),
description: format!(
"instance {:?}",
&instance.identity.name
),
},
ncpus: instance.ncpus,
memory: instance.memory,
hostname: instance.hostname.parse().unwrap(),
user_data: vec![],
ssh_public_keys: None,
network_interfaces:
params::InstanceNetworkInterfaceAttachment::Default,
external_ips: vec![],
disks: vec![],
boot_disk: None,
cpu_platform: None,
start: true,
auto_restart_policy: Default::default(),
anti_affinity_groups: Vec::new(),
}))
.expect_status(Some(StatusCode::BAD_REQUEST)),
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap()
.parsed_body()
.unwrap();
assert_eq!(
error.message,
format!("already exists: instance \"{}\"", instance_name).as_str()
);
// List instances again and expect to find the one we just created.
let instances = instances_list(&client, &get_instances_url()).await;
assert_eq!(instances.len(), 1);
instances_eq(&instances[0], &instance);
// Fetch the instance and expect it to match.
let instance = instance_get(&client, &instance_url).await;
instances_eq(&instances[0], &instance);
assert_eq!(instance.runtime.run_state, InstanceState::Starting);
// Check that the instance got a network interface
let nics_url = format!(
"/v1/vpc-subnets/default/network-interfaces?project={}&vpc=default",
PROJECT_NAME
);
let network_interfaces =
objects_list_page_authz::<InstanceNetworkInterface>(client, &nics_url)
.await
.items;
assert_eq!(network_interfaces.len(), 1);
assert_eq!(network_interfaces[0].instance_id, instance.identity.id);
assert_eq!(
network_interfaces[0].identity.name,
nexus_defaults::DEFAULT_PRIMARY_NIC_NAME
);
// Now, simulate completion of instance boot and check the state reported.
let instance_id = InstanceUuid::from_untyped_uuid(instance.identity.id);
instance_simulate(nexus, &instance_id).await;
let instance_next = instance_get(&client, &instance_url).await;
identity_eq(&instance.identity, &instance_next.identity);
assert_eq!(instance_next.runtime.run_state, InstanceState::Running);
assert!(
instance_next.runtime.time_run_state_updated
> instance.runtime.time_run_state_updated
);
// Request another boot. This should succeed without changing the state,
// not even the state timestamp.
let instance = instance_next;
let instance_next =
instance_post(&client, instance_name, InstanceOp::Start).await;
instances_eq(&instance, &instance_next);
let instance_next = instance_get(&client, &instance_url).await;
instances_eq(&instance, &instance_next);
// Reboot the instance.
let instance = instance_next;
let instance_next =
instance_post(&client, instance_name, InstanceOp::Reboot).await;
assert_eq!(instance_next.runtime.run_state, InstanceState::Rebooting);
assert!(
instance_next.runtime.time_run_state_updated
> instance.runtime.time_run_state_updated
);
let instance = instance_next;
instance_simulate(nexus, &instance_id).await;
let instance_next = instance_get(&client, &instance_url).await;
assert_eq!(instance_next.runtime.run_state, InstanceState::Running);
assert!(
instance_next.runtime.time_run_state_updated
> instance.runtime.time_run_state_updated
);
// Request a halt and verify both the immediate state and the finished state.
let instance = instance_next;
let instance_next =
instance_post(&client, instance_name, InstanceOp::Stop).await;
assert_eq!(instance_next.runtime.run_state, InstanceState::Stopping);
assert!(
instance_next.runtime.time_run_state_updated
> instance.runtime.time_run_state_updated
);
let instance = instance_next;
instance_simulate(nexus, &instance_id).await;
let instance_next =
instance_wait_for_state(client, instance_id, InstanceState::Stopped)
.await;
assert!(
instance_next.runtime.time_run_state_updated
> instance.runtime.time_run_state_updated
);
// Request another halt. This should succeed without changing the state,
// not even the state timestamp.
let instance = instance_next;
let instance_next =
instance_post(&client, instance_name, InstanceOp::Stop).await;
instances_eq(&instance, &instance_next);
let instance_next = instance_get(&client, &instance_url).await;
instances_eq(&instance, &instance_next);
assert_eq!(instance_next.runtime.run_state, InstanceState::Stopped);
// Attempt to reboot the halted instance. This should fail.
let _error: HttpErrorResponseBody = NexusRequest::expect_failure(
client,
StatusCode::BAD_REQUEST,
Method::POST,
get_instance_url(format!("{}/reboot", instance_name).as_str()).as_str(),
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap()
.parsed_body()
.unwrap();
// TODO communicating this error message through requires exporting error
// types from dropshot, translating that into a component of the generated
// client, and expressing that as a rich error type.
// assert_eq!(error.message, "cannot reboot instance in state \"stopped\"");
// State should still be stopped.
let instance = instance_get(&client, &instance_url).await;
assert_eq!(instance.runtime.run_state, InstanceState::Stopped);
// Start the instance. While it's starting, issue a reboot. This should
// succeed, having stopped in between.
let instance = instance_next;
let instance_next =
instance_post(&client, instance_name, InstanceOp::Start).await;
assert_eq!(instance_next.runtime.run_state, InstanceState::Starting);
assert!(
instance_next.runtime.time_run_state_updated
> instance.runtime.time_run_state_updated
);
let instance = instance_next;
let instance_next =
instance_post(&client, instance_name, InstanceOp::Reboot).await;
assert_eq!(instance_next.runtime.run_state, InstanceState::Rebooting);
assert!(
instance_next.runtime.time_run_state_updated
> instance.runtime.time_run_state_updated
);
let instance = instance_next;
instance_simulate(nexus, &instance_id).await;
let instance_next = instance_get(&client, &instance_url).await;
assert_eq!(instance_next.runtime.run_state, InstanceState::Running);
assert!(
instance_next.runtime.time_run_state_updated
> instance.runtime.time_run_state_updated
);
// Stop the instance. While it's stopping, issue a reboot. This should
// fail because you cannot stop an instance that's en route to a stopped
// state.
let instance = instance_next;
let instance_next =
instance_post(&client, instance_name, InstanceOp::Stop).await;
assert_eq!(instance_next.runtime.run_state, InstanceState::Stopping);
assert!(
instance_next.runtime.time_run_state_updated
> instance.runtime.time_run_state_updated
);
let _error: HttpErrorResponseBody = NexusRequest::expect_failure(
client,
StatusCode::BAD_REQUEST,
Method::POST,
get_instance_url(format!("{}/reboot", instance_name).as_str()).as_str(),
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap()
.parsed_body()
.unwrap();
// assert_eq!(error.message, "cannot reboot instance in state \"stopping\"");
let instance = instance_next;
instance_simulate(nexus, &instance_id).await;
let instance_next =
instance_wait_for_state(client, instance_id, InstanceState::Stopped)
.await;
assert!(
instance_next.runtime.time_run_state_updated
> instance.runtime.time_run_state_updated
);
// TODO-coverage add a test to try to delete the project at this point.
// Delete the instance.
NexusRequest::object_delete(client, &instance_url)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap();
// Check that the network interfaces for that instance are gone, peeking
// at the subnet-scoped URL so we don't 404 at the instance-scoped route.
let url_interfaces = format!(
"/v1/vpc-subnets/default/network-interfaces?project={}&vpc=default",
PROJECT_NAME,
);
let interfaces = objects_list_page_authz::<InstanceNetworkInterface>(
client,
&url_interfaces,
)
.await
.items;
assert!(
interfaces.is_empty(),
"Expected all network interfaces for the instance to be deleted"
);
// TODO-coverage re-add tests that check the server-side state after
// deleting. We need to figure out how these actually get cleaned up from
// the API namespace when this happens.
// Once more, try to reboot it. This should not work on a destroyed
// instance.
NexusRequest::expect_failure(
client,
StatusCode::NOT_FOUND,
Method::POST,
get_instance_url(format!("{}/reboot", instance_name).as_str()).as_str(),
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap();
// Similarly, we should not be able to start or stop the instance.
NexusRequest::expect_failure(
client,
StatusCode::NOT_FOUND,
Method::POST,
get_instance_start_url(instance_name).as_str(),
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap();
NexusRequest::expect_failure(
client,
StatusCode::NOT_FOUND,
Method::POST,
get_instance_stop_url(instance_name).as_str(),
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap();
}
#[nexus_test(extra_sled_agents = 3)]
async fn test_instance_start_creates_networking_state(
cptestctx: &ControlPlaneTestContext,
) {
let client = &cptestctx.external_client;
let apictx = &cptestctx.server.server_context();
let nexus = &apictx.nexus;
let instance_name = "series-of-tubes";
// This test requires some additional sleds that can receive V2P mappings.
let additional_sleds: Vec<_> = cptestctx.extra_sled_agents().collect();
create_project_and_pool(&client).await;
let instance_url = get_instance_url(instance_name);
let instance = create_instance(client, PROJECT_NAME, instance_name).await;
let instance_id = InstanceUuid::from_untyped_uuid(instance.identity.id);
// Drive the instance to Running, then stop it.
instance_simulate(nexus, &instance_id).await;
instance_post(&client, instance_name, InstanceOp::Stop).await;
instance_simulate(nexus, &instance_id).await;
instance_wait_for_state(client, instance_id, InstanceState::Stopped).await;
// Forcibly clear the instance's V2P mappings to simulate what happens when
// the control plane comes up when an instance is stopped.
let mut sled_agents: Vec<&Arc<SledAgent>> =
additional_sleds.iter().map(|x| &x.sled_agent).collect();
sled_agents.push(&cptestctx.first_sled_agent());
for agent in &sled_agents {
agent.v2p_mappings.lock().unwrap().clear();
}
// Start the instance and make sure that it gets to Running.
instance_post(&client, instance_name, InstanceOp::Start).await;
instance_simulate(nexus, &instance_id).await;
let instance = instance_get(&client, &instance_url).await;
assert_eq!(instance.runtime.run_state, InstanceState::Running);
// Now ensure the V2P mappings have been reestablished everywhere.
let nics_url =
format!("/v1/network-interfaces?instance={}", instance.identity.id,);
let nics =
objects_list_page_authz::<InstanceNetworkInterface>(client, &nics_url)
.await
.items;
assert_eq!(nics.len(), 1);
let datastore = nexus.datastore();
let opctx =
OpContext::for_tests(cptestctx.logctx.log.new(o!()), datastore.clone());
let (.., authz_instance) = LookupPath::new(&opctx, datastore)
.instance_id(instance.identity.id)
.lookup_for(nexus_db_queries::authz::Action::Read)
.await
.unwrap();
let guest_nics = datastore
.derive_guest_network_interface_info(&opctx, &authz_instance)
.await
.unwrap();
assert_eq!(guest_nics.len(), 1);
for agent in &sled_agents {
assert_sled_v2p_mappings(agent, &nics[0], guest_nics[0].vni).await;
}
// Ensure that the target sled agent for our instance has received
// up-to-date VPC routes.
let with_vmm = datastore
.instance_fetch_with_vmm(&opctx, &authz_instance)
.await
.unwrap();
let mut checked = false;
for agent in &sled_agents {
if Some(agent.id) == with_vmm.sled_id() {
assert_sled_vpc_routes(
agent,
&opctx,
datastore,
nics[0].subnet_id,
guest_nics[0].vni,
)
.await;
checked = true;
}
}
assert!(checked);
}
#[nexus_test(extra_sled_agents = 1)]
async fn test_instance_migrate(cptestctx: &ControlPlaneTestContext) {
use nexus_db_model::Migration;
use omicron_common::api::internal::nexus::MigrationState;
async fn migration_fetch(
cptestctx: &ControlPlaneTestContext,
migration_id: Uuid,
) -> Migration {
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::prelude::*;
use nexus_db_schema::schema::migration::dsl;
let datastore =
cptestctx.server.server_context().nexus.datastore().clone();
let db_state = dsl::migration
// N.B. that for the purposes of this test, we explicitly should
// *not* filter out migrations that are marked as deleted, as the
// migration record is marked as deleted once the migration completes.
.filter(dsl::id.eq(migration_id))
.select(Migration::as_select())
.get_results_async::<Migration>(
&*datastore.pool_connection_for_tests().await.unwrap(),
)
.await
.unwrap();
info!(&cptestctx.logctx.log, "refetched migration info from db";
"migration" => ?db_state);
db_state.into_iter().next().unwrap()
}
let client = &cptestctx.external_client;
let internal_client = &cptestctx.internal_client;
let apictx = &cptestctx.server.server_context();
let nexus = &apictx.nexus;
let instance_name = "bird-ecology";
// Get the second sled to migrate to/from.
let default_sled_id = cptestctx.first_sled_id();
let other_sled_id = cptestctx.second_sled_id();
create_project_and_pool(&client).await;
let instance_url = get_instance_url(instance_name);
// Explicitly create an instance with no disks. Simulated sled agent assumes
// that disks are co-located with their instances.
let instance = nexus_test_utils::resource_helpers::create_instance_with(
client,
PROJECT_NAME,
instance_name,
¶ms::InstanceNetworkInterfaceAttachment::Default,
Vec::<params::InstanceDiskAttachment>::new(),
Vec::<params::ExternalIpCreate>::new(),
true,
Default::default(),
None,
)
.await;
let instance_id = InstanceUuid::from_untyped_uuid(instance.identity.id);
// Poke the instance into an active state.
instance_simulate(nexus, &instance_id).await;
let instance_next = instance_get(&client, &instance_url).await;
assert_eq!(instance_next.runtime.run_state, InstanceState::Running);
let sled_info = nexus
.active_instance_info(&instance_id, None)
.await
.unwrap()
.expect("running instance should have a sled");
let original_sled = sled_info.sled_id;
let dst_sled_id = if original_sled == default_sled_id {
other_sled_id
} else {
default_sled_id
};
let migrate_url =
format!("/instances/{}/migrate", &instance_id.to_string());
let instance = NexusRequest::new(
RequestBuilder::new(internal_client, Method::POST, &migrate_url)
.body(Some(&InstanceMigrateRequest { dst_sled_id }))
.expect_status(Some(StatusCode::OK)),
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap()
.parsed_body::<Instance>()
.unwrap();
let new_sled_info = nexus
.active_instance_info(&instance_id, None)
.await
.unwrap()
.expect("running instance should have a sled");
let current_sled = new_sled_info.sled_id;
assert_eq!(current_sled, original_sled);
// Ensure that both sled agents report that the migration is in progress.
let migration_id = {
let datastore = apictx.nexus.datastore();
let opctx = OpContext::for_tests(
cptestctx.logctx.log.new(o!()),
datastore.clone(),
);
let (.., authz_instance) = LookupPath::new(&opctx, datastore)
.instance_id(instance.identity.id)
.lookup_for(nexus_db_queries::authz::Action::Read)
.await
.unwrap();
datastore
.instance_refetch(&opctx, &authz_instance)
.await
.unwrap()
.runtime_state
.migration_id
.expect("since we've started a migration, the instance record must have a migration id!")
};
let migration = dbg!(migration_fetch(cptestctx, migration_id).await);
assert_eq!(migration.target_state, MigrationState::Pending.into());
assert_eq!(migration.source_state, MigrationState::Pending.into());
let info = nexus
.active_instance_info(&instance_id, None)
.await
.unwrap()
.expect("instance should be on a sled");
let src_propolis_id = info.propolis_id;
let dst_propolis_id =
info.dst_propolis_id.expect("instance should have a migration target");
// Simulate the migration. We will use `instance_single_step_on_sled` to
// single-step both sled-agents through the migration state machine and
// ensure that the migration state looks nice at each step.
instance_simulate_migration_source(
cptestctx,
nexus,
original_sled,
src_propolis_id,
migration_id,
)
.await;
// Move source to "migrating".
vmm_single_step_on_sled(cptestctx, nexus, original_sled, src_propolis_id)
.await;
vmm_single_step_on_sled(cptestctx, nexus, original_sled, src_propolis_id)
.await;
let migration = dbg!(migration_fetch(cptestctx, migration_id).await);
assert_eq!(migration.source_state, MigrationState::InProgress.into());
assert_eq!(migration.target_state, MigrationState::Pending.into());
let instance = instance_get(&client, &instance_url).await;
assert_eq!(instance.runtime.run_state, InstanceState::Migrating);
// Move target to "migrating".
vmm_single_step_on_sled(cptestctx, nexus, dst_sled_id, dst_propolis_id)
.await;
vmm_single_step_on_sled(cptestctx, nexus, dst_sled_id, dst_propolis_id)
.await;
let migration = dbg!(migration_fetch(cptestctx, migration_id).await);
assert_eq!(migration.source_state, MigrationState::InProgress.into());
assert_eq!(migration.target_state, MigrationState::InProgress.into());
let instance = instance_get(&client, &instance_url).await;
assert_eq!(instance.runtime.run_state, InstanceState::Migrating);
// Move the source to "completed"
vmm_simulate_on_sled(cptestctx, nexus, original_sled, src_propolis_id)
.await;
let migration = dbg!(migration_fetch(cptestctx, migration_id).await);
assert_eq!(migration.source_state, MigrationState::Completed.into());
assert_eq!(migration.target_state, MigrationState::InProgress.into());
let instance = dbg!(instance_get(&client, &instance_url).await);
assert_eq!(instance.runtime.run_state, InstanceState::Migrating);
// Move the target to "completed".
vmm_simulate_on_sled(cptestctx, nexus, dst_sled_id, dst_propolis_id).await;
instance_wait_for_state(&client, instance_id, InstanceState::Running).await;
let current_sled = nexus
.active_instance_info(&instance_id, None)
.await
.unwrap()
.expect("migrated instance should still have a sled")
.sled_id;
assert_eq!(current_sled, dst_sled_id);
let migration = dbg!(migration_fetch(cptestctx, migration_id).await);
assert_eq!(migration.target_state, MigrationState::Completed.into());
assert_eq!(migration.source_state, MigrationState::Completed.into());
}
#[nexus_test(extra_sled_agents = 3)]
async fn test_instance_migrate_v2p_and_routes(
cptestctx: &ControlPlaneTestContext,
) {
let client = &cptestctx.external_client;
let internal_client = &cptestctx.internal_client;
let apictx = &cptestctx.server.server_context();
let nexus = &apictx.nexus;
let datastore = nexus.datastore();
let opctx =
OpContext::for_tests(cptestctx.logctx.log.new(o!()), datastore.clone());
let instance_name = "desert-locust";
// Get the extra test sleds.
let other_sleds: Vec<_> = cptestctx.extra_sled_agents().collect();
// Set up the project and test instance.
create_project_and_pool(client).await;
let instance = nexus_test_utils::resource_helpers::create_instance_with(
client,
PROJECT_NAME,
instance_name,
¶ms::InstanceNetworkInterfaceAttachment::Default,
// Omit disks: simulated sled agent assumes that disks are always co-
// located with their instances.
Vec::<params::InstanceDiskAttachment>::new(),
Vec::<params::ExternalIpCreate>::new(),
true,
Default::default(),
None,
)
.await;
let instance_id = InstanceUuid::from_untyped_uuid(instance.identity.id);
// The default configuration gives one NIC.
let nics_url = format!("/v1/network-interfaces?instance={}", instance_id);
let nics =
objects_list_page_authz::<InstanceNetworkInterface>(client, &nics_url)
.await
.items;
assert_eq!(nics.len(), 1);
// Poke the instance into an active state.
instance_simulate(nexus, &instance_id).await;
let instance_url = get_instance_url(instance_name);
let instance_next = instance_get(&client, &instance_url).await;
assert_eq!(instance_next.runtime.run_state, InstanceState::Running);
// Ensure that all of the V2P information is correct.
let (.., authz_instance) = LookupPath::new(&opctx, datastore)
.instance_id(instance_id.into_untyped_uuid())
.lookup_for(nexus_db_queries::authz::Action::Read)
.await
.unwrap();
let guest_nics = datastore
.derive_guest_network_interface_info(&opctx, &authz_instance)
.await
.unwrap();
let original_sled_id = nexus
.active_instance_info(&instance_id, None)
.await
.unwrap()
.expect("running instance should have a sled")
.sled_id;
let mut sled_agents = vec![cptestctx.first_sled_agent().clone()];
sled_agents.extend(other_sleds.iter().map(|tup| tup.sled_agent.clone()));
for sled_agent in &sled_agents {
assert_sled_v2p_mappings(sled_agent, &nics[0], guest_nics[0].vni).await;
}
let testctx_sled_id = cptestctx.first_sled_agent().id;
let dst_sled_id = if original_sled_id == testctx_sled_id {
other_sleds[0].sled_agent.id
} else {
testctx_sled_id
};
// Kick off migration and simulate its completion on the target.
let migrate_url =
format!("/instances/{}/migrate", &instance_id.to_string());
let _ = NexusRequest::new(
RequestBuilder::new(internal_client, Method::POST, &migrate_url)
.body(Some(&InstanceMigrateRequest { dst_sled_id }))
.expect_status(Some(StatusCode::OK)),