| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2021, quidame <[email protected]> |
| 4 |
# Copyright (c) 2013, Alexander Bulimov <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
author: |
| 12 |
- Alexander Bulimov (@abulimov) |
| 13 |
- quidame (@quidame) |
| 14 |
module: filesystem |
| 15 |
short_description: Makes a filesystem |
| 16 |
description: |
| 17 |
- This module creates a filesystem. |
| 18 |
extends_documentation_fragment: |
| 19 |
- community.general._attributes |
| 20 |
attributes: |
| 21 |
check_mode: |
| 22 |
support: full |
| 23 |
diff_mode: |
| 24 |
support: none |
| 25 |
options: |
| 26 |
state: |
| 27 |
description: |
| 28 |
- If O(state=present), the filesystem is created if it does not already exist, that is the default behaviour if O(state) |
| 29 |
is omitted. |
| 30 |
- If O(state=absent), filesystem signatures on O(dev) are wiped if it contains a filesystem (as known by C(blkid)). |
| 31 |
- When O(state=absent), all other options but O(dev) are ignored, and the module does not fail if the device O(dev) |
| 32 |
does not actually exist. |
| 33 |
type: str |
| 34 |
choices: [present, absent] |
| 35 |
default: present |
| 36 |
version_added: 1.3.0 |
| 37 |
fstype: |
| 38 |
choices: [bcachefs, btrfs, ext2, ext3, ext4, ext4dev, f2fs, lvm, ocfs2, reiserfs, xfs, vfat, swap, ufs] |
| 39 |
description: |
| 40 |
- Filesystem type to be created. This option is required with O(state=present) (or if O(state) is omitted). |
| 41 |
- V(ufs) support has been added in community.general 3.4.0. |
| 42 |
- V(bcachefs) support has been added in community.general 8.6.0. |
| 43 |
type: str |
| 44 |
aliases: [type] |
| 45 |
dev: |
| 46 |
description: |
| 47 |
- Target path to block device (Linux) or character device (FreeBSD) or regular file (both). |
| 48 |
- When setting Linux-specific filesystem types on FreeBSD, this module only works when applying to regular files, also known as |
| 49 |
disk images. |
| 50 |
- Currently V(lvm) (Linux-only) and V(ufs) (FreeBSD-only) do not support a regular file as their target O(dev). |
| 51 |
- Support for character devices on FreeBSD has been added in community.general 3.4.0. |
| 52 |
type: path |
| 53 |
required: true |
| 54 |
aliases: [device] |
| 55 |
force: |
| 56 |
description: |
| 57 |
- If V(true), allows to create new filesystem on devices that already has filesystem. |
| 58 |
type: bool |
| 59 |
default: false |
| 60 |
resizefs: |
| 61 |
description: |
| 62 |
- If V(true), if the block device and filesystem size differ, grow the filesystem into the space. |
| 63 |
- >- |
| 64 |
Supported when O(fstype) is one of: V(bcachefs), V(btrfs), V(ext2), V(ext3), V(ext4), V(ext4dev), V(f2fs), V(lvm), V(xfs), V(ufs) and V(vfat). |
| 65 |
Attempts to resize other filesystem types fail. |
| 66 |
- XFS only grows if mounted. Currently, the module is based on commands from C(util-linux) package to perform operations, |
| 67 |
so resizing of XFS is not supported on FreeBSD systems. |
| 68 |
- VFAT is likely to fail if C(fatresize < 1.04). |
| 69 |
- Mutually exclusive with O(uuid). |
| 70 |
type: bool |
| 71 |
default: false |
| 72 |
opts: |
| 73 |
description: |
| 74 |
- List of options to be passed to C(mkfs) command. |
| 75 |
type: str |
| 76 |
uuid: |
| 77 |
description: |
| 78 |
- Set filesystem's UUID to the given value. |
| 79 |
- The UUID options specified in O(opts) take precedence over this value. |
| 80 |
- See xfs_admin(8) (C(xfs)), tune2fs(8) (C(ext2), C(ext3), C(ext4), C(ext4dev)) for possible values. |
| 81 |
- For O(fstype=lvm) the value is ignored, it resets the PV UUID if set. |
| 82 |
- Supported for O(fstype) being one of V(bcachefs), V(ext2), V(ext3), V(ext4), V(ext4dev), V(lvm), or V(xfs). |
| 83 |
- This is B(not idempotent). Specifying this option always results in a change. |
| 84 |
- Mutually exclusive with O(resizefs). |
| 85 |
type: str |
| 86 |
version_added: 7.1.0 |
| 87 |
requirements: |
| 88 |
- Uses specific tools related to the O(fstype) for creating or resizing a filesystem (from packages e2fsprogs, xfsprogs, |
| 89 |
dosfstools, and so on). |
| 90 |
- Uses generic tools mostly related to the Operating System (Linux or FreeBSD) or available on both, as C(blkid). |
| 91 |
- On FreeBSD, either C(util-linux) or C(e2fsprogs) package is required. |
| 92 |
notes: |
| 93 |
- Potential filesystems on O(dev) are checked using C(blkid). In case C(blkid) is unable to detect a filesystem (and in |
| 94 |
case C(fstyp) on FreeBSD is also unable to detect a filesystem), this filesystem is overwritten even if O(force=false). |
| 95 |
- On FreeBSD systems, both C(e2fsprogs) and C(util-linux) packages provide a C(blkid) command that is compatible with this |
| 96 |
module. However, these packages conflict with each other, and only the C(util-linux) package provides the command required |
| 97 |
to not fail when O(state=absent). |
| 98 |
seealso: |
| 99 |
- module: community.general.filesize |
| 100 |
- module: ansible.posix.mount |
| 101 |
- name: xfs_admin(8) manpage for Linux |
| 102 |
description: Manual page of the GNU/Linux's xfs_admin implementation. |
| 103 |
link: https://man7.org/linux/man-pages/man8/xfs_admin.8.html |
| 104 |
- name: tune2fs(8) manpage for Linux |
| 105 |
description: Manual page of the GNU/Linux's tune2fs implementation. |
| 106 |
link: https://man7.org/linux/man-pages/man8/tune2fs.8.html |
| 107 |
""" |
| 108 |
|
| 109 |
EXAMPLES = r""" |
| 110 |
- name: Create a ext2 filesystem on /dev/sdb1 |
| 111 |
community.general.filesystem: |
| 112 |
fstype: ext2 |
| 113 |
dev: /dev/sdb1 |
| 114 |
|
| 115 |
- name: Create a ext4 filesystem on /dev/sdb1 and check disk blocks |
| 116 |
community.general.filesystem: |
| 117 |
fstype: ext4 |
| 118 |
dev: /dev/sdb1 |
| 119 |
opts: -cc |
| 120 |
|
| 121 |
- name: Blank filesystem signature on /dev/sdb1 |
| 122 |
community.general.filesystem: |
| 123 |
dev: /dev/sdb1 |
| 124 |
state: absent |
| 125 |
|
| 126 |
- name: Create a filesystem on top of a regular file |
| 127 |
community.general.filesystem: |
| 128 |
dev: /path/to/disk.img |
| 129 |
fstype: vfat |
| 130 |
|
| 131 |
- name: Reset an xfs filesystem UUID on /dev/sdb1 |
| 132 |
community.general.filesystem: |
| 133 |
fstype: xfs |
| 134 |
dev: /dev/sdb1 |
| 135 |
uuid: generate |
| 136 |
|
| 137 |
- name: Reset an ext4 filesystem UUID on /dev/sdb1 |
| 138 |
community.general.filesystem: |
| 139 |
fstype: ext4 |
| 140 |
dev: /dev/sdb1 |
| 141 |
uuid: random |
| 142 |
|
| 143 |
- name: Reset an LVM filesystem (PV) UUID on /dev/sdc |
| 144 |
community.general.filesystem: |
| 145 |
fstype: lvm |
| 146 |
dev: /dev/sdc |
| 147 |
uuid: random |
| 148 |
""" |
| 149 |
|
| 150 |
import os |
| 151 |
import platform |
| 152 |
import re |
| 153 |
import stat |
| 154 |
|
| 155 |
from ansible.module_utils.basic import AnsibleModule |
| 156 |
|
| 157 |
from ansible_collections.community.general.plugins.module_utils._lvm import pvs_runner |
| 158 |
from ansible_collections.community.general.plugins.module_utils._version import LooseVersion |
| 159 |
|
| 160 |
|
| 161 |
class Device: |
| 162 |
def __init__(self, module, path): |
| 163 |
self.module = module |
| 164 |
self.path = path |
| 165 |
|
| 166 |
def size(self): |
| 167 |
"""Return size in bytes of device. Returns int""" |
| 168 |
statinfo = os.stat(self.path) |
| 169 |
if stat.S_ISBLK(statinfo.st_mode): |
| 170 |
blockdev_cmd = self.module.get_bin_path("blockdev", required=True) |
| 171 |
dummy, out, dummy = self.module.run_command([blockdev_cmd, "--getsize64", self.path], check_rc=True) |
| 172 |
devsize_in_bytes = int(out) |
| 173 |
elif stat.S_ISCHR(statinfo.st_mode) and platform.system() == "FreeBSD": |
| 174 |
diskinfo_cmd = self.module.get_bin_path("diskinfo", required=True) |
| 175 |
dummy, out, dummy = self.module.run_command([diskinfo_cmd, self.path], check_rc=True) |
| 176 |
devsize_in_bytes = int(out.split()[2]) |
| 177 |
elif os.path.isfile(self.path): |
| 178 |
devsize_in_bytes = os.path.getsize(self.path) |
| 179 |
else: |
| 180 |
self.module.fail_json(changed=False, msg=f"Target device not supported: {self}") |
| 181 |
|
| 182 |
return devsize_in_bytes |
| 183 |
|
| 184 |
def get_mountpoint(self): |
| 185 |
"""Return (first) mountpoint of device. Returns None when not mounted.""" |
| 186 |
cmd_findmnt = self.module.get_bin_path("findmnt", required=True) |
| 187 |
|
| 188 |
# find mountpoint |
| 189 |
rc, mountpoint, dummy = self.module.run_command( |
| 190 |
[cmd_findmnt, "--mtab", "--noheadings", "--output", "TARGET", "--source", self.path], check_rc=False |
| 191 |
) |
| 192 |
if rc != 0: |
| 193 |
mountpoint = None |
| 194 |
else: |
| 195 |
mountpoint = mountpoint.split("\n")[0] |
| 196 |
|
| 197 |
return mountpoint |
| 198 |
|
| 199 |
def __str__(self): |
| 200 |
return self.path |
| 201 |
|
| 202 |
|
| 203 |
class Filesystem: |
| 204 |
MKFS: str | None = None |
| 205 |
MKFS_FORCE_FLAGS: list[str] | None = [] |
| 206 |
MKFS_SET_UUID_OPTIONS: list[str] | None = None |
| 207 |
MKFS_SET_UUID_EXTRA_OPTIONS: list[str] | None = [] |
| 208 |
INFO: str | None = None |
| 209 |
GROW: str | None = None |
| 210 |
GROW_SLACK: int = 0 |
| 211 |
GROW_MAX_SPACE_FLAGS: list[str] | None = [] |
| 212 |
GROW_MOUNTPOINT_ONLY = False |
| 213 |
CHANGE_UUID: str | None = None |
| 214 |
CHANGE_UUID_OPTION: str | None = None |
| 215 |
CHANGE_UUID_OPTION_HAS_ARG = True |
| 216 |
|
| 217 |
LANG_ENV = {"LANGUAGE": "C", "LC_ALL": "C"} |
| 218 |
|
| 219 |
def __init__(self, module): |
| 220 |
self.module = module |
| 221 |
|
| 222 |
@property |
| 223 |
def fstype(self): |
| 224 |
return type(self).__name__ |
| 225 |
|
| 226 |
def get_fs_size(self, dev): |
| 227 |
"""Return size in bytes of filesystem on device (integer). |
| 228 |
Should query the info with a per-fstype command that can access the |
| 229 |
device whenever it is mounted or not, and parse the command output. |
| 230 |
Parser must ensure to return an integer, or raise a ValueError. |
| 231 |
""" |
| 232 |
raise NotImplementedError() |
| 233 |
|
| 234 |
def create(self, opts, dev, uuid=None): |
| 235 |
if self.module.check_mode: |
| 236 |
return |
| 237 |
|
| 238 |
if uuid and self.MKFS_SET_UUID_OPTIONS: |
| 239 |
if not (set(self.MKFS_SET_UUID_OPTIONS) & set(opts)): |
| 240 |
opts += [self.MKFS_SET_UUID_OPTIONS[0], uuid] + self.MKFS_SET_UUID_EXTRA_OPTIONS |
| 241 |
|
| 242 |
mkfs = self.module.get_bin_path(self.MKFS, required=True) |
| 243 |
cmd = [mkfs] + self.MKFS_FORCE_FLAGS + opts + [str(dev)] |
| 244 |
self.module.run_command(cmd, check_rc=True) |
| 245 |
if uuid and self.CHANGE_UUID and self.MKFS_SET_UUID_OPTIONS is None: |
| 246 |
self.change_uuid(new_uuid=uuid, dev=dev) |
| 247 |
|
| 248 |
def wipefs(self, dev): |
| 249 |
if self.module.check_mode: |
| 250 |
return |
| 251 |
|
| 252 |
# wipefs comes with util-linux package (as 'blockdev' & 'findmnt' above) |
| 253 |
# that is ported to FreeBSD. The use of dd as a portable fallback is |
| 254 |
# not doable here if it needs get_mountpoint() (to prevent corruption of |
| 255 |
# a mounted filesystem), since 'findmnt' is not available on FreeBSD, |
| 256 |
# even in util-linux port for this OS. |
| 257 |
wipefs = self.module.get_bin_path("wipefs", required=True) |
| 258 |
cmd = [wipefs, "--all", str(dev)] |
| 259 |
self.module.run_command(cmd, check_rc=True) |
| 260 |
|
| 261 |
def grow_cmd(self, target): |
| 262 |
"""Build and return the resizefs commandline as list.""" |
| 263 |
cmdline = [self.module.get_bin_path(self.GROW, required=True)] |
| 264 |
cmdline += self.GROW_MAX_SPACE_FLAGS + [target] |
| 265 |
return cmdline |
| 266 |
|
| 267 |
def grow(self, dev): |
| 268 |
"""Get dev and fs size and compare. Returns stdout of used command.""" |
| 269 |
devsize_in_bytes = dev.size() |
| 270 |
|
| 271 |
try: |
| 272 |
fssize_in_bytes = self.get_fs_size(dev) |
| 273 |
except NotImplementedError: |
| 274 |
self.module.fail_json(msg=f"module does not support resizing {self.fstype} filesystem yet") |
| 275 |
except ValueError as err: |
| 276 |
self.module.warn(f"unable to process {self.INFO} output '{err}'") |
| 277 |
self.module.fail_json(msg=f"unable to process {self.INFO} output for {dev}") |
| 278 |
|
| 279 |
if fssize_in_bytes + self.GROW_SLACK >= devsize_in_bytes: |
| 280 |
self.module.exit_json(changed=False, msg=f"{self.fstype} filesystem is using the whole device {dev}") |
| 281 |
elif self.module.check_mode: |
| 282 |
self.module.exit_json(changed=True, msg=f"resizing filesystem {self.fstype} on device {dev}") |
| 283 |
|
| 284 |
if self.GROW_MOUNTPOINT_ONLY: |
| 285 |
mountpoint = dev.get_mountpoint() |
| 286 |
if not mountpoint: |
| 287 |
self.module.fail_json(msg=f"{dev} needs to be mounted for {self.fstype} operations") |
| 288 |
grow_target = mountpoint |
| 289 |
else: |
| 290 |
grow_target = str(dev) |
| 291 |
|
| 292 |
dummy, out, dummy = self.module.run_command(self.grow_cmd(grow_target), check_rc=True) |
| 293 |
return out |
| 294 |
|
| 295 |
def change_uuid_cmd(self, new_uuid, target): |
| 296 |
"""Build and return the UUID change command line as list.""" |
| 297 |
cmdline = [self.module.get_bin_path(self.CHANGE_UUID, required=True)] |
| 298 |
if self.CHANGE_UUID_OPTION_HAS_ARG: |
| 299 |
cmdline += [self.CHANGE_UUID_OPTION, new_uuid, target] |
| 300 |
else: |
| 301 |
cmdline += [self.CHANGE_UUID_OPTION, target] |
| 302 |
return cmdline |
| 303 |
|
| 304 |
def change_uuid(self, new_uuid, dev): |
| 305 |
"""Change filesystem UUID. Returns stdout of used command""" |
| 306 |
if self.module.check_mode: |
| 307 |
self.module.exit_json(change=True, msg=f"Changing {self.fstype} filesystem UUID on device {dev}") |
| 308 |
|
| 309 |
dummy, out, dummy = self.module.run_command( |
| 310 |
self.change_uuid_cmd(new_uuid=new_uuid, target=str(dev)), check_rc=True |
| 311 |
) |
| 312 |
return out |
| 313 |
|
| 314 |
|
| 315 |
class Ext(Filesystem): |
| 316 |
MKFS_FORCE_FLAGS = ["-F"] |
| 317 |
MKFS_SET_UUID_OPTIONS = ["-U"] |
| 318 |
INFO = "tune2fs" |
| 319 |
GROW = "resize2fs" |
| 320 |
CHANGE_UUID = "tune2fs" |
| 321 |
CHANGE_UUID_OPTION = "-U" |
| 322 |
|
| 323 |
def get_fs_size(self, dev): |
| 324 |
"""Get Block count and Block size and return their product.""" |
| 325 |
cmd = self.module.get_bin_path(self.INFO, required=True) |
| 326 |
dummy, out, dummy = self.module.run_command([cmd, "-l", str(dev)], check_rc=True, environ_update=self.LANG_ENV) |
| 327 |
|
| 328 |
block_count = block_size = None |
| 329 |
for line in out.splitlines(): |
| 330 |
if "Block count:" in line: |
| 331 |
block_count = int(line.split(":")[1].strip()) |
| 332 |
elif "Block size:" in line: |
| 333 |
block_size = int(line.split(":")[1].strip()) |
| 334 |
if None not in (block_size, block_count): |
| 335 |
break |
| 336 |
else: |
| 337 |
raise ValueError(repr(out)) |
| 338 |
|
| 339 |
return block_size * block_count |
| 340 |
|
| 341 |
|
| 342 |
class Ext2(Ext): |
| 343 |
MKFS = "mkfs.ext2" |
| 344 |
|
| 345 |
|
| 346 |
class Ext3(Ext): |
| 347 |
MKFS = "mkfs.ext3" |
| 348 |
|
| 349 |
|
| 350 |
class Ext4(Ext): |
| 351 |
MKFS = "mkfs.ext4" |
| 352 |
|
| 353 |
|
| 354 |
class XFS(Filesystem): |
| 355 |
MKFS = "mkfs.xfs" |
| 356 |
MKFS_FORCE_FLAGS = ["-f"] |
| 357 |
INFO = "xfs_info" |
| 358 |
GROW = "xfs_growfs" |
| 359 |
# XFS (defaults with 4KiB blocksize) requires at least 64 block of free |
| 360 |
# space to add a new allocation group, avoid resizing (noop, but shown as |
| 361 |
# diff) if the difference between the filesystem and the device is less |
| 362 |
GROW_SLACK = 64 * 4096 - 1 |
| 363 |
GROW_MOUNTPOINT_ONLY = True |
| 364 |
CHANGE_UUID = "xfs_admin" |
| 365 |
CHANGE_UUID_OPTION = "-U" |
| 366 |
|
| 367 |
def get_fs_size(self, dev): |
| 368 |
"""Get bsize and blocks and return their product.""" |
| 369 |
cmdline = [self.module.get_bin_path(self.INFO, required=True)] |
| 370 |
|
| 371 |
# Depending on the versions, xfs_info is able to get info from the |
| 372 |
# device, whenever it is mounted or not, or only if unmounted, or |
| 373 |
# only if mounted, or not at all. For any version until now, it is |
| 374 |
# able to query info from the mountpoint. So try it first, and use |
| 375 |
# device as the last resort: it may or may not work. |
| 376 |
mountpoint = dev.get_mountpoint() |
| 377 |
if mountpoint: |
| 378 |
cmdline += [mountpoint] |
| 379 |
else: |
| 380 |
cmdline += [str(dev)] |
| 381 |
dummy, out, dummy = self.module.run_command(cmdline, check_rc=True, environ_update=self.LANG_ENV) |
| 382 |
|
| 383 |
block_size = block_count = None |
| 384 |
for line in out.splitlines(): |
| 385 |
col = line.split("=") |
| 386 |
if col[0].strip() == "data": |
| 387 |
if col[1].strip() == "bsize": |
| 388 |
block_size = int(col[2].split()[0]) |
| 389 |
if col[2].split()[1] == "blocks": |
| 390 |
block_count = int(col[3].split(",")[0]) |
| 391 |
if None not in (block_size, block_count): |
| 392 |
break |
| 393 |
else: |
| 394 |
raise ValueError(repr(out)) |
| 395 |
|
| 396 |
return block_size * block_count |
| 397 |
|
| 398 |
|
| 399 |
class Reiserfs(Filesystem): |
| 400 |
MKFS = "mkfs.reiserfs" |
| 401 |
MKFS_FORCE_FLAGS = ["-q"] |
| 402 |
|
| 403 |
|
| 404 |
class Bcachefs(Filesystem): |
| 405 |
MKFS = "mkfs.bcachefs" |
| 406 |
MKFS_FORCE_FLAGS = ["--force"] |
| 407 |
MKFS_SET_UUID_OPTIONS = ["-U", "--uuid"] |
| 408 |
INFO = "bcachefs" |
| 409 |
GROW = "bcachefs" |
| 410 |
GROW_MAX_SPACE_FLAGS = ["device", "resize"] |
| 411 |
|
| 412 |
def get_fs_size(self, dev): |
| 413 |
"""Return size in bytes of filesystem on device (integer).""" |
| 414 |
dummy, stdout, dummy = self.module.run_command( |
| 415 |
[self.module.get_bin_path(self.INFO), "show-super", str(dev)], check_rc=True |
| 416 |
) |
| 417 |
|
| 418 |
for line in stdout.splitlines(): |
| 419 |
if "Size: " in line: |
| 420 |
parts = line.split() |
| 421 |
unit = parts[2] |
| 422 |
|
| 423 |
base = None |
| 424 |
exp = None |
| 425 |
|
| 426 |
units_2 = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] |
| 427 |
units_10 = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] |
| 428 |
|
| 429 |
try: |
| 430 |
exp = units_2.index(unit) |
| 431 |
base = 1024 |
| 432 |
except ValueError: |
| 433 |
exp = units_10.index(unit) |
| 434 |
base = 1000 |
| 435 |
|
| 436 |
if exp == 0: |
| 437 |
value = int(parts[1]) |
| 438 |
else: |
| 439 |
value = float(parts[1]) |
| 440 |
|
| 441 |
if base is not None and exp is not None: |
| 442 |
return int(value * pow(base, exp)) |
| 443 |
|
| 444 |
raise ValueError(repr(stdout)) |
| 445 |
|
| 446 |
|
| 447 |
class Btrfs(Filesystem): |
| 448 |
MKFS = "mkfs.btrfs" |
| 449 |
INFO = "btrfs" |
| 450 |
GROW = "btrfs" |
| 451 |
GROW_MAX_SPACE_FLAGS = ["filesystem", "resize", "max"] |
| 452 |
GROW_MOUNTPOINT_ONLY = True |
| 453 |
|
| 454 |
def __init__(self, module): |
| 455 |
super().__init__(module) |
| 456 |
mkfs = self.module.get_bin_path(self.MKFS, required=True) |
| 457 |
dummy, stdout, stderr = self.module.run_command([mkfs, "--version"], check_rc=True) |
| 458 |
match = re.search(r" v([0-9.]+)", stdout) |
| 459 |
if not match: |
| 460 |
# v0.20-rc1 use stderr |
| 461 |
match = re.search(r" v([0-9.]+)", stderr) |
| 462 |
if match: |
| 463 |
# v0.20-rc1 doesn't have --force parameter added in following version v3.12 |
| 464 |
if LooseVersion(match.group(1)) >= LooseVersion("3.12"): |
| 465 |
self.MKFS_FORCE_FLAGS = ["-f"] |
| 466 |
else: |
| 467 |
# assume version is greater or equal to 3.12 |
| 468 |
self.MKFS_FORCE_FLAGS = ["-f"] |
| 469 |
self.module.warn(f"Unable to identify mkfs.btrfs version ({stdout!r}, {stderr!r})") |
| 470 |
|
| 471 |
def get_fs_size(self, dev): |
| 472 |
"""Return size in bytes of filesystem on device (integer).""" |
| 473 |
mountpoint = dev.get_mountpoint() |
| 474 |
if not mountpoint: |
| 475 |
self.module.fail_json(msg=f"{dev} needs to be mounted for {self.fstype} operations") |
| 476 |
|
| 477 |
dummy, stdout, dummy = self.module.run_command( |
| 478 |
[self.module.get_bin_path(self.INFO), "filesystem", "usage", "-b", mountpoint], check_rc=True |
| 479 |
) |
| 480 |
for line in stdout.splitlines(): |
| 481 |
if "Device size" in line: |
| 482 |
return int(line.split()[-1]) |
| 483 |
raise ValueError(repr(stdout)) |
| 484 |
|
| 485 |
|
| 486 |
class Ocfs2(Filesystem): |
| 487 |
MKFS = "mkfs.ocfs2" |
| 488 |
MKFS_FORCE_FLAGS = ["-Fx"] |
| 489 |
|
| 490 |
|
| 491 |
class F2fs(Filesystem): |
| 492 |
MKFS = "mkfs.f2fs" |
| 493 |
INFO = "dump.f2fs" |
| 494 |
GROW = "resize.f2fs" |
| 495 |
|
| 496 |
def __init__(self, module): |
| 497 |
super().__init__(module) |
| 498 |
mkfs = self.module.get_bin_path(self.MKFS, required=True) |
| 499 |
dummy, out, dummy = self.module.run_command([mkfs, os.devnull], check_rc=False, environ_update=self.LANG_ENV) |
| 500 |
# Looking for " F2FS-tools: mkfs.f2fs Ver: 1.10.0 (2018-01-30)" |
| 501 |
# mkfs.f2fs displays version since v1.2.0 |
| 502 |
match = re.search(r"F2FS-tools: mkfs.f2fs Ver: ([0-9.]+) \(", out) |
| 503 |
if match is not None: |
| 504 |
# Since 1.9.0, mkfs.f2fs check overwrite before make filesystem |
| 505 |
# before that version -f switch wasn't used |
| 506 |
if LooseVersion(match.group(1)) >= LooseVersion("1.9.0"): |
| 507 |
self.MKFS_FORCE_FLAGS = ["-f"] |
| 508 |
|
| 509 |
def get_fs_size(self, dev): |
| 510 |
"""Get sector size and total FS sectors and return their product.""" |
| 511 |
cmd = self.module.get_bin_path(self.INFO, required=True) |
| 512 |
dummy, out, dummy = self.module.run_command([cmd, str(dev)], check_rc=True, environ_update=self.LANG_ENV) |
| 513 |
sector_size = sector_count = None |
| 514 |
for line in out.splitlines(): |
| 515 |
if "Info: sector size = " in line: |
| 516 |
# expected: 'Info: sector size = 512' |
| 517 |
sector_size = int(line.split()[4]) |
| 518 |
elif "Info: total FS sectors = " in line: |
| 519 |
# expected: 'Info: total FS sectors = 102400 (50 MB)' |
| 520 |
sector_count = int(line.split()[5]) |
| 521 |
if None not in (sector_size, sector_count): |
| 522 |
break |
| 523 |
else: |
| 524 |
raise ValueError(repr(out)) |
| 525 |
|
| 526 |
return sector_size * sector_count |
| 527 |
|
| 528 |
|
| 529 |
class VFAT(Filesystem): |
| 530 |
INFO = "fatresize" |
| 531 |
GROW = "fatresize" |
| 532 |
GROW_MAX_SPACE_FLAGS = ["-s", "max"] |
| 533 |
|
| 534 |
def __init__(self, module): |
| 535 |
super().__init__(module) |
| 536 |
if platform.system() == "FreeBSD": |
| 537 |
self.MKFS = "newfs_msdos" |
| 538 |
else: |
| 539 |
self.MKFS = "mkfs.vfat" |
| 540 |
|
| 541 |
def get_fs_size(self, dev): |
| 542 |
"""Get and return size of filesystem, in bytes.""" |
| 543 |
cmd = self.module.get_bin_path(self.INFO, required=True) |
| 544 |
dummy, out, dummy = self.module.run_command( |
| 545 |
[cmd, "--info", str(dev)], check_rc=True, environ_update=self.LANG_ENV |
| 546 |
) |
| 547 |
fssize = None |
| 548 |
for line in out.splitlines()[1:]: |
| 549 |
parts = line.split(":", 1) |
| 550 |
if len(parts) < 2: |
| 551 |
continue |
| 552 |
param, value = parts |
| 553 |
if param.strip() in ("Size", "Cur size"): |
| 554 |
fssize = int(value.strip()) |
| 555 |
break |
| 556 |
else: |
| 557 |
raise ValueError(repr(out)) |
| 558 |
|
| 559 |
return fssize |
| 560 |
|
| 561 |
|
| 562 |
class LVM(Filesystem): |
| 563 |
MKFS = "pvcreate" |
| 564 |
MKFS_FORCE_FLAGS = ["-f"] |
| 565 |
MKFS_SET_UUID_OPTIONS = ["-u", "--uuid"] |
| 566 |
MKFS_SET_UUID_EXTRA_OPTIONS = ["--norestorefile"] |
| 567 |
INFO = "pvs" |
| 568 |
GROW = "pvresize" |
| 569 |
CHANGE_UUID = "pvchange" |
| 570 |
CHANGE_UUID_OPTION = "-u" |
| 571 |
CHANGE_UUID_OPTION_HAS_ARG = False |
| 572 |
|
| 573 |
def __init__(self, module): |
| 574 |
super().__init__(module) |
| 575 |
self._pvs = pvs_runner(module) |
| 576 |
|
| 577 |
def get_fs_size(self, dev): |
| 578 |
"""Get and return PV size, in bytes.""" |
| 579 |
with self._pvs("noheadings nosuffix units fields devices") as ctx: |
| 580 |
dummy, size, dummy = ctx.run(units="b", fields="pv_size", devices=[str(dev)]) |
| 581 |
return int(size.strip()) |
| 582 |
|
| 583 |
|
| 584 |
class Swap(Filesystem): |
| 585 |
MKFS = "mkswap" |
| 586 |
MKFS_FORCE_FLAGS = ["-f"] |
| 587 |
|
| 588 |
|
| 589 |
class UFS(Filesystem): |
| 590 |
MKFS = "newfs" |
| 591 |
INFO = "dumpfs" |
| 592 |
GROW = "growfs" |
| 593 |
GROW_MAX_SPACE_FLAGS = ["-y"] |
| 594 |
|
| 595 |
def get_fs_size(self, dev): |
| 596 |
"""Get providersize and fragment size and return their product.""" |
| 597 |
cmd = self.module.get_bin_path(self.INFO, required=True) |
| 598 |
dummy, out, dummy = self.module.run_command([cmd, str(dev)], check_rc=True, environ_update=self.LANG_ENV) |
| 599 |
|
| 600 |
fragmentsize = providersize = None |
| 601 |
for line in out.splitlines(): |
| 602 |
if line.startswith("fsize"): |
| 603 |
fragmentsize = int(line.split()[1]) |
| 604 |
elif "providersize" in line: |
| 605 |
providersize = int(line.split()[-1]) |
| 606 |
if None not in (fragmentsize, providersize): |
| 607 |
break |
| 608 |
else: |
| 609 |
raise ValueError(repr(out)) |
| 610 |
|
| 611 |
return fragmentsize * providersize |
| 612 |
|
| 613 |
|
| 614 |
FILESYSTEMS = { |
| 615 |
"bcachefs": Bcachefs, |
| 616 |
"ext2": Ext2, |
| 617 |
"ext3": Ext3, |
| 618 |
"ext4": Ext4, |
| 619 |
"ext4dev": Ext4, |
| 620 |
"f2fs": F2fs, |
| 621 |
"reiserfs": Reiserfs, |
| 622 |
"xfs": XFS, |
| 623 |
"btrfs": Btrfs, |
| 624 |
"vfat": VFAT, |
| 625 |
"ocfs2": Ocfs2, |
| 626 |
"LVM2_member": LVM, |
| 627 |
"swap": Swap, |
| 628 |
"ufs": UFS, |
| 629 |
} |
| 630 |
|
| 631 |
|
| 632 |
def main(): |
| 633 |
friendly_names = { |
| 634 |
"lvm": "LVM2_member", |
| 635 |
} |
| 636 |
|
| 637 |
fstypes = set(FILESYSTEMS.keys()) - set(friendly_names.values()) | set(friendly_names.keys()) |
| 638 |
|
| 639 |
# There is no "single command" to manipulate filesystems, so we map them all out and their options |
| 640 |
module = AnsibleModule( |
| 641 |
argument_spec=dict( |
| 642 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 643 |
fstype=dict(type="str", aliases=["type"], choices=list(fstypes)), |
| 644 |
dev=dict(type="path", required=True, aliases=["device"]), |
| 645 |
opts=dict(type="str"), |
| 646 |
force=dict(type="bool", default=False), |
| 647 |
resizefs=dict(type="bool", default=False), |
| 648 |
uuid=dict(type="str"), |
| 649 |
), |
| 650 |
required_if=[("state", "present", ["fstype"])], |
| 651 |
mutually_exclusive=[ |
| 652 |
("resizefs", "uuid"), |
| 653 |
], |
| 654 |
supports_check_mode=True, |
| 655 |
) |
| 656 |
|
| 657 |
state = module.params["state"] |
| 658 |
dev = module.params["dev"] |
| 659 |
fstype = module.params["fstype"] |
| 660 |
opts = module.params["opts"] |
| 661 |
force = module.params["force"] |
| 662 |
resizefs = module.params["resizefs"] |
| 663 |
uuid = module.params["uuid"] |
| 664 |
|
| 665 |
mkfs_opts = [] |
| 666 |
if opts is not None: |
| 667 |
mkfs_opts = opts.split() |
| 668 |
|
| 669 |
changed = False |
| 670 |
|
| 671 |
if not os.path.exists(dev): |
| 672 |
msg = f"Device {dev} not found." |
| 673 |
if state == "present": |
| 674 |
module.fail_json(msg=msg) |
| 675 |
else: |
| 676 |
module.exit_json(msg=msg) |
| 677 |
|
| 678 |
dev = Device(module, dev) |
| 679 |
|
| 680 |
# In case blkid/fstyp isn't able to identify an existing filesystem, device |
| 681 |
# is considered as empty, then this existing filesystem would be overwritten |
| 682 |
# even if force isn't enabled. |
| 683 |
cmd = module.get_bin_path("blkid", required=True) |
| 684 |
rc, raw_fs, err = module.run_command([cmd, "-c", os.devnull, "-o", "value", "-s", "TYPE", str(dev)]) |
| 685 |
fs = raw_fs.strip() |
| 686 |
if not fs and platform.system() == "FreeBSD": |
| 687 |
cmd = module.get_bin_path("fstyp", required=True) |
| 688 |
rc, raw_fs, err = module.run_command([cmd, str(dev)]) |
| 689 |
fs = raw_fs.strip() |
| 690 |
|
| 691 |
if state == "present": |
| 692 |
if fstype in friendly_names: |
| 693 |
fstype = friendly_names[fstype] |
| 694 |
|
| 695 |
try: |
| 696 |
klass = FILESYSTEMS[fstype] |
| 697 |
except KeyError: |
| 698 |
module.fail_json(changed=False, msg=f"module does not support this filesystem ({fstype}) yet.") |
| 699 |
|
| 700 |
filesystem = klass(module) |
| 701 |
|
| 702 |
if uuid and not (filesystem.CHANGE_UUID or filesystem.MKFS_SET_UUID_OPTIONS): |
| 703 |
module.fail_json( |
| 704 |
changed=False, msg=f"module does not support UUID option for this filesystem ({fstype}) yet." |
| 705 |
) |
| 706 |
|
| 707 |
same_fs = fs and FILESYSTEMS.get(fs) == FILESYSTEMS[fstype] |
| 708 |
if same_fs and not resizefs and not uuid and not force: |
| 709 |
module.exit_json(changed=False) |
| 710 |
elif same_fs: |
| 711 |
if resizefs: |
| 712 |
if not filesystem.GROW: |
| 713 |
module.fail_json(changed=False, msg=f"module does not support resizing {fstype} filesystem yet.") |
| 714 |
|
| 715 |
out = filesystem.grow(dev) |
| 716 |
|
| 717 |
module.exit_json(changed=True, msg=out) |
| 718 |
elif uuid: |
| 719 |
out = filesystem.change_uuid(new_uuid=uuid, dev=dev) |
| 720 |
|
| 721 |
module.exit_json(changed=True, msg=out) |
| 722 |
elif fs and not force: |
| 723 |
module.fail_json(msg=f"'{dev}' is already used as {fs}, use force=true to overwrite", rc=rc, err=err) |
| 724 |
|
| 725 |
# create fs |
| 726 |
filesystem.create(opts=mkfs_opts, dev=dev, uuid=uuid) |
| 727 |
changed = True |
| 728 |
|
| 729 |
elif fs: |
| 730 |
# wipe fs signatures |
| 731 |
filesystem = Filesystem(module) |
| 732 |
filesystem.wipefs(dev) |
| 733 |
changed = True |
| 734 |
|
| 735 |
module.exit_json(changed=changed) |
| 736 |
|
| 737 |
|
| 738 |
if __name__ == "__main__": |
| 739 |
main() |