-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathsled.rs
3038 lines (2761 loc) · 110 KB
/
sled.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/.
//! [`DataStore`] methods on [`Sled`]s.
use super::DataStore;
use super::SQL_BATCH_SIZE;
use crate::authz;
use crate::context::OpContext;
use crate::db;
use crate::db::datastore::ValidateTransition;
use crate::db::error::public_error_from_diesel;
use crate::db::error::ErrorHandler;
use crate::db::model::to_db_sled_policy;
use crate::db::model::AffinityPolicy;
use crate::db::model::Sled;
use crate::db::model::SledResourceVmm;
use crate::db::model::SledState;
use crate::db::model::SledUpdate;
use crate::db::pagination::paginated;
use crate::db::pagination::Paginator;
use crate::db::pool::DbConnection;
use crate::db::queries::sled_reservation::sled_find_targets_query;
use crate::db::queries::sled_reservation::sled_insert_resource_query;
use crate::db::update_and_check::{UpdateAndCheck, UpdateStatus};
use crate::db::TransactionError;
use crate::transaction_retry::OptionalError;
use async_bb8_diesel::AsyncRunQueryDsl;
use chrono::Utc;
use diesel::prelude::*;
use nexus_db_model::ApplySledFilterExt;
use nexus_types::deployment::SledFilter;
use nexus_types::external_api::views::SledPolicy;
use nexus_types::external_api::views::SledProvisionPolicy;
use nexus_types::identity::Asset;
use omicron_common::api::external;
use omicron_common::api::external::CreateResult;
use omicron_common::api::external::DataPageParams;
use omicron_common::api::external::DeleteResult;
use omicron_common::api::external::Error;
use omicron_common::api::external::ListResultVec;
use omicron_common::api::external::ResourceType;
use omicron_common::bail_unless;
use omicron_uuid_kinds::GenericUuid;
use omicron_uuid_kinds::InstanceUuid;
use omicron_uuid_kinds::PropolisUuid;
use omicron_uuid_kinds::SledUuid;
use slog::Logger;
use std::collections::HashSet;
use std::fmt;
use strum::IntoEnumIterator;
use thiserror::Error;
use uuid::Uuid;
#[derive(Debug, thiserror::Error)]
enum SledReservationError {
#[error(
"Could not find any valid sled on which this instance can be placed"
)]
NotFound,
#[error(
"This instance belongs to an affinity group that requires it be placed \
on more than one sled. Instances can only placed on a single sled, so \
this is impossible to satisfy. Consider stopping other instances in \
the affinity group."
)]
TooManyAffinityConstraints,
#[error(
"This instance belongs to an affinity group that requires it to be \
placed on a sled, but also belongs to an anti-affinity group that \
prevents it from being placed on that sled. These constraints are \
contradictory. Consider stopping instances in those \
affinity/anti-affinity groups, or changing group membership."
)]
ConflictingAntiAndAffinityConstraints,
#[error(
"This instance must be placed on a specific sled to co-locate it \
with another instance in its affinity group, but that sled cannot \
current accept this instance. Consider stopping other instances \
in this instance's affinity groups, or changing its affinity \
group membership."
)]
RequiredAffinitySledNotValid,
}
impl From<SledReservationError> for external::Error {
fn from(err: SledReservationError) -> Self {
let msg = format!("Failed to place instance: {err}");
match err {
// "NotFound" can be resolved by adding more capacity
SledReservationError::NotFound
// "RequiredAffinitySledNotValid" is *usually* the result of a
// single sled filling up with several members of an Affinity group.
//
// It is also possible briefly when a sled with affinity groups is
// being expunged with running VMMs, but "insufficient capacity" is
// the much more common case.
//
// (Disambiguating these cases would require additional database
// queries, hence why this isn't being done right now)
| SledReservationError::RequiredAffinitySledNotValid => {
external::Error::insufficient_capacity(&msg, &msg)
},
// The following cases are constraint violations due to excessive
// affinity/anti-affinity groups -- even if additional capacity is
// added, they won't be fixed. Return a 400 error to signify to the
// caller that they're responsible for fixing these constraints.
SledReservationError::TooManyAffinityConstraints
| SledReservationError::ConflictingAntiAndAffinityConstraints => {
external::Error::invalid_request(&msg)
},
}
}
}
#[derive(Debug, thiserror::Error)]
enum SledReservationTransactionError {
#[error(transparent)]
Connection(#[from] Error),
#[error(transparent)]
Diesel(#[from] diesel::result::Error),
#[error(transparent)]
Reservation(#[from] SledReservationError),
}
// Chooses a sled for reservation with the supplied constraints.
//
// - "targets": All possible sleds which might be selected.
// - "anti_affinity_sleds": All sleds which are anti-affine to
// our requested reservation.
// - "affinity_sleds": All sleds which are affine to our requested
// reservation.
//
// We use the following logic to calculate a desirable sled, given a possible
// set of "targets", and the information from affinity groups.
//
// # Rules vs Preferences
//
// Due to the flavors of "affinity policy", it's possible to bucket affinity
// choices into two categories: "rules" and "preferences". "rules" are affinity
// dispositions for or against sled placement that must be followed, and
// "preferences" are affinity dispositions that should be followed for sled
// selection, in order of "most preferential" to "least preferential".
//
// As example of a "rule" is "an anti-affinity group exists, containing a
// target sled, with affinity_policy = 'fail'".
//
// An example of a "preference" is "an anti-affinity group exists, containing a
// target sled, but the policy is 'allow'." We don't want to use it as a target,
// but we will if there are no other choices.
//
// We apply rules before preferences to ensure they are always respected.
// Furthermore, the evaluation of preferences is a target-seeking operation,
// which identifies the distinct sets of targets, and searches them in
// decreasing preference order.
//
// # Logic
//
// ## Background: Notation
//
// We use the following symbols for sets below:
// - ∩: Intersection of two sets (A ∩ B is "everything that exists in A and
// also exists in B").
// - ∖: difference of two sets (A ∖ B is "everything that exists in A that does
// not exist in B).
//
// We also use the following notation for brevity:
// - AA,P=Fail: All sleds containing instances that are part of an anti-affinity
// group with policy = 'fail'.
// - AA,P=Allow: Same as above, but with policy = 'allow'.
// - A,P=Fail: All sleds containing instances that are part of an affinity group
// with policy = 'fail'.
// - A,P=Allow: Same as above, but with policy = 'allow'.
//
// ## Affinity: Apply Rules
//
// - Targets := All viable sleds for instance placement
// - Banned := AA,P=Fail
// - Required := A,P=Fail
// - if Required.len() > 1: Fail (too many constraints).
// - if Required.len() == 1...
// - ... if the entry exists in the "Banned" set: Fail
// (contradicting constraints 'Banned' + 'Required')
// - ... if the entry does not exist in "Targets": Fail
// ('Required' constraint not satisfiable)
// - ... if the entry does not exist in "Banned": Use it.
//
// If we have not yet picked a target, we can filter the set of targets to
// ignore "banned" sleds, and then apply preferences.
//
// - Targets := Targets ∖ Banned
//
// ## Affinity: Apply Preferences
//
// - Preferred := Targets ∩ A,P=Allow
// - Unpreferred := Targets ∩ AA,P=Allow
// - Both := Preferred ∩ Unpreferred
// - Preferred := Preferred ∖ Both
// - Unpreferred := Unpreferred ∖ Both
// - If Preferred isn't empty, pick a target from it.
// - Targets := Targets \ Unpreferred
// - If Targets isn't empty, pick a target from it.
// - If Unpreferred isn't empty, pick a target from it.
// - Fail, no targets are available.
fn pick_sled_reservation_target(
log: &Logger,
targets: &HashSet<SledUuid>,
banned: &HashSet<SledUuid>,
unpreferred: &HashSet<SledUuid>,
required: &HashSet<SledUuid>,
preferred: &HashSet<SledUuid>,
) -> Result<SledUuid, SledReservationError> {
if !banned.is_empty() {
info!(
log,
"anti-affinity policy prohibits placement on {} sleds", banned.len();
"banned" => ?banned,
);
}
if !required.is_empty() {
info!(
log,
"affinity policy requires placement on {} sleds", required.len();
"required" => ?required,
);
}
if required.len() > 1 {
return Err(SledReservationError::TooManyAffinityConstraints);
}
if let Some(required_id) = required.iter().next() {
// If we have a "required" sled, it must be chosen.
if banned.contains(&required_id) {
return Err(
SledReservationError::ConflictingAntiAndAffinityConstraints,
);
}
if !targets.contains(&required_id) {
return Err(SledReservationError::RequiredAffinitySledNotValid);
}
return Ok(*required_id);
}
// We have no "required" sleds, but might have preferences.
let mut targets: HashSet<_> =
targets.difference(&banned).cloned().collect();
// Only consider "preferred" sleds that are viable targets
let preferred: HashSet<_> =
targets.intersection(&preferred).cloned().collect();
// Only consider "unpreferred" sleds that are viable targets
let mut unpreferred: HashSet<_> =
targets.intersection(&unpreferred).cloned().collect();
// If a target is both preferred and unpreferred, it is not considered
// a part of either set.
let both = preferred.intersection(&unpreferred).cloned().collect();
// Grab a preferred target (which isn't also unpreferred) if one exists.
if let Some(target) = preferred.difference(&both).cloned().next() {
return Ok(target);
}
unpreferred = unpreferred.difference(&both).cloned().collect();
targets = targets.difference(&unpreferred).cloned().collect();
// Grab a target which not in the unpreferred set, if one exists.
if let Some(target) = targets.iter().cloned().next() {
return Ok(target);
}
// Grab a target from the unpreferred set, if one exists.
if let Some(target) = unpreferred.iter().cloned().next() {
return Ok(target);
}
return Err(SledReservationError::NotFound);
}
impl DataStore {
/// Stores a new sled in the database.
///
/// Returns the sled, and whether or not it was updated on success.
///
/// Returns an error if `sled_agent_gen` is stale, or the sled is
/// decommissioned.
pub async fn sled_upsert(
&self,
sled_update: SledUpdate,
) -> CreateResult<(Sled, bool)> {
use db::schema::sled::dsl;
// required for conditional upsert
use diesel::query_dsl::methods::FilterDsl;
let insertable_sled = sled_update.clone().into_insertable();
let now = insertable_sled.time_modified();
let sled = diesel::insert_into(dsl::sled)
.values(insertable_sled)
.on_conflict(dsl::id)
.do_update()
.set((
dsl::time_modified.eq(now),
dsl::ip.eq(sled_update.ip),
dsl::port.eq(sled_update.port),
dsl::repo_depot_port.eq(sled_update.repo_depot_port),
dsl::rack_id.eq(sled_update.rack_id),
dsl::is_scrimlet.eq(sled_update.is_scrimlet()),
dsl::usable_hardware_threads
.eq(sled_update.usable_hardware_threads),
dsl::usable_physical_ram.eq(sled_update.usable_physical_ram),
dsl::reservoir_size.eq(sled_update.reservoir_size),
dsl::sled_agent_gen.eq(sled_update.sled_agent_gen),
))
.filter(dsl::sled_agent_gen.lt(sled_update.sled_agent_gen))
.filter(dsl::sled_state.ne(SledState::Decommissioned))
.returning(Sled::as_returning())
.get_result_async(&*self.pool_connection_unauthorized().await?)
.await
.map_err(|e| {
public_error_from_diesel(
e,
ErrorHandler::Conflict(
ResourceType::Sled,
&sled_update.id().to_string(),
),
)
})?;
// We compare only seconds since the epoch, because writing to and
// reading from the database causes us to lose precision.
let was_modified = now.timestamp() == sled.time_modified().timestamp();
Ok((sled, was_modified))
}
/// Confirms that a sled exists and is in-service.
pub async fn check_sled_in_service(
&self,
opctx: &OpContext,
sled_id: SledUuid,
) -> Result<(), Error> {
let conn = &*self.pool_connection_authorized(&opctx).await?;
Self::check_sled_in_service_on_connection(conn, sled_id)
.await
.map_err(From::from)
}
/// Confirms that a sled exists and is in-service.
///
/// This function may be called from a transaction context.
pub async fn check_sled_in_service_on_connection(
conn: &async_bb8_diesel::Connection<DbConnection>,
sled_id: SledUuid,
) -> Result<(), TransactionError<Error>> {
use db::schema::sled::dsl;
let sled_exists_and_in_service = diesel::select(diesel::dsl::exists(
dsl::sled
.filter(dsl::time_deleted.is_null())
.filter(dsl::id.eq(sled_id.into_untyped_uuid()))
.sled_filter(SledFilter::InService),
))
.get_result_async::<bool>(conn)
.await?;
bail_unless!(
sled_exists_and_in_service,
"Sled {} is not in service",
sled_id,
);
Ok(())
}
pub async fn sled_list(
&self,
opctx: &OpContext,
pagparams: &DataPageParams<'_, Uuid>,
sled_filter: SledFilter,
) -> ListResultVec<Sled> {
opctx.authorize(authz::Action::ListChildren, &authz::FLEET).await?;
use db::schema::sled::dsl;
paginated(dsl::sled, dsl::id, pagparams)
.select(Sled::as_select())
.sled_filter(sled_filter)
.load_async(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))
}
/// List all sleds, making as many queries as needed to get them all
///
/// This should generally not be used in API handlers or other
/// latency-sensitive contexts, but it can make sense in saga actions or
/// background tasks.
pub async fn sled_list_all_batched(
&self,
opctx: &OpContext,
sled_filter: SledFilter,
) -> ListResultVec<Sled> {
opctx.authorize(authz::Action::ListChildren, &authz::FLEET).await?;
opctx.check_complex_operations_allowed()?;
let mut all_sleds = Vec::new();
let mut paginator = Paginator::new(SQL_BATCH_SIZE);
while let Some(p) = paginator.next() {
let batch = self
.sled_list(opctx, &p.current_pagparams(), sled_filter)
.await?;
paginator =
p.found_batch(&batch, &|s: &nexus_db_model::Sled| s.id());
all_sleds.extend(batch);
}
Ok(all_sleds)
}
pub async fn sled_reservation_create(
&self,
opctx: &OpContext,
instance_id: InstanceUuid,
propolis_id: PropolisUuid,
resources: db::model::Resources,
constraints: db::model::SledReservationConstraints,
) -> CreateResult<db::model::SledResourceVmm> {
self.sled_reservation_create_inner(
opctx,
instance_id,
propolis_id,
resources,
constraints,
)
.await
.map_err(|e| match e {
SledReservationTransactionError::Connection(e) => e,
SledReservationTransactionError::Diesel(e) => {
public_error_from_diesel(e, ErrorHandler::Server)
}
SledReservationTransactionError::Reservation(e) => e.into(),
})
}
async fn sled_reservation_create_inner(
&self,
opctx: &OpContext,
instance_id: InstanceUuid,
propolis_id: PropolisUuid,
resources: db::model::Resources,
constraints: db::model::SledReservationConstraints,
) -> Result<db::model::SledResourceVmm, SledReservationTransactionError>
{
let conn = self.pool_connection_authorized(opctx).await?;
// Check if resource ID already exists - if so, return it.
//
// This check makes this function idempotent. Beyond this point, however
// we rely on primary key constraints in the database to prevent
// concurrent reservations for same propolis_id.
use db::schema::sled_resource_vmm::dsl as resource_dsl;
let old_resource = resource_dsl::sled_resource_vmm
.filter(resource_dsl::id.eq(*propolis_id.as_untyped_uuid()))
.select(SledResourceVmm::as_select())
.limit(1)
.load_async(&*conn)
.await?;
if !old_resource.is_empty() {
return Ok(old_resource[0].clone());
}
let must_use_sleds: HashSet<SledUuid> = constraints
.must_select_from()
.into_iter()
.flatten()
.map(|id| SledUuid::from_untyped_uuid(*id))
.collect();
// Query for the set of possible sleds using a CTE.
//
// Note that this is not transactional, to reduce contention.
// However, that lack of transactionality means we need to validate
// our constraints again when we later try to INSERT the reservation.
let possible_sleds = sled_find_targets_query(instance_id, &resources)
.get_results_async::<(
// Sled UUID
Uuid,
// Would an allocation to this sled fit?
bool,
// Affinity policy on this sled
Option<AffinityPolicy>,
// Anti-affinity policy on this sled
Option<AffinityPolicy>,
)>(&*conn).await?;
// Translate the database results into a format which we can use to pick
// a sled using more complex rules.
//
// See: `pick_sled_reservation_target(...)`
let mut sled_targets = HashSet::new();
let mut banned = HashSet::new();
let mut unpreferred = HashSet::new();
let mut required = HashSet::new();
let mut preferred = HashSet::new();
for (sled_id, fits, affinity_policy, anti_affinity_policy) in
possible_sleds
{
let sled_id = SledUuid::from_untyped_uuid(sled_id);
if fits
&& (must_use_sleds.is_empty()
|| must_use_sleds.contains(&sled_id))
{
sled_targets.insert(sled_id);
}
if let Some(policy) = affinity_policy {
match policy {
AffinityPolicy::Fail => required.insert(sled_id),
AffinityPolicy::Allow => preferred.insert(sled_id),
};
}
if let Some(policy) = anti_affinity_policy {
match policy {
AffinityPolicy::Fail => banned.insert(sled_id),
AffinityPolicy::Allow => unpreferred.insert(sled_id),
};
}
}
// We loop here because our attempts to INSERT may be violated by
// concurrent operations. We'll respond by looking through a slightly
// smaller set of possible sleds.
//
// In the uncontended case, however, we'll only iterate through this
// loop once.
loop {
// Pick a reservation target, given the constraints we previously
// saw in the database.
let sled_target = pick_sled_reservation_target(
&opctx.log,
&sled_targets,
&banned,
&unpreferred,
&required,
&preferred,
)?;
// Create a SledResourceVmm record, associate it with the target
// sled.
let resource = SledResourceVmm::new(
propolis_id,
instance_id,
sled_target,
resources.clone(),
);
// Try to INSERT the record. If this is still a valid target, we'll
// use it. If it isn't a valid target, we'll shrink the set of
// viable sled targets and try again.
let rows_inserted = sled_insert_resource_query(&resource)
.execute_async(&*conn)
.await?;
if rows_inserted > 0 {
return Ok(resource);
}
sled_targets.remove(&sled_target);
banned.remove(&sled_target);
unpreferred.remove(&sled_target);
preferred.remove(&sled_target);
}
}
pub async fn sled_reservation_delete(
&self,
opctx: &OpContext,
vmm_id: PropolisUuid,
) -> DeleteResult {
use db::schema::sled_resource_vmm::dsl as resource_dsl;
diesel::delete(resource_dsl::sled_resource_vmm)
.filter(resource_dsl::id.eq(vmm_id.into_untyped_uuid()))
.execute_async(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?;
Ok(())
}
/// Sets the provision policy for this sled.
///
/// Errors if the sled is not in service.
///
/// Returns the previous policy.
pub async fn sled_set_provision_policy(
&self,
opctx: &OpContext,
authz_sled: &authz::Sled,
policy: SledProvisionPolicy,
) -> Result<SledProvisionPolicy, external::Error> {
match self
.sled_set_policy_impl(
opctx,
authz_sled,
SledPolicy::InService { provision_policy: policy },
ValidateTransition::Yes,
)
.await
{
Ok(old_policy) => Ok(old_policy
.provision_policy()
.expect("only valid policy was in-service")),
Err(error) => Err(error.into_external_error()),
}
}
/// Marks a sled as expunged, as directed by the operator.
///
/// This is an irreversible process! It should only be called after
/// sufficient warning to the operator.
///
/// This is idempotent, and it returns the old policy of the sled.
///
/// Calling this function also implicitly marks the disks attached to a sled
/// as "expunged".
pub async fn sled_set_policy_to_expunged(
&self,
opctx: &OpContext,
authz_sled: &authz::Sled,
) -> Result<SledPolicy, external::Error> {
self.sled_set_policy_impl(
opctx,
authz_sled,
SledPolicy::Expunged,
ValidateTransition::Yes,
)
.await
.map_err(|error| error.into_external_error())
}
pub(super) async fn sled_set_policy_impl(
&self,
opctx: &OpContext,
authz_sled: &authz::Sled,
new_sled_policy: SledPolicy,
check: ValidateTransition,
) -> Result<SledPolicy, TransitionError> {
opctx.authorize(authz::Action::Modify, authz_sled).await?;
let sled_id = authz_sled.id();
let err = OptionalError::new();
let conn = self.pool_connection_authorized(opctx).await?;
let policy = self
.transaction_retry_wrapper("sled_set_policy")
.transaction(&conn, |conn| {
let err = err.clone();
async move {
let t = SledTransition::Policy(new_sled_policy);
let valid_old_policies = t.valid_old_policies();
let valid_old_states = t.valid_old_states();
use db::schema::sled::dsl;
let query = diesel::update(dsl::sled)
.filter(dsl::time_deleted.is_null())
.filter(dsl::id.eq(sled_id));
let query = match check {
ValidateTransition::Yes => query
.filter(
dsl::sled_policy.eq_any(
valid_old_policies
.into_iter()
.map(to_db_sled_policy),
),
)
.filter(
dsl::sled_state
.eq_any(valid_old_states.iter().copied()),
)
.into_boxed(),
#[cfg(test)]
ValidateTransition::No => query.into_boxed(),
};
let query = query
.set((
dsl::sled_policy
.eq(to_db_sled_policy(new_sled_policy)),
dsl::time_modified.eq(Utc::now()),
))
.check_if_exists::<Sled>(sled_id);
let result = query.execute_and_check(&conn).await?;
let old_policy = match (check, result.status) {
(ValidateTransition::Yes, UpdateStatus::Updated) => {
result.found.policy()
}
(
ValidateTransition::Yes,
UpdateStatus::NotUpdatedButExists,
) => {
// Two reasons this can happen:
// 1. An idempotent update: this is treated as a
// success.
// 2. Invalid state transition: a failure.
//
// To differentiate between the two, check that the
// new policy is the same as the old policy, and
// that the old state is valid.
if result.found.policy() == new_sled_policy
&& valid_old_states
.contains(&result.found.state())
{
result.found.policy()
} else {
return Err(err.bail(
TransitionError::InvalidTransition {
current: result.found,
transition: SledTransition::Policy(
new_sled_policy,
),
},
));
}
}
#[cfg(test)]
(ValidateTransition::No, _) => result.found.policy(),
};
// When a sled is expunged, the associated disks with that
// sled should also be implicitly set to expunged.
let new_disk_policy = match new_sled_policy {
SledPolicy::InService { .. } => None,
SledPolicy::Expunged => {
Some(nexus_db_model::PhysicalDiskPolicy::Expunged)
}
};
if let Some(new_disk_policy) = new_disk_policy {
use db::schema::physical_disk::dsl as physical_disk_dsl;
diesel::update(physical_disk_dsl::physical_disk)
.filter(physical_disk_dsl::time_deleted.is_null())
.filter(physical_disk_dsl::sled_id.eq(sled_id))
.set(
physical_disk_dsl::disk_policy
.eq(new_disk_policy),
)
.execute_async(&conn)
.await?;
}
Ok(old_policy)
}
})
.await
.map_err(|e| {
if let Some(err) = err.take() {
return err;
}
TransitionError::from(public_error_from_diesel(
e,
ErrorHandler::Server,
))
})?;
Ok(policy)
}
/// Marks the state of the sled as decommissioned, as believed by Nexus.
///
/// This is an irreversible process! It should only be called after all
/// resources previously on the sled have been migrated over.
///
/// This is idempotent, and it returns the old state of the sled.
///
/// # Errors
///
/// This method returns an error if the sled policy is not a state that is
/// valid to decommission from (i.e. if [`SledPolicy::is_decommissionable`]
/// returns `false`).
pub async fn sled_set_state_to_decommissioned(
&self,
opctx: &OpContext,
authz_sled: &authz::Sled,
) -> Result<SledState, TransitionError> {
self.sled_set_state_impl(
opctx,
authz_sled,
SledState::Decommissioned,
ValidateTransition::Yes,
)
.await
}
pub(super) async fn sled_set_state_impl(
&self,
opctx: &OpContext,
authz_sled: &authz::Sled,
new_sled_state: SledState,
check: ValidateTransition,
) -> Result<SledState, TransitionError> {
use db::schema::sled::dsl;
opctx.authorize(authz::Action::Modify, authz_sled).await?;
let sled_id = authz_sled.id();
let err = OptionalError::new();
let conn = self.pool_connection_authorized(opctx).await?;
let old_state = self
.transaction_retry_wrapper("sled_set_state")
.transaction(&conn, |conn| {
let err = err.clone();
async move {
let query = diesel::update(dsl::sled)
.filter(dsl::time_deleted.is_null())
.filter(dsl::id.eq(sled_id));
let t = SledTransition::State(new_sled_state);
let valid_old_policies = t.valid_old_policies();
let valid_old_states = t.valid_old_states();
let query = match check {
ValidateTransition::Yes => query
.filter(
dsl::sled_policy.eq_any(
valid_old_policies
.iter()
.copied()
.map(to_db_sled_policy),
),
)
.filter(dsl::sled_state.eq_any(valid_old_states))
.into_boxed(),
#[cfg(test)]
ValidateTransition::No => query.into_boxed(),
};
let query = query
.set((
dsl::sled_state.eq(new_sled_state),
dsl::time_modified.eq(Utc::now()),
))
.check_if_exists::<Sled>(sled_id);
let result = query.execute_and_check(&conn).await?;
let old_state = match (check, result.status) {
(ValidateTransition::Yes, UpdateStatus::Updated) => {
result.found.state()
}
(
ValidateTransition::Yes,
UpdateStatus::NotUpdatedButExists,
) => {
// Two reasons this can happen:
// 1. An idempotent update: this is treated as a
// success.
// 2. Invalid state transition: a failure.
//
// To differentiate between the two, check that the
// new state is the same as the old state, and the
// found policy is valid.
if result.found.state() == new_sled_state
&& valid_old_policies
.contains(&result.found.policy())
{
result.found.state()
} else {
return Err(err.bail(
TransitionError::InvalidTransition {
current: result.found,
transition: SledTransition::State(
new_sled_state,
),
},
));
}
}
#[cfg(test)]
(ValidateTransition::No, _) => result.found.state(),
};
// When a sled is decommissioned, the associated disks with
// that sled should also be implicitly set to
// decommissioned.
//
// We use an explicit `match` to force ourselves to consider
// disk state if we add any addition sled states in the
// future.
let new_disk_state = match new_sled_state {
SledState::Active => None,
SledState::Decommissioned => Some(
nexus_db_model::PhysicalDiskState::Decommissioned,
),
};
if let Some(new_disk_state) = new_disk_state {
use db::schema::physical_disk::dsl as physical_disk_dsl;
diesel::update(physical_disk_dsl::physical_disk)
.filter(physical_disk_dsl::time_deleted.is_null())
.filter(physical_disk_dsl::sled_id.eq(sled_id))
.set(
physical_disk_dsl::disk_state
.eq(new_disk_state),
)
.execute_async(&conn)
.await?;
}
Ok(old_state)
}
})
.await
.map_err(|e| {
if let Some(err) = err.take() {
return err;
}
TransitionError::from(public_error_from_diesel(
e,
ErrorHandler::Server,
))
})?;
Ok(old_state)
}
}
// ---
// State transition validators
// ---
// The functions in this section return the old policies or states that are
// valid for a new policy or state, except idempotent transitions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SledTransition {
Policy(SledPolicy),
State(SledState),
}
impl SledTransition {
/// Returns the list of valid old policies, other than the provided one
/// (which is always considered valid).
///
/// For a more descriptive listing of valid transitions, see
/// `test_sled_transitions`.
fn valid_old_policies(&self) -> Vec<SledPolicy> {
use SledPolicy::*;
use SledProvisionPolicy::*;
use SledState::*;
match self {
SledTransition::Policy(new_policy) => match new_policy {
InService { provision_policy: Provisionable } => {
vec![InService { provision_policy: NonProvisionable }]
}
InService { provision_policy: NonProvisionable } => {
vec![InService { provision_policy: Provisionable }]
}
Expunged => SledProvisionPolicy::iter()
.map(|provision_policy| InService { provision_policy })
.collect(),
},
SledTransition::State(state) => {
match state {
Active => {
// Any policy is valid for the active state.
SledPolicy::iter().collect()
}
Decommissioned => {
SledPolicy::all_decommissionable().to_vec()
}
}
}
}
}
/// Returns the list of valid old states, other than the provided one
/// (which is always considered valid).
///
/// For a more descriptive listing of valid transitions, see
/// `test_sled_transitions`.
fn valid_old_states(&self) -> Vec<SledState> {
use SledState::*;
match self {
SledTransition::Policy(_) => {
// Policies can only be transitioned in the active state. (In
// the future, this will include other non-decommissioned
// states.)
vec![Active]
}
SledTransition::State(state) => match state {
Active => vec![],
Decommissioned => vec![Active],
},
}
}
}
impl fmt::Display for SledTransition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SledTransition::Policy(policy) => {
write!(f, "policy \"{}\"", policy)
}
SledTransition::State(state) => write!(f, "state \"{}\"", state),