-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathlib.rs
More file actions
2313 lines (2130 loc) · 80.9 KB
/
lib.rs
File metadata and controls
2313 lines (2130 loc) · 80.9 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/.
//! Integration testing facilities for Nexus
#[cfg(feature = "omicron-dev")]
use anyhow::Context;
use anyhow::Result;
use camino::Utf8Path;
use camino::Utf8PathBuf;
use chrono::Utc;
use dropshot::ConfigLogging;
use dropshot::ConfigLoggingLevel;
use dropshot::HandlerTaskMode;
use dropshot::test_util::ClientTestContext;
use dropshot::test_util::LogContext;
use futures::FutureExt;
use futures::future::BoxFuture;
use gateway_test_utils::setup::DEFAULT_SP_SIM_CONFIG;
use gateway_test_utils::setup::GatewayTestContext;
use hickory_resolver::TokioResolver;
use hickory_resolver::config::NameServerConfig;
use hickory_resolver::config::ResolverConfig;
use hickory_resolver::config::ResolverOpts;
use hickory_resolver::name_server::TokioConnectionProvider;
use hickory_resolver::proto::xfer::Protocol;
use id_map::IdMap;
use internal_dns_types::config::DnsConfigBuilder;
use internal_dns_types::names::DNS_ZONE_EXTERNAL_TESTING;
use internal_dns_types::names::ServiceName;
use nexus_config::Database;
use nexus_config::DpdConfig;
use nexus_config::InternalDns;
use nexus_config::MgdConfig;
use nexus_config::NUM_INITIAL_RESERVED_IP_ADDRESSES;
use nexus_config::NexusConfig;
use nexus_db_queries::db::pub_test_utils::crdb;
use nexus_sled_agent_shared::inventory::HostPhase2DesiredSlots;
use nexus_sled_agent_shared::inventory::OmicronSledConfig;
use nexus_sled_agent_shared::inventory::OmicronZoneDataset;
use nexus_sled_agent_shared::inventory::SledCpuFamily;
use nexus_sled_agent_shared::recovery_silo::RecoverySiloConfig;
use nexus_test_interface::InternalServer;
use nexus_test_interface::NexusServer;
use nexus_types::deployment::Blueprint;
use nexus_types::deployment::BlueprintDatasetConfig;
use nexus_types::deployment::BlueprintDatasetDisposition;
use nexus_types::deployment::BlueprintHostPhase2DesiredSlots;
use nexus_types::deployment::BlueprintPhysicalDiskConfig;
use nexus_types::deployment::BlueprintPhysicalDiskDisposition;
use nexus_types::deployment::BlueprintSledConfig;
use nexus_types::deployment::BlueprintSource;
use nexus_types::deployment::BlueprintZoneConfig;
use nexus_types::deployment::BlueprintZoneDisposition;
use nexus_types::deployment::BlueprintZoneImageSource;
use nexus_types::deployment::BlueprintZoneType;
use nexus_types::deployment::CockroachDbPreserveDowngrade;
use nexus_types::deployment::OmicronZoneExternalFloatingAddr;
use nexus_types::deployment::OmicronZoneExternalFloatingIp;
use nexus_types::deployment::OmicronZoneExternalSnatIp;
use nexus_types::deployment::OximeterReadMode;
use nexus_types::deployment::PlannerConfig;
use nexus_types::deployment::ReconfiguratorConfig;
use nexus_types::deployment::blueprint_zone_type;
use nexus_types::external_api::views::SledState;
use nexus_types::internal_api::params::DnsConfigParams;
use omicron_common::address::DNS_OPTE_IPV4_SUBNET;
use omicron_common::address::NEXUS_OPTE_IPV4_SUBNET;
use omicron_common::address::NTP_OPTE_IPV4_SUBNET;
use omicron_common::address::NTP_PORT;
use omicron_common::api::external::Generation;
use omicron_common::api::external::MacAddr;
use omicron_common::api::external::UserId;
use omicron_common::api::external::Vni;
use omicron_common::api::external::{IdentityMetadata, Name};
use omicron_common::api::internal::nexus::Certificate;
use omicron_common::api::internal::nexus::ProducerEndpoint;
use omicron_common::api::internal::nexus::ProducerKind;
use omicron_common::api::internal::shared::DatasetKind;
use omicron_common::api::internal::shared::NetworkInterface;
use omicron_common::api::internal::shared::NetworkInterfaceKind;
use omicron_common::api::internal::shared::SourceNatConfig;
use omicron_common::api::internal::shared::SwitchLocation;
use omicron_common::disk::CompressionAlgorithm;
use omicron_common::zpool_name::ZpoolName;
use omicron_sled_agent::sim;
use omicron_test_utils::dev;
use omicron_test_utils::dev::poll;
use omicron_test_utils::dev::poll::wait_for_watch_channel_condition;
use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition};
use omicron_uuid_kinds::BlueprintUuid;
use omicron_uuid_kinds::DatasetUuid;
use omicron_uuid_kinds::ExternalIpUuid;
use omicron_uuid_kinds::GenericUuid;
use omicron_uuid_kinds::OmicronZoneUuid;
use omicron_uuid_kinds::PhysicalDiskUuid;
use omicron_uuid_kinds::SledUuid;
use omicron_uuid_kinds::ZpoolUuid;
use oximeter_collector::Oximeter;
use oximeter_producer::LogConfig;
use oximeter_producer::Server as ProducerServer;
use sled_agent_client::types::EarlyNetworkConfig;
use sled_agent_client::types::EarlyNetworkConfigBody;
use sled_agent_client::types::RackNetworkConfigV2;
use slog::{Logger, debug, error, o};
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fmt::Debug;
use std::iter::{once, repeat, zip};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV6};
use std::sync::Arc;
use std::time::Duration;
use uuid::Uuid;
use nexus_types::deployment::PendingMgsUpdates;
pub use sim::TEST_HARDWARE_THREADS;
pub use sim::TEST_RESERVOIR_RAM;
pub mod background;
pub mod db;
pub mod http_testing;
pub mod resource_helpers;
pub mod sql;
pub const SLED_AGENT_UUID: &str = "b6d65341-167c-41df-9b5c-41cded99c229";
pub const SLED_AGENT2_UUID: &str = "039be560-54cc-49e3-88df-1a29dadbf913";
pub const RACK_UUID: &str = nexus_db_queries::db::pub_test_utils::RACK_UUID;
pub const SWITCH_UUID: &str = "dae4e1f1-410e-4314-bff1-fec0504be07e";
pub const PHYSICAL_DISK_UUID: &str = "fbf4e1f1-410e-4314-bff1-fec0504be07e";
pub const OXIMETER_UUID: &str = "39e6175b-4df2-4730-b11d-cbc1e60a2e78";
pub const PRODUCER_UUID: &str = "a6458b7d-87c3-4483-be96-854d814c20de";
pub const RACK_SUBNET: &str = "fd00:1122:3344:0100::/56";
/// Password for the user created by the test suite
///
/// This is only used by the test suite and `omicron-dev run-all` (the latter of
/// which uses the test suite setup code for most of its operation). These are
/// both transient deployments with no sensitive data.
pub const TEST_SUITE_PASSWORD: &str = "oxide";
pub struct ControlPlaneTestContextSledAgent {
_storage: camino_tempfile::Utf8TempDir,
server: sim::Server,
}
impl ControlPlaneTestContextSledAgent {
pub fn sled_agent(&self) -> &Arc<sim::SledAgent> {
&self.server.sled_agent
}
pub fn server(&self) -> &sim::Server {
&self.server
}
pub fn sled_agent_id(&self) -> SledUuid {
self.server.sled_agent.id
}
pub fn local_addr(&self) -> SocketAddr {
self.server.http_server.local_addr()
}
pub async fn start_pantry(&mut self) -> &sim::PantryServer {
self.server.start_pantry().await
}
pub async fn teardown(self) {
self.server.http_server.close().await.unwrap();
}
}
pub struct ControlPlaneTestContext<N> {
pub start_time: chrono::DateTime<chrono::Utc>,
pub external_client: ClientTestContext,
pub techport_client: ClientTestContext,
pub internal_client: ClientTestContext,
pub lockstep_client: ClientTestContext,
pub server: N,
pub database: dev::db::CockroachInstance,
pub database_admin: omicron_cockroach_admin::Server,
pub clickhouse: dev::clickhouse::ClickHouseDeployment,
pub logctx: LogContext,
pub sled_agents: Vec<ControlPlaneTestContextSledAgent>,
pub oximeter: Oximeter,
pub producer: ProducerServer,
pub gateway: BTreeMap<SwitchLocation, GatewayTestContext>,
pub dendrite: HashMap<SwitchLocation, dev::dendrite::DendriteInstance>,
pub mgd: HashMap<SwitchLocation, dev::maghemite::MgdInstance>,
pub external_dns_zone_name: String,
pub external_dns: dns_server::TransientServer,
pub internal_dns: dns_server::TransientServer,
pub initial_blueprint_id: BlueprintUuid,
pub silo_name: Name,
pub user_name: UserId,
pub password: String,
}
impl<N: NexusServer> ControlPlaneTestContext<N> {
/// Return the first simulated ['sim::Server']
pub fn first_sim_server(&self) -> &sim::Server {
self.sled_agents[0].server()
}
/// Return the first simulated Sled Agent
pub fn first_sled_agent(&self) -> &Arc<sim::SledAgent> {
self.sled_agents[0].sled_agent()
}
pub fn first_sled_id(&self) -> SledUuid {
self.sled_agents[0].sled_agent_id()
}
pub fn second_sled_id(&self) -> SledUuid {
self.sled_agents[1].sled_agent_id()
}
pub fn all_sled_agents(&self) -> impl Iterator<Item = &sim::Server> {
self.sled_agents.iter().map(|sa| sa.server())
}
/// Return an iterator over all sled agents except the first one
pub fn extra_sled_agents(&self) -> impl Iterator<Item = &sim::Server> {
self.all_sled_agents().skip(1)
}
/// Find a sled agent that doesn't match the provided ID
pub fn find_sled_agent(&self, exclude_sled: SledUuid) -> Option<SledUuid> {
self.all_sled_agents()
.find(|sa| sa.sled_agent.id != exclude_sled)
.map(|sa| sa.sled_agent.id)
}
pub fn wildcard_silo_dns_name(&self) -> String {
format!("*.sys.{}", self.external_dns_zone_name)
}
/// Wait until at least one inventory collection has been inserted into the
/// datastore.
///
/// # Panics
///
/// Panics if an inventory collection is not found within `timeout`.
pub async fn wait_for_at_least_one_inventory_collection(
&self,
timeout: Duration,
) {
let mut inv_rx = self.server.inventory_load_rx();
match wait_for_watch_channel_condition(
&mut inv_rx,
async |inv| {
if inv.is_some() {
Ok(())
} else {
Err(CondCheckError::<()>::NotYet)
}
},
timeout,
)
.await
{
Ok(()) => (),
Err(poll::Error::TimedOut(elapsed)) => {
panic!("no inventory collection found within {elapsed:?}");
}
Err(poll::Error::PermanentError(())) => {
unreachable!("check can only fail via timeout")
}
}
}
pub fn internal_client(&self) -> nexus_client::Client {
nexus_client::Client::new(
&format!("http://{}", self.internal_client.bind_address),
self.internal_client.client_log.clone(),
)
}
pub async fn teardown(mut self) {
self.server.close().await;
self.database.cleanup().await.unwrap();
self.clickhouse.cleanup().await.unwrap();
for sled_agent in self.sled_agents {
sled_agent.teardown().await;
}
self.oximeter.close().await.unwrap();
self.producer.close().await.unwrap();
for (_, gateway) in self.gateway {
gateway.teardown().await;
}
for (_, mut dendrite) in self.dendrite {
dendrite.cleanup().await.unwrap();
}
for (_, mut mgd) in self.mgd {
mgd.cleanup().await.unwrap();
}
self.logctx.cleanup_successful();
}
}
pub fn load_test_config() -> NexusConfig {
// We load as much configuration as we can from the test suite configuration
// file. In practice, TestContext requires that:
//
// - the Nexus TCP listen port be 0,
// - the CockroachDB TCP listen port be 0, and
// - if the log will go to a file then the path must be the sentinel value
// "UNUSED".
//
// (See LogContext::new() for details.) Given these restrictions, it may
// seem barely worth reading a config file at all. However, developers can
// change the logging level and local IP if they want, and as we add more
// configuration options, we expect many of those can be usefully configured
// (and reconfigured) for the test suite.
let config_file_path = Utf8Path::new("tests/config.test.toml");
NexusConfig::from_file(config_file_path)
.expect("failed to load config.test.toml")
}
pub async fn test_setup<N: NexusServer>(
test_name: &str,
extra_sled_agents: u16,
) -> ControlPlaneTestContext<N> {
let mut config = load_test_config();
test_setup_with_config::<N>(
test_name,
&mut config,
sim::SimMode::Explicit,
None,
extra_sled_agents,
DEFAULT_SP_SIM_CONFIG.into(),
)
.await
}
struct RackInitRequestBuilder {
internal_dns_config: DnsConfigBuilder,
mac_addrs: Box<dyn Iterator<Item = MacAddr> + Send>,
}
impl RackInitRequestBuilder {
fn new() -> Self {
Self {
internal_dns_config: DnsConfigBuilder::new(),
mac_addrs: Box::new(MacAddr::iter_system()),
}
}
fn add_service_to_dns(
&mut self,
zone_id: OmicronZoneUuid,
address: SocketAddrV6,
service_name: ServiceName,
) {
let zone = self
.internal_dns_config
.host_zone(zone_id, *address.ip())
.expect("Failed to set up DNS for {kind}");
self.internal_dns_config
.service_backend_zone(service_name, &zone, address.port())
.expect("Failed to set up DNS for {kind}");
}
fn add_gz_service_to_dns(
&mut self,
sled_id: SledUuid,
address: SocketAddrV6,
service_name: ServiceName,
) {
let sled = self
.internal_dns_config
.host_sled(sled_id, *address.ip())
.expect("Failed to set up DNS for GZ service");
self.internal_dns_config
.service_backend_sled(service_name, &sled, address.port())
.expect("Failed to set up DNS for GZ service");
}
// Special handling of Nexus, which has multiple SRV records for its single
// zone.
fn add_nexus_to_dns(
&mut self,
zone_id: OmicronZoneUuid,
address: SocketAddrV6,
lockstep_port: u16,
) {
self.internal_dns_config
.host_zone_nexus(zone_id, address, lockstep_port)
.expect("Failed to set up Nexus DNS");
}
// Special handling of ClickHouse, which has multiple SRV records for its
// single zone.
fn add_clickhouse_to_dns(
&mut self,
zone_id: OmicronZoneUuid,
address: SocketAddrV6,
) {
self.internal_dns_config
.host_zone_clickhouse_single_node(
zone_id,
ServiceName::Clickhouse,
address,
true,
)
.expect("Failed to setup ClickHouse DNS");
}
// Special handling of internal DNS, which has a second A/AAAA record and an
// NS record pointing to it.
fn add_internal_name_server_to_dns(
&mut self,
zone_id: OmicronZoneUuid,
http_address: SocketAddrV6,
dns_address: SocketAddrV6,
) {
self.internal_dns_config
.host_zone_internal_dns(
zone_id,
ServiceName::InternalDns,
http_address,
dns_address,
)
.expect("Failed to setup internal DNS");
}
}
pub struct ControlPlaneTestContextBuilder<'a, N: NexusServer> {
pub config: &'a mut NexusConfig,
test_name: &'a str,
rack_init_builder: RackInitRequestBuilder,
pub start_time: chrono::DateTime<chrono::Utc>,
pub logctx: LogContext,
pub external_client: Option<ClientTestContext>,
pub techport_client: Option<ClientTestContext>,
pub internal_client: Option<ClientTestContext>,
pub lockstep_client: Option<ClientTestContext>,
pub server: Option<N>,
pub database: Option<dev::db::CockroachInstance>,
pub database_admin: Option<omicron_cockroach_admin::Server>,
pub clickhouse: Option<dev::clickhouse::ClickHouseDeployment>,
pub sled_agents: Vec<ControlPlaneTestContextSledAgent>,
pub oximeter: Option<Oximeter>,
pub producer: Option<ProducerServer>,
pub gateway: BTreeMap<SwitchLocation, GatewayTestContext>,
pub dendrite: HashMap<SwitchLocation, dev::dendrite::DendriteInstance>,
pub mgd: HashMap<SwitchLocation, dev::maghemite::MgdInstance>,
// NOTE: Only exists after starting Nexus, until external Nexus is
// initialized.
nexus_internal: Option<<N as NexusServer>::InternalServer>,
nexus_internal_addr: Option<SocketAddr>,
pub external_dns_zone_name: Option<String>,
pub external_dns: Option<dns_server::TransientServer>,
pub internal_dns: Option<dns_server::TransientServer>,
dns_config: Option<DnsConfigParams>,
initial_blueprint_id: Option<BlueprintUuid>,
// Build sled configs as we go, ensuring that sled-agent's
// initial configuration agrees with the blueprint we build.
blueprint_zones: Vec<BlueprintZoneConfig>,
blueprint_sleds: Option<BTreeMap<SledUuid, BlueprintSledConfig>>,
pub silo_name: Option<Name>,
pub user_name: Option<UserId>,
pub password: Option<String>,
pub simulated_upstairs: Arc<sim::SimulatedUpstairs>,
}
type StepInitFn<'a, N> = Box<
dyn for<'b> FnOnce(
&'b mut ControlPlaneTestContextBuilder<'a, N>,
) -> BoxFuture<'b, ()>,
>;
impl<'a, N: NexusServer> ControlPlaneTestContextBuilder<'a, N> {
pub fn new(test_name: &'a str, config: &'a mut NexusConfig) -> Self {
let start_time = chrono::Utc::now();
let logctx = LogContext::new(test_name, &config.pkg.log);
let simulated_upstairs_log = logctx.log.new(o!(
"component" => "omicron_sled_agent::sim::SimulatedUpstairs",
));
Self {
config,
test_name,
rack_init_builder: RackInitRequestBuilder::new(),
start_time,
logctx,
external_client: None,
techport_client: None,
internal_client: None,
lockstep_client: None,
server: None,
database: None,
database_admin: None,
clickhouse: None,
sled_agents: vec![],
oximeter: None,
producer: None,
gateway: BTreeMap::new(),
dendrite: HashMap::new(),
mgd: HashMap::new(),
nexus_internal: None,
nexus_internal_addr: None,
external_dns_zone_name: None,
external_dns: None,
internal_dns: None,
dns_config: None,
initial_blueprint_id: None,
blueprint_zones: Vec::new(),
blueprint_sleds: None,
silo_name: None,
user_name: None,
password: None,
simulated_upstairs: Arc::new(sim::SimulatedUpstairs::new(
simulated_upstairs_log,
)),
}
}
pub async fn init_with_steps(
&mut self,
steps: Vec<(&str, StepInitFn<'a, N>)>,
timeout: Duration,
) {
let log = self.logctx.log.new(o!("component" => "init_with_steps"));
for (step_name, step) in steps {
debug!(log, "Running step {step_name}");
let step_fut = step(self);
match tokio::time::timeout(timeout, step_fut).await {
Ok(()) => {}
Err(_) => {
error!(
log,
"Timed out after {timeout:?} \
while running step {step_name}, failing test"
);
panic!(
"Timed out after {timeout:?} while running step {step_name}",
);
}
}
}
}
pub async fn start_crdb(&mut self, populate: bool) {
let populate = if populate {
PopulateCrdb::FromEnvironmentSeed
} else {
PopulateCrdb::Empty
};
self.start_crdb_impl(populate).await;
}
/// Private implementation of `start_crdb` that allows for a seed tarball to
/// be passed in. See [`PopulateCrdb`] for more details.
async fn start_crdb_impl(&mut self, populate: PopulateCrdb) {
let log = &self.logctx.log;
debug!(log, "Starting CRDB");
// Start up CockroachDB.
let database = match populate {
PopulateCrdb::FromEnvironmentSeed => {
crdb::test_setup_database(log).await
}
#[cfg(feature = "omicron-dev")]
PopulateCrdb::FromSeed { input_tar } => {
crdb::test_setup_database_from_seed(log, input_tar).await
}
PopulateCrdb::Empty => crdb::test_setup_database_empty(log).await,
};
eprintln!("DB URL: {}", database.pg_config());
let address = database
.pg_config()
.to_string()
.split("postgresql://root@")
.nth(1)
.expect("Malformed URL: Missing postgresql prefix")
.split('/')
.next()
.expect("Malformed URL: No slash after port")
.parse::<std::net::SocketAddrV6>()
.expect("Failed to parse port");
let zone_id = OmicronZoneUuid::new_v4();
let zpool_id = ZpoolUuid::new_v4();
eprintln!("DB address: {}", address);
self.rack_init_builder.add_service_to_dns(
zone_id,
address,
ServiceName::Cockroach,
);
let pool_name = illumos_utils::zpool::ZpoolName::new_external(zpool_id)
.to_string()
.parse()
.unwrap();
self.blueprint_zones.push(BlueprintZoneConfig {
disposition: BlueprintZoneDisposition::InService,
id: zone_id,
filesystem_pool: ZpoolName::new_external(zpool_id),
zone_type: BlueprintZoneType::CockroachDb(
blueprint_zone_type::CockroachDb {
address,
dataset: OmicronZoneDataset { pool_name },
},
),
image_source: BlueprintZoneImageSource::InstallDataset,
});
let http_address = database.http_addr();
self.database = Some(database);
let cli = omicron_cockroach_admin::CockroachCli::new(
omicron_test_utils::dev::db::COCKROACHDB_BIN.into(),
address,
http_address,
);
let server = omicron_cockroach_admin::start_server(
zone_id,
cli,
omicron_cockroach_admin::Config {
dropshot: dropshot::ConfigDropshot::default(),
log: ConfigLogging::StderrTerminal {
level: ConfigLoggingLevel::Error,
},
},
)
.await
.expect("Failed to start CRDB admin server");
self.database_admin = Some(server);
}
// Start ClickHouse database server.
pub async fn start_clickhouse(&mut self) {
let log = &self.logctx.log;
debug!(log, "Starting Clickhouse");
let clickhouse =
dev::clickhouse::ClickHouseDeployment::new_single_node(
&self.logctx,
)
.await
.unwrap();
let zone_id = OmicronZoneUuid::new_v4();
let zpool_id = ZpoolUuid::new_v4();
let http_address = clickhouse.http_address();
let http_port = http_address.port();
let native_address = clickhouse.native_address();
self.rack_init_builder.add_clickhouse_to_dns(zone_id, http_address);
self.clickhouse = Some(clickhouse);
// NOTE: We could pass this port information via DNS, rather than
// requiring it to be known before Nexus starts.
//
// See https://github.com/oxidecomputer/omicron/issues/6407.
self.config
.pkg
.timeseries_db
.address
.as_mut()
.expect("Tests expect to set a port of Clickhouse")
.set_port(http_port);
self.config.pkg.timeseries_db.address = Some(native_address.into());
let pool_name = illumos_utils::zpool::ZpoolName::new_external(zpool_id)
.to_string()
.parse()
.unwrap();
self.blueprint_zones.push(BlueprintZoneConfig {
disposition: BlueprintZoneDisposition::InService,
id: zone_id,
filesystem_pool: ZpoolName::new_external(zpool_id),
zone_type: BlueprintZoneType::Clickhouse(
blueprint_zone_type::Clickhouse {
address: http_address,
dataset: OmicronZoneDataset { pool_name },
},
),
image_source: BlueprintZoneImageSource::InstallDataset,
});
}
pub async fn start_gateway(
&mut self,
switch_location: SwitchLocation,
port: Option<u16>,
sp_sim_config_file: Utf8PathBuf,
) {
debug!(&self.logctx.log, "Starting Management Gateway");
let (mut mgs_config, sp_sim_config) =
gateway_test_utils::setup::load_test_config(sp_sim_config_file);
// The sp_sim_config_file contains suitable configuration information for a MGS daemon running on
// switch0. For switch1, the port information needs to be flipped in order for MGS to correctly identify
// itself as the switch1 MGS daemon.
if switch_location == SwitchLocation::Switch1 {
for config in mgs_config.switch.location.determination.iter_mut() {
let swap = config.sp_port_1.clone();
config.sp_port_1 = config.sp_port_2.clone();
config.sp_port_2 = swap;
}
}
let mgs_addr =
port.map(|port| SocketAddrV6::new(Ipv6Addr::LOCALHOST, port, 0, 0));
let gateway = gateway_test_utils::setup::test_setup_with_config(
self.test_name,
gateway_messages::SpPort::One,
mgs_config,
&sp_sim_config,
mgs_addr,
)
.await;
self.gateway.insert(switch_location, gateway);
}
pub async fn start_dendrite(&mut self, switch_location: SwitchLocation) {
let log = &self.logctx.log;
debug!(log, "Starting Dendrite for {switch_location}");
let mgs = self.gateway.get(&switch_location).unwrap();
let mgs_addr =
SocketAddrV6::new(Ipv6Addr::LOCALHOST, mgs.port, 0, 0).into();
// Set up a stub instance of dendrite
let dendrite = dev::dendrite::DendriteInstance::start(
0,
self.nexus_internal_addr,
Some(mgs_addr),
)
.await
.unwrap();
let port = dendrite.port;
self.dendrite.insert(switch_location, dendrite);
let address = SocketAddrV6::new(Ipv6Addr::LOCALHOST, port, 0, 0);
// Update the configuration options for Nexus, if it's launched later.
//
// NOTE: If dendrite is started after Nexus, this is ignored.
let config = DpdConfig { address: std::net::SocketAddr::V6(address) };
self.config.pkg.dendrite.insert(switch_location, config);
}
pub async fn start_mgd(&mut self, switch_location: SwitchLocation) {
let log = &self.logctx.log;
debug!(log, "Starting mgd for {switch_location}");
// Set up an instance of mgd
let mgd = dev::maghemite::MgdInstance::start(0).await.unwrap();
let port = mgd.port;
self.mgd.insert(switch_location, mgd);
let address = SocketAddrV6::new(Ipv6Addr::LOCALHOST, port, 0, 0);
debug!(log, "mgd port is {port}");
let config = MgdConfig { address: std::net::SocketAddr::V6(address) };
self.config.pkg.mgd.insert(switch_location, config);
}
pub async fn record_switch_dns(
&mut self,
sled_id: SledUuid,
switch_location: SwitchLocation,
) {
let log = &self.logctx.log;
debug!(
log,
"Recording DNS for the switch zones";
"sled_id" => sled_id.to_string(),
"switch_location" => switch_location.to_string(),
);
self.rack_init_builder
.internal_dns_config
.host_zone_switch(
sled_id,
Ipv6Addr::LOCALHOST,
self.dendrite.get(&switch_location).unwrap().port,
self.gateway.get(&switch_location).unwrap().port,
self.mgd.get(&switch_location).unwrap().port,
)
.unwrap();
}
pub async fn start_oximeter(&mut self) {
let log = &self.logctx.log;
debug!(log, "Starting Oximeter");
let nexus_internal_addr = self
.nexus_internal_addr
.expect("Must start Nexus internally before Oximeter");
let clickhouse = self
.clickhouse
.as_ref()
.expect("Must start Clickhouse before oximeter");
// Set up an Oximeter collector server
let collector_id = Uuid::parse_str(OXIMETER_UUID).unwrap();
let oximeter = start_oximeter(
log.new(o!("component" => "oximeter")),
nexus_internal_addr,
clickhouse.native_address().port(),
collector_id,
)
.await
.unwrap();
self.oximeter = Some(oximeter);
}
pub async fn start_producer_server(&mut self) {
let log = &self.logctx.log;
debug!(log, "Starting test metric Producer Server");
let nexus_internal_addr = self
.nexus_internal_addr
.expect("Must start Nexus internally before producer server");
// Set up a test metric producer server
let producer_id = Uuid::parse_str(PRODUCER_UUID).unwrap();
let producer =
start_producer_server(nexus_internal_addr, producer_id).unwrap();
register_test_producer(&producer).unwrap();
self.producer = Some(producer);
}
// Begin starting Nexus.
pub async fn start_nexus_internal(&mut self) -> Result<(), String> {
let log = &self.logctx.log;
debug!(log, "Starting Nexus (internal API)");
// In tests, disable blueprint planning.
self.config.pkg.initial_reconfigurator_config =
Some(ReconfiguratorConfig {
planner_enabled: false,
planner_config: PlannerConfig::default(),
});
self.config.deployment.internal_dns = InternalDns::FromAddress {
address: self
.internal_dns
.as_ref()
.expect("Must initialize internal DNS server first")
.dns_server
.local_address(),
};
self.config.deployment.database = Database::FromUrl {
url: self
.database
.as_ref()
.expect("Must start CRDB before Nexus")
.pg_config()
.clone(),
};
let nexus_internal = N::start_internal(&self.config, &log).await?;
let nexus_internal_addr =
nexus_internal.get_http_server_internal_address();
let internal_address = match nexus_internal_addr {
SocketAddr::V4(addr) => {
SocketAddrV6::new(addr.ip().to_ipv6_mapped(), addr.port(), 0, 0)
}
SocketAddr::V6(addr) => addr,
};
let lockstep_address = match nexus_internal
.get_http_server_lockstep_address()
{
SocketAddr::V4(addr) => {
SocketAddrV6::new(addr.ip().to_ipv6_mapped(), addr.port(), 0, 0)
}
SocketAddr::V6(addr) => addr,
};
assert_eq!(internal_address.ip(), lockstep_address.ip());
self.rack_init_builder.add_nexus_to_dns(
self.config.deployment.id,
internal_address,
lockstep_address.port(),
);
self.record_nexus_zone(
self.config.clone(),
internal_address,
lockstep_address.port(),
0,
);
self.nexus_internal = Some(nexus_internal);
self.nexus_internal_addr = Some(nexus_internal_addr);
Ok(())
}
pub async fn configure_second_nexus(&mut self) {
let log = &self.logctx.log;
debug!(log, "Configuring second Nexus (not to run)");
// Besides the Nexus that we just started, add an entry in the blueprint
// for the Nexus that developers can start using
// nexus/examples/config-second.toml.
//
// The details in its BlueprintZoneType mostly don't matter because
// those are mostly used for DNS (which we don't usually need here) and
// to tell sled agent how to start the zone (which isn't what's going on
// here). But it does need to be present for it to be able to determine
// on startup if it needs to quiesce.
let second_nexus_config_path =
Utf8Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../examples/config-second.toml");
let mut second_nexus_config =
NexusConfig::from_file(&second_nexus_config_path).unwrap();
// Okay, this is particularly awful. The system does not allow multiple
// zones to use the same external IP -- makes sense. But it actually is
// fine here because the IP is localhost and we're using host
// networking, and we've already ensured that the ports will be unique.
// Avoid tripping up the validation by using some other IP. This won't
// be used for anything. Pick something that's not in use anywhere
// else. This range is guaranteed by RFC 6666 to discard traffic.
second_nexus_config
.deployment
.dropshot_external
.dropshot
.bind_address
.set_ip("100::1".parse().unwrap());
let SocketAddr::V6(second_internal_address) =
second_nexus_config.deployment.dropshot_internal.bind_address
else {
panic!(
"expected IPv6 address for dropshot_internal in \
nexus/examples/config-second.toml"
);
};
let second_lockstep_port = second_nexus_config
.deployment
.dropshot_lockstep
.bind_address
.port();
self.record_nexus_zone(
second_nexus_config,
second_internal_address,
second_lockstep_port,
1,
);
}
fn record_nexus_zone(
&mut self,
config: NexusConfig,
internal_address: SocketAddrV6,
lockstep_port: u16,
which: usize,
) {
let id = config.deployment.id;
let mac = self
.rack_init_builder
.mac_addrs
.next()
.expect("ran out of MAC addresses");
self.blueprint_zones.push(BlueprintZoneConfig {
disposition: BlueprintZoneDisposition::InService,
id,
filesystem_pool: ZpoolName::new_external(ZpoolUuid::new_v4()),
zone_type: BlueprintZoneType::Nexus(blueprint_zone_type::Nexus {
external_dns_servers: config
.deployment
.external_dns_servers
.clone(),
external_ip: OmicronZoneExternalFloatingIp {
id: ExternalIpUuid::new_v4(),
ip: config
.deployment
.dropshot_external
.dropshot
.bind_address
.ip(),
},
external_tls: config.deployment.dropshot_external.tls,
internal_address,
lockstep_port,
nic: NetworkInterface {
id: Uuid::new_v4(),
ip: NEXUS_OPTE_IPV4_SUBNET
.nth(NUM_INITIAL_RESERVED_IP_ADDRESSES + 1 + which)
.unwrap()
.into(),
kind: NetworkInterfaceKind::Service {
id: id.into_untyped_uuid(),
},
mac,
name: format!("nexus-{}", id).parse().unwrap(),
primary: true,