-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy paththinpool.rs
More file actions
4228 lines (3795 loc) · 153 KB
/
Copy paththinpool.rs
File metadata and controls
4228 lines (3795 loc) · 153 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 http://mozilla.org/MPL/2.0/.
// Code to handle management of a pool's thinpool device.
use std::{
cmp::{max, min, Ordering},
collections::{hash_map::Entry, HashMap, HashSet},
marker::PhantomData,
thread::scope,
};
use itertools::Itertools;
use retry::{delay::Fixed, retry_with_index};
use serde_json::{Map, Value};
use devicemapper::{
device_exists, message, Bytes, DataBlocks, Device, DmDevice, DmName, DmNameBuf, DmOptions,
FlakeyTargetParams, LinearDev, LinearDevTargetParams, LinearTargetParams, MetaBlocks, Sectors,
TargetLine, ThinDevId, ThinPoolDev, ThinPoolStatus, ThinPoolStatusSummary, ThinPoolUsage, IEC,
};
use crate::{
engine::{
engine::{DumpState, Filesystem, StateDiff},
strat_engine::{
backstore::backstore::{v1, v2, InternalBackstore},
cmd::{set_uuid, thin_check, thin_metadata_size, thin_repair},
dm::{get_dm, list_of_thin_pool_devices, remove_optional_devices},
names::{
format_flex_ids, format_thin_ids, format_thinpool_ids, FlexRole, ThinPoolRole,
ThinRole,
},
serde_structs::{FlexDevsSave, Recordable, ThinPoolDevSave},
shared::merge,
thinpool::{filesystem::StratFilesystem, mdv::MetadataVol, thinids::ThinDevIdPool},
writing::wipe_sectors,
},
structures::Table,
types::{
Compare, Diff, FilesystemUuid, Name, PoolUuid, SetDeleteAction, StratFilesystemDiff,
ThinPoolDiff,
},
},
stratis::{StratisError, StratisResult},
};
// Maximum number of thin devices (filesystems) allowed on a thin pool.
// NOTE: This will eventually become a default configurable by the user.
const DEFAULT_FS_LIMIT: u64 = 100;
// 1 MiB
pub const DATA_BLOCK_SIZE: Sectors = Sectors(2 * IEC::Ki);
// 512 MiB
const INITIAL_MDV_SIZE: Sectors = Sectors(IEC::Mi);
// Use different constants for testing and application builds.
use self::consts::{DATA_ALLOC_SIZE, DATA_LOWATER};
#[cfg(not(test))]
mod consts {
use super::{DataBlocks, IEC};
// 50 GiB
pub const DATA_ALLOC_SIZE: DataBlocks = DataBlocks(50 * IEC::Ki);
// 15 GiB
pub const DATA_LOWATER: DataBlocks = DataBlocks(15 * IEC::Ki);
}
#[cfg(test)]
mod consts {
use super::{DataBlocks, IEC};
// 5 GiB
pub const DATA_ALLOC_SIZE: DataBlocks = DataBlocks(5 * IEC::Ki);
// 4 GiB
pub const DATA_LOWATER: DataBlocks = DataBlocks(4 * IEC::Ki);
}
#[derive(strum_macros::AsRefStr)]
#[strum(serialize_all = "snake_case")]
enum FeatureArg {
ErrorIfNoSpace,
NoDiscardPassdown,
SkipBlockZeroing,
}
fn sectors_to_datablocks(sectors: Sectors) -> DataBlocks {
DataBlocks(sectors / DATA_BLOCK_SIZE)
}
fn datablocks_to_sectors(data_blocks: DataBlocks) -> Sectors {
*data_blocks * DATA_BLOCK_SIZE
}
// Return all the useful identifying information for a particular thinpool
// device mapper device that is available.
fn thin_pool_identifiers(thin_pool: &ThinPoolDev) -> String {
format!(
"devicemapper name: {}, device number: {}, device node: {}",
thin_pool.name(),
thin_pool.device(),
thin_pool.devnode().display()
)
}
/// Transform a list of segments belonging to a single device into a
/// list of target lines for a linear device.
fn segs_to_table(
dev: Device,
segments: &[(Sectors, Sectors)],
) -> Vec<TargetLine<LinearDevTargetParams>> {
let mut table = Vec::new();
let mut logical_start_offset = Sectors(0);
for &(start_offset, length) in segments {
let params = LinearTargetParams::new(dev, start_offset);
let line = TargetLine::new(
logical_start_offset,
length,
LinearDevTargetParams::Linear(params),
);
table.push(line);
logical_start_offset += length;
}
table
}
/// Append the second list of segments to the first, or if the last
/// segment of the first argument is adjacent to the first segment of the
/// second argument, merge those two together.
/// Postcondition: left.len() + right.len() - 1 <= result.len()
/// Postcondition: result.len() <= left.len() + right.len()
fn coalesce_segs(
left: &[(Sectors, Sectors)],
right: &[(Sectors, Sectors)],
) -> Vec<(Sectors, Sectors)> {
if left.is_empty() {
return right.to_vec();
}
if right.is_empty() {
return left.to_vec();
}
let mut segments = Vec::with_capacity(left.len() + right.len());
segments.extend_from_slice(left);
// Combine first and last if they are contiguous.
let coalesced = {
let right_first = right.first().expect("!right.is_empty()");
let left_last = segments.last_mut().expect("!left.is_empty()");
if left_last.0 + left_last.1 == right_first.0 {
left_last.1 += right_first.1;
true
} else {
false
}
};
if coalesced {
segments.extend_from_slice(&right[1..]);
} else {
segments.extend_from_slice(right);
}
segments
}
/// Segment lists that the ThinPool keeps track of.
#[derive(Debug)]
struct Segments {
meta_segments: Vec<(Sectors, Sectors)>,
meta_spare_segments: Vec<(Sectors, Sectors)>,
data_segments: Vec<(Sectors, Sectors)>,
mdv_segments: Vec<(Sectors, Sectors)>,
}
/// A way of digesting the status reported on the thinpool into a value
/// that can be checked for equality. This way, two statuses,
/// collected at different times can be checked to determine whether their
/// gross, as opposed to fine, differences are significant.
/// In this implementation convert the status designations to strings which
/// match those strings that the kernel uses to identify the different states
#[derive(Clone, Copy, Debug, Eq, PartialEq, strum_macros::AsRefStr)]
pub enum ThinPoolStatusDigest {
#[strum(serialize = "Fail")]
Fail,
#[strum(serialize = "Error")]
Error,
#[strum(serialize = "rw")]
Good,
#[strum(serialize = "ro")]
ReadOnly,
#[strum(serialize = "out_of_data_space")]
OutOfSpace,
}
impl From<&ThinPoolStatus> for ThinPoolStatusDigest {
fn from(status: &ThinPoolStatus) -> ThinPoolStatusDigest {
match status {
ThinPoolStatus::Working(status) => match status.summary {
ThinPoolStatusSummary::Good => ThinPoolStatusDigest::Good,
ThinPoolStatusSummary::ReadOnly => ThinPoolStatusDigest::ReadOnly,
ThinPoolStatusSummary::OutOfSpace => ThinPoolStatusDigest::OutOfSpace,
},
ThinPoolStatus::Fail => ThinPoolStatusDigest::Fail,
ThinPoolStatus::Error => ThinPoolStatusDigest::Error,
}
}
}
/// Calculate the room available for data that is not taken up by metadata.
fn room_for_data(usable_size: Sectors, meta_size: Sectors) -> Sectors {
Sectors(
usable_size
.saturating_sub(*INITIAL_MDV_SIZE)
.saturating_sub(*meta_size * 2u64),
)
}
pub struct ThinPoolSizeParams {
meta_size: MetaBlocks,
data_size: DataBlocks,
mdv_size: Sectors,
}
impl ThinPoolSizeParams {
/// Create a new set of initial sizes for all flex devices.
pub fn new(total_usable: Sectors) -> StratisResult<Self> {
let meta_size = thin_metadata_size(DATA_BLOCK_SIZE, total_usable, DEFAULT_FS_LIMIT)?;
let data_size = min(
room_for_data(total_usable, meta_size),
datablocks_to_sectors(DATA_ALLOC_SIZE),
);
Ok(ThinPoolSizeParams {
data_size: sectors_to_datablocks(data_size),
meta_size: meta_size.metablocks(),
mdv_size: INITIAL_MDV_SIZE,
})
}
/// The number of Sectors in the MetaBlocks.
pub fn meta_size(&self) -> Sectors {
self.meta_size.sectors()
}
/// The number of Sectors in the DataBlocks.
pub fn data_size(&self) -> Sectors {
datablocks_to_sectors(self.data_size)
}
/// MDV size
pub fn mdv_size(&self) -> Sectors {
self.mdv_size
}
}
/// Convert the thin pool status to usage information.
fn status_to_usage(status: Option<&ThinPoolStatus>) -> Option<&ThinPoolUsage> {
status.and_then(|s| {
if let ThinPoolStatus::Working(w) = s {
Some(&w.usage)
} else {
None
}
})
}
/// Convert the thin pool status to the metadata low water mark.
fn status_to_meta_lowater(status: Option<&ThinPoolStatus>) -> Option<MetaBlocks> {
status.and_then(|s| {
if let ThinPoolStatus::Working(w) = s {
w.meta_low_water.map(MetaBlocks)
} else {
None
}
})
}
/// The number of physical sectors in use by this thinpool abstraction.
/// All sectors allocated to the mdv, all sectors allocated to the
/// metadata spare, and all sectors actually in use by the thinpool DM
/// device, either for the metadata device or for the data device.
fn calc_total_physical_used(data_used: Option<Sectors>, segments: &Segments) -> Option<Sectors> {
let data_dev_used = data_used?;
let meta_total = segments.meta_segments.iter().map(|s| s.1).sum();
let spare_total = segments.meta_spare_segments.iter().map(|s| s.1).sum();
let mdv_total = segments.mdv_segments.iter().map(|s| s.1).sum();
Some(data_dev_used + spare_total + meta_total + mdv_total)
}
/// A ThinPool struct contains the thinpool itself, the spare
/// segments for its metadata device, and the filesystems and filesystem
/// metadata associated with it.
#[derive(Debug)]
pub struct ThinPool<B> {
thin_pool: ThinPoolDev,
segments: Segments,
id_gen: ThinDevIdPool,
filesystems: Table<FilesystemUuid, StratFilesystem>,
mdv: MetadataVol,
/// The single DM device that the backstore presents as its upper-most
/// layer. All DM components obtain their storage from this layer.
/// The device will change if the backstore adds or removes a cache.
backstore_device: Device,
thin_pool_status: Option<ThinPoolStatus>,
allocated_size: Sectors,
fs_limit: u64,
enable_overprov: bool,
out_of_meta_space: bool,
backstore: PhantomData<B>,
}
impl<B> ThinPool<B> {
/// Get the last cached value for the total amount of space used on the pool.
/// Stratis metadata size will be added a layer about my StratPool.
pub fn total_physical_used(&self) -> Option<Sectors> {
calc_total_physical_used(self.used().map(|(du, _)| du), &self.segments)
}
/// Get the last cached value for the total amount of space used on the
/// thin pool in the data and metadata devices.
fn used(&self) -> Option<(Sectors, MetaBlocks)> {
status_to_usage(self.thin_pool_status.as_ref())
.map(|u| (datablocks_to_sectors(u.used_data), u.used_meta))
}
/// Sum the logical size of all filesystems on the pool.
pub fn filesystem_logical_size_sum(&self) -> StratisResult<Sectors> {
Ok(self
.mdv
.filesystems()?
.iter()
.map(|fssave| fssave.size)
.sum())
}
/// Set the current status of the thin_pool device to thin_pool_status.
/// If there has been a change, log that change at the info or warn level
/// as appropriate.
fn set_state(&mut self, thin_pool_status: Option<ThinPoolStatus>) {
let current_status = self.thin_pool_status.as_ref().map(|s| s.into());
let new_status: Option<ThinPoolStatusDigest> = thin_pool_status.as_ref().map(|s| s.into());
if current_status != new_status {
let current_status_str = current_status
.as_ref()
.map(|x| x.as_ref())
.unwrap_or_else(|| "none");
if new_status != Some(ThinPoolStatusDigest::Good) {
warn!(
"Status of thinpool device with \"{}\" changed from \"{}\" to \"{}\"",
thin_pool_identifiers(&self.thin_pool),
current_status_str,
new_status
.as_ref()
.map(|s| s.as_ref())
.unwrap_or_else(|| "none"),
);
} else {
info!(
"Status of thinpool device with \"{}\" changed from \"{}\" to \"{}\"",
thin_pool_identifiers(&self.thin_pool),
current_status_str,
new_status
.as_ref()
.map(|s| s.as_ref())
.unwrap_or_else(|| "none"),
);
}
}
self.thin_pool_status = thin_pool_status;
}
/// Tear down the components managed here: filesystems, the MDV,
/// and the actual thinpool device itself.
///
/// Err(_) contains a tuple with a bool as the second element indicating whether or not
/// there are filesystems that were unable to be torn down. This distinction exists because
/// if filesystems remain, the pool could receive IO and should remain in set up pool data
/// structures. However if all filesystems were torn down, the pool can be moved to
/// the designation of partially constructed pools as no IO can be received on the pool
/// and it has been partially torn down.
pub fn teardown(&mut self, pool_uuid: PoolUuid) -> Result<(), (StratisError, bool)> {
let fs_uuids = self
.filesystems
.iter()
.map(|(_, fs_uuid, _)| *fs_uuid)
.collect::<Vec<_>>();
// Must succeed in tearing down all filesystems before the
// thinpool..
for fs_uuid in fs_uuids {
StratFilesystem::teardown(pool_uuid, fs_uuid).map_err(|e| (e, true))?;
self.filesystems.remove_by_uuid(fs_uuid);
}
let devs = list_of_thin_pool_devices(pool_uuid);
remove_optional_devices(devs).map_err(|e| (e, false))?;
// ..but MDV has no DM dependencies with the above
self.mdv.teardown(pool_uuid).map_err(|e| (e, false))?;
Ok(())
}
/// Set the pool IO mode to error on writes when out of space.
///
/// This mode should be enabled when the pool is out of space to allocate to the
/// pool.
fn set_error_mode(&mut self) -> bool {
if !self.out_of_alloc_space() {
if let Err(e) = self.thin_pool.error_if_no_space(get_dm()) {
warn!(
"Could not put thin pool into IO error mode on out of space conditions: {}",
e
);
false
} else {
true
}
} else {
false
}
}
/// Set the pool IO mode to queue writes when out of space.
///
/// This mode should be enabled when the pool has space to allocate to the pool.
/// This prevents unnecessary IO errors while the pools is being extended and
/// the writes can then be processed after the extension.
pub fn set_queue_mode(&mut self) -> bool {
if self.out_of_alloc_space() {
if let Err(e) = self.thin_pool.queue_if_no_space(get_dm()) {
warn!(
"Could not put thin pool into IO queue mode on out of space conditions: {}",
e
);
false
} else {
true
}
} else {
false
}
}
/// Returns true if the pool has run out of available space to allocate.
pub fn out_of_alloc_space(&self) -> bool {
self.thin_pool
.table()
.table
.params
.feature_args
.contains(FeatureArg::ErrorIfNoSpace.as_ref())
}
pub fn get_filesystem_by_uuid(&self, uuid: FilesystemUuid) -> Option<(Name, &StratFilesystem)> {
self.filesystems.get_by_uuid(uuid)
}
pub fn get_mut_filesystem_by_uuid(
&mut self,
uuid: FilesystemUuid,
) -> Option<(Name, &mut StratFilesystem)> {
self.filesystems.get_mut_by_uuid(uuid)
}
pub fn get_filesystem_by_name(&self, name: &str) -> Option<(FilesystemUuid, &StratFilesystem)> {
self.filesystems.get_by_name(name)
}
pub fn get_mut_filesystem_by_name(
&mut self,
name: &str,
) -> Option<(FilesystemUuid, &mut StratFilesystem)> {
self.filesystems.get_mut_by_name(name)
}
pub fn has_filesystems(&self) -> bool {
!self.filesystems.is_empty()
}
pub fn filesystems(&self) -> Vec<(Name, FilesystemUuid, &StratFilesystem)> {
self.filesystems
.iter()
.map(|(name, uuid, x)| (name.clone(), *uuid, x))
.collect()
}
pub fn filesystems_mut(&mut self) -> Vec<(Name, FilesystemUuid, &mut StratFilesystem)> {
self.filesystems
.iter_mut()
.map(|(name, uuid, x)| (name.clone(), *uuid, x))
.collect()
}
/// Create a filesystem within the thin pool. Given name must not
/// already be in use.
pub fn create_filesystem(
&mut self,
pool_name: &str,
pool_uuid: PoolUuid,
name: &str,
size: Sectors,
size_limit: Option<Sectors>,
) -> StratisResult<FilesystemUuid> {
if self
.mdv
.filesystems()?
.into_iter()
.map(|fssave| fssave.name)
.collect::<HashSet<_>>()
.contains(name)
{
return Err(StratisError::Msg(format!(
"Pool {pool_name} already has a record of filesystem name {name}"
)));
}
let (fs_uuid, mut new_filesystem) = StratFilesystem::initialize(
pool_uuid,
&self.thin_pool,
size,
size_limit,
self.id_gen.new_id()?,
)?;
let name = Name::new(name.to_owned());
if let Err(err) = self.mdv.save_fs(&name, fs_uuid, &new_filesystem) {
if let Err(err2) = retry_with_index(Fixed::from_millis(100).take(4), |i| {
trace!(
"Cleanup new filesystem after failed save_fs() attempt {}",
i
);
new_filesystem.destroy(&self.thin_pool)
}) {
error!(
"When handling failed save_fs(), fs.destroy() failed: {}",
err2
)
}
return Err(err);
}
self.filesystems.insert(name, fs_uuid, new_filesystem);
let (name, fs) = self
.filesystems
.get_by_uuid(fs_uuid)
.expect("Inserted above");
fs.udev_fs_change(pool_name, fs_uuid, &name);
Ok(fs_uuid)
}
/// Create a filesystem snapshot of the origin. Given origin_uuid
/// must exist. Returns the Uuid of the new filesystem.
pub fn snapshot_filesystem(
&mut self,
pool_name: &str,
pool_uuid: PoolUuid,
origin_uuid: FilesystemUuid,
snapshot_name: &str,
) -> StratisResult<(FilesystemUuid, &mut StratFilesystem)> {
assert!(self.get_filesystem_by_name(snapshot_name).is_none());
let snapshot_fs_uuid = FilesystemUuid::new_v4();
let (snapshot_dm_name, snapshot_dm_uuid) =
format_thin_ids(pool_uuid, ThinRole::Filesystem(snapshot_fs_uuid));
let snapshot_id = self.id_gen.new_id()?;
let new_filesystem = match self.get_filesystem_by_uuid(origin_uuid) {
Some((fs_name, filesystem)) => filesystem.snapshot(
&self.thin_pool,
snapshot_name,
&snapshot_dm_name,
Some(&snapshot_dm_uuid),
&fs_name,
snapshot_fs_uuid,
snapshot_id,
origin_uuid,
)?,
None => {
return Err(StratisError::Msg(
"snapshot_filesystem failed, filesystem not found".into(),
));
}
};
let new_fs_name = Name::new(snapshot_name.to_owned());
self.mdv
.save_fs(&new_fs_name, snapshot_fs_uuid, &new_filesystem)?;
self.filesystems
.insert(new_fs_name, snapshot_fs_uuid, new_filesystem);
let (new_fs_name, fs) = self
.filesystems
.get_by_uuid(snapshot_fs_uuid)
.expect("Inserted above");
fs.udev_fs_change(pool_name, snapshot_fs_uuid, &new_fs_name);
Ok((
snapshot_fs_uuid,
self.filesystems
.get_mut_by_uuid(snapshot_fs_uuid)
.expect("just inserted")
.1,
))
}
/// Destroy a filesystem within the thin pool. Destroy metadata associated
/// with the thinpool. If there is a failure to destroy the filesystem,
/// retain it, and return an error.
///
/// * Ok(Some(uuid)) provides the uuid of the destroyed filesystem
/// * Ok(None) is returned if the filesystem did not exist
/// * Err(_) is returned if the filesystem could not be destroyed
fn destroy_filesystem(
&mut self,
pool_name: &str,
uuid: FilesystemUuid,
) -> StratisResult<Option<FilesystemUuid>> {
match self.filesystems.remove_by_uuid(uuid) {
Some((fs_name, mut fs)) => match fs.destroy(&self.thin_pool) {
Ok(_) => {
self.clear_out_of_meta_flag();
if let Err(err) = self.mdv.rm_fs(uuid) {
error!("Could not remove metadata for fs with UUID {} and name {} belonging to pool {}, reason: {:?}",
uuid,
fs_name,
pool_name,
err);
}
Ok(Some(uuid))
}
Err(err) => {
self.filesystems.insert(fs_name, uuid, fs);
Err(err)
}
},
None => Ok(None),
}
}
#[cfg(test)]
pub fn state(&self) -> Option<ThinPoolStatusDigest> {
self.thin_pool_status.as_ref().map(|s| s.into())
}
/// Rename a filesystem within the thin pool.
///
/// * Ok(Some(true)) is returned if the filesystem was successfully renamed.
/// * Ok(Some(false)) is returned if the source and target filesystem names are the same
/// * Ok(None) is returned if the source filesystem name does not exist
/// * An error is returned if the target filesystem name already exists
pub fn rename_filesystem(
&mut self,
pool_name: &str,
uuid: FilesystemUuid,
new_name: &str,
) -> StratisResult<Option<bool>> {
let old_name = rename_filesystem_pre!(self; uuid; new_name);
let new_name = Name::new(new_name.to_owned());
let filesystem = self
.filesystems
.remove_by_uuid(uuid)
.expect("Must succeed since self.filesystems.get_by_uuid() returned a value")
.1;
if let Err(err) = self.mdv.save_fs(&new_name, uuid, &filesystem) {
self.filesystems.insert(old_name, uuid, filesystem);
Err(err)
} else {
self.filesystems.insert(new_name, uuid, filesystem);
let (new_name, fs) = self.filesystems.get_by_uuid(uuid).expect("Inserted above");
fs.udev_fs_change(pool_name, uuid, &new_name);
Ok(Some(true))
}
}
/// The names of DM devices belonging to this pool that may generate events
pub fn get_eventing_dev_names(&self, pool_uuid: PoolUuid) -> Vec<DmNameBuf> {
let mut eventing = vec![
format_flex_ids(pool_uuid, FlexRole::ThinMeta).0,
format_flex_ids(pool_uuid, FlexRole::ThinData).0,
format_flex_ids(pool_uuid, FlexRole::MetadataVolume).0,
format_thinpool_ids(pool_uuid, ThinPoolRole::Pool).0,
];
eventing.extend(
self.filesystems
.iter()
.map(|(_, uuid, _)| format_thin_ids(pool_uuid, ThinRole::Filesystem(*uuid)).0),
);
eventing
}
/// Suspend the thinpool
pub fn suspend(&mut self) -> StratisResult<()> {
// thindevs automatically suspended when thinpool is suspended
self.thin_pool.suspend(get_dm(), DmOptions::default())?;
// If MDV suspend fails, resume the thin pool and return the error
if let Err(err) = self.mdv.suspend() {
if let Err(e) = self.thin_pool.resume(get_dm()) {
Err(StratisError::Chained(
"Suspending the MDV failed and MDV suspend clean up action of resuming the thin pool also failed".to_string(),
// NOTE: This should potentially put the pool in maintenance-only
// mode. For now, this will have no effect.
Box::new(StratisError::NoActionRollbackError{
causal_error: Box::new(err),
rollback_error: Box::new(StratisError::from(e)),
}),
))
} else {
Err(err)
}
} else {
Ok(())
}
}
/// Resume the thinpool
pub fn resume(&mut self) -> StratisResult<()> {
self.mdv.resume()?;
// thindevs automatically resumed here
self.thin_pool.resume(get_dm())?;
Ok(())
}
pub fn fs_limit(&self) -> u64 {
self.fs_limit
}
/// Returns a boolean indicating whether overprovisioning is disabled or not.
pub fn overprov_enabled(&self) -> bool {
self.enable_overprov
}
/// Indicate to the pool that it may now have more room for metadata growth.
pub fn clear_out_of_meta_flag(&mut self) {
self.out_of_meta_space = false;
}
/// Calculate filesystem metadata from current state
pub fn current_fs_metadata(&self, fs_name: Option<&str>) -> StratisResult<String> {
serde_json::to_string(
&self
.filesystems
.iter()
.filter_map(|(name, uuid, fs)| {
if fs_name.map(|n| *n == **name).unwrap_or(true) {
Some((*uuid, fs.record(name, *uuid)))
} else {
None
}
})
.collect::<HashMap<_, _>>(),
)
.map_err(|e| e.into())
}
/// Read filesystem metadata from mdv
pub fn last_fs_metadata(&self, fs_name: Option<&str>) -> StratisResult<String> {
serde_json::to_string(
&self
.mdv
.filesystems()?
.iter()
.filter_map(|fssave| {
if fs_name.map(|n| *n == fssave.name).unwrap_or(true) {
Some((fssave.uuid, fssave))
} else {
None
}
})
.collect::<HashMap<_, _>>(),
)
.map_err(|e| e.into())
}
}
impl ThinPool<v1::Backstore> {
/// Make a new thin pool.
#[cfg(any(test, feature = "test_extras"))]
pub fn new(
pool_uuid: PoolUuid,
thin_pool_size: &ThinPoolSizeParams,
data_block_size: Sectors,
backstore: &mut v1::Backstore,
) -> StratisResult<ThinPool<v1::Backstore>> {
let mut segments_list = backstore
.alloc(
pool_uuid,
&[
thin_pool_size.meta_size(),
thin_pool_size.meta_size(),
thin_pool_size.data_size(),
thin_pool_size.mdv_size(),
],
)?
.ok_or_else(|| {
let err_msg = "Could not allocate sufficient space for thinpool devices";
StratisError::Msg(err_msg.into())
})?;
let mdv_segments = segments_list.pop().expect("len(segments_list) == 4");
let data_segments = segments_list.pop().expect("len(segments_list) == 3");
let spare_segments = segments_list.pop().expect("len(segments_list) == 2");
let meta_segments = segments_list.pop().expect("len(segments_list) == 1");
let backstore_device = backstore.device().expect(
"Space has just been allocated from the backstore, so it must have a cap device",
);
// When constructing a thin-pool, Stratis reserves the first N
// sectors on a block device by creating a linear device with a
// starting offset. DM writes the super block in the first block.
// DM requires this first block to be zeros when the meta data for
// the thin-pool is initially created. If we don't zero the
// superblock DM issue error messages because it triggers code paths
// that are trying to re-adopt the device with the attributes that
// have been passed.
let (dm_name, dm_uuid) = format_flex_ids(pool_uuid, FlexRole::ThinMeta);
let meta_dev = LinearDev::setup(
get_dm(),
&dm_name,
Some(&dm_uuid),
segs_to_table(backstore_device, &[meta_segments]),
)?;
// Wipe the first 4 KiB, i.e. 8 sectors as recommended in kernel DM
// docs: device-mapper/thin-provisioning.txt: Setting up a fresh
// pool device.
wipe_sectors(
meta_dev.devnode(),
Sectors(0),
min(Sectors(8), meta_dev.size()),
)?;
let (dm_name, dm_uuid) = format_flex_ids(pool_uuid, FlexRole::ThinData);
let data_dev = LinearDev::setup(
get_dm(),
&dm_name,
Some(&dm_uuid),
segs_to_table(backstore_device, &[data_segments]),
)?;
let (dm_name, dm_uuid) = format_flex_ids(pool_uuid, FlexRole::MetadataVolume);
let mdv_dev = LinearDev::setup(
get_dm(),
&dm_name,
Some(&dm_uuid),
segs_to_table(backstore_device, &[mdv_segments]),
)?;
let mdv = MetadataVol::initialize(pool_uuid, mdv_dev)?;
let (dm_name, dm_uuid) = format_thinpool_ids(pool_uuid, ThinPoolRole::Pool);
let data_dev_size = data_dev.size();
let thinpool_dev = ThinPoolDev::new(
get_dm(),
&dm_name,
Some(&dm_uuid),
meta_dev,
data_dev,
data_block_size,
// Either set the low water mark to the standard low water mark if
// the device is larger than DATA_LOWATER or otherwise to half of the
// capacity of the data device.
min(
DATA_LOWATER,
DataBlocks((data_dev_size / DATA_BLOCK_SIZE) / 2),
),
vec![
FeatureArg::NoDiscardPassdown.as_ref().to_string(),
FeatureArg::SkipBlockZeroing.as_ref().to_string(),
],
)?;
let thin_pool_status = thinpool_dev.status(get_dm(), DmOptions::default()).ok();
let segments = Segments {
meta_segments: vec![meta_segments],
meta_spare_segments: vec![spare_segments],
data_segments: vec![data_segments],
mdv_segments: vec![mdv_segments],
};
Ok(ThinPool {
thin_pool: thinpool_dev,
segments,
id_gen: ThinDevIdPool::new_from_ids(&[]),
filesystems: Table::default(),
mdv,
backstore_device,
thin_pool_status,
allocated_size: backstore.datatier_allocated_size(),
fs_limit: DEFAULT_FS_LIMIT,
enable_overprov: true,
out_of_meta_space: false,
backstore: PhantomData,
})
}
/// Set the device on all DM devices
pub fn set_device(&mut self, backstore_device: Device) -> StratisResult<bool> {
if backstore_device == self.backstore_device {
return Ok(false);
}
let xform_target_line =
|line: &TargetLine<LinearDevTargetParams>| -> TargetLine<LinearDevTargetParams> {
let new_params = match line.params {
LinearDevTargetParams::Linear(ref params) => LinearDevTargetParams::Linear(
LinearTargetParams::new(backstore_device, params.start_offset),
),
LinearDevTargetParams::Flakey(ref params) => {
let feature_args = params.feature_args.iter().cloned().collect::<Vec<_>>();
LinearDevTargetParams::Flakey(FlakeyTargetParams::new(
backstore_device,
params.start_offset,
params.up_interval,
params.down_interval,
feature_args,
))
}
};
TargetLine::new(line.start, line.length, new_params)
};
let meta_table = self
.thin_pool
.meta_dev()
.table()
.table
.clone()
.iter()
.map(&xform_target_line)
.collect::<Vec<_>>();
let data_table = self
.thin_pool
.data_dev()
.table()
.table
.clone()
.iter()
.map(&xform_target_line)
.collect::<Vec<_>>();
let mdv_table = self
.mdv
.device()
.table()
.table
.clone()
.iter()
.map(&xform_target_line)
.collect::<Vec<_>>();
self.thin_pool.set_meta_table(get_dm(), meta_table)?;
self.thin_pool.set_data_table(get_dm(), data_table)?;
self.mdv.set_table(mdv_table)?;
self.backstore_device = backstore_device;
Ok(true)
}
}
impl ThinPool<v2::Backstore> {
/// Make a new thin pool.
pub fn new(
pool_uuid: PoolUuid,
thin_pool_size: &ThinPoolSizeParams,
data_block_size: Sectors,
backstore: &mut v2::Backstore,
) -> StratisResult<ThinPool<v2::Backstore>> {
let mut segments_list = backstore
.alloc(
pool_uuid,
&[
thin_pool_size.meta_size(),
thin_pool_size.meta_size(),
thin_pool_size.data_size(),
thin_pool_size.mdv_size(),
],
)?
.ok_or_else(|| {
let err_msg = "Could not allocate sufficient space for thinpool devices";
StratisError::Msg(err_msg.into())
})?;
let mdv_segments = segments_list.pop().expect("len(segments_list) == 4");
let data_segments = segments_list.pop().expect("len(segments_list) == 3");
let spare_segments = segments_list.pop().expect("len(segments_list) == 2");
let meta_segments = segments_list.pop().expect("len(segments_list) == 1");
let backstore_device = backstore.device().expect(
"Space has just been allocated from the backstore, so it must have a cap device",
);
// When constructing a thin-pool, Stratis reserves the first N
// sectors on a block device by creating a linear device with a
// starting offset. DM writes the super block in the first block.
// DM requires this first block to be zeros when the meta data for