-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathdns.rs
1682 lines (1581 loc) · 64.8 KB
/
dns.rs
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/.
//! Propagates DNS changes in a given blueprint
use crate::Sled;
use internal_dns_types::diff::DnsDiff;
use nexus_db_model::DnsGroup;
use nexus_db_queries::context::OpContext;
use nexus_db_queries::db::DataStore;
use nexus_db_queries::db::datastore::Discoverability;
use nexus_db_queries::db::datastore::DnsVersionUpdateBuilder;
use nexus_types::deployment::Blueprint;
use nexus_types::deployment::execution::Overridables;
use nexus_types::deployment::execution::blueprint_external_dns_config;
use nexus_types::deployment::execution::blueprint_internal_dns_config;
use nexus_types::identity::Resource;
use nexus_types::internal_api::params::DnsConfigParams;
use nexus_types::internal_api::params::DnsConfigZone;
use omicron_common::api::external::Error;
use omicron_common::api::external::InternalContext;
use omicron_common::bail_unless;
use omicron_uuid_kinds::SledUuid;
use slog::{debug, info, o};
use std::collections::BTreeMap;
pub(crate) async fn deploy_dns(
opctx: &OpContext,
datastore: &DataStore,
creator: String,
blueprint: &Blueprint,
sleds_by_id: &BTreeMap<SledUuid, Sled>,
overrides: &Overridables,
) -> Result<(), Error> {
// First, fetch the current DNS configs.
let internal_dns_config_current = datastore
.dns_config_read(opctx, DnsGroup::Internal)
.await
.internal_context("reading current DNS (internal)")?;
let external_dns_config_current = datastore
.dns_config_read(opctx, DnsGroup::External)
.await
.internal_context("reading current DNS (external)")?;
// We could check here that the DNS version we found isn't newer than when
// the blueprint was generated. But we have to check later when we try to
// update the database anyway. And we're not wasting much effort allowing
// this proceed for now. This way, we have only one code path for this and
// we know it's being hit when we exercise this condition.
// Next, construct the DNS config represented by the blueprint.
let internal_dns_zone_blueprint =
blueprint_internal_dns_config(blueprint, sleds_by_id, overrides)
.map_err(|e| Error::InternalError {
internal_message: e.to_string(),
})?;
let silos = datastore
.silo_list_all_batched(opctx, Discoverability::All)
.await
.internal_context("listing Silos (for configuring external DNS)")?
.into_iter()
.map(|silo| silo.name().clone())
.collect::<Vec<_>>();
let nexus_external_dns_zone_names = datastore
.dns_zones_list_all(opctx, DnsGroup::External)
.await
.internal_context("listing DNS zones")?
.into_iter()
.map(|z| z.zone_name)
.collect::<Vec<_>>();
// Other parts of the system support multiple external DNS zone names. We
// do not here. If we decide to support this in the future, this mechanism
// will need to be updated.
bail_unless!(
nexus_external_dns_zone_names.len() == 1,
"expected exactly one external DNS zone"
);
// unwrap: we just checked the length.
let external_dns_zone_name =
nexus_external_dns_zone_names.into_iter().next().unwrap();
let external_dns_zone_blueprint = blueprint_external_dns_config(
blueprint,
&silos,
external_dns_zone_name,
);
// Deploy the changes.
deploy_dns_one(
opctx,
datastore,
creator.clone(),
blueprint,
&internal_dns_config_current,
internal_dns_zone_blueprint,
DnsGroup::Internal,
)
.await?;
deploy_dns_one(
opctx,
datastore,
creator,
blueprint,
&external_dns_config_current,
external_dns_zone_blueprint,
DnsGroup::External,
)
.await?;
Ok(())
}
pub(crate) async fn deploy_dns_one(
opctx: &OpContext,
datastore: &DataStore,
creator: String,
blueprint: &Blueprint,
dns_config_current: &DnsConfigParams,
dns_zone_blueprint: DnsConfigZone,
dns_group: DnsGroup,
) -> Result<(), Error> {
let log = opctx
.log
.new(o!("blueprint_execution" => format!("dns {:?}", dns_group)));
// Other parts of the system support multiple external DNS zones. We do not
// do so here.
let dns_zone_current = dns_config_current
.sole_zone()
.map_err(|e| Error::internal_error(&format!("{:#}", e)))?;
// Looking at the current contents of DNS, prepare an update that will make
// it match what it should be.
let comment = format!("blueprint {} ({})", blueprint.id, blueprint.comment);
let maybe_update = dns_compute_update(
&log,
dns_group,
comment,
creator,
dns_zone_current,
&dns_zone_blueprint,
)?;
let Some(update) = maybe_update else {
// Nothing to do.
return Ok(());
};
// Our goal here is to update the DNS configuration stored in the database
// to match the blueprint. But it's always possible that we're executing a
// blueprint that's no longer the current target. In that case, we want to
// fail without making any changes. We definitely don't want to
// accidentally clobber changes that have been made by another instance
// executing a newer target blueprint.
//
// To avoid this problem, before generating a blueprint, Nexus fetches the
// current DNS generation and stores that into the blueprint itself. Here,
// when we execute the blueprint, we make our database update conditional on
// that still being the current DNS generation. If some other instance has
// already come along and updated the database, whether for this same
// blueprint or a newer one, our attempt to update the database will fail.
//
// Let's look at a tricky example. Suppose:
//
// 1. The system starts with some initial blueprint B1 with DNS version 3.
// The blueprint has been fully executed and all is well.
//
// 2. Blueprint B2 gets generated. It stores DNS version 3. It's made the
// current target. Execution has not started yet.
//
// 3. Blueprint B3 gets generated. It also stores DNS version 3 because
// that's still the current version in DNS. B3 is made the current
// target.
//
// Assume B2 and B3 specify different DNS contents (e.g., have a
// different set of Omicron zones in them).
//
// 4. Nexus instance N1 finds B2 to be the current target and starts
// executing it. (Assume it found this between 2 and 3 above.)
//
// 5. Nexus instance N2 finds B3 to be the current target and starts
// executing it.
//
// During execution:
//
// * N1 will assemble a new version of DNS called version 4, generate a diff
// between version 3 (which is fixed) and version 4, and attempt to apply
// this to the database conditional on the current version being version
// 3.
//
// * N2 will do the same, but its version 4 will look different.
//
// Now, one of two things could happen:
//
// 1. N1 wins. Its database update applies successfully. In the database,
// the DNS version becomes version 4. In this case, N2 loses. Its
// database operation fails altogether. At this point, any subsequent
// attempt to execute blueprint B3 will fail because any DNS update will
// be conditional on the database having version 3. The only way out of
// this is for the planner to generate a new blueprint B4 that's exactly
// equivalent to B3 except that the stored DNS version is 4. Then we'll
// be able to execute that.
//
// 2. N2 wins. Its database update applies successfully. In the database,
// the DNS version becomes version 4. In this case, N1 loses. Its
// database operation fails altogether. At this point, any subsequent
// attempt to execute blueprint B3 will fail because any DNS update will
// be conditional on the databae having version 3. No further action is
// needed, though, because we've successfully executed the latest target
// blueprint.
//
// In both cases, the system will (1) converge to having successfully
// executed the target blueprint, and (2) never have rolled any changes back
// -- DNS only ever moves forward, closer to the latest desired state.
let blueprint_generation = match dns_group {
DnsGroup::Internal => blueprint.internal_dns_version,
DnsGroup::External => blueprint.external_dns_version,
};
let dns_config_blueprint = DnsConfigParams {
zones: vec![dns_zone_blueprint],
time_created: chrono::Utc::now(),
generation: blueprint_generation.next(),
};
info!(
log,
"attempting to update from generation {} to generation {}",
dns_config_current.generation,
dns_config_blueprint.generation,
);
datastore
.dns_update_from_version(
opctx,
update,
dns_config_current.generation.into(),
)
.await
}
fn dns_compute_update(
log: &slog::Logger,
dns_group: DnsGroup,
comment: String,
creator: String,
current_zone: &DnsConfigZone,
new_zone: &DnsConfigZone,
) -> Result<Option<DnsVersionUpdateBuilder>, Error> {
let mut update = DnsVersionUpdateBuilder::new(dns_group, comment, creator);
let diff = DnsDiff::new(¤t_zone, &new_zone)
.map_err(|e| Error::internal_error(&format!("{:#}", e)))?;
if diff.is_empty() {
info!(log, "no changes");
return Ok(None);
}
for (name, new_records) in diff.names_added() {
debug!(
log,
"adding name";
"dns_name" => name,
"new_records" => ?new_records,
);
update.add_name(
name.to_string(),
new_records.into_iter().cloned().collect(),
)?;
}
for (name, old_records) in diff.names_removed() {
debug!(
log,
"removing name";
"dns_name" => name,
"old_records" => ?old_records,
);
update.remove_name(name.to_string())?;
}
for (name, old_records, new_records) in diff.names_changed() {
debug!(
log,
"updating name";
"dns_name" => name,
"old_records" => ?old_records,
"new_records" => ?new_records,
);
update.remove_name(name.to_string())?;
update.add_name(
name.to_string(),
new_records.into_iter().cloned().collect(),
)?;
}
Ok(Some(update))
}
#[cfg(test)]
mod test {
use super::*;
use crate::Sled;
use crate::test_utils::overridables_for_test;
use crate::test_utils::realize_blueprint_and_expect;
use id_map::IdMap;
use internal_dns_resolver::Resolver;
use internal_dns_types::config::Host;
use internal_dns_types::config::Zone;
use internal_dns_types::names::BOUNDARY_NTP_DNS_NAME;
use internal_dns_types::names::DNS_ZONE;
use internal_dns_types::names::ServiceName;
use nexus_db_model::DnsGroup;
use nexus_db_model::Silo;
use nexus_db_queries::authn;
use nexus_db_queries::authz;
use nexus_db_queries::context::OpContext;
use nexus_db_queries::db::DataStore;
use nexus_inventory::CollectionBuilder;
use nexus_inventory::now_db_precision;
use nexus_reconfigurator_planning::blueprint_builder::BlueprintBuilder;
use nexus_reconfigurator_planning::example::ExampleSystemBuilder;
use nexus_reconfigurator_preparation::PlanningInputFromDb;
use nexus_sled_agent_shared::inventory::OmicronZoneConfig;
use nexus_sled_agent_shared::inventory::OmicronZoneImageSource;
use nexus_sled_agent_shared::inventory::OmicronZoneType;
use nexus_sled_agent_shared::inventory::SledRole;
use nexus_sled_agent_shared::inventory::ZoneKind;
use nexus_test_utils::resource_helpers::DiskTest;
use nexus_test_utils::resource_helpers::create_silo;
use nexus_test_utils_macros::nexus_test;
use nexus_types::deployment::Blueprint;
use nexus_types::deployment::BlueprintSledConfig;
use nexus_types::deployment::BlueprintTarget;
use nexus_types::deployment::BlueprintZoneConfig;
use nexus_types::deployment::BlueprintZoneDisposition;
use nexus_types::deployment::BlueprintZoneImageSource;
use nexus_types::deployment::BlueprintZoneType;
use nexus_types::deployment::CockroachDbClusterVersion;
use nexus_types::deployment::CockroachDbPreserveDowngrade;
use nexus_types::deployment::CockroachDbSettings;
pub use nexus_types::deployment::OmicronZoneExternalFloatingAddr;
pub use nexus_types::deployment::OmicronZoneExternalFloatingIp;
pub use nexus_types::deployment::OmicronZoneExternalSnatIp;
use nexus_types::deployment::SledFilter;
use nexus_types::deployment::blueprint_zone_type;
use nexus_types::external_api::params;
use nexus_types::external_api::shared;
use nexus_types::external_api::views::SledState;
use nexus_types::identity::Resource;
use nexus_types::internal_api::params::DnsConfigParams;
use nexus_types::internal_api::params::DnsConfigZone;
use nexus_types::internal_api::params::DnsRecord;
use nexus_types::internal_api::params::Srv;
use nexus_types::silo::silo_dns_name;
use omicron_common::address::IpRange;
use omicron_common::address::Ipv6Subnet;
use omicron_common::address::RACK_PREFIX;
use omicron_common::address::SLED_PREFIX;
use omicron_common::address::get_sled_address;
use omicron_common::address::get_switch_zone_address;
use omicron_common::api::external::Generation;
use omicron_common::api::external::IdentityMetadataCreateParams;
use omicron_common::policy::BOUNDARY_NTP_REDUNDANCY;
use omicron_common::policy::COCKROACHDB_REDUNDANCY;
use omicron_common::policy::CRUCIBLE_PANTRY_REDUNDANCY;
use omicron_common::policy::INTERNAL_DNS_REDUNDANCY;
use omicron_common::policy::NEXUS_REDUNDANCY;
use omicron_common::policy::OXIMETER_REDUNDANCY;
use omicron_common::zpool_name::ZpoolName;
use omicron_test_utils::dev::test_setup_log;
use omicron_uuid_kinds::BlueprintUuid;
use omicron_uuid_kinds::ExternalIpUuid;
use omicron_uuid_kinds::OmicronZoneUuid;
use omicron_uuid_kinds::ZpoolUuid;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::mem;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddrV6;
use std::sync::Arc;
type ControlPlaneTestContext =
nexus_test_utils::ControlPlaneTestContext<omicron_nexus::Server>;
fn dns_config_empty() -> DnsConfigParams {
DnsConfigParams {
generation: Generation::new(),
time_created: chrono::Utc::now(),
zones: vec![DnsConfigZone {
zone_name: String::from("internal"),
records: HashMap::new(),
}],
}
}
/// **********************************************************************
/// DEPRECATION WARNING:
///
/// Remove when `deprecated_omicron_zone_config_to_blueprint_zone_config`
/// is deleted.
/// **********************************************************************
///
/// Errors from converting an [`OmicronZoneType`] into a [`BlueprintZoneType`].
#[derive(Debug, Clone)]
pub enum InvalidOmicronZoneType {
#[allow(unused)]
ExternalIpIdRequired { kind: ZoneKind },
}
/// **********************************************************************
/// DEPRECATION WARNING: Do not call this function in new code !!!
/// **********************************************************************
///
/// Convert an [`OmicronZoneConfig`] to a [`BlueprintZoneConfig`].
///
/// A `BlueprintZoneConfig` is a superset of `OmicronZoneConfig` and
/// contains auxiliary information not present in an `OmicronZoneConfig`.
/// Therefore, the only valid direction for a real system to take is a
/// lossy conversion from `BlueprintZoneConfig` to `OmicronZoneConfig`.
/// This function, however, does the opposite. We therefore have to inject
/// fake information to fill in the unknown fields in the generated
/// `OmicronZoneConfig`.
///
/// This is bad, and we should generally feel bad for doing it :). At
/// the time this was done we were backporting the blueprint system into
/// RSS while trying not to change too much code. This was a judicious
/// shortcut used right before a release for stability reasons. As the
/// number of zones managed by the reconfigurator has grown, the use
/// of this function has become more egregious, and so it was removed
/// from the production code path and into this test module. This move
/// itself is a judicious shortcut. We have a test in this module,
/// `test_blueprint_internal_dns_basic`, that is the last caller of this
/// function, and so we have moved this function into this module.
///
/// Ideally, we would get rid of this function altogether and use another
/// method for generating `BlueprintZoneConfig` structures. Unfortunately,
/// there are still a few remaining zones that need to be implemented in the
/// `BlueprintBuilder`, and some of them require custom code. Until that is
/// done, we don't have a good way of generating a test representation of
/// the real system that would properly serve this test. We could generate
/// a `BlueprintZoneConfig` by hand for each zone type in this test, on
/// top of the more modern `SystemDescription` setup, but that isn't much
/// different than what we do in this test. We'd also eventually remove it
/// for better test setup when our `BlueprintBuilder` is capable of properly
/// constructing all zone types. Instead, we do the simple thing, and reuse
/// what we alreaady have.
///
/// # Errors
///
/// If `config.zone_type` is a zone that has an external IP address (Nexus,
/// boundary NTP, external DNS), `external_ip_id` must be `Some(_)` or this
/// method will return an error.
pub fn deprecated_omicron_zone_config_to_blueprint_zone_config(
config: OmicronZoneConfig,
disposition: BlueprintZoneDisposition,
external_ip_id: Option<ExternalIpUuid>,
) -> Result<BlueprintZoneConfig, InvalidOmicronZoneType> {
let kind = config.zone_type.kind();
let zone_type = match config.zone_type {
OmicronZoneType::BoundaryNtp {
address,
dns_servers,
domain,
nic,
ntp_servers,
snat_cfg,
} => {
let external_ip_id = external_ip_id.ok_or(
InvalidOmicronZoneType::ExternalIpIdRequired { kind },
)?;
BlueprintZoneType::BoundaryNtp(
blueprint_zone_type::BoundaryNtp {
address,
ntp_servers,
dns_servers,
domain,
nic,
external_ip: OmicronZoneExternalSnatIp {
id: external_ip_id,
snat_cfg,
},
},
)
}
OmicronZoneType::Clickhouse { address, dataset } => {
BlueprintZoneType::Clickhouse(blueprint_zone_type::Clickhouse {
address,
dataset,
})
}
OmicronZoneType::ClickhouseKeeper { address, dataset } => {
BlueprintZoneType::ClickhouseKeeper(
blueprint_zone_type::ClickhouseKeeper { address, dataset },
)
}
OmicronZoneType::ClickhouseServer { address, dataset } => {
BlueprintZoneType::ClickhouseServer(
blueprint_zone_type::ClickhouseServer { address, dataset },
)
}
OmicronZoneType::CockroachDb { address, dataset } => {
BlueprintZoneType::CockroachDb(
blueprint_zone_type::CockroachDb { address, dataset },
)
}
OmicronZoneType::Crucible { address, dataset } => {
BlueprintZoneType::Crucible(blueprint_zone_type::Crucible {
address,
dataset,
})
}
OmicronZoneType::CruciblePantry { address } => {
BlueprintZoneType::CruciblePantry(
blueprint_zone_type::CruciblePantry { address },
)
}
OmicronZoneType::ExternalDns {
dataset,
dns_address,
http_address,
nic,
} => {
let external_ip_id = external_ip_id.ok_or(
InvalidOmicronZoneType::ExternalIpIdRequired { kind },
)?;
BlueprintZoneType::ExternalDns(
blueprint_zone_type::ExternalDns {
dataset,
http_address,
dns_address: OmicronZoneExternalFloatingAddr {
id: external_ip_id,
addr: dns_address,
},
nic,
},
)
}
OmicronZoneType::InternalDns {
dataset,
dns_address,
gz_address,
gz_address_index,
http_address,
} => BlueprintZoneType::InternalDns(
blueprint_zone_type::InternalDns {
dataset,
http_address,
dns_address,
gz_address,
gz_address_index,
},
),
OmicronZoneType::InternalNtp { address } => {
BlueprintZoneType::InternalNtp(
blueprint_zone_type::InternalNtp { address },
)
}
OmicronZoneType::Nexus {
external_dns_servers,
external_ip,
external_tls,
internal_address,
nic,
} => {
let external_ip_id = external_ip_id.ok_or(
InvalidOmicronZoneType::ExternalIpIdRequired { kind },
)?;
BlueprintZoneType::Nexus(blueprint_zone_type::Nexus {
internal_address,
external_ip: OmicronZoneExternalFloatingIp {
id: external_ip_id,
ip: external_ip,
},
nic,
external_tls,
external_dns_servers,
})
}
OmicronZoneType::Oximeter { address } => {
BlueprintZoneType::Oximeter(blueprint_zone_type::Oximeter {
address,
})
}
};
let image_source = match config.image_source {
OmicronZoneImageSource::InstallDataset => {
BlueprintZoneImageSource::InstallDataset
}
OmicronZoneImageSource::Artifact { .. } => {
// BlueprintZoneImageSource::Artifact has both a version and a
// hash in it, while OmicronZoneImageSource::Artifact only has a
// hash field. Rather than conjuring up a fake version, we
// simply panic here.
unreachable!(
"this test does not use OmicronZoneImageSource::Artifact"
)
}
};
Ok(BlueprintZoneConfig {
disposition,
id: config.id,
filesystem_pool: config.filesystem_pool,
zone_type,
image_source,
})
}
/// test blueprint_internal_dns_config(): trivial case of an empty blueprint
#[test]
fn test_blueprint_internal_dns_empty() {
let blueprint = BlueprintBuilder::build_empty_with_sleds(
std::iter::empty(),
"test-suite",
);
let blueprint_dns = blueprint_internal_dns_config(
&blueprint,
&BTreeMap::new(),
&Default::default(),
)
.unwrap();
assert!(blueprint_dns.records.is_empty());
}
/// test blueprint_dns_config(): exercise various different conditions
/// - one of each type of zone in service
/// - some zones not in service
#[test]
fn test_blueprint_internal_dns_basic() {
// We'll use the standard representative inventory collection to build a
// blueprint. The main thing we care about here is that we have at
// least one zone of each type. Later, we'll mark a couple of the sleds
// as Scrimlets to exercise that case.
let representative = nexus_inventory::examples::representative();
let collection = representative.builder.build();
let rack_subnet_base: Ipv6Addr =
"fd00:1122:3344:0100::".parse().unwrap();
let rack_subnet =
ipnet::Ipv6Net::new(rack_subnet_base, RACK_PREFIX).unwrap();
let possible_sled_subnets = rack_subnet.subnets(SLED_PREFIX).unwrap();
let mut blueprint_sleds = BTreeMap::new();
for (sled_id, sa) in collection.sled_agents {
// Convert the inventory `OmicronZonesConfig`s into
// `BlueprintZoneConfig`s. This is going to get more painful over
// time as we add to blueprints, but for now we can make this work.
let zones = sa
.omicron_zones
.zones
.into_iter()
.map(|config| -> BlueprintZoneConfig {
deprecated_omicron_zone_config_to_blueprint_zone_config(
config,
BlueprintZoneDisposition::InService,
// We don't get external IP IDs in inventory
// collections. We'll just make one up for every
// zone that needs one here. This is gross.
Some(ExternalIpUuid::new_v4()),
)
.expect("failed to convert zone config")
})
.collect();
blueprint_sleds.insert(
sled_id,
BlueprintSledConfig {
state: SledState::Active,
sled_agent_generation: sa.omicron_zones.generation,
disks: IdMap::new(),
datasets: IdMap::new(),
zones,
},
);
}
let dns_empty = dns_config_empty();
let initial_dns_generation = dns_empty.generation;
let mut blueprint = Blueprint {
id: BlueprintUuid::new_v4(),
sleds: blueprint_sleds,
pending_mgs_updates: BTreeMap::new(),
cockroachdb_setting_preserve_downgrade:
CockroachDbPreserveDowngrade::DoNotModify,
parent_blueprint_id: None,
internal_dns_version: initial_dns_generation,
external_dns_version: Generation::new(),
cockroachdb_fingerprint: String::new(),
clickhouse_cluster_config: None,
time_created: now_db_precision(),
creator: "test-suite".to_string(),
comment: "test blueprint".to_string(),
};
// To make things slightly more interesting, let's add a zone that's
// not currently in service.
let out_of_service_id = OmicronZoneUuid::new_v4();
let out_of_service_addr = Ipv6Addr::LOCALHOST;
blueprint.sleds.values_mut().next().unwrap().zones.insert(
BlueprintZoneConfig {
disposition: BlueprintZoneDisposition::Expunged {
as_of_generation: Generation::new(),
ready_for_cleanup: false,
},
id: out_of_service_id,
filesystem_pool: Some(ZpoolName::new_external(
ZpoolUuid::new_v4(),
)),
zone_type: BlueprintZoneType::Oximeter(
blueprint_zone_type::Oximeter {
address: SocketAddrV6::new(
out_of_service_addr,
12345,
0,
0,
),
},
),
image_source: BlueprintZoneImageSource::InstallDataset,
},
);
// To generate the blueprint's DNS config, we need to make up a
// different set of information about the Quiesced fake system.
let sleds_by_id = blueprint
.sleds
.keys()
.zip(possible_sled_subnets)
.enumerate()
.map(|(i, (sled_id, subnet))| {
let sled_info = Sled::new(
*sled_id,
get_sled_address(Ipv6Subnet::new(subnet.network())),
// The first two of these (arbitrarily) will be marked
// Scrimlets.
if i < 2 { SledRole::Scrimlet } else { SledRole::Gimlet },
);
(*sled_id, sled_info)
})
.collect();
let mut blueprint_dns_zone = blueprint_internal_dns_config(
&blueprint,
&sleds_by_id,
&Default::default(),
)
.unwrap();
assert_eq!(blueprint_dns_zone.zone_name, DNS_ZONE);
// Now, verify a few different properties about the generated DNS
// configuration:
//
// 1. Every zone (except for the one that we added not-in-service)
// should have some DNS name with a AAAA record that points at the
// zone's underlay IP. (i.e., every Omiron zone is _in_ DNS)
//
// 2. Every SRV record that we find should have a "target" that points
// to another name within the DNS configuration, and that name should
// be one of the ones with a AAAA record pointing to an Omicron zone.
//
// 3. There is at least one SRV record for each service that we expect
// to appear in the representative system that we're working with.
//
// 4. Our out-of-service zone does *not* appear in the DNS config,
// neither with an AAAA record nor in an SRV record.
//
// 5. The boundary NTP zones' IP addresses are mapped to AAAA records in
// the special boundary DNS name (in addition to having their normal
// zone DNS name -> AAAA record from 1).
//
// Together, this tells us that we have SRV records for all services,
// that those SRV records all point to at least one of the Omicron zones
// for that service, and that we correctly ignored zones that were not
// in service.
// To start, we need a mapping from underlay IP to the corresponding
// Omicron zone.
let mut omicron_zones_by_ip: BTreeMap<_, _> = blueprint
.all_omicron_zones(BlueprintZoneDisposition::is_in_service)
.map(|(_, zone)| (zone.underlay_ip(), zone.id))
.collect();
println!("omicron zones by IP: {:#?}", omicron_zones_by_ip);
// Check to see that the out-of-service zone was actually excluded
assert!(
omicron_zones_by_ip.values().all(|id| *id != out_of_service_id)
);
// We also want a mapping from underlay IP to the corresponding switch
// zone. In this case, the value is the Scrimlet's sled id.
let mut switch_sleds_by_ip: BTreeMap<_, _> = sleds_by_id
.iter()
.filter_map(|(sled_id, sled)| {
if sled.is_scrimlet() {
let sled_subnet =
sleds_by_id.get(sled_id).unwrap().subnet();
let switch_zone_ip = get_switch_zone_address(sled_subnet);
Some((switch_zone_ip, *sled_id))
} else {
None
}
})
.collect();
// Prune the special boundary NTP DNS name out, collecting their IP
// addresses, and build a list of expected SRV targets to ensure these
// IPs show up both in the special boundary NTP DNS name and as their
// normal SRV records.
let boundary_ntp_ips = blueprint_dns_zone
.records
.remove(BOUNDARY_NTP_DNS_NAME)
.expect("missing boundary NTP DNS name")
.into_iter()
.map(|record| match record {
DnsRecord::Aaaa(ip) => ip,
_ => panic!("expected AAAA record; got {record:?}"),
});
let mut expected_boundary_ntp_srv_targets = boundary_ntp_ips
.map(|ip| {
let Some(zone_id) = omicron_zones_by_ip.get(&ip) else {
panic!("did not find zone ID for boundary NTP IP {ip}");
};
let name = Host::Zone(Zone::Other(*zone_id)).fqdn();
println!(
"Boundary NTP IP {ip} maps to expected \
SRV record target {name}"
);
name
})
.collect::<BTreeSet<_>>();
// Now go through all the DNS names that have AAAA records and remove
// any corresponding Omicron zone. While doing this, construct a set of
// the fully-qualified DNS names (i.e., with the zone name suffix
// appended) that had AAAA records. We'll use this later to make sure
// all the SRV records' targets that we find are valid.
let mut expected_srv_targets: BTreeSet<_> = BTreeSet::new();
for (name, records) in &blueprint_dns_zone.records {
let addrs: Vec<_> = records
.iter()
.filter_map(|dns_record| match dns_record {
DnsRecord::Aaaa(addr) => Some(addr),
_ => None,
})
.collect();
for addr in addrs {
if let Some(zone_id) = omicron_zones_by_ip.remove(addr) {
println!(
"IP {} found in DNS corresponds with zone {}",
addr, zone_id
);
expected_srv_targets.insert(format!(
"{}.{}",
name, blueprint_dns_zone.zone_name
));
continue;
}
if let Some(scrimlet_id) = switch_sleds_by_ip.remove(addr) {
println!(
"IP {} found in DNS corresponds with switch zone \
for Scrimlet {}",
addr, scrimlet_id
);
expected_srv_targets.insert(format!(
"{}.{}",
name, blueprint_dns_zone.zone_name
));
continue;
}
println!(
"note: found IP ({}) not corresponding to any \
Omicron zone or switch zone (name {:?})",
addr, name
);
}
}
println!(
"Omicron zones whose IPs were not found in DNS: {:?}",
omicron_zones_by_ip,
);
assert!(
omicron_zones_by_ip.is_empty(),
"some Omicron zones' IPs were not found in DNS"
);
println!(
"Scrimlets whose switch zone IPs were not found in DNS: {:?}",
switch_sleds_by_ip,
);
assert!(
switch_sleds_by_ip.is_empty(),
"some switch zones' IPs were not found in DNS"
);
// Now go through all DNS names that have SRV records. For each one,
//
// 1. If its name corresponds to the name of one of the SRV services
// that we expect the system to have, record that fact. At the end
// we'll verify that we found at least one SRV record for each such
// service.
//
// 2. Make sure that the SRV record points at a name that we found in
// the previous pass (i.e., that corresponds to an Omicron zone).
//
// There are some ServiceNames missing here because they are not part of
// our representative config (e.g., ClickhouseKeeper) or they don't
// currently have DNS record at all (e.g., SledAgent, Maghemite, Mgd,
// Tfport).
let mut srv_kinds_expected = BTreeSet::from([
ServiceName::Clickhouse,
ServiceName::ClickhouseNative,
ServiceName::Cockroach,
ServiceName::InternalDns,
ServiceName::ExternalDns,
ServiceName::Nexus,
ServiceName::Oximeter,
ServiceName::Dendrite,
ServiceName::CruciblePantry,
ServiceName::BoundaryNtp,
ServiceName::InternalNtp,
]);
for (name, records) in &blueprint_dns_zone.records {
let mut this_kind = None;
let kinds_left: Vec<_> =
srv_kinds_expected.iter().copied().collect();
for kind in kinds_left {
if kind.dns_name() == *name {
srv_kinds_expected.remove(&kind);
this_kind = Some(kind);
}
}
let srvs: Vec<_> = records
.iter()
.filter_map(|dns_record| match dns_record {
DnsRecord::Srv(srv) => Some(srv),
_ => None,
})
.collect();
for srv in srvs {
assert!(
expected_srv_targets.contains(&srv.target),
"found SRV record with target {:?} that does not \
correspond to a name that points to any Omicron zone",
srv.target
);
if this_kind == Some(ServiceName::BoundaryNtp) {
assert!(
expected_boundary_ntp_srv_targets.contains(&srv.target),
"found boundary NTP SRV record with target {:?} \
that does not correspond to an expected boundary \
NTP zone",
srv.target,
);
expected_boundary_ntp_srv_targets.remove(&srv.target);
}
}
}
println!("SRV kinds with no records found: {:?}", srv_kinds_expected);
assert!(srv_kinds_expected.is_empty());
println!(
"Boundary NTP SRV targets not found: {:?}",
expected_boundary_ntp_srv_targets
);
assert!(expected_boundary_ntp_srv_targets.is_empty());
}
#[tokio::test]
async fn test_blueprint_external_dns_basic() {
static TEST_NAME: &str = "test_blueprint_external_dns_basic";
let logctx = test_setup_log(TEST_NAME);
let (_, mut blueprint) =
ExampleSystemBuilder::new(&logctx.log, TEST_NAME).nsleds(5).build();
blueprint.internal_dns_version = Generation::new();
blueprint.external_dns_version = Generation::new();
let my_silo = Silo::new(params::SiloCreate {
identity: IdentityMetadataCreateParams {
name: "my-silo".parse().unwrap(),
description: String::new(),
},
quotas: params::SiloQuotasCreate::empty(),
discoverable: false,
identity_mode: shared::SiloIdentityMode::SamlJit,
admin_group_name: None,
tls_certificates: vec![],
mapped_fleet_roles: Default::default(),
})
.unwrap();
// It shouldn't ever be possible to have no Silos at all, but at least
// make sure we don't panic.
let external_dns_zone = blueprint_external_dns_config(
&blueprint,
&[],