Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_btrfs.py

raw
1 # Copyright (c) 2022, Gregory Furlong <[email protected]>
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import os
11 import re
12 import typing as t
13
14 from ansible.module_utils.common.text.converters import to_bytes
15
16 if t.TYPE_CHECKING:
17 from ansible.module_utils.basic import AnsibleModule
18
19
20 def normalize_subvolume_path(path):
21 """
22 Normalizes btrfs subvolume paths to ensure exactly one leading slash, no trailing slashes and no consecutive slashes.
23 In addition, if the path is prefixed with a leading <FS_TREE>, this value is removed.
24 """
25 fstree_stripped = re.sub(r"^<FS_TREE>", "", path)
26 result = re.sub(r"/+$", "", re.sub(r"/+", "/", f"/{fstree_stripped}"))
27 return result if len(result) > 0 else "/"
28
29
30 class BtrfsModuleException(Exception):
31 pass
32
33
34 class BtrfsCommands:
35 """
36 Provides access to a subset of the Btrfs command line
37 """
38
39 def __init__(self, module: AnsibleModule) -> None:
40 self.__module = module
41 self.__module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
42 self.__btrfs: str = self.__module.get_bin_path("btrfs", required=True)
43
44 def filesystem_show(self) -> list[dict[str, t.Any]]:
45 command = [self.__btrfs, "filesystem", "show", "-d"]
46 result = self.__module.run_command(command, check_rc=True)
47 stdout = [x.strip() for x in result[1].splitlines()]
48 filesystems = []
49 current = None
50 for line in stdout:
51 if line.startswith("Label"):
52 current = self.__parse_filesystem(line)
53 filesystems.append(current)
54 elif line.startswith("devid"):
55 if current is None:
56 raise ValueError("Found 'devid' line without previous 'Label' line")
57 current["devices"].append(self.__parse_filesystem_device(line))
58 return filesystems
59
60 def __parse_filesystem(self, line) -> dict[str, t.Any]:
61 label = re.sub(r"\s*uuid:.*$", "", re.sub(r"^Label:\s*", "", line))
62 id = re.sub(r"^.*uuid:\s*", "", line)
63
64 filesystem: dict[str, t.Any] = {}
65 filesystem["label"] = label.strip("'") if label != "none" else None
66 filesystem["uuid"] = id
67 filesystem["devices"] = []
68 filesystem["mountpoints"] = []
69 filesystem["subvolumes"] = []
70 filesystem["default_subvolid"] = None
71 return filesystem
72
73 def __parse_filesystem_device(self, line: str) -> str:
74 return re.sub(r"^.*path\s", "", line)
75
76 def subvolumes_list(self, filesystem_path: str) -> list[dict[str, t.Any]]:
77 command = [self.__btrfs, "subvolume", "list", "-tap", to_bytes(filesystem_path)]
78 result = self.__module.run_command(command, check_rc=True)
79 stdout = [x.split("\t") for x in result[1].splitlines()]
80 subvolumes: list[dict[str, t.Any]] = [{"id": 5, "parent": None, "path": "/"}]
81 if len(stdout) > 2:
82 subvolumes.extend([self.__parse_subvolume_list_record(x) for x in stdout[2:]])
83 return subvolumes
84
85 def __parse_subvolume_list_record(self, item: list[str]) -> dict[str, t.Any]:
86 return {
87 "id": int(item[0]),
88 "parent": int(item[2]),
89 "path": normalize_subvolume_path(item[5]),
90 }
91
92 def subvolume_get_default(self, filesystem_path: str) -> int:
93 command = [self.__btrfs, "subvolume", "get-default", to_bytes(filesystem_path)]
94 result = self.__module.run_command(command, check_rc=True)
95 # ID [n] ...
96 return int(result[1].strip().split()[1])
97
98 def subvolume_set_default(self, filesystem_path: str, subvolume_id: int) -> None:
99 command = [self.__btrfs, "subvolume", "set-default", str(subvolume_id), to_bytes(filesystem_path)]
100 self.__module.run_command(command, check_rc=True)
101
102 def subvolume_create(self, subvolume_path: str) -> None:
103 command = [self.__btrfs, "subvolume", "create", to_bytes(subvolume_path)]
104 self.__module.run_command(command, check_rc=True)
105
106 def subvolume_snapshot(self, snapshot_source: str, snapshot_destination: str) -> None:
107 command = [self.__btrfs, "subvolume", "snapshot", to_bytes(snapshot_source), to_bytes(snapshot_destination)]
108 self.__module.run_command(command, check_rc=True)
109
110 def subvolume_delete(self, subvolume_path: str) -> None:
111 command = [self.__btrfs, "subvolume", "delete", to_bytes(subvolume_path)]
112 self.__module.run_command(command, check_rc=True)
113
114
115 class BtrfsInfoProvider:
116 """
117 Utility providing details of the currently available btrfs filesystems
118 """
119
120 def __init__(self, module: AnsibleModule) -> None:
121 self.__module = module
122 self.__btrfs_api = BtrfsCommands(module)
123 self.__findmnt_path: str = self.__module.get_bin_path("findmnt", required=True)
124
125 def get_filesystems(self) -> list[dict[str, t.Any]]:
126 filesystems = self.__btrfs_api.filesystem_show()
127 mountpoints = self.__find_mountpoints()
128 for filesystem in filesystems:
129 device_mountpoints = self.__filter_mountpoints_for_devices(mountpoints, filesystem["devices"])
130 filesystem["mountpoints"] = device_mountpoints
131
132 if len(device_mountpoints) > 0:
133 # any path within the filesystem can be used to query metadata
134 mountpoint = device_mountpoints[0]["mountpoint"]
135 filesystem["subvolumes"] = self.get_subvolumes(mountpoint)
136 filesystem["default_subvolid"] = self.get_default_subvolume_id(mountpoint)
137
138 return filesystems
139
140 def get_mountpoints(self, filesystem_devices: list[str]) -> list[dict[str, t.Any]]:
141 mountpoints = self.__find_mountpoints()
142 return self.__filter_mountpoints_for_devices(mountpoints, filesystem_devices)
143
144 def get_subvolumes(self, filesystem_path) -> list[dict[str, t.Any]]:
145 return self.__btrfs_api.subvolumes_list(filesystem_path)
146
147 def get_default_subvolume_id(self, filesystem_path) -> int:
148 return self.__btrfs_api.subvolume_get_default(filesystem_path)
149
150 def __filter_mountpoints_for_devices(
151 self, mountpoints: list[dict[str, t.Any]], devices: list[str]
152 ) -> list[dict[str, t.Any]]:
153 return [m for m in mountpoints if (m["device"] in devices)]
154
155 def __find_mountpoints(self) -> list[dict[str, t.Any]]:
156 command = [self.__findmnt_path, "-t", "btrfs", "-nvP"]
157 result = self.__module.run_command(command)
158 mountpoints = []
159 if result[0] == 0:
160 lines = result[1].splitlines()
161 for line in lines:
162 mountpoint = self.__parse_mountpoint_pairs(line)
163 mountpoints.append(mountpoint)
164 return mountpoints
165
166 def __parse_mountpoint_pairs(self, line) -> dict[str, t.Any]:
167 pattern = re.compile(
168 r'^TARGET="(?P<target>.*)"\s+SOURCE="(?P<source>.*)"\s+FSTYPE="(?P<fstype>.*)"\s+OPTIONS="(?P<options>.*)"\s*$'
169 )
170 match = pattern.search(line)
171 if match is not None:
172 groups = match.groupdict()
173
174 return {
175 "mountpoint": groups["target"],
176 "device": groups["source"],
177 "subvolid": self.__extract_mount_subvolid(groups["options"]),
178 }
179 else:
180 raise BtrfsModuleException(f"Failed to parse findmnt result for line: {line!r}")
181
182 def __extract_mount_subvolid(self, mount_options: str) -> int:
183 for option in mount_options.split(","):
184 if option.startswith("subvolid="):
185 return int(option[len("subvolid=") :])
186 raise BtrfsModuleException(f"Failed to find subvolid for mountpoint in options {mount_options!r}")
187
188
189 class BtrfsSubvolume:
190 """
191 Wrapper class providing convenience methods for inspection of a btrfs subvolume
192 """
193
194 def __init__(self, filesystem: BtrfsFilesystem, subvolume_id: int):
195 self.__filesystem = filesystem
196 self.__subvolume_id = subvolume_id
197
198 def get_filesystem(self) -> BtrfsFilesystem:
199 return self.__filesystem
200
201 def is_mounted(self) -> bool:
202 mountpoints = self.get_mountpoints()
203 return mountpoints is not None and len(mountpoints) > 0
204
205 def is_filesystem_root(self) -> bool:
206 return self.__subvolume_id == 5
207
208 def is_filesystem_default(self) -> bool:
209 return self.__filesystem.default_subvolid == self.__subvolume_id
210
211 def get_mounted_path(self) -> str | None:
212 mountpoints = self.get_mountpoints()
213 if mountpoints is not None and len(mountpoints) > 0:
214 return mountpoints[0]
215 if self.parent is not None:
216 parent = self.__filesystem.get_subvolume_by_id(self.parent)
217 parent_path = parent.get_mounted_path() if parent else None
218 if parent_path is not None:
219 return f"{parent_path}{os.path.sep}{self.name}"
220 return None
221
222 def get_mountpoints(self) -> list[str]:
223 return self.__filesystem.get_mountpoints_by_subvolume_id(self.__subvolume_id)
224
225 def get_child_relative_path(self, absolute_child_path: str) -> str:
226 """
227 Get the relative path from this subvolume to the named child subvolume.
228 The provided parameter is expected to be normalized as by normalize_subvolume_path.
229 """
230 path = self.path
231 if absolute_child_path.startswith(path):
232 relative = absolute_child_path[len(path) :]
233 return re.sub(r"^/*", "", relative)
234 else:
235 raise BtrfsModuleException(f"Path '{absolute_child_path}' doesn't start with '{path}'")
236
237 def get_parent_subvolume(self) -> BtrfsSubvolume | None:
238 parent_id = self.parent
239 return self.__filesystem.get_subvolume_by_id(parent_id) if parent_id is not None else None
240
241 def get_child_subvolumes(self) -> list[BtrfsSubvolume]:
242 return self.__filesystem.get_subvolume_children(self.__subvolume_id)
243
244 @property
245 def __info(self) -> dict[str, t.Any]:
246 result = self.__filesystem.get_subvolume_info_for_id(self.__subvolume_id)
247 # assert result is not None
248 return result # type: ignore
249
250 @property
251 def id(self) -> int:
252 return self.__subvolume_id
253
254 @property
255 def name(self):
256 return self.path.split("/").pop()
257
258 @property
259 def path(self) -> str:
260 return self.__info["path"]
261
262 @property
263 def parent(self):
264 return self.__info["parent"]
265
266
267 class BtrfsFilesystem:
268 """
269 Wrapper class providing convenience methods for inspection of a btrfs filesystem
270 """
271
272 def __init__(self, info: dict[str, t.Any], provider: BtrfsInfoProvider, module: AnsibleModule) -> None:
273 self.__provider = provider
274
275 # constant for module execution
276 self.__uuid: str = info["uuid"]
277 self.__label: str = info["label"]
278 self.__devices: list[str] = info["devices"]
279
280 # refreshable
281 self.__default_subvolid: int | None = info["default_subvolid"] if "default_subvolid" in info else None
282 self.__update_mountpoints(info["mountpoints"] if "mountpoints" in info else [])
283 self.__update_subvolumes(info["subvolumes"] if "subvolumes" in info else [])
284
285 @property
286 def uuid(self) -> str:
287 return self.__uuid
288
289 @property
290 def label(self) -> str:
291 return self.__label
292
293 @property
294 def default_subvolid(self) -> int | None:
295 return self.__default_subvolid
296
297 @property
298 def devices(self) -> list[str]:
299 return list(self.__devices)
300
301 def refresh(self) -> None:
302 self.refresh_mountpoints()
303 self.refresh_subvolumes()
304 self.refresh_default_subvolume()
305
306 def refresh_mountpoints(self) -> None:
307 mountpoints = self.__provider.get_mountpoints(list(self.__devices))
308 self.__update_mountpoints(mountpoints)
309
310 def __update_mountpoints(self, mountpoints: list[dict[str, t.Any]]) -> None:
311 self.__mountpoints: dict[int, list[str]] = dict()
312 for i in mountpoints:
313 subvolid: int = i["subvolid"]
314 mountpoint: str = i["mountpoint"]
315 if subvolid not in self.__mountpoints:
316 self.__mountpoints[subvolid] = []
317 self.__mountpoints[subvolid].append(mountpoint)
318
319 def refresh_subvolumes(self) -> None:
320 filesystem_path = self.get_any_mountpoint()
321 if filesystem_path is not None:
322 subvolumes = self.__provider.get_subvolumes(filesystem_path)
323 self.__update_subvolumes(subvolumes)
324
325 def __update_subvolumes(self, subvolumes: list[dict[str, t.Any]]) -> None:
326 # TODO strategy for retaining information on deleted subvolumes?
327 self.__subvolumes: dict[int, dict[str, t.Any]] = dict()
328 for subvolume in subvolumes:
329 self.__subvolumes[subvolume["id"]] = subvolume
330
331 def refresh_default_subvolume(self) -> None:
332 filesystem_path = self.get_any_mountpoint()
333 if filesystem_path is not None:
334 self.__default_subvolid = self.__provider.get_default_subvolume_id(filesystem_path)
335
336 def contains_device(self, device: str) -> bool:
337 return device in self.__devices
338
339 def contains_subvolume(self, subvolume: str) -> bool:
340 return self.get_subvolume_by_name(subvolume) is not None
341
342 def get_subvolume_by_id(self, subvolume_id: int) -> BtrfsSubvolume | None:
343 return BtrfsSubvolume(self, subvolume_id) if subvolume_id in self.__subvolumes else None
344
345 def get_subvolume_info_for_id(self, subvolume_id: int) -> dict[str, t.Any] | None:
346 return self.__subvolumes[subvolume_id] if subvolume_id in self.__subvolumes else None
347
348 def get_subvolume_by_name(self, subvolume: str) -> BtrfsSubvolume | None:
349 for subvolume_info in self.__subvolumes.values():
350 if subvolume_info["path"] == subvolume:
351 return BtrfsSubvolume(self, subvolume_info["id"])
352 return None
353
354 def get_any_mountpoint(self) -> str | None:
355 for subvol_mountpoints in self.__mountpoints.values():
356 if len(subvol_mountpoints) > 0:
357 return subvol_mountpoints[0]
358 # maybe error?
359 return None
360
361 def get_any_mounted_subvolume(self) -> BtrfsSubvolume | None:
362 for subvolid, subvol_mountpoints in self.__mountpoints.items():
363 if len(subvol_mountpoints) > 0:
364 return self.get_subvolume_by_id(subvolid)
365 return None
366
367 def get_mountpoints_by_subvolume_id(self, subvolume_id: int) -> list[str]:
368 return self.__mountpoints[subvolume_id] if subvolume_id in self.__mountpoints else []
369
370 def get_nearest_subvolume(self, subvolume: str) -> BtrfsSubvolume:
371 """Return the identified subvolume if existing, else the closest matching parent"""
372 subvolumes_by_path = self.__get_subvolumes_by_path()
373 while len(subvolume) > 1:
374 if subvolume in subvolumes_by_path:
375 return BtrfsSubvolume(self, subvolumes_by_path[subvolume]["id"])
376 else:
377 subvolume = re.sub(r"/[^/]+$", "", subvolume)
378
379 return BtrfsSubvolume(self, 5)
380
381 def get_mountpath_as_child(self, subvolume_name: str) -> str:
382 """Find a path to the target subvolume through a mounted ancestor"""
383 nearest = self.get_nearest_subvolume(subvolume_name)
384 nearest_or_none: BtrfsSubvolume | None = nearest
385 if nearest.path == subvolume_name:
386 nearest_or_none = nearest.get_parent_subvolume()
387 if nearest_or_none is None or nearest_or_none.get_mounted_path() is None:
388 raise BtrfsModuleException(f"Failed to find a path '{subvolume_name}' through a mounted parent subvolume")
389 else:
390 return f"{nearest_or_none.get_mounted_path()}{os.path.sep}{nearest_or_none.get_child_relative_path(subvolume_name)}"
391
392 def get_subvolume_children(self, subvolume_id: int) -> list[BtrfsSubvolume]:
393 return [BtrfsSubvolume(self, x["id"]) for x in self.__subvolumes.values() if x["parent"] == subvolume_id]
394
395 def __get_subvolumes_by_path(self) -> dict[str, dict[str, t.Any]]:
396 result = {}
397 for s in self.__subvolumes.values():
398 path = s["path"]
399 result[path] = s
400 return result
401
402 def is_mounted(self) -> bool:
403 return self.__mountpoints is not None and len(self.__mountpoints) > 0
404
405 def get_summary(self) -> dict[str, t.Any]:
406 subvolumes = []
407 sources = self.__subvolumes.values() if self.__subvolumes is not None else []
408 for subvolume in sources:
409 id = subvolume["id"]
410 subvolumes.append(
411 {
412 "id": id,
413 "path": subvolume["path"],
414 "parent": subvolume["parent"],
415 "mountpoints": self.get_mountpoints_by_subvolume_id(id),
416 }
417 )
418
419 return {
420 "default_subvolume": self.__default_subvolid,
421 "devices": self.__devices,
422 "label": self.__label,
423 "uuid": self.__uuid,
424 "subvolumes": subvolumes,
425 }
426
427
428 class BtrfsFilesystemsProvider:
429 """
430 Provides methods to query available btrfs filesystems
431 """
432
433 def __init__(self, module: AnsibleModule) -> None:
434 self.__module = module
435 self.__provider = BtrfsInfoProvider(module)
436 self.__filesystems: dict[str, BtrfsFilesystem] | None = None
437
438 def get_matching_filesystem(self, criteria: dict[str, t.Any]) -> BtrfsFilesystem:
439 if criteria["device"] is not None:
440 criteria["device"] = os.path.realpath(criteria["device"])
441
442 self.__check_init()
443 # assert self.__filesystems is not None # TODO
444 self_filesystems: dict[str, BtrfsFilesystem] = self.__filesystems # type: ignore
445 matching = [f for f in self_filesystems.values() if self.__filesystem_matches_criteria(f, criteria)]
446 if len(matching) == 1:
447 return matching[0]
448 else:
449 raise BtrfsModuleException(
450 f"Found {len(matching)} filesystems matching criteria uuid={criteria['uuid']} label={criteria['label']} device={criteria['device']}"
451 )
452
453 def __filesystem_matches_criteria(self, filesystem: BtrfsFilesystem, criteria: dict[str, t.Any]):
454 return (
455 (criteria["uuid"] is None or filesystem.uuid == criteria["uuid"])
456 and (criteria["label"] is None or filesystem.label == criteria["label"])
457 and (criteria["device"] is None or filesystem.contains_device(criteria["device"]))
458 )
459
460 def get_filesystem_for_device(self, device: str) -> BtrfsFilesystem | None:
461 real_device = os.path.realpath(device)
462 self.__check_init()
463 # assert self.__filesystems is not None # TODO
464 self_filesystems: dict[str, BtrfsFilesystem] = self.__filesystems # type: ignore
465 for fs in self_filesystems.values():
466 if fs.contains_device(real_device):
467 return fs
468 return None
469
470 def get_filesystems(self) -> list[BtrfsFilesystem]:
471 self.__check_init()
472 # assert self.__filesystems is not None # TODO
473 self_filesystems: dict[str, BtrfsFilesystem] = self.__filesystems # type: ignore
474 return list(self_filesystems.values())
475
476 def __check_init(self) -> None:
477 if self.__filesystems is None:
478 self.__filesystems = dict()
479 for f in self.__provider.get_filesystems():
480 uuid = f["uuid"]
481 self.__filesystems[uuid] = BtrfsFilesystem(f, self.__provider, self.__module)