o
    *b¬+  ã                   @   s@   d dl Z d dlmZ d dlmZ d dlmZ G dd„ deƒZdS )é    N)Úquote)ÚCluster)Úis_executablec                       s˜   e Zd ZdZdZdZdZdZdZdZ	g d¢Z
dd	„ Zd
d„ Z‡ fdd„Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Z‡  ZS ) ÚocpaV  
    This profile is for use with OpenShift Container Platform (v4) clusters
    instead of the kubernetes profile.

    This profile will favor using the `oc` transport type, which means it will
    leverage a locally installed `oc` binary. This is also how node enumeration
    is done. To instead use SSH to connect to the nodes, use the
    '--transport=control_persist' option.

    Thus, a functional `oc` binary for the user executing sos collect is
    required. Functional meaning that the user can run `oc` commands with
    clusterAdmin privileges.

    If this requires the use of a secondary configuration file, specify that
    path with the 'kubeconfig' cluster option.

    Alternatively, provide a clusterAdmin access token either via the 'token'
    cluster option or, preferably, the SOSOCPTOKEN environment variable.

    By default, this profile will enumerate only master nodes within the
    cluster, and this may be changed by overriding the 'role' cluster option.
    To collect from all nodes in the cluster regardless of role, use the form
    -c ocp.role=''.

    Filtering nodes by a label applied to that node is also possible via the
    label cluster option, though be aware that this is _combined_ with the role
    option mentioned above.

    To avoid redundant collections of OCP API information (e.g. 'oc get'
    commands), this profile will attempt to enable the openshift plugin on only
    a single master node. If the none of the master nodes have a functional
    'oc' binary available, *and* the --no-local option is used, that means that
    no API data will be collected.
    zOpenShift Container Platform v4)zopenshift-hyperkubezopenshift-clientsFNzsos-collect-tmp))ÚlabelÚ z3Colon delimited list of labels to select nodes with)ÚroleÚmasterz*Colon delimited list of roles to filter on)Ú
kubeconfigr   zPath to the kubeconfig file)Útokenr   z1Service account token to use for oc authorizationc                 C   s$   |   d¡rd|   d¡|f S d| S )zcFormat the oc command to optionall include the kubeconfig file if
        one is specified
        r
   zoc --config %s %szoc %s)Ú
get_option)ÚselfÚcmd© r   ú</usr/lib/python3/dist-packages/sos/collector/clusters/ocp.pyÚ
fmt_oc_cmdE   s   
zocp.fmt_oc_cmdc                 C   s   |   d| j ¡}|d dkS )zXAttempt to login to the API using the oc command using a provided
        token
        z3oc login --insecure-skip-tls-verify=True --token=%sÚstatusr   )Úexec_primary_cmdr   )r   Z_resr   r   r   Ú_attempt_oc_loginM   s   ÿzocp._attempt_oc_loginc                    sT   t t| ƒ ¡ r	dS |  d¡pt dd ¡| _| jr|  ¡  |  d¡}|  	|¡d dkS )NTr   ÚSOSOCPTOKENZwhoamir   r   )
Úsuperr   Úcheck_enabledr   ÚosÚgetenvr   r   r   r   )r   Z_who©Ú	__class__r   r   r   U   s   
zocp.check_enabledc                 C   s   |   ¡ dksdS |  |  d¡¡}|d dk| _| js#|  d¡ tdƒ‚|  d| j ¡ |  d	| j ¡}|d dkr;d
S |  d|d  ¡ tdƒ‚)zpCreate the project that we will be executing in for any nodes'
        collection via a container image
        ÚocNzauth can-i '*' '*'r   r   zWCheck for cluster-admin privileges returned false, cannot create project in OCP clusterzLInsufficient permissions to create temporary collection project.
Aborting...z#Creating new temporary project '%s'zoc new-project %sTzFailed to create project: %sÚoutputz?Failed to create temporary project for collection. 
Aborting...)Úset_transport_typer   r   Úoc_cluster_adminZ	log_debugÚ	ExceptionÚlog_infoÚproject)r   ÚoutÚretr   r   r   Úsetup^   s   
z	ocp.setupc                 C   sH   | j r"|  d| j  ¡}|d dks|  d|d  ¡ |  d¡ d| _ dS )	z8Remove the project we created to execute within
        zoc delete project %sr   r   z$Error deleting temporary project: %sr   zoc project defaultNT)r"   r   Z	log_error)r   r$   r   r   r   Úcleanupv   s   ÿ
zocp.cleanupc           	   	   C   s˜   i }d|d v rJ|  d¡ ¡ }i }dD ]}z| | ¡ ¡||< W q ty)   Y qw |D ]}| ¡ }i ||d < |D ]}|||  ||d  |< q:q,|S )a‡  From the output of get_nodes(), construct an easier-to-reference
        dict of nodes that will be used in determining labels, primary status,
        etc...

        :param nodelist:        The split output of `oc get nodes`
        :type nodelist:         ``list``

        :returns:           A dict of nodes with `get nodes` columns as keys
        :rtype:             ``dict``
        ÚNAMEr   )r   ÚrolesÚversionzos-image)ÚpopÚsplitÚindexÚupperr    )	r   ZnodelistÚnodesZstatlineÚidxÚstateÚnodeZ_nodeÚcolumnr   r   r   Ú_build_dictƒ   s"   ÿÿzocp._build_dictc                 C   sJ   | j jdkr
| j jS tdƒrdS |  d¡ | j d¡ | j js#tdƒ dS )NÚautor   z]Local installation of 'oc' not found or is not correctly configured. Will use ControlPersist.z=Preferred transport 'oc' not available, will fallback to SSH.z?Press ENTER to continue connecting with SSH, or Ctrl+C toabort.Zcontrol_persist)ZoptsZ	transportr   r!   Úui_logÚwarnZbatchÚinput)r   r   r   r   r   Ÿ   s   
ÿzocp.set_transport_typec           
      C   s  g }i | _ d}|  d¡rd |  d¡ d¡¡}|dt|ƒ 7 }|  |  |¡¡}|d dkrt|  d¡d	kr9|  d
¡ dd„ |  d¡ d¡D ƒ}|  |d  	¡ ¡| _ | j  
¡ D ]\}}|rl|D ]}||d krj| |¡ q]qU| |¡ qU|S d}	d|d v r~d}	t|	ƒ‚)Nzget nodes -o wider   ú,ú:z -l %sr   r   r   r	   z‡NOTE: By default, only master nodes are listed.
To collect from all/more nodes, override the role option with '-c ocp.role=role1:role2'c                 S   s   g | ]}|‘qS r   r   )Ú.0Úrr   r   r   Ú
<listcomp>»   s    z!ocp.get_nodes.<locals>.<listcomp>r   r(   z'oc' command failedzMissing or incompleteza'oc' failed due to missing kubeconfig on primary node. Specify one via '-c ocp.kubeconfig=<path>')Ú	node_dictr   Újoinr+   r   r   r   Zlog_warnr3   Ú
splitlinesÚitemsÚappendr    )
r   r.   r   ÚlabelsÚresr(   Z	node_namer1   r   Úmsgr   r   r   Ú	get_nodes®   s2   


€þûzocp.get_nodesc                 C   s:   |j | jvrdS dD ]}|| j|j  d v r|  S q
dS )Nr   )r	   Zworkerr(   ©Úaddressr=   )r   r1   r   r   r   r   Úset_node_labelÌ   s   ÿzocp.set_node_labelc                 C   s$   |j | jvrdS d| j|j  d v S )NFr	   r(   rF   )r   Zsosnoder   r   r   Úcheck_node_is_primaryÔ   s   zocp.check_node_is_primaryc                 C   sü   |j  d¡ | jr|j d¡ d S d}|jjr$d}|jdddr$|d7 }|jd	| |jjdd
}|d dkr:d| _n,| jrG| j|j	d< d| _n|  
d¡rf|  
d¡}| |¡rf|jjr^d| }||j	d< d| _| jr|d|j }| j |¡ | j |¡ d S d S )NZ	openshiftúopenshift.no-oc=onr   z/host/bin/ocz/root/.kube/configT)Ú	need_rootz% --kubeconfig /host/root/.kube/configz	%s whoami)Zuse_containerrK   r   r   r   r
   z/host/%sZ
KUBECONFIGzcAPI collections will be performed on %s
Note: API collections may extend runtime by 10s of minutes
)Zenable_pluginsrA   Úapi_collect_enabledÚplugoptsZhostZcontainerizedZfile_existsZrun_commandr   Zsos_env_varsr   rG   ZsoslogÚinfor5   )r   r1   Z_oc_cmdZcan_ocZkcrD   r   r   r   Úset_primary_optionsÙ   s>   
û



þûzocp.set_primary_optionsc                 C   s   |j  d¡ d S )NrJ   )rM   rA   )r   r1   r   r   r   Úset_node_options  s   zocp.set_node_options)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Zcluster_nameZpackagesrL   r   r"   r   Zoption_listr   r   r   r%   r&   r3   r   rE   rH   rI   rO   rP   Ú__classcell__r   r   r   r   r      s*    #	+r   )r   Zpipesr   Zsos.collector.clustersr   Zsos.utilitiesr   r   r   r   r   r   Ú<module>   s
   
