mirror of
https://github.com/ansible-collections/community.general.git
synced 2024-09-14 20:13:21 +02:00
replaces logging with display for network connection plugins (#22819)
* updates network_cli and netconf connection plugins * updates ansible-connection
This commit is contained in:
parent
ed7cace425
commit
e20ed8bc0c
3 changed files with 38 additions and 32 deletions
|
@ -50,8 +50,8 @@ from ansible.playbook.play_context import PlayContext
|
|||
from ansible.plugins import connection_loader
|
||||
from ansible.utils.path import unfrackpath, makedirs_safe
|
||||
from ansible.errors import AnsibleConnectionFailure
|
||||
from ansible.utils.display import Display
|
||||
|
||||
logger = logging.getLogger('ansible-connection')
|
||||
|
||||
def do_fork():
|
||||
'''
|
||||
|
@ -110,10 +110,6 @@ def recv_data(s):
|
|||
data += d
|
||||
return data
|
||||
|
||||
def log(msg, host, user=None):
|
||||
msg = 'h=%s u=%s %s' % (host, user, msg)
|
||||
logger.debug(msg)
|
||||
|
||||
|
||||
class Server():
|
||||
|
||||
|
@ -121,13 +117,12 @@ class Server():
|
|||
|
||||
self.path = path
|
||||
self.play_context = play_context
|
||||
self.log = lambda x: log(x, play_context.remote_addr, play_context.remote_user)
|
||||
|
||||
self.log("starting new persistent socket with path %s" % path)
|
||||
display.display("starting new persistent socket with path %s" % path, log_only=True)
|
||||
|
||||
self._start_time = datetime.datetime.now()
|
||||
|
||||
self.log("using connection plugin %s" % self.play_context.connection)
|
||||
display.display("using connection plugin %s" % self.play_context.connection, log_only=True)
|
||||
|
||||
self.conn = connection_loader.get(play_context.connection, play_context, sys.stdin)
|
||||
self.conn._connect()
|
||||
|
@ -135,7 +130,7 @@ class Server():
|
|||
raise AnsibleConnectionFailure('unable to connect to remote host')
|
||||
|
||||
connection_time = datetime.datetime.now() - self._start_time
|
||||
self.log('connection established in %s' % connection_time)
|
||||
display.display('connection established in %s' % connection_time, log_only=True)
|
||||
|
||||
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.socket.bind(path)
|
||||
|
@ -173,7 +168,7 @@ class Server():
|
|||
signal.alarm(C.PERSISTENT_CONNECT_TIMEOUT)
|
||||
try:
|
||||
(s, addr) = self.socket.accept()
|
||||
self.log('incoming request accepted on persistent socket')
|
||||
display.display('incoming request accepted on persistent socket', log_only=True)
|
||||
# clear the alarm
|
||||
# FIXME: potential race condition here between the accept and
|
||||
# time to this call.
|
||||
|
@ -191,7 +186,7 @@ class Server():
|
|||
rc = 255
|
||||
try:
|
||||
if data.startswith(b'EXEC: '):
|
||||
self.log("socket operation is EXEC")
|
||||
display.display("socket operation is EXEC", log_only=True)
|
||||
cmd = data.split(b'EXEC: ')[1]
|
||||
(rc, stdout, stderr) = self.conn.exec_command(cmd)
|
||||
elif data.startswith(b'PUT: ') or data.startswith(b'FETCH: '):
|
||||
|
@ -199,16 +194,16 @@ class Server():
|
|||
stdout = stderr = ''
|
||||
try:
|
||||
if op == 'FETCH:':
|
||||
self.log("socket operation is FETCH")
|
||||
display.display("socket operation is FETCH", log_only=True)
|
||||
self.conn.fetch_file(src, dst)
|
||||
elif op == 'PUT:':
|
||||
self.log("socket operation is PUT")
|
||||
display.display("socket operation is PUT", log_only=True)
|
||||
self.conn.put_file(src, dst)
|
||||
rc = 0
|
||||
except:
|
||||
pass
|
||||
elif data.startswith(b'CONTEXT: '):
|
||||
self.log("socket operation is CONTEXT")
|
||||
display.display("socket operation is CONTEXT", log_only=True)
|
||||
pc_data = data.split(b'CONTEXT: ')[1]
|
||||
|
||||
src = StringIO(pc_data)
|
||||
|
@ -221,7 +216,7 @@ class Server():
|
|||
self.dispatch(self.conn, 'update_play_context', pc)
|
||||
continue
|
||||
else:
|
||||
self.log("socket operation is UNKNOWN")
|
||||
display.display("socket operation is UNKNOWN", log_only=True)
|
||||
stdout = ''
|
||||
stderr = 'Invalid action specified'
|
||||
except:
|
||||
|
@ -230,20 +225,20 @@ class Server():
|
|||
|
||||
signal.alarm(0)
|
||||
|
||||
self.log("socket operation completed with rc %s" % rc)
|
||||
display.display("socket operation completed with rc %s" % rc, log_only=True)
|
||||
|
||||
send_data(s, to_bytes(str(rc)))
|
||||
send_data(s, to_bytes(stdout))
|
||||
send_data(s, to_bytes(stderr))
|
||||
s.close()
|
||||
except Exception as e:
|
||||
self.log(traceback.foramt_exec())
|
||||
display.display(traceback.foramt_exec(), log_only=True)
|
||||
finally:
|
||||
# when done, close the connection properly and cleanup
|
||||
# the socket file so it can be recreated
|
||||
end_time = datetime.datetime.now()
|
||||
delta = end_time - self._start_time
|
||||
self.log('shutting down control socket, connection was active for %s secs' % delta)
|
||||
display.display('shutting down control socket, connection was active for %s secs' % delta, log_only=True)
|
||||
try:
|
||||
self.conn.close()
|
||||
self.socket.close()
|
||||
|
@ -357,4 +352,5 @@ def main():
|
|||
sys.exit(rc)
|
||||
|
||||
if __name__ == '__main__':
|
||||
display = Display()
|
||||
main()
|
||||
|
|
|
@ -38,7 +38,12 @@ try:
|
|||
except ImportError:
|
||||
raise AnsibleError("ncclient is not installed")
|
||||
|
||||
logger = logging.getLogger('ansible.netconf')
|
||||
try:
|
||||
from __main__ import display
|
||||
except ImportError:
|
||||
from ansible.utils.display import Display
|
||||
display = Display()
|
||||
|
||||
logging.getLogger('ncclient').setLevel(logging.INFO)
|
||||
|
||||
class Connection(ConnectionBase):
|
||||
|
@ -51,7 +56,7 @@ class Connection(ConnectionBase):
|
|||
super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
|
||||
|
||||
self._network_os = self._play_context.network_os or 'default'
|
||||
self.log('network_os is set to %s' % self._network_os)
|
||||
display.display('network_os is set to %s' % self._network_os, log_only=True)
|
||||
|
||||
self._manager = None
|
||||
self._connected = False
|
||||
|
@ -63,7 +68,7 @@ class Connection(ConnectionBase):
|
|||
def _connect(self):
|
||||
super(Connection, self)._connect()
|
||||
|
||||
self.log('ssh connection done, stating ncclient')
|
||||
display.display('ssh connection done, stating ncclient', log_only=True)
|
||||
|
||||
allow_agent = True
|
||||
if self._play_context.password is not None:
|
||||
|
@ -95,7 +100,7 @@ class Connection(ConnectionBase):
|
|||
if not self._manager.connected:
|
||||
return (1, '', 'not connected')
|
||||
|
||||
self.log('ncclient manager object created successfully')
|
||||
display.display('ncclient manager object created successfully', log_only=True)
|
||||
|
||||
self._connected = True
|
||||
return (0, self._manager.session_id, '')
|
||||
|
|
|
@ -32,7 +32,12 @@ from ansible.plugins import terminal_loader
|
|||
from ansible.plugins.connection import ensure_connect
|
||||
from ansible.plugins.connection.paramiko_ssh import Connection as _Connection
|
||||
|
||||
logger = logging.getLogger('ansible.network_cli')
|
||||
try:
|
||||
from __main__ import display
|
||||
except ImportError:
|
||||
from ansible.utils.display import Display
|
||||
display = Display()
|
||||
|
||||
|
||||
class Connection(_Connection):
|
||||
''' CLI (shell) SSH connections on Paramiko '''
|
||||
|
@ -60,7 +65,7 @@ class Connection(_Connection):
|
|||
def update_play_context(self, play_context):
|
||||
"""Updates the play context information for the connection"""
|
||||
|
||||
self.log('updating play_context for connection')
|
||||
display.display('updating play_context for connection', log_only=True)
|
||||
|
||||
if self._play_context.become is False and play_context.become is True:
|
||||
auth_pass = play_context.become_pass
|
||||
|
@ -75,7 +80,7 @@ class Connection(_Connection):
|
|||
"""Connections to the device and sets the terminal type"""
|
||||
super(Connection, self)._connect()
|
||||
|
||||
self.log('ssh connection done, setting terminal')
|
||||
display.display('ssh connection done, setting terminal', log_only=True)
|
||||
|
||||
network_os = self._play_context.network_os
|
||||
if not network_os:
|
||||
|
@ -89,11 +94,11 @@ class Connection(_Connection):
|
|||
raise AnsibleConnectionFailure('network os %s is not supported' % network_os)
|
||||
|
||||
self._connected = True
|
||||
self.log('ssh connection has completed successfully')
|
||||
display.display('ssh connection has completed successfully', log_only=True)
|
||||
|
||||
@ensure_connect
|
||||
def open_shell(self):
|
||||
self.log('attempting to open shell to device')
|
||||
display.display('attempting to open shell to device', log_only=True)
|
||||
self._shell = self.ssh.invoke_shell()
|
||||
self._shell.settimeout(self._play_context.timeout)
|
||||
|
||||
|
@ -106,18 +111,18 @@ class Connection(_Connection):
|
|||
auth_pass = self._play_context.become_pass
|
||||
self._terminal.on_authorize(passwd=auth_pass)
|
||||
|
||||
self.log('shell successfully opened')
|
||||
display.display('shell successfully opened', log_only=True)
|
||||
return (0, 'ok', '')
|
||||
|
||||
def close(self):
|
||||
self.log('closing connection')
|
||||
display.display('closing connection', log_only=True)
|
||||
self.close_shell()
|
||||
super(Connection, self).close()
|
||||
self._connected = False
|
||||
|
||||
def close_shell(self):
|
||||
"""Closes the vty shell if the device supports multiplexing"""
|
||||
self.log('closing shell on device')
|
||||
display.display('closing shell on device', log_only=True)
|
||||
if self._shell:
|
||||
self._terminal.on_close_shell()
|
||||
|
||||
|
@ -161,7 +166,7 @@ class Connection(_Connection):
|
|||
return
|
||||
return self.receive(obj)
|
||||
except (socket.timeout, AttributeError) as exc:
|
||||
self.log(traceback.format_exc())
|
||||
display.display(traceback.format_exc(), log_only=True)
|
||||
raise AnsibleConnectionFailure("timeout trying to send command: %s" % command.strip())
|
||||
|
||||
def _strip(self, data):
|
||||
|
@ -213,7 +218,7 @@ class Connection(_Connection):
|
|||
|
||||
def alarm_handler(self, signum, frame):
|
||||
"""Alarm handler raised in case of command timeout """
|
||||
self.log('closing shell due to sigalarm')
|
||||
display.display('closing shell due to sigalarm', log_only=True)
|
||||
self.close_shell()
|
||||
|
||||
def exec_command(self, cmd):
|
||||
|
|
Loading…
Reference in a new issue