a '¡DgQ˜ã@s´UdZddlZddlZddlZddlZddlZddlZddlmZddl m Z m Z m Z m Z ddlmZmZmZmZmZddlmZddlmZddlmZdd lmZdd lmZe e¡Z d Z!d Z"d Z#dZ$dZ%dddœZ&e e'e'fe(d<dddgegdœZ)ee(d<dZ*dZ+dZ,dZ-dddœZ.d d dœZ/d!d"gZ0gd#¢Z1d$Z2de2iZ3dud%d&„Z4e'eee5dd'œd(d)„Z6d*d+„Z7d,d-„Z8d.d/„Z9d0d1„Z:d2d3„Z;d4d5„Zd:d;„Z?e'e'd<œd=d>„Z@e'd?œd@dA„ZAe'd?œdBdC„ZBdDdE„ZCe'eDdFœdGdH„ZEdIdJdKdLœZFdMZGe e'e'fd?œdNdO„ZHdPdQ„ZIdvdSdT„ZJdUdV„ZKdwdWdX„ZLdxdYdZ„ZMd[d\„ZNd]d^„ZOd_d`„ZPdadb„ZQdcdd„ZRdedf„ZSdgdh„ZTdidj„ZUdkdl„ZVdydmdn„ZWdodp„ZXdzdrds„ZYdteãóz,apply_debconf_selections..ú#z[:\s].*Úz pkgs_cfgd: %srzno need for reconfig)r,r@rAÚjoinÚsortedÚkeysr\ÚencodeÚsetÚitemsÚ splitlinesÚ startswithrDÚsubÚaddr Zget_installed_packagesÚ intersectionr_rc) r&r[Z pkgs_cfgdZ_keyZcontentÚlinerbZpkgs_installedZ need_reconfigr"rgr#r1Øs(          r1cCs6t tjdd�¡}t d|¡|D]}t |¡q"dS)z%clean out any local cloud-init configz/etc/cloud/cloud.cfg.d/*dpkg*©Úpathz#cleaning cloud-init config from: %sN)Úglobr Ú target_pathr@rAÚosÚunlink)ÚflistZdpkg_cfgr"r"r#Úclean_cloud_initûs rcCsL|}| d¡r|dd…}| d¡}|dkr<||dd…}| dd¡}|S)zæmirrorurl_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Ú_)rZÚfindÚreplace)ÚmirrorÚstringÚposr"r"r#Úmirrorurl_to_apt_fileprefixs    r‰c CsÚt|ƒ}t t¡}| ¡D]º\}}| |¡}|s2q|tjjt |ƒ}|tjjt |ƒ}||krdqt |ƒ} t   d|¡D]X} d|| | d…f} t   d| | ¡zt | | ¡WqztyÐt jddd�Yqz0qzqdS)z>rename_apt_lists - rename apt lists to preserve old cache dataz%s_*z%s%sNzRenaming apt list %s to %szFailed to rename apt list:T)Úexc_info)r$r r{Ú APT_LISTSrqr,r|ryÚsepr‰r_rzr@rAÚrenamerPr`) Z new_mirrorsr!Zdefault_mirrorsZprer%ZomirrorZnmirrorZoprefixZnprefixZolenÚfilenameZnewnamer"r"r#rKs$   rKcCs8ddddddœ}z ||}Wnty2|}Yn0|S)zÉthere 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)ZupdatesZ backportsÚsecurityZproposedrT)ÚKeyError)ÚsuiteÚmappingZretsuiter"r"r#Úmap_known_suites/sû   r“)Ú deb822_entryr)cCs<t d|¡s8t dd|¡}t t›d|¡}dt|dƒS|S)z0If no active Suites, disable this deb822 source.z\nSuites:[ \t]+([\w-]+)z \nSuites:.*rkz7## Entry disabled by cloud-init, due to disable_suites z# disabled by cloud-init: )rDÚfindallrtÚDISABLE_SUITES_REDACT_PREFIXr)r”r"r"r#Ú%disable_deb822_section_without_suitesAs ÿÿÿr—)r)c s$g}‡fdd„|Dƒ‰t d|ˆ¡d}| ¡D]Ô}| d¡r^|rR||›d�7}q0| |¡q0|rj| ¡rŒ|r€| t|ƒ¡d}| |¡q0|}| d¡s¨||d7}q0ˆrø| ¡dd …}‡fd d„|Dƒ}||krø|t›|›d�7}d d   |¡›�}||d7}q0|�r| t|ƒ¡d  |¡S) z:reads the deb822 format config and comment disabled suitescs g|]}t t|ƒdˆi¡‘qS)r<)r Ú render_stringr“©rer‘)rTr"r#rhTsÿz)disable_suites_deb822..zDisabling suites %s as %srkrjrdzSuites:éNcsg|]}|ˆvr|‘qSr"r"r™)Údisabled_suite_namesr"r#rhrsþzSuites: ú ) r@rArrrsr^Úisspacer—Úsplitr–rl) ÚdisabledÚsrcrTZnew_srcZnew_deb822_entryrwZnew_lineZ orig_suitesZ new_suitesr")r›rTr#Údisable_suites_deb822QsH þ    ÿ    þr¡c Csê|s|S|}t|ƒr t|||ƒS|D]À}t|ƒ}t |d|i¡}t d||¡d}| d¡D]‚}| d¡rt||7}q\|  ¡}t |ƒdkrÖd} |d d¡rÂ|dd …D]} | d7} |   d ¡r¦qÂq¦|| |krÖd |}||7}q\|}q$|S) zRreads the config for suites to be disabled and removes those from the templater<zDisabling suite %s as %srkTrjršéú[Nú]z"# suite disabled by cloud-init: %s) Úis_deb822_sources_formatr¡r“r r˜r@rArrrsržr_rZ) rŸr rTZretsrcr‘Z releasesuiteZnewsrcrwZcolsZpcolÚcolr"r"r#Údisable_suites€s6      r§cCs0dD]&}| |g¡D]}t||||d�qqdS)z=Adds any keys included in the primary/security mirror clauses©Úprimaryr�)Ú file_nameN)r,Ú add_apt_key)r&r'rrfr†r"r"r#rI¨srI)Úapt_src_contentr)cCs6t d|tj¡rdSt d|tj¡r(dSt d¡dS)a?Simple check for deb822 format for apt source content Only validates that minimal required keys are present in the file, which indicates we are likely deb822 format. Doesn't handle if multiple sections all contain deb822 keys. Return True if content looks like it is deb822 formatted APT source. z^(deb |deb-src )Fz'^(Types: |Suites: |Components: |URIs: )Tzapt.sources_list value does not match either deb822 source keys or deb/deb-src list keys. Assuming APT deb/deb-src list format.)rDr•ÚMr@r`)r¬r"r"r#r¥¯s ÿÿr¥zetc/aptú sources.listzsources.list.d)úDir::EtcúDir::Etc::sourcelistúDir::Etc::sourcepartsz@(Dir::Etc|Dir::Etc::sourceparts|Dir::Etc::sourcelist) \"([^\"]+)c Cs4zJddl}| ¡|j dtd¡}|j dtd¡}|j dtd¡}WnÄt�yzt ddg¡\}}WnTtjyÄtd}td}td}d|›d|›�d|›d|›d�d œYYS0t  t |¡}t |ƒ}| dtd¡}| dtd¡}| dtd¡}Yn0d|›d|›�d|›d|›d�d œS) aReturn a dict of applicable apt configuration or defaults. Prefer python apt_pkg if present. Fallback to apt-config dump command if present out output parsed Fallback to DEFAULT_APT_CFG if apt-config command absent or output unparsable. rNr¯r°r±z apt-configÚdumpr€)Ú sourcelistÚ sourceparts) Úapt_pkgZ init_configZconfigr,ÚDEFAULT_APT_CFGÚ ImportErrorr ÚProcessExecutionErrorrDr•Ú APT_CFG_REr.)rµÚetcr³r´Zapt_dumprƒZ matched_cfgZapt_cmd_configr"r"r#Ú get_apt_cfgÓs@ÿÿþ ÿÿ þr»cCsªtƒ}|d}|d›|jj›d�}tjr0|}n|}||dœ}|D] } || || <|| ||  ¡<qB| dd¡} | sÐt d¡tjrˆdnd } |  d |jj›| ›�¡} | s²|  d ¡} | sÆt  d |¡dSt   | ¡} t  | |¡} | �rt| ƒ�r||k�rt d |¡|}nt d|¡|}t| d¡| |ƒ}t j||dd�||k�r¦tj |¡�r¦t |jj¡}|�r�|t   |¡k�r¦t d|¡t  |t¡nt d|¡t  |¡dS)zŽgenerate_sources_list create a source.list file based on a custom or default template by replacing mirrors and release in the templater³r´z.sources)r<r8Ú sources_listNz1No custom template provided, fall back to builtinz.deb822rkz sources.list.r®z#No template found, not rendering %szAProvided 'sources_list' user-data is deb822 format, writing to %szFProvided 'sources_list' user-data is not deb822 format, fallback to %sr§i¤)Úmodez*Replacing %s to favor deb822 source formatz)Removing %s to favor deb822 source format)r»Údistror%rZAPT_DEB822_SOURCE_LIST_FILEÚlowerr,r@ÚinfoZget_template_filenamer`r Zload_text_filer r˜r¥rAr§Ú write_filer|ryÚexistsÚDEB822_ALLOWED_APT_SOURCES_LISTÚUBUNTU_DEFAULT_APT_SOURCES_LISTÚdel_file)r&rTrUr'r3Zapt_sources_listZapt_sources_deb822Z aptsrc_filerVÚkZtmplZtmpl_fmtZ template_fnZrenderedrŸZexpected_contentr"r"r#rJsp    ÿ      ýýÿþÿÿrJFcCsRt d|¡z t |¡j}td||||d�WStjyLt d¡‚Yn0dS)zM actual adding of a key as defined in key argument to the system zAdding key: '%s'ru)Ú output_filerYÚhardenedz(failed to add apt GPG Key to apt keyringN) r@rAÚpathlibÚPathÚstemÚapt_keyr r¸rQ)rfrªrrÈr%r"r"r#Úadd_apt_key_rawLs   ÿ rÍc CsÜg}tƒ}t | dd¡¡rVdD]4}| |¡r ||D]}ddh |¡r6| d¡q6q | di¡}| ¡D]6}ddh |¡r†| d¡|| dd ¡ƒrj| d ¡qj|D]} t | ¡s¦|  t | ¡q¦|rØ|j   t |ƒ¡d S) aÌInstall missing package dependencies based on apt_sources config. Inspect the cloud config user-data provided. When user-data indicates conditions where add_apt_key or add-apt-repository will be called, ensure the required command dependencies are present installed. Perform this inspection upfront because it is very expensive to call distro.install_packages due to a preliminary 'apt update' called before package installation. r:Fr¨rfÚkeyidrr;ÚsourcerkrN)rpr rHr,rvruÚvaluesÚshutilr6r^rr¾Zinstall_packagesrm) r&r?r'Zmissing_packagesZ required_cmdsZ mirror_keyZ mirror_itemZapt_sources_dictÚentÚcommandr"r"r#rG\s&        rGcCs`d|vr8d|vr8t}d|vr$|d}| |d|¡|d<d|vr\t|d|pR|d||d�SdS)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 rÎrfÚ keyserverrŽ©rÈN)ÚDEFAULT_KEYSERVERZ getkeybyidrÍ)rÒr'rrÈrªrÔr"r"r#r«~sÿr«c CsÒ|dur i}|durtdƒ‚t|tƒs2td|ƒ‚|D�]†}||}t d|¡d|vr`||d<d|vrŽd|dvrŽt|||dd �}||d <n t|||ƒd|vr¤q6|d}t ||¡}|d  d ¡sÜt j   d |d¡|d<|d  d ¡sú|dd 7<||ƒ�r>zt dd|g¡Wq6tj�y:t d¡‚Yq60q6tj|dd�} z8d|} d} d|v�rt|d�std} tj| | | d�Wq6t�y¼} zt d| | ¡‚WYd} ~ q6d} ~ 00q6|jjdd�dS)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 matcherzunknown apt format: %szadding source/key '%s'rŽrÏz $KEY_FILETrÕZKEY_FILEr€z/etc/apt/sources.list.d/z.listrz --no-updatezadd-apt-repository failed.rxz%s Úar^Úw)Úomodezfailed write to file %s: %s)Úforce)rr-r.Ú TypeErrorr@rAr«r r˜rsr|ryrlrZr r¸rQr{r rÁrOr¾Zupdate_package_sources) Úsrcdictr'rr>r?rŽrÒÚkey_filerÏZsourcefnÚcontentsrÙZdetailr"r"r#rR‘s\       ÿ ÿ rRcCs~i}tjdddd�t|tƒrbt d¡|D]2}d|vrNd|d<t |d¡}n|d}|||<q,nt|tƒrr|}nt dƒ‚|S) z1convert v1 apt format to v2 (dict in apt_sources)zConfig key 'apt_sources'ú22.1zUse 'apt' instead)Ú deprecatedÚdeprecated_versionZ extra_messagez9apt config: convert V1 to V2 format (source list to dict)rŽzcloud_config_sources.listzunknown apt_sources format) rÚ deprecater-rar@rAr Z rand_dict_keyr.r)ZsrclistrÜZsrcentrfr"r"r#Úconvert_v1_to_v2_apt_formatés$ý    rãcCs,| |d¡dur(| |¡||<||=dSdS)ziconvert an old key to the new one if the old one exists returns true if a key was found and convertedNTF©r,)ÚoldcfgÚaptcfgÚoldkeyÚnewkeyr"r"r#Ú convert_keys récCsHgd¢}d}ddgi}|D]\}}t||||ƒrd}q|rD|g|d<dS)zBconvert old apt_mirror keys into the new more advanced mirror spec))Ú apt_mirrorÚuri)Úapt_mirror_searchrF)Úapt_mirror_search_dnsÚ search_dnsFÚarchesÚdefaultTr©N)ré)råræZkeymapZ convertedZnewmcfgrçrèr"r"r#Úconvert_mirrors  rñc CsZddddddddddd d œ }g}|D]*}||vr$||d vrD||=q$| |¡q$|sX|Stjd |›�d d�| dd¡}|durîtjdd d�|D]V}||}||}||=|dus’| |d¡durÆq’|||kr’td||||fƒ‚q’|Si}|D]"}||duröt|||||ƒqöt||ƒ|D]$}| |d¡du�r(td|ƒ‚�q(||d<|S)z:convert old to new keys and adapt restructured mirror specr;NÚproxyÚ http_proxyÚ https_proxyÚ ftp_proxyr:r¼r9) Ú apt_sourcesrêrìríZ apt_proxyZapt_http_proxyZ apt_ftp_proxyZapt_https_proxyZapt_preserve_sources_listZapt_custom_sources_listr9)NrkzThe following config key(s): rß)ràrár*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^rrâr,rrérñ)råZ mapoldkeysZ needtoconvertrçZ newaptcfgrèZverifyrær"r"r#Úconvert_v2_to_v3_apt_format!sjõ   þ þ  þÿ  r÷cCs,| dd¡}|dur t|ƒ|d<t|ƒ}|S)z‰convert 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)r,rãr÷)r&rör"r"r#r+ks   r+c Cs¸d}|r´d}g}|dkrd}n|dkr,d}ntdƒ‚t ||¡j}d | d¡d d…¡}|rl| d |¡| d ¡g} |jj } d | |d | f} |D]} |  | | ¡q–t  | ¡}|S)zG Try to resolve a list of predefines DNS names to pick mirrors Nrkr©r†r�zsecurity-mirrorzunknown mirror typeÚ.ršz.%s)z .localdomainrkzhttp://%s-%s%s/%sz%s) rr Zget_hostname_fqdnÚfqdnrlržr^Úextendr¾r%Úsearch_for_mirror) Z configuredÚ mirrortyper&r'r†ZmydomZdomsZ mirrordnsrùZ mirror_listr¾Z mirrorfmtZpostr"r"r#Úsearch_for_mirror_dnszs.ÿ rýcCsX|dur|dur|}||dœS|j ¡}|rP| ¡}|d|d<|d|d<|St|ƒS)z^sets security mirror to primary if not defined. returns defaults if no mirrors are definedNrr©rr�r)Z datasourceZget_package_mirror_inforr$)ÚpmirrorÚsmirrorr!r'Ú mirror_infoÚmr"r"r#Úupdate_mirror_info£s    rcCsT| |d¡}|durdSd}|D].}| d¡p0g}||vrB|Sd|vr |}q |S)zuout of a list of potential mirror configurations select and return the one matching the architecture (or default)Nrïrðrä)r&rür!Zmirror_cfg_listrðZmirror_cfg_elemrïr"r"r#Úget_arch_mirrorconfig»s rcCs`t|||ƒ}|durdS| dd¡}|dur>t | dd¡¡}|dur\t| dd¡|||ƒ}|S)z’pass the three potential stages of mirror specification returns None is neither of them found anything otherwise the first hit is returnedNrërFrî)rr,r rûrý)r&rür!r'Zmcfgr†r"r"r#Ú get_mirrorÎs  ÿrcCsn|durt ¡}t d|¡t|d||ƒ}t d|¡t|d||ƒ}t d|¡t||||ƒ}|d|d<|S) afind_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©zgot primary mirror: %sr�zgot security mirror: %srr=)r rr@rArr)r&r'r!rþrÿrr"r"r#rBès    rBcs¶d}‡fdd„|Dƒ}t|ƒrBt d|¡t |d |¡d¡n"tj |¡rdt  |¡t d|¡ˆ  dd¡r�t d |¡t |ˆ  d¡¡n"tj |¡r²t  |¡t d |¡dS) zHapply_apt_config Applies any apt*proxy config from if specified ))ròúAcquire::http::Proxy "%s";)rór)rõzAcquire::ftp::Proxy "%s";)rôzAcquire::https::Proxy "%s";cs(g|] \}}ˆ |¡r|ˆ |¡‘qSr"rä)rer%Úfmt©r&r"r#rh riz$apply_apt_config..zwrite apt proxy info to %srdz#no apt proxy configured, removed %sZconfNzwrite apt config info to %sz$no apt config configured, removed %s) r_r@rAr rÁrlr|ryÚisfilerÅr,)r&Z proxy_fnameZ config_fnameZcfgsZproxiesr"rr#rLs        rLTcsZdd„‰‡‡‡fdd„}‡‡fdd„}|dkr6||ƒS|dksF|d krN||ƒStd ƒ‚d S) adapt-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) cSsJtj t¡rtgng}t t¡D]}| d¡r | t|¡q |rF|SdS)zÎreturn 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.ascrk)r|ryrÚAPT_LOCAL_KEYSÚlistdirÚAPT_TRUSTED_GPG_DIRrZr^)Z key_filesÚfiler"r"r#Ú_get_key_files/s  zapt_key.._get_key_filesc sœd}ˆst td ˆ¡¡n|z2ˆr&tnt}| ˆ¡}d |ˆ¡}t ||¡WnHtj ytt td ˆ¡¡Yn$t y–t td ˆ¡¡Yn0|S)ziapt-key add 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 Zlogexcr@r/ÚCLOUD_INIT_GPG_DIRr ZdearmorrÁr r¸ÚUnicodeDecodeError)r4rªZkey_dirÚstdout)rYrÈrÇr"r#Ú apt_key_add>s( ÿ ÿ   ÿ  ÿ zapt_key..apt_key_addc shg}ˆƒD]R}z| |j|ˆd�¡Wq tjyZ}zt d||¡WYd}~q d}~00q d |¡S)zapt-key list returns string of all trusted keys (in /etc/apt/trusted.gpg and /etc/apt/trusted.gpg.d/) )Ú human_outputzFailed to list key "%s": %sNrd)r^Z list_keysr r¸r@r`rl)r4Zkey_listrÝÚerror)r rr"r#Ú apt_key_listZs  ÿ&zapt_key..apt_key_listruZfingerraz@apt_key() commands add, list, and finger are currently supportedN)r)rÓrrÇrYrÈrrrr")r rYrÈrrÇr#rÌsÿrÌz cloud-init)N)F)FN)NN)N)NNFT)[Ú__doc__rzZloggingr|rÉrDrÑÚtextwraprÚtypingrrrrZ cloudinitrrr r r Zcloudinit.cloudr Zcloudinit.configr Zcloudinit.config.schemarZ cloudinit.gpgrZcloudinit.settingsrZ getLoggerÚ__name__r@rCr r rr–rÚstrÚ__annotations__rr‹rNrMrÖrrrrrÄrÃr$rar5r7r2r\rcr1rr‰rKr“r—r¡r§rIÚboolr¥r¶r¹r»rJrÍrGr«rRrãrérñr÷r+rýrrrrBrLrÌr]r"r"r"r#Ú s´       þü þþ ÿ  .  # /(ýÿ3F " ÿ X J) ú Yÿ