o id~H @s\ddlZddlZddlZddlmZmZmZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlmZddlmZzddlmZWney]ddlmZYnwdZz ddlZeedZWn&eefye d Z!dd l"m#Z#d Z$e!%d e#e$d ddd YnwdZ&ddZ'dLddZ(dMddZ)ddZ*dNddZ+dd Z,dOd!d"Z-e&dddddddddf d#d$Z.dOd%d&Z/dPd(d)Z0dQd+d,Z1ej2fd-d.Z3d/d0Z4d1d2Z5d3d4Z6d5d6Z7d7d8Z8ej9d9d:d;Z:dd?ZZ?GdFdGdGe@ZAGdHdIdIZBGdJdKdKeCZDdS)RN)PopenPIPESTDOUT)closing)deque) parse_version)parseFTsos)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)replace_whitespacei,cCsTt|d}t|j|kr|| d|WdS1s#wYdS)z,Returns the last number_of_bytes of filenamerbN)openosstatst_sizeseekread)filenamenumber_of_bytesfr//usr/lib/python3/dist-packages/sos/utilities.pytail2s $rrcCsVt|tr'zt||WSty&td}|d|tt YSwt|S)z@Returns a file-like object that can be used as a context managerr zfileobj: %s could not be opened) isinstancestrrIOErrorlogging getLoggerdebugrioStringIO) path_or_filemodelogrrrfileobj:s    r(@cCs`t|}||krd||S||krd||S||kr"d||S||kr,d||Sd|S)zCConverts a number of bytes to a shorter, more human friendly formatz%.1fTz%.1fGz%.1fMz%.1fKz%d)float)bytes_KMGTfnrrr convert_bytesGs    r4c str'zt|ddg}jdkotfdd|D WSty&Ynwt|d }z|dWWdd StyKYWdd Sw1sOwYdS) 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) mime_type startswith).0_mt_ftuprr hz!file_is_binary..trNFT) magic_modmagicdetect_from_filenameencodingany ExceptionrrUnicodeDecodeError)fname_mimestfilerr;rfile_is_binaryVs*       rKc cs|rtj|tjj}||7}t|D]/\}}}|r,|tjj|kr,|dd=|r5t||s5qt||D] }tj||Vq;qdS)zGenerator function to find files recursively. Usage:: for filename in find("*.properties", "/var/log/foobar"): print filename N) rpathdirnamecountsepwalkfnmatchfilterjoin) file_patterntop_dir max_depth path_pattern base_depthrLdirlistfilelistnamerrrfindxs r\c sRg}|D]"}t|}|fdd|DWdn1s!wYq|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|VqdSr6)rematch)r9linepatternrrr=szgrep..N)r(extend)rafiles_or_pathsmatchesfopforr`rgreps rgcs\tjddtjj}gfdd|D}r%|fdd|D7}tdd|DS)z6Returns if a command matches an executable on the PATHPATHcsg|] }tj|qSr)rrLrS)r9p)commandrr z!is_executable..cs g|] }tj|dqS)/)rrLrSlstrip)r9csysrootrrrlscss|] }t|tjVqdSr6)raccessX_OK)r9rLrrrr=sz is_executable..)renvirongetsplitrLpathseprE)rkrrpaths candidatesr)rkrrr is_executables r{c  sPfdd} fdd} tj} d| d<|r.|D]\}}|r'|| |<q| |dq|r?tdr?d |r9d nd ||f}t|}g}|D]#}|d rfd |vrft |}|r`| |qH| |qH| |qH| rtt | d}nt }ztt|d||rtnt d| d| d}| st|j||}nt||}r|jr| ||jsn,z ||r|ndWn ty|| r|d|_d||jdYWSw| r||dur |dus|}|j}Wn(ty}z| r||jtjkr dd d dWYd}~S|d}~ww|jdks|jdkr!d}|j||dS)zExecute a command and return a dictionary of status and output, optionally changing root or current working directory before executing command. cs,r dkr trtdSdSNrn)rchrootchdirr)r~r}rr_child_prep_fns  z.sos_get_command_output.._child_prep_fncs,s |dkr|ttddS)N|{Gz?)poll terminateSoSTimeoutErrortimesleep)proc)pollerrr _check_pollersz-sos_get_command_output.._check_pollerzC.UTF-8LC_ALLNtimeoutztimeout %s %ds %sz --foregroundrirn*wFT)shellstdoutstderrbufsizeenv close_fds preexec_fnr)statusoutput truncated~)rrucopyitemspopr{shlexrwr8globrbappendrrrr AsyncReaderr FakeReaderrunningwaitrFrclose get_contentsis_fullrOSErrorerrnoENOENT returncode)rkrrr}r~r foregroundr5 sizelimitrto_filerrcmd_envkeyvalueargs expanded_argsarg expanded_arg_outputrjreaderrrer)r~r}rrsos_get_command_outputs                   rcsXdd}ttt|g}fddt|tjD}r*fdd|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..rcsg|] \}}|jkr|qSr) __module__)r9cnameclass_) module_fqnamerrrls z!import_module..csg|] }t|r|qSr) issubclass)r9m) superclassesrrrl"rm) rpartition __import__globalslocalsinspect getmembersisclass)rr module_namemodulemodulesr)rrr import_modules  rcCst||||ddS)zeShell out to an external command and return the output or the empty string in case of error. )rr}r~r)r)cmdrr}runatrrr shell_out's rrcCsNgd}d}|dkr|dkr|d7}|d}|dkr|dksd||||fS)N)BKiBMiBGiBTiBrr)r@g@z%.*f%sr)size precisionsuffixes suffixindexrrrget_human_readable/srcCs>|r|tjkr||stj||d}t||}||Sr|)rrOr8rLrSrogetattr)rLrrmethodr_methrrr _os_wrapper9s   rcCs$d|vr t||dtdSt||dS)Nrr)rexists)rrrLrrrrr path_existsAs rcC t||dS)Nisdirrrrrr path_isdirG rcCr)Nisfilerrrrr path_isfileKrrcCr)Nislinkrrrrr path_islinkOrrcCst||dtS)Nlistdir)rrrrrrrSrrqcGs8|r||stj||tj}tjj|g|RSr6)r8rrLrSrorO)rLrrrjrrr path_joinWsrcCs 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`` zzr)textrrrbold]s rc sg}g||t|trS|D]?\}||r!||vr)|tqttrQz|tfdd|DdWn tyIYnwqn||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|VqdSr6r)r9r)vrrr=sz/recursive_dict_values_by_key..rcsg|]}|vr|qSrr)r9d)_filtrrrlsz0recursive_dict_values_by_key..)rbrdictrrrecursive_dict_values_by_key IndexErrorkeys)dobjr_itemskr)rrrrjs2        rcCst|S)zParse the version string ) version_parse)versionrrrrsrc@s8eZdZdZddZeddZddZedd Zd S) rzUsed as a replacement AsyncReader for when we are writing directly to disk, and allows us to keep more simplified flows for executing, monitoring, and collecting command output. cCs||_||_dSr6)processr5)selfrr5rrr__init__ zFakeReader.__init__cCsdS)NFrrrrrrszFakeReader.is_fullcCs|jsdSdS)Nrir)r5rrrrrrzFakeReader.get_contentscCs|jduSr6)rrrrrrrszFakeReader.runningN) __name__r __qualname____doc__rpropertyrrrrrrrrs rcs<eZdZdZfddZddZddZedd ZZ S) rzUsed to limit 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. csbtt|||_||_d|_d|_|r!|d}t||j|_t|jd|_d|_ | dS)Nir*)maxlenT) superrrchanr5 chunksizeslotsintrrstart)rchannelrr5 __class__rrrs zAsyncReader.__init__c CsJz |j|j}|s n|j|qWn ttfyYnwd|_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. TFN)r rr rr ValueErrorrr)rr_rrrruns   zAsyncReader.runcCsH|jr td|js|jsddd|jDSddd|jDS)z-Returns the contents of the deque as a stringrricss|] }|ddVqdS)zutf-8ignoreN)decoder9lnrrrr=r>z+AsyncReader.get_contents..rcss|]}|VqdSr6rrrrrr=s)rrrr5rSrrrrrrs  zAsyncReader.get_contentscCs|jsdSt|j|jkS)z?Checks if the deque is full, implying that output was truncatedF)r lenrrrrrrszAsyncReader.is_full) rrrrrrrrr __classcell__rrrrrs   rc@s8eZdZdZddZddZddZdd Zd d Zd S) ImporterHelperzProvides 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)rrrrrrs zImporterHelper.__init__cCs tj|}tj|\}}|S)z-Returns the plugin module name given the path)rrLbasenamesplitext)rrLbaser[extrrr _plugin_names zImporterHelper._plugin_namecsfdd|D}||S)Ncs(g|]}d|vr|dr|qS)rz.py)endswithr)r9pluginrrrrl s z9ImporterHelper._get_plugins_from_list..)sort)rlist_pluginsrrr_get_plugins_from_list s z%ImporterHelper._get_plugins_from_listcCs4tj|rttd|}||}|r|SgSdS)Nz*.py)rrLrlistr\r%)rrLpy_filespnamesrrr_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__rrLrrbr))rr$rLrrr get_moduless   zImporterHelper.get_modulesN) rrrrrrr%r)r+rrrrrs rc@s$eZdZddZddZddZdS) TempFileUtilcCs||_g|_dSr6)tmp_dirfiles)rr-rrrr(rzTempFileUtil.__init__cCs2tj|jd\}}t|d}|j||f|S)N)dirzw+)tempfilemkstempr-rfdopenr.r)rfdrHfobjrrrnew,s zTempFileUtil.newc Csb|jD](\}}z ||Wn tyYnwzt|Wqty+Yqwg|_dSr6)r.flushrrFrunlink)rrHrrrrclean3s    zTempFileUtil.cleanN)rrrrr5r8rrrrr,&s r,c@s eZdZdS)rN)rrrrrrrrAsr)r)r)r*r+r,)NNr6)rNN)r)Err]r subprocessrrrr rQrrrr0 threadingrr# contextlibr collectionsr pkg_resourcesrr SyntaxErrorpackaging.versionrrArBrC__file__ ImportErrorAttributeErrorr!r'textwrapr msgwarningTIMEOUT_DEFAULTrr(r4rKr\rgr{rrrrrLrrrrrrrOrrrrThreadrobjectrr,rrrrrrs|           "   q    6=-