a
    k d\                     @   s  d dl Z 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mZmZmZ d dlm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mZ d dlmZ d d	lm Z  d d
l!m"Z"m#Z#m$Z$m%Z% d dl&m'Z' d dl(m)Z) dZ*dgdgddgddgddgdgdgg dg ddgddgdZ+e,e-Z.e/dZ0g dZ1ej2ej3 d  Z4G d!d" d"ej5e j6d#Z7e8e9d$d%d&Z:e8d'd(d)Z;dej<fd*d+Z=d,d- Z>e8ee7 d.d/d0Z?d7d3d4Z@d5d6 ZAdS )8    N)StringIO)AnyMappingMutableMappingOptionalType)importer)log)netpersistencessh_utilsubp
temp_utils
type_utilsutil)LinuxNetworking
Networking)hosts)+ALLOW_EC2_MIRRORS_ON_NON_AWS_INSTANCE_TYPES)
activatorseninetwork_state	renderers)parse_net_config_data)RendererallalpinearchdebianZubuntufreebsdZ	dragonflygentooZcosnetbsdopenbsd)Z	almalinuxZamazonZcentosZ
cloudlinuxZ	eurolinuxZfedoraZmarinerZmiraclelinuxZopenmandrivaZphotonZrhelZrockyZ	virtuozzo)Zopensusezopensuse-leapzopensuse-microoszopensuse-tumbleweedZsle_hpcz	sle-microZsles	openEulerOpenCloudOSZ	TencentOS)r   r   r   r   r    r!   r"   ZredhatZsuser#   r$   z#^[a-z][a-z]-(?:[a-z]+-)+[0-9][a-z]$)Zchronyzsystemd-timesyncdZntpZntpdate-c                   @   s  e Zd ZU dZdZdZdZdZdZdZ	dgZ
i Zeeeeef f ed	< d
ZeZee ed< ddddZdZdZdZeed< dd Zed
dddZejdd Zdd Z e!e"ee#j$  dddZ%e&dd d!Z'e&d"d#d$Z(d%d& Z)dd'd(Z*dd)d*Z+dd+d,Z,d-d. Z-ejdd/d0Z.ejd1d2 Z/d3d4 Z0dd5d6Z1dd7d8Z2dd:d;Z3dd<d=Z4d>d? Z5de6dd@dAZ7ejddBdCZ8ejdDdE Z9dFdG Z:dHdI Z;ejddJdKZ<ejdLdM Z=ejdNdO Z>dPdQ Z?dRdS Z@eAdTdU ZBdVdW ZCdXdY ZDe!dZd[ ZEd\d] ZFd^d_ ZGd`da ZHdbdc ZIddde ZJdfdg ZKdhdi ZLdjdk ZMddldmZNeOe6dndodpZPddrdsZQddtduZRddvdwZSdxdy ZTeedzd{d|ZUd}d~ ZVedddZWdeOeedddZXd
S )Distrozpython3-pipz/usr/libz
/etc/hostsz"/etc/sudoers.d/90-cloud-init-usersz/etc/hostnamez/usr/share/zoneinfoz	root:rootservicerenderer_configsNnetworking_clsz-Hz-Pz-r)ZhaltZpoweroffZreboot   Fz/etc/resolv.confZosfamilyc                 C   s    || _ || _|| _|  | _d S N)Z_paths_cfgnamer)   
networking)selfr-   Zcfgpaths r1   >/usr/lib/python3.9/site-packages/cloudinit/distros/__init__.py__init__r   s    zDistro.__init__)ci_pkl_versionreturnc                 C   s    d| j vs| jj s|  | _dS )z)Perform deserialization fixes for Distro.r.   N)__dict__r.   r)   )r/   r4   r1   r1   r2   	_unpicklex   s    zDistro._unpicklec                 C   s
   t  d S r+   NotImplementedError)r/   Zpkglistr1   r1   r2   install_packages   s    zDistro.install_packagesc                 C   s   t d| j dS )=Deprecated. Remove if/when arch and gentoo support renderers.zhLegacy function '_write_network' was called in distro '%s'.
_write_network_config needs implementation.
N)r9   r-   )r/   settingsr1   r1   r2   _write_network   s
    zDistro._write_network)r5   c                 C   s:   t | jdd}ztj|dW S  tjy4   Y dS 0 dS )z=Return the configured network activator for this environment.)networkr   Npriority)r   get_cfg_by_pathr,   r   Zselect_activatorZNoActivatorException)r/   r@   r1   r1   r2   network_activator   s    zDistro.network_activatorc                 C   sD   t | jdd }tj|d\}}td|| || j|d}|S )N)r>   r   r?   z-Selected renderer '%s' from priority list: %s)Zconfig)	r   rA   r,   r   ZselectLOGdebugr(   get)r/   r@   r-   Z
render_clsrendererr1   r1   r2   _get_renderer   s    zDistro._get_rendererrF   c                 C   s   | | d S r+   )Zrender_network_state)r/   r   rF   r1   r1   r2   _write_network_state   s    zDistro._write_network_statec                 C   s4   t j| jt|}t j|s0td||f |S )Nz(Invalid timezone %s, no file found at %s)ospathjointz_zone_dirstrisfileIOError)r/   tztz_filer1   r1   r2   _find_tz_file   s    
zDistro._find_tz_filec                 C   s   | j ||S r+   )r,   rE   )r/   opt_namedefaultr1   r1   r2   
get_option   s    zDistro.get_optionc                 C   s   || j |< d S r+   )r,   )r/   rT   valuer1   r1   r2   
set_option   s    zDistro.set_optionc                 C   s(   |  ||}| || j | | d S r+   )_select_hostname_write_hostnamehostname_conf_fn_apply_hostname)r/   hostnamefqdnZwriteable_hostnamer1   r1   r2   set_hostname   s    zDistro.set_hostnamec                 C   s   t  S )z?Wrapper to report whether this distro uses systemd or sysvinit.)uses_systemdr/   r1   r1   r2   r`      s    zDistro.uses_systemdc                 C   s
   t  d S r+   r8   )r/   commandargsZpkgsr1   r1   r2   package_command   s    zDistro.package_commandc                 C   s
   t  d S r+   r8   ra   r1   r1   r2   update_package_sources   s    zDistro.update_package_sourcesc                 C   s   t  d }|dv rdS |S )N   )i386Zi486Zi586Zi686rg   )rJ   uname)r/   r   r1   r1   r2   get_primary_arch   s    zDistro.get_primary_archc                 C   s"   |  dg }|s|  }t||S )Npackage_mirrors)rV   ri   _get_arch_package_mirror_info)r/   r   mirror_infor1   r1   r2   rk      s    z$Distro._get_arch_package_mirror_infoc                 C   s   |  |}t||dS )N)data_sourcerl   )rk   _get_package_mirror_info)r/   r   rm   Z	arch_infor1   r1   r2   get_package_mirror_info   s    
zDistro.get_package_mirror_infoTc                 C   s   |  |}|r| |S dS )r;   F)r=   _bring_up_interfaces)r/   r<   bring_upZ	dev_namesr1   r1   r2   apply_network   s    

zDistro.apply_networkc                 C   sL   | j }td| dd| dg}t|}tj||dd}| j||dS )r;   ziapply_network_config is not currently implemented for distribution '%s'.  Attempting to use apply_network
z-# Converted from network_config for distro %sz4# Implementation of _write_network_config is needed.T)headerZrender_hwaddressrq   )		__class__rC   warningrL   r   r   r   Znetwork_state_to_enirr   )r/   	netconfigrq   Zdistrort   nscontentsr1   r1   r2   "_apply_network_from_network_config   s    
z)Distro._apply_network_from_network_configc                 C   s   t  S r+   )r
   generate_fallback_configra   r1   r1   r2   r|      s    zDistro.generate_fallback_configc                 C   s   z|   }W n  ty,   | j||d Y S 0 t||d}| || |rxtd | j}|sltd dS |	| n
td dS )a  Apply the network config.

        If bring_up is True, attempt to bring up the passed in devices. If
        devices is None, attempt to bring up devices returned by
        _write_network_config.

        Returns True if any devices failed to come up, otherwise False.
        ru   rH   z/Bringing up newly configured network interfacesz>No network activator found, not bringing up network interfacesTz3Not bringing up newly configured network interfacesF)
rG   r9   r{   r   rI   rC   rD   rB   rw   Zbring_up_all_interfaces)r/   rx   rq   rF   r   rB   r1   r1   r2   apply_network_config  s&    

zDistro.apply_network_configc                 C   s
   t  d S r+   r8   )r/   localeZout_fnr1   r1   r2   apply_locale'  s    zDistro.apply_localec                 C   s
   t  d S r+   r8   )r/   rQ   r1   r1   r2   set_timezone+  s    zDistro.set_timezonec                 C   s   dS )Nz	127.0.0.1r1   ra   r1   r1   r2   _get_localhost_ip/  s    zDistro._get_localhost_ipc                 C   s
   t  d S r+   r8   ra   r1   r1   r2   
get_locale2  s    zDistro.get_localec                 C   s
   t  d S r+   r8   )r/   filenamerU   r1   r1   r2   _read_hostname5  s    zDistro._read_hostnamec                 C   s
   t  d S r+   r8   )r/   r]   r   r1   r1   r2   rZ   9  s    zDistro._write_hostnamec                 C   s
   t  d S r+   r8   ra   r1   r1   r2   _read_system_hostname=  s    zDistro._read_system_hostnamec                 C   sF   t d| ztd|g W n" tjy@   tt d| Y n0 d S )Nz2Non-persistently setting the system hostname to %sr]   z;Failed to non-persistently adjust the system hostname to %s)rC   rD   r   ZProcessExecutionErrorr   logexc)r/   r]   r1   r1   r2   r\   A  s    zDistro._apply_hostnamec                 C   s&   t | jd| jr|r|S |s"|S |S )NZprefer_fqdn_over_hostname)r   Zget_cfg_option_boolr,   prefer_fqdn)r/   r]   r^   r1   r1   r2   rY   R  s    
zDistro._select_hostnamec                 C   s6   g }| D ](}|t vr"td||t |  q|S )Nz&No distributions found for osfamily {})
OSFAMILIES
ValueErrorformatextend)Zfamily_listZdistrosZfamilyr1   r1   r2   expand_osfamily`  s    zDistro.expand_osfamilyc           
   
   C   s  |}|  ||}|r,tj|r,| |}nd }|  \}}g }|rL||krV|| |rj||krt||krt|| |r|r||krtd|| d S t	dd |D }t
d|t| |D ]8}	z| ||	 W q ty   ttd||	 Y q0 q||v r| | d S )Nz6%s differs from %s, assuming user maintained hostname.c                 S   s   g | ]}|r|qS r1   r1   ).0fr1   r1   r2   
<listcomp>      z*Distro.update_hostname.<locals>.<listcomp>z/Attempting to update hostname to %s in %s filesz!Failed to write hostname %s to %s)rY   rJ   rK   existsr   r   appendrC   infosetrD   lenrZ   rP   r   r   r\   )
r/   r]   r^   Zprev_hostname_fnZapplying_hostnameZprev_hostnameZsys_fnZsys_hostnameZupdate_filesfnr1   r1   r2   update_hostnamek  sJ    


zDistro.update_hostnamec                 C   s~  d}t j| jr&tt| j}ntd}tjdd}| 	 }|
|}d}|sj|||| d}nd}|D ]T}d }	g }
t|dkr|d }	t|dkr|dd  }
|	d urr|	|krr||
v rrd}qr|r6t|}|||g || |D ]B}t|dkr|||d  qt|dkr|j|g|R   q|rzt }|rV|d	|  |d	|  tj| j| d
d d S )N addedbaseFTr*   r      z%s
i  )mode)rJ   rK   r   hosts_fnr   Z	HostsConfr   	load_filemake_headerr   Z	get_entryZ	add_entryr   listr   Zdel_entriesr   write
write_filegetvalue)r/   r]   r^   rt   ZehZlocal_ipZ	prev_infoZneed_changeentryZ
entry_fqdnZentry_aliasesZnew_entriesrz   r1   r1   r2   update_etc_hosts  sJ    


zDistro.update_etc_hostsc                 C   s   | j stt| _ | j S )z7Allow distro to determine the preferred ntp client list)_preferred_ntp_clientsr   PREFERRED_NTP_CLIENTSra   r1   r1   r2   preferred_ntp_clients  s    
zDistro.preferred_ntp_clientsc                 C   s   t dS )r;   Nr8   )r/   Zdevice_namer1   r1   r2   _bring_up_interface  s    zDistro._bring_up_interfacec                 C   s0   d}|D ]}|  |s|d7 }q|dkr,dS dS )r;   r   r*   TF)r   )r/   Zdevice_namesZ	am_faileddr1   r1   r2   rp     s    

zDistro._bring_up_interfacesc                 C   s
   |  dS )NZdefault_user)rV   ra   r1   r1   r2   get_default_user  s    zDistro.get_default_userc                 K   s  t |rtd| dS d|v r.|d}nd}d|g}d|g}t  r^|d |d ddd	d
ddddddd
}dddd}dg}|d}	|	rt|	t	r|	
d}	t|	trtd| dd |	D }	d|	|d< |d}
|
r|	|
 |r2|	r2|	D ]*}t |s| | td|| qd| v rPt	|d |d< t| D ]\}}||v r|rt|t	r||| |g ||v r||| dg n||| |g n,||v r\|r\|||  |||  q\|d s|d!r"|d" |d" n|d# |d# td$| ztj||d% W n8 ty } zt td&| |W Y d}~n
d}~0 0 dS )'z
        Add a user to the system using standard GNU tools

        This should be overriden on distros where useradd is not desirable or
        not available.
        z!User %s already exists, skipping.Ncreate_groupsTZuseradd--extrausersz	--commentz--homez--gidz--uidz--groupsz
--passwordz--shellz--expiredatez
--inactivez--selinux-user)
Zgecoshomedirprimary_groupuidgroupspasswdshellZ
expiredateZinactiveZselinux_userz--no-user-groupz--systemz--no-log-init)Zno_user_groupsystemZno_log_initr   r   ,zDEPRECATED: The user %s has a 'groups' config value of type dict which is deprecated and will be removed in a future version of cloud-init. Use a comma-delimited string or array instead: group1,group2.c                 S   s   g | ]}|  qS r1   strip)r   gr1   r1   r2   r   2  r   z#Distro.add_user.<locals>.<listcomp>r   z created group '%s' for user '%s'r   ZREDACTEDZno_create_homer   z-Mz-mzAdding user %s	logstringzFailed to create user %s)r   is_userrC   r   popsystem_is_snappyr   rE   
isinstancerN   splitdictrw   rL   is_groupcreate_grouprD   keyssorteditemsr   r   	Exceptionr   )r/   r-   kwargsr   Zuseradd_cmdZlog_useradd_cmdZuseradd_optsZuseradd_flagsZredact_optsr   r   groupkeyvaler1   r1   r2   add_user  s    















zDistro.add_userc              
   K   s   | d}| dd}g d}|r,|d || td| z<tj||dd\}}td	|| t|}| d
d}	W n6 ty }
 zttd| |
W Y d}
~
n
d}
~
0 0 |	S )zD
        Add a snappy user to the system using snappy tools
        snapuserknownF)Zsnapzcreate-userz--sudoerz--jsonz--knownzAdding snap user %sT)r   capturez snap create-user returned: %s:%susernameNzFailed to create snap user %s)	rE   r   rC   rD   r   r   Z	load_jsonr   r   )r/   r-   r   r   r   Zcreate_user_cmdouterrZjobjr   r   r1   r1   r2   add_snap_usere  s$    




zDistro.add_snap_userc                 K   s  d|v r| j |fi |S | j|fi | d|v rL|d rL| ||d  d|v rp|d rp| j||d dd |ddr| | d|v r|d r| ||d  n|d du rtd	| d
|v rJ|d
 }t|t	r|g}nt|t
rt| }|dur:t|tttfs,tdt| g }nt|p8g }tt|| d|v r|dg }|sztd||d  n:|d }tj}|d|}|d|}tjt|||d dS )a}  
        Creates or partially updates the ``name`` user in the system.

        This defers the actual user creation to ``self.add_user`` or
        ``self.add_snap_user``, and most of the keys in ``kwargs`` will be
        processed there if and only if the user does not already exist.

        Once the existence of the ``name`` user has been ensured, this method
        then processes these keys (for both just-created and pre-existing
        users):

        * ``plain_text_passwd``
        * ``hashed_passwd``
        * ``lock_passwd``
        * ``sudo``
        * ``ssh_authorized_keys``
        * ``ssh_redirect_user``
        r   Zplain_text_passwdZhashed_passwdT)hashedlock_passwdZsudoFzxDEPRECATED: The user %s has a 'sudo' config value of 'false' which will be dropped after April 2027. Use 'null' instead.Zssh_authorized_keysNzZInvalid type '%s' detected for 'ssh_authorized_keys', expected list, string, dict, or set.Zssh_redirect_userZcloud_public_ssh_keysz^Unable to disable SSH logins for %s given ssh_redirect_user: %s. No cloud public-keys present.z$USERz$DISABLE_USER)options)r   r   
set_passwdrE   r   write_sudo_rulesrC   rw   r   rN   r   r   valuestupler   typer   Zsetup_user_keysZDISABLE_USER_OPTSreplace)r/   r-   r   r   Z
cloud_keysZredirect_userZdisable_optionr1   r1   r2   create_user  s`    






zDistro.create_userc              
   C   s   dd|gdd|gf}zt dd |D }W n@ tyj } z(td|dd	 |D f |W Y d
}~n
d
}~0 0 zt| W n6 ty } zttd| |W Y d
}~n
d
}~0 0 d
S )zL
        Lock the password of a user, i.e., disable password logins
        r   z-lusermodz--lockc                 s   s    | ]}t |d  r|V  qdS )r   N)r   which)r   Ztoolr1   r1   r2   	<genexpr>  r   z%Distro.lock_passwd.<locals>.<genexpr>zBUnable to lock user account '%s'. No tools available.   Tried: %s.c                 S   s   g | ]}|d  qS )r   r1   r   cr1   r1   r2   r     r   z&Distro.lock_passwd.<locals>.<listcomp>Nz&Failed to disable password for user %s)nextStopIterationRuntimeErrorr   r   r   r   rC   )r/   r-   Z
lock_toolscmdr   r1   r1   r2   r     s     zDistro.lock_passwdc              
   C   sP   zt  dd|g W n6 tyJ } zttd| |W Y d }~n
d }~0 0 d S )Nr   z--expirezFailed to set 'expire' for %s)r   r   r   r   rC   )r/   userr   r1   r1   r2   expire_passwd  s
    zDistro.expire_passwdc              
   C   st   d||f }dg}|r | d ztj||d| d W n6 tyn } zttd| |W Y d }~n
d }~0 0 dS )Nz%s:%schpasswd-ezchpasswd for %sr   zFailed to set password for %sT)r   r   r   r   r   rC   )r/   r   r   r   Zpass_stringr   r   r1   r1   r2   r     s    
zDistro.set_passwd)plist_inr   c                 C   s<   d dd |D d }dg|r&dgng  }t|| d S )Nrs   c                 s   s    | ]\}}d  ||gV  qdS ):NrL   )r   r-   passwordr1   r1   r2   r   
  r   z"Distro.chpasswd.<locals>.<genexpr>r   r   )rL   r   )r/   r   r   Zpayloadr   r1   r1   r2   r     s    zDistro.chpasswd/etc/sudoersc              
   C   sF  d}d}t j|r"t|}d}d}| D ]N}| }td|}|sLq.|	d }|s`q.t j
|}||kr.d} q~q.|s6zx|sddtjddd	| dg}	d
|	}t||d n.dtjddd	| dg}	d
|	}t|| td|| W n8 ty4 }
 zttd| |
W Y d }
~
n
d }
~
0 0 t|d d S )Nr   FTz^[#|@]includedir\s+(.*)$r*   z?# See sudoers(5) for more information on "#include" directives:r   r   z#includedir %srs      zAdded '#includedir %s' to %szFailed to write %si  )rJ   rK   r   r   r   
splitlinesr   researchr   abspathr   rL   r   append_filerC   rD   rP   r   Z
ensure_dir)r/   rK   Z	sudo_baseZsudoers_contentsZbase_existsZfound_includelineZinclude_matchZincluded_dirlinesr   r1   r1   r2   ensure_sudo_dir  sR    




zDistro.ensure_sudo_dirc           
   
   C   sV  |s
| j }dd| g}t|ttfrB|D ]}|d||f  q(n4t|tr`|d||f  nd}t|t| d	|}|d7 }| 
tj| tj|st |g}zt|d	|d W n8 ty }	 zttd| |	W Y d }	~	n
d }	~	0 0 nJzt|| W n8 tyP }	 zttd| |	W Y d }	~	n
d }	~	0 0 d S )	Nr   z# User rules for %sz%s %sz1Can not create sudoers rule addition with type %rrs   r   zFailed to write sudoers file %sz Failed to append sudoers file %s)ci_sudoers_fnr   r   r   r   rN   	TypeErrorr   Zobj_namerL   r   rJ   rK   dirnamer   r   r   r   rP   r   rC   r   )
r/   r   ZrulesZ	sudo_filer   ZrulemsgZcontentrz   r   r1   r1   r2   r   B  s:    

zDistro.write_sudo_rulesc                 C   s   d|g}t  r|d |s"g }t |r:td| n<zt| td| W n  tyt   t 	td| Y n0 t
|dkr|D ]@}t |std|| qtdd	d
||g td|| qd S )NZgroupaddr   z(Skipping creation of existing group '%s'zCreated new group %szFailed to create group %sr   zCUnable to add group member '%s' to group '%s'; user does not exist.r   z-az-GzAdded user '%s' to group '%s')r   r   r   r   rC   rw   r   r   r   r   r   r   )r/   r-   membersZgroup_add_cmdmemberr1   r1   r2   r   g  s.    



zDistro.create_groupc             
   C   sx   d| j | g}z|dkr$dt| }W n4 tyZ } ztd|f |W Y d }~n
d }~0 0 ||g }|rt|| |S )NZshutdownZnowz+%dz?power_state[delay] must be 'now' or '+m' (minutes). found '%s'.)shutdown_options_mapintr   r   r   )r/   r   Zdelaymessagerb   r   rc   r1   r1   r2   shutdown_command  s     

zDistro.shutdown_command)actionr'   c              	   C   s   | j }|  sd|v rTdg}d|gd|gd|gd|gd|gd|gd|gd	|gd
}n6|dg|dg|dg|dg|dg|dg|dg|d	gd
}t|t||  }tj|ddS )z
        Perform the requested action on a service. This handles the common
        'systemctl' and 'service' cases and may be overridden in subclasses
        as necessary.
        May raise ProcessExecutionError
        Z	systemctlstopstartenabledisablerestartzreload-or-restartzreload-or-try-restartstatus)r  r  r  r  r	  reloadz
try-reloadr
  T)r   )init_cmdr`   r   r   )r/   r  r'   r  Zcmdsr   r1   r1   r2   manage_service  s.    
zDistro.manage_servicec                 C   s*   |   r tdd||||g nt d S )NZ	localectlzset-x11-keymap)r`   r   r9   )r/   ZlayoutZmodelZvariantr   r1   r1   r2   
set_keymap  s    zDistro.set_keymapc                 C   s.   t jdd}t|ds|S tj| jddS )NT)Z	needs_exeZnoexecz
cloud-initZclouddir)r   Zget_tmp_ancestorr   Zhas_mount_optrJ   rK   rL   usr_lib_exec)r/   Ztmp_dirr1   r1   r2   get_tmp_exec_path  s    zDistro.get_tmp_exec_pathr   )rb   r   cwdc              	   K   s>   |rd| dnd}t j dd|d|d d| gfi |S )	a`  
        Perform a command as the requested user. Behaves like subp()

        Note: We pass `PATH` to the user env by using `env`. This could be
        probably simplified after bionic EOL by using
        `su --whitelist-environment=PATH ...`, more info on:
        https://lore.kernel.org/all/20180815110445.4qefy5zx5gfgbqly@ws.net.home/T/
        zcd z && r   Zsur%   z-czenv PATH=$PATH  )r   rL   )r/   rb   r   r  r   Z	directoryr1   r1   r2   do_as  s    	zDistro.do_as)N)N)N)NN)N)NN)T)T)F)N)N)F)r   )N)N)r   )Y__name__
__module____qualname__Zpip_package_namer  r   r   r[   rM   Zdefault_ownerr  r(   r   rN   r   r   __annotations__r   r   r)   r   r   r   Z_ci_pkl_versionr   Zresolve_conf_fnr3   r  r7   abcabstractmethodr:   r=   propertyr   r   ZNetworkActivatorrB   r   rG   rI   rS   rV   rX   r_   r`   rd   re   ri   rk   ro   rr   r{   r|   boolr}   r   r   r   r   r   rZ   r   r\   rY   staticmethodr   r   r   r   r   rp   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r1   r1   r1   r2   r&   \   s   










%




A+

u[


1
%
 "r&   )	metaclassurltransformationsc                 C   s   zt j| }W n ty$   Y dS 0 |j}|du r8dS |D ]}||}|du r<|   S q<|}|jdurvd||j}t j|j|dS )a  
    Apply transformations to a URL's hostname, return transformed URL.

    This is a separate function because unwrapping and rewrapping only the
    hostname portion of a URL is complex.

    :param url:
        The URL to operate on.
    :param transformations:
        A list of ``(str) -> Optional[str]`` functions, which will be applied
        in order to the hostname portion of the URL.  If any function
        (regardless of ordering) returns None, ``url`` will be returned without
        any modification.

    :return:
        A string whose value is ``url`` with the hostname ``transformations``
        applied, or ``None`` if ``url`` is unparseable.
    Nz{}:{})netloc)	urllibparseurlsplitr   r]   portr   
urlunsplit_replace)r  r   partsZnew_hostnameZtransformationZ
new_netlocr1   r1   r2   &_apply_hostname_transformations_to_url  s    

r)  )r  c                    s2   t d  dd dd  fdddd g}t| |S )aH  
    Given a mirror URL, replace or remove any invalid URI characters.

    This performs the following actions on the URL's hostname:
      * Checks if it is an IP address, returning the URL immediately if it is
      * Converts it to its IDN form (see below for details)
      * Replaces any non-Letters/Digits/Hyphen (LDH) characters in it with
        hyphens
      * Removes any leading/trailing hyphens from each domain name label

    Before we replace any invalid domain name characters, we first need to
    ensure that any valid non-ASCII characters in the hostname will not be
    replaced, by ensuring the hostname is in its Internationalized domain name
    (IDN) representation (see RFC 5890).  This conversion has to be applied to
    the whole hostname (rather than just the substitution variables), because
    the Punycode algorithm used by IDNA transcodes each part of the hostname as
    a whole string (rather than encoding individual characters).  It cannot be
    applied to the whole URL, because (a) the Punycode algorithm expects to
    operate on domain names so doesn't output a valid URL, and (b) non-ASCII
    characters in non-hostname parts of the URL aren't encoded via Punycode.

    To put this in RFC 5890's terminology: before we remove or replace any
    characters from our domain name (which we do to ensure that each label is a
    valid LDH Label), we first ensure each label is in its A-label form.

    (Note that Python's builtin idna encoding is actually IDNA2003, not
    IDNA2008.  This changes the specifics of how some characters are encoded to
    ASCII, but doesn't affect the logic here.)

    :param url:
        The URL to operate on.

    :return:
        A sanitized version of the URL, which will have been IDNA encoded if
        necessary, or ``None`` if the generated string is not a parseable URL.
    .c                 S   s   t | rd S | S r+   )r
   Zis_ip_addressr]   r1   r1   r2   <lambda>9  r   z&_sanitize_mirror_url.<locals>.<lambda>c                 S   s   |  ddS )NZidnaascii)encodedecoder+  r1   r1   r2   r,  <  r   c                    s   d  fdd| D S )Nr   c                 3   s   | ]}| v r|nd V  qdS r%   Nr1   r   Zacceptable_charsr1   r2   r   >  s   9_sanitize_mirror_url.<locals>.<lambda>.<locals>.<genexpr>r   r+  r1  r1   r2   r,  >  s   c                 S   s   d dd | dD S )Nr*  c                 s   s   | ]}| d V  qdS r0  r   )r   partr1   r1   r2   r   B  s   r2  )rL   r   r+  r1   r1   r2   r,  B  s   
)LDH_ASCII_CHARSr)  r  r1   r1  r2   _sanitize_mirror_url  s    &
r5  c              
   C   s&  | si } i }|rb|j rb|j |d< t|j rb|j dd }trLd| |d< n|jdkrbd| |d< |rv|jrv|j|d< i }| di  D ]\}}|||< q| d	i  D ]h\}}g }	|D ]B}
z|
| }W n ty   Y qY n0 t	|}|d ur|	
| q||	}|r|||< qtd
| |S )Navailability_zoner   z%s
ec2_regionZec2regionZfailsafer   zfiltered distro mirror info: %s)r6  
_EC2_AZ_REmatchr   Zplatform_typer9  rE   r   KeyErrorr5  r   rC   rD   )rl   rm   Zmirror_filtersubstr8  resultsr-   ZmirrorZ
searchlistZmirrorsZtmplfoundr1   r1   r2   rn   J  s>    







rn   c                 C   s8   d }| D ]*}| d}||v r&|  S d|v r|}q|S )NarchesrU   )rE   )rj   r   rU   itemr@  r1   r1   r2   rk   }  s    
rk   )r-   r5   c                 C   sH   t | dtgdg\}}|s,td| |f t |d }t|d}|S )Nr   r&   z1No distribution found for distro %s (searched %s)r   )r   find_moduler  ImportErrorimport_modulegetattr)r-   ZlocsZlooked_locsmodclsr1   r1   r2   fetch  s    
rH  /etc/timezone/etc/localtimec                 C   sh   t |t|  d  |rd|rdtj|}|s<tj|sX|rJt | t	|| nt 
|| d S )Nrs   )r   r   rN   rstriprJ   rK   islinkr   Zdel_filesymlinkcopy)rQ   rR   Ztz_confZtz_localrL  r1   r1   r2   set_etc_timezone  s    
rO  c                  C   s2   zt d} t| jW S  ty,   Y dS 0 d S )Nz/run/systemd/systemF)rJ   lstatstatS_ISDIRst_moder   )resr1   r1   r2   r`     s
    
r`   )NrI  rJ  )Br  rJ   r   rQ  stringurllib.parser"  ior   typingr   r   r   r   r   Z	cloudinitr   r	   Zloggingr
   r   r   r   r   r   r   Zcloudinit.distros.networkingr   r   Zcloudinit.distros.parsersr   Zcloudinit.featuresr   Zcloudinit.netr   r   r   r   Zcloudinit.net.network_stater   Zcloudinit.net.rendererr   ZALL_DISTROSr   Z	getLoggerr  rC   compiler:  r   ascii_lettersdigitsr4  ZCloudInitPickleMixinABCMetar&   rN   r   r)  r5  Zsearch_for_mirrorrn   rk   rH  rO  r`   r1   r1   r1   r2   <module>   sd   $		$

       +<
3 
