509318396
Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­Â�Â­
<!DOCTYPE html>
<html>
3
\¼me �  ã               @   sŒ  d dl Z d dlZd dlZd dl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 d dlmZmZ d dlmZ d dlmZ d d	lmZ ejeƒZeejgƒZd5ZdZG dd„ dƒZdd„ Z ej!ej"gZ#G dd„ de	j$ƒZ%G dd„ de%ƒZ&dd„ Z'dd„ Z(dd„ Z)dd„ Z*dd„ Z+d d!„ Z,d"d#„ Z-d$d%„ Z.d&d'„ Z/d(d)„ Z0d*d+„ Z1d6d-d.„Z2d/d0„ Z3d1d2„ Z4e&e	j5ffe%e	j5e	j6ffgZ7d3d4„ Z8dS )7é    N)ÚList)ÚdmiÚnetÚsources)Ú
url_helper)ÚutilÚwarnings)Ú
EventScopeÚ	EventType)ÚNoDHCPLeaseError)ÚEphemeralIPNetwork)Úec2Ú
datasourceÚEc2Ú	strict_idÚwarnc               @   s,   e Zd ZdZdZdZdZdZdZdZ	dZ
d	S )
Ú
CloudNamesZaliyunZawsZ	brightboxZzstackÚe24cloudZoutscaleÚunknownzno-ec2-metadataN)Ú__name__Ú
__module__Ú__qualname__ÚALIYUNÚAWSÚ	BRIGHTBOXÚZSTACKÚE24CLOUDÚOUTSCALEÚUNKNOWNÚNO_EC2_METADATA© r    r    ú#/usr/lib/python3.6/DataSourceEc2.pyr   !   s   r   c             C   s   | j dkod| jkS )Ni”  zmeta-data/tags/)ÚcodeÚurl)Ú	exceptionr    r    r!   Úskip_404_tag_errors1   s    r%   c                   sx  e Zd ZU dZdddgZdZdddgZee d	Z	d
Z
dZejZdZejejejejejhiZ‡ fdd„Zdd„ Zdd„ Zdd„ Zedd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZ edd„ ƒZ!edd „ ƒZ"ed!d"„ ƒZ#d#d$„ Z$d%d&„ Z%d'd(„ Z&d)d*„ Z'd+d,„ Z(ed-d.„ ƒZ)ed/d0„ ƒZ*d1d2„ Z+ed3d4„ ƒZ,e‡ fd5d6„ƒZ-d7d8„ Z.dDd9d:„Z/d;d<„ Z0d=d>„ Z1dEd?d@„Z2dFdBdC„Z3‡  Z4S )GÚDataSourceEc2r   zhttp://169.254.169.254zhttp://[fd00:ec2::254]zhttp://instance-data.:8773z
2009-04-04z
2021-03-23z
2018-09-24z
2016-09-02éx   é2   NFc                s   t t| ƒj|||ƒ d | _d S )N)Úsuperr&   Ú__init__Úmetadata_address)ÚselfÚsys_cfgÚdistroÚpaths)Ú	__class__r    r!   r*   d   s    zDataSourceEc2.__init__c             C   s   t ƒ S )z5Return the cloud name as identified during _get_data.)Úidentify_platform)r,   r    r    r!   Ú_get_cloud_nameh   s    zDataSourceEc2._get_cloud_namec             C   sF  t tj| jttƒdƒ\}}tjd|| j| j	ƒ |dkrF| jt
jkrFdS | jt
jkrVdS | jràtjƒ rrtjdƒ dS yVt| j| jddd��8}|jrœd|j› �nd	}tjtjd
|› �| jd�| _W d Q R X W n tk
rÜ   dS X ntjtjd
| jd�| _| j�sdS | jjdd ƒ| _| jjdd ƒ| _| jjdi ƒjdi ƒjdi ƒ| _dS )Nr   z0strict_mode: %s, cloud_name=%s cloud_platform=%sÚtrueFz1FreeBSD doesn't support running dhclient with -sfT)Úipv4Úipv6ú Ú zCrawl of metadata service)ÚlogfuncÚmsgÚfuncz	meta-dataz	user-dataÚdynamiczinstance-identityÚdocument)r   N)Úread_strict_moder   Úget_cfg_by_pathr-   ÚSTRICT_ID_PATHÚSTRICT_ID_DEFAULTÚLOGÚdebugÚ
cloud_nameÚplatformr   r   r   Úperform_dhcp_setupZ
is_FreeBSDr   r.   Úfallback_interfaceÚ	state_msgÚlog_timeÚcrawl_metadataZ_crawled_metadatar   ÚgetÚmetadataZuserdata_rawÚidentity)r,   Zstrict_modeZ_sleepZnetwrG   r    r    r!   Ú	_get_datal   sV    



zDataSourceEc2._get_datac             C   sN   | j s
dS | j jdi ƒjdi ƒ}x(|jdi ƒjƒ D ]\}}d|kr2dS q2W dS )z6Report if this instance type is Ec2 Classic (non-vpc).FÚnetworkÚ
interfacesÚmacszvpc-idT)rK   rJ   Úitems)r,   Z	ifaces_mdZ_macZmac_datar    r    r!   Úis_classic_instance¤   s    z!DataSourceEc2.is_classic_instancec             C   s   | j s
d S | j jdƒS )Nzami-launch-index)rK   rJ   )r,   r    r    r!   Úlaunch_index±   s    zDataSourceEc2.launch_indexc             C   s.   t | dƒstjjƒ | _| js(tjjƒ | _| jS )NÚ_platform_type)Úhasattrr&   ÚdsnameÚlowerrT   )r,   r    r    r!   rD   ·   s
    
zDataSourceEc2.platformc             C   s   dS )Nzlatest/api/tokenr    )r,   r    r    r!   Úapi_token_routeÁ   s    zDataSourceEc2.api_token_routec             C   s   dS )NZ21600r    )r,   r    r    r!   Úimdsv2_token_ttl_secondsÅ   s    z&DataSourceEc2.imdsv2_token_ttl_secondsc             C   s   dS )NzX-aws-ec2-metadata-tokenr    )r,   r    r    r!   Úimdsv2_token_put_headerÉ   s    z%DataSourceEc2.imdsv2_token_put_headerc             C   s
   | j d S )Nz-ttl-seconds)rZ   )r,   r    r    r!   Úimdsv2_token_req_headerÍ   s    z%DataSourceEc2.imdsv2_token_req_headerc             C   s   | j | jgS )N)rZ   r[   )r,   r    r    r!   Úimdsv2_token_redactÑ   s    z!DataSourceEc2.imdsv2_token_redactc             C   s²   d}| j ƒ }xž| jD ]”}|j| j|ƒ}ytj||| jd�}W n2 tjk
rn } ztj	d||ƒ W Y dd}~X qX |j
dkrŠtj	d|ƒ |S |j
dkrd}tj	|||jƒ qW | jS )	aE  Get the best supported api version from the metadata service.

        Loop through all extended support metadata versions in order and
        return the most-fully featured metadata api version discovered.

        If extended_metadata_versions aren't present, return the datasource's
        min_metadata_version.
        z{0}/{1}/meta-data/instance-id)r#   ÚheadersÚheaders_redactzurl %s raised exception %sNéÈ   z#Found preferred metadata version %si”  z0Metadata api version %s not present. Headers: %s)Ú_get_headersÚextended_metadata_versionsÚformatr+   ÚuhelpÚreadurlr\   ÚUrlErrorrA   rB   r"   r]   Úmin_metadata_version)r,   Zurl_tmplr]   Zapi_verr#   ZrespÚer9   r    r    r!   Úget_metadata_api_versionÕ   s$    
 

z&DataSourceEc2.get_metadata_api_versionc             C   sh   | j tjkrZt| dd ƒsF| jƒ }tj|| j| j| j	| j
d�jdi ƒ| _| jjd| jd ƒS | jd S d S )NrL   )Ú
headers_cbr^   Úexception_cbr<   Z
instanceIdzinstance-id)rC   r   r   Úgetattrrh   r   Úget_instance_identityr+   r`   r\   Ú_refresh_stale_aws_token_cbrJ   rL   rK   )r,   Úapi_versionr    r    r!   Úget_instance_idô   s    

zDataSourceEc2.get_instance_idc       
      C   sÈ   | j tkrdS g }i }| j}d}x*|D ]"}dj||ƒ}|j|ƒ |||< q&W tjdƒ d}d}| jƒ }	y0tj	||	j
|	jtj| j| j|| jdd�	\}}W n tjk
r¬   Y nX |rÄ|rÄ|| _|| S dS )a  Get an API token for EC2 Instance Metadata Service.

        On EC2. IMDS will always answer an API token, unless
        the instance owner has disabled the IMDS HTTP endpoint or
        the network topology conflicts with the configured hop-limit.
        NÚPUTz{0}/{1}zFetching Ec2 IMDSv2 API TokenF)	ÚurlsÚmax_waitÚtimeoutÚ	status_cbri   rj   Úrequest_methodr^   Zconnect_synchronously)rC   Ú IDMSV2_SUPPORTED_CLOUD_PLATFORMSrX   rb   ÚappendrA   rB   Úget_url_paramsrc   Úwait_for_urlÚmax_wait_secondsÚtimeout_secondsÚwarningr`   Ú_imds_exception_cbr\   re   Ú
_api_token)
r,   Úmdurlsrq   Úurl2baseÚurl_pathru   r#   ÚcurÚresponseÚ
url_paramsr    r    r!   Ú_maybe_fetch_api_token  s>    



z$DataSourceEc2._maybe_fetch_api_tokenc          	   C   sv  | j }| jƒ }|jdkrdS |jd| jƒ}dd„ |D ƒ}t|ƒt|ƒkrdtjdtt|ƒt|ƒ ƒƒ t	|ƒrr|}ntj
dƒ | j}| j|ƒ}| oš| jtk�r g }i }dj| jd	�}d
}	x*|D ]"}
dj|
|ƒ}|j|ƒ |
||< q¾W tjƒ }tj||j|jtj
| j| j|	d�\}
}|
�r ||
 }|�r<|| _tjd| jƒ n2| jtk�rTtj
dƒ ntjd|ttjƒ | ƒƒ t|ƒS )Nr   FÚmetadata_urlsc             S   s   g | ]}t j|ƒr|‘qS r    )r   Zis_resolvable_url)Ú.0Úxr    r    r!   ú
<listcomp>C  s    z;DataSourceEc2.wait_for_metadata_service.<locals>.<listcomp>z,Removed the following from metadata urls: %sz+Empty metadata url list! using default listz{ver}/meta-data/instance-id)ZverZGETz{0}/{1})rq   rr   rs   rt   r^   ri   ru   zUsing metadata source: '%s'z)IMDS's HTTP endpoint is probably disabledz(Giving up on md from %s after %s seconds)Úds_cfgrx   rz   rJ   r†   ÚsetrA   rB   ÚlistÚlenr|   r…   rC   rv   rb   rf   rw   Útimerc   ry   r{   r\   r`   r+   ZcriticalÚintÚbool)r,   Zmcfgr„   r   Zfilteredr+   rq   r€   r�   ru   r#   r‚   Z
start_timeÚ_r    r    r!   Úwait_for_metadata_service:  s^    





z'DataSourceEc2.wait_for_metadata_servicec             C   sä   d| j krd S d }| j d }t|tƒs6tjd|ƒ d S x6|jƒ D ]*\}}||krV|}P |dkr@|dkr@|}q@W |d kr†tjd|ƒ d S |}|jdƒsœd| }tjj	|ƒr¬|S | j
tjj|ƒƒ}|rÔtjd||ƒ |S |dkràd S |S )	Nzblock-device-mappingz+block-device-mapping not a dictionary: '%s'Z	ephemeralZ
ephemeral0z Unable to convert %s to a deviceú/z/dev/%szRemapped device name %s => %s)rK   Ú
isinstanceÚdictrA   rB   rQ   Ú
startswithÚosÚpathÚexistsZ_remap_deviceÚbasename)r,   ÚnameÚfoundZbdmZentnameZdeviceZofoundZremappedr    r    r!   Údevice_name_to_deviceƒ  s8    



z#DataSourceEc2.device_name_to_devicec             C   sP   y6| j tjkr&| jjd| jd d ƒS | jd d S W n tk
rJ   d S X d S )NZavailabilityZoneZ	placementzavailability-zone)rC   r   r   rL   rJ   rK   ÚKeyError)r,   r    r    r!   Úavailability_zone¶  s    zDataSourceEc2.availability_zonec             C   sT   | j tjkr6| jjdƒ}| jr2| r2| jd d… }|S | j}|d k	rP|d d… S d S )NÚregioné   éÿÿÿÿr¢   )rC   r   r   rL   rJ   rŸ   )r,   r    Zazr    r    r!   r    Ã  s    zDataSourceEc2.regionc             C   s,   |sd S | j tjkr(ttj|ttƒ|ƒ d S )N)rC   r   r   Úwarn_if_necessaryr   r>   r?   r@   )r,   ÚcfgZis_new_instancer    r    r!   ÚactivateÑ  s    zDataSourceEc2.activatec             C   sø   | j tjkr| j S | jdkr*tjdƒ dS d}td| jkoD| jtj	kƒ}|rjtj
dƒ tjtj
d| jd� | j}| jjdƒ}t|tƒràt||tj| jddƒd	�}| jƒ rìtj| jƒ| _| jtj jtjƒ | jtj jtjƒ ntjd
|ƒ || _ | j S )z@Return a network config dict for rendering ENI or netplan files.Nz8Unexpected call to network_config when metadata is None.rN   zPMetadata 'network' not present: Refreshing stale metadata from prior to upgrade.zRe-crawl of metadata service)r8   r9   r:   Zapply_full_imds_network_configT)Úfallback_nicÚfull_network_configz%Metadata 'network' key not valid: %s.)Ú_network_configr   ÚUNSETrK   rA   r|   r�   rC   r   r   rB   r   rH   Úget_datarF   rJ   r”   r•   Ú#convert_ec2_metadata_network_configZget_cfg_option_boolrŠ   rR   ÚcopyÚdeepcopyZdefault_update_eventsr	   ÚNETWORKÚaddr
   ÚBOOTÚBOOT_LEGACY)r,   ÚresultZno_network_metadata_on_awsZifaceZnet_mdr    r    r!   Únetwork_configÚ  sF    





zDataSourceEc2.network_configc                s:   | j d kr4t| dd ƒ}|r(|| _ d | _ntt| ƒjS | j S )Nr¦   )Z_fallback_interfacerk   r¦   r)   r&   rF   )r,   Z_legacy_fbnic)r0   r    r!   rF     s    
z DataSourceEc2.fallback_interfacec       	      C   s  | j ƒ si S | jƒ }| j}i }| jtkr:| j}| j}d}n&| jtjkrTd }}t	}nd } }}yxt
j|| j| j||d�}tj|ƒ|d< t
j|| j| j|||d�|d< | jtjkrÖt
j|| j| j||d�}d|i|d< W n& tk
� rþ   tjtd| jƒ i S X ||d	< |S )
zªCrawl metadata service when available.

        @returns: Dictionary of crawled metadata content containing the keys:
          meta-data, user-data and dynamic.
        N)ri   r^   rj   z	user-data)ri   r^   rj   Zretrieval_exception_ignore_cbz	meta-datazinstance-identityr;   z'Failed reading from metadata address %sZ_metadata_api_version)r’   rh   r\   rC   rv   rm   Ú#_skip_or_refresh_stale_aws_token_cbr   r   r%   r   Zget_instance_userdatar+   r`   r   Zmaybe_b64decodeZget_instance_metadatar   rl   Ú	ExceptionZlogexcrA   )	r,   rn   ZredactZcrawled_metadataZexc_cbZ	exc_cb_udZskip_cbZraw_userdatarL   r    r    r!   rI   $  sX    
zDataSourceEc2.crawl_metadatac             C   s�   | j tkrdS |dkr| j}tjdƒ | j|i}dj| j| jƒ}yt	j
||| jdd�}W n0 t	jk
rˆ } ztjd||ƒ dS d}~X nX |jS )z�Request new metadata API token.
        @param seconds: The lifetime of the token in seconds

        @return: The API token or None if unavailable.
        Nz!Refreshing Ec2 metadata API tokenz{}/{}rp   )r]   r^   ru   z/Unable to get API token: %s raised exception %s)rC   rv   rY   rA   rB   r[   rb   r+   rX   rc   rd   r\   re   r|   Úcontents)r,   ZsecondsZrequest_headerZ	token_urlrƒ   rg   r    r    r!   Ú_refresh_api_token\  s$    



z DataSourceEc2._refresh_api_tokenc             C   s$   t jt j||ƒ}|sdS | j||ƒS )zSCallback will not retry on SKIP_USERDATA_CODES or if no token
        is available.F)r   Zskip_retry_on_codesZSKIP_USERDATA_CODESrm   )r,   r9   r$   Zretryr    r    r!   r´   y  s
    z1DataSourceEc2._skip_or_refresh_stale_aws_token_cbc             C   s*   t |tjƒr&|jdkr&tjdƒ d| _dS )z=Exception handler for Ec2 to refresh token if token is stale.i‘  z+Clearing cached Ec2 API token due to expiryNT)r”   rc   re   r"   rA   rB   r~   )r,   r9   r$   r    r    r!   rm   ƒ  s    
z)DataSourceEc2._refresh_stale_aws_token_cbc             C   sD   t |tjƒr@|jr@|jdkr@|jdkr2tjdƒ n
tjdƒ |‚dS )a2  Fail 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.
        i�  i“  zLEc2 IMDS endpoint returned a 403 error. HTTP endpoint is disabled. Aborting.z2Fatal error while requesting Ec2 IMDSv2 API tokensN)r”   rc   re   r"   rA   r|   )r,   r9   r$   r    r    r!   r}   ‹  s    
z DataSourceEc2._imds_exception_cbr7   c             C   sN   | j tkri S | j| ji}| j|kr(|S | jsB| jƒ | _| jsBi S | j| jiS )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.
        )rC   rv   r[   rY   rX   r~   r·   rZ   )r,   r#   Zrequest_token_headerr    r    r!   r`   ¦  s    


zDataSourceEc2._get_headers)N)N)r7   )5r   r   r   rV   r†   rf   ra   r   ÚstrZurl_max_waitZurl_timeoutr~   r   r©   r¨   rE   r	   r®   r
   ZBOOT_NEW_INSTANCEr°   r±   ZHOTPLUGZsupported_update_eventsr*   r2   rM   rR   ÚpropertyrS   rD   rX   rY   rZ   r[   r\   rh   ro   r…   r’   r�   rŸ   r    r¥   r³   rF   rI   r·   r´   rm   r}   r`   Ú__classcell__r    r    )r0   r!   r&   9   sZ   

8
2I3	=8


r&   c                   s$   e Zd ZdZdZ‡ fdd„Z‡  ZS )ÚDataSourceEc2Localay  Datasource 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.
    Tc                s8   t jt jf}| j|kr*tjd|| jƒ dS tt| ƒjƒ S )Nz+Local Ec2 mode only supported on %s, not %sF)	r   r   r   rC   rA   rB   r)   r»   rª   )r,   Zsupported_platforms)r0   r    r!   rª   É  s    
zDataSourceEc2Local.get_data)r   r   r   Ú__doc__rE   rª   rº   r    r    )r0   r!   r»   ¾  s   r»   c             C   s8   yt | ƒS  tk
r2 } ztj|ƒ |S d }~X nX d S )N)Úparse_strict_modeÚ
ValueErrorrA   r|   )ÚcfgvalÚdefaultrg   r    r    r!   r=   Õ  s
    
r=   c             C   sœ   | dkrd
S | dkrdS | s dS | j dƒ\}}}|dkrHtd|| f ƒ‚|r�yt|ƒ}W q” tk
rŒ } ztd	|| f ƒ|‚W Y d d }~X q”X nd }||fS )NTr3   FÚfalser   r   ú,zUInvalid mode '%s' in strict_id setting '%s': Expected one of 'true', 'false', 'warn'.z<Invalid sleep '%s' in strict_id setting '%s': not an integer)r3   N)rÁ   N)r   r   )r3   rÁ   r   )Ú	partitionr¾   r�   )r¿   Úmoder‘   Úsleeprg   r    r    r!   r½   Ý  s*    
r½   c             C   s^   yt | ƒ\}}W n* tk
r: } ztj|ƒ d S d }~X nX |dkrHd S tjd|d|d� d S )NrÁ   Z
non_ec2_mdT)rÄ   rÅ   )r½   r¾   rA   r|   r   Zshow_warning)r¿   r¤   rÄ   rÅ   rg   r    r    r!   r£   þ  s    
r£   c             C   s   | d dkrt jS d S )NÚproduct_namezAlibaba Cloud ECS)r   r   )Údatar    r    r!   Úidentify_aliyun  s    rÈ   c             C   s4   | d j dƒr0| d dks*| d | d kr0tjS d S )NÚuuidr   Úuuid_sourceÚ
hypervisorÚserial)r–   r   r   )rÇ   r    r    r!   Úidentify_aws  s    rÍ   c             C   s   | d j dƒrtjS d S )NrÌ   z.brightbox.com)Úendswithr   r   )rÇ   r    r    r!   Úidentify_brightbox  s    rÏ   c             C   s   | d j dƒrtjS d S )NÚ	asset_tagz
.zstack.io)rÎ   r   r   )rÇ   r    r    r!   Úidentify_zstack  s    rÑ   c             C   s   | d dkrt jS d S )NÚvendorr   )r   r   )rÇ   r    r    r!   Úidentify_e24cloud$  s    rÓ   c             C   s*   | d dj ƒ kr&| d dj ƒ kr&tjS d S )NrÆ   z3DS Outscale VMrÒ   z3DS Outscale)rW   r   r   )rÇ   r    r    r!   Úidentify_outscale)  s    rÔ   c              C   sv   t ƒ } ttttttdd„ f}xT|D ]L}y|| ƒ}|r8|S W q" tk
rl } ztj	d|| |ƒ W Y d d }~X q"X q"W d S )Nc             S   s   t jS )N)r   r   )rˆ   r    r    r!   Ú<lambda>;  s    z#identify_platform.<locals>.<lambda>z'calling %s with %s raised exception: %s)
Ú_collect_platform_datarÍ   rÏ   rÑ   rÓ   rÔ   rÈ   rµ   rA   r|   )rÇ   ZchecksZcheckerr²   rg   r    r    r!   r1   1  s     

r1   c              C   sâ   i } yt jdƒjƒ }d| d< W n& tk
rD   tjdƒ}d| d< Y nX |dkrRd}|jƒ | d< tjd	ƒ}|dkrtd}|jƒ | d
< tjdƒ}|dkr–d}|jƒ | d< tjdƒ}|r´|ndjƒ | d< tjdƒ}|rÒ|ndjƒ | d< | S )a‡  Returns a dictionary of platform info from dmi or /sys/hypervisor.

    Keys in the dictionary are as follows:
       uuid: system-uuid from dmi or /sys/hypervisor
       uuid_source: 'hypervisor' (/sys/hypervisor/uuid) or 'dmi'
       serial: dmi 'system-serial-number' (/sys/.../product_serial)
       asset_tag: 'dmidecode -s chassis-asset-tag'
       vendor: dmi 'system-manufacturer' (/sys/.../sys_vendor)
       product_name: dmi 'system-product-name' (/sys/.../system-manufacturer)

    On Ec2 instances experimentation is that product_serial is upper case,
    and product_uuid is lower case.  This returns lower case values for both.
    z/sys/hypervisor/uuidrË   rÊ   zsystem-uuidr   Nr7   rÉ   zsystem-serial-numberrÌ   zchassis-asset-tagrÐ   zsystem-manufacturerrÒ   zsystem-product-namerÆ   )r   Z	load_fileÚstriprµ   r   Zread_dmi_datarW   )rÇ   rÉ   rÌ   rÐ   rÒ   rÆ   r    r    r!   rÖ   H  s.    




rÖ   Tc             C   sŒ  di dœ}|st jƒ }| d d }|sˆx|jƒ D ]\}}||kr0P q0W ddd|jƒ i|dœ}|j|ƒ}	|	jd	ƒrxd|d
< ||d |< |S d}
xªt|jƒ ƒD ]š\}}|j|ƒ}	|	s²qšt|	jd|
ƒƒd }
d|
d i}d|dd|jƒ i|dœ}|	jd	ƒ�rd|d
< ||d< t|	|ƒ|d< |d �s(|jdƒ ||d |< qšW t	|d ƒdk�rˆx<|d j
ƒ D ],}|d | jdƒ |d | jddƒ �qXW |S )a  Convert ec2 metadata to network config version 2 data dict.

    @param: network_md: 'network' portion of EC2 metadata.
       generally formed as {"interfaces": {"macs": {}} where
       'macs' is a dictionary with mac address as key and contents like:
       {"device-number": "0", "interface-id": "...", "local-ipv4s": ...}
    @param: macs_to_nics: Optional dict of mac addresses and nic names. If
       not provided, get_interfaces_by_mac is called to get it from the OS.
    @param: fallback_nic: Optionally provide the primary nic interface name.
       This nic will be guaranteed to minimally have a dhcp4 configuration.
    @param: full_network_config: Boolean set True to configure all networking
       presented by IMDS. This includes rendering secondary IPv4 and IPv6
       addresses on all NICs and rendering network config on secondary NICs.
       If False, only the primary nic will be configured and only with dhcp
       (IPv4/IPv6).

    @return A dict of network config version 2 based on the metadata and macs.
    é   )ÚversionÚ	ethernetsrO   rP   TFZ
macaddress)Údhcp4Údhcp6Úmatchzset-nameÚipv6srÜ   rÚ   r   zdevice-numberr¡   zroute-metricéd   )rÛ   zdhcp4-overridesrÜ   rÝ   zset-namezdhcp6-overridesÚ	addresseszdhcp4-overridesN)r   Zget_interfaces_by_macrQ   rW   rJ   Úsortedr�   Úget_secondary_addressesÚpopr�   Úkeys)Z
network_mdZmacs_to_nicsr¦   r§   ZnetcfgZmacs_metadataÚmacZnic_nameZ
dev_configÚnic_metadataZnic_idxZdhcp_overrider    r    r!   r«   w  sR    







r«   c             C   s€   | j dƒ}| j dƒ}g }tt|tƒo.t|ƒdkƒrH|jt| d||dƒƒ tt|tƒo^t|ƒdkƒrx|jt| d||dƒƒ t|ƒS )z Parse interface-specific nic metadata and return any secondary IPs

    :return: List of secondary IPv4 or IPv6 addresses to configure on the
    interface
    zlocal-ipv4srÞ   r¡   zsubnet-ipv4-cidr-blockZ24zsubnet-ipv6-cidr-blockZ128)rJ   r�   r”   rŒ   r�   ÚextendÚ_get_secondary_addressesrá   )ræ   rå   Zipv4srÞ   rà   r    r    r!   râ   À  s    

râ   c       
      C   sŒ   g }| j |ƒ}|}| s*t|jdƒƒdkrPd|kr6dnd}tjd|||||ƒ n|jdƒd }x(|dd… D ]}	|jdj|	|d	�ƒ qlW |S )
z£Return list of IP addresses as CIDRs for secondary IPs

    The CIDR prefix will be default_prefix if cidr_key is absent or not
    parseable in nic_metadata.
    r“   rØ   r4   r5   zJCould not parse %s %s for mac %s. %s network config prefix defaults to /%sr¡   Nz{ip}/{prefix})ÚipÚprefix)rJ   r�   ÚsplitrA   r|   rw   rb   )
ræ   Zcidr_keyrå   ZipsZdefault_prefixrà   Zcidrrê   Zip_typeré   r    r    r!   rè   Ù  s     
rè   c             C   s   t j| tƒS )N)r   Zlist_from_dependsÚdatasources)Zdependsr    r    r!   Úget_datasource_listý  s    rí   )r   r   r   )NNT)9r¬   Zloggingr—   rŽ   Ztypingr   Z	cloudinitr   r   r   r   rc   r   r   Zcloudinit.eventr	   r
   Zcloudinit.net.dhcpr   Zcloudinit.net.ephemeralr   Zcloudinit.sources.helpersr   Z	getLoggerr   rA   Ú	frozensetZ	NOT_FOUNDZSKIP_METADATA_URL_CODESr?   r@   r   r%   r   r   rv   Z
DataSourcer&   r»   r=   r½   r£   rÈ   rÍ   rÏ   rÑ   rÓ   rÔ   r1   rÖ   r«   râ   rè   ZDEP_FILESYSTEMZDEP_NETWORKrì   rí   r    r    r    r!   Ú<module>   sT   
     
!
0
H
