Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2017, Jasper Lievisse Adriaanse <[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: vmadm
11 short_description: Manage SmartOS virtual machines and zones
12 description:
13 - Manage SmartOS virtual machines through vmadm(1M).
14 author: Jasper Lievisse Adriaanse (@jasperla)
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: full
20 diff_mode:
21 support: none
22 options:
23 archive_on_delete:
24 description:
25 - When enabled, the zone dataset is mounted on C(/zones/archive) upon removal.
26 type: bool
27 autoboot:
28 description:
29 - Whether or not a VM is booted when the system is rebooted.
30 type: bool
31 brand:
32 choices: [joyent, joyent-minimal, lx, kvm, bhyve]
33 default: joyent
34 description:
35 - Type of virtual machine. The V(bhyve) option was added in community.general 0.2.0.
36 type: str
37 boot:
38 description:
39 - Set the boot order for KVM VMs.
40 type: str
41 cpu_cap:
42 description:
43 - Sets a limit on the amount of CPU time that can be used by a VM. Use V(0) for no cap.
44 type: int
45 cpu_shares:
46 description:
47 - Sets a limit on the number of fair share scheduler (FSS) CPU shares for a VM. This limit is relative to all other
48 VMs on the system.
49 type: int
50 cpu_type:
51 choices: [qemu64, host]
52 default: qemu64
53 description:
54 - Control the type of virtual CPU exposed to KVM VMs.
55 type: str
56 customer_metadata:
57 description:
58 - Metadata to be set and associated with this VM, this contain customer modifiable keys.
59 type: dict
60 delegate_dataset:
61 description:
62 - Whether to delegate a ZFS dataset to an OS VM.
63 type: bool
64 disk_driver:
65 description:
66 - Default value for a virtual disk model for KVM guests.
67 type: str
68 disks:
69 description:
70 - A list of disks to add, valid properties are documented in vmadm(1M).
71 type: list
72 elements: dict
73 dns_domain:
74 description:
75 - Domain value for C(/etc/hosts).
76 type: str
77 docker:
78 description:
79 - Docker images need this flag enabled along with the O(brand) set to C(lx).
80 type: bool
81 filesystems:
82 description:
83 - Mount additional filesystems into an OS VM.
84 type: list
85 elements: dict
86 firewall_enabled:
87 description:
88 - Enables the firewall, allowing fwadm(1M) rules to be applied.
89 type: bool
90 flexible_disk_size:
91 description:
92 - This sets an upper bound for the amount of space that a bhyve instance may use for its disks and snapshots of those
93 disks (in MiBs).
94 type: int
95 version_added: 10.5.0
96 force:
97 description:
98 - Force a particular action (in other words, stop or delete a VM).
99 type: bool
100 fs_allowed:
101 description:
102 - Comma separated list of filesystem types this zone is allowed to mount.
103 type: str
104 hostname:
105 description:
106 - Zone/VM hostname.
107 type: str
108 image_uuid:
109 description:
110 - Image UUID.
111 type: str
112 indestructible_delegated:
113 description:
114 - Adds an C(@indestructible) snapshot to delegated datasets.
115 type: bool
116 indestructible_zoneroot:
117 description:
118 - Adds an C(@indestructible) snapshot to zoneroot.
119 type: bool
120 internal_metadata:
121 description:
122 - Metadata to be set and associated with this VM, this contains operator generated keys.
123 type: dict
124 internal_metadata_namespace:
125 description:
126 - List of namespaces to be set as C(internal_metadata-only); these namespaces come from O(internal_metadata) rather
127 than O(customer_metadata).
128 type: str
129 kernel_version:
130 description:
131 - Kernel version to emulate for LX VMs.
132 type: str
133 limit_priv:
134 description:
135 - Set (comma separated) list of privileges the zone is allowed to use.
136 type: str
137 maintain_resolvers:
138 description:
139 - Resolvers in C(/etc/resolv.conf) are updated when updating the O(resolvers) property.
140 type: bool
141 max_locked_memory:
142 description:
143 - Total amount of memory (in MiBs) on the host that can be locked by this VM.
144 type: int
145 max_lwps:
146 description:
147 - Maximum number of lightweight processes this VM is allowed to have running.
148 type: int
149 max_physical_memory:
150 description:
151 - Maximum amount of memory (in MiBs) on the host that the VM is allowed to use.
152 type: int
153 max_swap:
154 description:
155 - Maximum amount of virtual memory (in MiBs) the VM is allowed to use.
156 type: int
157 mdata_exec_timeout:
158 description:
159 - Timeout in seconds (or 0 to disable) for the C(svc:/smartdc/mdata:execute) service that runs user-scripts in the zone.
160 type: int
161 name:
162 aliases: [alias]
163 description:
164 - Name of the VM. vmadm(1M) uses this as an optional name.
165 type: str
166 nic_driver:
167 description:
168 - Default value for a virtual NIC model for KVM guests.
169 type: str
170 nics:
171 description:
172 - A list of nics to add, valid properties are documented in vmadm(1M).
173 type: list
174 elements: dict
175 nowait:
176 description:
177 - Consider the provisioning complete when the VM first starts, rather than when the VM has rebooted.
178 type: bool
179 owner_uuid:
180 description:
181 - Define the UUID of the owner of the VM.
182 type: str
183 version_added: 10.5.0
184 qemu_opts:
185 description:
186 - Additional qemu arguments for KVM guests. This overwrites the default arguments provided by vmadm(1M) and should only
187 be used for debugging.
188 type: str
189 qemu_extra_opts:
190 description:
191 - Additional qemu cmdline arguments for KVM guests.
192 type: str
193 quota:
194 description:
195 - Quota on zone filesystems (in MiBs).
196 type: int
197 ram:
198 description:
199 - Amount of virtual RAM for a KVM guest (in MiBs).
200 type: int
201 resolvers:
202 description:
203 - List of resolvers to be put into C(/etc/resolv.conf).
204 type: list
205 elements: str
206 routes:
207 description:
208 - Dictionary that maps destinations to gateways, these are set as static routes in the VM.
209 type: dict
210 spice_opts:
211 description:
212 - Addition options for SPICE-enabled KVM VMs.
213 type: str
214 spice_password:
215 description:
216 - Password required to connect to SPICE. By default no password is set. Please note this can be read from the Global
217 Zone.
218 type: str
219 state:
220 choices: [present, running, absent, deleted, stopped, created, restarted, rebooted]
221 default: running
222 description:
223 - States for the VM to be in. Please note that V(present), V(stopped) and V(restarted) operate on a VM that is currently
224 provisioned. V(present) means that the VM is created if it was absent, and that it is in a running state. V(absent)
225 shutdowns the zone before removing it. V(stopped) means the zone is created if it does not exist already, before shutting
226 it down.
227 type: str
228 tmpfs:
229 description:
230 - Amount of memory (in MiBs) that is available in the VM for the C(/tmp) filesystem.
231 type: int
232 uuid:
233 description:
234 - UUID of the VM. Can either be a full UUID or V(*) for all VMs.
235 type: str
236 vcpus:
237 description:
238 - Number of virtual CPUs for a KVM guest.
239 type: int
240 vga:
241 description:
242 - Specify VGA emulation used by KVM VMs.
243 type: str
244 virtio_txburst:
245 description:
246 - Number of packets that can be sent in a single flush of the tx queue of virtio NICs.
247 type: int
248 virtio_txtimer:
249 description:
250 - Timeout (in nanoseconds) for the TX timer of virtio NICs.
251 type: int
252 vnc_password:
253 description:
254 - Password required to connect to VNC. By default no password is set. Please note this can be read from the Global Zone.
255 type: str
256 vnc_port:
257 description:
258 - TCP port to listen of the VNC server. Or set V(0) for random, or V(-1) to disable.
259 type: int
260 zfs_data_compression:
261 description:
262 - Specifies compression algorithm used for this VMs data dataset. This option only has effect on delegated datasets.
263 type: str
264 zfs_data_recsize:
265 description:
266 - Suggested block size (power of 2) for files in the delegated dataset's filesystem.
267 type: int
268 zfs_filesystem_limit:
269 description:
270 - Maximum number of filesystems the VM can have.
271 type: int
272 zfs_io_priority:
273 description:
274 - IO throttle priority value relative to other VMs.
275 type: int
276 zfs_root_compression:
277 description:
278 - Specifies compression algorithm used for this VMs root dataset. This option only has effect on the zoneroot dataset.
279 type: str
280 zfs_root_recsize:
281 description:
282 - Suggested block size (power of 2) for files in the zoneroot dataset's filesystem.
283 type: int
284 zfs_snapshot_limit:
285 description:
286 - Number of snapshots the VM can have.
287 type: int
288 zpool:
289 description:
290 - ZFS pool the VM's zone dataset is created in.
291 type: str
292 """
293
294 EXAMPLES = r"""
295 - name: Create SmartOS zone
296 community.general.vmadm:
297 brand: joyent
298 state: present
299 alias: fw_zone
300 image_uuid: 95f265b8-96b2-11e6-9597-972f3af4b6d5
301 firewall_enabled: true
302 indestructible_zoneroot: true
303 nics:
304 - nic_tag: admin
305 ip: dhcp
306 primary: true
307 internal_metadata:
308 root_pw: 'secret'
309 quota: 1
310
311 - name: Delete a zone
312 community.general.vmadm:
313 alias: test_zone
314 state: deleted
315
316 - name: Stop all zones
317 community.general.vmadm:
318 uuid: '*'
319 state: stopped
320 """
321
322 RETURN = r"""
323 uuid:
324 description: UUID of the managed VM.
325 returned: always
326 type: str
327 sample: 'b217ab0b-cf57-efd8-cd85-958d0b80be33'
328 alias:
329 description: Alias of the managed VM.
330 returned: When addressing a VM by alias.
331 type: str
332 sample: 'dns-zone'
333 state:
334 description: State of the target, after execution.
335 returned: success
336 type: str
337 sample: 'running'
338 """
339
340 import json
341 import os
342 import re
343 import tempfile
344 import traceback
345
346 from ansible.module_utils.basic import AnsibleModule
347
348 # While vmadm(1M) supports a -E option to return any errors in JSON, the
349 # generated JSON does not play well with the JSON parsers of Python.
350 # The returned message contains '\n' as part of the stacktrace,
351 # which breaks the parsers.
352
353
354 def get_vm_prop(module, uuid, prop):
355 # Lookup a property for the given VM.
356 # Returns the property, or None if not found.
357 cmd = [module.vmadm, "lookup", "-j", "-o", prop, f"uuid={uuid}"]
358
359 (rc, stdout, stderr) = module.run_command(cmd)
360
361 if rc != 0:
362 module.fail_json(msg=f"Could not perform lookup of {prop} on {uuid}", rc=rc, stdout=stdout, stderr=stderr)
363
364 try:
365 stdout_json = json.loads(stdout)
366 except Exception as e:
367 module.fail_json(
368 msg=f"Invalid JSON returned by vmadm for uuid lookup of {prop}",
369 details=f"{e}",
370 exception=traceback.format_exc(),
371 )
372
373 if stdout_json:
374 return stdout_json[0].get(prop)
375
376
377 def get_vm_uuid(module, alias):
378 # Lookup the uuid that goes with the given alias.
379 # Returns the uuid or '' if not found.
380 cmd = [module.vmadm, "lookup", "-j", "-o", "uuid", f"alias={alias}"]
381
382 (rc, stdout, stderr) = module.run_command(cmd)
383
384 if rc != 0:
385 module.fail_json(msg=f"Could not retrieve UUID of {alias}", rc=rc, stdout=stdout, stderr=stderr)
386
387 # If no VM was found matching the given alias, we get back an empty array.
388 # That is not an error condition as we might be explicitly checking for its
389 # absence.
390 try:
391 stdout_json = json.loads(stdout)
392 except Exception as e:
393 module.fail_json(
394 msg=f"Invalid JSON returned by vmadm for uuid lookup of {alias}",
395 details=f"{e}",
396 exception=traceback.format_exc(),
397 )
398
399 if stdout_json:
400 return stdout_json[0].get("uuid")
401
402
403 def get_all_vm_uuids(module):
404 # Retrieve the UUIDs for all VMs.
405 cmd = [module.vmadm, "lookup", "-j", "-o", "uuid"]
406
407 (rc, stdout, stderr) = module.run_command(cmd)
408
409 if rc != 0:
410 module.fail_json(msg="Failed to get VMs list", rc=rc, stdout=stdout, stderr=stderr)
411
412 try:
413 stdout_json = json.loads(stdout)
414 return [v["uuid"] for v in stdout_json]
415 except Exception as e:
416 module.fail_json(msg="Could not retrieve VM UUIDs", details=f"{e}", exception=traceback.format_exc())
417
418
419 def new_vm(module, uuid, vm_state):
420 payload_file = create_payload(module, uuid)
421
422 (rc, stdout, stderr) = vmadm_create_vm(module, payload_file)
423
424 if rc != 0:
425 changed = False
426 module.fail_json(msg="Could not create VM", rc=rc, stdout=stdout, stderr=stderr)
427 else:
428 changed = True
429 # 'vmadm create' returns all output to stderr...
430 match = re.match("Successfully created VM (.*)", stderr)
431 if match:
432 vm_uuid = match.groups()[0]
433 if not is_valid_uuid(vm_uuid):
434 module.fail_json(msg=f"Invalid UUID for VM {vm_uuid}?")
435 else:
436 module.fail_json(msg="Could not retrieve UUID of newly created(?) VM")
437
438 # Now that the VM is created, ensure it is in the desired state (if not 'running')
439 if vm_state != "running":
440 ret = set_vm_state(module, vm_uuid, vm_state)
441 if not ret:
442 module.fail_json(msg=f"Could not set VM {vm_uuid} to state {vm_state}")
443
444 try:
445 os.unlink(payload_file)
446 except Exception as e:
447 # Since the payload may contain sensitive information, fail hard
448 # if we cannot remove the file so the operator knows about it.
449 module.fail_json(
450 msg=f"Could not remove temporary JSON payload file {payload_file}: {e}", exception=traceback.format_exc()
451 )
452
453 return changed, vm_uuid
454
455
456 def vmadm_create_vm(module, payload_file):
457 # Create a new VM using the provided payload.
458 cmd = [module.vmadm, "create", "-f", payload_file]
459
460 return module.run_command(cmd)
461
462
463 def set_vm_state(module, vm_uuid, vm_state):
464 p = module.params
465
466 # Check if the VM is already in the desired state.
467 state = get_vm_prop(module, vm_uuid, "state")
468 if state and (state == vm_state):
469 return None
470
471 # Lookup table for the state to be in, and which command to use for that.
472 # vm_state: [vmadm commandm, forceable?]
473 cmds = {
474 "stopped": ["stop", True],
475 "running": ["start", False],
476 "deleted": ["delete", True],
477 "rebooted": ["reboot", False],
478 }
479
480 command, forceable = cmds[vm_state]
481 force = ["-F"] if p["force"] and forceable else []
482
483 cmd = [module.vmadm, command] + force + [vm_uuid]
484
485 (dummy, dummy, stderr) = module.run_command(cmd)
486
487 match = re.match("^Successfully.*", stderr)
488 return match is not None
489
490
491 def create_payload(module, uuid):
492 # Create the JSON payload (vmdef) and return the filename.
493
494 # Filter out the few options that are not valid VM properties.
495 module_options = ["force", "state"]
496 vmdef = {k: v for k, v in module.params.items() if k not in module_options and v}
497
498 try:
499 vmdef_json = json.dumps(vmdef)
500 except Exception:
501 module.fail_json(msg="Could not create valid JSON payload", exception=traceback.format_exc())
502
503 # Create the temporary file that contains our payload, and set tight
504 # permissions for it may container sensitive information.
505 try:
506 # XXX: When there's a way to get the current ansible temporary directory
507 # drop the mkstemp call and rely on ANSIBLE_KEEP_REMOTE_FILES to retain
508 # the payload (thus removing the `save_payload` option).
509 fname = tempfile.mkstemp()[1]
510 os.chmod(fname, 0o400)
511 with open(fname, "w") as fh:
512 fh.write(vmdef_json)
513 except Exception as e:
514 module.fail_json(msg=f"Could not save JSON payload: {e}", exception=traceback.format_exc())
515
516 return fname
517
518
519 def vm_state_transition(module, uuid, vm_state):
520 ret = set_vm_state(module, uuid, vm_state)
521
522 # Whether the VM changed state.
523 if ret is None:
524 return False
525 elif ret:
526 return True
527 else:
528 module.fail_json(msg=f"Failed to set VM {uuid} to state {vm_state}")
529
530
531 def is_valid_uuid(uuid):
532 return re.match("^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$", uuid, re.IGNORECASE) is not None
533
534
535 def validate_uuids(module):
536 failed = [
537 name
538 for name, pvalue in [(x, module.params[x]) for x in ["uuid", "image_uuid"]]
539 if pvalue and pvalue != "*" and not is_valid_uuid(pvalue)
540 ]
541
542 if failed:
543 module.fail_json(msg=f"No valid UUID(s) found for: {', '.join(failed)}")
544
545
546 def manage_all_vms(module, vm_state):
547 # Handle operations for all VMs, which can by definition only
548 # be state transitions.
549 state = module.params["state"]
550
551 if state == "created":
552 module.fail_json(msg='State "created" is only valid for tasks with a single VM')
553
554 # If any of the VMs has a change, the task as a whole has a change.
555 any_changed = False
556
557 # First get all VM uuids and for each check their state, and adjust it if needed.
558 for uuid in get_all_vm_uuids(module):
559 current_vm_state = get_vm_prop(module, uuid, "state")
560 if not current_vm_state and vm_state == "deleted":
561 any_changed = False
562 else:
563 if module.check_mode:
564 if (not current_vm_state) or (get_vm_prop(module, uuid, "state") != state):
565 any_changed = True
566 else:
567 any_changed = vm_state_transition(module, uuid, vm_state) or any_changed
568
569 return any_changed
570
571
572 def main():
573 # In order to reduce the clutter and boilerplate for trivial options,
574 # abstract the vmadm properties and build the dict of arguments later.
575 # Dict of all options that are simple to define based on their type.
576 # They're not required and have a default of None.
577 properties = {
578 "str": [
579 "boot",
580 "disk_driver",
581 "dns_domain",
582 "fs_allowed",
583 "hostname",
584 "image_uuid",
585 "internal_metadata_namespace",
586 "kernel_version",
587 "limit_priv",
588 "nic_driver",
589 "owner_uuid",
590 "qemu_opts",
591 "qemu_extra_opts",
592 "spice_opts",
593 "uuid",
594 "vga",
595 "zfs_data_compression",
596 "zfs_root_compression",
597 "zpool",
598 ],
599 "bool": [
600 "archive_on_delete",
601 "autoboot",
602 "delegate_dataset",
603 "docker",
604 "firewall_enabled",
605 "force",
606 "indestructible_delegated",
607 "indestructible_zoneroot",
608 "maintain_resolvers",
609 "nowait",
610 ],
611 "int": [
612 "cpu_cap",
613 "cpu_shares",
614 "flexible_disk_size",
615 "max_locked_memory",
616 "max_lwps",
617 "max_physical_memory",
618 "max_swap",
619 "mdata_exec_timeout",
620 "quota",
621 "ram",
622 "tmpfs",
623 "vcpus",
624 "virtio_txburst",
625 "virtio_txtimer",
626 "vnc_port",
627 "zfs_data_recsize",
628 "zfs_filesystem_limit",
629 "zfs_io_priority",
630 "zfs_root_recsize",
631 "zfs_snapshot_limit",
632 ],
633 "dict": ["customer_metadata", "internal_metadata", "routes"],
634 }
635
636 # Start with the options that are not as trivial as those above.
637 options = dict(
638 state=dict(
639 default="running",
640 type="str",
641 choices=["present", "running", "absent", "deleted", "stopped", "created", "restarted", "rebooted"],
642 ),
643 name=dict(type="str", aliases=["alias"]),
644 brand=dict(default="joyent", type="str", choices=["joyent", "joyent-minimal", "lx", "kvm", "bhyve"]),
645 cpu_type=dict(default="qemu64", type="str", choices=["host", "qemu64"]),
646 # Regular strings, however these require additional options.
647 spice_password=dict(type="str", no_log=True),
648 vnc_password=dict(type="str", no_log=True),
649 disks=dict(type="list", elements="dict"),
650 nics=dict(type="list", elements="dict"),
651 resolvers=dict(type="list", elements="str"),
652 filesystems=dict(type="list", elements="dict"),
653 )
654
655 # Add our 'simple' options to options dict.
656 for type in properties:
657 for p in properties[type]:
658 option = dict(type=type)
659 options[p] = option
660
661 module = AnsibleModule(argument_spec=options, supports_check_mode=True, required_one_of=[["name", "uuid"]])
662
663 module.vmadm = module.get_bin_path("vmadm", required=True)
664
665 p = module.params
666 uuid = p["uuid"]
667 state = p["state"]
668
669 # Translate the state parameter into something we can use later on.
670 if state in ["present", "running"]:
671 vm_state = "running"
672 elif state in ["stopped", "created"]:
673 vm_state = "stopped"
674 elif state in ["absent", "deleted"]:
675 vm_state = "deleted"
676 elif state in ["restarted", "rebooted"]:
677 vm_state = "rebooted"
678
679 result = {"state": state}
680
681 # While it is possible to refer to a given VM by its `alias`, it is easier
682 # to operate on VMs by their UUID. So if we're not given a `uuid`, look
683 # it up.
684 if not uuid:
685 uuid = get_vm_uuid(module, p["name"])
686 # Bit of a chicken and egg problem here for VMs with state == deleted.
687 # If they're going to be removed in this play, we have to lookup the
688 # uuid. If they're already deleted there's nothing to lookup.
689 # So if state == deleted and get_vm_uuid() returned '', the VM is already
690 # deleted and there's nothing else to do.
691 if uuid is None and vm_state == "deleted":
692 result["name"] = p["name"]
693 module.exit_json(**result)
694
695 validate_uuids(module)
696
697 if p["name"]:
698 result["name"] = p["name"]
699 result["uuid"] = uuid
700
701 if uuid == "*":
702 result["changed"] = manage_all_vms(module, vm_state)
703 module.exit_json(**result)
704
705 # The general flow is as follows:
706 # - first the current state of the VM is obtained by its UUID.
707 # - If the state was not found and the desired state is 'deleted', return.
708 # - If the state was not found, it means the VM has to be created.
709 # Subsequently the VM will be set to the desired state (i.e. stopped)
710 # - Otherwise, it means the VM exists already and we operate on its
711 # state (for example reboot it.)
712 #
713 # In the future it should be possible to query the VM for a particular
714 # property as a valid state (i.e. queried) so the result can be
715 # registered.
716 # Also, VMs should be able to get their properties updated.
717 # Managing VM snapshots should be part of a standalone module.
718
719 # First obtain the VM state to determine what needs to be done with it.
720 current_vm_state = get_vm_prop(module, uuid, "state")
721
722 # First handle the case where the VM should be deleted and is not present.
723 if not current_vm_state and vm_state == "deleted":
724 result["changed"] = False
725 elif module.check_mode:
726 # Shortcut for check mode, if there is no VM yet, it will need to be created.
727 # Or, if the VM is not in the desired state yet, it needs to transition.
728 result["changed"] = (not current_vm_state) or (get_vm_prop(module, uuid, "state") != state)
729 elif not current_vm_state:
730 # No VM was found that matched the given ID (alias or uuid), so we create it.
731 result["changed"], result["uuid"] = new_vm(module, uuid, vm_state)
732 else:
733 # VM was found, operate on its state directly.
734 result["changed"] = vm_state_transition(module, uuid, vm_state)
735
736 module.exit_json(**result)
737
738
739 if __name__ == "__main__":
740 main()