x[hV&dZddlZddlZddlmZddlmZmZmZm Z m Z m Z m Z ddl mZddlmZddlmZmZddlmZddlmZmZej2eZGdd ZGd d ZGd d ZGddZde ee efde e fdZ!y)z.Module for ephemeral network context managers N)partial)AnyCallableDictListLiteralOptionalTuple)NoDHCPLeaseErrormaybe_perform_dhcp_discovery)ProcessExecutionError)UrlError wait_for_urlc@eZdZdZ d defdZdZdZdZdZ d Z y) EphemeralIPv4NetworkaContext 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. Ninterface_addrs_before_dhcpc t||||gstdj|||| tj||_||_||_||_||_ ||_ g|_ ||_ |jd|j |_ |j|j i|_y#t$r } tdj| | d} ~ wwxYw)aSetup 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 ValueErrorformatnetipv4_mask_to_net_prefixprefix interfaceip broadcastrouter static_routes cleanup_cmdsdistrocidrgetr) selfr!rrprefix_or_maskrrrres 9/usr/lib/python3/dist-packages/cloudinit/net/ephemeral.py__init__zEphemeralIPv4Network.__init__s*Ir>9=>GNNr>9   55nEDK#" *,. wwiq . +F+J+J NNB, ( %vay  sB;; C$CC$ch |j|jr|j y|j r|jyy#t$r9}dt|jvrdt|jvrYd}~xd}~wwxYw#t$r|jdddwxYw)zSet up ephemeral network if interface is not connected. This context manager handles the lifecycle of the network interface, addresses, routes, etc z File existszAddress already assignedN) _bringup_devicer strstderrr_bringup_static_routesr_bringup_router__exit__)r$r&s r' __enter__zEphemeralIPv4Network.__enter__Ns  $$&&!!++-$$&))  HH)0AHH E  ,%  MM$d +  s3ABB B/B B BBB1c4|jD] }| y)zTeardown anything we set up.N)r )r$ excp_type excp_valueexcp_tracebackcmds r'r/zEphemeralIPv4Network.__exit__rs$$ C E ctjd|j|j|jt j j|ji}|jd}|jjd}|j|jdiDcgc]}|jdc}v}|j|jjdiDcgc]}|jdc}v}|r,tjd|j|jnE|jjj|j|j|j|r!tjd|jn1|jjj|jd|r!tjd |jnO|jjt!|jjj"|jd|r!tjd |jy |jjt!|jjj$|j|jy cc}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 %supipv4rz1Skip adding ip address: %s already has address %sz9Skip bringing up network link: interface %s is already upinet)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)LOGdebugrr"rnetinfo netdev_infor#rrr!net_opsadd_addrlink_upr appendr link_downdel_addr)r$interface_addrs_after_dhcphas_linkhad_linkrhas_iphad_ips r'r*z$EphemeralIPv4Network._bringup_devicews4 H NN II NN  &-%8%8%:%>%> NNB& ".11$73377=#=#A#A&"#M BFF4L  66::62F  FF4L    IIC  KK   ( ( 4>>   IIK  KK   ' 'v ' F  II)     $ $KK''11NN!   II)     $ $KK''00$..$)) ]  s 0K5K c 0|jD]\}}|jjj|j|||j j dt|jjj|j||y)Nrgateway) rr!r@ append_routerr insertr del_route)r$ net_addressrMs r'r-z+EphemeralIPv4Network._bringup_static_routess%)$6$6  K KK   , , W     $ $KK''11NN#   r6c  |jjj}d|vr0tj d|j |j y|jjj|j |j|j|jjdt|jjj|j |j|j|jjj|j d|j|jjdt|jjj|j dy)z>9 M r6)NN) __name__ __module__ __qualname____doc__dictr(r0r/r*r-r.r6r'rrs;$. &*. `"H GR0 r6rc"eZdZdZdZdZdZy)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. cX|stdj|||_||_y)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 zCannot init network on {0}N)rrrr!)r$r!rs r'r(zEphemeralIPv6Network.__init__s,9@@KL L" r6ctj|jddk7r0|jjj |jyy)zlinux kernel does autoconfiguration even when autoconf=0 https://www.kernel.org/doc/html/latest/networking/ipv6.html operstater8N)r read_sys_netrr!r@rBr$s r'r0zEphemeralIPv6Network.__enter__ s?   DNNK 8D @ KK   ' ' 7 Ar6cy)z%No need to set the link to down stateNr^r$_argss r'r/zEphemeralIPv6Network.__exit__sr6N)rYrZr[r\r(r0r/r^r6r'r`r`s 84r6r`cZeZdZ d deeeeeffdZdZ dZ dZ dZ dZ d Zy) EphemeralDHCPv4Nconnectivity_urls_datac||_d|_d|_||_|xsg|_||_t j|_yN) iface_ephipv4lease dhcp_log_funcrkr!r>r?r)r$r!rnrkrqs r'r(zEphemeralDHCPv4.__init__sF 8< /3 *&<&B# +2+>+>+@(r6c~t|jx}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#>  ' '#    II#    ""r6c$|jy)z Teardown sandboxed dhcp context.N) clean_network)r$r2r3r4s r'r/zEphemeralDHCPv4.__exit__7s r6cfd|_|jr|jjdddyy)z@Exit _ephipv4 context to teardown of ip configuration performed.N)rpror/res r'rwzEphemeralDHCPv4.clean_network;s+ == MM " "4t 4 r6c|jr |jSt|j|j|j|_|js t t jd|jd|jd|jdddddgddd}|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-addressz subnet-maskzbroadcast-address)zrfc3442-classless-static-routeszclassless-static-routesrz unknown-121routers)rrr%rrrrr%rrr)rpr r!rnrqr r<r=extract_dhcp_options_mappingrmask_and_ipv4_to_bcast_addr dhcp_clientparse_static_routesrrr0ro)r$nmapkwargsephipv4s r'rtzEphemeralDHCPv4.obtain_leaseAsV :::: 1 KKT%7%7  zz"$ $ 1 JJ{ # JJ ' JJ} %  %!+,    2248k""%"A"A'(&,#F;  / " '';;?+ ? # ' KK (,(H(H    zzr6ci}|jD]G\}}t|tr|j|||*|jj |||<I|Srm)items isinstancelistget_first_option_valuerpr#)r$rresultinternal_referencelease_option_namess r'r{z,EphemeralDHCPv4.extract_dhcp_options_mappingxsh6:jjl P 2  2,d3++&(:F.2ZZ^^>/+J'( Kr6)NNN)rYrZr[r rrr+rr(r0r/rwrtr{rr^r6r'rjrjsPAE A!)d38n)= > A #5 5n Kr6rjc teZdZdZ d dededeeeee ffdZ dZ de 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. Nipv6r9rkc||_||_||_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 ExitStackstack state_msgr!rk)r$r!rrr9rks r'r(zEphemeralIPNetwork.__init__s?&#  ))+   &<#r6c(|js|js|Sg}d}t|jx}rtj d||Stj d|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_versionrzusing link-local ipv6zGFailed to bring up EphemeralIPNetwork. Datasource setup cannot continuer) r9rrsrkr<r= _perform_ephemeral_network_setuprCrerror)r$ exceptionsephemeral_obtainedimds_urlipv4_ephemeral_obtainedipv4_exceptionipv6_ephemeral_obtainedipv6_exceptions r'r0zEphemeralIPNetwork.__enter__s.yyK "3  ' '  8  IIL K CD 99555H 4 #^ "9 9 !!.1 99555H 4 #^ "9 9 !!.1 II1$))4DN! II3 Q-  r6r)r9rreturnc |dk(r;|jjt|j|jnM|dk(r:|jjt |j|jnt 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!rnrzUnsupported 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$rr&s r'rz3EphemeralIPNetwork._perform_ephemeral_network_setups" V# ((##{{"nn v% ((( !#;J =62h/N+/ tXi(( )/br6rrkrcJfd}stjdytdDxsd} tDcgc]}|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. cfDcgc]}|d|k(r|jdc}d}|Scc}w)z Helper function to get headers for a given URL from the connectivity URLs data provided to _check_connectivity_to_imds. urlheadersrr#)rurl_datarrks r' _headers_cbz0_check_connectivity_to_imds.._headers_cb3sH3 #% LL #      s .zZNo connectivity URLs provided. Skipping connectivity check before ephemeral network setup.Nc3@K|]}|jddyw)timeoutrNr).0rs r' z._check_connectivity_to_imds..Hs N8HLLA & NsrFr)urls headers_cbrconnect_synchronouslymax_waitz5Failed to reach IMDS without ephemeral network setup.z8Failed to reach IMDS without ephemeral network setup: %s)r<r=maxrr)rkrrrurl_that_worked_r&s` r'rsrss6  "  J  N7M NN  )2HIh(5/I""'  . IIM N5J   F     s( A9 A4 A94A99 B"BB")"r\rlogging functoolsrtypingrrrrrr r cloudinit.netrcloudinit.netinfor>cloudinit.net.dhcpr r cloudinit.subpr cloudinit.url_helperrr getLoggerrYr<rr`rjrr+rsr^r6r'rsFFF#M07g!b b J44@pKpKfJJZQ c3h0Q c]Qr6