o
    O6ufðO  ã                   @   sx  d dl Z d dlZd dlZd dlZd dlmZmZmZ d dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dlmZ zd dlmZ W n eya   d dlmZ Y nw dZzd dlZe e¡ dZW n& eefy—   e d	¡Z d d
l!m"Z" dZ#e  $de"e#ddd� d ¡ Y nw dZ%g d¢Z&dd„ Z'dOdd„Z(dd„ Z)dPdd„Z*dQdd„Z+d d!„ Z,dRd"d#„Z-d$d%„ Z.dSd&d'„Z/e%ddddddddddfd(d)„Z0dSd*d+„Z1dTd-d.„Z2dUd0d1„Z3e j4fd2d3„Z5d4d5„ Z6d6d7„ Z7d8d9„ Z8d:d;„ Z9d<d=„ Z:e j;d>œd?d@„Z<dAdB„ Z=g fdCdD„Z>G dEdF„ dFƒZ?G dGdH„ dHej@ƒZAG dIdJ„ dJeBƒZCG dKdL„ dLƒZDG dMdN„ dNeEƒZFdS )Vé    N)ÚPopenÚPIPEÚSTDOUT)Úclosing)Údeque)Úparse)Úparse_versionFTÚsos)ÚfillzÜWARNING: 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,  )ÚTIMEOUT_DEFAULTÚImporterHelperÚSoSTimeoutErrorÚTempFileUtilÚboldÚfile_is_binaryÚfileobjÚfindÚget_human_readableÚgrepÚimport_moduleÚis_executableÚlistdirr   Úpath_existsÚ
path_isdirÚpath_isfileÚpath_islinkÚ	path_joinÚrecursive_dict_values_by_keyÚ	shell_outÚsos_get_command_outputÚtailc              
   C   s�   t  d¡}z#|j| dd�\}}}|s| W S t  dd|¡ d¡}|› d|› �}|W S  tyG } zt d| › d	|› �¡ | W  Y d
}~S d
}~ww )z< Convert the version into a PEP440 compliant version scheme.z2^([0-9][0-9.]*(?:(?:a|b|rc|.post|.dev)[0-9]+)*)\+?é   )Úmaxsplitz[+~]+Ú.ú-ú+zUnable to format z to pep440 format: N)ÚreÚcompileÚsplitÚsubÚstripÚ	ExceptionÚlogÚdebug)ÚverÚpublic_version_reÚ_ÚpublicÚlocalÚsanitized_localÚpep440_versionÚerr© r9   ú//usr/lib/python3/dist-packages/sos/utilities.pyÚformat_version_to_pep440M   s   ÿ€þr;   c                 C   s   |r
t | ƒ}t|ƒS t| ƒS )z6 Converts the version to PEP440 format before parsing )r;   r   )r1   Úpep440Ú
ver_pep440r9   r9   r:   Úsos_parse_version^   s   r>   c                 C   sT   t | dƒ�}t | ¡j|kr| | d¡ | ¡ W  d  ƒ S 1 s#w   Y  dS )z,Returns the last number_of_bytes of filenameÚrbé   N)ÚopenÚosÚstatÚst_sizeÚseekÚread)ÚfilenameÚnumber_of_bytesÚfr9   r9   r:   r#   g   s
   $ýr#   Úrc                 C   sZ   t | tƒr)zt| |ƒW S  ty(   t d¡}| d| › d�¡ tt 	¡ ƒ Y S w t| ƒS )z@Returns a file-like object that can be used as a context managerr	   z	fileobj: z could not be opened)
Ú
isinstanceÚstrrA   ÚIOErrorÚloggingÚ	getLoggerr0   r   ÚioÚStringIO)Úpath_or_fileÚmoder/   r9   r9   r:   r   o   s   

ýr   é   é   é   @ì        c                 C   s^   t | ƒ}| |kr|| d›S | |kr|| d›S | |kr"|| d›S | |kr,|| d›S | › S )zCConverts a number of bytes to a shorter, more human friendly formatz.1fTz.1fGz.1fMz.1fK)Úfloat)Úbytes_ÚKÚMÚGÚTÚfnr9   r9   r:   Úconvert_bytes|   s   r_   c              	      s¬   t r'zt | ¡‰ ddg}ˆ jdkot‡ fdd„|D ƒƒ W S  ty&   Y nw t| dƒ� }z| d¡ W W d  ƒ d	S  tyK   Y W d  ƒ d
S w 1 sOw   Y  dS )az  Helper 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``
    ztext/zinode/Úbinaryc                 3   s   � | ]	}ˆ j  |¡V  qd S ©N)Ú	mime_typeÚ
startswith)Ú.0Ú_mt©Ú_ftupr9   r:   Ú	<genexpr>�   ó   € z!file_is_binary.<locals>.<genexpr>Útrr$   NFT)	Ú	magic_modÚmagicÚdetect_from_filenameÚencodingÚanyr.   rA   rF   ÚUnicodeDecodeError)ÚfnameÚ_mimesÚtfiler9   rf   r:   r   ‹   s*   

ÿÿÿ
ûùúr   c           	      c   s’   � |rt j |¡ t jj¡}||7 }t  |¡D ]/\}}}|r,| t jj¡|kr,|dd…= |r5t ||¡s5qt || ¡D ]
}t j ||¡V  q;qdS )z›Generator function to find files recursively.
    Usage::

        for filename in find("*.properties", "/var/log/foobar"):
            print filename
    N)	rB   ÚpathÚdirnameÚcountÚsepÚwalkÚfnmatchÚfilterÚjoin)	Úfile_patternÚtop_dirÚ	max_depthÚpath_patternÚ
base_depthrt   ÚdirlistÚfilelistÚnamer9   r9   r:   r   ­   s   €
ÿùr   c              	      sR   g }|D ]"}t |ƒ�}| ‡ fdd„|D ƒ¡ W d  ƒ n1 s!w   Y  q|S )z”Returns lines matched in fnames, where fnames can either be pathnames to
    files to grep through or open file objects to grep through line by linec                 3   s    � | ]}t  ˆ |¡r|V  qd S ra   )r)   Úmatch)rd   Úline©Úpatternr9   r:   rh   Ê   s   € zgrep.<locals>.<genexpr>N)r   Úextend)r‡   Úfiles_or_pathsÚmatchesÚfopÚfor9   r†   r:   r   Ã   s   
ÿ€r   c                    s\   t j dd¡ t jj¡}ˆ g‡ fdd„|D ƒ }ˆr%|‡fdd„|D ƒ7 }tdd„ |D ƒƒS )z6Returns if a command matches an executable on the PATHÚPATHÚ c                    s   g | ]	}t j |ˆ ¡‘qS r9   )rB   rt   r{   )rd   Úp)Úcommandr9   r:   Ú
<listcomp>Ó   ó    z!is_executable.<locals>.<listcomp>c                    s    g | ]}t j ˆ | d ¡¡‘qS )ú/)rB   rt   r{   Úlstrip)rd   Úc©Úsysrootr9   r:   r‘   Õ   s    ÿc                 s   s   � | ]
}t  |t j¡V  qd S ra   )rB   ÚaccessÚX_OK)rd   rt   r9   r9   r:   rh   Ø   s   € z is_executable.<locals>.<genexpr>)rB   ÚenvironÚgetr+   rt   Úpathsepro   )r�   r—   ÚpathsÚ
candidatesr9   )r�   r—   r:   r   Ï   s   ÿr   c              
      s‚  ‡ ‡‡fdd„}‡fdd„}ˆr!t  ˆ¡}| |jˆ|jˆdœ¡ tj ¡ }d|d< |rB| ¡ D ]\}}|r;|||< q0| |d¡ q0|rWt	d	ƒrWd
|rMdnd› d|› d| › �} t
 | ¡}g }|D ]#}| d¡r~d|v r~t |¡}|rx| |¡ q`| |¡ q`| |¡ q`|
rŒt|
dƒ}nt}ztt|d||r—tntd|d|d�}|
s©t|j||ƒ}nt||ƒ}ˆr»|jrº||ƒ |js³n,z| |rÂ|nd¡ W n  tyæ   | ¡  |
r×| ¡  d|_d| ¡ |jdœ Y W S w |
rí| ¡  | ¡ du rú	 | ¡ du só| ¡ }|j}W n) t�y+ } z|
�r| ¡  |j t j!k�r%ddddœW  Y d}~S |‚d}~ww |j"dk�s8|j"dk�r:d}|j"||dœS )zœExecute a command and return a dictionary of status and output,
    optionally changing root or current working directory before
    executing command.
    c                      sf   ˆrˆdkrt  ˆ¡ ˆr(t  t ˆ¡j¡ t  t ˆ¡j¡ t  t ˆ¡j	¡ ˆ r1t  ˆ ¡ d S d S ©Nr“   )
rB   ÚchrootÚsetgidÚpwdÚgetpwnamÚpw_gidÚsetuidÚpw_uidÚchdirÚpw_dirr9   )r§   r    Úrunasr9   r:   Ú_child_prep_fnç   s   
ÿz.sos_get_command_output.<locals>._child_prep_fnc                    s,   ˆ ƒ s	|   ¡ dkr|  ¡  t‚t d¡ d S )Né|   ç{®Gáz„?)ÚpollÚ	terminater   ÚtimeÚsleep)Úproc)Úpollerr9   r:   Ú_check_pollerñ   s   z-sos_get_command_output.<locals>._check_poller)ÚHOMEÚLOGNAMEÚPWDÚUSERzC.UTF-8ÚLC_ALLNÚtimeoutztimeout z--foregroundrŽ   ú zs r“   Ú*ÚwFéÿÿÿÿT)ÚshellÚstdoutÚstderrÚbufsizeÚenvÚ	close_fdsÚ
preexec_fnr«   )ÚstatusÚoutputÚ	truncatedé   é~   ó    )#r¢   r£   Úupdater¨   rB   rš   ÚcopyÚitemsÚpopr   Úshlexr+   rc   Úglobrˆ   ÚappendrA   r   r   r   ÚAsyncReaderr¿   Ú
FakeReaderÚrunningÚwaitr.   r®   ÚcloseÚget_contentsÚis_fullr­   ÚOSErrorÚerrnoÚENOENTÚ
returncode)r�   r¹   rÀ   r    r§   rÂ   Ú
foregroundr`   Ú	sizelimitr²   Úto_filer©   rª   r³   Úpwd_userÚcmd_envÚkeyÚvalueÚargsÚexpanded_argsÚargÚexpanded_argÚ_outputr�   Úreaderr¿   rÇ   Úer9   )r§   r    r²   r©   r:   r"   Û   sž   

ü

ÿ


ý
ÿ€ÿù	ÿ
€úýr"   c              
      s’   ˆ   d¡d }ztˆ tƒ tƒ |gƒ}W n ty- } ztdˆ › d|jj› �ƒ |‚d}~ww ‡ fdd„t 	|tj
¡D ƒ}ˆrG‡fdd„|D ƒ}|S )	a  Imports 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:  Nc                    s   g | ]\}}|j ˆ kr|‘qS r9   )Ú
__module__)rd   ÚcnameÚclass_)Úmodule_fqnamer9   r:   r‘   c  s    
þz!import_module.<locals>.<listcomp>c                    s   g | ]	}t |ˆ ƒr|‘qS r9   )Ú
issubclass)rd   Úm)Úsuperclassesr9   r:   r‘   g  r’   )Ú
rpartitionÚ
__import__ÚglobalsÚlocalsÚImportErrorÚprintÚ	__class__Ú__name__ÚinspectÚ
getmembersÚisclass)rî   rñ   Úmodule_nameÚmodulerê   Úmodulesr9   )rî   rñ   r:   r   W  s    
ÿ€ý
ÿr   é   c                 C   s   t | |||d�d S )zeShell out to an external command and return the output or the empty
    string in case of error.
    )r¹   r    r§   rÆ   )r"   )Úcmdr¹   r    Úrunatr9   r9   r:   r!   l  s
   ÿÿr!   r@   c                 C   sV   g d¢}d}| dkr|dk r|d7 }| d } | dkr|dk s| d|› d�›|| › �S )	N)ÚBÚKiBÚMiBÚGiBÚTiBr   rT   é   r$   g      �@r&   rI   r9   )ÚsizeÚ	precisionÚsuffixesÚsuffixindexr9   r9   r:   r   t  s   þr   c                 C   s>   |r|t jkr|  |¡st j ||  d¡¡} t||ƒ}|| ƒS rŸ   )rB   rw   rc   rt   r{   r”   Úgetattr)rt   r—   Úmethodrþ   Ú_methr9   r9   r:   Ú_os_wrapper~  s
   

r  c                 C   s$   d| v rt | |dtd�S t | |dƒS )Nr»   rÐ   )rþ   Úexists)r  rÐ   ©rt   r—   r9   r9   r:   r   †  s   r   c                 C   ó   t | |dƒS )NÚisdir©r  r  r9   r9   r:   r   Œ  ó   r   c                 C   r  )NÚisfiler  r  r9   r9   r:   r   �  r  r   c                 C   r  )NÚislinkr  r  r9   r9   r:   r   ”  r  r   c                 C   s   t | |dtƒS )Nr   )r  rB   r  r9   r9   r:   r   ˜  ó   r   r–   c                G   s8   |r|   |¡stj ||  tj¡¡} tjj| g|¢R Ž S ra   )rc   rB   rt   r{   r”   rw   )rt   r—   r�   r9   r9   r:   r   œ  s   r   c                 C   s   d|  d S )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``
    z[1mz[0mr9   )Útextr9   r9   r:   r   ¢  s   
r   c              	      sÂ   g }g ‰ |  |¡ t| tƒrS|  ¡ D ]?\}‰ˆ  |¡ |r!||v r)|  tˆƒ¡ qtˆtƒrQz|  t‡fdd„|D ƒƒd ¡ W n	 tyI   Y nw ˆ   ˆ ¡ ¡ qn|  | ¡ ‡ fdd„|D ƒS )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``
    c                 3   s    � | ]}|ˆ v rˆ | V  qd S ra   r9   )rd   râ   )Úvr9   r:   rh   Ö  s   € ÿz/recursive_dict_values_by_key.<locals>.<genexpr>r   c                    s   g | ]}|ˆ vr|‘qS r9   r9   )rd   Úd)Ú_filtr9   r:   r‘   â  s    z0recursive_dict_values_by_key.<locals>.<listcomp>)rˆ   rK   ÚdictrÍ   rÑ   r    Ú
IndexErrorÚkeys)Údobjr   Ú_itemsÚkr9   )r  r  r:   r    ¯  s2   



ÿþÿþ€î
r    c                   @   s8   e Zd ZdZdd„ Zedd„ ƒZdd„ Zedd	„ ƒZd
S )rÓ   z¾Used 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.
    c                 C   s   || _ || _d S ra   )Úprocessr`   )Úselfr$  r`   r9   r9   r:   Ú__init__ë  ó   
zFakeReader.__init__c                 C   s   dS )NFr9   ©r%  r9   r9   r:   rØ   ï  s   zFakeReader.is_fullc                 C   s   | j sdS dS )NrŽ   rÊ   )r`   r(  r9   r9   r:   r×   ó  r  zFakeReader.get_contentsc                 C   s   | j  ¡ d u S ra   )r$  r­   r(  r9   r9   r:   rÔ   ö  s   zFakeReader.runningN)	rù   rë   Ú__qualname__Ú__doc__r&  ÚpropertyrØ   r×   rÔ   r9   r9   r9   r:   rÓ   å  s    
rÓ   c                       s<   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zedd	„ ƒZ‡  Z	S )
rÒ   zÏUsed 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.
    c                    s^   t ƒ  ¡  || _|| _d| _d | _|r|d }t|| j ƒ| _t| jd�| _d| _|  	¡  d S )Ni   rU   )ÚmaxlenT)
Úsuperr&  Úchanr`   Ú	chunksizeÚslotsÚintr   rÔ   Ústart)r%  ÚchannelrÞ   r`   ©rø   r9   r:   r&    s   
zAsyncReader.__init__c              	   C   sJ   z	 | j  | j¡}|sn| j |¡ qW n ttfy   Y nw d| _dS )al  Reads 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.  rF   r/  r   rÑ   Ú
ValueErrorrM   rÔ   )r%  r…   r9   r9   r:   Úrun  s   	ûþ
zAsyncReader.runc                 C   sH   | j rt d¡ | j s| jsd dd„ | jD ƒ¡S d dd„ | jD ƒ¡S )z-Returns the contents of the deque as a stringr¬   rŽ   c                 s   s   � | ]	}|  d d¡V  qdS )zutf-8ÚignoreN)Údecode©rd   Úlnr9   r9   r:   rh   ,  ri   z+AsyncReader.get_contents.<locals>.<genexpr>rÊ   c                 s   s   � | ]}|V  qd S ra   r9   r9  r9   r9   r:   rh   .  s   € )rÔ   r¯   r°   r`   r{   r   r(  r9   r9   r:   r×   %  s   
ÿzAsyncReader.get_contentsc                 C   s   | j sdS t| jƒ| j kS )z?Checks if the deque is full, implying that output was truncatedF)r0  Úlenr   r(  r9   r9   r:   rØ   0  s   zAsyncReader.is_full)
rù   rë   r)  r*  r&  r6  r×   r+  rØ   Ú__classcell__r9   r9   r4  r:   rÒ   û  s    rÒ   c                   @   s8   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ ZdS )r   z¯Provides 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.
    c                 C   s
   || _ dS )zopackage is a package module
        import my.package.module
        helper = ImporterHelper(my.package.module)N)Úpackage)r%  r=  r9   r9   r:   r&  >  s   
zImporterHelper.__init__c                 C   s    t j |¡}t j |¡\}}|S )z-Returns the plugin module name given the path)rB   rt   ÚbasenameÚsplitext)r%  rt   Úbaserƒ   Úextr9   r9   r:   Ú_plugin_nameD  s   zImporterHelper._plugin_namec                    s   ‡ fdd„|D ƒ}|  ¡  |S )Nc                    s(   g | ]}d |vr|  d¡rˆ  |¡‘qS )r&  z.py)ÚendswithrB  )rd   Úpluginr(  r9   r:   r‘   K  s
    þz9ImporterHelper._get_plugins_from_list.<locals>.<listcomp>)Úsort)r%  Úlist_Úpluginsr9   r(  r:   Ú_get_plugins_from_listJ  s
   
ÿz%ImporterHelper._get_plugins_from_listc                 C   s0   t j |¡rttd|ƒƒ}|  |¡}|r|S g S )Nz*.py)rB   rt   r  Úlistr   rH  )r%  rt   Úpy_filesÚpnamesr9   r9   r:   Ú_find_plugins_in_dirQ  s   
z#ImporterHelper._find_plugins_in_dirc                 C   s2   g }| j jD ]}tj |¡r| |  |¡¡ q|S )zQReturns the list of importable modules in the configured python
        package. )r=  Ú__path__rB   rt   r  rˆ   rL  )r%  rG  rt   r9   r9   r:   Úget_modulesY  s   €zImporterHelper.get_modulesN)	rù   rë   r)  r*  r&  rB  rH  rL  rN  r9   r9   r9   r:   r   8  s    r   c                   @   s$   e Zd Zdd„ Zdd„ Zdd„ ZdS )r   c                 C   s   || _ g | _d S ra   )Útmp_dirÚfiles)r%  rO  r9   r9   r:   r&  f  r'  zTempFileUtil.__init__c                 C   s2   t j| jd�\}}t |d¡}| j ||f¡ |S )N)Údirzw+)ÚtempfileÚmkstemprO  rB   ÚfdopenrP  rÑ   )r%  Úfdrq   Úfobjr9   r9   r:   Únewj  s   zTempFileUtil.newc              	   C   sb   | j D ](\}}z
| ¡  | ¡  W n	 ty   Y nw zt |¡ W q ty+   Y qw g | _ d S ra   )rP  ÚflushrÖ   r.   rB   Úunlink)r%  rq   rI   r9   r9   r:   Úcleanq  s   þþ
zTempFileUtil.cleanN)rù   rë   r)  r&  rW  rZ  r9   r9   r9   r:   r   d  s    r   c                   @   s   e Zd ZdS )r   N)rù   rë   r)  r9   r9   r9   r:   r   �  s    r   )T)rJ   )rT   rU   rV   rW   )NNra   )r   NN)r@   )GrB   r¢   r)   rú   Ú
subprocessr   r   r   rN   ry   rÚ   rÏ   rÐ   rR  Ú	threadingr¯   rP   Ú
contextlibr   Úcollectionsr   Úpackaging.versionr   r   rö   Úpkg_resourcesrk   rl   rm   Ú__file__ÚAttributeErrorrO   r/   Útextwrapr
   ÚmsgÚwarningr   Ú__all__r;   r>   r#   r   r_   r   r   r   r   r"   r   r!   r   rt   r  r   r   r   r   r   rw   r   r   r    rÓ   ÚThreadrÒ   Úobjectr   r   rÙ   r   r9   r9   r9   r:   Ú<module>   s‚   ÿ

 ø
	


"

ý
|


6=,