U
    -_gW\                     @   sN  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 d dlm	Z	m
Z
mZmZmZmZmZmZmZmZ d dlmZmZ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  d d
l!m"Z# zd dl$Z$dZ%W n e&k
r   dZ%Y nX dZ'G dd deZ(dZ)dZ*dZ+G dd de(Z,G dd de,Z-G dd de,Z.G dd de(Z/dS )    N)DeviceAuthorizationClass)RedHatPlugin)
RHEL_PRESETSRHVRHELCBRHOSPRHOCPRH_CFMERH_SATELLITEAAPEDAAAPCONTROLLER)LinuxPolicyENV_HOST_SYSROOT
OS_RELEASE)RpmPackageManager)FlatpakPackageManager)MultiPackageManager)boldconvert_bytesTIMEOUT_DEFAULT)_sosTFzRed Hat Enterprise Linuxc                       sz   e Zd ZdZddgZdZdZdZdZdZ	dZ
d	Zd
ZdZdZd fdd	Ze fddZdd Zdd Zdd Z  ZS )RedHatPolicyRed Hat)zDistribution Websitezhttps://www.redhat.com/)zCommercial Supportzhttps://access.redhat.com/z/var/tmpFZfriendlyNpodmansosz	/usr/sbinzVhttps://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/auth/devicezPhttps://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/tokenTc                    s   t  j||||d d| _tttg| j|d| _|  jt	g7  _| jj
| _| jsftjd td | | j| _| jrd| _nd| _|  jtjd 7  _|  jtjd	 7  _| js|   |   d S )
Nsysrootinitprobe_runtimeremote_execF)ZprimaryZ	fallbackschrootr    z'Could not obtain installed package list   z/usr/sbin:/usr/bin:/root/binz'/sbin:/bin:/usr/sbin:/usr/bin:/root/binz/usr/local/binz/usr/local/sbin)super__init__usrmover   r   r   r   package_managerZvalid_subclassesr   Zpackagespkgssysstderrwriteexitcheck_usrmovePATHospathsepr    Zset_exec_pathZload_presetsselfr   r   r   r    	__class__ =/usr/lib/python3/dist-packages/sos/policies/distros/redhat.pyr$   8   s2    


zRedHatPolicy.__init__c                    sz   | t k	rtt | | d S |d ttttd}| D ]8\}}t	d| }|jdd|d|j
ddd	 q<d S )
NzThis policy is a building block for all other Red Hat family distributions. You are likely looking for one of the distributions listed below.
)centosrhelZredhatcoreosfedoraz	policies. z>8z<35z<30F)newline)r   r#   display_distro_helpZadd_textCentOsPolicy
RHELPolicyRedHatCoreOSPolicyFedoraPolicyitemsr   os_release_name)clsZsectionZsubsZsubcvalueZsublnr2   r4   r5   r;   Z   s"    z RedHatPolicy.display_distro_helpc                 C   s8   d|kr t jdot jdS |d d }|d dkS )aq  Test whether the running system implements UsrMove.

            If the 'filesystem' package is present, it will check that the
            version is greater than 3. If the package is not present the
            '/bin' and '/sbin' paths are checked and UsrMove is assumed
            if both are symbolic links.

            :param pkgs: a packages dictionary
        Z
filesystemz/binz/sbinversionr   3)r.   pathislink)r1   r'   Zfilesys_versionr4   r4   r5   r,   s   s    
zRedHatPolicy.check_usrmovec                 C   s2   g }dd }| j r.|D ]}||| q|S |S )a2  Mangle paths for post-UsrMove systems.

            If the system implements UsrMove, all files will be in
            '/usr/[s]bin'. This method substitutes all the /[s]bin
            references in the 'files' list with '/usr/[s]bin'.

            :param files: the list of package managed files
        c                 S   s:   ddg}| |kr*| t jd| dd  fS tdd| fS )Nz/bin/rpmz
/bin/mailxz/usrr"   z(^)(/s?bin)z\1/usr\2)r.   rF   joinresub)rF   Z
skip_pathsr4   r4   r5   transform_path   s    z8RedHatPolicy.mangle_package_path.<locals>.transform_path)r%   extend)r1   filespathsrK   fr4   r4   r5   mangle_package_path   s    	z RedHatPolicy.mangle_package_pathc                 C   s   |s
| j S |S N)_tmp_dir)r1   Zopt_tmp_dirr4   r4   r5   get_tmp_dir   s    zRedHatPolicy.get_tmp_dir)NNTN)__name__
__module____qualname__vendorvendor_urlsrR   Z_in_containerZname_pattern
upload_urlupload_userZdefault_container_runtimeZsos_pkg_nameZsos_bin_pathclient_identifier_urltoken_endpointr$   classmethodr;   r,   rP   rS   __classcell__r4   r4   r2   r5   r   %   s,     "r   a[  
Any information provided to %(vendor)s will be treated in accordance with the published support policies at:

  %(vendor_urls)s

The generated archive may contain data considered sensitive and its content should be reviewed by the originating organization before being passed to any third party.

No changes will be made to system configuration.
zhttps://api.access.redhat.comzsftp://sftp.access.redhat.comc                       s   e Zd ZdZdZdZeZdZe	de
 d ZeZdZdZd	Zd' fdd	Zdd Zdd Zdd Zdd Zd(ddZdd Zdd Zdd Zd) fdd	Zdd  Z fd!d"Zd#d$ Zd%d& Z  ZS )*r=   at  
    The RHEL policy is used specifically for Red Hat Enterprise Linux, of
    any release, and not forks or derivative distributions. For example, this
    policy will be loaded for any RHEL 8 installation, but will not be loaded
    for CentOS Stream 8 or Red Hat CoreOS, for which there are separate
    policies.

    Plugins activated by installed packages will only be activated if those
    packages are installed via RPM (dnf/yum inclusive). Packages installed by
    other means are not considered by this policy.

    By default, --upload will be directed to using the SFTP location provided
    by Red Hat for technical support cases. Users who provide login credentials
    for their Red Hat Customer Portal account will have their archives uploaded
    to a user-specific directory.

    If users provide those credentials as well as a case number, --upload will
    instead attempt to directly upload archives to the referenced case, thus
    streamlining the process of providing data to technical support engineers.

    If either or both of the credentials or case number are omitted or are
    incorrect, then a temporary anonymous user will be used for upload to the
    SFTP server, and users will need to provide that information to their
    technical support engineer. This information will be printed at the end of
    the upload process for any sos report execution.
    r   z/etc/redhat-releaser7   a  This command will collect diagnostic and configuration information from this %(os_release_name)s system and installed applications.

An archive containing the collected information will be generated in %(tmpdir)s and may be provided to a %(vendor)s support representative.
%(vendor_text)s
postNi   @Tc                    s"   t  j||||d | t d S Nr   )r#   r$   Zregister_presetsr   r0   r2   r4   r5   r$      s
    
zRHELPolicy.__init__c                 C   s8   | j d jr| jtd | js4t| _| jd d S )NcmdlineoptszVThe option --upload-user has been deprecated in favour of device authorization in RHEL&No case id provided, uploading to SFTP)commonsrZ   ui_loginfo_case_idRH_SFTP_HOSTrY   r1   r4   r4   r5   prompt_for_upload_user   s    z!RHELPolicy.prompt_for_upload_userc                 C   s    | j d jr| jtd d S )Nrb   zVThe option --upload-pass has been deprecated in favour of device authorization in RHEL)rd   Zupload_passre   rf   rg   rj   r4   r4   r5   prompt_for_upload_password   s    z%RHELPolicy.prompt_for_upload_passwordc                 C   sf   | j r| j S | jd j r$| jd j S | jd jdkr8tS | jd jsT| jd tS d}t|| j  S )Nrb   Zsftprc   z /support/v1/cases/%s/attachments)rY   rd   Zupload_protocolri   rh   re   rf   RH_API_HOST)r1   Zrh_case_apir4   r4   r5   get_upload_url   s    zRHELPolicy.get_upload_urlc                 C   s   d| j  }d|iS )NzBearer ZAuthorization)_device_token)r1   Zstr_authr4   r4   r5   _get_upload_https_auth  s    z!RHELPolicy._get_upload_https_authc                 C   sh   d|j dd ||  fi}t| j| j}| | _| j	d| 
   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
        file//Device authorized correctly. Uploading file to )rM   headersverifytimeout)namesplit_get_upload_headersr   r[   r\   get_access_tokenro   re   rf   get_upload_url_stringrequestsr`   rn   rp   r   )r1   archiverv   rM   RHELAuthr4   r4   r5   _upload_https_post  s      
 zRHELPolicy._upload_https_postc                 C   s   |   trdddS i S )NZfalsezno-cache)Z	isPrivatezcache-control)rn   
startswithrm   rj   r4   r4   r5   rz   $  s    
zRHELPolicy._get_upload_headersc                 C   s0   |   trdS |   tr$dS | | jS )NzRed Hat Customer PortalzRed Hat Secure FTP)rn   r   rm   ri   Z_get_obfuscated_upload_urlrY   rj   r4   r4   r5   r|   )  s
    z RHELPolicy.get_upload_url_stringc                 C   s@   | j dd }| jr&| j d| }| jr<tj| j|}|S )zThe RH SFTP server will only automatically connect file uploads to
        cases if the filename _starts_ with the case number
        rr   rs   rg   )Zupload_archive_namery   rh   Zupload_directoryr.   rF   rH   )r1   fnamer4   r4   r5   _get_sftp_upload_name0  s    z RHELPolicy._get_sftp_upload_namec              
      s  t dd |  kr t  S ts,tdd}d}| jszt| j	| j
}W n: tk
r } zdt|krv| jd W 5 d}~X Y nX | | _| jr| jd|    td }d}| jr4|  }	tj||	d	d
}|jdkrt|jd }t|jd }n*| jd|j d|   | jd n~ddi}
tj|t|
d	d}|jdkrt|j}|d }|d }| jtd| d n| jd|j d|   |r|rt j||dS tddS )zOverride the base upload_sftp to allow for setting an on-demand
        generated anonymous login for the RH SFTP server if a username and
        password are not given
        z//r"   zPpython3-requests is not installed and is required for obtaining SFTP auth token.Nzend user deniedz:Device token authorization has been cancelled by the user.rt   z/support/v2/sftp/token
   )ru   rw      Zusernametokenz$DEBUG: auth attempt failed (status: z): zUUnable to retrieve Red Hat auth token using provided credentials. Will try anonymous.ZisAnonymousT)datarw   zUser z^ used for anonymous upload. Please inform your support engineer so they may retrieve the data.z)DEBUG: anonymous request failed (status: )userpasswordz1Could not retrieve valid or anonymous credentials)ri   ry   rn   r#   upload_sftpREQUESTS_LOADED	Exceptionro   r   r[   r\   strre   rf   r{   r|   rm   rp   r}   r`   Zstatus_codejsonloadstextdebugerrordumpsrg   )r1   r   r   Z_tokenZ_userr   eZurlZretru   ZadataZanonZrespr2   r4   r5   r   <  sb    

zRHELPolicy.upload_sftpc                 C   s>   t j|}|| jkr:| jtdt| j d t| _	d S )NzLSize of archive is bigger than Red Hat Customer Portal limit for uploads of z  via sos http upload. 
)
r.   rF   getsize_max_size_requestre   Zwarningrg   r   ri   rY   )r1   r~   sizer4   r4   r5   check_file_too_big  s    
zRHELPolicy.check_file_too_bigc              
      s   z(|   tr| | t |}W nb tk
r } zDd}| jtsL | j	t
d| dt  t| _t |}W 5 d}~X Y nX |S )zOverride the base upload_archive to provide for automatic failover
        from RHCP failures to the public RH dropbox
        Fz0Upload to Red Hat Customer Portal failed due to z	. Trying N)rn   r   rm   r   r#   upload_archiver   rY   re   r   rg   ri   )r1   r~   Zuploadedr   r2   r4   r5   r     s    
zRHELPolicy.upload_archivec                 C   sF   z,| j d}| j|d  d }t|d W S  tk
r@   Y nX dS )Nzredhat-release*r   rD   F)r&   all_pkgs_by_name_regexr'   intr   )r1   ZrrZpkgnamer4   r4   r5   dist_version  s    zRHELPolicy.dist_versionc                 C   s   dD ]&}| j | ddr| t  S q| dd k	rD| tS | dd k	r\| tS | dd k	rt| tS | dd k	s| dd k	r| tS | d	d k	r| t	S d
D ] }| |d k	r| t
  S q| tS )N)ZrescueZ	emergencyz.targetFzsatellite-commonzrhosp-releaseZcfmezovirt-engineZvdsmzautomation-controller-server)zautomation-eda-controllerz automation-eda-controller-server)Zinit_systemZ
is_runningfind_presetr   pkg_by_namer   r   r
   r   r   r   r   )r1   targetpkgr4   r4   r5   probe_preset  s&    




zRHELPolicy.probe_preset)NNTN)T)NN) rT   rU   rV   __doc__rW   os_release_fileRHEL_RELEASE_STRrA   os_release_idrg   disclaimer_textmsgri   Z_upload_urlZ_upload_methodro   r   r$   rk   rl   rn   rp   r   rz   r|   r   r   r   r   r   r   r^   r4   r4   r2   r5   r=      s<   	  
Kr=   c                   @   s"   e Zd ZdZdgZdZdZdZdS )r<   ZCentOS)Community Websitezhttps://www.centos.org/z/etc/centos-releasezCentOS Linuxr6   N)rT   rU   rV   rW   rX   r   rA   r   r4   r4   r4   r5   r<     s
   r<   c                       sv   e Zd ZdZdZede d ZdZdZ	dZ
dZd	Zd
Zd fdd	ZedddZdd ZdddZdd Z  ZS )r>   aB  
    Red Hat CoreOS is a containerized host built upon Red Hat Enterprise Linux
    and as such this policy is built on top of the RHEL policy. For users, this
    should be entirely transparent as any behavior exhibited or influenced on
    RHEL systems by that policy will be seen on RHCOS systems as well.

    The one change is that this policy ensures that sos collect will deploy a
    container on RHCOS systems in order to facilitate sos report collection,
    as RHCOS discourages non-default package installation via rpm-ostree which
    is used to maintain atomicity for RHCOS nodes. The default container image
    used by this policy is the support-tools image maintained by Red Hat on
    registry.redhat.io.

    Note that this policy is only loaded when sos is directly run on an RHCOS
    node - if sos collect uses the `oc` transport (the default transport that
    will be attempted by the ocp cluster profile), then the policy loaded
    inside the launched pod will be RHEL. Again, this is expected and will not
    impact how sos report collections are performed.
    zRed Hat Enterprise Linux CoreOSzThis command will collect diagnostic and configuration information from this %(os_release_name)s system.

An archive containing the collected information will be generated in %(tmpdir)s and may be provided to a %(vendor)s support representative.
r_   Tr   z&registry.redhat.io/rhel8/support-toolsz/hostz
rpm -q sosz/var/lib/kubelet/config.jsonNc                    s   t  j||||d d S ra   r#   r$   r0   r2   r4   r5   r$     s    
zRedHatCoreOSPolicy.__init__ c              	   C   s   |rd|kS d}t tjkr|S tjt  t }z>t|ddd&}|  D ]}|| j|kO }qJW 5 Q R X W n tk
r~   Y nX |S )NZCoreOSFrzutf-8)encoding)	r   r.   environr   openread
splitlinesrA   IOError)rB   ZremoteZcoreosZhost_releaseZhfileliner4   r4   r5   check  s    
zRedHatCoreOSPolicy.checkc                 C   s
   |  tS rQ   )r   r	   rj   r4   r4   r5   r     s    zRedHatCoreOSPolicy.probe_presetFc                 C   sL   |p| j }|rdnd}| j d| j d| j d| d| d|p@d d| S )Nz--pull=alwaysr   z run -di --name zE --privileged --ipc=host --net=host --pid=host -e HOST=/host -e NAME=z
 -e IMAGE=r9   zr -v /run:/run -v /var/log:/var/log -v /etc/machine-id:/etc/machine-id -v /etc/localtime:/etc/localtime -v /:/host )container_imagecontainer_runtimesos_container_name)r1   ZimageZauthZ
force_pullZ_imageZ_pullr4   r4   r5   create_sos_container  s    
4z'RedHatCoreOSPolicy.create_sos_containerc                 C   s   d| j  S )Nzpodman rm --force )r   rj   r4   r4   r5   set_cleanup_cmd,  s    z"RedHatCoreOSPolicy.set_cleanup_cmd)NNTN)r   )NNF)rT   rU   rV   r   rA   rg   r   r   Zcontainerizedr   r   Zsos_path_stripZcontainer_version_commandZcontainer_authfiler$   r]   r   r   r   r   r^   r4   r4   r2   r5   r>     s*   	  
r>   c                       sB   e Zd ZdZdZddgZdZdZdZd fd
d	Z	dd Z
  ZS )r?   aj  
    The policy for Fedora based systems, regardless of spin/edition. This
    policy is based on the parent Red Hat policy, and thus will only check for
    RPM packages when considering packaged-based plugin enablement. Packages
    installed by other sources are not considered.

    There is no default --upload location for this policy. If users need to
    upload an sos report archive from a Fedora system, they will need to
    provide the location via --upload-url, and optionally login credentials
    for that location via --upload-user and --upload-pass (or the appropriate
    environment variables).
    zthe Fedora Project)r   zhttps://fedoraproject.org/)zCommunity Forumsz%https://discussion.fedoraproject.org/z/etc/fedora-releasezFedora Linuxr8   NTc                    s   t  j||||d d S ra   r   r0   r2   r4   r5   r$   F  s    
zFedoraPolicy.__init__c                 C   s&   |  dp| jdd }t|d S )Nzfedora-releasezfedora-release-.*rs   rD   )r   r&   r   r   )r1   r   r4   r4   r5   fedora_versionL  s    
zFedoraPolicy.fedora_version)NNTN)rT   rU   rV   r   rW   rX   r   rA   r   r$   r   r^   r4   r4   r2   r5   r?   0  s     r?   )0r   r.   r(   rI   Zsos.policies.authr   Zsos.report.pluginsr   Zsos.presets.redhatr   r   r   r   r   r	   r
   r   r   r   Zsos.policies.distrosr   r   r   Z!sos.policies.package_managers.rpmr   Z%sos.policies.package_managers.flatpakr   Zsos.policies.package_managersr   Zsos.utilitiesr   r   r   r   r   rg   r}   r   ImportErrorr   r   r   rm   ri   r=   r<   r>   r?   r4   r4   r4   r5   <module>   s8   0
}   X