Debian Codegraph @

ansible_collections/community/general/plugins/modules/btrfs_subvolume.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2022, Gregory Furlong <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: btrfs_subvolume
11 short_description: Manage btrfs subvolumes
12 version_added: "6.6.0"
13
14 description: Creates, updates and deletes btrfs subvolumes and snapshots.
15
16 options:
17 automount:
18 description:
19 - Allow the module to temporarily mount the targeted btrfs filesystem in order to validate the current state and make
20 any required changes.
21 type: bool
22 default: false
23 default:
24 description:
25 - Make the subvolume specified by O(name) the filesystem's default subvolume.
26 type: bool
27 default: false
28 filesystem_device:
29 description:
30 - A block device contained within the btrfs filesystem to be targeted.
31 - Useful when multiple btrfs filesystems are present to specify which filesystem should be targeted.
32 type: path
33 filesystem_label:
34 description:
35 - A descriptive label assigned to the btrfs filesystem to be targeted.
36 - Useful when multiple btrfs filesystems are present to specify which filesystem should be targeted.
37 type: str
38 filesystem_uuid:
39 description:
40 - A unique identifier assigned to the btrfs filesystem to be targeted.
41 - Useful when multiple btrfs filesystems are present to specify which filesystem should be targeted.
42 type: str
43 name:
44 description:
45 - Name of the subvolume/snapshot to be targeted.
46 required: true
47 type: str
48 recursive:
49 description:
50 - When true, indicates that parent/child subvolumes should be created/removedas necessary to complete the operation
51 (for O(state=present) and O(state=absent) respectively).
52 type: bool
53 default: false
54 snapshot_source:
55 description:
56 - Identifies the source subvolume for the created snapshot.
57 - Infers that the created subvolume is a snapshot.
58 type: str
59 snapshot_conflict:
60 description:
61 - Policy defining behavior when a subvolume already exists at the path of the requested snapshot.
62 - V(skip) - Create a snapshot only if a subvolume does not yet exist at the target location, otherwise indicate that
63 no change is required. Warning, this option does not yet verify that the target subvolume was generated from a snapshot
64 of the requested source.
65 - V(clobber) - If a subvolume already exists at the requested location, delete it first. This option is not idempotent
66 and results in a new snapshot being generated on every execution.
67 - V(error) - If a subvolume already exists at the requested location, return an error. This option is not idempotent
68 and results in an error on replay of the module.
69 type: str
70 choices: [skip, clobber, error]
71 default: skip
72 state:
73 description:
74 - Indicates the current state of the targeted subvolume.
75 type: str
76 choices: [absent, present]
77 default: present
78
79 notes:
80 - If any or all of the options O(filesystem_device), O(filesystem_label) or O(filesystem_uuid) parameters are provided,
81 there is expected to be a matching btrfs filesystem. If none are provided and only a single btrfs filesystem exists or
82 only a single btrfs filesystem is mounted, that filesystem is used; otherwise, the module takes no action and returns an
83 error.
84 extends_documentation_fragment:
85 - community.general._attributes
86
87 attributes:
88 check_mode:
89 support: partial
90 details:
91 - In some scenarios it may erroneously report intermediate subvolumes being created. After mounting, if a directory
92 like file is found where the subvolume would have been created, the operation is skipped.
93 diff_mode:
94 support: none
95
96 author:
97 - Gregory Furlong (@gnfzdz)
98 """
99
100 EXAMPLES = r"""
101 - name: Create a @home subvolume under the root subvolume
102 community.general.btrfs_subvolume:
103 name: /@home
104 filesystem_device: /dev/vda2
105
106 - name: Remove the @home subvolume if it exists
107 community.general.btrfs_subvolume:
108 name: /@home
109 state: absent
110 filesystem_device: /dev/vda2
111
112 - name: Create a snapshot of the root subvolume named @
113 community.general.btrfs_subvolume:
114 name: /@
115 snapshot_source: /
116 filesystem_device: /dev/vda2
117
118 - name: Create a snapshot of the root subvolume and make it the new default subvolume
119 community.general.btrfs_subvolume:
120 name: /@
121 snapshot_source: /
122 default: true
123 filesystem_device: /dev/vda2
124
125 - name: Create a snapshot of the /@ subvolume and recursively creating intermediate subvolumes as required
126 community.general.btrfs_subvolume:
127 name: /@snapshots/@2022_06_09
128 snapshot_source: /@
129 recursive: true
130 filesystem_device: /dev/vda2
131
132 - name: Remove the /@ subvolume and recursively delete child subvolumes as required
133 community.general.btrfs_subvolume:
134 name: /@snapshots/@2022_06_09
135 snapshot_source: /@
136 recursive: true
137 filesystem_device: /dev/vda2
138 """
139
140 RETURN = r"""
141 filesystem:
142 description:
143 - A summary of the final state of the targeted btrfs filesystem.
144 type: dict
145 returned: success
146 contains:
147 uuid:
148 description: A unique identifier assigned to the filesystem.
149 returned: success
150 type: str
151 sample: 96c9c605-1454-49b8-a63a-15e2584c208e
152 label:
153 description: An optional label assigned to the filesystem.
154 returned: success
155 type: str
156 sample: Tank
157 devices:
158 description: A list of devices assigned to the filesystem.
159 returned: success
160 type: list
161 sample:
162 - /dev/sda1
163 - /dev/sdb1
164 default_subvolume:
165 description: The ID of the filesystem's default subvolume.
166 returned: success and if filesystem is mounted
167 type: int
168 sample: 5
169 subvolumes:
170 description: A list of dicts containing metadata for all of the filesystem's subvolumes.
171 returned: success and if filesystem is mounted
172 type: list
173 elements: dict
174 contains:
175 id:
176 description: An identifier assigned to the subvolume, unique within the containing filesystem.
177 type: int
178 sample: 256
179 mountpoints:
180 description: Paths where the subvolume is mounted on the targeted host.
181 type: list
182 sample: ["/home"]
183 parent:
184 description: The identifier of this subvolume's parent.
185 type: int
186 sample: 5
187 path:
188 description: The full path of the subvolume relative to the btrfs fileystem's root.
189 type: str
190 sample: /@home
191
192 modifications:
193 description:
194 - A list where each element describes a change made to the target btrfs filesystem.
195 type: list
196 returned: Success
197 elements: str
198
199 target_subvolume_id:
200 description:
201 - The ID of the subvolume specified with the O(name) parameter, either pre-existing or created as part of module execution.
202 type: int
203 sample: 257
204 returned: Success and subvolume exists after module execution
205 """
206
207 import os
208 import tempfile
209
210 from ansible.module_utils.basic import AnsibleModule
211
212 from ansible_collections.community.general.plugins.module_utils._btrfs import (
213 BtrfsCommands,
214 BtrfsFilesystemsProvider,
215 BtrfsModuleException,
216 normalize_subvolume_path,
217 )
218
219
220 class BtrfsSubvolumeModule:
221 __BTRFS_ROOT_SUBVOLUME = "/"
222 __BTRFS_ROOT_SUBVOLUME_ID = 5
223 __BTRFS_SUBVOLUME_INODE_NUMBER = 256
224
225 __CREATE_SUBVOLUME_OPERATION = "create"
226 __CREATE_SNAPSHOT_OPERATION = "snapshot"
227 __DELETE_SUBVOLUME_OPERATION = "delete"
228 __SET_DEFAULT_SUBVOLUME_OPERATION = "set-default"
229
230 __UNKNOWN_SUBVOLUME_ID = "?"
231
232 def __init__(self, module):
233 self.module = module
234 self.__btrfs_api = BtrfsCommands(module)
235 self.__provider = BtrfsFilesystemsProvider(module)
236
237 # module parameters
238 name = self.module.params["name"]
239 self.__name = normalize_subvolume_path(name) if name is not None else None
240 self.__state = self.module.params["state"]
241
242 self.__automount = self.module.params["automount"]
243 self.__default = self.module.params["default"]
244 self.__filesystem_device = self.module.params["filesystem_device"]
245 self.__filesystem_label = self.module.params["filesystem_label"]
246 self.__filesystem_uuid = self.module.params["filesystem_uuid"]
247 self.__recursive = self.module.params["recursive"]
248 self.__snapshot_conflict = self.module.params["snapshot_conflict"]
249 snapshot_source = self.module.params["snapshot_source"]
250 self.__snapshot_source = normalize_subvolume_path(snapshot_source) if snapshot_source is not None else None
251
252 # execution state
253 self.__filesystem = None
254 self.__required_mounts = []
255 self.__unit_of_work = []
256 self.__completed_work = []
257 self.__temporary_mounts = dict()
258
259 def run(self):
260 error = None
261 try:
262 self.__load_filesystem()
263 self.__prepare_unit_of_work()
264
265 if not self.module.check_mode:
266 # check required mounts & mount
267 if len(self.__unit_of_work) > 0:
268 self.__execute_unit_of_work()
269 self.__filesystem.refresh()
270 else:
271 # check required mounts
272 self.__completed_work.extend(self.__unit_of_work)
273 except Exception as e:
274 error = e
275 finally:
276 self.__cleanup_mounts()
277 if self.__filesystem is not None:
278 self.__filesystem.refresh_mountpoints()
279
280 return (error, self.get_results())
281
282 # Identify the targeted filesystem and obtain the current state
283 def __load_filesystem(self):
284 if self.__has_filesystem_criteria():
285 filesystem = self.__find_matching_filesytem()
286 else:
287 filesystem = self.__find_default_filesystem()
288
289 # The filesystem must be mounted to obtain the current state (subvolumes, default, etc)
290 if not filesystem.is_mounted():
291 if not self.__automount:
292 raise BtrfsModuleException(
293 f"Target filesystem uuid={filesystem.uuid} is not currently mounted and automount=False."
294 "Mount explicitly before module execution or pass automount=True"
295 )
296 elif self.module.check_mode:
297 # TODO is failing the module an appropriate outcome in this scenario?
298 raise BtrfsModuleException(
299 f"Target filesystem uuid={filesystem.uuid} is not currently mounted. Unable to validate the current"
300 "state while running with check_mode=True"
301 )
302 else:
303 self.__mount_subvolume_id_to_tempdir(filesystem, self.__BTRFS_ROOT_SUBVOLUME_ID)
304 filesystem.refresh()
305 self.__filesystem = filesystem
306
307 def __has_filesystem_criteria(self):
308 return (
309 self.__filesystem_uuid is not None
310 or self.__filesystem_label is not None
311 or self.__filesystem_device is not None
312 )
313
314 def __find_matching_filesytem(self):
315 criteria = {
316 "uuid": self.__filesystem_uuid,
317 "label": self.__filesystem_label,
318 "device": self.__filesystem_device,
319 }
320 return self.__provider.get_matching_filesystem(criteria)
321
322 def __find_default_filesystem(self):
323 filesystems = self.__provider.get_filesystems()
324 filesystem = None
325
326 if len(filesystems) == 1:
327 filesystem = filesystems[0]
328 else:
329 mounted_filesystems = [x for x in filesystems if x.is_mounted()]
330 if len(mounted_filesystems) == 1:
331 filesystem = mounted_filesystems[0]
332
333 if filesystem is not None:
334 return filesystem
335 else:
336 raise BtrfsModuleException(
337 f"Failed to automatically identify targeted filesystem. No explicit device indicated and found {len(filesystems)} available filesystems."
338 )
339
340 # Prepare unit of work
341 def __prepare_unit_of_work(self):
342 if self.__state == "present":
343 if self.__snapshot_source is None:
344 self.__prepare_subvolume_present()
345 else:
346 self.__prepare_snapshot_present()
347
348 if self.__default:
349 self.__prepare_set_default()
350 elif self.__state == "absent":
351 self.__prepare_subvolume_absent()
352
353 def __prepare_subvolume_present(self):
354 subvolume = self.__filesystem.get_subvolume_by_name(self.__name)
355 if subvolume is None:
356 self.__prepare_before_create_subvolume(self.__name)
357 self.__stage_create_subvolume(self.__name)
358
359 def __prepare_before_create_subvolume(self, subvolume_name):
360 closest_parent = self.__filesystem.get_nearest_subvolume(subvolume_name)
361 self.__stage_required_mount(closest_parent)
362 if self.__recursive:
363 self.__prepare_create_intermediates(closest_parent, subvolume_name)
364
365 def __prepare_create_intermediates(self, closest_subvolume, subvolume_name):
366 relative_path = closest_subvolume.get_child_relative_path(self.__name)
367 missing_subvolumes = [x for x in relative_path.split(os.path.sep) if len(x) > 0]
368 if len(missing_subvolumes) > 1:
369 current = closest_subvolume.path
370 for s in missing_subvolumes[:-1]:
371 separator = os.path.sep if current[-1] != os.path.sep else ""
372 current = current + separator + s
373 self.__stage_create_subvolume(current, True)
374
375 def __prepare_snapshot_present(self):
376 source_subvolume = self.__filesystem.get_subvolume_by_name(self.__snapshot_source)
377 subvolume = self.__filesystem.get_subvolume_by_name(self.__name)
378 subvolume_exists = subvolume is not None
379
380 if subvolume_exists:
381 if self.__snapshot_conflict == "skip":
382 # No change required
383 return
384 elif self.__snapshot_conflict == "error":
385 raise BtrfsModuleException(
386 f"Target subvolume={self.__name} already exists and snapshot_conflict='error'"
387 )
388
389 if source_subvolume is None:
390 raise BtrfsModuleException(f"Source subvolume {self.__snapshot_source} does not exist")
391 elif subvolume is not None and source_subvolume.id == subvolume.id:
392 raise BtrfsModuleException("Snapshot source and target are the same.")
393 else:
394 self.__stage_required_mount(source_subvolume)
395
396 if subvolume_exists and self.__snapshot_conflict == "clobber":
397 self.__prepare_delete_subvolume_tree(subvolume)
398 elif not subvolume_exists:
399 self.__prepare_before_create_subvolume(self.__name)
400
401 self.__stage_create_snapshot(source_subvolume, self.__name)
402
403 def __prepare_subvolume_absent(self):
404 subvolume = self.__filesystem.get_subvolume_by_name(self.__name)
405 if subvolume is not None:
406 self.__prepare_delete_subvolume_tree(subvolume)
407
408 def __prepare_delete_subvolume_tree(self, subvolume):
409 if subvolume.is_filesystem_root():
410 raise BtrfsModuleException("Can not delete the filesystem's root subvolume")
411 if not self.__recursive and len(subvolume.get_child_subvolumes()) > 0:
412 raise BtrfsModuleException(
413 f"Subvolume targeted for deletion {subvolume.path} has children and recursive=False."
414 "Either explicitly delete the child subvolumes first or pass "
415 "parameter recursive=True."
416 )
417
418 self.__stage_required_mount(subvolume.get_parent_subvolume())
419 queue = self.__prepare_recursive_delete_order(subvolume) if self.__recursive else [subvolume]
420 # prepare unit of work
421 for s in queue:
422 if s.is_mounted():
423 # TODO potentially unmount the subvolume if automount=True ?
424 raise BtrfsModuleException(f"Can not delete mounted subvolume={s.path}")
425 if s.is_filesystem_default():
426 self.__stage_set_default_subvolume(self.__BTRFS_ROOT_SUBVOLUME, self.__BTRFS_ROOT_SUBVOLUME_ID)
427 self.__stage_delete_subvolume(s)
428
429 def __prepare_recursive_delete_order(self, subvolume):
430 """Return the subvolume and all descendents as a list, ordered so that descendents always occur before their ancestors"""
431 pending = [subvolume]
432 ordered = []
433 while len(pending) > 0:
434 next = pending.pop()
435 ordered.append(next)
436 pending.extend(next.get_child_subvolumes())
437 ordered.reverse() # reverse to ensure children are deleted before their parent
438 return ordered
439
440 def __prepare_set_default(self):
441 subvolume = self.__filesystem.get_subvolume_by_name(self.__name)
442 subvolume_id = subvolume.id if subvolume is not None else None
443
444 if self.__filesystem.default_subvolid != subvolume_id:
445 self.__stage_set_default_subvolume(self.__name, subvolume_id)
446
447 # Stage operations to the unit of work
448 def __stage_required_mount(self, subvolume):
449 if subvolume.get_mounted_path() is None:
450 if self.__automount:
451 self.__required_mounts.append(subvolume)
452 else:
453 raise BtrfsModuleException(
454 f"The requested changes will require the subvolume '{subvolume.path}' to be mounted, but automount=False"
455 )
456
457 def __stage_create_subvolume(self, subvolume_path, intermediate=False):
458 """
459 Add required creation of an intermediate subvolume to the unit of work
460 If intermediate is true, the action will be skipped if a directory like file is found at target
461 after mounting a parent subvolume
462 """
463 self.__unit_of_work.append(
464 {
465 "action": self.__CREATE_SUBVOLUME_OPERATION,
466 "target": subvolume_path,
467 "intermediate": intermediate,
468 }
469 )
470
471 def __stage_create_snapshot(self, source_subvolume, target_subvolume_path):
472 """Add creation of a snapshot from source to target to the unit of work"""
473 self.__unit_of_work.append(
474 {
475 "action": self.__CREATE_SNAPSHOT_OPERATION,
476 "source": source_subvolume.path,
477 "source_id": source_subvolume.id,
478 "target": target_subvolume_path,
479 }
480 )
481
482 def __stage_delete_subvolume(self, subvolume):
483 """Add deletion of the target subvolume to the unit of work"""
484 self.__unit_of_work.append(
485 {
486 "action": self.__DELETE_SUBVOLUME_OPERATION,
487 "target": subvolume.path,
488 "target_id": subvolume.id,
489 }
490 )
491
492 def __stage_set_default_subvolume(self, subvolume_path, subvolume_id=None):
493 """Add update of the filesystem's default subvolume to the unit of work"""
494 self.__unit_of_work.append(
495 {
496 "action": self.__SET_DEFAULT_SUBVOLUME_OPERATION,
497 "target": subvolume_path,
498 "target_id": subvolume_id,
499 }
500 )
501
502 # Execute the unit of work
503 def __execute_unit_of_work(self):
504 self.__check_required_mounts()
505 for op in self.__unit_of_work:
506 if op["action"] == self.__CREATE_SUBVOLUME_OPERATION:
507 self.__execute_create_subvolume(op)
508 elif op["action"] == self.__CREATE_SNAPSHOT_OPERATION:
509 self.__execute_create_snapshot(op)
510 elif op["action"] == self.__DELETE_SUBVOLUME_OPERATION:
511 self.__execute_delete_subvolume(op)
512 elif op["action"] == self.__SET_DEFAULT_SUBVOLUME_OPERATION:
513 self.__execute_set_default_subvolume(op)
514 else:
515 raise ValueError(f"Unknown operation type '{op['action']}'")
516
517 def __execute_create_subvolume(self, operation):
518 target_mounted_path = self.__filesystem.get_mountpath_as_child(operation["target"])
519 if not self.__is_existing_directory_like(target_mounted_path):
520 self.__btrfs_api.subvolume_create(target_mounted_path)
521 self.__completed_work.append(operation)
522
523 def __execute_create_snapshot(self, operation):
524 source_subvolume = self.__filesystem.get_subvolume_by_name(operation["source"])
525 source_mounted_path = source_subvolume.get_mounted_path()
526 target_mounted_path = self.__filesystem.get_mountpath_as_child(operation["target"])
527
528 self.__btrfs_api.subvolume_snapshot(source_mounted_path, target_mounted_path)
529 self.__completed_work.append(operation)
530
531 def __execute_delete_subvolume(self, operation):
532 target_mounted_path = self.__filesystem.get_mountpath_as_child(operation["target"])
533 self.__btrfs_api.subvolume_delete(target_mounted_path)
534 self.__completed_work.append(operation)
535
536 def __execute_set_default_subvolume(self, operation):
537 target = operation["target"]
538 target_id = operation["target_id"]
539
540 if target_id is None:
541 target_subvolume = self.__filesystem.get_subvolume_by_name(target)
542
543 if target_subvolume is None:
544 self.__filesystem.refresh() # the target may have been created earlier in module execution
545 target_subvolume = self.__filesystem.get_subvolume_by_name(target)
546
547 if target_subvolume is None:
548 raise BtrfsModuleException(f"Failed to find existing subvolume '{target}'")
549 else:
550 target_id = target_subvolume.id
551
552 self.__btrfs_api.subvolume_set_default(self.__filesystem.get_any_mountpoint(), target_id)
553 self.__completed_work.append(operation)
554
555 def __is_existing_directory_like(self, path):
556 return os.path.exists(path) and (
557 os.path.isdir(path) or os.stat(path).st_ino == self.__BTRFS_SUBVOLUME_INODE_NUMBER
558 )
559
560 def __check_required_mounts(self):
561 filtered = self.__filter_child_subvolumes(self.__required_mounts)
562 if len(filtered) > 0:
563 for subvolume in filtered:
564 self.__mount_subvolume_id_to_tempdir(self.__filesystem, subvolume.id)
565 self.__filesystem.refresh_mountpoints()
566
567 def __filter_child_subvolumes(self, subvolumes):
568 """Filter the provided list of subvolumes to remove any that are a child of another item in the list"""
569 filtered = []
570 last = None
571 ordered = sorted(subvolumes, key=lambda x: x.path)
572 for next in ordered:
573 if last is None or next.path[0 : len(last)] != last:
574 filtered.append(next)
575 last = next.path
576 return filtered
577
578 # Create/cleanup temporary mountpoints
579 def __mount_subvolume_id_to_tempdir(self, filesystem, subvolid):
580 # this check should be redundant
581 if self.module.check_mode or not self.__automount:
582 raise BtrfsModuleException(
583 "Unable to temporarily mount required subvolumes"
584 f" with automount={self.__automount} and check_mode={self.module.check_mode}"
585 )
586
587 cache_key = f"{filesystem.uuid}:{int(subvolid)}"
588 # The subvolume was already mounted, so return the current path
589 if cache_key in self.__temporary_mounts:
590 return self.__temporary_mounts[cache_key]
591
592 device = filesystem.devices[0]
593 mountpoint = tempfile.mkdtemp(dir="/tmp")
594 self.__temporary_mounts[cache_key] = mountpoint
595
596 mount = self.module.get_bin_path("mount", required=True)
597 command = [mount, "-o", f"noatime,subvolid={int(subvolid)}", device, mountpoint]
598 self.module.run_command(command, check_rc=True)
599
600 return mountpoint
601
602 def __cleanup_mounts(self):
603 for key in self.__temporary_mounts.keys():
604 self.__cleanup_mount(self.__temporary_mounts[key])
605
606 def __cleanup_mount(self, mountpoint):
607 umount = self.module.get_bin_path("umount", required=True)
608 result = self.module.run_command([umount, mountpoint])
609 if result[0] == 0:
610 rmdir = self.module.get_bin_path("rmdir", required=True)
611 self.module.run_command([rmdir, mountpoint])
612
613 # Format and return results
614 def get_results(self):
615 target = self.__filesystem.get_subvolume_by_name(self.__name)
616 return dict(
617 changed=len(self.__completed_work) > 0,
618 filesystem=self.__filesystem.get_summary(),
619 modifications=self.__get_formatted_modifications(),
620 target_subvolume_id=(target.id if target is not None else None),
621 )
622
623 def __get_formatted_modifications(self):
624 return [self.__format_operation_result(op) for op in self.__completed_work]
625
626 def __format_operation_result(self, operation):
627 action_type = operation["action"]
628 if action_type == self.__CREATE_SUBVOLUME_OPERATION:
629 return self.__format_create_subvolume_result(operation)
630 elif action_type == self.__CREATE_SNAPSHOT_OPERATION:
631 return self.__format_create_snapshot_result(operation)
632 elif action_type == self.__DELETE_SUBVOLUME_OPERATION:
633 return self.__format_delete_subvolume_result(operation)
634 elif action_type == self.__SET_DEFAULT_SUBVOLUME_OPERATION:
635 return self.__format_set_default_subvolume_result(operation)
636 else:
637 raise ValueError(f"Unknown operation type '{operation['action']}'")
638
639 def __format_create_subvolume_result(self, operation):
640 target = operation["target"]
641 target_subvolume = self.__filesystem.get_subvolume_by_name(target)
642 target_id = target_subvolume.id if target_subvolume is not None else self.__UNKNOWN_SUBVOLUME_ID
643 return f"Created subvolume '{target}' ({target_id})"
644
645 def __format_create_snapshot_result(self, operation):
646 source = operation["source"]
647 source_id = operation["source_id"]
648
649 target = operation["target"]
650 target_subvolume = self.__filesystem.get_subvolume_by_name(target)
651 target_id = target_subvolume.id if target_subvolume is not None else self.__UNKNOWN_SUBVOLUME_ID
652 return f"Created snapshot '{target}' ({target_id}) from '{source}' ({source_id})"
653
654 def __format_delete_subvolume_result(self, operation):
655 target = operation["target"]
656 target_id = operation["target_id"]
657 return f"Deleted subvolume '{target}' ({target_id})"
658
659 def __format_set_default_subvolume_result(self, operation):
660 target = operation["target"]
661 if "target_id" in operation:
662 target_id = operation["target_id"]
663 else:
664 target_subvolume = self.__filesystem.get_subvolume_by_name(target)
665 target_id = target_subvolume.id if target_subvolume is not None else self.__UNKNOWN_SUBVOLUME_ID
666 return f"Updated default subvolume to '{target}' ({target_id})"
667
668
669 def run_module():
670 module_args = dict(
671 automount=dict(type="bool", default=False),
672 default=dict(type="bool", default=False),
673 filesystem_device=dict(type="path"),
674 filesystem_label=dict(type="str"),
675 filesystem_uuid=dict(type="str"),
676 name=dict(type="str", required=True),
677 recursive=dict(type="bool", default=False),
678 state=dict(type="str", default="present", choices=["present", "absent"]),
679 snapshot_source=dict(type="str"),
680 snapshot_conflict=dict(type="str", default="skip", choices=["skip", "clobber", "error"]),
681 )
682
683 module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
684
685 subvolume = BtrfsSubvolumeModule(module)
686 error, result = subvolume.run()
687 if error is not None:
688 module.fail_json(str(error), **result)
689 else:
690 module.exit_json(**result)
691
692
693 def main():
694 run_module()
695
696
697 if __name__ == "__main__":
698 main()