a >h3r@sddlZddlZddlZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZz ddlZWneyYn0dZdZdZd ZGd d d ZGd d d eZGdddeZdS)N)datetime)Lock) find_spec)sos_get_command_outputfilelinkZnodedirc@seZdZdZeddZedZdZ dZ e Z ddZ d d Zd d Zd dZddZddZddZd-ddZd.ddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,ZdS)/Archivez!Abstract base class for archives.cCs|jS)z6Returns the archive class's name as a string. )__name__)clsr //usr/lib/python3.9/site-packages/sos/archive.py archive_type+szArchive.archive_typeZsosZunsetFcCsd|d|S)Nz [archive:z] )rselfmsgr r r _format_msg8szArchive._format_msgcCs ||_dSN)_debug)rdebugr r r set_debug;szArchive.set_debugcCs|j||dSr)logerrorrrr r r log_error>szArchive.log_errorcCs|j||dSr)rZwarningrrr r r log_warnAszArchive.log_warncCs|j||dSr)rinforrr r r log_infoDszArchive.log_infocCs |js dS|j||dSr)rrrrrr r r log_debugGszArchive.log_debugcCs|jSr)_namerr r r nameLsz Archive.nameNcCstdSrNotImplementedError)rsrcdestforcer r r add_fileRszArchive.add_filewcCstdSrr!)rcontentr$moder r r add_stringUszArchive.add_stringcCstdSrr!)rr(r$r r r add_binaryXszArchive.add_binarycCstdSrr!)rsource link_namer r r add_link[szArchive.add_linkcCstdSrr!rpathr r r add_dir^szArchive.add_dircCstdSrr!)rr0r)devicer r r add_nodeaszArchive.add_nodecCstdS)zReturn a temporary directory that clients of the archive may use to write content to. The content of the path is guaranteed to be included in the generated archive.Nr!rr r r get_tmp_dirdszArchive.get_tmp_dircCstdS)zReturn the maximum file name length this archive can support. This is the lesser of the name length limit of the archive format and any temporary file system based cache.Nr!rr r r name_maxjszArchive.name_maxcCstdS)aTReturn a string representing the path to the temporary archive. For archive classes that implement in-line handling this will be the archive file itself. Archives that use a directory based cache prior to packaging should return the path to the temporary directory where the report content is locatedNr!rr r r get_archive_pathpszArchive.get_archive_pathcCstdS)z:Clean up any temporary resources used by an Archive class.Nr!rr r r cleanupyszArchive.cleanupcCstdS)aFinalize an archive object via method. This may involve creating An archive that is subsequently compressed or simply closing an archive that supports in-line handling. If method is automatic then the following methods are tried in order: xz, gzipNr!rmethodr r r finalize}szArchive.finalize)NF)r')r __module__ __qualname____doc__ classmethodrloggingZ getLoggerrrrr _path_lockrrrrrrr r&r*r+r.r1r3r4r5r6r7r:r r r r r (s2     r c@seZdZdZdZdZdZd7ddZddZdd Z d8d d Z d9ddZ ddZ d:ddZ d;ddZddZddZddZddZdd Zd!d"Zd#d$ZdTest whether path ``path`` is inside the archive. rB)rXrFr0rM)r0rootr r in_archivesz8FileCacheArchive._make_leading_paths..in_archiverCr)rCrBz Making path r)zMaking symlink '' -> 'rEzMaking directory )rrNrXrFr0isdirrYsplitappendreverserMexistsislinkreadlink_make_leading_pathsnormpathrSrHsymlinkmkdir)rr#r)r$r\src_dirr0Z path_compsheadtailZabs_pathZsrc_pathcomptargetZ target_dirZ target_srcr rZr rfsR          z$FileCacheArchive._make_leading_pathsFc Cs\|p ||}|tkr|}ntj|d}|s4|Stj|r\tj|s\td|dtj|s|tkrt|ntj|d}||dd}|r|Stj|rXt |}d} |t krt |j st| |df|tkrt |j st| |df|tkr,||j s,t| |d f|tkrTt |j sTt| |d fd S|S) a4Check a new destination path in the archive. Since it is possible for multiple plugins to collect the same paths, and since plugins can now run concurrently, it is possible for two threads to race in archive methods: historically the archive class only needed to test for the actual presence of a path, since it was impossible for another `Archive` client to enter the class while another method invocation was being dispatched. Deal with this by implementing a locking scheme for operations that modify the path structure of the archive, and by testing explicitly for conflicts with any existing content at the specified destination path. It is not an error to attempt to create a path that already exists in the archive so long as the type of the object to be added matches the type of object already found at the path. It is an error to attempt to re-create an existing path with a different path type (for example, creating a symbolic link at a path already occupied by a regular file). :param src: the source path to be copied to the archive :param path_type: the type of object to be copied :param dest: an optional destination path :param force: force file creation even if the path exists :returns: An absolute destination path if the path should be copied now or `None` otherwise rzpath 'z' exists and is not a directorycSs(tt|t|t|t|gSr)anystatS_ISBLKS_ISCHRS_ISFIFOS_ISSOCKr]r r r is_special7s z/FileCacheArchive.check_path..is_specialz path '%s' exists and is not a %sz regular filez symbolic linkz special fileZ directoryN)rVP_DIRrFr0r`rcr_ ValueErrorrflstatP_FILErpS_ISREGst_modeP_LINKS_ISLNKP_NODES_ISDIR) rr# path_typer$r%dest_dirrjrustZve_msgr r r check_paths6   zFileCacheArchive.check_pathc Cszdt|}|ds |drDt||tj||j|jfdn t||t ||j |j Wn<t y}z$| d|d|dWYd}~n d}~00dS)N/sys//proc/)nszcaught 'z' setting attributes of 'rE)rFrprXshutilcopymodeutime st_atime_ns st_mtime_nscopystatchownst_uidst_gid Exceptionr)rr#r$_stater r r _copy_attributesSs   z!FileCacheArchive._copy_attributesc CsP|j2|s|}|j|t|d}|s6WddSt|ddszt||WnRty}z:|ds|drxn|d|d|dWYd}~n d}~00| ||d|d}nR| dt |d d d $}|D]}| |qWdn1s0Yd }| d |d|jdWdn1sB0YdS)Nr%readrrzFile z not collected: 'rErr'utf-8encodingz open filezadded z to FileCacheArchive ')r@rrygetattrrcopyOSErrorrXrrseekopenwriterrN)rr#r$r%r file_namefliner r r r&`s.  .  , zFileCacheArchive.add_filer'c Cs|j|}|j|tdd}tj||ddb}t|trD|dd}||t j |rf| ||| d|d|jd Wdn1s0YWdn1s0YdS) NTrrrutf8ignorezadded string at 'z' to FileCacheArchive 'rE)r@rrycodecsr isinstancebytesdecoderrFr0rcrrrN)rr(r$r)r#rr r r r*s      zFileCacheArchive.add_stringc Cs|j||t}|s(WddStj|ddd}||Wdn1sX0Y|d|d|jdWdn1s0YdS)Nwbrzadded binary content at 'z' to archive 'rE)r@rryrrrrrN)rr(r$rr r r r+s ( zFileCacheArchive.add_binaryc Cs|d|d|d|jh||t}|s@WddStj|sxt|||d|d|d|jdWdn1s0Y|d|d|d |tj |}tj tj ||}| |}d d }tj |stj|r|}tj |}tj |t|}tj||}|||r\|d |d |ddS|d|d|d|||nntj|r|d|d||nBtj|r|d|d||n|d|d|dS)Nzadding symlink at 'r^rEzadded symlink at 'z' to 'z' in archive 'zLink follow up: source=z link_name=z dest=c Sstj|}tj|s.tjtj||}tj|}||krFdSzt|Wn>ty}z&|jdkr|WYd}~dSWYd}~n d}~00dS)zReturn ``True`` if the symbolic link ``link_name`` is part of a file system loop, or ``False`` otherwise. T(NF) rFr0dirnamerSrealpathrMrprerrno)r-r,Zlink_dirrr r r is_loops    z*FileCacheArchive.add_link..is_loopzLink 'z' - 'z' loops: skipping...z Adding link z -> z for link follow upz Adding dir z Adding file zNo link follow up: source=)rr@rr|rFr0lexistsrhrNrrrMrVrcrdrerHr.r_r1isfiler&) rr,r-r$Z source_dirZhost_path_nameZdest_path_namerrr r r r.sJ   (       zFileCacheArchive.add_linkcCs6|j||tWdn1s(0YdS)zmCreate a directory in the archive. :param path: the path in the host file system to add N)r@rrvr/r r r r1szFileCacheArchive.add_dirc Cs||t}|sdStj|szt|||Wn^ty}zF|jtjkrxd}| d|d|dWYd}~dS|WYd}~n d}~00| ||dS)NzOperation not permittedz add_node: z - mknod 'rE) rr~rFr0rcmknodrrEPERMrr)rr0r)r2r$rrr r r r3s   zFileCacheArchive.add_nodecCs&dtjvr"tjd}t|j|SdS)N PC_NAME_MAX)rFpathconf_namespathconfrN)rZ pc_name_maxr r r r5s  zFileCacheArchive.name_maxcCs|jSrrNrr r r r4 szFileCacheArchive.get_tmp_dircCs|jSrrrr r r r6 sz!FileCacheArchive.get_archive_pathcCs8tjtj|j||d|d|d|jddS)zsCreate path, including leading components. Used by sos.sosreport to set up sos_* directories. r]zcreated directory at 'z' in FileCacheArchive 'rEN)rFrOr0rMrNr)rr0r)r r r rOs zFileCacheArchive.makedirscCs||}tj|ddddS)Nrrr)rerrors)rVrrr/r r r open_files zFileCacheArchive.open_filecCstj|jrt|jdSr)rFr0r_rNrrmtreerr r r r7szFileCacheArchive.cleanupcCsft}|jj}||}|jd||jd||jd|||jjddtj dddS) zAdds component-agnostic data to the manifest so that individual SoSComponents do not need to redundantly add these manually Zend_timerun_time compression)indent sos_reportsz manifest.jsonN) rZnowrLZ start_timeZ add_fieldr*Zget_jsonrFr0rM)rr9endstartrr r r add_final_manifest_data s z(FileCacheArchive.add_final_manifest_datacCsN||j|_tj|j|j}t|j|||_tj|j||_ dS)zeRename the archive to an obfuscated version using an initialized SoSCleaner instance N) Zobfuscate_stringrrFr0rMrIrenamerNr _archive_name)rZcleanerZ _new_rootr r r rename_archive_root-s z$FileCacheArchive.rename_archive_rootc CstjtjB}t|dr(|j}|j|B}n|}|}d}||}|}Wdn1s\0Yt|t s|| dd}tj ||||d\} } | r| | |nd} | S)aApply a regexp substitution to a file in the archive. :param path: Path in the archive where the file can be found :type path: ``str`` :param regexp: A regex to match the contents of the file :type regexp: ``str`` or compiled ``re`` object :param subst: The substitution string to be used to replace matches within the file :type subst: ``str`` :returns: Number of replacements made :rtype: ``int`` patternrBNrr)flagsr) re IGNORECASE MULTILINEhasattrrrrrrstrrsubnr*) rr0ZregexpsubstZ common_flagsrrr(readableresultZ replacementsr r r do_file_sub7s$    &    zFileCacheArchive.do_file_subc Cs|d|jd|dz||}Wn<tyd}z$|d||WYd}~Sd}~00||d|jdt |jj d|j drz | |WSty}z(d }||d ||WYd}~Sd}~00n|SdS) Nzfinalizing archive 'z' using method 'rEz+An error occurred compressing the archive: zbuilt archive at 'z' (size=)Zencryptz)An error occurred encrypting the archive: ) rrN_build_archiverrr r7rrFrpst_sizerJ_encrypt)rr9reserrrZexp_msgr r r r:\s(    zFileCacheArchive.finalizecCs|dd}|d7}d|d}d}|jdrL|d|jdd7}||7}|jd r|jd d d }d |i}|d 7}d|d}||7}t|d|dd}|ddkr|S|ddkr|jdrd}qd}nd|dd|d}t|dS)aEncrypts the compressed archive using GPG. If encryption fails for any reason, it should be logged by sos but not cause execution to stop. The assumption is that the unencrypted archive would still be of use to the user, and/or that the end user has another means of securing the archive. Returns the name of the encrypted archive, or raises an exception to signal that encryption failed and the unencrypted archive name should be used. z sosreport-zsecured-sosreport-z.gpgzgpg --batch -o rNkeyz--trust-model always -e -r passwordz'"rBZsos_gpgz-c --passphrase-fd 0 z/bin/bash -c "echo $sos_gpg | "rT)timeoutenvstderrstatuszSpecified key not in keyringzCould not read passphrasezgpg exited with code z and error output)replacerJrr)rarchiveZarc_nameZenc_cmdrpasswdrrr r r rss,        zFileCacheArchive._encryptcCs|Sr)r r8r r r rszFileCacheArchive._build_archive)N)rD)NF)NF)r')rD)r r;r<r=rIrNrrRrVrYrfrrr&r*r+r.r1r3r5r4r6rOrr7rrrr:rrr r r r rAs:  ] K $  G    %)rAcsTeZdZdZdZdZdfdd ZdddZdd Zd d Z d d Z ddZ Z S)TarFileArchivez: archive class using python TarFile to create tar archivesNFc s6t|||||||d|_tj|||_dS)Ntar)superrR_suffixrFr0rMr rrP __class__r r rRszTarFileArchive.__init__cCsP|j|_|jd|jd<|jd|jd<|r4||_n|j|_|j|_|j |_ dS)Nz.9fZatimectime) st_mtimemtimest_atime pax_headersst_ctimer)r{ruidrgid)rZtar_infofstatr)r r r set_tarinfo_from_statsz$TarFileArchive.set_tarinfo_from_statcs|jttj|jdds*|jgd}tfdd|DrLdSzt}Wntyp|YS0|j r| }|r||j d<| |||S)N)z /version.txt$z/sos_logs(/.*)?z/sos_reports(/.*)?c3s|]}t|VqdSr)rmatch).0skip orig_pathr r z9TarFileArchive.copy_permissions_filter..zRHT.security.selinux) r lenrFr0r`rNrorpr_with_selinux_contextget_selinux_contextrr)rtarinfoZskipsrcontextr rr copy_permissions_filters       z&TarFileArchive.copy_permissions_filtercCs.zt|\}}|WSty(YdS0dSr)selinuxZ getfileconr)rr0_cr r r rs  z"TarFileArchive.get_selinux_contextcCs|jd|jS)N.)rNrrr r r r szTarFileArchive.namecCsd}|dkr tddurdnd}|durb|d}|jd||_|jd|7_d|}id d id d id }tj|jfd|i||n}dD]B}tjtj |j |r|j tj |j ||j d|dq|j |j |j |j dWdn1s0Y|S)Nr'autolzmaxzgzipiprzw: compresslevelpreset)Nr r r))z version.txtrZsos_logsrC)arcname)rfilter)rstriprrtarfilerrFr0rcrMrNaddrrr )rr9_modeZ _comp_modekwargsrZ_contentr r r rs8    &zTarFileArchive._build_archive)N)N) r r;r<r=r9rrRrrrr r __classcell__r r rr rs r)rFrrr?rrrprr threadingrimportlib.utilrZ sos.utilitiesrr ImportErrorryr|r~rvr rArr r r r  s4      ]