forked from rockstor/rockstor-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
btrfs.py
2323 lines (2163 loc) · 95.9 KB
/
btrfs.py
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
"""
Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
RockStor is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import collections
import json
import re
import time
import os
from system.osi import (
run_command,
create_tmp_dir,
is_share_mounted,
is_mounted,
get_dev_byid_name,
convert_to_kib,
toggle_path_rw,
get_device_path,
dev_mount_point,
)
from system.exceptions import CommandException
from pool_scrub import PoolScrub
from huey.contrib.djhuey import task
from django.conf import settings
import logging
from datetime import datetime
"""
system level helper methods to interact with the btrfs filesystem
"""
logger = logging.getLogger(__name__)
MKFS_BTRFS = "/usr/sbin/mkfs.btrfs"
BTRFS = "/usr/sbin/btrfs"
MOUNT = "/usr/bin/mount"
UMOUNT = "/usr/bin/umount"
DEFAULT_MNT_DIR = "/mnt2/"
RMDIR = "/usr/bin/rmdir"
QID = "2015"
# The following model/db default setting is also used when quotas are disabled.
PQGROUP_DEFAULT = settings.MODEL_DEFS["pqgroup"]
# Potential candidate for settings.conf.in but currently only used here and
# facilitates easier user modification, ie without buildout re-config step.
# N.B. 'root/var/lib/machines' is auto created by systemd:
# https://cgit.freedesktop.org/systemd/systemd/commit/?id=113b3fc1a8061f4a24dd0db74e9a3cd0083b2251
ROOT_SUBVOL_EXCLUDE = [
"root",
"@",
"@/root",
"tmp",
"@/tmp",
"var",
"@/var",
"boot/grub2/i386-pc",
"@/boot/grub2/i386-pc",
"boot/grub2/x86_64-efi",
"@/boot/grub2/x86_64-efi",
"boot/grub2/arm64-efi",
"@/boot/grub2/arm64-efi",
"srv",
"@/srv",
"usr/local",
"@/usr/local",
"opt",
"@/opt",
"root/var/lib/machines",
"@/.snapshots",
".snapshots",
]
# Note in the above we have a non symmetrical exclusions entry of '@/.snapshots
# this is to help distinguish our .snapshots from snapper's rollback subvol.
# System-wide subvolume exclude list.
SUBVOL_EXCLUDE = [".beeshome", "@/.beeshome"]
# tuple subclass for devices from a btrfs view.
Dev = collections.namedtuple("Dev", "temp_name is_byid devid size allocated")
# Named Tuple for Device Pool Info.
DevPoolInfo = collections.namedtuple("DevPoolInfo", "devid size allocated uuid label")
# Named Tuple for btrfs device usage info.
DevUsageInfo = collections.namedtuple("DevUsageInfo", "temp_name size allocated")
# Named Tuple for default_subvol info: id (string) path (string) boot_to_snap (boolean)
DefaultSubvol = collections.namedtuple("DefaultSubvol", "id path boot_to_snap")
# Named Tuple for balance status: active (boolean) internal (boolean) status (dict)
BalanceStatusAll = collections.namedtuple("BalanceStatusAll", "active internal status")
# Named Tuple to define raid profile limits and data/metadata
btrfs_profile = collections.namedtuple(
"btrfs_profile", "min_dev_count max_dev_missing data_raid metadata_raid"
)
# List of Rockstor btrfs raid profiles indexed by their name.
# I.e. PROFILE[raid_level].min_dev_count
# N.B. Mixed profiles indicated by "-" i.e. DATA-METADATA
# https://btrfs.readthedocs.io/en/latest/Kernel-by-version.html#jan-2020
# RAID1C34 along with incompatible flag added in kernel 5.5.
# https://btrfs.readthedocs.io/en/latest/Kernel-by-version.html#nov-2021 kernel 5.15
# enabled running raid0 and 10 with a minimum of 1 & 2 devices respectively.
# https://btrfs.readthedocs.io/en/latest/mkfs.btrfs.html
# "It's recommended to use specific profiles ..."
# The following are Rockstor's specifics:
PROFILE = {
# Fail through profile to account catch unknown raid levels/combinations.
# We specify a min dev count of 4 to account for any raid level,
# and likewise play safe by allowing for no missing devices.
"unknown": btrfs_profile(
min_dev_count=4, max_dev_missing=0, data_raid="unknown", metadata_raid="unknown"
),
# non redundant profiles!
"single": btrfs_profile(
min_dev_count=1, max_dev_missing=0, data_raid="single", metadata_raid="single"
),
"single-dup": btrfs_profile(
min_dev_count=1, max_dev_missing=0, data_raid="single", metadata_raid="dup"
),
"raid0": btrfs_profile(
min_dev_count=2, max_dev_missing=0, data_raid="raid0", metadata_raid="raid0"
),
# Mirrored profiles:
"raid1": btrfs_profile(
min_dev_count=2, max_dev_missing=1, data_raid="raid1", metadata_raid="raid1"
),
"raid1c3": btrfs_profile(
min_dev_count=3, max_dev_missing=2, data_raid="raid1c3", metadata_raid="raid1c3"
),
"raid1c4": btrfs_profile(
min_dev_count=4, max_dev_missing=3, data_raid="raid1c4", metadata_raid="raid1c4"
),
"raid10": btrfs_profile(
min_dev_count=4, max_dev_missing=1, data_raid="raid10", metadata_raid="raid10"
),
# Parity raid levels (recommended min_dev_count is 3 & 4 respectively)
"raid5": btrfs_profile(
min_dev_count=2, max_dev_missing=1, data_raid="raid5", metadata_raid="raid5"
),
"raid6": btrfs_profile(
min_dev_count=3, max_dev_missing=2, data_raid="raid6", metadata_raid="raid6"
),
# ------- MIXED PROFILES DATA-METADATA (max 10 chars) -------
# Mixed Mirrored profiles:
"raid1-1c3": btrfs_profile(
min_dev_count=3, max_dev_missing=1, data_raid="raid1", metadata_raid="raid1c3"
),
"raid1-1c4": btrfs_profile(
min_dev_count=4, max_dev_missing=1, data_raid="raid1", metadata_raid="raid1c4"
),
"raid10-1c3": btrfs_profile(
min_dev_count=4, max_dev_missing=1, data_raid="raid10", metadata_raid="raid1c3"
),
"raid10-1c4": btrfs_profile(
min_dev_count=4, max_dev_missing=1, data_raid="raid10", metadata_raid="raid1c4"
),
# Parity data - Mirrored metadata
"raid5-1": btrfs_profile(
min_dev_count=2, max_dev_missing=1, data_raid="raid5", metadata_raid="raid1"
),
"raid5-1c3": btrfs_profile(
min_dev_count=3, max_dev_missing=1, data_raid="raid5", metadata_raid="raid1c3"
),
"raid6-1c3": btrfs_profile(
min_dev_count=3, max_dev_missing=2, data_raid="raid6", metadata_raid="raid1c3"
),
"raid6-1c4": btrfs_profile(
min_dev_count=4, max_dev_missing=2, data_raid="raid6", metadata_raid="raid1c4"
),
}
def add_pool(pool, disks):
"""
Makes a btrfs pool (filesystem) of name 'pool' using the by-id disk names
provided, then attempts to enable quotas for this pool.
:param pool: Pool object.
:param disks: list of by-id disk names without paths to make the pool from.
:return o, err, rc from last command executed.
"""
disks_fp = [get_device_path(d) for d in disks]
draid = PROFILE[pool.raid].data_raid
mraid = PROFILE[pool.raid].metadata_raid
cmd = [MKFS_BTRFS, "-f", "-d", draid, "-m", mraid, "-L", pool.name]
cmd.extend(disks_fp)
# Run the create pool command, any exceptions are logged and raised by
# run_command as a CommandException.
out, err, rc = run_command(cmd, log=True)
# Note that given our cmd (mkfs.btrfs) is executed with the default
# run_command flag of throw=True then program execution is stopped in the
# event of rc != 0 so the following clause is redundant but offers an
# additional level of isolation.
# Only execute enable_quota on above btrfs command having an rc=0
if rc == 0:
out2, err2, rc2 = enable_quota(pool)
if rc2 != 0:
e_msg = (
"non-zero code ({}) returned by enable_quota() while "
"enabling quota on a newly created pool : pool name = {}, "
"output: {}, error: {}.".format(rc2, pool.name, out2, err2)
)
logger.error(e_msg)
return out2, err2, rc2
else:
logger.error(
"Unknown state in add_pool() - non-zero code ({}) "
"returned by {} with output: {} and error: {}.".format(rc, cmd, out, err)
)
return out, err, rc
def dev_stats_zero(target):
"""
Simple and fast wrapper around 'btrfs device stats -c target'
Intended as a quick boolean pool health check, ie do any devs have errors?
The command used requires a mounted pool (vol) and does not appear to wake
drive from a standby state.
Bit 6 (64 decimal) of return code is set when non zero errors are found.
:param target: Pool mount point or device name with path
:return: True if zero errors are reported, False otherwise.
"""
cmd = [BTRFS, "device", "stats", "-c", target]
o, e, rc = run_command(cmd, throw=False)
# logger.debug('out = {} err = {} rc = {}'.format(o, e, rc))
if rc & 64: # bitwise AND for Bit 6
return False
return True
def get_dev_io_error_stats(target, json_format=True):
"""
Wrapper / parser for 'btrfs device stats -c target' intended to populate
the disk model io_error_stats property: called from within try clause.
:param target: device with path eg: /dev/sda or /dev/disk/by-id/virtio-3333
:param json_format: Defaults to json format but can return dict.
:return: json or dict format of retrieved values or None if error or no
btrfs mount.
"""
cmd = [BTRFS, "device", "stats", "-c", get_device_path(target)]
o, e, rc = run_command(cmd, throw=False)
stats = {
"write_io_errs": "0",
"read_io_errs": "0",
"flush_io_errs": "0",
"corruption_errs": "0",
"generation_errs": "0",
}
if rc == 0: # we have low level confirmation of 0 errors so return dict.
# Avoids unnecessary parsing as we already know all errors are zero.
if not json_format:
return stats
return json.dumps(stats)
if rc == 1:
# Device not part of a mounted btrfs vol, or dev is unknown.
return None
for line in o:
fields = line.split(".")
# e.g. ['[/dev/vdb]', 'write_io_errs 0']
if len(fields) != 2:
continue # Skip line as unknown and will fail following index.
sub_fields = fields[1].split()
# e.g. ['write_io_errs', '0']
if sub_fields[1] == "0": # optimization.
continue # We already have this in our stats template.
stats[sub_fields[0]] = sub_fields[1] # ie {'write_io_errs': '42'}
if not json_format:
return stats
return json.dumps(stats)
def pool_missing_dev_count(label):
"""
Parses 'btrfs fi show --raw label' to return number of missing devices.
Extracts vol total dev count from e.g.: "\tTotal devices 3 FS bytes used 2.63GiB".
And counts the number of lines there-after beginning "\tdevid" and not ending
in "SING" or "sing" (for "MISSING"/"missing").
Label is used as this is preserved in our Pool db so will work if the pool
fails to mount, and there by allows surfacing this as a potential reason
for the mount failure.
:param label: Pool label.
:return: int for number of missing devices (total - attached).
"""
if label is None:
return 0
# --raw used to minimise pre-processing of irrelevant 'used' info (units).
cmd = [BTRFS, "fi", "show", "--raw", label]
o, e, rc = run_command(cmd)
total_devices = 0
attached_devids = 0
for line in o:
if not line:
continue
# Skip "Label:" line as it has no 'missing' info.
# Skip "warning, device 8 is missing" lines as they only appear when unmounted.
# Skip "(TAB)*** Some devices missing" we count devid lines no ending in MISSING
if line.startswith(("Lab", "war", "\t**")):
continue
if line.startswith("\tTotal"):
total_devices = int(line.split()[2])
continue
if not total_devices == 0:
# Leap 15.4 default & backport kernels (not missing)
# devid 5 size 5.00GiB used 2.12GiB path /dev/sda
# Newer Stable Kernel Backport (e.g. 6.2.0+) add a MISSING:
# older kernels do not have entries for missing devices.
# devid 1 size 0 used 0 path MISSING
if line.startswith("\tdev") and not line.endswith(("SING", "sing")):
attached_devids += 1
return total_devices - attached_devids
def degraded_pools_found():
"""
Primarily intended to indicate the existence of any degraded pools, managed
or otherwise. Originally used by data_collector to feed real time Web-UI
indicators. Non-managed pool coverage allows for the indication of a
degraded mount requirement pre-import or on fresh disaster recovery
installs.
:return: Number of degraded pools as indicated by any line ending in
"missing" following an associated "Label" line.
"""
# --raw used to minimise pre-processing of irrelevant 'used' info (units).
cmd = [BTRFS, "fi", "show", "--raw"]
o, e, rc = run_command(cmd)
degraded_pool_count = 0
in_pool = False
for line in o:
if not in_pool and line[0:3] == "Lab":
in_pool = True
continue
# Account for older and newer kernels respectively:
if in_pool and line.lower().endswith("missing"):
# we are in pool details and have found a missing device
degraded_pool_count += 1
# use in_pool switch to avoid counting this pool twice if it has
# multiple missing as at least 1 missing dev is degraded.
in_pool = False
elif line == "":
# pool listings delimited by blank lines
in_pool = False
return degraded_pool_count
def set_pool_label(label, dev_temp_name, root_pool=False):
"""
Wrapper around 'btrfs fi label dev|mnt_pt' initially intended to auto label
pools (btrfs vols) that have 'none' as label since a label is assumed.
Could server as more general purpose once we have pool re-naming.
:param dev_temp_name: full_dev_path
:param label: Desired label: overridden if root_pool = True.
:param root_pool: Boolean indicator of system root ('/') pool.
:return: new label if successful or None if command exception.
"""
# we override accessor and label for the system pool.
if root_pool:
# root_pool already mounted so we must use mount point.
accessor = "/"
label = settings.SYS_VOL_LABEL
else: # adapt to mounted or unmounted non system root pools:
mount_point = dev_mount_point(dev_temp_name)
if mount_point is not None:
accessor = mount_point
else:
accessor = dev_temp_name
# This requirement limits importing ro pools with no label.
cmd = [BTRFS, "fi", "label", accessor, label]
# Consider udevadm trigger on this device as label changed.
try:
logger.debug("Attempting auto pool label for ({}).".format(accessor))
o, e, rc = run_command(cmd, log=True)
except CommandException as e:
logger.error(
"Pool label attempt on {} to {} failed with "
"error: {}".format(accessor, label, e.err)
)
return None
return label
def get_dev_pool_info():
"""
Variant of get_pool_info() intended for low level use where a system wide
view is required with temp_name indexing. Used as a replacement for
get_pool_info in _update_disk_state() and _refresh_pool_state() to allow
for one call to acquire all pool info system wide. Pool counterpart to
osi.py's scan_disks(). Note that there is likely much duplication within
the returned structure but we provide fast / light lookup for each device
member thereafter via it's own named tuple.
:return sys_pool_info: dict indexed by temp_name with DevPoolInfo values.
"""
cmd = [BTRFS, "fi", "show", "--raw"]
o, e, rc = run_command(cmd)
# Label: 'rockstor_rockstor' uuid: be5d2c5a-cc86-4c9a-96da-0a2add43f079
# Total devices 1 FS bytes used 2444705792
# devid 1 size 14935916544 used 3825205248 path /dev/sda3
#
# Label: 'rock-pool' uuid: be4814da-a054-4ffe-82e7-b40ec33e4343
# Total devices 5 FS bytes used 3913490432
# devid 17 size 5368709120 used 1073741824 path /dev/sdb
# devid 18 size 5368709120 used 2415919104 path /dev/sdd
sys_pool_info = {}
uuid = None # Every pool has one.
label = "none" # What is shown when there is no label on a pool.
devid = 0 # Real ones start at 1 so this can be a flag of sorts.
for line in o:
if line == "":
continue
fields = line.strip().split()
if fields[0] == "Label:": # Pool header: set uuid and label
label = fields[1].strip("'") # single quotes present when != none
uuid = fields[3]
elif fields[0] == "Total":
continue
elif fields[0] == "devid":
devid = int(fields[1])
size = int(fields[3]) / 1024 # Bytes to KB
allocated = int(fields[5]) / 1024 # Bytes to KB
temp_name = fields[-1]
dp_info = DevPoolInfo(
devid=devid, size=size, allocated=allocated, uuid=uuid, label=label
)
sys_pool_info[temp_name] = dp_info
# logger.debug('get_dev_pool_info() returning {}'.format(sys_pool_info))
return sys_pool_info
def get_pool_info(disk):
"""
Extracts pool information by running btrfs fi show <disk> and collates
the results in a property keyed dictionary The disks ('disks' key) names
found are translated to the by-id type (/dev/disk/by-id) so that their
counterparts in the db's Disk.name field can be found. No path is stored.
N.B. devices without serial may have no by-id counterpart.
Enforces a non 'none' label by substituting the uuid if label = none.
Used by CommandView()._refresh_pool_state() and
DiskDetailView()._btrfs_disk_import
:param disk: by-id disk name without path
:return: a dictionary with keys of 'disks', 'label', 'uuid',
'hasMissingDev', 'fullDevCount', and 'missingDevCount'.
'disks' keys a dict of Dev named tuples index by their by-id names, while
'label' and 'uuid' keys are for strings. 'hasMissingDev' is Boolean and
defaults to False. 'fullDevCount' is taken from the "Total devices" line.
'missingDevCount' is derived from fullDevCount - attached devs count.
"""
dpath = get_device_path(disk)
cmd = [BTRFS, "fi", "show", "--raw", dpath]
o, e, rc = run_command(cmd)
# Label: 'rockstor_rockstor' uuid: be5d2c5a-cc86-4c9a-96da-0a2add43f079
# Total devices 1 FS bytes used 2465906688
# devid 1 size 14935916544 used 5406457856 path /dev/sda3
pool_info = {
"disks": {},
"hasMissingDev": False,
"fullDevCount": 0,
"missingDevCount": 0,
}
full_dev_count = 0 # Number of devices in non degraded state.
attached_dev_count = 0 # Number of currently attached devices.
for l in o:
if re.match("Label", l) is not None:
fields = l.split()
pool_info["uuid"] = fields[3]
pool_info["label"] = fields[1].strip("'")
elif re.match("\tdevid", l) is not None:
# We have a line starting with <tab>devid, extract the temp_name,
# devid, is_byid, size, and used. Collect in a named tuple.
# We convert name into the db Disk.name by-id format so that our
# caller can locate a drive and update it's pool field reference.
attached_dev_count += 1
# Express device info line as a list of line elements.
fields = l.split()
temp_name = fields[-1]
dev_byid, is_byid = get_dev_byid_name(temp_name, remove_path=True)
devid = fields[1]
size = int(fields[3]) / 1024 # Bytes to KB
allocated = int(fields[5]) / 1024 # Bytes to KB
dev_info = Dev(
temp_name=temp_name,
is_byid=is_byid,
devid=devid,
size=size,
allocated=allocated,
)
pool_info["disks"][dev_byid] = dev_info
elif re.match("\tTotal devices", l) is not None:
fields = l.split()
full_dev_count = int(fields[2])
elif re.match("\t\*\*\* Some devices missing", l) is not None:
pool_info["hasMissingDev"] = True
pool_info["fullDevCount"] = full_dev_count
pool_info["missingDevCount"] = full_dev_count - attached_dev_count
# logger.debug('get_pool_info() returning {}'.format(pool_info))
return pool_info
def get_pool_raid_levels(mnt_pt):
o, e, rc = run_command([BTRFS, "fi", "df", mnt_pt])
# data, system, metadata, globalreserve
raid_d = {}
for l in o:
fields = l.split()
if len(fields) > 1:
block = fields[0][:-1].lower()
raid = fields[1][:-1].lower()
if block not in raid_d:
raid_d[block] = raid
return raid_d
def get_pool_raid_profile(raid_levels):
"""
Abstracts raid_levels from get_pool_raid_levels(mnt_pt) to a Rockstor raid Profile.
See PROFILES const.
:param raid_levels: dict returned by get_pool_raid_levels()
:return: a PROFILE index.
"""
# dict.get returns None if key not found.
data_raid = raid_levels.get("data")
metadata_raid = raid_levels.get("metadata")
raid_profile = "unknown"
if data_raid is None or metadata_raid is None:
return raid_profile
if data_raid == metadata_raid:
raid_profile = data_raid
else:
# Post Python >= 3.9 use removeprefix("raid")
if metadata_raid.startswith("raid"): # 4 characters
raid_profile = data_raid + "-" + metadata_raid[4:]
else:
raid_profile = data_raid + "-" + metadata_raid
if raid_profile not in PROFILE:
return "unknown"
return raid_profile
def cur_devices(mnt_pt):
"""
When given a btrfs mount point a list containing the full path of all
devices is generated by wrapping the btrfs fi show <mnt_pt> command and
parsing the devid line.
Used by resize_pool() to ascertain membership status of a device in a pool
:param mnt_pt: btrfs mount point
:return: list containing the current reported devices associated with a
btrfs mount point in by-id (with full path) format.
"""
dev_list_byid = []
o, e, rc = run_command([BTRFS, "fi", "show", mnt_pt])
for l in o:
l = l.strip()
if re.match("devid ", l) is not None:
# The following extracts the devices from the above command output,
# ie /dev/sda type names, but these are transient and we use their
# by-id type counterparts in the db and our logging hence the
# call to convert the 'now' names to by-id type names.
# N.B. As opposed to get_pool_info we want to preserve the path as
# our caller expects this full path format.
dev_byid, is_byid = get_dev_byid_name(l.split()[-1])
dev_list_byid.append(dev_byid)
return dev_list_byid
def resize_pool_cmd(pool, dev_list_byid, add=True):
"""
Given a pool and list of device names, returns the appropriate cmd of type:
"btrfs <device list> add(default)/delete root_mnt_pt(pool)", or returns
None if a disk member sanity check fails: ie if all the supplied devices
are either, not pool members (when deleting) or are already pool members
(when adding). If any device in the supplied dev_list fails this test then
no command is generated and None is returned.
:param pool: btrfs pool object
:param dev_list_byid: by-id device list to add/delete (without paths).
:param add: when true (default) or not specified then 'device add'
dev_list devices to pool, when specified as True 'device delete'
dev_list devices from pool.
:return: appropriate btrfs command, or None if member sanity checks failed.
"""
if pool.has_missing_dev and not add:
if dev_list_byid == []:
dev_list_byid = ["missing"]
else:
# list has at least a single element
# substiture 'missing' for any member matching 'detached-'
dev_list_byid = [
"missing"
if re.match("detached-", dev) is not None
else get_device_path(dev)
for dev in dev_list_byid
]
else:
dev_list_byid = [get_device_path(dev) for dev in dev_list_byid]
root_mnt_pt = mount_root(pool)
cur_dev = cur_devices(root_mnt_pt)
resize_flag = "add"
if not add:
resize_flag = "delete"
resize_cmd = [BTRFS, "device", resize_flag]
# Until we verify that all devices are or are not already members of the
# given pool, depending on if we are adding (default) or removing
# (add=False), we set our resize flag to false.
resize = False
# TODO: This test looks to pass if only one member passes. Revisit.
# TODO: But we are after a fail if only one member fails.
for d in dev_list_byid:
if (resize_flag == "add" and (d not in cur_dev)) or (
resize_flag == "delete" and ((d in cur_dev) or d == "missing")
):
resize = True # Basic disk member of pool sanity check passed.
resize_cmd.append(d)
if not resize:
logger.debug(
"Resize pool - member sanity check failed. "
"Retuning None as btrfs add/delete command."
)
return None
resize_cmd.append(root_mnt_pt)
return resize_cmd
def mount_root(pool):
"""
Mounts a given pool at the default mount root (usually /mnt2/) using the
pool.name as the final path entry. Ie pool.name = test-pool will be mounted
at /mnt2/test-pool. Any mount options held in pool.mnt_options will be
added to the mount command via the -o option as will a compress =
pool.compression entry.
If the pool concerned has root.role == "root" (i.e. it's the system pool), there are
2 possible mount variants; depending on default_subvol().boot_to_snap:
Boot to snap True: add "subvol=/@" and mount as per normal data pools at /mnt2/ROOT
Boot to snap False: use the existing fstab managed mount at "/", ie no /mnt2/ROOT.
N.B. Initially the mount target is defined by /dev/disk/by-label/pool.name,
if this fails then an attempt to mount by each member of
/dev/disk/by-id/pool.disk_set.all() but only if there are any members.
If this second method also fails then an exception is raised, currently all
but the last failed mount by device name is logged. If no disk members were
reported by pool.disk_set.count() a separate Exception is raised.
:param pool: pool object
:return: either the relevant mount point or an Exception which either
indicates 'no disks in pool' or 'Unknown Reason'
"""
root_pool_mnt = pool.mnt_pt
if pool.is_mounted:
return root_pool_mnt
# Creates a directory to act as the mount point.
create_tmp_dir(root_pool_mnt)
toggle_path_rw(root_pool_mnt, rw=False)
mnt_device = "/dev/disk/by-label/{}".format(pool.name)
mnt_cmd = [MOUNT, mnt_device, root_pool_mnt]
mnt_options = ""
if pool.mnt_options is not None:
mnt_options = pool.mnt_options
if pool.compression is not None:
if re.search("compress", mnt_options) is None:
mnt_options = "{},compress={}".format(mnt_options, pool.compression)
if pool.role == "root" and root_pool_mnt != "/": # boot-to-snap - See pool model
mnt_options = "{},subvol=/@".format(mnt_options)
# Prior to a mount by label attempt we call btrfs device scan on all
# members of our pool. This call ensures btrfs has up-to-date info on
# the relevant devices and avoids the potential overkill of a system wide
# call such as is performed in the rockstor-bootstrap service on boot.
# Disk.target_name ensures we observe any redirect roles.
device_scan([dev.target_name for dev in pool.disk_set.attached()])
if os.path.exists(mnt_device):
if len(mnt_options) > 0:
mnt_cmd.extend(["-o", mnt_options])
run_command(mnt_cmd)
return root_pool_mnt
# If we cannot mount by-label, let's try mounting by device; one by one
# until we get our first success. All devices known to our pool object
# have already been scanned prior to our mount by label attempt above.
if pool.disk_set.count() < 1:
raise Exception(
"Cannot mount Pool({}) as it has no disks in it.".format(pool.name)
)
last_device = pool.disk_set.attached().last()
logger.info("Mount by label ({}) failed.".format(mnt_device))
for device in pool.disk_set.attached():
mnt_device = get_device_path(device.target_name)
logger.info("Attempting mount by device ({}).".format(mnt_device))
if os.path.exists(mnt_device):
mnt_cmd = [MOUNT, mnt_device, root_pool_mnt]
if len(mnt_options) > 0:
mnt_cmd.extend(["-o", mnt_options])
try:
run_command(mnt_cmd)
return root_pool_mnt
except Exception as e:
if device.name == last_device.name:
# exhausted mounting using all devices in the pool
raise e
logger.error(
"Error mounting: {}. "
"Will try using another device.".format(mnt_cmd)
)
logger.exception(e)
else:
logger.error("Device ({}) was not found".format(mnt_device))
raise Exception(
"Failed to mount Pool({}) due to an unknown reason. "
"Command used {}".format(pool.name, mnt_cmd)
)
def umount_root(root_pool_mnt):
if not os.path.exists(root_pool_mnt):
return
try:
o, e, rc = run_command([UMOUNT, "-l", root_pool_mnt])
except CommandException as ce:
if ce.rc == 32:
for l in ce.err:
l = l.strip()
if re.search("not mounted$", l) is not None:
return
raise ce
for i in range(20):
if not is_mounted(root_pool_mnt):
toggle_path_rw(root_pool_mnt, rw=True)
run_command([RMDIR, root_pool_mnt])
return
time.sleep(2)
run_command([UMOUNT, "-f", root_pool_mnt])
toggle_path_rw(root_pool_mnt, rw=True)
run_command([RMDIR, root_pool_mnt])
return
def is_subvol(mnt_pt):
"""
Simple wrapper around "btrfs subvolume show mnt_pt"
:param mnt_pt: mount point of subvolume to query
:return: True if subvolume mnt_pt exists, else False
"""
show_cmd = [BTRFS, "subvolume", "show", mnt_pt]
# Throw=False on run_command to silence CommandExceptions.
o, e, rc = run_command(show_cmd, throw=False)
if rc == 0:
return True
return False
def subvol_info(mnt_pt):
info = {}
o, e, rc = run_command([BTRFS, "subvolume", "show", mnt_pt], throw=False)
if rc == 0:
for i in o:
fields = i.strip().split(":")
if len(fields) > 1:
info[fields[0].strip()] = fields[1].strip()
return info
def add_share(pool, share_name, qid):
"""
Wrapper for 'btrfs subvol create' pool_mnt/share_name that will contextually also
include a Rockstor native qgroup option, e.g. '-i 2015/6', if our -1/-1 flag value
for quotas disabled is not found.
A Rockstor 'share' is a btrfs 'subvolume'.
:param pool: pool object
:param share_name: string for proposed share (btrfs subvol) name.
:return run_command(generated_command) or True if given pool subvol already exists.
"""
root_pool_mnt = mount_root(pool)
subvol_mnt_pt = root_pool_mnt + "/" + share_name
# Ensure our root_pool_mnt is not immutable, see: remove_share()
toggle_path_rw(root_pool_mnt, rw=True)
if not is_subvol(subvol_mnt_pt):
if qid == PQGROUP_DEFAULT: # Quotas disabled
sub_vol_cmd = [BTRFS, "subvolume", "create", subvol_mnt_pt]
else:
sub_vol_cmd = [BTRFS, "subvolume", "create", "-i", qid, subvol_mnt_pt]
return run_command(sub_vol_cmd)
return True
def mount_share(share, mnt_pt):
# TODO: Consider making mnt_pt optional as per helper_mount_share() as then
# TODO: we could remove almost system wide many duplicates of temp mnt_pt
# TODO: created just prior and only for this methods call.
if is_mounted(mnt_pt):
return
mount_root(share.pool)
pool_device = get_device_path(share.pool.disk_set.attached().first().target_name)
qgroup = share.qgroup
# share.qgroup = "0/subvolid" use for subvol reference as more
# flexible than "subvol=share.subvol_name" (prior method).
subvol_str = "subvolid={}".format(qgroup[2:])
create_tmp_dir(mnt_pt)
toggle_path_rw(mnt_pt, rw=False)
mnt_cmd = [MOUNT, "-t", "btrfs", "-o", subvol_str, pool_device, mnt_pt]
return run_command(mnt_cmd)
def mount_snap(share, snap_name, snap_qgroup, snap_mnt=None):
pool_device = get_device_path(share.pool.disk_set.attached().first().target_name)
share_path = share.mnt_pt
rel_snap_path = ".snapshots/{}/{}".format(share.name, snap_name)
snap_path = "{}/{}".format(share.pool.mnt_pt, rel_snap_path).replace("//", "/")
if snap_mnt is None:
snap_mnt = "{}/.{}".format(share_path, snap_name)
if is_mounted(snap_mnt):
return
mount_share(share, share_path)
if is_subvol(snap_path):
create_tmp_dir(snap_mnt)
# snap_qgroup = "0/subvolid" use for subvol reference as more
# flexible than "subvol=rel_snap_path" (prior method).
subvol_str = "subvolid={}".format(snap_qgroup[2:])
return run_command([MOUNT, "-o", subvol_str, pool_device, snap_mnt], log=True)
def default_subvol():
"""
Returns the default vol/subvol id, path, and boot_to_snap boolean for /, used by
system-rollback/boot-to-snapshot.
If not set this ID = 5 i.e. the top level of the volume.
Works by parsing the output from 'btrfs subvol get-default /':
not set (default):
ID 5 (FS_TREE)
no system rollback enabled:
ID 257 gen 5796 top level 5 path @
or another example of the same:
ID 256 gen 2858 top level 5 path @
root configured for snapshots/rollback (default before any rollbacks):
ID 268 gen 2345 top level 267 path @/.snapshots/1/snapshot
and after having rolled back this can look like the following:
ID 456 gen 24246 top level 258 path @/.snapshots/117/snapshot
"""
cmd = [BTRFS, "subvolume", "get-default", "/"]
out, e, rc = run_command(cmd, throw=False)
if rc == 0 and len(out) > 0:
# we have no run error and at least one line of output
line_list = out[0].split()
return DefaultSubvol(
id=line_list[1],
path=line_list[-1], # N.B. can return ("5", "FS_TREE")
boot_to_snap=(line_list[-1] != "@" and line_list[-1] != "(FS_TREE)"),
)
logger.exception(e)
raise e
def snapshot_idmap(pool_mnt_pt):
"""
Executes 'btrfs subvol list -s pool_mnt_pt' and parses the result. Returns
a map/dictionary with snapshot id as key and it's path (relative to
pool_mnt_pt) as value, ie with the 'home' subvol having a snapshot:
'ID 286 gen 43444 cgen 43444 top le [...] path .snapshots/home/home-snap-1'
we return = {'286': '.snapshots/home/home-snap-1'}
:param pool_mnt_pt: Pool (vol) mount point.
:return: Dict of relative snapshot paths indexed by their subvol id.
"""
out, e, rc = run_command([BTRFS, "subvolume", "list", "-s", pool_mnt_pt])
snap_idmap = {}
for line in out:
if re.match("ID ", line) is not None:
fields = line.strip().split()
snap_idmap[fields[1]] = fields[-1].replace("@/", "", 1)
return snap_idmap
def shares_info(pool):
"""
Returns a dictionary of share/subvol names via passed pool mount point
lookup and using this to run "btrfs subvol list -s mnt_point" for snapshots
and "btrfs subvol list -p mnt_point" for all subvols including parent id.
N.B. Child snapshots and subvolumes are ignored but writable snapshots that
are immediate children of a pool (vol) are not ignored and regarded as
shares in their own right (a Share 'clone' in Rockstor parlance).
:param pool: Pool object
:return: dictionary indexed by share/subvol names found directly under
Pool.name. Indexed values are share/subvol qgroup ie "0/266" see
Share.qgroup model definition.
"""
try:
pool_mnt_pt = mount_root(pool)
except CommandException as e:
if e.rc == 32:
# mount failed, so we just assume that something has gone wrong at
# a lower level, like a device failure. Return empty share map.
# application state can be removed. If the low level failure is
# recovered, state gets reconstructed anyway.
return {}
raise
snap_idmap = snapshot_idmap(pool_mnt_pt)
default_id = default_subvol().id
o, e, rc = run_command([BTRFS, "subvolume", "list", "-p", pool_mnt_pt])
shares_d = {}
share_ids = []
for l in o:
if re.match("ID ", l) is None:
continue
fields = l.split()
if fields[-1] in SUBVOL_EXCLUDE:
logger.debug(
"Skipping system-wide excluded subvol: name=({}).".format(fields[-1])
)
continue
# Exclude root fs (in subvol) to avoid dependence on subvol name to
# root fs top level dir name collision for normal operation.
# And to expose root fs components that are themselves a subvol of
# the root fs subvol ie @ with subvol @/home as they are inherently
# more appropriate than the entire root fs anyway.
# temp
if pool.role == "root":
# Vol/subvol auto mounted if no subvol/subvolid options are used.
# Skipped to surface it's subvols as we only surface one layer.
# Relevant to system rollback by booting from snapshots.
if fields[-1] in ROOT_SUBVOL_EXCLUDE or fields[1] == default_id:
logger.debug("Skipping excluded subvol: name=({}).".format(fields[-1]))
continue
vol_id = fields[1]
if vol_id in snap_idmap:
# snapshot so check if is_clone:
s_name, writable, is_clone = parse_snap_details(
pool_mnt_pt, snap_idmap[vol_id]
)
if not is_clone:
continue
parent_id = fields[5]
if parent_id in share_ids:
# subvol of subvol. add it so child subvols can also be ignored.
share_ids.append(vol_id)
elif parent_id in snap_idmap and not parent_id == default_id:
# Boot to snapshot root pools are themselves a snapshot.
# snapshot/subvol of snapshot.
# add it so child subvols can also be ignored.
snap_idmap[vol_id] = fields[-1].replace("@/", "", 1)
else:
# Found subvol of pool or excluded subvol- storing for return.
# Non snapper root rollback config:
# ID 257 gen 5351 parent 5 top level 5 path @
# ID 296 gen 5338 parent 257 top level 257 path home
# When root is a snapper root rollback config we have:
# ID 257 gen 33 parent 5 top level 5 path @
# ID 264 gen 216 parent 257 top level 257 path @/home
# We have assumed the prior behaviour and as we mount the root pool
# vol/subvol via it's label we have /mnt2/ROOT not /mnt2/@.
# Remove '@/' from rel path if found ie '@/home' to 'home' as then
# pool+relative path works.
shares_d[fields[-1].replace("@/", "", 1)] = "0/{}".format(vol_id)
share_ids.append(vol_id)
return shares_d
def parse_snap_details(pool_mnt_pt, snap_rel_path):
"""
Returns a snapshot,s name or None if that snap is deemed to be a clone.
Clone (is_clone) = writable snapshot + direct child of pool_mnt_pt.
All calls also return writable, and is_clone booleans.
:param pool_mnt_pt: Pool (vol) mount point, ie: settings.MNT_PT/pool.name
:param snap_rel_path: Relative snapshot path .
:return: snap_name (None if clone), writable (Boolean), is_clone (Boolean)
Note: is_clone is redundant but serves as a convenience boolean.
"""
if pool_mnt_pt == "/":
full_snap_path = pool_mnt_pt + snap_rel_path
else:
full_snap_path = pool_mnt_pt + "/" + snap_rel_path
writable = not get_property(full_snap_path, "ro")
snap_name = None
is_clone = False
if writable and (len(snap_rel_path.split("/")) == 1):
# writable snapshot + direct child of pool = Rockstor clone.
is_clone = True # (leaving snap_name = None as not a snap but a clone)
else:
snap_name = snap_rel_path.split("/")[-1]
return snap_name, writable, is_clone
def snaps_info(pool_mnt_pt, share_name):
"""
Generates a dictionary of Rockstor relevant on-pool snapshots which do not
include clones. See parse_snap_details() for clone definition.
Works by analysing the varying output of differently optioned btrfs subvol
commands and parse_snap_details() to extract the snap name (from rel path)
and
:param pool_mnt_pt: Pool (vol) mount point, ie: settings.MNT_PT/pool.name
:param share_name: share/snap.name
:return: dict indexed by snap name with tuple values of:
(qgroup, writable) where qgroup = 0/subvolid and writable = Boolean.
"""
# -p = show parent ID, -u = uuid of subvol, -q = parent uuid of subvol
o, e, rc = run_command([BTRFS, "subvolume", "list", "-u", "-p", "-q", pool_mnt_pt])
subvol_id = share_uuid = None
for l in o:
if re.match("ID ", l) is not None:
fields = l.split()
if fields[-1].replace("@/", "", 1) == share_name:
subvol_id = fields[1]
share_uuid = fields[12]
if subvol_id is None:
return {}