-
Notifications
You must be signed in to change notification settings - Fork 35
/
sled.rs
1468 lines (1335 loc) · 53.7 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::Sled;
use crate::db::model::SledResource;
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::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 std::fmt;
use strum::IntoEnumIterator;
use thiserror::Error;
use uuid::Uuid;
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::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.
///
/// 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: Uuid,
) -> 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))
.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,
resource_id: Uuid,
resource_kind: db::model::SledResourceKind,
resources: db::model::Resources,
constraints: db::model::SledReservationConstraints,
) -> CreateResult<db::model::SledResource> {
#[derive(Debug)]
enum SledReservationError {
NotFound,
}
let err = OptionalError::new();
let conn = self.pool_connection_authorized(opctx).await?;
self.transaction_retry_wrapper("sled_reservation_create")
.transaction(&conn, |conn| {
// Clone variables into retryable function
let err = err.clone();
let constraints = constraints.clone();
let resources = resources.clone();
async move {
use db::schema::sled_resource::dsl as resource_dsl;
// Check if resource ID already exists - if so, return it.
let old_resource = resource_dsl::sled_resource
.filter(resource_dsl::id.eq(resource_id))
.select(SledResource::as_select())
.limit(1)
.load_async(&conn)
.await?;
if !old_resource.is_empty() {
return Ok(old_resource[0].clone());
}
// If it doesn't already exist, find a sled with enough space
// for the resources we're requesting.
use db::schema::sled::dsl as sled_dsl;
// This answers the boolean question:
// "Does the SUM of all hardware thread usage, plus the one we're trying
// to allocate, consume less threads than exists on the sled?"
let sled_has_space_for_threads =
(diesel::dsl::sql::<diesel::sql_types::BigInt>(
&format!(
"COALESCE(SUM(CAST({} as INT8)), 0)",
resource_dsl::hardware_threads::NAME
),
) + resources.hardware_threads)
.le(sled_dsl::usable_hardware_threads);
// This answers the boolean question:
// "Does the SUM of all RAM usage, plus the one we're trying
// to allocate, consume less RAM than exists on the sled?"
let sled_has_space_for_rss =
(diesel::dsl::sql::<diesel::sql_types::BigInt>(
&format!(
"COALESCE(SUM(CAST({} as INT8)), 0)",
resource_dsl::rss_ram::NAME
),
) + resources.rss_ram)
.le(sled_dsl::usable_physical_ram);
// Determine whether adding this service's reservoir allocation
// to what's allocated on the sled would avoid going over quota.
let sled_has_space_in_reservoir =
(diesel::dsl::sql::<diesel::sql_types::BigInt>(
&format!(
"COALESCE(SUM(CAST({} as INT8)), 0)",
resource_dsl::reservoir_ram::NAME
),
) + resources.reservoir_ram)
.le(sled_dsl::reservoir_size);
// Generate a query describing all of the sleds that have space
// for this reservation.
let mut sled_targets = sled_dsl::sled
.left_join(
resource_dsl::sled_resource
.on(resource_dsl::sled_id.eq(sled_dsl::id)),
)
.group_by(sled_dsl::id)
.having(
sled_has_space_for_threads
.and(sled_has_space_for_rss)
.and(sled_has_space_in_reservoir),
)
.filter(sled_dsl::time_deleted.is_null())
// Ensure that reservations can be created on the sled.
.sled_filter(SledFilter::ReservationCreate)
.select(sled_dsl::id)
.into_boxed();
// Further constrain the sled IDs according to any caller-
// supplied constraints.
if let Some(must_select_from) =
constraints.must_select_from()
{
sled_targets = sled_targets.filter(
sled_dsl::id.eq_any(must_select_from.to_vec()),
);
}
sql_function!(fn random() -> diesel::sql_types::Float);
// We only actually care about one target here, so this
// query should have a `.limit(1)` attached. We fetch all
// sled targets to leave additional debugging information in
// the logs, for now.
let sled_targets = sled_targets
.order(random())
.get_results_async::<Uuid>(&conn)
.await?;
info!(
opctx.log,
"found {} available sled targets", sled_targets.len();
"sled_ids" => ?sled_targets,
);
if sled_targets.is_empty() {
return Err(err.bail(SledReservationError::NotFound));
}
// Create a SledResource record, associate it with the target
// sled.
let resource = SledResource::new(
resource_id,
sled_targets[0],
resource_kind,
resources,
);
diesel::insert_into(resource_dsl::sled_resource)
.values(resource)
.returning(SledResource::as_returning())
.get_result_async(&conn)
.await
}
})
.await
.map_err(|e| {
if let Some(err) = err.take() {
match err {
SledReservationError::NotFound => {
return external::Error::insufficient_capacity(
"No sleds can fit the requested instance",
"No sled targets found that had enough \
capacity to fit the requested instance.",
);
}
}
}
public_error_from_diesel(e, ErrorHandler::Server)
})
}
pub async fn sled_reservation_delete(
&self,
opctx: &OpContext,
resource_id: Uuid,
) -> DeleteResult {
use db::schema::sled_resource::dsl as resource_dsl;
diesel::delete(resource_dsl::sled_resource)
.filter(resource_dsl::id.eq(resource_id))
.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, external::Error> {
self.sled_set_state_impl(
opctx,
authz_sled,
SledState::Decommissioned,
ValidateTransition::Yes,
)
.await
.map_err(|error| error.into_external_error())
}
pub(super) async fn sled_set_state_impl(
&self,
opctx: &OpContext,
authz_sled: &authz::Sled,
new_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 query = diesel::update(dsl::sled)
.filter(dsl::time_deleted.is_null())
.filter(dsl::id.eq(sled_id));
let t = SledTransition::State(new_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_state),
dsl::time_modified.eq(Utc::now()),
))
.check_if_exists::<Sled>(sled_id);
let result = query
.execute_and_check(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?;
match (check, result.status) {
(ValidateTransition::Yes, UpdateStatus::Updated) => {
Ok(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_state
&& valid_old_policies.contains(&result.found.policy())
{
Ok(result.found.state())
} else {
Err(TransitionError::InvalidTransition {
current: result.found,
transition: SledTransition::State(new_state),
})
}
}
#[cfg(test)]
(ValidateTransition::No, _) => Ok(result.found.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(super) 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),
}
}
}
impl IntoEnumIterator for SledTransition {
type Iterator = std::vec::IntoIter<Self>;
fn iter() -> Self::Iterator {
let v: Vec<_> = SledPolicy::iter()
.map(SledTransition::Policy)
.chain(SledState::iter().map(SledTransition::State))
.collect();
v.into_iter()
}
}
/// An error that occurred while setting a policy or state.
#[derive(Debug, Error)]
#[must_use]
pub(super) enum TransitionError {
/// The state transition check failed.
///
/// The sled is returned.
#[error(
"sled id {} has current policy \"{}\" and state \"{}\" \
and the transition to {} is not permitted",
.current.id(),
.current.policy(),
.current.state(),
.transition,
)]
InvalidTransition {
/// The current sled as fetched from the database.
current: Sled,
/// The new policy or state that was attempted.
transition: SledTransition,
},
/// Some other kind of error occurred.
#[error("database error")]
External(#[from] external::Error),
}
impl TransitionError {
fn into_external_error(self) -> external::Error {
match self {
TransitionError::InvalidTransition { .. } => {
external::Error::conflict(self.to_string())
}
TransitionError::External(e) => e.clone(),
}
}
#[cfg(test)]
pub(super) fn ensure_invalid_transition(self) -> anyhow::Result<()> {
match self {
TransitionError::InvalidTransition { .. } => Ok(()),
TransitionError::External(e) => Err(anyhow::anyhow!(e)
.context("expected invalid transition, got other error")),
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::db::datastore::test::{
sled_baseboard_for_test, sled_system_hardware_for_test,
};
use crate::db::datastore::test_utils::{
datastore_test, sled_set_policy, sled_set_state, Expected,
IneligibleSleds,
};
use crate::db::lookup::LookupPath;
use crate::db::model::ByteCount;
use crate::db::model::SqlU32;
use anyhow::{Context, Result};
use itertools::Itertools;
use nexus_db_model::Generation;
use nexus_db_model::PhysicalDisk;
use nexus_db_model::PhysicalDiskKind;
use nexus_db_model::PhysicalDiskPolicy;
use nexus_test_utils::db::test_setup_database;
use nexus_types::identity::Asset;
use omicron_common::api::external;
use omicron_test_utils::dev;
use omicron_uuid_kinds::GenericUuid;
use omicron_uuid_kinds::SledUuid;
use predicates::{prelude::*, BoxPredicate};
use std::net::{Ipv6Addr, SocketAddrV6};
fn rack_id() -> Uuid {
Uuid::parse_str(nexus_test_utils::RACK_UUID).unwrap()
}
#[tokio::test]
async fn upsert_sled_updates_hardware() {
let logctx = dev::test_setup_log("upsert_sled_updates_hardware");
let mut db = test_setup_database(&logctx.log).await;
let (_opctx, datastore) = datastore_test(&logctx, &db).await;
let mut sled_update = test_new_sled_update();
let (observed_sled, _) =
datastore.sled_upsert(sled_update.clone()).await.unwrap();
assert_eq!(
observed_sled.usable_hardware_threads,
sled_update.usable_hardware_threads
);
assert_eq!(
observed_sled.usable_physical_ram,
sled_update.usable_physical_ram
);
assert_eq!(observed_sled.reservoir_size, sled_update.reservoir_size);
// Modify the sizes of hardware
sled_update.usable_hardware_threads =
SqlU32::new(sled_update.usable_hardware_threads.0 + 1);
const MIB: u64 = 1024 * 1024;
sled_update.usable_physical_ram = ByteCount::from(
external::ByteCount::try_from(
sled_update.usable_physical_ram.0.to_bytes() + MIB,
)
.unwrap(),
);
sled_update.reservoir_size = ByteCount::from(
external::ByteCount::try_from(
sled_update.reservoir_size.0.to_bytes() + MIB,
)
.unwrap(),
);
// Bump the generation number so the insert succeeds.
sled_update.sled_agent_gen.0 = sled_update.sled_agent_gen.0.next();
// Test that upserting the sled propagates those changes to the DB.
let (observed_sled, _) = datastore
.sled_upsert(sled_update.clone())
.await
.expect("Could not upsert sled during test prep");
assert_eq!(
observed_sled.usable_hardware_threads,
sled_update.usable_hardware_threads
);
assert_eq!(
observed_sled.usable_physical_ram,
sled_update.usable_physical_ram
);
assert_eq!(observed_sled.reservoir_size, sled_update.reservoir_size);
db.cleanup().await.unwrap();
logctx.cleanup_successful();
}
#[tokio::test]
async fn upsert_sled_updates_fails_with_stale_sled_agent_gen() {
let logctx = dev::test_setup_log(
"upsert_sled_updates_fails_with_stale_sled_agent_gen",
);
let mut db = test_setup_database(&logctx.log).await;
let (_opctx, datastore) = datastore_test(&logctx, &db).await;
let mut sled_update = test_new_sled_update();
let (observed_sled, _) =
datastore.sled_upsert(sled_update.clone()).await.unwrap();
assert_eq!(observed_sled.reservoir_size, sled_update.reservoir_size);
// Modify the reservoir size
const MIB: u64 = 1024 * 1024;
sled_update.reservoir_size = ByteCount::from(
external::ByteCount::try_from(
sled_update.reservoir_size.0.to_bytes() + MIB,
)
.unwrap(),
);
// Fail the update, since the generation number didn't change.
assert!(datastore.sled_upsert(sled_update.clone()).await.is_err());
// Bump the generation number so the next insert succeeds.
sled_update.sled_agent_gen.0 = sled_update.sled_agent_gen.0.next();
// Test that upserting the sled propagates those changes to the DB.
let (observed_sled, _) = datastore
.sled_upsert(sled_update.clone())
.await
.expect("Could not upsert sled during test prep");
assert_eq!(observed_sled.reservoir_size, sled_update.reservoir_size);
// Now reset the generation to a lower value and try again.
// This should fail.
let current_gen = sled_update.sled_agent_gen;
sled_update.sled_agent_gen = Generation::new();
assert!(datastore.sled_upsert(sled_update.clone()).await.is_err());
// Now bump the generation from the saved `current_gen`
// Change the reservoir value again. This should succeed.
sled_update.reservoir_size = ByteCount::from(
external::ByteCount::try_from(
sled_update.reservoir_size.0.to_bytes() + MIB,
)
.unwrap(),
);
sled_update.sled_agent_gen.0 = current_gen.0.next();
// Test that upserting the sled propagates those changes to the DB.
let (observed_sled, _) = datastore
.sled_upsert(sled_update.clone())
.await
.expect("Could not upsert sled during test prep");
assert_eq!(observed_sled.reservoir_size, sled_update.reservoir_size);
assert_eq!(observed_sled.sled_agent_gen, sled_update.sled_agent_gen);
db.cleanup().await.unwrap();
logctx.cleanup_successful();
}
#[tokio::test]
async fn upsert_sled_doesnt_update_decommissioned() {
let logctx =
dev::test_setup_log("upsert_sled_doesnt_update_decommissioned");
let mut db = test_setup_database(&logctx.log).await;
let (opctx, datastore) = datastore_test(&logctx, &db).await;
let mut sled_update = test_new_sled_update();
let (observed_sled, _) =
datastore.sled_upsert(sled_update.clone()).await.unwrap();
assert_eq!(
observed_sled.usable_hardware_threads,
sled_update.usable_hardware_threads
);
assert_eq!(
observed_sled.usable_physical_ram,
sled_update.usable_physical_ram
);
assert_eq!(observed_sled.reservoir_size, sled_update.reservoir_size);
// Set the sled to decommissioned (this is not a legal transition, but
// we don't care about sled policy in sled_upsert, just the state.)
sled_set_state(
&opctx,
&datastore,
SledUuid::from_untyped_uuid(observed_sled.id()),
SledState::Decommissioned,
ValidateTransition::No,
Expected::Ok(SledState::Active),
)
.await
.unwrap();
// Modify the sizes of hardware
sled_update.usable_hardware_threads =
SqlU32::new(sled_update.usable_hardware_threads.0 + 1);
const MIB: u64 = 1024 * 1024;
sled_update.usable_physical_ram = ByteCount::from(
external::ByteCount::try_from(
sled_update.usable_physical_ram.0.to_bytes() + MIB,
)
.unwrap(),
);
sled_update.reservoir_size = ByteCount::from(
external::ByteCount::try_from(
sled_update.reservoir_size.0.to_bytes() + MIB,
)
.unwrap(),
);
// Upserting the sled should produce an error, because it is decommissioend.
assert!(datastore.sled_upsert(sled_update.clone()).await.is_err());
// The sled should not have been updated.
let (_, observed_sled_2) = LookupPath::new(&opctx, &datastore)
.sled_id(observed_sled.id())
.fetch_for(authz::Action::Modify)
.await
.unwrap();
assert_eq!(
observed_sled_2.usable_hardware_threads,
observed_sled.usable_hardware_threads,
"usable_hardware_threads should not have changed"
);
assert_eq!(
observed_sled_2.usable_physical_ram,
observed_sled.usable_physical_ram,
"usable_physical_ram should not have changed"
);
assert_eq!(
observed_sled_2.reservoir_size, observed_sled.reservoir_size,
"reservoir_size should not have changed"
);
db.cleanup().await.unwrap();
logctx.cleanup_successful();
}
/// Test that new reservations aren't created on non-provisionable sleds.
#[tokio::test]
async fn sled_reservation_create_non_provisionable() {
let logctx =
dev::test_setup_log("sled_reservation_create_non_provisionable");
let mut db = test_setup_database(&logctx.log).await;
let (opctx, datastore) = datastore_test(&logctx, &db).await;