Your IP : 216.73.217.13


Current Path : /usr/lib/python3/dist-packages/sos/policies/distros/__pycache__/
Upload File :
Current File : //usr/lib/python3/dist-packages/sos/policies/distros/__pycache__/__init__.cpython-38.pyc

U

���b�s�@s�ddlZddlZddlmZddlmZddlmZddlm	Z	ddl
mZddlm
Z
ddlmZdd	lmZdd
lmZmZmZzddlZdZWnek
r�dZYnXd
ZdZGdd�de�ZGdd�de�ZdS)�N)�getpass)�_sos)�Policy)�
InitSystem)�SystemdInit)�CrioContainerRuntime)�PodmanContainerRuntime)�DockerContainerRuntime)�	shell_out�
is_executable�boldTFZ	containerZHOSTcs�eZdZdZdZdZdZdZdZdZ	dZ
dZdZdZ
dZdZdZdZdZdZdZdZd	Zd
ZdZdZdT�fdd
�	Zedd��Zdd�Zdd�Zdd�Zdd�Z dd�Z!dd�Z"edd��Z#edd��Z$ed d!��Z%d"d#�Z&d$d%�Z'd&d'�Z(d(d)�Z)d*d+�Z*d,d-�Z+d.d/�Z,d0d1�Z-dUd2d3�Z.d4d5�Z/d6d7�Z0d8d9�Z1d:d;�Z2dVd<d=�Z3d>d?�Z4dWd@dA�Z5dBdC�Z6dXdDdE�Z7dFdG�Z8dYdHdI�Z9dJdK�Z:dLdM�Z;dZdNdO�Z<dPdQ�Z=dRdS�Z>�Z?S)[�LinuxPolicyzfThis policy is meant to be an abc class that provides common
    implementations used in Linux distrosZLinux�Nonez/bin:/sbin:/usr/bin:/usr/sbinN�/�dockerFz/usr/binzsos-collector-tmpTcs tt|�j|||d�|r"||_n|��p,d|_|��|dk	rH||_n$tj�	d�rdt
|jd�|_nt�|_i|_|j
�rt|d�t|d�t|d�g}|D]F}|��r�||j|j<|j|jkr�|j|j|jd<|j|j��q�|j�rd|j��k�rt|j���}|j|d|jd<dS)N)�sysroot�
probe_runtime�remote_execrz/run/systemd/system/)�chroot)Zpolicy�defaultr)�superr
�__init__r�_container_init�init_kernel_modulesZinit_system�os�path�isdirrrZruntimesrrr	rZcheck_is_active�name�default_container_runtimeZload_container_info�keys�list)�selfr�initrrZ_crunZruntime�idx��	__class__��?/usr/lib/python3/dist-packages/sos/policies/distros/__init__.pyrHs8��zLinuxPolicy.__init__cCsddgS)Nz/etc/passwdz/etc/shadowr&)�clsr&r&r'�set_forbidden_pathsps�zLinuxPolicy.set_forbidden_pathscCs|jS�N)�release�r!r&r&r'�kernel_versionwszLinuxPolicy.kernel_versioncCs|jSr*)Zhostnamer,r&r&r'�	host_namezszLinuxPolicy.host_namecCs|jSr*)Zsmpr,r&r&r'�
is_kernel_smp}szLinuxPolicy.is_kernel_smpcCs|jSr*)�machiner,r&r&r'�get_arch�szLinuxPolicy.get_archcCs|��S)z)Returns the name usd in the pre_work step)r.r,r&r&r'�get_local_name�szLinuxPolicy.get_local_namecCst�dd|�S)Nz[^-a-z,A-Z.0-9]�)�re�sub)r!rr&r&r'�sanitize_filename�szLinuxPolicy.sanitize_filenamecCs2|tkr|�|�n|�d|j�|�|�dS)Nz%s Distribution Policy)r
�display_self_help�	set_title�distro�display_distro_help�r(�sectionr&r&r'�display_help�szLinuxPolicy.display_helpcCs|�d�|�d�dS)NzSoS Distribution Policiesz�Distributions supported by SoS will each have a specific policy defined for them, to ensure proper operation of SoS on those systems.)r8�add_textr;r&r&r'r7�s
�zLinuxPolicy.display_self_helpc	Cs|jr |jtjk	r |�|j�n
|�d�|ddd�}|�d|j�|jd|jdd�|jd|jdd�|�d�}|jD]$}|jd�d	|d
|d�dd�q~|�d�}|jt	d
�d	ddd��dd�|j
D]:}|j
|}d	�|j�
��}|jd
�d	||j|�dd�q�dS)Nz;
Detailed help information for this policy is not availableFzDefault --upload location: %szDefault container runtime: %s)�newlinez"$PATH used when running report: %szReference URLsz{:>8}{:<30}{:<40}� r�z#Presets Available With This Policy
z{:>8}{:<20}{:<45}{:<30}zPreset NameZDescriptionzEnabled Options)�__doc__r
r>�_upload_urlr�PATHZadd_section�vendor_urls�formatrZpresets�joinZoptsZto_argsZdesc)	r(r<Z_polZrefsec�urlZpresecZpresetZ_presetZ_optsr&r&r'r:�sZ����

�
���

��zLinuxPolicy.display_distro_helpcCs^ttjkrZtjtdkrZd|_ttjkrZtjts6dStj�tjt|j�|_tjtSdS)z�Check if sos is running in a container and perform container
        specific initialisation based on ENV_HOST_SYSROOT.
        )rZociZpodmanTN)�
ENV_CONTAINERr�environZ
_in_container�ENV_HOST_SYSROOTr�abspathZ_tmp_dirr,r&r&r'r�s


�
zLinuxPolicy._container_initc	CsLg|_t��j}tdd|jd���}|j�dd�|dd�D��|�d|�}zHt	|d	��4}|D](}|�
d
�d�
d�d}|j�|�qbW5QRXWntk
r�YnXd
dd�}|�d|�}g}	z@t	|d	��,}
|
D] }d|kr�|	�|�
d�d�q�W5QRXWntk
�r YnX|D] }|||	k�r&|j�|��q&dS)zxObtain a list of loaded kernel modules to reference later for plugin
        enablement and SoSPredicate checks
        Zlsmodr)�timeoutrcSsg|]}|��d���qS)r)�split�strip)�.0�liner&r&r'�
<listcomp>�sz3LinuxPolicy.init_kernel_modules.<locals>.<listcomp>rANz#/usr/lib/modules/%s/modules.builtin�rr���z.koZCONFIG_NET_DEVLINKZCONFIG_BLK_DEV_DM)ZdevlinkZdm_modz/boot/config-%sz=y)
Zkernel_modsr�unamer+r
r�
splitlines�extend�join_sysroot�openrN�append�IOError)r!r+�lines�builtinsZmfilerQZkmodZconfig_stringsZ
booted_configZkconfigsZkfileZbuiltinr&r&r'r�s>

���$zLinuxPolicy.init_kernel_modulescCs*|jr&|jdkr&tj�|j|�d��}|S)Nr)rrrrG�lstrip)r!rr&r&r'rX
szLinuxPolicy.join_sysrootcCs�|jd}|jr|jnd}|j|_|j|_|j|_|j|_d|_|js�|j	s�zT|r`||jd_nt
td�|�|jd_|jr�|�
�r�|��|��|��Wntk
r�|���YnX|jr�|j|_dS)N�cmdlineoptsr3zSOptionally, please enter the case id that you are generating this report for [%s]: )�commonsZcase_id�
upload_url�upload_user�upload_directoryZupload_pass�upload_password�upload_archive_nameZbatch�quiet�input�_Zupload�get_upload_url�prompt_for_upload_user�prompt_for_upload_passwordZ_print�KeyboardInterrupt)r!Zcmdline_optsZcaseidr&r&r'�pre_works8
���zLinuxPolicy.pre_workcCs&|��s"d|��}tt|��|_dS)zdShould be overridden by policies to determine if a user needs to
        be provided or not
        z#Please provide upload user for %s: N)�get_upload_userrirgrhrb�r!�msgr&r&r'rj9sz"LinuxPolicy.prompt_for_upload_usercCs0|��s,|��|jkr,d|��}t|�|_dS)zsShould be overridden by policies to determine if a password needs to
        be provided for upload or not
        z+Please provide the upload password for %s: N)�get_upload_passwordrn�_upload_userrrdror&r&r'rkAs��z&LinuxPolicy.prompt_for_upload_passwordcCsF||_|js|��|_|js$td��|��}ttd|����|�S)a

        Entry point for sos attempts to upload the generated archive to a
        policy or user specified location.

        Curerntly there is support for HTTPS, SFTP, and FTP. HTTPS uploads are
        preferred for policy-defined defaults.

        Policies that need to override uploading methods should override the
        respective upload_https(), upload_sftp(), and/or upload_ftp() methods
        and should NOT override this method.

        :param archive: The archive filepath to use for upload
        :type archive: ``str``

        In order to enable this for a policy, that policy needs to implement
        the following:

        Required Class Attrs

        :_upload_url:     The default location to use. Note these MUST include
                          protocol header
        :_upload_user:    Default username, if any else None
        :_upload_password: Default password, if any else None

        The following Class Attrs may optionally be overidden by the Policy

        :_upload_directory:     Default FTP server directory, if any


        The following methods may be overridden by ``Policy`` as needed

        `prompt_for_upload_user()`
            Determines if sos should prompt for a username or not.

        `get_upload_user()`
            Determines if the default or a different username should be used

        `get_upload_https_auth()`
            Format authentication data for HTTPS uploads

        `get_upload_url_string()`
            Print a more human-friendly string than vendor URLs
        z;No upload destination provided by policy or by --upload-urlzAttempting upload to %s)rerari�	Exception�_determine_upload_type�printrh�get_upload_url_string)r!�archiveZupload_funcr&r&r'�upload_archiveKs,
zLinuxPolicy.upload_archivecCsx|j|j|jd�}|jdj|��kr6||jdjSd|jkrHtd��|j�d�\}}||��krptd|��||S)aBased on the url provided, determine what type of upload to attempt.

        Note that this requires users to provide a FQDN address, such as
        https://myvendor.com/api or ftp://myvendor.com instead of
        myvendor.com/api or myvendor.com
        )Zftp�sftpZhttpsr_z://z#Must provide protocol in upload URLz(Unsupported or unrecognized protocol: %s)	�
upload_ftp�upload_sftp�upload_httpsr`Zupload_protocolrrarsrN)r!ZprotsZprotrHr&r&r'rt�s�
z"LinuxPolicy._determine_upload_typecCs&|s|��}|s|��}tj�||�S)agFormats the user/password credentials using basic auth

        :param user: The username for upload
        :type user: ``str``

        :param password: Password for `user` to use for upload
        :type password: ``str``

        :returns: The user/password auth suitable for use in reqests calls
        :rtype: ``requests.auth.HTTPBasicAuth()``
        )rnrq�requests�authZ
HTTPBasicAuth)r!�user�passwordr&r&r'�get_upload_https_auth�s
z!LinuxPolicy.get_upload_https_authcCs|jp
|jS)z�Helper function to determine if we should use the policy default
        upload url or one provided by the user

        :returns: The URL to use for upload
        :rtype: ``str``
        )rarCr,r&r&r'ri�szLinuxPolicy.get_upload_urlcCs|��S)z�Used by distro policies to potentially change the string used to
        report upload location from the URL to a more human-friendly string
        )rir,r&r&r'rv�sz!LinuxPolicy.get_upload_url_stringcCst�dd�p|jp|jS)z�Helper function to determine if we should use the policy default
        upload user or one provided by the user

        :returns: The username to use for upload
        :rtype: ``str``
        Z
SOSUPLOADUSERN)r�getenvrbrrr,r&r&r'rn�s
��zLinuxPolicy.get_upload_usercCst�dd�p|jp|jS)a_Helper function to determine if we should use the policy default
        upload password or one provided by the user

        A user provided password, either via option or the 'SOSUPLOADPASSWORD'
        environment variable will have precendent over any policy value

        :returns: The password to use for upload
        :rtype: ``str``
        ZSOSUPLOADPASSWORDN)rr�rd�_upload_passwordr,r&r&r'rq�s

��zLinuxPolicy.get_upload_passwordcCstd�std��zddl}Wntk
r8td��YnXd}|sJ|��}|sV|��}|���dd�}d	||f}|j|d
d�}dd
d|j	|j
g}|j|dd�}	|	dkr�d}n�|	dk�r|�|�dd|j	|j
g}
|j|
dd�dk}|�sT|�
�td|����nP|	dk�r td|����n4|	dk�r<td|����n|	dk�rTtd|j��|�sr|�
�td|����d|j|��f}|�|�d|j	|j
dg}|j|d d�}
|
dk�r�|�d!�dS|
dk�r�td"��n<|
dk�r�td#|j��n"|
dk�rtd$��ntd%|j��dS)&a�Attempts to upload the archive to an SFTP location.

        Due to the lack of well maintained, secure, and generally widespread
        python libraries for SFTP, sos will shell-out to the system's local ssh
        installation in order to handle these uploads.

        Do not override this method with one that uses python-paramiko, as the
        upstream sos team will reject any PR that includes that dependency.
        ryzSFTP is not locally supportedrNzFSFTP upload requires python3-pexpect, which is not currently installedFzsftp://r3z%sftp -oStrictHostKeyChecking=no %s@%szutf-8)�encodingzsftp>z	password:zConnection refused��rMTrAzPermission denied�
z%Incorrect username or password for %s�z)Connection refused by %s. Incorrect port?�z#Timeout hit trying to connect to %s�z.Unexpected error trying to connect to sftp: %sz Unable to connect via SFTP to %sz	put %s %sz100%zNo such file or directory�ZbyezTimeout expired while uploadingzUnknown error during upload: %sz&Unable to write archive to destinationz#Unexpected response from server: %s)rrs�pexpect�ImportErrorrnrqri�replaceZspawnZTIMEOUTZEOFZexpectZsendline�closervZbeforere�_get_sftp_upload_name)r!rr�r�Zsftp_connectedZsftp_urlZsftp_cmdZretZsftp_expectsr#Zpass_expectsZput_cmdZput_expectsZput_successr&r&r'r{�s��

��
�
�
���
�






zLinuxPolicy.upload_sftpcCs*|j�d�d}|jr&tj�|j|�}|S)aIf a specific file name pattern is required by the SFTP server,
        override this method in the relevant Policy. Otherwise the archive's
        name on disk will be used

        :returns:       Filename as it will exist on the SFTP server
        :rtype:         ``str``
        rrT)rerNrcrrrG)r!�fnamer&r&r'r�5sz!LinuxPolicy._get_sftp_upload_namecCstj|��||��|d�S)z�If upload_https() needs to use requests.put(), use this method.

        Policies should override this method instead of the base upload_https()

        :param archive:     The open archive file object
        )�datar~�verify)r}�putrir�)r!rwr�r&r&r'�_upload_https_putBs�zLinuxPolicy._upload_https_putcCsiS)zJDefine any needed headers to be passed with the POST request here
        r&r,r&r&r'�_get_upload_headersMszLinuxPolicy._get_upload_headerscCs8d|j�d�d||��fi}tj|��||��|d�S)z�If upload_https() needs to use requests.post(), use this method.

        Policies should override this method instead of the base upload_https()

        :param archive:     The open archive file object
        �filerrT)�filesr~r�)rrNr�r}Zpostrir�)r!rwr�r�r&r&r'�_upload_https_postRs���zLinuxPolicy._upload_https_postc	Cs�tstd��t|jd���}|jdjdkr2|j}n|jdj}|jdjdk}|dkrd|�||�}n|�	||�}|j
dkr�|j
dkr�|j
d	kr�td
��td|j
|jf��W5QR�dSQRXd
S)z�Attempts to upload the archive to an HTTPS location.

        :returns: ``True`` if upload is successful
        :rtype: ``bool``

        :raises: ``Exception`` if upload was unsuccessful
        z7Unable to upload due to missing python requests library�rbr_�autoFr�����i�z/Authentication failed: invalid user credentialszPOST request returned %s: %sTN)�REQUESTS_LOADEDrsrYrer`Z
upload_method�_upload_methodZupload_no_ssl_verifyr�r�Zstatus_code�reason)r!Zarc�methodr�rSr&r&r'r|as&
�
�zLinuxPolicy.upload_httpsc
Cs�zddl}ddl}Wntk
r0td��YnX|s>|��}|dkrNtd��|�dd�}|sf|��}|sr|��}|s�|jp�|j	}z,|j
|||dd�}|s�td	��|�|�Wn�|jk
r�td
|��Yn�|j
k
r�td|��Yn�|jk
�rv}zft|���d}	|	dk�r*td
|��|	dk�r@td|��|	dk�rVtd|��tdt|���W5d}~XYnXzBt|jd��"}
|�d|j�d�d|
�W5QRX|��WdStk
�r�td��YnXdS)aTAttempts to upload the archive to either the policy defined or user
        provided FTP location.

        :param url: The URL to upload to
        :type url: ``str``

        :param directory: The directory on the FTP server to write to
        :type directory: ``str`` or ``None``

        :param user: The user to authenticate with
        :type user: ``str``

        :param password: The password to use for `user`
        :type password: ``str``

        :returns: ``True`` if upload is successful
        :rtype: ``bool``

        :raises: ``Exception`` if upload in unsuccessful
        rNzmissing python ftplib libraryzIno FTP server specified by policy, use --upload-url to specify a locationzftp://r3r�r�z3connection failed, did you set a user and password?z"timeout hit while connecting to %szunable to connect to %sZ503zcould not login as '%s'Z530zinvalid password for user '%s'Z550z$could not set upload directory to %sz%error trying to establish session: %sr�zSTOR %srrTTzcould not open archive file)�ftplib�socketr�rsrir�rnrqrc�_upload_directoryZFTP�cwdrMZgaierrorZ
error_perm�strrNrYreZ
storbinary�quitr[)r!rHZ	directoryrr�r�r�Zsession�err�errnoZ_arcfiler&r&r'rz�s`


���zLinuxPolicy.upload_ftpcCsdS)z�If sosreport commands need to always be prefixed with something,
        for example running in a specific container image, then it should be
        defined here.

        If no prefix should be set, return an empty string instead of None.
        r3r&r,r&r&r'�set_sos_prefix�szLinuxPolicy.set_sos_prefixcCsdS)zcIf a host requires additional cleanup, the command should be set and
        returned here
        r3r&r,r&r&r'�set_cleanup_cmd�szLinuxPolicy.set_cleanup_cmdcCsdS)aIReturns the command that will create the container that will be
        used for running commands inside a container on hosts that require it.

        This will use the container runtime defined for the host type to
        launch a container. From there, we use the defined runtime to exec into
        the container's namespace.

        :param image:   The name of the image if not using the policy default
        :type image:    ``str`` or ``None``

        :param auth:    The auth string required by the runtime to pull an
                        image from the registry
        :type auth:     ``str`` or ``None``

        :param force_pull:  Should the runtime forcibly pull the image
        :type force_pull:   ``bool``

        :returns:   The command to execute to launch the temp container
        :rtype:     ``str``
        r3r&)r!Zimager~Z
force_pullr&r&r'�create_sos_container�sz LinuxPolicy.create_sos_containercCsd|j|jfS)a�Restarts the container created for sos collect if it has stopped.

        This is called immediately after create_sos_container() as the command
        to create the container will exit and the container will stop. For
        current container runtimes, subsequently starting the container will
        default to opening a bash shell in the container to keep it running,
        thus allowing us to exec into it again.
        z%s start %s�Zcontainer_runtime�sos_container_namer,r&r&r'�restart_sos_container�s	�z!LinuxPolicy.restart_sos_containercCs |jrd|j|j|fS|SdS)aReturns the command that allows us to exec into the created
        container for sos collect.

        :param cmd: The command to run in the sos container
        :type cmd: ``str``

        :returns: The command to execute to run `cmd` in the container
        :rtype: ``str``
        z
%s exec %s %sNr�)r!�cmdr&r&r'�format_container_commands
�z$LinuxPolicy.format_container_command)NNTN)NN)NN)T)T)NNNN)NNF)@�__name__�
__module__�__qualname__rBr9�vendorrDr"rCr�rrr�r�rZ_preferred_hash_namerarbrdZ
containerizedZcontainer_imageZsos_path_stripZsos_pkg_nameZsos_bin_pathr�Zcontainer_version_commandZcontainer_authfiler�classmethodr)r-r.r/r1r2r6r=r7r:rrrXrmrjrkrxrtr�rirvrnrqr{r�r�r�r�r|rzr�r�r�r�r��
__classcell__r&r&r$r'r
&s��(



1/'
6
	
d


O	
r
c@seZdZdZdgZdZdZdS)�GenericLinuxPolicyz�This Policy will be returned if no other policy can be loaded. This
    should allow for IndependentPlugins to be executed on any system)zUpstream Projectz https://github.com/sosreport/sosZSoSaSoS was unable to determine that the distribution of this system is supported, and has loaded a generic configuration. This may not provide desired behavior, and users are encouraged to request a new distribution-specifc policy at the GitHub project above.
N)r�r�r�rBrEr�Zvendor_textr&r&r&r'r�sr�)rr4rZsosrrhZsos.policiesrZsos.policies.init_systemsrZ!sos.policies.init_systems.systemdrZsos.policies.runtimes.criorZsos.policies.runtimes.podmanrZsos.policies.runtimes.dockerr	Z
sos.utilitiesr
rrr}r�r�rIrKr
r�r&r&r&r'�<module>s0
r