o
    w7eq                  
   @   sL  U d 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	 ddlm
Z ddl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 eeZdZdZdZdZeZddgZ dddede edgeg dZ!ee"d< ee!Z dZ#dZ$dZ%dZ&dddZ'dddZ(d d!gZ)g d"Z*dgd#d$Z+d%e,d&ed'ed(e-d)df
d*d+Z.d,d- Z/d.d/ Z0dhd0d1Z1dhd2d3Z2dhd4d5Z3d6d7 Z4d8d9 Z5d:d; Z6d<d= Z7d>d? Z8d@dA Z9dBdC Z:didEdFZ;djdGdHZ<dIdJ Z=	dkdKdLZ>dMdN Z?dOdP Z@dQdR ZAdSdT ZBdUdV ZCdWdX ZDdYdZ ZEd[d\ ZFd]d^ ZGdhd_d`ZHdadb ZI	cdldddeZJdfe4iZKdS )mz*Apt Configure: Configure apt for the user.    N)dedent)gpg)log)subp	templaterutil)Cloud)Config)
MetaSchemaget_meta_doc)PER_INSTANCEz
^[\w-]+:\wz/etc/apt/trusted.gpgz/etc/apt/trusted.gpg.d/z/etc/apt/cloud-init.gpg.d/ubuntudebiancc_apt_configurezApt ConfigurezConfigure apt for the usera          This module handles both configuration of apt options and adding
        source lists.  There are configuration options such as
        ``apt_get_wrapper`` and ``apt_get_command`` that control how
        cloud-init invokes apt-get. These configuration options are
        handled on a per-distro basis, so consult documentation for
        cloud-init's distro support for instructions on using
        these config options.

        .. note::
            To ensure that apt configuration is valid yaml, any strings
            containing special characters, especially ``:`` should be quoted.

        .. note::
            For more information about apt configuration, see the
            ``Additional apt configuration`` example.a-	          apt:
          preserve_sources_list: false
          disable_suites:
            - $RELEASE-updates
            - backports
            - $RELEASE
            - mysuite
          primary:
            - arches:
                - amd64
                - i386
                - default
              uri: 'http://us.archive.ubuntu.com/ubuntu'
              search:
                - 'http://cool.but-sometimes-unreachable.com/ubuntu'
                - 'http://us.archive.ubuntu.com/ubuntu'
              search_dns: false
            - arches:
                - s390x
                - arm64
              uri: 'http://archive-to-use-for-arm64.example.com/ubuntu'

          security:
            - arches:
                - default
              search_dns: true
          sources_list: |
              deb $MIRROR $RELEASE main restricted
              deb-src $MIRROR $RELEASE main restricted
              deb $PRIMARY $RELEASE universe restricted
              deb $SECURITY $RELEASE-security multiverse
          debconf_selections:
              set1: the-package the-package/some-flag boolean true
          conf: |
              APT {
                  Get {
                      Assume-Yes 'true';
                      Fix-Broken 'true';
                  }
              }
          proxy: 'http://[[user][:pass]@]host[:port]/'
          http_proxy: 'http://[[user][:pass]@]host[:port]/'
          ftp_proxy: 'ftp://[[user][:pass]@]host[:port]/'
          https_proxy: 'https://[[user][:pass]@]host[:port]/'
          sources:
              source1:
                  keyid: 'keyid'
                  keyserver: 'keyserverurl'
                  source: 'deb [signed-by=$KEY_FILE] http://<url>/ bionic main'
              source2:
                  source: 'ppa:<ppa-name>'
              source3:
                  source: 'deb $MIRROR $RELEASE multiverse'
                  key: |
                      ------BEGIN PGP PUBLIC KEY BLOCK-------
                      <key data>
                      ------END PGP PUBLIC KEY BLOCK-------
              source4:
                  source: 'deb $MIRROR $RELEASE multiverse'
                  append: false
                  key: |
                      ------BEGIN PGP PUBLIC KEY BLOCK-------
                      <key data>
                      ------END PGP PUBLIC KEY BLOCK-------)idnametitledescriptiondistrosexamples	frequencyactivate_by_schema_keysmetaz/var/lib/apt/listsz'/etc/apt/apt.conf.d/94cloud-init-configz)/etc/apt/apt.conf.d/90cloud-init-aptproxyzkeyserver.ubuntu.comz!http://archive.ubuntu.com/ubuntu/z"http://security.ubuntu.com/ubuntu/PRIMARYSECURITYz$http://ports.ubuntu.com/ubuntu-portsamd64i386)s390xarm64armhfpowerpcppc64elriscv64c                 C   s>   | du r	t |} | tv rt S | tv rt S td|  )zreturns the default mirrors for the target. These depend on the
    architecture, for more see:
    https://wiki.ubuntu.com/UbuntuDevelopment/PackageArchive#PortsNz#No default mirror known for arch %s)r   get_dpkg_architecturePRIMARY_ARCHESPRIMARY_ARCH_MIRRORScopyPORTS_ARCHESPORTS_MIRRORS
ValueError)archtarget r-   C/usr/lib/python3/dist-packages/cloudinit/config/cc_apt_configure.pyget_default_mirrors   s   
r/   r   cfgcloudargsreturnc                 C   sP   d}t |}|di }t|tstdjt|dt|| t||| dS )zprocess the config for apt_config. This can be called from
    curthooks if a global apt config was provided or via the "apt"
    standalone command.Naptz9Expected dictionary for 'apt' config, found {config_type})config_type)	convert_to_v3_apt_formatget
isinstancedictr*   formattypeapply_debconf_selections	apply_apt)r   r0   r1   r2   r,   apt_cfgr-   r-   r.   handle   s   

r?   c                   C   s(   t  rdS tdstdsdS dS )N)Fzsystem is snappy.zapt-getr4   )Fzno apt commands.)TzApt is available.)r   system_is_snappyr   whichr-   r-   r-   r.   _should_configure_on_empty_apt   s
   rB   c              	   C   s  | st  \}}|std| d S td|  tj|dd }t|}t| ||d}td| t| ddrLt	| | t
| ||| t||| zt| tt W n ttfyd   td	 Y nw d
| v r|}||d< |d |d< d }	| dt}
|
rt|
j}	t| d
 ||||	d tjg d|dddgd\}}td|}dd |D }|rtd| |D ]	}t|tj qd S )Nz#Nothing to do: No apt config and %szhandling apt config: %sr,   codename)r+   zApt Mirror info: %spreserve_sources_listFz)Failed to apply proxy or apt config info:sourcesRELEASEMIRRORadd_apt_repo_match)r,   template_paramsaa_repo_match)psz-ozppid,pid-CdirmngrrM   z	gpg-agentTr      )r,   capturercsz(?P<ppid>\d+)\s+(?P<pid>\d+)c                 S   s$   g | ]}|d  dkrt |d qS )r   1rO   )int).0pidr-   r-   r.   
<listcomp>   s   $ zapply_apt.<locals>.<listcomp>z&Killing gpg-agent and dirmngr pids: %s)rB   LOGdebugr   lsb_releaser$   find_apt_mirror_infois_falser7   add_mirror_keysgenerate_sources_listrename_apt_listsapply_apt_configAPT_PROXY_FNAPT_CONFIG_FNIOErrorOSError	exceptionADD_APT_REPO_MATCHrecompilesearchadd_apt_sourcesr   findalloskillsignalSIGKILL)r0   r1   r,   should_configmsgreleaser+   mirrorsparamsmatchermatchcfggpg_process_out_errgpg_pidsroot_gpg_pidsgpg_pidr-   r-   r.   r=      s^   


	
r=   c                 C   s*   |  ds	| d7 } tjdg| |dd d S )N   
zdebconf-set-selectionsTdatar,   rP   )endswithr   )
selectionsr,   r-   r-   r.   debconf_set_selections  s   

r   c                 C   s   g }g }| D ]}|t v rtd| t | | || q|| qt|r.td| t|rCtjddgt| d |dd d S d S )Nzunconfiguring %szSThe following packages were installed and preseeded, but cannot be unconfigured: %szdpkg-reconfigurez--frontend=noninteractiveTr|   )CONFIG_CLEANERSrW   rX   appendlenwarningr   list)packagesr,   	unhandled	to_configpkgr-   r-   r.   dpkg_reconfigure  s.   
r   c           
         s   |  d  std dS d fddt  D }t| |d t } 	 D ]\}}|
 D ]}|dr=q5td	d
|}|| q5q-t|}td| ||}	t|	dkrhtd dS t|	|d dS )z2apply_debconf_selections - push content to debconfdebconf_selectionsz(debconf_selections was not set in configN
c                    s   g | ]} | qS r-   r-   )rT   keyselsetsr-   r.   rV   =  s    z,apply_debconf_selections.<locals>.<listcomp>rC   #z[:\s].* zpkgs_cfgd: %sr   zno need for reconfig)r7   rW   rX   joinsortedkeysr   encodesetitems
splitlines
startswithrf   subaddr   get_installed_packagesintersectionr   r   )
r0   r,   r   	pkgs_cfgd_keycontentliner   pkgs_installedneed_reconfigr-   r   r.   r<   2  s*   

 



r<   c                 C   s6   t  t| d}td| |D ]}t| qdS )z%clean out any local cloud-init configz/etc/cloud/cloud.cfg.d/*dpkg*z#cleaning cloud-init config from: %sN)globr   target_pathrW   rX   rk   unlink)r,   flistdpkg_cfgr-   r-   r.   clean_cloud_initU  s   
r   c                 C   sL   | }| dr|dd }|d}|dkr||d d }|dd}|S )zmirrorurl_to_apt_fileprefix
    Convert a mirror url to the file prefix used by apt on disk to
    store cache information for that mirror.
    To do so do:
    - take off ???://
    - drop tailing /
    - convert in string / to _/r   z://   N_)r~   findreplace)mirrorstringposr-   r-   r.   mirrorurl_to_apt_fileprefix`  s   

r   c              
   C   s   t |}t|t}| D ]\\}}| |}|sq|tjj t	| }|tjj t	| }	||	kr3qt
|}
td| D ]+}d|	||
d f }td|| zt|| W q> tyi   tjddd Y q>w qdS )z>rename_apt_lists - rename apt lists to preserve old cache dataz%s_*z%s%sNzRenaming apt list %s to %szFailed to rename apt list:T)exc_info)r/   r   r   	APT_LISTSr   r7   rk   pathsepr   r   r   rW   rX   renamerc   r   )new_mirrorsr,   r+   default_mirrorsprer   omirrornmirroroprefixnprefixolenfilenamenewnamer-   r-   r.   r^   r  s*   
r^   c                 C   s8   dddddd}z||  }W |S  t y   | }Y |S w )zthere are a few default names which will be auto-extended.
    This comes at the inability to use those names literally as suites,
    but on the other hand increases readability of the cfg quite a lotz$RELEASE-updatesz$RELEASE-backportsz$RELEASE-securityz$RELEASE-proposedz$RELEASE)updates	backportssecurityproposedrq   )KeyError)suitemappingretsuiter-   r-   r.   map_known_suites  s   
r   c                 C   s   | s|S |}| D ]`}t |}t|d|i}td|| d}|dD ]A}|dr0||7 }q$| }t|dkrad}	|d drW|dd	 D ]}
|	d7 }	|
	d
rV nqI||	 |krad| }||7 }q$|}q|S )zRreads the config for suites to be disabled and removes those
    from the templaterG   zDisabling suite %s as %sr   Tr   rO      [N]z"# suite disabled by cloud-init: %s)
r   r   render_stringrW   rX   r   r   splitr   r~   )disabledsrcrq   retsrcr   releasesuitenewsrcr   colspcolcolr-   r-   r.   disable_suites  s4   


r   c                 C   s.   dD ]}|  |g D ]	}t|||d q
qdS )z=Adds any keys included in the primary/security mirror clauses)primaryr   )	file_nameN)r7   add_apt_key)r0   r,   r   r   r-   r-   r.   r\     s
   r\   c                 C   s   d}||d}|D ]}|| ||< || ||  < q	| dd}|du rGtd |d|jj }|s9|d}|sBtd dS t	|}t
||}	t| d	|	|}
tj||
d
d dS )zgenerate_sources_list
    create a source.list file based on a custom or default template
    by replacing mirrors and release in the templatez/etc/apt/sources.list)rG   rD   sources_listNz1No custom template provided, fall back to builtinzsources.list.%szsources.listz6No template found, not rendering /etc/apt/sources.listr   i  )mode)lowerr7   rW   infoget_template_filenamedistror   r   r   	load_filer   r   r   
write_file)r0   rq   rr   r1   aptsrcrs   ktmpltemplate_fnrenderedr   r-   r-   r.   r]     s,   




r]   Fc                 C   sH   t d|  zt|j}td|| |dW S  tjy#   t d  w )zM
    actual adding of a key as defined in key argument
    to the system
    zAdding key:
'%s'r   )output_filer}   hardenedz(failed to add apt GPG Key to apt keyring)	rW   rX   pathlibPathstemapt_keyr   ProcessExecutionErrorrd   )r   r   r   r,   r   r-   r-   r.   add_apt_key_raw  s   
r   c                 C   s^   d| v rd| vrt }d| v r| d }t| d || d< d| v r-t| d |p)| d |dS dS )z
    Add key to the system as defined in ent (if any).
    Supports raw keys or keyid's
    The latter will as a first step fetched to get the raw key
    keyidr   	keyserverr   r   N)DEFAULT_KEYSERVERr   
getkeybyidr   )entr,   r   r   r   r-   r-   r.   r     s   r   c                 C   s   | j   d S N)r   update_package_sources)r1   r-   r-   r.   update_packages	  s   r   c                 C   s  |du ri }|du rt dt| tstd|  | D ]}| | }td| d|vr/||d< d|v rEd|d v rEt||dd	}||d
< nt||}d|vrOq|d }t||}|d 	dskt
jd|d |d< |d dsz|d  d7  < ||rztjdd|g|d W n tjy   td  w qt||d }	zd| }
d}d|v r|d sd}tj|	|
|d W q ty } ztd|	|  d}~ww t| dS )a  
    install keys and repo source .list files defined in 'sources'

    for each 'source' entry in the config:
        1. expand template variables and write source .list file in
                /etc/apt/sources.list.d/
        2. install defined keys
        3. update packages via distro-specific method (i.e. apt-key update)


    @param srcdict: a dict containing elements required
    @param cloud: cloud instance object

    Example srcdict value:
    {
    'rio-grande-repo': {
        'source': 'deb [signed-by=$KEY_FILE] $MIRROR $RELEASE main',
        'keyid': 'B59D 5F15 97A5 04B7 E230  6DCA 0620 BBCF 0368 3F77',
        'keyserver': 'pgp.mit.edu'
        }
    }

    Note: Deb822 format is not supported
    Nz did not get a valid repo matcherzunknown apt format: %szadding source/key '%s'r   sourcez	$KEY_FILETr   KEY_FILEr   z/etc/apt/sources.list.d/z.listzadd-apt-repositoryz--no-updaterC   zadd-apt-repository failed.z%s
ar   w)omodezfailed write to file %s: %s)r*   r8   r9   	TypeErrorrW   rX   r   r   r   r   rk   r   r   r~   r   r   rd   r   r   r   rb   r   )srcdictr1   r,   rJ   rK   r   r   key_filer   sourcefncontentsr   detailr-   r-   r.   ri     sd   




ri   c                 C   s~   i }t jdddd t| tr2td | D ]}d|vr'd|d< t |d}n|d }|||< q|S t| tr;| }|S td)	z1convert v1 apt format to v2 (dict in apt_sources)zConfig key 'apt_sources'22.1zUse 'apt' instead)
deprecateddeprecated_versionextra_messagez9apt config: convert V1 to V2 format (source list to dict)r   zcloud_config_sources.listzunknown apt_sources format)	r   	deprecater8   r   rW   rX   rand_dict_keyr9   r*   )srclistr  srcentr   r-   r-   r.   convert_v1_to_v2_apt_formatf  s&   



r  c                 C   s,   |  |ddur|  |||< | |= dS dS )ziconvert an old key to the new one if the old one exists
    returns true if a key was found and convertedNTFr7   )oldcfgaptcfgoldkeynewkeyr-   r-   r.   convert_key  s
   r  c                 C   sL   g d}d}ddgi}|D ]\}}t | |||rd}q|r$|g|d< dS dS )zBconvert old apt_mirror keys into the new more advanced mirror spec))
apt_mirroruri)apt_mirror_searchrh   )apt_mirror_search_dns
search_dnsFarchesdefaultTr   N)r  )r  r  keymap	convertednewmcfgr  r  r-   r-   r.   convert_mirror  s   
r  c                 C   sV  ddddddddddd	d
}g }|D ]}|| v r'| | dv r"| |= q| | q|s,| S tjd| dd | dd}|durwtjddd |D ]+}|| }| | }| |= |du sb||ddu rcqI||| krttd||| |f qI| S i }|D ]}|| durt| ||||  q{t| | |D ]}| |ddurtd| q|| d< | S )z:convert old to new keys and adapt restructured mirror specrF   Nproxy
http_proxyhttps_proxy	ftp_proxyrE   r   rI   )apt_sourcesr  r  r  	apt_proxyapt_http_proxyapt_ftp_proxyapt_https_proxyapt_preserve_sources_listapt_custom_sources_listrI   )Nr   zThe following config key(s): r  )r  r  r4   z0Support for combined old and new apt module keysz@Old and New apt format defined with unequal values %s vs %s @ %sz&old apt key '%s' left after conversion)r   r   r
  r7   r*   r  r  )r  
mapoldkeysneedtoconvertr  	newaptcfgr  verifyr  r-   r-   r.   convert_v2_to_v3_apt_format  sr   

r/  c                 C   s,   |  dd}|durt|| d< t| } | S )zconvert the old list based format to the new dict based one. After that
    convert the old dict keys/format to v3 a.k.a 'new apt config'r$  N)r7   r  r/  )r0   r$  r-   r-   r.   r6     s
   r6   c                 C   s   d}| rZd}g }|dkrd}n|dkrd}nt dt||j}d|dd	d }|r6|d
|  |d g }	|jj	}
d|
|d|
f }|D ]	}|	||  qKt
|	}|S )zG
    Try to resolve a list of predefines DNS names to pick mirrors
    Nr   r   r   r   zsecurity-mirrorzunknown mirror type.rO   z.%s)z.localdomainr   zhttp://%s-%s%s/%sz%s)r*   r   get_hostname_fqdnfqdnr   r   r   extendr   r   search_for_mirror)
configured
mirrortyper0   r1   r   mydomdoms	mirrordnsr2  mirror_listr   	mirrorfmtpostr-   r-   r.   search_for_mirror_dns  s.   
r=  c                 C   sX   | dur|du r
| }| |dS |j  }|r(| }|d |d< |d |d< |S t|S )z^sets security mirror to primary if not defined.
    returns defaults if no mirrors are definedNr   r   r   r   r   )
datasourceget_package_mirror_infor'   r/   )pmirrorsmirrorr+   r1   mirror_infomr-   r-   r.   update_mirror_info   s   

rD  c                 C   sT   |  |d}|du rdS d}|D ]}| dpg }||v r!|  S d|v r'|}q|S )zuout of a list of potential mirror configurations select
    and return the one matching the architecture (or default)Nr  r  r  )r0   r6  r+   mirror_cfg_listr  mirror_cfg_elemr  r-   r-   r.   get_arch_mirrorconfig8  s   rG  c                 C   s`   t | ||}|du rdS |dd}|du rt|dd}|du r.t|dd|| |}|S )zpass the three potential stages of mirror specification
    returns None is neither of them found anything otherwise the first
    hit is returnedNr  rh   r  )rG  r7   r   r4  r=  )r0   r6  r+   r1   mcfgr   r-   r-   r.   
get_mirrorK  s   rI  c                 C   sn   |du rt  }td| t| d||}td| t| d||}td| t||||}|d |d< |S )	a  find_apt_mirror_info
    find an apt_mirror given the cfg provided.
    It can check for separate config of primary and security mirrors
    If only primary is given security is assumed to be equal to primary
    If the generic apt_mirror is given that is defining for both
    Nz!got arch for mirror selection: %sr   zgot primary mirror: %sr   zgot security mirror: %sr   rH   )r   r$   rW   rX   rI  rD  )r0   r1   r+   r@  rA  rB  r-   r-   r.   rZ   e  s   rZ   c                    s   d} fdd|D }t |r!td| t|d|d  ntj|r2t	| td|  
ddrItd	| t| 
d dS tj|r\t	| td
| dS dS )zHapply_apt_config
    Applies any apt*proxy config from if specified
    ))r   Acquire::http::Proxy "%s";)r!  rJ  )r#  zAcquire::ftp::Proxy "%s";)r"  zAcquire::https::Proxy "%s";c                    s(   g | ]\}}  |r|  | qS r-   r  )rT   r   fmtr0   r-   r.   rV     s   ( z$apply_apt_config.<locals>.<listcomp>zwrite apt proxy info to %sr   z#no apt proxy configured, removed %sconfNzwrite apt config info to %sz$no apt config configured, removed %s)r   rW   rX   r   r   r   rk   r   isfiledel_filer7   )r0   proxy_fnameconfig_fnamecfgsproxiesr-   rL  r.   r_   }  s   

r_   Tc                    sR   dd  fdd} fdd}| dkr| S | dks"| d	kr%| S t d
)ad  apt-key replacement

    commands implemented: 'add', 'list', 'finger'

    @param output_file: name of output gpg file (without .gpg or .asc)
    @param data: key contents
    @param human_output: list keys formatted for human parsing
    @param hardened: write keys to to /etc/apt/cloud-init.gpg.d/ (referred to
    with [signed-by] in sources file)
    c                  S   sJ   t jtr	tgng } t tD ]}|dr| t|  q| r#| S dS )zreturn all apt keys

        /etc/apt/trusted.gpg (if it exists) and all keyfiles (and symlinks to
        keyfiles) in /etc/apt/trusted.gpg.d/ are returned

        based on apt-key implementation
        )z.gpgz.ascr   )rk   r   rN  APT_LOCAL_KEYSlistdirAPT_TRUSTED_GPG_DIRr~   r   )	key_filesfiler-   r-   r.   _get_key_files  s   
zapt_key.<locals>._get_key_filesc               	      s   d} st td  | S zrtnt}t }d|} t | | W | S  t	j
y=   t td  Y | S  tyO   t td  Y | S w )ziapt-key add <file>

        returns filepath to new keyring, or '/dev/null' when an error occurs
        z	/dev/nullz)Unknown filename, failed to add key: "{}"z{}{}.gpgz Gpg error, failed to add key: {}z#Decode error, failed to add key: {})r   logexcrW   r:   CLOUD_INIT_GPG_DIRrV  r   dearmorr   r   r   UnicodeDecodeError)r   key_dirstdout)r}   r   r   r-   r.   apt_key_add  s0   


	

zapt_key.<locals>.apt_key_addc                     sf   g }   D ](}z|  tj|d W q tjy- } ztd|| W Y d}~qd}~ww d| S )zapt-key list

        returns string of all trusted keys (in /etc/apt/trusted.gpg and
        /etc/apt/trusted.gpg.d/)
        )human_outputzFailed to list key "%s": %sNr   )r   r   r   r   r   rW   r   r   )key_listr  error)rY  ra  r-   r.   apt_key_list  s   

zapt_key.<locals>.apt_key_listr   fingerr   z@apt_key() commands add, list, and finger are currently supported)r*   )commandr   r}   r   ra  r`  rd  r-   )rY  r}   r   ra  r   r.   r     s   r   z
cloud-init)NNr   )FN)NFN)NNN)NNFT)L__doc__r   rk   r   rf   rm   textwrapr   	cloudinitr   r   loggingr   r   r   cloudinit.cloudr   cloudinit.configr	   cloudinit.config.schemar
   r   cloudinit.settingsr   	getLogger__name__rW   re   rT  rV  r[  r   r   r   __annotations__r   ra   r`   r   r&   r)   r%   r(   r/   strr   r?   rB   r=   r   r   r<   r   r   r^   r   r   r\   r]   r   r   r   ri   r  r  r  r/  r6   r=  rD  rG  rI  rZ   r_   r   r   r-   r-   r-   r.   <module>   s   
E`
	
;

!#&


Y
J)

R