HEX
Server: Apache
System: Linux server2.voipitup.com.au 4.18.0-553.104.1.lve.el8.x86_64 #1 SMP Tue Feb 10 20:07:30 UTC 2026 x86_64
User: posscale (1027)
PHP: 8.2.29
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //opt/saltstack/salt/lib/python3.10/site-packages/salt/utils/__pycache__/vmware.cpython-310.pyc
o

�N�g��@s�dZddlZddlZddlZddlZddlZddlmZddlZ	ddl
Z	ddlZ	ddlZ	ddl
Z	zddlmZmZmZmZmZddlmZmZmZdZWneyWdZYnwzddlmZdd	lmZdZWneysdZYnwzddlZddl Z dZ!Wney�dZ!Ynwe�"e#�Z$d
d�Z%	d�dd
�Z&	d�dd�Z'	d�dd�Z(dd�Z)dd�Z*								d�dd�Z+d�dd�Z,d�dd�Z-dd�Z.d d!�Z/d"d#�Z0d$d%�Z1d&d'�Z2d(d)�Z3d*d+�Z4d,d-�Z5d.d/�Z6d0d1�Z7d2d3�Z8d4d5�Z9d6d7�Z:				d�d8d9�Z;	:	d�d;d<�Z<				d�d=d>�Z=d?d@�Z>dAdB�Z?dCdD�Z@dEdF�ZAd�dGdH�ZBdIdJ�ZCd�dKdL�ZDdMdN�ZEdOdP�ZFd�dQdR�ZGdSdT�ZHdUdV�ZIdWdX�ZJdYdZ�ZKd�d[d\�ZLd�d]d^�ZMd_d`�ZNdadb�ZOd�dcdd�ZPd�dedf�ZQ	d�dgdh�ZR			d�didj�ZSdkdl�ZTd�dmdn�ZUdodp�ZVdqdr�ZWdsdt�ZXdudv�ZYdwdx�ZZdydz�Z[d{d|�Z\d}d~�Z]dd��Z^			d�d�d��Z_d�d��Z`d�d�d��Zad�d��Zbd�d��Zc	d�d�d��Zdd�d�d��Zed�d��Zf				d�d�d��Zg	d�d�d��Zhd�d�d��Zid�d�d��Zjd�d�d��Zkd�d�d��Zl	d�d�d��Zmd�d�d��Znd�d��Zod�d�d��Zp	d�d�d��Zqd�d��Zr		d�d�d��Zsd�d��Ztd�d��Zud�d��Zvd�d��Zwd�d��Zxd�d��Zyd�d��Zzd�d�d��Z{				d�d�d��Z|d�d�d��Z}d�d�d„Z~d�dĄZd�d�dDŽZ�	d�d�dɄZ�d�d�d˄Z�d�d̈́Z�d�dτZ�d�dфZ�dS)�an	
Connection library for VMware

.. versionadded:: 2015.8.2

This is a base library used by a number of VMware services such as VMware
ESX, ESXi, and vCenter servers.

:codeauthor: Nitin Madhok <nmadhok@g.clemson.edu>
:codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstanley.com>

Dependencies
~~~~~~~~~~~~

- pyVmomi Python Module
- ESXCLI: This dependency is only needed to use the ``esxcli`` function. No other
  functions in this module rely on ESXCLI.

pyVmomi
-------

PyVmomi can be installed via pip:

.. code-block:: bash

    pip install pyVmomi

.. note::

    Version 6.0 of pyVmomi has some problems with SSL error handling on certain
    versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
    Python 2.7.9, or newer must be present. This is due to an upstream dependency
    in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
    version of Python is not in the supported range, you will need to install an
    earlier version of pyVmomi. See `Issue #29537`_ for more information.

.. _Issue #29537: https://github.com/saltstack/salt/issues/29537

Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:

.. code-block:: bash

    pip install pyVmomi==5.5.0.2014.1.1

The 5.5.0.2014.1.1 is a known stable version that this original VMware utils file
was developed against.

ESXCLI
------

This dependency is only needed to use the ``esxcli`` function. At the time of this
writing, no other functions in this module rely on ESXCLI.

The ESXCLI package is also referred to as the VMware vSphere CLI, or vCLI. VMware
provides vCLI package installation instructions for `vSphere 5.5`_ and
`vSphere 6.0`_.

.. _vSphere 5.5: http://pubs.vmware.com/vsphere-55/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html
.. _vSphere 6.0: http://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html

Once all of the required dependencies are in place and the vCLI package is
installed, you can check to see if you can connect to your ESXi host or vCenter
server by running the following command:

.. code-block:: bash

    esxcli -s <host-location> -u <username> -p <password> system syslog config get

If the connection was successful, ESXCLI was successfully installed on your system.
You should see output related to the ESXi host's syslog configuration.

�N)�
BadStatusLine)�
Disconnect�GetSi�GetStub�SmartConnect�SoapStubAdapter)�VmomiSupport�vim�vmodlTF)�Unauthenticated)�create_vsphere_clientcCstrdSdS)z,
    Only load if PyVmomi is installed.
    T)FzBMissing dependency: The salt.utils.vmware module requires pyVmomi.)�HAS_PYVMOMI�rr�E/opt/saltstack/salt/lib/python3.10/site-packages/salt/utils/vmware.py�__virtual__wsrc

Cs�tjj�d�}|st�d�dS|durd}|durd}|r&|d|�d�7}|s5|d	�||||||�7}n
|d
�|||||||�7}tjjj	|dd�}	|	S)
a(
    Shell out and call the specified esxcli command, parse the result
    and return something sane.

    :param host: ESXi or vCenter host to connect to
    :param user: User to connect as, usually root
    :param pwd: Password to connect with
    :param port: TCP port
    :param cmd: esxcli command and arguments
    :param esxi_host: If `host` is a vCenter host, then esxi_host is the
                      ESXi machine on which to execute this command
    :param credstore: Optional path to the credential store file

    :return: Dictionary
    �esxclizJMissing dependency: The salt.utils.vmware.esxcli function requires ESXCLI.FN��httpsz --credstore '�'z5 -s {} -u {} -p '{}' --protocol={} --portnumber={} {}z; -s {} -h {} -u {} -p '{}' --protocol={} --portnumber={} {}�quiet)Zoutput_loglevel)
�salt�utils�path�which�log�error�format�modulesZcmdmodZrun_all)
�host�user�pwd�cmd�protocol�portZ	esxi_hostZ	credstoreZesx_cmd�retrrrr�s*���rc
Csb|stjjj||d�}d}zt||||d�}W|Sty0}zt�|�WYd}~|Sd}~ww)a�
    Internal helper method to create an instance of the vSphere API client.
    Please provide username and password to authenticate.

    :param basestring server:
        vCenter host name or IP address
    :param basestring username:
        Name of the user
    :param basestring password:
        Password of the user
    :param Session session:
        Request HTTP session instance. If not specified, one
        is automatically created and used
    :param boolean verify_ssl:
        Verify the SSL certificate. Default: True
    :param basestring ca_bundle:
        Path to the ca bundle to use when verifying SSL certificates.

    :returns:
        Vsphere Client instance
    :rtype:
        :class:`vmware.vapi.vmc.client.VsphereClient`
    )�
verify_ssl�	ca_bundleN)�server�username�password�session)rr�httpr*rrr�trace)r'r(r)r*r%r&�client�errrrr�get_vsphere_client�s����r/c	
Cs�t�d�d}	|dkr |durtj�d��|durtj�d��n>|dkrT|durI|durIzt|||�}	Wn)tyH}
ztj�t|
���d}
~
wwd�	|�}tj�|��tj�d|�d	���t�d
||�d�	|�}z|rxt
||||||	|d�}
Wn^ty�}
zd
|
jvr�t�
d|
j�t�
d�t�
d��WYd}
~
n:d}
~
wty�}
z*t|
tjj�r�d|
jvs�dt|
�vr�d}nt�|
�t|
d�r�|
jn|}tj�|��d}
~
ww|�s`zt
|||||t��|	|d�}
Wntt�y_}
zgdt|
�v�r?t�tj�}tj|_zt
|||||||	|d�}
WnAt�y>}
zt�|
�t|
d��r*|
jnt|
�}tj�d|�d|����d}
~
wwt|
d��rH|
jn|}t�|
�tj�|��WYd}
~
nd}
~
wwt�t|
�|
S)z|
    Internal method to authenticate with a vCenter server or ESX/ESXi host
    and return the service instance object.
    zRetrieving new service instanceN�userpasszXLogin mechanism userpass was specified but the mandatory parameter 'username' is missingzXLogin mechanism userpass was specified but the mandatory parameter 'password' is missingZsspizKLogin mechanism '{}' was specified but the mandatory parameters are missingzUnsupported mechanism: 'rz7Connecting using the '%s' mechanism, with username '%s'zPCould not connect to host '{}'. Please check the debug log for more information.)rrr r"r#�b64token�	mechanismzunexpected keyword argumentz5Initial connect to the VMware endpoint failed with %szOThis may mean that a version of PyVmomi EARLIER than 6.0.0.2016.6 is installed.z/We recommend updating to that version or later.z [SSL: CERTIFICATE_VERIFY_FAILED]z�Could not verify the SSL certificate. You can use verify_ssl: False if you do not want to verify the SSL certificate. This is not recommended as it is considered insecure.�msg)rrr r"r#�
sslContextr1r2zcertificate verify failedzCould not connect to host 'z': )rr,r�
exceptions�CommandExecutionError�get_gssapi_token�	ExceptionZVMwareConnectionError�strrr�	TypeError�messager�
isinstancer	�faultZHostConnectFaultr3�	exception�hasattr�ssl�_create_unverified_context�
SSLContext�PROTOCOL_TLSv1�	CERT_NONE�verify_mode�atexit�registerr)rr(r)r"r#r2�	principal�domainr%�token�exc�err_msgZdefault_msg�service_instance�contextrrr�_get_service_instance�s�
������
�����	
��
��
�
�
��
�

�

���
���rOcCs|jjj|d�}|S)z�
    Get a reference to a VMware customization spec for the purposes of customizing a clone

    si
        ServiceInstance for the vSphere or ESXi server (see get_service_instance)

    customization_spec_name
        Name of the customization spec

    ��name)�contentZcustomizationSpecManagerZGetCustomizationSpec)�siZcustomization_spec_namerrr�get_customizationspec_refes�rTcCs>t|�}|j�|j|gd�}|jD]}|j|kr|SqdS)a
    Get reference to an object of specified object type and name

    si
        ServiceInstance for the vSphere or ESXi server (see get_service_instance)

    obj_type
        Type of the object (vim.StoragePod, vim.Datastore, etc)

    obj_name
        Name of the object

    TN)�
get_inventory�viewManager�CreateContainerView�
rootFolder�viewrQ)rS�obj_type�obj_name�	inventory�	container�itemrrr�get_mor_using_container_viewvs
�

�r_r0c	Csx|durd}|durd}t�}	|	r1t�}
tjj��s+t|
d�r1|
jd�|t	|�g�kr1t
|	�d}	|	s@t|||||||||d�	}	t�
d�z|	��W|	Stjjynt�
d�t
|	�t|||||||||d�	}	Y|	Stjjy�}zt�|�tj�d	|j����d}~wtjjy�}zt�|�tj�|j��d}~wtjy�}zt�|�tj�|j��d}~ww)
ak
    Authenticate with a vCenter server or ESX/ESXi host and return the service instance object.

    host
        The location of the vCenter server or ESX/ESXi host.

    username
        The username used to login to the vCenter server or ESX/ESXi host.
        Required if mechanism is ``userpass``

    password
        The password used to login to the vCenter server or ESX/ESXi host.
        Required if mechanism is ``userpass``

    protocol
        Optionally set to alternate protocol if the vCenter server or ESX/ESXi host is not
        using the default protocol. Default protocol is ``https``.

    port
        Optionally set to alternate port if the vCenter server or ESX/ESXi host is not
        using the default port. Default port is ``443``.

    mechanism
        pyVmomi connection mechanism. Can either be ``userpass`` or ``sspi``.
        Default mechanism is ``userpass``.

    principal
        Kerberos service principal. Required if mechanism is ``sspi``

    domain
        Kerberos user domain. Required if mechanism is ``sspi``

    verify_ssl
        Verify the SSL certificate. Default: True
    Nrrr�:)r%z*Checking connection is still authenticatedz.Session no longer authenticating. Reconnecting�,Not enough permissions. Required privilege: )rrrr�platformZis_proxyr?r�joinr9rrOrr,ZCurrentTimer	r=ZNotAuthenticated�NoPermissionr>r5�VMwareApiError�privilegeId�VimFaultr3r
�RuntimeFault�VMwareRuntimeError)rr(r)r"r#r2rHrIr%rM�stubrKrrr�get_service_instance�sv/��


�
��

��
�
��rkc	Csht��}d|_tj|_|j}|j�d�d}|j�d�d}|t	�
�d<t||||d|d�}|j|_|S)aT
    Returns a stub that points to a different path,
    created from an existing connection.

    service_instance
        The Service Instance.

    path
        Path of the new stub.

    ns
        Namespace of the new stub.
        Default value is None

    version
        Version of the new stub.
        Default value is None.
    Fr`r�"�ZvcSessionCookie)r�nsr�versionZpoolSizer4)r@�create_default_context�check_hostnamerDrE�_stubr�splitZcookierZGetRequestContextr)	rMrrnrorNrj�hostnameZsession_cookieZnew_stubrrr�get_new_service_instance_stub�s�ru�	<unnamed>cCs,|s|j}t�d|�t�d�}|j|_|S)z�
    Retrieves the service instance from a managed object.

    me_ref
        Reference to a managed object (of type vim.ManagedEntity).

    name
        Name of managed object. This field is optional.
    z4[%s] Retrieving service instance from managed object�ServiceInstance)rQrr,r	rwrr)�mo_refrQrSrrr�(get_service_instance_from_managed_object"s

ryc
Cs�t�d�zt|�WdStjjy)}zt�|�tj�	d|j
����d}~wtjjyB}zt�|�tj�	|j��d}~wt
jyZ}zt�|�tj�|j��d}~ww)z�
    Function that disconnects from the vCenter server or ESXi host

    service_instance
        The Service Instance from which to obtain managed object references.
    Z
DisconnectingraN)rr,rr	r=rdr>rr5rerfrgr3r
rhri�rMrKrrr�
disconnect4s$


��
�
��r{c
Cs�z|jjj}WnNtjjy$}zt�|�tj	�
d|j����d}~wtjjy=}zt�|�tj	�
|j
��d}~wtjyU}zt�|�tj	�|j
��d}~wwt�d|�|dkrbdS|dkrhdStj	�
d�|���)	z�
    Function that returns True if the connection is made to a vCenter Server and
    False if the connection is made to an ESXi host

    service_instance
        The Service Instance from which to obtain managed object references.
    raNz
api_type = %sZ
VirtualCenterT�	HostAgentFzEUnexpected api type '{}' . Supported types: 'VirtualCenter/HostAgent')rR�about�apiTyper	r=rdrr>rr5rerfrgr3r
rhrir,r)rMZapi_typerKrrr�is_connection_to_a_vcenterKs4

��
�
���rc
Cs�z|jjWStjjy"}zt�|�tj�	d|j
����d}~wtjjy;}zt�|�tj�	|j��d}~wt
jyS}zt�|�tj�|j��d}~ww)z�
    Returns information of the vCenter or ESXi host

    service_instance
        The Service Instance from which to obtain managed object references.
    raN)rRr}r	r=rdrr>rr5rerfrgr3r
rhrirzrrr�get_service_infols"


��
�
��r�cCsPt|�}||vr&t|�}|j�|jtjgd�}|jD]}|j|kr%|SqdS)z�
    Return a reference to a Distributed Virtual Switch object.

    :param service_instance: PyVmomi service instance
    :param dvs_name: Name of DVS to return
    :return: A PyVmomi DVS object
    TN)	�list_dvsrUrVrWrXr	�DistributedVirtualSwitchrYrQ)rM�dvs_nameZswitchesr\r]r^rrr�_get_dvs�s�

�r�cC�
|jjjS)zT
    Helper function that returns a list of PhysicalNics and their information.
    )�config�network�pnic�Zhost_referencerrr�
_get_pnics��
r�cCr�)zS
    Helper function that returns a list of VirtualNics and their information.
    )r�r��vnicr�rrr�
_get_vnics�r�r�cCs|jjS)z_
    Helper function that returns a list of Virtual NicManagers
    and their information.
    )�
configManagerZvirtualNicManagerr�rrr�_get_vnic_manager�sr�cC�"|jD]}|j|kr|SqdS�z�
    Return a portgroup object corresponding to the portgroup name on the dvs

    :param dvs: DVS object
    :param portgroup_name: Name of portgroup to return
    :return: Portgroup object
    N��	portgrouprQ��dvsZportgroup_namer�rrr�_get_dvs_portgroup��


�r�cCr�r�r�r�rrr�_get_dvs_uplink_portgroup�r�r�cCs�tstd��|�d|�d|��}t�d|�t�|tj�}t�|�}d}|jsG|�	|�}|r8t
�tj
j�|��S|jr<n|sDtj�d��|jr'tj�d��)z�
    Get the gssapi token for Kerberos connection

    principal
       The service principal
    host
       Host url where we would like to authenticate
    domain
       Kerberos user domain
    z#The gssapi library is not imported.�/�@z%Retrieving gsspi token for service %sNz,Can't receive token, no response from serverz-Context established, but didn't receive token)�
HAS_GSSAPI�ImportErrorr�debug�gssapi�NameZC_NT_USER_NAMEZInitContextZestablished�step�base64�	b64encoderrZstringutils�to_bytesr5r6)rHrrIZserviceZservice_name�ctxZin_tokenZ	out_tokenrrrr7�s*

��
�r7cCs\i}t|�jjdk�r�|jj�|��jtj	gd�}|�r�|j
�r�|j
djjj
|d<|j
djjj|d<|j
djjjD]
}|jjdkrI|j|d<q<|j
djjjj|d<|j
djjjj
|d	<|j
djjjj|d
<|j
djjjj|d<|j
djjjj|d<|j
djjjj|d
<|j
djjdd|d<|j
djjj|d<|j
djjj���d�|d<|j
djj dj!|d<|j
djjjj"|d<|j
djj#j$|d<|j
djj#j%|d<|d|d|d<i|d<i|d<i|d<i|d<|j
dj&j'j(j)D]O}g|d|j*<g|d|j*<g|d|j*<|d|j*�+|j,j-j.�|d|j*�+|j,j-j.�|j,j-j/�rE|d|j*�+|j,j-j/j0�|j,j1|d|j*<�q|j
dj&j'j2j3|d<|j
dj&j'j2j4|d<d�5|j
dj&j'j2j3|j
dj&j'j2j4�r|dnd |j
dj&j'j2j4�|d!<|j
dj&j'j6j7D]}|j1|d|j*<�q�|j
dj&j8j9j:j|d"<d#}|S)$z�
    Return hardware info for standard minion grains if the service_instance is a HostAgent type

    service_instance
        The service instance object to get hardware info for

    .. versionadded:: 2016.11.0
    r|TrZmanufacturerZproductnameZ
ServiceTagZserialnumberZ
osfullnameZosmanufacturerZ	osreleaseZosbuildZ	os_family�os�Z	mem_totalZbiosversionz%m/%d/%YZbiosreleasedateZ	cpu_modelZkernelZnum_cpu_socketsZ
num_cpu_coresZnum_cpusZ
ip_interfacesZip4_interfacesZip6_interfacesZhwaddr_interfacesrrIz{}{}{}�.�Zfqdn�timezoneN);rUr}r~rRrVrW�RetrieveContentrXr	�
HostSystemrYZhardwareZ
systemInfo�vendorZmodelZotherIdentifyingInfoZidentifierType�keyZidentifierValueZsummaryr��productZfullNamero�buildrQZ
memorySizeZbiosInfoZbiosVersionZreleaseDate�date�strftimeZcpuPkg�descriptionZ
productLineIdZcpuInfoZnumCpuPackagesZnumCpuCoresr�Z
networkSystemZ
networkConfigr��device�append�spec�ipZ	ipAddressZ
ipV6ConfigZipV6AddressZmacZ	dnsConfigZhostNameZ
domainNamerZnetworkInfor�ZdateTimeSystemZdateTimeInfoZtimeZone)rMZ
hw_grain_datarY�_dataZ_vnicZ_pnicrrr�get_hardware_grains�s�	�
�������
�������
�
�r�cCs|��S)z�
    Return the inventory of a Service Instance Object.

    service_instance
        The Service Instance Object for which to obtain inventory.
    )r��rMrrrrUFsrUc
Cs�zt�d�|��jWStjjy(}zt�|�tj	�
d|j����d}~wtjjyA}zt�|�tj	�
|j
��d}~wtjyY}zt�|�tj	�|j
��d}~ww)z�
    Returns the root folder of a vCenter.

    service_instance
        The Service Instance Object for which to obtain the root folder.
    zRetrieving root folderraN)rr,r�rXr	r=rdr>rr5rerfrgr3r
rhrirzrrr�get_root_folderPs$


��
�
��r�c

Cs�|st|�}|}d}|sx|sxd}z|jj�||gd�}WnNtjjy9}zt�|�t	j
�d|j����d}~wtjj
yR}zt�|�t	j
�|j��d}~wtjyj}zt�|�t	j
�|j��d}~wwtjjjdddtjjd�}tjjj||s�dnd|d�}	tjjj||s�dnd|s�|gndd	�}
tjjj|
g|	gdd
�}z
|jj�|g�}WnNtjjy�}zt�|�t	j
�d|j����d}~wtjj
y�}zt�|�t	j
�|j��d}~wtjy�}zt�|�t	j
�|j��d}~ww|�rZz|��W|Stjj�y&}zt�|�t	j
�d|j����d}~wtjj
�y@}zt�|�t	j
�|j��d}~wtj�yY}zt�|�t	j
�|j��d}~ww|S)a7
    Returns the content of the specified type of object for a Service Instance.

    For more information, please see:
    http://pubs.vmware.com/vsphere-50/index.jsp?topic=%2Fcom.vmware.wssdk.pg.doc_50%2FPG_Ch5_PropertyCollector.7.6.html

    service_instance
        The Service Instance from which to obtain content.

    obj_type
        The type of content to obtain.

    property_list
        An optional list of object properties to used to return even more filtered content results.

    container_ref
        An optional reference to the managed object to search under. Can either be an object of type Folder, Datacenter,
        ComputeResource, Resource Pool or HostSystem. If not specified, default behaviour is to search under the inventory
        rootFolder.

    traversal_spec
        An optional TraversalSpec to be used instead of the standard
        ``Traverse All`` spec.

    local_properties
        Flag specifying whether the properties to be retrieved are local to the
        container. If that is the case, the traversal spec needs to be None.
    FTraNZtraverseEntitiesrY�rQr�skip�type)r��allZpathSet)�objr��	selectSet)Z	objectSet�propSetZreportMissingObjectsInResults)r�rRrVrWr	r=rdrr>rr5rerfrgr3r
rhri�query�PropertyCollector�
TraversalSpecrYZ
ContainerViewZPropertySpecZ
ObjectSpecZ
FilterSpecZpropertyCollectorZRetrieveContentsZDestroy)
rMrZ�
property_list�
container_ref�traversal_spec�local_propertiesZobj_refZlocal_traversal_specrKZ
property_specZobj_specZfilter_specrRrrr�get_contentgs�%�

��
�
����
���

��
�
��

�

��
�
��r�rQcCsVt|||g|d�}|D]}t|�dd���d�}|||ks"||kr(|dSqdS)a
    Returns the first managed object reference having the specified property value.

    service_instance
        The Service Instance from which to obtain managed object references.

    object_type
        The type of content for which to obtain managed object references.

    property_value
        The name of the property for which to obtain the managed object reference.

    property_name
        An object property used to return the specified object reference results. Defaults to ``name``.

    container_ref
        An optional reference to the managed object to search under. Can either be an object of type Folder, Datacenter,
        ComputeResource, Resource Pool or HostSystem. If not specified, default behaviour is to search under the inventory
        rootFolder.
    )r�r��objectr�z'"N)�get_mors_with_propertiesr9�get�strip)rM�object_typeZproperty_valueZ
property_namer��object_listr�Zobj_idrrr�get_mor_by_property�s��r�c
Cs�||g}||||d�}z	t|i|��}Wn/ty$t|i|��}Yn tyC}	z|	jtjkr2�t|i|��}WYd}	~	nd}	~	wwg}
|D]}i}|jD]}
|
j||
j<qO|j|d<|
�	|�qHt
�dt|
��|
S)a�
    Returns a list containing properties and managed object references for the managed object.

    service_instance
        The Service Instance from which to obtain managed object references.

    object_type
        The type of content for which to obtain managed object references.

    property_list
        An optional list of object properties used to return even more filtered managed object reference results.

    container_ref
        An optional reference to the managed object to search under. Can either be an object of type Folder, Datacenter,
        ComputeResource, Resource Pool or HostSystem. If not specified, default behaviour is to search under the inventory
        rootFolder.

    traversal_spec
        An optional TraversalSpec to be used instead of the standard
        ``Traverse All`` spec

    local_properties
        Flag specigying whether the properties to be retrieved are local to the
        container. If that is the case, the traversal spec needs to be None.
    )r�r�r�r�Nr�zRetrieved %s objects)
r�r�OSError�errnoZEPIPEr��valrQr�r�rr,�len)rMr�r�r�r�r�Zcontent_argsZcontent_kwargsrRrKr�r��
propertiesZproprrrr�s2"���

r�cCs�t|�}t�dt|�j�zt|t|�|dgdd�}|dd}Wn
tjjy.d}Ynwt�d|t|�j|�t|t|�||dd�}|sQt	j
�d|�d	���|dS)
z�
    Returns specific properties of a managed object, retrieved in an
    optimally.

    mo_ref
        The managed object reference.

    properties
        List of properties of the managed object to retrieve.
    zRetrieving name of %srQT)r�r�r�rrvz%Retrieving properties '%s' of %s '%s'zProperties of managed object 'z' weren't retrieved)ryrr,r��__name__r�r
r��InvalidPropertyrr5re)rxr�rM�itemsZmo_namerrr� get_properties_of_managed_objectOs@����
�r�cCst|dg�}|�d�S)z�
    Returns the name of a managed object.
    If the name wasn't found, it returns None.

    mo_ref
        The managed object reference.
    rQ)r�r�)rx�propsrrr�get_managed_object_name{s
r�cCsl|dkr
tjj��S|dkrtjj��S|dkrtjj��S|dkr(tjj��S|dkr2tjj��Std��)z�
    Return the network adapter type.

    adpater_type
        The adapter type from which to obtain the network adapter type.
    �vmxnet�vmxnet2�vmxnet3�e1000�e1000ez,An unknown network adapter object type name.)	r	�vmr��
VirtualVmxnet�VirtualVmxnet2�VirtualVmxnet3�VirtualE1000�
VirtualE1000e�
ValueError)Zadapter_typerrr�get_network_adapter_type�sr�cCslt|tjjj�r
dSt|tjjj�rdSt|tjjj�rdSt|tjjj�r(dSt|tjjj�r2dSt	d��)z�
    Returns the network adapter type.

    adapter_object
        The adapter object from which to obtain the network adapter type.
    r�r�r�r�r�z'An unknown network adapter object type.)
r<r	r�r�r�r�r�r�r�r�)Zadapter_objectrrr�get_network_adapter_object_type�sr�c	s�t|�}t�d|�rd���nd��dg}tjjjddtj	tjjjddtj
d	�gd
�}t|�}��fdd�t|tj
|||d
�D�}|S)a
    Returns distributed virtual switches (DVSs) in a datacenter.

    dc_ref
        The parent datacenter reference.

    dvs_names
        The names of the DVSs to return. Default is None.

    get_all_dvss
        Return all DVSs in the datacenter. Default is False.
    zCRetrieving DVSs in datacenter '%s', dvs_names='%s', get_all_dvss=%s�,NrQ�
networkFolderT�childEntityF�rr�r��rr�r�r�c�(g|]}�s�r|d�vr|d�qS�rQr�r��.0�i��	dvs_names�get_all_dvssrr�
<listcomp>���	�	�zget_dvss.<locals>.<listcomp>�r�r�r�)r�rr,rcr
r�r�r�r	�
Datacenter�Folderryr�r�)�dc_refr�r��dc_namer�r�rMr�rr�r�get_dvss�s8
����
��r�cCslt|�}t�d|�t|�}tjjjddtj	d�}t
|tj|dg|d�}|s0tj
�d|�d���|d	d
S)z6
    Retrieves the network folder of a datacenter
    z,Retrieving network folder in datacenter '%s'r�Fr�rQr�zNetwork folder in datacenter 'z' wasn't retrievedrr�)r�rr,ryr
r�r�r�r	r�r�r�rr5�VMwareObjectRetrievalError)r�r�rMr��entriesrrr�get_network_folder�s$��
�rc
Cst|�}t�d||�|st��}|jst��|_||j_t|�}z|�	|�}WnNtj
jyE}zt�|�t
j�d|j����d}~wtj
jy^}zt�|�t
j�|j��d}~wtjyv}zt�|�t
j�|j��d}~wwt||t|j��dS)aq
    Creates a distributed virtual switches (DVS) in a datacenter.
    Returns the reference to the newly created distributed virtual switch.

    dc_ref
        The parent datacenter reference.

    dvs_name
        The name of the DVS to create.

    dvs_create_spec
        The DVS spec (vim.DVSCreateSpec) to use when creating the DVS.
        Default is None.
    z$Creating DVS '%s' in datacenter '%s'raN)r�rr,r	Z
DVSCreateSpecZ
configSpecZVMwareDVSConfigSpecrQrZCreateDVS_Taskr=rdr>rr5rerfrgr3r
rhri�
wait_for_taskr9�	__class__)r�r�Zdvs_create_specr�Znetw_folder_ref�taskrKrrr�
create_dvs�s4


��
�
��rc
C��t|�}t�d|�z|�|�}WnNtjjy.}zt�|�tj	�
d|j����d}~wtjjyG}zt�|�tj	�
|j
��d}~wtjy_}zt�|�tj	�|j
��d}~wwt||t|j��dS)z�
    Updates a distributed virtual switch with the config_spec.

    dvs_ref
        The DVS reference.

    dvs_config_spec
        The updated config spec (vim.VMwareDVSConfigSpec) to be applied to
        the DVS.
    zUpdating dvs '%s'raN)r�rr,ZReconfigureDvs_Taskr	r=rdr>rr5rerfrgr3r
rhrirr9r)�dvs_refZdvs_config_specr�rrKrrr�
update_dvss(

��
�
��rc
Cs�t|�}t�d||�z	|j|d�WdStjjy1}zt�|�tj	�
d|j����d}~wtjjyJ}zt�|�tj	�
|j
��d}~wtjyb}zt�|�tj	�|j
��d}~ww)z�
    Sets whether NIOC is enabled on a DVS.

    dvs_ref
        The DVS reference.

    enabled
        Flag specifying whether NIOC is enabled.
    z<Setting network resource management enable to %s on dvs '%s')�enableraN)r�rr,ZEnableNetworkResourceManagementr	r=rdr>rr5rerfrgr3r
rhri)r�enabledr�rKrrr�+set_dvs_network_resource_management_enabled;s.
�

��
�
��rc	s�t|tjtjf�stj�d��t|�}t�	dt
|�j|�r"d���nd��dg}t|tj�rFt
jjjddtjt
jjjdd	tjd
�gd�}nt
jjjdd	tjd
�}t|�}��fd
d�t|tj|||d�D�}|S)az
    Returns distributed virtual porgroups (dvportgroups).
    The parent object can be either a datacenter or a dvs.

    parent_ref
        The parent object reference. Can be either a datacenter or a dvs.

    portgroup_names
        The names of the dvss to return. Default is None.

    get_all_portgroups
        Return all portgroups in the parent. Default is False.
    zEParent has to be either a datacenter, or a distributed virtual switchzMRetrieving portgroup in %s '%s', portgroups_names='%s', get_all_portgroups=%sr�NrQr�Tr�Fr�r�r�c�(g|]}�s�r|d�vr|d�qSr�rr���get_all_portgroups�portgroup_namesrrr��r�z$get_dvportgroups.<locals>.<listcomp>r�)r<r	r�r�rr5�ArgumentValueErrorr�rr,r�r�rcr
r�r�r�r�ryr��DistributedVirtualPortgroup)�
parent_refrr�parent_namer�r�rMr�rr
r�get_dvportgroupsZsJ��������rcCsrt|�}t�d|�tjjjddtjd�}t	|�}dd�t
|tj|dg|d�D�}|s5tj
�d	|�d
���|dS)z�
    Returns the uplink distributed virtual portgroup of a distributed virtual
    switch (dvs)

    dvs_ref
        The dvs reference
    z'Retrieving uplink portgroup of dvs '%s'r�Fr�cSs.g|]}|drdd�|dD�r|d�qS)�tagcS�g|]	}|jdkr|�qS)zSYSTEM/DVS.UPLINKPG�r�)r��trrrr���z5get_uplink_dvportgroup.<locals>.<listcomp>.<listcomp>r�r)r��entryrrrr��s�	��z*get_uplink_dvportgroup.<locals>.<listcomp>rr�zUplink portgroup of DVS 'z' wasn't foundr)r�rr,r
r�r�r�r	r�ryr�rrr5r�)rr�r�rMr�rrr�get_uplink_dvportgroup�s(���
�rc
Cs�t|�}t�d|j|�t�d|�z|�|�}WnNtjjy6}zt�|�t	j
�d|j����d}~wtjj
yO}zt�|�t	j
�|j��d}~wtjyg}zt�|�t	j
�|j��d}~wwt||t|j��dS)z�
    Creates a distributed virtual portgroup on a distributed virtual switch
    (dvs)

    dvs_ref
        The dvs reference

    spec
        Portgroup spec (vim.DVPortgroupConfigSpec)
    zAdding portgroup %s to dvs '%s'z	spec = %sraN)r�rr,rQZCreateDVPortgroup_Taskr	r=rdr>rr5rerfrgr3r
rhrirr9r)rr�r�rrKrrr�create_dvportgroup�s*

��
�
��rc
Cr)z�
    Updates a distributed virtual portgroup

    portgroup_ref
        The portgroup reference

    spec
        Portgroup spec (vim.DVPortgroupConfigSpec)
    zUpdating portgrouo %sraN)r�rr,ZReconfigureDVPortgroup_Taskr	r=rdr>rr5rerfrgr3r
rhrirr9r)�
portgroup_refr��pg_namerrKrrr�update_dvportgroup�s(


��
�
��rc
Cs�t|�}t�d|�z|��}WnNtjjy-}zt�|�tj	�
d|j����d}~wtjjyF}zt�|�tj	�
|j
��d}~wtjy^}zt�|�tj	�|j
��d}~wwt||t|j��dS)zd
    Removes a distributed virtual portgroup

    portgroup_ref
        The portgroup reference
    zRemoving portgroup %sraN)r�rr,�Destroy_Taskr	r=rdr>rr5rerfrgr3r
rhrirr9r)rrrrKrrr�remove_dvportgroup�s(

��
�
��r!c	s�t|tj�stj�d��t|�}t�dt	|�j
|�rd���nd��dg}t|�}t
jjjddtjt
jjjdd	tjd
�gd�}��fdd
�t|tj|||d�D�}|S)as
    Returns networks of standard switches.
    The parent object can be a datacenter.

    parent_ref
        The parent object reference. A datacenter object.

    network_names
        The name of the standard switch networks. Default is None.

    get_all_networks
        Boolean indicates whether to return all networks in the parent.
        Default is False.
    zParent has to be a datacenter.zHRetrieving network from %s '%s', network_names='%s', get_all_networks=%sr�NrQr�Tr�Fr�r�crr�rr���get_all_networks�
network_namesrrr�-r�z get_networks.<locals>.<listcomp>r�)r<r	r�rr5rr�rr,r�r�rcryr
r�r�r�r�r��Network)rr$r#rr�rMr�r�rr"r�get_networkss>����
��r&cCs:|durdg}g}t|||�}|D]	}|�|d�q|S)a�
    Returns a simple list of objects from a given service instance.

    service_instance
        The Service Instance for which to obtain a list of objects.

    object_type
        The type of content for which to obtain information.

    properties
        An optional list of object properties used to return reference results.
        If not provided, defaults to ``name``.
    NrQ)r�r�)rMZ
vim_objectr�r�Z	item_listr^rrr�list_objects;sr'c
Cs�t�d�z|jj}W|Stjjy)}zt�|�tj	�
d|j����d}~wtjjyB}zt�|�tj	�
|j
��d}~wtjyZ}zt�|�tj	�|j
��d}~ww)z�
    Returns the license manager.

    service_instance
        The Service Instance Object from which to obrain the license manager.
    zRetrieving license managerraN)rr�rR�licenseManagerr	r=rdr>rr5rerfrgr3r
rhri)rMZlic_managerrKrrr�get_license_managerSs&

�

��
�
��r)c
Cs�t�d�z|jjj}WnNtjjy)}zt�|�t	j
�d|j����d}~wtjj
yB}zt�|�t	j
�|j��d}~wtjyZ}zt�|�t	j
�|j��d}~ww|sct	j
�d��|S)z�
    Returns the license assignment manager.

    service_instance
        The Service Instance Object from which to obrain the license manager.
    z%Retrieving license assignment managerraNz,License assignment manager was not retrieved)rr�rRr(ZlicenseAssignmentManagerr	r=rdr>rr5rerfrgr3r
rhrir�)rMZlic_assignment_managerrKrrr�get_license_assignment_managerls0
�

��
�
���r*c
Cs�|st|�}t�d�z|jWStjjy,}zt�|�tj	�
d|j����d}~wtjjyE}zt�|�tj	�
|j
��d}~wtjy]}zt�|�tj	�|j
��d}~ww)a
    Returns the licenses on a specific instance.

    service_instance
        The Service Instance Object from which to obrain the licenses.

    license_manager
        The License Manager object of the service instance. If not provided it
        will be retrieved.
    zRetrieving licensesraN)r)rr�Zlicensesr	r=rdr>rr5rerfrgr3r
rhri)rM�license_managerrKrrr�get_licenses�s(


��
�
��r,c
Cs�|st|�}t��}d|_||_t�d|�z
|�||g�}W|Stjj	y=}zt�
|�tj�
d|j����d}~wtjjyV}zt�
|�tj�
|j��d}~wtjyn}zt�
|�tj�|j��d}~ww)aC
    Adds a license.

    service_instance
        The Service Instance Object.

    key
        The key of the license to add.

    description
        The description of the license to add.

    license_manager
        The License Manager object of the service instance. If not provided it
        will be retrieved.
    ZVpxClientLicenseLabelzAdding license '%s'raN)r)r	ZKeyValuer��valuerr�Z
AddLicenser=rdr>rr5rerfrgr3r
rhri)rMr�r�r+Zlabel�vmware_licenserKrrr�add_license�s0�

��
�
��r/c	
Cs|st|�}|stj�d��d}d}d}|sr|rd}d}z|jjj}WnQtjj	y@}zt
�|�tj�d|j
����d}~wtjjyY}zt
�|�tj�|j��d}~wtjyq}zt
�|�tj�|j��d}~ww|j}t
�d|�z|�|�}WnNtjj	y�}zt
�|�tj�d|j
����d}~wtjjy�}zt
�|�tj�|j��d}~wtjy�}zt
�|�tj�|j��d}~ww|dkr�t|�d	kr�t
�d
�tj�d��|r�||djkr�t
�d
||dj�tj�d��dd�|D�S)a�
    Returns the licenses assigned to an entity. If entity ref is not provided,
    then entity_name is assumed to be the vcenter. This is later checked if
    the entity name is provided.

    service_instance
        The Service Instance Object from which to obtain the licenses.

    entity_ref
        VMware entity to get the assigned licenses for.
        If None, the entity is the vCenter itself.
        Default is None.

    entity_name
        Entity name used in logging.
        Default is None.

    license_assignment_manager
        The LicenseAssignmentManager object of the service instance.
        If not provided it will be retrieved.
        Default is None.
    zNo entity_name passedNZmoidFT�uuidraz$Retrieving licenses assigned to '%s'rmzCUnexpectectedly retrieved more than one VCenter license assignment.z2Unexpected return. Expect only a single assignmentrz0Getting license info for wrong vcenter: %s != %sz3Got license assignment info for a different vcentercS�g|]}|j�qSr)ZassignedLicense)r��arrrr�%�z)get_assigned_licenses.<locals>.<listcomp>)r*rr5rrRr}�instanceUuidr	r=rdrr>rerfrgr3r
rhri�_moIdr,ZQueryAssignedLicensesr�r�ZentityDisplayName)	rM�
entity_ref�entity_name�license_assignment_manager�	entity_idZentity_typeZ
check_namerKZassignmentsrrr�get_assigned_licenses�s~

��
�
��

��
�
��
���r:c	
Csz|st|�}d}|s[z|jjj}WnDtjjy.}zt�|�t	j
�d|j����d}~wtjj
yB}zt	j
�|j��d}~wtjyU}zt	j
�|j��d}~ww|sZd}n|j}t�d|�z
|�|||�}W|Stjjy�}zt�|�t	j
�d|j����d}~wtjj
y�}zt�|�t	j
�|j��d}~wtjy�}zt�|�t	j
�|j��d}~ww)a�
    Assigns a license to an entity.

    service_instance
        The Service Instance Object from which to obrain the licenses.

    license_key
        The key of the license to add.

    license_name
        The description of the license to add.

    entity_ref
        VMware entity to assign the license to.
        If None, the entity is the vCenter itself.
        Default is None.

    entity_name
        Entity name used in logging.
        Default is None.

    license_assignment_manager
        The LicenseAssignmentManager object of the service instance.
        If not provided it will be retrieved
        Default is None.
    NraZvCenterzAssigning license to '%s')r*rRr}r4r	r=rdrr>rr5rerfrgr3r
rhrir5r,ZUpdateAssignedLicense)	rMZlicense_keyZlicense_namer6r7r8r9rKr.rrr�assign_license(sX"

��������

��
�
��r;cC�t|tj�S)z�
    Returns a list of datacenters associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain datacenters.
    )r'r	r�r�rrr�list_datacenterst�r=cs&��fdd�t|tjdgd�D�}|S)aX
    Returns all datacenters in a vCenter.

    service_instance
        The Service Instance Object from which to obtain cluster.

    datacenter_names
        List of datacenter names to filter by. Default value is None.

    get_all_datacenters
        Flag specifying whether to retrieve all datacenters.
        Default value is None.
    cr�r�rr���datacenter_names�get_all_datacentersrrr��s���z#get_datacenters.<locals>.<listcomp>rQ)r�)r�r	r�)rMr@rAr�rr?r�get_datacenters~s
��rBcCs.t||gd�}|stj�d|�d���|dS)z�
    Returns a vim.Datacenter managed object.

    service_instance
        The Service Instance Object from which to obtain datacenter.

    datacenter_name
        The datacenter name
    )r@zDatacenter 'z' was not foundr)rBrr5r�)rM�datacenter_namer�rrr�get_datacenter�s

�rDc
Cs�t|�}t�d|�z|�|�}W|Stjjy/}zt�|�tj	�
d|j����d}~wtjjyH}zt�|�tj	�
|j
��d}~wtjy`}zt�|�tj	�|j
��d}~ww)z�
    Creates a datacenter.

    .. versionadded:: 2017.7.0

    service_instance
        The Service Instance Object

    datacenter_name
        The datacenter name
    zCreating datacenter '%s'raN)r�rr,ZCreateDatacenterr	r=rdr>rr5rerfrgr3r
rhri)rMrCZroot_folderZdc_objrKrrr�create_datacenter�s(�

��
�
��rEc	s�t|�}t�d�|�t||d�}tjjjddtj	tjjjddtj
d�gd�}�fd	d
�t|tj|dg|d�D�}|sHt
j�d
��d|�d���|dS)z�
    Returns a cluster in a datacenter.

    dc_ref
        The datacenter reference

    cluster
        The cluster to be retrieved
    z,Retrieving cluster '%s' from datacenter '%s'rP�
hostFolderTr�Fr�r�cs g|]}|d�kr|d�qSr�rr���clusterrrr��s
�zget_cluster.<locals>.<listcomp>rQr�z	Cluster 'z' was not found in datacenter 'rr)r�rr,ryr
r�r�r�r	r�r�r��ClusterComputeResourcerr5r�)r�rHr�rSr�r�rrGr�get_cluster�s4
���

���rJc
Cs�t|�}t�d||�z
|j�||�WdStjjy2}zt�|�t	j
�d|j����d}~wtjj
yK}zt�|�t	j
�|j��d}~wtjyc}zt�|�t	j
�|j��d}~ww)z�
    Creates a cluster in a datacenter.

    dc_ref
        The parent datacenter reference.

    cluster_name
        The cluster name.

    cluster_spec
        The cluster spec (vim.ClusterConfigSpecEx).
        Defaults to None.
    z(Creating cluster '%s' in datacenter '%s'raN)r�rr,rFZCreateClusterExr	r=rdr>rr5rerfrgr3r
rhri)r��cluster_name�cluster_specr�rKrrr�create_cluster�s&

��
�
��rMc
Cs�t|�}t�d|�z	|j|dd�}WnNtjjy0}zt�|�tj	�
d|j����d}~wtjjyI}zt�|�tj	�
|j
��d}~wtjya}zt�|�tj	�|j
��d}~wwt||d�dS)z�
    Updates a cluster in a datacenter.

    cluster_ref
        The cluster reference.

    cluster_spec
        The cluster spec (vim.ClusterConfigSpecEx).
        Defaults to None.
    zUpdating cluster '%s'T)�modifyraNZClusterUpdateTask)r�rr,ZReconfigureComputeResource_Taskr	r=rdr>rr5rerfrgr3r
rhrir)Zcluster_refrLrKrrKrrr�update_clusters(

��
�
��rOcCr<)z�
    Returns a list of clusters associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain clusters.
    )r'r	rIr�rrr�
list_clusters+r>rPcCr<)z�
    Returns a list of datastore clusters associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain datastore clusters.
    )r'r	�
StoragePodr�rrr�list_datastore_clusters5r>rRcCr<)z�
    Returns a list of datastores associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain datastores.
    )r'r	�	Datastorer�rrr�list_datastores?r>rTc
Csg}t|||d�}|D]{}z|jjd|j�d|��|d�}WnNtjjy;}	zt�|	�t	j
�d|	j����d}	~	wtjj
yT}	zt�|	�t	j
�|	j��d}	~	wtjyl}	zt�|	�t	j
�|	j��d}	~	wwz|�t	jj�||d��Wqt	j
jy�Yqw|S)a�
    Get the files with a given browser specification from the datastore.

    service_instance
        The Service Instance Object from which to obtain datastores.

    directory
        The name of the directory where we would like to search

    datastores
        Name of the datastores

    container_object
        The base object for searches

    browser_spec
        BrowserSpec object which defines the search criteria

    return
        list of vim.host.DatastoreBrowser.SearchResults objects
    )�datastore_names�[z] )Z
datastorePathZ
searchSpecraNzquery virtual machine files)�get_datastoresZbrowserZSearchDatastore_TaskrQr	r=rdrr>rr5rerfrgr3r
rhrir�r�vmwarer�VMwareFileNotFoundError)
rM�	directoryZ
datastoresZcontainer_objectZbrowser_spec�filesZdatastore_objectsZdatobjrrKrrr�get_datastore_filesIsF�
�

��
�
�����r\c
s�t|�}�r
t�d|�nt�d|����r(t|tj�s(tj�d�	|j
j����s��r�t�d��t|||�}tj
j�|dg�}|�dg�}g}	dd�|D�D]!}
�fdd�|
jD�s]qPt�d	|
jd
d�|
jD��|	�|
j�qPt�d|	��r���|	�n|	��s��s�t�d��gSt�d
��t|tj�r�tjjjdddtjd�}njt|tj�r�tjjjdddtjd�}nWt|tj�r�tjjjdddtjd�}nDt|tj�r�tjjjdddtjd�}n1t|tj��rt|�dk�rtjjjdtjjjddtjd�gdtjd�}ntj�d|j
j�d���t|tjdg||d�}t�dt|����fdd�|D�}t�dd d�|D��d!d�|D�S)"a	
    Returns a list of vim.Datastore objects representing the datastores visible
    from a VMware object, filtered by their names, or the backing disk
    cannonical name or scsi_addresses

    service_instance
        The Service Instance Object from which to obtain datastores.

    reference
        The VMware object from which the datastores are visible.

    datastore_names
        The list of datastore names to be retrieved. Default value is None.

    backing_disk_ids
        The list of canonical names of the disks backing the datastores
        to be retrieved. Only supported if reference is a vim.HostSystem.
        Default value is None

    get_all_datastores
        Specifies whether to retrieve all disks in the host.
        Default value is False.
    z)Retrieving all datastores visible to '%s'zLRetrieving datastores visible to '%s': names = (%s); backing disk ids = (%s)z?Unsupported reference type '{}' when backing disk filter is setz.Filtering datastores with backing disk ids: %szfileSystemVolumeInfo.mountInfocSs g|]}t|jtj�r|j�qSr)r<Zvolumer	ZHostVmfsVolumer�rrrr��s
��z"get_datastores.<locals>.<listcomp>csg|]	}|j�vr|�qSr��diskName�r��e)�backing_disk_idsrrr��rz(Found datastore '%s' for disk id(s) '%s'cSr1rr]r_rrrr��r3z#Datastore found for disk filter: %szYNo datastore to be filtered after retrieving the datastores backed by the disk id(s) '%s'zdatastore_names = %sZhost_datastore_traversal�	datastoreFr�Zcluster_datastore_traversalZdatacenter_datastore_traversalZdatastore_cluster_traversalr�ZDatacentersr�)rr�r�r�zUnsupported reference type 'rrQ)r�r�r�r�zRetrieved %s datastorescs g|]}�s|d�vr|�qSrPrr�)rU�get_all_datastoresrrr�	� zFiltered datastores: %scS�g|]}|d�qSrPrr�rrrr�	�cSre)r�rr�rrrr�	rf) r�rr,r<r	r�rr5rrrr��get_storage_systemrrXr�r��extentrQr��extendr
r�r�r�rIr�rQr�r�rSr�)
rMZ	referencerUrarcr[�storage_systemr�Zmount_infosZdisk_datastoresZvolr�r�r)rarUrcrrW�s��
��
�������
������rWc
Cs�t|�}t�d||�z|�|�WdStjjy0}zt�|�tj	�
d|j����d}~wtjjyI}zt�|�tj	�
|j
��d}~wtjya}zt�|�tj	�|j
��d}~ww)z�
    Renames a datastore

    datastore_ref
        vim.Datastore reference to the datastore object to be changed

    new_datastore_name
        New datastore name
    zRenaming datastore '%s' to '%s'raN)r�rr,ZRenameDatastorer	r=rdr>rr5rerfrgr3r
rhri)�
datastore_refZnew_datastore_name�ds_namerKrrr�rename_datastore	s&


��
�
��rmcCsh|st|�}tjjjdtjdd�}t|tjdg||d�}|s(t	j
�d|�d���t�
d|�|d	d
S)z)
    Returns a host's storage system
    �configManager.storageSystemF�rr�r�Z
systemFile�r�r�r��Host's '�"' storage system was not retrievedz[%s] Retrieved storage systemrr�)r�r
r�r�r�r	r�r��HostStorageSystemrr5r�rr,)rM�host_refrtr��objsrrrrg7	s$��
�rgc
Cs�z	|j|gd�}WnNtjjy&}zt�|�tj�d|j	����d}~wtjj
y?}zt�|�tj�|j��d}~wtj
yW}zt�|�tj�|j��d}~wwt�d|d�|dS)z`
    Returns partition information for a device path, of type
    vim.HostDiskPartitionInfo
    )�
devicePathraN�partition_info = %sr)ZRetrieveDiskPartitionInfor	r=rdrr>rr5rerfrgr3r
rhrir,)rj�device_pathZpartition_infosrKrrr�_get_partition_infoQ	s*
�

��
�
��ryc
spt�d�dd�|jjD�}|stj�d�|j���|d�t	j
|jj|jjd�}d�_z|j
|t	jj|d�}WnNt	jjyU}zt�|�tj�d	|j����d
}~wt	jjyn}zt�|�tj�|j��d
}~wtjy�}zt�|�tj�|j��d
}~wwt�d|�t�d��fd
d�|jjD�}|s�tj�d�|j���t�d|d�|d|jfS)z�
    Computes the new disk partition info when adding a new vmfs partition that
    uses up the remainder of the disk; returns a tuple
    (new_partition_number, vim.HostDiskPartitionSpec
    zUAdding a partition at the end of the disk and getting the new computed partition speccSr)Znone)r��r��prrrr�u	rz4_get_new_computed_partition_spec.<locals>.<listcomp>z+Free partition was not found on device '{}'r)�total�	partition�vmfs)rvZpartitionFormat�layoutraNzcomputed partition info = {0}zRetrieving new partition numbercsTg|]&}|jj�jjks�jjdkr(|jjdkr(|jj�jjkr(|jdkr|j�qS)rrmr~)�start�block�endr�r}rz�Zfree_partitionrrr��	s
�zANew partition was not found in computed partitions of device '{}'znew partition number = %s)rr,rr}rr5ZVMwareObjectNotFoundErrorrZ
deviceNamer	ZHostDiskPartitionLayoutr|r�ZComputeDiskPartitionInfoZ$HostDiskPartitionInfoPartitionFormatZgptr=rdr>rerfrgr3r
rhriZVMwareNotFoundErrorr�)rjrx�partition_infoZfree_partitionsrZcomputed_partition_inforKZpartition_numbersrr�r� _get_new_computed_partition_speci	sb����
�

��
�
��

���r�c
CsTt|�}|j}t�d||||�|st||d�}t|||�}|}t||j�}	t�d|	�t	||j|	�\}
}t
jt
j||t
j
||
d�d�|j|d�}z	|jj�|�}
WnNt
jjyo}zt�|�tj�d|j����d}~wt
jjy�}zt�|�tj�|j��d}~wtjy�}zt�|�tj�|j��d}~wwt�d	||�|
S)
aA
    Creates a VMFS datastore from a disk_id

    host_ref
        vim.HostSystem object referencing a host to create the datastore on

    datastore_name
        Name of the datastore

    disk_ref
        vim.HostScsiDislk on which the datastore is created

    vmfs_major_version
        VMFS major version to use
    z>Creating datastore '%s' on host '%s', scsi disk '%s', vmfs v%srPrw)r^r})ZmajorVersionZ
volumeNamerh)r~ZdiskUuidr}raNz#Created datastore '%s' on host '%s')r��
canonicalNamerr�ryrgryrvr,r�r	ZVmfsDatastoreCreateSpecZHostVmfsSpecZHostScsiDiskPartitionr0r�ZdatastoreSystemZCreateVmfsDatastorer=rdr>rr5rerfrgr3r
rhri)rtZdatastore_nameZdisk_refZvmfs_major_versionrjrt�disk_idrSZtarget_diskr�Znew_partition_numberZpartition_specr�Zds_refrKrrr�create_vmfs_datastore�	s`�����

��
�
��r�cCsp|st|�}t|�}tjjjdtjdd�}t|tj	dg||d�}|s,t
j�d|�d���t
�d|�|d	d
S)z�
    Returns a host's datastore system

    host_ref
        Reference to the ESXi host

    hostname
        Name of the host. This argument is optional.
    zconfigManager.datastoreSystemFrorbrprqz$' datastore system was not retrievedz[%s] Retrieved datastore systemrr�)r�ryr
r�r�r�r	r�r�ZHostDatastoreSystemrr5r�rr,)rtrtrMr�rurrr�get_host_datastore_system�	s&��
�r�c
Cs"t|gd��}|d}t�d|�|�d�}|s"tj�d|�d���t|dj�}t	|dj|d�}z|�
|�WnNtjj
yV}zt�|�tj�d	|j����d
}~wtjjyo}zt�|�tj�|j��d
}~wtjy�}zt�|�tj�|j��d
}~wwt�d||�d
S)z�
    Creates a VMFS datastore from a disk_id

    service_instance
        The Service Instance Object containing the datastore

    datastore_ref
        The reference to the datastore to remove
    )r�inforQrQzRemoving datastore '%s'rzDatastore 'z+' can't be removed. No attached hosts foundr)rtraNz[%s] Removed datastore '%s')r�rr�r�rr5rer�r�r�ZRemoveDatastorer	r=rdr>rfrgr3r
rhrir,)rMrkZds_propsrlZds_hostsrtZhost_ds_systemrKrrr�remove_datastore
s8


�

��
�
��r�cCs�dg}|r
|s
tj�d��|sg}|st|�}nt||�}|r$|�d�t|tj||d�}t	�
ddd�|D��g}|D]/}	|rTt|	dtj�sIq<t
|	d�}
|
|krTq<|r^|�|	d�q<|	d|vrk|�|	d�q<|S)	a�
    Returns a list of vim.HostSystem objects representing ESXi hosts
    in a vcenter filtered by their names and/or datacenter, cluster membership.

    service_instance
        The Service Instance Object from which to obtain the hosts.

    datacenter_name
        The datacenter name. Default is None.

    host_names
        The host_names to be retrieved. Default is None.

    cluster_name
        The cluster name - used to restrict the hosts retrieved. Only used if
        the datacenter is set.  This argument is optional.

    get_all_hosts
        Specifies whether to retrieve all hosts in the container.
        Default value is False.
    rQz7Must specify the datacenter when specifying the cluster�parent�r�r�zRetrieved hosts: %scSrerPr)r��hrrrr�j
rfzget_hosts.<locals>.<listcomp>r�)rr5rr�rDr�r�r	r�rr,r<rIr�)rMrC�
host_namesrKZ
get_all_hostsr�Zstart_point�hostsZfiltered_hostsr�rrrr�	get_hosts6
sD�


��r�c
sT|st|�}|st|||�}z|j}WnNtjjy0}zt�|�tj	�
d|j����d}~wtjjyI}zt�|�tj	�
|j
��d}~wtjya}zt�|�tj	�|j
��d}~ww|sntj	�d|�d���|j}|s}tj	�d|�d���|jdur�tj	�d|�d���i}|jD]�|��fdd	��jD��q�t�d
||�|S)a�
    Returns a map between the scsi addresses and the keys of all luns on an ESXi
    host.
        map[<scsi_address>] = <lun key>

    service_instance
        The Service Instance Object from which to obtain the hosts

    host_ref
        The vim.HostSystem object representing the host that contains the
        requested disks.

    storage_system
        The host's storage system. Default is None.

    hostname
        Name of the host. Default is None.
    raNrq�'' storage device info was not retrievedz"' multipath info was not retrievedz"No luns were retrieved from host 'rcs i|]}|j�d�d�j�qS)r�r)rQrs�lunrz��lrr�
<dictcomp>�
rdz4_get_scsi_address_to_lun_key_map.<locals>.<dictcomp>z+Scsi address to lun id map on host '%s': %s)r�rg�storageDeviceInfor	r=rdrr>rr5rerfrgr3r
rhrir�Z
multipathInfor��updaterr,)rMrtrjrt�device_inforKZmultipath_info�lun_key_by_scsi_addrrr�r� _get_scsi_address_to_lun_key_map�
sR


��
�
��
�
�

�
�r�c
Cs6|st|�}|s t||d�}t|||�}|s tj�d|�d���z|j}WnNtjj	yB}zt
�|�tj�d|j
����d}~wtjjy[}zt
�|�tj�|j��d}~wtjys}zt
�|�tj�|j��d}~ww|s�tj�d|�d���|j}|r�t
�d|dd	�|D��|St
�d
|�gS)a>
    Returns a list of all vim.HostScsiDisk objects in a disk

    host_ref
        The vim.HostSystem object representing the host that contains the
        requested disks.

    storage_system
        The host's storage system. Default is None.

    hostname
        Name of the host. This argument is optional.
    rPrqrrraNr�z$Retrieved scsi luns in host '%s': %scSr1r�r��r�r�rrrr��
r3z get_all_luns.<locals>.<listcomp>z#Retrieved no scsi_luns in host '%s')r�ryrgrr5r�r�r	r=rdrr>rerfrgr3r
rhriZscsiLunr,)rtrjrtrSr�rK�	scsi_lunsrrr�get_all_luns�
sP
�


��
�
��
��r�csb|st|�}t||d�}|st|||�}t||||�}dd�t|||�D���fdd�|��D�S)a]
    Returns a map of all vim.ScsiLun objects on a ESXi host keyed by their
    scsi address

    host_ref
        The vim.HostSystem object representing the host that contains the
        requested disks.

    storage_system
        The host's storage system. Default is None.

    hostname
        Name of the host. This argument is optional.
    rPcSsi|]}|j|�qSrr�r��drrrr�
s�z/get_scsi_address_to_lun_map.<locals>.<dictcomp>csi|]	\}}|�|�qSrr)r��	scsi_addrZlun_key�Zluns_to_key_maprrr�
s��)r�ryrgr�r�r�)rtrjrtrSZlun_ids_to_scsi_addr_maprr�r�get_scsi_address_to_lun_map�
s�
�
�r�c
s�t|�}�r
t�d|�nt�d|����s�sgSt||d�}t|||�}g��rCt||||�}�fdd�|��D��t�d��t||�}���fdd�|D�}	t�d|d	d�|	D��|	S)
aS
    Returns a list of vim.HostScsiDisk objects representing disks
    in a ESXi host, filtered by their cannonical names and scsi_addresses

    host_ref
        The vim.HostSystem object representing the host that contains the
        requested disks.

    disk_ids
        The list of canonical names of the disks to be retrieved. Default value
        is None

    scsi_addresses
        The list of scsi addresses of the disks to be retrieved. Default value
        is None

    get_all_disks
        Specifies whether to retrieve all disks in the host.
        Default value is False.
    z!Retrieving all disks in host '%s'z@Retrieving disks in host '%s': ids = (%s); scsi addresses = (%s)rPcsg|]
\}}|�vr|�qSrr)r�r�r�)�scsi_addressesrrr�<s
�zget_disks.<locals>.<listcomp>z&disk_keys based on scsi_addresses = %scs8g|]}t|tj�r�s�r|j�vs|j�vr|�qSr)r<r	�HostScsiDiskr�r�)r�Zdisk)�disk_ids�	disk_keys�
get_all_disksrrr�Ds
���

�
z Retrieved disks in host '%s': %scSr1rr�r�rrrr�Ur3)r�rr,ryrgr�r�r�)
rtr�r�r�rtrSrjr�r�Z
scsi_disksr)r�r�r�r�r�	get_diskss@��
�
��r�c
s�t|�}t|�}|st|||�}t|dg�}|�d�s%tj�d|�d���t�	d|t
|d�d�dd�|dD����fdd�|dD�}|sUtj�d	��d
|�d���t�	d||dj�t
||dj�}t�	d
|t
|jj���|S)a
    Returns all partitions on a disk

    host_ref
        The reference of the ESXi host containing the disk

    disk_id
        The canonical name of the disk whose partitions are to be removed

    storage_system
        The ESXi host's storage system. Default is None.
    �storageDeviceInfo.scsiLunz#No devices were retrieved in host 'r�[%s] Retrieved %s devices: %s�, cSr1rr�r�rrrr�wr3z+get_disk_partition_info.<locals>.<listcomp>c�&g|]}t|tj�r|j�kr|�qSr�r<r	r�r�r��r�rrr�y�
�
��Disk '�' was not found in host '�[%s] device_path = %srz+[%s] Retrieved %s partition(s) on disk '%s')r�ryrgr�r�rr5r�rr,r�rcrvryr�r})rtr�rjrtrMr��disksr�rr�r�get_disk_partition_infoZsB
�

�
�
��
�r�c	s�|st|�}|st|||�}tjjjdtjdd�}t|tj	dg||d�}|s0t
j�d|�d���t
�d|t|d	�dg��d
�dd�|d	�dg�D����fd
d�|d	�dg�D�}|slt
j�d��d|�d���t
�d||d	j�z
|�|d	jt���WnNtjjy�}zt
�|�t
j�d|j����d}~wtjjy�}zt
�|�t
j�|j��d}~wtjy�}zt
�|�t
j�|j��d}~wwt
�d|��dS)a�
    Erases all partitions on a disk

    in a vcenter filtered by their names and/or datacenter, cluster membership

    service_instance
        The Service Instance Object from which to obtain all information

    host_ref
        The reference of the ESXi host containing the disk

    disk_id
        The canonical name of the disk whose partitions are to be removed

    hostname
        The ESXi hostname. Default is None.

    storage_system
        The ESXi host's storage system. Default is None.
    rnFror��r�r�rqz' devices were not retrievedr�rr�cSr1rr�r�rrrr��r3z)erase_disk_partitions.<locals>.<listcomp>cr�rr�r�r�rrr��r�r�r�rr�raNz#[%s] Erased partitions on disk '%s')r�rgr
r�r�r�r	r�r�rsrr5r�rr,r�r�rcrvZUpdateDiskPartitionsZHostDiskPartitionSpecr=rdr>rerfrgr3rhri)	rMrtr�rtrjr��resultsr�rKrr�r�erase_disk_partitions�sl��
���
���

��
�
��r�c	
sNt|�}�r
t�d|�nt�d|���sgSz|jj}WnNtjjy;}zt�|�t	j
�d|j����d}~wtjj
yT}zt�|�t	j
�|j��d}~wtjyl}zt�|�t	j
�|j��d}~ww|syt	j
�d|�d���|j}|s�t	j
�d|�d���|j}|s�gS��fdd	�|D�}t�d
|dd	�|D��|S)a�
    Returns a list of vim.VsanHostDiskMapping objects representing disks
    in a ESXi host, filtered by their cannonical names.

    host_ref
        The vim.HostSystem object representing the host that contains the
        requested disks.

    cache_disk_ids
        The list of cannonical names of the cache disks to be retrieved. The
        canonical name of the cache disk is enough to identify the disk group
        because it is guaranteed to have one and only one cache disk.
        Default is None.

    get_all_disk_groups
        Specifies whether to retrieve all disks groups in the host.
        Default value is False.
    z'Retrieving all disk groups on host '%s'zARetrieving disk groups from host '%s', with cache disk ids : (%s)raNzNo host config found on host 'rz$No vsan storage info found on host 'cs g|]}�s|jj�vr|�qSr��ssdr�)r�Zdm��cache_disk_ids�get_all_disk_groupsrrr�s��z"get_diskgroups.<locals>.<listcomp>z<Retrieved disk groups on host '%s', with cache disk ids : %scSsg|]}|jj�qSrr�r�rrrr�rf)r�rr,r�ZvsanHostConfigr	r=rdr>rr5rerfrgr3r
rhrir�ZstorageInfoZdiskMapping)	rtr�r�rtZvsan_host_configrKZvsan_storage_infoZvsan_disk_mappingsZdisk_groupsrr�r�get_diskgroups�s`�

��
�
��
�
���r�cCsp|jj|kstj�d�|jj|���dd�|jD�}t|�t|�kr0tj�d�t|�t|����t�	d|�dS)zw
    Checks that the disks in a disk group are as expected and raises
    CheckError exceptions if the check fails
    z?Incorrect diskgroup cache disk; got id: '{}'; expected id: '{}'cSr1rr�r�rrrr�,r3z-_check_disks_in_diskgroup.<locals>.<listcomp>z;Incorrect capacity disks; got ids: '{}'; expected ids: '{}'z2Checked disks in diskgroup with cache disk id '%s'T)
r�r�rr5rrZnonSsd�sortedrr,)Z
disk_groupZ
cache_disk_idZcapacity_disk_idsZ
non_ssd_disksrrr�_check_disks_in_diskgroup!s����r�cCs�t|�}t|�}t�d|�|s?tjjjdtj	dd�}t
|tjdg||d�}|r/|d�d�s7t�d|�d	S|dddSt
|dg�}|sOt�d|�d	S|ddS)
a�
    Returns a vim.HostScsiDisk if the host cache is configured on the specified
    host, other wise returns None

    host_ref
        The vim.HostSystem object representing the host that contains the
        requested disks.

    host_cache_manager
        The vim.HostCacheConfigurationManager object representing the cache
        configuration manager on the specified host. Default is None. If None,
        it will be retrieved in the method
    z&Retrieving the host cache on host '%s'�'configManager.cacheConfigurationManagerFroZcacheConfigurationInfor�rzHost '%s' has no host cacheN)r�ryrr,r
r�r�r�r	r�r�ZHostCacheConfigurationManagerr�r�)rt�host_cache_managerrtrMr�r�rrr�get_host_cache8s6���r�c	
Cs2t|�}|st|dg�}|�d�stj�d|�d���|d}t�d||j|�t	j
||d�}t�d|�z|�|�}WnNt	jj
yY}zt�|�tj�d|j����d}~wt	jjyr}zt�|�tj�|j��d}~wtjy�}zt�|�tj�|j��d}~wwt||d	�t�d
|�dS)aB
    Configures the host cahe of the specified host

    host_ref
        The vim.HostSystem object representing the host that contains the
        requested disks.

    datastore_ref
        The vim.Datastore opject representing the datastore the host cache will
        be configured on.

    swap_size_MiB
        The size in Mibibytes of the swap.

    host_cache_manager
        The vim.HostCacheConfigurationManager object representing the cache
        configuration manager on the specified host. Default is None. If None,
        it will be retrieved in the method
    r�zHost 'z' has no host cachezIConfiguring the host cache on host '%s', datastore '%s', swap size=%s MiB)rbZswapSizezhost_cache_spec=%sraNZHostCacheConfigurationTaskz"Configured host cache on host '%s'T)r�r�r�rr5r�rr,rQr	ZHostCacheConfigurationSpecZConfigureHostCache_Taskr=rdr>rerfrgr3r
rhrir)	rtrkZ
swap_size_MiBr�rtr�r�rrKrrr�configure_host_cacheesP�

���

��
�
��r�cCr<)z�
    Returns a list of hosts associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain hosts.
    )r'r	r�r�rrr�
list_hosts�r>r�c	Cs�dg}|sg}|rt||�}nt|�}t|tj||d�}g}|D]}|s*|d|vr1|�|d�q |s>tj�d�	||���|S)al
    Retrieves resource pool objects

    service_instance
        The service instance object to query the vCenter

    resource_pool_names
        Resource pool names

    datacenter_name
        Name of the datacenter where the resource pool is available

    get_all_resource_pools
        Boolean

    return
        Resourcepool managed object reference
    rQr�r�zIThe resource pools with properties names={} get_all={} could not be found)
rDr�r�r	�ResourcePoolr�rr5r�r)	rMZresource_pool_namesrCZget_all_resource_poolsr�r�Zresource_poolsZselected_pools�poolrrr�get_resource_pools�s2����r�cCr<)z�
    Returns a list of resource pools associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain resource pools.
    )r'r	r�r�rrr�list_resourcepools�r>r�cCr<)z�
    Returns a list of networks associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain networks.
    )r'r	r%r�rrr�
list_networks�r>r�cCr<)z�
    Returns a list of VMs associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain VMs.
    )r'r	�VirtualMachiner�rrr�list_vms�r>r�cCr<)z�
    Returns a list of folders associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain folders.
    )r'r	r�r�rrr�list_folders
r>r�cCr<)z�
    Returns a list of distributed virtual switches associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain distributed virtual switches.
    )r'r	r�r�rrrr�
r>r�cCr<)z�
    Returns a list of vApps associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain vApps.
    )r'r	Z
VirtualAppr�rrr�
list_vapps
r>r�cCst|tjj�S)z�
    Returns a list of distributed virtual portgroups associated with a given service instance.

    service_instance
        The Service Instance Object from which to obtain distributed virtual switches.
    )r'r	r�rr�rrr�list_portgroups
sr�rmr�c
Cs�d}t��}t�d||jj�z|j}Wngtjjy1}zt�	|�t
j�d|j
����d}~wtjjyJ}zt�	|�t
j�|j��d}~wtjjyc}zt�	|�t
j�|j��d}~wtjy{}zt�	|�t
j�|j��d}~ww|jdks�|jdk�r-||dkr�d�|||�}	|dkr�t�|	�nt�|	�t�d	t��|d	�|d
7}z|j}Wnitjjy�}zt�	|�t
j�d|j
����d}~wtjjy�}zt�	|�t
j�|j��d}~wtjj�y	}zt�	|�t
j�|j��d}~wtj�y"}zt�	|�t
j�|j��d}~ww|jdks�|jdks�|jdk�rOd�|||�}	|dk�rGt�|	�|jSt�|	�|jSz|j�tjj�yp}zt�	|�t
j�d|j
����d}~wtjj�y�}zt�	|�t
j�|j��d}~wtjj�y�}zt�	|�t
j�|j��d}~wtjj�y�}zt�	|�t
j�|j��d}~wtjj�y�}zt�	|�|j}
|j�r�|
�d
|jdj�d�}
t
j�|
��d}~ww)a3
    Waits for a task to be completed.

    task
        The task to wait for.

    instance_name
        The name of the ESXi host, vCenter Server, or Virtual Machine that
        the task is being run on.

    task_type
        The type of task being performed. Useful information for debugging purposes.

    sleep_seconds
        The number of seconds to wait before querying the task again.
        Defaults to ``1`` second.

    log_level
        The level at which to log task information. Default is ``debug``,
        but ``info`` is also supported.
    rztask = %s, task_type = %sraNZrunningZqueuedz+[ {} ] Waiting for {} task to finish [{} s]r�g�?rm�successz3[ {} ] Successfully completed {} task in {} secondsz (�)) �timerr,rr�r�r	r=rdr>rr5rerfZFileNotFoundrYr3rgr
rhri�staterr��sleep�resultr�SystemErrorZVMwareSystemErrorZInvalidArgumentZfaultMessager;)rZ
instance_nameZ	task_typeZ
sleep_secondsZ	log_levelZtime_counterZ
start_timeZ	task_inforKr3Zexc_messagerrrr)
s�


��
�
�
���



��
�
�
����


�

��
�
�
�
��rcs�|r|stjj�||�}|sgd�}tjjj|tj|||d�}�fdd�|D�}|s0tj�d��t	|�dkr@tj�
d�dg���|d	S)
a�
    Get virtual machine properties based on the traversal specs and properties list,
    returns Virtual Machine object with properties.

    service_instance
        Service instance object to access vCenter

    name
        Name of the virtual machine.

    datacenter
        Datacenter name

    vm_properties
        List of vm properties.

    traversal_spec
        Traversal Spec object(s) for searching.

    parent_ref
        Container Reference object for searching under a given object.
    )rQzconfig.hardware.devicezsummary.storage.committedzsummary.storage.uncommittedzsummary.storage.unsharedz
layoutEx.filezconfig.guestFullNamezconfig.guestIdz	guest.netzconfig.hardware.memoryMBzconfig.hardware.numCPUzconfig.files.vmPathNamezsummary.runtime.powerStatezguest.toolsStatusr�csg|]
}|d�kr|�qSrPr)r�r�rPrrr��
sz&get_vm_by_property.<locals>.<listcomp>z"The virtual machine was not found.rm� zSMultiple virtual machines were found with thesame name, please specify a container.r)rrrXrDr�r	r�r5r�r��VMwareMultipleObjectsErrorrc)rMrQ�
datacenter�
vm_propertiesr�rZvm_listZvm_formattedrrPr�get_vm_by_property�
s0�����r�c
	Cst�d�|r.t||dgd�}tjjj|dgd�}d|vr#|d}|Stj�d�	ddg���d	|vrZtjj�
||d	g|�}t|�d
krTtj�d�	dd�
|d	�g���|d
}|S|r~tjj�||�}tjjj|dgd�}	d|	vrx|	d}|Stj�d��|S)z�
    Returns a Folder Object

    service_instance
        Service instance object

    datacenter
        Name of the datacenter

    placement
        Placement dictionary

    base_vm_name
        Existing virtual machine name (for cloning)
    zRetrieving folder informationrQ)r�r��r�r�zThe virtual machine parent�object is not definedZfolderrm�'Multiple instances are available of thezspecified folder {}r�vmFolderz.The datacenter vm folder object is not defined)rr,r�rrrXr�r5r�rcZget_foldersr�r�rrD)
rMr��	placementZbase_vm_name�	vm_objectZvm_props�
folder_objectZfolder_objects�datacenter_objectZdc_propsrrr�
get_folder�
sT
�� �����������r�cCst�d�d\}}d|vr�t|||dgd�}|s)tj�d�dd�|d�g���zt|dd	gd
�}|d	}WnBt	j
jyzt	j
jj
ddtjt	j
jj
d	d
tjd�gd�}t|tj|ddg|d�}|rm|dd}ntj�d�|d���Ynw|d}||fSd|vr�t||dg|d�}	t|	�dkr�tj�d�dd�|d�g���|	d}t|dgd
�}
d|
vr�|
d}||fStj�d�ddg���d|vr�t||�}t||d�}t|d	gd
�}
d	|
vr�|
d	}ntj�d�ddg���|}||fStj�d�dg���)aP
    To create a virtual machine a resource pool needs to be supplied, we would like to use the strictest as possible.

    datacenter
        Name of the datacenter

    placement
        Dictionary with the placement info, cluster, host resource pool name

    return
        Resource pool, cluster and host object if any applies
    z Retrieving placement information�NNr)rCr�r�zThe specified hostz{} cannot be found.rZresourcePoolr�r�TFr�r�rQr�r�z-The resource pool of host {} cannot be found.Zresourcepool)rCrmr�zspecified host {}.zThe resource pool's parentr�rHzThe cluster's resource poolzPlacement is not defined.)rr,r�rr5r�rcrr�r
r�r�r�r�r	r�rIr�r�r�r�r�rDrJ)rMr�r��resourcepool_objectZplacement_objectZhost_objectsZ
host_propsr�Z
resourcepoolsZresourcepool_objectsZ	res_propsr�Zcluster_objectZ
clus_propsrrr�
get_placements�

����
����
�����*��������
�
��
�r�cCsd|��dkrt|dd�}n|��dkrt|d�}n|��dkr't|�}ntj�d��|dd�S)z�
    Converts the given size to KB based on the unit, returns a long integer.

    unit
        Unit of the size eg. GB; Note: to VMware a GB is the same as GiB = 1024MiB
    size
        Number which represents the size
    Zgbr�ZmbZkbzThe unit is not specifiedZKB)�size�unit)�lower�intrr5r)r�r�Ztarget_sizerrr�
convert_to_kb~s	

r��onc
Cs�|dkr[z|��}d}Wn�tjjy)}zt�|�tj�d|j	����d}~wtjj
yB}zt�|�tj�|j��d}~wtj
yZ}zt�|�tj�|j��d}~ww|dkr�z|��}d}WnTtjjy�}zt�|�tj�d|j	����d}~wtjj
y�}zt�|�tj�|j��d}~wtj
y�}zt�|�tj�|j��d}~wwtj�d��zt|t|�|�W|Stjjy�}ztj�d�d	d
|��g���d}~ww)z�
    Powers on/off a virtual machine specified by its name.

    virtual_machine
        vim.VirtualMachine object to power on/off virtual machine

    action
        Operation option to power on/off the machine
    r�zpower onraNZoffz	power offz!The given action is not supportedr�zAn error occurred during powerz!operation, a file was not found: )ZPowerOnr	r=rdrr>rr5rerfrgr3r
rhriZPowerOffrrr�rYZVMwarePowerOnErrorrc)Zvirtual_machine�actionrZ	task_namerKrrr�power_cycle_vm�sh


��
�
��

��
�
��
������r�c
Cs�z|rt|tj�r|j|||d�}n|j||d�}WnNtjjy7}zt�|�tj	�
d|j����d}~wtjjyP}zt�|�tj	�
|j
��d}~wtjyh}zt�|�tj	�|j
��d}~wwt||ddd�}|S)a�
    Creates virtual machine from config spec

    vm_name
        Virtual machine name to be created

    vm_config_spec
        Virtual Machine Config Spec object

    folder_object
        vm Folder managed object reference

    resourcepool_object
        Resource pool object where the machine will be created

    host_object
        Host object where the machine will ne placed (optional)

    return
        Virtual Machine managed object reference
    )r�r)r�raNz
CreateVM Task�
r�)r<r	r�Z
CreateVM_Taskr=rdrr>rr5rerfrgr3r
rhrir)�vm_name�vm_config_specr�r��host_objectrrKr�rrr�	create_vm�s0��

��
�
��r�c
Csz|r|jj||d||d�}n
|jj||d|d�}WnNtjjy7}zt�|�tj�	d|j
����d}~wtjjyP}zt�|�tj�	|j��d}~wt
jyh}zt�|�tj�|j��d}~wwz	t||d�}W|Stjjy�}z	tj�d�|���d}~ww)a$
    Registers a virtual machine to the inventory with the given vmx file, on success
    it returns the vim.VirtualMachine managed object reference

    datacenter
        Datacenter object of the virtual machine, vim.Datacenter object

    name
        Name of the virtual machine

    vmx_path:
        Full path to the vmx file, datastore name should be included

    resourcepool
        Placement resource pool of the virtual machine, vim.ResourcePool object

    host
        Placement host of the virtual machine, vim.HostSystem object
    F)rrQ�
asTemplaterr�)rrQr�r�raNzRegisterVM TaskzYAn error occurred during registration operation, the configuration file was not found: {})r�ZRegisterVM_Taskr	r=rdrr>rr5rerfrgr3r
rhrirrYZVMwareVmRegisterErrorr)r�rQZvmx_pathr�r�rrK�vm_refrrr�register_vm�sL���

��
�
������r�c
Cs�t|�}t�d|�z|�|�}WnNtjjy.}zt�|�tj	�
d|j����d}~wtjjyG}zt�|�tj	�
|j
��d}~wtjy_}zt�|�tj	�|j
��d}~wwt||d�}|S)z�
    Updates the virtual machine configuration with the given object

    vm_ref
        Virtual machine managed object reference

    vm_config_spec
        Virtual machine config spec object to update
    zUpdating vm '%s'raNzReconfigureVM Task)r�rr,ZReconfigVM_Taskr	r=rdr>rr5rerfrgr3r
rhrir)r�r�r�rrKrrr�	update_vm/s*


��
�
��r�c
Cs�t|�}t�d|�z|��}WnNtjjy-}zt�|�tj	�
d|j����d}~wtjjyF}zt�|�tj	�
|j
��d}~wtjy^}zt�|�tj	�|j
��d}~wwt||d�dS)�o
    Destroys the virtual machine

    vm_ref
        Managed object reference of a virtual machine object
    �Destroying vm '%s'raNzDestroy Task)r�rr,r r	r=rdr>rr5rerfrgr3r
rhrir)r�r�rrKrrr�	delete_vmLs(

��
�
��r�c
Cs�t|�}t�d|�z|��WdStjjy.}zt�|�tj	�
d|j����d}~wtjjyB}ztj	�
|j
��d}~wtjyU}ztj	�|j
��d}~ww)r�r�raN)r�rr,ZUnregisterVMr	r=rdr>rr5rerfrgr3r
rhri)r�r�rKrrr�
unregister_vmes"

�����r�)NNNN)NTN)T)NNNNr0NNTr�)rv)NNNF)rQN)NF)N)NNN)NNF)rmr�)r�)��__doc__rFr��loggingr@r��http.clientrZsalt.exceptionsrZsalt.modules.cmdmodZsalt.utils.pathZsalt.utils.platformZsalt.utils.stringutilsZ
pyVim.connectrrrrrZpyVmomirr	r
r
r�Z!com.vmware.vapi.std.errors_clientrZvmware.vapi.vsphere.clientrZHAS_VSPHERE_SDKr�r�r��	getLoggerr�rrrr/rOrTr_rkruryr{rr�r�r�r�r�r�r�r7r�rUr�r�r�r�r�r�r�r�r�rrrrrrrrr!r&r'r)r*r,r/r:r;r=rBrDrErJrMrOrPrRrTr\rWrmrgryr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rr�r�r�r�r�r�r�r�r�r�rrrr�<module>sbJ���

�5
�0
�

�
o
%!#X

�
�.
�=,
.
'
: 

4

(
�\
�L

)


<
�
H
�
B &
�K
�
>
5
 
G4
�
PD
.
�=

�7







k
�
I
<h
9
�
.6