Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replaces logging with display for network connection plugins #22819

Merged
merged 1 commit into from
Mar 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 14 additions & 18 deletions bin/ansible-connection
Original file line number Diff line number Diff line change
Expand Up @@ -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():
'''
Expand Down Expand Up @@ -110,32 +110,27 @@ 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():

def __init__(self, path, play_context):

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()
if not self.conn.connected:
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)
Expand Down Expand Up @@ -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.
Expand All @@ -191,24 +186,24 @@ 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: '):
(op, src, dst) = shlex.split(to_native(data))
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)
Expand All @@ -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:
Expand All @@ -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()
Expand Down Expand Up @@ -357,4 +352,5 @@ def main():
sys.exit(rc)

if __name__ == '__main__':
display = Display()
main()
13 changes: 9 additions & 4 deletions lib/ansible/plugins/connection/netconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@
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):
Expand All @@ -51,7 +56,7 @@ def __init__(self, play_context, new_stdin, *args, **kwargs):
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
Expand All @@ -63,7 +68,7 @@ def log(self, msg):
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:
Expand Down Expand Up @@ -95,7 +100,7 @@ def _connect(self):
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, '')
Expand Down
25 changes: 15 additions & 10 deletions lib/ansible/plugins/connection/network_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@
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 '''
Expand Down Expand Up @@ -60,7 +65,7 @@ def log(self, msg):
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
Expand All @@ -75,7 +80,7 @@ def _connect(self):
"""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:
Expand All @@ -89,11 +94,11 @@ def _connect(self):
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)

Expand All @@ -106,18 +111,18 @@ def open_shell(self):
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()

Expand Down Expand Up @@ -161,7 +166,7 @@ def send(self, obj):
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):
Expand Down Expand Up @@ -213,7 +218,7 @@ def _find_prompt(self, response):

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):
Expand Down