Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, Alexander Bulimov <[email protected]>
4 # Based on lvol module by Jeroen Hoekx <[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 module: lvg
14 short_description: Configure LVM volume groups
15 description:
16 - This module creates, removes or resizes volume groups.
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: none
24 options:
25 vg:
26 description:
27 - The name of the volume group.
28 type: str
29 required: true
30 pvs:
31 description:
32 - List of comma-separated devices to use as physical devices in this volume group.
33 - Required when creating or resizing volume group.
34 - The module runs C(pvcreate) if needed.
35 - This parameter defines the B(desired state) of the physical volumes in the volume group.
36 When the volume group already exists, physical volumes not listed here are removed from it by default.
37 To add physical volumes without removing existing unlisted ones, set O(remove_extra_pvs=false).
38 type: list
39 elements: str
40 pesize:
41 description:
42 - The size of the physical extent. O(pesize) must be a power of 2 of at least 1 sector (where the sector size is the
43 largest sector size of the PVs currently used in the VG), or at least 128KiB.
44 - O(pesize) can be optionally suffixed by a UNIT (k/K/m/M/g/G), default unit is megabyte.
45 type: str
46 default: "4"
47 pv_options:
48 description:
49 - Additional options to pass to C(pvcreate) when creating the volume group.
50 type: str
51 default: ''
52 pvresize:
53 description:
54 - If V(true), resize the physical volume to the maximum available size.
55 type: bool
56 default: false
57 version_added: '0.2.0'
58 vg_options:
59 description:
60 - Additional options to pass to C(vgcreate) when creating the volume group.
61 type: str
62 default: ''
63 state:
64 description:
65 - Control if the volume group exists and its state.
66 - The states V(active) and V(inactive) implies V(present) state. Added in 7.1.0.
67 - If V(active) or V(inactive), the module manages the VG's logical volumes current state. The module also handles the
68 VG's autoactivation state if supported unless when creating a volume group and the autoactivation option specified
69 in O(vg_options).
70 type: str
71 choices: [absent, present, active, inactive]
72 default: present
73 force:
74 description:
75 - If V(true), allows to remove volume group with logical volumes.
76 type: bool
77 default: false
78 reset_vg_uuid:
79 description:
80 - Whether the volume group's UUID is regenerated.
81 - This is B(not idempotent). Specifying this parameter always results in a change.
82 type: bool
83 default: false
84 version_added: 7.1.0
85 reset_pv_uuid:
86 description:
87 - Whether the volume group's physical volumes' UUIDs are regenerated.
88 - This is B(not idempotent). Specifying this parameter always results in a change.
89 type: bool
90 default: false
91 version_added: 7.1.0
92 remove_extra_pvs:
93 description:
94 - Remove physical volumes from the volume group which are not in O(pvs).
95 type: bool
96 default: true
97 version_added: 10.4.0
98 seealso:
99 - module: community.general.filesystem
100 - module: community.general.lvol
101 - module: community.general.parted
102 notes:
103 - This module does not modify PE size for already present volume group.
104 """
105
106 EXAMPLES = r"""
107 - name: Create a volume group on top of /dev/sda1 with physical extent size = 32MB
108 community.general.lvg:
109 vg: vg.services
110 pvs: /dev/sda1
111 pesize: 32
112
113 - name: Create a volume group on top of /dev/sdb with physical extent size = 128KiB
114 community.general.lvg:
115 vg: vg.services
116 pvs: /dev/sdb
117 pesize: 128K
118
119 # If, for example, we already have VG vg.services on top of /dev/sdb1,
120 # this VG will be extended by /dev/sdc5. Or if vg.services was created on
121 # top of /dev/sda5, we first extend it with /dev/sdb1 and /dev/sdc5,
122 # and then reduce by /dev/sda5.
123 - name: Create or resize a volume group on top of /dev/sdb1 and /dev/sdc5.
124 community.general.lvg:
125 vg: vg.services
126 pvs:
127 - /dev/sdb1
128 - /dev/sdc5
129
130 - name: Remove a volume group with name vg.services
131 community.general.lvg:
132 vg: vg.services
133 state: absent
134
135 - name: Create a volume group on top of /dev/sda3 and resize the volume group /dev/sda3 to the maximum possible
136 community.general.lvg:
137 vg: resizableVG
138 pvs: /dev/sda3
139 pvresize: true
140
141 - name: Deactivate a volume group
142 community.general.lvg:
143 state: inactive
144 vg: vg.services
145
146 - name: Activate a volume group
147 community.general.lvg:
148 state: active
149 vg: vg.services
150
151 - name: Add new PVs to volume group without removing existing ones
152 community.general.lvg:
153 vg: vg.services
154 pvs: /dev/sdb1,/dev/sdc1
155 remove_extra_pvs: false
156 state: present
157
158 - name: Reset a volume group UUID
159 community.general.lvg:
160 state: inactive
161 vg: vg.services
162 reset_vg_uuid: true
163
164 - name: Reset both volume group and pv UUID
165 community.general.lvg:
166 state: inactive
167 vg: vg.services
168 pvs:
169 - /dev/sdb1
170 - /dev/sdc5
171 reset_vg_uuid: true
172 reset_pv_uuid: true
173 """
174
175 import itertools
176 import os
177 import shlex
178
179 from ansible.module_utils.basic import AnsibleModule
180
181 from ansible_collections.community.general.plugins.module_utils._lvm import (
182 pvchange_runner,
183 pvcreate_runner,
184 pvresize_runner,
185 pvs_runner,
186 vgchange_runner,
187 vgcreate_runner,
188 vgextend_runner,
189 vgreduce_runner,
190 vgremove_runner,
191 vgs_runner,
192 )
193
194 VG_AUTOACTIVATION_OPT = "--setautoactivation"
195
196
197 def parse_vgs(data):
198 vgs = []
199 for line in data.splitlines():
200 parts = line.strip().split(";")
201 vgs.append(
202 {
203 "name": parts[0],
204 "pv_count": int(parts[1]),
205 "lv_count": int(parts[2]),
206 }
207 )
208 return vgs
209
210
211 def find_mapper_device_name(module, dm_device):
212 dmsetup_cmd = module.get_bin_path("dmsetup", True)
213 mapper_prefix = "/dev/mapper/"
214 rc, dm_name, err = module.run_command([dmsetup_cmd, "info", "-C", "--noheadings", "-o", "name", dm_device])
215 if rc != 0:
216 module.fail_json(msg="Failed executing dmsetup command.", rc=rc, err=err)
217 mapper_device = mapper_prefix + dm_name.rstrip()
218 return mapper_device
219
220
221 def parse_pvs(module, data):
222 pvs = []
223 dm_prefix = "/dev/dm-"
224 for line in data.splitlines():
225 parts = line.strip().split(";")
226 if parts[0].startswith(dm_prefix):
227 parts[0] = find_mapper_device_name(module, parts[0])
228 pvs.append(
229 {
230 "name": parts[0],
231 "vg_name": parts[1],
232 }
233 )
234 return pvs
235
236
237 def find_vg(module, vg, vgs):
238 if not vg:
239 return None
240 with vgs("noheadings separator fields", check_rc=True) as ctx:
241 dummy, current_vgs, dummy = ctx.run(separator=";", fields="vg_name,pv_count,lv_count")
242 return next((test_vg for test_vg in parse_vgs(current_vgs) if test_vg["name"] == vg), None)
243
244
245 def is_autoactivation_supported(module, vg_cmd):
246 dummy, vgchange_opts, dummy = module.run_command([vg_cmd, "--help"], check_rc=True)
247 return VG_AUTOACTIVATION_OPT in vgchange_opts
248
249
250 def activate_vg(module, vg, active, vgs, vgchange):
251 changed = False
252 vgchange_cmd = module.get_bin_path("vgchange", True)
253 vgs_fields = ["lv_attr"]
254
255 autoactivation_enabled = False
256 autoactivation_supported = is_autoactivation_supported(module=module, vg_cmd=vgchange_cmd)
257
258 if autoactivation_supported:
259 vgs_fields.append("autoactivation")
260
261 with vgs("noheadings separator fields vg", check_rc=True) as ctx:
262 dummy, current_vg_lv_states, dummy = ctx.run(separator=";", fields=",".join(vgs_fields), vg=[vg])
263
264 lv_active_count = 0
265 lv_inactive_count = 0
266
267 for line in current_vg_lv_states.splitlines():
268 parts = line.strip().split(";")
269 if parts[0][4] == "a":
270 lv_active_count += 1
271 else:
272 lv_inactive_count += 1
273 if autoactivation_supported:
274 autoactivation_enabled = autoactivation_enabled or parts[1] == "enabled"
275
276 activate_flag = None
277 if active and lv_inactive_count > 0:
278 activate_flag = True
279 elif not active and lv_active_count > 0:
280 activate_flag = False
281
282 # Extra logic necessary because vgchange returns error when autoactivation is already set
283 if autoactivation_supported:
284 if active and not autoactivation_enabled:
285 if module.check_mode:
286 changed = True
287 else:
288 vgchange("setautoactivation vg", check_rc=True).run(setautoactivation=True, vg=[vg])
289 changed = True
290 elif not active and autoactivation_enabled:
291 if module.check_mode:
292 changed = True
293 else:
294 vgchange("setautoactivation vg", check_rc=True).run(setautoactivation=False, vg=[vg])
295 changed = True
296
297 if activate_flag is not None:
298 if module.check_mode:
299 changed = True
300 else:
301 vgchange("activate vg", check_rc=True).run(activate=activate_flag, vg=[vg])
302 changed = True
303
304 return changed
305
306
307 def get_vgcreate_setautoactivation(module, state, vg_options_str):
308 if state not in ["active", "inactive"]:
309 return None
310 if VG_AUTOACTIVATION_OPT in vg_options_str:
311 return None
312 vgcreate_cmd = module.get_bin_path("vgcreate", True)
313 if not is_autoactivation_supported(module=module, vg_cmd=vgcreate_cmd):
314 return None
315 return state == "active"
316
317
318 def get_pv_values_for_resize(module, device, pvs):
319 with pvs("noheadings nosuffix units separator fields devices", check_rc=True) as ctx:
320 dummy, pv_values, dummy = ctx.run(
321 units="b", separator=";", fields="dev_size,pv_size,pe_start,vg_extent_size", devices=[device]
322 )
323
324 values = pv_values.strip().split(";")
325 dev_size = int(values[0])
326 pv_size = int(values[1])
327 pe_start = int(values[2])
328 vg_extent_size = int(values[3])
329
330 return (dev_size, pv_size, pe_start, vg_extent_size)
331
332
333 def resize_pv(module, device, pvs, pvresize):
334 changed = False
335 dev_size, pv_size, pe_start, vg_extent_size = get_pv_values_for_resize(module=module, device=device, pvs=pvs)
336 if (dev_size - (pe_start + pv_size)) > vg_extent_size:
337 if module.check_mode:
338 changed = True
339 else:
340 # If there is a missing pv on the machine, versions of pvresize rc indicates failure.
341 with pvresize("device") as ctx:
342 rc, out, err = ctx.run(device=[device])
343 dummy, new_pv_size, dummy, dummy = get_pv_values_for_resize(module=module, device=device, pvs=pvs)
344 if pv_size == new_pv_size:
345 module.fail_json(msg="Failed executing pvresize command.", rc=rc, err=err, out=out)
346 else:
347 changed = True
348
349 return changed
350
351
352 def reset_uuid_pv(module, device, pvs, pvchange):
353 changed = False
354 with pvs("noheadings fields devices", check_rc=True) as ctx:
355 dummy, orig_uuid, dummy = ctx.run(fields="uuid", devices=[device])
356
357 if module.check_mode:
358 changed = True
359 else:
360 # If there is a missing pv on the machine, pvchange rc indicates failure.
361 with pvchange("uuid device") as ctx:
362 pvchange_rc, pvchange_out, pvchange_err = ctx.run(uuid=True, device=[device])
363 with pvs("noheadings fields devices", check_rc=True) as ctx:
364 dummy, new_uuid, dummy = ctx.run(fields="uuid", devices=[device])
365 if orig_uuid.strip() == new_uuid.strip():
366 module.fail_json(
367 msg=f"PV ({device}) UUID change failed", rc=pvchange_rc, err=pvchange_err, out=pvchange_out
368 )
369 else:
370 changed = True
371
372 return changed
373
374
375 def reset_uuid_vg(module, vg, vgchange):
376 changed = False
377 if module.check_mode:
378 changed = True
379 else:
380 vgchange("uuid vg", check_rc=True).run(uuid=True, vg=[vg])
381 changed = True
382
383 return changed
384
385
386 def main():
387 module = AnsibleModule(
388 argument_spec=dict(
389 vg=dict(type="str", required=True),
390 pvs=dict(type="list", elements="str"),
391 pesize=dict(type="str", default="4"),
392 pv_options=dict(type="str", default=""),
393 pvresize=dict(type="bool", default=False),
394 vg_options=dict(type="str", default=""),
395 state=dict(type="str", default="present", choices=["absent", "present", "active", "inactive"]),
396 force=dict(type="bool", default=False),
397 reset_vg_uuid=dict(type="bool", default=False),
398 reset_pv_uuid=dict(type="bool", default=False),
399 remove_extra_pvs=dict(type="bool", default=True),
400 ),
401 required_if=[
402 ["reset_pv_uuid", True, ["pvs"]],
403 ],
404 supports_check_mode=True,
405 )
406
407 vg = module.params["vg"]
408 state = module.params["state"]
409 force = module.boolean(module.params["force"])
410 do_pvresize = module.boolean(module.params["pvresize"])
411 pvoptions = shlex.split(module.params["pv_options"])
412 reset_vg_uuid = module.boolean(module.params["reset_vg_uuid"])
413 reset_pv_uuid = module.boolean(module.params["reset_pv_uuid"])
414 remove_extra_pvs = module.boolean(module.params["remove_extra_pvs"])
415
416 pvs = pvs_runner(module)
417 pvcreate = pvcreate_runner(module)
418 pvchange = pvchange_runner(module)
419 pvresize = pvresize_runner(module)
420 vgs = vgs_runner(module)
421 vgcreate = vgcreate_runner(module)
422 vgchange = vgchange_runner(module)
423 vgextend = vgextend_runner(module)
424 vgreduce = vgreduce_runner(module)
425 vgremove = vgremove_runner(module)
426
427 this_vg = find_vg(module=module, vg=vg, vgs=vgs)
428 present_state = state in ["present", "active", "inactive"]
429 pvs_required = present_state and this_vg is None
430 changed = False
431
432 dev_list = []
433 if module.params["pvs"]:
434 dev_list = list(module.params["pvs"])
435 elif pvs_required:
436 module.fail_json(msg="No physical volumes given.")
437
438 # LVM always uses real paths not symlinks so replace symlinks with actual path
439 for idx, dev in enumerate(dev_list):
440 dev_list[idx] = os.path.realpath(dev)
441
442 if present_state:
443 # check given devices
444 for test_dev in dev_list:
445 if not os.path.exists(test_dev):
446 module.fail_json(msg=f"Device {test_dev} not found.")
447
448 # get pv list
449 if dev_list:
450 pvs_filter_pv_name = " || ".join(f"pv_name = {x}" for x in itertools.chain(dev_list, module.params["pvs"]))
451 pvs_filter_vg_name = f"vg_name = {vg}"
452 pvs_select = f"{pvs_filter_pv_name} || {pvs_filter_vg_name}"
453 else:
454 pvs_select = None
455
456 with pvs("noheadings separator fields select", check_rc=True) as ctx:
457 dummy, current_pvs, dummy = ctx.run(separator=";", fields="pv_name,vg_name", select=pvs_select)
458
459 # check pv for devices
460 pv_list = parse_pvs(module, current_pvs)
461 used_pvs = [pv for pv in pv_list if pv["name"] in dev_list and pv["vg_name"] and pv["vg_name"] != vg]
462 if used_pvs:
463 module.fail_json(msg=f"Device {used_pvs[0]['name']} is already in {used_pvs[0]['vg_name']} volume group.")
464
465 if this_vg is None:
466 if present_state:
467 setautoactivation = get_vgcreate_setautoactivation(
468 module=module, state=state, vg_options_str=module.params["vg_options"]
469 )
470 # create VG
471 if module.check_mode:
472 changed = True
473 else:
474 # create PV
475 for current_dev in dev_list:
476 pvcreate("pv_options force device", check_rc=True).run(
477 pv_options=pvoptions, force=True, device=[current_dev]
478 )
479 changed = True
480 vgcreate("vg_options pesize setautoactivation vg pvs", check_rc=True).run(
481 vg_options=shlex.split(module.params["vg_options"]),
482 setautoactivation=setautoactivation,
483 pvs=dev_list,
484 )
485 changed = True
486 else:
487 if state == "absent":
488 if module.check_mode:
489 module.exit_json(changed=True)
490 else:
491 if this_vg["lv_count"] == 0 or force:
492 # remove VG
493 vgremove("force vg", check_rc=True).run(force=True, vg=[vg])
494 module.exit_json(changed=True)
495 else:
496 module.fail_json(msg=f"Refuse to remove non-empty volume group {vg} without force=true")
497 # activate/deactivate existing VG
498 elif state == "active":
499 changed = activate_vg(module=module, vg=vg, active=True, vgs=vgs, vgchange=vgchange)
500 elif state == "inactive":
501 changed = activate_vg(module=module, vg=vg, active=False, vgs=vgs, vgchange=vgchange)
502
503 # reset VG uuid
504 if reset_vg_uuid:
505 changed = reset_uuid_vg(module=module, vg=vg, vgchange=vgchange) or changed
506
507 # resize VG
508 if dev_list:
509 current_devs = [os.path.realpath(pv["name"]) for pv in pv_list if pv["vg_name"] == vg]
510 devs_to_remove = list(set(current_devs) - set(dev_list))
511 devs_to_add = list(set(dev_list) - set(current_devs))
512
513 if not remove_extra_pvs:
514 devs_to_remove = []
515
516 if current_devs:
517 if present_state:
518 for device in current_devs:
519 if do_pvresize:
520 changed = resize_pv(module=module, device=device, pvs=pvs, pvresize=pvresize) or changed
521 if reset_pv_uuid:
522 changed = reset_uuid_pv(module=module, device=device, pvs=pvs, pvchange=pvchange) or changed
523
524 if devs_to_add or devs_to_remove:
525 if module.check_mode:
526 changed = True
527 else:
528 if devs_to_add:
529 # create PV
530 for current_dev in devs_to_add:
531 pvcreate("pv_options force device", check_rc=True).run(
532 pv_options=pvoptions, force=True, device=[current_dev]
533 )
534 changed = True
535 # add PV to our VG
536 vgextend("vg pvs", check_rc=True).run(vg=[vg], pvs=devs_to_add)
537 changed = True
538
539 # remove some PV from our VG
540 if devs_to_remove:
541 vgreduce("force vg pvs", check_rc=True).run(force=True, vg=[vg], pvs=devs_to_remove)
542 changed = True
543
544 module.exit_json(changed=changed)
545
546
547 if __name__ == "__main__":
548 main()