Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, Jeroen Hoekx <[email protected]>, Alexander Bulimov <[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 author:
11 - Jeroen Hoekx (@jhoekx)
12 - Alexander Bulimov (@abulimov)
13 - Raoul Baudach (@unkaputtbar112)
14 - Ziga Kern (@zigaSRC)
15 module: lvol
16 short_description: Configure LVM logical volumes
17 description:
18 - This module creates, removes or resizes logical volumes.
19 extends_documentation_fragment:
20 - community.general._attributes
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: none
26 options:
27 vg:
28 type: str
29 required: true
30 description:
31 - The volume group this logical volume is part of.
32 lv:
33 type: str
34 description:
35 - The name of the logical volume.
36 size:
37 type: str
38 description:
39 - The size of the logical volume, according to lvcreate(8) C(--size), by default in megabytes or optionally with one
40 of [bBsSkKmMgGtTpPeE] units; or according to lvcreate(8) C(--extents) as a percentage of [VG|PVS|FREE|ORIGIN]; Float
41 values must begin with a digit.
42 - When resizing, apart from specifying an absolute size you may, according to lvextend(8)|lvreduce(8) C(--size), specify
43 the amount to extend the logical volume with the prefix V(+) or the amount to reduce the logical volume by with prefix
44 V(-).
45 - Resizing using V(+) or V(-) was not supported prior to community.general 3.0.0.
46 - Please note that when using V(+), V(-), or percentage of FREE, the module is B(not idempotent).
47 state:
48 type: str
49 description:
50 - Control if the logical volume exists. If V(present) and the volume does not already exist then the O(size) option
51 is required.
52 choices: [absent, present]
53 default: present
54 active:
55 description:
56 - Whether the volume is active and visible to the host.
57 type: bool
58 default: true
59 force:
60 description:
61 - Shrink or remove operations of volumes requires this switch. Ensures that filesystems never get corrupted/destroyed
62 by mistake.
63 type: bool
64 default: false
65 opts:
66 type: str
67 description:
68 - Free-form options to be passed to the lvcreate command.
69 snapshot:
70 type: str
71 description:
72 - The name of a snapshot volume to be configured. When creating a snapshot volume, the O(lv) parameter specifies the
73 origin volume.
74 pvs:
75 type: list
76 elements: str
77 description:
78 - List of physical volumes (for example V(/dev/sda, /dev/sdb)).
79 thinpool:
80 type: str
81 description:
82 - The thin pool volume name. When you want to create a thin provisioned volume, specify a thin pool volume name.
83 shrink:
84 description:
85 - Shrink if current size is higher than size requested.
86 type: bool
87 default: true
88 resizefs:
89 description:
90 - Resize the underlying filesystem together with the logical volume.
91 - Supported for C(ext2), C(ext3), C(ext4), C(reiserfs) and C(XFS) filesystems. Attempts to resize other filesystem types
92 result in failure.
93 type: bool
94 default: false
95 notes:
96 - You must specify lv (when managing the state of logical volumes) or thinpool (when managing a thin provisioned volume).
97 """
98
99 EXAMPLES = r"""
100 - name: Create a logical volume of 512m
101 community.general.lvol:
102 vg: firefly
103 lv: test
104 size: 512
105
106 - name: Create a logical volume of 512m with disks /dev/sda and /dev/sdb
107 community.general.lvol:
108 vg: firefly
109 lv: test
110 size: 512
111 pvs:
112 - /dev/sda
113 - /dev/sdb
114
115 - name: Create cache pool logical volume
116 community.general.lvol:
117 vg: firefly
118 lv: lvcache
119 size: 512m
120 opts: --type cache-pool
121
122 - name: Create a logical volume of 512g.
123 community.general.lvol:
124 vg: firefly
125 lv: test
126 size: 512g
127
128 - name: Create a logical volume the size of all remaining space in the volume group
129 community.general.lvol:
130 vg: firefly
131 lv: test
132 size: 100%FREE
133
134 - name: Create a logical volume with special options
135 community.general.lvol:
136 vg: firefly
137 lv: test
138 size: 512g
139 opts: -r 16
140
141 - name: Extend the logical volume to 1024m.
142 community.general.lvol:
143 vg: firefly
144 lv: test
145 size: 1024
146
147 - name: Extend the logical volume to consume all remaining space in the volume group
148 community.general.lvol:
149 vg: firefly
150 lv: test
151 size: +100%FREE
152
153 - name: Extend the logical volume by given space
154 community.general.lvol:
155 vg: firefly
156 lv: test
157 size: +512M
158
159 - name: Extend the logical volume to take all remaining space of the PVs and resize the underlying filesystem
160 community.general.lvol:
161 vg: firefly
162 lv: test
163 size: 100%PVS
164 resizefs: true
165
166 - name: Resize the logical volume to % of VG
167 community.general.lvol:
168 vg: firefly
169 lv: test
170 size: 80%VG
171 force: true
172
173 - name: Reduce the logical volume to 512m
174 community.general.lvol:
175 vg: firefly
176 lv: test
177 size: 512
178 force: true
179
180 - name: Reduce the logical volume by given space
181 community.general.lvol:
182 vg: firefly
183 lv: test
184 size: -512M
185 force: true
186
187 - name: Set the logical volume to 512m and do not try to shrink if size is lower than current one
188 community.general.lvol:
189 vg: firefly
190 lv: test
191 size: 512
192 shrink: false
193
194 - name: Remove the logical volume.
195 community.general.lvol:
196 vg: firefly
197 lv: test
198 state: absent
199 force: true
200
201 - name: Create a snapshot volume of the test logical volume.
202 community.general.lvol:
203 vg: firefly
204 lv: test
205 snapshot: snap1
206 size: 100m
207
208 - name: Deactivate a logical volume
209 community.general.lvol:
210 vg: firefly
211 lv: test
212 active: false
213
214 - name: Create a deactivated logical volume
215 community.general.lvol:
216 vg: firefly
217 lv: test
218 size: 512g
219 active: false
220
221 - name: Create a thin pool of 512g
222 community.general.lvol:
223 vg: firefly
224 thinpool: testpool
225 size: 512g
226
227 - name: Create a thin volume of 128g
228 community.general.lvol:
229 vg: firefly
230 lv: test
231 thinpool: testpool
232 size: 128g
233 """
234
235 import re
236 import shlex
237
238 from ansible.module_utils.basic import AnsibleModule
239
240 from ansible_collections.community.general.plugins.module_utils._lvm import (
241 lvchange_runner,
242 lvcreate_runner,
243 lvextend_runner,
244 lvreduce_runner,
245 lvremove_runner,
246 lvs_runner,
247 vgs_runner,
248 )
249
250
251 def mkversion(major, minor, patch):
252 return (1000 * 1000 * int(major)) + (1000 * int(minor)) + int(patch)
253
254
255 def parse_lvs(data):
256 lvs = []
257 for line in data.splitlines():
258 parts = line.strip().split(";")
259 lvs.append(
260 {
261 "name": parts[0].replace("[", "").replace("]", ""),
262 "size": float(parts[1]),
263 "active": (parts[2][4] == "a"),
264 "thinpool": (parts[2][0] == "t"),
265 "thinvol": (parts[2][0] == "V"),
266 }
267 )
268 return lvs
269
270
271 def parse_vgs(data):
272 vgs = []
273 for line in data.splitlines():
274 parts = line.strip().split(";")
275 vgs.append({"name": parts[0], "size": float(parts[1]), "free": float(parts[2]), "ext_size": float(parts[3])})
276 return vgs
277
278
279 def get_lvm_version(module):
280 ver_cmd = module.get_bin_path("lvm", required=True)
281 rc, out, err = module.run_command([ver_cmd, "version"])
282 if rc != 0:
283 return None
284 m = re.search(r"LVM version:\s+(\d+)\.(\d+)\.(\d+)", out)
285 if not m:
286 return None
287 return mkversion(m.group(1), m.group(2), m.group(3))
288
289
290 def _run_resize(module, is_extend, lvextend, lvreduce, size_opt, size_value, resizefs, lv_name, pvs):
291 size_key = f"size_{size_opt}"
292 if is_extend:
293 with lvextend(f"test resizefs {size_key} lv pvs") as ctx:
294 return ctx.run(test=module.check_mode, resizefs=resizefs, **{size_key: size_value}, lv=[lv_name], pvs=pvs)
295 else:
296 with lvreduce(f"test force resizefs {size_key} lv pvs") as ctx:
297 return ctx.run(
298 test=module.check_mode, force=True, resizefs=resizefs, **{size_key: size_value}, lv=[lv_name], pvs=pvs
299 )
300
301
302 def main():
303 module = AnsibleModule(
304 argument_spec=dict(
305 vg=dict(type="str", required=True),
306 lv=dict(type="str"),
307 size=dict(type="str"),
308 opts=dict(type="str"),
309 state=dict(type="str", default="present", choices=["absent", "present"]),
310 force=dict(type="bool", default=False),
311 shrink=dict(type="bool", default=True),
312 active=dict(type="bool", default=True),
313 snapshot=dict(type="str"),
314 pvs=dict(type="list", elements="str"),
315 resizefs=dict(type="bool", default=False),
316 thinpool=dict(type="str"),
317 ),
318 supports_check_mode=True,
319 required_one_of=(["lv", "thinpool"],),
320 )
321
322 # Determine if the "--yes" option should be used
323 version_found = get_lvm_version(module)
324 if version_found is None:
325 module.fail_json(msg="Failed to get LVM version number")
326 version_yesopt = mkversion(2, 2, 99) # First LVM with the "--yes" option
327 use_yes = version_found >= version_yesopt
328
329 vg = module.params["vg"]
330 lv = module.params["lv"]
331 size = module.params["size"]
332 opts = shlex.split(module.params["opts"] or "")
333 state = module.params["state"]
334 force = module.boolean(module.params["force"])
335 shrink = module.boolean(module.params["shrink"])
336 active = module.boolean(module.params["active"])
337 resizefs = module.boolean(module.params["resizefs"])
338 thinpool = module.params["thinpool"]
339 size_opt = "L"
340 size_unit = "m"
341 size_operator = None
342 snapshot = module.params["snapshot"]
343 pvs = module.params["pvs"] or []
344
345 if size:
346 # LVEXTEND(8)/LVREDUCE(8) -l, -L options: Check for relative value for resizing
347 if size.startswith("+"):
348 size_operator = "+"
349 size = size[1:]
350 elif size.startswith("-"):
351 size_operator = "-"
352 size = size[1:]
353 # LVCREATE(8) does not support [+-]
354
355 # LVCREATE(8)/LVEXTEND(8)/LVREDUCE(8) -l --extents option with percentage
356 if "%" in size:
357 size_parts = size.split("%", 1)
358 size_percent = int(size_parts[0])
359 if size_percent > 100:
360 module.fail_json(msg="Size percentage cannot be larger than 100%")
361 size_whole = size_parts[1]
362 if size_whole == "ORIGIN" and snapshot is None:
363 module.fail_json(msg="Percentage of ORIGIN supported only for snapshot volumes")
364 elif size_whole not in ["VG", "PVS", "FREE", "ORIGIN"]:
365 module.fail_json(msg="Specify extents as a percentage of VG|PVS|FREE|ORIGIN")
366 size_opt = "l"
367 size_unit = ""
368
369 # LVCREATE(8)/LVEXTEND(8)/LVREDUCE(8) -L --size option unit
370 if "%" not in size:
371 if size[-1].lower() in "bskmgtpe":
372 size_unit = size[-1]
373 size = size[0:-1]
374
375 try:
376 float(size)
377 if not size[0].isdigit():
378 raise ValueError()
379 except ValueError:
380 module.fail_json(msg=f"Bad size specification of '{size}'")
381
382 # when no unit, megabytes by default
383 if size_opt == "l":
384 unit = "m"
385 else:
386 unit = size_unit
387
388 vgs = vgs_runner(module)
389 lvs = lvs_runner(module)
390 lvcreate = lvcreate_runner(module)
391 lvremove = lvremove_runner(module)
392 lvextend = lvextend_runner(module)
393 lvreduce = lvreduce_runner(module)
394 lvchange = lvchange_runner(module)
395
396 # Get information on volume group requested
397 with vgs("noheadings nosuffix units separator fields vg") as ctx:
398 rc, current_vgs, err = ctx.run(units=unit.lower(), separator=";", fields="vg_name,size,free,vg_extent_size")
399
400 if rc != 0:
401 if state == "absent":
402 module.exit_json(changed=False, stdout=f"Volume group {vg} does not exist.")
403 else:
404 module.fail_json(msg=f"Volume group {vg} does not exist.", rc=rc, err=err)
405
406 vg_data = parse_vgs(current_vgs)
407 this_vg = vg_data[0]
408
409 # Get information on logical volume requested
410 with lvs("all noheadings nosuffix units separator fields vg") as ctx:
411 rc, current_lvs, err = ctx.run(units=unit.lower(), separator=";", fields="lv_name,size,lv_attr")
412
413 if rc != 0:
414 if state == "absent":
415 module.exit_json(changed=False, stdout=f"Volume group {vg} does not exist.")
416 else:
417 module.fail_json(msg=f"Volume group {vg} does not exist.", rc=rc, err=err)
418
419 changed = False
420
421 lv_data = parse_lvs(current_lvs)
422
423 if snapshot:
424 # Check snapshot pre-conditions
425 for test_lv in lv_data:
426 if test_lv["name"] == lv or test_lv["name"] == thinpool:
427 if not test_lv["thinpool"] and not thinpool:
428 break
429 else:
430 module.fail_json(msg="Snapshots of thin pool LVs are not supported.")
431 else:
432 module.fail_json(msg=f"Snapshot origin LV {lv} does not exist in volume group {vg}.")
433 check_lv = snapshot
434 elif thinpool:
435 if lv:
436 # Check thin volume pre-conditions
437 for test_lv in lv_data:
438 if test_lv["name"] == thinpool:
439 break
440 else:
441 module.fail_json(msg=f"Thin pool LV {thinpool} does not exist in volume group {vg}.")
442 check_lv = lv
443 else:
444 check_lv = thinpool
445 else:
446 check_lv = lv
447
448 for test_lv in lv_data:
449 if test_lv["name"] in (check_lv, check_lv.rsplit("/", 1)[-1]):
450 this_lv = test_lv
451 break
452 else:
453 this_lv = None
454
455 msg = ""
456 if this_lv is None:
457 if state == "present":
458 if size_operator is not None:
459 if size_operator == "-" or (size_whole not in ["VG", "PVS", "FREE", "ORIGIN", None]):
460 module.fail_json(msg=f"Bad size specification of '{size_operator}{size}' for creating LV")
461 # Require size argument except for snapshot of thin volumes
462 if (lv or thinpool) and not size:
463 for test_lv in lv_data:
464 if test_lv["name"] == lv and test_lv["thinvol"] and snapshot:
465 break
466 else:
467 module.fail_json(msg="No size given.")
468
469 # create LV
470 size_value = f"{size}{size_unit}"
471 if snapshot is not None:
472 if size_opt == "l":
473 with lvcreate("test yes size_l is_snapshot lv opts vg") as ctx:
474 rc, dummy, err = ctx.run(
475 test=module.check_mode,
476 yes=use_yes,
477 size_l=size_value if size else None,
478 is_snapshot=True,
479 lv=snapshot,
480 opts=opts,
481 vg=[f"{vg}/{lv}"],
482 )
483 else:
484 with lvcreate("test yes size_L is_snapshot lv opts vg") as ctx:
485 rc, dummy, err = ctx.run(
486 test=module.check_mode,
487 yes=use_yes,
488 size_L=size_value if size else None,
489 is_snapshot=True,
490 lv=snapshot,
491 opts=opts,
492 vg=[f"{vg}/{lv}"],
493 )
494 elif thinpool:
495 if lv:
496 if size_opt == "l":
497 module.fail_json(changed=False, msg="Thin volume sizing with percentage not supported.")
498 with lvcreate("test yes lv size_V opts thin vg") as ctx:
499 rc, dummy, err = ctx.run(
500 test=module.check_mode,
501 yes=use_yes,
502 lv=lv,
503 size_V=size_value,
504 opts=opts,
505 vg=[f"{vg}/{thinpool}"],
506 )
507 else:
508 if size_opt == "l":
509 with lvcreate("test yes size_l opts thin vg pvs") as ctx:
510 rc, dummy, err = ctx.run(
511 test=module.check_mode,
512 yes=use_yes,
513 size_l=size_value,
514 opts=opts,
515 vg=[f"{vg}/{thinpool}"],
516 pvs=pvs,
517 )
518 else:
519 with lvcreate("test yes size_L opts thin vg pvs") as ctx:
520 rc, dummy, err = ctx.run(
521 test=module.check_mode,
522 yes=use_yes,
523 size_L=size_value,
524 opts=opts,
525 vg=[f"{vg}/{thinpool}"],
526 pvs=pvs,
527 )
528 else:
529 if size_opt == "l":
530 with lvcreate("test yes lv size_l opts vg pvs") as ctx:
531 rc, dummy, err = ctx.run(
532 test=module.check_mode,
533 yes=use_yes,
534 lv=lv,
535 size_l=size_value,
536 opts=opts,
537 pvs=pvs,
538 )
539 else:
540 with lvcreate("test yes lv size_L opts vg pvs") as ctx:
541 rc, dummy, err = ctx.run(
542 test=module.check_mode,
543 yes=use_yes,
544 lv=lv,
545 size_L=size_value,
546 opts=opts,
547 pvs=pvs,
548 )
549 if rc == 0:
550 changed = True
551 else:
552 module.fail_json(msg=f"Creating logical volume '{lv}' failed", rc=rc, err=err)
553 else:
554 if state == "absent":
555 # remove LV
556 if not force:
557 module.fail_json(msg=f"Sorry, no removal of logical volume {this_lv['name']} without force=true.")
558 with lvremove("test force lv") as ctx:
559 rc, dummy, err = ctx.run(test=module.check_mode, force=True, lv=[f"{vg}/{this_lv['name']}"])
560 if rc == 0:
561 module.exit_json(changed=True)
562 else:
563 module.fail_json(msg=f"Failed to remove logical volume {lv}", rc=rc, err=err)
564
565 elif not size:
566 pass
567
568 elif size_opt == "l":
569 # Resize LV based on % value
570 tool = None
571 size_free = this_vg["free"]
572 if size_whole == "VG" or size_whole == "PVS":
573 size_requested = size_percent * this_vg["size"] / 100
574 else: # size_whole == 'FREE':
575 size_requested = size_percent * this_vg["free"] / 100
576
577 if size_operator == "+":
578 size_requested += this_lv["size"]
579 elif size_operator == "-":
580 size_requested = this_lv["size"] - size_requested
581
582 # According to latest documentation (LVM2-2.03.11) all tools round down
583 size_requested -= size_requested % this_vg["ext_size"]
584
585 if this_lv["size"] < size_requested:
586 if (size_free > 0) and (size_free >= (size_requested - this_lv["size"])):
587 tool = "extend"
588 else:
589 module.fail_json(
590 msg=(
591 f"Logical Volume {this_lv['name']} could not be extended. Not enough free space left "
592 f"({size_requested - this_lv['size']}{unit} required / {size_free}{unit} available)"
593 )
594 )
595 elif shrink and this_lv["size"] > size_requested + this_vg["ext_size"]: # more than an extent too large
596 if size_requested < 1:
597 module.fail_json(msg=f"Sorry, no shrinking of {this_lv['name']} to 0 permitted.")
598 elif not force:
599 module.fail_json(msg=f"Sorry, no shrinking of {this_lv['name']} without force=true")
600 else:
601 tool = "reduce"
602
603 if tool:
604 size_value = f"{size_operator or ''}{size}{size_unit}"
605 lv_name = f"{vg}/{this_lv['name']}"
606 rc, out, err = _run_resize(
607 module, tool == "extend", lvextend, lvreduce, size_opt, size_value, resizefs, lv_name, pvs
608 )
609 if "Reached maximum COW size" in out:
610 module.fail_json(msg=f"Unable to resize {lv} to {size}{size_unit}", rc=rc, err=err, out=out)
611 elif rc == 0:
612 changed = True
613 msg = f"Volume {this_lv['name']} resized to {size_requested}{unit}"
614 elif "matches existing size" in err or "matches existing size" in out:
615 module.exit_json(changed=False, vg=vg, lv=this_lv["name"], size=this_lv["size"])
616 elif "not larger than existing size" in err or "not larger than existing size" in out:
617 module.exit_json(
618 changed=False,
619 vg=vg,
620 lv=this_lv["name"],
621 size=this_lv["size"],
622 msg="Original size is larger than requested size",
623 err=err,
624 )
625 else:
626 module.fail_json(msg=f"Unable to resize {lv} to {size}{size_unit}", rc=rc, err=err)
627
628 else:
629 # resize LV based on absolute values
630 tool = None
631 if float(size) > this_lv["size"] or size_operator == "+":
632 tool = "extend"
633 elif shrink and float(size) < this_lv["size"] or size_operator == "-":
634 if float(size) == 0:
635 module.fail_json(msg=f"Sorry, no shrinking of {this_lv['name']} to 0 permitted.")
636 if not force:
637 module.fail_json(msg=f"Sorry, no shrinking of {this_lv['name']} without force=true.")
638 else:
639 tool = "reduce"
640
641 if tool:
642 size_value = f"{size_operator or ''}{size}{size_unit}"
643 lv_name = f"{vg}/{this_lv['name']}"
644 rc, out, err = _run_resize(
645 module, tool == "extend", lvextend, lvreduce, size_opt, size_value, resizefs, lv_name, pvs
646 )
647 if "Reached maximum COW size" in out:
648 module.fail_json(msg=f"Unable to resize {lv} to {size}{size_unit}", rc=rc, err=err, out=out)
649 elif rc == 0:
650 changed = True
651 elif "matches existing size" in err or "matches existing size" in out:
652 module.exit_json(changed=False, vg=vg, lv=this_lv["name"], size=this_lv["size"])
653 elif "not larger than existing size" in err or "not larger than existing size" in out:
654 module.exit_json(
655 changed=False,
656 vg=vg,
657 lv=this_lv["name"],
658 size=this_lv["size"],
659 msg="Original size is larger than requested size",
660 err=err,
661 )
662 else:
663 module.fail_json(msg=f"Unable to resize {lv} to {size}{size_unit}", rc=rc, err=err)
664
665 if this_lv is not None:
666 if active:
667 with lvchange("active lv") as ctx:
668 rc, dummy, err = ctx.run(active=True, lv=[f"{vg}/{this_lv['name']}"])
669 if rc == 0:
670 module.exit_json(
671 changed=(not this_lv["active"]) or changed, vg=vg, lv=this_lv["name"], size=this_lv["size"]
672 )
673 else:
674 module.fail_json(msg=f"Failed to activate logical volume {lv}", rc=rc, err=err)
675 else:
676 with lvchange("active lv") as ctx:
677 rc, dummy, err = ctx.run(active=False, lv=[f"{vg}/{this_lv['name']}"])
678 if rc == 0:
679 module.exit_json(changed=this_lv["active"] or changed, vg=vg, lv=this_lv["name"], size=this_lv["size"])
680 else:
681 module.fail_json(msg=f"Failed to deactivate logical volume {lv}", rc=rc, err=err)
682
683 module.exit_json(changed=changed, msg=msg)
684
685
686 if __name__ == "__main__":
687 main()