U
    Ӈg V                     @   s   d Z ddlZddlZddlmZ ddlmZmZmZm	Z	m
Z
mZmZ ddl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 eeZG dd	 d	ZG d
d dZG dd dZG dd dZe	ee ef  ee  dddZ!dS )z.Module for ephemeral network context managers
    N)partial)AnyCallableDictListLiteralOptionalTuple)NoDHCPLeaseErrormaybe_perform_dhcp_discovery)ProcessExecutionError)UrlErrorwait_for_urlc                   @   sH   e Zd ZdZdedddZdd Zdd	 Zd
d Zdd Z	dd Z
dS )EphemeralIPv4Networka  Context manager which sets up temporary static network configuration.

    No operations are performed if the provided interface already has the
    specified configuration.
    This can be verified with the connectivity_urls_data.
    If unconnected, bring up the interface with valid ip, prefix and broadcast.
    If router is provided setup a default route for that interface. Upon
    context exit, clean up the interface leaving no configuration behind.
    N)interface_addrs_before_dhcpc	           
   
   C   s   t ||||gs$td||||zt|| _W n2 tk
rf }	 ztd|	|	W 5 d}	~	X Y nX || _|| _|| _|| _	|| _
g | _|| _| j d| j | _|| ji | _dS )a  Setup context manager and validate call signature.

        @param interface: Name of the network interface to bring up.
        @param ip: IP address to assign to the interface.
        @param prefix_or_mask: Either netmask of the format X.X.X.X or an int
            prefix.
        @param broadcast: Broadcast address for the IPv4 network.
        @param router: Optionally the default gateway IP.
        @param static_routes: Optionally a list of static routes from DHCP
        z5Cannot init network on {0} with {1}/{2} and bcast {3}z4Cannot setup network, invalid prefix or netmask: {0}N/)all
ValueErrorformatnetZipv4_mask_to_net_prefixprefix	interfaceip	broadcastrouterstatic_routescleanup_cmdsdistrocidrgetr   )
selfr   r   r   prefix_or_maskr   r   r   r   e r#   9/usr/lib/python3/dist-packages/cloudinit/net/ephemeral.py__init__   s>        zEphemeralIPv4Network.__init__c              
   C   s   zpz|    W n@ tk
rN } z"dt|jkr>dt|jkr> W 5 d}~X Y nX | jr`|   n| jrn|   W n$ tk
r   | ddd  Y nX dS )zSet up ephemeral network if interface is not connected.

        This context manager handles the lifecycle of the network interface,
        addresses, routes, etc
        zFile existszAddress already assignedN)	_bringup_devicer   strstderrr   _bringup_static_routesr   _bringup_router__exit__)r    r"   r#   r#   r$   	__enter__N   s"    
zEphemeralIPv4Network.__enter__c                 C   s   | j D ]
}|  qdS )zTeardown anything we set up.N)r   )r    	excp_type
excp_valueexcp_tracebackcmdr#   r#   r$   r+   r   s    
zEphemeralIPv4Network.__exit__c                 C   s:  t d| j| j| j t | ji }|d}| jd}| j	dd |di D k}| j	dd | jdi D k}|rt d| j| j	 n| j
j| j| j| j |rt d| j n| j
jj| jd	d
 |rt d| j n| jt| j
jj| jd	d
 |rt d| j	 n| jt| j
jj| j| j dS )af  Perform the ip commands to fully set up the device.

        Dhcp clients behave differently in how they leave link state and ip
        address assignment.

        Attempt assigning address and setting up link if needed to be done.
        Set cleanup_cmds to return the interface state to how it was prior
        to execution of the dhcp client.
        z:Attempting setup of ephemeral network on %s with %s brd %supc                 S   s   g | ]}| d qS r   r   .0r   r#   r#   r$   
<listcomp>   s    z8EphemeralIPv4Network._bringup_device.<locals>.<listcomp>ipv4c                 S   s   g | ]}| d qS r2   r3   r4   r#   r#   r$   r6      s   z1Skip adding ip address: %s already has address %sz9Skip bringing up network link: interface %s is already upZinet)ZfamilyzLNot queueing link down: link [%s] was up prior before receiving a dhcp leasezSNot queueing address removal: address %s was assigned before receiving a dhcp leaseN)LOGdebugr   r   r   netinfonetdev_infor   r   r   r   net_opsZadd_addrlink_upr   appendr   Z	link_downZdel_addr)r    Zinterface_addrs_after_dhcpZhas_linkZhad_linkZhas_ipZhad_ipr#   r#   r$   r&   w   sv    
 



    z$EphemeralIPv4Network._bringup_devicec              
   C   sJ   | j D ]>\}}| jj| j|| | jdt| jjj| j||d qd S )Nr   gateway)	r   r   r<   Zappend_router   r   insertr   	del_route)r    Znet_addressr@   r#   r#   r$   r)      s      z+EphemeralIPv4Network._bringup_static_routesc              	   C   s   | j j }d|kr,td| j|  dS | j jj| j| j| j	d | j
dt| j jj| j| j| j	d | j jj| jd| jd | j
dt| j jj| jd dS )z<Perform the ip commands to fully setup the router if needed.defaultz<Skip ephemeral route setup. %s already has default route: %sN)Zsource_addressr   r?   )r   r<   Zget_default_router8   r9   r   stripZ	add_router   r   r   rA   r   rB   )r    outr#   r#   r$   r*      s>      	  z$EphemeralIPv4Network._bringup_router)NN)__name__
__module____qualname____doc__dictr%   r,   r+   r&   r)   r*   r#   r#   r#   r$   r      s     0$Ir   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	EphemeralIPv6NetworkzContext manager which sets up a ipv6 link local address

    The linux kernel assigns link local addresses on link-up, which is
    sufficient for link-local communication.
    c                 C   s"   |st d||| _|| _dS )zSetup context manager and validate call signature.

        @param interface: Name of the network interface to bring up.
        @param ip: IP address to assign to the interface.
        @param prefix: IPv6 uses prefixes, not netmasks
        zCannot init network on {0}N)r   r   r   r   )r    r   r   r#   r#   r$   r%      s    zEphemeralIPv6Network.__init__c                 C   s&   t | jddkr"| jj| j dS )zlinux kernel does autoconfiguration even when autoconf=0

        https://www.kernel.org/doc/html/latest/networking/ipv6.html
        Z	operstater1   N)r   Zread_sys_netr   r   r<   r=   r    r#   r#   r$   r,     s    zEphemeralIPv6Network.__enter__c                 G   s   dS )z%No need to set the link to down stateNr#   r    Z_argsr#   r#   r$   r+     s    zEphemeralIPv6Network.__exit__N)rF   rG   rH   rI   r%   r,   r+   r#   r#   r#   r$   rK      s   rK   c                   @   s\   e Zd Zdeeeeef   dddZdd Z	dd Z
d	d
 Zdd Zdd Zdd ZdS )EphemeralDHCPv4Nconnectivity_urls_datac                 C   s6   || _ d | _d | _|| _|pg | _|| _t | _d S N)	iface_ephipv4leasedhcp_log_funcrP   r   r:   r;   r   )r    r   rR   rP   rU   r#   r#   r$   r%     s    
zEphemeralDHCPv4.__init__c                 C   s&   t | j }rtd| dS |  S )zUSetup sandboxed dhcp context, unless connectivity_url can already be
        reached.z:Skip ephemeral DHCP setup, instance has connectivity to %sN)_check_connectivity_to_imdsrP   r8   r9   obtain_lease)r    Zimds_reached_at_urlr#   r#   r$   r,   (  s    zEphemeralDHCPv4.__enter__c                 C   s   |    dS )z Teardown sandboxed dhcp context.N)clean_network)r    r-   r.   r/   r#   r#   r$   r+   7  s    zEphemeralDHCPv4.__exit__c                 C   s    d| _ | jr| jddd dS )z@Exit _ephipv4 context to teardown of ip configuration performed.N)rT   rS   r+   rL   r#   r#   r$   rX   ;  s    zEphemeralDHCPv4.clean_networkc                 C   s   | j r| j S t| j| j| j| _ | j s,t td| j d | j d | j d  dddddddd	gd
d}| |}|d st	
|d |d |d< |d r| jj|d |d< t| jfd| ji|}|  || _| j S )a9  Perform dhcp discovery in a sandboxed environment if possible.

        @return: A dict representing dhcp options on the most recent lease
            obtained from the dhclient discovery if run, otherwise an error
            is raised.

        @raises: NoDHCPLeaseError if no leases could be obtained.
        z#Received dhcp lease on %s for %s/%sr   zfixed-addresszsubnet-maskzbroadcast-addresszrfc3442-classless-static-routeszclassless-static-routesr   zunknown-121Zrouters)r   r   r!   r   r   r   r   r!   r   r   )rT   r   r   rR   rU   r
   r8   r9   extract_dhcp_options_mappingr   Zmask_and_ipv4_to_bcast_addrZdhcp_clientZparse_static_routesr   r   r,   rS   )r    nmapkwargsZephipv4r#   r#   r$   rW   A  s^    	  
 zEphemeralDHCPv4.obtain_leasec                 C   sD   i }|  D ]2\}}t|tr.| ||| q| j|||< q|S rQ   )items
isinstancelistget_first_option_valuerT   r   )r    rZ   resultZinternal_referencelease_option_namesr#   r#   r$   rY   x  s    
  z,EphemeralDHCPv4.extract_dhcp_options_mappingc                 C   s(   |D ]}| |s| j |||< qd S rQ   )r   rT   )r    Zinternal_mappingra   r`   Zdifferent_namesr#   r#   r$   r_     s    
z&EphemeralDHCPv4.get_first_option_value)NNN)rF   rG   rH   r   r   r   r'   r   r%   r,   r+   rX   rW   rY   r_   r#   r#   r#   r$   rN     s      7rN   c                   @   sd   e Zd ZdZdeeeeeee	f   dddZ
dd	 Zed
 eeee f dddZdd ZdS )EphemeralIPNetworkah  Combined ephemeral context manager for IPv4 and IPv6

    Either ipv4 or ipv6 ephemeral network may fail to initialize, but if either
    succeeds, then this context manager will not raise exception. This allows
    either ipv4 or ipv6 ephemeral network to succeed, but requires that error
    handling for networks unavailable be done within the context.
    FTN)ipv6r7   rP   c                 C   s2   || _ || _|| _t | _d| _|| _|| _dS )a  
        Args:
            distro: The distro object
            interface: The interface to bring up
            ipv6: Whether to bring up an ipv6 network
            ipv4: Whether to bring up an ipv4 network
            connectivity_urls_data: List of url data to use for connectivity
                check before attempting to bring up ephemeral networks. If
                connectivity can be established to any of the urls, then the
                ephemeral network setup is skipped.
         N)	r   r7   rc   
contextlib	ExitStackstack	state_msgr   rP   )r    r   r   rc   r7   rP   r#   r#   r$   r%     s    
zEphemeralIPNetwork.__init__c                 C   s   | j s| js| S g }d}t| j }r6td| | S td | j rl| jdd\}}||O }|rl|| | jr| jdd\}}||O }|r|| | jr|s| j sd| _|st	d |d	 | S )
NFz:We already have connectivity to IMDS at %s, skipping DHCP.z/No connectivity to IMDS, attempting DHCP setup.r7   )
ip_versionrc   zusing link-local ipv6zGFailed to bring up EphemeralIPNetwork. Datasource setup cannot continuer   )
r7   rc   rV   rP   r8   r9    _perform_ephemeral_network_setupr>   rh   error)r    
exceptionsZephemeral_obtainedZimds_urlZipv4_ephemeral_obtainedZipv4_exceptionZipv6_ephemeral_obtainedZipv6_exceptionr#   r#   r$   r,     sB    




zEphemeralIPNetwork.__enter__)r7   rc   )ri   returnc              
   C   s   zf|dkr$| j t| j| jd n.|dkrD| j t| j| j ntd| td| j| W dS  t	t
fk
r } z td| j| d|f W Y S d	}~X Y nX d	S )
a  
        Attempt to bring up an ephemeral network for the specified IP version.

        Args:
            ip_version (str): The IP version to bring up ("ipv4" or "ipv6").

        Returns:
            Tuple: A tuple containing:
                - a boolean indicating whether an ephemeral network was
                    successfully obtained
                - an optional exception if ephemeral network setup failed
                    or None if successful
        r7   )r   rR   rc   zUnsupported IP version: z7Successfully brought up %s for ephemeral %s networking.)TNz2Failed to bring up %s for ephemeral %s networking.FN)rg   enter_contextrN   r   r   rK   r   r8   r9   r   r
   )r    ri   r"   r#   r#   r$   rj     s:    z3EphemeralIPNetwork._perform_ephemeral_network_setupc                 G   s   | j   d S rQ   )rg   closerM   r#   r#   r$   r+     s    zEphemeralIPNetwork.__exit__)FTN)rF   rG   rH   rI   boolr   r   r   r'   r   r%   r,   r   r	   	Exceptionrj   r+   r#   r#   r#   r$   rb     s      61rb   )rP   rm   c              
      s    fdd} st d dS tdd  D p2d}z$tdd	  D ||d
dd\}}W n. tk
r } zt d| W 5 d}~X Y nX |st d dS |S dS )a  
    Perform a connectivity check to the provided URLs to determine if the
    ephemeral network setup is necessary.

    This function attempts to reach one of the provided URLs and returns the
    URL that was successfully reached. If none of the URLs can be reached,
    it returns None.

    The timeout for the request is determined by the highest timeout value
    provided in the connectivity URLs data. If no timeout is provided, a
    default timeout of 5 seconds is used.

    Args:
        connectivity_urls_data: A list of dictionaries, each containing
            the following keys:
            - "url" (str): The URL to check connectivity for.
            - "headers" (dict, optional): Headers to include in the request.
            - "timeout" (int, optional): Timeout for the request in seconds.

    Returns:
        Optional[str]: The URL that was successfully reached, or None if no
        connectivity was established.
    c                    s    fddD d }|S )z
        Helper function to get headers for a given URL from the connectivity
        URLs data provided to _check_connectivity_to_imds.
        c                    s"   g | ]}|d   kr| dqS urlZheadersr3   r5   Zurl_datars   r#   r$   r6   8  s   zD_check_connectivity_to_imds.<locals>._headers_cb.<locals>.<listcomp>r   r#   rr   rO   ru   r$   _headers_cb3  s    
z0_check_connectivity_to_imds.<locals>._headers_cbzZNo connectivity URLs provided. Skipping connectivity check before ephemeral network setup.Nc                 s   s   | ]}| d dV  qdS )timeoutr   Nr3   rt   r#   r#   r$   	<genexpr>H  s     z._check_connectivity_to_imds.<locals>.<genexpr>   c                 S   s   g | ]}|d  qS ru   r#   rt   r#   r#   r$   r6   N  s     z/_check_connectivity_to_imds.<locals>.<listcomp>Fr   )ZurlsZ
headers_cbrw   Zconnect_synchronouslyZmax_waitz8Failed to reach IMDS without ephemeral network setup: %sz5Failed to reach IMDS without ephemeral network setup.)r8   r9   maxr   r   )rP   rv   rw   Zurl_that_worked_r"   r#   rO   r$   rV     s6    
rV   )"rI   re   Zlogging	functoolsr   typingr   r   r   r   r   r   r	   Zcloudinit.netr   Zcloudinit.netinfor:   Zcloudinit.net.dhcpr
   r   Zcloudinit.subpr   Zcloudinit.url_helperr   r   Z	getLoggerrF   r8   r   rK   rN   rb   r'   rV   r#   r#   r#   r$   <module>   s&   $
 f s 