U
    -_g;                     @   s(  d dl Z d dlZd dlmZ d dlmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZmZmZmZmZ zd dlZdZW n ek
r   dZY nX zd dlZd dlmZ  dZ!W n ek
r   dZ!Y nX dZ"dZ#dZ$G dd deZ%G dd de%Z&dS )    N)getpass)_sos)Policy)
InitSystem)SystemdInit)CrioContainerRuntime)PodmanContainerRuntime)DockerContainerRuntime)LxdContainerRuntime)	shell_outis_executableboldsos_get_command_outputTIMEOUT_DEFAULTTF)Configz/etc/os-releaseZ	containerZHOSTc                       s^  e Zd ZdZdZdZdZdZdZdZ	dZ
dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZd	Z dZ!dZ"dZ#d
Z$dZ%dZ&dZ'dq fdd	Z(e)dd Z*e)drddZ+dd Z,dd Z-dd Z.dd Z/dd Z0dd Z1e)dd  Z2e)d!d" Z3e)d#d$ Z4d%d& Z5d'd( Z6d)d* Z7d+d, Z8d-d. Z9d/d0 Z:d1d2 Z;d3d4 Z<d5d6 Z=d7d8 Z>d9d: Z?d;d< Z@d=d> ZAdsd?d@ZBdAdB ZCdCdD ZDdEdF ZEdGdH ZFdIdJ ZGdKdL ZHdMdN ZIdOdP ZJdQdR ZKdSdT ZLdUdV ZMdtdWdXZNdYdZ ZOdud[d\ZPd]d^ ZQdvd_d`ZRdadb ZSdwdcddZTdxdedfZUdgdh ZVdidj ZWdydkdlZXdmdn ZYdodp ZZ  Z[S )zLinuxPolicyzfThis policy is meant to be an abc class that provides common
    implementations used in Linux distrosNonez/bin:/sbin:/usr/bin:/usr/sbinN /zhttps://s3.amazonaws.comdockerFz/usr/binzsos-collector-tmpTc                    s   t  j|||d |r|| _n|  p(d| _|   |d k	rD|| _n$tjdr`t	| jd| _nt
 | _i | _| jrt| dt| dt| dt| dg}|D ]F}| r|| j|j< |j| jkr| j|j | jd< | j|j   q| jrd| jkrt| j }| j|d  | jd< d S )N)sysrootprobe_runtimeremote_execr   z/run/systemd/system/)chroot)Zpolicydefaultr   )super__init__r   _container_initinit_kernel_modulesZinit_systemospathisdirr   r   Zruntimesr   r   r	   r   r
   Zcheck_is_activenamedefault_container_runtimeZload_container_infolistkeys)selfr   initr   r   Z_crunZruntimeidx	__class__ ?/usr/lib/python3/dist-packages/sos/policies/distros/__init__.pyr   c   s:    zLinuxPolicy.__init__c                 C   s   ddgS )Nz/etc/passwdz/etc/shadowr+   clsr+   r+   r,   set_forbidden_paths   s    zLinuxPolicy.set_forbidden_pathsc              
      s    fdd}|r||S t j jrNt j jt jt j jkrNdS ttddd}|| W  5 Q R  S Q R X dS )|
        This function is responsible for determining if the underlying system
        is supported by this policy.
        c                    s`    j g} jr| j |  D ]8}|dr"|ddd  d d}||kr" dS q"dS )N)zNAME=zID==   r   z"'TF)os_release_nameos_release_idappend
splitlines
startswithsplitstrip)ZcontentZ_matcheslineZ_distror-   r+   r,   _check_release   s    
z)LinuxPolicy.check.<locals>._check_releaseTrutf-8encodingN)	r   r    isfileos_release_filebasenamerealpathopen
OS_RELEASEread)r.   remoter;   fr+   r-   r,   check   s    zLinuxPolicy.checkc                 C   s   | j S N)releaser&   r+   r+   r,   kernel_version   s    zLinuxPolicy.kernel_versionc                 C   s   | j S rJ   )ZhostnamerL   r+   r+   r,   	host_name   s    zLinuxPolicy.host_namec                 C   s   | j S rJ   )ZsmprL   r+   r+   r,   is_kernel_smp   s    zLinuxPolicy.is_kernel_smpc                 C   s   | j S rJ   )machinerL   r+   r+   r,   get_arch   s    zLinuxPolicy.get_archc                 C   s   |   S )z)Returns the name usd in the pre_work step)rN   rL   r+   r+   r,   get_local_name   s    zLinuxPolicy.get_local_namec                 C   s   t dd|S )Nz[^-a-z,A-Z.0-9]r   resub)r&   r"   r+   r+   r,   sanitize_filename   s    zLinuxPolicy.sanitize_filenamec                 C   s4   | t kr| | n|| j d | | d S )Nz Distribution Policy)r   display_self_help	set_titler3   display_distro_helpr.   sectionr+   r+   r,   display_help   s    zLinuxPolicy.display_helpc                 C   s   | d |d d S )NzSoS Distribution PolicieszDistributions supported by SoS will each have a specific policy defined for them, to ensure proper operation of SoS on those systems.)rX   add_textrZ   r+   r+   r,   rW      s    
zLinuxPolicy.display_self_helpc           	      C   s6  | j r | j tj k	r || j  n
|d | d d d}|d|j  |jd|j dd |jd|j dd |d}| jD ],}|jdd	|d
 d|d ddd q|d}|jtdd	dddddddd |j	
 D ]@\}}d|j }|jdd	|d|jd|ddd qd S )Nz;
Detailed help information for this policy is not availableFzDefault --upload location: zDefault container runtime: )newlinez $PATH used when running report: zReference URLs z>8r   z<30r2   z<40z#Presets Available With This Policy
zPreset Namez<20ZDescriptionz<45zEnabled Options)__doc__r   r]   _upload_urlr#   PATHZadd_sectionvendor_urlsr   ZpresetsitemsjoinZoptsZto_argsZdesc)	r.   r[   Z_polZrefsecurlZpresecZpresetvalueZ_optsr+   r+   r,   rY      sB    




*
zLinuxPolicy.display_distro_helpc                 C   s^   t tjkrZtjt  dkrZd| _ttjkrZtjt s6dS tjtjt | j | _tjt S dS )zCheck if sos is running in a container and perform container
        specific initialisation based on ENV_HOST_SYSROOT.
        )r   ZociZpodmanTN)ENV_CONTAINERr   environZ_in_containerENV_HOST_SYSROOTr    abspathZ_tmp_dirrL   r+   r+   r,   r      s    



zLinuxPolicy._container_initc              
   C   s  g | _ t j}tdd| jd }| j dd |dd D  | d| d	}zLt	|d
dd4}|D ](}|
dd 
dd }| j | qjW 5 Q R X W n4 tk
r } z| jd|  W 5 d}~X Y nX ddd}d| d| df}	|	D ]$}
| |
}
tj|
r|
} q0q| jd dS g }	zHt	|d
dd0}|D ]$}d|krJ|	|
dd  qJW 5 Q R X W n6 tk
r } z| jd|  W 5 d}~X Y nX | D ] \}}||	kr| j | qdS )zxObtain a list of loaded kernel modules to reference later for plugin
        enablement and SoSPredicate checks
        Zlsmodr   )timeoutr   c                 S   s   g | ]}|  d   qS )r   )r8   r9   ).0r:   r+   r+   r,   
<listcomp>  s    z3LinuxPolicy.init_kernel_modules.<locals>.<listcomp>r2   Nz/usr/lib/modules/z/modules.builtinr<   r=   r>   r   z.koz Unable to read kernel builtins: ZCONFIG_NET_DEVLINKZCONFIG_BLK_DEV_DM)ZdevlinkZdm_modz/boot/config-z/lib/modules/z/configz#Unable to find booted kernel configz=yz%Unable to read booted kernel config: )Zkernel_modsr   unamerK   r   r   r6   extendjoin_sysrootrD   r8   r5   IOErrorsoslogwarningr    existsrd   )r&   rK   linesbuiltinsZmfiler:   ZkmoderrZconfig_stringsZkconfigsZkconfigZbooted_configZkfileZbuiltinrg   r+   r+   r,   r     sP    


$


&$
zLinuxPolicy.init_kernel_modulesc                 C   s*   | j r&| j dkr&tj| j |d}|S )Nr   )r   r   r    re   lstrip)r&   r    r+   r+   r,   rr   K  s    zLinuxPolicy.join_sysrootc                 C   s8  | j d }|jr|jnd}|jr(|   |j| _|j| _|j| _|j| _d| _	|j
| _
|j| _|j| _|j| _|j| _|j| _|js|js|r|| j d _nttd| | j d _|jr|j| _|js4|js4|jr|  r|jdks|   |   n,|jdkr(|   |   |   |   | jd d S )Ncmdlineoptsr   zSOptionally, please enter the case id that you are generating this report for [%s]: s3)commonsZcase_idZlow_priority_configure_low_priority
upload_urlupload_userupload_directoryZupload_passupload_passwordupload_archive_nameupload_s3_endpointupload_s3_regionupload_s3_access_keyupload_s3_bucketupload_s3_object_prefixupload_s3_secret_keyZbatchquietinput_Zuploadget_upload_urlupload_protocolprompt_for_upload_userprompt_for_upload_passwordprompt_for_upload_s3_bucketprompt_for_upload_s3_endpointprompt_for_upload_s3_access_keyprompt_for_upload_s3_secret_keyui_loginfo)r&   Zcmdline_optsZcaseidr+   r+   r,   pre_workP  sR    

zLinuxPolicy.pre_workc              
   C   s   t  }tdrdtd| dd}|d dkr<| jd qpd|d	  d
|d  d}| j| n| jd zt 	d | jd W n4 t
k
r } z| jd|  W 5 d}~X Y nX dS )ay  Used to constrain sos to a 'low priority' execution, potentially
        letting individual policies set their own definition of what that is.

        By default, this will attempt to assign sos to an idle io class via
        ionice if available. We will also renice our own pid to 19 in order to
        not cause competition with other host processes for CPU time.
        Zionicezionice -c3 -p    rl   Zstatusr   zSet IO class to idlez Error setting IO class to idle: outputz (exit code )zNWarning: unable to constrain report to idle IO class: ionice is not available.   zSet niceness of report to 19z%Error setting report niceness to 19: N)r   getpidr   r   rt   r   errorr   ru   nice	Exception)r&   Z_pidretmsgry   r+   r+   r,   r~     s$     
z#LinuxPolicy._configure_low_priorityc                 C   s4   |   s0d|   d|   d}tt|| _dS )zvShould be overridden by policies to determine if an access key needs
        to be provided for upload or not
        z0Please provide the upload access key for bucket  via endpoint : N)get_upload_s3_access_keyget_upload_s3_bucketget_upload_s3_endpointr   r   r   r&   r   r+   r+   r,   r     s    z+LinuxPolicy.prompt_for_upload_s3_access_keyc                 C   s0   |   s,d|   d|   d}t|| _dS )zuShould be overridden by policies to determine if a secret key needs
        to be provided for upload or not
        z0Please provide the upload secret key for bucket r   r   N)get_upload_s3_secret_keyr   r   r   r   r   r+   r+   r,   r     s    z+LinuxPolicy.prompt_for_upload_s3_secret_keyc                 C   sH   | j sB| jr*| jdr*| jdd | _ nttd}|d| _ | j S )zqShould be overridden by policies to determine if a bucket needs to
        be provided for upload or not
        s3://r   Nz"Please provide the upload bucket: r   )r   r   r7   r   r   r9   )r&   
user_inputr+   r+   r,   r     s    z'LinuxPolicy.prompt_for_upload_s3_bucketc                 C   s>   | j }| js8d|   d| d}tt|}|p4|| _| jS )ztShould be overridden by policies to determine if an endpoint needs
        to be provided for upload or not
        z.Please provide the upload endpoint for bucket z (default: z): )_upload_s3_endpointr   r   r   r   )r&   Zdefault_endpointr   r   r+   r+   r,   r     s    
z)LinuxPolicy.prompt_for_upload_s3_endpointc                 C   s*   |   s&d|   d}tt|| _dS )zdShould be overridden by policies to determine if a user needs to
        be provided or not
        zPlease provide upload user for r   N)get_upload_userr   r   r   r   r   r+   r+   r,   r     s    z"LinuxPolicy.prompt_for_upload_userc                 C   s4   |   s0|  | jkr0d|   d}t|| _dS )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 r   N)get_upload_passwordr   _upload_userr   r   r   r+   r+   r,   r     s
    z&LinuxPolicy.prompt_for_upload_passwordc                 C   sL   || _ | js|  | _| js$td|  }| jtd|    | S )a
  
        Entry point for sos attempts to upload the generated archive to a
        policy or user specified location.

        Currently 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-urlzAttempting upload to )	r   r   r   r   _determine_upload_typer   r   r   get_upload_url_string)r&   archiveZupload_funcr+   r+   r,   upload_archive  s    ,
zLinuxPolicy.upload_archivec                 C   sv   | j | j| j| jd}| jd j|kr6|| jd j S d| jkrHtd| jd\}}||krntd| || S )a  Based 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
        )ZftpsftpZhttpsr|   r{   z://z#Must provide protocol in upload URLz&Unsupported or unrecognized protocol: )	
upload_ftpupload_sftpupload_https	upload_s3r}   r   r   r   r8   )r&   ZprotsZprotr   r+   r+   r,   r   #  s    
z"LinuxPolicy._determine_upload_typec                 C   s&   |s|   }|s|  }tj||S )ah  Formats 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 requests calls
        :rtype: ``requests.auth.HTTPBasicAuth()``
        )r   r   requestsauthZHTTPBasicAuth)r&   userpasswordr+   r+   r,   get_upload_https_auth9  s
    z!LinuxPolicy.get_upload_https_authc                 C   s   t ddp| jp| jS )zHelper function to determine if we should use the policy default
        upload access key or one provided by the user

        :returns: The access_key to use for upload
        :rtype: ``str``
        ZSOSUPLOADS3ACCESSKEYN)r   getenvr   _upload_s3_access_keyrL   r+   r+   r,   r   L  s
    z$LinuxPolicy.get_upload_s3_access_keyc                 C   s   | j s|   | j S )zHelper function to determine if we should use the policy default
        upload endpoint or one provided by the user

        :returns: The S3 Endpoint to use for upload
        :rtype: ``str``
        )r   r   rL   r+   r+   r,   r   W  s    z"LinuxPolicy.get_upload_s3_endpointc                 C   s   | j p
| jS )zHelper function to determine if we should use the policy default
        upload region or one provided by the user

        :returns: The S3 region to use for upload
        :rtype: ``str``
        )r   _upload_s3_regionrL   r+   r+   r,   get_upload_s3_regionb  s    z LinuxPolicy.get_upload_s3_regionc                 C   sb   | j rH| j drH| j dd dd}|d | _t|dkrH|d | _| jsV|   | jp`| jS )zHelper function to determine if we should use the policy default
        upload bucket or one provided by the user

        :returns: The S3 bucket to use for upload
        :rtype: ``str``
        r   r   Nr   r2   r   )r   r7   r8   r   lenr   r   _upload_s3_bucket)r&   Zbucket_and_prefixr+   r+   r,   r   k  s    

z LinuxPolicy.get_upload_s3_bucketc                 C   s   | j p
| jS )zHelper function to determine if we should use the policy default
        upload object prefix or one provided by the user

        :returns: The S3 object prefix to use for upload
        :rtype: ``str``
        )r   _upload_s3_object_prefixrL   r+   r+   r,   get_upload_s3_object_prefix{  s    z'LinuxPolicy.get_upload_s3_object_prefixc                 C   s   t ddp| jp| jS )zHelper function to determine if we should use the policy default
        upload secret key or one provided by the user

        :returns: The S3 secret key to use for upload
        :rtype: ``str``
        ZSOSUPLOADS3SECRETKEYN)r   r   r   _upload_s3_secret_keyrL   r+   r+   r,   r     s
    z$LinuxPolicy.get_upload_s3_secret_keyc                 C   sF   | j s:| jr:| jr:| jr:|  }|  }d| d| | _| j pD| jS )zHelper 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``
        r   r   )r   r   r   r   r   r   ra   )r&   bucketprefixr+   r+   r,   r     s    zLinuxPolicy.get_upload_urlc                 C   s   d}t |d|}|S )Nz([^:]+://[^:]+:)([^@]+)(@.+)z\1********\3rS   )r&   rf   patternZobfuscated_urlr+   r+   r,   _get_obfuscated_upload_url  s    z&LinuxPolicy._get_obfuscated_upload_urlc                 C   s   |  |  S )zUsed by distro policies to potentially change the string used to
        report upload location from the URL to a more human-friendly string
        )r   r   rL   r+   r+   r,   r     s    z!LinuxPolicy.get_upload_url_stringc                 C   s   t ddp| jp| jS )zHelper 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   r   r   r   rL   r+   r+   r,   r     s
    zLinuxPolicy.get_upload_userc                 C   s   t ddp| jp| jS )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``
        ZSOSUPLOADPASSWORDN)r   r   r   _upload_passwordrL   r+   r+   r,   r     s
    
zLinuxPolicy.get_upload_passwordc              
   C   s:  t dstdzddl}W n, tk
rH } ztd|W 5 d}~X Y nX d}|sZ|  }|sf|  }|  dd}d	| d
| }|j|dd}ddd|j	|j
g}	|j|	dd}
|
dkrd}n|
dkr|| dd|j	|j
g}|j|dddk}|sr|  td|   nX|
dkr:td|   dn8|
dkrXtd|   n|
dkrrtd|j |s|  td|   d| j d |   }|| d!|j	|j
d"g}|j|d#d}|dkr|d$ dS |dkrtd%|dkrtd&|j |dkr&td'td(|j dS ))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.
        r   zSFTP is not locally supportedr   NzFSFTP upload requires python3-pexpect, which is not currently installedFzsftp://r   z sftp -oStrictHostKeyChecking=no @r=   r>   zsftp>z	password:zConnection refused   r   Tr2   zPermission denied
   z#Incorrect username or password for    zConnection refused by z. Incorrect port?   z!Timeout hit trying to connect to    z,Unexpected error trying to connect to sftp: zUnable to connect via SFTP to zput r_   z100%zNo such file or directory   ZbyezTimeout expired while uploadingzUnknown error during upload: z&Unable to write archive to destinationz!Unexpected response from server: )r   r   pexpectImportErrorr   r   r   replaceZspawnZTIMEOUTZEOFZexpectZsendlinecloser   Zbeforer   _get_sftp_upload_name)r&   r   r   r   ry   Zsftp_connectedZsftp_urlZsftp_cmdr   Zsftp_expectsr(   Zpass_expectsZput_cmdZput_expectsZput_successr+   r+   r,   r     s~    










zLinuxPolicy.upload_sftpc                 C   s*   | j dd }| jr&tj| j|}|S )a  If 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``
        r   ro   )r   r8   r   r   r    re   )r&   fnamer+   r+   r,   r   '  s    z!LinuxPolicy._get_sftp_upload_namec                 C   s   t j|  ||  |tdS )zIf 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   verifyrl   )r   putr   r   r   )r&   r   r   r+   r+   r,   _upload_https_put4  s
     zLinuxPolicy._upload_https_putc                 C   s   i S )zJDefine any needed headers to be passed with the POST request here
        r+   rL   r+   r+   r,   _get_upload_headers?  s    zLinuxPolicy._get_upload_headersc                 C   s:   d|j dd ||  fi}tj|  ||  |tdS )zIf 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
        filer   ro   )filesr   r   rl   )r"   r8   r   r   Zpostr   r   r   )r&   r   r   r   r+   r+   r,   _upload_https_postD  s      zLinuxPolicy._upload_https_postc              	   C   s   t stdt| jd}| jd jdkr2| j}n| jd j}| jd jdk}|dkrd| ||}n| 	||}|j
dkr|j
dkrtd	td
|j
 d|j W 5 Q R  dS Q R X dS )zAttempts 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 credentialszPOST request returned r   TN)REQUESTS_LOADEDr   rD   r   r}   Zupload_method_upload_methodZupload_no_ssl_verifyr   r   Zstatus_codereason)r&   Zarcmethodr   r<   r+   r+   r,   r   S  s"    

zLinuxPolicy.upload_httpsc              
   C   s  ddl }ddl}|s|  }|dkr,td|dd}|sD|  }|sP|  }|s`| jp^| j}z.|j	|||dd}|std|
| W n  |jk
r } ztd	| |W 5 d}~X Y n |jk
r } ztd
| |W 5 d}~X Y n |jk
r } zzt| d }	|	dkr4td| d||	dkrPtd| d||	dkrjtd| |tdt| |W 5 d}~X Y nX t| jd$}
|d| jdd  |
 W 5 Q R X |  dS )aT  Attempts 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
        r   NzIno FTP server specified by policy, use --upload-url to specify a locationzftp://r   r   r   z3connection failed, did you set a user and password?z timeout hit while connecting to zunable to connect to Z503zcould not login as ''Z530zinvalid password for user 'Z550z"could not set upload directory to z#error trying to establish session: r   zSTOR r   ro   T)ftplibsocketr   r   r   r   r   r   _upload_directoryZFTPcwdrl   ZgaierrorZ
error_permstrr8   rD   r   Z
storbinaryquit)r&   rf   Z	directoryr   r   r   r   Zsessionry   errnoZ_arcfiler+   r+   r,   r   r  sT      


 zLinuxPolicy.upload_ftpc              
   C   s$  t std|s|  }|s$|  }|s6|  d}|s|  }|dkr`|dr`|dd }|dkr|ds|r| dnd}|s| 	 }|s| 
 }tdd}tjd|||||d	}z*|| jdd
  }	|| j||	 W dS  tk
r }
 ztdt|
 |
W 5 d}
~
X Y nX dS )a  Attempts to upload the archive to an S3 bucket.

        :param endpoint: The S3 endpoint to upload to
        :type endpoint: str

        :param region: The S3 region to upload to
        :type region: str

        :param bucket: The name of the S3 bucket to upload to
        :type bucket: str

        :param prefix: The prefix for the S3 object/key
        :type prefix: str

        :param access_key: The access key for the S3 bucket
        :type access_key: str

        :param secret_key: The secret key for the S3 bucket
        :type secret_key: str

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

        :raises: Exception if upload is unsuccessful
        z4Unable to upload due to missing python boto3 libraryr   r   r2   Nzapp/sos)Zuser_agent_extrar|   )Zendpoint_urlZregion_nameZaws_access_key_idZaws_secret_access_keyZconfigro   TzFailed to upload to S3: )BOTO3_LOADEDr   r   r   r   r9   r   r7   endswithr   r   BotocoreConfigboto3Zclientr   r8   Zupload_filer   )r&   ZendpointZregionr   r   Z
access_keyZ
secret_keyZboto3_configZ	s3_clientkeyer+   r+   r,   r     sD    
 zLinuxPolicy.upload_s3c                 C   s   dS )zIf sos report 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.
        r   r+   rL   r+   r+   r,   set_sos_prefix  s    zLinuxPolicy.set_sos_prefixc                 C   s   dS )zcIf a host requires additional cleanup, the command should be set and
        returned here
        r   r+   rL   r+   r+   r,   set_cleanup_cmd  s    zLinuxPolicy.set_cleanup_cmdc                 C   s   dS )aI  Returns 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``
        r   r+   )r&   Zimager   Z
force_pullr+   r+   r,   create_sos_container  s    z LinuxPolicy.create_sos_containerc                 C   s   | j  d| j S )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 start Zcontainer_runtimesos_container_namerL   r+   r+   r,   restart_sos_container#  s    
z!LinuxPolicy.restart_sos_containerc                 C   s"   | j r| j  d| j d| S |S )a  Returns 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 exec r_   r   )r&   cmdr+   r+   r,   format_container_command/  s    z$LinuxPolicy.format_container_command)NNTN)r   )NN)NN)T)T)NNNN)NNNNNN)NNF)\__name__
__module____qualname__r`   vendorrb   r'   rA   r3   r4   ra   r   r   r   r   r   r   r   r   r   r   r#   Z_preferred_hash_namer   r   r   r   r   r   r   r   r   ZcontainerizedZcontainer_imageZsos_path_stripZsos_pkg_nameZsos_bin_pathr   Zcontainer_version_commandZcontainer_authfiler   classmethodr/   rI   rM   rN   rO   rQ   rR   rV   r\   rW   rY   r   r   rr   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__r+   r+   r)   r,   r   2   s     )



*;6
8
		
c


F    
D	
r   c                   @   s,   e Zd ZdZdgZdZdZed	ddZdS )
GenericLinuxPolicyzThis Policy will be returned if no other policy can be loaded. This
    should allow for IndependentPlugins to be executed on any system)zUpstream Projectz https://github.com/sosreport/sosZSoSa  SoS 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.
r   c                 C   s   t dS )r0   N)NotImplementedError)r.   rG   r+   r+   r,   rI   L  s    zGenericLinuxPolicy.checkN)r   )	r   r   r  r`   rc   r  Zvendor_textr  rI   r+   r+   r+   r,   r  @  s   r  )'r   rT   r   Zsosr   r   Zsos.policiesr   Zsos.policies.init_systemsr   Z!sos.policies.init_systems.systemdr   Zsos.policies.runtimes.crior   Zsos.policies.runtimes.podmanr   Zsos.policies.runtimes.dockerr	   Zsos.policies.runtimes.lxdr
   Zsos.utilitiesr   r   r   r   r   r   r   r   r   Zbotocore.configr   r   r   rE   rh   rj   r   r  r+   r+   r+   r,   <module>   sF   

        