Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Alain Dejoux <[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 - Alain Dejoux (@adejoux)
12 module: aix_lvol
13 short_description: Configure AIX LVM logical volumes
14 description:
15 - This module creates, removes or resizes AIX logical volumes. Inspired by M(community.general.lvol) module.
16 deprecated:
17 removed_in: 15.0.0
18 why: The module is not actively maintained.
19 alternative: >-
20 Use C(ibm.power_aix.lvol) instead.
21 See U(https://ibm.github.io/ansible-power-aix/modules/lvol.html) for details.
22 extends_documentation_fragment:
23 - community.general._attributes
24 attributes:
25 check_mode:
26 support: full
27 diff_mode:
28 support: none
29 options:
30 vg:
31 description:
32 - The volume group this logical volume is part of.
33 type: str
34 required: true
35 lv:
36 description:
37 - The name of the logical volume.
38 type: str
39 required: true
40 lv_type:
41 description:
42 - The type of the logical volume.
43 type: str
44 default: jfs2
45 size:
46 description:
47 - The size of the logical volume with one of the [MGT] units.
48 type: str
49 copies:
50 description:
51 - The number of copies of the logical volume.
52 - Maximum copies are 3.
53 type: int
54 default: 1
55 policy:
56 description:
57 - Sets the interphysical volume allocation policy.
58 - V(maximum) allocates logical partitions across the maximum number of physical volumes.
59 - V(minimum) allocates logical partitions across the minimum number of physical volumes.
60 type: str
61 choices: [maximum, minimum]
62 default: maximum
63 state:
64 description:
65 - Control if the logical volume exists. If V(present) and the volume does not already exist then the O(size) option
66 is required.
67 type: str
68 choices: [absent, present]
69 default: present
70 opts:
71 description:
72 - Free-form options to be passed to the mklv command.
73 type: str
74 default: ''
75 pvs:
76 description:
77 - A list of physical volumes, for example V([hdisk1, hdisk2]).
78 type: list
79 elements: str
80 default: []
81 """
82
83 EXAMPLES = r"""
84 - name: Create a logical volume of 512M
85 community.general.aix_lvol:
86 vg: testvg
87 lv: testlv
88 size: 512M
89
90 - name: Create a logical volume of 512M with disks hdisk1 and hdisk2
91 community.general.aix_lvol:
92 vg: testvg
93 lv: test2lv
94 size: 512M
95 pvs: [hdisk1, hdisk2]
96
97 - name: Create a logical volume of 512M mirrored
98 community.general.aix_lvol:
99 vg: testvg
100 lv: test3lv
101 size: 512M
102 copies: 2
103
104 - name: Create a logical volume of 1G with a minimum placement policy
105 community.general.aix_lvol:
106 vg: rootvg
107 lv: test4lv
108 size: 1G
109 policy: minimum
110
111 - name: Create a logical volume with special options like mirror pool
112 community.general.aix_lvol:
113 vg: testvg
114 lv: testlv
115 size: 512M
116 opts: -p copy1=poolA -p copy2=poolB
117
118 - name: Extend the logical volume to 1200M
119 community.general.aix_lvol:
120 vg: testvg
121 lv: test4lv
122 size: 1200M
123
124 - name: Remove the logical volume
125 community.general.aix_lvol:
126 vg: testvg
127 lv: testlv
128 state: absent
129 """
130
131 RETURN = r"""
132 msg:
133 type: str
134 description: A friendly message describing the task result.
135 returned: always
136 sample: Logical volume testlv created.
137 """
138
139 import re
140
141 from ansible.module_utils.basic import AnsibleModule
142
143
144 def convert_size(module, size):
145 unit = size[-1].upper()
146 units = ["M", "G", "T"]
147 try:
148 multiplier = 1024 ** units.index(unit)
149 except ValueError:
150 module.fail_json(msg="No valid size unit specified.")
151
152 return int(size[:-1]) * multiplier
153
154
155 def round_ppsize(x, base=16):
156 new_size = int(base * round(float(x) / base))
157 if new_size < x:
158 new_size += base
159 return new_size
160
161
162 def parse_lv(data):
163 name = None
164
165 for line in data.splitlines():
166 match = re.search(r"LOGICAL VOLUME:\s+(\w+)\s+VOLUME GROUP:\s+(\w+)", line)
167 if match is not None:
168 name = match.group(1)
169 vg = match.group(2)
170 continue
171 match = re.search(r"LPs:\s+(\d+).*PPs", line)
172 if match is not None:
173 lps = int(match.group(1))
174 continue
175 match = re.search(r"PP SIZE:\s+(\d+)", line)
176 if match is not None:
177 pp_size = int(match.group(1))
178 continue
179 match = re.search(r"INTER-POLICY:\s+(\w+)", line)
180 if match is not None:
181 policy = match.group(1)
182 continue
183
184 if not name:
185 return None
186
187 size = lps * pp_size
188
189 return {"name": name, "vg": vg, "size": size, "policy": policy}
190
191
192 def parse_vg(data):
193 for line in data.splitlines():
194 match = re.search(r"VOLUME GROUP:\s+(\w+)", line)
195 if match is not None:
196 name = match.group(1)
197 continue
198
199 match = re.search(r"TOTAL PP.*\((\d+)", line)
200 if match is not None:
201 size = int(match.group(1))
202 continue
203
204 match = re.search(r"PP SIZE:\s+(\d+)", line)
205 if match is not None:
206 pp_size = int(match.group(1))
207 continue
208
209 match = re.search(r"FREE PP.*\((\d+)", line)
210 if match is not None:
211 free = int(match.group(1))
212 continue
213
214 return {"name": name, "size": size, "free": free, "pp_size": pp_size}
215
216
217 def main():
218 module = AnsibleModule(
219 argument_spec=dict(
220 vg=dict(type="str", required=True),
221 lv=dict(type="str", required=True),
222 lv_type=dict(type="str", default="jfs2"),
223 size=dict(type="str"),
224 opts=dict(type="str", default=""),
225 copies=dict(type="int", default=1),
226 state=dict(type="str", default="present", choices=["absent", "present"]),
227 policy=dict(type="str", default="maximum", choices=["maximum", "minimum"]),
228 pvs=dict(type="list", elements="str", default=list()),
229 ),
230 supports_check_mode=True,
231 )
232
233 vg = module.params["vg"]
234 lv = module.params["lv"]
235 lv_type = module.params["lv_type"]
236 size = module.params["size"]
237 opts = module.params["opts"]
238 copies = module.params["copies"]
239 policy = module.params["policy"]
240 state = module.params["state"]
241 pvs = module.params["pvs"]
242
243 if policy == "maximum":
244 lv_policy = "x"
245 else:
246 lv_policy = "m"
247
248 # Add echo command when running in check-mode
249 if module.check_mode:
250 test_opt = [module.get_bin_path("echo", required=True)]
251 else:
252 test_opt = []
253
254 # check if system commands are available
255 lsvg_cmd = module.get_bin_path("lsvg", required=True)
256 lslv_cmd = module.get_bin_path("lslv", required=True)
257
258 # Get information on volume group requested
259 rc, vg_info, err = module.run_command([lsvg_cmd, vg])
260
261 if rc != 0:
262 if state == "absent":
263 module.exit_json(changed=False, msg=f"Volume group {vg} does not exist.")
264 else:
265 module.fail_json(msg=f"Volume group {vg} does not exist.", rc=rc, out=vg_info, err=err)
266
267 this_vg = parse_vg(vg_info)
268
269 if size is not None:
270 # Calculate pp size and round it up based on pp size.
271 lv_size = round_ppsize(convert_size(module, size), base=this_vg["pp_size"])
272
273 # Get information on logical volume requested
274 rc, lv_info, err = module.run_command([lslv_cmd, lv])
275
276 if rc != 0:
277 if state == "absent":
278 module.exit_json(changed=False, msg=f"Logical Volume {lv} does not exist.")
279
280 this_lv = parse_lv(lv_info)
281
282 if state == "present" and not size:
283 if this_lv is None:
284 module.fail_json(msg="No size given.")
285
286 if this_lv is None:
287 if state == "present":
288 if lv_size > this_vg["free"]:
289 module.fail_json(
290 msg=f"Not enough free space in volume group {this_vg['name']}: {this_vg['free']} MB free."
291 )
292
293 # create LV
294 mklv_cmd = module.get_bin_path("mklv", required=True)
295
296 cmd = (
297 test_opt
298 + [mklv_cmd, "-t", lv_type, "-y", lv, "-c", copies, "-e", lv_policy, opts, vg, f"{lv_size}M"]
299 + pvs
300 )
301 rc, out, err = module.run_command(cmd)
302 if rc == 0:
303 module.exit_json(changed=True, msg=f"Logical volume {lv} created.")
304 else:
305 module.fail_json(msg=f"Creating logical volume {lv} failed.", rc=rc, out=out, err=err)
306 else:
307 if state == "absent":
308 # remove LV
309 rmlv_cmd = module.get_bin_path("rmlv", required=True)
310 rc, out, err = module.run_command(test_opt + [rmlv_cmd, "-f", this_lv["name"]])
311 if rc == 0:
312 module.exit_json(changed=True, msg=f"Logical volume {lv} deleted.")
313 else:
314 module.fail_json(msg=f"Failed to remove logical volume {lv}.", rc=rc, out=out, err=err)
315 else:
316 if this_lv["policy"] != policy:
317 # change lv allocation policy
318 chlv_cmd = module.get_bin_path("chlv", required=True)
319 rc, out, err = module.run_command(test_opt + [chlv_cmd, "-e", lv_policy, this_lv["name"]])
320 if rc == 0:
321 module.exit_json(changed=True, msg=f"Logical volume {lv} policy changed: {policy}.")
322 else:
323 module.fail_json(msg=f"Failed to change logical volume {lv} policy.", rc=rc, out=out, err=err)
324
325 if vg != this_lv["vg"]:
326 module.fail_json(msg=f"Logical volume {lv} already exist in volume group {this_lv['vg']}")
327
328 # from here the last remaining action is to resize it, if no size parameter is passed we do nothing.
329 if not size:
330 module.exit_json(changed=False, msg=f"Logical volume {lv} already exist.")
331
332 # resize LV based on absolute values
333 if int(lv_size) > this_lv["size"]:
334 extendlv_cmd = module.get_bin_path("extendlv", required=True)
335 cmd = test_opt + [extendlv_cmd, lv, f"{lv_size - this_lv['size']}M"]
336 rc, out, err = module.run_command(cmd)
337 if rc == 0:
338 module.exit_json(changed=True, msg=f"Logical volume {lv} size extended to {lv_size}MB.")
339 else:
340 module.fail_json(msg=f"Unable to resize {lv} to {lv_size}MB.", rc=rc, out=out, err=err)
341 elif lv_size < this_lv["size"]:
342 module.fail_json(
343 msg=f"No shrinking of Logical Volume {lv} permitted. Current size: {this_lv['size']} MB"
344 )
345 else:
346 module.exit_json(changed=False, msg=f"Logical volume {lv} size is already {lv_size}MB.")
347
348
349 if __name__ == "__main__":
350 main()