Debian Codegraph @

pkg/storaged/btrfs/btrfs-tool.py

raw
1 #! /usr/bin/python3
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 # btrfs-tool -- Query and monitor btrfs filesystems
5 #
6 # This program monitors all btrfs filesystems and reports their
7 # subvolumes and other things.
8 #
9 # It can do that continuously, or as a one shot operation. The tool
10 # mounts btrfs filesystems as necessary to retrieve the requested
11 # information, but does it in a polite way: they are mounted once and
12 # then left mounted until that is no longer needed. Typically, you
13 # might see some mounts when a Cockpit session starts, and the
14 # corresponding unmounts when it ends.
15 #
16 # This tool can be run multiple times concurrently with itself, and it
17 # won't get confused.
18
19 import ctypes
20 import json
21 import os
22 import re
23 import signal
24 import subprocess
25 import sys
26 import time
27
28
29 def debug(msg):
30 # subprocess.check_call(["logger", msg])
31 # sys.stderr.write(msg + "\n")
32 pass
33
34
35 TMP_MP_DIR = "/run/cockpit/btrfs"
36
37
38 def list_filesystems():
39 output = json.loads(subprocess.check_output(["lsblk", "--json", "--paths", "--list", "--noheadings",
40 "--output", "NAME,FSTYPE,UUID,MOUNTPOINTS"]))
41 filesystems = {}
42 for b in output['blockdevices']:
43 if b['fstype'] == "btrfs":
44 uuid = b['uuid']
45 mps = list(filter(lambda x: x is not None, b['mountpoints']))
46 real_mps = list(filter(lambda x: not x.startswith(TMP_MP_DIR), mps))
47 has_tmp_mp = len(real_mps) < len(mps)
48 if uuid not in filesystems:
49 filesystems[uuid] = {
50 'uuid': uuid,
51 'devices': [b['name']],
52 'mountpoints': real_mps,
53 'has_tmp_mountpoint': has_tmp_mp
54 }
55 else:
56 filesystems[uuid]['devices'] += [b['name']]
57 filesystems[uuid]['mountpoints'] += real_mps
58 filesystems[uuid]['has_tmp_mountpoint'] = filesystems[uuid]['has_tmp_mountpoint'] or has_tmp_mp
59 return filesystems
60
61
62 def get_tmp_mountpoint_path(uuid):
63 return os.path.join(TMP_MP_DIR, uuid)
64
65
66 mount_errors = {}
67
68
69 def add_tmp_mountpoint(fs):
70 global mount_errors
71 uuid = fs['uuid']
72 if uuid in mount_errors:
73 return None
74 path = get_tmp_mountpoint_path(uuid)
75 try:
76 debug(f"MOUNTING {path}")
77 os.makedirs(path, exist_ok=True)
78 subprocess.check_call(["mount", fs['devices'][0], path])
79 return path
80 except Exception as err:
81 sys.stderr.write(f"Failed to mount {path}: {err}\n")
82 mount_errors[uuid] = str(err)
83 return None
84
85
86 def remove_tmp_mountpoint(uuid):
87 path = get_tmp_mountpoint_path(uuid)
88 try:
89 debug(f"UNMOUNTING {path}")
90 subprocess.check_call(["umount", path])
91 except Exception as err:
92 sys.stderr.write(f"Failed to unmount {path}: {err}\n")
93
94
95 def get_mount_point(fs, opt_mount):
96 if len(fs['mountpoints']) > 0:
97 if fs['has_tmp_mountpoint']:
98 remove_tmp_mountpoint(fs['uuid'])
99 return fs['mountpoints'][0]
100 elif fs['has_tmp_mountpoint']:
101 return get_tmp_mountpoint_path(fs['uuid'])
102 elif opt_mount:
103 return add_tmp_mountpoint(fs)
104 else:
105 return None
106
107
108 def get_subvolume_info(mp):
109 lines = subprocess.check_output(["btrfs", "subvolume", "list", "-apuq", mp]).splitlines()
110 subvols = []
111 for line in lines:
112 match = re.match(rb"ID (\d+).*parent (\d+).*parent_uuid (.*)uuid (.*) path (<FS_TREE>/)?(.*)", line)
113 if match:
114 pathname = match[6].decode(errors='replace')
115 # Ignore podman btrfs subvolumes, they are an implementation detail.
116 if "containers/storage/btrfs/subvolumes" not in pathname:
117 subvols += [
118 {
119 'pathname': pathname,
120 'id': int(match[1]),
121 'parent': int(match[2]),
122 'uuid': match[4].decode(),
123 'parent_uuid': None if match[3][0] == ord("-") else match[3].decode().strip()
124 }
125 ]
126 return subvols
127
128
129 def get_default_subvolume(mp):
130 output = subprocess.check_output(["btrfs", "subvolume", "get-default", mp])
131 match = re.match(rb"ID (\d+).*", output)
132 if match:
133 return int(match[1])
134 else:
135 return None
136
137
138 def get_usages(uuid):
139 output = subprocess.check_output(["btrfs", "filesystem", "show", "--raw", uuid])
140 usages = {}
141 for line in output.splitlines():
142 match = re.match(rb".*used\s+(\d+)\s+path\s+([\w/]+).*", line)
143 if match:
144 usages[match[2].decode()] = int(match[1])
145 return usages
146
147
148 def poll(opt_mount):
149 global mount_errors
150 debug(f"POLL mount {opt_mount}")
151 filesystems = list_filesystems()
152 info = {}
153 for fs in filesystems.values():
154 mp = get_mount_point(fs, opt_mount)
155 try:
156 data = {'usages': get_usages(fs['uuid'])}
157 if mp:
158 data['subvolumes'] = get_subvolume_info(mp)
159 data['default_subvolume'] = get_default_subvolume(mp)
160 elif fs['uuid'] in mount_errors:
161 data['error'] = {'error': mount_errors[fs['uuid']]}
162 info[fs['uuid']] = data
163 except Exception as err:
164 info[fs['uuid']] = {'error': str(err)}
165
166 return info
167
168
169 def cmd_monitor(opt_mount):
170 old_infos = poll(opt_mount)
171 sys.stdout.write(json.dumps(old_infos) + "\n")
172 sys.stdout.flush()
173 while True:
174 time.sleep(5.0)
175 new_infos = poll(opt_mount)
176 if new_infos != old_infos:
177 sys.stdout.write(json.dumps(new_infos) + "\n")
178 sys.stdout.flush()
179 old_infos = new_infos
180
181
182 def cmd_poll(opt_mount):
183 infos = poll(opt_mount)
184 sys.stdout.write(json.dumps(infos) + "\n")
185 sys.stdout.flush()
186
187
188 def unshare_mounts():
189 # The os.unshare function is available since Python 3.12, but we
190 # still need to support older Pythons.
191 if "unshare" in os.__dict__:
192 os.unshare(os.CLONE_NEWNS)
193 else:
194 libc = ctypes.CDLL(None)
195 libc.unshare.argtypes = [ctypes.c_int]
196 get_errno_loc = libc.__errno_location
197 get_errno_loc.restype = ctypes.POINTER(ctypes.c_int)
198 ret = libc.unshare(2**17)
199 if ret != 0:
200 errno = get_errno_loc()[0]
201 raise OSError(errno, os.strerror(errno))
202 subprocess.check_call(["mount", "--make-rslave", "/"])
203
204
205 def cmd_do(uuid, cmd):
206 debug(f"DO {uuid} {cmd}")
207 filesystems = list_filesystems()
208 for fs in filesystems.values():
209 if fs['uuid'] == uuid:
210 path = TMP_MP_DIR
211 dev = fs['devices'][0]
212 os.makedirs(path, mode=0o700, exist_ok=True)
213 subprocess.check_call(["mount", dev, path])
214 subprocess.check_call(cmd, cwd=path)
215
216
217 def cmd(args):
218 unshare_mounts()
219 if len(args) > 1:
220 if args[1] == "poll":
221 cmd_poll(len(args) > 2)
222 elif args[1] == "monitor":
223 cmd_monitor(len(args) > 2)
224 elif args[1] == "do":
225 cmd_do(args[2], args[3:])
226
227
228 def main(args):
229 signal.signal(signal.SIGTERM, lambda _signo, _stack: sys.exit(0))
230 try:
231 cmd(args)
232 except Exception as err:
233 sys.stderr.write(str(err) + "\n")
234 sys.exit(1)
235
236
237 main(sys.argv)