dbfdg 3 ([Qha(@sddlZddlZddlZddlZddlmZmZmZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlmZddlmZyddlmZWn ek rddlmZYnXejdZdZyddlZeje d ZWnFee!fk r<dd l"m#Z#d Z$ej%d e#e$d ddd YnXdZ&ddddddddddddddddd d!d"d#d$d%d&d'gZ'd(d)Z(dSd*d+Z)d,d'Z*dTd.dZ+d/d0Z,d1dZ-dUd2dZ.d3dZ/dVd4dZ0e1d5d6d7Z2e&dddddddddddf d8d%Z3dWd9d&Z4dXd:dZ5dYddZ7ej8fd?d@Z9dAdZ:dBdZ;dCd Zej?dFdGd"Z@dHdZAgfdId#ZBGdJdKdKZCGdLdMdMejDZEGdNdOdOejDZFGdPddZGGdQddZHGdRddeIZJdS)[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_logstailcCstjd}yB|j|dd\}}}|s(|Stjdd|jd}|d|}|Stk r}ztjd|d ||Sd }~XnXd 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_ZpublicZlocalZsanitized_localZpep440_versionerrr3/usr/lib/python3.6/utilities.pyformat_version_to_pep440Psr5cCs|rt|}t|St|S)z6 Converts the version to PEP440 format before parsing )r5r)r0Zpep440Z ver_pep440r3r3r4sos_parse_versionasr6c Cs<t|d(}tj|j|kr*|j| d|jSQRXdS)z,Returns the last number_of_bytes of filenamerbN)openosstatst_sizeseekread)filenameZnumber_of_bytesfr3r3r4r"js rc CsVt|trJyt||ddStk rFtjd|dttjSXnt|SdS)z@Returns a file-like object that can be used as a context managerzutf-8)encodingz fileobj: z could not be openedN) isinstancestrr9IOErrorr.r/rioStringIO)Z path_or_filemoder3r3r4rrs cCsHdd d d d}x2|jD]&\}}||krt||d|SqW|S) zCConverts a number of bytes to a shorter, more human friendly formatr#( )TGMKz.1fli@ii)itemsfloat)Z num_bytesZsizesZsymbolsizer3r3r4 convert_bytes~s rTcstrNy4tj|ddg}jdko8tfdd|D Stk rLYnXt|ddd*}y|jd d Stk rd SXWd QRXd 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|]}jj|VqdS)N)Z mime_type startswith).0Z_mt)_ftupr3r4 sz!file_is_binary..Ztrzutf-8)rBr#FTN) magic_modmagicdetect_from_filenamerBanyr-r9r>UnicodeDecodeError)fnameZ_mimesZtfiler3)rXr4rs    c cs|r"tjj|jtjj}||7}xrtj|D]d\}}}|rX|jtjj|krX|dd=|rltj|| rlq.x$tj||D]}tjj||VqzWq.WdS)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_depthZ path_patternZ base_depthr`ZdirlistZfilelistnamer3r3r4rs c sBg}x8|D]0}t|}|jfdd|DWdQRXq W|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|]}tj|r|VqdS)N)r(match)rWline)patternr3r4rYszgrep..N)rextend)rkZfiles_or_pathsZmatchesZfopZfor3)rkr4rs   &cs\tjjddjtjj}gfdd|D}rJ|fdd|D7}tdd|DS)z6Returns if a command matches an executable on the PATHPATHcsg|]}tjj|qSr3)r:r`rg)rWp)commandr3r4 sz!is_executable..cs g|]}tjj|jdqS)/)r:r`rglstrip)rWc)sysrootr3r4rqscss|]}tj|tjVqdS)N)r:accessX_OK)rWr`r3r3r4rYsz is_executable..)r:environgetr*r`pathsepr])rprupathsZ candidatesr3)rprur4rs )urlc Csddlm}m}y`||}|js&|jrnd}|jr:||j7}|jrP|d|j7}||j||j|j |j |j fS|St k r|SXdS)zK Replace username:password@ with ********@ in proxy URL if present r)urlparse urlunparsez ********@:N) Z urllib.parser}r~ZusernameZpasswordZhostnameZportschemer`ZparamsZqueryZfragmentr-)r|r}r~Z parsed_urlZnetlocr3r3r4scrub_url_credentials   rc ,s\fdd} fdd}rBtj}|j|j|jdtjj}d|d<|rx.|jD]"\}}|rx|||<qb|j|dqbW|rt d rd |rd nd d |d|}t j |}g}xP|D]H}|j dod|krt j |}|r|j|n |j|q|j|qW| rL|r$t}n&| r@tjtjj| d}n t| d}nt}zyt|d||rjtntd|d| dv}| r|r| rtjtjj| d}n t| d}t|j|||}n t||}nt|j||}rx|jr||qWnzy|j|r |ndWn`tk rt|j| r\| r\t| d}t ||dWdQRXd|_d|j!|j"dSXx|j#dkrqxW| r| rt| d }t |||j"p|j$dkWdQRX|j$dkrd}n|j!}|j$||j"dSQRXWnBt%k r<}z$|j&t&j'kr(dd d dS|WYdd}~XnXWdt(|drV|j)XdS) zExecute a command and return a dictionary of status and output, optionally changing root or current working directory before executing command. csbrdkrtjrPtjtjjtjtjjtjtjj r^tjdS)Nrr) r:chrootsetgidpwdgetpwnamZpw_gidsetuidZpw_uidchdirpw_dirr3)rrrunasr3r4_child_prep_fns  z.sos_get_command_output.._child_prep_fncs,s|jdkr|jttjddS)N|g{Gz?)poll terminatertimesleep)proc)pollerr3r4 _check_pollersz-sos_get_command_output.._check_poller)HOMEZLOGNAMEZPWDZUSERzC.UTF-8LC_ALLNtimeoutztimeout z --foregroundrn zs rr*)dirwbFr#T)shellstdoutstderrbufsizeenvZ close_fdsZ preexec_fnr)ZstatusoutputZ truncatedr~close)rr)*rrupdaterr:rxcopyrQpoprshlexr*rVglobrlappendrtempfileZ TemporaryFiler`rar9rr HeadReaderr FakeReader TailReaderrunningwaitr-rr! get_contentsis_fullr returncodeOSErrorerrnoENOENThasattrr)rprrrrrZ foregroundrU sizelimitrZto_fileZtacrrrZpwd_userZcmd_envkeyvalueargsZ expanded_argsargZ expanded_argZ_outputroreaderf_dstrer3)rrrrr4r s                         c Csd}d}d}|jtj|jjdkr,dStj|jdtjd}|jd}}|||krdd}x^|dkr|j|d|}||d|kr|d krfPqf|rd }n|j ||d|d|}qfWWdQRXdS) zPython implementation of the tac utility with support for multiline logs (starting with space). It is intended to reverse the output of 'journalctl --reverse'.  rL rN)rvr#TFr) flushr:fstatfilenor<mmapZ ACCESS_READrSrfindwrite) f_srcrZ drop_last_logZ NEWLINE_BZ NEWLINE_IZSPACE_IZmmZsep1Zsep2r3r3r4r!~s(  csjdd }yttt|g}Wn>tk rd}z"tdd|jj|WYdd}~XnXfddtj |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%r#z"Error while trying to load module z: Ncsg|]\}}|jkr|qSr3) __module__)rWZcnameZclass_) module_fqnamer3r4rqsz!import_module..csg|]}t|r|qSr3) issubclass)rWm) superclassesr3r4rqsr) rpartition __import__globalslocals ImportErrorprint __class____name__inspectZ getmembersZisclass)rrZ module_namemodulermodulesr3)rrr4rs rJcCst||||ddS)zeShell out to an external command and return the output or the empty string in case of error. )rrrr)r )cmdrrZrunatr3r3r4rsr8cCsRdddddg}d}x$|dkr6|dkr6|d 7}|d }qW|d |d ||S) NBZKiBZMiBZGiBZTiBrir#g@r%r@r3)rSZ precisionsuffixesZ suffixindexr3r3r4rs  cCs>|r,|tjkr,|j|s,tjj||jd}t||}||S)Nrr)r:rcrVr`rgrsgetattr)r`rumethodrZ_methr3r3r4 _os_wrappers   rcCs$d|krt||dtdSt||dS)Nrr)rexists)rr)r`rur3r3r4rscCs t||dS)Nisdir)r)r`rur3r3r4rscCs t||dS)Nisfile)r)r`rur3r3r4rscCs t||dS)Nislink)r)r`rur3r3r4rscCst||dtS)Nr)rr:)r`rur3r3r4rs)rucGs8|r&|j| r&tjj||jtj}tjj|f|S)N)rVr:r`rgrsrc)r`ruror3r3r4rscCs 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`` zzr3)textr3r3r4rs c sg}g|j|t|trx|jD]\}j|| sF||krV|jtq&ttr&y$|jtfdd|DdWntk rYnXjjq&Wn |j|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|]}|kr|VqdS)Nr3)rWr)vr3r4rY(sz/recursive_dict_values_by_key..rcsg|]}|kr|qSr3r3)rWd)_filtr3r4rq3sz0recursive_dict_values_by_key..)rlrCdictrQrr IndexErrorkeys)ZdobjrZ_itemskr3)rrr4rs&      c@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||_||_dS)N)processrU)selfrrUr3r3r4__init__<szFakeReader.__init__cCsdS)NFr3)rr3r3r4r@szFakeReader.is_fullcCs|js dSdS)Nrnr)rU)rr3r3r4rDszFakeReader.get_contentscCs|jjdkS)N)rr)rr3r3r4rGszFakeReader.runningN) rr __qualname____doc__rpropertyrrrr3r3r3r4r6s  rcs@eZdZdZd ZfddZddZddZed 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. ics8tj||_||_|d|_||_d|_|jdS)NiT)superrrr remainingrUrstart)rrrrrU)rr3r4rSs  zHeadReader.__init__cCs^xH|jdkrH|jjt|j|j}|s(P|jj||jt|8_qW|jjd|_ 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)rZbufr3r3r4run\s   zHeadReader.runcCs|js dSdS)Nrnr)rU)rr3r3r4riszHeadReader.get_contentscCs |jdkS)Nr)r)rr3r3r4rlszHeadReader.is_fulli) rrrrrrrrrr __classcell__r3r3)rr4rLs   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^tj||_||_d|_d|_|r>|d}t||j|_t|jd|_d|_|j dS)Nii)maxlenT) rrchanrU chunksizeslotsintrrr)rZchannelrrU)rr3r4rys zTailReader.__init__c CsNy*x$|jj|j}|sP|jj|qWWnttfk rBYnXd|_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)rr>rrr ValueErrorrEr)rrjr3r3r4rs zTailReader.runcCsHx|jrtjdqW|js2djdd|jDSdjdd|jDS)z-Returns the contents of the deque as a stringg{Gz?rncss|]}|jddVqdS)zutf-8ignoreN)decode)rWlnr3r3r4rYsz*TailReader.get_contents..rcss|] }|VqdS)Nr3)rWrr3r3r4rYs)rrrrUrgr)rr3r3r4rs zTailReader.get_contentscCs|js dSt|j|jkS)z?Checks if the deque is full, implying that output was truncatedF)rrr)rr3r3r4rszTailReader.is_full) rrrrrrrrrrr3r3)rr4rqs   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)rrr3r3r4rszImporterHelper.__init__cCs tjj|}tjj|\}}|S)z-Returns the plugin module name given the path)r:r`basenamesplitext)rr`baserhr1r3r3r4 _plugin_names zImporterHelper._plugin_namecsfdd|D}|j|S)Ncs(g|] }d|kr|jdrj|qS)rz.py)endswithr)rWZplugin)rr3r4rqsz9ImporterHelper._get_plugins_from_list..)sort)rZlist_pluginsr3)rr4_get_plugins_from_lists z%ImporterHelper._get_plugins_from_listcCs0tjj|r,ttd|}|j|}|r,|SgS)Nz*.py)r:r`rlistrr )rr`Zpy_filesZpnamesr3r3r4_find_plugins_in_dirs   z#ImporterHelper._find_plugins_in_dircCs6g}x,|jjD] }tjj|r|j|j|qW|S)zQReturns the list of importable modules in the configured python package. )r__path__r:r`rrlr )rr r`r3r3r4 get_moduless  zImporterHelper.get_modulesN) rrrrrrr r rr3r3r3r4r s c@s$eZdZddZddZddZdS)rcCs||_g|_dS)N)tmp_dirfiles)rrr3r3r4rszTempFileUtil.__init__cCs2tj|jd\}}tj|d}|jj||f|S)N)rzw+)rZmkstemprr:fdopenrr)rfdr_Zfobjr3r3r4news zTempFileUtil.newcCslx`|jD]V\}}y|j|jWntk r8YnXytj|Wqtk r\YqXqWg|_dS)N)rrrr-r:unlink)rr_r@r3r3r4cleans  zTempFileUtil.cleanN)rrrrrrr3r3r3r4rsc@s eZdZdS)rN)rrrr3r3r3r4rs)T)rA)NN)N)F)N)rJNN)r8)Kr:rr(r subprocessrrrZloggingrerrrrZ threadingrrFr contextlibr collectionsrZpackaging.versionrrrZ pkg_resourcesZ getLoggerr.rZr[r\__file__AttributeErrortextwrapr msgZwarningr __all__r5r6r"rrTrrrrrDrr r!rrrr`rrrrrrrcrrrrZThreadrrr rrrr3r3r3r4 s     "   "   *    6%<,