| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
""" |
| 19 |
This module contains Python object representations for btrfs metadata items. |
| 20 |
|
| 21 |
Additionally, the helper :class:`FileSystem` provides a convenient way to start |
| 22 |
exploring an online btrfs filesystem. |
| 23 |
""" |
| 24 |
|
| 25 |
import btrfs |
| 26 |
import collections.abc |
| 27 |
import copy |
| 28 |
import datetime |
| 29 |
import os |
| 30 |
import re |
| 31 |
import struct |
| 32 |
import uuid |
| 33 |
|
| 34 |
U8_MAX = (1 << 8) - 1 |
| 35 |
ULLONG_MAX = (1 << 64) - 1 |
| 36 |
ULONG_MAX = (1 << 32) - 1 |
| 37 |
|
| 38 |
|
| 39 |
def U8(n): |
| 40 |
""" |
| 41 |
:param int n: Any number. |
| 42 |
:returns: Unsigned 8 bit number. |
| 43 |
:rtype: int |
| 44 |
|
| 45 |
Example:: |
| 46 |
|
| 47 |
>>> btrfs.ctree.U8(64) |
| 48 |
64 |
| 49 |
>>> btrfs.ctree.U8(-1) |
| 50 |
255 |
| 51 |
>>> btrfs.ctree.U8(0x4000) |
| 52 |
0 |
| 53 |
|
| 54 |
""" |
| 55 |
return n & U8_MAX |
| 56 |
|
| 57 |
|
| 58 |
def ULL(n): |
| 59 |
""" |
| 60 |
:param int n: Any number. |
| 61 |
:returns: Unsigned 64 bit number. |
| 62 |
:rtype: int |
| 63 |
|
| 64 |
Example:: |
| 65 |
|
| 66 |
>>> btrfs.ctree.ULL(64) |
| 67 |
64 |
| 68 |
>>> btrfs.ctree.ULL(-1) |
| 69 |
18446744073709551615 |
| 70 |
>>> btrfs.ctree.ULL(0x4000) |
| 71 |
16384 |
| 72 |
""" |
| 73 |
return n & ULLONG_MAX |
| 74 |
|
| 75 |
|
| 76 |
def _struct_format(s): |
| 77 |
f = s.format |
| 78 |
|
| 79 |
if type(f) == bytes: |
| 80 |
return f.decode('utf-8') |
| 81 |
return f |
| 82 |
|
| 83 |
|
| 84 |
ROOT_TREE_OBJECTID = 1 |
| 85 |
EXTENT_TREE_OBJECTID = 2 |
| 86 |
CHUNK_TREE_OBJECTID = 3 |
| 87 |
DEV_TREE_OBJECTID = 4 |
| 88 |
FS_TREE_OBJECTID = 5 |
| 89 |
ROOT_TREE_DIR_OBJECTID = 6 |
| 90 |
CSUM_TREE_OBJECTID = 7 |
| 91 |
QUOTA_TREE_OBJECTID = 8 |
| 92 |
UUID_TREE_OBJECTID = 9 |
| 93 |
FREE_SPACE_TREE_OBJECTID = 10 |
| 94 |
BLOCK_GROUP_TREE_OBJECTID = 11 |
| 95 |
|
| 96 |
DEV_STATS_OBJECTID = 0 |
| 97 |
BALANCE_OBJECTID = ULL(-4) |
| 98 |
ORPHAN_OBJECTID = ULL(-5) |
| 99 |
TREE_LOG_OBJECTID = ULL(-6) |
| 100 |
TREE_LOG_FIXUP_OBJECTID = ULL(-7) |
| 101 |
TREE_RELOC_OBJECTID = ULL(-8) |
| 102 |
DATA_RELOC_TREE_OBJECTID = ULL(-9) |
| 103 |
EXTENT_CSUM_OBJECTID = ULL(-10) |
| 104 |
FREE_SPACE_OBJECTID = ULL(-11) |
| 105 |
FREE_INO_OBJECTID = ULL(-12) |
| 106 |
MULTIPLE_OBJECTIDS = ULL(-255) |
| 107 |
|
| 108 |
FIRST_FREE_OBJECTID = 256 |
| 109 |
LAST_FREE_OBJECTID = ULL(-256) |
| 110 |
FIRST_CHUNK_TREE_OBJECTID = 256 |
| 111 |
|
| 112 |
DEV_ITEMS_OBJECTID = 1 |
| 113 |
|
| 114 |
|
| 115 |
INODE_ITEM_KEY = 1 |
| 116 |
INODE_REF_KEY = 12 |
| 117 |
INODE_EXTREF_KEY = 13 |
| 118 |
XATTR_ITEM_KEY = 24 |
| 119 |
ORPHAN_ITEM_KEY = 48 |
| 120 |
DIR_LOG_ITEM_KEY = 60 |
| 121 |
DIR_LOG_INDEX_KEY = 72 |
| 122 |
DIR_ITEM_KEY = 84 |
| 123 |
DIR_INDEX_KEY = 96 |
| 124 |
EXTENT_DATA_KEY = 108 |
| 125 |
EXTENT_CSUM_KEY = 128 |
| 126 |
ROOT_ITEM_KEY = 132 |
| 127 |
ROOT_BACKREF_KEY = 144 |
| 128 |
ROOT_REF_KEY = 156 |
| 129 |
EXTENT_ITEM_KEY = 168 |
| 130 |
METADATA_ITEM_KEY = 169 |
| 131 |
TREE_BLOCK_REF_KEY = 176 |
| 132 |
EXTENT_DATA_REF_KEY = 178 |
| 133 |
SHARED_BLOCK_REF_KEY = 182 |
| 134 |
SHARED_DATA_REF_KEY = 184 |
| 135 |
BLOCK_GROUP_ITEM_KEY = 192 |
| 136 |
FREE_SPACE_INFO_KEY = 198 |
| 137 |
FREE_SPACE_EXTENT_KEY = 199 |
| 138 |
FREE_SPACE_BITMAP_KEY = 200 |
| 139 |
DEV_EXTENT_KEY = 204 |
| 140 |
DEV_ITEM_KEY = 216 |
| 141 |
CHUNK_ITEM_KEY = 228 |
| 142 |
QGROUP_STATUS_KEY = 240 |
| 143 |
QGROUP_INFO_KEY = 242 |
| 144 |
QGROUP_LIMIT_KEY = 244 |
| 145 |
QGROUP_RELATION_KEY = 246 |
| 146 |
BALANCE_ITEM_KEY = 248 |
| 147 |
TEMPORARY_ITEM_KEY = 248 |
| 148 |
DEV_STATS_KEY = 249 |
| 149 |
PERSISTENT_ITEM_KEY = 249 |
| 150 |
DEV_REPLACE_KEY = 250 |
| 151 |
UUID_KEY_SUBVOL = 251 |
| 152 |
UUID_KEY_RECEIVED_SUBVOL = 252 |
| 153 |
STRING_ITEM_KEY = 253 |
| 154 |
|
| 155 |
BLOCK_GROUP_SINGLE = 0 |
| 156 |
BLOCK_GROUP_DATA = 1 << 0 |
| 157 |
BLOCK_GROUP_SYSTEM = 1 << 1 |
| 158 |
BLOCK_GROUP_METADATA = 1 << 2 |
| 159 |
BLOCK_GROUP_RAID0 = 1 << 3 |
| 160 |
BLOCK_GROUP_RAID1 = 1 << 4 |
| 161 |
BLOCK_GROUP_DUP = 1 << 5 |
| 162 |
BLOCK_GROUP_RAID10 = 1 << 6 |
| 163 |
BLOCK_GROUP_RAID5 = 1 << 7 |
| 164 |
BLOCK_GROUP_RAID6 = 1 << 8 |
| 165 |
BLOCK_GROUP_RAID1C3 = 1 << 9 |
| 166 |
BLOCK_GROUP_RAID1C4 = 1 << 10 |
| 167 |
|
| 168 |
BLOCK_GROUP_TYPE_MASK = ( |
| 169 |
BLOCK_GROUP_DATA | |
| 170 |
BLOCK_GROUP_SYSTEM | |
| 171 |
BLOCK_GROUP_METADATA |
| 172 |
) |
| 173 |
|
| 174 |
BLOCK_GROUP_PROFILE_MASK = ( |
| 175 |
BLOCK_GROUP_RAID0 | |
| 176 |
BLOCK_GROUP_RAID1 | |
| 177 |
BLOCK_GROUP_RAID1C3 | |
| 178 |
BLOCK_GROUP_RAID1C4 | |
| 179 |
BLOCK_GROUP_RAID5 | |
| 180 |
BLOCK_GROUP_RAID6 | |
| 181 |
BLOCK_GROUP_DUP | |
| 182 |
BLOCK_GROUP_RAID10 |
| 183 |
) |
| 184 |
|
| 185 |
AVAIL_ALLOC_BIT_SINGLE = 1 << 48 |
| 186 |
SPACE_INFO_GLOBAL_RSV = 1 << 49 |
| 187 |
|
| 188 |
|
| 189 |
_block_group_flags_str_map = { |
| 190 |
BLOCK_GROUP_DATA: 'DATA', |
| 191 |
BLOCK_GROUP_METADATA: 'METADATA', |
| 192 |
BLOCK_GROUP_SYSTEM: 'SYSTEM', |
| 193 |
BLOCK_GROUP_RAID0: 'RAID0', |
| 194 |
BLOCK_GROUP_RAID1: 'RAID1', |
| 195 |
BLOCK_GROUP_DUP: 'DUP', |
| 196 |
BLOCK_GROUP_RAID10: 'RAID10', |
| 197 |
BLOCK_GROUP_RAID5: 'RAID5', |
| 198 |
BLOCK_GROUP_RAID6: 'RAID6', |
| 199 |
BLOCK_GROUP_RAID1C3: 'RAID1C3', |
| 200 |
BLOCK_GROUP_RAID1C4: 'RAID1C4', |
| 201 |
} |
| 202 |
|
| 203 |
_balance_args_profiles_str_map = { |
| 204 |
BLOCK_GROUP_RAID0: 'RAID0', |
| 205 |
BLOCK_GROUP_RAID1: 'RAID1', |
| 206 |
BLOCK_GROUP_DUP: 'DUP', |
| 207 |
BLOCK_GROUP_RAID10: 'RAID10', |
| 208 |
BLOCK_GROUP_RAID5: 'RAID5', |
| 209 |
BLOCK_GROUP_RAID6: 'RAID6', |
| 210 |
BLOCK_GROUP_RAID1C3: 'RAID1C3', |
| 211 |
BLOCK_GROUP_RAID1C4: 'RAID1C4', |
| 212 |
AVAIL_ALLOC_BIT_SINGLE: 'SINGLE', |
| 213 |
} |
| 214 |
|
| 215 |
QGROUP_LEVEL_SHIFT = 48 |
| 216 |
|
| 217 |
EXTENT_FLAG_DATA = 1 << 0 |
| 218 |
EXTENT_FLAG_TREE_BLOCK = 1 << 1 |
| 219 |
BLOCK_FLAG_FULL_BACKREF = 1 << 8 |
| 220 |
|
| 221 |
_extent_flags_str_map = { |
| 222 |
EXTENT_FLAG_DATA: 'DATA', |
| 223 |
EXTENT_FLAG_TREE_BLOCK: 'TREE_BLOCK', |
| 224 |
BLOCK_FLAG_FULL_BACKREF: 'FULL_BACKREF', |
| 225 |
} |
| 226 |
|
| 227 |
INODE_NODATASUM = 1 << 0 |
| 228 |
INODE_NODATACOW = 1 << 1 |
| 229 |
INODE_READONLY = 1 << 2 |
| 230 |
INODE_NOCOMPRESS = 1 << 3 |
| 231 |
INODE_PREALLOC = 1 << 4 |
| 232 |
INODE_SYNC = 1 << 5 |
| 233 |
INODE_IMMUTABLE = 1 << 6 |
| 234 |
INODE_APPEND = 1 << 7 |
| 235 |
INODE_NODUMP = 1 << 8 |
| 236 |
INODE_NOATIME = 1 << 9 |
| 237 |
INODE_DIRSYNC = 1 << 10 |
| 238 |
INODE_COMPRESS = 1 << 11 |
| 239 |
INODE_ROOT_ITEM_INIT = 1 << 31 |
| 240 |
|
| 241 |
_inode_flags_str_map = { |
| 242 |
INODE_NODATASUM: 'NODATASUM', |
| 243 |
INODE_NODATACOW: 'NODATACOW', |
| 244 |
INODE_READONLY: 'READONLY', |
| 245 |
INODE_NOCOMPRESS: 'NOCOMPRESS', |
| 246 |
INODE_PREALLOC: 'PREALLOC', |
| 247 |
INODE_SYNC: 'SYNC', |
| 248 |
INODE_IMMUTABLE: 'IMMUTABLE', |
| 249 |
INODE_APPEND: 'APPEND', |
| 250 |
INODE_NODUMP: 'NODUMP', |
| 251 |
INODE_NOATIME: 'NOATIME', |
| 252 |
INODE_DIRSYNC: 'DIRSYNC', |
| 253 |
INODE_COMPRESS: 'COMPRESS', |
| 254 |
INODE_ROOT_ITEM_INIT: 'ROOT_ITEM_INIT', |
| 255 |
} |
| 256 |
|
| 257 |
ROOT_SUBVOL_RDONLY = 1 << 0 |
| 258 |
|
| 259 |
_root_flags_str_map = { |
| 260 |
ROOT_SUBVOL_RDONLY: 'RDONLY', |
| 261 |
} |
| 262 |
|
| 263 |
FT_UNKNOWN = 0 |
| 264 |
FT_REG_FILE = 1 |
| 265 |
FT_DIR = 2 |
| 266 |
FT_CHRDEV = 3 |
| 267 |
FT_BLKDEV = 4 |
| 268 |
FT_FIFO = 5 |
| 269 |
FT_SOCK = 6 |
| 270 |
FT_SYMLINK = 7 |
| 271 |
FT_XATTR = 8 |
| 272 |
FT_MAX = 9 |
| 273 |
|
| 274 |
_dir_item_type_str_map = { |
| 275 |
FT_UNKNOWN: 'UNKNOWN', |
| 276 |
FT_REG_FILE: 'FILE', |
| 277 |
FT_DIR: 'DIR', |
| 278 |
FT_CHRDEV: 'CHRDEV', |
| 279 |
FT_BLKDEV: 'BLKDEV', |
| 280 |
FT_FIFO: 'FIFO', |
| 281 |
FT_SOCK: 'SOCK', |
| 282 |
FT_SYMLINK: 'SYMLINK', |
| 283 |
FT_XATTR: 'XATTR', |
| 284 |
} |
| 285 |
|
| 286 |
COMPRESS_NONE = 0 |
| 287 |
COMPRESS_ZLIB = 1 |
| 288 |
COMPRESS_LZO = 2 |
| 289 |
COMPRESS_ZSTD = 3 |
| 290 |
|
| 291 |
_compress_type_str_map = { |
| 292 |
COMPRESS_NONE: 'none', |
| 293 |
COMPRESS_ZLIB: 'zlib', |
| 294 |
COMPRESS_LZO: 'lzo', |
| 295 |
COMPRESS_ZSTD: 'zstd', |
| 296 |
} |
| 297 |
|
| 298 |
FILE_EXTENT_INLINE = 0 |
| 299 |
FILE_EXTENT_REG = 1 |
| 300 |
FILE_EXTENT_PREALLOC = 2 |
| 301 |
|
| 302 |
_file_extent_type_str_map = { |
| 303 |
FILE_EXTENT_INLINE: 'inline', |
| 304 |
FILE_EXTENT_REG: 'regular', |
| 305 |
FILE_EXTENT_PREALLOC: 'prealloc', |
| 306 |
} |
| 307 |
|
| 308 |
FREE_SPACE_USING_BITMAPS = 1 |
| 309 |
|
| 310 |
_free_space_info_flags_str_map = { |
| 311 |
FREE_SPACE_USING_BITMAPS: 'bitmaps', |
| 312 |
} |
| 313 |
|
| 314 |
|
| 315 |
def qgroup_level(objectid): |
| 316 |
"""Helper to get qgroup level from a qgroup relation objectid. |
| 317 |
|
| 318 |
:param int objectid: 64-bit object ID field. |
| 319 |
:returns: qgroup level. |
| 320 |
:rtype: int |
| 321 |
""" |
| 322 |
return objectid >> QGROUP_LEVEL_SHIFT |
| 323 |
|
| 324 |
|
| 325 |
def qgroup_subvid(objectid): |
| 326 |
"""Helper to get qgroup subvolume ID from a qgroup relation objectid. |
| 327 |
|
| 328 |
:param int objectid: 64-bit object ID field. |
| 329 |
:returns: qgroup subvolume ID. |
| 330 |
:rtype: int |
| 331 |
""" |
| 332 |
return objectid & ((1 << QGROUP_LEVEL_SHIFT) - 1) |
| 333 |
|
| 334 |
|
| 335 |
def _qgroup_objectid(level, subvid): |
| 336 |
return (level << QGROUP_LEVEL_SHIFT) + subvid |
| 337 |
|
| 338 |
|
| 339 |
_key_objectid_str_map = { |
| 340 |
ROOT_TREE_OBJECTID: 'ROOT_TREE', |
| 341 |
EXTENT_TREE_OBJECTID: 'EXTENT_TREE', |
| 342 |
CHUNK_TREE_OBJECTID: 'CHUNK_TREE', |
| 343 |
DEV_TREE_OBJECTID: 'DEV_TREE', |
| 344 |
FS_TREE_OBJECTID: 'FS_TREE', |
| 345 |
ROOT_TREE_DIR_OBJECTID: 'ROOT_TREE_DIR', |
| 346 |
CSUM_TREE_OBJECTID: 'CSUM_TREE', |
| 347 |
QUOTA_TREE_OBJECTID: 'QUOTA_TREE', |
| 348 |
UUID_TREE_OBJECTID: 'UUID_TREE', |
| 349 |
FREE_SPACE_TREE_OBJECTID: 'FREE_SPACE_TREE', |
| 350 |
BLOCK_GROUP_TREE_OBJECTID: 'BLOCK_GROUP_TREE', |
| 351 |
BALANCE_OBJECTID: 'BALANCE', |
| 352 |
ORPHAN_OBJECTID: 'ORPHAN', |
| 353 |
TREE_LOG_OBJECTID: 'TREE_LOG', |
| 354 |
TREE_LOG_FIXUP_OBJECTID: 'TREE_LOG_FIXUP', |
| 355 |
TREE_RELOC_OBJECTID: 'TREE_RELOC', |
| 356 |
DATA_RELOC_TREE_OBJECTID: 'DATA_RELOC_TREE', |
| 357 |
EXTENT_CSUM_OBJECTID: 'EXTENT_CSUM', |
| 358 |
FREE_SPACE_OBJECTID: 'FREE_SPACE', |
| 359 |
FREE_INO_OBJECTID: 'FREE_INO', |
| 360 |
MULTIPLE_OBJECTIDS: 'MULTIPLE', |
| 361 |
} |
| 362 |
|
| 363 |
|
| 364 |
def _key_objectid_str(objectid, _type): |
| 365 |
if _type == DEV_EXTENT_KEY: |
| 366 |
return str(objectid) |
| 367 |
if _type == QGROUP_RELATION_KEY: |
| 368 |
return "{}/{}".format(qgroup_level(objectid), qgroup_subvid(objectid)) |
| 369 |
if _type == UUID_KEY_SUBVOL or _type == UUID_KEY_RECEIVED_SUBVOL: |
| 370 |
return "0x{:0>16x}".format(objectid) |
| 371 |
|
| 372 |
if objectid == ROOT_TREE_OBJECTID and _type == DEV_ITEM_KEY: |
| 373 |
return 'DEV_ITEMS' |
| 374 |
if objectid == DEV_STATS_OBJECTID and _type == PERSISTENT_ITEM_KEY: |
| 375 |
return 'DEV_STATS' |
| 376 |
if objectid == FIRST_CHUNK_TREE_OBJECTID and _type == CHUNK_ITEM_KEY: |
| 377 |
return 'FIRST_CHUNK_TREE' |
| 378 |
if objectid == ULLONG_MAX: |
| 379 |
return '-1' |
| 380 |
|
| 381 |
return _key_objectid_str_map.get(objectid, str(objectid)) |
| 382 |
|
| 383 |
|
| 384 |
_key_str_objectid_map = {v: k for k, v in _key_objectid_str_map.items()} |
| 385 |
_key_str_objectid_map.update({ |
| 386 |
'DEV_ITEMS': ROOT_TREE_OBJECTID, |
| 387 |
'DEV_STATS': DEV_STATS_OBJECTID, |
| 388 |
'FIRST_CHUNK_TREE': FIRST_CHUNK_TREE_OBJECTID, |
| 389 |
}) |
| 390 |
|
| 391 |
_re_qgroup_objectid = re.compile(r'^(?P<level>\d+)/(?P<subvid>\d+)$') |
| 392 |
|
| 393 |
|
| 394 |
def _key_str_objectid(objectid_str, _type): |
| 395 |
|
| 396 |
try: |
| 397 |
objectid = int(objectid_str) |
| 398 |
if objectid > -256 and objectid <= ULLONG_MAX: |
| 399 |
return objectid |
| 400 |
except ValueError: |
| 401 |
pass |
| 402 |
|
| 403 |
if objectid_str in _key_str_objectid_map: |
| 404 |
return _key_str_objectid_map[objectid_str] |
| 405 |
|
| 406 |
if _type in (QGROUP_RELATION_KEY, QGROUP_INFO_KEY, QGROUP_LIMIT_KEY): |
| 407 |
match = _re_qgroup_objectid.match(objectid_str) |
| 408 |
if match is not None: |
| 409 |
return _qgroup_objectid(**match.groupdict()) |
| 410 |
else: |
| 411 |
raise ValueError("Unparsable key objectid {} for qgroup type {}".format( |
| 412 |
objectid_str, _key_type_str(_type))) |
| 413 |
|
| 414 |
if objectid_str.startswith('0x'): |
| 415 |
try: |
| 416 |
return int(objectid_str, 0) |
| 417 |
except Exception: |
| 418 |
pass |
| 419 |
|
| 420 |
raise ValueError("Unparsable key objectid {}".format(objectid_str)) |
| 421 |
|
| 422 |
|
| 423 |
_key_type_str_map = { |
| 424 |
INODE_ITEM_KEY: 'INODE_ITEM', |
| 425 |
INODE_REF_KEY: 'INODE_REF', |
| 426 |
INODE_EXTREF_KEY: 'INODE_EXTREF', |
| 427 |
XATTR_ITEM_KEY: 'XATTR_ITEM', |
| 428 |
ORPHAN_ITEM_KEY: 'ORPHAN_ITEM', |
| 429 |
DIR_LOG_ITEM_KEY: 'DIR_LOG_ITEM', |
| 430 |
DIR_LOG_INDEX_KEY: 'DIR_LOG_INDEX', |
| 431 |
DIR_ITEM_KEY: 'DIR_ITEM', |
| 432 |
DIR_INDEX_KEY: 'DIR_INDEX', |
| 433 |
EXTENT_DATA_KEY: 'EXTENT_DATA', |
| 434 |
EXTENT_CSUM_KEY: 'EXTENT_CSUM', |
| 435 |
ROOT_ITEM_KEY: 'ROOT_ITEM', |
| 436 |
ROOT_BACKREF_KEY: 'ROOT_BACKREF', |
| 437 |
ROOT_REF_KEY: 'ROOT_REF', |
| 438 |
EXTENT_ITEM_KEY: 'EXTENT_ITEM', |
| 439 |
METADATA_ITEM_KEY: 'METADATA_ITEM', |
| 440 |
TREE_BLOCK_REF_KEY: 'TREE_BLOCK_REF', |
| 441 |
EXTENT_DATA_REF_KEY: 'EXTENT_DATA_REF', |
| 442 |
SHARED_BLOCK_REF_KEY: 'SHARED_BLOCK_REF', |
| 443 |
SHARED_DATA_REF_KEY: 'SHARED_DATA_REF', |
| 444 |
BLOCK_GROUP_ITEM_KEY: 'BLOCK_GROUP_ITEM', |
| 445 |
FREE_SPACE_INFO_KEY: 'FREE_SPACE_INFO', |
| 446 |
FREE_SPACE_EXTENT_KEY: 'FREE_SPACE_EXTENT', |
| 447 |
FREE_SPACE_BITMAP_KEY: 'FREE_SPACE_BITMAP', |
| 448 |
DEV_EXTENT_KEY: 'DEV_EXTENT', |
| 449 |
DEV_ITEM_KEY: 'DEV_ITEM', |
| 450 |
CHUNK_ITEM_KEY: 'CHUNK_ITEM', |
| 451 |
QGROUP_STATUS_KEY: 'QGROUP_STATUS', |
| 452 |
QGROUP_INFO_KEY: 'QGROUP_INFO', |
| 453 |
QGROUP_LIMIT_KEY: 'QGROUP_LIMIT', |
| 454 |
QGROUP_RELATION_KEY: 'QGROUP_RELATION', |
| 455 |
DEV_REPLACE_KEY: 'DEV_REPLACE', |
| 456 |
UUID_KEY_SUBVOL: 'UUID_KEY_SUBVOL', |
| 457 |
UUID_KEY_RECEIVED_SUBVOL: 'UUID_KEY_RECEIVED_SUBVOL', |
| 458 |
STRING_ITEM_KEY: 'STRING_ITEM', |
| 459 |
TEMPORARY_ITEM_KEY: 'TEMPORARY_ITEM', |
| 460 |
PERSISTENT_ITEM_KEY: 'PERSISTENT_ITEM', |
| 461 |
} |
| 462 |
|
| 463 |
|
| 464 |
def _key_type_str(_type): |
| 465 |
return _key_type_str_map.get(_type, str(_type)) |
| 466 |
|
| 467 |
|
| 468 |
_key_str_type_map = {v: k for k, v in _key_type_str_map.items()} |
| 469 |
|
| 470 |
|
| 471 |
def _key_str_type(type_str): |
| 472 |
|
| 473 |
try: |
| 474 |
type_ = int(type_str) |
| 475 |
except ValueError: |
| 476 |
pass |
| 477 |
else: |
| 478 |
if type_ >= -1 and type_ <= 255: |
| 479 |
return type_ |
| 480 |
if type_str in _key_str_type_map: |
| 481 |
return _key_str_type_map[type_str] |
| 482 |
raise ValueError("Unknown key type {}".format(type_str)) |
| 483 |
|
| 484 |
|
| 485 |
def _key_offset_str(offset, _type): |
| 486 |
if _type == QGROUP_RELATION_KEY or _type == QGROUP_INFO_KEY or _type == QGROUP_LIMIT_KEY: |
| 487 |
return "{}/{}".format(qgroup_level(offset), qgroup_subvid(offset)) |
| 488 |
if _type == UUID_KEY_SUBVOL or _type == UUID_KEY_RECEIVED_SUBVOL: |
| 489 |
return "0x{:0>16x}".format(offset) |
| 490 |
if offset == ULLONG_MAX: |
| 491 |
return '-1' |
| 492 |
if _type == ROOT_ITEM_KEY: |
| 493 |
return _key_objectid_str_map.get(offset, str(offset)) |
| 494 |
|
| 495 |
return str(offset) |
| 496 |
|
| 497 |
|
| 498 |
def _key_str_offset(offset_str, _type): |
| 499 |
|
| 500 |
try: |
| 501 |
offset = int(offset_str) |
| 502 |
except ValueError: |
| 503 |
pass |
| 504 |
else: |
| 505 |
if offset >= -1 and offset <= ULLONG_MAX: |
| 506 |
return offset |
| 507 |
|
| 508 |
if _type in (QGROUP_RELATION_KEY, QGROUP_INFO_KEY, QGROUP_LIMIT_KEY): |
| 509 |
match = _re_qgroup_objectid.match(offset_str) |
| 510 |
if match is not None: |
| 511 |
return _qgroup_objectid(**{k: int(v) for k, v in match.groupdict().items()}) |
| 512 |
else: |
| 513 |
raise ValueError("Unparsable key offset {} for qgroup type {}".format( |
| 514 |
offset_str, _key_type_str(_type))) |
| 515 |
|
| 516 |
if offset_str.startswith('0x'): |
| 517 |
try: |
| 518 |
return int(offset_str, 0) |
| 519 |
except Exception: |
| 520 |
pass |
| 521 |
|
| 522 |
raise ValueError("Unparsable key offset {}".format(offset_str)) |
| 523 |
|
| 524 |
|
| 525 |
class ItemNotFoundError(IndexError): |
| 526 |
"""Helper exception for lookup convenience functions. |
| 527 |
|
| 528 |
If a convenience function on a :class:`btrfs.ctree.FileSystem` object is |
| 529 |
supposed to return exactly one object at a specific location, and no object |
| 530 |
is found, this type of exception is raised. |
| 531 |
|
| 532 |
An example is the :func:`~btrfs.ctree.FileSystem.block_group` helper, which |
| 533 |
raises this error if no block group item is found at the exact specified |
| 534 |
location. |
| 535 |
""" |
| 536 |
pass |
| 537 |
|
| 538 |
|
| 539 |
KEY_MAX = (1 << 136) - 1 |
| 540 |
|
| 541 |
|
| 542 |
class Key(object): |
| 543 |
r"""Btrfs metadata trees have a key space of 136-bit numbers. |
| 544 |
|
| 545 |
A full 136-bit tree key is composed as: |
| 546 |
(objectid << 72) + (type << 64) + offset |
| 547 |
|
| 548 |
:param objectid: 64-bit object ID number or string representation. |
| 549 |
:type objectid: Union[int, str] |
| 550 |
:param type\_: 8-bit type number or string representation. |
| 551 |
:type type\_: Union[int, str] |
| 552 |
:param int offset: 64-bit offset number or string representation. |
| 553 |
:type offset: Union[int, str] |
| 554 |
|
| 555 |
Key objects support sorting and simple addition and subtraction. Also, |
| 556 |
when subtracting 1 from a zero key, the value wraps around to the largest |
| 557 |
value possible, vice versa. |
| 558 |
|
| 559 |
Example:: |
| 560 |
|
| 561 |
>>> key1 = btrfs.ctree.Key(425, 'DIR_ITEM', 17818406) |
| 562 |
>>> key1 |
| 563 |
Key(425, 84, 17818406) |
| 564 |
>>> str(key1) |
| 565 |
'(425 DIR_ITEM 17818406)' |
| 566 |
>>> key2 = btrfs.ctree.Key(442, btrfs.ctree.EXTENT_DATA_KEY, 0) |
| 567 |
>>> key2 > key1 |
| 568 |
True |
| 569 |
|
| 570 |
>>> min_key = btrfs.ctree.Key(0, 0, 0) |
| 571 |
>>> min_key |
| 572 |
Key(0, 0, 0) |
| 573 |
>>> str(min_key) |
| 574 |
'(0 0 0)' |
| 575 |
>>> min_key - 1 |
| 576 |
Key(18446744073709551615, 255, 18446744073709551615) |
| 577 |
>>> str(min_key - 1) |
| 578 |
'(-1 255 -1)' |
| 579 |
|
| 580 |
The `-1` value in the string representation is just a convenience way to |
| 581 |
write the maximum allowed number. The actual value for a 64 bit number is |
| 582 |
still 18446744073709551615, and for 8 bit that's 255 of course. |
| 583 |
|
| 584 |
For example, when setting up a minimum and maximum key for a metadata |
| 585 |
search, the arithmetic that can be done helps quickly defining the maximum |
| 586 |
value. The next example shows the key range for finding all intormation |
| 587 |
about an inode in a filesystem tree: |
| 588 |
|
| 589 |
Example:: |
| 590 |
|
| 591 |
>>> inum = 31337 |
| 592 |
>>> min_key = btrfs.ctree.Key(inum, 0, 0) |
| 593 |
>>> max_key = btrfs.ctree.Key(inum + 1, 0, 0) - 1 |
| 594 |
>>> |
| 595 |
>>> min_key |
| 596 |
Key(31337, 0, 0) |
| 597 |
>>> max_key |
| 598 |
Key(31337, 255, 18446744073709551615) |
| 599 |
|
| 600 |
Last but not least, the utils module contains the helper function |
| 601 |
:func:`~btrfs.utils.parse_key_string` to dissect a full text key string: |
| 602 |
|
| 603 |
Example:: |
| 604 |
|
| 605 |
>>> btrfs.utils.parse_key_string('(535 EXTENT_DATA 0)') |
| 606 |
Key(535, 108, 0) |
| 607 |
""" |
| 608 |
|
| 609 |
def __init__(self, objectid, type_, offset): |
| 610 |
if isinstance(type_, int): |
| 611 |
self._type = U8(type_) |
| 612 |
elif isinstance(type_, str): |
| 613 |
self._type = U8(_key_str_type(type_)) |
| 614 |
else: |
| 615 |
raise ValueError("Key type needs to be either string or integer: {}.".format(type_)) |
| 616 |
if isinstance(objectid, int): |
| 617 |
self._objectid = ULL(objectid) |
| 618 |
elif isinstance(objectid, str): |
| 619 |
self._objectid = ULL(_key_str_objectid(objectid, self._type)) |
| 620 |
else: |
| 621 |
raise ValueError("Key objectid needs to be either string or integer: {}.".format( |
| 622 |
objectid)) |
| 623 |
if isinstance(offset, int): |
| 624 |
self._offset = ULL(offset) |
| 625 |
elif isinstance(offset, str): |
| 626 |
self._offset = ULL(_key_str_offset(offset, self._type)) |
| 627 |
else: |
| 628 |
raise ValueError("Key offset needs to be either string or integer: {}.".format( |
| 629 |
offset)) |
| 630 |
self._pack() |
| 631 |
|
| 632 |
@property |
| 633 |
def objectid(self): |
| 634 |
"""Key Object ID""" |
| 635 |
return self._objectid |
| 636 |
|
| 637 |
@objectid.setter |
| 638 |
def objectid(self, _objectid): |
| 639 |
self._objectid = _objectid |
| 640 |
self._pack() |
| 641 |
|
| 642 |
@property |
| 643 |
def type(self): |
| 644 |
"""Key Type""" |
| 645 |
return self._type |
| 646 |
|
| 647 |
@type.setter |
| 648 |
def type(self, _type): |
| 649 |
self._type = _type |
| 650 |
self._pack() |
| 651 |
|
| 652 |
@property |
| 653 |
def offset(self): |
| 654 |
"""Key Offset""" |
| 655 |
return self._offset |
| 656 |
|
| 657 |
@offset.setter |
| 658 |
def offset(self, _offset): |
| 659 |
self._offset = _offset |
| 660 |
self._pack() |
| 661 |
|
| 662 |
@property |
| 663 |
def key(self): |
| 664 |
"""Full numeric 136-bit key value.""" |
| 665 |
return self._key |
| 666 |
|
| 667 |
@key.setter |
| 668 |
def key(self, _key): |
| 669 |
self._key = _key & KEY_MAX |
| 670 |
self._unpack() |
| 671 |
|
| 672 |
def _pack(self): |
| 673 |
self._key = (self.objectid << 72) + (self._type << 64) + self.offset |
| 674 |
|
| 675 |
def _unpack(self): |
| 676 |
self._objectid = ULL(self._key >> 72) |
| 677 |
self._type = U8(self._key >> 64) |
| 678 |
self._offset = ULL(self._key) |
| 679 |
|
| 680 |
def __lt__(self, other): |
| 681 |
if isinstance(other, Key): |
| 682 |
return self._key < other._key |
| 683 |
return self._key < other |
| 684 |
|
| 685 |
def __le__(self, other): |
| 686 |
if isinstance(other, Key): |
| 687 |
return self._key <= other._key |
| 688 |
return self._key <= other |
| 689 |
|
| 690 |
def __eq__(self, other): |
| 691 |
if isinstance(other, Key): |
| 692 |
return self._key == other._key |
| 693 |
return self._key == other |
| 694 |
|
| 695 |
def __ge__(self, other): |
| 696 |
if isinstance(other, Key): |
| 697 |
return self._key >= other._key |
| 698 |
return self._key >= other |
| 699 |
|
| 700 |
def __gt__(self, other): |
| 701 |
if isinstance(other, Key): |
| 702 |
return self._key > other._key |
| 703 |
return self._key > other |
| 704 |
|
| 705 |
def __repr__(self): |
| 706 |
return "Key({}, {}, {})".format(self._objectid, self._type, self._offset) |
| 707 |
|
| 708 |
def __str__(self): |
| 709 |
return "({} {} {})".format( |
| 710 |
_key_objectid_str(self._objectid, self._type), |
| 711 |
_key_type_str(self._type), |
| 712 |
_key_offset_str(self._offset, self._type), |
| 713 |
) |
| 714 |
|
| 715 |
def __add__(self, amount): |
| 716 |
new_key = copy.copy(self) |
| 717 |
new_key.key += amount |
| 718 |
return new_key |
| 719 |
|
| 720 |
def __sub__(self, amount): |
| 721 |
new_key = copy.copy(self) |
| 722 |
new_key.key -= amount |
| 723 |
return new_key |
| 724 |
|
| 725 |
|
| 726 |
class DiskKey(Key): |
| 727 |
"""Object representation of struct `btrfs_disk_key`. |
| 728 |
|
| 729 |
Objects of this type are used in metadata search results. |
| 730 |
""" |
| 731 |
_disk_key = struct.Struct('<QBQ') |
| 732 |
|
| 733 |
def __init__(self, data): |
| 734 |
super(DiskKey, self).__init__(*DiskKey._disk_key.unpack_from(data)) |
| 735 |
|
| 736 |
|
| 737 |
class FileSystem(object): |
| 738 |
"""The FileSystem object is a bit of a spider in the web of this library. |
| 739 |
It contains a lot of convenience methods providing quick access to all |
| 740 |
kinds of functionality. |
| 741 |
|
| 742 |
:param str path: Path to the mounted filesystem. |
| 743 |
|
| 744 |
:ivar str path: The filesystem path used to initialize this object. |
| 745 |
:ivar uuid.UUID fsid: Filesystem ID. |
| 746 |
:ivar int nodesize: B-tree node size (same as leaf size). |
| 747 |
:ivar int sectorsize: Smallest allocatable block size in bytes for storing |
| 748 |
data. |
| 749 |
|
| 750 |
The fsid, nodesize and sectorsize values are cached from a call to |
| 751 |
:func:`~btrfs.ctree.FileSystem.fs_info` when initializing the object. |
| 752 |
|
| 753 |
It is highly recommended to use the built in context manager. Doing so |
| 754 |
prevents leaking the internal open file descriptor. |
| 755 |
|
| 756 |
Example:: |
| 757 |
|
| 758 |
>>> with btrfs.ctree.FileSystem('/') as fs: |
| 759 |
... print(fs.top_level().generation) |
| 760 |
... |
| 761 |
3382004 |
| 762 |
""" |
| 763 |
def __init__(self, path): |
| 764 |
self.path = path |
| 765 |
self.fd = os.open(path, os.O_RDONLY) |
| 766 |
_fs_info = self.fs_info() |
| 767 |
self.fsid = _fs_info.fsid |
| 768 |
self.nodesize = _fs_info.nodesize |
| 769 |
self.sectorsize = _fs_info.sectorsize |
| 770 |
self._block_group_tree = self.features().compat_ro_flags & \ |
| 771 |
btrfs.ioctl.FEATURE_COMPAT_RO_BLOCK_GROUP_TREE != 0 |
| 772 |
|
| 773 |
def __enter__(self): |
| 774 |
return self |
| 775 |
|
| 776 |
def fs_info(self): |
| 777 |
""" |
| 778 |
:returns: General filesystem information. |
| 779 |
:rtype: :class:`btrfs.ioctl.FsInfo` |
| 780 |
""" |
| 781 |
return btrfs.ioctl.fs_info(self.fd) |
| 782 |
|
| 783 |
def dev_info(self, devid): |
| 784 |
""" |
| 785 |
:param int devid: Device ID. |
| 786 |
:returns: Device information. |
| 787 |
:rtype: :class:`btrfs.ioctl.DevInfo` |
| 788 |
""" |
| 789 |
return btrfs.ioctl.dev_info(self.fd, devid) |
| 790 |
|
| 791 |
def dev_stats(self, devid, reset=False): |
| 792 |
""" |
| 793 |
:param int devid: Device ID. |
| 794 |
:param bool reset: Reset device error counters to zero. |
| 795 |
:returns: Device statistics. |
| 796 |
:rtype: :class:`btrfs.ioctl.DevStats` |
| 797 |
""" |
| 798 |
return btrfs.ioctl.dev_stats(self.fd, devid, reset) |
| 799 |
|
| 800 |
def space_info(self): |
| 801 |
""" |
| 802 |
:returns: Space information |
| 803 |
:rtype: List[:class:`btrfs.ioctl.SpaceInfo`] |
| 804 |
""" |
| 805 |
return btrfs.ioctl.space_info(self.fd) |
| 806 |
|
| 807 |
def search(self, tree, min_key=None, max_key=None): |
| 808 |
""" |
| 809 |
Retrieve all metadata items within a specific range. This is basically |
| 810 |
a thin wrapper around the :func:`~btrfs.ioctl.search_v2` with a bit |
| 811 |
limited functionality, but suited for almost all use cases when quickly |
| 812 |
searching around. |
| 813 |
|
| 814 |
:param int tree: The metadata tree we're searching in. |
| 815 |
:param btrfs.ctree.Key min_key: Minimum key value for items to return. |
| 816 |
:param btrfs.ctree.Key max_key: Maximum key value for items to return. |
| 817 |
:returns: Any metadata item found in the search range, as sub class of |
| 818 |
:class:`~btrfs.ctree.ItemData`, helped by the |
| 819 |
:func:`btrfs.ctree.classify` function. |
| 820 |
:rtype: Iterator[:class:`~btrfs.ctree.ItemData`] |
| 821 |
""" |
| 822 |
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key): |
| 823 |
yield btrfs.ctree.classify(header, data) |
| 824 |
|
| 825 |
def devices(self, min_devid=1, max_devid=ULLONG_MAX): |
| 826 |
""" |
| 827 |
:param int min_devid: Lowest Device ID to search for. |
| 828 |
:param int max_devid: Highest Device ID to search for. |
| 829 |
:returns: Device Items from the Chunk tree. |
| 830 |
:rtype: Iterator[:class:`~btrfs.ctree.DevItem`] |
| 831 |
""" |
| 832 |
tree = CHUNK_TREE_OBJECTID |
| 833 |
min_key = Key(DEV_ITEMS_OBJECTID, DEV_ITEM_KEY, min_devid) |
| 834 |
max_key = Key(DEV_ITEMS_OBJECTID, DEV_ITEM_KEY, max_devid) |
| 835 |
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key): |
| 836 |
yield DevItem(header, data) |
| 837 |
|
| 838 |
def chunks(self, min_vaddr=0, max_vaddr=ULLONG_MAX, nr_items=None): |
| 839 |
""" |
| 840 |
:param int min_vaddr: Lowest virtual address to search for. |
| 841 |
:param int max_vaddr: Highest virtual address to search for. |
| 842 |
:param int nr_items: Maximum amount of items to return. Defaults to no limit. |
| 843 |
:returns: Chunk items from the Chunk tree. |
| 844 |
:rtype: Iterator[:class:`~btrfs.ctree.Chunk`] |
| 845 |
""" |
| 846 |
tree = CHUNK_TREE_OBJECTID |
| 847 |
min_key = Key(FIRST_CHUNK_TREE_OBJECTID, CHUNK_ITEM_KEY, min_vaddr) |
| 848 |
max_key = Key(FIRST_CHUNK_TREE_OBJECTID, CHUNK_ITEM_KEY, max_vaddr) |
| 849 |
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key, |
| 850 |
nr_items=nr_items): |
| 851 |
yield Chunk(header, data) |
| 852 |
|
| 853 |
def dev_extents(self, min_devid=1, max_devid=ULLONG_MAX): |
| 854 |
""" |
| 855 |
:param int min_devid: Lowest Device ID to search for. |
| 856 |
:param int max_devid: Highest Device ID to search for. |
| 857 |
:returns: Device Extent Items from the Device tree. |
| 858 |
:rtype: Iterator[:class:`~btrfs.ctree.DevExtent`] |
| 859 |
""" |
| 860 |
tree = DEV_TREE_OBJECTID |
| 861 |
min_key = btrfs.ctree.Key(min_devid, 0, 0) |
| 862 |
max_key = btrfs.ctree.Key(max_devid, 255, ULLONG_MAX) |
| 863 |
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key): |
| 864 |
yield DevExtent(header, data) |
| 865 |
|
| 866 |
def block_groups(self, min_vaddr=0, max_vaddr=ULLONG_MAX, nr_items=None): |
| 867 |
""" |
| 868 |
:param int min_vaddr: Lowest virtual address to search for. |
| 869 |
:param int max_vaddr: Highest virtual address to search for. |
| 870 |
:param int nr_items: Maximum amount of items to return. Defaults to no limit. |
| 871 |
:returns: Block Group items from the Extent Tree or Block Group Tree |
| 872 |
:rtype: Iterator[:class:`~btrfs.ctree.BlockGroupItem`] |
| 873 |
""" |
| 874 |
if not self._block_group_tree: |
| 875 |
for chunk in self.chunks(min_vaddr, max_vaddr, nr_items): |
| 876 |
try: |
| 877 |
yield self.block_group(chunk.vaddr, chunk.length) |
| 878 |
except btrfs.ctree.ItemNotFoundError: |
| 879 |
|
| 880 |
|
| 881 |
|
| 882 |
pass |
| 883 |
else: |
| 884 |
tree = BLOCK_GROUP_TREE_OBJECTID |
| 885 |
min_key = Key(min_vaddr, BLOCK_GROUP_ITEM_KEY, 0) |
| 886 |
max_key = Key(max_vaddr, BLOCK_GROUP_ITEM_KEY, ULLONG_MAX) |
| 887 |
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key, |
| 888 |
nr_items=nr_items): |
| 889 |
yield BlockGroupItem(header, data) |
| 890 |
|
| 891 |
def block_group(self, vaddr, length=None): |
| 892 |
""" |
| 893 |
:param int vaddr: Starting virtual address of the block group. |
| 894 |
:param int length: Block group length (optional). If this information |
| 895 |
is already known, it can be used to construct an exact match for |
| 896 |
the search key. |
| 897 |
:returns: Block Group Item |
| 898 |
:rtype: :class:`~btrfs.ctree.BlockGroupItem` |
| 899 |
:raises: :class:`ItemNotFoundError` if no Block Group Item can be found |
| 900 |
at the address. |
| 901 |
""" |
| 902 |
if not self._block_group_tree: |
| 903 |
tree = EXTENT_TREE_OBJECTID |
| 904 |
else: |
| 905 |
tree = BLOCK_GROUP_TREE_OBJECTID |
| 906 |
min_offset = length if length is not None else 0 |
| 907 |
max_offset = length if length is not None else ULLONG_MAX |
| 908 |
min_key = Key(vaddr, BLOCK_GROUP_ITEM_KEY, min_offset) |
| 909 |
max_key = Key(vaddr, BLOCK_GROUP_ITEM_KEY, max_offset) |
| 910 |
block_groups = [BlockGroupItem(header, data) |
| 911 |
for header, data in |
| 912 |
btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key, nr_items=1)] |
| 913 |
if len(block_groups) == 0: |
| 914 |
raise ItemNotFoundError("No block group at vaddr {}".format(vaddr)) |
| 915 |
return block_groups[0] |
| 916 |
|
| 917 |
def extents(self, min_vaddr=0, max_vaddr=ULLONG_MAX, |
| 918 |
load_data_refs=False, load_metadata_refs=False): |
| 919 |
""" |
| 920 |
:param int min_vaddr: Lowest virtual address to search for. |
| 921 |
:param int max_vaddr: Highest virtual address to search for. |
| 922 |
:param bool load_data_refs: Parse and load backreference information |
| 923 |
for data extents. |
| 924 |
:param bool load_metadata_refs: Parse and load backreference |
| 925 |
information for metadata extents. |
| 926 |
:returns: Extent and MetaData Items from the Extent tree |
| 927 |
:rtype: Iterator[Union[:class:`ExtentItem`, :class:`MetaDataItem`]] |
| 928 |
|
| 929 |
The 'refs' are backreference information. These sub items are stored |
| 930 |
inside the :class:`ExtentItem` and :class:`MetaDataItem` Items, and |
| 931 |
overflow to separately indexed items. When dealing with search results |
| 932 |
in user space, these backreferences are of little use to us, since the |
| 933 |
search API only allows us to search in tree leaves. So, they're ignored |
| 934 |
by default. |
| 935 |
""" |
| 936 |
tree = EXTENT_TREE_OBJECTID |
| 937 |
min_key = Key(min_vaddr, 0, 0) |
| 938 |
max_key = Key(max_vaddr, 255, ULLONG_MAX) |
| 939 |
extent = None |
| 940 |
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key): |
| 941 |
if header.type == EXTENT_ITEM_KEY: |
| 942 |
if extent is not None: |
| 943 |
yield extent |
| 944 |
extent = ExtentItem(header, data, load_data_refs=load_data_refs, |
| 945 |
load_metadata_refs=load_metadata_refs) |
| 946 |
elif header.type == METADATA_ITEM_KEY: |
| 947 |
if extent is not None: |
| 948 |
yield extent |
| 949 |
extent = MetaDataItem(header, data, load_refs=load_metadata_refs) |
| 950 |
elif header.type == EXTENT_DATA_REF_KEY: |
| 951 |
if load_data_refs: |
| 952 |
extent._append_extent_data_ref(ExtentDataRef(header, data)) |
| 953 |
elif header.type == SHARED_DATA_REF_KEY: |
| 954 |
if load_data_refs: |
| 955 |
extent._append_shared_data_ref(SharedDataRef(header, data)) |
| 956 |
elif header.type == TREE_BLOCK_REF_KEY: |
| 957 |
if load_metadata_refs: |
| 958 |
extent._append_tree_block_ref(TreeBlockRef(header)) |
| 959 |
elif header.type == SHARED_BLOCK_REF_KEY: |
| 960 |
if load_metadata_refs: |
| 961 |
extent._append_shared_block_ref(SharedBlockRef(header)) |
| 962 |
elif header.type != BLOCK_GROUP_ITEM_KEY: |
| 963 |
raise Exception("BUG: unexpected object {}".format( |
| 964 |
Key(header.objectid, header.type, header.offset))) |
| 965 |
|
| 966 |
if extent is not None: |
| 967 |
yield extent |
| 968 |
|
| 969 |
def top_level(self): |
| 970 |
""" |
| 971 |
:returns: The top level subvolume with ID 5, a.k.a. `FS_TREE_OBJECTID`. |
| 972 |
:rtype: :class:`RootItem` |
| 973 |
""" |
| 974 |
return list(self.subvolumes(min_id=FS_TREE_OBJECTID, max_id=FS_TREE_OBJECTID))[0] |
| 975 |
|
| 976 |
def subvolumes(self, min_id=FIRST_FREE_OBJECTID, max_id=LAST_FREE_OBJECTID): |
| 977 |
""" |
| 978 |
:param int min_id: Lowest subvolume ID to search for. |
| 979 |
:param int max_id: Highest subvolume ID to search for. |
| 980 |
:returns: Root Items from the Root tree, containing subvolume information. |
| 981 |
:rtype: Iterator[:class:`RootItem`] |
| 982 |
""" |
| 983 |
tree = ROOT_TREE_OBJECTID |
| 984 |
if min_id == max_id: |
| 985 |
min_type = ROOT_ITEM_KEY |
| 986 |
max_type = ROOT_ITEM_KEY |
| 987 |
else: |
| 988 |
min_type = 0 |
| 989 |
max_type = 255 |
| 990 |
min_key = Key(min_id, min_type, 0) |
| 991 |
max_key = Key(max_id, max_type, ULLONG_MAX) |
| 992 |
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key): |
| 993 |
if header.type != ROOT_ITEM_KEY: |
| 994 |
continue |
| 995 |
yield RootItem(header, data) |
| 996 |
|
| 997 |
def orphan_subvol_ids(self): |
| 998 |
""" |
| 999 |
:returns: ObjectID numbers of orphaned items in the Root tree. |
| 1000 |
:rtype: List[int] |
| 1001 |
""" |
| 1002 |
tree = ROOT_TREE_OBJECTID |
| 1003 |
min_key = Key(ORPHAN_OBJECTID, ORPHAN_ITEM_KEY, 0) |
| 1004 |
max_key = Key(ORPHAN_OBJECTID, ORPHAN_ITEM_KEY, ULLONG_MAX) |
| 1005 |
subvol_ids = [header.offset |
| 1006 |
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key)] |
| 1007 |
return subvol_ids |
| 1008 |
|
| 1009 |
def free_space_extents(self, min_vaddr=0, max_vaddr=ULLONG_MAX): |
| 1010 |
""" |
| 1011 |
:param int min_vaddr: Minimum virtual address when searching for free space. |
| 1012 |
:param int max_vaddr: Maximum virtual address when searching for free space. |
| 1013 |
:returns: Free space extent information from the Free Space Tree. |
| 1014 |
:rtype: Iterator[:class:`btrfs.free_space_tree.FreeSpaceExtent`] |
| 1015 |
|
| 1016 |
.. note:: |
| 1017 |
|
| 1018 |
The Free Space Tree can contain both Free Space Extent Items and |
| 1019 |
Free Space Bitmap Items, which contain a more compact |
| 1020 |
representation of free space extents. This helper function will |
| 1021 |
transparently unpack these bitmaps and return one type of helper |
| 1022 |
object, the :class:`~btrfs.free_space_tree.FreeSpaceExtent` |
| 1023 |
object. |
| 1024 |
""" |
| 1025 |
tree = FREE_SPACE_TREE_OBJECTID |
| 1026 |
min_key = Key(min_vaddr, 0, 0) |
| 1027 |
max_key = Key(max_vaddr, 255, ULLONG_MAX) |
| 1028 |
for header, data in btrfs.ioctl.search_v2(self.fd, tree, min_key, max_key): |
| 1029 |
if header.type == FREE_SPACE_EXTENT_KEY: |
| 1030 |
yield btrfs.free_space_tree.FreeSpaceExtent(header.objectid, header.offset) |
| 1031 |
elif header.type == FREE_SPACE_BITMAP_KEY: |
| 1032 |
yield from FreeSpaceBitmap(header, data).unpack(self.sectorsize) |
| 1033 |
elif header.type != FREE_SPACE_INFO_KEY: |
| 1034 |
raise Exception("BUG: unexpected object {}".format( |
| 1035 |
Key(header.objectid, header.type, header.offset))) |
| 1036 |
|
| 1037 |
def sync(self): |
| 1038 |
"""Call the btrfs sync kernel function, causing a transaction commit.""" |
| 1039 |
btrfs.ioctl.sync(self.fd) |
| 1040 |
|
| 1041 |
def features(self): |
| 1042 |
""" |
| 1043 |
:returns: Filesystem Features. |
| 1044 |
:rtype: :class:`btrfs.ioctl.FeatureFlags` |
| 1045 |
""" |
| 1046 |
return btrfs.ioctl.get_features(self.fd) |
| 1047 |
|
| 1048 |
def mixed_groups(self): |
| 1049 |
""" |
| 1050 |
:returns: True if this filesystem used mixed block groups with metadata |
| 1051 |
and data in the same block groups, else False. |
| 1052 |
:rtype: bool |
| 1053 |
""" |
| 1054 |
return self.features().incompat_flags & btrfs.ioctl.FEATURE_INCOMPAT_MIXED_GROUPS != 0 |
| 1055 |
|
| 1056 |
def usage(self): |
| 1057 |
""" |
| 1058 |
:returns: Detailed filesystem usage information. |
| 1059 |
:rtype: :class:`btrfs.fs_usage.FsUsage` |
| 1060 |
""" |
| 1061 |
return btrfs.fs_usage.FsUsage(self) |
| 1062 |
|
| 1063 |
def __exit__(self, exc_type, exc_value, exc_traceback): |
| 1064 |
os.close(self.fd) |
| 1065 |
|
| 1066 |
|
| 1067 |
class ItemData(object): |
| 1068 |
"""ItemData is a base class for all tree item types. |
| 1069 |
|
| 1070 |
:ivar key: Key under which this item is stored in the tree. |
| 1071 |
:type key: :class:`~btrfs.ctree.Key` |
| 1072 |
""" |
| 1073 |
def __init__(self, header): |
| 1074 |
if isinstance(header, btrfs.ioctl.SearchHeader): |
| 1075 |
self.key = Key(header.objectid, header.type, header.offset) |
| 1076 |
elif header is not None: |
| 1077 |
raise TypeError("Not a SearchHeader: {}".format(header)) |
| 1078 |
|
| 1079 |
def _setattr_from_key(self, objectid_attr=None, type_attr=None, offset_attr=None): |
| 1080 |
if objectid_attr is not None: |
| 1081 |
setattr(self, objectid_attr, self.key.objectid) |
| 1082 |
if type_attr is not None: |
| 1083 |
setattr(self, type_attr, self.key.type) |
| 1084 |
if offset_attr is not None: |
| 1085 |
setattr(self, offset_attr, self.key.offset) |
| 1086 |
self._key_attrs = objectid_attr, type_attr, offset_attr |
| 1087 |
|
| 1088 |
def __lt__(self, other): |
| 1089 |
return self.key < other.key |
| 1090 |
|
| 1091 |
|
| 1092 |
class SubItem(object): |
| 1093 |
pass |
| 1094 |
|
| 1095 |
|
| 1096 |
class DevItem(ItemData): |
| 1097 |
"""Object representation of struct `btrfs_dev_item`. |
| 1098 |
|
| 1099 |
A `DevItem` contains information about a single block device that is |
| 1100 |
attached to the filesystem. |
| 1101 |
|
| 1102 |
* Tree: `CHUNK_TREE_OBJECTID` (3) |
| 1103 |
* Key objectid: `DEV_ITEMS_OBJECTID` (1) |
| 1104 |
* Key type: `DEV_ITEM_KEY` (216) |
| 1105 |
* Key offset: Device ID. |
| 1106 |
|
| 1107 |
:ivar int devid: Device ID. |
| 1108 |
:ivar int total_bytes: Total amount of bytes. |
| 1109 |
:ivar int bytes_used: Total amount of allocated bytes. |
| 1110 |
:ivar int io_align: *Not used*, set to same value as sector_size. |
| 1111 |
:ivar int io_width: *Not used*, set to same value as sector_size. |
| 1112 |
:ivar int sector_size: Smallest IO block size to use. |
| 1113 |
:ivar int type: *Not used* |
| 1114 |
:ivar int generation: *Not used* |
| 1115 |
:ivar int start_offset: *Not used* |
| 1116 |
:ivar int dev_group: *Not used* |
| 1117 |
:ivar int seek_speed: *Not used* |
| 1118 |
:ivar int bandwidth: *Not used* |
| 1119 |
:ivar uuid.UUID uuid: Device UUID. |
| 1120 |
:ivar uuid.UUID fsid: Filesystem ID. |
| 1121 |
|
| 1122 |
""" |
| 1123 |
_dev_item = struct.Struct('<3Q3L3QL2B16s16s') |
| 1124 |
|
| 1125 |
def __init__(self, header, data): |
| 1126 |
super().__init__(header) |
| 1127 |
self.devid, self.total_bytes, self.bytes_used, self.io_align, self.io_width, \ |
| 1128 |
self.sector_size, self.type, self.generation, self.start_offset, self.dev_group, \ |
| 1129 |
self.seek_speed, self.bandwidth, uuid_bytes, fsid_bytes = \ |
| 1130 |
DevItem._dev_item.unpack(data) |
| 1131 |
self.uuid = uuid.UUID(bytes=uuid_bytes) |
| 1132 |
self.fsid = uuid.UUID(bytes=fsid_bytes) |
| 1133 |
|
| 1134 |
def __str__(self): |
| 1135 |
return "dev item devid {self.devid} uuid {self.uuid} bytes_used {self.bytes_used} " \ |
| 1136 |
"total_bytes {self.total_bytes}".format(self=self) |
| 1137 |
|
| 1138 |
|
| 1139 |
class Chunk(ItemData): |
| 1140 |
"""Object representation of struct `btrfs_chunk`. |
| 1141 |
|
| 1142 |
A `Chunk` is a piece of virtual address space. A `Chunk` has a 1 to 1 |
| 1143 |
relationship to a :class:`BlockGroupItem`, and a 1 to many relationship |
| 1144 |
with a fixed amount of :class:`Stripe` objects. |
| 1145 |
|
| 1146 |
* Tree: `CHUNK_TREE_OBJECTID` (3) |
| 1147 |
* Key objectid: `FIRST_CHUNK_TREE_OBJECTID` (256) |
| 1148 |
* Key type: `CHUNK_ITEM_KEY` (228) |
| 1149 |
* Key offset: Virtual address. |
| 1150 |
|
| 1151 |
:ivar int vaddr: Virtual address where the Chunk starts (taken from the |
| 1152 |
offset field of the item key). |
| 1153 |
:ivar int length: Chunk length in bytes, |
| 1154 |
:ivar int owner: Extent tree the chunk belongs to. *Not used*, always 2 |
| 1155 |
now. |
| 1156 |
:ivar int stripe_len: Hardcoded to `BTRFS_STRIPE_LEN`, which is 64kiB. |
| 1157 |
:ivar int type: Block group flags for the corresponding block group. So, a |
| 1158 |
Chunk **type** contains both Block Group **type** and **profile**. |
| 1159 |
:ivar int io_align: *Not used*, see `stripe_len`. |
| 1160 |
:ivar int io_width: *Not used*, see `stripe_len`. |
| 1161 |
:ivar int sector_size: Smallest IO block size to use. |
| 1162 |
:ivar int num_stripes: Amount of :class:`Stripe` (or, also the amount of |
| 1163 |
:class:`Device Extent`) objects related to this `Chunk`. |
| 1164 |
:ivar int sub_stripes: A hack for `RAID10`. For `RAID10` this value is 2, |
| 1165 |
otherwise 1. |
| 1166 |
:ivar stripes: :class:`Stripe` Items that are stored inside this Chunk Item. |
| 1167 |
:vartype stripes: List[:class:`Stripe`] |
| 1168 |
""" |
| 1169 |
_chunk = struct.Struct('<4Q3L2H') |
| 1170 |
|
| 1171 |
def __init__(self, header, data): |
| 1172 |
super().__init__(header) |
| 1173 |
self._setattr_from_key(offset_attr='vaddr') |
| 1174 |
self.length, self.owner, self.stripe_len, self.type, self.io_align, \ |
| 1175 |
self.io_width, self.sector_size, self.num_stripes, self.sub_stripes = \ |
| 1176 |
Chunk._chunk.unpack_from(data) |
| 1177 |
self.stripes = [] |
| 1178 |
pos = Chunk._chunk.size |
| 1179 |
for i in range(self.num_stripes): |
| 1180 |
next_pos = pos + Stripe._stripe.size |
| 1181 |
self.stripes.append(Stripe(data[pos:next_pos])) |
| 1182 |
pos = next_pos |
| 1183 |
|
| 1184 |
def __str__(self): |
| 1185 |
return "chunk vaddr {self.vaddr} type {self.type_str} length {self.length_str} " \ |
| 1186 |
"num_stripes {self.num_stripes}".format(self=self) |
| 1187 |
|
| 1188 |
@staticmethod |
| 1189 |
def _pretty_properties(): |
| 1190 |
return [ |
| 1191 |
(btrfs.utils.pretty_size, 'length'), |
| 1192 |
(btrfs.utils.pretty_size, 'stripe_len'), |
| 1193 |
(btrfs.utils.pretty_size, 'io_align'), |
| 1194 |
(btrfs.utils.pretty_size, 'io_width'), |
| 1195 |
(btrfs.utils.pretty_size, 'sector_size'), |
| 1196 |
(btrfs.utils.block_group_flags_str, 'type'), |
| 1197 |
] |
| 1198 |
|
| 1199 |
|
| 1200 |
class Stripe(SubItem): |
| 1201 |
"""Object representation of struct `btrfs_stripe`. |
| 1202 |
|
| 1203 |
A list of `Stripe` items is hidden inside the `Chunk` item and each of them |
| 1204 |
contains information that points to the beginning of a `Device Extent`, |
| 1205 |
which is an actual allocated piece of physical disk space in which data |
| 1206 |
ends up that is written to the virtual address space of the `Chunk`. |
| 1207 |
|
| 1208 |
:ivar int devid: Device ID of the device that holds the `Device Extent`. |
| 1209 |
:ivar int offset: Physical address on the device where the `Device Extent` starts. |
| 1210 |
:ivar uuid.UUID uuid: Device UUID of the device with the above listed devid. |
| 1211 |
""" |
| 1212 |
_stripe = struct.Struct('<2Q16s') |
| 1213 |
|
| 1214 |
def __init__(self, data): |
| 1215 |
self.devid, self.offset, uuid_bytes = Stripe._stripe.unpack(data) |
| 1216 |
self.uuid = uuid.UUID(bytes=uuid_bytes) |
| 1217 |
|
| 1218 |
def __str__(self): |
| 1219 |
return "stripe devid {self.devid} offset {self.offset}".format(self=self) |
| 1220 |
|
| 1221 |
|
| 1222 |
class DevExtent(ItemData): |
| 1223 |
"""Object representation of struct `btrfs_dev_extent`. |
| 1224 |
|
| 1225 |
The `Device Extent` is a range of physical address space allocated from one |
| 1226 |
of the attached devices and used by a `Chunk` to store data. |
| 1227 |
|
| 1228 |
* Tree: `DEV_TREE_OBJECTID` (4) |
| 1229 |
* Key objectid: Device ID. |
| 1230 |
* Key type: `DEV_EXTENT_KEY` (204) |
| 1231 |
* Key offset: Physical address. |
| 1232 |
|
| 1233 |
:ivar int devid: Device ID of the device that holds this `Device Extent` |
| 1234 |
(taken from the objectid field of the item key). |
| 1235 |
:ivar int paddr: Physical address on the device where the `Device Extent` |
| 1236 |
starts (taken from the offset field of the item key). |
| 1237 |
:ivar int chunk_tree: Chunk tree the device extent belongs to. This is |
| 1238 |
always 3 now. |
| 1239 |
:ivar int chunk_offset: Virtual address of the related `Chunk`. |
| 1240 |
:ivar int length: Length in physical bytes. |
| 1241 |
:ivar uuid.UUID chunk_tree_uuid: UUID of the chunk tree that this `Device |
| 1242 |
Extent` belongs to. This is currently always the UUID of tree 3. |
| 1243 |
""" |
| 1244 |
_dev_extent = struct.Struct('<4Q16s') |
| 1245 |
|
| 1246 |
def __init__(self, header, data): |
| 1247 |
super().__init__(header) |
| 1248 |
self._setattr_from_key(objectid_attr='devid', offset_attr='paddr') |
| 1249 |
self.chunk_tree, self.chunk_objectid, self.chunk_offset, self.length, \ |
| 1250 |
chunk_tree_uuid_bytes = DevExtent._dev_extent.unpack(data) |
| 1251 |
self.chunk_tree_uuid = uuid.UUID(bytes=chunk_tree_uuid_bytes) |
| 1252 |
|
| 1253 |
@property |
| 1254 |
def vaddr(self): |
| 1255 |
"""Alias for the chunk_offset attribute.""" |
| 1256 |
return self.chunk_offset |
| 1257 |
|
| 1258 |
def __str__(self): |
| 1259 |
return "dev extent devid {self.devid} paddr {self.paddr} length {self.length_str} " \ |
| 1260 |
"chunk {self.chunk_offset}".format(self=self) |
| 1261 |
|
| 1262 |
@staticmethod |
| 1263 |
def _pretty_properties(): |
| 1264 |
return [ |
| 1265 |
(btrfs.utils.pretty_size, 'length'), |
| 1266 |
] |
| 1267 |
|
| 1268 |
|
| 1269 |
class BlockGroupItem(ItemData): |
| 1270 |
"""Object representation of struct `btrfs_block_group_item`. |
| 1271 |
|
| 1272 |
The `Block Group` has a 1 to 1 relationship with a `Chunk` and tracks some |
| 1273 |
usage information about a range of virtual address space. |
| 1274 |
|
| 1275 |
* Tree: `EXTENT_TREE_OBJECTID` (2) or `BLOCK_GROUP_TREE_OBJECTID` (11) |
| 1276 |
* Key objectid: Virtual address. |
| 1277 |
* Key type: `BLOCK_GROUP_ITEM_KEY` (192) |
| 1278 |
* Key offset: Block Group length. |
| 1279 |
|
| 1280 |
If the block_group_tree feature is enabled on the filesystem, these items |
| 1281 |
can be found inside the Block Group Tree instead of the Extent Tree. |
| 1282 |
|
| 1283 |
:ivar int vaddr: Virtual address where the Bock Group starts (taken from |
| 1284 |
the objectid field of the item key). |
| 1285 |
:ivar int length: Block Group length in bytes (taken from the offset field |
| 1286 |
of the item key). |
| 1287 |
:ivar int used: Amount of bytes used by Extents in the Block Group. |
| 1288 |
:ivar int chunk_objectid: Object ID of the Chunk this Block Group relates |
| 1289 |
to. Currently always 256. |
| 1290 |
:ivar int flags: Type and profile for this Block Group. e.g. 0x11, which is |
| 1291 |
`DATA|RAID1`. |
| 1292 |
""" |
| 1293 |
_block_group_item = struct.Struct('<3Q') |
| 1294 |
|
| 1295 |
def __init__(self, header, data): |
| 1296 |
super().__init__(header) |
| 1297 |
self._setattr_from_key(objectid_attr='vaddr', offset_attr='length') |
| 1298 |
self.used, self.chunk_objectid, self.flags = \ |
| 1299 |
BlockGroupItem._block_group_item.unpack(data) |
| 1300 |
|
| 1301 |
@property |
| 1302 |
def used_pct(self): |
| 1303 |
"""Convenience property that calculates the percentage of usage.""" |
| 1304 |
return int(round((self.used * 100) / self.length)) |
| 1305 |
|
| 1306 |
def __str__(self): |
| 1307 |
return "block group vaddr {self.vaddr} length {self.length} " \ |
| 1308 |
"flags {self.flags_str} used {self.used} used_pct {self.used_pct}".format(self=self) |
| 1309 |
|
| 1310 |
@staticmethod |
| 1311 |
def _pretty_properties(): |
| 1312 |
return [ |
| 1313 |
(btrfs.utils.pretty_size, 'length'), |
| 1314 |
(btrfs.utils.pretty_size, 'used'), |
| 1315 |
(btrfs.utils.block_group_flags_str, 'flags'), |
| 1316 |
] |
| 1317 |
|
| 1318 |
|
| 1319 |
class ExtentItem(ItemData): |
| 1320 |
"""Object representation of struct `btrfs_extent_item`. |
| 1321 |
|
| 1322 |
An :class:`ExtentItem` lives in the Extent Tree and tracks information |
| 1323 |
about a piece of virtual address space that is in use. A FileExtentItem |
| 1324 |
object from a subvolume tree can point to it, to let us know a file in the |
| 1325 |
filesystem uses part of this extent. |
| 1326 |
|
| 1327 |
* Tree: `EXTENT_TREE_OBJECTID` (2) |
| 1328 |
* Key objectid: Virtual address. |
| 1329 |
* Key type: `EXTENT_ITEM_KEY` (168) |
| 1330 |
* Key offset: Extent length. |
| 1331 |
|
| 1332 |
If the `skinny_metadata` feature is enabled in the filesystem, then |
| 1333 |
metadata extents are stored separately as :class:`MetaDataItem`. |
| 1334 |
|
| 1335 |
An :class:`ExtentItem` includes inline backreference items. In the kernel, |
| 1336 |
this information is used to be able to find out which different inodes in |
| 1337 |
subvolume trees are using data from this extent. For us, in userspace, this |
| 1338 |
information is not very relevant, since we cannot look into B-tree nodes |
| 1339 |
using the kernel search API. So, by default the backreference information |
| 1340 |
is ignored when creating these kind of objects from a metadata search. |
| 1341 |
|
| 1342 |
Instead, to find out who is referencing data from an extent, the |
| 1343 |
:func:`btrfs.ioctl.logical_ino` and |
| 1344 |
:func:`btrfs.ioctl.logical_ino_v2` functions can be used. |
| 1345 |
|
| 1346 |
:ivar int vaddr: Virtual address where the Extent starts (taken from the |
| 1347 |
objectid field of the item key). |
| 1348 |
:ivar int length: Length of the extent in bytes (taken from the offset |
| 1349 |
field of the item key). |
| 1350 |
:ivar int refs: Amount of explicit references to this extent. |
| 1351 |
:ivar int generation: Generation of the filesystem when this extent was |
| 1352 |
created. |
| 1353 |
:ivar int flags: Some flags describing which type of extent this is. |
| 1354 |
|
| 1355 |
The flags are an or-ed combination of one or more of the following values |
| 1356 |
(available as attribute of this module): |
| 1357 |
|
| 1358 |
- EXTENT_FLAG_DATA: This extent contains data. |
| 1359 |
- EXTENT_FLAG_TREE_BLOCK: This extent contains a metadata tree block. |
| 1360 |
- BLOCK_FLAG_FULL_BACKREF: The tree block backreference contains a full |
| 1361 |
back reference. |
| 1362 |
|
| 1363 |
When backreference information is being loaded, there are a few additional |
| 1364 |
lists present in this object. Also, when using the |
| 1365 |
:func:`FileSystem.extents` helper to retrieve extent information, then |
| 1366 |
separately stored backreference items which do not fit into the extent item |
| 1367 |
itself any more are also appended to these lists: |
| 1368 |
|
| 1369 |
If the extent is a data extent, then this object contains: |
| 1370 |
|
| 1371 |
:ivar extent_data_refs: Indirect back references. |
| 1372 |
:vartype extent_data_refs: List[Union[:class:`InlineExtentDataRef`, |
| 1373 |
:class:`ExtentDataRef`]] |
| 1374 |
:ivar shared_data_refs: Shared back references. |
| 1375 |
:vartype shared_data_refs: List[Union[:class:`InlineSharedDataRef`, |
| 1376 |
:class:`SharedDataRef`]] |
| 1377 |
|
| 1378 |
If the extent is a metadata tree block, then this object contains: |
| 1379 |
|
| 1380 |
:ivar tree_block_refs: Tree block backreferences. |
| 1381 |
:vartype tree_block_refs: List[Union[:class:`InlineTreeBlockRef`, |
| 1382 |
:class:`TreeBlockRef`]] |
| 1383 |
:ivar shared_block_refs: Shared tree block backreferences. |
| 1384 |
:vartype shared_block_refs: List[Union[:class:`InlineSharedBlockRef`, |
| 1385 |
:class:`SharedBlockRef`]] |
| 1386 |
|
| 1387 |
Further documentation of backreferences is out of scope for this module. |
| 1388 |
Please refer to the btrfs wiki about resolving extent backreferences for |
| 1389 |
more information. |
| 1390 |
""" |
| 1391 |
_extent_item = struct.Struct('<3Q') |
| 1392 |
_extent_inline_ref = struct.Struct('<BQ') |
| 1393 |
|
| 1394 |
def __init__(self, header, data, load_data_refs=True, load_metadata_refs=True): |
| 1395 |
super().__init__(header) |
| 1396 |
self._setattr_from_key(objectid_attr='vaddr', offset_attr='length') |
| 1397 |
pos = 0 |
| 1398 |
self.refs, self.generation, self.flags = ExtentItem._extent_item.unpack_from(data, pos) |
| 1399 |
pos += ExtentItem._extent_item.size |
| 1400 |
if self.flags == EXTENT_FLAG_DATA and load_data_refs: |
| 1401 |
self.extent_data_refs = [] |
| 1402 |
self.shared_data_refs = [] |
| 1403 |
while pos < len(data): |
| 1404 |
inline_ref_type, inline_ref_offset = \ |
| 1405 |
ExtentItem._extent_inline_ref.unpack_from(data, pos) |
| 1406 |
if inline_ref_type == EXTENT_DATA_REF_KEY: |
| 1407 |
pos += 1 |
| 1408 |
next_pos = pos + InlineExtentDataRef._inline_extent_data_ref.size |
| 1409 |
self.extent_data_refs.append(InlineExtentDataRef(data[pos:next_pos])) |
| 1410 |
pos = next_pos |
| 1411 |
elif inline_ref_type == SHARED_DATA_REF_KEY: |
| 1412 |
pos += 1 |
| 1413 |
next_pos = pos + InlineSharedDataRef._inline_shared_data_ref.size |
| 1414 |
self.shared_data_refs.append(InlineSharedDataRef(data[pos:next_pos])) |
| 1415 |
pos = next_pos |
| 1416 |
elif self.flags & EXTENT_FLAG_TREE_BLOCK and load_metadata_refs: |
| 1417 |
next_pos = pos + TreeBlockInfo._tree_block_info.size |
| 1418 |
self.tree_block_info = TreeBlockInfo(data[pos:next_pos]) |
| 1419 |
pos = next_pos |
| 1420 |
self.tree_block_refs = [] |
| 1421 |
self.shared_block_refs = [] |
| 1422 |
while pos < len(data): |
| 1423 |
inline_ref_type, inline_ref_offset = \ |
| 1424 |
ExtentItem._extent_inline_ref.unpack_from(data, pos) |
| 1425 |
if inline_ref_type == TREE_BLOCK_REF_KEY: |
| 1426 |
self.tree_block_refs.append(InlineTreeBlockRef(inline_ref_offset)) |
| 1427 |
elif inline_ref_type == SHARED_BLOCK_REF_KEY: |
| 1428 |
self.shared_block_refs.append(InlineSharedBlockRef(inline_ref_offset)) |
| 1429 |
else: |
| 1430 |
raise Exception("BUG: expected inline TREE_BLOCK_REF or SHARED_BLOCK_REF_KEY " |
| 1431 |
"but got inline_ref_type {}".format(inline_ref_type)) |
| 1432 |
pos += ExtentItem._extent_inline_ref.size |
| 1433 |
|
| 1434 |
def _append_extent_data_ref(self, ref): |
| 1435 |
self.extent_data_refs.append(ref) |
| 1436 |
|
| 1437 |
def _append_shared_data_ref(self, ref): |
| 1438 |
self.shared_data_refs.append(ref) |
| 1439 |
|
| 1440 |
def _append_tree_block_ref(self, ref): |
| 1441 |
self.tree_block_refs.append(ref) |
| 1442 |
|
| 1443 |
def _append_shared_block_ref(self, ref): |
| 1444 |
self.shared_block_refs.append(ref) |
| 1445 |
|
| 1446 |
def __str__(self): |
| 1447 |
return "extent vaddr {self.vaddr} length {self.length} refs {self.refs} " \ |
| 1448 |
"gen {self.generation} flags {self.flags_str}".format(self=self) |
| 1449 |
|
| 1450 |
@staticmethod |
| 1451 |
def _pretty_properties(): |
| 1452 |
return [ |
| 1453 |
(btrfs.utils.extent_flags_str, 'flags'), |
| 1454 |
] |
| 1455 |
|
| 1456 |
|
| 1457 |
class ExtentDataRef(ItemData): |
| 1458 |
"""Object representation of struct `btrfs_extent_data_ref`. |
| 1459 |
|
| 1460 |
Documentation of this item is out of scope for this module. Please refer to |
| 1461 |
the btrfs wiki about resolving extent backreferences for more information. |
| 1462 |
|
| 1463 |
* Tree: `EXTENT_TREE_OBJECTID` (2) |
| 1464 |
* Key type: `EXTENT_DATA_REF_KEY` (178) |
| 1465 |
|
| 1466 |
:ivar int root: root |
| 1467 |
:ivar int objectid: objectid |
| 1468 |
:ivar int offset: offset |
| 1469 |
:ivar int count: count |
| 1470 |
""" |
| 1471 |
_extent_data_ref = struct.Struct('<3QL') |
| 1472 |
|
| 1473 |
def __init__(self, header, data): |
| 1474 |
super().__init__(header) |
| 1475 |
self.root, self.objectid, self.offset, self.count = \ |
| 1476 |
ExtentDataRef._extent_data_ref.unpack(data) |
| 1477 |
|
| 1478 |
def __str__(self): |
| 1479 |
return "extent data backref root {self.root} objectid {self.objectid} " \ |
| 1480 |
"offset {self.offset} count {self.count}".format(self=self) |
| 1481 |
|
| 1482 |
|
| 1483 |
class InlineExtentDataRef(ExtentDataRef): |
| 1484 |
"""Identical content to :class:`ExtentDataRef`, but the backreference was |
| 1485 |
inlined in the extent item.""" |
| 1486 |
_inline_extent_data_ref = ExtentDataRef._extent_data_ref |
| 1487 |
|
| 1488 |
def __init__(self, data): |
| 1489 |
self.root, self.objectid, self.offset, self.count = \ |
| 1490 |
InlineExtentDataRef._inline_extent_data_ref.unpack(data) |
| 1491 |
|
| 1492 |
def __str__(self): |
| 1493 |
return "inline extent data backref root {self.root} objectid {self.objectid} " \ |
| 1494 |
"offset {self.offset} count {self.count}".format(self=self) |
| 1495 |
|
| 1496 |
|
| 1497 |
class SharedDataRef(ItemData): |
| 1498 |
"""Object representation of struct `btrfs_shared_data_ref`. |
| 1499 |
|
| 1500 |
Documentation of this item is out of scope for this module. Please refer to |
| 1501 |
the btrfs wiki about resolving extent backreferences for more information. |
| 1502 |
|
| 1503 |
* Tree: `EXTENT_TREE_OBJECTID` (2) |
| 1504 |
* Key type: `SHARED_DATA_REF_KEY` (184) |
| 1505 |
|
| 1506 |
:ivar int parent: parent |
| 1507 |
:ivar int count: count |
| 1508 |
""" |
| 1509 |
_shared_data_ref = struct.Struct('<L') |
| 1510 |
|
| 1511 |
def __init__(self, header, data): |
| 1512 |
super().__init__(header) |
| 1513 |
self._setattr_from_key(offset_attr='parent') |
| 1514 |
self.count, = SharedDataRef._shared_data_ref.unpack(data) |
| 1515 |
|
| 1516 |
def __str__(self): |
| 1517 |
return "shared data backref parent {self.parent} count {self.count}".format(self=self) |
| 1518 |
|
| 1519 |
|
| 1520 |
class InlineSharedDataRef(SharedDataRef): |
| 1521 |
"""Identical content to :class:`SharedDataRef`, but the backreference was |
| 1522 |
inlined in the extent item.""" |
| 1523 |
_inline_shared_data_ref = struct.Struct('<QL') |
| 1524 |
|
| 1525 |
def __init__(self, data): |
| 1526 |
self.parent, self.count = InlineSharedDataRef._inline_shared_data_ref.unpack(data) |
| 1527 |
|
| 1528 |
def __str__(self): |
| 1529 |
return "inline shared data backref parent {self.parent} " \ |
| 1530 |
"count {self.count}".format(self=self) |
| 1531 |
|
| 1532 |
|
| 1533 |
class TreeBlockInfo(SubItem): |
| 1534 |
"""Object representation of struct `btrfs_tree_block_info`. |
| 1535 |
|
| 1536 |
Documentation of this item is out of scope for this module. Please refer to |
| 1537 |
the btrfs wiki about resolving extent backreferences for more information. |
| 1538 |
|
| 1539 |
:ivar key: key |
| 1540 |
:vartype key: :class:`Key` |
| 1541 |
:ivar int level: level |
| 1542 |
""" |
| 1543 |
_tree_block_info = struct.Struct('<QBQB') |
| 1544 |
|
| 1545 |
def __init__(self, data): |
| 1546 |
tb_objectid, tb_type, tb_offset, self.level = \ |
| 1547 |
TreeBlockInfo._tree_block_info.unpack(data) |
| 1548 |
self.key = Key(tb_objectid, tb_type, tb_offset) |
| 1549 |
|
| 1550 |
def __str__(self): |
| 1551 |
return "tree block key {self.key} level {self.level}".format(self=self) |
| 1552 |
|
| 1553 |
|
| 1554 |
class MetaDataItem(ItemData): |
| 1555 |
"""Object representation of struct `btrfs_metadata_item`. |
| 1556 |
|
| 1557 |
A :class:`MetaDataItem` lives in the Extent Tree and tracks information |
| 1558 |
about a piece of virtual address space that is in use to store a metadata |
| 1559 |
tree block. |
| 1560 |
|
| 1561 |
* Tree: `EXTENT_TREE_OBJECTID` (2) |
| 1562 |
* Key objectid: Virtual address. |
| 1563 |
* Key type: `METADATA_ITEM_KEY` (169) |
| 1564 |
* Key offset: Extent length. |
| 1565 |
|
| 1566 |
If the `skinny_metadata` filesystem feature is enabled, metadata extents |
| 1567 |
are tracked using this item type, which encodes all necessecary data in a |
| 1568 |
more compact way than using a regular extent item. |
| 1569 |
|
| 1570 |
:ivar int vaddr: Virtual address where the Extent starts (taken from the |
| 1571 |
objectid field of the item key). |
| 1572 |
:ivar int skinny_level: Tree level. |
| 1573 |
field of the item key). |
| 1574 |
:ivar int refs: Amount of explicit references to this extent. |
| 1575 |
:ivar int generation: Generation of the filesystem when this extent was |
| 1576 |
created. |
| 1577 |
:ivar int flags: See below. |
| 1578 |
|
| 1579 |
The flags are an or-ed combination of one or more of the following values |
| 1580 |
(available as attribute of this module): |
| 1581 |
|
| 1582 |
- EXTENT_FLAG_TREE_BLOCK: This extent contains a metadata tree block. |
| 1583 |
- BLOCK_FLAG_FULL_BACKREF: The tree block backreference contains a full |
| 1584 |
back reference. |
| 1585 |
|
| 1586 |
When backreference information is being loaded, there are a few additional |
| 1587 |
lists present in this object. Also, when using the |
| 1588 |
:func:`FileSystem.extents` helper to retrieve extent information, then |
| 1589 |
separately stored backreference items which do not fit into the extent item |
| 1590 |
itself any more are also appended to these lists: |
| 1591 |
|
| 1592 |
:ivar tree_block_refs: Tree block backreferences. |
| 1593 |
:vartype tree_block_refs: List[Union[:class:`InlineTreeBlockRef`, |
| 1594 |
:class:`TreeBlockRef`]] |
| 1595 |
:ivar shared_block_refs: Shared tree block backreferences. |
| 1596 |
:vartype shared_block_refs: List[Union[:class:`InlineSharedBlockRef`, |
| 1597 |
:class:`SharedBlockRef`]] |
| 1598 |
|
| 1599 |
Further documentation of backreferences is out of scope for this module. |
| 1600 |
Please refer to the btrfs wiki about resolving extent backreferences for |
| 1601 |
more information. |
| 1602 |
""" |
| 1603 |
def __init__(self, header, data, load_refs=True): |
| 1604 |
super().__init__(header) |
| 1605 |
self._setattr_from_key(objectid_attr='vaddr', offset_attr='skinny_level') |
| 1606 |
self.refs, self.generation, self.flags = ExtentItem._extent_item.unpack_from(data) |
| 1607 |
if load_refs: |
| 1608 |
self._load_refs(data[ExtentItem._extent_item.size:]) |
| 1609 |
|
| 1610 |
def _load_refs(self, data): |
| 1611 |
pos = 0 |
| 1612 |
self.tree_block_refs = [] |
| 1613 |
self.shared_block_refs = [] |
| 1614 |
while pos < len(data): |
| 1615 |
inline_ref_type, inline_ref_offset = \ |
| 1616 |
ExtentItem._extent_inline_ref.unpack_from(data, pos) |
| 1617 |
if inline_ref_type == TREE_BLOCK_REF_KEY: |
| 1618 |
self.tree_block_refs.append(InlineTreeBlockRef(inline_ref_offset)) |
| 1619 |
elif inline_ref_type == SHARED_BLOCK_REF_KEY: |
| 1620 |
self.shared_block_refs.append(InlineSharedBlockRef(inline_ref_offset)) |
| 1621 |
else: |
| 1622 |
raise Exception("BUG: expected inline TREE_BLOCK_REF or SHARED_BLOCK_REF_KEY " |
| 1623 |
"in METADATA_ITEM {}, but got inline_ref_type {}" |
| 1624 |
"".format(self.key, inline_ref_type)) |
| 1625 |
pos += ExtentItem._extent_inline_ref.size |
| 1626 |
|
| 1627 |
def _append_tree_block_ref(self, ref): |
| 1628 |
self.tree_block_refs.append(ref) |
| 1629 |
|
| 1630 |
def _append_shared_block_ref(self, ref): |
| 1631 |
self.shared_block_refs.append(ref) |
| 1632 |
|
| 1633 |
def __str__(self): |
| 1634 |
return "metadata vaddr {self.vaddr} refs {self.refs} gen {self.generation} " \ |
| 1635 |
"flags {self.flags_str} skinny level {self.skinny_level}".format(self=self) |
| 1636 |
|
| 1637 |
@staticmethod |
| 1638 |
def _pretty_properties(): |
| 1639 |
return [ |
| 1640 |
(btrfs.utils.extent_flags_str, 'flags'), |
| 1641 |
] |
| 1642 |
|
| 1643 |
|
| 1644 |
class TreeBlockRef(ItemData): |
| 1645 |
"""Tree block reference |
| 1646 |
|
| 1647 |
Documentation of this item is out of scope for this module. Please refer to |
| 1648 |
the btrfs wiki about resolving extent backreferences for more information. |
| 1649 |
|
| 1650 |
* Tree: `EXTENT_TREE_OBJECTID` (2) |
| 1651 |
* Key type: `TREE_BLOCK_REF_KEY` (176) |
| 1652 |
|
| 1653 |
:ivar int root: root |
| 1654 |
""" |
| 1655 |
def __init__(self, header): |
| 1656 |
super().__init__(header) |
| 1657 |
self._setattr_from_key(offset_attr='root') |
| 1658 |
|
| 1659 |
def __str__(self): |
| 1660 |
return "tree block backref root {}".format(_key_objectid_str(self.root, None)) |
| 1661 |
|
| 1662 |
|
| 1663 |
class InlineTreeBlockRef(TreeBlockRef): |
| 1664 |
"""Identical content to :class:`TreeBlockRef`, but the backreference was |
| 1665 |
inlined in the extent item.""" |
| 1666 |
def __init__(self, root): |
| 1667 |
self.root = root |
| 1668 |
|
| 1669 |
def __str__(self): |
| 1670 |
return "inline tree block backref root {}".format(_key_objectid_str(self.root, None)) |
| 1671 |
|
| 1672 |
|
| 1673 |
class SharedBlockRef(ItemData): |
| 1674 |
"""Shared tree block reference |
| 1675 |
|
| 1676 |
Documentation of this item is out of scope for this module. Please refer to |
| 1677 |
the btrfs wiki about resolving extent backreferences for more information. |
| 1678 |
|
| 1679 |
* Tree: `EXTENT_TREE_OBJECTID` (2) |
| 1680 |
* Key type: `SHARED_BLOCK_REF_KEY` (182) |
| 1681 |
|
| 1682 |
:ivar int parent: parent |
| 1683 |
""" |
| 1684 |
def __init__(self, header): |
| 1685 |
super().__init__(header) |
| 1686 |
self._setattr_from_key(offset_attr='parent') |
| 1687 |
|
| 1688 |
def __str__(self): |
| 1689 |
return "shared block backref parent {}".format(self.parent) |
| 1690 |
|
| 1691 |
|
| 1692 |
class InlineSharedBlockRef(SharedBlockRef): |
| 1693 |
"""Identical content to :class:`SharedBlockRef`, but the backreference was |
| 1694 |
inlined in the extent item.""" |
| 1695 |
def __init__(self, parent): |
| 1696 |
self.parent = parent |
| 1697 |
|
| 1698 |
def __str__(self): |
| 1699 |
return "inline shared block backref parent {}".format(self.parent) |
| 1700 |
|
| 1701 |
|
| 1702 |
class TimeSpec(object): |
| 1703 |
"""Object representation of struct `btrfs_timespec`. |
| 1704 |
|
| 1705 |
The :class:`TimeSpec` type of item is used embedded in other metadata items |
| 1706 |
when a time value needs to be stored. Examples are the mtime, ctime etc |
| 1707 |
fields in an inode item. |
| 1708 |
|
| 1709 |
It's also possible to create objects of this type manually. To do so, use |
| 1710 |
the static :func:`~TimeSpec.from_values` helper function. (The regular |
| 1711 |
object constructor is reserved for the code parsing metadata items from |
| 1712 |
search queries.) |
| 1713 |
|
| 1714 |
:ivar int sec: seconds |
| 1715 |
:ivar int nsec: nanoseconds |
| 1716 |
|
| 1717 |
Example:: |
| 1718 |
|
| 1719 |
>>> my_time = btrfs.ctree.TimeSpec.from_values(1546280270, 4044945) |
| 1720 |
>>> my_time.sec |
| 1721 |
1546280270 |
| 1722 |
>>> my_time.nsec |
| 1723 |
4044945 |
| 1724 |
>>> my_time.iso8601 |
| 1725 |
'2018-12-31T18:17:50.404495' |
| 1726 |
""" |
| 1727 |
_timespec = struct.Struct('<QL') |
| 1728 |
|
| 1729 |
@staticmethod |
| 1730 |
def from_values(sec, nsec): |
| 1731 |
"""Create a Timespec object |
| 1732 |
|
| 1733 |
:param int sec: seconds |
| 1734 |
:param int nsec: nanoseconds |
| 1735 |
""" |
| 1736 |
t = TimeSpec.__new__(TimeSpec) |
| 1737 |
t.sec = sec |
| 1738 |
t.nsec = nsec |
| 1739 |
return t |
| 1740 |
|
| 1741 |
def __init__(self, data): |
| 1742 |
self.sec, self.nsec = TimeSpec._timespec.unpack_from(data) |
| 1743 |
|
| 1744 |
@property |
| 1745 |
def iso8601(self): |
| 1746 |
"""Return the timestamp as ISO8601 formatted string.""" |
| 1747 |
return datetime.datetime.utcfromtimestamp( |
| 1748 |
float("{self.sec}.{self.nsec}".format(self=self)) |
| 1749 |
).isoformat() |
| 1750 |
|
| 1751 |
def __str__(self): |
| 1752 |
return "{self.sec}.{self.nsec} ({self.iso8601})".format(self=self) |
| 1753 |
|
| 1754 |
|
| 1755 |
class InodeItem(ItemData): |
| 1756 |
"""Object representation of struct `btrfs_inode_item`. |
| 1757 |
|
| 1758 |
The inode item stores information of a single file or directory. Not the |
| 1759 |
name, because a file can have multiple names. |
| 1760 |
|
| 1761 |
* Tree: `FS_TREE_OBJECTID` (5) or any other subvolume tree. |
| 1762 |
* Key objectid: Inode number. |
| 1763 |
* Key type: `INODE_ITEM_KEY` (1) |
| 1764 |
* Key offset: 0 |
| 1765 |
|
| 1766 |
:ivar int objectid: The inode number. (taken from the objectid field of the |
| 1767 |
item key). |
| 1768 |
:ivar int generation: Generation of the filesystem when the inode was |
| 1769 |
created. |
| 1770 |
:ivar int transid: Generation of the filesystem when the inode was last |
| 1771 |
changed. |
| 1772 |
:ivar int size: File size in bytes. |
| 1773 |
:ivar int nbytes: Allocated disk blocks for this file in bytes. |
| 1774 |
:ivar int block_group: Only used for free space cache v1, for which it's |
| 1775 |
the related block group virtual address. |
| 1776 |
:ivar int nlink: Amount of hardlinks the file has. |
| 1777 |
:ivar int uid: Numerical user id of the owner of the file. |
| 1778 |
:ivar int gid: Numerical group id of the owner of the file. |
| 1779 |
:ivar int mode: File permissions. |
| 1780 |
:ivar int rdev: Major and minor device numbers for special files. |
| 1781 |
:ivar int flags: Inode flags, see below. |
| 1782 |
:ivar int sequence: Sequence number for NFS. |
| 1783 |
:ivar atime: Time of last access. |
| 1784 |
:vartype atime: :class:`~btrfs.ctree.TimeSpec` |
| 1785 |
:ivar ctime: Time of last file metadata change. Also updated when file |
| 1786 |
contents change. |
| 1787 |
:vartype ctime: :class:`~btrfs.ctree.TimeSpec` |
| 1788 |
:ivar mtime: Time of last modification to file contents. |
| 1789 |
:vartype mtime: :class:`~btrfs.ctree.TimeSpec` |
| 1790 |
:ivar otime: Time of file birth. |
| 1791 |
:vartype otime: :class:`~btrfs.ctree.TimeSpec` |
| 1792 |
|
| 1793 |
The flags are an or-ed combination of one or more of the following values |
| 1794 |
(available as attribute of this module): |
| 1795 |
|
| 1796 |
- INODE_NODATASUM |
| 1797 |
- INODE_NODATACOW |
| 1798 |
- INODE_READONLY |
| 1799 |
- INODE_NOCOMPRESS |
| 1800 |
- INODE_PREALLOC |
| 1801 |
- INODE_SYNC |
| 1802 |
- INODE_IMMUTABLE |
| 1803 |
- INODE_APPEND |
| 1804 |
- INODE_NODUMP |
| 1805 |
- INODE_NOATIME |
| 1806 |
- INODE_DIRSYNC |
| 1807 |
- INODE_COMPRESS |
| 1808 |
""" |
| 1809 |
_inode_item_parts = [ |
| 1810 |
struct.Struct('<5Q4L3Q32x'), |
| 1811 |
TimeSpec._timespec, |
| 1812 |
TimeSpec._timespec, |
| 1813 |
TimeSpec._timespec, |
| 1814 |
TimeSpec._timespec, |
| 1815 |
] |
| 1816 |
_inode_item = struct.Struct('<' + ''.join([_struct_format(s)[1:] |
| 1817 |
for s in _inode_item_parts])) |
| 1818 |
|
| 1819 |
def __init__(self, header, data): |
| 1820 |
super().__init__(header) |
| 1821 |
if header is not None: |
| 1822 |
self._setattr_from_key(objectid_attr='objectid') |
| 1823 |
self.generation, self.transid, self.size, self.nbytes, self.block_group, \ |
| 1824 |
self.nlink, self.uid, self.gid, self.mode, self.rdev, self.flags, self.sequence = \ |
| 1825 |
InodeItem._inode_item_parts[0].unpack_from(data) |
| 1826 |
pos = InodeItem._inode_item_parts[0].size |
| 1827 |
next_pos = pos + TimeSpec._timespec.size |
| 1828 |
self.atime = TimeSpec(data[pos:next_pos]) |
| 1829 |
pos, next_pos = next_pos, next_pos + TimeSpec._timespec.size |
| 1830 |
self.ctime = TimeSpec(data[pos:next_pos]) |
| 1831 |
pos, next_pos = next_pos, next_pos + TimeSpec._timespec.size |
| 1832 |
self.mtime = TimeSpec(data[pos:next_pos]) |
| 1833 |
pos, next_pos = next_pos, next_pos + TimeSpec._timespec.size |
| 1834 |
self.otime = TimeSpec(data[pos:next_pos]) |
| 1835 |
|
| 1836 |
def __str__(self): |
| 1837 |
result = ["inode"] |
| 1838 |
if hasattr(self, 'objectid'): |
| 1839 |
result.append("objectid {self.objectid}".format(self=self)) |
| 1840 |
result.append("generation {self.generation} transid {self.transid} size {self.size} " |
| 1841 |
"nbytes {self.nbytes} block_group {self.block_group} mode {self.mode_str} " |
| 1842 |
"nlink {self.nlink} uid {self.uid} gid {self.gid} rdev {self.rdev} " |
| 1843 |
"flags {self.flags:#x}({self.flags_str})".format(self=self)) |
| 1844 |
return " ".join(result) |
| 1845 |
|
| 1846 |
@staticmethod |
| 1847 |
def _pretty_properties(): |
| 1848 |
return [ |
| 1849 |
(btrfs.utils.inode_flags_str, 'flags'), |
| 1850 |
(btrfs.utils.inode_mode_str, 'mode'), |
| 1851 |
] |
| 1852 |
|
| 1853 |
|
| 1854 |
class InodeRefList(ItemData, collections.abc.MutableSequence): |
| 1855 |
"""A collection of struct `btrfs_inode_ref` indexed under a single tree |
| 1856 |
key. |
| 1857 |
|
| 1858 |
A :class:`InodeRefList` is a list of :class:`InodeRef` objects which |
| 1859 |
contain information about every name the inode is known under in a single |
| 1860 |
directory. So, when we already know the inode number of a file, we can find |
| 1861 |
in which places it has hardlinks pointing at it. |
| 1862 |
|
| 1863 |
* Tree: `FS_TREE_OBJECTID` (5) or any other subvolume tree. |
| 1864 |
* Key objectid: Inode number. |
| 1865 |
* Key type: `INODE_REF_KEY` (12) |
| 1866 |
* Key offset: Inode number of the containing directory. |
| 1867 |
|
| 1868 |
This class is a helper that does not exist in Btrfs itself. |
| 1869 |
|
| 1870 |
Besides acting as an immutable list of :class:`InodeRef` objects, there are |
| 1871 |
some additional attributes: |
| 1872 |
|
| 1873 |
:ivar int objectid: Inode number of the file. (taken from the objectid |
| 1874 |
field of the item key) |
| 1875 |
:ivar int parent_objectid: Inode number of the containing directory. (taken |
| 1876 |
from the offset field of the item key) |
| 1877 |
""" |
| 1878 |
def __init__(self, header, data): |
| 1879 |
super().__init__(header) |
| 1880 |
self._setattr_from_key(objectid_attr='objectid', offset_attr='parent_objectid') |
| 1881 |
self._list = [] |
| 1882 |
pos = 0 |
| 1883 |
while pos < header.len: |
| 1884 |
inode_ref = InodeRef(data, pos) |
| 1885 |
self._list.append(inode_ref) |
| 1886 |
pos += InodeRef._inode_ref.size + inode_ref.name_len |
| 1887 |
|
| 1888 |
def __getitem__(self, index): |
| 1889 |
return self._list[index] |
| 1890 |
|
| 1891 |
def __setitem__(self, index, value): |
| 1892 |
raise NotImplementedError("{} objects should not be changed.".format(type(self).__name__)) |
| 1893 |
|
| 1894 |
def __delitem__(self, index): |
| 1895 |
raise NotImplementedError("{} objects should not be changed.".format(type(self).__name__)) |
| 1896 |
|
| 1897 |
def __len__(self): |
| 1898 |
return len(self._list) |
| 1899 |
|
| 1900 |
def insert(self, index, value): |
| 1901 |
"""Not implemented.""" |
| 1902 |
raise NotImplementedError("{} objects should not be changed.".format(type(self).__name__)) |
| 1903 |
|
| 1904 |
def __str__(self): |
| 1905 |
return "inode ref list objectid {self.objectid} parent_objectid {self.parent_objectid} " \ |
| 1906 |
"size {}".format(len(self), self=self) |
| 1907 |
|
| 1908 |
|
| 1909 |
class InodeRef(SubItem): |
| 1910 |
"""Object representation of struct `btrfs_inode_ref`. |
| 1911 |
|
| 1912 |
Also see :class:`InodeRefList`. |
| 1913 |
|
| 1914 |
:ivar int index: Directory index number in the containing directory. Refer |
| 1915 |
to the `parent_objectid` attribute of the :class:`InodeRefList` object |
| 1916 |
that contains this :class:`InodeRef` to find the inode number of the |
| 1917 |
directory. |
| 1918 |
:ivar int name_len: Amount of bytes used to store the filename. |
| 1919 |
:ivar bytes name: Filename as bytes. |
| 1920 |
""" |
| 1921 |
_inode_ref = struct.Struct('<QH') |
| 1922 |
|
| 1923 |
def __init__(self, data, pos): |
| 1924 |
self.index, self.name_len = InodeRef._inode_ref.unpack_from(data, pos) |
| 1925 |
pos += InodeRef._inode_ref.size |
| 1926 |
self.name, = struct.Struct('<{}s'.format(self.name_len)).unpack_from(data, pos) |
| 1927 |
|
| 1928 |
def __str__(self): |
| 1929 |
return "inode ref index {self.index} name {self.name_str}".format(self=self) |
| 1930 |
|
| 1931 |
def _pretty_properties(): |
| 1932 |
return [ |
| 1933 |
(btrfs.utils.embedded_text_for_str, 'name') |
| 1934 |
] |
| 1935 |
|
| 1936 |
|
| 1937 |
class InodeExtrefList(ItemData, collections.abc.MutableSequence): |
| 1938 |
"""A collection of struct `btrfs_inode_extref` indexed under a single tree |
| 1939 |
key. |
| 1940 |
|
| 1941 |
A :class:`InodeExtrefList` is a list of :class:`InodeExtref` objects. By |
| 1942 |
default, names under which a file is known are stored in the |
| 1943 |
:class:`InodeRefList` of :class:`InodeRef`. However, if a file has so many |
| 1944 |
hardlinks that that item would become bigger than a metadata page, the rest |
| 1945 |
of the items are stored separately. |
| 1946 |
|
| 1947 |
* Tree: `FS_TREE_OBJECTID` (5) or any other subvolume tree. |
| 1948 |
* Key objectid: Inode number. |
| 1949 |
* Key type: `INODE_EXTREF_KEY` (13) |
| 1950 |
* Key offset: :func:`~btrfs.crc32.extref_hash` of the filename. |
| 1951 |
|
| 1952 |
The :class:`InodeExtref` item is a list because multiple different |
| 1953 |
filenames can end up having the same crc32 value. |
| 1954 |
|
| 1955 |
This class is a helper that does not exist in Btrfs itself. |
| 1956 |
|
| 1957 |
Besides acting as an immutable list of :class:`InodeExtRef` objects, there |
| 1958 |
are some additional attributes: |
| 1959 |
|
| 1960 |
:ivar int objectid: Inode number of the file. (taken from the objectid |
| 1961 |
field of the item key) |
| 1962 |
:ivar int extref_hash: :func:`~btrfs.crc32.extref_hash` of the filename. |
| 1963 |
(taken from the offset field of the item key) |
| 1964 |
""" |
| 1965 |
def __init__(self, header, data): |
| 1966 |
super().__init__(header) |
| 1967 |
self._setattr_from_key(objectid_attr='objectid', offset_attr='extref_hash') |
| 1968 |
self._list = [] |
| 1969 |
pos = 0 |
| 1970 |
while pos < header.len: |
| 1971 |
inode_extref = InodeExtref(data, pos) |
| 1972 |
self._list.append(inode_extref) |
| 1973 |
pos += len(inode_extref) |
| 1974 |
|
| 1975 |
def __getitem__(self, index): |
| 1976 |
return self._list[index] |
| 1977 |
|
| 1978 |
def __setitem__(self, index, value): |
| 1979 |
raise NotImplementedError("{} objects should not be changed.".format(type(self).__name__)) |
| 1980 |
|
| 1981 |
def __delitem__(self, index): |
| 1982 |
raise NotImplementedError("{} objects should not be changed.".format(type(self).__name__)) |
| 1983 |
|
| 1984 |
def __len__(self): |
| 1985 |
return len(self._list) |
| 1986 |
|
| 1987 |
def insert(self, index, value): |
| 1988 |
"""Not implemented.""" |
| 1989 |
raise NotImplementedError("{} objects should not be changed.".format(type(self).__name__)) |
| 1990 |
|
| 1991 |
def __str__(self): |
| 1992 |
return "inode extref list objectid {self.objectid} " \ |
| 1993 |
"hash {self.extref_hash} size {}".format(len(self), self=self) |
| 1994 |
|
| 1995 |
|
| 1996 |
class InodeExtref(object): |
| 1997 |
"""Object representation of struct `btrfs_inode_extref`. |
| 1998 |
|
| 1999 |
Also see :class:`InodeExtrefList`. |
| 2000 |
|
| 2001 |
:ivar int parent_objectid: Inode number of the containing directory. |
| 2002 |
:ivar int index: Directory index number in the containing directory. |
| 2003 |
:ivar int name_len: Amount of bytes used to store the filename. |
| 2004 |
:ivar bytes name: Filename as bytes. |
| 2005 |
""" |
| 2006 |
_inode_extref = struct.Struct('<QQH') |
| 2007 |
|
| 2008 |
def __init__(self, data, pos): |
| 2009 |
self.parent_objectid, self.index, self.name_len = \ |
| 2010 |
InodeExtref._inode_extref.unpack_from(data, pos) |
| 2011 |
pos += InodeExtref._inode_extref.size |
| 2012 |
self.name, = struct.Struct('<{}s'.format(self.name_len)).unpack_from(data, pos) |
| 2013 |
|
| 2014 |
def __str__(self): |
| 2015 |
return "inode extref parent_objectid {self.parent_objectid} index {self.index} " \ |
| 2016 |
"name {self.name_str}".format(self=self) |
| 2017 |
|
| 2018 |
def _pretty_properties(): |
| 2019 |
return [ |
| 2020 |
(btrfs.utils.embedded_text_for_str, 'name') |
| 2021 |
] |
| 2022 |
|
| 2023 |
|
| 2024 |
class DirItemList(ItemData, collections.abc.MutableSequence): |
| 2025 |
"""A collection of struct `btrfs_dir_item` indexed under a single tree key. |
| 2026 |
|
| 2027 |
A :class:`DirItemList` is a list of :class:`DirItem` objects. Based on a |
| 2028 |
filename hash, they point to the inode item for the corresponding file. |
| 2029 |
Since multiple different filenames can end up having the same name hash, |
| 2030 |
this item can contain multiple :class:`DirItem` objects. |
| 2031 |
|
| 2032 |
* Tree: `FS_TREE_OBJECTID` (5) or any other subvolume tree. |
| 2033 |
* Key objectid: Inode number of the directory. |
| 2034 |
* Key type: `DIR_ITEM_KEY` (84) |
| 2035 |
* Key offset: :func:`~btrfs.crc32.name_hash` of the filename. |
| 2036 |
|
| 2037 |
This class is a helper that does not exist in Btrfs itself. |
| 2038 |
|
| 2039 |
Besides acting as an immutable list of :class:`DirItem` objects, there are |
| 2040 |
some additional attributes: |
| 2041 |
|
| 2042 |
:ivar int objectid: Inode number of the directory. (taken from the objectid |
| 2043 |
field of the item key) |
| 2044 |
:ivar int name_hash: :func:`~btrfs.crc32.name_hash` of the filename. |
| 2045 |
(taken from the offset field of the item key) |
| 2046 |
""" |
| 2047 |
def __init__(self, header, data): |
| 2048 |
super().__init__(header) |
| 2049 |
self._setattr_from_key(objectid_attr='objectid', offset_attr='name_hash') |
| 2050 |
self._list = [] |
| 2051 |
pos = 0 |
| 2052 |
while pos < header.len: |
| 2053 |
cls = {DIR_ITEM_KEY: DirItem, XATTR_ITEM_KEY: XAttrItem} |
| 2054 |
dir_item = cls[self.key.type](data, pos) |
| 2055 |
self._list.append(dir_item) |
| 2056 |
pos += DirItem._dir_item.size + dir_item.name_len + dir_item.data_len |
| 2057 |
|
| 2058 |
def __getitem__(self, index): |
| 2059 |
return self._list[index] |
| 2060 |
|
| 2061 |
def __setitem__(self, index, value): |
| 2062 |
raise NotImplementedError("{} objects should not be changed.".format(type(self).__name__)) |
| 2063 |
|
| 2064 |
def __delitem__(self, index): |
| 2065 |
raise NotImplementedError("{} objects should not be changed.".format(type(self).__name__)) |
| 2066 |
|
| 2067 |
def __len__(self): |
| 2068 |
return len(self._list) |
| 2069 |
|
| 2070 |
def insert(self, index, value): |
| 2071 |
"""Not implemented.""" |
| 2072 |
raise NotImplementedError("{} objects should not be changed.".format(type(self).__name__)) |
| 2073 |
|
| 2074 |
def __str__(self): |
| 2075 |
return "dir item list objectid {self.objectid} name_hash {self.name_hash} " \ |
| 2076 |
"size {}".format(len(self), self=self) |
| 2077 |
|
| 2078 |
|
| 2079 |
class XAttrItemList(DirItemList): |
| 2080 |
"""A collection of struct `btrfs_dir_item`, used to store extended |
| 2081 |
attributes and indexed under a single tree key. |
| 2082 |
|
| 2083 |
An :class:`XAttrItemList` is a list of :class:`XAttrItem` objects, which |
| 2084 |
contain key value pairs in the `name` and `data` fields of the dir_item |
| 2085 |
struct. Since multiple different keys can end up having the same name |
| 2086 |
hash, this item can contain multiple :class:`XAttrItem` objects. |
| 2087 |
|
| 2088 |
* Tree: `FS_TREE_OBJECTID` (5) or any other subvolume tree. |
| 2089 |
* Key objectid: Inode number of a file on which the xattr is set. |
| 2090 |
* Key type: `XATTR_ITEM_KEY` (24) |
| 2091 |
* Key offset: :func:`~btrfs.crc32.name_hash` of the key. |
| 2092 |
|
| 2093 |
This class is a helper that does not exist in Btrfs itself. |
| 2094 |
|
| 2095 |
Besides acting as an immutable list of :class:`XAttrItem` objects, there |
| 2096 |
are some additional attributes: |
| 2097 |
|
| 2098 |
:ivar int objectid: Inode number of a file on which the xattr is set. |
| 2099 |
(taken from the objectid field of the item key) |
| 2100 |
:ivar int name_hash: :func:`~btrfs.crc32.name_hash` of the xattr key. |
| 2101 |
(taken from the offset field of the item key) |
| 2102 |
""" |
| 2103 |
def __str__(self): |
| 2104 |
return "xattr item list objectid {self.objectid} name_hash {self.name_hash} " \ |
| 2105 |
"size {}".format(len(self), self=self) |
| 2106 |
|
| 2107 |
|
| 2108 |
class DirItem(SubItem): |
| 2109 |
"""Object representation of struct `btrfs_dir_item`. |
| 2110 |
|
| 2111 |
Based on the name hash of a filename, this object directly points to the |
| 2112 |
inode item for the corresponding file. Using this mapping allows quick file |
| 2113 |
access when the name is known, even in directories with a large amount of |
| 2114 |
files in them. |
| 2115 |
|
| 2116 |
Also see :class:`DirItemList`. |
| 2117 |
|
| 2118 |
:ivar location: Key of the file inode item. |
| 2119 |
:vartype location: :class:`DiskKey` |
| 2120 |
:ivar int transid: Generation of the filesystem when this item was created. |
| 2121 |
:ivar int data_len: *Not used*, always 0. |
| 2122 |
:ivar int name_len: Amount of bytes used to store the filename. |
| 2123 |
:ivar int type: File type that is represented by the inode item that is |
| 2124 |
being referenced. |
| 2125 |
:ivar bytes name: Filename as bytes. |
| 2126 |
|
| 2127 |
File type is one of the following values (available as attribute of this |
| 2128 |
module): |
| 2129 |
|
| 2130 |
- FT_UNKNOWN |
| 2131 |
- FT_REG_FILE |
| 2132 |
- FT_DIR |
| 2133 |
- FT_CHRDEV |
| 2134 |
- FT_BLKDEV |
| 2135 |
- FT_FIFO |
| 2136 |
- FT_SOCK |
| 2137 |
- FT_SYMLINK |
| 2138 |
- FT_XATTR |
| 2139 |
- FT_MAX |
| 2140 |
""" |
| 2141 |
_dir_item_parts = [ |
| 2142 |
DiskKey._disk_key, |
| 2143 |
struct.Struct('<QHHB') |
| 2144 |
] |
| 2145 |
_dir_item = struct.Struct('<' + ''.join([_struct_format(s)[1:] for s in _dir_item_parts])) |
| 2146 |
|
| 2147 |
def __init__(self, data, pos): |
| 2148 |
next_pos = pos + DiskKey._disk_key.size |
| 2149 |
self.location = DiskKey(data[pos:next_pos]) |
| 2150 |
pos = next_pos |
| 2151 |
self.transid, self.data_len, self.name_len, self.type = \ |
| 2152 |
DirItem._dir_item_parts[1].unpack_from(data, pos) |
| 2153 |
pos += DirItem._dir_item_parts[1].size |
| 2154 |
self.name, = struct.Struct('<{}s'.format(self.name_len)).unpack_from(data, pos) |
| 2155 |
pos += self.name_len |
| 2156 |
self.data, = struct.Struct('<{}s'.format(self.data_len)).unpack_from(data, pos) |
| 2157 |
pos += self.data_len |
| 2158 |
|
| 2159 |
def __str__(self): |
| 2160 |
return "dir item location {self.location} type {self.type_str} " \ |
| 2161 |
"name {self.name_str}".format(self=self) |
| 2162 |
|
| 2163 |
@staticmethod |
| 2164 |
def _pretty_properties(): |
| 2165 |
return [ |
| 2166 |
(btrfs.utils.dir_item_type_str, 'type'), |
| 2167 |
(btrfs.utils.embedded_text_for_str, 'name'), |
| 2168 |
(btrfs.utils.embedded_text_for_str, 'data'), |
| 2169 |
] |
| 2170 |
|
| 2171 |
|
| 2172 |
class XAttrItem(DirItem): |
| 2173 |
"""Object representation of struct `btrfs_dir_item`, used to store extended |
| 2174 |
attribute information. |
| 2175 |
|
| 2176 |
This object contains a key and value for an extended attribute on a file. |
| 2177 |
It reuses the `dir_item` data structure. |
| 2178 |
|
| 2179 |
Also see :class:`XattrItemList`. |
| 2180 |
|
| 2181 |
:ivar int transid: Generation of the filesystem when this item was created. |
| 2182 |
:ivar int name_len: Amount of bytes used to store the key. |
| 2183 |
:ivar int data_len: Amount of bytes used to store the value. |
| 2184 |
:ivar bytes name: Key as bytes. |
| 2185 |
:ivar bytes data: Value as bytes. |
| 2186 |
""" |
| 2187 |
def __str__(self): |
| 2188 |
return "xattr item name {self.name_str} data {self.data_str}".format(self=self) |
| 2189 |
|
| 2190 |
|
| 2191 |
class DirIndex(ItemData): |
| 2192 |
"""Object representation of struct `btrfs_dir_item`, but used to store |
| 2193 |
filenames ordered on directory index. |
| 2194 |
|
| 2195 |
The :class:`DirIndex` objects list the contents of a directory in the order |
| 2196 |
in which items were added. |
| 2197 |
|
| 2198 |
* Tree: `FS_TREE_OBJECTID` (5) or any other subvolume tree. |
| 2199 |
* Key objectid: Inode number of the directory. |
| 2200 |
* Key type: `DIR_INDEX_KEY` (96) |
| 2201 |
* Key offset: Index in the directory. |
| 2202 |
|
| 2203 |
:ivar int objectid: Inode number of the directory. (taken from the objectid |
| 2204 |
field of the item key) |
| 2205 |
:ivar int index: Index in the directory. (taken from the offset field of |
| 2206 |
the item key) |
| 2207 |
:ivar location: Key of the file inode item. |
| 2208 |
:vartype location: :class:`DiskKey` |
| 2209 |
:ivar int transid: Generation of the filesystem when this item was created. |
| 2210 |
:ivar int data_len: *Not used*, always 0. |
| 2211 |
:ivar int name_len: Amount of bytes used to store the filename. |
| 2212 |
:ivar int type: File type that is represented by the inode item that is |
| 2213 |
being referenced. |
| 2214 |
:ivar bytes name: Filename as bytes. |
| 2215 |
|
| 2216 |
File type is one of the following values (available as attribute of this |
| 2217 |
module): |
| 2218 |
|
| 2219 |
- FT_UNKNOWN |
| 2220 |
- FT_REG_FILE |
| 2221 |
- FT_DIR |
| 2222 |
- FT_CHRDEV |
| 2223 |
- FT_BLKDEV |
| 2224 |
- FT_FIFO |
| 2225 |
- FT_SOCK |
| 2226 |
- FT_SYMLINK |
| 2227 |
- FT_XATTR |
| 2228 |
- FT_MAX |
| 2229 |
""" |
| 2230 |
def __init__(self, header, data): |
| 2231 |
super().__init__(header) |
| 2232 |
self._setattr_from_key(objectid_attr='objectid', offset_attr='index') |
| 2233 |
self.location = DiskKey(data[:DiskKey._disk_key.size]) |
| 2234 |
pos = DiskKey._disk_key.size |
| 2235 |
self.transid, self.data_len, self.name_len, self.type = \ |
| 2236 |
DirItem._dir_item_parts[1].unpack_from(data, pos) |
| 2237 |
pos += DirItem._dir_item_parts[1].size |
| 2238 |
self.name, = struct.Struct('<{}s'.format(self.name_len)).unpack_from(data, pos) |
| 2239 |
|
| 2240 |
def __str__(self): |
| 2241 |
return "dir index objectid {self.objectid} index {self.index} " \ |
| 2242 |
"location {self.location} type {self.type_str} " \ |
| 2243 |
"name {self.name_str}".format(self=self) |
| 2244 |
|
| 2245 |
@staticmethod |
| 2246 |
def _pretty_properties(): |
| 2247 |
return [ |
| 2248 |
(btrfs.utils.dir_item_type_str, 'type'), |
| 2249 |
(btrfs.utils.embedded_text_for_str, 'name'), |
| 2250 |
] |
| 2251 |
|
| 2252 |
|
| 2253 |
class RootItem(ItemData): |
| 2254 |
"""Object representation of struct `btrfs_root_item`. |
| 2255 |
|
| 2256 |
The :class:`RootItem` lives in the root tree, a.k.a. the 'tree of trees'. |
| 2257 |
It contains information about the root metadata node of another tree. |
| 2258 |
|
| 2259 |
* Tree: `ROOT_TREE_OBJECTID` (1). |
| 2260 |
* Key objectid: Tree ID. |
| 2261 |
* Key type: `ROOT_ITEM_KEY` (132) |
| 2262 |
* Key offset: Index in the directory. |
| 2263 |
|
| 2264 |
:ivar int objectid: Tree ID. (taken from the objectid field of the item |
| 2265 |
key) |
| 2266 |
:ivar inode: Embedded inode item. Only the flags field of it is used. |
| 2267 |
:vartype inode: :class:`InodeItem` |
| 2268 |
:ivar int generation: Generation of the filesystem when this root was |
| 2269 |
created. |
| 2270 |
:ivar int root_dirid: Objectid for the root directory in a subvolume tree |
| 2271 |
(always 256 in that case). 0 for other trees. |
| 2272 |
:ivar int bytenr: Virtual address of the root node of this tree. |
| 2273 |
:ivar int byte_limit: *Not used* |
| 2274 |
:ivar int bytes_used: *Not used* |
| 2275 |
:ivar int last_snapshot: The generation of the filesystem when the most |
| 2276 |
recent snapshot of a subvolume was made. |
| 2277 |
:ivar int flags: See below. |
| 2278 |
:ivar int refs: *Not used*, either 0 or 1. |
| 2279 |
:ivar drop_progress: Key of the last removed item during cleanup of a |
| 2280 |
removed subvolume. |
| 2281 |
:vartype drop_progress: :class:`DiskKey` |
| 2282 |
:ivar int drop_level: The tree level of the metadata node or leaf that |
| 2283 |
contains the key from drop_progress. |
| 2284 |
:ivar int level: The height of the tree that this root item refers to. |
| 2285 |
|
| 2286 |
The flags are an or-ed combination of one or more of the following values |
| 2287 |
(available as attribute of this module): |
| 2288 |
|
| 2289 |
- ROOT_SUBVOL_RDONLY: The subvolume is read only. |
| 2290 |
|
| 2291 |
The following fields were introduced in Linux 3.6. Btrfs would still allow |
| 2292 |
using the filesystem with an older kernel, but if the content of |
| 2293 |
generation_v2 does not match generation, all new fields would be |
| 2294 |
invalidated: |
| 2295 |
|
| 2296 |
:ivar int generation_v2: Same value as generation. |
| 2297 |
:ivar uuid: Subvolume UUID. |
| 2298 |
:vartype uuid: :class:`uuid.UUID` |
| 2299 |
:ivar parent_uuid: Subvolume UUID that this subvolume is a snapshot of. |
| 2300 |
:vartype parent_uuid: :class:`uuid.UUID` |
| 2301 |
:ivar received_uuid: Subvolume UUID of the subvolume that this subvolume |
| 2302 |
was duplicated from using send/receive. |
| 2303 |
:vartype received_uuid: :class:`uuid.UUID` |
| 2304 |
:ivar int ctransid: Generation when the tree was last modified. |
| 2305 |
:ivar int otransid: Generation when the tree was created. |
| 2306 |
:ivar int stransid: Generation of the filesystem from which a subvolume was |
| 2307 |
sent. Only used if this is a received subvolume. |
| 2308 |
:ivar int rtransid: Generation of this filesystem when the subvolume was |
| 2309 |
received. |
| 2310 |
:ivar ctime: Timestamp for ctransid. |
| 2311 |
:vartype ctime: :class:`TimeSpec` |
| 2312 |
:ivar otime: Timestamp for otransid. |
| 2313 |
:vartype otime: :class:`TimeSpec` |
| 2314 |
:ivar stime: Timestamp for stransid. |
| 2315 |
:vartype stime: :class:`TimeSpec` |
| 2316 |
:ivar rtime: Timestamp for rtransid. |
| 2317 |
:vartype rtime: :class:`TimeSpec` |
| 2318 |
""" |
| 2319 |
_root_item_parts = [ |
| 2320 |
InodeItem._inode_item, |
| 2321 |
struct.Struct('<7QL'), |
| 2322 |
DiskKey._disk_key, |
| 2323 |
struct.Struct('<BBQ16s16s16s4Q'), |
| 2324 |
TimeSpec._timespec, |
| 2325 |
TimeSpec._timespec, |
| 2326 |
TimeSpec._timespec, |
| 2327 |
TimeSpec._timespec, |
| 2328 |
] |
| 2329 |
_root_item = struct.Struct('<' + ''.join([_struct_format(s)[1:] |
| 2330 |
for s in _root_item_parts])) |
| 2331 |
|
| 2332 |
def __init__(self, header, data): |
| 2333 |
super().__init__(header) |
| 2334 |
self._setattr_from_key(objectid_attr='objectid') |
| 2335 |
self.inode = InodeItem(None, data[:InodeItem._inode_item.size]) |
| 2336 |
pos = InodeItem._inode_item.size |
| 2337 |
self.generation, self.root_dirid, self.bytenr, self.byte_limit, self.bytes_used, \ |
| 2338 |
self.last_snapshot, self.flags, self.refs = \ |
| 2339 |
RootItem._root_item_parts[1].unpack_from(data, pos) |
| 2340 |
pos += RootItem._root_item_parts[1].size |
| 2341 |
self.drop_progress = DiskKey(data[pos:pos+DiskKey._disk_key.size]) |
| 2342 |
pos += DiskKey._disk_key.size |
| 2343 |
self.drop_level, self.level, self.generation_v2, uuid_bytes, parent_uuid_bytes, \ |
| 2344 |
received_uuid_bytes, self.ctransid, self.otransid, self.stransid, self.rtransid = \ |
| 2345 |
RootItem._root_item_parts[3].unpack_from(data, pos) |
| 2346 |
self.uuid = uuid.UUID(bytes=uuid_bytes) |
| 2347 |
self.parent_uuid = uuid.UUID(bytes=parent_uuid_bytes) |
| 2348 |
self.received_uuid = uuid.UUID(bytes=received_uuid_bytes) |
| 2349 |
pos += RootItem._root_item_parts[3].size |
| 2350 |
next_pos = pos + TimeSpec._timespec.size |
| 2351 |
self.ctime = TimeSpec(data[pos:next_pos]) |
| 2352 |
pos, next_pos = next_pos, next_pos + TimeSpec._timespec.size |
| 2353 |
self.otime = TimeSpec(data[pos:next_pos]) |
| 2354 |
pos, next_pos = next_pos, next_pos + TimeSpec._timespec.size |
| 2355 |
self.stime = TimeSpec(data[pos:next_pos]) |
| 2356 |
pos, next_pos = next_pos, next_pos + TimeSpec._timespec.size |
| 2357 |
self.rtime = TimeSpec(data[pos:next_pos]) |
| 2358 |
|
| 2359 |
def __str__(self): |
| 2360 |
return "root {self.key.objectid} uuid {self.uuid} " \ |
| 2361 |
"generation {self.generation} last_snapshot {self.last_snapshot} " \ |
| 2362 |
"flags {self.flags:#x}({self.flags_str})".format(self=self) |
| 2363 |
|
| 2364 |
@staticmethod |
| 2365 |
def _pretty_properties(): |
| 2366 |
return [ |
| 2367 |
(btrfs.utils.root_item_flags_str, 'flags'), |
| 2368 |
] |
| 2369 |
|
| 2370 |
|
| 2371 |
class RootRef(ItemData): |
| 2372 |
"""Object representation of `btrfs_root_ref`. |
| 2373 |
|
| 2374 |
The :class:`RootRef` item lives in the root tree, a.k.a. the 'tree of |
| 2375 |
trees'. It contains information about the place where a subvolume is |
| 2376 |
located inside another subvolume. |
| 2377 |
|
| 2378 |
* Tree: `ROOT_TREE_OBJECTID` (1). |
| 2379 |
* Key objectid: Parent tree ID. |
| 2380 |
* Key type: `ROOT_REF_KEY` (156) |
| 2381 |
* Key offset: Tree ID of the subvolume. |
| 2382 |
|
| 2383 |
:ivar int parent_tree: Containing Tree ID. (taken from the objectid field of |
| 2384 |
the item key) |
| 2385 |
:ivar int tree: Tree ID of the subvolume. (taken from the offset field of |
| 2386 |
the item key) |
| 2387 |
:ivar int dirid: Inode number of the containing directory. |
| 2388 |
:ivar int sequence: Directory index number in the containing directory. |
| 2389 |
:ivar int name_len: Amount of bytes used to store the filename. |
| 2390 |
:ivar bytes name: Filename as bytes. |
| 2391 |
|
| 2392 |
When combining this information with a call to the ino_lookup ioctl, we can |
| 2393 |
quickly figure out the relative path inside the containing subvolume. |
| 2394 |
|
| 2395 |
E.g. for (259 ROOT_REF 1052) in the root tree, with dirid 20197, sequence |
| 2396 |
65 and name baz, we can do btrfs.ioctl.ino_lookup(fd, 259, 20197). The |
| 2397 |
result is e.g. name_bytes=b'foo/bar/', so the location inside the |
| 2398 |
containing subvolume is foo/bar/baz. |
| 2399 |
|
| 2400 |
When doing such a thing recursively, the same output as seen in btrfs sub |
| 2401 |
list -a can be produced. |
| 2402 |
""" |
| 2403 |
_root_ref_item = struct.Struct('<QQH') |
| 2404 |
|
| 2405 |
def __init__(self, header, data): |
| 2406 |
super().__init__(header) |
| 2407 |
self._setattr_from_key(objectid_attr='parent_tree', offset_attr='tree') |
| 2408 |
self.dirid, self.sequence, self.name_len = RootRef._root_ref_item.unpack_from(data) |
| 2409 |
pos = RootRef._root_ref_item.size |
| 2410 |
self.name, = struct.Struct('<{}s'.format(self.name_len)).unpack_from(data, pos) |
| 2411 |
|
| 2412 |
def __str__(self): |
| 2413 |
return "root ref parent_tree {self.parent_tree} tree {self.tree} dirid {self.dirid} " \ |
| 2414 |
"sequence {self.sequence} name {self.name_str}".format(self=self) |
| 2415 |
|
| 2416 |
def _pretty_properties(): |
| 2417 |
return [ |
| 2418 |
(btrfs.utils.embedded_text_for_str, 'name') |
| 2419 |
] |
| 2420 |
|
| 2421 |
|
| 2422 |
class FileExtentItem(ItemData): |
| 2423 |
"""Object representation of `btrfs_file_extent_item`. |
| 2424 |
|
| 2425 |
For every piece of a file, the :class:`FileExtentItem` points to the data |
| 2426 |
extent where the actual data is stored. A :class:`FileExtentItem` does not |
| 2427 |
have to reference a complete extent. It can also use part of it. |
| 2428 |
|
| 2429 |
* Tree: `FS_TREE_OBJECTID` (5) or any other subvolume tree. |
| 2430 |
* Key objectid: Inode number of the file. |
| 2431 |
* Key type: `EXTENT_DATA_KEY` (108) |
| 2432 |
* Key offset: Logical offset in the file where the referenced data appears. |
| 2433 |
|
| 2434 |
:ivar int objectid: The inode number of the file. (taken from the objectid |
| 2435 |
field of the item key). |
| 2436 |
:ivar int logical_offset: Logical offset in the file where the referenced |
| 2437 |
data appears. (taken from the offset field of the item key). |
| 2438 |
:ivar int generation: Generation of the filesystem when this file extent |
| 2439 |
was created. |
| 2440 |
:ivar int ram_bytes: Upper limit on the memory needed in bytes to store the |
| 2441 |
extent after decompression. |
| 2442 |
:ivar int compression: Compression type, see below. |
| 2443 |
|
| 2444 |
The compression field can have one of the following values (available as |
| 2445 |
attribute of this module): |
| 2446 |
|
| 2447 |
- COMPRESS_NONE |
| 2448 |
- COMPRESS_ZLIB |
| 2449 |
- COMPRESS_LZO |
| 2450 |
- COMPRESS_ZSTD |
| 2451 |
|
| 2452 |
:ivar int encryption: *Not used* Encryption type, always 0. |
| 2453 |
:ivar int other_encoding: *Not used* |
| 2454 |
:ivar int type: Type of extent, see below. |
| 2455 |
|
| 2456 |
The extent type can be one of the following: |
| 2457 |
|
| 2458 |
- FILE_EXTENT_INLINE: This is an inline extent. The data is stored inside |
| 2459 |
the metadata leaf, right after the type field. |
| 2460 |
- FILE_EXTENT_REG: This is a regular extent. |
| 2461 |
- FILE_EXTENT_PREALLOC: Preallocated extent (for which no actual data is |
| 2462 |
written yet). |
| 2463 |
|
| 2464 |
If the extent type is FILE_EXTENT_INLINE, the following fields are *not* |
| 2465 |
available: |
| 2466 |
|
| 2467 |
:ivar int disk_bytenr: Virtual address of the data extent we reference a |
| 2468 |
range from. |
| 2469 |
:ivar int disk_num_bytes: Size of the data extent we reference a range |
| 2470 |
from. |
| 2471 |
:ivar int offset: The offset inside the data extent where the data we need |
| 2472 |
starts. |
| 2473 |
:ivar int num_bytes: The amount of bytes to be used from that offset |
| 2474 |
onwards. |
| 2475 |
|
| 2476 |
This means that (disk_bytenr EXTENT_ITEM disk_num_bytes) is the tree key of |
| 2477 |
the extent item in the extent tree. Also, remember that these numbers will |
| 2478 |
always be multiples of disk block sizes, because that's how it gets cowed. |
| 2479 |
We don't just use 1 or 2 bytes from another extent. |
| 2480 |
""" |
| 2481 |
_file_extent_item_parts = [ |
| 2482 |
struct.Struct('<QQBB2xB'), |
| 2483 |
struct.Struct('<4Q'), |
| 2484 |
] |
| 2485 |
_file_extent_item = struct.Struct('<' + ''.join([_struct_format(s)[1:] |
| 2486 |
for s in _file_extent_item_parts])) |
| 2487 |
|
| 2488 |
def __init__(self, header, data): |
| 2489 |
super().__init__(header) |
| 2490 |
self._setattr_from_key(objectid_attr='objectid', offset_attr='logical_offset') |
| 2491 |
self.generation, self.ram_bytes, self.compression, self.encryption, self.type = \ |
| 2492 |
FileExtentItem._file_extent_item_parts[0].unpack_from(data) |
| 2493 |
if self.type != FILE_EXTENT_INLINE: |
| 2494 |
pos = FileExtentItem._file_extent_item_parts[0].size |
| 2495 |
self.disk_bytenr, self.disk_num_bytes, self.offset, self.num_bytes = \ |
| 2496 |
FileExtentItem._file_extent_item_parts[1].unpack_from(data, pos) |
| 2497 |
else: |
| 2498 |
self._inline_encoded_nbytes = \ |
| 2499 |
header.len - FileExtentItem._file_extent_item_parts[0].size |
| 2500 |
|
| 2501 |
def __str__(self): |
| 2502 |
ret = ["extent data at {self.logical_offset} generation {self.generation} " |
| 2503 |
"ram_bytes {self.ram_bytes} " |
| 2504 |
"compression {self.compression_str} type {self.type_str}".format(self=self)] |
| 2505 |
if self.type != FILE_EXTENT_INLINE: |
| 2506 |
ret.append("disk_bytenr {self.disk_bytenr} disk_num_bytes {self.disk_num_bytes} " |
| 2507 |
"offset {self.offset} num_bytes {self.num_bytes}".format(self=self)) |
| 2508 |
else: |
| 2509 |
ret.append("inline_encoded_nbytes {self._inline_encoded_nbytes}".format(self=self)) |
| 2510 |
return ' '.join(ret) |
| 2511 |
|
| 2512 |
@staticmethod |
| 2513 |
def _pretty_properties(): |
| 2514 |
return [ |
| 2515 |
(btrfs.utils.compress_type_str, 'compression'), |
| 2516 |
(btrfs.utils.file_extent_type_str, 'type'), |
| 2517 |
] |
| 2518 |
|
| 2519 |
|
| 2520 |
class FreeSpaceInfo(ItemData): |
| 2521 |
"""Object representation of struct `btrfs_free_space_info`. |
| 2522 |
|
| 2523 |
The free space tree contains a free space info item for every block group. |
| 2524 |
|
| 2525 |
* Tree: `FREE_SPACE_TREE_OBJECTID` (10). |
| 2526 |
* Key objectid: Virtual address. |
| 2527 |
* Key type: `FREE_SPACE_INFO_KEY` (198) |
| 2528 |
* Key offset: Block Group length. |
| 2529 |
|
| 2530 |
:ivar int vaddr: Virtual address. (taken from the objectid field of the |
| 2531 |
item key) |
| 2532 |
:ivar int length: Block Group length. (taken from the offset field of the |
| 2533 |
item key) |
| 2534 |
:ivar int extent_count: Amount of free space extents in the Block Group. |
| 2535 |
:ivar int flags: A flag indicating if the free space for this Block Group |
| 2536 |
is stored as bitmap. The flag is `FREE_SPACE_USING_BITMAPS`, available |
| 2537 |
as attribute of this module. |
| 2538 |
""" |
| 2539 |
_free_space_info = struct.Struct('<LL') |
| 2540 |
|
| 2541 |
def __init__(self, header, data): |
| 2542 |
super().__init__(header) |
| 2543 |
self._setattr_from_key(objectid_attr='vaddr', offset_attr='length') |
| 2544 |
self.extent_count, self.flags = FreeSpaceInfo._free_space_info.unpack(data) |
| 2545 |
|
| 2546 |
def __str__(self): |
| 2547 |
return "free space info vaddr {self.vaddr} length {self.length_str} " \ |
| 2548 |
"extent_count {self.extent_count} flags {self.flags_str}".format(self=self) |
| 2549 |
|
| 2550 |
@staticmethod |
| 2551 |
def _pretty_properties(): |
| 2552 |
return [ |
| 2553 |
(btrfs.utils.pretty_size, 'length'), |
| 2554 |
(btrfs.utils.free_space_info_flags_str, 'flags'), |
| 2555 |
] |
| 2556 |
|
| 2557 |
|
| 2558 |
class FreeSpaceExtent(ItemData): |
| 2559 |
"""Object representation for free space extent information. |
| 2560 |
|
| 2561 |
* Tree: `FREE_SPACE_TREE_OBJECTID` (10). |
| 2562 |
* Key objectid: Virtual address of the start of the free space. |
| 2563 |
* Key type: `FREE_SPACE_EXTENT_KEY` (199) |
| 2564 |
* Key offset: Length of the free space. |
| 2565 |
|
| 2566 |
Note that this metadata object type does not have actual item data. All |
| 2567 |
needed information is encoded in the item key. |
| 2568 |
|
| 2569 |
:ivar int vaddr: Virtual address of the start of the free space. (taken |
| 2570 |
from the objectid field of the item key) |
| 2571 |
:ivar int length: Length of the free space. (taken from the offset field of |
| 2572 |
the item key) |
| 2573 |
""" |
| 2574 |
def __init__(self, header, data): |
| 2575 |
super().__init__(header) |
| 2576 |
self._setattr_from_key(objectid_attr='vaddr', offset_attr='length') |
| 2577 |
|
| 2578 |
def __str__(self): |
| 2579 |
return "free space extent vaddr {self.vaddr} length {self.length}".format(self=self) |
| 2580 |
|
| 2581 |
@staticmethod |
| 2582 |
def _pretty_properties(): |
| 2583 |
return [ |
| 2584 |
(btrfs.utils.pretty_size, 'length'), |
| 2585 |
] |
| 2586 |
|
| 2587 |
|
| 2588 |
class FreeSpaceBitmap(ItemData): |
| 2589 |
"""Object representation for free space bitmap information. |
| 2590 |
|
| 2591 |
* Tree: `FREE_SPACE_TREE_OBJECTID` (10). |
| 2592 |
* Key objectid: Virtual address of the start of the free space bitmap. |
| 2593 |
* Key type: `FREE_SPACE_BITMAP_KEY` (200) |
| 2594 |
* Key offset: Length of the covered virtual address space. |
| 2595 |
|
| 2596 |
:ivar int vaddr: Virtual address of the start of the free space bitmap. |
| 2597 |
(taken from the objectid field of the item key) |
| 2598 |
:ivar int length: Length of the covered virtual address space. (taken from |
| 2599 |
the offset field of the item key) |
| 2600 |
:ivar bytes bitmap: The free space bitmap. |
| 2601 |
""" |
| 2602 |
def __init__(self, header, data): |
| 2603 |
super().__init__(header) |
| 2604 |
self._setattr_from_key(objectid_attr='vaddr', offset_attr='length') |
| 2605 |
self.bitmap = data |
| 2606 |
|
| 2607 |
def unpack(self, sectorsize): |
| 2608 |
"""Unpack the free space bitmap. |
| 2609 |
|
| 2610 |
:param int sectorsize: sectorsize property of the filesystem. |
| 2611 |
|
| 2612 |
:returns: A generator of :class:`btrfs.free_space_tree.FreeSpaceExtent` |
| 2613 |
tuples. |
| 2614 |
:rtype: Iterator[:class:`btrfs.free_space_tree.FreeSpaceExtent`] |
| 2615 |
""" |
| 2616 |
offset = self.vaddr |
| 2617 |
prev_bit = 0 |
| 2618 |
for cur_byte in self.bitmap: |
| 2619 |
for bitnr in range(8): |
| 2620 |
bit = 1 & (cur_byte >> bitnr) |
| 2621 |
if prev_bit == 0 and bit == 1: |
| 2622 |
extent_start = offset |
| 2623 |
elif prev_bit == 1 and bit == 0: |
| 2624 |
yield btrfs.free_space_tree.FreeSpaceExtent( |
| 2625 |
extent_start, offset - extent_start) |
| 2626 |
prev_bit = bit |
| 2627 |
offset += sectorsize |
| 2628 |
if prev_bit == 1: |
| 2629 |
yield btrfs.free_space_tree.FreeSpaceExtent(extent_start, offset - extent_start) |
| 2630 |
|
| 2631 |
def __str__(self): |
| 2632 |
return "free space bitmap for vaddr {self.vaddr} length {self.length}".format(self=self) |
| 2633 |
|
| 2634 |
|
| 2635 |
class OrphanItem(ItemData): |
| 2636 |
"""Object representation for orphan item information from the root tree. |
| 2637 |
|
| 2638 |
* Tree: `ROOT_TREE_OBJECTID` (1). |
| 2639 |
* Key objectid: `ORPHAN_OBJECTID` (-5). |
| 2640 |
* Key type: `ORPHAN_ITEM_KEY` (48). |
| 2641 |
* Key offset: objectid of the item in the root tree that is orphaned and |
| 2642 |
needs to be cleaned up. |
| 2643 |
|
| 2644 |
:ivar int objectid: objectid of the item in the root tree that is orphaned |
| 2645 |
and needs to be cleaned up. (taken from the offset field of the item |
| 2646 |
key) |
| 2647 |
""" |
| 2648 |
def __init__(self, header, _): |
| 2649 |
super().__init__(header) |
| 2650 |
self._setattr_from_key(offset_attr='objectid') |
| 2651 |
|
| 2652 |
def __str__(self): |
| 2653 |
return "orphan objectid {self.objectid}".format(self=self) |
| 2654 |
|
| 2655 |
|
| 2656 |
class NotImplementedItem(ItemData): |
| 2657 |
"""Placeholder object for metadata item types that have not been implemented yet.""" |
| 2658 |
def __init__(self, header, data): |
| 2659 |
super().__init__(header) |
| 2660 |
self._data = bytearray(data) |
| 2661 |
|
| 2662 |
def __str__(self): |
| 2663 |
return "not implemented item data ({} bytes)".format(len(self._data)) |
| 2664 |
|
| 2665 |
|
| 2666 |
class UnknownItem(ItemData): |
| 2667 |
"""Placeholder object for metadata item types that are unrecognized.""" |
| 2668 |
def __init__(self, header, data): |
| 2669 |
super().__init__(header) |
| 2670 |
self._data = bytearray(data) |
| 2671 |
|
| 2672 |
def __str__(self): |
| 2673 |
return "unknown item data ({} bytes)".format(len(self._data)) |
| 2674 |
|
| 2675 |
|
| 2676 |
_key_type_class_map = { |
| 2677 |
INODE_ITEM_KEY: InodeItem, |
| 2678 |
INODE_REF_KEY: InodeRefList, |
| 2679 |
INODE_EXTREF_KEY: InodeExtrefList, |
| 2680 |
XATTR_ITEM_KEY: DirItemList, |
| 2681 |
ORPHAN_ITEM_KEY: OrphanItem, |
| 2682 |
DIR_LOG_ITEM_KEY: NotImplementedItem, |
| 2683 |
DIR_LOG_INDEX_KEY: NotImplementedItem, |
| 2684 |
DIR_ITEM_KEY: DirItemList, |
| 2685 |
DIR_INDEX_KEY: DirIndex, |
| 2686 |
EXTENT_DATA_KEY: FileExtentItem, |
| 2687 |
EXTENT_CSUM_KEY: NotImplementedItem, |
| 2688 |
ROOT_ITEM_KEY: RootItem, |
| 2689 |
ROOT_REF_KEY: RootRef, |
| 2690 |
ROOT_BACKREF_KEY: NotImplementedItem, |
| 2691 |
EXTENT_ITEM_KEY: ExtentItem, |
| 2692 |
METADATA_ITEM_KEY: MetaDataItem, |
| 2693 |
TREE_BLOCK_REF_KEY: TreeBlockRef, |
| 2694 |
EXTENT_DATA_REF_KEY: ExtentDataRef, |
| 2695 |
SHARED_BLOCK_REF_KEY: SharedBlockRef, |
| 2696 |
SHARED_DATA_REF_KEY: SharedDataRef, |
| 2697 |
BLOCK_GROUP_ITEM_KEY: BlockGroupItem, |
| 2698 |
FREE_SPACE_INFO_KEY: FreeSpaceInfo, |
| 2699 |
FREE_SPACE_EXTENT_KEY: FreeSpaceExtent, |
| 2700 |
FREE_SPACE_BITMAP_KEY: FreeSpaceBitmap, |
| 2701 |
DEV_EXTENT_KEY: DevExtent, |
| 2702 |
DEV_ITEM_KEY: DevItem, |
| 2703 |
CHUNK_ITEM_KEY: Chunk, |
| 2704 |
QGROUP_STATUS_KEY: NotImplementedItem, |
| 2705 |
QGROUP_INFO_KEY: NotImplementedItem, |
| 2706 |
QGROUP_LIMIT_KEY: NotImplementedItem, |
| 2707 |
DEV_REPLACE_KEY: NotImplementedItem, |
| 2708 |
UUID_KEY_SUBVOL: NotImplementedItem, |
| 2709 |
UUID_KEY_RECEIVED_SUBVOL: NotImplementedItem, |
| 2710 |
STRING_ITEM_KEY: NotImplementedItem, |
| 2711 |
} |
| 2712 |
|
| 2713 |
|
| 2714 |
def classify(header, data): |
| 2715 |
""" |
| 2716 |
Convenience function to automatically convert an item header and data into |
| 2717 |
one of the object types in this module. |
| 2718 |
|
| 2719 |
:param header: Search header. |
| 2720 |
:type header: :class:`btrfs.ioctl.SearchHeader` |
| 2721 |
:param bytes data: Item data. |
| 2722 |
:returns: Object representing the metadata item. |
| 2723 |
:rtype: Subclass of :class:`ItemData` |
| 2724 |
|
| 2725 |
Example:: |
| 2726 |
|
| 2727 |
>>> with btrfs.FileSystem('/') as fs: |
| 2728 |
... chunk_tree_objects = btrfs.ioctl.search_v2(fs.fd, 3) |
| 2729 |
... btrfs.utils.pretty_print( |
| 2730 |
... (btrfs.ctree.classify(header, data) |
| 2731 |
... for header, data in chunk_tree_objects) |
| 2732 |
... ) |
| 2733 |
|
| 2734 |
The search function returns a generator, which we name chunk_tree_objects. |
| 2735 |
The pretty printer can handle any iterable, so the above fragment will, in |
| 2736 |
a 'streaming' way, dump the chunk tree on the screen. |
| 2737 |
""" |
| 2738 |
if header.type == PERSISTENT_ITEM_KEY: |
| 2739 |
if header.objectid == DEV_STATS_OBJECTID: |
| 2740 |
return NotImplementedItem(header, data) |
| 2741 |
return UnknownItem(header, data) |
| 2742 |
|
| 2743 |
if header.type == TEMPORARY_ITEM_KEY: |
| 2744 |
if header.objectid == BALANCE_OBJECTID: |
| 2745 |
return NotImplementedItem(header, data) |
| 2746 |
return UnknownItem(header, data) |
| 2747 |
|
| 2748 |
return _key_type_class_map.get(header.type, UnknownItem)(header, data) |