2016-10-26 19:38:08 +02:00
|
|
|
#!/usr/bin/env python
|
2017-11-09 21:04:40 +01:00
|
|
|
# Copyright: (c) 2017, Ansible Project
|
|
|
|
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
2016-10-26 19:38:08 +02:00
|
|
|
from __future__ import (absolute_import, division, print_function)
|
|
|
|
|
2017-01-13 01:20:25 +01:00
|
|
|
__metaclass__ = type
|
2016-10-26 19:38:08 +02:00
|
|
|
__requires__ = ['ansible']
|
2017-01-13 01:20:25 +01:00
|
|
|
|
2016-10-26 19:38:08 +02:00
|
|
|
|
|
|
|
import fcntl
|
2018-08-10 15:26:58 +02:00
|
|
|
import hashlib
|
2016-10-26 19:38:08 +02:00
|
|
|
import os
|
|
|
|
import signal
|
|
|
|
import socket
|
|
|
|
import sys
|
2018-08-02 08:38:37 +02:00
|
|
|
import time
|
2016-10-26 19:38:08 +02:00
|
|
|
import traceback
|
2017-06-06 10:26:25 +02:00
|
|
|
import errno
|
2017-11-09 21:04:40 +01:00
|
|
|
import json
|
2016-10-26 19:38:08 +02:00
|
|
|
|
2018-04-25 22:00:15 +02:00
|
|
|
from contextlib import contextmanager
|
|
|
|
|
2016-10-26 19:38:08 +02:00
|
|
|
from ansible import constants as C
|
2018-07-31 03:55:42 +02:00
|
|
|
from ansible.module_utils._text import to_bytes, to_text
|
2017-05-12 18:13:51 +02:00
|
|
|
from ansible.module_utils.six import PY3
|
2018-01-24 22:18:45 +01:00
|
|
|
from ansible.module_utils.six.moves import cPickle, StringIO
|
2017-11-14 21:51:14 +01:00
|
|
|
from ansible.module_utils.connection import Connection, ConnectionError, send_data, recv_data
|
2017-11-09 21:04:40 +01:00
|
|
|
from ansible.module_utils.service import fork_process
|
2018-11-16 18:11:33 +01:00
|
|
|
from ansible.parsing.ajson import AnsibleJSONEncoder, AnsibleJSONDecoder
|
2016-10-26 19:38:08 +02:00
|
|
|
from ansible.playbook.play_context import PlayContext
|
2017-08-15 22:38:59 +02:00
|
|
|
from ansible.plugins.loader import connection_loader
|
2016-10-26 19:38:08 +02:00
|
|
|
from ansible.utils.path import unfrackpath, makedirs_safe
|
2017-03-21 04:08:02 +01:00
|
|
|
from ansible.utils.display import Display
|
2017-11-09 21:04:40 +01:00
|
|
|
from ansible.utils.jsonrpc import JsonRpcServer
|
2016-10-26 19:38:08 +02:00
|
|
|
|
2016-11-30 22:26:49 +01:00
|
|
|
|
2018-08-10 15:26:58 +02:00
|
|
|
def read_stream(byte_stream):
|
|
|
|
size = int(byte_stream.readline().strip())
|
|
|
|
|
|
|
|
data = byte_stream.read(size)
|
|
|
|
if len(data) < size:
|
|
|
|
raise Exception("EOF found before data was complete")
|
|
|
|
|
|
|
|
data_hash = to_text(byte_stream.readline().strip())
|
|
|
|
if data_hash != hashlib.sha1(data).hexdigest():
|
|
|
|
raise Exception("Read {0} bytes, but data did not match checksum".format(size))
|
|
|
|
|
|
|
|
# restore escaped loose \r characters
|
|
|
|
data = data.replace(br'\r', b'\r')
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
2018-04-25 22:00:15 +02:00
|
|
|
@contextmanager
|
|
|
|
def file_lock(lock_path):
|
|
|
|
"""
|
|
|
|
Uses contextmanager to create and release a file lock based on the
|
|
|
|
given path. This allows us to create locks using `with file_lock()`
|
|
|
|
to prevent deadlocks related to failure to unlock properly.
|
|
|
|
"""
|
|
|
|
|
|
|
|
lock_fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600)
|
|
|
|
fcntl.lockf(lock_fd, fcntl.LOCK_EX)
|
|
|
|
yield
|
|
|
|
fcntl.lockf(lock_fd, fcntl.LOCK_UN)
|
|
|
|
os.close(lock_fd)
|
|
|
|
|
|
|
|
|
2017-11-09 21:04:40 +01:00
|
|
|
class ConnectionProcess(object):
|
2016-10-26 19:38:08 +02:00
|
|
|
'''
|
2017-11-09 21:04:40 +01:00
|
|
|
The connection process wraps around a Connection object that manages
|
|
|
|
the connection to a remote device that persists over the playbook
|
2016-10-26 19:38:08 +02:00
|
|
|
'''
|
2017-12-15 05:51:56 +01:00
|
|
|
def __init__(self, fd, play_context, socket_path, original_path, ansible_playbook_pid=None):
|
2016-10-26 19:38:08 +02:00
|
|
|
self.play_context = play_context
|
2017-11-09 21:04:40 +01:00
|
|
|
self.socket_path = socket_path
|
|
|
|
self.original_path = original_path
|
2017-03-21 03:26:18 +01:00
|
|
|
|
2017-11-09 21:04:40 +01:00
|
|
|
self.fd = fd
|
|
|
|
self.exception = None
|
2016-11-30 22:26:49 +01:00
|
|
|
|
2017-11-09 21:04:40 +01:00
|
|
|
self.srv = JsonRpcServer()
|
|
|
|
self.sock = None
|
2017-03-14 15:31:02 +01:00
|
|
|
|
2017-11-22 16:30:06 +01:00
|
|
|
self.connection = None
|
2017-12-15 05:51:56 +01:00
|
|
|
self._ansible_playbook_pid = ansible_playbook_pid
|
2017-11-22 16:30:06 +01:00
|
|
|
|
2018-05-21 16:58:35 +02:00
|
|
|
def start(self, variables):
|
2017-11-09 21:04:40 +01:00
|
|
|
try:
|
|
|
|
messages = list()
|
|
|
|
result = {}
|
|
|
|
|
2018-12-19 16:54:42 +01:00
|
|
|
messages.append(('vvvv', 'control socket path is %s' % self.socket_path))
|
2017-11-09 21:04:40 +01:00
|
|
|
|
|
|
|
# If this is a relative path (~ gets expanded later) then plug the
|
|
|
|
# key's path on to the directory we originally came from, so we can
|
|
|
|
# find it now that our cwd is /
|
|
|
|
if self.play_context.private_key_file and self.play_context.private_key_file[0] not in '~/':
|
|
|
|
self.play_context.private_key_file = os.path.join(self.original_path, self.play_context.private_key_file)
|
2017-12-15 05:51:56 +01:00
|
|
|
self.connection = connection_loader.get(self.play_context.connection, self.play_context, '/dev/null',
|
|
|
|
ansible_playbook_pid=self._ansible_playbook_pid)
|
2018-05-21 16:58:35 +02:00
|
|
|
self.connection.set_options(var_options=variables)
|
2018-12-19 16:54:42 +01:00
|
|
|
|
2017-11-09 21:04:40 +01:00
|
|
|
self.connection._connect()
|
2018-07-31 06:53:44 +02:00
|
|
|
|
2017-11-22 16:30:06 +01:00
|
|
|
self.connection._socket_path = self.socket_path
|
2017-11-09 21:04:40 +01:00
|
|
|
self.srv.register(self.connection)
|
2018-12-19 16:54:42 +01:00
|
|
|
messages.extend([('vvvv', msg) for msg in sys.stdout.getvalue().splitlines()])
|
|
|
|
messages.append(('vvvv', 'connection to remote device started successfully'))
|
2017-11-09 21:04:40 +01:00
|
|
|
|
|
|
|
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
|
|
self.sock.bind(self.socket_path)
|
|
|
|
self.sock.listen(1)
|
2018-12-19 16:54:42 +01:00
|
|
|
messages.append(('vvvv', 'local domain socket listeners started successfully'))
|
2017-11-09 21:04:40 +01:00
|
|
|
except Exception as exc:
|
2018-12-20 22:38:59 +01:00
|
|
|
messages.extend(self.connection.pop_messages())
|
2017-11-09 21:04:40 +01:00
|
|
|
result['error'] = to_text(exc)
|
|
|
|
result['exception'] = traceback.format_exc()
|
|
|
|
finally:
|
|
|
|
result['messages'] = messages
|
2018-11-16 18:11:33 +01:00
|
|
|
self.fd.write(json.dumps(result, cls=AnsibleJSONEncoder))
|
2017-11-09 21:04:40 +01:00
|
|
|
self.fd.close()
|
2016-10-26 19:38:08 +02:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
try:
|
2017-11-22 16:30:06 +01:00
|
|
|
while self.connection.connected:
|
2017-06-06 10:26:25 +02:00
|
|
|
signal.signal(signal.SIGALRM, self.connect_timeout)
|
|
|
|
signal.signal(signal.SIGTERM, self.handler)
|
2018-05-16 14:59:01 +02:00
|
|
|
signal.alarm(self.connection.get_option('persistent_connect_timeout'))
|
2017-06-06 10:26:25 +02:00
|
|
|
|
2017-11-09 21:04:40 +01:00
|
|
|
self.exception = None
|
|
|
|
(s, addr) = self.sock.accept()
|
2017-06-06 10:26:25 +02:00
|
|
|
signal.alarm(0)
|
2016-10-26 19:38:08 +02:00
|
|
|
|
2017-11-09 21:04:40 +01:00
|
|
|
signal.signal(signal.SIGALRM, self.command_timeout)
|
2016-10-26 19:38:08 +02:00
|
|
|
while True:
|
|
|
|
data = recv_data(s)
|
|
|
|
if not data:
|
|
|
|
break
|
|
|
|
|
2018-07-20 06:34:53 +02:00
|
|
|
signal.alarm(self.connection.get_option('persistent_command_timeout'))
|
2017-11-09 21:04:40 +01:00
|
|
|
resp = self.srv.handle_request(data)
|
2016-11-30 22:26:49 +01:00
|
|
|
signal.alarm(0)
|
|
|
|
|
2017-11-09 21:04:40 +01:00
|
|
|
send_data(s, to_bytes(resp))
|
2017-06-06 10:26:25 +02:00
|
|
|
|
2016-10-26 19:38:08 +02:00
|
|
|
s.close()
|
2017-06-06 10:26:25 +02:00
|
|
|
|
2016-10-26 19:38:08 +02:00
|
|
|
except Exception as e:
|
2017-06-06 10:26:25 +02:00
|
|
|
# socket.accept() will raise EINTR if the socket.close() is called
|
2017-11-09 21:04:40 +01:00
|
|
|
if hasattr(e, 'errno'):
|
|
|
|
if e.errno != errno.EINTR:
|
|
|
|
self.exception = traceback.format_exc()
|
|
|
|
else:
|
|
|
|
self.exception = traceback.format_exc()
|
2017-06-06 10:26:25 +02:00
|
|
|
|
2016-10-26 19:38:08 +02:00
|
|
|
finally:
|
2018-08-02 08:38:37 +02:00
|
|
|
# allow time for any exception msg send over socket to receive at other end before shutting down
|
|
|
|
time.sleep(0.1)
|
|
|
|
|
|
|
|
# when done, close the connection properly and cleanup the socket file so it can be recreated
|
2017-06-06 10:26:25 +02:00
|
|
|
self.shutdown()
|
|
|
|
|
|
|
|
def connect_timeout(self, signum, frame):
|
2018-08-02 08:38:37 +02:00
|
|
|
msg = 'persistent connection idle timeout triggered, timeout value is %s secs.\nSee the timeout setting options in the Network Debug and ' \
|
|
|
|
'Troubleshooting Guide.' % self.connection.get_option('persistent_connect_timeout')
|
|
|
|
display.display(msg, log_only=True)
|
|
|
|
raise Exception(msg)
|
2017-06-06 10:26:25 +02:00
|
|
|
|
|
|
|
def command_timeout(self, signum, frame):
|
2018-08-02 08:38:37 +02:00
|
|
|
msg = 'command timeout triggered, timeout value is %s secs.\nSee the timeout setting options in the Network Debug and Troubleshooting Guide.'\
|
|
|
|
% self.connection.get_option('persistent_command_timeout')
|
|
|
|
display.display(msg, log_only=True)
|
|
|
|
raise Exception(msg)
|
2017-06-06 10:26:25 +02:00
|
|
|
|
|
|
|
def handler(self, signum, frame):
|
2018-08-02 08:38:37 +02:00
|
|
|
msg = 'signal handler called with signal %s.' % signum
|
|
|
|
display.display(msg, log_only=True)
|
|
|
|
raise Exception(msg)
|
2017-06-06 10:26:25 +02:00
|
|
|
|
|
|
|
def shutdown(self):
|
2017-11-09 21:04:40 +01:00
|
|
|
""" Shuts down the local domain socket
|
|
|
|
"""
|
2018-12-17 18:53:32 +01:00
|
|
|
lock_path = unfrackpath("%s/.ansible_pc_lock_%s" % os.path.split(self.socket_path))
|
2017-11-22 16:30:06 +01:00
|
|
|
if os.path.exists(self.socket_path):
|
|
|
|
try:
|
|
|
|
if self.sock:
|
|
|
|
self.sock.close()
|
|
|
|
if self.connection:
|
|
|
|
self.connection.close()
|
2018-09-08 02:59:46 +02:00
|
|
|
except Exception:
|
2017-11-22 16:30:06 +01:00
|
|
|
pass
|
|
|
|
finally:
|
|
|
|
if os.path.exists(self.socket_path):
|
|
|
|
os.remove(self.socket_path)
|
|
|
|
setattr(self.connection, '_socket_path', None)
|
|
|
|
setattr(self.connection, '_connected', False)
|
2018-12-17 18:53:32 +01:00
|
|
|
|
|
|
|
if os.path.exists(lock_path):
|
|
|
|
os.remove(lock_path)
|
|
|
|
|
2017-06-06 10:26:25 +02:00
|
|
|
display.display('shutdown complete', log_only=True)
|
|
|
|
|
2017-08-17 21:04:43 +02:00
|
|
|
|
2016-10-26 19:38:08 +02:00
|
|
|
def main():
|
2017-11-09 21:04:40 +01:00
|
|
|
""" Called to initiate the connect to the remote device
|
|
|
|
"""
|
|
|
|
rc = 0
|
|
|
|
result = {}
|
|
|
|
messages = list()
|
|
|
|
socket_path = None
|
|
|
|
|
2017-05-12 18:13:51 +02:00
|
|
|
# Need stdin as a byte stream
|
|
|
|
if PY3:
|
|
|
|
stdin = sys.stdin.buffer
|
|
|
|
else:
|
|
|
|
stdin = sys.stdin
|
2017-01-13 01:20:25 +01:00
|
|
|
|
2018-01-24 22:18:45 +01:00
|
|
|
# Note: update the below log capture code after Display.display() is refactored.
|
|
|
|
saved_stdout = sys.stdout
|
|
|
|
sys.stdout = StringIO()
|
|
|
|
|
2016-10-26 19:38:08 +02:00
|
|
|
try:
|
|
|
|
# read the play context data via stdin, which means depickling it
|
2018-08-10 15:26:58 +02:00
|
|
|
vars_data = read_stream(stdin)
|
|
|
|
init_data = read_stream(stdin)
|
2018-05-21 16:58:35 +02:00
|
|
|
|
2017-05-13 03:04:48 +02:00
|
|
|
if PY3:
|
|
|
|
pc_data = cPickle.loads(init_data, encoding='bytes')
|
2018-05-21 16:58:35 +02:00
|
|
|
variables = cPickle.loads(vars_data, encoding='bytes')
|
2017-05-13 03:04:48 +02:00
|
|
|
else:
|
|
|
|
pc_data = cPickle.loads(init_data)
|
2018-05-21 16:58:35 +02:00
|
|
|
variables = cPickle.loads(vars_data)
|
2016-10-26 19:38:08 +02:00
|
|
|
|
2017-11-09 21:04:40 +01:00
|
|
|
play_context = PlayContext()
|
|
|
|
play_context.deserialize(pc_data)
|
2018-02-13 16:59:37 +01:00
|
|
|
display.verbosity = play_context.verbosity
|
2017-06-06 10:26:25 +02:00
|
|
|
|
2016-10-26 19:38:08 +02:00
|
|
|
except Exception as e:
|
2017-11-09 21:04:40 +01:00
|
|
|
rc = 1
|
|
|
|
result.update({
|
|
|
|
'error': to_text(e),
|
|
|
|
'exception': traceback.format_exc()
|
|
|
|
})
|
|
|
|
|
|
|
|
if rc == 0:
|
|
|
|
ssh = connection_loader.get('ssh', class_only=True)
|
2017-12-15 05:51:56 +01:00
|
|
|
ansible_playbook_pid = sys.argv[1]
|
|
|
|
cp = ssh._create_control_path(play_context.remote_addr, play_context.port, play_context.remote_user, play_context.connection, ansible_playbook_pid)
|
2017-11-09 21:04:40 +01:00
|
|
|
|
|
|
|
# create the persistent connection dir if need be and create the paths
|
|
|
|
# which we will be using later
|
|
|
|
tmp_path = unfrackpath(C.PERSISTENT_CONTROL_PATH_DIR)
|
|
|
|
makedirs_safe(tmp_path)
|
|
|
|
|
|
|
|
socket_path = unfrackpath(cp % dict(directory=tmp_path))
|
2018-12-17 18:53:32 +01:00
|
|
|
lock_path = unfrackpath("%s/.ansible_pc_lock_%s" % os.path.split(socket_path))
|
2017-11-09 21:04:40 +01:00
|
|
|
|
2018-04-25 22:00:15 +02:00
|
|
|
with file_lock(lock_path):
|
|
|
|
if not os.path.exists(socket_path):
|
2018-12-19 16:54:42 +01:00
|
|
|
messages.append(('vvvv', 'local domain socket does not exist, starting it'))
|
2018-04-25 22:00:15 +02:00
|
|
|
original_path = os.getcwd()
|
|
|
|
r, w = os.pipe()
|
|
|
|
pid = fork_process()
|
2017-11-09 21:04:40 +01:00
|
|
|
|
2018-04-25 22:00:15 +02:00
|
|
|
if pid == 0:
|
|
|
|
try:
|
|
|
|
os.close(r)
|
|
|
|
wfd = os.fdopen(w, 'w')
|
|
|
|
process = ConnectionProcess(wfd, play_context, socket_path, original_path, ansible_playbook_pid)
|
2018-05-21 16:58:35 +02:00
|
|
|
process.start(variables)
|
2018-04-25 22:00:15 +02:00
|
|
|
except Exception:
|
2018-12-19 16:54:42 +01:00
|
|
|
messages.append(('error', traceback.format_exc()))
|
2018-04-25 22:00:15 +02:00
|
|
|
rc = 1
|
2017-11-09 21:04:40 +01:00
|
|
|
|
2018-04-25 22:00:15 +02:00
|
|
|
if rc == 0:
|
|
|
|
process.run()
|
2018-09-20 21:04:30 +02:00
|
|
|
else:
|
|
|
|
process.shutdown()
|
2017-11-09 21:04:40 +01:00
|
|
|
|
2018-04-25 22:00:15 +02:00
|
|
|
sys.exit(rc)
|
2017-11-09 21:04:40 +01:00
|
|
|
|
2018-04-25 22:00:15 +02:00
|
|
|
else:
|
|
|
|
os.close(w)
|
|
|
|
rfd = os.fdopen(r, 'r')
|
2018-11-16 18:11:33 +01:00
|
|
|
data = json.loads(rfd.read(), cls=AnsibleJSONDecoder)
|
2018-04-25 22:00:15 +02:00
|
|
|
messages.extend(data.pop('messages'))
|
|
|
|
result.update(data)
|
2016-10-26 19:38:08 +02:00
|
|
|
|
2017-11-09 21:04:40 +01:00
|
|
|
else:
|
2018-12-19 16:54:42 +01:00
|
|
|
messages.append(('vvvv', 'found existing local domain socket, using it!'))
|
2018-04-25 22:00:15 +02:00
|
|
|
conn = Connection(socket_path)
|
2018-07-20 06:34:53 +02:00
|
|
|
conn.set_options(var_options=variables)
|
2018-04-25 22:00:15 +02:00
|
|
|
pc_data = to_text(init_data)
|
|
|
|
try:
|
2018-12-19 16:54:42 +01:00
|
|
|
conn.update_play_context(pc_data)
|
2018-04-25 22:00:15 +02:00
|
|
|
except Exception as exc:
|
|
|
|
# Only network_cli has update_play context, so missing this is
|
|
|
|
# not fatal e.g. netconf
|
|
|
|
if isinstance(exc, ConnectionError) and getattr(exc, 'code', None) == -32601:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
result.update({
|
|
|
|
'error': to_text(exc),
|
|
|
|
'exception': traceback.format_exc()
|
|
|
|
})
|
2016-11-30 22:26:49 +01:00
|
|
|
|
2018-12-20 22:38:59 +01:00
|
|
|
if os.path.exists(socket_path):
|
|
|
|
messages.extend(Connection(socket_path).pop_messages())
|
2018-12-19 16:54:42 +01:00
|
|
|
messages.append(('vvvv', sys.stdout.getvalue()))
|
2017-11-09 21:04:40 +01:00
|
|
|
result.update({
|
|
|
|
'messages': messages,
|
|
|
|
'socket_path': socket_path
|
|
|
|
})
|
2016-10-26 19:38:08 +02:00
|
|
|
|
2018-01-24 22:18:45 +01:00
|
|
|
sys.stdout = saved_stdout
|
2017-11-09 21:04:40 +01:00
|
|
|
if 'exception' in result:
|
|
|
|
rc = 1
|
2018-11-16 18:11:33 +01:00
|
|
|
sys.stderr.write(json.dumps(result, cls=AnsibleJSONEncoder))
|
2017-11-09 21:04:40 +01:00
|
|
|
else:
|
|
|
|
rc = 0
|
2018-11-16 18:11:33 +01:00
|
|
|
sys.stdout.write(json.dumps(result, cls=AnsibleJSONEncoder))
|
2016-11-30 22:26:49 +01:00
|
|
|
|
2016-10-26 19:38:08 +02:00
|
|
|
sys.exit(rc)
|
|
|
|
|
2018-02-13 16:59:37 +01:00
|
|
|
|
2016-10-26 19:38:08 +02:00
|
|
|
if __name__ == '__main__':
|
2017-03-21 04:08:02 +01:00
|
|
|
display = Display()
|
2016-10-26 19:38:08 +02:00
|
|
|
main()
|