3 ܓid(@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(dUd*d+Z)d,d'Z*dVd.dZ+d/d0Z,d1d2Z-d3dZ.dWd4dZ/d5dZ0dXd6dZ1e2d7d8d9Z3e&dddddddddddf d:d%Z4dYd;d&Z5dZdd$Z7d\d@dZ8ej9fdAdBZ:dCdZ;dDdZdGdZ?ej@dHdId"ZAdJdZBgfdKd#ZCGdLdMdMZDGdNdOdOejEZFGdPdQdQejEZGGdRddZHGdSddZIGdTddeJZKdS)]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 rTc CsZ|d ddkrVt|ddd.}|j}tjd |r8d Stjd |rHd SWdQRXdSdS)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.csr.crt.pemrAzutf-8)rBz-----BEGIN CERTIFICATE-----Z certificatez"-----BEGIN [A-Z]+ PRIVATE KEY-----Zcertificatekey)rVrWrX)r9r>r(search)fnamer@Zcontentr3r3r4file_is_certificates   r\cstrNy4tj|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)r[Z_mimesZtfiler3)r`r4rs    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_depthrgZdirlistZfilelistnamer3r3r4rs 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)r_line)patternr3r4raszgrep..N)rextend)rrZfiles_or_pathsZmatchesZfopZfor3)rrr4rs   &cs\tjjddjtjj}gfdd|D}rJ|fdd|D7}tdd|DS)z6Returns if a command matches an executable on the PATHPATHcsg|]}tjj|qSr3)r:rgrn)r_p)commandr3r4 sz!is_executable..cs g|]}tjj|jdqS)/)r:rgrnlstrip)r_c)sysrootr3r4rxscss|]}tj|tjVqdS)N)r:accessX_OK)r_rgr3r3r4rasz is_executable..)r:environgetr*rgpathsepre)rwr|pathsZ candidatesr3)rwr|r4rs )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.parserrZusernameZpasswordZhostnameZportschemergZparamsZqueryZfragmentr-)rrrZ parsed_urlZnetlocr3r3r4scrub_url_credentials   rc 4sfdd} fdd}rdytj}Wntk rJddddSX|j|j|jdtjj}d |d <|rx.|jD]"\}}|r|||<q|j |d qW|rt d rd |rdndd|d|}t j |}g}xT|D]L}|j dr*d|kr*tj|}|r|j|n |j|q|j|qW| rr|rJt}n&| rftjtjj| d}n t| d}nt}zyt|d||rtntd|d| dv}| r|r| rtjtjj| d}n t| d}t|j|||}n t||}nt|j||}r"x|jr||q Wnzy|j|r2|nd Wn`tk r|j | r| rt| d}t!||dWd QRXd|_d|j"|j#dSXx|j$d krqW| r| rt| d }t!|||j#p|j%dkWd QRX|j%dkrd}n|j"}|j%||j#dSQRXWnBt&k rb}z$|j't'j(krNddddS|WYd d }~XnXWd t)|dr||j*Xd S) zExecute a command and return a dictionary of status and output, optionally changing root or current working directory before executing command. csbrdkrtjrPtjtjjtjtjjtjtjj r^tjdS)Nry) 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_pollerru)ZstatusoutputZ truncated)HOMEZLOGNAMEZPWDZUSERzC.UTF-8LC_ALLNtimeoutztimeout z --foreground zs ry*)dirwbFr#T)shellstdoutstderrbufsizeenvZ close_fdsZ preexec_fnrr~close)rr)+rrKeyErrorupdaterr:rcopyrQpoprshlexr*r^globrsappendrtempfileZ TemporaryFilergrhr9rr HeadReaderr FakeReader TailReaderrunningwaitr-rr! get_contentsis_fullr returncodeOSErrorerrnoENOENThasattrr)rwrrrrrZ foregroundr] sizelimitrZto_fileZtacrrrZpwd_userZcmd_envkeyvalueargsZ expanded_argsargZ expanded_argZ_outputrvreaderf_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)r}r#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__)r_ZcnameZclass_) module_fqnamer3r4rxsz!import_module..csg|]}t|r|qSr3) issubclass)r_m) superclassesr3r4rxsr) 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) NBZKiBZMiBZGiBZTiBrirUr#g@r%r@r3)rSZ precisionsuffixesZ suffixindexr3r3r4rs  cCs>|r,|tjkr,|j|s,tjj||jd}t||}||S)Nry)r:rjr^rgrnrzgetattr)rgr|methodrZ_methr3r3r4 _os_wrappers   rcCs$d|krt||dtdSt||dS)Nrr)rexists)rr)rgr|r3r3r4rscCs t||dS)Nisdir)r)rgr|r3r3r4rscCs t||dS)Nisfile)r)rgr|r3r3r4rscCs t||dS)Nislink)r)rgr|r3r3r4rscCst||dtS)Nr)rr:)rgr|r3r3r4rs)r|cGs8|r&|j| r&tjj||jtj}tjj|f|S)N)r^r:rgrnrzrj)rgr|rvr3r3r4rscCs 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)textr3r3r4r s 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)r_r)vr3r4raBsz/recursive_dict_values_by_key..rcsg|]}|kr|qSr3r3)r_d)_filtr3r4rxMsz0recursive_dict_values_by_key..)rsrCdictrQrr 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)processr])selfrr]r3r3r4__init__VszFakeReader.__init__cCsdS)NFr3)rr3r3r4rZszFakeReader.is_fullcCs|js dSdS)Nrur)r])rr3r3r4r^szFakeReader.get_contentscCs|jjdkS)N)rr)rr3r3r4raszFakeReader.runningN) rr __qualname____doc__rpropertyrrrr3r3r3r4rPs  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 remainingr]rstart)rrrrr])rr3r4rms  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)rZbufr3r3r4runvs   zHeadReader.runcCs|js dSdS)Nrur)r])rr3r3r4rszHeadReader.get_contentscCs |jdkS)Nr)r)rr3r3r4rszHeadReader.is_fulli) rrrrrrrrrr __classcell__r3r3)rr4rfs   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) rrchanr] chunksizeslotsintrrr)rZchannelrr])rr3r4rs 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)rrqr3r3r4rs zTailReader.runcCsHx|jrtjdqW|js2djdd|jDSdjdd|jDS)z-Returns the contents of the deque as a stringg{Gz?rucss|]}|jddVqdS)zutf-8ignoreN)decode)r_lnr3r3r4rasz*TailReader.get_contents..rcss|] }|VqdS)Nr3)r_r r3r3r4ras)rrrr]rnr)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)rr4rs   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 r3r3r4rszImporterHelper.__init__cCs tjj|}tjj|\}}|S)z-Returns the plugin module name given the path)r:rgbasenamesplitext)rrgbaseror1r3r3r4 _plugin_names zImporterHelper._plugin_namecsfdd|D}|j|S)Ncs(g|] }d|kr|jdrj|qS)rz.py)endswithr)r_Zplugin)rr3r4rxsz9ImporterHelper._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:rgrlistrr)rrgZpy_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:rgrrsr)rrrgr3r3r4 get_moduless  zImporterHelper.get_modulesN) rrrrrrrrrr3r3r3r4r 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)Lr:rr(r subprocessrrrZloggingrlrrrrZ threadingrrFr contextlibr collectionsrZpackaging.versionrrrZ pkg_resourcesZ getLoggerr.rbrcrd__file__AttributeErrortextwrapr msgZwarningr __all__r5r6r"rrTr\rrrrrDrr r!rrrrgrrrrrrrjrrrrZThreadrrr rrrr3r3r3r4 s     "   "   *    6%<,