a G%@id @sddlZddlZddlZddlZddlmZmZmZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlmZddlmZzddlmZWneyddlmZYn0edZdZzddlZee d ZWnDee!fy8dd l"m#Z#d Z$e%d e#e$d ddd Yn0dZ&gdZ'ddZ(dTddZ)ddZ*dUddZ+ddZ,ddZ-ddZ.dVd d!Z/d"d#Z0dWd$d%Z1e2d&d'd(Z3e&dddddddddddf d)d*Z4dXd+d,Z5dYd-d.Z6dZd0d1Z7d[d3d4Z8ej9fd5d6Z:d7d8Z;d9d:ZZ>d?d@Z?ej@dAdBdCZAdDdEZBgfdFdGZCGdHdIdIZDGdJdKdKejEZFGdLdMdMejEZGGdNdOdOZHGdPdQdQZIGdRdSdSeJZKdS)\N)PopenPIPESTDOUT)closing)deque)parse) parse_versionZsosFT)fillzWARNING: Failed to load 'magic' module version >= 0.4.20 which sos aims to use for detecting binary files. A less effective method will be used. It is recommended to install proper python3-magic package with the module.  H)Zreplace_whitespacei,)TIMEOUT_DEFAULTImporterHelperSoSTimeoutError TempFileUtilboldfile_is_binaryfileobjfindget_human_readablegrep import_module is_executablelistdirr path_exists path_isdir path_isfile path_islink path_joinrecursive_dict_values_by_key shell_outsos_get_command_outputtac_logstailc Cstd}zF|j|dd\}}}|s*|WStdd|d}|d|}|WSty}z&td|d ||WYd }~Sd }~00d S) z< Convert the version into a PEP440 compliant version scheme.z2^([0-9][0-9.]*(?:(?:a|b|rc|.post|.dev)[0-9]+)*)\+?)maxsplitz[+~]+.-+zUnable to format z to pep440 format: N)recompilesplitsubstrip Exceptionlogdebug)verZpublic_version_re_ZpubliclocalZsanitized_localZpep440_versionerrr41/usr/lib/python3.9/site-packages/sos/utilities.pyformat_version_to_pep440Psr6cCs|rt|}t|St|S)z6 Converts the version to PEP440 format before parsing )r6r)r0Zpep440Z ver_pep440r4r4r5sos_parse_versionasr7cCsTt|d6}t|j|kr*|| d|WdS1sF0YdS)z,Returns the last number_of_bytes of filenamerbN)openosstatst_sizeseekread)filenameZnumber_of_bytesfr4r4r5r"js r"rcCsZt|trNzt||ddWStyJtd|dttYS0nt|SdS)z@Returns a file-like object that can be used as a context managerutf-8encodingz fileobj: z could not be openedN) isinstancestrr:IOErrorr.r/rioStringIO)Z path_or_filemoder4r4r5rrs  rcCsHddddd}|D]*\}}||krt||d|Sq|S)zCConverts a number of bytes to a shorter, more human friendly formatli@)TGMKz.1f)itemsfloat)Z num_bytesZsizessymbolsizer4r4r5 convert_bytes~s rVcCs|dddvrt|dddP}|}td|rDWddStd |r`Wdd SWdn1st0YdSdS) aHelper to determine if a given file is a certificate or not. This is especially helpful for `sos clean`, which cannot obfuscate certificate files content and instead, by default, will keep them as is. :param fname: The full path of the file to check :type fname: ``str`` :returns: The type of the certificate or ``None`` :rtype: ``string`` or ``None`` N)z.csrz.crtz.pemrBrCrDz-----BEGIN CERTIFICATE-----Z certificatez"-----BEGIN [A-Z]+ PRIVATE KEY-----Zcertificatekey)r:r?r(search)fnamerAZcontentr4r4r5file_is_certificates   .rZc strNz6t|ddg}jdko8tfdd|D WStyLYn0t|dddN}z|d WWd d StyYWd d S0Wd n1s0Yd S) azHelper to determine if a given file contains binary content or not. This is especially helpful for `sos clean`, which cannot obfuscate binary data and instead, by default, will remove binary files. :param fname: The full path of the file to check binaryness of :type fname: ``str`` :returns: True if binary, else False :rtype: ``bool`` ztext/zinode/binaryc3s|]}j|VqdSN)Z mime_type startswith).0Z_mtZ_ftupr4r5 z!file_is_binary..trrCrDr#NFT) magic_modmagicdetect_from_filenamerEanyr-r:r?UnicodeDecodeError)rYZ_mimesZtfiler4r_r5rs      rc cs|r"tj|tjj}||7}t|D]^\}}}|rV|tjj|krV|dd=|rht||shq,t||D]}tj||Vqtq,dS)zGenerator function to find files recursively. Usage:: for filename in find("*.properties", "/var/log/foobar"): print filename N) r;pathdirnamecountsepwalkfnmatchfilterjoin) Z file_patternZtop_dirZ max_depth path_patternZ base_depthrhdirlistZfilelistnamer4r4r5rs rc sRg}|D]D}t|(}|fdd|DWdq1sB0Yq|S)zReturns lines matched in fnames, where fnames can either be pathnames to files to grep through or open file objects to grep through line by linec3s|]}t|r|VqdSr\)r(match)r^linepatternr4r5r`razgrep..N)rextend)rvZfiles_or_pathsmatchesZfopfor4rur5rs  8rcs\tjddtjj}gfdd|D}rJ|fdd|D7}tdd|DS)z6Returns if a command matches an executable on the PATHPATHcsg|]}tj|qSr4)r;rhro)r^p)commandr4r5 raz!is_executable..cs g|]}tj|dqS)/)r;rhrolstrip)r^csysrootr4r5r~scss|]}t|tjVqdSr\)r;accessX_OK)r^rhr4r4r5r`raz is_executable..)r;environgetr*rhpathseprf)r}rpathsZ candidatesr4)r}rr5rs r)urlcCsddlm}m}zd||}|js&|jrpd}|jr:||j7}|jrP|d|j7}||j||j|j |j |j fWS|WSt y|YS0dS)zK Replace username:password@ with ********@ in proxy URL if present r)urlparse urlunparsez ********@:N) urllib.parserrusernamepasswordhostnameportschemerhparamsqueryfragmentr-)rrrZ parsed_urlnetlocr4r4r5scrub_url_credentials      rc  s2fdd} fdd}rfzt}WntyLddddYS0||j|jdtj}d |d <|r|D]"\}}|r|||<q| |d q|rt d rd |rdndd|d|}t |}g}|D]L}| dr&d|vr&t|}|r||n ||q||q| rl|rDt}n&| r`tjtj| d}n t| d}nt}zz"t|d||rtntd|d| d}| r|r| rtjtj| d}n t| d}t|j|||}n t||}nt|j||}r|jr||qnz||r(|nd Wnty| | r| rt| d}t!||dWd n1s0Yd|_d|"|j#dYWd WWt$|dr|%S0|&d urq| r4| r4t| d*}t!|||j#p|j'dkWd n1s*0Y|j'dvrFd}n|"}|j'||j#dWd WWt$|dr|%S1s0YWnft(y}zL|j)t)j*krddddWYd }~Wt$|dr|%S|WYd }~n d }~00Wt$|dr.|%nt$|dr,|%0d S)zExecute a command and return a dictionary of status and output, optionally changing root or current working directory before executing command. csbrdkrtrPttjttjttj r^tdSNr) r;chrootsetgidpwdgetpwnampw_gidsetuidpw_uidchdirpw_dirr4)rrrunasr4r5_child_prep_fns  z.sos_get_command_output.._child_prep_fncs,s|dkr|ttddS)N|{Gz?)poll terminatertimesleep)proc)pollerr4r5 _check_pollersz-sos_get_command_output.._check_pollerr{)statusoutputZ truncated)HOMEZLOGNAMEZPWDZUSERzC.UTF-8LC_ALLNtimeoutztimeout z --foreground zs r*dirwbFT)shellstdoutstderrbufsizeenvZ close_fdsZ preexec_fnrcloser)~rra)+rrKeyErrorupdaterr;rcopyrRpoprshlexr*r]globrwappendrtempfileZ TemporaryFilerhrir:rr HeadReaderr FakeReader TailReaderrunningwaitr-rr! get_contentsis_fullhasattrrr returncodeOSErrorerrnoENOENT)r}rrrrrZ foregroundr[ sizelimitrZto_fileZtacrrrZpwd_userZcmd_envkeyvalueargsZ expanded_argsargZ expanded_argZ_outputr|readerf_dstrer4)rrrrr5r s                 ,   $     r c Csd}d}d}|t|jdkr,dStj|dtjd}|d}}|||krdd}|dkr||d|}||d|kr|d krdqqd|rd }n| ||d|d|}qdWdn1s0YdS) zPython implementation of the tac utility with support for multiline logs (starting with space). It is intended to reverse the output of 'journalctl --reverse'.  rN)rr#TrF) flushr;fstatfilenor=mmapZ ACCESS_READrUrfindwrite) f_srcrZ drop_last_logZ NEWLINE_BZ NEWLINE_IZSPACE_IZmmZsep1Zsep2r4r4r5r!s( r!c sdd}zttt|g}Wn@tyf}z(tdd|jj|WYd}~n d}~00fddt |tj D}rfdd|D}|S) aImports the module module_fqname and returns a list of defined classes from that module. If superclasses is defined then the classes returned will be subclasses of the specified superclass or superclasses. If superclasses is plural it must be a tuple of classes.r%rz"Error while trying to load module z: Ncsg|]\}}|jkr|qSr4) __module__)r^Zcnameclass_) module_fqnamer4r5r~s  z!import_module..csg|]}t|r|qSr4) issubclass)r^m) superclassesr4r5r~ra) rpartition __import__globalslocals ImportErrorprint __class____name__inspectZ getmembersZisclass)rrZ module_namemodulermodulesr4)rrr5rs   rcCst||||ddS)zeShell out to an external command and return the output or the empty string in case of error. )rrrr)r )cmdrrZrunatr4r4r5rs rr9cCsHgd}d}|dkr.|dkr.|d7}|d}q |d|d||S) N)BZKiBZMiBZGiBZTiBrrMr#g@r%rAr4)rUZ precisionsuffixesZ suffixindexr4r4r5rs  rcCs>|r,|tjkr,||s,tj||d}t||}||Sr)r;rkr]rhrorgetattr)rhrmethodrZ_methr4r4r5 _os_wrappers   rcCs$d|vrt||dtdSt||dS)Nrr)rexists)rrrhrr4r4r5rsrcCs t||dS)Nisdirrrr4r4r5rsrcCs t||dS)Nisfilerrr4r4r5rsrcCs t||dS)Nislinkrrr4r4r5rsrcCst||dtS)Nr)rr;rr4r4r5rsrrcGs8|r$||s$tj||tj}tjj|g|RSr\)r]r;rhrorrk)rhrr|r4r4r5rsrcCs d|dS)a"Helper to make text bold in console output, without pulling in dependencies to the project unneccessarily. :param text: The text to make bold :type text: ``str`` :returns: The text wrapped in the ASCII codes to display as bold :rtype: ``str`` zzr4)textr4r4r5r s rc sg}g||t|tr|D]~\}||rB||vrR|tq$ttr$z$|tfdd|DdWntyYn0q$n ||fdd|DS)a Recursively compile all elements of a potentially nested dict by a set of keys. If a given key is a dict within ``dobj``, then _all_ elements within that dict, regardless of child keys, will be returned. For example, if a Plugin searches the devices dict for the 'storage' key, then all storage devices under the that dict (e.g. block, fibre, etc...) will be returned. However, if the Plugin specifies 'block' via ``keys``, then only the block devices within the devices['storage'] dict will be returned. Any elements passed here that are _not_ keys within the dict or any nested dicts will also be returned. :param dobj: The 'top-level' dict to intially search by :type dobj: ``dict`` :param keys: Which keys to compile elements from within ``dobj``. If no keys are given, all nested elements are returned :param keys: ``list`` of ``str`` :returns: All elements within the dict and any nested dicts :rtype: ``list`` c3s|]}|vr|VqdSr\r4)r^r)vr4r5r`Asz/recursive_dict_values_by_key..rcsg|]}|vr|qSr4r4)r^d)_filtr4r5r~Mraz0recursive_dict_values_by_key..)rwrFdictrRrr IndexErrorkeys)Zdobjr Z_itemskr4)r rr5rs,        rc@s8eZdZdZddZeddZddZedd Zd S) rzUsed when we are writing directly to disk without sizelimits, this allows us to keep more simplified flows for executing, monitoring, and collecting command output. cCs||_||_dSr\)processr[)selfrr[r4r4r5__init__VszFakeReader.__init__cCsdS)NFr4rr4r4r5rZszFakeReader.is_fullcCs|js dSdSNr{rar[rr4r4r5r^szFakeReader.get_contentscCs|jduSr\)rrrr4r4r5raszFakeReader.runningN) rr __qualname____doc__rpropertyrrrr4r4r4r5rPs rcs@eZdZdZdZfddZddZddZed d Z Z S) rzzUsed to 'head' the command output (f_src) to a given size without deadlocking sos. Takes a sizelimit value in MB. rLcs8t||_||_|d|_||_d|_|dS)NrLT)superrrr remainingr[rstart)rrrrr[rr4r5rms  zHeadReader.__init__cCsZ|jdkrF|jt|j|j}|s&qF|j||jt|8_q|jd|_ dS)zReads from the f_src (Popen stdout pipe) until we reach sizelimit. once done, close f_src to signal the program that we are done. rFN) rrr?min COPY_BUFSIZErrlenrr)rbufr4r4r5runvs   zHeadReader.runcCs|js dSdSrrrr4r4r5rszHeadReader.get_contentscCs |jdkS)Nr)rrr4r4r5rszHeadReader.is_full) rrrrrrrrrr __classcell__r4r4rr5rfs  rcs<eZdZdZfddZddZddZedd ZZ S) rzUsed to tail the command output to a given size without deadlocking sos. Takes a sizelimit value in MB, and will compile stdout from Popen into a string that is limited to the given sizelimit. cs^t||_||_d|_d|_|r>|d}t||j|_t|jd|_d|_| dS)NirL)maxlenT) rrchanr[ chunksizeslotsintrrr)rZchannelrr[rr4r5rs zTailReader.__init__c CsHz&|j|j}|sq$|j|qWnttfy<Yn0d|_dS)alReads from the channel (pipe) that is the output pipe for a called Popen. As we are reading from the pipe, the output is added to a deque. After the size of the deque exceeds the sizelimit earlier (older) entries are removed. This means the returned output is chunksize-sensitive, but is not really byte-sensitive. FN)r"r?r#rr ValueErrorrHr)rrtr4r4r5rs zTailReader.runcCsD|jrtdq|js.ddd|jDSddd|jDS)z-Returns the contents of the deque as a stringrr{css|]}|ddVqdS)rCignoreN)decoder^Zlnr4r4r5r`raz*TailReader.get_contents..racss|] }|VqdSr\r4r)r4r4r5r`ra)rrrr[rorrr4r4r5rs  zTailReader.get_contentscCs|js dSt|j|jkS)z?Checks if the deque is full, implying that output was truncatedF)r$rrrr4r4r5rszTailReader.is_full) rrrrrrrrrr r4r4rr5rs   rc@s8eZdZdZddZddZddZdd Zd d Zd S) r zProvides a list of modules that can be imported in a package. Importable modules are located along the module __path__ list and modules are files that end in .py. cCs ||_dS)zopackage is a package module import my.package.module helper = ImporterHelper(my.package.module)N)package)rr*r4r4r5rszImporterHelper.__init__cCs tj|}tj|\}}|S)z-Returns the plugin module name given the path)r;rhbasenamesplitext)rrhbaserrr1r4r4r5 _plugin_names zImporterHelper._plugin_namecsfdd|D}||S)Ncs(g|] }d|vr|dr|qS)rz.py)endswithr.)r^Zpluginrr4r5r~sz9ImporterHelper._get_plugins_from_list..)sort)rZlist_pluginsr4rr5_get_plugins_from_lists  z%ImporterHelper._get_plugins_from_listcCs0tj|r,ttd|}||}|r,|SgS)Nz*.py)r;rhrlistrr2)rrhZpy_filesZpnamesr4r4r5_find_plugins_in_dirs   z#ImporterHelper._find_plugins_in_dircCs2g}|jjD] }tj|r |||q |S)zQReturns the list of importable modules in the configured python package. )r*__path__r;rhrrwr4)rr1rhr4r4r5 get_moduless   zImporterHelper.get_modulesN) rrrrrr.r2r4r6r4r4r4r5r s r c@s$eZdZddZddZddZdS)rcCs||_g|_dSr\)tmp_dirfiles)rr7r4r4r5rszTempFileUtil.__init__cCs2tj|jd\}}t|d}|j||f|S)Nrzw+)rZmkstempr7r;fdopenr8r)rfdrYZfobjr4r4r5news zTempFileUtil.newc Csd|jD]R\}}z||Wnty4Yn0zt|WqtyVYq0qg|_dSr\)r8rrr-r;unlink)rrYrAr4r4r5cleans   zTempFileUtil.cleanN)rrrrr;r=r4r4r4r5rsrc@s eZdZdS)rN)rrrr4r4r4r5rsr)T)rB)NN)N)F)N)rNN)r9)Lr;rr(r subprocessrrrZloggingrmrrrr threadingrrIr contextlibr collectionsrZpackaging.versionrrrZ pkg_resourcesZ getLoggerr.rcrdre__file__AttributeErrortextwrapr msgZwarningr __all__r6r7r"rrVrZrrrrrGrr r!rrrrhrrrrrrrkrrrrThreadrrr rrrr4r4r4r5 s      "   "    *    6%<,