-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathupdate.rs
More file actions
2443 lines (2263 loc) · 86.9 KB
/
Copy pathupdate.rs
File metadata and controls
2443 lines (2263 loc) · 86.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Software Updates
use super::deployment::BlueprintTargetReleaseStatus;
use crate::app::background::LoadedTargetBlueprint;
use bytes::Bytes;
use chrono::DateTime;
use chrono::TimeDelta;
use chrono::Utc;
use display_error_chain::DisplayErrorChain;
use dropshot::HttpError;
use futures::Stream;
use illumos_utils::zone::PROPOLIS_ZONE_PREFIX;
use nexus_auth::authz;
use nexus_db_lookup::LookupPath;
use nexus_db_model::Generation;
use nexus_db_model::TufRepoUpload;
use nexus_db_model::TufTrustRoot;
use nexus_db_model::saga_types::Saga;
use nexus_db_model::saga_types::SagaId;
use nexus_db_queries::context::OpContext;
use nexus_db_queries::db::{datastore::SQL_BATCH_SIZE, pagination::Paginator};
use nexus_types::deployment::Blueprint;
use nexus_types::deployment::SledFilter;
use nexus_types::deployment::TargetReleaseDescription;
use nexus_types::external_api::update;
use nexus_types::external_api::update::TufSignedRootRole;
use nexus_types::identity::Asset;
use nexus_types::internal_api::views as internal_views;
use nexus_types::inventory::Collection;
use nexus_types::inventory::Zpool;
use nexus_types::tuf_repo::TufRepoDescription;
use omicron_common::api::external::InternalContext;
use omicron_common::api::external::Nullable;
use omicron_common::api::external::{DataPageParams, Error};
use omicron_uuid_kinds::{GenericUuid, SledUuid, TufTrustRootUuid};
use semver::Version;
use sled_agent_types::inventory::SvcsEnabledNotOnlineResult;
use sled_hardware_types::BaseboardId;
use slog::KV;
use slog::Record;
use slog::Serializer;
use slog::info;
use slog::warn;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::error::Error as _;
use std::iter;
use std::sync::Arc;
use tokio::sync::watch;
use tufaceous::ExpirationEnforcement;
use tufaceous::RepositoryLoader;
use tufaceous_artifact::ArtifactHash;
use uuid::Uuid;
/// Threshold at which we consider an active saga stuck.
///
/// Sagas can sometimes spend time being unassigned or recovered across Nexus
/// restarts. To calculate this threshold we took a sample of 10,000 sagas and
/// only 3 took longer than 15 minutes from time_created to done (1h32m, 34m24s
/// and 19m23s). Since sagas running longer than 15 minutes are so rare in
/// practice, we use that as the threshold. Anything older is much more likely
/// stuck than legitimately still in progress.
// TODO-K: Remove in https://github.com/oxidecomputer/omicron/issues/10538
#[cfg(test)]
const STUCK_SAGA_THRESHOLD: TimeDelta = TimeDelta::minutes(15);
/// Threshold at which we consider an inventory collection too old for the
/// purpose of reporting system health via the update status endpoint
///
/// During an update, inventories are collected pretty frequently (around
/// once a minute or more).
const STALE_INVENTORY_THRESHOLD: TimeDelta = TimeDelta::minutes(20);
/// Threshold at which we consider the update status's last step planned to be
/// within the boundaries of an update in progress.
///
/// This is chosen to be large enough to cover any update-related step (e.g.,
/// sled reboot) under normal conditions. Host OS updates can take a very long
/// time, usually around 10 minutes. Using `omdb reconfigurator history` we
/// took a sample of 1000 events and the longest interval between steps during
/// an update was ~13 minutes between 2 sled host OS updates. We give ourselves
/// a bit more time than that before considering an update stuck.
const STUCK_UPDATE_THRESHOLD: TimeDelta = TimeDelta::minutes(20);
/// Used to pull data out of the channels
#[derive(Clone)]
pub struct UpdateStatusHandle {
latest_blueprint: watch::Receiver<Option<LoadedTargetBlueprint>>,
}
impl UpdateStatusHandle {
pub fn new(
latest_blueprint: watch::Receiver<Option<LoadedTargetBlueprint>>,
) -> Self {
Self { latest_blueprint }
}
}
/// Inputs used to decide, based on health checks of a subset of system
/// components, whether the user should contact support before or after an
/// update.
struct UpdateContactSupportChecksInput {
inventory: Arc<Collection>,
stuck_sagas: Result<Vec<Saga>, Error>,
blueprint: Arc<Blueprint>,
// None when no target release has ever been set on the system.
current_target_version: Option<Version>,
internal_update_status: internal_views::UpdateStatus,
}
impl UpdateContactSupportChecksInput {
/// Identify a set of problems present in the system based on a series of
/// health checks.
fn problems(&self) -> UpdateStatusProblems {
let stuck_update_last_blueprint_created_time =
match UpdateActivityState::new(
&self.blueprint,
self.current_target_version.as_ref(),
) {
UpdateActivityState::Stuck => Some(self.blueprint.time_created),
UpdateActivityState::Idle | UpdateActivityState::InProgress => {
None
}
};
let missing_sleds: BTreeSet<SledUuid> = self
.internal_update_status
.sleds
.iter()
.filter(|sled| {
// `unknown()` returns the representation of the update status
// for a given sled ID that isn't present in inventory or hasn't
// reported a reconciliation result yet.
**sled
== internal_views::SledAgentUpdateStatus::unknown(
sled.sled_id,
)
})
.map(|sled| sled.sled_id)
.collect();
let (stuck_sagas, stuck_sagas_error_message) = match &self.stuck_sagas {
Ok(sagas) => (
sagas
.iter()
.map(|s| StuckSaga { id: s.id, name: s.name.clone() })
.collect(),
None,
),
Err(e) => (BTreeSet::new(), Some(e.to_string())),
};
let stale_inventory_last_collection_time_done = if self
.inventory
.time_done
< Utc::now() - STALE_INVENTORY_THRESHOLD
{
Some(self.inventory.time_done)
} else {
None
};
let unhealthy_zpools_by_sled = self
.inventory
.unhealthy_zpools()
.into_iter()
.map(|(sled, zpools)| (sled, zpools.into_iter().cloned().collect()))
.collect();
let enabled_smf_services_not_online_by_sled = self
.inventory
.enabled_smf_services_not_online()
.into_iter()
.filter_map(|(sled, svcs_result)| {
let mut svcs_result = svcs_result.clone();
match &mut svcs_result {
SvcsEnabledNotOnlineResult::SvcsEnabledNotOnline(svcs) => {
// Propolis zones are continuously torn down depending
// on the VMM state. When one of these zones is being
// torn down, it can cause false-positives with the
// contact_support field. In addition, offline services
// in these zones do not affect an update. We remove all
// services from propolis zones from the problems list.
svcs.services
.retain(|svc| !is_propolis_zone(&svc.zone));
// If there are no services or errors left then we drop
// the sled entirely.
if svcs.is_empty() {
None
} else {
Some((sled, svcs_result))
}
}
// Command errors and unavailable data aren't
// propolis-specific, so they're always retained.
SvcsEnabledNotOnlineResult::DataUnavailable
| SvcsEnabledNotOnlineResult::SvcsCmdError(_) => {
Some((sled, svcs_result))
}
}
})
.collect();
UpdateStatusProblems {
stuck_sagas,
stuck_sagas_error_message,
stuck_update_last_blueprint_created_time,
stale_inventory_last_collection_time_done,
unhealthy_zpools_by_sled,
enabled_smf_services_not_online_by_sled,
missing_sleds,
}
}
}
// String matching here because it is the most straightforward way to check
// if a zone is a propolis zone or not. This way of identifying a zone is not
// ideal but in this case it makes sense. This `contact_support` field will only
// be in use until a proper FM implementation is in place. The only consequence
// of this pattern matching failing (e.g. the propolis zone prefix changes and
// is also no longer set by this constant) would be that the contact_support
// field reports a false positive, but would have no further impact than that.
//
// This function should not be used for anything other than filtering propolis
// zones out of the `enabled_smf_services_not_online_by_sled` field
fn is_propolis_zone(zone: &str) -> bool {
zone.starts_with(PROPOLIS_ZONE_PREFIX)
}
/// Identifies a saga that has been running or unwinding for too long.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct StuckSaga {
id: SagaId,
name: String,
}
/// Problems identified by update health checks.
#[derive(Debug, Default, PartialEq, Eq)]
struct UpdateStatusProblems {
/// Sagas that have been running or unwinding longer than
/// `STUCK_SAGA_THRESHOLD`.
stuck_sagas: BTreeSet<StuckSaga>,
/// Error message if the query for stuck sagas itself failed.
stuck_sagas_error_message: Option<String>,
/// The time the last blueprint was created if an update is in progress, and
/// the last blueprint created is older than `STUCK_UPDATE_THRESHOLD`.
stuck_update_last_blueprint_created_time: Option<DateTime<Utc>>,
/// The time the last collection was finished if the latest inventory
/// collection is older than `STALE_INVENTORY_THRESHOLD`.
stale_inventory_last_collection_time_done: Option<DateTime<Utc>>,
/// Zpools that are not in an `Online` state.
unhealthy_zpools_by_sled: BTreeMap<SledUuid, Vec<Zpool>>,
/// Enabled SMF services that are not in an `online` state.
enabled_smf_services_not_online_by_sled:
BTreeMap<SledUuid, SvcsEnabledNotOnlineResult>,
/// IDs of sleds that aren't present in inventory or haven't reported a
/// reconciliation result yet.
missing_sleds: BTreeSet<SledUuid>,
}
impl UpdateStatusProblems {
fn is_empty(&self) -> bool {
let Self {
stuck_sagas,
stuck_sagas_error_message,
stuck_update_last_blueprint_created_time,
stale_inventory_last_collection_time_done,
unhealthy_zpools_by_sled,
enabled_smf_services_not_online_by_sled,
missing_sleds,
} = self;
stuck_sagas.is_empty()
&& stuck_sagas_error_message.is_none()
&& stuck_update_last_blueprint_created_time.is_none()
&& stale_inventory_last_collection_time_done.is_none()
&& unhealthy_zpools_by_sled.is_empty()
&& enabled_smf_services_not_online_by_sled.is_empty()
&& missing_sleds.is_empty()
}
}
impl KV for UpdateStatusProblems {
// We keep this custome serialisation as using slog-derive would print out
// every item always, we only want to log fields that contain problems.
fn serialize(
&self,
_record: &Record,
serializer: &mut dyn Serializer,
) -> slog::Result {
let Self {
stuck_sagas,
stuck_sagas_error_message,
stuck_update_last_blueprint_created_time,
stale_inventory_last_collection_time_done,
unhealthy_zpools_by_sled,
enabled_smf_services_not_online_by_sled,
missing_sleds,
} = self;
if !stuck_sagas.is_empty() {
serializer.emit_arguments(
"stuck_sagas".into(),
&format_args!("{:?}", stuck_sagas),
)?;
}
if let Some(error) = &stuck_sagas_error_message {
serializer.emit_arguments(
"stuck_sagas_error_message".into(),
&format_args!("{error}"),
)?;
}
if let Some(time_last_blueprint_created) =
&stuck_update_last_blueprint_created_time
{
serializer.emit_arguments(
"stuck_update_last_blueprint_created_time".into(),
&format_args!("{time_last_blueprint_created}"),
)?;
}
if let Some(collection_time_done) =
&stale_inventory_last_collection_time_done
{
serializer.emit_arguments(
"stale_inventory_last_collection_time_done".into(),
&format_args!("{collection_time_done}"),
)?;
}
if !unhealthy_zpools_by_sled.is_empty() {
serializer.emit_arguments(
"unhealthy_zpools_by_sled".into(),
&format_args!("{:?}", unhealthy_zpools_by_sled),
)?;
}
if !enabled_smf_services_not_online_by_sled.is_empty() {
serializer.emit_arguments(
"enabled_smf_services_not_online_by_sled".into(),
&format_args!("{:?}", enabled_smf_services_not_online_by_sled),
)?;
}
if !missing_sleds.is_empty() {
serializer.emit_arguments(
"missing_sleds".into(),
&format_args!("{:?}", missing_sleds),
)?;
}
Ok(())
}
}
/// Returns true if the system appears to be mid-update.
///
/// If no target release has ever been set, the system has only ever been
/// mupdated and is not mid-update.
///
/// Otherwise, a system is considered mid-update when the current target
/// blueprint shows a previous update is still in progress (relative to
/// `current_target_version`). This catches the window between a new target
/// release being set and any components actually moving to that version, where
/// every component is still on the prior version.
fn is_update_in_progress(
blueprint: &Blueprint,
current_target_version: Option<&Version>,
) -> bool {
// `BlueprintTargetReleaseStatus::new` does not check Hubris components,
// but for the sake of what we need here are not be fully necessary.
//
// `BlueprintTargetReleaseStatus::new` will report that the update is in
// progress until all zones and OS images are on the current version. We
// don't update them until after all the Hubris components have completed
// their updates, so if we were to get stuck while still updating Hubris
// components, the check below will sitll be sufficient.
let blueprint_in_progress = match current_target_version {
Some(v) => match BlueprintTargetReleaseStatus::new(blueprint, v) {
BlueprintTargetReleaseStatus::FoundDifferentVersion { .. } => true,
// We don't consider a Mupdate as an "update in-progress" because
// recofigurator is not driving this update.
BlueprintTargetReleaseStatus::WaitingForMupdateToBeCleared {
..
}
| BlueprintTargetReleaseStatus::AllComponentsMatchTargetRelease => {
false
}
},
// When `current_target_version` is `None` no target release has ever
// been set. We can safely assume no update is in progress.
None => false,
};
blueprint_in_progress
}
#[derive(Clone, Debug)]
enum UpdateActivityState {
Idle,
InProgress,
Stuck,
}
impl UpdateActivityState {
fn new(
blueprint: &Blueprint,
current_target_version: Option<&Version>,
) -> Self {
// First, we determine if an update is not in progress.
if !is_update_in_progress(blueprint, current_target_version) {
return UpdateActivityState::Idle;
}
// An update is considered "stuck" if it is in progress but the last
// created blueprint is older than `STUCK_UPDATE_THRESHOLD`.
if blueprint.time_created < Utc::now() - STUCK_UPDATE_THRESHOLD {
UpdateActivityState::Stuck
} else {
UpdateActivityState::InProgress
}
}
}
impl super::Nexus {
pub(crate) async fn updates_put_repository(
&self,
opctx: &OpContext,
body: impl Stream<Item = Result<Bytes, HttpError>> + Send + Sync + 'static,
file_name: String,
) -> Result<TufRepoUpload, HttpError> {
let mut loader = RepositoryLoader::new();
let mut paginator = Paginator::new(
SQL_BATCH_SIZE,
dropshot::PaginationOrder::Ascending,
);
while let Some(p) = paginator.next() {
let batch = self
.db_datastore
.tuf_trust_root_list(opctx, &p.current_pagparams())
.await?;
paginator = p.found_batch(&batch, &|a| a.id.into_untyped_uuid());
for root in batch {
loader = loader.trust_root(root.root_role.0.to_bytes());
}
}
let repo = loader
.compute_archive_sha256(true)
// Expiration enforcement is disabled for uploaded repos; see
// RFD 721.
.expiration_enforcement(ExpirationEnforcement::Unsafe)
.v1_compatibility(true)
.load_zip_stream(body, None, &self.log)
.await
.map_err(|err| {
// Downcast to an underlying `dropshot::HttpError` if possible.
if let Some(source) = err.source()
&& let Some(err) = source.downcast_ref::<HttpError>()
{
// manual Clone::clone
HttpError {
status_code: err.status_code,
error_code: err.error_code.clone(),
external_message: err.external_message.clone(),
internal_message: err.internal_message.clone(),
headers: err.headers.clone(),
}
} else {
let message = DisplayErrorChain::new(&err).to_string();
if err.is_repository_error() {
// Error is due to bad repository contents.
HttpError::for_bad_request(None, message)
} else {
// Error is likely due to something else.
HttpError::for_unavail(None, message)
}
}
})?;
// Now store the artifacts in the database.
let description = TufRepoDescription {
artifacts: repo.artifacts().clone(),
metadata: repo.metadata().clone(),
system_version: repo.system_version().clone(),
hash: ArtifactHash(*repo.archive_sha256().ok_or_else(|| {
HttpError::for_unavail(
None,
"tufaceous should have calculated repo hash but didn't"
.to_owned(),
)
})?),
file_name,
};
let response = self
.db_datastore
.tuf_repo_insert(opctx, &description)
.await
.map_err(HttpError::from)?;
// Move the `tufaceous::Repository` (which carries with it the temporary
// file storing the artifacts) into the artifact replication background
// task, then immediately activate the task. (If this repo was already
// uploaded, the artifacts should immediately be dropped by the task.)
self.tuf_artifact_replication_tx.send(repo).await.map_err(|err| {
// This error can only happen while Nexus's Tokio runtime is
// shutting down; Sender::send returns an error only if the
// receiver has hung up, and the receiver should live for
// as long as Nexus does (it belongs to the background task
// driver.)
//
// In the unlikely event that it does happen within this narrow
// window, the impact is that the database has recorded a
// repository for which we no longer have the artifacts. The fix
// would be to reupload the repository.
Error::internal_error(&format!(
"failed to send artifacts for replication: {err}"
))
})?;
self.background_tasks.task_tuf_artifact_replication.activate();
Ok(response)
}
pub(crate) async fn updates_get_repository(
&self,
opctx: &OpContext,
system_version: Version,
) -> Result<nexus_db_model::TufRepo, Error> {
self.db_datastore
.tuf_repo_get_by_version(opctx, system_version.into())
.await
}
pub(crate) async fn updates_list_repositories(
&self,
opctx: &OpContext,
pagparams: &DataPageParams<'_, Version>,
) -> Result<Vec<nexus_db_model::TufRepo>, Error> {
self.db_datastore.tuf_repo_list(opctx, pagparams).await
}
pub(crate) async fn updates_add_trust_root(
&self,
opctx: &OpContext,
trust_root: TufSignedRootRole,
) -> Result<TufTrustRoot, HttpError> {
self.db_datastore
.tuf_trust_root_insert(opctx, TufTrustRoot::new(trust_root))
.await
.map_err(HttpError::from)
}
pub(crate) async fn updates_get_trust_root(
&self,
opctx: &OpContext,
id: TufTrustRootUuid,
) -> Result<TufTrustRoot, HttpError> {
let (.., trust_root) = LookupPath::new(opctx, &self.db_datastore)
.tuf_trust_root(id)
.fetch()
.await?;
Ok(trust_root)
}
pub(crate) async fn updates_list_trust_roots(
&self,
opctx: &OpContext,
pagparams: &DataPageParams<'_, Uuid>,
) -> Result<Vec<TufTrustRoot>, HttpError> {
self.db_datastore
.tuf_trust_root_list(opctx, pagparams)
.await
.map_err(HttpError::from)
}
pub(crate) async fn updates_delete_trust_root(
&self,
opctx: &OpContext,
id: TufTrustRootUuid,
) -> Result<(), HttpError> {
let (authz, ..) = LookupPath::new(opctx, &self.db_datastore)
.tuf_trust_root(id)
.fetch_for(authz::Action::Delete)
.await?;
self.db_datastore
.tuf_trust_root_delete(opctx, &authz)
.await
.map_err(HttpError::from)
}
/// Get external update status with aggregated component counts
pub async fn update_status_external(
&self,
opctx: &OpContext,
) -> Result<update::UpdateStatus, Error> {
let db_target_release =
self.datastore().target_release_get_current(opctx).await?;
let current_tuf_repo = match db_target_release.tuf_repo_id {
Some(tuf_repo_id) => Some(
self.datastore()
.tuf_repo_get_by_id(opctx, tuf_repo_id.into())
.await?,
),
None => None,
};
let target_release =
current_tuf_repo.as_ref().map(|repo| update::TargetRelease {
time_requested: db_target_release.time_requested,
version: repo.repo.system_version.0.clone(),
});
let Some(inventory) =
self.inventory_load_rx().borrow_and_update().clone()
else {
return Err(Error::internal_error("No inventory collection found"));
};
let internal_status = self
.get_internal_update_status(
opctx,
&db_target_release,
current_tuf_repo,
&inventory,
)
.await?;
let components_by_release_version =
component_version_counts(&internal_status).await?;
let blueprint_target = self
.update_status
.latest_blueprint
.borrow()
.clone() // drop read lock held by outstanding borrow
.ok_or_else(|| {
Error::internal_error(
"Tried to get update status before \
target blueprint is loaded",
)
})?;
let time_last_step_planned = blueprint_target.target.time_made_target;
// Update activity is suspended if the current target release generation
// is less than the blueprint's minimum generation
let suspended = *db_target_release.generation
< blueprint_target.blueprint.target_release_minimum_generation;
// Decide whether to surface a "contact support" signal based on health
// checks against a subset of components in the system
let contact_support = self
.contact_support(
opctx,
inventory,
Arc::clone(&blueprint_target.blueprint),
target_release.as_ref().map(|t| &t.version),
internal_status,
)
.await?;
Ok(update::UpdateStatus {
target_release: Nullable(target_release),
components_by_release_version,
time_last_step_planned,
suspended,
contact_support,
})
}
/// Identify known reasons why we would want a customer to call support
/// before starting an upgrade or if an upgrade just finished. This is not
/// an exhaustive health check. Long term, this will be replaced by an
/// "active problems" facility driven by the Fault Management system. For
/// now, we look for this list of known, serious problems:
///
/// - No sagas have been running for longer than an hour.
/// - An inventory collection exists
/// - No update is in progress, or an update is in progress and the last
/// blueprint created is not older than the value of
/// STUCK_UPDATE_THRESHOLD.
/// - All zpools are online.
/// - All enabled SMF services are in an online state.
/// - All expacted sleds are present.
async fn contact_support(
&self,
opctx: &OpContext,
inventory: Arc<Collection>,
blueprint: Arc<Blueprint>,
current_target_version: Option<&Version>,
internal_update_status: internal_views::UpdateStatus,
) -> Result<bool, Error> {
// If an update is in progress but not stuck, the remaining checks
// could fail mid-update and shouldn't trigger a contact-support
// signal.
match UpdateActivityState::new(&blueprint, current_target_version) {
UpdateActivityState::InProgress => {
info!(
opctx.log,
"skipping update health checks; update in progress with last \
blueprint created within the last {}",
omicron_common::format_time_delta(STUCK_UPDATE_THRESHOLD);
);
return Ok(false);
}
UpdateActivityState::Idle | UpdateActivityState::Stuck => {}
};
let checks = UpdateContactSupportChecksInput {
inventory,
// TODO-K: Temporarily disabling the retrieval of stuck sagas.
// In https://github.com/oxidecomputer/omicron/issues/10531 we found
// some old unwinding sagas that didn't really affect the update
// process in any way. The actual new retrieval method will be in
// https://github.com/oxidecomputer/omicron/issues/10538, but to
// make sure we don't block the upcoming release, we are disabling
// saga reporting for now.
stuck_sagas: Ok(vec![]),
blueprint,
current_target_version: current_target_version.cloned(),
internal_update_status,
};
let problems = checks.problems();
let contact_support = !problems.is_empty();
if contact_support {
warn!(
opctx.log,
"found problems in the system before or after an update";
problems
);
}
Ok(contact_support)
}
async fn get_internal_update_status(
&self,
opctx: &OpContext,
target_release: &nexus_db_model::TargetRelease,
current_tuf_repo: Option<nexus_db_model::TufRepoDescription>,
inventory: &Arc<Collection>,
) -> Result<internal_views::UpdateStatus, Error> {
// Build current TargetReleaseDescription, defaulting to Initial if
// there is no tuf repo ID which, based on DB constraints, happens if
// and only if target_release_source is 'unspecified', which should only
// happen in the initial state before any target release has been set
let curr_target_desc = match current_tuf_repo {
Some(repo) => TargetReleaseDescription::TufRepo(repo.into()),
None => TargetReleaseDescription::Initial,
};
// Get previous target release (if it exists). Build the "prev"
// TargetReleaseDescription from the previous generation if available,
// otherwise fall back to Initial.
let prev_repo_id =
if let Some(prev_gen) = target_release.generation.prev() {
self.datastore()
.target_release_get_generation(opctx, Generation(prev_gen))
.await
.internal_context("fetching previous target release")?
.and_then(|r| r.tuf_repo_id)
} else {
None
};
// It should never happen that a target release other than the initial
// one with target_release_source unspecified should be missing a
// tuf_repo_id. So if we have a tuf_repo_id for the previous target
// release, we should always have one for the current target.
if prev_repo_id.is_some() && target_release.tuf_repo_id.is_none() {
return Err(Error::internal_error(
"Target release has no tuf repo but previous release has one",
));
}
let prev_target_desc = match prev_repo_id {
Some(id) => TargetReleaseDescription::TufRepo(
self.datastore()
.tuf_repo_get_by_id(opctx, id.into())
.await?
.into(),
),
None => TargetReleaseDescription::Initial,
};
// Get the list of sleds that should be reported as a part of the update
// status. (In particular, this allows us to filter out sleds that are
// physically present but not part of the cluster, as well as add
// "unknown" counts for sleds that ought to be present but aren't.)
let expected_sleds = self
.datastore()
.sled_list_all_batched(
opctx,
SledFilter::SpsUpdatedByReconfigurator,
)
.await?
.iter()
.map(|sled| {
(
BaseboardId {
part_number: sled.part_number().to_string(),
serial_number: sled.serial_number().to_string(),
},
sled.id(),
)
})
.collect();
// It's weird to use the internal view this way. It would feel more
// correct to extract shared logic and call it in both places. On the
// other hand, that sharing would be boilerplatey and not add much yet.
// So for now, use the internal view, but plan to extract shared logic
// or do our own thing here once things settle.
let status = internal_views::UpdateStatus::new(
&prev_target_desc,
&curr_target_desc,
&expected_sleds,
&inventory,
);
Ok(status)
}
}
/// Build a map of version strings to the number of components on that
/// version
async fn component_version_counts(
status: &internal_views::UpdateStatus,
) -> Result<BTreeMap<String, usize>, Error> {
let sled_versions = status.sleds.iter().flat_map(|sled| {
let zone_versions = sled.zones.iter().map(|zone| zone.version.clone());
// boot_disk tells you which slot is relevant
let host_version = sled.host_phase_2.boot_disk_version();
zone_versions.chain(iter::once(host_version))
});
let mgs_driven_versions = status.mgs_driven.iter().flat_map(|status| {
// for the SP, slot0_version is the active one
let sp_version = status.sp.slot0_version.clone();
// for the bootloader, stage0_version is the active one.
let bootloader_version = status.rot_bootloader.stage0_version.clone();
// for the RoT, get the version of the active slot.
let rot_version = status.rot.active_slot_version();
// This is an SP; it will only have a host OS phase 1 if it's a
// sled (and not a switch / PSC). If it does, we have to check
// the version of the active slot.
let host_version = status.host_os_phase_1.active_slot_version();
iter::once(sp_version)
.chain(iter::once(rot_version))
.chain(iter::once(bootloader_version))
.chain(host_version)
});
let mut counts = BTreeMap::new();
for version in sled_versions.chain(mgs_driven_versions) {
// Don't use `version.to_string()` here because that will report
// specific errors; instead, flatten all errors to just "error".
// It's fine to use `.to_string()` for the non-error variants.
let version = match version {
internal_views::TufRepoVersion::Unknown
| internal_views::TufRepoVersion::InstallDataset
| internal_views::TufRepoVersion::Version(_) => version.to_string(),
internal_views::TufRepoVersion::Error(_) => "error".to_string(),
};
*counts.entry(version).or_insert(0) += 1;
}
Ok(counts)
}
#[cfg(test)]
mod test {
use super::*;
use chrono::Utc;
use nexus_db_model::saga_types::Saga;
use nexus_db_model::saga_types::SecId;
use nexus_inventory::CollectionBuilder;
use nexus_reconfigurator_planning::example::example;
use nexus_test_utils_macros::nexus_test;
use nexus_types::deployment::BlueprintArtifactVersion;
use nexus_types::deployment::BlueprintHostPhase2DesiredContents;
use nexus_types::deployment::BlueprintHostPhase2DesiredSlots;
use nexus_types::deployment::BlueprintZoneImageSource;
use omicron_common::api::external::ByteCount;
use omicron_test_utils::dev::test_setup_log;
use omicron_uuid_kinds::PropolisUuid;
use omicron_uuid_kinds::SledUuid;
use omicron_uuid_kinds::ZpoolUuid;
use sled_agent_types::inventory::ConfigReconcilerInventoryStatus;
use sled_agent_types::inventory::FmdInventory;
use sled_agent_types::inventory::Inventory;
use sled_agent_types::inventory::InventoryZpool;
use sled_agent_types::inventory::OmicronFileSourceResolverInventory;
use sled_agent_types::inventory::SledCpuFamily;
use sled_agent_types::inventory::SledRole;
use sled_agent_types::inventory::SvcEnabledNotOnline;
use sled_agent_types::inventory::SvcEnabledNotOnlineState;
use sled_agent_types::inventory::SvcsEnabledNotOnline;
use sled_agent_types::inventory::SvcsEnabledNotOnlineResult;
use sled_agent_types::inventory::SvcsError;
use sled_agent_types::inventory::ZpoolHealth;
use slog::Logger;
use slog::o;
use tufaceous_artifact::ArtifactHash;
use tufaceous_artifact::ArtifactVersion;
use uuid::Uuid;
type ControlPlaneTestContext =
nexus_test_utils::ControlPlaneTestContext<crate::Server>;
fn fake_sled_inventory(
zpools: Vec<InventoryZpool>,
smf_services: SvcsEnabledNotOnlineResult,
) -> Inventory {
Inventory {
baseboard_id: BaseboardId {
part_number: "test-model".to_string(),
serial_number: "test-pc".to_string(),
},
reservoir_size: ByteCount::from(1024),
sled_role: SledRole::Gimlet,
sled_agent_address: "[::1]:56792".parse().unwrap(),
sled_id: SledUuid::new_v4(),
usable_hardware_threads: 10,
usable_physical_ram: ByteCount::from(1024 * 1024),
cpu_family: SledCpuFamily::AmdMilan,
disks: vec![],
zpools,
datasets: vec![],
ledgered_sled_config: None,
reconciler_status: ConfigReconcilerInventoryStatus::NotYetRun,
last_reconciliation: None,
file_source_resolver: OmicronFileSourceResolverInventory::new_fake(
),
smf_services_enabled_not_online: smf_services,
reference_measurements: iddqd::IdOrdMap::new(),
fmd: Ok(FmdInventory::default()),
}
}
fn healthy_zpools() -> Vec<InventoryZpool> {
vec![InventoryZpool {
id: ZpoolUuid::new_v4(),
total_size: ByteCount::from(1024 * 1024),
health: ZpoolHealth::Online,
}]
}
fn unhealthy_zpools() -> Vec<InventoryZpool> {
vec![
InventoryZpool {
id: ZpoolUuid::new_v4(),
total_size: ByteCount::from(1024 * 1024),
health: ZpoolHealth::Online,
},
InventoryZpool {
id: ZpoolUuid::new_v4(),
total_size: ByteCount::from(1024 * 1024),
health: ZpoolHealth::Degraded,
},
]
}
fn healthy_services() -> SvcsEnabledNotOnlineResult {
SvcsEnabledNotOnlineResult::SvcsEnabledNotOnline(SvcsEnabledNotOnline {
services: vec![],
errors: vec![],
time_of_status: Utc::now(),
})
}
fn unhealthy_services() -> SvcsEnabledNotOnlineResult {
SvcsEnabledNotOnlineResult::SvcsEnabledNotOnline(SvcsEnabledNotOnline {
services: vec![
SvcEnabledNotOnline {
fmri: "svc:/system/test:default".to_string(),
zone: "global".to_string(),
state: SvcEnabledNotOnlineState::Maintenance,
},
SvcEnabledNotOnline {
fmri: "svc:/system/test2:default".to_string(),
zone: "global".to_string(),
state: SvcEnabledNotOnlineState::Offline,
},
],
errors: vec![],
time_of_status: Utc::now(),
})
}
fn propolis_zone_name() -> String {
format!("{PROPOLIS_ZONE_PREFIX}{}", PropolisUuid::new_v4())
}