
    Vhb                         d dl mZmZmZ eZdZdZdZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlmZ d dlmZ d Zd	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functiona)'  
module: vmadm
short_description: Manage SmartOS virtual machines and zones
description:
  - Manage SmartOS virtual machines through vmadm(1M).
author: Jasper Lievisse Adriaanse (@jasperla)
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
options:
  archive_on_delete:
    required: false
    description:
      - When enabled, the zone dataset is mounted on C(/zones/archive) upon removal.
    type: bool
  autoboot:
    required: false
    description:
      - Whether or not a VM is booted when the system is rebooted.
    type: bool
  brand:
    choices: [joyent, joyent-minimal, lx, kvm, bhyve]
    default: joyent
    description:
      - Type of virtual machine. The V(bhyve) option was added in community.general 0.2.0.
    type: str
  boot:
    required: false
    description:
      - Set the boot order for KVM VMs.
    type: str
  cpu_cap:
    required: false
    description:
      - Sets a limit on the amount of CPU time that can be used by a VM. Use V(0) for no cap.
    type: int
  cpu_shares:
    required: false
    description:
      - Sets a limit on the number of fair share scheduler (FSS) CPU shares for a VM. This limit is relative to all other
        VMs on the system.
    type: int
  cpu_type:
    required: false
    choices: [qemu64, host]
    default: qemu64
    description:
      - Control the type of virtual CPU exposed to KVM VMs.
    type: str
  customer_metadata:
    required: false
    description:
      - Metadata to be set and associated with this VM, this contain customer modifiable keys.
    type: dict
  delegate_dataset:
    required: false
    description:
      - Whether to delegate a ZFS dataset to an OS VM.
    type: bool
  disk_driver:
    required: false
    description:
      - Default value for a virtual disk model for KVM guests.
    type: str
  disks:
    required: false
    description:
      - A list of disks to add, valid properties are documented in vmadm(1M).
    type: list
    elements: dict
  dns_domain:
    required: false
    description:
      - Domain value for C(/etc/hosts).
    type: str
  docker:
    required: false
    description:
      - Docker images need this flag enabled along with the O(brand) set to C(lx).
    type: bool
  filesystems:
    required: false
    description:
      - Mount additional filesystems into an OS VM.
    type: list
    elements: dict
  firewall_enabled:
    required: false
    description:
      - Enables the firewall, allowing fwadm(1M) rules to be applied.
    type: bool
  flexible_disk_size:
    required: false
    description:
      - This sets an upper bound for the amount of space that a bhyve instance may use for its disks and snapshots of those disks (in MiBs).
    type: int
    version_added: 10.5.0
  force:
    required: false
    description:
      - Force a particular action (in other words, stop or delete a VM).
    type: bool
  fs_allowed:
    required: false
    description:
      - Comma separated list of filesystem types this zone is allowed to mount.
    type: str
  hostname:
    required: false
    description:
      - Zone/VM hostname.
    type: str
  image_uuid:
    required: false
    description:
      - Image UUID.
    type: str
  indestructible_delegated:
    required: false
    description:
      - Adds an C(@indestructible) snapshot to delegated datasets.
    type: bool
  indestructible_zoneroot:
    required: false
    description:
      - Adds an C(@indestructible) snapshot to zoneroot.
    type: bool
  internal_metadata:
    required: false
    description:
      - Metadata to be set and associated with this VM, this contains operator generated keys.
    type: dict
  internal_metadata_namespace:
    required: false
    description:
      - List of namespaces to be set as C(internal_metadata-only); these namespaces come from O(internal_metadata) rather
        than O(customer_metadata).
    type: str
  kernel_version:
    required: false
    description:
      - Kernel version to emulate for LX VMs.
    type: str
  limit_priv:
    required: false
    description:
      - Set (comma separated) list of privileges the zone is allowed to use.
    type: str
  maintain_resolvers:
    required: false
    description:
      - Resolvers in C(/etc/resolv.conf) are updated when updating the O(resolvers) property.
    type: bool
  max_locked_memory:
    required: false
    description:
      - Total amount of memory (in MiBs) on the host that can be locked by this VM.
    type: int
  max_lwps:
    required: false
    description:
      - Maximum number of lightweight processes this VM is allowed to have running.
    type: int
  max_physical_memory:
    required: false
    description:
      - Maximum amount of memory (in MiBs) on the host that the VM is allowed to use.
    type: int
  max_swap:
    required: false
    description:
      - Maximum amount of virtual memory (in MiBs) the VM is allowed to use.
    type: int
  mdata_exec_timeout:
    required: false
    description:
      - Timeout in seconds (or 0 to disable) for the C(svc:/smartdc/mdata:execute) service that runs user-scripts in the zone.
    type: int
  name:
    required: false
    aliases: [alias]
    description:
      - Name of the VM. vmadm(1M) uses this as an optional name.
    type: str
  nic_driver:
    required: false
    description:
      - Default value for a virtual NIC model for KVM guests.
    type: str
  nics:
    required: false
    description:
      - A list of nics to add, valid properties are documented in vmadm(1M).
    type: list
    elements: dict
  nowait:
    required: false
    description:
      - Consider the provisioning complete when the VM first starts, rather than when the VM has rebooted.
    type: bool
  owner_uuid:
    required: false
    description:
      - Define the UUID of the owner of the VM.
    type: str
    version_added: 10.5.0
  qemu_opts:
    required: false
    description:
      - Additional qemu arguments for KVM guests. This overwrites the default arguments provided by vmadm(1M) and should only
        be used for debugging.
    type: str
  qemu_extra_opts:
    required: false
    description:
      - Additional qemu cmdline arguments for KVM guests.
    type: str
  quota:
    required: false
    description:
      - Quota on zone filesystems (in MiBs).
    type: int
  ram:
    required: false
    description:
      - Amount of virtual RAM for a KVM guest (in MiBs).
    type: int
  resolvers:
    required: false
    description:
      - List of resolvers to be put into C(/etc/resolv.conf).
    type: list
    elements: str
  routes:
    required: false
    description:
      - Dictionary that maps destinations to gateways, these are set as static routes in the VM.
    type: dict
  spice_opts:
    required: false
    description:
      - Addition options for SPICE-enabled KVM VMs.
    type: str
  spice_password:
    required: false
    description:
      - Password required to connect to SPICE. By default no password is set. Please note this can be read from the Global
        Zone.
    type: str
  state:
    choices: [present, running, absent, deleted, stopped, created, restarted, rebooted]
    default: running
    description:
      - States for the VM to be in. Please note that V(present), V(stopped) and V(restarted) operate on a VM that is currently
        provisioned. V(present) means that the VM is created if it was absent, and that it is in a running state. V(absent)
        shutdowns the zone before removing it. V(stopped) means the zone is created if it does not exist already, before shutting
        it down.
    type: str
  tmpfs:
    required: false
    description:
      - Amount of memory (in MiBs) that is available in the VM for the C(/tmp) filesystem.
    type: int
  uuid:
    required: false
    description:
      - UUID of the VM. Can either be a full UUID or V(*) for all VMs.
    type: str
  vcpus:
    required: false
    description:
      - Number of virtual CPUs for a KVM guest.
    type: int
  vga:
    required: false
    description:
      - Specify VGA emulation used by KVM VMs.
    type: str
  virtio_txburst:
    required: false
    description:
      - Number of packets that can be sent in a single flush of the tx queue of virtio NICs.
    type: int
  virtio_txtimer:
    required: false
    description:
      - Timeout (in nanoseconds) for the TX timer of virtio NICs.
    type: int
  vnc_password:
    required: false
    description:
      - Password required to connect to VNC. By default no password is set. Please note this can be read from the Global Zone.
    type: str
  vnc_port:
    required: false
    description:
      - TCP port to listen of the VNC server. Or set V(0) for random, or V(-1) to disable.
    type: int
  zfs_data_compression:
    required: false
    description:
      - Specifies compression algorithm used for this VMs data dataset. This option only has effect on delegated datasets.
    type: str
  zfs_data_recsize:
    required: false
    description:
      - Suggested block size (power of 2) for files in the delegated dataset's filesystem.
    type: int
  zfs_filesystem_limit:
    required: false
    description:
      - Maximum number of filesystems the VM can have.
    type: int
  zfs_io_priority:
    required: false
    description:
      - IO throttle priority value relative to other VMs.
    type: int
  zfs_root_compression:
    required: false
    description:
      - Specifies compression algorithm used for this VMs root dataset. This option only has effect on the zoneroot dataset.
    type: str
  zfs_root_recsize:
    required: false
    description:
      - Suggested block size (power of 2) for files in the zoneroot dataset's filesystem.
    type: int
  zfs_snapshot_limit:
    required: false
    description:
      - Number of snapshots the VM can have.
    type: int
  zpool:
    required: false
    description:
      - ZFS pool the VM's zone dataset is created in.
    type: str
a  
- name: Create SmartOS zone
  community.general.vmadm:
    brand: joyent
    state: present
    alias: fw_zone
    image_uuid: 95f265b8-96b2-11e6-9597-972f3af4b6d5
    firewall_enabled: true
    indestructible_zoneroot: true
    nics:
      - nic_tag: admin
        ip: dhcp
        primary: true
    internal_metadata:
      root_pw: 'secret'
    quota: 1

- name: Delete a zone
  community.general.vmadm:
    alias: test_zone
    state: deleted

- name: Stop all zones
  community.general.vmadm:
    uuid: '*'
    state: stopped
ai  
uuid:
  description: UUID of the managed VM.
  returned: always
  type: str
  sample: 'b217ab0b-cf57-efd8-cd85-958d0b80be33'
alias:
  description: Alias of the managed VM.
  returned: When addressing a VM by alias.
  type: str
  sample: 'dns-zone'
state:
  description: State of the target, after execution.
  returned: success
  type: str
  sample: 'running'
N)AnsibleModule)	to_nativec                    | j                   ddd|dj                  |      g}| j                  |      \  }}}|dk7  r#| j                  dj                  ||      |       	 t	        j
                  |      }r|d   j                  |      S y # t        $ rH}| j                  dj                  |      t        |      t        j                         	       Y d }~cd }~ww xY w)
Nlookup-j-ozuuid={0}r   z&Could not perform lookup of {0} on {1}msg	exception5Invalid JSON returned by vmadm for uuid lookup of {0}r   detailsr   vmadmformatrun_command	fail_jsonjsonloads	Exceptionr   	traceback
format_excget)	moduleuuidpropcmdrcstdoutstderrstdout_jsones	            k/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/vmadm.pyget_vm_propr'     s     <<4tZ5F5Ft5L
MC!--c2R	Qw8??dKW] 	 	_Djj( 1~!!$''   DGNNtTaLI,@,@,B 	 	D 	DDs    B 	C>CCc                    | j                   dddddj                  |      g}| j                  |      \  }}}|dk7  r"| j                  dj                  |      |       	 t	        j
                  |      }r|d   j                  d      S y # t        $ rH}| j                  d	j                  |      t        |      t        j                         
       Y d }~cd }~ww xY w)Nr	   r
   r   r   z	alias={0}r   zCould not retrieve UUID of {0}r   r   r   r   )r   aliasr    r!   r"   r#   r$   r%   s           r&   get_vm_uuidr*     s     <<4v{7I7I%7P
QC!--c2R	Qw077>& 	 	RDjj( 1~!!&))   DGNNuUaLI,@,@,B 	 	D 	DDs   B 	C>CCc                 d   | j                   ddddg}| j                  |      \  }}}|dk7  r| j                  d|       	 t        j                  |      }|D cg c]  }|d   	 c}S c c}w # t
        $ r9}| j                  dt        |      t        j                         	       Y d }~y d }~ww xY w)
Nr	   r
   r   r   r   zFailed to get VMs listr   zCould not retrieve VM UUIDsr   )	r   r   r   r   r   r   r   r   r   )r   r    r!   r"   r#   r$   vr%   s           r&   get_all_vm_uuidsr-     s    <<4v
6C!--c2R	Qw5H;jj(#./a&	/// ;:IaL#,#7#7#9 	 	; 	;;s*    A- A(%A- (A- -	B/6/B**B/c           	         t        | |      }t        | |      \  }}}|dk7  rd}| j                  d|       nd}t        j                  d|      }|r@|j                         d   }	t        |	      s4| j                  dj                  |	             n| j                  d	       |d
k7  r1t        | 	|      }
|
s"| j                  dj                  |	|             	 t        j                  |       |	fS # t        $ rK}| j                  dj                  |t        |            t        j                                Y d }~|	fS d }~ww xY w)Nr   FzCould not create VMr   TzSuccessfully created VM (.*)zInvalid UUID for VM {0}?r   z.Could not retrieve UUID of newly created(?) VMrunningz!Could not set VM {0} to state {1}z5Could not remove temporary JSON payload file {0}: {1})create_payloadvmadm_create_vmr   rematchgroupsis_valid_uuidr   set_vm_stateosunlinkr   r   r   r   )r   r   vm_statepayload_filer!   dummyr#   changedr4   vm_uuidretr%   s               r&   new_vmr@     sX   !&$/L)&,?R	Qw2fE7@llnQ'G )  %?%F%Fw%O P!QR y vw9C  %H%O%OPWYa%b c;
		, G  ; 	T[[\hjstujvw#,#7#7#9 	 	; 	; G;s   C4 4	E=>EEc                 D    | j                   dd|g}| j                  |      S )Ncreatez-f)r   r   )r   r;   r    s      r&   r2   r2     s%    <<4
6Cc""    c                    | j                   }t        | |d      }|r||k(  ry ddgddgddgddgd}||   \  }}|d	   r|rd
gng }| j                  |g|z   |gz   }	| j                  |	      \  }
}
}t	        j
                  d|      }|d uS )NstatestopTstartFdeletereboot)stoppedr0   deletedrebootedforcez-Fz^Successfully.*)paramsr'   r   r   r3   r4   )r   r>   r:   prE   cmdscommand	forceablerM   r    r<   r#   r4   s                r&   r7   r7     s    A 1E%8#
 D>U#d#u%	D hGYjYTFBE<<
!E
)WI
5C#//4UE6HH&/ErC   c                 t   ddg}| j                   j                         D ci c]  \  }}||vr|r|| }}}	 t        j                  |      }	 t        j                         d   }t        j                  |d       t        |d      5 }	|	j                         d d d        |S c c}}w # t        $ r/}| j                  dt        j                                Y d }~d }~ww xY w# 1 sw Y   |S xY w# t        $ r<}| j                  dt        |      z  t        j                                Y d }~S d }~ww xY w)	NrM   rE   z#Could not create valid JSON payloadr         wzCould not save JSON payload: %s)rN   itemsr   dumpsr   r   r   r   tempfilemkstempr8   chmodopenwriter   )
r   r   module_optionskr,   vmdef
vmdef_jsonr%   fnamefhs
             r&   r1   r1   )  sB    w'N MM'')AqN"q 	
1E YZZ&
	q   "1%
% 	!HHZ 	!
 L3  Y5AUAUAW 	 	Y 	YY	!
 L  q>1MYbYmYmYoppLqsR   B$B* 9C2 C%C2 *	C"3%CC"%C/*C2 /C2 2	D7;1D22D7c                 n    t        | ||      }|y|ry| j                  dj                  ||             y )NFTz!Failed to set VM {0} to state {1}r/   )r7   r   r   )r   r   r:   r?   s       r&   vm_state_transitionre   J  s?    
vtX
.C {	@GGhWXrC   c                 P    t        j                  d| t         j                        d uS )Nz+^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$)r3   r4   
IGNORECASE)r   s    r&   r6   r6   V  s     88A4W_cccrC   c                    dD cg c]  }|| j                   |   f c}D cg c]  \  }}|r|dk7  rt        |      s| }}}|r1| j                  dj                  dj	                  |                   y y c c}w c c}}w )N)r   
image_uuid*zNo valid UUID(s) found for: {0}z, r/   )rN   r6   r   r   join)r   xnamepvaluefaileds        r&   validate_uuidsrp   Z  s     =SSqaq!12SD&fmM&,A 	F  >EEdiiPVFWXY 	 Ts
   A8A=c                 
   | j                   d   }|dk(  r| j                  d       d}t        |       D ]L  }t        | |d      }|s|dk(  rd}| j                  r|rt        | |d      |k7  s9d}<t        | ||      xs |}N |S )NrE   createdz8State "created" is only valid for tasks with a single VMr/   FrK   T)rN   r   r-   r'   
check_modere   )r   r:   rE   any_changedr   current_vm_states         r&   manage_all_vmsrv   e  s     MM'"E	WX K !( 	Y&vtW=H	$9K  (k&$.PTY.Y"&K1&$IX[	Y rC   c                     g dg dg dg dd} t        t        ddg d	      t        dd
g      t        ddg d	      t        ddddg	      t        dd      t        dd      t        dd      t        dd      t        dd      t        dd      
      }| D ]  }| |   D ]  }t        |      }|||<     t        |dddgg      }|j                  dd      |_        |j                  }|d   }|d   }|dv rd}n|dv rd}n|d v rd!}n|d"v rd#}d|i}	|s0t        ||d         }|d!k(  r|d   |	d<    |j                  d'i |	 t        |       |d   r|d   |	d<   ||	d<   |d$k(  r!t        |      |	d%<    |j                  d'i |	 t        ||d      }
|
sd!k(  rd&|	d%<   nN|j                  r|
 xs t        ||d      |k7  |	d%<   n)|
st        ||      \  |	d%<   |	d<   nt        ||      |	d%<    |j                  d'i |	 y )(N)bootdisk_driver
dns_domain
fs_allowedhostnameri   internal_metadata_namespacekernel_version
limit_priv
nic_driver
owner_uuid	qemu_optsqemu_extra_opts
spice_optsr   vgazfs_data_compressionzfs_root_compressionzpool)
archive_on_deleteautobootdelegate_datasetdockerfirewall_enabledrM   indestructible_delegatedindestructible_zonerootmaintain_resolversnowait)cpu_cap
cpu_sharesflexible_disk_sizemax_locked_memorymax_lwpsmax_physical_memorymax_swapmdata_exec_timeoutquotaramtmpfsvcpusvirtio_txburstvirtio_txtimervnc_portzfs_data_recsizezfs_filesystem_limitzfs_io_priorityzfs_root_recsizezfs_snapshot_limit)customer_metadatainternal_metadataroutes)strboolintdictr0   r   )presentr0   absentrK   rJ   rr   	restartedrL   )defaulttypechoicesr)   )r   aliasesjoyent)r   zjoyent-minimallxkvmbhyveqemu64hostT)r   no_loglistr   )r   elements)
rE   rm   brandcpu_typespice_passwordvnc_passworddisksnics	resolversfilesystems)r   rm   r   )argument_specsupports_check_moderequired_one_ofr   )requiredrE   )r   r0   )rJ   rr   rJ   )r   rK   rK   )r   rL   rL   rj   r=   F )r   r   get_bin_pathr   rN   r*   	exit_jsonrp   rv   r'   rs   r@   re   )
propertiesoptionsr   rO   optionr   r   rE   r:   resultru   s              r&   mainr     s   



 E+J2 n

 I
 F

 X&
 t4uT20v/FU3fv65G<   D! 	 At_FGAJ	  
   &)*F &&w&>FLAV9DgJE &&	(	(	'	'	+	+uF
 61V9- <H	1vYF6NF&v&6y6vF6Ns{*68<y"6"" #649 I 5!y			 "21c{64QX7Y]b7by,264,J)y6&> 0hGyFvrC   __main__)
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURNr   r8   r3   rY   r   ansible.module_utils.basicr   +ansible.module_utils.common.text.convertersr   r'   r*   r-   r@   r2   r7   r1   re   r6   rp   rv   r   __name__r   rC   r&   <module>r      s    A @Vp
8
$  	 	   5 A(,*2;"!H#8B	YdZ4Pf zF rC   