a ah€iÚ<ã@sôddlZddlZddlmZmZddlmZmZddlmZ ddlm Z ddl m Z m Z ddlmZddlmZdd lmZdd lmZmZe e¡Zd ZGd d „d ejƒZdd„Zdd„ZGdd„deƒZeej ffeej ej!ffgZ"dd„Z#dS)éN)ÚListÚUnion)ÚdmiÚsources)Ú url_helper)Úutil)Ú EventScopeÚ EventType)ÚNoDHCPLeaseError)ÚEphemeralIPNetwork)ÚDataSourceHostname)ÚaliyunÚec2zAlibaba Cloud ECScsBeZdZUdZdgZdZgZeee d<dZ dZ dZ e jZeeefe d<d Zed d „ƒZ‡fd d „Zeddœ‡fdd„ Zd:dd„Zdd„Zdd„Zedd„ƒZedd„ƒZedd„ƒZedd„ƒZedd „ƒZed!d"„ƒZ d#d$„Z!d%d&„Z"d'd(„Z#d)d*„Z$d+d,„Z%d-d.„Z&d/d0„Z'd1d2„Z(d;d3d4„Z)dÚDataSourceAliYunZAliYunzhttp://100.100.100.200z 2016-01-01Úextended_metadata_versionséðé2NÚ_network_configFcCsdS)NzX-aliyun-ecs-metadata-token©©ÚselfrrúF/usr/lib/python3.9/site-packages/cloudinit/sources/DataSourceAliYun.pyÚimdsv2_token_put_header+sz(DataSourceAliYun.imdsv2_token_put_headercs:tt|ƒ |||¡t |j¡|_|jtj t j ¡dS©N) ÚsuperrÚ__init__ÚcopyÚdeepcopyZdefault_update_eventsrZNETWORKÚaddr ZBOOT)rZsys_cfgÚdistroÚpaths©Ú __class__rrr/szDataSourceAliYun.__init__)Úci_pkl_versionÚreturncstƒ |¡dSr)rÚ _unpickle)rr#r!rrr%4szDataSourceAliYun._unpicklecCs*|j d¡}d}|dur d}d}t||ƒS)NÚhostnameFzlocalhost.localdomainT)ÚmetadataÚgetr )rZfqdnZ resolve_ipZ metadata_onlyr&Z is_defaultrrrÚ get_hostname7s  zDataSourceAliYun.get_hostnamecCst|j di¡ƒS)Nz public-keys)Úparse_public_keysr'r(rrrrÚget_public_ssh_keys?sz$DataSourceAliYun.get_public_ssh_keyscCstƒr|j ¡SdS)NZNO_ALIYUN_METADATA)Ú _is_aliyunÚdsnameÚlowerrrrrÚ_get_cloud_nameBs z DataSourceAliYun._get_cloud_namecCs |j ¡Sr)r-r.rrrrÚplatformGszDataSourceAliYun.platformcCsdS)Nzlatest/api/tokenrrrrrÚapi_token_routeLsz DataSourceAliYun.api_token_routecCsdS)NZ21600rrrrrÚimdsv2_token_ttl_secondsPsz)DataSourceAliYun.imdsv2_token_ttl_secondscCs |j|jgSr)rÚimdsv2_token_req_headerrrrrÚimdsv2_token_redactTsz$DataSourceAliYun.imdsv2_token_redactcCs |jdS)Nz -ttl-seconds)rrrrrr3Xsz(DataSourceAliYun.imdsv2_token_req_headercCsn|jtjkr|jSi}|jj}|j d¡}t|tƒrRt j ||t   |j dd¡d}nt d|¡|S||_|jS)z@Return a network config dict for rendering ENI or netplan files.ÚnetworkZapply_full_imds_network_configT)Z fallback_nicZfull_network_configz%Metadata 'network' key not valid: %s.)rrÚUNSETrÚfallback_interfacer'r(Ú isinstanceÚdictr Z#convert_ecs_metadata_network_configrZget_cfg_option_boolÚds_cfgÚLOGÚwarning)rÚresultZifaceZnet_mdrrrÚnetwork_config\s"   ÿý zDataSourceAliYun.network_configc Cs´g}i}|j}d}|D]"}d ||¡}| |¡|||<qt d¡d}d}| ¡} z0tj|| j| j tj |j |j ||j dd \}}Wntjy˜Yn0|r°|r°||_||SdS)a=Get an API token for ECS Instance Metadata Service. On ECS. IMDS will always answer an API token, set HttpTokens=optional (default) when create instance will not forcefully use the security-enhanced mode (IMDSv2). https://api.alibabacloud.com/api/Ecs/2014-05-26/RunInstances ÚPUTz{0}/{1}zFetching Ecs IMDSv2 API TokenNF) ÚurlsZmax_waitÚtimeoutZ status_cbÚ headers_cbÚ exception_cbÚrequest_methodÚheaders_redactZconnect_synchronously)r1ÚformatÚappendr;ÚdebugZget_url_paramsÚuhelpZ wait_for_urlZmax_wait_secondsZtimeout_secondsr<Ú _get_headersÚ_imds_exception_cbr4ÚUrlErrorÚ _api_token) rÚmdurlsr@Zurl2baseZurl_pathrDÚurlZcurÚresponseZ url_paramsrrrÚ_maybe_fetch_api_tokenss<     ÷ z'DataSourceAliYun._maybe_fetch_api_tokencCsJ|j}| d|j¡}| |¡}|r8||_t d|j¡n t d¡t|ƒS)NÚ metadata_urlszUsing metadata source: '%s'z)IMDS's HTTP endpoint is probably disabled) r:r(rRrQÚmetadata_addressr;rHr<Úbool)rZmcfgrNrSrrrÚwait_for_metadata_service¥s  z*DataSourceAliYun.wait_for_metadata_servicec Cs| ¡s iS|j}i}|j}|j}d}|j}z®tj|j|j|j ||dd|d<tj|j|j|j ||dd|d<z&tj |j|j|j ||d}||d<WnBt yÖt   td|j¡tj|j|j|j |||d|d<Yn0Wn(t yt   td |j¡iYS0|S) z·Crawl metadata service when available. @returns: Dictionary of crawled metadata content containing the keys: meta-data, user-data, vendor-data and dynamic. Nú user-data)rBrErCZ item_nameú vendor-data)rBrErCú meta-dataz@Faild read json meta-data from %s fall back directory tree style)rBrErCZretrieval_exception_ignore_cbz'Failed reading from metadata address %s)rUr4Ú_refresh_stale_aliyun_token_cbÚ&_skip_or_refresh_stale_aliyun_token_cbÚ#_skip_json_path_meta_path_aliyun_cbr Zget_instance_dataÚmin_metadata_versionrSrJZget_instance_meta_dataÚ ExceptionrZlogexcr;rZget_instance_metadata)rZredactZcrawled_metadataZexc_cbZ exc_cb_udZskip_cbZexe_cb_whole_metar=rrrÚcrawl_metadata³spú ú û  üúý zDataSourceAliYun.crawl_metadatacCs*t|tjƒr&|jdkr&t d¡d|_dS)z=Exception handler for Ecs to refresh token if token is stale.i‘z+Clearing cached Ecs API token due to expiryNT)r8rIrLÚcoder;rHrM©rÚmsgÚ exceptionrrrrYós z/DataSourceAliYun._refresh_stale_aliyun_token_cbcCs |j|vS)z/Returns False if cause.code is in status_codes.)r_)rZ status_codesÚcauserrrÚ_skip_retry_on_codesûsz%DataSourceAliYun._skip_retry_on_codescCs"| tj|¡}|sdS| ||¡S)z^Callback will not retry on SKIP_USERDATA_VENDORDATA_CODES or if no token is available.F)rdrZSKIP_USERDATA_CODESrY)rrarbZretryrrrrZÿsz7DataSourceAliYun._skip_or_refresh_stale_aliyun_token_cbcCs0t|tjƒr$|jdkr$t d¡dS| ||¡S)z7Callback will not retry of whole meta_path is not foundi”z&whole meta_path is not found, skippingF)r8rIrLr_r;r<rYr`rrrr[s z4DataSourceAliYun._skip_json_path_meta_path_aliyun_cbcCsþ|j|j ¡krdS|jrªt ¡r0t d¡dSzbt|j |j j ddd8}|  ¡|_ t d|j rld|j ›nd¡Wdƒn1s†0YWq´ty¦YdS0n |  ¡|_ |j rÆt|j tƒsÊdS|j  di¡|_|j  d i¡|_|j  d i¡|_dS) NFz1FreeBSD doesn't support running dhclient with -sfT)Zipv4Zipv6zCrawled metadata service%sú ÚrXrVrW)Z cloud_namer-r.Úperform_dhcp_setuprZ is_FreeBSDr;rHr rr7r^Z_crawled_metadataZ state_msgr r8r9r(r'Z userdata_rawZvendordata_raw)rZnetwrrrÚ _get_datas< ü þ&   ÿzDataSourceAliYun._get_datac Csˆ|dur|j}t d¡|j|i}d |j|j¡}ztj|||j dd}Wn6tj y€}zt  d||¡WYd}~dSd}~00|j S)zRequest new metadata API token. @param seconds: The lifetime of the token in seconds @return: The API token or None if unavailable. Nz!Refreshing Ecs metadata API tokenz{}/{}r?)ZheadersrErDz/Unable to get API token: %s raised exception %s) r2r;rHr3rFrSr1rIZreadurlr4rLr<Úcontents)rZsecondsZrequest_headerZ token_urlrPÚerrrÚ_refresh_api_token/s$  ü ÿz#DataSourceAliYun._refresh_api_tokenrfcCs@|j|ji}|j|vr|S|js4| ¡|_|js4iS|j|jiS)z·Return a dict of headers for accessing a url. If _api_token is unset on AWS, attempt to refresh the token via a PUT and then return the updated token header. )r3r2r1rMrkr)rrOZrequest_token_headerrrrrJJsÿ  zDataSourceAliYun._get_headerscCsDt|tjƒr@|jr@|jdkr@|jdkr2t d¡n t d¡|‚dS)a2Fail quickly on proper AWS if IMDSv2 rejects API token request Guidance from Amazon is that if IMDSv2 had disabled token requests by returning a 403, or cloud-init malformed requests resulting in other 40X errors, we want the datasource detection to fail quickly without retries as those symptoms will likely not be resolved by retries. Exceptions such as requests.ConnectionError due to IMDS being temporarily unroutable or unavailable will still retry due to the callsite wait_for_url. ii“zLEcs IMDS endpoint returned a 403 error. HTTP endpoint is disabled. Aborting.z2Fatal error while requesting Ecs IMDSv2 API tokensN)r8rIrLr_r;r<r`rrrrK_s  ÿÿz#DataSourceAliYun._imds_exception_cb)FFF)N)rf)N)-Ú__name__Ú __module__Ú __qualname__r-rRr\rrÚstrÚ__annotations__Z url_max_waitZ url_timeoutrMrr6rrr9rgÚpropertyrrÚintr%r)r+r/r0r1r2r4r3r>rQrUr^rYrdrZr[rhrkrJrKÚ __classcell__rrr!rrsN          2@!  rcCst d¡tkS)Nzsystem-product-name)rZ read_dmi_dataÚALIYUN_PRODUCTrrrrr,{sr,cCsŽg}| ¡D]|\}}t|tƒr.| | ¡¡q t|tƒrD| |¡q t|tƒr | dg¡}t|tƒrt| | ¡¡q t|tƒr | |¡q |S)Nz openssh-key) Úitemsr8rorGÚstripÚlistÚextendr9r()Z public_keysÚkeysZ_key_idZkey_bodyÚkeyrrrr*s        r*c@seZdZdZdZdS)ÚDataSourceAliYunLocalayDatasource run at init-local which sets up network to query metadata. In init-local, no network is available. This subclass sets up minimal networking with dhclient on a viable nic so that it can talk to the metadata service. If the metadata service provides network configuration then render the network configuration for that instance based on metadata. TN)rlrmrnÚ__doc__rgrrrrr{sr{cCs t |t¡Sr)rZlist_from_dependsÚ datasources)ZdependsrrrÚget_datasource_list£sr~)$rZloggingÚtypingrrZ cloudinitrrrrIrZcloudinit.eventrr Zcloudinit.net.dhcpr Zcloudinit.net.ephemeralr Zcloudinit.sourcesr Zcloudinit.sources.helpersr rZ getLoggerrlr;rtZ DataSourcerr,r*r{ZDEP_FILESYSTEMZ DEP_NETWORKr}r~rrrrÚs,      h þ