Debian Codegraph @

bin/btrfs-balance-least-used

raw symbols SCIP
1 #!/usr/bin/python3
2 #
3 # Copyright (C) 2017 Hans van Kranenburg <[email protected]>
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining
6 # a copy of this software and associated documentation files (the
7 # "Software"), to deal in the Software without restriction, including
8 # without limitation the rights to use, copy, modify, merge, publish,
9 # distribute, sublicense, and/or sell copies of the Software, and to
10 # permit persons to whom the Software is furnished to do so, subject to
11 # the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included
14 # in all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
24 import argparse
25 import btrfs
26 import errno
27 import heapq
28 import sys
29 import time
30
31
32 class Bork(Exception):
33 pass
34
35
36 def load_block_groups(fs, max_used_pct):
37 min_used_pct = 101
38 block_groups = []
39 print("Loading block group objects with used_pct <= {} ...".format(max_used_pct),
40 end='', flush=True)
41 for chunk in fs.chunks():
42 if not (chunk.type & btrfs.BLOCK_GROUP_DATA):
43 continue
44 try:
45 block_group = fs.block_group(chunk.vaddr, chunk.length)
46 if block_group.used_pct <= max_used_pct:
47 block_groups.append((block_group.used_pct, block_group))
48 if block_group.used_pct < min_used_pct:
49 min_used_pct = block_group.used_pct
50 except IndexError:
51 continue
52 heapq.heapify(block_groups)
53 print(" found {}".format(len(block_groups)))
54 return min_used_pct, block_groups
55
56
57 def balance_one_block_group(fs, block_groups, max_used_pct):
58 next_used_pct, next_block_group = block_groups[0]
59 try:
60 block_group = fs.block_group(next_block_group.vaddr, next_block_group.length)
61 except IndexError:
62 heapq.heappop(block_groups)
63 return
64 vaddr = block_group.vaddr
65 used_pct = block_group.used_pct
66 if used_pct > next_used_pct:
67 if used_pct > max_used_pct:
68 print("Ignoring block group vaddr {} used_pct changed {} -> {}".format(
69 vaddr, next_used_pct, used_pct))
70 heapq.heappop(block_groups)
71 else:
72 print("Postponing block group vaddr {} used_pct changed {} -> {}".format(
73 vaddr, next_used_pct, used_pct))
74 heapq.heapreplace(block_groups, (used_pct, block_group))
75 return
76
77 start_time = time.time()
78 heapq.heappop(block_groups)
79 args = btrfs.ioctl.BalanceArgs(vstart=vaddr, vend=vaddr+1)
80 print("Balance block group vaddr {} used_pct {} ...".format(
81 vaddr, used_pct), end='', flush=True)
82 try:
83 progress = btrfs.ioctl.balance_v2(fs.fd, data_args=args)
84 end_time = time.time()
85 print(" duration {} sec total {}".format(int(end_time - start_time), progress.considered))
86 except KeyboardInterrupt:
87 end_time = time.time()
88 print(" duration {} sec".format(int(end_time - start_time)))
89 raise
90
91
92 def parse_args():
93 parser = argparse.ArgumentParser()
94 parser.add_argument(
95 '-u',
96 '--usage',
97 type=int,
98 default=100,
99 help="Only consider block groups with less than this percentage used",
100 )
101 parser.add_argument(
102 'mountpoint',
103 help="Btrfs filesystem mountpoint",
104 )
105 return parser.parse_args()
106
107
108 def permission_check(fs):
109 """This is a simple canary function that explodes if the user does not have
110 enough permissions to use the search ioctl.
111 """
112 fs.top_level()
113
114
115 def main():
116 args = parse_args()
117 max_used_pct = args.usage
118 path = args.mountpoint
119 try:
120 with btrfs.FileSystem(path) as fs:
121 permission_check(fs)
122 min_used_pct, block_groups = load_block_groups(fs, max_used_pct)
123 if len(block_groups) == 0:
124 print("Nothing to do, least used block group has used_pct {}".format(min_used_pct))
125 return
126 while len(block_groups) > 0:
127 balance_one_block_group(fs, block_groups, max_used_pct)
128 except OSError as e:
129 if e.errno == errno.EPERM:
130 raise Bork("Insufficient permissions to use the btrfs kernel API.\n"
131 "Hint: Try running the script as root user.".format(e))
132 elif e.errno == errno.ENOTTY:
133 raise Bork("Unable to retrieve data. Hint: Not a mounted btrfs file system?")
134 raise
135
136
137 if __name__ == '__main__':
138 try:
139 main()
140 except KeyboardInterrupt:
141 print("Exiting...")
142 sys.exit(130) # 128 + SIGINT
143 except Bork as e:
144 print("Error: {0}".format(e), file=sys.stderr)
145 sys.exit(1)
146 except Exception as e:
147 print(e)
148 sys.exit(1)