܍~cpdZddlZddlZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddl m Z mZmZddlmZmZmZdZe jeZdZd Zd Zed Zd Zd ZdZdZdZ dZ!dZ"dZ#dZ$Gddej%Z&dZ'dZ(dZ)dZ*dZ+dZ,dZ-dZ.efdZ/efd Z0efd!Z1efd"Z2d#Z3d$Z4e&ej5ffe&ej5ej6ffgZ7d%Z8d&Z9d.d(Z:d)Z;d*Zed-kr e>dSdS)/a Cloud-Init DataSource for VMware This module provides a cloud-init datasource for VMware systems and supports multiple transports types, including: * EnvVars * GuestInfo 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)dmi)log)netsourcesutil)ProcessExecutionErrorsubpwhichz/sys/class/dmi/id/product_uuidzNo value foundenvvar guestinfozvmware-rpctoolredactzcleanup-guestinfo VMX_GUESTINFOz---z local-ipv4z local-ipv6zwait-on-networkipv4ipv6cXeZdZdZdZd dZdZdZdZe dZ d Z d Z d Z dS) DataSourceVMwarea 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. However, this datasource still supports supplying Network Config Version 2 data 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. VMwareNcrtj|||||d|_t|_dSN)r DataSource__init__data_access_methodVMWARE_RPCTOOLvmware_rpctool)selfsys_cfgdistropathsud_procs D/usr/lib/python3/dist-packages/cloudinit/sources/DataSourceVMware.pyrzDataSourceVMware.__init__s7##D'65'JJJ"&,cd\}}}tjtdr?t d}t d}t d}|s|s|r t |_|jsdtjd}|t dd Sd | vrt d d S|jsX|j rQtd|j }td|j }td|j }|s|s|r t|_|jstd d Std |t%t'||_||_||_||js|js|jrdSd S)ay _get_data loads the metadata, userdata, and vendordata from one of the following locations in the given order: * envvars * guestinfo 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. )NNNmetadatauserdata vendordatazsystem-product-nameNzNo system-product-name foundFvmwarezNot a VMware platformz)failed to find a valid data access methodzusing data access method %sT)osenvirongetrguestinfo_envvarDATA_ACCESS_METHOD_ENVVARrr read_dmi_dataLOGdebuglowerrr DATA_ACCESS_METHOD_GUESTINFOerrorinfo_get_subplatformprocess_metadataload_json_or_yamlr$ userdata_rawvendordata_raw redact_keys)rmdudvd system_types r _get_datazDataSourceVMware._get_datas & B :>>- , , D!*--B!*--B!,//B DR D2 D*C'& +,ABBK" 8999u{002222 1222u& K" Kz4+>??z4+>??|T-@AAKKrK.JD+&  IIA B B B5 .0E0E0G0GHHH)):2)>)>?? !  = D- 1D 45r!ct|j}td|t |t j|j|g|_|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.r3advertise_local_ip_addrsr mergemanydictpersist_instance_data)ris_new_instance host_infos r setupzDataSourceVMware.setupsm$DM22  $i000 !+++ *DM9+EFF ""$$$$$r!cd}|jtkrt}n$|jtkrt}n t jS|jd|ddS)Nz (r$))rr,get_guestinfo_envvar_key_namer1get_guestinfo_key_namerMETADATA_UNKNOWN)rget_key_name_fns r r4z!DataSourceVMware._get_subplatformsg  "&? ? ?;OO  $(D D D4OO+ +  # # # OJ ' ' ' '  r!cd|jvrtdn=tdd|ji|jd<|jddS)Nnetworkzusing metadata network configzusing fallback network configconfig)r$r.r/rgenerate_fallback_config)rs r network_configzDataSourceVMware.network_configsm  % % II5 6 6 6 6 II5 6 6 6$+>>@@(DM) $}Y'11r!cN|jrd|jvr |jdSttd5}t||jd<|jdcdddS#1swxYwYdS)Nz instance-idr)r$openPRODUCT_UUID_FILE_PATHstrreadrstripr0)rid_files r get_instance_idz DataSourceVMware.get_instance_ids = 0]dm;;=/ / (# . . 0'+.w||~~+>+>+E+E+G+G+M+M+O+ODM- (=/ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0sABB!BcddD],}||jvr!tj|j|cS-gS)N)zpublic-keys-datapublic_keys_dataz public-keys public_keys)r$rnormalize_pubkey_data)rkey_names r get_public_ssh_keysz$DataSourceVMware.get_public_ssh_keyssL  N NH 4=((4T]85LMMMMM) r!cd}t|jvr|jt}n t|jvr|jt}|jtkrt ||jdSdSr)REDACTr$CLEANUP_GUESTINFOrr1guestinfo_redact_keysr)rkeys_to_redacts r r9zDataSourceVMware.redact_keyssm T] " "!]62NN $- / /!]+<=N  "&B B B !.$2E F F F F F C Br!r)__name__ __module__ __qualname____doc__dsnamerr>rFr4propertyrQrZr`r9r!r rrds8F---- GGGR%%%8    22X2000    G G G G Gr!rctd||d}|dvrCtd||tjtj|}nR|dvr1td||tj|}ntd||}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)z gzip+base64zgz+b64zDecoding %s format %s)base64b64zPlain-text data %s)r.r/r decomp_gzipb64d decode_binary)keyenc_typedataraw_datas r decoderw(s II7hGGGH,,, )8S999#DIdOO44 & & & )8S9999T?? &,,,  h ' ''r!ctj|}|}t|dks |tkrdS|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)rrrrXlenGUESTINFO_EMPTY_YAML_VAL)vals r get_none_if_empty_valr|=sE  S ! !C **,,C 3xx1}}777t Jr!cB|sdS|t}|r0tt|td||t }|r2tt |td|dSdS)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)r* LOCAL_IPV4guestinfo_set_valuer.r3 LOCAL_IPV6)rE local_ipv4 local_ipv6s r rArAOs z**JNJ 333 @*MMMz**JNJ 333 @*MMMMMNNr!cbt|}|r|Std|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 No value found for key %sN)r|r.r/)rsr{s r handle_returned_guestinfo_valres8  $ $C  II)3/// 4r!c d|zS)Nz guestinfo.rlrss r rJrJrs # r!ctdt|zdddS)Nzvmx.._)rJupperreplacers r rIrIvs4 +C00 0 7 7 9 9 A A#sB O OOr!ct|}|sdSt|dz}tt|||S)N .encoding)guestinfo_envvar_get_valuerwrI)rsr{rts r r+r+zsI $S ) )C t)# *;< 2 2C t"3#4nEEH (--x = ==r!c8td| t|dt|zg\}}|tkrtd|n|std|t ||S#t$rR}|jtkrtd|ntj td||Yd}~n.d}~wt$rtj td|YnwxYwdS)z: Returns a guestinfo value for the specified key. z"Getting guestinfo value for key %sz info-get rz(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.r/r rJNOVALr2rrstderrrlogexc Exception)rsrstdoutrr2s r rrsIII2C888 4S999    U?? II13 7 7 7 7 G II@# F F F,S&999    <5 II13 7 7 7 7 K>          +         4sA7B DAC,,(DDcR|dkrd}td|| t|dt|d|gdS#t$r'}t jtd|||Yd}~n/d}~wt$rt jtd||YnwxYwdS) z| Sets a guestinfo value for the specified key. Set value to an empty string to clear an existing guestinfo key. r# z$Setting guestinfo key=%s to value=%sz info-set Tz.Failed to set guestinfo key=%s to value=%s: %sNzAUnexpected error while trying to set guestinfo key=%s to value=%s)r.r/r rJrrrr)rsvaluerr2s r rrs  {{II4c5AAA  $:3$?$?$?$?G    t      <                  -          4s$A B$A88)B$#B$c|sdSt|ttfvr|g}|D]}t|}td|t |t|std|td|t |dzd|std|dS)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.encodingrr#zfailed to clear %s.encoding) typelisttuplerJr.r3rrzr2)keysrrsr_s r rdrds  ::$ & &v ? ?)#.. )))" )>   6 II*H 5 5 5 '222"3#4b.II ? II3X > > > ? ?r!c|siS tj|S#tjtf$rtj|cYSwxYw)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. )r load_jsonjsonJSONDecodeError TypeError load_yaml)rus r r6r6s_  $~d###  ) ,$$$~d#####$s*AAcd}d|vr |d}|d=d}d|vr |d}|d=|rt|tjjr1tddt j|i}n=td|td||}dt|i}td|||d<|S) z_ process_metadata processes metadata and loads the optional network configuration. NrNznetwork.encodingz#network data copied to 'config' keyrOznetwork data to be decoded %szmetadata.networkznetwork data %s) isinstance collectionsabcMappingr.r/copydeepcopyrwr6)rurN network_encdec_nets r r5r5 s GDy/ OKT!!-. # $ " g{6 7 7  II; < < <w!7!78GG II5w ? ? ?/gFFG+G44G #W---!Y Kr!c6tj|tS)zK Return a list of data sources that match this set of dependencies )rlist_from_depends datasources)dependss r get_datasource_listr0s  $Wk : ::r!ctj}d|vrdS|d}tj|vrtj|vrdSd}d}|tj}|r|\}}tj|}|ri|tj}|rHt |dkrtd||nd|dvr|dd}|tj} | r| \}} tj| } | ri| tj} | rHt | dkrtd| | nd| dvr| dd}|rk|si|tj} | rHt | dkrtd|| nd| dvr| dd}|sk|ri| tj}|rHt |dkrtd| |nd|dvr|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. default)NNNz,device %s has more than one ipv4 address: %saddrrz,device %s has more than one ipv6 address: %s) netifacesgatewaysAF_INETAF_INET6r* ifaddressesryr.warning) r default_gwrrgw4rdev4 addr4_famsaf_inet4gw6dev6 addr6_famsaf_inet6s r get_default_ip_addrsr7s!##H  z)$J++  j 0 0z D D ..* + +C /4*400  /!~~i&788H /x==1$$KKF  x{**#A;v.D ..+ , ,C /4*400  /!~~i&899H /x==1$$KKF  x{**#A;v.D  +D +>>)"455  +8}}q   B 8A;&&{6*  +D +>>)"344  +8}}q   B 8A;&&{6* :r!r#c|}|r|dkrtj} tj|ddtjdtj}|D]}|dr |d}nn#tj$rYnwxYw|S)zoGet fully qualified domain name from name. An empty argument is interpreted as meaning the local host. z0.0.0.0Nr)stripr get_hostnamesocket getaddrinfo SOCK_DGRAM AI_CANONNAMEr2)nameaddrsrs r getfqdnrs ::<| r@| D]=}|d }t|st#j|}|d =| r| |d<|||<>|S)zP Returns host information such as the host name and network interfaces. rN interfaces)by-macby-ipv4by-ipv6hostnamezlocal-hostnamelocal_hostnamerrrNrrz00:00:00:00:00:00rrmac)r OrderedDictrrrrr~rrrrr*AF_LINKrrrappendrr)rEr default_ipv4 default_ipv6by_macby_ipv4by_ipv6ifacesdev_name addr_famsaf_linkrrrrsr{ af_inet4_valsip_info af_inet6_valss r get_host_infors7  %133&244&244 It(**++H/ ( *&. "#&. "#!5!7!7L,- , *- , * y !, / 9F "<0;G "<0;G  ! # #F5#5#)(33 -- 122==!233==!344  %v++!*V$C % % %   H  CC , " '22G+GFO<<! !((1111+F  , " '22G+GFO<<! !((1111+F F3K  ## # #fo',,mG,,K%!$CJ"  ## # #fo',,mG,,K%!$CJ" r!c:d}d}t|vr|t}t|vr9|t}t|tr|}nt j|}t |vr9|t }t|tr|}nt j|}d\}}}|t}|dpi} | dpi} | dpi} | dpi} |r| rt| dknd}|sd}|r| rt| dknd}|sd}|2t d||||tj d |t d |S) NF)NFFrNrrrrzII+,,, r!c tjn#t$rYnwxYwttdt diddddiii}t |}tj||g}ttj |dS)z7 Executed when this file is used as a program. TFrNrOdhcpN) loggingsetupBasicLoggingrrrrr@rrBprint json_dumps)r$rEs r mainr Gs !####        $ %  Hvtn- H ))I!8Y"788H $/( # #$$$$$s  ##__main__)r#)?rirrrrr(rrr cloudinitrrrrrrcloudinit.subprr r rU getLoggerrfr.rr,r1rrbrcrrzr~rrrrrrrwr|rArrJrIr+rr rrrdr6r5DEP_FILESYSTEM DEP_NETWORKrrrrrrr@r rlr!r rs:44l  $$$$$$((((((((((==========9g!!$*'(( '     #AGAGAGAGAGw)AGAGAGH(((*$NNN,   PPPEEEKKK #1 > > > >-;$$$$N4B((((V0>????, $ $ $D.01.0CDE ;;;WWWz.VVVr555p%%%( zDFFFFFr!