o
    w7e                     @   s  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ZddlZddlZddl	m
Z
mZ ddl	mZ ddl	mZmZmZ ddlmZ ddlmZmZmZ dZeeZd	Zd
ZdZdZedZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(G dd dej)Z*dd Z+dd Z,dd Z-dd  Z.d!d" Z/d#d$ Z0d%d& Z1d'd( Z2d)d* Z3d+d, Z4efd-dZ5efd.d/Z6efd0d1Z7efd2d3Z8d4d5 Z9d6d7 Z:e*ej;ffe*ej;ej<ffgZ=d8d9 Z>d:d; Z?dHd=d>Z@d?d@ ZAdAdB ZBdCdD ZCdEdF ZDedGkreD  dS dS )Ia	  Cloud-Init DataSource for VMware

This module provides a cloud-init datasource for VMware systems and supports
multiple transports types, including:

    * EnvVars
    * GuestInfo
    * IMC (Guest Customization)

Netifaces (https://github.com/al45tair/netifaces)

    Please note this module relies on the netifaces project to introspect the
    runtime, network configuration of the host on which this datasource is
    running. This is in contrast to the rest of cloud-init which uses the
    cloudinit/netinfo module.

    The reasons for using netifaces include:

        * Netifaces is built in C and is more portable across multiple systems
          and more deterministic than shell exec'ing local network commands and
          parsing their output.

        * Netifaces provides a stable way to determine the view of the host's
          network after DHCP has brought the network online. Unlike most other
          datasources, this datasource still provides support for JINJA queries
          based on networking information even when the network is based on a
          DHCP lease. While this does not tie this datasource directly to
          netifaces, it does mean the ability to consistently obtain the
          correct information is paramount.

        * It is currently possible to execute this datasource on macOS
          (which many developers use today) to print the output of the
          get_host_info function. This function calls netifaces to obtain
          the same runtime network configuration that the datasource would
          persist to the local system's instance data.

          However, the netinfo module fails on macOS. The result is either a
          hung operation that requires a SIGINT to return control to the user,
          or, if brew is used to install iproute2mac, the ip commands are used
          but produce output the netinfo module is unable to parse.

          While macOS is not a target of cloud-init, this feature is quite
          useful when working on this datasource.

          For more information about this behavior, please see the following
          PR comment, https://bit.ly/3fG7OVh.

    The authors of this datasource are not opposed to moving away from
    netifaces. The goal may be to eventually do just that. This proviso was
    added to the top of this module as a way to remind future-us and others
    why netifaces was used in the first place in order to either smooth the
    transition away from netifaces or embrace it further up the cloud-init
    stack.
    N)atomic_helperdmi)log)netsourcesutil)guestcust_util)ProcessExecutionErrorsubpwhichz/sys/class/dmi/id/product_uuidzNo value foundenvvar	guestinfoimczvmware-rpctoolredactzcleanup-guestinfoVMX_GUESTINFOz---z
local-ipv4z
local-ipv6zwait-on-networkipv4ipv6c                   @   s   e Zd ZdZdZdddZdd Zdd	 Zd
d Zdd Z	dd Z
edd Zdd Zdd Zdd Zdd Zdd Zdd ZdS )DataSourceVMwareau  
    Setting the hostname:
        The hostname is set by way of the metadata key "local-hostname".

    Setting the instance ID:
        The instance ID may be set by way of the metadata key "instance-id".
        However, if this value is absent then the instance ID is read
        from the file /sys/class/dmi/id/product_uuid.

    Configuring the network:
        The network is configured by setting the metadata key "network"
        with a value consistent with Network Config Versions 1 or 2,
        depending on the Linux distro's version of cloud-init:

            Network Config Version 1 - http://bit.ly/cloudinit-net-conf-v1
            Network Config Version 2 - http://bit.ly/cloudinit-net-conf-v2

        For example, CentOS 7's official cloud-init package is version
        0.7.9 and does not support Network Config Version 2.

        imc transport:
            Either Network Config Version 1 or Network Config Version 2 is
            supported which depends on the customization type.
            For LinuxPrep customization, Network config Version 1 data is
            parsed from the customization specification.
            For CloudinitPrep customization, Network config Version 2 data
            is parsed from the customization specification.

        envvar and guestinfo tranports:
            Network Config Version 2 data is supported as long as the Linux
            distro's cloud-init package is new enough to parse the data.
            The metadata key "network.encoding" may be used to indicate the
            format of the metadata key "network". Valid encodings are base64
            and gzip+base64.
    VMwareNc                 C   sN   t j| |||| i | _d | _t| _t| jdft	| j
dft| jdfg| _d S )NFT)r   
DataSource__init__cfgdata_access_methodVMWARE_RPCTOOLvmware_rpctoolDATA_ACCESS_METHOD_ENVVARget_envvar_data_fnDATA_ACCESS_METHOD_GUESTINFOget_guestinfo_data_fnDATA_ACCESS_METHOD_IMCget_imc_data_fn possible_data_access_method_list)selfsys_cfgdistropathsud_proc r'   D/usr/lib/python3/dist-packages/cloudinit/sources/DataSourceVMware.pyr      s   




zDataSourceVMware.__init__c                 C   s   t j| }d|| jf S )Nz%s [seed=%s])r   r   __str__r   )r"   rootr'   r'   r(   r)      s   zDataSourceVMware.__str__c                 C   s   d\}}}| j D ]\}}}|rt sq| \}}}|s|s|r$|| _ nq| js/td dS td|   tt|| _	|| _
|| _|   | j	sQ| j
sQ| jrSdS dS )a  
        _get_data loads the metadata, userdata, and vendordata from one of
        the following locations in the given order:

            * envvars
            * guestinfo
            * imc

        Please note when updating this function with support for new data
        transports, the order should match the order in the dscheck_VMware
        function from the file ds-identify.
        NNNz)failed to find a valid data access methodFzusing data access method %sT)r!   is_vmware_platformr   LOGerrorinfo_get_subplatformprocess_metadataload_json_or_yamlmetadatauserdata_rawvendordata_rawredact_keys)r"   mdudvdr   get_data_fnrequire_vmware_platformr'   r'   r(   	_get_data   s0   


zDataSourceVMware._get_datac                 C   s<   t | j}td| t| t| j|g| _|   dS )a(  setup(is_new_instance)

        This is called before user-data and vendor-data have been processed.

        Unless the datasource has set mode to 'local', then networking
        per 'fallback' or per 'network_config' will have been written and
        brought up the OS at this point.
        zgot host-info: %sN)wait_on_networkr3   r-   r/   advertise_local_ip_addrsr   mergemanydictpersist_instance_data)r"   is_new_instance	host_infor'   r'   r(   setup   s
   

zDataSourceVMware.setupc                 C   sL   d }| j tkr
t}n| j tkrt}n| j tkrt}ntjS d| j |df S )Nz%s (%s)r3   )	r   r   get_guestinfo_envvar_key_namer   get_guestinfo_key_namer   get_imc_key_namer   METADATA_UNKNOWN)r"   get_key_name_fnr'   r'   r(   r0      s   


z!DataSourceVMware._get_subplatformc                 C   s   | j S N)r   r"   r'   r'   r(   get_config_obj  s   zDataSourceVMware.get_config_objc                 C   sB   d| j v rtd ntd d| j i| j d< | j d d S )Nnetworkzusing metadata network configzusing fallback network configconfig)r3   r-   debugr$   generate_fallback_configrJ   r'   r'   r(   network_config  s   



zDataSourceVMware.network_configc                 C   sl   | j rd| j v r| j d S ttd}t|   | j d< | j d W  d    S 1 s/w   Y  d S )Nzinstance-idr)r3   openPRODUCT_UUID_FILE_PATHstrreadrstriplower)r"   id_filer'   r'   r(   get_instance_id  s   
$z DataSourceVMware.get_instance_idc                 C   s,   dD ]}|| j v rt| j |   S qg S )N)zpublic-keys-datapublic_keys_datazpublic-keyspublic_keys)r3   r   normalize_pubkey_data)r"   key_namer'   r'   r(   get_public_ssh_keys'  s
   
z$DataSourceVMware.get_public_ssh_keysc                 C   sL   d }t | jv r| jt  }n
t| jv r| jt }| jtkr$t|| j d S d S rI   )REDACTr3   CLEANUP_GUESTINFOr   r   guestinfo_redact_keysr   )r"   keys_to_redactr'   r'   r(   r6   2  s   



zDataSourceVMware.redact_keysc                 C   s:   d\}}}t jtdrtd}td}td}|||fS )z<
        check to see if there is data via env vars
        r+    r3   userdata
vendordata)osenvirongetr   guestinfo_envvarr"   r7   r8   r9   r'   r'   r(   r   >  s   

z#DataSourceVMware.get_envvar_data_fnc                 C   s>   d\}}}| j rtd| j }td| j }td| j }|||fS )zK
        check to see if there is data via the guestinfo transport
        r+   r3   rd   re   )r   r   rj   r'   r'   r(   r   J  s   

z&DataSourceVMware.get_guestinfo_data_fnc                 C   s  d\}}}t | j}t | j}|s|std |||fS t  s(|||fS t | j}|du r7|||fS t	j
|}t |}t |\}	}
|	rh|rhtd t | jj| jd||| j\}}}| _n|
rz|rztd t |\}}}ntd t| |||fS )zN
        check to see if there is data via vmware guest customization
        r+   z-Customization for VMware platform is disabledNz3Getting data via VMware customization configurationscriptszFGetting data via VMware raw cloudinit data customization configurationz1No allowed customization configuration data found)r   is_vmware_cust_enabledr#   is_raw_data_cust_enabledds_cfgr-   rN   is_cust_plugin_availableget_cust_cfg_filerf   pathdirnameparse_cust_cfgget_cust_cfg_typeget_data_from_imc_cust_cfgr%   	cloud_dir	get_cpathr$   r   #get_data_from_imc_raw_data_cust_cfgr   del_dir)r"   r7   r8   r9   allow_vmware_custallow_raw_data_custcust_cfg_filecust_cfg_dircust_cfgis_vmware_cust_cfgis_raw_data_cust_cfgr'   r'   r(   r    V  sL   










z DataSourceVMware.get_imc_data_fnrI   )__name__
__module____qualname____doc__dsnamer   r)   r<   rC   r0   rK   propertyrP   rY   r^   r6   r   r   r    r'   r'   r'   r(   r   i   s"    $
9

	r   c                  C   s>   t d} | d u rtd dS d|  vrtd dS dS )Nzsystem-product-namezNo system-product-name foundFvmwarezNot a VMware platformT)r   read_dmi_datar-   rN   rW   )system_typer'   r'   r(   r,     s   


r,   c                 C   sv   t d| | d}|dv rt d||  tt|}n|dv r.t d||  t|}nt d|  |}t|S )z
    decode returns the decoded string value of data
    key is a string used to identify the data being decoded in log messages
    z'Getting encoded data for key=%s, enc=%sN)zgzip+base64zgz+b64zDecoding %s format %s)base64b64zPlain-text data %s)r-   rN   r   decomp_gzipr   b64ddecode_binary)keyenc_typedataraw_datar'   r'   r(   decode  s   
r   c                 C   s.   t | } |  } t| dks| tkrdS | S )a  
    get_none_if_empty_val returns None if the provided value, once stripped
    of its trailing whitespace, is empty or equal to GUESTINFO_EMPTY_YAML_VAL.

    The return value is always a string, regardless of whether the input is
    a bytes class or a string.
    r   N)r   r   rV   lenGUESTINFO_EMPTY_YAML_VAL)valr'   r'   r(   get_none_if_empty_val  s
   
r   c                 C   sX   | sdS |  t}|rtt| td| |  t}|r*tt| td| dS dS )z
    advertise_local_ip_addrs gets the local IP address information from
    the provided host_info map and sets the addresses in the guestinfo
    namespace
    Nz-advertised local ipv4 address %s in guestinfoz-advertised local ipv6 address %s in guestinfo)rh   
LOCAL_IPV4guestinfo_set_valuer-   r/   
LOCAL_IPV6)rB   
local_ipv4
local_ipv6r'   r'   r(   r>     s   



r>   c                 C   s    t |}|r|S td|  dS )z
    handle_returned_guestinfo_val returns the provided value if it is
    not empty or set to GUESTINFO_EMPTY_YAML_VAL, otherwise None is
    returned
    No value found for key %sN)r   r-   rN   )r   r   r'   r'   r(   handle_returned_guestinfo_val  s
   r   c                 C   s   dS )Nzvmware-toolsr'   r   r'   r'   r(   rF     s   rF   c                 C   s   d|  S )Nz
guestinfo.r'   r   r'   r'   r(   rE     s   rE   c                 C   s   dt |   dddS )Nzvmx.._)rE   upperreplacer   r'   r'   r(   rD     s   rD   c                 C   s,   t | }|sd S t | d }tt| ||S )N	.encoding)guestinfo_envvar_get_valuer   rD   )r   r   r   r'   r'   r(   ri     s
   ri   c                 C   s   t | }t| tj|dS )Nrc   )rD   r   rf   rg   rh   )r   env_keyr'   r'   r(   r     s   r   c                 C   s0   t | |}|s	dS t | d |}tt| ||S )zj
    guestinfo returns the guestinfo value for the provided key, decoding
    the value when required
    Nr   )guestinfo_get_valuer   rE   )r   r   r   r   r'   r'   r(   r     s
   
c              
   C   s   t d|  z%t|dt|  g\}}|tkrt d|  n|s&t d|  t| |W S  tyY } z"|jtkr?t d|  nt	
t d| | W Y d}~dS W Y d}~dS d}~w tyi   t	
t d|  Y dS w )z:
    Returns a guestinfo value for the specified key.
    z"Getting guestinfo value for key %sz	info-get r   z(Failed to get guestinfo value for key %sz,Failed to get guestinfo value for key %s: %sNz?Unexpected error while trying to get guestinfo value for key %s)r-   rN   r
   rE   NOVALr.   r   r	   stderrr   logexc	Exception)r   r   stdoutr   r.   r'   r'   r(   r   
  sB   


r   c              
   C   s   |dkrd}t d| | zt|dt| |f g W dS  ty8 } ztt d| || W Y d}~dS d}~w tyI   tt d| | Y dS w )	z|
    Sets a guestinfo value for the specified key. Set value to an empty string
    to clear an existing guestinfo key.
    rc    z$Setting guestinfo key=%s to value=%szinfo-set %s %sTz.Failed to set guestinfo key=%s to value=%s: %sNzAUnexpected error while trying to set guestinfo key=%s to value=%s)r-   rN   r
   rE   r	   r   r   r   )r   valuer   r.   r'   r'   r(   r   1  s:   
r   c                 C   s   | sdS t | ttfvr| g} | D ],}t|}td| t|t|s)td| td| t|d d|s=td| qdS )z
    guestinfo_redact_keys redacts guestinfo of all of the keys in the given
    list. each key will have its value set to "---". Since the value is valid
    YAML, cloud-init can still read it if it tries.
    Nzclearing %szfailed to clear %szclearing %s.encodingr   rc   zfailed to clear %s.encoding)	typelisttuplerE   r-   r/   r   r   r.   )keysr   r   r]   r'   r'   r(   ra   \  s    ra   c              	   C   sF   | si S t | tr| S zt| W S  tjtfy"   t|  Y S w )z
    load first attempts to unmarshal the provided data as JSON, and if
    that fails then attempts to unmarshal the data as YAML. If data is
    None then a new dictionary is returned.
    )
isinstancedictr   	load_jsonjsonJSONDecodeError	TypeError	load_yaml)r   r'   r'   r(   r2   r  s   
r2   c                 C   s   | si S d}d| v r| d }| d= d}d| v r| d }| d= |rPt |tjjr4td dt|i}ntd| td||}dt	|i}td| || d< | S )	z_
    process_metadata processes metadata and loads the optional network
    configuration.
    NrL   znetwork.encodingz#network data copied to 'config' keyrM   znetwork data to be decoded %szmetadata.networkznetwork data %s)
r   collectionsabcMappingr-   rN   copydeepcopyr   r2   )r   rL   network_encdec_netr'   r'   r(   r1     s*   
r1   c                 C   s   t | tS )zK
    Return a list of data sources that match this set of dependencies
    )r   list_from_dependsdatasources)dependsr'   r'   r(   get_datasource_list  s   r   c                  C   s  t  } d| vr
dS | d }t j|vrt j|vrdS d}d}|t j}|rS|\}}t |}|rS|t j}|rSt|dkrGtd|| nd|d v rS|d d }|t j}	|	r|	\}}
t |
}|r|t j}|rt|dkr|td|
| nd|d v r|d d }|r|s|t j}|rt|dkrtd|| nd|d v r|d d }|s|r|t j}|rt|dkrtd|
| ||fS d|d v r|d d }||fS )	aI  
    Returns the default IPv4 and IPv6 addresses based on the device(s) used for
    the default route. Please note that None may be returned for either address
    family if that family has no default route or if there are multiple
    addresses associated with the device used by the default route for a given
    address.
    default)NNN   z,device %s has more than one ipv4 address: %saddrr   z,device %s has more than one ipv6 address: %s)		netifacesgatewaysAF_INETAF_INET6rh   ifaddressesr   r-   rN   )r   
default_gwr   r   gw4r   dev4
addr4_famsaf_inet4gw6dev6
addr6_famsaf_inet6r'   r'   r(   get_default_ip_addrs  s~   	



r   rc   c                 C   st   |   } | r
| dkrt } zt| ddtjdtj}W n tjy'   Y | S w |D ]}|d r7|d }  | S q*| S )zoGet fully qualified domain name from name.
    An empty argument is interpreted as meaning the local host.
    z0.0.0.0Nr      )stripr   get_hostnamesocketgetaddrinfo
SOCK_DGRAMAI_CANONNAMEr.   )nameaddrsr   r'   r'   r(   getfqdn  s$   r   c                 C   s&   t tj| }|o|jp|jp|j S )zn
    Returns false if the address is loopback, link local or unspecified;
    otherwise true is returned.
    )r   maybe_get_address	ipaddress
ip_addressis_link_localis_loopbackis_unspecified)r   r   r'   r'   r(   is_valid_ip_addr'  s   r   c                  C   s  ddt  t  t  dii} tt }|r$|| d< || d< || d< t \}}|r/|| t< |r5|| t< | d d d }| d d d }| d d d	 }t	 }|D ]}t
|}	|	tj}
|	tj}|	tj}d
}|
r|d|
d v r||
d d }|dkrqS|r|s|r|}i }|rg }|D ]}t|d sq|| q||d< |rg }|D ]}t|d sq|| q||d< |||< |r|D ]}|d }t|sqt|}|d= |r||d< |||< q|r|D ]}|d }t|sqt|}|d= |r||d< |||< qqS| S )zP
    Returns host information such as the host name and network interfaces.
    rL   
interfaces)by-macby-ipv4by-ipv6hostnamezlocal-hostnamelocal_hostnamer   r   r   Nr   r   z00:00:00:00:00:00r   r   mac)r   OrderedDictr   r   r   r   r   r   r   r   r   rh   AF_LINKr   r   r   appendr   r   )rB   r   default_ipv4default_ipv6by_macby_ipv4by_ipv6ifacesdev_name	addr_famsaf_linkr   r   r   r   r   af_inet4_valsip_infoaf_inet6_valsr'   r'   r(   get_host_info2  s   	





r   c                 C   s6  d}d}t | v r6| t  }t|v r!|t }t|tr|}nt|}t|v r6|t }t|tr1|}nt|}d\}}}|d u rt }|dpHi }	|	dpOi }
|
dpVi }|
dp]i }|rn|rht	|dknd}|snd }|r~|rxt	|dknd}|s~d }|d u rt
d|||| td	 |d u s?t
d
 |S )NF)NFFrL   r   r   r   r   z<waiting on network: wait4=%s, ready4=%s, wait6=%s, ready6=%sr   zwaiting on network complete)WAIT_ON_NETWORKWAIT_ON_NETWORK_IPV4r   boolr   translate_boolWAIT_ON_NETWORK_IPV6r   rh   r   r-   rN   timesleep)r3   wait_on_ipv4wait_on_ipv6r=   wait_on_ipv4_valwait_on_ipv6_valrB   
ipv4_ready
ipv6_readyrL   r   r   r   r'   r'   r(   r=     sR   






r=   c                  C   sd   zt   W n	 ty   Y nw ttdtdiddddiii} t| }t| |g} t	t
|  dS )z7
    Executed when this file is used as a program.
    TFrL   rM   dhcpN)loggingsetupBasicLoggingr   r   r  r  r=   r   r?   printr   
json_dumps)r3   rB   r'   r'   r(   main  s   r  __main__)rc   )Er   r   r   r   r   rf   r   r  r   	cloudinitr   r   r   r  r   r   r   $cloudinit.sources.helpers.vmware.imcr   cloudinit.subpr	   r
   r   rS   	getLoggerr   r-   r   r   r   r   r   r_   r`   r   r   r   r   r   r  r  r   r   r,   r   r   r>   r   rF   rE   rD   ri   r   r   r   r   ra   r2   r1   DEP_FILESYSTEMDEP_NETWORKr   r   r   r   r   r   r=   r  r'   r'   r'   r(   <module>   s|   
7
  )'+
$
]Y8
