| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2021, quidame <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt 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: filesize |
| 11 |
|
| 12 |
short_description: Create a file with a given size, or resize it if it exists |
| 13 |
|
| 14 |
description: |
| 15 |
- This module is a simple wrapper around C(dd) to create, extend or truncate a file, given its size. It can be used to manage |
| 16 |
swap files (that require contiguous blocks) or alternatively, huge sparse files. |
| 17 |
author: |
| 18 |
- quidame (@quidame) |
| 19 |
|
| 20 |
version_added: "3.0.0" |
| 21 |
|
| 22 |
attributes: |
| 23 |
check_mode: |
| 24 |
support: full |
| 25 |
diff_mode: |
| 26 |
support: full |
| 27 |
|
| 28 |
options: |
| 29 |
path: |
| 30 |
description: |
| 31 |
- Path of the regular file to create or resize. |
| 32 |
type: path |
| 33 |
required: true |
| 34 |
size: |
| 35 |
description: |
| 36 |
- Requested size of the file. |
| 37 |
- The value is a number (either C(int) or C(float)) optionally followed by a multiplicative suffix, that can be one |
| 38 |
of V(B) (bytes), V(KB) or V(kB) (= 1000B), V(MB) or V(mB) (= 1000kB), V(GB) or V(gB) (= 1000MB), and so on for V(T), |
| 39 |
V(P), V(E), V(Z) and V(Y); or alternatively one of V(K), V(k) or V(KiB) (= 1024B); V(M), V(m) or V(MiB) (= 1024KiB); |
| 40 |
V(G), V(g) or V(GiB) (= 1024MiB); and so on. |
| 41 |
- If the multiplicative suffix is not provided, the value is treated as an integer number of blocks of O(blocksize) |
| 42 |
bytes each (float values are rounded to the closest integer). |
| 43 |
- When the O(size) value is equal to the current file size, does nothing. |
| 44 |
- When the O(size) value is bigger than the current file size, bytes from O(source) (if O(sparse) is not V(false)) are |
| 45 |
appended to the file without truncating it, in other words, without modifying the existing bytes of the file. |
| 46 |
- When the O(size) value is smaller than the current file size, it is truncated to the requested value without modifying |
| 47 |
bytes before this value. |
| 48 |
- That means that a file of any arbitrary size can be grown to any other arbitrary size, and then resized down to its |
| 49 |
initial size without modifying its initial content. |
| 50 |
type: raw |
| 51 |
required: true |
| 52 |
blocksize: |
| 53 |
description: |
| 54 |
- Size of blocks, in bytes if not followed by a multiplicative suffix. |
| 55 |
- The numeric value (before the unit) B(MUST) be an integer (or a C(float) if it equals an integer). |
| 56 |
- If not set, the size of blocks is guessed from the OS and commonly results in V(512) or V(4096) bytes, that is used |
| 57 |
internally by the module or when O(size) has no unit. |
| 58 |
type: raw |
| 59 |
source: |
| 60 |
description: |
| 61 |
- Device or file that provides input data to provision the file. |
| 62 |
- This parameter is ignored when O(sparse=true). |
| 63 |
type: path |
| 64 |
default: /dev/zero |
| 65 |
force: |
| 66 |
description: |
| 67 |
- Whether or not to overwrite the file if it exists, in other words, to truncate it from 0. When V(true), the module |
| 68 |
is not idempotent, that means it always reports RV(ignore:changed=true). |
| 69 |
- O(force=true) and O(sparse=true) are mutually exclusive. |
| 70 |
type: bool |
| 71 |
default: false |
| 72 |
sparse: |
| 73 |
description: |
| 74 |
- Whether or not the file to create should be a sparse file. |
| 75 |
- This option is effective only on newly created files, or when growing a file, only for the bytes to append. |
| 76 |
- This option is not supported on OSes or filesystems not supporting sparse files. |
| 77 |
- O(force=true) and O(sparse=true) are mutually exclusive. |
| 78 |
type: bool |
| 79 |
default: false |
| 80 |
unsafe_writes: |
| 81 |
description: |
| 82 |
- This option is silently ignored. This module always modifies file size in-place. |
| 83 |
requirements: |
| 84 |
- dd (Data Duplicator) in PATH |
| 85 |
|
| 86 |
extends_documentation_fragment: |
| 87 |
- ansible.builtin.files |
| 88 |
- community.general._attributes |
| 89 |
|
| 90 |
seealso: |
| 91 |
- name: dd(1) manpage for Linux |
| 92 |
description: Manual page of the GNU/Linux's dd implementation (from GNU coreutils). |
| 93 |
link: https://man7.org/linux/man-pages/man1/dd.1.html |
| 94 |
|
| 95 |
- name: dd(1) manpage for IBM AIX |
| 96 |
description: Manual page of the IBM AIX's dd implementation. |
| 97 |
link: https://www.ibm.com/support/knowledgecenter/ssw_aix_72/d_commands/dd.html |
| 98 |
|
| 99 |
- name: dd(1) manpage for Mac OSX |
| 100 |
description: Manual page of the Mac OSX's dd implementation. |
| 101 |
link: https://www.unix.com/man-page/osx/1/dd/ |
| 102 |
|
| 103 |
- name: dd(1M) manpage for Solaris |
| 104 |
description: Manual page of the Oracle Solaris's dd implementation. |
| 105 |
link: https://docs.oracle.com/cd/E36784_01/html/E36871/dd-1m.html |
| 106 |
|
| 107 |
- name: dd(1) manpage for FreeBSD |
| 108 |
description: Manual page of the FreeBSD's dd implementation. |
| 109 |
link: https://www.freebsd.org/cgi/man.cgi?dd(1) |
| 110 |
|
| 111 |
- name: dd(1) manpage for OpenBSD |
| 112 |
description: Manual page of the OpenBSD's dd implementation. |
| 113 |
link: https://man.openbsd.org/dd |
| 114 |
|
| 115 |
- name: dd(1) manpage for NetBSD |
| 116 |
description: Manual page of the NetBSD's dd implementation. |
| 117 |
link: https://man.netbsd.org/dd.1 |
| 118 |
|
| 119 |
- name: busybox(1) manpage for Linux |
| 120 |
description: Manual page of the GNU/Linux's busybox, that provides its own dd implementation. |
| 121 |
link: https://www.unix.com/man-page/linux/1/busybox |
| 122 |
""" |
| 123 |
|
| 124 |
EXAMPLES = r""" |
| 125 |
- name: Create a file of 1G filled with null bytes |
| 126 |
community.general.filesize: |
| 127 |
path: /var/bigfile |
| 128 |
size: 1G |
| 129 |
|
| 130 |
- name: Extend the file to 2G (2*1024^3) |
| 131 |
community.general.filesize: |
| 132 |
path: /var/bigfile |
| 133 |
size: 2G |
| 134 |
|
| 135 |
- name: Reduce the file to 2GB (2*1000^3) |
| 136 |
community.general.filesize: |
| 137 |
path: /var/bigfile |
| 138 |
size: 2GB |
| 139 |
|
| 140 |
- name: Fill a file with random bytes for backing a LUKS device |
| 141 |
community.general.filesize: |
| 142 |
path: ~/diskimage.luks |
| 143 |
size: 512.0 MiB |
| 144 |
source: /dev/urandom |
| 145 |
|
| 146 |
- name: Take a backup of MBR boot code into a file, overwriting it if it exists |
| 147 |
community.general.filesize: |
| 148 |
path: /media/sdb1/mbr.bin |
| 149 |
size: 440B |
| 150 |
source: /dev/sda |
| 151 |
force: true |
| 152 |
|
| 153 |
- name: Create/resize a sparse file of/to 8TB |
| 154 |
community.general.filesize: |
| 155 |
path: /var/local/sparsefile |
| 156 |
size: 8TB |
| 157 |
sparse: true |
| 158 |
|
| 159 |
- name: Create a file with specific size and attributes, to be used as swap space |
| 160 |
community.general.filesize: |
| 161 |
path: /var/swapfile |
| 162 |
size: 2G |
| 163 |
blocksize: 512B |
| 164 |
mode: u=rw,go= |
| 165 |
owner: root |
| 166 |
group: root |
| 167 |
""" |
| 168 |
|
| 169 |
RETURN = r""" |
| 170 |
cmd: |
| 171 |
description: Command executed to create or resize the file. |
| 172 |
type: str |
| 173 |
returned: when changed or failed |
| 174 |
sample: /usr/bin/dd if=/dev/zero of=/var/swapfile bs=1048576 seek=3072 count=1024 |
| 175 |
|
| 176 |
filesize: |
| 177 |
description: Dictionary of sizes related to the file. |
| 178 |
type: dict |
| 179 |
returned: always |
| 180 |
contains: |
| 181 |
blocks: |
| 182 |
description: Number of blocks in the file. |
| 183 |
type: int |
| 184 |
sample: 500 |
| 185 |
blocksize: |
| 186 |
description: Size of the blocks in bytes. |
| 187 |
type: int |
| 188 |
sample: 1024 |
| 189 |
bytes: |
| 190 |
description: Size of the file, in bytes, as the product of RV(filesize.blocks) and RV(filesize.blocksize). |
| 191 |
type: int |
| 192 |
sample: 512000 |
| 193 |
iec: |
| 194 |
description: Size of the file, in human-readable format, following IEC standard. |
| 195 |
type: str |
| 196 |
sample: 500.0 KiB |
| 197 |
si: |
| 198 |
description: Size of the file, in human-readable format, following SI standard. |
| 199 |
type: str |
| 200 |
sample: 512.0 kB |
| 201 |
|
| 202 |
size_diff: |
| 203 |
description: Difference (positive or negative) between old size and new size, in bytes. |
| 204 |
type: int |
| 205 |
sample: -1234567890 |
| 206 |
returned: always |
| 207 |
|
| 208 |
path: |
| 209 |
description: Realpath of the file if it is a symlink, otherwise the same than module's param. |
| 210 |
type: str |
| 211 |
sample: /var/swap0 |
| 212 |
returned: always |
| 213 |
""" |
| 214 |
|
| 215 |
|
| 216 |
import math |
| 217 |
import os |
| 218 |
import re |
| 219 |
|
| 220 |
from ansible.module_utils.basic import AnsibleModule |
| 221 |
|
| 222 |
# These are the multiplicative suffixes understood (or returned) by dd and |
| 223 |
# others (ls, df, lvresize, lsblk...). |
| 224 |
SIZE_UNITS = dict( |
| 225 |
B=1, |
| 226 |
kB=1000**1, |
| 227 |
KB=1000**1, |
| 228 |
KiB=1024**1, |
| 229 |
K=1024**1, |
| 230 |
k=1024**1, |
| 231 |
MB=1000**2, |
| 232 |
mB=1000**2, |
| 233 |
MiB=1024**2, |
| 234 |
M=1024**2, |
| 235 |
m=1024**2, |
| 236 |
GB=1000**3, |
| 237 |
gB=1000**3, |
| 238 |
GiB=1024**3, |
| 239 |
G=1024**3, |
| 240 |
g=1024**3, |
| 241 |
TB=1000**4, |
| 242 |
tB=1000**4, |
| 243 |
TiB=1024**4, |
| 244 |
T=1024**4, |
| 245 |
t=1024**4, |
| 246 |
PB=1000**5, |
| 247 |
pB=1000**5, |
| 248 |
PiB=1024**5, |
| 249 |
P=1024**5, |
| 250 |
p=1024**5, |
| 251 |
EB=1000**6, |
| 252 |
eB=1000**6, |
| 253 |
EiB=1024**6, |
| 254 |
E=1024**6, |
| 255 |
e=1024**6, |
| 256 |
ZB=1000**7, |
| 257 |
zB=1000**7, |
| 258 |
ZiB=1024**7, |
| 259 |
Z=1024**7, |
| 260 |
z=1024**7, |
| 261 |
YB=1000**8, |
| 262 |
yB=1000**8, |
| 263 |
YiB=1024**8, |
| 264 |
Y=1024**8, |
| 265 |
y=1024**8, |
| 266 |
) |
| 267 |
|
| 268 |
|
| 269 |
def bytes_to_human(size, iec=False): |
| 270 |
"""Return human-readable size (with SI or IEC suffix) from bytes. This is |
| 271 |
only to populate the returned result of the module, not to handle the |
| 272 |
file itself (we only rely on bytes for that). |
| 273 |
""" |
| 274 |
unit = "B" |
| 275 |
for u, v in SIZE_UNITS.items(): |
| 276 |
if size < v: |
| 277 |
continue |
| 278 |
if iec: |
| 279 |
if "i" not in u or size / v >= 1024: |
| 280 |
continue |
| 281 |
else: |
| 282 |
if v % 5 or size / v >= 1000: |
| 283 |
continue |
| 284 |
unit = u |
| 285 |
|
| 286 |
hsize = round(size / SIZE_UNITS[unit], 2) |
| 287 |
if unit == "B": |
| 288 |
hsize = int(hsize) |
| 289 |
|
| 290 |
unit = re.sub(r"^(.)", lambda m: m.expand(r"\1").upper(), unit) |
| 291 |
if unit == "KB": |
| 292 |
unit = "kB" |
| 293 |
|
| 294 |
return f"{hsize} {unit}" |
| 295 |
|
| 296 |
|
| 297 |
def smart_blocksize(size, unit, product, bsize): |
| 298 |
"""Ensure the total size can be written as blocks*blocksize, with blocks |
| 299 |
and blocksize being integers. |
| 300 |
""" |
| 301 |
if not product % bsize: |
| 302 |
return bsize |
| 303 |
|
| 304 |
# Basically, for a file of 8kB (=8000B), system's block size of 4096 bytes |
| 305 |
# is not usable. The smallest integer number of kB to work with 512B blocks |
| 306 |
# is 64, the nexts are 128, 192, 256, and so on. |
| 307 |
|
| 308 |
unit_size = SIZE_UNITS[unit] |
| 309 |
|
| 310 |
if size == int(size): |
| 311 |
if unit_size > SIZE_UNITS["MiB"]: |
| 312 |
if unit_size % 5: |
| 313 |
return SIZE_UNITS["MiB"] |
| 314 |
return SIZE_UNITS["MB"] |
| 315 |
return unit_size |
| 316 |
|
| 317 |
if unit == "B": |
| 318 |
raise AssertionError("byte is the smallest unit and requires an integer value") |
| 319 |
|
| 320 |
if 0 < product < bsize: |
| 321 |
return product |
| 322 |
|
| 323 |
for bsz in (1024, 1000, 512, 256, 128, 100, 64, 32, 16, 10, 8, 4, 2): |
| 324 |
if not product % bsz: |
| 325 |
return bsz |
| 326 |
return 1 |
| 327 |
|
| 328 |
|
| 329 |
def split_size_unit(string, isint=False): |
| 330 |
"""Split a string between the size value (int or float) and the unit. |
| 331 |
Support optional space(s) between the numeric value and the unit. |
| 332 |
""" |
| 333 |
unit = re.sub(r"(\d|\.)", r"", string).strip() |
| 334 |
value = float(re.sub(unit, r"", string).strip()) |
| 335 |
if isint and unit in ("B", ""): |
| 336 |
if int(value) != value: |
| 337 |
raise AssertionError("invalid blocksize value: bytes require an integer value") |
| 338 |
|
| 339 |
if not unit: |
| 340 |
unit = None |
| 341 |
product = int(round(value)) |
| 342 |
else: |
| 343 |
if unit not in SIZE_UNITS.keys(): |
| 344 |
raise AssertionError( |
| 345 |
f"invalid size unit ({unit}): unit must be one of {', '.join(sorted(SIZE_UNITS, key=SIZE_UNITS.get))}, or none." |
| 346 |
) |
| 347 |
product = int(round(value * SIZE_UNITS[unit])) |
| 348 |
return value, unit, product |
| 349 |
|
| 350 |
|
| 351 |
def size_string(value): |
| 352 |
"""Convert a raw value to a string, but only if it is an integer, a float |
| 353 |
or a string itself. |
| 354 |
""" |
| 355 |
if not isinstance(value, (int, float, str)): |
| 356 |
raise AssertionError(f"invalid value type ({type(value)}): size must be integer, float or string") |
| 357 |
return str(value) |
| 358 |
|
| 359 |
|
| 360 |
def size_spec(args): |
| 361 |
"""Return a dictionary with size specifications, especially the size in |
| 362 |
bytes (after rounding it to an integer number of blocks). |
| 363 |
""" |
| 364 |
blocksize_in_bytes = split_size_unit(args["blocksize"], True)[2] |
| 365 |
if blocksize_in_bytes == 0: |
| 366 |
raise AssertionError("block size cannot be equal to zero") |
| 367 |
|
| 368 |
size_value, size_unit, size_result = split_size_unit(args["size"]) |
| 369 |
if not size_unit: |
| 370 |
blocks = int(math.ceil(size_value)) |
| 371 |
else: |
| 372 |
blocksize_in_bytes = smart_blocksize(size_value, size_unit, size_result, blocksize_in_bytes) |
| 373 |
blocks = int(math.ceil(size_result / blocksize_in_bytes)) |
| 374 |
|
| 375 |
args["size_diff"] = round_bytes = int(blocks * blocksize_in_bytes) |
| 376 |
args["size_spec"] = dict( |
| 377 |
blocks=blocks, |
| 378 |
blocksize=blocksize_in_bytes, |
| 379 |
bytes=round_bytes, |
| 380 |
iec=bytes_to_human(round_bytes, True), |
| 381 |
si=bytes_to_human(round_bytes), |
| 382 |
) |
| 383 |
return args["size_spec"] |
| 384 |
|
| 385 |
|
| 386 |
def current_size(args): |
| 387 |
"""Return the size of the file at the given location if it exists, or None.""" |
| 388 |
path = args["path"] |
| 389 |
if os.path.exists(path): |
| 390 |
if not os.path.isfile(path): |
| 391 |
raise AssertionError(f"{path} exists but is not a regular file") |
| 392 |
args["file_size"] = os.stat(path).st_size |
| 393 |
else: |
| 394 |
args["file_size"] = None |
| 395 |
return args["file_size"] |
| 396 |
|
| 397 |
|
| 398 |
def complete_dd_cmdline(args, dd_cmd): |
| 399 |
"""Compute dd options to grow or truncate a file.""" |
| 400 |
if args["file_size"] == args["size_spec"]["bytes"] and not args["force"]: |
| 401 |
# Nothing to do. |
| 402 |
return list() |
| 403 |
|
| 404 |
bs = args["size_spec"]["blocksize"] |
| 405 |
|
| 406 |
# For sparse files (create, truncate, grow): write count=0 block. |
| 407 |
if args["sparse"]: |
| 408 |
seek = args["size_spec"]["blocks"] |
| 409 |
elif args["force"] or not os.path.exists(args["path"]): # Create file |
| 410 |
seek = 0 |
| 411 |
elif args["size_diff"] < 0: # Truncate file |
| 412 |
seek = args["size_spec"]["blocks"] |
| 413 |
elif args["size_diff"] % bs: # Grow file |
| 414 |
seek = int(args["file_size"] / bs) + 1 |
| 415 |
else: |
| 416 |
seek = int(args["file_size"] / bs) |
| 417 |
|
| 418 |
count = args["size_spec"]["blocks"] - seek |
| 419 |
dd_cmd += [f"bs={bs}", f"seek={seek}", f"count={count}"] |
| 420 |
|
| 421 |
return dd_cmd |
| 422 |
|
| 423 |
|
| 424 |
def main(): |
| 425 |
module = AnsibleModule( |
| 426 |
argument_spec=dict( |
| 427 |
path=dict(type="path", required=True), |
| 428 |
size=dict(type="raw", required=True), |
| 429 |
blocksize=dict(type="raw"), |
| 430 |
source=dict(type="path", default="/dev/zero"), |
| 431 |
sparse=dict(type="bool", default=False), |
| 432 |
force=dict(type="bool", default=False), |
| 433 |
), |
| 434 |
supports_check_mode=True, |
| 435 |
add_file_common_args=True, |
| 436 |
) |
| 437 |
args = dict(**module.params) |
| 438 |
diff = dict(before=dict(), after=dict()) |
| 439 |
|
| 440 |
if args["sparse"] and args["force"]: |
| 441 |
module.fail_json(msg="parameters values are mutually exclusive: force=true|sparse=true") |
| 442 |
if not os.path.exists(os.path.dirname(args["path"])): |
| 443 |
module.fail_json(msg="parent directory of the file must exist prior to run this module") |
| 444 |
if not args["blocksize"]: |
| 445 |
args["blocksize"] = str(os.statvfs(os.path.dirname(args["path"])).f_frsize) |
| 446 |
|
| 447 |
try: |
| 448 |
args["size"] = size_string(args["size"]) |
| 449 |
args["blocksize"] = size_string(args["blocksize"]) |
| 450 |
initial_filesize = current_size(args) |
| 451 |
size_descriptors = size_spec(args) |
| 452 |
except AssertionError as err: |
| 453 |
module.fail_json(msg=f"{err}") |
| 454 |
|
| 455 |
expected_filesize = size_descriptors["bytes"] |
| 456 |
if initial_filesize: |
| 457 |
args["size_diff"] = expected_filesize - initial_filesize |
| 458 |
diff["after"]["size"] = expected_filesize |
| 459 |
diff["before"]["size"] = initial_filesize |
| 460 |
|
| 461 |
result = dict(changed=args["force"], size_diff=args["size_diff"], path=args["path"], filesize=size_descriptors) |
| 462 |
|
| 463 |
dd_bin = module.get_bin_path("dd", True) |
| 464 |
dd_cmd = [dd_bin, f"if={args['source']}", f"of={args['path']}"] |
| 465 |
|
| 466 |
if expected_filesize != initial_filesize or args["force"]: |
| 467 |
result["cmd"] = " ".join(complete_dd_cmdline(args, dd_cmd)) |
| 468 |
if module.check_mode: |
| 469 |
result["changed"] = True |
| 470 |
else: |
| 471 |
result["rc"], dummy, result["stderr"] = module.run_command(dd_cmd) |
| 472 |
|
| 473 |
diff["after"]["size"] = result_filesize = result["size_diff"] = current_size(args) |
| 474 |
if initial_filesize: |
| 475 |
result["size_diff"] = result_filesize - initial_filesize |
| 476 |
if not args["force"]: |
| 477 |
result["changed"] = result_filesize != initial_filesize |
| 478 |
|
| 479 |
if result["rc"]: |
| 480 |
msg = f"dd error while creating file {args['path']} with size {args['size']} from source {args['source']}: see stderr for details" |
| 481 |
module.fail_json(msg=msg, **result) |
| 482 |
if result_filesize != expected_filesize: |
| 483 |
msg = ( |
| 484 |
f"module error while creating file {args['path']} with size {args['size']} " |
| 485 |
f"from source {args['source']}: file is {result_filesize} bytes long" |
| 486 |
) |
| 487 |
module.fail_json(msg=msg, **result) |
| 488 |
|
| 489 |
# dd follows symlinks, and so does this module, while file module doesn't. |
| 490 |
# If we call it, this is to manage file's mode, owner and so on, not the |
| 491 |
# symlink's ones. |
| 492 |
file_params = dict(**module.params) |
| 493 |
if os.path.islink(args["path"]): |
| 494 |
file_params["path"] = result["path"] = os.path.realpath(args["path"]) |
| 495 |
|
| 496 |
if args["file_size"] is not None: |
| 497 |
file_args = module.load_file_common_arguments(file_params) |
| 498 |
result["changed"] = module.set_fs_attributes_if_different(file_args, result["changed"], diff=diff) |
| 499 |
result["diff"] = diff |
| 500 |
|
| 501 |
module.exit_json(**result) |
| 502 |
|
| 503 |
|
| 504 |
if __name__ == "__main__": |
| 505 |
main() |