3 cj-@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z m Z m Z mZmZmZddlmZddlmZmZmZdZejeZdZdZd Zd Zd Zd Z d Z!dZ"dZ#dZ$dZ%dZ&dZ'Gdddej(Z)ddZ*ddZ+ddZ,ddZ-ddZ.d d!Z/d"d#Z0d$d%Z1d&d'Z2d(d)Z3d*d+Z4d,d-Z5d.d Z6d/d0Z7d1d2Z8d3d4Z9d5d6Z:d7d8Z;e)ejd9d:Z?d;d<Z@dId>d?ZAd@dAZBdBdCZCdDdEZDdFdGZEedHkreEdS)Ja 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_helperdmilognetsourcesutil)guestcust_util)ProcessExecutionErrorsubpwhichz/sys/class/dmi/id/product_uuidzNo value foundZenvvar guestinfoZimcZredactzcleanup-guestinfo VMX_GUESTINFOz---z local-ipv4z local-ipv6zwait-on-networkipv4ipv6c@seZdZdZdZd ddZddZdd Zd d Zd d Z ddZ e ddZ ddZ ddZddZddZddZddZddZdS)!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. ZVMwareNcCsTtjj|||||i|_d|_d|_d|_t|jdft |j dft |j dfg|_ dS)NFT)r DataSource__init__cfgdata_access_methodrpctool rpctool_fnDATA_ACCESS_METHOD_ENVVARget_envvar_data_fnDATA_ACCESS_METHOD_GUESTINFOget_guestinfo_data_fnDATA_ACCESS_METHOD_IMCget_imc_data_fn possible_data_access_method_list)selfsys_cfgdistropathsZud_procr"&/usr/lib/python3.6/DataSourceVMware.pyrs  zDataSourceVMware.__init__cCstjj|}d||jfS)Nz %s [seed=%s])rr__str__r)rrootr"r"r#r$s zDataSourceVMware.__str__cCsd\}}}xB|jD]8\}}}|r*t r*q|\}}}|sB|sB|r||_PqW|jsbtjddStjd|jtt||_ ||_ ||_ |j |j s|j s|j rdSdSdS)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. Nz)failed to find a valid data access methodFzusing data access method %sT)NNN) ris_vmware_platformrLOGdebuginfo_get_subplatformprocess_metadataload_json_or_yamlmetadataZ userdata_rawZvendordata_raw redact_keys)rmdudvdrZ get_data_fnZrequire_vmware_platformr"r"r# _get_datas(     zDataSourceVMware._get_datacCsDt|j}tjd|t||j|jtj|j|g|_|j dS)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. zgot host-info: %sN) wait_on_networkr-r'r)advertise_local_ip_addrsrrr mergemanydictZpersist_instance_data)rZis_new_instance host_infor"r"r#setups  zDataSourceVMware.setupcCsLd}|jtkrt}n&|jtkr$t}n|jtkr4t}ntjSd|j|dfS)Nz%s (%s)r-) rrget_guestinfo_envvar_key_namerget_guestinfo_key_namerget_imc_key_namerZMETADATA_UNKNOWN)rZget_key_name_fnr"r"r#r*s   z!DataSourceVMware._get_subplatformcCs|jS)N)r)rr"r"r#get_config_objszDataSourceVMware.get_config_objcCsBd|jkrtjdntjdd|jji|jd<|jddS)Nnetworkzusing metadata network configzusing fallback network configconfig)r-r'r(r Zgenerate_fallback_config)rr"r"r#network_configs    zDataSourceVMware.network_configc CsT|jrd|jkr|jdSttd&}t|jjj|jd<|jdSQRXdS)Nz instance-idr)r-openPRODUCT_UUID_FILE_PATHstrreadrstriplower)rZid_filer"r"r#get_instance_ids   z DataSourceVMware.get_instance_idcCs.|jr*|jtkr*tr*tjd|jdSdS)Nz"Cache fallback is allowed for : %sTF)rrr&r'r(r*)rr"r"r#check_if_fallback_is_allowed&s  z-DataSourceVMware.check_if_fallback_is_allowedcCs,x&dD]}||jkrtj|j|SqWgS)Npublic-keys-datapublic_keys_data public-keys public_keys)rHrIrJrK)r-rZnormalize_pubkey_data)rkey_namer"r"r#get_public_ssh_keys2s z$DataSourceVMware.get_public_ssh_keyscCsLd}t|jkr|jt}nt|jkr.|jt}|jtkrHt||j|jdS)N)REDACTr-CLEANUP_GUESTINFOrrguestinfo_redact_keysrr)rZkeys_to_redactr"r"r#r.=s     zDataSourceVMware.redact_keyscCs:d\}}}tjjtdr0td}td}td}|||fS)z< check to see if there is data via env vars Nr-userdata vendordata)NNN)osenvirongetr guestinfo_envvar)rr/r0r1r"r"r#rKs  z#DataSourceVMware.get_envvar_data_fncCs$td}td}|r,||_t|_tjd||rL|s@||_t|_tjd||js`tjdd Sdd}y||j|jStk r}ztj td |j||r|j|krd S|stj d dStj d ||_t|_y||j|jStk r tj td |j|dSXWYdd}~XnXdS)zK check to see if there is data via the guestinfo transport vmtoolsdzvmware-rpctoolzdiscovered vmware-rpctool: %szdiscovered vmtoolsd: %szno rpctool discoveredNcSsDd\}}}tjd|td||}td||}td||}|||fS)Nzquery guestinfo with %sr-rRrS)NNN)r'r)r )rrr/r0r1r"r"r#query_guestinfoss      z?DataSourceVMware.get_guestinfo_data_fn..query_guestinfoz%Failed to query guestinfo with %s: %sz$vmtoolsd fallback option not presentzfallback to vmtoolsd)NNN)NNN)NNN)NNN) r rexec_vmware_rpctoolrr'r( exec_vmtoolsd Exceptionrlogexcr))rrXZvmware_rpctoolrYerrorr"r"r#rWsP     z&DataSourceVMware.get_guestinfo_data_fnc Csd\}}}tj|j}tj|j}| rB| rBtjd|||fStjsT|||fStj|j}|dkrr|||fSt j j |}tj |}tj |\} } | r|rtjdtj|jj|jjd|||j\}}}|_n0| o|rtjdtj|\}}}n tjdtj||||fS)zN check to see if there is data via vmware guest customization Nz-Customization for VMware platform is disabledz3Getting data via VMware customization configurationscriptszFGetting data via VMware raw cloudinit data customization configurationz1No allowed customization configuration data found)NNN)rZis_vmware_cust_enabledrZis_raw_data_cust_enabledZds_cfgr'r(Zis_cust_plugin_availableZget_cust_cfg_filerTpathdirnameZparse_cust_cfgZget_cust_cfg_typeZget_data_from_imc_cust_cfgr!Z cloud_dirZ get_cpathr rZ#get_data_from_imc_raw_data_cust_cfgrZdel_dir) rr/r0r1Zallow_vmware_custZallow_raw_data_custZ cust_cfg_fileZ cust_cfg_dirZcust_cfgZis_vmware_cust_cfgZis_raw_data_cust_cfgr"r"r#rs>               z DataSourceVMware.get_imc_data_fn)N)__name__ __module__ __qualname____doc__Zdsnamerr$r2r7r*r;propertyr>rFrGrMr.rrrr"r"r"r#rgs # 9     LrcCs>tjd}|dkr tjddSd|jkr:tjddSdS)Nzsystem-product-namezNo system-product-name foundFZvmwarezNot a VMware platformT)rZ read_dmi_datar'r(rE)Z system_typer"r"r#r&s    r&cCsvtjd||d}|d kr:tjd||tjtj|}n2|d kr\tjd||tj|}ntjd||}tj|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 gzip+base64gz+b64zDecoding %s format %sbase64b64zPlain-text data %s)rgrh)rirj)r'r(rZ decomp_gziprZb64d decode_binary)keyenc_typedataZraw_datar"r"r#decodes  rocCs.tj|}|j}t|dks&|tkr*dS|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. rN)rrkrDlenGUESTINFO_EMPTY_YAML_VAL)valr"r"r#get_none_if_empty_vals rscCsj| s| s| rdS|jt}|r>tt|||tjd||jt}|rftt|||tjd|dS)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)rV LOCAL_IPV4guestinfo_set_valuer'r) LOCAL_IPV6)r6rrZ local_ipv4Z local_ipv6r"r"r#r4s   r4cCs t|}|r|Stjd|dS)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 zNo value found for key %sN)rsr'r()rlrrr"r"r#handle_returned_guestinfo_val%s  rwcCsdS)Nz vmware-toolsr")rlr"r"r#r:2sr:cCsd|S)Nz guestinfo.r")rlr"r"r#r96sr9cCsdt|jjdddS)Nzvmx.._)r9upperreplace)rlr"r"r#r8:sr8cCs,t|}|sdSt|d}tt|||S)Nz .encoding)guestinfo_envvar_get_valueror8)rlrrrmr"r"r#rW>s  rWcCst|}t|tjj|dS)NrQ)r8rwrTrUrV)rlZenv_keyr"r"r#r~Fsr~cCst||g\}}||fS)N)r )rargstdoutstderrr"r"r#rZKsrZcCst|d|g\}}||fS)Nz--cmd)r )rrrrr"r"r#r[Psr[cCs4t|||}|sdSt|d||}tt|||S)zj guestinfo returns the guestinfo value for the provided key, decoding the value when required Nz .encoding)guestinfo_get_valueror9)rlrrrrrmr"r"r#r Us  cCstjd|yF||dt|\}}|tkr:tjd|n|sJtjd|t||Stk r}z2|jtkr|tjd|ntj td|||WYdd}~Xn6t k r}ztj td|||WYdd}~XnXdS)z: Returns a guestinfo value for the specified key. z"Getting guestinfo value for key %sz info-get zNo value found for key %sz(Failed to get guestinfo value for key %sz,Failed to get guestinfo value for key %s: %sNzCUnexpected error while trying to get guestinfo value for key %s: %s) r'r(r9NOVALr^rwr rrr]r\)rlrrrrr^r"r"r#ras4    rcCs|dkr d}tjd||y||dt||fdStk rh}ztjtd|||WYdd}~Xn$tk rtjtd||YnXdS) z| Sets a guestinfo value for the specified key. Set value to an empty string to clear an existing guestinfo key. rQ z$Setting guestinfo key=%s to value=%szinfo-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'r(r9r rr]r\)rlvaluerrr^r"r"r#rus*  rucCs|sdSt|ttfkr|g}xd|D]\}t|}tjd|t|t||sVtjd|tjd|t|dd||s$tjd|q$WdS)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 %szfailed to clear %szclearing %s.encodingz .encodingrQzfailed to clear %s.encoding) typelisttupler9r'r)rurqr^)keysrrrlrLr"r"r#rPs     rPc CsF|siSt|tr|Sy tj|Stjtfk r@tj|SXdS)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. N) isinstancedictrZ load_jsonjsonZJSONDecodeError TypeErrorZ load_yaml)rnr"r"r#r,s  r,cCs|siSd}d|kr"|d}|d=d}d|kr<|d}|d=|rt|tjjrhtjddtj|i}n$tjd|td||}dt |i}tjd|||d<|S) z_ process_metadata processes metadata and loads the optional network configuration. Nr<znetwork.encodingz#network data copied to 'config' keyr=znetwork data to be decoded %szmetadata.networkznetwork data %s) r collectionsabcMappingr'r(copydeepcopyror,)rnr<Z network_encZdec_netr"r"r#r+s(     r+cCs tj|tS)zK Return a list of data sources that match this set of dependencies )rZlist_from_depends datasources)Zdependsr"r"r#get_datasource_listsrc Cstj}d|krdS|d}tj|kr4tj|kr4d Sd}d}|jtj}|r|\}}tj|}|r|jtj}|rt|dkrtjd||nd|dkr|dd}|jtj} | r| \}} tj| } | r| jtj} | rt| dkrtjd| | nd| dkr| dd}|rr| rr|jtj} | rrt| dkrXtjd|| nd| dkrr| dd}| r|r| jtj}|rt|dkrtjd| |nd|dkr|dd}||fS) 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. defaultNrzz,device %s has more than one ipv4 address: %saddrrz,device %s has more than one ipv6 address: %s)NN)NN) netifacesgatewaysAF_INETAF_INET6rV ifaddressesrpr'r() rZ default_gwrrZgw4ryZdev4Z addr4_famsaf_inet4Zgw6Zdev6Z addr6_famsaf_inet6r"r"r#get_default_ip_addrsst                 rrQc Csv|j}| s|dkrtj}ytj|ddtjdtj}Wntjk rPYn"Xx|D]}|drX|d}PqXW|S)zoGet fully qualified domain name from name. An empty argument is interpreted as meaning the local host. z0.0.0.0Nr)stripr get_hostnamesocketZ getaddrinfoZ SOCK_DGRAMZ AI_CANONNAMEr^)nameZaddrsrr"r"r#getfqdnls rcCs&tjtj|}|o$|jp"|jp"|j S)zn Returns false if the address is loopback, link local or unspecified; otherwise true is returned. )rZmaybe_get_address ipaddressZ ip_addressZ is_link_localZ is_loopbackZis_unspecified)rrrr"r"r#is_valid_ip_addrsrcCsRddtjtjtjdii}ttj}|rH||d<||d<||d<t\}}|r^||t<|rj||t<|ddd}|ddd}|ddd }tj }x|D]}tj |} | j tj } | j tj } | j tj} d } | rd | d kr| d d } | d kr q| r| s| r| }i}| rbg}x*| D]"}t|d sJq4|j|q4W||d<| rg}x*| D]"}t|d sqr|j|qrW||d<|||<| rxJ| D]B}|d }t|sΐqtj|}|d =| r| |d<|||<qW| rxJ| D]B}|d }t|sqtj|}|d =| r<| |d<|||<qWqW|S)zP Returns host information such as the host name and network interfaces. r< interfaces)zby-maczby-ipv4zby-ipv6hostnamezlocal-hostnameZlocal_hostnamezby-maczby-ipv4zby-ipv6Nrrz00:00:00:00:00:00rrmac)r OrderedDictrrrrrtrvrrrrVZAF_LINKrrrappendrr)r6rZ default_ipv4Z default_ipv6Zby_macby_ipv4by_ipv6ZifacesZdev_nameZ addr_famsZaf_linkrrrrlrrZ af_inet4_valsZip_infoZ af_inet6_valsr"r"r# get_host_infos                rc Cs:d}d}t|krl|t}t|krB|t}t|tr8|}n tj|}t|krl|t}t|trb|}n tj|}d \}}}x|dkr*t}|jdpi} | jdpi} | jdpi} | jdpi} |r| rt | dknd}|sd}|r| rt | dknd}|sd}|dkrxt j d||||t j dqxWt j d |S) NFr<rzby-ipv4zby-ipv6rz@sv   x   ,+$ ]  Y8