Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Adam Števko <[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: beadm
11 short_description: Manage ZFS boot environments on FreeBSD/Solaris/illumos systems
12 description:
13 - Create, delete or activate ZFS boot environments.
14 - Mount and unmount ZFS boot environments.
15 author: Adam Števko (@xen0l)
16 extends_documentation_fragment:
17 - community.general._attributes
18 attributes:
19 check_mode:
20 support: full
21 diff_mode:
22 support: none
23 options:
24 name:
25 description:
26 - ZFS boot environment name.
27 type: str
28 required: true
29 aliases: ["be"]
30 snapshot:
31 description:
32 - If specified, the new boot environment is cloned from the given snapshot or inactive boot environment.
33 type: str
34 description:
35 description:
36 - Associate a description with a new boot environment. This option is available only on Solarish platforms.
37 type: str
38 options:
39 description:
40 - Create the datasets for new BE with specific ZFS properties.
41 - Multiple options can be specified.
42 - This option is available only on Solarish platforms.
43 type: str
44 mountpoint:
45 description:
46 - Path where to mount the ZFS boot environment.
47 type: path
48 state:
49 description:
50 - Create or delete ZFS boot environment.
51 type: str
52 choices: [absent, activated, mounted, present, unmounted]
53 default: present
54 force:
55 description:
56 - Specifies if the unmount should be forced.
57 type: bool
58 default: false
59 """
60
61 EXAMPLES = r"""
62 - name: Create ZFS boot environment
63 community.general.beadm:
64 name: upgrade-be
65 state: present
66
67 - name: Create ZFS boot environment from existing inactive boot environment
68 community.general.beadm:
69 name: upgrade-be
70 snapshot: be@old
71 state: present
72
73 - name: Create ZFS boot environment with compression enabled and description "upgrade"
74 community.general.beadm:
75 name: upgrade-be
76 options: "compression=on"
77 description: upgrade
78 state: present
79
80 - name: Delete ZFS boot environment
81 community.general.beadm:
82 name: old-be
83 state: absent
84
85 - name: Mount ZFS boot environment on /tmp/be
86 community.general.beadm:
87 name: BE
88 mountpoint: /tmp/be
89 state: mounted
90
91 - name: Unmount ZFS boot environment
92 community.general.beadm:
93 name: BE
94 state: unmounted
95
96 - name: Activate ZFS boot environment
97 community.general.beadm:
98 name: upgrade-be
99 state: activated
100 """
101
102 RETURN = r"""
103 name:
104 description: BE name.
105 returned: always
106 type: str
107 sample: pre-upgrade
108 snapshot:
109 description: ZFS snapshot to create BE from.
110 returned: always
111 type: str
112 sample: rpool/ROOT/oi-hipster@fresh
113 description:
114 description: BE description.
115 returned: always
116 type: str
117 sample: Upgrade from 9.0 to 10.0
118 options:
119 description: BE additional options.
120 returned: always
121 type: str
122 sample: compression=on
123 mountpoint:
124 description: BE mountpoint.
125 returned: always
126 type: str
127 sample: /mnt/be
128 state:
129 description: State of the target.
130 returned: always
131 type: str
132 sample: present
133 force:
134 description: If forced action is wanted.
135 returned: always
136 type: bool
137 sample: false
138 """
139
140 import os
141
142 from ansible.module_utils.basic import AnsibleModule
143
144
145 class BE:
146 def __init__(self, module):
147 self.module = module
148
149 self.name = module.params["name"]
150 self.snapshot = module.params["snapshot"]
151 self.description = module.params["description"]
152 self.options = module.params["options"]
153 self.mountpoint = module.params["mountpoint"]
154 self.state = module.params["state"]
155 self.force = module.params["force"]
156 self.is_freebsd = os.uname()[0] == "FreeBSD"
157
158 def _beadm_list(self):
159 cmd = [self.module.get_bin_path("beadm"), "list", "-H"]
160 if "@" in self.name:
161 cmd.append("-s")
162 return self.module.run_command(cmd)
163
164 def _find_be_by_name(self, out):
165 if "@" in self.name:
166 for line in out.splitlines():
167 if self.is_freebsd:
168 check = line.split()
169 if check == []:
170 continue
171 full_name = check[0].split("/")
172 if full_name == []:
173 continue
174 check[0] = full_name[len(full_name) - 1]
175 if check[0] == self.name:
176 return check
177 else:
178 check = line.split(";")
179 if check[0] == self.name:
180 return check
181 else:
182 for line in out.splitlines():
183 if self.is_freebsd:
184 check = line.split()
185 if check[0] == self.name:
186 return check
187 else:
188 check = line.split(";")
189 if check[0] == self.name:
190 return check
191 return None
192
193 def exists(self):
194 (rc, out, dummy) = self._beadm_list()
195
196 if rc == 0:
197 return bool(self._find_be_by_name(out))
198 else:
199 return False
200
201 def is_activated(self):
202 (rc, out, dummy) = self._beadm_list()
203
204 if rc == 0:
205 line = self._find_be_by_name(out)
206 if line is None:
207 return False
208 if self.is_freebsd:
209 if "R" in line[1]:
210 return True
211 else:
212 if "R" in line[2]:
213 return True
214
215 return False
216
217 def activate_be(self):
218 cmd = [self.module.get_bin_path("beadm"), "activate", self.name]
219 return self.module.run_command(cmd)
220
221 def create_be(self):
222 cmd = [self.module.get_bin_path("beadm"), "create"]
223
224 if self.snapshot:
225 cmd.extend(["-e", self.snapshot])
226 if not self.is_freebsd:
227 if self.description:
228 cmd.extend(["-d", self.description])
229 if self.options:
230 cmd.extend(["-o", self.options])
231
232 cmd.append(self.name)
233
234 return self.module.run_command(cmd)
235
236 def destroy_be(self):
237 cmd = [self.module.get_bin_path("beadm"), "destroy", "-F", self.name]
238 return self.module.run_command(cmd)
239
240 def is_mounted(self):
241 (rc, out, dummy) = self._beadm_list()
242
243 if rc == 0:
244 line = self._find_be_by_name(out)
245 if line is None:
246 return False
247 if self.is_freebsd:
248 # On FreeBSD, we exclude currently mounted BE on /, as it is
249 # special and can be activated even if it is mounted. That is not
250 # possible with non-root BEs.
251 if line[2] != "-" and line[2] != "/":
252 return True
253 else:
254 if line[3]:
255 return True
256
257 return False
258
259 def mount_be(self):
260 cmd = [self.module.get_bin_path("beadm"), "mount", self.name]
261
262 if self.mountpoint:
263 cmd.append(self.mountpoint)
264
265 return self.module.run_command(cmd)
266
267 def unmount_be(self):
268 cmd = [self.module.get_bin_path("beadm"), "unmount"]
269 if self.force:
270 cmd.append("-f")
271 cmd.append(self.name)
272
273 return self.module.run_command(cmd)
274
275
276 def main():
277 module = AnsibleModule(
278 argument_spec=dict(
279 name=dict(type="str", required=True, aliases=["be"]),
280 snapshot=dict(type="str"),
281 description=dict(type="str"),
282 options=dict(type="str"),
283 mountpoint=dict(type="path"),
284 state=dict(
285 type="str", default="present", choices=["absent", "activated", "mounted", "present", "unmounted"]
286 ),
287 force=dict(type="bool", default=False),
288 ),
289 supports_check_mode=True,
290 )
291 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
292
293 be = BE(module)
294
295 rc = None
296 out = ""
297 err = ""
298 result = {}
299 result["name"] = be.name
300 result["state"] = be.state
301
302 if be.snapshot:
303 result["snapshot"] = be.snapshot
304
305 if be.description:
306 result["description"] = be.description
307
308 if be.options:
309 result["options"] = be.options
310
311 if be.mountpoint:
312 result["mountpoint"] = be.mountpoint
313
314 if be.state == "absent":
315 # beadm on FreeBSD and Solarish systems differs in delete behaviour in
316 # that we are not allowed to delete activated BE on FreeBSD while on
317 # Solarish systems we cannot delete BE if it is mounted. We add mount
318 # check for both platforms as BE should be explicitly unmounted before
319 # being deleted. On FreeBSD, we also check if the BE is activated.
320 if be.exists():
321 if not be.is_mounted():
322 if module.check_mode:
323 module.exit_json(changed=True)
324
325 if be.is_freebsd:
326 if be.is_activated():
327 module.fail_json(msg="Unable to remove active BE!")
328
329 (rc, out, err) = be.destroy_be()
330
331 if rc != 0:
332 module.fail_json(msg=f'Error while destroying BE: "{err}"', name=be.name, stderr=err, rc=rc)
333 else:
334 module.fail_json(msg="Unable to remove BE as it is mounted!")
335
336 elif be.state == "present":
337 if not be.exists():
338 if module.check_mode:
339 module.exit_json(changed=True)
340
341 (rc, out, err) = be.create_be()
342
343 if rc != 0:
344 module.fail_json(msg=f'Error while creating BE: "{err}"', name=be.name, stderr=err, rc=rc)
345
346 elif be.state == "activated":
347 if not be.is_activated():
348 if module.check_mode:
349 module.exit_json(changed=True)
350
351 # On FreeBSD, beadm is unable to activate mounted BEs, so we add
352 # an explicit check for that case.
353 if be.is_freebsd:
354 if be.is_mounted():
355 module.fail_json(msg="Unable to activate mounted BE!")
356
357 (rc, out, err) = be.activate_be()
358
359 if rc != 0:
360 module.fail_json(msg=f'Error while activating BE: "{err}"', name=be.name, stderr=err, rc=rc)
361 elif be.state == "mounted":
362 if not be.is_mounted():
363 if module.check_mode:
364 module.exit_json(changed=True)
365
366 (rc, out, err) = be.mount_be()
367
368 if rc != 0:
369 module.fail_json(msg=f'Error while mounting BE: "{err}"', name=be.name, stderr=err, rc=rc)
370
371 elif be.state == "unmounted":
372 if be.is_mounted():
373 if module.check_mode:
374 module.exit_json(changed=True)
375
376 (rc, out, err) = be.unmount_be()
377
378 if rc != 0:
379 module.fail_json(msg=f'Error while unmounting BE: "{err}"', name=be.name, stderr=err, rc=rc)
380
381 if rc is None:
382 result["changed"] = False
383 else:
384 result["changed"] = True
385
386 if out:
387 result["stdout"] = out
388 if err:
389 result["stderr"] = err
390
391 module.exit_json(**result)
392
393
394 if __name__ == "__main__":
395 main()