o
    3'f                     @   s(  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 d dlmZ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 d dlmZmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlm Z  e!e"Z#dZ$dZ%G dd dZ&dd Z'e&j(e&j)gZ*dZ+G dd dej,Z-G dd de-Z.dd Z/dd Z0dd Z1dd  Z2d!d" Z3d#d$ Z4d%d& Z5d'd( Z6d)d* Z7d+d, Z8d-d. Z9ej:fd/ee;ef d0ee;e;f d1ed2ee;e<f fd3d4Z=d5e>d6e;d7e>d8ed9e?d:e<d2dfd;d<Z@ddd=ej:fd>d?ZAd@dA ZBdBdC ZCe.ejDffe-ejDejEffgZFdDdE ZGdS )F    N)suppress)DictList)dminetsources)
url_helper)utilwarnings)Distro)
EventScope	EventType)netplan)NoDHCPLeaseError)EphemeralIPNetwork)NicOrder)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 )

CloudNamesaliyunaws	brightboxzstacke24cloudoutscaleunknownzno-ec2-metadataN)__name__
__module____qualname__ALIYUNAWS	BRIGHTBOXZSTACKE24CLOUDOUTSCALEUNKNOWNNO_EC2_METADATA r*   r*   A/usr/lib/python3/dist-packages/cloudinit/sources/DataSourceEc2.pyr   $   s    r   c                 C   s   | j dko	d| jv S )N  zmeta-data/tags/)codeurl)	exceptionr*   r*   r+   skip_404_tag_errors4   s   r0   zS
ENV{ID_NET_DRIVER}=="vif|ena|ixgbevf", GOTO="cloudinit_hook"
GOTO="cloudinit_end"
c                       s  e Zd ZU dZg dZdZg dZee e	d< dZ
dZdZejZd	ZejejejejejhiZeZ fd
dZdeddf 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!d0d1 Z/d2d3 Z0e!d4d5 Z1d6d7 Z2dCd8d9Z3d:d; Z4d<d= Z5dCd>d?Z6dDdAdBZ7  Z8S )EDataSourceEc2r   )zhttp://169.254.169.254zhttp://[fd00:ec2::254]zhttp://instance-data.:8773z
2009-04-04)z
2021-03-23z
2018-09-24z
2016-09-02extended_metadata_versionsx   2   NFc                    s,   t t| ||| d | _d | _tj| _d S N)superr1   __init__metadata_addressidentityr   MAC_fallback_nic_order)selfsys_cfgdistropaths	__class__r*   r+   r7   o   s   zDataSourceEc2.__init__ci_pkl_versionreturnc                    s   t  | t| _tj| _d S r5   )r6   	_unpickle_EXTRA_HOTPLUG_UDEV_RULESextra_hotplug_udev_rulesr   r:   r;   )r<   rB   r@   r*   r+   rD   u   s   zDataSourceEc2._unpicklec                 C   s   t  S )z5Return the cloud name as identified during _get_data.)identify_platformr<   r*   r*   r+   _get_cloud_namez   s   zDataSourceEc2._get_cloud_namec                 C   sX  t t| jttd\}}td|| j| j	 |dkr#| jt
jkr#dS | jt
jkr+dS | jrzt r9td dS z6t| j| jjddd!}|jrOd|j nd	}tjtjd
| | jd| _W d    n1 siw   Y  W n tyy   Y dS w tjtjd
| jd| _| jsdS | jdd | _| jdd | _| jdi di di | _dS )N)r   Nz0strict_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func	meta-data	user-datadynamicinstance-identitydocument)read_strict_moder	   get_cfg_by_pathr=   STRICT_ID_PATHSTRICT_ID_DEFAULTLOGdebug
cloud_nameplatformr   r(   r)   perform_dhcp_setup
is_FreeBSDr   r>   fallback_interface	state_msglog_timecrawl_metadata_crawled_metadatar   getmetadatauserdata_rawr9   )r<   strict_mode_sleepnetwrc   r*   r*   r+   	_get_data~   sj   

zDataSourceEc2._get_datac                 C   sL   | j sdS | j di di }|di  D ]\}}d|v r# dS qdS )z6Report if this instance type is Ec2 Classic (non-vpc).Fnetwork
interfacesmacszvpc-idT)rh   rg   items)r<   	ifaces_md_macmac_datar*   r*   r+   is_classic_instance   s   z!DataSourceEc2.is_classic_instancec                 C   s   | j sd S | j dS )Nzami-launch-index)rh   rg   rH   r*   r*   r+   launch_index   s   zDataSourceEc2.launch_indexc                 C   s   | j s	tj | _ | j S r5   )_platform_typer1   dsnamelowerrH   r*   r*   r+   r_      s   zDataSourceEc2.platformc                 C      dS )Nzlatest/api/tokenr*   rH   r*   r*   r+   api_token_route      zDataSourceEc2.api_token_routec                 C   rz   )N21600r*   rH   r*   r*   r+   imdsv2_token_ttl_seconds   r|   z&DataSourceEc2.imdsv2_token_ttl_secondsc                 C   rz   )NzX-aws-ec2-metadata-tokenr*   rH   r*   r*   r+   imdsv2_token_put_header   r|   z%DataSourceEc2.imdsv2_token_put_headerc                 C   s
   | j d S )Nz-ttl-seconds)r   rH   r*   r*   r+   imdsv2_token_req_header   s   
z%DataSourceEc2.imdsv2_token_req_headerc                 C   s   | j | jgS r5   )r   r   rH   r*   r*   r+   imdsv2_token_redact   s   z!DataSourceEc2.imdsv2_token_redactc                 C   s   d}|   }| jD ]M}|| j|}ztj||| jd}W n tjy7 } zt	d|| W Y d}~q	d}~ww |j
dkrGt	d| |  S |j
dkrVd}t	|||j q	| 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 %sr,   z0Metadata api version %s not present. Headers: %s)_get_headersr2   formatr8   uhelpreadurlr   UrlErrorr\   r]   r-   r   min_metadata_version)r<   url_tmplr   api_verr.   resperQ   r*   r*   r+   get_metadata_api_version   s,   




z&DataSourceEc2.get_metadata_api_versionc                 C   sd   | j tjkr-t| dd s#|  }tj|| j| j| j	| j
ddi | _| jd| jd S | jd S )Nr9   
headers_cbr   exception_cbrW   
instanceIdzinstance-id)r^   r   r#   getattrr   r   get_instance_identityr8   r   r   _refresh_stale_aws_token_cbrg   r9   rh   )r<   api_versionr*   r*   r+   get_instance_id  s    

zDataSourceEc2.get_instance_idc           
      C   s   | j tvrdS g }i }| j}d}|D ]}d||}|| |||< qtd d}d}|  }	ztj	||	j
|	jtj| j| j|| jdd	\}}W n
 tjyS   Y nw |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PUT{0}/{1}zFetching Ec2 IMDSv2 API TokenF)	urlsmax_waittimeout	status_cbr   r   request_methodr   connect_synchronously)r^    IDMSV2_SUPPORTED_CLOUD_PLATFORMSr{   r   appendr\   r]   get_url_paramsr   wait_for_urlmax_wait_secondstimeout_secondswarningr   _imds_exception_cbr   r   
_api_token)
r<   mdurlsr   url2baseurl_pathr   r.   curresponse
url_paramsr*   r*   r+   _maybe_fetch_api_token  sB   



z$DataSourceEc2._maybe_fetch_api_tokenc              	   C   sx  g }d}| j }|  }|jdkrdS |d| j}dd |D }t|t|kr6tdtt|t|  t	|r=|}nt
d | j}| |}|s| jtvri }dj| jd	}	d
}
|D ]}d||	}|| |||< q^t }tj||j|jtj
| j| j|
d\}}|r|| }|r|| _td| j t|S | jtv rt
d t|S td|tt |  t|S )Nr   Fmetadata_urlsc                 S   s   g | ]	}t |r|qS r*   )r	   is_resolvable_url).0xr*   r*   r+   
<listcomp>T  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)verGETr   )r   r   r   r   r   r   r   zUsing metadata source: '%s'z)IMDS's HTTP endpoint is probably disabledz(Giving up on md from %s after %s seconds)ds_cfgr   r   rg   r   setr\   r]   listlenr   r   r^   r   r   r   r   time	monotonicr   r   r   r   r   r8   criticalintbool)r<   r   
start_timemcfgr   r   filteredr8   r   r   r   r.   r   _r*   r*   r+   wait_for_metadata_serviceI  sn   










z'DataSourceEc2.wait_for_metadata_servicec                 C   s   d| j vrd S d }| j d }t|tstd| d S | D ]\}}||kr+|} n|dkr5|dkr5|}q|d u rBtd| d S |}|dsMd| }tj	|rU|S | 
tj|}|ritd|| |S |dkrod S |S )	Nzblock-device-mappingz+block-device-mapping not a dictionary: '%s'	ephemeral
ephemeral0z Unable to convert %s to a device/z/dev/%szRemapped device name %s => %s)rh   
isinstancedictr\   r]   rq   
startswithospathexists_remap_devicebasename)r<   namefoundbdmentnamedeviceofoundremappedr*   r*   r+   device_name_to_device  s:   



z#DataSourceEc2.device_name_to_devicec                 C   sL   z| j tjkr| jd| jd d W S | jd d W S  ty%   Y d S w )NavailabilityZone	placementzavailability-zone)r^   r   r#   r9   rg   rh   KeyErrorrH   r*   r*   r+   availability_zone  s   zDataSourceEc2.availability_zonec                 C   sR   | j tjkr| jd}| jr|s| jd d }|S | j}|d ur'|d d S d S )Nregion)r^   r   r#   r9   rg   r   )r<   r   azr*   r*   r+   r     s   
zDataSourceEc2.regionc                 C   s0   |sd S | j tjkrtt|tt| d S d S r5   )r^   r   r(   warn_if_necessaryr	   rY   rZ   r[   )r<   cfgis_new_instancer*   r*   r+   activate  s   zDataSourceEc2.activatec              	   C   s  | j tjkr	| j S | jdu rtd dS d}td| jvo"| jtj	k}|r5t
d tjtj
d| jd | jj}| jd}t|trut|| j|t| jdd| jd	}|  rtt| j| _| jtj tj | jtj tj  nt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 servicerO   apply_full_imds_network_configT)fallback_nicfull_network_configfallback_nic_orderz%Metadata 'network' key not valid: %s.)!_network_configr   UNSETrh   r\   r   r   r^   r   r#   r]   r	   rd   get_datar>   rb   rg   r   r   #convert_ec2_metadata_network_configget_cfg_option_boolr   r;   ru   copydeepcopydefault_update_eventsr   NETWORKaddr   BOOTBOOT_LEGACY)r<   resultno_network_metadata_on_awsifacenet_mdr*   r*   r+   network_config  s^   



zDataSourceEc2.network_configc           	      C   s  |   si S |  }| j}i }| jtv r| j}| j}d}n| jtjkr*d }}t	}nd } }}z<t
j|| j| j||d}t||d< t
j|| j| j|||d|d< | jtjkrkt
j|| j| j||d}d|i|d< W n ty   ttd| j i  Y S w ||d	< |S )
zCrawl metadata service when available.

        @returns: Dictionary of crawled metadata content containing the keys:
          meta-data, user-data and dynamic.
        Nr   rT   )r   r   r   retrieval_exception_ignore_cbrS   rV   rU   z'Failed reading from metadata address %s_metadata_api_version)r   r   r   r^   r   r   #_skip_or_refresh_stale_aws_token_cbr   r'   r0   r   get_instance_userdatar8   r   r	   maybe_b64decodeget_instance_metadatar#   r   	Exceptionlogexcr\   )	r<   r   redactcrawled_metadataexc_cb	exc_cb_udskip_cbraw_userdatar9   r*   r*   r+   re   )  sd   

zDataSourceEc2.crawl_metadatac              
   C   s   | j tvrdS |du r| j}td | j|i}d| j| j}zt	j
||| jdd}W |jS  t	jyI } ztd|| W Y d}~dS d}~ww )zRequest 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{}/{}r   )r   r   r   z/Unable to get API token: %s raised exception %s)r^   r   r~   r\   r]   r   r   r8   r{   r   r   r   r   r   contents)r<   secondsrequest_header	token_urlr   r   r*   r*   r+   _refresh_api_tokena  s,   


z DataSourceEc2._refresh_api_tokenc                 C   s$   t t j||}|sdS | ||S )zSCallback will not retry on SKIP_USERDATA_CODES or if no token
        is available.F)r   skip_retry_on_codesSKIP_USERDATA_CODESr   )r<   rQ   r/   retryr*   r*   r+   r   ~  s   z1DataSourceEc2._skip_or_refresh_stale_aws_token_cbc                 C   s*   t |tjr|jdkrt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   r   r   r-   r\   r]   r   r<   rQ   r/   r*   r*   r+   r     s   
z)DataSourceEc2._refresh_stale_aws_token_cbc                 C   sN   t |tjr!|jr#|jdkr%|jdkrtd |td |dS dS 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   r   r   r-   r\   r   r  r*   r*   r+   r     s   
z DataSourceEc2._imds_exception_cbrN   c                 C   sN   | j tvri S | j| ji}| j|v r|S | js!|  | _| js!i S | j| jiS )zReturn 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.
        )r^   r   r   r~   r{   r   r  r   )r<   r.   request_token_headerr*   r*   r+   r     s   


zDataSourceEc2._get_headersr5   )rN   )9r   r    r!   rx   r   r   r2   r   str__annotations__url_max_waiturl_timeoutr   r   r   r   r`   r   r   r   BOOT_NEW_INSTANCEr   r   HOTPLUGsupported_update_eventsrE   rF   r7   r   rD   rI   rm   ru   propertyrv   r_   r{   r~   r   r   r   r   r   r   r   r   r   r   r   r   re   r  r   r   r   r   __classcell__r*   r*   r@   r+   r1   C   sn   
 	8






2J3

	
>
8

r1   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|vrtd|| j dS tt|  S )Nz+Local Ec2 mode only supported on %s, not %sF)	r   r#   r'   r^   r\   r]   r6   r  r   )r<   supported_platformsr@   r*   r+   r     s   
zDataSourceEc2Local.get_data)r   r    r!   __doc__r`   r   r  r*   r*   r@   r+   r    s    r  c              
   C   s>   zt | W S  ty } zt| |W  Y d }~S d }~ww r5   )parse_strict_mode
ValueErrorr\   r   )cfgvaldefaultr   r*   r*   r+   rX     s   

rX   c              
   C   s   | du rdS | du rdS | sdS |  d\}}}|dvr$td|| f |rEz	t|}W ||fS  tyD } z	td	|| f |d }~ww d }||fS )
NT)rJ   NF)falseN)r   r   ,)rJ   r!  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)	partitionr  r   )r  moder   sleepr   r*   r*   r+   r    s:   
	r  c              
   C   sd   zt | \}}W n ty  } zt| W Y d }~d S d }~ww |dkr'd S tjd|d|d d S )Nr!  
non_ec2_mdT)r$  r%  )r  r  r\   r   r
   show_warning)r  r   r$  r%  r   r*   r*   r+   r     s   
r   c                 C      | d dkr	t jS d S )Nproduct_namezAlibaba Cloud ECS)r   r"   datar*   r*   r+   identify_aliyun     r,  c                 C   sp   | d }| drtjS tt t|j  dr&tjW  d    S W d    d S 1 s1w   Y  d S )Nuuidr   )	r   r   r#   r   r  r.  UUIDbytes_lehex)r+  uuid_strr*   r*   r+   identify_aws  s   


r3  c                 C      | d  dr
tjS d S )Nserialz.brightbox.com)endswithr   r$   r*  r*   r*   r+   identify_brightbox%     r7  c                 C   r4  )N	asset_tagz
.zstack.io)r6  r   r%   r*  r*   r*   r+   identify_zstack*  r8  r:  c                 C   r(  )Nvendorr   )r   r&   r*  r*   r*   r+   identify_e24cloud/  r-  r<  c                 C   s.   | d d  kr| d d  krtjS d S d S )Nr)  z3DS Outscale VMr;  z3DS Outscale)ry   r   r'   r*  r*   r*   r+   identify_outscale4  s
   r=  c                  C   sx   t  } ttttttdd f}|D ])}z|| }|r|W   S W q ty9 } zt	d|| | W Y d }~qd }~ww d S )Nc                 S   s   t jS r5   )r   r(   )r   r*   r*   r+   <lambda>F  s    z#identify_platform.<locals>.<lambda>z'calling %s with %s raised exception: %s)
_collect_platform_datar3  r7  r:  r<  r=  r,  r   r\   r   )r+  checkscheckerr   r   r*   r*   r+   rG   <  s,   	
rG   c                  C   s   d} t tt td } W d   n1 sw   Y  | p&tdp&d} tdp-d}tdp4d}tdp;d}tdpBd}|  | | | | d	S )
aF  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
       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.
    Nz/sys/hypervisor/uuidzsystem-uuidrN   zsystem-serial-numberzchassis-asset-tagzsystem-manufacturerzsystem-product-namer.  r5  r9  r;  r)  )	r   OSErrorUnicodeDecodeErrorr	   load_text_filestripr   read_dmi_datary   rB  r*   r*   r+   r?  S  s   r?  macs_metadatamacs_to_nicsr   rC   c                    sn   i }t dkst dkr|S tdd tfdd }dd  dd tt| fd	dd
D S )aI  
    Builds a dictionary containing macs as keys and nic orders as values,
    taking into account `network-card` and `device-number` if present.

    Note that the first NIC will be the primary NIC as it will be the one with
    [network-card] == 0 and device-number == 0 if present.

    @param macs_metadata: dictionary with mac address as key and contents like:
    {"device-number": "0", "interface-id": "...", "local-ipv4s": ...}
    @macs_to_nics: dictionary with mac address as key and nic name as value

    @return: Dictionary with macs as keys and nic orders as values.
    r   c                 S   s   | d d uS )N   r*   mmdr*   r*   r+   r>    s    z"_build_nic_order.<locals>.<lambda>c                    s   |   | |  fS r5   )rg   )mac)rH  rI  r*   r+   r>    s    c                 S   s    |  |d }|d urt|S |S r5   )rg   r   )diktkey	alt_valuevaluer*   r*   r+   _get_key_as_int_or  s   z,_build_nic_order.<locals>._get_key_as_int_orc                 S   s   i | ]
\}\}}}||qS r*   r*   )r   irM  _mac_metadata	_nic_namer*   r*   r+   
<dictcomp>  s    z$_build_nic_order.<locals>.<dictcomp>c                    sB    | d dt d | d dt dtjkr| d fS | d fS )NrJ  znetwork-cardinfinitydevice-number   r   )floatr   NIC_NAMErK  )rR  r   r*   r+   r>    s   

)rO  )r   filtermapkeys	enumeratesorted)rH  rI  r   	nic_ordervalid_macs_metadatar*   )rR  r   rH  rI  r+   _build_nic_orders  s&   
rc  
dev_confignic_namenic_metadatar>   is_ipv4tablec             
   C   sJ  |r| d}| d}n
| d}| d}|r|s*td|r%d dS d dS |  d	s3g | d	< |rhz|jj||d
}|d }	W n ty\ }
 ztd||
 W Y d}
~
nd}
~
ww | d	 d|	|d t|t	rp|gn|}|D ]}| d	 ||d qt|  dsg | d< t|t	r|gn|}|D ]}| d ||d qdS )a  
    Configure policy-based routing on secondary NICs / secondary IPs to
    ensure outgoing packets are routed via the correct interface.

    @param: dev_config: network cfg v2 to be updated inplace.
    @param: nic_name: nic name. Only used if ipv4.
    @param: nic_metadata: nic metadata from IMDS.
    @param: distro: Instance of Distro. Only used if ipv4.
    @param: is_ipv4: Boolean indicating if we are acting over ipv4 or not.
    @param: table: Routing table id.
    subnet-ipv4-cidr-blocklocal-ipv4szsubnet-ipv6-cidr-blocksipv6szANot enough IMDS information to configure policy routing for IPv%s46Nroutes)r>   routerszoCould not perform dhcp discovery on %s to find its gateway. Not adding default route via the gateway. Error: %sz	0.0.0.0/0)toviarh  )rp  rh  routing-policy)fromrh  )
rg   r\   r]   dhcp_clientdhcp_discoveryr   r   r   r   r  )rd  re  rf  r>   rg  rh  subnet_prefix_routesipsleasegatewayr   prefix_routeipr*   r*   r+   _configure_policy_routing  sl   






r|  Tc              	   C   s  di d}|st  }| d d }|sC| D ]
\}}	|	|kr! nqddd| i|	d}
||}|d	r;d|
d
< |
|d |	< |S t|jtj}t	|||}t
| }|D ]{}|| }	||}|sfqX|| }|dk}d|d d i}d|dd| i|	d}
d| }|r|dr|sd|d< t|
||	|d|d |d	rd|
d
< ||
d< |r|dr|st|
||	|d|d t|||
d< |
d s|
d |
|d |	< qXt|d dkr|d  D ])}	|d |	 d |d |	 dd |d |	 dd |d |	 dd q|S )a8  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: distro: instance of Distro.
    @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.
    rY  )version	ethernetsro   rp   TF
macaddress)dhcp4dhcp6matchset-namerk  r  r~  r   zroute-metricrJ  d   )r  dhcp4-overridesr  r  r  rX  z
use-routes)r>   re  rf  rg  rh  zdhcp6-overrides	addressesr  Nrn  rr  )r   get_interfaces_by_macrq   ry   rg   r   network_rendererr   Rendererrc  r`  r^  r|  get_secondary_addressespopr   )
network_mdr>   rI  r   r   r   netcfgrH  rM  re  rd  rf  
is_netplanra  rp   nic_idxis_primary_nicdhcp_overriderh  r*   r*   r+   r     s   







r   c                 C   s   |  d}|  d}g }tt|tot|dkr$|t| d||d tt|to/t|dkr<|t| d||d t|S )zParse interface-specific nic metadata and return any secondary IPs

    :return: List of secondary IPv4 or IPv6 addresses to configure on the
    interface
    rj  rk  rJ  ri  24zsubnet-ipv6-cidr-block128)rg   r   r   r   r   extend_get_secondary_addressesr`  )rf  rM  ipv4srk  r  r*   r*   r+   r    s    



r  c           
      C   s   g }|  |}|}|rt|ddkr'd|v rdnd}td||||| n|dd }|dd D ]}	|dj|	|d	 q4|S )
zReturn 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   rY  rK   rL   zJCould not parse %s %s for mac %s. %s network config prefix defaults to /%srJ  Nz{ip}/{prefix})r{  prefix)rg   r   splitr\   r   r   r   )
rf  cidr_keyrM  rw  default_prefixr  cidrr  ip_typer{  r*   r*   r+   r    s"   

r  c                 C   s   t | tS r5   )r   list_from_dependsdatasources)dependsr*   r*   r+   get_datasource_list  s   r  )Hr   loggingr   r   r.  
contextlibr   typingr   r   	cloudinitr   r   r   r   r   r	   r
   cloudinit.distrosr   cloudinit.eventr   r   cloudinit.netr   cloudinit.net.dhcpr   cloudinit.net.ephemeralr   cloudinit.sourcesr   cloudinit.sources.helpersr   	getLoggerr   r\   rZ   r[   r   r0   r#   r"   r   rE   
DataSourcer1   r  rX   r  r   r,  r3  r7  r:  r<  r=  rG   r?  r:   r  r   rc  r   r   r|  r   r  r  DEP_FILESYSTEMDEP_NETWORKr  r  r*   r*   r*   r+   <module>   s   

     !#



C
X
|
