Debian Codegraph @

btrfs/fs_usage.py

raw symbols SCIP
1 # Copyright (C) 2018 Hans van Kranenburg <[email protected]>
2 #
3 # This file is part of the python-btrfs module.
4 #
5 # python-btrfs is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # python-btrfs is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with python-btrfs. If not, see <http://www.gnu.org/licenses/>.
17
18 """
19 This module provides advanced usage reporting for a btrfs filesystem.
20
21 By calling the :func:`~btrfs.ctree.FileSystem.usage` function on a
22 :class:`btrfs.ctree.FileSystem` object, an :class:`FsUsage` object is returned
23 that can be inspected.
24
25 Example::
26
27 >>> import btrfs
28 >>> with btrfs.FileSystem('/') as fs:
29 ... usage = fs.usage()
30 ... btrfs.utils.pretty_print(usage)
31
32 .. note::
33
34 If you're not yet familiar with it, btrfs terminology can be quite
35 confusing.
36
37 Here's just an example: In btrfs terminology, a ‘space’ is the collection
38 of all block groups that have identical type and profile flags. For
39 example, Metadata, DUP is a ‘space’. The word ‘space’ is also used for the
40 distinction between ‘physical address space’ and ‘virtual address space’.
41
42 """
43
44 import btrfs
45 import copy
46 from btrfs.ctree import ( # noqa
47 BLOCK_GROUP_DATA, BLOCK_GROUP_SYSTEM, BLOCK_GROUP_METADATA,
48 BLOCK_GROUP_TYPE_MASK, BLOCK_GROUP_PROFILE_MASK,
49 )
50
51
52 class DevSpaceUsage(object):
53 """Physical usage details for a single space per device.
54
55 For example, a `Data, DUP` chunk of 1GiB results in a 2GiB allocation of
56 physical bytes on the device. A `Data, RAID5` chunk of 3GiB, allocated over
57 4 devices results in a 1GiB allocation on each device, with 256MiB reserved
58 for parity.
59
60 :ivar int flags: Block group type and profile, e.g. `Data, RAID1`.
61 :ivar int devid: Device ID
62 :ivar int allocated: Total amount of allocated physical bytes.
63 :ivar int parity: Amount of allocated physical bytes reserved for parity.
64
65 .. note::
66 Objects of this type are provided as part of an :class:`FsUsage` object.
67
68 """
69 def __init__(self, devid, flags):
70 self.flags = flags
71 self.devid = devid
72 self.allocated = 0
73 self.parity = 0
74
75 def _add_usage(self, allocated, parity):
76 self.allocated += allocated
77 self.parity += parity
78
79 @staticmethod
80 def _pretty_properties():
81 return [
82 (btrfs.utils.block_group_flags_str, 'flags'),
83 (btrfs.utils.pretty_size, 'allocated'),
84 (btrfs.utils.pretty_size, 'parity'),
85 ]
86
87
88 class DevUsage(object):
89 """Physical usage details for a device.
90
91 :ivar int devid: Device ID
92 :ivar int total: Total amount of bytes.
93 :ivar int allocated: Total amount of allocated bytes.
94 :ivar dev_space_usage: Allocated and parity bytes per space for this
95 device, indexed by space flags.
96 :vartype dev_space_usage: dict of DevSpaceUsage
97 :ivar int unallocatable: Physical bytes that are not allocatable because of
98 unbalanced device sizes.
99 :ivar int unallocatable_reclaimable: Physical bytes that are not
100 allocatable because of unbalanced allocations.
101
102 .. note::
103 Objects of this type are provided as part of an :class:`FsUsage` object.
104
105 """
106 def __init__(self, device):
107 self.devid = device.devid
108 self.total = device.total_bytes
109 self.allocated = device.bytes_used
110 self.unallocated = self.total - self.allocated
111 self.dev_space_usage = {}
112 self.unallocatable_soft = None # set during FsUsage init
113 self.unallocatable_hard = None # set during FsUsage init
114 self.unallocatable_reclaimable = None # set during FsUsage init
115
116 def _dev_space_usage_key_str(flags):
117 return btrfs.utils.block_group_flags_str(flags)
118
119 def _add_usage(self, flags, allocated, parity):
120 if flags not in self.dev_space_usage:
121 self.dev_space_usage[flags] = DevSpaceUsage(self.devid, flags)
122 self.dev_space_usage[flags]._add_usage(allocated, parity)
123
124 def _init_unallocatable_reclaimable(self):
125 self.unallocatable_reclaimable = \
126 max(self.unallocatable_soft - self.unallocatable_hard, 0)
127
128 @staticmethod
129 def _pretty_properties():
130 return [
131 (btrfs.utils.pretty_size, 'total'),
132 (btrfs.utils.pretty_size, 'allocated'),
133 (btrfs.utils.pretty_size, 'unallocated'),
134 (btrfs.utils.pretty_size, 'unallocatable_soft'),
135 (btrfs.utils.pretty_size, 'unallocatable_hard'),
136 (btrfs.utils.pretty_size, 'unallocatable_reclaimable'),
137 ]
138
139
140 class RawSpaceUsage(object):
141 """Physical usage details per space.
142
143 For example, if the `Metadata, RAID1` space has a 2GiB size in terms of
144 virtual addressing, in which 768MiB is used, then the allocated physical
145 size is 4GiB and amount of physical bytes used is 1.5GiB. A `Data, RAID6`
146 space of 8GiB, consisting of two 4GiB block groups (virtual address space),
147 each distributed over 6 devices, will occupy 2*(4+2) = 12 GiB physical
148 allocated bytes and have 4GiB of allocated bytes reserved for parity
149 blocks.
150
151 :ivar int flags: Block group type and profile, e.g. `Data, RAID1`.
152 :ivar int allocated: Total amount of allocated bytes.
153 :ivar int parity: Total amount of allocated bytes reserved for parity
154 blocks.
155 :ivar int used: Total amount of physical bytes used.
156
157 .. note::
158 Objects of this type are provided as part of an :class:`FsUsage` object.
159
160 """
161 def __init__(self, space):
162 self.flags = space.flags
163 ratio = btrfs.volumes.block_group_profile_ncopies(space.flags)
164 self.allocated = space.total_bytes * ratio # initially missing parity blocks
165 self.used = space.used_bytes * ratio
166 self.parity = 0
167
168 def _add_usage(self, parity):
169 self.allocated += parity
170 self.parity += parity
171
172 @staticmethod
173 def _pretty_properties():
174 return [
175 (btrfs.utils.block_group_flags_str, 'flags'),
176 (btrfs.utils.pretty_size, 'allocated'),
177 (btrfs.utils.pretty_size, 'parity'),
178 (btrfs.utils.pretty_size, 'used'),
179 ]
180
181
182 class BlockGroupTypeUsage(object):
183 """Physical usage details per block group type.
184
185 Totals per block group type (`System`, `Data`, `Metadata`, or,
186 `Data+Metadata` for mixed mode), disregarding the block group profile
187 (`Single`, `RAID1`, etc).
188
189 :ivar int type: Block group type, e.g. `Metadata`.
190 :ivar int allocated: Total amount of allocated bytes.
191 :ivar int parity: Total amount of allocated bytes reserved for parity
192 blocks.
193 :ivar int used: Total amount of physical bytes used.
194
195 .. note::
196 Objects of this type are provided as part of an :class:`FsUsage` object.
197
198 """
199 def __init__(self, block_group_type):
200 self.type = block_group_type
201 self.allocated = 0
202 self.used = 0
203 self.parity = 0
204
205 def _add_usage(self, allocated, parity, used):
206 self.allocated += allocated
207 self.parity += parity
208 self.used += used
209
210 @staticmethod
211 def _pretty_properties():
212 return [
213 (btrfs.utils.block_group_flags_str, 'type'),
214 (btrfs.utils.pretty_size, 'allocated'),
215 (btrfs.utils.pretty_size, 'parity'),
216 (btrfs.utils.pretty_size, 'used'),
217 ]
218
219
220 class VirtualSpaceUsage(object):
221 """Virtual usage per space.
222
223 :ivar int flags: Block group type and profile, e.g. `Data, RAID1`.
224 :ivar int total: Total amount of allocated bytes for this space.
225 :ivar int used: Total amount of virtual bytes used.
226
227 .. note::
228 Objects of this type are provided as part of an :class:`FsUsage` object.
229
230 """
231 def __init__(self, space):
232 self.flags = space.flags
233 self.total = space.total_bytes
234 self.used = space.used_bytes
235
236 @staticmethod
237 def _pretty_properties():
238 return [
239 (btrfs.utils.block_group_flags_str, 'flags'),
240 (btrfs.utils.pretty_size, 'total'),
241 (btrfs.utils.pretty_size, 'used'),
242 ]
243
244
245 class VirtualBlockGroupTypeUsage(object):
246 """Virtual address space usage per block group type.
247
248 Totals for the virtual address space per block group type (`System`,
249 `Data`, `Metadata`, or, `Data+Metadata` for mixed mode), disregarding the
250 block group profile (`Single`, `RAID1`, etc).
251
252 :ivar int flags: Block group type, e.g. `Metadata`.
253 :ivar int total: Total amount of allocated bytes.
254 :ivar int used: Total amount of virtual bytes used.
255 :ivar int unused: Amount of allocated but unused virtual bytes.
256
257 .. note::
258 Objects of this type are provided as part of an :class:`FsUsage` object.
259
260 """
261 def __init__(self, block_group_type):
262 self.type = block_group_type
263 self.total = 0
264 self.used = 0
265 self.unused = None
266
267 def _add_usage(self, total, used):
268 self.total += total
269 self.used += used
270 self.unused = self.total - self.used
271
272 @staticmethod
273 def _pretty_properties():
274 return [
275 (btrfs.utils.block_group_flags_str, 'type'),
276 (btrfs.utils.pretty_size, 'total'),
277 (btrfs.utils.pretty_size, 'used'),
278 (btrfs.utils.pretty_size, 'unused'),
279 ]
280
281
282 class FsUsage(object):
283 """Detailed usage information for a file system.
284
285 When creating an object of this type, the first argument, fs, is mandatory.
286 The other arguments can be used to influence the simulation to predict free
287 space and unallocatable space with explicit hints instead of using
288 information from the current filesystem, This is used by the
289 space-calculator program to run the simulation starting with a completely
290 empty filesystem.
291
292 :param btrfs.ctree.FileSystem fs: Filesystem to examine.
293 :param int data_metadata_ratio: Data to metadata ratio to use when running
294 the simulation to predict free space and unallocatable space.
295 :param int target_profile_metadata: Explicitly set metadata profile to use
296 for new allocations when running the simulation to predict free
297 and unallocatable space (not for a mixed filesystem).
298 :param int target_profile_data: Explicitly set data profile to use for new
299 allocations when running the simulation to predict free and
300 unallocatable space (not for a mixed filesystem).
301 :param int target_profile_mixed: Explicitly set metadata and data profile
302 to use for new allocations when running the simulation to predict free
303 and unallocatable space (only for a mixed filesystem).
304
305 Target block group profiles (used for new chunk allocations):
306
307 :ivar int target_profile_system: Profile for new System chunk allocations.
308 :ivar int target_profile_metadata: Profile for new Metadata chunk
309 allocations (not for a mixed filesystem).
310 :ivar int target_profile_data: Profile for new Data chunk allocations (not
311 for a mixed filesystem).
312 :ivar int target_profile_mixed: Profile for new Data+Metadata chunk
313 allocations (only for a mixed filesystem).
314
315 Usage details for the physical address space:
316
317 :ivar int total: Total amount of physical bytes in the filesystem.
318 :ivar int allocated: Total amount of allocated physical bytes.
319 :ivar int parity: Total amount of allocated bytes reserved for parity
320 blocks.
321 :ivar dev_usage: Physical usage details per device, indexed by Device ID.
322 :vartype dev_usage: dict of DevUsage
323 :ivar block_group_type_usage: Physical usage details per block group type,
324 indexed by block group type.
325 :vartype block_group_type_usage: dict of BlockGroupTypeUsage
326 :ivar raw_space_usage: Physical usage details per space, indexed by space
327 flags.
328 :vartype raw_space_usage: dict of RawSpaceUsage
329
330 Usage details for the virtual address space:
331
332 :ivar int virtual_total: Total amount of virtual address space.
333 :ivar int virtual_used: Total amount of bytes used inside the virtual
334 address space.
335 :ivar virtual_block_group_type_usage: Virtual address space usage per block
336 group type, indexed by block group type.
337 :vartype virtual_block_group_type_usage: dict of VirtualBlockGroupTypeUsage
338 :ivar VirtualSpaceUsage virtual_space_usage: Virtual usage per space,
339 indexed by space flags.
340 :vartype virtual_space_usage: dict of VirtualSpaceUsage
341
342 Allocatable space information:
343
344 The *soft* unallocatable amount of bytes is the currently unallocatable
345 part of the physical bytes on attached devices because the allocations in
346 the filesystem are unbalanced. This value is estimated by extrapolating the
347 current usage pattern and simulating new chunk allocations using the
348 current target allocation profiles. By doing so, we also discover how much
349 extra *virtual* address space these allocations would result in.
350
351 :ivar int unallocatable_soft: Unallocatable physical disk space because of
352 unbalanced allocations.
353 :ivar int estimated_allocatable_virtual_metadata: Estimated amount of
354 virtual address space bytes that can be added by allocating physical
355 bytes for metadata, based on the current usage pattern (not for a mixed
356 filesystem).
357 :ivar int estimated_allocatable_virtual_data: Estimated amount of virtual
358 address space bytes that can be added by allocating physical bytes for
359 data, based on the current usage pattern (not for a mixed filesystem).
360 :ivar int estimated_allocatable_virtual_mixed: Estimated amount of virtual
361 address space bytes that can be added by allocating physical bytes for
362 metadata and data,, based on the current usage pattern (only for a
363 mixed filesystem).
364
365 The *hard* unallocatable amount of bytes is the amount of physical bytes
366 that cannot be used for allocations, because of having different sizes of
367 devices attached. These values are unallocatable disk space that remains
368 after trying to simulate data and metadata allocations in a ratio similar
369 to current usage, starting with all disks being empty.
370
371 :ivar int unallocatable_hard: Unallocatable physical disk space because of
372 unbalanced device sizes.
373 :ivar int estimated_full_allocatable_virtual_metadata: Estimated amount of
374 virtual address space bytes for metadata, in case of optimally balanced
375 allocations. (not for a mixed filesystem).
376 :ivar int estimated_full_allocatable_virtual_data: Estimated amount of
377 virtual address space bytes for data, in case of optimally balanced
378 allocations. (not for a mixed filesystem).
379 :ivar int estimated_full_allocatable_virtual_mixed: Estimated amount of
380 virtual address space bytes for metadata and data, in case of optimally
381 balanced allocations. (only for a mixed filesystem).
382
383 The difference between *soft* and *hard* unallocatable bytes is the amount
384 of physical disk space that can be reclaimed for allocations when
385 rebalancing the filesystem.
386
387 :ivar int unallocatable_reclaimable: Unallocatable physical bytes that can
388 be reclaimed when balancing the filesystem.
389
390 Some other totals for convenience:
391
392 :ivar int allocatable: The total amount of physical bytes that are
393 allocatable in this filesystem. I.e. total size minus
394 unallocatable_soft.
395 :ivar int allocatable_left: The amount of allocatable physical bytes
396 remaining, until the filesystem will report being out of space, given
397 current usage pattern and target profiles.
398
399 By combining the unused virtual space in already allocated chunks and
400 estimated allocatable virtual bytes, we get actual numbers of estimated
401 free space. I.e., what we would like df to show us.
402
403 :ivar int free_metadata: Estimated virtual space left to use for metadata
404 (not for a mixed filesystem).
405 :ivar int free_data: Estimated virtual space left to use for data (not for
406 a mixed filesystem).
407 :ivar int free_mixed: Estimated virtual space left to use for metadata and
408 data (only for a mixed filesystem).
409
410 """
411 def __init__(self, fs, data_metadata_ratio=None,
412 target_profile_metadata=None,
413 target_profile_data=None,
414 target_profile_mixed=None):
415 self._mixed_groups = fs.mixed_groups()
416
417 # Spaces and devices are a source of information
418 spaces = [
419 space
420 for space in fs.space_info()
421 if space.flags != btrfs.ctree.SPACE_INFO_GLOBAL_RSV
422 ]
423 devices = list(fs.devices())
424
425 self.raw_space_usage = {
426 space.flags: RawSpaceUsage(space)
427 for space in spaces
428 }
429 self.dev_usage = {
430 device.devid: DevUsage(device)
431 for device in devices
432 }
433 self.total = sum(
434 device.total_bytes
435 for device in devices
436 )
437 self.allocated = sum(
438 device.bytes_used
439 for device in devices
440 )
441 self.parity = 0
442
443 BLOCK_GROUP_MIXED = btrfs.BLOCK_GROUP_METADATA | btrfs.BLOCK_GROUP_DATA
444 if not self._mixed_groups:
445 if target_profile_metadata is not None:
446 self.target_profile_system = target_profile_metadata | btrfs.BLOCK_GROUP_SYSTEM
447 self.target_profile_metadata = target_profile_metadata | btrfs.BLOCK_GROUP_METADATA
448 if target_profile_data is not None:
449 self.target_profile_data = target_profile_data | btrfs.BLOCK_GROUP_DATA
450 else:
451 if target_profile_mixed is not None:
452 self.target_profile_system = target_profile_mixed | btrfs.BLOCK_GROUP_SYSTEM
453 self.target_profile_mixed = target_profile_mixed | BLOCK_GROUP_MIXED
454
455 # We walk the chunk list because every block group / chunk can be laid
456 # out over any amount of disks. To collect e.g. the amount of parity
457 # bytes, we need to look at all of them.
458 #
459 # Confusing: chunk.type is actually all the flags, so type and profile
460 # combined.
461 for chunk in fs.chunks():
462 flags = chunk.type
463 if flags not in self.raw_space_usage:
464 continue # A conversion to this profile just started right now?
465 # Remember last seen chunk types as target profiles
466 block_group_type = flags & BLOCK_GROUP_TYPE_MASK
467 if block_group_type == BLOCK_GROUP_SYSTEM:
468 self.target_profile_system = flags
469 elif not self._mixed_groups:
470 if block_group_type == BLOCK_GROUP_DATA:
471 self.target_profile_data = flags
472 elif block_group_type == BLOCK_GROUP_METADATA:
473 self.target_profile_metadata = flags
474 else:
475 self.target_profile_mixed = flags
476
477 dev_extent_length = btrfs.volumes.chunk_to_dev_extent_length(chunk)
478 chunk_raw_parity_bytes = btrfs.volumes.chunk_to_raw_parity_bytes(chunk)
479 self.parity += chunk_raw_parity_bytes
480 self.raw_space_usage[flags]._add_usage(chunk_raw_parity_bytes)
481 dev_extent_parity_bytes = chunk_raw_parity_bytes // len(chunk.stripes)
482 for stripe in chunk.stripes:
483 if stripe.devid not in self.dev_usage:
484 continue # A device just got added?
485 self.dev_usage[stripe.devid]._add_usage(flags,
486 dev_extent_length,
487 dev_extent_parity_bytes)
488
489 # Combine information from different spaces with same chunk type into
490 # totals per block group type. So, e.g. all DATA space, regardless of
491 # being single, RAID1, etc...
492 self.block_group_type_usage = {}
493 for raw_space in self.raw_space_usage.values():
494 space_type = raw_space.flags & BLOCK_GROUP_TYPE_MASK
495 if space_type not in self.block_group_type_usage:
496 self.block_group_type_usage[space_type] = BlockGroupTypeUsage(space_type)
497 self.block_group_type_usage[space_type]._add_usage(
498 raw_space.allocated, raw_space.parity, raw_space.used)
499
500 self.virtual_space_usage = {
501 space.flags: VirtualSpaceUsage(space)
502 for space in spaces
503 }
504
505 # Combine information from different spaces with same chunk type into
506 # totals per block group type. So, e.g. all DATA space, regardless of
507 # being single, RAID1, etc...
508 self.virtual_block_group_type_usage = {}
509
510 for virtual_space in self.virtual_space_usage.values():
511 space_type = virtual_space.flags & BLOCK_GROUP_TYPE_MASK
512 if space_type not in self.virtual_block_group_type_usage:
513 self.virtual_block_group_type_usage[space_type] = \
514 VirtualBlockGroupTypeUsage(space_type)
515 self.virtual_block_group_type_usage[space_type]._add_usage(
516 virtual_space.total, virtual_space.used)
517
518 # The total size of the block groups in the virtual address space
519 self.virtual_total = sum(
520 virtual_space.total
521 for virtual_space in self.virtual_space_usage.values()
522 )
523
524 self.virtual_used = sum(
525 virtual_space.used
526 for virtual_space in self.virtual_space_usage.values()
527 )
528
529 if data_metadata_ratio is not None:
530 self.default_data_metadata_ratio = data_metadata_ratio
531 else:
532 self.default_data_metadata_ratio = 200
533
534 # Estimate the amount of unallocatable raw disk space if the sizes of
535 # attached block devices are unbalanced. We start the simulation with
536 # the entire sizes of the attached devices and keep allocating chunks
537 # until not possible any more.
538 #
539 device_sizes = {
540 devid: dev_usage.total
541 for devid, dev_usage in self.dev_usage.items()
542 }
543 if not self._mixed_groups:
544 # The estimated "full" allocatable numbers are the estimation of
545 # virtual space to be used for data and metadata when the
546 # filesystem would be totally empty to begin with.
547 #
548 # This is e.g. used by the space calculator example.
549 dev_unallocatable_hard, \
550 self.estimated_full_allocatable_virtual_metadata, \
551 self.estimated_full_allocatable_virtual_data = \
552 self._simulate_chunk_allocations(device_sizes)
553 else:
554 dev_unallocatable_hard, \
555 self.estimated_full_allocatable_virtual_mixed = \
556 self._simulate_chunk_allocations(device_sizes)
557 for devid, unallocatable_hard in dev_unallocatable_hard.items():
558 self.dev_usage[devid].unallocatable_hard = unallocatable_hard
559 self.unallocatable_hard = sum(dev_unallocatable_hard.values())
560
561 # Next, we estimate the amount of unallocatable raw disk space when
562 # starting out with the current state of the filesystem.
563 unallocated_sizes = {
564 devid: dev_usage.unallocated
565 for devid, dev_usage in self.dev_usage.items()
566 }
567 if not self._mixed_groups:
568 dev_unallocatable_soft, \
569 self.estimated_allocatable_virtual_metadata, \
570 self.estimated_allocatable_virtual_data = \
571 self._simulate_chunk_allocations(unallocated_sizes)
572 else:
573 dev_unallocatable_soft, \
574 self.estimated_allocatable_virtual_mixed = \
575 self._simulate_chunk_allocations(unallocated_sizes)
576 for devid, unallocatable_soft in dev_unallocatable_soft.items():
577 self.dev_usage[devid].unallocatable_soft = unallocatable_soft
578 self.unallocatable_soft = sum(dev_unallocatable_soft.values())
579
580 # At this point, it is possible that the unallocatable_hard amounts are
581 # higher than the unallocatable_soft amounts. E.g. if we just switched
582 # to another target profile. In that case, this means we can not fully
583 # rewrite all data to the target profile!
584
585 # For convenience reasons, we provide a few more derived numbers...
586 #
587 # If the soft unallocatable amount of bytes is higher than the hard
588 # amount, we can reclaim space by balancing the filesystem.
589 self.unallocatable_reclaimable = \
590 max(self.unallocatable_soft - self.unallocatable_hard, 0)
591 for dev_usage in self.dev_usage.values():
592 dev_usage._init_unallocatable_reclaimable()
593
594 self.allocatable = self.total - self.unallocatable_soft
595 self.allocatable_left = self.allocatable - self.allocated
596
597 if not self._mixed_groups:
598 self.free_metadata = self.estimated_allocatable_virtual_metadata
599 if btrfs.BLOCK_GROUP_METADATA in self.virtual_block_group_type_usage:
600 self.free_metadata += \
601 self.virtual_block_group_type_usage[btrfs.BLOCK_GROUP_METADATA].unused
602 self.free_data = self.estimated_allocatable_virtual_data
603 if btrfs.BLOCK_GROUP_DATA in self.virtual_block_group_type_usage:
604 self.free_data += \
605 self.virtual_block_group_type_usage[btrfs.BLOCK_GROUP_DATA].unused
606 else:
607 self.free_mixed = self.estimated_allocatable_virtual_mixed
608 if BLOCK_GROUP_MIXED in self.virtual_block_group_type_usage:
609 self.free_mixed += \
610 self.virtual_block_group_type_usage[BLOCK_GROUP_MIXED].unused
611
612 def _raw_space_usage_key_str(flags):
613 return btrfs.utils.block_group_flags_str(flags)
614
615 def _block_group_type_usage_key_str(block_group_type):
616 return btrfs.utils.block_group_flags_str(block_group_type)
617
618 def _virtual_space_usage_key_str(flags):
619 return btrfs.utils.block_group_flags_str(flags)
620
621 def _virtual_block_group_type_usage_key_str(block_group_type):
622 return btrfs.utils.block_group_flags_str(block_group_type)
623
624 def _data_metadata_ratio(self):
625 """
626 Determine data to metadata ratio for allocation simulation for wasted space.
627
628 E.g. a ratio of 200 means that for every X bytes of metadata, we can
629 allocate 200*X bytes for data.
630
631 Actual simulation ratio is a weighted combination of the current data to
632 metadata ratio and the default of 200, where the weight of the current
633 ratio increases if the filesystem is filled up more.
634
635 If an empty filesystem is presented (this is used for the space
636 calculator), then just use the default that was set earlier.
637 """
638 if self._mixed_groups:
639 raise ValueError("Data to metadata ratio is irrelevant for mixed groups.")
640 if BLOCK_GROUP_METADATA not in self.virtual_block_group_type_usage:
641 return self.default_data_metadata_ratio
642 used_fraction = self.virtual_used / self.total
643 used_metadata = self.virtual_block_group_type_usage[BLOCK_GROUP_METADATA].used
644 used_data = self.virtual_block_group_type_usage[BLOCK_GROUP_DATA].used
645 used_ratio = used_data / used_metadata
646 return used_fraction * used_ratio + (1 - used_fraction) * self.default_data_metadata_ratio
647
648 def _alloc_chunk(self, sizes, flags):
649 """
650 This is used by the wasted space calculator.
651
652 sizes is a dictionary {devid: allocatable_bytes, ...}
653 which will be modified in place as side effect
654 flags contains allocation type, which is DATA (also for mixed) or METADATA
655
656 This function tries to reduce unallocated raw bytes on each disk in a way
657 similar to the workings of the btrfs chunk allocator. The sizes dictionary
658 will be modified in place while doing so. When returning False, no chunk
659 allocation is possible any more, and sizes will show the amount of
660 unallocatable bytes per device.
661 """
662 attrs = btrfs.volumes._raid_attrs(flags & BLOCK_GROUP_PROFILE_MASK)
663 if flags & BLOCK_GROUP_DATA:
664 max_stripe_size = btrfs.utils.SZ_1G
665 max_chunk_size = btrfs.volumes.BTRFS_MAX_DATA_CHUNK_SIZE
666 elif flags & BLOCK_GROUP_METADATA:
667 if self.total > 50 * btrfs.utils.SZ_1G:
668 max_stripe_size = btrfs.utils.SZ_1G
669 else:
670 max_stripe_size = btrfs.utils.SZ_256M
671 max_chunk_size = max_stripe_size
672 else:
673 raise ValueError("Only DATA and METADATA supported here")
674 # we don't want a chunk larger than 10% of writeable space
675 max_chunk_size = min(self.total // 10, max_chunk_size)
676 # [(devid, unallocated), ...], most unallocated space per device first
677 non_zero_sizes = {
678 devid: unallocated
679 for devid, unallocated in sizes.items()
680 if unallocated > 0
681 }
682 sorted_sizes = sorted(list(non_zero_sizes.items()), key=lambda x: -x[1])
683 # Keep a multiple of devs_increment, chop off the rest
684 sorted_sizes = sorted_sizes[:len(sorted_sizes) -
685 (len(sorted_sizes) % attrs.devs_increment)]
686 if len(sorted_sizes) < attrs.devs_min:
687 return 0
688 # Keep only the amount we need for a single chunk allocation
689 if attrs.devs_max != 0:
690 sorted_sizes = sorted_sizes[:min(len(sorted_sizes), attrs.devs_max)]
691 # Actual device extent size is limited by the device with least amount of
692 # available space and by max_stripe_size.
693 stripe_size = min(max_stripe_size, sorted_sizes[-1][1] // attrs.dev_stripes)
694 # But, there's another limit, the max_chunk_size...
695 num_stripes = len(sorted_sizes) * attrs.dev_stripes
696 chunk_size = btrfs.volumes.dev_extent_length_to_chunk_length(
697 flags, num_stripes, stripe_size)
698 if chunk_size > max_chunk_size:
699 stripe_size = btrfs.volumes.chunk_length_to_dev_extent_length(
700 flags, num_stripes, max_chunk_size)
701 chunk_size = max_chunk_size
702 # Finally, decrease unallocated space
703 for devid, _ in sorted_sizes:
704 sizes[devid] -= stripe_size * attrs.dev_stripes
705 return chunk_size
706
707 def _simulate_chunk_allocations(self, sizes):
708 """
709 Try to do metadata and data allocations until no longer possible. The sizes
710 dictionary is modified in place and lists the amount of unallocatable space
711 per disk when the function returns.
712 """
713 _sizes = copy.deepcopy(sizes) # copy will be modified in place
714 if not self._mixed_groups:
715 ratio = self._data_metadata_ratio()
716 metadata_flags = self.target_profile_metadata
717 data_flags = self.target_profile_data
718 virtual_data = 0
719 virtual_metadata = 0
720 while True:
721 chunk_size = self._alloc_chunk(_sizes, metadata_flags)
722 if chunk_size == 0:
723 return _sizes, virtual_metadata, virtual_data
724 virtual_metadata += chunk_size
725 while virtual_data / virtual_metadata < ratio:
726 chunk_size = self._alloc_chunk(_sizes, data_flags)
727 if chunk_size == 0:
728 return _sizes, virtual_metadata, virtual_data
729 virtual_data += chunk_size
730 else:
731 flags = self.target_profile_mixed
732 virtual_mixed = 0
733 while True:
734 chunk_size = self._alloc_chunk(_sizes, flags)
735 if chunk_size == 0:
736 return _sizes, virtual_mixed
737 virtual_mixed += chunk_size
738
739 @staticmethod
740 def _pretty_properties():
741 return [
742 (btrfs.utils.space_profile_description, 'target_profile_system'),
743 (btrfs.utils.space_profile_description, 'target_profile_metadata'),
744 (btrfs.utils.space_profile_description, 'target_profile_data'),
745 (btrfs.utils.space_profile_description, 'target_profile_mixed'),
746 (btrfs.utils.btrfs.utils.pretty_size, 'total'),
747 (btrfs.utils.btrfs.utils.pretty_size, 'allocated'),
748 (btrfs.utils.btrfs.utils.pretty_size, 'parity'),
749 (btrfs.utils.btrfs.utils.pretty_size, 'virtual_total'),
750 (btrfs.utils.btrfs.utils.pretty_size, 'virtual_used'),
751 (btrfs.utils.btrfs.utils.pretty_size, 'unalloctable_soft'),
752 (btrfs.utils.btrfs.utils.pretty_size, 'estimated_allocatable_virtual_metadata'),
753 (btrfs.utils.btrfs.utils.pretty_size, 'estimated_allocatable_virtual_data'),
754 (btrfs.utils.btrfs.utils.pretty_size, 'estimated_allocatable_virtual_mixed'),
755 (btrfs.utils.btrfs.utils.pretty_size, 'unallocatable_hard'),
756 (btrfs.utils.btrfs.utils.pretty_size, 'estimated_full_allocatable_virtual_metadata'),
757 (btrfs.utils.btrfs.utils.pretty_size, 'estimated_full_allocatable_virtual_data'),
758 (btrfs.utils.btrfs.utils.pretty_size, 'estimated_full_allocatable_virtual_mixed'),
759 (btrfs.utils.btrfs.utils.pretty_size, 'unallocatable_reclaimable'),
760 (btrfs.utils.btrfs.utils.pretty_size, 'allocatable'),
761 (btrfs.utils.btrfs.utils.pretty_size, 'allocatable_left'),
762 (btrfs.utils.btrfs.utils.pretty_size, 'free_metadata'),
763 (btrfs.utils.btrfs.utils.pretty_size, 'free_data'),
764 (btrfs.utils.btrfs.utils.pretty_size, 'free_mixed'),
765 ]