-
Notifications
You must be signed in to change notification settings - Fork 40
/
deployment.rs
1420 lines (1274 loc) · 48.1 KB
/
deployment.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/.
//! Types representing deployed software and configuration
//!
//! For more on this, see the crate-level documentation for
//! `nexus/reconfigurator/planning`.
//!
//! This lives in nexus/types because it's used by both nexus/db-model and
//! nexus/reconfigurator/planning. (It could as well just live in
//! nexus/db-model, but nexus/reconfigurator/planning does not currently know
//! about nexus/db-model and it's convenient to separate these concerns.)
use crate::external_api::views::SledState;
use crate::internal_api::params::DnsConfigParams;
use crate::inventory::Collection;
pub use crate::inventory::SourceNatConfig;
pub use crate::inventory::ZpoolName;
use blueprint_diff::ClickhouseClusterConfigDiffTablesForSingleBlueprint;
use derive_more::From;
use nexus_sled_agent_shared::inventory::OmicronZoneConfig;
use nexus_sled_agent_shared::inventory::OmicronZoneType;
use nexus_sled_agent_shared::inventory::OmicronZonesConfig;
use nexus_sled_agent_shared::inventory::ZoneKind;
use omicron_common::api::external::ByteCount;
use omicron_common::api::external::Generation;
use omicron_common::api::internal::shared::DatasetKind;
use omicron_common::disk::CompressionAlgorithm;
use omicron_common::disk::DatasetConfig;
use omicron_common::disk::DatasetName;
use omicron_common::disk::DatasetsConfig;
use omicron_common::disk::DiskIdentity;
use omicron_common::disk::OmicronPhysicalDisksConfig;
use omicron_common::disk::SharedDatasetConfig;
use omicron_uuid_kinds::CollectionUuid;
use omicron_uuid_kinds::DatasetUuid;
use omicron_uuid_kinds::OmicronZoneUuid;
use omicron_uuid_kinds::SledUuid;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::fmt;
use std::net::Ipv6Addr;
use std::net::SocketAddrV6;
use strum::EnumIter;
use strum::IntoEnumIterator;
use uuid::Uuid;
mod blueprint_diff;
mod blueprint_display;
mod clickhouse;
pub mod execution;
mod network_resources;
mod planning_input;
mod tri_map;
mod zone_type;
pub use clickhouse::ClickhouseClusterConfig;
pub use network_resources::AddNetworkResourceError;
pub use network_resources::OmicronZoneExternalFloatingAddr;
pub use network_resources::OmicronZoneExternalFloatingIp;
pub use network_resources::OmicronZoneExternalIp;
pub use network_resources::OmicronZoneExternalIpEntry;
pub use network_resources::OmicronZoneExternalIpKey;
pub use network_resources::OmicronZoneExternalSnatIp;
pub use network_resources::OmicronZoneNetworkResources;
pub use network_resources::OmicronZoneNic;
pub use network_resources::OmicronZoneNicEntry;
pub use planning_input::ClickhouseMode;
pub use planning_input::ClickhousePolicy;
pub use planning_input::CockroachDbClusterVersion;
pub use planning_input::CockroachDbPreserveDowngrade;
pub use planning_input::CockroachDbSettings;
pub use planning_input::DiskFilter;
pub use planning_input::PlanningInput;
pub use planning_input::PlanningInputBuildError;
pub use planning_input::PlanningInputBuilder;
pub use planning_input::Policy;
pub use planning_input::SledDetails;
pub use planning_input::SledDisk;
pub use planning_input::SledFilter;
pub use planning_input::SledLookupError;
pub use planning_input::SledLookupErrorKind;
pub use planning_input::SledResources;
pub use planning_input::ZpoolFilter;
pub use zone_type::blueprint_zone_type;
pub use zone_type::BlueprintZoneType;
pub use zone_type::DurableDataset;
use blueprint_display::{
constants::*, BpDiffState, BpGeneration, BpOmicronZonesTableSchema,
BpPhysicalDisksTableSchema, BpTable, BpTableData, BpTableRow,
KvListWithHeading,
};
pub use blueprint_diff::BlueprintDiff;
/// Describes a complete set of software and configuration for the system
// Blueprints are a fundamental part of how the system modifies itself. Each
// blueprint completely describes all of the software and configuration
// that the control plane manages. See the nexus/reconfigurator/planning
// crate-level documentation for details.
//
// Blueprints are different from policy. Policy describes the things that an
// operator would generally want to control. The blueprint describes the
// details of implementing that policy that an operator shouldn't have to deal
// with. For example, the operator might write policy that says "I want
// 5 external DNS zones". The system could then generate a blueprint that
// _has_ 5 external DNS zones on 5 specific sleds. The blueprint includes all
// the details needed to achieve that, including which image these zones should
// run, which zpools their persistent data should be stored on, their public and
// private IP addresses, their internal DNS names, etc.
//
// It must be possible for multiple Nexus instances to execute the same
// blueprint concurrently and converge to the same thing. Thus, these _cannot_
// be how a blueprint works:
//
// - "add a Nexus zone" -- two Nexus instances operating concurrently would
// add _two_ Nexus zones (which is wrong)
// - "ensure that there is a Nexus zone on this sled with this id" -- the IP
// addresses and images are left unspecified. Two Nexus instances could pick
// different IPs or images for the zone.
//
// This is why blueprints must be so detailed. The key principle here is that
// **all the work of ensuring that the system do the right thing happens in one
// process (the update planner in one Nexus instance). Once a blueprint has
// been committed, everyone is on the same page about how to execute it.** The
// intent is that this makes both planning and executing a lot easier. In
// particular, by the time we get to execution, all the hard choices have
// already been made.
//
// Currently, blueprints are limited to describing only the set of Omicron
// zones deployed on each host and some supporting configuration (e.g., DNS).
// This is aimed at supporting add/remove sleds. The plan is to grow this to
// include more of the system as we support more use cases.
#[derive(Clone, Debug, Eq, PartialEq, JsonSchema, Deserialize, Serialize)]
pub struct Blueprint {
/// unique identifier for this blueprint
pub id: Uuid,
/// A map of sled id -> desired state of the sled.
///
/// A sled is considered part of the control plane cluster iff it has an
/// entry in this map.
pub sled_state: BTreeMap<SledUuid, SledState>,
/// A map of sled id -> zones deployed on each sled, along with the
/// [`BlueprintZoneDisposition`] for each zone.
///
/// Unlike `sled_state`, this map may contain entries for sleds that are no
/// longer a part of the control plane cluster (e.g., sleds that have been
/// decommissioned, but still have expunged zones where cleanup has not yet
/// completed).
pub blueprint_zones: BTreeMap<SledUuid, BlueprintZonesConfig>,
/// A map of sled id -> disks in use on each sled.
pub blueprint_disks: BTreeMap<SledUuid, BlueprintPhysicalDisksConfig>,
/// A map of sled id -> datasets in use on each sled
pub blueprint_datasets: BTreeMap<SledUuid, BlueprintDatasetsConfig>,
/// which blueprint this blueprint is based on
pub parent_blueprint_id: Option<Uuid>,
/// internal DNS version when this blueprint was created
// See blueprint execution for more on this.
pub internal_dns_version: Generation,
/// external DNS version when thi blueprint was created
// See blueprint execution for more on this.
pub external_dns_version: Generation,
/// CockroachDB state fingerprint when this blueprint was created
// See `nexus/db-queries/src/db/datastore/cockroachdb_settings.rs` for more
// on this.
pub cockroachdb_fingerprint: String,
/// Whether to set `cluster.preserve_downgrade_option` and what to set it to
pub cockroachdb_setting_preserve_downgrade: CockroachDbPreserveDowngrade,
/// Allocation of Clickhouse Servers and Keepers for replicated clickhouse
/// setups. This is set to `None` if replicated clickhouse is not in use.
pub clickhouse_cluster_config: Option<ClickhouseClusterConfig>,
/// when this blueprint was generated (for debugging)
pub time_created: chrono::DateTime<chrono::Utc>,
/// identity of the component that generated the blueprint (for debugging)
/// This would generally be the Uuid of a Nexus instance.
pub creator: String,
/// human-readable string describing why this blueprint was created
/// (for debugging)
pub comment: String,
}
impl Blueprint {
/// Return metadata for this blueprint.
pub fn metadata(&self) -> BlueprintMetadata {
BlueprintMetadata {
id: self.id,
parent_blueprint_id: self.parent_blueprint_id,
internal_dns_version: self.internal_dns_version,
external_dns_version: self.external_dns_version,
cockroachdb_fingerprint: self.cockroachdb_fingerprint.clone(),
cockroachdb_setting_preserve_downgrade: Some(
self.cockroachdb_setting_preserve_downgrade,
),
time_created: self.time_created,
creator: self.creator.clone(),
comment: self.comment.clone(),
}
}
/// Iterate over the [`BlueprintZoneConfig`] instances in the blueprint
/// that match the provided filter, along with the associated sled id.
pub fn all_omicron_zones(
&self,
filter: BlueprintZoneFilter,
) -> impl Iterator<Item = (SledUuid, &BlueprintZoneConfig)> {
Blueprint::filtered_zones(&self.blueprint_zones, filter)
}
/// Iterate over the [`BlueprintZoneConfig`] instances that match the
/// provided filter, along with the associated sled id.
//
// This is a scoped function so that it can be used in the
// `BlueprintBuilder` during planning as well as in the `Blueprint`.
pub fn filtered_zones(
zones_by_sled_id: &BTreeMap<SledUuid, BlueprintZonesConfig>,
filter: BlueprintZoneFilter,
) -> impl Iterator<Item = (SledUuid, &BlueprintZoneConfig)> {
zones_by_sled_id.iter().flat_map(move |(sled_id, z)| {
z.zones
.iter()
.filter(move |z| z.disposition.matches(filter))
.map(|z| (*sled_id, z))
})
}
/// Iterate over the [`BlueprintDatasetsConfig`] instances in the blueprint.
pub fn all_omicron_datasets(
&self,
filter: BlueprintDatasetFilter,
) -> impl Iterator<Item = &BlueprintDatasetConfig> {
self.blueprint_datasets
.iter()
.flat_map(move |(_, datasets)| datasets.datasets.values())
.filter(move |d| d.disposition.matches(filter))
}
/// Iterate over the [`BlueprintZoneConfig`] instances in the blueprint
/// that do not match the provided filter, along with the associated sled
/// id.
pub fn all_omicron_zones_not_in(
&self,
filter: BlueprintZoneFilter,
) -> impl Iterator<Item = (SledUuid, &BlueprintZoneConfig)> {
self.blueprint_zones.iter().flat_map(move |(sled_id, z)| {
z.zones
.iter()
.filter(move |z| !z.disposition.matches(filter))
.map(|z| (*sled_id, z))
})
}
/// Iterate over the ids of all sleds in the blueprint
pub fn sleds(&self) -> impl Iterator<Item = SledUuid> + '_ {
self.blueprint_zones.keys().copied()
}
/// Summarize the difference between two blueprints.
///
/// The argument provided is the "before" side, and `self` is the "after"
/// side. This matches the order of arguments to
/// [`Blueprint::diff_since_collection`].
pub fn diff_since_blueprint(&self, before: &Blueprint) -> BlueprintDiff {
BlueprintDiff::new(
DiffBeforeMetadata::Blueprint(Box::new(before.metadata())),
DiffBeforeClickhouseClusterConfig::from(before),
before.sled_state.clone(),
before
.blueprint_zones
.iter()
.map(|(sled_id, zones)| (*sled_id, zones.clone().into()))
.collect(),
before
.blueprint_disks
.iter()
.map(|(sled_id, disks)| (*sled_id, disks.clone().into()))
.collect(),
before
.blueprint_datasets
.iter()
.map(|(sled_id, datasets)| (*sled_id, datasets.clone().into()))
.collect(),
&self,
)
}
/// Summarize the differences between a collection and a blueprint.
///
/// This gives an idea about what would change about a running system if
/// one were to execute the blueprint.
///
/// Note that collections do not include information about zone
/// disposition, so it is assumed that all zones in the collection have the
/// [`InService`](BlueprintZoneDisposition::InService) disposition.
pub fn diff_since_collection(&self, before: &Collection) -> BlueprintDiff {
// We'll assume any sleds present in a collection were active; if they
// were decommissioned they wouldn't be present.
let before_state = before
.sled_agents
.keys()
.map(|sled_id| (*sled_id, SledState::Active))
.collect();
let before_zones = before
.sled_agents
.iter()
.map(|(sled_id, sa)| (*sled_id, sa.omicron_zones.clone().into()))
.collect();
let before_disks = before
.sled_agents
.iter()
.map(|(sled_id, sa)| {
(
*sled_id,
CollectionPhysicalDisksConfig {
disks: sa
.disks
.iter()
.map(|d| d.identity.clone())
.collect::<BTreeSet<_>>(),
}
.into(),
)
})
.collect();
let before_datasets = before
.sled_agents
.iter()
.map(|(sled_id, sa)| {
(
*sled_id,
CollectionDatasetsConfig {
datasets: sa
.datasets
.iter()
.map(|d| (CollectionDatasetIdentifier::from(d), d.clone().into()))
.collect::<BTreeMap<_, BlueprintDatasetConfigForDiff>>(),
}
.into(),
)
})
.collect();
BlueprintDiff::new(
DiffBeforeMetadata::Collection { id: before.id },
DiffBeforeClickhouseClusterConfig::from(before),
before_state,
before_zones,
before_disks,
before_datasets,
&self,
)
}
/// Return a struct that can be displayed to present information about the
/// blueprint.
pub fn display(&self) -> BlueprintDisplay<'_> {
BlueprintDisplay { blueprint: self }
}
}
impl BpTableData for &OmicronPhysicalDisksConfig {
fn bp_generation(&self) -> BpGeneration {
BpGeneration::Value(self.generation)
}
fn rows(&self, state: BpDiffState) -> impl Iterator<Item = BpTableRow> {
let sorted_disk_ids: BTreeSet<DiskIdentity> =
self.disks.iter().map(|d| d.identity.clone()).collect();
sorted_disk_ids.into_iter().map(move |d| {
BpTableRow::from_strings(state, vec![d.vendor, d.model, d.serial])
})
}
}
impl BpTableData for BlueprintOrCollectionZonesConfig {
fn bp_generation(&self) -> BpGeneration {
BpGeneration::Value(self.generation())
}
fn rows(&self, state: BpDiffState) -> impl Iterator<Item = BpTableRow> {
self.zones().map(move |zone| {
BpTableRow::from_strings(
state,
vec![
zone.kind().report_str().to_string(),
zone.id().to_string(),
zone.disposition().to_string(),
zone.underlay_ip().to_string(),
],
)
})
}
}
// Useful implementation for printing two column tables stored in a `BTreeMap`, where
// each key and value impl `Display`.
impl<S1, S2> BpTableData for (Generation, &BTreeMap<S1, S2>)
where
S1: fmt::Display,
S2: fmt::Display,
{
fn bp_generation(&self) -> BpGeneration {
BpGeneration::Value(self.0)
}
fn rows(&self, state: BpDiffState) -> impl Iterator<Item = BpTableRow> {
self.1.iter().map(move |(s1, s2)| {
BpTableRow::from_strings(
state,
vec![s1.to_string(), s2.to_string()],
)
})
}
}
/// Wrapper to allow a [`Blueprint`] to be displayed with information.
///
/// Returned by [`Blueprint::display()`].
#[derive(Clone, Debug)]
#[must_use = "this struct does nothing unless displayed"]
pub struct BlueprintDisplay<'a> {
blueprint: &'a Blueprint,
// TODO: add colorization with a stylesheet
}
impl<'a> BlueprintDisplay<'a> {
fn make_cockroachdb_table(&self) -> KvListWithHeading {
let fingerprint = if self.blueprint.cockroachdb_fingerprint.is_empty() {
NONE_PARENS.to_string()
} else {
self.blueprint.cockroachdb_fingerprint.clone()
};
KvListWithHeading::new_unchanged(
COCKROACHDB_HEADING,
vec![
(COCKROACHDB_FINGERPRINT, fingerprint),
(
COCKROACHDB_PRESERVE_DOWNGRADE,
self.blueprint
.cockroachdb_setting_preserve_downgrade
.to_string(),
),
],
)
}
fn make_metadata_table(&self) -> KvListWithHeading {
let comment = if self.blueprint.comment.is_empty() {
NONE_PARENS.to_string()
} else {
self.blueprint.comment.clone()
};
KvListWithHeading::new_unchanged(
METADATA_HEADING,
vec![
(CREATED_BY, self.blueprint.creator.clone()),
(
CREATED_AT,
humantime::format_rfc3339_millis(
self.blueprint.time_created.into(),
)
.to_string(),
),
(COMMENT, comment),
(
INTERNAL_DNS_VERSION,
self.blueprint.internal_dns_version.to_string(),
),
(
EXTERNAL_DNS_VERSION,
self.blueprint.external_dns_version.to_string(),
),
],
)
}
// Return tables representing a [`ClickhouseClusterConfig`] in a given blueprint
fn make_clickhouse_cluster_config_tables(
&self,
) -> Option<(KvListWithHeading, BpTable, BpTable)> {
let config = &self.blueprint.clickhouse_cluster_config.as_ref()?;
let diff_table =
ClickhouseClusterConfigDiffTablesForSingleBlueprint::new(
BpDiffState::Unchanged,
config,
);
Some((diff_table.metadata, diff_table.keepers, diff_table.servers))
}
}
impl<'a> fmt::Display for BlueprintDisplay<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let b = self.blueprint;
writeln!(f, "blueprint {}", b.id)?;
writeln!(
f,
"parent: {}",
b.parent_blueprint_id
.map(|u| u.to_string())
.unwrap_or_else(|| String::from("<none>"))
)?;
// Keep track of any sled_ids that have been seen in the first loop.
let mut seen_sleds = BTreeSet::new();
// Loop through all sleds that have physical disks and print a table of
// those physical disks.
//
// If there are corresponding zones, print those as well.
for (sled_id, disks) in &self.blueprint.blueprint_disks {
// Construct the disks subtable
let disks_table = BpTable::new(
BpPhysicalDisksTableSchema {},
disks.bp_generation(),
disks.rows(BpDiffState::Unchanged).collect(),
);
// Look up the sled state
let sled_state = self
.blueprint
.sled_state
.get(sled_id)
.map(|state| state.to_string())
.unwrap_or_else(|| {
"blueprint error: unknown sled state".to_string()
});
// Construct the zones subtable
match self.blueprint.blueprint_zones.get(sled_id) {
Some(zones) => {
let zones =
BlueprintOrCollectionZonesConfig::from(zones.clone());
let zones_tab = BpTable::new(
BpOmicronZonesTableSchema {},
zones.bp_generation(),
zones.rows(BpDiffState::Unchanged).collect(),
);
writeln!(
f,
"\n sled: {sled_id} ({sled_state})\n\n{disks_table}\n\n{zones_tab}\n"
)?;
}
None => writeln!(
f,
"\n sled: {sled_id} ({sled_state})\n\n{disks_table}\n"
)?,
}
seen_sleds.insert(sled_id);
}
// Now create and display a table of zones on sleds that don't
// yet have physical disks.
//
// This should basically be impossible, so we warn if it occurs.
for (sled_id, zones) in &self.blueprint.blueprint_zones {
if !seen_sleds.contains(sled_id) && !zones.zones.is_empty() {
let zones =
BlueprintOrCollectionZonesConfig::from(zones.clone());
writeln!(
f,
"\n!{sled_id}\n{}\n{}\n\n",
"WARNING: Zones exist without physical disks!",
BpTable::new(
BpOmicronZonesTableSchema {},
zones.bp_generation(),
zones.rows(BpDiffState::Unchanged).collect()
)
)?;
}
}
if let Some((t1, t2, t3)) = self.make_clickhouse_cluster_config_tables()
{
writeln!(f, "{t1}\n{t2}\n{t3}\n")?;
}
writeln!(f, "{}", self.make_cockroachdb_table())?;
writeln!(f, "{}", self.make_metadata_table())?;
Ok(())
}
}
/// Information about an Omicron zone as recorded in a blueprint.
///
/// Currently, this is similar to [`OmicronZonesConfig`], but also contains a
/// per-zone [`BlueprintZoneDisposition`].
///
/// Part of [`Blueprint`].
#[derive(Debug, Clone, Eq, PartialEq, JsonSchema, Deserialize, Serialize)]
pub struct BlueprintZonesConfig {
/// Generation number of this configuration.
///
/// This generation number is owned by the control plane. See
/// [`OmicronZonesConfig::generation`] for more details.
pub generation: Generation,
/// The list of running zones.
pub zones: Vec<BlueprintZoneConfig>,
}
impl From<BlueprintZonesConfig> for OmicronZonesConfig {
fn from(config: BlueprintZonesConfig) -> Self {
Self {
generation: config.generation,
zones: config.zones.into_iter().map(From::from).collect(),
}
}
}
impl BlueprintZonesConfig {
/// Sorts the list of zones stored in this configuration.
///
/// This is not strictly necessary. But for testing (particularly snapshot
/// testing), it's helpful for zones to be in sorted order.
pub fn sort(&mut self) {
self.zones.sort_unstable_by_key(zone_sort_key);
}
/// Converts self to an [`OmicronZonesConfig`], applying the provided
/// [`BlueprintZoneFilter`].
///
/// The filter controls which zones should be exported into the resulting
/// [`OmicronZonesConfig`].
pub fn to_omicron_zones_config(
&self,
filter: BlueprintZoneFilter,
) -> OmicronZonesConfig {
OmicronZonesConfig {
generation: self.generation,
zones: self
.zones
.iter()
.filter(|z| z.disposition.matches(filter))
.cloned()
.map(OmicronZoneConfig::from)
.collect(),
}
}
/// Returns true if all zones in the blueprint have a disposition of
/// `Expunged`, false otherwise.
pub fn are_all_zones_expunged(&self) -> bool {
self.zones
.iter()
.all(|c| c.disposition == BlueprintZoneDisposition::Expunged)
}
}
trait ZoneSortKey {
fn kind(&self) -> ZoneKind;
fn id(&self) -> OmicronZoneUuid;
}
impl ZoneSortKey for BlueprintZoneConfig {
fn kind(&self) -> ZoneKind {
self.zone_type.kind()
}
fn id(&self) -> OmicronZoneUuid {
self.id
}
}
impl ZoneSortKey for OmicronZoneConfig {
fn kind(&self) -> ZoneKind {
self.zone_type.kind()
}
fn id(&self) -> OmicronZoneUuid {
self.id
}
}
impl ZoneSortKey for BlueprintOrCollectionZoneConfig {
fn kind(&self) -> ZoneKind {
BlueprintOrCollectionZoneConfig::kind(self)
}
fn id(&self) -> OmicronZoneUuid {
BlueprintOrCollectionZoneConfig::id(self)
}
}
fn zone_sort_key<T: ZoneSortKey>(z: &T) -> impl Ord {
// First sort by kind, then by ID. This makes it so that zones of the same
// kind (e.g. Crucible zones) are grouped together.
(z.kind(), z.id())
}
/// Describes one Omicron-managed zone in a blueprint.
///
/// Part of [`BlueprintZonesConfig`].
#[derive(Debug, Clone, Eq, PartialEq, JsonSchema, Deserialize, Serialize)]
pub struct BlueprintZoneConfig {
/// The disposition (desired state) of this zone recorded in the blueprint.
pub disposition: BlueprintZoneDisposition,
pub id: OmicronZoneUuid,
/// zpool used for the zone's (transient) root filesystem
pub filesystem_pool: Option<ZpoolName>,
pub zone_type: BlueprintZoneType,
}
impl BlueprintZoneConfig {
/// Returns the underlay IP address associated with this zone.
///
/// Assumes all zone have exactly one underlay IP address (which is
/// currently true).
pub fn underlay_ip(&self) -> Ipv6Addr {
self.zone_type.underlay_ip()
}
}
impl From<BlueprintZoneConfig> for OmicronZoneConfig {
fn from(z: BlueprintZoneConfig) -> Self {
Self {
id: z.id,
filesystem_pool: z.filesystem_pool,
zone_type: z.zone_type.into(),
}
}
}
/// The desired state of an Omicron-managed zone in a blueprint.
///
/// Part of [`BlueprintZoneConfig`].
#[derive(
Debug,
Copy,
Clone,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
JsonSchema,
Deserialize,
Serialize,
EnumIter,
)]
#[serde(rename_all = "snake_case")]
pub enum BlueprintZoneDisposition {
/// The zone is in-service.
InService,
/// The zone is not in service.
Quiesced,
/// The zone is permanently gone.
Expunged,
}
impl BlueprintZoneDisposition {
/// Returns true if the zone disposition matches this filter.
pub fn matches(self, filter: BlueprintZoneFilter) -> bool {
// This code could be written in three ways:
//
// 1. match self { match filter { ... } }
// 2. match filter { match self { ... } }
// 3. match (self, filter) { ... }
//
// We choose 1 here because we expect many filters and just a few
// dispositions, and 1 is the easiest form to represent that.
match self {
Self::InService => match filter {
BlueprintZoneFilter::All => true,
BlueprintZoneFilter::Expunged => false,
BlueprintZoneFilter::ShouldBeRunning => true,
BlueprintZoneFilter::ShouldBeExternallyReachable => true,
BlueprintZoneFilter::ShouldBeInInternalDns => true,
BlueprintZoneFilter::ShouldDeployVpcFirewallRules => true,
},
Self::Quiesced => match filter {
BlueprintZoneFilter::All => true,
BlueprintZoneFilter::Expunged => false,
// Quiesced zones are still running.
BlueprintZoneFilter::ShouldBeRunning => true,
// Quiesced zones should not have external resources -- we do
// not want traffic to be directed to them.
BlueprintZoneFilter::ShouldBeExternallyReachable => false,
// Quiesced zones should not be exposed in DNS.
BlueprintZoneFilter::ShouldBeInInternalDns => false,
// Quiesced zones should get firewall rules.
BlueprintZoneFilter::ShouldDeployVpcFirewallRules => true,
},
Self::Expunged => match filter {
BlueprintZoneFilter::All => true,
BlueprintZoneFilter::Expunged => true,
BlueprintZoneFilter::ShouldBeRunning => false,
BlueprintZoneFilter::ShouldBeExternallyReachable => false,
BlueprintZoneFilter::ShouldBeInInternalDns => false,
BlueprintZoneFilter::ShouldDeployVpcFirewallRules => false,
},
}
}
/// Returns all zone dispositions that match the given filter.
pub fn all_matching(
filter: BlueprintZoneFilter,
) -> impl Iterator<Item = Self> {
BlueprintZoneDisposition::iter().filter(move |&d| d.matches(filter))
}
}
impl fmt::Display for BlueprintZoneDisposition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
// Neither `write!(f, "...")` nor `f.write_str("...")` obey fill
// and alignment (used above), but this does.
BlueprintZoneDisposition::InService => "in service".fmt(f),
BlueprintZoneDisposition::Quiesced => "quiesced".fmt(f),
BlueprintZoneDisposition::Expunged => "expunged".fmt(f),
}
}
}
/// Filters that apply to blueprint zones.
///
/// This logic lives here rather than within the individual components making
/// decisions, so that this is easier to read.
///
/// The meaning of a particular filter should not be overloaded -- each time a
/// new use case wants to make a decision based on the zone disposition, a new
/// variant should be added to this enum.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum BlueprintZoneFilter {
// ---
// Prefer to keep this list in alphabetical order.
// ---
/// All zones.
All,
/// Zones that have been expunged.
Expunged,
/// Zones that are desired to be in the RUNNING state
ShouldBeRunning,
/// Filter by zones that should have external IP and DNS resources.
ShouldBeExternallyReachable,
/// Filter by zones that should be in internal DNS.
ShouldBeInInternalDns,
/// Filter by zones that should be sent VPC firewall rules.
ShouldDeployVpcFirewallRules,
}
/// Filters that apply to blueprint datasets.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum BlueprintDatasetFilter {
// ---
// Prefer to keep this list in alphabetical order.
// ---
/// All datasets
All,
/// Datasets that have been expunged.
Expunged,
/// Datasets that are in-service.
InService,
}
/// Information about an Omicron physical disk as recorded in a blueprint.
///
/// Part of [`Blueprint`].
pub type BlueprintPhysicalDisksConfig =
omicron_common::disk::OmicronPhysicalDisksConfig;
pub type BlueprintPhysicalDiskConfig =
omicron_common::disk::OmicronPhysicalDiskConfig;
/// Information about Omicron datasets as recorded in a blueprint.
#[derive(Debug, Clone, Eq, PartialEq, JsonSchema, Deserialize, Serialize)]
pub struct BlueprintDatasetsConfig {
pub generation: Generation,
pub datasets: BTreeMap<DatasetUuid, BlueprintDatasetConfig>,
}
impl From<BlueprintDatasetsConfig> for DatasetsConfig {
fn from(config: BlueprintDatasetsConfig) -> Self {
Self {
generation: config.generation,
datasets: config
.datasets
.into_iter()
.map(|(id, d)| (id, d.into()))
.collect(),
}
}
}
/// The desired state of an Omicron-managed dataset in a blueprint.
///
/// Part of [`BlueprintDatasetConfig`].
#[derive(
Debug,
Copy,
Clone,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
JsonSchema,
Deserialize,
Serialize,
EnumIter,
)]
#[serde(rename_all = "snake_case")]
pub enum BlueprintDatasetDisposition {
/// The dataset is in-service.
InService,
/// The dataset is permanently gone.
Expunged,
}
impl BlueprintDatasetDisposition {
pub fn matches(self, filter: BlueprintDatasetFilter) -> bool {
match self {
Self::InService => match filter {
BlueprintDatasetFilter::All => true,
BlueprintDatasetFilter::Expunged => false,
BlueprintDatasetFilter::InService => true,
},
Self::Expunged => match filter {
BlueprintDatasetFilter::All => true,
BlueprintDatasetFilter::Expunged => true,
BlueprintDatasetFilter::InService => false,
},
}
}
}
/// Information about a dataset as recorded in a blueprint
#[derive(Debug, Clone, Eq, PartialEq, JsonSchema, Deserialize, Serialize)]
pub struct BlueprintDatasetConfig {
pub disposition: BlueprintDatasetDisposition,
pub id: DatasetUuid,
pub pool: ZpoolName,
pub kind: DatasetKind,
pub address: Option<SocketAddrV6>,
pub quota: Option<ByteCount>,
pub reservation: Option<ByteCount>,
pub compression: CompressionAlgorithm,
}
impl From<BlueprintDatasetConfig> for DatasetConfig {
fn from(config: BlueprintDatasetConfig) -> Self {
Self {
id: config.id,
name: DatasetName::new(config.pool, config.kind),
inner: SharedDatasetConfig {
quota: config.quota,
reservation: config.reservation,
compression: config.compression,
},
}
}
}
/// Information about a dataset as used for diffing collections and blueprints.
///
/// This struct acts as a "lowest common denominator" between the
/// inventory and blueprint types, for the purposes of comparison.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct BlueprintDatasetConfigForDiff {
pub name: String,
pub id: Option<DatasetUuid>,