-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathdisk.rs
More file actions
540 lines (480 loc) · 12.7 KB
/
Copy pathdisk.rs
File metadata and controls
540 lines (480 loc) · 12.7 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
// 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/.
//! Disk related types shared among crates
use anyhow::bail;
use camino::{Utf8Path, Utf8PathBuf};
use daft::Diffable;
use iddqd::IdOrdItem;
use iddqd::id_upcast;
use omicron_uuid_kinds::DatasetUuid;
use omicron_uuid_kinds::PhysicalDiskUuid;
use omicron_uuid_kinds::ZpoolUuid;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
use crate::api::internal::shared::DatasetKindParseError;
use crate::{
api::external::ByteCount,
zpool_name::{ZpoolKind, ZpoolName},
};
pub use crate::api::internal::shared::DatasetKind;
#[derive(
Clone,
Debug,
Deserialize,
Serialize,
JsonSchema,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
)]
pub struct OmicronPhysicalDiskConfig {
pub identity: DiskIdentity,
pub id: PhysicalDiskUuid,
pub pool_id: ZpoolUuid,
}
impl IdOrdItem for OmicronPhysicalDiskConfig {
type Key<'a> = PhysicalDiskUuid;
fn key(&self) -> Self::Key<'_> {
self.id
}
id_upcast!();
}
#[derive(
Debug,
PartialEq,
Eq,
Hash,
Serialize,
Deserialize,
Clone,
JsonSchema,
PartialOrd,
Ord,
)]
pub 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.
kind: DatasetKind,
}
impl DatasetName {
pub fn new(pool_name: ZpoolName, kind: DatasetKind) -> Self {
Self { pool_name, kind }
}
pub fn into_parts(self) -> (ZpoolName, DatasetKind) {
(self.pool_name, self.kind)
}
pub fn pool(&self) -> &ZpoolName {
&self.pool_name
}
pub fn kind(&self) -> &DatasetKind {
&self.kind
}
/// Returns the full name of the dataset, as would be returned from
/// "zfs get" or "zfs list".
///
/// If this dataset should be encrypted, this automatically adds the
/// "crypt" dataset component.
pub fn full_name(&self) -> String {
// Currently, we encrypt all datasets except Crucible.
//
// Crucible already performs encryption internally, and we
// avoid double-encryption.
if self.kind.dataset_should_be_encrypted() {
self.full_encrypted_name()
} else {
self.full_unencrypted_name()
}
}
/// Returns the mountpoint of the dataset.
///
/// If this dataset is delegated to a non-global zone, returns "/data".
///
/// If this dataset is intended for the global zone and should be encrypted,
/// this automatically adds the "crypt" dataset component.
pub fn mountpoint(&self, root: &Utf8Path) -> Utf8PathBuf {
if self.kind.zoned() {
Utf8PathBuf::from("/data")
} else {
self.pool_name.dataset_mountpoint(
root,
&if self.kind.dataset_should_be_encrypted() {
format!("crypt/{}", self.kind)
} else {
self.kind.to_string()
},
)
}
}
fn full_encrypted_name(&self) -> String {
format!("{}/crypt/{}", self.pool_name, self.kind)
}
fn full_unencrypted_name(&self) -> String {
format!("{}/{}", self.pool_name, self.kind)
}
}
#[derive(Debug, thiserror::Error)]
pub enum DatasetNameParseError {
#[error("missing '/' separator in dataset name {0}")]
MissingSlash(String),
#[error("could not parse zpool name {zpool}: {err}")]
ParseZpoolName { zpool: String, err: String },
#[error("could not parse dataset kind {kind}")]
ParseDatasetKind {
kind: String,
#[source]
err: DatasetKindParseError,
},
#[error("expected `crypt/` for kind {kind:?} in dataset name {name}")]
MissingCryptInName { kind: DatasetKind, name: String },
#[error("unexpected `crypt/` for kind {kind:?} in dataset name {name}")]
UnexpectedCryptInName { kind: DatasetKind, name: String },
}
impl FromStr for DatasetName {
type Err = DatasetNameParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (pool_name, remainder) = s.split_once('/').ok_or_else(|| {
DatasetNameParseError::MissingSlash(s.to_string())
})?;
let pool_name = ZpoolName::from_str(pool_name).map_err(|err| {
DatasetNameParseError::ParseZpoolName {
zpool: pool_name.to_string(),
err,
}
})?;
let (kind_str, name_has_crypt) =
if let Some(remainder) = remainder.strip_prefix("crypt/") {
(remainder, true)
} else {
(remainder, false)
};
let kind = DatasetKind::from_str(kind_str).map_err(|err| {
DatasetNameParseError::ParseDatasetKind {
kind: kind_str.to_string(),
err,
}
})?;
match (kind.dataset_should_be_encrypted(), name_has_crypt) {
(true, true) | (false, false) => Ok(Self { pool_name, kind }),
(true, false) => Err(DatasetNameParseError::MissingCryptInName {
kind,
name: s.to_string(),
}),
(false, true) => {
Err(DatasetNameParseError::UnexpectedCryptInName {
kind,
name: s.to_string(),
})
}
}
}
}
#[derive(
Copy,
Clone,
Debug,
Deserialize,
Serialize,
JsonSchema,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
Diffable,
)]
pub struct GzipLevel(u8);
// Fastest compression level
const GZIP_LEVEL_MIN: u8 = 1;
// Best compression ratio
const GZIP_LEVEL_MAX: u8 = 9;
impl GzipLevel {
pub const fn new<const N: u8>() -> Self {
assert!(N >= GZIP_LEVEL_MIN, "Compression level too small");
assert!(N <= GZIP_LEVEL_MAX, "Compression level too large");
Self(N)
}
}
impl FromStr for GzipLevel {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let level = s.parse::<u8>()?;
if level < GZIP_LEVEL_MIN || level > GZIP_LEVEL_MAX {
bail!("Invalid gzip compression level: {level}");
}
Ok(Self(level))
}
}
#[derive(
Copy,
Clone,
Debug,
Default,
Deserialize,
Serialize,
JsonSchema,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
Diffable,
)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum CompressionAlgorithm {
// Selects a default compression algorithm. This is dependent on both the
// zpool and OS version.
On,
// Disables compression.
#[default]
Off,
// Selects the default Gzip compression level.
//
// According to the ZFS docs, this is "gzip-6", but that's a default value,
// which may change with OS updates.
Gzip,
GzipN {
level: GzipLevel,
},
Lz4,
Lzjb,
Zle,
}
/// These match the arguments which can be passed to "zfs set compression=..."
impl fmt::Display for CompressionAlgorithm {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use CompressionAlgorithm::*;
let s = match self {
On => "on",
Off => "off",
Gzip => "gzip",
GzipN { level } => {
return write!(f, "gzip-{}", level.0);
}
Lz4 => "lz4",
Lzjb => "lzjb",
Zle => "zle",
};
write!(f, "{}", s)
}
}
impl FromStr for CompressionAlgorithm {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use CompressionAlgorithm::*;
let c = match s {
"on" => On,
"" | "off" => Off,
"gzip" => Gzip,
"lz4" => Lz4,
"lzjb" => Lzjb,
"zle" => Zle,
_ => {
let Some(suffix) = s.strip_prefix("gzip-") else {
bail!("Unknown compression algorithm {s}");
};
GzipN { level: suffix.parse()? }
}
};
Ok(c)
}
}
/// Shared configuration information to request a dataset.
#[derive(
Clone,
Debug,
Default,
Deserialize,
Serialize,
JsonSchema,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
)]
pub struct SharedDatasetConfig {
/// The compression mode to be used by the dataset
pub compression: CompressionAlgorithm,
/// The upper bound on the amount of storage used by this dataset
pub quota: Option<ByteCount>,
/// The lower bound on the amount of storage usable by this dataset
pub reservation: Option<ByteCount>,
}
/// Configuration information necessary to request a single dataset.
///
/// These datasets are tracked directly by Nexus.
#[derive(
Clone,
Debug,
Deserialize,
Serialize,
JsonSchema,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
)]
pub struct DatasetConfig {
/// The UUID of the dataset being requested
pub id: DatasetUuid,
/// The dataset's name
pub name: DatasetName,
#[serde(flatten)]
pub inner: SharedDatasetConfig,
}
impl IdOrdItem for DatasetConfig {
type Key<'a> = DatasetUuid;
fn key(&self) -> Self::Key<'_> {
self.id
}
id_upcast!();
}
/// Uniquely identifies a disk.
#[derive(
Debug,
Clone,
PartialEq,
Eq,
Hash,
Ord,
PartialOrd,
Serialize,
Deserialize,
JsonSchema,
Diffable,
)]
pub struct DiskIdentity {
pub vendor: String,
pub model: String,
pub serial: String,
}
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Hash,
Serialize,
Deserialize,
JsonSchema,
Ord,
PartialOrd,
)]
pub enum DiskVariant {
U2,
M2,
}
impl From<ZpoolKind> for DiskVariant {
fn from(kind: ZpoolKind) -> DiskVariant {
match kind {
ZpoolKind::External => DiskVariant::U2,
ZpoolKind::Internal => DiskVariant::M2,
}
}
}
/// Describes an M.2 slot, often in the context of writing a system image to
/// it.
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
PartialOrd,
Ord,
Deserialize,
Serialize,
JsonSchema,
Diffable,
strum::EnumIter,
)]
#[cfg_attr(any(test, feature = "testing"), derive(test_strategy::Arbitrary))]
pub enum M2Slot {
A,
B,
}
impl M2Slot {
/// Flip from `A` to `B` or vice versa.
pub fn toggled(self) -> Self {
match self {
Self::A => Self::B,
Self::B => Self::A,
}
}
/// Convert this slot to an MGS "firmware slot" index.
pub fn to_mgs_firmware_slot(self) -> u16 {
match self {
Self::A => 0,
Self::B => 1,
}
}
/// Convert a putative MGS "firmware slot" index to an `M2Slot`, returning
/// `None` if `slot` is invalid.
pub fn from_mgs_firmware_slot(slot: u16) -> Option<Self> {
match slot {
0 => Some(Self::A),
1 => Some(Self::B),
_ => None,
}
}
}
impl fmt::Display for M2Slot {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::A => f.write_str("A"),
Self::B => f.write_str("B"),
}
}
}
impl FromStr for M2Slot {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"a" | "A" => Ok(Self::A),
"b" | "B" => Ok(Self::B),
_ => Err(format!(
"unrecognized value {s} for M2 slot. \
Must be one of `a`, `A`, `b`, or `B`",
)),
}
}
}
impl TryFrom<i64> for M2Slot {
type Error = anyhow::Error;
fn try_from(value: i64) -> Result<Self, Self::Error> {
match value {
// Gimlet should have 2 M.2 drives: drive A is assigned slot 17, and
// drive B is assigned slot 18.
17 => Ok(Self::A),
18 => Ok(Self::B),
_ => bail!("unexpected M.2 slot {value}"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use test_strategy::proptest;
#[proptest]
fn parse_dataset_name(pool_id: [u8; 16], kind: DatasetKind) {
let pool_id = ZpoolUuid::from_bytes(pool_id);
for pool in
[ZpoolName::new_internal(pool_id), ZpoolName::new_external(pool_id)]
{
let dataset_name = DatasetName::new(pool, kind.clone());
let s = dataset_name.full_name();
match DatasetName::from_str(&s) {
Ok(d) => assert_eq!(d, dataset_name),
Err(err) => panic!("failed to parse dataset name {s}: {err}"),
}
}
}
}