-
Notifications
You must be signed in to change notification settings - Fork 40
/
planner.rs
3519 lines (3180 loc) · 133 KB
/
planner.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/.
//! High-level facilities for generating Blueprints
//!
//! See crate-level documentation for details.
use crate::blueprint_builder::BlueprintBuilder;
use crate::blueprint_builder::Ensure;
use crate::blueprint_builder::EnsureMultiple;
use crate::blueprint_builder::Error;
use crate::blueprint_builder::Operation;
use crate::planner::omicron_zone_placement::PlacementError;
use nexus_sled_agent_shared::inventory::ZoneKind;
use nexus_types::deployment::Blueprint;
use nexus_types::deployment::BlueprintZoneConfig;
use nexus_types::deployment::BlueprintZoneDisposition;
use nexus_types::deployment::BlueprintZoneFilter;
use nexus_types::deployment::CockroachDbClusterVersion;
use nexus_types::deployment::CockroachDbPreserveDowngrade;
use nexus_types::deployment::CockroachDbSettings;
use nexus_types::deployment::PlanningInput;
use nexus_types::deployment::SledDetails;
use nexus_types::deployment::SledFilter;
use nexus_types::deployment::ZpoolFilter;
use nexus_types::external_api::views::SledPolicy;
use nexus_types::external_api::views::SledState;
use nexus_types::inventory::Collection;
use omicron_uuid_kinds::SledUuid;
use slog::error;
use slog::{info, warn, Logger};
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::str::FromStr;
pub(crate) use self::omicron_zone_placement::DiscretionaryOmicronZone;
use self::omicron_zone_placement::OmicronZonePlacement;
use self::omicron_zone_placement::OmicronZonePlacementSledState;
pub use self::rng::PlannerRng;
mod omicron_zone_placement;
pub(crate) mod rng;
pub struct Planner<'a> {
log: Logger,
input: &'a PlanningInput,
blueprint: BlueprintBuilder<'a>,
// latest inventory collection
//
// We must be very careful when using this during planning. The real-world
// state may have changed since this inventory was collected. Planning
// choices should not depend on this still being totally accurate.
//
// If we do start depending on specific criteria (e.g., it contains
// information about all sleds that we expect), we should verify that up
// front and update callers to ensure that it's true.
inventory: &'a Collection,
}
impl<'a> Planner<'a> {
pub fn new_based_on(
log: Logger,
parent_blueprint: &'a Blueprint,
input: &'a PlanningInput,
creator: &str,
// NOTE: Right now, we just assume that this is the latest inventory
// collection. See the comment on the corresponding field in `Planner`.
inventory: &'a Collection,
) -> anyhow::Result<Planner<'a>> {
let blueprint = BlueprintBuilder::new_based_on(
&log,
parent_blueprint,
input,
inventory,
creator,
)?;
Ok(Planner { log, input, blueprint, inventory })
}
/// Within tests, set a seeded 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 with_rng(mut self, rng: PlannerRng) -> Self {
// This is an owned builder (self rather than &mut self) because it is
// almost never going to be conditional.
self.blueprint.set_rng(rng);
self
}
pub fn plan(mut self) -> Result<Blueprint, Error> {
self.do_plan()?;
Ok(self.blueprint.build())
}
fn do_plan(&mut self) -> Result<(), Error> {
// We perform planning in two loops: the first one turns expunged sleds
// into expunged zones, and the second one adds services.
self.do_plan_expunge()?;
self.do_plan_add()?;
self.do_plan_decommission()?;
self.do_plan_cockroachdb_settings();
Ok(())
}
fn do_plan_decommission(&mut self) -> Result<(), Error> {
// Check for any sleds that are currently commissioned but can be
// decommissioned. Our gates for decommissioning are:
//
// 1. The policy indicates the sled has been removed (i.e., the policy
// is "expunged"; we may have other policies that satisfy this
// requirement in the future).
// 2. All zones associated with the sled have been marked expunged.
// 3. There are no instances assigned to this sled. This is blocked by
// omicron#4872, so today we omit this check entirely, as any sled
// that could be otherwise decommissioned that still has instances
// assigned to it needs support intervention for cleanup.
// 4. All disks associated with the sled have been marked expunged. This
// happens implicitly when a sled is expunged, so is covered by our
// first check.
for (sled_id, sled_details) in
self.input.all_sleds(SledFilter::Commissioned)
{
// Check 1: look for sleds that are expunged.
match (sled_details.policy, sled_details.state) {
// If the sled is still in service, don't decommission it.
(SledPolicy::InService { .. }, _) => continue,
// If the sled is already decommissioned it... why is it showing
// up when we ask for commissioned sleds? Warn, but don't try to
// decommission it again.
(SledPolicy::Expunged, SledState::Decommissioned) => {
error!(
self.log,
"decommissioned sled returned by \
SledFilter::Commissioned";
"sled_id" => %sled_id,
);
continue;
}
// The sled is expunged but not yet decommissioned; fall through
// to check the rest of the criteria.
(SledPolicy::Expunged, SledState::Active) => (),
}
// Check 2: have all this sled's zones been expunged? It's possible
// we ourselves have made this change, which is fine.
let all_zones_expunged = self
.blueprint
.current_sled_zones(sled_id, BlueprintZoneFilter::All)
.all(|zone| {
zone.disposition == BlueprintZoneDisposition::Expunged
});
// Check 3: Are there any instances assigned to this sled? See
// comment above; while we wait for omicron#4872, we just assume
// there are no instances running.
let num_instances_assigned = 0;
if all_zones_expunged && num_instances_assigned == 0 {
self.blueprint
.set_sled_state(sled_id, SledState::Decommissioned);
}
}
Ok(())
}
fn do_plan_expunge(&mut self) -> Result<(), Error> {
let mut commissioned_sled_ids = BTreeSet::new();
// Remove services from sleds marked expunged. We use
// `SledFilter::Commissioned` and have a custom `needs_zone_expungement`
// function that allows us to produce better errors.
for (sled_id, sled_details) in
self.input.all_sleds(SledFilter::Commissioned)
{
commissioned_sled_ids.insert(sled_id);
// Perform the expungement, for any zones that might need it.
self.blueprint.expunge_zones_for_sled(sled_id, sled_details)?;
}
// Check for any decommissioned sleds (i.e., sleds for which our
// blueprint has zones, but are not in the input sled list). Any zones
// for decommissioned sleds must have already be expunged for
// decommissioning to have happened; fail if we find non-expunged zones
// associated with a decommissioned sled.
for sled_id in self.blueprint.sled_ids_with_zones() {
if !commissioned_sled_ids.contains(&sled_id) {
let num_zones = self
.blueprint
.current_sled_zones(sled_id, BlueprintZoneFilter::All)
.filter(|zone| {
zone.disposition != BlueprintZoneDisposition::Expunged
})
.count();
if num_zones > 0 {
return Err(
Error::DecommissionedSledWithNonExpungedZones {
sled_id,
num_zones,
},
);
}
}
}
Ok(())
}
fn do_plan_add(&mut self) -> Result<(), Error> {
// Internal DNS is a prerequisite for bringing up all other zones. At
// this point, we assume that internal DNS (as a service) is already
// functioning.
// After we make our initial pass through the sleds below to check for
// zones every sled should have (NTP, Crucible), we'll start making
// decisions about placing other service zones. We need to _exclude_ any
// sleds for which we just added an NTP zone, as we won't be able to add
// additional services to them until that NTP zone has been brought up.
//
// We will not mark sleds getting Crucible zones as ineligible; other
// control plane service zones starting concurrently with Crucible zones
// is fine.
let mut sleds_waiting_for_ntp_zone = BTreeSet::new();
for (sled_id, sled_resources) in
self.input.all_sled_resources(SledFilter::InService)
{
// First, we need to ensure that sleds are using their expected
// disks. This is necessary before we can allocate any zones.
if let EnsureMultiple::Changed {
added,
updated,
expunged: _,
removed,
} = self.blueprint.sled_ensure_disks(sled_id, &sled_resources)?
{
info!(
&self.log,
"altered physical disks";
"sled_id" => %sled_id
);
self.blueprint.record_operation(Operation::UpdateDisks {
sled_id,
added,
updated,
removed,
});
// Note that this doesn't actually need to short-circuit the
// rest of the blueprint planning, as long as during execution
// we send this request first.
}
// Check for an NTP zone. Every sled should have one. If it's not
// there, all we can do is provision that one zone. We have to wait
// for that to succeed and synchronize the clock before we can
// provision anything else.
if self.blueprint.sled_ensure_zone_ntp(sled_id)? == Ensure::Added {
info!(
&self.log,
"found sled missing NTP zone (will add one)";
"sled_id" => %sled_id
);
self.blueprint.record_operation(Operation::AddZone {
sled_id,
kind: ZoneKind::BoundaryNtp,
});
// Don't make any other changes to this sled. However, this
// change is compatible with any other changes to other sleds,
// so we can "continue" here rather than "break".
sleds_waiting_for_ntp_zone.insert(sled_id);
continue;
}
// Now we've established that the current blueprint _says_ there's
// an NTP zone on this system. But we must wait for it to actually
// be there before we can proceed to add anything else. Otherwise,
// we may wind up trying to provision this zone at the same time as
// other zones, and Sled Agent will reject requests to provision
// other zones before the clock is synchronized.
//
// Note that it's always possible that the NTP zone was added after
// this inventory was collected (in which case we'll erroneously
// choose to bail out here, but we'll pick it up again next time
// we're invoked). It's conceivable that the NTP zone was removed
// after this inventory was collected (in which case we'd be making
// a wrong decision here). However, we don't ever do this today.
// If we were to do something like that (maybe as part of upgrading
// the NTP zone or switching between an internal NTP vs. boundary
// NTP zone), we'll need to be careful how we do it to avoid a
// problem here.
let has_ntp_inventory = self
.inventory
.sled_agents
.get(&sled_id)
.map(|sled_agent| {
sled_agent
.omicron_zones
.zones
.iter()
.any(|z| z.zone_type.is_ntp())
})
.unwrap_or(false);
if !has_ntp_inventory {
info!(
&self.log,
"parent blueprint contains NTP zone, but it's not in \
inventory yet";
"sled_id" => %sled_id,
);
continue;
}
// Every provisionable zpool on the sled should have a Crucible zone
// on it.
let mut ncrucibles_added = 0;
for zpool_id in sled_resources.all_zpools(ZpoolFilter::InService) {
if self
.blueprint
.sled_ensure_zone_crucible(sled_id, *zpool_id)?
== Ensure::Added
{
info!(
&self.log,
"found sled zpool missing Crucible zone (will add one)";
"sled_id" => ?sled_id,
"zpool_id" => ?zpool_id,
);
ncrucibles_added += 1;
}
}
if ncrucibles_added > 0 {
// Don't make any other changes to this sled. However, this
// change is compatible with any other changes to other sleds,
// so we can "continue" here rather than "break".
// (Yes, it's currently the last thing in the loop, but being
// explicit here means we won't forget to do this when more code
// is added below.)
self.blueprint.record_operation(Operation::AddZone {
sled_id,
kind: ZoneKind::Crucible,
});
continue;
}
}
self.do_plan_add_discretionary_zones(&sleds_waiting_for_ntp_zone)?;
// Now that we've added all the disks and zones we plan on adding,
// ensure that all sleds have the datasets they need to have.
self.do_plan_datasets()?;
Ok(())
}
fn do_plan_datasets(&mut self) -> Result<(), Error> {
for (sled_id, sled_resources) in
self.input.all_sled_resources(SledFilter::InService)
{
if let EnsureMultiple::Changed {
added,
updated,
expunged,
removed,
} =
self.blueprint.sled_ensure_datasets(sled_id, &sled_resources)?
{
info!(
&self.log,
"altered datasets";
"sled_id" => %sled_id,
"added" => added,
"updated" => updated,
"expunged" => expunged,
"removed" => removed,
);
self.blueprint.record_operation(Operation::UpdateDatasets {
sled_id,
added,
updated,
expunged,
removed,
});
}
}
Ok(())
}
fn do_plan_add_discretionary_zones(
&mut self,
sleds_waiting_for_ntp_zone: &BTreeSet<SledUuid>,
) -> Result<(), Error> {
// We usually don't need to construct an `OmicronZonePlacement` to add
// discretionary zones, so defer its creation until it's needed.
let mut zone_placement = None;
for zone_kind in [
DiscretionaryOmicronZone::BoundaryNtp,
DiscretionaryOmicronZone::Clickhouse,
DiscretionaryOmicronZone::ClickhouseKeeper,
DiscretionaryOmicronZone::ClickhouseServer,
DiscretionaryOmicronZone::CockroachDb,
DiscretionaryOmicronZone::CruciblePantry,
DiscretionaryOmicronZone::InternalDns,
DiscretionaryOmicronZone::ExternalDns,
DiscretionaryOmicronZone::Nexus,
DiscretionaryOmicronZone::Oximeter,
] {
let num_zones_to_add = self.num_additional_zones_needed(zone_kind);
if num_zones_to_add == 0 {
continue;
}
// We need to add at least one zone; construct our `zone_placement`
// (or reuse the existing one if a previous loop iteration already
// created it).
let zone_placement = zone_placement.get_or_insert_with(|| {
// This constructs a picture of the sleds as we currently
// understand them, as far as which sleds have discretionary
// zones. This will remain valid as we loop through the
// `zone_kind`s in this function, as any zone additions will
// update the `zone_placement` heap in-place.
let current_discretionary_zones = self
.input
.all_sled_resources(SledFilter::Discretionary)
.filter(|(sled_id, _)| {
!sleds_waiting_for_ntp_zone.contains(&sled_id)
})
.map(|(sled_id, sled_resources)| {
OmicronZonePlacementSledState {
sled_id,
num_zpools: sled_resources
.all_zpools(ZpoolFilter::InService)
.count(),
discretionary_zones: self
.blueprint
.current_sled_zones(
sled_id,
BlueprintZoneFilter::ShouldBeRunning,
)
.filter_map(|zone| {
DiscretionaryOmicronZone::from_zone_type(
&zone.zone_type,
)
})
.collect(),
}
});
OmicronZonePlacement::new(current_discretionary_zones)
});
self.add_discretionary_zones(
zone_placement,
zone_kind,
num_zones_to_add,
)?;
}
Ok(())
}
// Given the current blueprint state and policy, returns the number of
// additional zones needed of the given `zone_kind` to satisfy the policy.
fn num_additional_zones_needed(
&mut self,
zone_kind: DiscretionaryOmicronZone,
) -> usize {
// Count the number of `kind` zones on all in-service sleds. This
// will include sleds that are in service but not eligible for new
// services, but will not include sleds that have been expunged or
// decommissioned.
let mut num_existing_kind_zones = 0;
for sled_id in self.input.all_sled_ids(SledFilter::InService) {
let num_zones_of_kind = self
.blueprint
.sled_num_running_zones_of_kind(sled_id, zone_kind.into());
num_existing_kind_zones += num_zones_of_kind;
}
let target_count = match zone_kind {
DiscretionaryOmicronZone::BoundaryNtp => {
self.input.target_boundary_ntp_zone_count()
}
DiscretionaryOmicronZone::Clickhouse => {
self.input.target_clickhouse_zone_count()
}
DiscretionaryOmicronZone::ClickhouseKeeper => {
self.input.target_clickhouse_keeper_zone_count()
}
DiscretionaryOmicronZone::ClickhouseServer => {
self.input.target_clickhouse_server_zone_count()
}
DiscretionaryOmicronZone::CockroachDb => {
self.input.target_cockroachdb_zone_count()
}
DiscretionaryOmicronZone::CruciblePantry => {
self.input.target_crucible_pantry_zone_count()
}
DiscretionaryOmicronZone::InternalDns => {
self.input.target_internal_dns_zone_count()
}
DiscretionaryOmicronZone::ExternalDns => {
// TODO-cleanup: When external DNS addresses are
// in the policy, this can use the input, too.
self.blueprint.count_parent_external_dns_zones()
}
DiscretionaryOmicronZone::Nexus => {
self.input.target_nexus_zone_count()
}
DiscretionaryOmicronZone::Oximeter => {
self.input.target_oximeter_zone_count()
}
};
// TODO-correctness What should we do if we have _too many_
// `zone_kind` zones? For now, just log it the number of zones any
// time we have at least the minimum number.
let num_zones_to_add =
target_count.saturating_sub(num_existing_kind_zones);
if num_zones_to_add == 0 {
info!(
self.log, "sufficient {zone_kind:?} zones exist in plan";
"desired_count" => target_count,
"current_count" => num_existing_kind_zones,
);
}
num_zones_to_add
}
// Attempts to place `num_zones_to_add` new zones of `kind`.
//
// It is not an error if there are too few eligible sleds to start a
// sufficient number of zones; instead, we'll log a warning and start as
// many as we can (up to `num_zones_to_add`).
fn add_discretionary_zones(
&mut self,
zone_placement: &mut OmicronZonePlacement,
kind: DiscretionaryOmicronZone,
mut num_zones_to_add: usize,
) -> Result<(), Error> {
// Build a map of sled -> new zones to add.
let mut sleds_to_change: BTreeMap<SledUuid, usize> = BTreeMap::new();
for i in 0..num_zones_to_add {
match zone_placement.place_zone(kind) {
Ok(sled_id) => {
*sleds_to_change.entry(sled_id).or_default() += 1;
}
Err(PlacementError::NoSledsEligible { .. }) => {
// We won't treat this as a hard error; it's possible
// (albeit unlikely?) we're in a weird state where we need
// more sleds or disks to come online, and we may need to be
// able to produce blueprints to achieve that status.
warn!(
self.log,
"failed to place all new desired {kind:?} zones";
"placed" => i,
"wanted_to_place" => num_zones_to_add,
);
// Adjust `num_zones_to_add` downward so it's consistent
// with the number of zones we're actually adding.
num_zones_to_add = i;
break;
}
}
}
// For each sled we need to change, actually do so.
let mut new_zones_added = 0;
for (sled_id, additional_zone_count) in sleds_to_change {
// TODO-cleanup This is awkward: the builder wants to know how many
// total zones go on a given sled, but we have a count of how many
// we want to add. Construct a new target count. Maybe the builder
// should provide a different interface here?
let new_total_zone_count = self
.blueprint
.sled_num_running_zones_of_kind(sled_id, kind.into())
+ additional_zone_count;
let result = match kind {
DiscretionaryOmicronZone::BoundaryNtp => self
.blueprint
.sled_promote_internal_ntp_to_boundary_ntp(sled_id)?,
DiscretionaryOmicronZone::Clickhouse => {
self.blueprint.sled_ensure_zone_multiple_clickhouse(
sled_id,
new_total_zone_count,
)?
}
DiscretionaryOmicronZone::ClickhouseKeeper => {
self.blueprint.sled_ensure_zone_multiple_clickhouse_keeper(
sled_id,
new_total_zone_count,
)?
}
DiscretionaryOmicronZone::ClickhouseServer => {
self.blueprint.sled_ensure_zone_multiple_clickhouse_server(
sled_id,
new_total_zone_count,
)?
}
DiscretionaryOmicronZone::CockroachDb => {
self.blueprint.sled_ensure_zone_multiple_cockroachdb(
sled_id,
new_total_zone_count,
)?
}
DiscretionaryOmicronZone::CruciblePantry => {
self.blueprint.sled_ensure_zone_multiple_crucible_pantry(
sled_id,
new_total_zone_count,
)?
}
DiscretionaryOmicronZone::InternalDns => {
self.blueprint.sled_ensure_zone_multiple_internal_dns(
sled_id,
new_total_zone_count,
)?
}
DiscretionaryOmicronZone::ExternalDns => {
self.blueprint.sled_ensure_zone_multiple_external_dns(
sled_id,
new_total_zone_count,
)?
}
DiscretionaryOmicronZone::Nexus => {
self.blueprint.sled_ensure_zone_multiple_nexus(
sled_id,
new_total_zone_count,
)?
}
DiscretionaryOmicronZone::Oximeter => {
self.blueprint.sled_ensure_zone_multiple_oximeter(
sled_id,
new_total_zone_count,
)?
}
};
match result {
EnsureMultiple::Changed {
added,
updated,
expunged,
removed,
} => {
info!(
self.log, "modified zones on sled";
"sled_id" => %sled_id,
"kind" => ?kind,
"added" => added,
"updated" => updated,
"expunged" => expunged,
"removed" => removed,
);
new_zones_added += added;
}
// This is only possible if we asked the sled to ensure the same
// number of zones it already has, but that's impossible based
// on the way we built up `sleds_to_change`.
EnsureMultiple::NotNeeded => unreachable!(
"sled on which we added {kind:?} zones did not add any"
),
}
}
// Double check that we didn't make any arithmetic mistakes. If we've
// arrived here, we think we've added the number of `kind` zones we
// needed to.
assert_eq!(
new_zones_added, num_zones_to_add,
"internal error counting {kind:?} zones"
);
Ok(())
}
fn do_plan_cockroachdb_settings(&mut self) {
// Figure out what we should set the CockroachDB "preserve downgrade
// option" setting to based on the planning input.
//
// CockroachDB version numbers look like SemVer but are not. Major
// version numbers consist of the first *two* components, which
// represent the year and the Nth release that year. So the major
// version in "22.2.7" is "22.2".
//
// A given major version of CockroachDB is backward compatible with the
// storage format of the previous major version of CockroachDB. This is
// shown by the `version` setting, which displays the current storage
// format version. When `version` is '22.2', versions v22.2.x or v23.1.x
// can be used to run a node. This allows for rolling upgrades of nodes
// within the cluster and also preserves the ability to rollback until
// the new software version can be validated.
//
// By default, when all nodes of a cluster are upgraded to a new major
// version, the upgrade is "auto-finalized"; `version` is changed to the
// new major version, and rolling back to a previous major version of
// CockroachDB is no longer possible.
//
// The `cluster.preserve_downgrade_option` setting can be used to
// control this. This setting can only be set to the current value
// of the `version` setting, and when it is set, CockroachDB will not
// perform auto-finalization. To perform finalization and finish the
// upgrade, a client must reset the "preserve downgrade option" setting.
// Finalization occurs in the background, and the "preserve downgrade
// option" setting should not be changed again until finalization
// completes.
//
// We determine the appropriate value for `preserve_downgrade_option`
// based on:
//
// 1. the _target_ cluster version from the `Policy` (what we want to
// be running)
// 2. the `version` setting reported by CockroachDB (what we're
// currently running)
//
// by saying:
//
// - If we don't recognize the `version` CockroachDB reports, we will
// do nothing.
// - If our target version is _equal to_ what CockroachDB reports,
// we will ensure `preserve_downgrade_option` is set to the current
// `version`. This prevents auto-finalization when we deploy the next
// major version of CockroachDB as part of an update.
// - If our target version is _older than_ what CockroachDB reports, we
// will also ensure `preserve_downgrade_option` is set to the current
// `version`. (This will happen on newly-initialized clusters when
// we deploy a version of CockroachDB that is newer than our current
// policy.)
// - If our target version is _newer than_ what CockroachDB reports, we
// will ensure `preserve_downgrade_option` is set to the default value
// (the empty string). This will trigger finalization.
let policy = self.input.target_cockroachdb_cluster_version();
let CockroachDbSettings { version, .. } =
self.input.cockroachdb_settings();
let value = match CockroachDbClusterVersion::from_str(version) {
// The current version is known to us.
Ok(version) => {
if policy > version {
// Ensure `cluster.preserve_downgrade_option` is reset so we
// can upgrade.
CockroachDbPreserveDowngrade::AllowUpgrade
} else {
// The cluster version is equal to or newer than the
// version we want by policy. In either case, ensure
// `cluster.preserve_downgrade_option` is set.
CockroachDbPreserveDowngrade::Set(version)
}
}
// The current version is unknown to us; we are likely in the middle
// of an cluster upgrade.
Err(_) => CockroachDbPreserveDowngrade::DoNotModify,
};
self.blueprint.cockroachdb_preserve_downgrade(value);
info!(
&self.log,
"will ensure cockroachdb setting";
"setting" => "cluster.preserve_downgrade_option",
"value" => ?value,
);
// Hey! Listen!
//
// If we need to manage more CockroachDB settings, we should ensure
// that no settings will be modified if we don't recognize the current
// cluster version -- we're likely in the middle of an upgrade!
//
// https://www.cockroachlabs.com/docs/stable/cluster-settings#change-a-cluster-setting
}
}
/// Returns `Some(reason)` if the sled needs its zones to be expunged,
/// based on the policy and state.
fn sled_needs_all_zones_expunged(
state: SledState,
policy: SledPolicy,
) -> Option<ZoneExpungeReason> {
match state {
SledState::Active => {}
SledState::Decommissioned => {
// A decommissioned sled that still has resources attached to it is
// an illegal state, but representable. If we see a sled in this
// state, we should still expunge all zones in it, but parent code
// should warn on it.
return Some(ZoneExpungeReason::SledDecommissioned);
}
}
match policy {
SledPolicy::InService { .. } => None,
SledPolicy::Expunged => Some(ZoneExpungeReason::SledExpunged),
}
}
pub(crate) fn zone_needs_expungement(
sled_details: &SledDetails,
zone_config: &BlueprintZoneConfig,
input: &PlanningInput,
) -> Option<ZoneExpungeReason> {
// Should we expunge the zone because the sled is gone?
if let Some(reason) =
sled_needs_all_zones_expunged(sled_details.state, sled_details.policy)
{
return Some(reason);
}
// Should we expunge the zone because durable storage is gone?
if let Some(durable_storage_zpool) = zone_config.zone_type.durable_zpool() {
let zpool_id = durable_storage_zpool.id();
if !sled_details.resources.zpool_is_provisionable(&zpool_id) {
return Some(ZoneExpungeReason::DiskExpunged);
}
};
// Should we expunge the zone because transient storage is gone?
if let Some(ref filesystem_zpool) = zone_config.filesystem_pool {
let zpool_id = filesystem_zpool.id();
if !sled_details.resources.zpool_is_provisionable(&zpool_id) {
return Some(ZoneExpungeReason::DiskExpunged);
}
};
// Should we expunge the zone because clickhouse clusters are no longer
// enabled via policy?
if !input.clickhouse_cluster_enabled() {
if zone_config.zone_type.is_clickhouse_keeper()
|| zone_config.zone_type.is_clickhouse_server()
{
return Some(ZoneExpungeReason::ClickhouseClusterDisabled);
}
}
// Should we expunge the zone because single-node clickhouse is no longer
// enabled via policy?
if !input.clickhouse_single_node_enabled() {
if zone_config.zone_type.is_clickhouse() {
return Some(ZoneExpungeReason::ClickhouseSingleNodeDisabled);
}
}
None
}
/// The reason a sled's zones need to be expunged.
///
/// This is used only for introspection and logging -- it's not part of the
/// logical flow.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub(crate) enum ZoneExpungeReason {
DiskExpunged,
SledDecommissioned,
SledExpunged,
ClickhouseClusterDisabled,
ClickhouseSingleNodeDisabled,
}
#[cfg(test)]
mod test {
use super::Planner;
use crate::blueprint_builder::test::assert_planning_makes_no_changes;
use crate::blueprint_builder::test::verify_blueprint;
use crate::blueprint_builder::BlueprintBuilder;
use crate::blueprint_builder::EnsureMultiple;
use crate::example::example;
use crate::example::ExampleSystemBuilder;
use crate::example::SimRngState;
use crate::planner::rng::PlannerRng;
use crate::system::SledBuilder;
use chrono::NaiveDateTime;
use chrono::TimeZone;
use chrono::Utc;
use clickhouse_admin_types::ClickhouseKeeperClusterMembership;
use clickhouse_admin_types::KeeperId;
use expectorate::assert_contents;
use nexus_sled_agent_shared::inventory::ZoneKind;
use nexus_types::deployment::blueprint_zone_type;
use nexus_types::deployment::BlueprintDiff;
use nexus_types::deployment::BlueprintZoneDisposition;
use nexus_types::deployment::BlueprintZoneFilter;
use nexus_types::deployment::BlueprintZoneType;
use nexus_types::deployment::ClickhouseMode;
use nexus_types::deployment::ClickhousePolicy;
use nexus_types::deployment::CockroachDbClusterVersion;
use nexus_types::deployment::CockroachDbPreserveDowngrade;
use nexus_types::deployment::CockroachDbSettings;
use nexus_types::deployment::SledDisk;
use nexus_types::external_api::views::PhysicalDiskPolicy;
use nexus_types::external_api::views::PhysicalDiskState;
use nexus_types::external_api::views::SledPolicy;
use nexus_types::external_api::views::SledProvisionPolicy;
use nexus_types::external_api::views::SledState;
use omicron_common::api::external::Generation;
use omicron_common::disk::DiskIdentity;
use omicron_common::policy::CRUCIBLE_PANTRY_REDUNDANCY;
use omicron_test_utils::dev::test_setup_log;
use omicron_uuid_kinds::PhysicalDiskUuid;
use omicron_uuid_kinds::SledUuid;
use omicron_uuid_kinds::ZpoolUuid;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::net::IpAddr;
use typed_rng::TypedUuidRng;
// Generate a ClickhousePolicy ignoring fields we don't care about for
/// planner tests
fn clickhouse_policy(mode: ClickhouseMode) -> ClickhousePolicy {
ClickhousePolicy { version: 0, mode, time_created: Utc::now() }
}
/// Runs through a basic sequence of blueprints for adding a sled
#[test]
fn test_basic_add_sled() {
static TEST_NAME: &str = "planner_basic_add_sled";
let logctx = test_setup_log(TEST_NAME);
// Use our example system.
let mut rng = SimRngState::from_seed(TEST_NAME);
let (mut example, blueprint1) = ExampleSystemBuilder::new_with_rng(
&logctx.log,
rng.next_system_rng(),
)
.build();
verify_blueprint(&blueprint1);
println!("{}", blueprint1.display());
// Now run the planner. It should do nothing because our initial
// system didn't have any issues that the planner currently knows how to
// fix.
let blueprint2 = Planner::new_based_on(
logctx.log.clone(),
&blueprint1,
&example.input,
"no-op?",
&example.collection,
)
.expect("failed to create planner")
.with_rng(PlannerRng::from_seed((TEST_NAME, "bp2")))
.plan()
.expect("failed to plan");
let diff = blueprint2.diff_since_blueprint(&blueprint1);
println!("1 -> 2 (expected no changes):\n{}", diff.display());
assert_eq!(diff.sleds_added.len(), 0);
assert_eq!(diff.sleds_removed.len(), 0);
assert_eq!(diff.sleds_modified.len(), 0);
assert_eq!(diff.zones.added.len(), 0);
assert_eq!(diff.zones.removed.len(), 0);
assert_eq!(diff.zones.modified.len(), 0);
assert_eq!(diff.zones.errors.len(), 0);
assert_eq!(diff.physical_disks.added.len(), 0);
assert_eq!(diff.physical_disks.removed.len(), 0);
assert_eq!(diff.datasets.added.len(), 0);
assert_eq!(diff.datasets.removed.len(), 0);
assert_eq!(diff.datasets.modified.len(), 0);
assert_eq!(diff.datasets.unchanged.len(), 3);
verify_blueprint(&blueprint2);
// Now add a new sled.
let mut sled_id_rng = rng.next_sled_id_rng();
let new_sled_id = sled_id_rng.next();
let _ =
example.system.sled(SledBuilder::new().id(new_sled_id)).unwrap();
let input = example.system.to_planning_input_builder().unwrap().build();
// Check that the first step is to add an NTP zone
let blueprint3 = Planner::new_based_on(
logctx.log.clone(),
&blueprint2,
&input,
"test: add NTP?",
&example.collection,
)
.expect("failed to create planner")
.with_rng(PlannerRng::from_seed((TEST_NAME, "bp3")))
.plan()
.expect("failed to plan");
let diff = blueprint3.diff_since_blueprint(&blueprint2);
println!(
"2 -> 3 (expect new NTP zone on new sled):\n{}",
diff.display()
);
assert_contents(
"tests/output/planner_basic_add_sled_2_3.txt",
&diff.display().to_string(),
);
assert_eq!(diff.sleds_added.len(), 1);
assert_eq!(diff.physical_disks.added.len(), 1);
assert_eq!(diff.datasets.added.len(), 1);
let sled_id = *diff.sleds_added.first().unwrap();
let sled_zones = diff.zones.added.get(&sled_id).unwrap();
// We have defined elsewhere that the first generation contains no
// zones. So the first one with zones must be newer. See