|
| 1 | +#!/usr/bin/python3 |
| 2 | +# |
| 3 | +# Copyright (C) 2018 Hans van Kranenburg <[email protected]> |
| 4 | +# , 2023 Jacob Chapman <github.com/chapmanjacobd> |
| 5 | +# |
| 6 | +# Permission is hereby granted, free of charge, to any person obtaining |
| 7 | +# a copy of this software and associated documentation files (the |
| 8 | +# "Software"), to deal in the Software without restriction, including |
| 9 | +# without limitation the rights to use, copy, modify, merge, publish, |
| 10 | +# distribute, sublicense, and/or sell copies of the Software, and to |
| 11 | +# permit persons to whom the Software is furnished to do so, subject to |
| 12 | +# the following conditions: |
| 13 | +# |
| 14 | +# The above copyright notice and this permission notice shall be included |
| 15 | +# in all copies or substantial portions of the Software. |
| 16 | +# |
| 17 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 18 | +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 19 | +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| 20 | +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
| 21 | +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, |
| 22 | +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| 23 | +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 24 | + |
| 25 | +import argparse |
| 26 | +import errno |
| 27 | +import sys |
| 28 | +from itertools import repeat |
| 29 | +from multiprocessing import Pool |
| 30 | + |
| 31 | +import btrfs |
| 32 | +from btrfs.utils import pretty_size |
| 33 | + |
| 34 | + |
| 35 | +class Bork(Exception): |
| 36 | + pass |
| 37 | + |
| 38 | + |
| 39 | +def parse_args(): |
| 40 | + parser = argparse.ArgumentParser() |
| 41 | + parser.add_argument( |
| 42 | + '--usage', |
| 43 | + action="store_true", |
| 44 | + help="Print device blockgroup usage", |
| 45 | + ) |
| 46 | + parser.add_argument( |
| 47 | + 'mountpoint', |
| 48 | + help="Btrfs filesystem mountpoint", |
| 49 | + ) |
| 50 | + return parser.parse_args() |
| 51 | + |
| 52 | + |
| 53 | +def safe_get_block_group(t): |
| 54 | + fs, vaddr = t |
| 55 | + try: |
| 56 | + return fs.block_group(vaddr) |
| 57 | + except IndexError: |
| 58 | + return None |
| 59 | + |
| 60 | + |
| 61 | +def report_usage(args): |
| 62 | + with btrfs.FileSystem(args.mountpoint) as fs: |
| 63 | + devices = fs.devices() |
| 64 | + devids = [d.devid for d in devices] |
| 65 | + fs_chunks = list(fs.chunks()) |
| 66 | + |
| 67 | + print(args.mountpoint, '\t', fs.usage().virtual_used_str, '\t', len(fs_chunks), 'fs chunks') |
| 68 | + for devid in devids: |
| 69 | + dev_info = fs.dev_info(devid) |
| 70 | + dev_vaddrs = [d.vaddr for d in fs.dev_extents(devid)] |
| 71 | + print( |
| 72 | + dev_info.path, |
| 73 | + '\t', |
| 74 | + dev_info.bytes_used_str, |
| 75 | + '\t', |
| 76 | + len(dev_vaddrs), |
| 77 | + 'device blockgroup extents', |
| 78 | + "({:.0%})".format(len(dev_vaddrs) / len(fs_chunks)), |
| 79 | + ) |
| 80 | + |
| 81 | + if args.usage: |
| 82 | + print('\nBlockgroup usage:') |
| 83 | + for devid in devids: |
| 84 | + print(fs.dev_info(devid).path) |
| 85 | + dev_vaddrs = [d.vaddr for d in fs.dev_extents(devid)] |
| 86 | + |
| 87 | + chunk_stats = {} |
| 88 | + with Pool() as pool: |
| 89 | + results = pool.map(safe_get_block_group, zip(repeat(fs), dev_vaddrs)) |
| 90 | + for bg in [r for r in results if r is not None]: |
| 91 | + if bg.flags_str in chunk_stats: |
| 92 | + chunk_stats[bg.flags_str]['count'] += 1 |
| 93 | + chunk_stats[bg.flags_str]['size_used'] += bg.used |
| 94 | + chunk_stats[bg.flags_str]['percent_used'].append(bg.used_pct) |
| 95 | + else: |
| 96 | + chunk_stats[bg.flags_str] = { |
| 97 | + 'count': 1, |
| 98 | + 'size_used': bg.used, |
| 99 | + 'percent_used': [bg.used_pct], |
| 100 | + } |
| 101 | + |
| 102 | + for data_flag in sorted(chunk_stats): |
| 103 | + stats = chunk_stats[data_flag] |
| 104 | + |
| 105 | + print('\t', data_flag) |
| 106 | + print('\t' * 2, 'Blockgroups at least partially on disk:', stats['count']) |
| 107 | + print('\t' * 2, 'Data-device dependance:', pretty_size(stats['size_used'])) |
| 108 | + print('\t' * 2, 'Approx. blockgroup percentage packed:') |
| 109 | + |
| 110 | + grouped_stats = {} |
| 111 | + for percent in stats['percent_used']: |
| 112 | + group = (percent // 10) * 10 |
| 113 | + if group in grouped_stats: |
| 114 | + grouped_stats[group] += 1 |
| 115 | + else: |
| 116 | + grouped_stats[group] = 1 |
| 117 | + |
| 118 | + min_count = min(count for _group, count in grouped_stats.items()) |
| 119 | + max_count = max(count for _group, count in grouped_stats.items()) |
| 120 | + for group, count in sorted(grouped_stats.items()): |
| 121 | + try: |
| 122 | + scaled_count = int(60 * (count - min_count) / (max_count - min_count)) |
| 123 | + except ZeroDivisionError: |
| 124 | + scaled_count = 1 |
| 125 | + print( |
| 126 | + '\t' * 2, |
| 127 | + f' {str(group).rjust(3)}% packed', |
| 128 | + '*' * max(scaled_count, 1), |
| 129 | + f"({count})", |
| 130 | + ) |
| 131 | + print('\n') |
| 132 | + |
| 133 | + |
| 134 | +def main(): |
| 135 | + args = parse_args() |
| 136 | + try: |
| 137 | + report_usage(args) |
| 138 | + except OSError as e: |
| 139 | + if e.errno == errno.EPERM: |
| 140 | + raise Bork( |
| 141 | + "Insufficient permissions to use the btrfs kernel API.\n" |
| 142 | + "Hint: Try running the script as root user.".format(e) |
| 143 | + ) |
| 144 | + elif e.errno == errno.ENOTTY: |
| 145 | + raise Bork("Unable to retrieve data. Hint: Not a mounted btrfs file system?") |
| 146 | + raise |
| 147 | + |
| 148 | + |
| 149 | +if __name__ == '__main__': |
| 150 | + try: |
| 151 | + main() |
| 152 | + except KeyboardInterrupt: |
| 153 | + print("Exiting...") |
| 154 | + sys.exit(130) # 128 + SIGINT |
| 155 | + except Bork as e: |
| 156 | + print("Error: {0}".format(e), file=sys.stderr) |
| 157 | + sys.exit(1) |
| 158 | + except Exception as e: |
| 159 | + print(e) |
| 160 | + sys.exit(1) |
0 commit comments