-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathctree.py
2748 lines (2270 loc) · 102 KB
/
ctree.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) 2016 Hans van Kranenburg <hans@knorrie.org>
#
# This file is part of the python-btrfs module.
#
# python-btrfs is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# python-btrfs 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with python-btrfs. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains Python object representations for btrfs metadata items.
Additionally, the helper :class:`FileSystem` provides a convenient way to start
exploring an online btrfs filesystem.
"""
import btrfs
import collections.abc
import copy
import datetime
import os
import re
import struct
import uuid
U8_MAX = (1 << 8) - 1
ULLONG_MAX = (1 << 64) - 1
ULONG_MAX = (1 << 32) - 1
def U8(n):
"""
:param int n: Any number.
:returns: Unsigned 8 bit number.
:rtype: int
Example::
>>> btrfs.ctree.U8(64)
64
>>> btrfs.ctree.U8(-1)
255
>>> btrfs.ctree.U8(0x4000)
0
"""
return n & U8_MAX
def ULL(n):
"""
:param int n: Any number.
:returns: Unsigned 64 bit number.
:rtype: int
Example::
>>> btrfs.ctree.ULL(64)
64
>>> btrfs.ctree.ULL(-1)
18446744073709551615
>>> btrfs.ctree.ULL(0x4000)
16384
"""
return n & ULLONG_MAX
def _struct_format(s):
f = s.format
# Python <= 3.6 returns bytes, 3.7 returns str, yay.
if type(f) == bytes:
return f.decode('utf-8')
return f
ROOT_TREE_OBJECTID = 1 #: Root tree
EXTENT_TREE_OBJECTID = 2 #: Extent tree
CHUNK_TREE_OBJECTID = 3 #: Chunk tree
DEV_TREE_OBJECTID = 4 #: Device tree
FS_TREE_OBJECTID = 5 #: Top level subvolume tree
ROOT_TREE_DIR_OBJECTID = 6 #: Used in the root tree to store default subvolume information.
CSUM_TREE_OBJECTID = 7 #: Checksum tree
QUOTA_TREE_OBJECTID = 8 #: Quota tree
UUID_TREE_OBJECTID = 9 #: Subvolume UUID tree
FREE_SPACE_TREE_OBJECTID = 10 #: Free space tree
BLOCK_GROUP_TREE_OBJECTID = 11 #: Block group tree
DEV_STATS_OBJECTID = 0 #: Object ID of device statistics in the Device tree.
BALANCE_OBJECTID = ULL(-4) #: Object ID to store balance status. (-4)
ORPHAN_OBJECTID = ULL(-5) #: Object ID to store orphans that need cleaning. (-5)
TREE_LOG_OBJECTID = ULL(-6)
TREE_LOG_FIXUP_OBJECTID = ULL(-7)
TREE_RELOC_OBJECTID = ULL(-8)
DATA_RELOC_TREE_OBJECTID = ULL(-9)
EXTENT_CSUM_OBJECTID = ULL(-10) #: Object ID used for checksum items. (-10)
FREE_SPACE_OBJECTID = ULL(-11) #: Object ID for free space cache v1 items. (-11)
FREE_INO_OBJECTID = ULL(-12)
MULTIPLE_OBJECTIDS = ULL(-255)
FIRST_FREE_OBJECTID = 256 #: First available Object ID for subvolume trees.
LAST_FREE_OBJECTID = ULL(-256) #: Last available Object ID for subvolume trees. (-256)
FIRST_CHUNK_TREE_OBJECTID = 256 #: Object ID for Chunk objects in the Chunk tree.
DEV_ITEMS_OBJECTID = 1 #: Object ID for Device items in the Device tree.
INODE_ITEM_KEY = 1 #: Key type used by :class:`InodeItem`
INODE_REF_KEY = 12 #: Key type used by :class:`InodeRefList`
INODE_EXTREF_KEY = 13 # Key type used by :class:`InodeExtrefList(`
XATTR_ITEM_KEY = 24 #: Key type used by :class:`XAttrItemList`
ORPHAN_ITEM_KEY = 48 #: Key type used to track orphaned roots.
DIR_LOG_ITEM_KEY = 60
DIR_LOG_INDEX_KEY = 72
DIR_ITEM_KEY = 84 #: Key type used by :class:`DirItemList`
DIR_INDEX_KEY = 96 #: Key type used by :class:`DirIndex`
EXTENT_DATA_KEY = 108 #: Key type used by :class:`FileExtentItem`
EXTENT_CSUM_KEY = 128 #: Key type used for checksum items.
ROOT_ITEM_KEY = 132 #: Key type used by :class:`RootItem`
ROOT_BACKREF_KEY = 144
ROOT_REF_KEY = 156 #: Key type used by :class:`RootRef`
EXTENT_ITEM_KEY = 168 #: Key type used by :class:`ExtentItem`
METADATA_ITEM_KEY = 169 #: Key type used by :class:`MetaDataItem`
TREE_BLOCK_REF_KEY = 176 #: Key type used by :class:`TreeBlockRef`
EXTENT_DATA_REF_KEY = 178 #: Key type used by :class:`ExtentDataRef`
SHARED_BLOCK_REF_KEY = 182 #: Key type used by :class:`SharedBlockRef`
SHARED_DATA_REF_KEY = 184 #: Key type used by :class:`SharedDataRef`
BLOCK_GROUP_ITEM_KEY = 192 #: Key type used by :class:`BlockGroupItem`
FREE_SPACE_INFO_KEY = 198 #: Key type used by :class:`FreeSpaceInfo`
FREE_SPACE_EXTENT_KEY = 199 #: Key type used by :class:`FreeSpaceExtent`
FREE_SPACE_BITMAP_KEY = 200 #: Key type used by :class:`FreeSpaceBitmap`
DEV_EXTENT_KEY = 204 #: Key type used by :class:`DevExtent`
DEV_ITEM_KEY = 216 #: Key type used by :class:`DevItem`
CHUNK_ITEM_KEY = 228 #: Key type used by :class:`Chunk`
QGROUP_STATUS_KEY = 240
QGROUP_INFO_KEY = 242
QGROUP_LIMIT_KEY = 244
QGROUP_RELATION_KEY = 246
BALANCE_ITEM_KEY = 248 #: Balance status item key. Replaced by `TEMPORARY_ITEM_KEY`.
TEMPORARY_ITEM_KEY = 248 #: Key for various short term persistent stored items.
DEV_STATS_KEY = 249 #: Device statistics key. Replaced by `PERSISTENT_ITEM_KEY`.
PERSISTENT_ITEM_KEY = 249 #: Key for various long term persistent stored items.
DEV_REPLACE_KEY = 250
UUID_KEY_SUBVOL = 251
UUID_KEY_RECEIVED_SUBVOL = 252
STRING_ITEM_KEY = 253
BLOCK_GROUP_SINGLE = 0 #: Block Group single type. Does not exist in kernel code.
BLOCK_GROUP_DATA = 1 << 0 #: Block Group DATA type.
BLOCK_GROUP_SYSTEM = 1 << 1 #: Block Group SYSTEM type.
BLOCK_GROUP_METADATA = 1 << 2 #: Block Group METADATA type.
BLOCK_GROUP_RAID0 = 1 << 3 #: Block Group RAID0 profile.
BLOCK_GROUP_RAID1 = 1 << 4 #: Block Group RAID1 profile.
BLOCK_GROUP_DUP = 1 << 5 #: Block Group DUP profile.
BLOCK_GROUP_RAID10 = 1 << 6 #: Block Group RAID10 profile.
BLOCK_GROUP_RAID5 = 1 << 7 #: Block Group RAID5 profile.
BLOCK_GROUP_RAID6 = 1 << 8 #: Block Group RAID6 profile.
BLOCK_GROUP_RAID1C3 = 1 << 9 #: Block Group RAID1C3 profile.
BLOCK_GROUP_RAID1C4 = 1 << 10 #: Block Group RAID1C4 profile.
BLOCK_GROUP_TYPE_MASK = (
BLOCK_GROUP_DATA |
BLOCK_GROUP_SYSTEM |
BLOCK_GROUP_METADATA
) #: All Block Group type bits (data, system, metadata).
BLOCK_GROUP_PROFILE_MASK = (
BLOCK_GROUP_RAID0 |
BLOCK_GROUP_RAID1 |
BLOCK_GROUP_RAID1C3 |
BLOCK_GROUP_RAID1C4 |
BLOCK_GROUP_RAID5 |
BLOCK_GROUP_RAID6 |
BLOCK_GROUP_DUP |
BLOCK_GROUP_RAID10
) #: All Block Group profile bits (raid1, dup, etc...).
AVAIL_ALLOC_BIT_SINGLE = 1 << 48 # used in balance_args
SPACE_INFO_GLOBAL_RSV = 1 << 49
_block_group_flags_str_map = {
BLOCK_GROUP_DATA: 'DATA',
BLOCK_GROUP_METADATA: 'METADATA',
BLOCK_GROUP_SYSTEM: 'SYSTEM',
BLOCK_GROUP_RAID0: 'RAID0',
BLOCK_GROUP_RAID1: 'RAID1',
BLOCK_GROUP_DUP: 'DUP',
BLOCK_GROUP_RAID10: 'RAID10',
BLOCK_GROUP_RAID5: 'RAID5',
BLOCK_GROUP_RAID6: 'RAID6',
BLOCK_GROUP_RAID1C3: 'RAID1C3',
BLOCK_GROUP_RAID1C4: 'RAID1C4',
}
_balance_args_profiles_str_map = {
BLOCK_GROUP_RAID0: 'RAID0',
BLOCK_GROUP_RAID1: 'RAID1',
BLOCK_GROUP_DUP: 'DUP',
BLOCK_GROUP_RAID10: 'RAID10',
BLOCK_GROUP_RAID5: 'RAID5',
BLOCK_GROUP_RAID6: 'RAID6',
BLOCK_GROUP_RAID1C3: 'RAID1C3',
BLOCK_GROUP_RAID1C4: 'RAID1C4',
AVAIL_ALLOC_BIT_SINGLE: 'SINGLE',
}
QGROUP_LEVEL_SHIFT = 48
EXTENT_FLAG_DATA = 1 << 0
EXTENT_FLAG_TREE_BLOCK = 1 << 1
BLOCK_FLAG_FULL_BACKREF = 1 << 8
_extent_flags_str_map = {
EXTENT_FLAG_DATA: 'DATA',
EXTENT_FLAG_TREE_BLOCK: 'TREE_BLOCK',
BLOCK_FLAG_FULL_BACKREF: 'FULL_BACKREF',
}
INODE_NODATASUM = 1 << 0
INODE_NODATACOW = 1 << 1
INODE_READONLY = 1 << 2
INODE_NOCOMPRESS = 1 << 3
INODE_PREALLOC = 1 << 4
INODE_SYNC = 1 << 5
INODE_IMMUTABLE = 1 << 6
INODE_APPEND = 1 << 7
INODE_NODUMP = 1 << 8
INODE_NOATIME = 1 << 9
INODE_DIRSYNC = 1 << 10
INODE_COMPRESS = 1 << 11
INODE_ROOT_ITEM_INIT = 1 << 31
_inode_flags_str_map = {
INODE_NODATASUM: 'NODATASUM',
INODE_NODATACOW: 'NODATACOW',
INODE_READONLY: 'READONLY',
INODE_NOCOMPRESS: 'NOCOMPRESS',
INODE_PREALLOC: 'PREALLOC',
INODE_SYNC: 'SYNC',
INODE_IMMUTABLE: 'IMMUTABLE',
INODE_APPEND: 'APPEND',
INODE_NODUMP: 'NODUMP',
INODE_NOATIME: 'NOATIME',
INODE_DIRSYNC: 'DIRSYNC',
INODE_COMPRESS: 'COMPRESS',
INODE_ROOT_ITEM_INIT: 'ROOT_ITEM_INIT',
}
ROOT_SUBVOL_RDONLY = 1 << 0
_root_flags_str_map = {
ROOT_SUBVOL_RDONLY: 'RDONLY',
}
FT_UNKNOWN = 0
FT_REG_FILE = 1
FT_DIR = 2
FT_CHRDEV = 3
FT_BLKDEV = 4
FT_FIFO = 5
FT_SOCK = 6
FT_SYMLINK = 7
FT_XATTR = 8
FT_MAX = 9
_dir_item_type_str_map = {
FT_UNKNOWN: 'UNKNOWN',
FT_REG_FILE: 'FILE',
FT_DIR: 'DIR',
FT_CHRDEV: 'CHRDEV',
FT_BLKDEV: 'BLKDEV',
FT_FIFO: 'FIFO',
FT_SOCK: 'SOCK',
FT_SYMLINK: 'SYMLINK',
FT_XATTR: 'XATTR',
}
COMPRESS_NONE = 0
COMPRESS_ZLIB = 1
COMPRESS_LZO = 2
COMPRESS_ZSTD = 3
_compress_type_str_map = {
COMPRESS_NONE: 'none',
COMPRESS_ZLIB: 'zlib',
COMPRESS_LZO: 'lzo',
COMPRESS_ZSTD: 'zstd',
}
FILE_EXTENT_INLINE = 0
FILE_EXTENT_REG = 1
FILE_EXTENT_PREALLOC = 2
_file_extent_type_str_map = {
FILE_EXTENT_INLINE: 'inline',
FILE_EXTENT_REG: 'regular',
FILE_EXTENT_PREALLOC: 'prealloc',
}
FREE_SPACE_USING_BITMAPS = 1
_free_space_info_flags_str_map = {
FREE_SPACE_USING_BITMAPS: 'bitmaps',
}
def qgroup_level(objectid):
"""Helper to get qgroup level from a qgroup relation objectid.
:param int objectid: 64-bit object ID field.
:returns: qgroup level.
:rtype: int
"""
return objectid >> QGROUP_LEVEL_SHIFT
def qgroup_subvid(objectid):
"""Helper to get qgroup subvolume ID from a qgroup relation objectid.
:param int objectid: 64-bit object ID field.
:returns: qgroup subvolume ID.
:rtype: int
"""
return objectid & ((1 << QGROUP_LEVEL_SHIFT) - 1)
def _qgroup_objectid(level, subvid):
return (level << QGROUP_LEVEL_SHIFT) + subvid
_key_objectid_str_map = {
ROOT_TREE_OBJECTID: 'ROOT_TREE',
EXTENT_TREE_OBJECTID: 'EXTENT_TREE',
CHUNK_TREE_OBJECTID: 'CHUNK_TREE',
DEV_TREE_OBJECTID: 'DEV_TREE',
FS_TREE_OBJECTID: 'FS_TREE',
ROOT_TREE_DIR_OBJECTID: 'ROOT_TREE_DIR',
CSUM_TREE_OBJECTID: 'CSUM_TREE',
QUOTA_TREE_OBJECTID: 'QUOTA_TREE',
UUID_TREE_OBJECTID: 'UUID_TREE',
FREE_SPACE_TREE_OBJECTID: 'FREE_SPACE_TREE',
BLOCK_GROUP_TREE_OBJECTID: 'BLOCK_GROUP_TREE',
BALANCE_OBJECTID: 'BALANCE',
ORPHAN_OBJECTID: 'ORPHAN',
TREE_LOG_OBJECTID: 'TREE_LOG',
TREE_LOG_FIXUP_OBJECTID: 'TREE_LOG_FIXUP',
TREE_RELOC_OBJECTID: 'TREE_RELOC',
DATA_RELOC_TREE_OBJECTID: 'DATA_RELOC_TREE',
EXTENT_CSUM_OBJECTID: 'EXTENT_CSUM',
FREE_SPACE_OBJECTID: 'FREE_SPACE',
FREE_INO_OBJECTID: 'FREE_INO',
MULTIPLE_OBJECTIDS: 'MULTIPLE',
}
def _key_objectid_str(objectid, _type):
if _type == DEV_EXTENT_KEY:
return str(objectid)
if _type == QGROUP_RELATION_KEY:
return "{}/{}".format(qgroup_level(objectid), qgroup_subvid(objectid))
if _type == UUID_KEY_SUBVOL or _type == UUID_KEY_RECEIVED_SUBVOL:
return "0x{:0>16x}".format(objectid)
if objectid == ROOT_TREE_OBJECTID and _type == DEV_ITEM_KEY:
return 'DEV_ITEMS'
if objectid == DEV_STATS_OBJECTID and _type == PERSISTENT_ITEM_KEY:
return 'DEV_STATS'
if objectid == FIRST_CHUNK_TREE_OBJECTID and _type == CHUNK_ITEM_KEY:
return 'FIRST_CHUNK_TREE'
if objectid == ULLONG_MAX:
return '-1'
return _key_objectid_str_map.get(objectid, str(objectid))
_key_str_objectid_map = {v: k for k, v in _key_objectid_str_map.items()}
_key_str_objectid_map.update({
'DEV_ITEMS': ROOT_TREE_OBJECTID,
'DEV_STATS': DEV_STATS_OBJECTID,
'FIRST_CHUNK_TREE': FIRST_CHUNK_TREE_OBJECTID,
})
_re_qgroup_objectid = re.compile(r'^(?P<level>\d+)/(?P<subvid>\d+)$')
def _key_str_objectid(objectid_str, _type):
# is it just a number?
try:
objectid = int(objectid_str)
if objectid > -256 and objectid <= ULLONG_MAX:
return objectid
except ValueError:
pass
# is it known text?
if objectid_str in _key_str_objectid_map:
return _key_str_objectid_map[objectid_str]
# is it a qgroup identifier?
if _type in (QGROUP_RELATION_KEY, QGROUP_INFO_KEY, QGROUP_LIMIT_KEY):
match = _re_qgroup_objectid.match(objectid_str)
if match is not None:
return _qgroup_objectid(**match.groupdict())
else:
raise ValueError("Unparseable key objectid {} for qgroup type {}".format(
objectid_str, _key_type_str(_type)))
# is it some UUID hex string?
if objectid_str.startswith('0x'):
try:
return int(objectid_str, 0)
except Exception:
pass
# otherwise, we don't know
raise ValueError("Unparseable key objectid {}".format(objectid_str))
_key_type_str_map = {
INODE_ITEM_KEY: 'INODE_ITEM',
INODE_REF_KEY: 'INODE_REF',
INODE_EXTREF_KEY: 'INODE_EXTREF',
XATTR_ITEM_KEY: 'XATTR_ITEM',
ORPHAN_ITEM_KEY: 'ORPHAN_ITEM',
DIR_LOG_ITEM_KEY: 'DIR_LOG_ITEM',
DIR_LOG_INDEX_KEY: 'DIR_LOG_INDEX',
DIR_ITEM_KEY: 'DIR_ITEM',
DIR_INDEX_KEY: 'DIR_INDEX',
EXTENT_DATA_KEY: 'EXTENT_DATA',
EXTENT_CSUM_KEY: 'EXTENT_CSUM',
ROOT_ITEM_KEY: 'ROOT_ITEM',
ROOT_BACKREF_KEY: 'ROOT_BACKREF',
ROOT_REF_KEY: 'ROOT_REF',
EXTENT_ITEM_KEY: 'EXTENT_ITEM',
METADATA_ITEM_KEY: 'METADATA_ITEM',
TREE_BLOCK_REF_KEY: 'TREE_BLOCK_REF',
EXTENT_DATA_REF_KEY: 'EXTENT_DATA_REF',
SHARED_BLOCK_REF_KEY: 'SHARED_BLOCK_REF',
SHARED_DATA_REF_KEY: 'SHARED_DATA_REF',
BLOCK_GROUP_ITEM_KEY: 'BLOCK_GROUP_ITEM',
FREE_SPACE_INFO_KEY: 'FREE_SPACE_INFO',
FREE_SPACE_EXTENT_KEY: 'FREE_SPACE_EXTENT',
FREE_SPACE_BITMAP_KEY: 'FREE_SPACE_BITMAP',
DEV_EXTENT_KEY: 'DEV_EXTENT',
DEV_ITEM_KEY: 'DEV_ITEM',
CHUNK_ITEM_KEY: 'CHUNK_ITEM',
QGROUP_STATUS_KEY: 'QGROUP_STATUS',
QGROUP_INFO_KEY: 'QGROUP_INFO',
QGROUP_LIMIT_KEY: 'QGROUP_LIMIT',
QGROUP_RELATION_KEY: 'QGROUP_RELATION',
DEV_REPLACE_KEY: 'DEV_REPLACE',
UUID_KEY_SUBVOL: 'UUID_KEY_SUBVOL',
UUID_KEY_RECEIVED_SUBVOL: 'UUID_KEY_RECEIVED_SUBVOL',
STRING_ITEM_KEY: 'STRING_ITEM',
TEMPORARY_ITEM_KEY: 'TEMPORARY_ITEM',
PERSISTENT_ITEM_KEY: 'PERSISTENT_ITEM',
}
def _key_type_str(_type):
return _key_type_str_map.get(_type, str(_type))
_key_str_type_map = {v: k for k, v in _key_type_str_map.items()}
def _key_str_type(type_str):
# is it just a number?
try:
type_ = int(type_str)
except ValueError:
pass
else:
if type_ >= -1 and type_ <= 255:
return type_
if type_str in _key_str_type_map:
return _key_str_type_map[type_str]
raise ValueError("Unknown key type {}".format(type_str))
def _key_offset_str(offset, _type):
if _type == QGROUP_RELATION_KEY or _type == QGROUP_INFO_KEY or _type == QGROUP_LIMIT_KEY:
return "{}/{}".format(qgroup_level(offset), qgroup_subvid(offset))
if _type == UUID_KEY_SUBVOL or _type == UUID_KEY_RECEIVED_SUBVOL:
return "0x{:0>16x}".format(offset)
if offset == ULLONG_MAX:
return '-1'
if _type == ROOT_ITEM_KEY:
return _key_objectid_str_map.get(offset, str(offset))
return str(offset)
def _key_str_offset(offset_str, _type):
# is it just a number?
try:
offset = int(offset_str)
except ValueError:
pass
else:
if offset >= -1 and offset <= ULLONG_MAX:
return offset
# is it a qgroup identifier?
if _type in (QGROUP_RELATION_KEY, QGROUP_INFO_KEY, QGROUP_LIMIT_KEY):
match = _re_qgroup_objectid.match(offset_str)
if match is not None:
return _qgroup_objectid(**{k: int(v) for k, v in match.groupdict().items()})
else:
raise ValueError("Unparseable key offset {} for qgroup type {}".format(
offset_str, _key_type_str(_type)))
# is it some UUID hex string?
if offset_str.startswith('0x'):
try:
return int(offset_str, 0)
except Exception:
pass
# otherwise, we don't know
raise ValueError("Unparseable key offset {}".format(offset_str))
class ItemNotFoundError(IndexError):
"""Helper exception for lookup convenience functions.
If a convenience function on a :class:`btrfs.ctree.FileSystem` object is
supposed to return exactly one object at a specific location, and no object
is found, this type of exception is raised.
An example is the :func:`~btrfs.ctree.FileSystem.block_group` helper, which
raises this error if no block group item is found at the exact specified
location.
"""
pass
KEY_MAX = (1 << 136) - 1
class Key(object):
r"""Btrfs metadata trees have a key space of 136-bit numbers.
A full 136-bit tree key is composed as:
(objectid << 72) + (type << 64) + offset
:param objectid: 64-bit object ID number or string representation.
:type objectid: Union[int, str]
:param type\_: 8-bit type number or string representation.
:type type\_: Union[int, str]
:param int offset: 64-bit offset number or string representation.
:type offset: Union[int, str]
Key objects support sorting and simple addition and subtraction. Also,
when subtracting 1 from a zero key, the value wraps around to the largest
value possible, vice versa.
Example::
>>> key1 = btrfs.ctree.Key(425, 'DIR_ITEM', 17818406)
>>> key1
Key(425, 84, 17818406)
>>> str(key1)
'(425 DIR_ITEM 17818406)'
>>> key2 = btrfs.ctree.Key(442, btrfs.ctree.EXTENT_DATA_KEY, 0)
>>> key2 > key1
True
>>> min_key = btrfs.ctree.Key(0, 0, 0)
>>> min_key
Key(0, 0, 0)
>>> str(min_key)
'(0 0 0)'
>>> min_key - 1
Key(18446744073709551615, 255, 18446744073709551615)
>>> str(min_key - 1)
'(-1 255 -1)'
The `-1` value in the string representation is just a convenience way to
write the maximum allowed number. The actual value for a 64 bit numer is
still 18446744073709551615, and for 8 bit that's 255 of course.
For example, when setting up a minimum and maximum key for a metadata
search, the arithmetic that can be done helps quickly defining the maximum
value. The next example shows the key range for finding all intormation
about an inode in a filesystem tree:
Example::
>>> inum = 31337
>>> min_key = btrfs.ctree.Key(inum, 0, 0)
>>> max_key = btrfs.ctree.Key(inum + 1, 0, 0) - 1
>>>
>>> min_key
Key(31337, 0, 0)
>>> max_key
Key(31337, 255, 18446744073709551615)
Last but not least, the utils module contains the helper function
:func:`~btrfs.utils.parse_key_string` to dissect a full text key string:
Example::
>>> btrfs.utils.parse_key_string('(535 EXTENT_DATA 0)')
Key(535, 108, 0)
"""
def __init__(self, objectid, type_, offset):
if isinstance(type_, int):
self._type = U8(type_)
elif isinstance(type_, str):
self._type = U8(_key_str_type(type_))
else:
raise ValueError("Key type needs to be either string or integer: {}.".format(type_))
if isinstance(objectid, int):
self._objectid = ULL(objectid)
elif isinstance(objectid, str):
self._objectid = ULL(_key_str_objectid(objectid, self._type))
else:
raise ValueError("Key objectid needs to be either string or integer: {}.".format(
objectid))
if isinstance(offset, int):
self._offset = ULL(offset)
elif isinstance(offset, str):
self._offset = ULL(_key_str_offset(offset, self._type))
else:
raise ValueError("Key offset needs to be either string or integer: {}.".format(
offset))
self._pack()
@property
def objectid(self):
"""Key Object ID"""
return self._objectid
@objectid.setter
def objectid(self, _objectid):
self._objectid = _objectid
self._pack()
@property
def type(self):
"""Key Type"""
return self._type
@type.setter
def type(self, _type):
self._type = _type
self._pack()
@property
def offset(self):
"""Key Offset"""
return self._offset
@offset.setter
def offset(self, _offset):
self._offset = _offset
self._pack()
@property
def key(self):
"""Full numeric 136-bit key value."""
return self._key
@key.setter
def key(self, _key):
self._key = _key & KEY_MAX
self._unpack()
def _pack(self):
self._key = (self.objectid << 72) + (self._type << 64) + self.offset
def _unpack(self):
self._objectid = ULL(self._key >> 72)
self._type = U8(self._key >> 64)
self._offset = ULL(self._key)
def __lt__(self, other):
if isinstance(other, Key):
return self._key < other._key
return self._key < other
def __le__(self, other):
if isinstance(other, Key):
return self._key <= other._key
return self._key <= other
def __eq__(self, other):
if isinstance(other, Key):
return self._key == other._key
return self._key == other
def __ge__(self, other):
if isinstance(other, Key):
return self._key >= other._key
return self._key >= other
def __gt__(self, other):
if isinstance(other, Key):
return self._key > other._key
return self._key > other
def __repr__(self):
return "Key({}, {}, {})".format(self._objectid, self._type, self._offset)
def __str__(self):
return "({} {} {})".format(
_key_objectid_str(self._objectid, self._type),
_key_type_str(self._type),
_key_offset_str(self._offset, self._type),
)
def __add__(self, amount):
new_key = copy.copy(self)
new_key.key += amount
return new_key
def __sub__(self, amount):
new_key = copy.copy(self)
new_key.key -= amount
return new_key
class DiskKey(Key):
"""Object representation of struct `btrfs_disk_key`.
Objects of this type are used in metadata search results.
"""
_disk_key = struct.Struct('<QBQ')
def __init__(self, data):
super(DiskKey, self).__init__(*DiskKey._disk_key.unpack_from(data))
class FileSystem(object):
"""The FileSystem object is a bit of a spider in the web of this library.
It contains a lot of convenience methods providing quick access to all
kinds of functionality.
:param str path: Path to the mounted filesystem.
:ivar str path: The filesystem path used to initialize this object.
:ivar uuid.UUID fsid: Filesystem ID.
:ivar int nodesize: B-tree node size (same as leaf size).
:ivar int sectorsize: Smallest allocatable block size in bytes for storing
data.
The fsid, nodesize and sectorsize values are cached from a call to
:func:`~btrfs.ctree.FileSystem.fs_info` when initializing the object.
It is highly recommended to use the built in context manager. Doing so
prevents leaking the internal open file descriptor.
Example::
>>> with btrfs.ctree.FileSystem('/') as fs:
... print(fs.top_level().generation)
...
3382004
"""
def __init__(self, path):
self.path = path
self.fd = os.open(path, os.O_RDONLY)
_fs_info = self.fs_info()
self.fsid = _fs_info.fsid
self.nodesize = _fs_info.nodesize
self.sectorsize = _fs_info.sectorsize
self._block_group_tree = self.features().compat_ro_flags & \
btrfs.ioctl.FEATURE_COMPAT_RO_BLOCK_GROUP_TREE != 0
def __enter__(self):
return self
def fs_info(self):
"""
:returns: General filesystem information.
:rtype: :class:`btrfs.ioctl.FsInfo`
"""
return btrfs.ioctl.fs_info(self.fd)
def dev_info(self, devid):
"""
:param int devid: Device ID.
:returns: Device information.
:rtype: :class:`btrfs.ioctl.DevInfo`
"""
return btrfs.ioctl.dev_info(self.fd, devid)
def dev_stats(self, devid, reset=False):
"""
:param int devid: Device ID.
:param bool reset: Reset device error counters to zero.
:returns: Device statistics.
:rtype: :class:`btrfs.ioctl.DevStats`
"""
return btrfs.ioctl.dev_stats(self.fd, devid, reset)
def space_info(self):
"""
:returns: Space information
:rtype: List[:class:`btrfs.ioctl.SpaceInfo`]
"""
return btrfs.ioctl.space_info(self.fd)
def search(self, tree, min_key=None, max_key=None):
"""
Retrieve all metadata items within a specific range. This is basically
a thin wrapper around the :func:`~btrfs.ioctl.search_v2` with a bit
limited functionality, but suited for almost all use cases when quickly
searching around.
:param int tree: The metadata tree we're searching in.
:param btrfs.ctree.Key min_key: Minimum key value for items to return.
:param btrfs.ctree.Key max_key: Maximum key value for items to return.
:returns: Any metadata item found in the search range, as sub class of
:class:`~btrfs.ctree.ItemData`, helped by the
:func:`btrfs.ctree.classify` function.
:rtype: Iterator[:class:`~btrfs.ctree.ItemData`]
"""
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key):
yield btrfs.ctree.classify(header, data)
def devices(self, min_devid=1, max_devid=ULLONG_MAX):
"""
:param int min_devid: Lowest Device ID to search for.
:param int max_devid: Highest Device ID to search for.
:returns: Device Items from the Chunk tree.
:rtype: Iterator[:class:`~btrfs.ctree.DevItem`]
"""
tree = CHUNK_TREE_OBJECTID
min_key = Key(DEV_ITEMS_OBJECTID, DEV_ITEM_KEY, min_devid)
max_key = Key(DEV_ITEMS_OBJECTID, DEV_ITEM_KEY, max_devid)
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key):
yield DevItem(header, data)
def chunks(self, min_vaddr=0, max_vaddr=ULLONG_MAX, nr_items=None):
"""
:param int min_vaddr: Lowest virtual address to search for.
:param int max_vaddr: Highest virtual address to search for.
:param int nr_items: Maximum amount of items to return. Defaults to no limit.
:returns: Chunk items from the Chunk tree.
:rtype: Iterator[:class:`~btrfs.ctree.Chunk`]
"""
tree = CHUNK_TREE_OBJECTID
min_key = Key(FIRST_CHUNK_TREE_OBJECTID, CHUNK_ITEM_KEY, min_vaddr)
max_key = Key(FIRST_CHUNK_TREE_OBJECTID, CHUNK_ITEM_KEY, max_vaddr)
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key,
nr_items=nr_items):
yield Chunk(header, data)
def dev_extents(self, min_devid=1, max_devid=ULLONG_MAX):
"""
:param int min_devid: Lowest Device ID to search for.
:param int max_devid: Highest Device ID to search for.
:returns: Device Extent Items from the Device tree.
:rtype: Iterator[:class:`~btrfs.ctree.DevExtent`]
"""
tree = DEV_TREE_OBJECTID
min_key = btrfs.ctree.Key(min_devid, 0, 0)
max_key = btrfs.ctree.Key(max_devid, 255, ULLONG_MAX)
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key):
yield DevExtent(header, data)
def block_groups(self, min_vaddr=0, max_vaddr=ULLONG_MAX, nr_items=None):
"""
:param int min_vaddr: Lowest virtual address to search for.
:param int max_vaddr: Highest virtual address to search for.
:param int nr_items: Maximum amount of items to return. Defaults to no limit.
:returns: Block Group items from the Extent Tree or Block Group Tree
:rtype: Iterator[:class:`~btrfs.ctree.BlockGroupItem`]
"""
if not self._block_group_tree:
for chunk in self.chunks(min_vaddr, max_vaddr, nr_items):
try:
yield self.block_group(chunk.vaddr, chunk.length)
except btrfs.ctree.ItemNotFoundError:
# This is simply to prevent the program from aborting when a block
# group is removed in between doing the chunks lookup and the block
# group item lookup.
pass
else:
tree = BLOCK_GROUP_TREE_OBJECTID
min_key = Key(min_vaddr, BLOCK_GROUP_ITEM_KEY, 0)
max_key = Key(max_vaddr, BLOCK_GROUP_ITEM_KEY, ULLONG_MAX)
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key,
nr_items=nr_items):
yield BlockGroupItem(header, data)
def block_group(self, vaddr, length=None):
"""
:param int vaddr: Starting virtual address of the block group.
:param int length: Block group length (optional). If this information
is already known, it can be used to construct an exact match for
the search key.
:returns: Block Group Item
:rtype: :class:`~btrfs.ctree.BlockGroupItem`
:raises: :class:`ItemNotFoundError` if no Block Group Item can be found
at the address.
"""
if not self._block_group_tree:
tree = EXTENT_TREE_OBJECTID
else:
tree = BLOCK_GROUP_TREE_OBJECTID
min_offset = length if length is not None else 0
max_offset = length if length is not None else ULLONG_MAX
min_key = Key(vaddr, BLOCK_GROUP_ITEM_KEY, min_offset)
max_key = Key(vaddr, BLOCK_GROUP_ITEM_KEY, max_offset)
block_groups = [BlockGroupItem(header, data)
for header, data in
btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key, nr_items=1)]
if len(block_groups) == 0:
raise ItemNotFoundError("No block group at vaddr {}".format(vaddr))
return block_groups[0]
def extents(self, min_vaddr=0, max_vaddr=ULLONG_MAX,
load_data_refs=False, load_metadata_refs=False):
"""
:param int min_vaddr: Lowest virtual address to search for.
:param int max_vaddr: Highest virtual address to search for.
:param bool load_data_refs: Parse and load backreference information
for data extents.
:param bool load_metadata_refs: Parse and load backreference
information for metadata extents.
:returns: Extent and MetaData Items from the Extent tree
:rtype: Iterator[Union[:class:`ExtentItem`, :class:`MetaDataItem`]]
The 'refs' are backreference information. These sub items are stored
inside the :class:`ExtentItem` and :class:`MetaDataItem` Items, and
overflow to separately indexed items. When dealing with search results
in user space, these backreferences are of little use to us, since the
search API only allows us to search in tree leaves. So, they're ignored
by default.
"""
tree = EXTENT_TREE_OBJECTID
min_key = Key(min_vaddr, 0, 0)
max_key = Key(max_vaddr, 255, ULLONG_MAX)
extent = None
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key):
if header.type == EXTENT_ITEM_KEY:
if extent is not None:
yield extent
extent = ExtentItem(header, data, load_data_refs=load_data_refs,
load_metadata_refs=load_metadata_refs)
elif header.type == METADATA_ITEM_KEY:
if extent is not None:
yield extent
extent = MetaDataItem(header, data, load_refs=load_metadata_refs)
elif header.type == EXTENT_DATA_REF_KEY:
if load_data_refs:
extent._append_extent_data_ref(ExtentDataRef(header, data))
elif header.type == SHARED_DATA_REF_KEY:
if load_data_refs:
extent._append_shared_data_ref(SharedDataRef(header, data))
elif header.type == TREE_BLOCK_REF_KEY:
if load_metadata_refs:
extent._append_tree_block_ref(TreeBlockRef(header))
elif header.type == SHARED_BLOCK_REF_KEY:
if load_metadata_refs:
extent._append_shared_block_ref(SharedBlockRef(header))
elif header.type != BLOCK_GROUP_ITEM_KEY:
raise Exception("BUG: unexpected object {}".format(
Key(header.objectid, header.type, header.offset)))
if extent is not None:
yield extent
def top_level(self):
"""
:returns: The top level subvolume with ID 5, a.k.a. `FS_TREE_OBJECTID`.
:rtype: :class:`RootItem`
"""
return list(self.subvolumes(min_id=FS_TREE_OBJECTID, max_id=FS_TREE_OBJECTID))[0]
def subvolumes(self, min_id=FIRST_FREE_OBJECTID, max_id=LAST_FREE_OBJECTID):
"""
:param int min_id: Lowest subvolume ID to search for.
:param int max_id: Highest subvolume ID to search for.
:returns: Root Items from the Root tree, containing subvolume information.
:rtype: Iterator[:class:`RootItem`]
"""
tree = ROOT_TREE_OBJECTID
if min_id == max_id:
min_type = ROOT_ITEM_KEY
max_type = ROOT_ITEM_KEY
else:
min_type = 0
max_type = 255
min_key = Key(min_id, min_type, 0)
max_key = Key(max_id, max_type, ULLONG_MAX)
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key):
if header.type != ROOT_ITEM_KEY:
continue
yield RootItem(header, data)
def orphan_subvol_ids(self):
"""
:returns: ObjectID numbers of orphaned items in the Root tree.
:rtype: List[int]