Current File : //usr/lib/python3/dist-packages/cloudinit/net/__pycache__/ephemeral.cpython-312.pyc
�

ӇgV��&�dZddlZddlZddlmZddlmZmZmZm	Z	m
Z
mZmZddl
mZddlmZddlmZmZddlmZddlmZmZej2e�ZGd�d	�ZGd
�d�ZGd�d
�ZGd�d�Zde	ee efdee fd�Z!y)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�@�eZdZdZ		d
defd�Zd�Zd�Zd�Zd�Z	d	�Z
y)�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	���t||||g�stdj||||���	tj|�|_||_||_||_||_	||_
g|_||_|j�d|j
��|_
|j|ji�|_y#t$r }	tdj|	��|	�d}	~	wwxYw)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�net�ipv4_mask_to_net_prefix�prefix�	interface�ip�	broadcast�router�
static_routes�cleanup_cmds�distro�cidr�getr)
�selfr!rr�prefix_or_maskrrrr�es
          �9/usr/lib/python3/dist-packages/cloudinit/net/ephemeral.py�__init__zEphemeralIPv4Network.__init__s���*�I�r�>�9�=�>��G�N�N��r�>�9���
�
	��5�5�n�E�D�K�#������"������*���,.�������w�w�i�q����
�.��	�+F�+J�+J��N�N�B�,
��(���	���%�v�a�y���
��	�s�B;�;	C$�C�C$c�h�		|j�|jr|j�y|jr|j�yy#t$r9}dt|j�vrdt|j�vr�Yd}~�xd}~wwxYw#t$r|jddd��wxYw)z�Set up ephemeral network if interface is not connected.

        This context manager handles the lifecycle of the network interface,
        addresses, routes, etc
        zFile existszAddress already assignedN)	�_bringup_devicer
�str�stderrr�_bringup_static_routesr�_bringup_router�__exit__)r$r&s  r'�	__enter__zEphemeralIPv4Network.__enter__Ns���	�
��$�$�&�&�!�!��+�+�-�����$�$�&���))�
� ���H�H�)��0��A�H�H�
�E����	
��,%�	��M�M�$��d�+��	�s3�A�B�B�	B�/B�B�B�B�B1c�4�|jD]	}|��y)zTeardown anything we set up.N)r )r$�	excp_type�
excp_value�excp_traceback�cmds     r'r/zEphemeralIPv4Network.__exit__rs���$�$�	�C��E�	�c��tjd|j|j|j�tj�j|ji�}|jd�}|jjd�}|j|jdi�D�cgc]}|jd���c}v}|j|jjdi�D�cgc]}|jd���c}v}|r,tjd|j|j�nE|jjj|j|j|j�|r!tjd|j�n1|jjj|jd��|r!tjd	|j�nO|jjt!|jjj"|jd���|r!tjd
|j�y|jjt!|jjj$|j|j��ycc}wcc}w)afPerform 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�up�ipv4rz1Skip adding ip address: %s already has address %sz9Skip bringing up network link: interface %s is already up�inet)�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�debugrr"r�netinfo�netdev_infor#rrr!�net_ops�add_addr�link_upr �appendr�	link_down�del_addr)r$�interface_addrs_after_dhcp�has_link�had_linkr�has_ip�had_ips       r'r*z$EphemeralIPv4Network._bringup_devicews4��	�	�	�H��N�N��I�I��N�N�		
�&-�%8�%8�%:�%>�%>��N�N�B�&
�"�.�1�1�$�7���3�3�7�7��=�����#=�#A�#A�&�"�#M�
��B�F�F�4�L�
�
������6�6�:�:�6�2�F�
��
�F�F�4�L�
�
��
��I�I�C�������
�
�K�K���(�(�����	�	�4�>�>�
���I�I�K����
�

�K�K���'�'����v�'�F���I�I�)����
�
���$�$���K�K�'�'�1�1��N�N�!��
���I�I�)����
�
���$�$���K�K�'�'�0�0�$�.�.�$�)�)��
��]
��
s�0K�5Kc
�0�|jD]�\}}|jjj|j||�|j
j
dt|jjj|j||�����y)Nr��gateway)	rr!r@�append_routerr �insertr�	del_route)r$�net_addressrMs   r'r-z+EphemeralIPv4Network._bringup_static_routes�s���%)�$6�$6�	� �K��
�K�K���,�,�����W�
�
���$�$����K�K�'�'�1�1��N�N��#�	�
�	r6c	� �|jjj�}d|vr0tj	d|j
|j
��y|jjj|j
|j|j��|jjdt|jjj|j
|j|j���|jjj|j
d|j��|jjdt|jjj|j
d��y)z<Perform the ip commands to fully setup the router if needed.�defaultz<Skip ephemeral route setup. %s already has default route: %sN)�source_addressrrL)r!r@�get_default_router<r=r�strip�	add_routerrr rOrrP)r$�outs  r'r.z$EphemeralIPv4Network._bringup_router�s(���k�k�!�!�3�3�5������I�I�N�����	�	��
�

������%�%��N�N�D�K�K����	&�	
�	
��� � �
�����#�#�-�-�������#�w�w�	
�	
�	
�����%�%��N�N�I�t�{�{�	&�	
�	
��� � �
��D�K�K�'�'�1�1�4�>�>�9�M�	
r6)NN)�__name__�
__module__�__qualname__�__doc__�dictr(r0r/r*r-r.�r6r'rrs;���$��.
�&*�.
�`"�H�
G�R�0
r6rc�"�eZdZdZd�Zd�Zd�Zy)�EphemeralIPv6Networkz�Context 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�X�|stdj|���||_||_y)z�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: IPv6 uses prefixes, not netmasks
        zCannot init network on {0}N)rrrr!)r$r!rs   r'r(zEphemeralIPv6Network.__init__�s,����9�@�@��K�L�L�"�����r6c��tj|jd�dk7r0|jjj|j�yy)z�linux kernel does autoconfiguration even when autoconf=0

        https://www.kernel.org/doc/html/latest/networking/ipv6.html
        �	operstater8N)r�read_sys_netrr!r@rB�r$s r'r0zEphemeralIPv6Network.__enter__s?��
���D�N�N�K�8�D�@��K�K���'�'����7�Ar6c��y)z%No need to set the link to down stateNr^�r$�_argss  r'r/zEphemeralIPv6Network.__exit__s�r6N)rYrZr[r\r(r0r/r^r6r'r`r`�s����8�4r6r`c�Z�eZdZ			d
deeeeeffd�Zd�Z	d�Z
d�Zd�Zd�Z
d	�Zy)�EphemeralDHCPv4N�connectivity_urls_datac��||_d|_d|_||_|xsg|_||_t
j�|_y�N)	�iface�_ephipv4�lease�
dhcp_log_funcrkr!r>r?r)r$r!rnrkrqs     r'r(zEphemeralDHCPv4.__init__sF����
�8<��
�/3��
�*���&<�&B���#����+2�+>�+>�+@��(r6c�~�t|j�x}rtjd|�y|j	�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_imdsrkr<r=�obtain_lease)r$�imds_reached_at_urls  r'r0zEphemeralDHCPv4.__enter__(sL��#>��'�'�#
�
��
�
�I�I��#�
�
�� � �"�"r6c�$�|j�y)z Teardown sandboxed dhcp context.N)�
clean_network)r$r2r3r4s    r'r/zEphemeralDHCPv4.__exit__7s�����r6c�f�d|_|jr|jjddd�yy)z@Exit _ephipv4 context to teardown of ip configuration performed.N)rpror/res r'rwzEphemeralDHCPv4.clean_network;s+����
��=�=��M�M�"�"�4��t�4�r6c��|jr|jSt|j|j|j�|_|js
t��tjd|jd|jd|jd�ddddgd�dd�}|j|�}|d	stj|d
|d�|d	<|dr+|jjj|d�|d<t|jfd
|ji|��}|j�||_|jS)a9Perform 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/%srz
fixed-addresszsubnet-maskzbroadcast-address)zrfc3442-classless-static-routeszclassless-static-routesrzunknown-121�routers)rrr%rrrrr%rrr)rprr!rnrqrr<r=�extract_dhcp_options_mappingr�mask_and_ipv4_to_bcast_addr�dhcp_client�parse_static_routesrrr0ro)r$�nmap�kwargs�ephipv4s    r'rtzEphemeralDHCPv4.obtain_leaseAsV���:�:��:�:��1��K�K����T�%7�%7�
��
��z�z�"�$�$��	�	�1��J�J�{�#��J�J��'��J�J�}�%�		
�%�!�+�,�� �
���2�2�4�8���k�"�"%�"A�"A��'�(�&��,�#�F�;���/�"����'�'�;�;��?�+��
�?�#�
'��K�K�
�(,�(H�(H�
��
��
	������
��z�z�r6c��i}|j�D]G\}}t|t�r|j|||��*|jj|�||<�I|Srm)�items�
isinstance�list�get_first_option_valuerpr#)r$r�result�internal_reference�lease_option_namess     r'r{z,EphemeralDHCPv4.extract_dhcp_options_mappingxsh����6:�j�j�l�	P�2�� 2��,�d�3��+�+�&�(:�F��.2�Z�Z�^�^�<N�-O��)�*�
	P��
r6c�r�|D]2}|j|�r�|jj|�||<�4yrm)r#rp)r$�internal_mappingr�r��different_namess     r'r�z&EphemeralDHCPv4.get_first_option_value�s:�� 2�	K�O��:�:�.�/�+/�:�:�>�>�/�+J��'�(�	Kr6)NNN)rYrZr[r	rrr+rr(r0r/rwrtr{r�r^r6r'rjrjsP���AE��
A�!)��d�3��8�n�)=� >�	
A�
#��5�5�n	�Kr6rjc�t�eZdZdZ			d
dededeeeee	ffd�Z
d�Zded	d
e
eeeffd�Zd�Zy)�EphemeralIPNetworkahCombined 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.
    N�ipv6r9rkc��||_||_||_tj�|_d|_||_||_y)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)	rr9r��
contextlib�	ExitStack�stack�	state_msgr!rk)r$r!rr�r9rks      r'r(zEphemeralIPNetwork.__init__�s?��&#�����	���	��)�)�+��
� ������&<��#r6c�(�|js|js|Sg}d}t|j�x}rtjd|�|Stjd�|jr-|j
d��\}}||z}|r|j|�|jr-|j
d��\}}||z}|r|j|�|jrs|jsd|_|stjd�|d	�|S)
NFz:We already have connectivity to IMDS at %s, skipping DHCP.z/No connectivity to IMDS, attempting DHCP setup.r9)�
ip_versionr�zusing link-local ipv6zGFailed to bring up EphemeralIPNetwork. Datasource setup cannot continuer)
r9r�rsrkr<r=� _perform_ephemeral_network_setuprCr��error)r$�
exceptions�ephemeral_obtained�imds_url�ipv4_ephemeral_obtained�ipv4_exception�ipv6_ephemeral_obtained�ipv6_exceptions        r'r0zEphemeralIPNetwork.__enter__�s.���y�y�����K��
�"��3��'�'�
�
�8�
�
�I�I�L��
��K�	�	�	�C�D��9�9��5�5��5�H�
4�#�^�
�"9�9����!�!�.�1��9�9��5�5��5�H�
4�#�^�
�"9�9����!�!�.�1�
�I�I�1�$�)�)�4�D�N�!�
�I�I�3�
��Q�-���r6r�)r9r��returnc���	|dk(r;|jjt|j|j���nM|dk(r:|jjt|j|j��nt
d|����tjd|j|�y#ttf$r/}tjd|j|�d|fcYd	}~Sd	}~wwxYw)
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
        r9)r!rnr�zUnsupported IP version: z7Successfully brought up %s for ephemeral %s networking.)TNz2Failed to bring up %s for ephemeral %s networking.FN)r��
enter_contextrjr!rr`rr<r=r
r)r$r�r&s   r'r�z3EphemeralIPNetwork._perform_ephemeral_network_setup�s���"	��V�#��
�
�(�(�#�#�{�{�"�n�n����v�%��
�
�(�(�(���������!�#;�J�<�!H�I�I��I�I�I�����
�
��%�'7�8�	��I�I�D�����
�
�!�8�O��
	�s�B.B1�1C/�$C*�$C/�*C/c�8�|jj�yrm)r��closergs  r'r/zEphemeralIPNetwork.__exit__s���
�
���r6)FTN)rYrZr[r\�boolr	rrr+rr(r0rr
�	Exceptionr�r/r^r6r'r�r��s~�����AE�
=��	=�
�=�!)��d�3��8�n�)=� >�
=�62�h/��N�+�/�
�t�X�i�(�(�	)�/�br6r�rkr�c�J���fd�}�stjd�ytd��D��xsd}	t�D�cgc]}|d��	c}||dd�	�\}}|stjd
�y|Scc}w#t$r }tjd|�Yd}~yd}~wwxYw)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�f���D�cgc]}|d|k(r|jd���c}d}|Scc}w)z�
        Helper function to get headers for a given URL from the connectivity
        URLs data provided to _check_connectivity_to_imds.
        �url�headersr�r#)r��url_datar�rks   �r'�_headers_cbz0_check_connectivity_to_imds.<locals>._headers_cb3sH���3�
�����#�%�
�L�L��#�
��	
��
���
s� .zZNo connectivity URLs provided. Skipping connectivity check before ephemeral network setup.Nc3�@K�|]}|jdd����y�w)�timeoutrNr�)�.0r�s  r'�	<genexpr>z._check_connectivity_to_imds.<locals>.<genexpr>Hs����N�8�H�L�L��A�&�N�s��r�Fr)�urls�
headers_cbr��connect_synchronously�max_waitz5Failed to reach IMDS without ephemeral network setup.z8Failed to reach IMDS without ephemeral network setup: %s)r<r=�maxrr)rkr�r�r��url_that_worked�_r&s`      r'rsrss����6
�"��	�	�
J�	
��	�N�7M�N�N�	
���
�)�2H�I�h�(�5�/�I�"��"'��
����.��I�I�M�N�����5J���
��	�	�F�
�	
�	
���
�s(�	A9�A4�A9�4A9�9	B"�B�B")"r\r��logging�	functoolsr�typingrrrrrr	r
�
cloudinit.netr�cloudinit.netinfor>�cloudinit.net.dhcprr�cloudinit.subpr
�cloudinit.url_helperrr�	getLoggerrYr<rr`rjr�r+rsr^r6r'�<module>r�s�������F�F�F��#�M�0�7��g����!��b
�b
�J4�4�@pK�pK�fJ�J�ZQ� ��c�3�h��0�Q�
�c�]�Qr6