-
Notifications
You must be signed in to change notification settings - Fork 40
/
storage_manager.rs
1413 lines (1280 loc) · 48.8 KB
/
storage_manager.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/.
//! Management of sled-local storage.
use crate::nexus::LazyNexusClient;
use crate::params::DatasetKind;
use crate::profile::*;
use futures::stream::FuturesOrdered;
use futures::FutureExt;
use futures::StreamExt;
use illumos_utils::dladm::Etherstub;
use illumos_utils::link::VnicAllocator;
use illumos_utils::running_zone::{InstalledZone, RunningZone};
use illumos_utils::zone::AddressRequest;
use illumos_utils::zpool::{ZpoolKind, ZpoolName};
use illumos_utils::{zfs::Mountpoint, zone::ZONE_PREFIX, zpool::ZpoolInfo};
use nexus_client::types::PhysicalDiskDeleteRequest;
use nexus_client::types::PhysicalDiskKind;
use nexus_client::types::PhysicalDiskPutRequest;
use nexus_client::types::ZpoolPutRequest;
use omicron_common::api::external::{ByteCount, ByteCountRangeError};
use omicron_common::backoff;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sled_hardware::{Disk, DiskIdentity, DiskVariant, UnparsedDisk};
use slog::Logger;
use std::collections::hash_map;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::net::{IpAddr, Ipv6Addr, SocketAddrV6};
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use tokio::fs::{create_dir_all, File};
use tokio::io::AsyncWriteExt;
use tokio::sync::{mpsc, oneshot, Mutex};
use tokio::task::JoinHandle;
use uuid::Uuid;
#[cfg(test)]
use illumos_utils::{zfs::MockZfs as Zfs, zpool::MockZpool as Zpool};
#[cfg(not(test))]
use illumos_utils::{zfs::Zfs, zpool::Zpool};
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error(transparent)]
DiskError(#[from] sled_hardware::DiskError),
// TODO: We could add the context of "why are we doint this op", maybe?
#[error(transparent)]
ZfsListDataset(#[from] illumos_utils::zfs::ListDatasetsError),
#[error(transparent)]
ZfsEnsureFilesystem(#[from] illumos_utils::zfs::EnsureFilesystemError),
#[error(transparent)]
ZfsSetValue(#[from] illumos_utils::zfs::SetValueError),
#[error(transparent)]
ZfsGetValue(#[from] illumos_utils::zfs::GetValueError),
#[error(transparent)]
GetZpoolInfo(#[from] illumos_utils::zpool::GetInfoError),
#[error(transparent)]
Fstyp(#[from] illumos_utils::fstyp::Error),
#[error(transparent)]
ZoneCommand(#[from] illumos_utils::running_zone::RunCommandError),
#[error(transparent)]
ZoneBoot(#[from] illumos_utils::running_zone::BootError),
#[error(transparent)]
ZoneEnsureAddress(#[from] illumos_utils::running_zone::EnsureAddressError),
#[error(transparent)]
ZoneInstall(#[from] illumos_utils::running_zone::InstallZoneError),
#[error("No U.2 Zpools found")]
NoU2Zpool,
#[error("Failed to parse UUID from {path}: {err}")]
ParseUuid {
path: PathBuf,
#[source]
err: uuid::Error,
},
#[error("Error parsing pool {name}'s size: {err}")]
BadPoolSize {
name: String,
#[source]
err: ByteCountRangeError,
},
#[error("Failed to parse the dataset {name}'s UUID: {err}")]
ParseDatasetUuid {
name: String,
#[source]
err: uuid::Error,
},
#[error("Zpool Not Found: {0}")]
ZpoolNotFound(String),
#[error("Failed to serialize toml (intended for {path:?}): {err}")]
Serialize {
path: PathBuf,
#[source]
err: toml::ser::Error,
},
#[error("Failed to deserialize toml from {path:?}: {err}")]
Deserialize {
path: PathBuf,
#[source]
err: toml::de::Error,
},
#[error("Failed to perform I/O: {message}: {err}")]
Io {
message: String,
#[source]
err: std::io::Error,
},
#[error("Underlay not yet initialized")]
UnderlayNotInitialized,
}
impl Error {
fn io(message: &str, err: std::io::Error) -> Self {
Self::Io { message: message.to_string(), err }
}
}
/// A ZFS storage pool.
struct Pool {
name: ZpoolName,
info: ZpoolInfo,
// ZFS filesytem UUID -> Zone.
zones: HashMap<Uuid, RunningZone>,
parent: DiskIdentity,
}
impl Pool {
/// Queries for an existing Zpool by name.
///
/// Returns Ok if the pool exists.
fn new(name: ZpoolName, parent: DiskIdentity) -> Result<Pool, Error> {
let info = Zpool::get_info(&name.to_string())?;
Ok(Pool { name, info, zones: HashMap::new(), parent })
}
/// Associate an already running zone with this pool object.
///
/// Typically this is used when a dataset within the zone (identified
/// by ID) has a running zone (e.g. Crucible, Cockroach) operating on
/// behalf of that data.
fn add_zone(&mut self, id: Uuid, zone: RunningZone) {
self.zones.insert(id, zone);
}
/// Access a zone managing data within this pool.
fn get_zone(&self, id: Uuid) -> Option<&RunningZone> {
self.zones.get(&id)
}
/// Returns the ID of the pool itself.
fn id(&self) -> Uuid {
self.name.id()
}
fn parent(&self) -> &DiskIdentity {
&self.parent
}
/// Returns the path for the configuration of a particular
/// dataset within the pool. This configuration file provides
/// the necessary information for zones to "launch themselves"
/// after a reboot.
async fn dataset_config_path(
&self,
dataset_id: Uuid,
) -> Result<PathBuf, Error> {
let path = std::path::Path::new(omicron_common::OMICRON_CONFIG_PATH)
.join(self.id().to_string());
create_dir_all(&path).await.map_err(|err| Error::Io {
message: format!("creating config dir {path:?}, which would contain config for {dataset_id}"),
err,
})?;
let mut path = path.join(dataset_id.to_string());
path.set_extension("toml");
Ok(path)
}
}
#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
struct DatasetName {
// A unique identifier for the Zpool on which the dataset is stored.
pool_name: ZpoolName,
// A name for the dataset within the Zpool.
dataset_name: String,
}
impl DatasetName {
fn new(pool_name: ZpoolName, dataset_name: &str) -> Self {
Self { pool_name, dataset_name: dataset_name.to_string() }
}
fn full(&self) -> String {
format!("{}/{}", self.pool_name, self.dataset_name)
}
}
// Description of a dataset within a ZFS pool, which should be created
// by the Sled Agent.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
struct DatasetInfo {
address: SocketAddrV6,
kind: DatasetKind,
name: DatasetName,
}
impl DatasetInfo {
fn new(
pool: ZpoolName,
kind: DatasetKind,
address: SocketAddrV6,
) -> DatasetInfo {
match kind {
DatasetKind::CockroachDb { .. } => DatasetInfo {
name: DatasetName::new(pool, "cockroachdb"),
address,
kind,
},
DatasetKind::Clickhouse { .. } => DatasetInfo {
name: DatasetName::new(pool, "clickhouse"),
address,
kind,
},
DatasetKind::Crucible { .. } => DatasetInfo {
name: DatasetName::new(pool, "crucible"),
address,
kind,
},
}
}
fn zone_prefix(&self) -> String {
format!("{}{}_", ZONE_PREFIX, self.name.full())
}
}
// Ensures that a zone backing a particular dataset is running.
async fn ensure_running_zone(
log: &Logger,
vnic_allocator: &VnicAllocator<Etherstub>,
dataset_info: &DatasetInfo,
dataset_name: &DatasetName,
do_format: bool,
underlay_address: Ipv6Addr,
) -> Result<RunningZone, Error> {
let address_request = AddressRequest::new_static(
IpAddr::V6(*dataset_info.address.ip()),
None,
);
let err = RunningZone::get(
log,
&vnic_allocator,
&dataset_info.zone_prefix(),
address_request,
)
.await;
match err {
Ok(zone) => {
info!(log, "Zone for {} is already running", dataset_name.full());
return Ok(zone);
}
Err(illumos_utils::running_zone::GetZoneError::NotFound { .. }) => {
info!(log, "Zone for {} was not found", dataset_name.full());
let zone_root_path = dataset_name
.pool_name
.dataset_mountpoint(sled_hardware::disk::ZONE_DATASET);
info!(
log,
"Installing zone {} to {}",
dataset_name.full(),
zone_root_path.display()
);
let installed_zone = InstalledZone::install(
log,
vnic_allocator,
&zone_root_path,
&dataset_info.name.dataset_name,
Some(&dataset_name.pool_name.to_string()),
&[zone::Dataset { name: dataset_name.full() }],
&[],
&[],
vec![],
None,
vec![],
vec![],
)
.await?;
let datalink = installed_zone.get_control_vnic_name();
let gateway = &underlay_address.to_string();
let listen_addr = &dataset_info.address.ip().to_string();
let listen_port = &dataset_info.address.port().to_string();
let zone = match dataset_info.kind {
DatasetKind::CockroachDb { .. } => {
let config = PropertyGroupBuilder::new("config")
.add_property("datalink", "astring", datalink)
.add_property("gateway", "astring", gateway)
.add_property("listen_addr", "astring", listen_addr)
.add_property("listen_port", "astring", listen_port)
.add_property("store", "astring", "/data");
let profile = ProfileBuilder::new("omicron").add_service(
ServiceBuilder::new("oxide/cockroachdb").add_instance(
ServiceInstanceBuilder::new("default")
.add_property_group(config),
),
);
profile.add_to_zone(log, &installed_zone).await.map_err(
|err| Error::io("Failed to setup CRDB profile", err),
)?;
let zone = RunningZone::boot(installed_zone).await?;
// Await liveness of the cluster.
info!(log, "start_zone: awaiting liveness of CRDB");
let check_health = || async {
let http_addr = SocketAddrV6::new(
*dataset_info.address.ip(),
8080,
0,
0,
);
reqwest::get(format!(
"http://{}/health?ready=1",
http_addr
))
.await
.map_err(backoff::BackoffError::transient)
};
let log_failure = |_, call_count, total_duration| {
if call_count == 0 {
info!(log, "cockroachdb not yet alive");
} else if total_duration
> std::time::Duration::from_secs(5)
{
warn!(log, "cockroachdb not yet alive"; "total duration" => ?total_duration);
}
};
backoff::retry_notify_ext(
backoff::retry_policy_internal_service(),
check_health,
log_failure,
)
.await
.expect("expected an infinite retry loop waiting for crdb");
info!(log, "CRDB is online");
// If requested, format the cluster with the initial tables.
if do_format {
info!(log, "Formatting CRDB");
zone.run_cmd(&[
"/opt/oxide/cockroachdb/bin/cockroach",
"sql",
"--insecure",
"--host",
&dataset_info.address.to_string(),
"--file",
"/opt/oxide/cockroachdb/sql/dbwipe.sql",
])?;
zone.run_cmd(&[
"/opt/oxide/cockroachdb/bin/cockroach",
"sql",
"--insecure",
"--host",
&dataset_info.address.to_string(),
"--file",
"/opt/oxide/cockroachdb/sql/dbinit.sql",
])?;
info!(log, "Formatting CRDB - Completed");
}
zone
}
DatasetKind::Clickhouse { .. } => {
let config = PropertyGroupBuilder::new("config")
.add_property("datalink", "astring", datalink)
.add_property("gateway", "astring", gateway)
.add_property("listen_addr", "astring", listen_addr)
.add_property("listen_port", "astring", listen_port)
.add_property("store", "astring", "/data");
let profile = ProfileBuilder::new("omicron").add_service(
ServiceBuilder::new("oxide/clickhouse").add_instance(
ServiceInstanceBuilder::new("default")
.add_property_group(config),
),
);
profile.add_to_zone(log, &installed_zone).await.map_err(
|err| {
Error::io("Failed to setup clickhouse profile", err)
},
)?;
RunningZone::boot(installed_zone).await?
}
DatasetKind::Crucible => {
let dataset = &dataset_info.name.full();
let uuid = &Uuid::new_v4().to_string();
let config = PropertyGroupBuilder::new("config")
.add_property("datalink", "astring", datalink)
.add_property("gateway", "astring", gateway)
.add_property("dataset", "astring", dataset)
.add_property("listen_addr", "astring", listen_addr)
.add_property("listen_port", "astring", listen_port)
.add_property("uuid", "astring", uuid)
.add_property("store", "astring", "/data");
let profile = ProfileBuilder::new("omicron").add_service(
ServiceBuilder::new("oxide/crucible/agent")
.add_instance(
ServiceInstanceBuilder::new("default")
.add_property_group(config),
),
);
profile.add_to_zone(log, &installed_zone).await.map_err(
|err| {
Error::io("Failed to setup crucible profile", err)
},
)?;
RunningZone::boot(installed_zone).await?
}
};
Ok(zone)
}
Err(illumos_utils::running_zone::GetZoneError::NotRunning {
name,
state,
}) => {
// TODO(https://github.com/oxidecomputer/omicron/issues/725):
unimplemented!("Handle a zone which exists, but is not running: {name}, in {state:?}");
}
Err(err) => {
// TODO(https://github.com/oxidecomputer/omicron/issues/725):
unimplemented!(
"Handle a zone which exists, has some other problem: {err}"
);
}
}
}
// The type of a future which is used to send a notification to Nexus.
type NotifyFut =
Pin<Box<dyn futures::Future<Output = Result<(), String>> + Send>>;
#[derive(Debug)]
struct NewFilesystemRequest {
zpool_id: Uuid,
dataset_kind: DatasetKind,
address: SocketAddrV6,
responder: oneshot::Sender<Result<(), Error>>,
}
struct UnderlayRequest {
underlay: UnderlayAccess,
responder: oneshot::Sender<Result<(), Error>>,
}
#[derive(PartialEq, Eq, Clone)]
enum DiskWrapper {
Real { disk: Disk, devfs_path: PathBuf },
Synthetic { zpool_name: ZpoolName },
}
impl From<Disk> for DiskWrapper {
fn from(disk: Disk) -> Self {
let devfs_path = disk.devfs_path().clone();
Self::Real { disk, devfs_path }
}
}
impl DiskWrapper {
fn identity(&self) -> DiskIdentity {
match self {
DiskWrapper::Real { disk, .. } => disk.identity().clone(),
DiskWrapper::Synthetic { zpool_name } => {
let id = zpool_name.id();
DiskIdentity {
vendor: "synthetic-vendor".to_string(),
serial: format!("synthetic-serial-{id}"),
model: "synthetic-model".to_string(),
}
}
}
}
fn variant(&self) -> DiskVariant {
match self {
DiskWrapper::Real { disk, .. } => disk.variant(),
DiskWrapper::Synthetic { zpool_name } => match zpool_name.kind() {
ZpoolKind::External => DiskVariant::U2,
ZpoolKind::Internal => DiskVariant::M2,
},
}
}
fn zpool_name(&self) -> &ZpoolName {
match self {
DiskWrapper::Real { disk, .. } => disk.zpool_name(),
DiskWrapper::Synthetic { zpool_name } => zpool_name,
}
}
}
#[derive(Clone)]
pub struct StorageResources {
// All disks, real and synthetic, being managed by this sled
disks: Arc<Mutex<HashMap<DiskIdentity, DiskWrapper>>>,
// A map of "Uuid" to "pool".
pools: Arc<Mutex<HashMap<Uuid, Pool>>>,
}
impl StorageResources {
/// Returns all M.2 zpools
pub async fn all_m2_zpools(&self) -> Vec<ZpoolName> {
self.all_zpools(DiskVariant::M2).await
}
pub async fn all_zpools(&self, variant: DiskVariant) -> Vec<ZpoolName> {
let disks = self.disks.lock().await;
disks
.values()
.filter_map(|disk| {
if let DiskWrapper::Real { disk, .. } = disk {
if disk.variant() == variant {
return Some(disk.zpool_name().clone());
}
};
None
})
.collect()
}
}
/// Describes the access to the underlay used by the StorageManager.
pub struct UnderlayAccess {
pub lazy_nexus_client: LazyNexusClient,
pub underlay_address: Ipv6Addr,
pub sled_id: Uuid,
}
// A worker that starts zones for pools as they are received.
struct StorageWorker {
log: Logger,
nexus_notifications: FuturesOrdered<NotifyFut>,
rx: mpsc::Receiver<StorageWorkerRequest>,
vnic_allocator: VnicAllocator<Etherstub>,
underlay: Arc<Mutex<Option<UnderlayAccess>>>,
}
#[derive(Clone, Debug)]
enum NotifyDiskRequest {
Add { identity: DiskIdentity, variant: DiskVariant },
Remove(DiskIdentity),
}
impl StorageWorker {
// Ensures the named dataset exists as a filesystem with a UUID, optionally
// creating it if `do_format` is true.
//
// Returns the UUID attached to the ZFS filesystem.
fn ensure_dataset_with_id(
dataset_name: &DatasetName,
do_format: bool,
) -> Result<Uuid, Error> {
let zoned = true;
let fs_name = &dataset_name.full();
Zfs::ensure_filesystem(
&format!(
"{}/{}",
dataset_name.pool_name, dataset_name.dataset_name
),
Mountpoint::Path(PathBuf::from("/data")),
zoned,
do_format,
)?;
// Ensure the dataset has a usable UUID.
if let Ok(id_str) = Zfs::get_oxide_value(&fs_name, "uuid") {
if let Ok(id) = id_str.parse::<Uuid>() {
return Ok(id);
}
}
let id = Uuid::new_v4();
Zfs::set_oxide_value(&fs_name, "uuid", &id.to_string())?;
Ok(id)
}
// Starts the zone for a dataset within a particular zpool.
//
// If requested via the `do_format` parameter, may also initialize
// these resources.
//
// Returns the UUID attached to the underlying ZFS dataset.
// Returns (was_inserted, Uuid).
async fn initialize_dataset_and_zone(
&mut self,
pool: &mut Pool,
dataset_info: &DatasetInfo,
do_format: bool,
) -> Result<(bool, Uuid), Error> {
// Ensure the underlying dataset exists before trying to poke at zones.
let dataset_name = &dataset_info.name;
info!(&self.log, "Ensuring dataset {} exists", dataset_name.full());
let id =
StorageWorker::ensure_dataset_with_id(&dataset_name, do_format)?;
// If this zone has already been processed by us, return immediately.
if let Some(_) = pool.get_zone(id) {
return Ok((false, id));
}
// Otherwise, the zone may or may not exist.
// We need to either look up or create the zone.
info!(
&self.log,
"Ensuring zone for {} is running",
dataset_name.full()
);
let underlay_guard = self.underlay.lock().await;
let Some(underlay) = underlay_guard.as_ref() else {
return Err(Error::UnderlayNotInitialized);
};
let underlay_address = underlay.underlay_address;
drop(underlay_guard);
let zone = ensure_running_zone(
&self.log,
&self.vnic_allocator,
dataset_info,
&dataset_name,
do_format,
underlay_address,
)
.await?;
info!(
&self.log,
"Zone {} with address {} is running",
zone.name(),
dataset_info.address,
);
pool.add_zone(id, zone);
Ok((true, id))
}
// Adds a "notification to nexus" to `nexus_notifications`,
// informing it about the addition of `pool_id` to this sled.
fn add_zpool_notify(&mut self, pool: &Pool, size: ByteCount) {
let pool_id = pool.name.id();
let DiskIdentity { vendor, serial, model } = pool.parent.clone();
let underlay = self.underlay.clone();
let notify_nexus = move || {
let zpool_request = ZpoolPutRequest {
size: size.into(),
disk_vendor: vendor.clone(),
disk_serial: serial.clone(),
disk_model: model.clone(),
};
let underlay = underlay.clone();
async move {
let underlay_guard = underlay.lock().await;
let Some(underlay) = underlay_guard.as_ref() else {
return Err(backoff::BackoffError::transient(Error::UnderlayNotInitialized.to_string()));
};
let sled_id = underlay.sled_id;
let lazy_nexus_client = underlay.lazy_nexus_client.clone();
drop(underlay_guard);
lazy_nexus_client
.get()
.await
.map_err(|e| {
backoff::BackoffError::transient(e.to_string())
})?
.zpool_put(&sled_id, &pool_id, &zpool_request)
.await
.map_err(|e| {
backoff::BackoffError::transient(e.to_string())
})?;
Ok(())
}
};
let log = self.log.clone();
let name = pool.name.clone();
let disk = pool.parent().clone();
let log_post_failure = move |_, call_count, total_duration| {
if call_count == 0 {
info!(log, "failed to notify nexus about a new pool {name} on disk {disk:?}");
} else if total_duration > std::time::Duration::from_secs(30) {
warn!(log, "failed to notify nexus about a new pool {name} on disk {disk:?}";
"total duration" => ?total_duration);
}
};
self.nexus_notifications.push_back(
backoff::retry_notify_ext(
backoff::retry_policy_internal_service_aggressive(),
notify_nexus,
log_post_failure,
)
.boxed(),
);
}
async fn ensure_using_exactly_these_disks(
&mut self,
resources: &StorageResources,
unparsed_disks: Vec<UnparsedDisk>,
) -> Result<(), Error> {
let mut new_disks = HashMap::new();
// We may encounter errors while parsing any of the disks; keep track of
// any errors that occur and return any of them if something goes wrong.
//
// That being said, we should not prevent access to the other disks if
// only one failure occurs.
let mut err: Option<Error> = None;
// Ensure all disks conform to the expected partition layout.
for disk in unparsed_disks.into_iter() {
match sled_hardware::Disk::new(&self.log, disk).map_err(|err| {
warn!(self.log, "Could not ensure partitions: {err}");
err
}) {
Ok(disk) => {
new_disks.insert(disk.identity().clone(), disk);
}
Err(e) => {
warn!(self.log, "Cannot parse disk: {e}");
err = Some(e.into());
}
};
}
let mut disks = resources.disks.lock().await;
// Remove disks that don't appear in the "new_disks" set.
//
// This also accounts for zpools and notifies Nexus.
let disks_to_be_removed = disks
.iter_mut()
.filter(|(key, old_disk)| {
// If this disk appears in the "new" and "old" set, it should
// only be removed if it has changed.
//
// This treats a disk changing in an unexpected way as a
// "removal and re-insertion".
match old_disk {
DiskWrapper::Real { disk, .. } => {
if let Some(new_disk) = new_disks.get(*key) {
// Changed Disk -> Disk should be removed.
new_disk != disk
} else {
// Real disk, not in the new set -> Disk should be removed.
true
}
}
// Synthetic disk -> Disk should NOT be removed.
DiskWrapper::Synthetic { .. } => false,
}
})
.map(|(_key, disk)| disk.clone())
.collect::<Vec<_>>();
for disk in disks_to_be_removed {
if let Err(e) = self
.delete_disk_locked(&resources, &mut disks, &disk.identity())
.await
{
warn!(self.log, "Failed to delete disk: {e}");
err = Some(e);
}
}
// Add new disks to `resources.disks`.
//
// This also accounts for zpools and notifies Nexus.
for (key, new_disk) in new_disks {
if let Some(old_disk) = disks.get(&key) {
// In this case, the disk should be unchanged.
//
// This assertion should be upheld by the filter above, which
// should remove disks that changed.
assert!(old_disk == &new_disk.into());
} else {
let disk = DiskWrapper::Real {
disk: new_disk.clone(),
devfs_path: new_disk.devfs_path().clone(),
};
if let Err(e) =
self.upsert_disk_locked(&resources, &mut disks, disk).await
{
warn!(self.log, "Failed to upsert disk: {e}");
err = Some(e);
}
}
}
if let Some(err) = err {
Err(err)
} else {
Ok(())
}
}
async fn upsert_disk(
&mut self,
resources: &StorageResources,
disk: UnparsedDisk,
) -> Result<(), Error> {
info!(self.log, "Upserting disk: {disk:?}");
// Ensure the disk conforms to an expected partition layout.
let disk =
sled_hardware::Disk::new(&self.log, disk).map_err(|err| {
warn!(self.log, "Could not ensure partitions: {err}");
err
})?;
let mut disks = resources.disks.lock().await;
let disk = DiskWrapper::Real {
disk: disk.clone(),
devfs_path: disk.devfs_path().clone(),
};
self.upsert_disk_locked(resources, &mut disks, disk).await
}
async fn upsert_synthetic_disk(
&mut self,
resources: &StorageResources,
zpool_name: ZpoolName,
) -> Result<(), Error> {
info!(self.log, "Upserting synthetic disk for: {zpool_name:?}");
let mut disks = resources.disks.lock().await;
sled_hardware::Disk::ensure_zpool_ready(&self.log, &zpool_name)?;
let disk = DiskWrapper::Synthetic { zpool_name };
self.upsert_disk_locked(resources, &mut disks, disk).await
}
async fn upsert_disk_locked(
&mut self,
resources: &StorageResources,
disks: &mut tokio::sync::MutexGuard<
'_,
HashMap<DiskIdentity, DiskWrapper>,
>,
disk: DiskWrapper,
) -> Result<(), Error> {
disks.insert(disk.identity(), disk.clone());
self.physical_disk_notify(NotifyDiskRequest::Add {
identity: disk.identity(),
variant: disk.variant(),
});
self.upsert_zpool(&resources, disk.identity(), disk.zpool_name())
.await?;
Ok(())
}
async fn delete_disk(
&mut self,
resources: &StorageResources,
disk: UnparsedDisk,
) -> Result<(), Error> {
info!(self.log, "Deleting disk: {disk:?}");
// TODO: Don't we need to do some accounting, e.g. for all the information
// that's no longer accessible? Or is that up to Nexus to figure out at
// a later point-in-time?
//
// If we're storing zone images on the M.2s for internal services, how
// do we reconcile them?
let mut disks = resources.disks.lock().await;
self.delete_disk_locked(resources, &mut disks, disk.identity()).await
}
async fn delete_disk_locked(
&mut self,
resources: &StorageResources,
disks: &mut tokio::sync::MutexGuard<
'_,
HashMap<DiskIdentity, DiskWrapper>,
>,
key: &DiskIdentity,
) -> Result<(), Error> {
if let Some(parsed_disk) = disks.remove(key) {
resources.pools.lock().await.remove(&parsed_disk.zpool_name().id());
self.physical_disk_notify(NotifyDiskRequest::Remove(key.clone()));
}
Ok(())
}
// Adds a "notification to nexus" to `self.nexus_notifications`, informing it
// about the addition/removal of a physical disk to this sled.
fn physical_disk_notify(&mut self, disk: NotifyDiskRequest) {
let underlay = self.underlay.clone();
let disk2 = disk.clone();
let notify_nexus = move || {
let disk = disk.clone();
let underlay = underlay.clone();
async move {
let underlay_guard = underlay.lock().await;
let Some(underlay) = underlay_guard.as_ref() else {
return Err(backoff::BackoffError::transient(Error::UnderlayNotInitialized.to_string()));
};
let sled_id = underlay.sled_id;
let lazy_nexus_client = underlay.lazy_nexus_client.clone();
drop(underlay_guard);
let nexus = lazy_nexus_client.get().await.map_err(|e| {
backoff::BackoffError::transient(e.to_string())
})?;
match &disk {
NotifyDiskRequest::Add { identity, variant } => {
let request = PhysicalDiskPutRequest {
model: identity.model.clone(),
serial: identity.serial.clone(),
vendor: identity.vendor.clone(),
variant: match variant {
DiskVariant::U2 => PhysicalDiskKind::U2,
DiskVariant::M2 => PhysicalDiskKind::M2,
},
sled_id,
};
nexus.physical_disk_put(&request).await.map_err(
|e| backoff::BackoffError::transient(e.to_string()),
)?;
}
NotifyDiskRequest::Remove(disk_identity) => {
let request = PhysicalDiskDeleteRequest {
model: disk_identity.model.clone(),
serial: disk_identity.serial.clone(),
vendor: disk_identity.vendor.clone(),
sled_id,
};
nexus.physical_disk_delete(&request).await.map_err(
|e| backoff::BackoffError::transient(e.to_string()),
)?;
}
}
Ok(())
}
};
let log = self.log.clone();
// This notification is often invoked before Nexus has started
// running, so avoid flagging any errors as concerning until some
// time has passed.
let log_post_failure = move |_, call_count, total_duration| {
if call_count == 0 {
info!(log, "failed to notify nexus about {disk2:?}");
} else if total_duration > std::time::Duration::from_secs(30) {
warn!(log, "failed to notify nexus about {disk2:?}";
"total duration" => ?total_duration);
}
};
self.nexus_notifications.push_back(
backoff::retry_notify_ext(
backoff::retry_policy_internal_service_aggressive(),
notify_nexus,
log_post_failure,
)
.boxed(),
);
}
async fn upsert_zpool(
&mut self,
resources: &StorageResources,
parent: DiskIdentity,
pool_name: &ZpoolName,
) -> Result<(), Error> {
let mut pools = resources.pools.lock().await;
let zpool = Pool::new(pool_name.clone(), parent)?;
let pool = match pools.entry(pool_name.id()) {