Repository navigation
Expand file tree
/
Copy pathbuilder.rs
More file actions
3176 lines (2927 loc) · 115 KB
/
Copy pathbuilder.rs
File metadata and controls
3176 lines (2927 loc) · 115 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/.
//! Low-level facility for generating Blueprints
use crate::blueprint_editor::BlueprintResourceAllocator;
use crate::blueprint_editor::BlueprintResourceAllocatorInputError;
use crate::blueprint_editor::DiskExpungeDetails;
use crate::blueprint_editor::EditedSled;
use crate::blueprint_editor::ExternalNetworkingChoice;
use crate::blueprint_editor::ExternalNetworkingError;
use crate::blueprint_editor::ExternalSnatNetworkingChoice;
use crate::blueprint_editor::NoAvailableDnsSubnets;
use crate::blueprint_editor::SledEditError;
use crate::blueprint_editor::SledEditor;
use crate::planner::ZoneExpungeReason;
use crate::planner::rng::PlannerRng;
use anyhow::Context as _;
use anyhow::anyhow;
use anyhow::bail;
use clickhouse_admin_types::OXIMETER_CLUSTER;
use id_map::IdMap;
use itertools::Either;
use nexus_inventory::now_db_precision;
use nexus_sled_agent_shared::inventory::OmicronZoneDataset;
use nexus_sled_agent_shared::inventory::ZoneKind;
use nexus_types::deployment::Blueprint;
use nexus_types::deployment::BlueprintDatasetDisposition;
use nexus_types::deployment::BlueprintPhysicalDiskConfig;
use nexus_types::deployment::BlueprintPhysicalDiskDisposition;
use nexus_types::deployment::BlueprintSledConfig;
use nexus_types::deployment::BlueprintZoneConfig;
use nexus_types::deployment::BlueprintZoneDisposition;
use nexus_types::deployment::BlueprintZoneImageSource;
use nexus_types::deployment::BlueprintZoneType;
use nexus_types::deployment::ClickhouseClusterConfig;
use nexus_types::deployment::CockroachDbPreserveDowngrade;
use nexus_types::deployment::DiskFilter;
use nexus_types::deployment::OmicronZoneExternalFloatingAddr;
use nexus_types::deployment::OmicronZoneExternalFloatingIp;
use nexus_types::deployment::OmicronZoneExternalSnatIp;
use nexus_types::deployment::OximeterReadMode;
use nexus_types::deployment::PendingMgsUpdates;
use nexus_types::deployment::PlanningInput;
use nexus_types::deployment::SledFilter;
use nexus_types::deployment::SledResources;
use nexus_types::deployment::ZpoolFilter;
use nexus_types::deployment::ZpoolName;
use nexus_types::deployment::blueprint_zone_type;
use nexus_types::external_api::views::SledState;
use nexus_types::inventory::Collection;
use omicron_common::address::CLICKHOUSE_HTTP_PORT;
use omicron_common::address::DNS_HTTP_PORT;
use omicron_common::address::DNS_PORT;
use omicron_common::address::NTP_PORT;
use omicron_common::address::ReservedRackSubnet;
use omicron_common::api::external::Generation;
use omicron_common::api::external::TufRepoDescription;
use omicron_common::api::external::Vni;
use omicron_common::api::internal::shared::NetworkInterface;
use omicron_common::api::internal::shared::NetworkInterfaceKind;
use omicron_common::policy::INTERNAL_DNS_REDUNDANCY;
use omicron_uuid_kinds::GenericUuid;
use omicron_uuid_kinds::MupdateOverrideUuid;
use omicron_uuid_kinds::OmicronZoneUuid;
use omicron_uuid_kinds::PhysicalDiskUuid;
use omicron_uuid_kinds::SledUuid;
use omicron_uuid_kinds::ZpoolUuid;
use once_cell::unsync::OnceCell;
use slog::Logger;
use slog::debug;
use slog::error;
use slog::info;
use slog::o;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashSet;
use std::collections::btree_map::Entry;
use std::fmt;
use std::iter;
use std::net::IpAddr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use std::net::SocketAddrV6;
use thiserror::Error;
use super::ClickhouseZonesThatShouldBeRunning;
use super::clickhouse::ClickhouseAllocator;
use nexus_types::inventory::BaseboardId;
use std::sync::Arc;
/// Errors encountered while assembling blueprints
#[derive(Debug, Error)]
pub enum Error {
#[error(
"sled {sled_id}: no available zpools for additional {kind:?} zones"
)]
NoAvailableZpool { sled_id: SledUuid, kind: ZoneKind },
#[error("no Nexus zones exist in parent blueprint")]
NoNexusZonesInParentBlueprint,
#[error("no Boundary NTP zones exist in parent blueprint")]
NoBoundaryNtpZonesInParentBlueprint,
#[error(
"invariant violation: found decommissioned sled with \
{num_zones} non-expunged zones: {sled_id}"
)]
DecommissionedSledWithNonExpungedZones {
sled_id: SledUuid,
num_zones: usize,
},
#[error("programming error in planner")]
Planner(#[source] anyhow::Error),
#[error("error editing sled {sled_id}")]
SledEditError {
sled_id: SledUuid,
#[source]
err: SledEditError,
},
#[error("error constructing resource allocator")]
AllocatorInput(#[from] BlueprintResourceAllocatorInputError),
#[error("error allocating internal DNS subnet")]
AllocateInternalDnsSubnet(#[from] NoAvailableDnsSubnets),
#[error("error allocating external networking resources")]
AllocateExternalNetworking(#[from] ExternalNetworkingError),
#[error("can only have {INTERNAL_DNS_REDUNDANCY} internal DNS servers")]
PolicySpecifiesTooManyInternalDnsServers,
#[error("zone is already up-to-date and should not be updated")]
ZoneAlreadyUpToDate,
#[error(
"mismatch while setting target_release_minimum_generation, \
expected current value is {expected} but actual value is {actual}"
)]
TargetReleaseMinimumGenerationMismatch {
expected: Generation,
actual: Generation,
},
}
/// Describes the result of an idempotent "ensure" operation
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Ensure {
/// a new item was added
Added,
/// an existing item was updated
Updated,
/// no action was necessary
NotNeeded,
}
/// Describes whether an idempotent "ensure" operation resulted in multiple
/// actions taken or no action was necessary
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum EnsureMultiple {
/// action was taken within the operation
Changed {
/// An item was added to the blueprint
added: usize,
/// An item was updated within the blueprint
updated: usize,
/// An item was expunged in the blueprint
expunged: usize,
/// An item was removed from the blueprint.
///
/// This happens after expungement or decommissioning has completed
/// depending upon the resource type.
removed: usize,
},
/// no action was necessary
NotNeeded,
}
impl From<EditCounts> for EnsureMultiple {
fn from(value: EditCounts) -> Self {
let EditCounts { added, updated, expunged, removed } = value;
if added == 0 && updated == 0 && expunged == 0 && removed == 0 {
Self::NotNeeded
} else {
Self::Changed { added, updated, expunged, removed }
}
}
}
/// Counts of changes made by an operation.
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub struct EditCounts {
/// An item was added to the blueprint
pub added: usize,
/// An item was updated within the blueprint
pub updated: usize,
/// An item was expunged in the blueprint
pub expunged: usize,
/// An item was removed from the blueprint.
///
/// This happens after expungement or decommissioning has completed
/// depending upon the resource type.
pub removed: usize,
}
impl EditCounts {
pub fn zeroes() -> Self {
Self::default()
}
pub fn has_nonzero_counts(&self) -> bool {
*self != Self::zeroes()
}
pub fn difference_since(self, other: Self) -> Self {
Self {
added: self.added - other.added,
updated: self.updated - other.updated,
expunged: self.expunged - other.expunged,
removed: self.removed - other.removed,
}
}
}
/// Counts of changes made by `BlueprintStorageEditor`.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct StorageEditCounts {
pub disks: EditCounts,
pub datasets: EditCounts,
}
/// Counts of changes made by operations that may affect multiple resources.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct SledEditCounts {
pub disks: EditCounts,
pub datasets: EditCounts,
pub zones: EditCounts,
}
impl SledEditCounts {
pub fn zeroes() -> Self {
Self {
disks: EditCounts::zeroes(),
datasets: EditCounts::zeroes(),
zones: EditCounts::zeroes(),
}
}
fn has_nonzero_counts(&self) -> bool {
let Self { disks, datasets, zones } = self;
disks.has_nonzero_counts()
|| datasets.has_nonzero_counts()
|| zones.has_nonzero_counts()
}
fn difference_since(self, other: Self) -> Self {
Self {
disks: self.disks.difference_since(other.disks),
datasets: self.datasets.difference_since(other.datasets),
zones: self.zones.difference_since(other.zones),
}
}
}
impl From<StorageEditCounts> for SledEditCounts {
fn from(value: StorageEditCounts) -> Self {
let StorageEditCounts { disks, datasets } = value;
Self { disks, datasets, zones: EditCounts::zeroes() }
}
}
/// Describes operations which the BlueprintBuilder has performed to arrive
/// at its state.
///
/// This information is meant to act as a more strongly-typed flavor of
/// "comment", identifying which operations have occurred on the blueprint.
#[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) enum Operation {
AddZone {
sled_id: SledUuid,
kind: ZoneKind,
},
UpdateDisks {
sled_id: SledUuid,
added: usize,
updated: usize,
removed: usize,
},
UpdateDatasets {
sled_id: SledUuid,
added: usize,
updated: usize,
expunged: usize,
removed: usize,
},
ZoneExpunged {
sled_id: SledUuid,
reason: ZoneExpungeReason,
count: usize,
},
DiskExpunged {
sled_id: SledUuid,
details: DiskExpungeDetails,
},
SledExpunged {
sled_id: SledUuid,
num_disks_expunged: usize,
num_datasets_expunged: usize,
num_zones_expunged: usize,
},
SledNoopZoneImageSourcesUpdated {
sled_id: SledUuid,
count: usize,
},
}
impl fmt::Display for Operation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::AddZone { sled_id, kind } => {
write!(f, "sled {sled_id}: added zone: {}", kind.report_str())
}
Self::UpdateDisks { sled_id, added, updated, removed } => {
write!(
f,
"sled {sled_id}: added {added} disks, updated {updated}, removed {removed} disks"
)
}
Self::UpdateDatasets {
sled_id,
added,
updated,
expunged,
removed,
} => {
write!(
f,
"sled {sled_id}: added {added} datasets, updated: {updated}, expunged {expunged}, removed {removed} datasets"
)
}
Self::ZoneExpunged { sled_id, reason, count } => {
let reason = match reason {
ZoneExpungeReason::ClickhouseClusterDisabled => {
"clickhouse cluster disabled via policy"
}
ZoneExpungeReason::ClickhouseSingleNodeDisabled => {
"clickhouse single-node disabled via policy"
}
};
write!(
f,
"sled {sled_id}: expunged {count} zones because: {reason}"
)
}
Self::DiskExpunged { sled_id, details } => {
write!(
f,
"sled {sled_id}: expunged disk {} with \
{} associated datasets and {} associated zones",
details.disk_id,
details.num_datasets_expunged,
details.num_zones_expunged,
)
}
Self::SledExpunged {
sled_id,
num_disks_expunged,
num_datasets_expunged,
num_zones_expunged,
} => {
write!(
f,
"sled {sled_id} expunged \
(expunged {num_disks_expunged} disks, \
{num_datasets_expunged} datasets, \
{num_zones_expunged} zones)"
)
}
Self::SledNoopZoneImageSourcesUpdated { sled_id, count } => {
write!(
f,
"sled {sled_id}: performed {count} noop \
zone image source updates"
)
}
}
}
}
/// Helper for assembling a blueprint
///
/// There are two basic ways to assemble a new blueprint:
///
/// 1. Build one directly. This would generally only be used once in the
/// lifetime of a rack, to assemble the first blueprint during rack setup.
/// It is also common in tests. To start with a blueprint that contains an
/// empty zone config for some number of sleds, use
/// [`BlueprintBuilder::build_empty_with_sleds`].
///
/// 2. Build one _from_ another blueprint, called the "parent", making changes
/// as desired. Use [`BlueprintBuilder::new_based_on`] for this. Once the
/// new blueprint is created, there is no dependency on the parent one.
/// However, the new blueprint can only be made the system's target if its
/// parent is the current target.
pub struct BlueprintBuilder<'a> {
#[allow(dead_code)]
log: Logger,
/// previous blueprint, on which this one will be based
parent_blueprint: &'a Blueprint,
/// The latest inventory collection
#[allow(unused)]
collection: &'a Collection,
// These fields are used to allocate resources for sleds.
input: &'a PlanningInput,
// `allocators` contains logic for choosing new underlay IPs, external IPs,
// internal DNS subnets, etc. It's held in a `OnceCell` to delay its
// creation until it's first needed; the planner expunges zones before
// adding zones, so this delay allows us to reuse resources that just came
// free. (This is implicit and awkward; as we rework the builder we should
// rework this to make it more explicit.)
//
// Note: this is currently still a `once_cell` `OnceCell` rather than a std
// `OnceCell`, because `get_or_try_init` isn't stable yet.
resource_allocator: OnceCell<BlueprintResourceAllocator>,
// These fields will become part of the final blueprint. See the
// corresponding fields in `Blueprint`.
sled_editors: BTreeMap<SledUuid, SledEditor>,
cockroachdb_setting_preserve_downgrade: CockroachDbPreserveDowngrade,
target_release_minimum_generation: Generation,
creator: String,
operations: Vec<Operation>,
comments: Vec<String>,
pending_mgs_updates: PendingMgsUpdates,
// Random number generator for new UUIDs
rng: PlannerRng,
}
impl<'a> BlueprintBuilder<'a> {
/// Directly construct a `Blueprint` that contains an empty zone config for
/// the given sleds.
pub fn build_empty_with_sleds(
sled_ids: impl Iterator<Item = SledUuid>,
creator: &str,
) -> Blueprint {
Self::build_empty_with_sleds_impl(
sled_ids,
creator,
PlannerRng::from_entropy(),
)
}
/// A version of [`Self::build_empty_with_sleds`] that allows the
/// blueprint ID to be generated from a deterministic RNG.
pub fn build_empty_with_sleds_seeded(
sled_ids: impl Iterator<Item = SledUuid>,
creator: &str,
rng: PlannerRng,
) -> Blueprint {
Self::build_empty_with_sleds_impl(sled_ids, creator, rng)
}
fn build_empty_with_sleds_impl(
sled_ids: impl Iterator<Item = SledUuid>,
creator: &str,
mut rng: PlannerRng,
) -> Blueprint {
let sleds = sled_ids
.map(|sled_id| {
let config = BlueprintSledConfig {
state: SledState::Active,
sled_agent_generation: Generation::new(),
disks: IdMap::default(),
datasets: IdMap::default(),
zones: IdMap::default(),
remove_mupdate_override: None,
};
(sled_id, config)
})
.collect::<BTreeMap<_, _>>();
let num_sleds = sleds.len();
Blueprint {
id: rng.next_blueprint(),
sleds,
pending_mgs_updates: PendingMgsUpdates::new(),
parent_blueprint_id: None,
internal_dns_version: Generation::new(),
external_dns_version: Generation::new(),
target_release_minimum_generation: Generation::new(),
cockroachdb_fingerprint: String::new(),
cockroachdb_setting_preserve_downgrade:
CockroachDbPreserveDowngrade::DoNotModify,
clickhouse_cluster_config: None,
oximeter_read_version: Generation::new(),
oximeter_read_mode: OximeterReadMode::SingleNode,
time_created: now_db_precision(),
creator: creator.to_owned(),
comment: format!("starting blueprint with {num_sleds} empty sleds"),
}
}
/// Construct a new `BlueprintBuilder` based on a previous blueprint,
/// starting with no changes from that state
pub fn new_based_on(
log: &Logger,
parent_blueprint: &'a Blueprint,
input: &'a PlanningInput,
inventory: &'a Collection,
creator: &str,
) -> anyhow::Result<BlueprintBuilder<'a>> {
let log = log.new(o!(
"component" => "BlueprintBuilder",
"parent_id" => parent_blueprint.id.to_string(),
));
// Convert our parent blueprint's sled configs into `SledEditor`s.
let mut sled_editors = BTreeMap::new();
for (sled_id, sled_cfg) in &parent_blueprint.sleds {
let state = sled_cfg.state;
let editor = match state {
SledState::Active => {
let subnet = input
.sled_lookup(SledFilter::Commissioned, *sled_id)
.with_context(|| {
format!(
"failed to find sled details for \
active sled in parent blueprint {sled_id}"
)
})?
.resources
.subnet;
SledEditor::for_existing_active(subnet, sled_cfg.clone())
}
SledState::Decommissioned => {
SledEditor::for_existing_decommissioned(sled_cfg.clone())
}
}
.with_context(|| {
format!("failed to construct SledEditor for sled {sled_id}")
})?;
sled_editors.insert(*sled_id, editor);
}
// Add new, empty `SledEditor`s for any commissioned sleds in our input
// that weren't in the parent blueprint. (These are newly-added sleds.)
for (sled_id, details) in input.all_sleds(SledFilter::Commissioned) {
if let Entry::Vacant(slot) = sled_editors.entry(sled_id) {
slot.insert(SledEditor::for_new_active(
details.resources.subnet,
));
}
}
Ok(BlueprintBuilder {
log,
parent_blueprint,
collection: inventory,
input,
resource_allocator: OnceCell::new(),
sled_editors,
cockroachdb_setting_preserve_downgrade: parent_blueprint
.cockroachdb_setting_preserve_downgrade,
pending_mgs_updates: parent_blueprint.pending_mgs_updates.clone(),
target_release_minimum_generation: parent_blueprint
.target_release_minimum_generation,
creator: creator.to_owned(),
operations: Vec::new(),
comments: Vec::new(),
rng: PlannerRng::from_entropy(),
})
}
pub fn parent_blueprint(&self) -> &Blueprint {
&self.parent_blueprint
}
fn resource_allocator(
&mut self,
) -> Result<&mut BlueprintResourceAllocator, Error> {
self.resource_allocator.get_or_try_init(|| {
// Check the planning input: there shouldn't be any external
// networking resources in the database (the source of `input`)
// that we don't know about from the parent blueprint.
//
// TODO-cleanup Should the planner do this instead? Move this check
// to blippy.
ensure_input_networking_records_appear_in_parent_blueprint(
self.parent_blueprint,
self.input,
)
.map_err(Error::Planner)?;
let allocator = BlueprintResourceAllocator::new(
self.sled_editors.values(),
self.input.service_ip_pool_ranges().to_vec(),
)?;
Ok::<_, Error>(allocator)
})?;
Ok(self.resource_allocator.get_mut().expect("get_or_init succeeded"))
}
/// Iterates over the list of sled IDs for which we have zones.
///
/// This may include decommissioned sleds.
pub fn sled_ids_with_zones(&self) -> impl Iterator<Item = SledUuid> + '_ {
self.sled_editors.keys().copied()
}
pub fn current_sled_zones<F>(
&self,
sled_id: SledUuid,
filter: F,
) -> impl Iterator<Item = &BlueprintZoneConfig>
where
F: FnMut(BlueprintZoneDisposition) -> bool,
{
let Some(editor) = self.sled_editors.get(&sled_id) else {
return Either::Left(iter::empty());
};
Either::Right(editor.zones(filter))
}
pub fn current_sled_disks<F>(
&self,
sled_id: SledUuid,
filter: F,
) -> impl Iterator<Item = &BlueprintPhysicalDiskConfig>
where
F: FnMut(BlueprintPhysicalDiskDisposition) -> bool,
{
let Some(editor) = self.sled_editors.get(&sled_id) else {
return Either::Left(iter::empty());
};
Either::Right(editor.disks(filter))
}
/// Assemble a final [`Blueprint`] based on the contents of the builder
pub fn build(mut self) -> Blueprint {
let blueprint_id = self.rng.next_blueprint();
// Collect the Omicron zones config for all sleds, including sleds that
// are no longer in service and need expungement work.
let mut sleds = BTreeMap::new();
for (sled_id, editor) in self.sled_editors {
let EditedSled { config, edit_counts } = editor.finalize();
sleds.insert(sled_id, config);
if edit_counts.has_nonzero_counts() {
debug!(
self.log, "sled modified in new blueprint";
"sled_id" => %sled_id,
"blueprint_id" => %blueprint_id,
"disk_edits" => ?edit_counts.disks,
"dataset_edits" => ?edit_counts.datasets,
"zone_edits" => ?edit_counts.zones,
);
} else {
debug!(
self.log, "sled unchanged in new blueprint";
"sled_id" => %sled_id,
"blueprint_id" => %blueprint_id,
);
}
}
// If we have the clickhouse cluster setup enabled via policy and we
// don't yet have a `ClickhouseClusterConfiguration`, then we must
// create one and feed it to our `ClickhouseAllocator`.
let clickhouse_allocator = if self.input.clickhouse_cluster_enabled() {
let parent_config = self
.parent_blueprint
.clickhouse_cluster_config
.clone()
.unwrap_or_else(|| {
info!(
self.log,
concat!(
"Clickhouse cluster enabled by policy: ",
"generating initial 'ClickhouseClusterConfig' ",
"and 'ClickhouseAllocator'"
)
);
ClickhouseClusterConfig::new(
OXIMETER_CLUSTER.to_string(),
self.rng.next_clickhouse().to_string(),
)
});
Some(ClickhouseAllocator::new(
self.log.clone(),
parent_config,
self.collection.latest_clickhouse_keeper_membership(),
))
} else {
if self.parent_blueprint.clickhouse_cluster_config.is_some() {
info!(
self.log,
concat!(
"clickhouse cluster disabled via policy ",
"discarding existing 'ClickhouseAllocator' and ",
"the resulting generated 'ClickhouseClusterConfig"
)
);
}
None
};
// If we have an allocator, use it to generate a new config. If an error
// is returned then log it and carry over the parent_config.
let clickhouse_cluster_config = clickhouse_allocator.map(|a| {
let should_be_running = ClickhouseZonesThatShouldBeRunning::new(
sleds.iter().map(|(id, c)| (*id, c)),
);
match a.plan(&should_be_running) {
Ok(config) => config,
Err(e) => {
error!(self.log, "clickhouse allocator error: {e}");
a.parent_config().clone()
}
}
});
let (oximeter_read_mode, oximeter_read_version) = {
let policy = self.input.oximeter_read_settings();
(policy.mode.clone(), policy.version)
};
Blueprint {
id: blueprint_id,
sleds,
pending_mgs_updates: self.pending_mgs_updates,
parent_blueprint_id: Some(self.parent_blueprint.id),
internal_dns_version: self.input.internal_dns_version(),
external_dns_version: self.input.external_dns_version(),
target_release_minimum_generation: self
.target_release_minimum_generation,
cockroachdb_fingerprint: self
.input
.cockroachdb_settings()
.state_fingerprint
.clone(),
cockroachdb_setting_preserve_downgrade: self
.cockroachdb_setting_preserve_downgrade,
clickhouse_cluster_config,
oximeter_read_version: oximeter_read_version.into(),
oximeter_read_mode,
time_created: now_db_precision(),
creator: self.creator,
comment: self
.comments
.into_iter()
.chain(self.operations.iter().map(|op| op.to_string()))
.collect::<Vec<String>>()
.join(", "),
}
}
pub fn current_sled_state(
&self,
sled_id: SledUuid,
) -> Result<SledState, Error> {
let editor = self.sled_editors.get(&sled_id).ok_or_else(|| {
Error::Planner(anyhow!(
"tried to get sled state for unknown sled {sled_id}"
))
})?;
Ok(editor.state())
}
/// Set the desired state of the given sled.
pub fn set_sled_decommissioned(
&mut self,
sled_id: SledUuid,
) -> Result<(), Error> {
let editor = self.sled_editors.get_mut(&sled_id).ok_or_else(|| {
Error::Planner(anyhow!(
"tried to set sled state for unknown sled {sled_id}"
))
})?;
editor
.decommission()
.map_err(|err| Error::SledEditError { sled_id, err })
}
/// Within tests, set an RNG for deterministic results.
///
/// This will ensure that tests that use this builder will produce the same
/// results each time they are run.
pub fn set_rng(&mut self, rng: PlannerRng) -> &mut Self {
self.rng = rng;
self
}
/// This is a short human-readable string summarizing the changes reflected
/// in the blueprint. This is only intended for debugging.
pub fn comment<S>(&mut self, comment: S)
where
String: From<S>,
{
self.comments.push(String::from(comment));
}
/// Records an operation to the blueprint, identifying what changes have
/// occurred.
///
/// This is currently intended only for debugging.
pub(crate) fn record_operation(&mut self, operation: Operation) {
self.operations.push(operation);
}
/// Expunges a disk from a sled.
pub(crate) fn expunge_disk(
&mut self,
sled_id: SledUuid,
disk_id: PhysicalDiskUuid,
) -> Result<(), Error> {
let editor = self.sled_editors.get_mut(&sled_id).ok_or_else(|| {
Error::Planner(anyhow!(
"tried to expunge disk for unknown sled {sled_id}"
))
})?;
let details = editor
.expunge_disk(&disk_id)
.map_err(|err| Error::SledEditError { sled_id, err })?;
if details.did_expunge_disk {
self.record_operation(Operation::DiskExpunged { sled_id, details });
}
Ok(())
}
/// Expunge everything on a sled.
pub(crate) fn expunge_sled(
&mut self,
sled_id: SledUuid,
) -> Result<(), Error> {
let editor = self.sled_editors.get_mut(&sled_id).ok_or_else(|| {
Error::Planner(anyhow!("tried to expunge unknown sled {sled_id}"))
})?;
// We don't have an explicit "sled disposition" in the blueprint, but we
// can expunge all the disks, datasets, and zones on the sled. It is
// sufficient to just expunge the disks: expunging all disks will
// expunge all datasets and zones that depend on those disks, which
// should include all datasets and zones on the sled. (We'll
// double-check this below and fail if this is wrong.)
let mut num_disks_expunged = 0;
let mut num_datasets_expunged = 0;
let mut num_zones_expunged = 0;
let mut disks_to_expunge = Vec::new();
for disk in
editor.disks(BlueprintPhysicalDiskDisposition::is_in_service)
{
disks_to_expunge.push(disk.id);
}
for disk_id in disks_to_expunge {
let details = editor
.expunge_disk(&disk_id)
.map_err(|err| Error::SledEditError { sled_id, err })?;
if details.did_expunge_disk {
num_disks_expunged += 1;
}
num_datasets_expunged += details.num_datasets_expunged;
num_zones_expunged += details.num_zones_expunged;
// When we expunge a disk on an expunged sled, we can decommission
// it immediately because the sled is already gone. There is no sled
// agent to notify about the disk expungement.
editor
.decommission_disk(&disk_id)
.map_err(|err| Error::SledEditError { sled_id, err })?;
}
// Expunging a disk expunges any datasets and zones that depend on it,
// so expunging all in-service disks should have also expunged all
// datasets and zones. Double-check that that's true.
let mut zones_ready_for_cleanup = Vec::new();
for zone in editor.zones(BlueprintZoneDisposition::any) {
match zone.disposition {
BlueprintZoneDisposition::Expunged { .. } => {
// Since this is a full sled expungement, we'll never see an
// inventory collection indicating the zones are shut down,
// nor do we need to: go ahead and mark any expunged zones
// as ready for cleanup.
zones_ready_for_cleanup.push(zone.id);
}
BlueprintZoneDisposition::InService => {
return Err(Error::Planner(anyhow!(
"expunged all disks but a zone \
is still in service: {zone:?}"
)));
}
}
}
if let Some(dataset) =
editor.datasets(BlueprintDatasetDisposition::is_in_service).next()
{
return Err(Error::Planner(anyhow!(
"expunged all disks but a dataset \
is still in service: {dataset:?}"
)));
}
for zone_id in zones_ready_for_cleanup {
editor
.mark_expunged_zone_ready_for_cleanup(&zone_id)
.map_err(|err| Error::SledEditError { sled_id, err })?;
}
// If we didn't expunge anything, this sled was presumably expunged in a
// prior planning run. Only note the operation if we did anything.
if num_disks_expunged > 0
|| num_datasets_expunged > 0
|| num_zones_expunged > 0
{
self.record_operation(Operation::SledExpunged {
sled_id,
num_disks_expunged,
num_datasets_expunged,
num_zones_expunged,
});
}
Ok(())
}
/// Mark expunged zones as ready for cleanup.
pub(crate) fn mark_expunged_zones_ready_for_cleanup(
&mut self,
sled_id: SledUuid,
zone_ids: &[OmicronZoneUuid],
) -> Result<(), Error> {
let editor = self.sled_editors.get_mut(&sled_id).ok_or_else(|| {
Error::Planner(anyhow!("tried to expunge unknown sled {sled_id}"))
})?;
for zone_id in zone_ids {
editor
.mark_expunged_zone_ready_for_cleanup(zone_id)
.map_err(|err| Error::SledEditError { sled_id, err })?;
}
Ok(())
}
pub(crate) fn expunge_all_multinode_clickhouse(
&mut self,
sled_id: SledUuid,
reason: ZoneExpungeReason,
) -> Result<(), Error> {
let editor = self.sled_editors.get_mut(&sled_id).ok_or_else(|| {
Error::Planner(anyhow!(
"tried to expunge multinode clickhouse zones for unknown \
sled {sled_id}"
))
})?;
let mut zones_to_expunge = Vec::new();
for zone in editor.zones(BlueprintZoneDisposition::is_in_service) {
if zone.zone_type.is_clickhouse_keeper()
|| zone.zone_type.is_clickhouse_server()
{
zones_to_expunge.push(zone.id);
}
}
let mut nexpunged = 0;
for zone_id in zones_to_expunge {
if editor
.expunge_zone(&zone_id)
.map_err(|err| Error::SledEditError { sled_id, err })?
{
nexpunged += 1;
}
}
if nexpunged > 0 {
self.record_operation(Operation::ZoneExpunged {
sled_id,
reason,
count: nexpunged,
});
}
Ok(())
}
pub(crate) fn expunge_all_singlenode_clickhouse(
&mut self,
sled_id: SledUuid,
reason: ZoneExpungeReason,
) -> Result<(), Error> {
let editor = self.sled_editors.get_mut(&sled_id).ok_or_else(|| {
Error::Planner(anyhow!(
"tried to expunge singlenode clickhouse zones for unknown \
sled {sled_id}"
))
})?;