3 ܓiA@sZddlZddlZddlZddlmZddlZddlmZmZddl m Z GdddZ dS)N)quote)ConnectionExceptionCommandTimeoutException)boldc@s eZdZdZdZdZddZddZdd Zd d Z d d Z e ddZ e ddZ e ddZeddZeddZddZddZddZddZd d!Ze d"d#Zd=d'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Zd7d8Z d9d:Z!d;d<Z"dS)>RemoteTransportaOThe base class used for defining supported remote transports to connect to remote nodes in conjunction with `sos collect`. This abstraction is used to manage the backend connections to nodes so that SoSNode() objects can be leveraged generically to connect to nodes, inspect those nodes, and run commands on them. Z undefinedNcCsF||_|d|_|d|_|d|_d|_tjd|_tjd|_dS)NZ cmdlineoptstmpdir need_sudoZsosZsos_ui) addressoptsrr _hostnameloggingZ getLoggersoslogZui_log)selfr Zcommonsr/usr/lib/python3.6/__init__.py__init__#s    zRemoteTransport.__init__cCsd}tj|d|S)zUAttempts to obfuscate sensitive information in log messages such as passwordsz>(?P(pass|key|secret|PASS|KEY|SECRET).*?=)(?P.*?\s)z\g****** )resub)rmsgZregrrr_sanitize_log_msg,sz!RemoteTransport._sanitize_log_msgcCs8tjdd}d|jd|d|}|jj|dS)z#Used to print and log info messages[:z] N)inspectstackhostnamer info)rrcallerlmsgrrrlog_info2szRemoteTransport.log_infocCs8tjdd}d|jd|d|}|jj|dS)z$Used to print and log error messagesrrrrz] N)rrrr error)rrrrrrr log_error8szRemoteTransport.log_errorcCsB|j|}tjdd}d|jd|d|}|jj|dS)z$Used to print and log debug messagesrrrrz] N)rrrrr debug)rrrrrr log_debug>s zRemoteTransport.log_debugcCs|jrd|jkr|jS|jS)NZ localhost)r r )rrrrrEszRemoteTransport.hostnamecCsdS)zIs the transport __currently__ connected to the node, or otherwise capable of seamlessly running a command or similar on the node? Fr)rrrr connectedKszRemoteTransport.connectedcCsdS)aThis is the command string needed to leverage the remote transport when executing commands. For example, for an SSH transport this would be the `ssh ` string prepended to any command so that the command is executed by the ssh binary. This is also referenced by the `remote_exec` parameter for policies when loading a policy for a remote node Nr)rrrr remote_execRs zRemoteTransport.remote_execcCs^|tkr|j|S|j|jjjddd|jrP|jtjk rP|j|jn |jddS)N_ z Transport Detailed Helpz5Detailed information not available for this transport)rdisplay_self_help set_titlenametitlereplace__doc__add_text)clssectionrrr display_help^s zRemoteTransport.display_helpcCs|jd|jdtdd|jdtdd|jdd d lm}xJ|D]B}td |}d |jd }|jdd|d|dddqRWdS)NzSoS Remote Transport Helpzb Transports define how SoS connects to nodes and executes commands on them for the purposes of an z sos collectz run. Generally, this means transports define how commands are wrapped locally so that they are executed on the remote node(s) instead.zTransports are generally selected by the cluster profile loaded for a given execution, however users may explicitly set one using 'z--transport=$transport_namezI'. Note that not all transports will function for all cluster/node types.zBy default, OpenSSH Control Persist is attempted. Additional information for each supported transport is available in the following help sections: r) TRANSPORTSzcollect.transports.zThe 'z ' transportr(z>8z<45z<30F)newline)r*r/rZsos.collector.sosnoder3lower)r0r1r3Z transportZ_secZ_descrrrr)ls   z!RemoteTransport.display_self_helpcCs |j|r|js|jdSdS)zPerform the connection steps in order to ensure that we are able to connect to the node for all future operations. Note that this should not provide an interactive shell at this time. TF)_connectr _get_hostname)rpasswordrrrconnects  zRemoteTransport.connectcCstd|jddS)zActually perform the connection requirements. Should be overridden by specific transports that subclass RemoteTransport z Transport z does not define connectN)NotImplementedErrorr+)rr8rrrr6szRemoteTransport._connectcCsd}d}xv|dkr~|jd|dy|j|r4dSWn<tk rr}z |jd|d||}WYd d }~XnX|d7}q W|jd td |d S) zAttempts to reconnect to the node using the standard connect() but does not do so indefinitely. This imposes a strict number of retry attempts before failing out runknownzAttempting reconnect (#z ) to nodeTz Attempt #z exception: Nz7Unable to reconnect to node after 5 attempts, aborting.zlast exception from transport: )r$r9 Exceptionr"r)rr8attemptsZlast_errerrrrr reconnects    zRemoteTransport.reconnectcCsZy"|jr|jdn |jdWn2tk rT}z|jd|WYdd}~XnXdS)zfPerform whatever steps are necessary, if any, to terminate any connection to the node z#Successfully disconnected from nodez;Unable to successfully disconnect, see log for more detailszFailed to disconnect: N) _disconnectr$r"r=)rr?rrr disconnects  zRemoteTransport.disconnectcCstd|jddS)Nz Transport z does not define disconnect)r:r+)rrrrrAszRemoteTransport._disconnectcCsdS)z Transports may override this to control when/if commands executed over the transport needs to utilize a shell on the remote host. Fr)rrrr _need_shellszRemoteTransport._need_shellFautocCsX|jd||dks*|dkr&|jndrHdt|}|jd||j||||S)aRun a command on the node, returning its output and exit code. This should return the exit code of the command being executed, not the exit code of whatever mechanism the transport uses to execute that command :param cmd: The command to run :type cmd: ``str`` :param timeout: The maximum time in seconds to allow the cmd to run :type timeout: ``int``` :param need_root: Does ``cmd`` require root privileges? :type need_root: ``bool`` :param env: Specify env vars to be passed to the ``cmd`` :type env: ``dict`` :param use_shell: Does ``cmd`` require execution within a shell? :type use_shell: ``bool`` or ``auto`` for transport-determined :returns: Output of ``cmd`` and the exit code :rtype: ``dict`` with keys ``output`` and ``status`` zRunning command TrEFz /bin/bash -c z Shell requested, command is now )r$rCr_run_command_with_pexpect)rcmdtimeout need_rootenvZ use_shellrrr run_commands zRemoteTransport.run_commandcCs |jdt|}|j}|S)aFormat the command in the way needed for the remote transport to successfully execute it as one would when manually executing it :param cmd: The command being executed, as formatted by SoSNode :type cmd: ``str`` :returns: The command further formatted as needed by this transport :rtype: ``str`` r()r&rlstrip)rrGrrr_format_cmd_for_execs z$RemoteTransport._format_cmd_for_execc Cs |j|}|sd}ytj|d|d}Wn6tjjk r\}z|j|jdddSd}~XnXtjtjg}|r|j j dkr|j dd g|j ||d }|dkr|j |||j ||d }|d kr|j} |j|j| dS|dkrt||jd|d|dddS)aExecute the command using pexpect, which allows us to more easily handle prompts and timeouts compared to directly leveraging the subprocess.Popen() method. :param cmd: The command to execute. This will be automatically formatted to use the transport. :type cmd: ``str`` :param timeout: The maximum time in seconds to run ``cmd`` :type timeout: ``int`` :param need_root: Does ``cmd`` need to run as root or with sudo? :type need_root: ``bool`` :param env: Any env vars that ``cmd`` should be run with :type env: ``dict`` Nzutf-8)encodingrJ)statusoutputrootz\[sudo\] password for .*:z Password:)rHrrrzUnexpected index z from pexpect: i)rTr)rMpexpectZspawn exceptionsZExceptionPexpectr$valueZEOFZTIMEOUTr Zssh_userextendexpect_send_pexpect_passwordZbeforecloseZ exitstatusr) rrGrHrIrJresultr?Z_expectsindexoutrrrrFs2     z)RemoteTransport._run_command_with_pexpectcCsz|dkrB|jj r2|jj r2d}|j|t||j|jjn4|dkrv|jjshd}|j|t||j|jjdS)a`Handle password prompts for sudo and su usage for non-root SSH users :param index: The index pexpect.spawn returned to match against either a sudo or su prompt :type index: ``int`` :param result: The spawn running the command :type result: ``pexpect.spawn`` rTz>Unable to run command: sudo password required but not providedrz5Unable to run command as root: no root password givenN)r Zsudo_pwZ nopasswd_sudor"r=ZsendlineZ root_password)rr]r\rrrrrZ;s   z&RemoteTransport._send_pexpect_passwordcCsJ|jd}|ddkr$|dj|_|js2|j|_|jd|j|jS)zDetermine the hostname of the node and set that for future reference and logging :returns: The hostname of the system, per the `hostname` command :rtype: ``str`` rrQrrRzHostname set to )rKstripr r r )rZ_outrrrr7Ss  zRemoteTransport._get_hostnamecCsd}yJx:|dkr@|d7}|j||}|r,dS|jd|dqW|jddStk r}z&|jd |d |d ||WYd d }~XnXd S) aZCopy a local file, fname, to dest on the remote node :param fname: The name of the file to copy :type fname: ``str`` :param dest: Where to save the file to remotely :type dest: ``str`` :returns: True if file was successfully copied to remote, or False :rtype: ``bool`` rrrTzFile copy attempt z failedz!File copy failed after 3 attemptsFz1Exception encountered during config copy attempt z for z: N)_copy_file_to_remoter r=r")rfnamedestr>retr?rrrcopy_file_to_remotecs    z#RemoteTransport.copy_file_to_remotecCstd|jddS)Nz Transport z does not support file copying)r:r+)rrarbrrrr`~sz$RemoteTransport._copy_file_to_remotecCsd}yJx:|dkr@|d7}|j||}|r,dS|jd|dqW|jddStk r}z&|jd |d |d ||WYd d }~XnXd S) a_Copy a remote file, fname, to dest on the local node :param fname: The name of the file to retrieve :type fname: ``str`` :param dest: Where to save the file to locally :type dest: ``str`` :returns: True if file was successfully copied from remote, or False :rtype: ``bool`` rr<rTzFile retrieval attempt z failedz&File retrieval failed after 5 attemptsFz/Exception encountered during retrieval attempt z for z: N)_retrieve_filer r=r")rrarbr>rcr?rrr retrieve_files    zRemoteTransport.retrieve_filecCstd|jddS)Nz Transport z does not support file copying)r:r+)rrarbrrrreszRemoteTransport._retrieve_filecCs|jd||j|S)zRead the given file fname and return its contents :param fname: The name of the file to read :type fname: ``str`` :returns: The content of the file :rtype: ``str`` z Reading file )r$ _read_file)rrarrr read_files zRemoteTransport.read_filecCst|jd|dd}|ddkr(|dSd|dkrH|jd|d n(|jd |d |djd d ddS)Nzcat )rHrQrrRz No such filezFile z does not exist on nodezError reading z: rrrP)rKr$r"split)rraresrrrrgs  (zRemoteTransport._read_file)rDFNrE)#__name__ __module__ __qualname__r.r+Z default_userrrr r"r$propertyrr%r& classmethodr2r)r9r6r@rBrArCrKrMrFrZr7rdr`rfrerhrgrrrrrs>     !    %9 r) rr rZshlexrrUZsos.collector.exceptionsrrZ sos.utilitiesrrrrrr s