Debian Codegraph @

lib/ansible/cli/scripts/ansible_connection_cli_stub.py

raw
1 # Copyright: (c) 2017, Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3 from __future__ import annotations
4
5 import fcntl
6 import io
7 import os
8 import pickle
9 import signal
10 import socket
11 import sys
12 import time
13 import traceback
14 import errno
15 import json
16
17 from contextlib import contextmanager
18
19 from ansible import constants as C
20 from ansible.cli.arguments import option_helpers as opt_help
21 from ansible.module_utils.common.text.converters import to_bytes, to_text
22 from ansible.module_utils.connection import Connection, ConnectionError, send_data, recv_data
23 from ansible.module_utils.service import fork_process
24 from ansible.module_utils._internal._json._profiles import _tagless
25 from ansible.playbook.play_context import PlayContext
26 from ansible.plugins.loader import connection_loader, init_plugin_loader
27 from ansible.utils.path import unfrackpath, makedirs_safe
28 from ansible.utils.display import Display
29 from ansible.utils.jsonrpc import JsonRpcServer
30
31 display = Display()
32
33
34 def read_stream(byte_stream):
35 size = int(byte_stream.readline().strip())
36
37 data = byte_stream.read(size)
38 if len(data) < size:
39 raise Exception("EOF found before data was complete")
40
41 return data
42
43
44 @contextmanager
45 def file_lock(lock_path):
46 """
47 Uses contextmanager to create and release a file lock based on the
48 given path. This allows us to create locks using `with file_lock()`
49 to prevent deadlocks related to failure to unlock properly.
50 """
51
52 lock_fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600)
53 fcntl.lockf(lock_fd, fcntl.LOCK_EX)
54 yield
55 fcntl.lockf(lock_fd, fcntl.LOCK_UN)
56 os.close(lock_fd)
57
58
59 class ConnectionProcess(object):
60 """
61 The connection process wraps around a Connection object that manages
62 the connection to a remote device that persists over the playbook
63 """
64 def __init__(self, fd, play_context, socket_path, original_path, task_uuid=None, ansible_playbook_pid=None):
65 self.play_context = play_context
66 self.socket_path = socket_path
67 self.original_path = original_path
68 self._task_uuid = task_uuid
69
70 self.fd = fd
71 self.exception = None
72
73 self.srv = JsonRpcServer()
74 self.sock = None
75
76 self.connection = None
77 self._ansible_playbook_pid = ansible_playbook_pid
78
79 def start(self, options):
80 messages = list()
81 result = {}
82
83 try:
84 messages.append(('vvvv', 'control socket path is %s' % self.socket_path))
85
86 # If this is a relative path (~ gets expanded later) then plug the
87 # key's path on to the directory we originally came from, so we can
88 # find it now that our cwd is /
89 if self.play_context.private_key_file and self.play_context.private_key_file[0] not in '~/':
90 self.play_context.private_key_file = os.path.join(self.original_path, self.play_context.private_key_file)
91 self.connection = connection_loader.get(self.play_context.connection, self.play_context, '/dev/null',
92 task_uuid=self._task_uuid, ansible_playbook_pid=self._ansible_playbook_pid)
93 try:
94 self.connection.set_options(direct=options)
95 except ConnectionError as exc:
96 messages.append(('debug', to_text(exc)))
97 raise ConnectionError('Unable to decode JSON from response set_options. See the debug log for more information.')
98
99 self.connection._socket_path = self.socket_path
100 self.srv.register(self.connection)
101 messages.extend([('vvvv', msg) for msg in sys.stdout.getvalue().splitlines()])
102
103 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
104 self.sock.bind(self.socket_path)
105 self.sock.listen(1)
106 messages.append(('vvvv', 'local domain socket listeners started successfully'))
107 except Exception as exc:
108 messages.extend(self.connection.pop_messages())
109 result['error'] = to_text(exc)
110 result['exception'] = traceback.format_exc()
111 finally:
112 result['messages'] = messages
113 self.fd.write(json.dumps(result, cls=_tagless.Encoder))
114 self.fd.close()
115
116 def run(self):
117 try:
118 log_messages = self.connection.get_option('persistent_log_messages')
119 while not self.connection._conn_closed:
120 signal.signal(signal.SIGALRM, self.connect_timeout)
121 signal.signal(signal.SIGTERM, self.handler)
122 signal.alarm(self.connection.get_option('persistent_connect_timeout'))
123
124 self.exception = None
125 (s, addr) = self.sock.accept()
126 signal.alarm(0)
127 signal.signal(signal.SIGALRM, self.command_timeout)
128 while True:
129 data = recv_data(s)
130 if not data:
131 break
132
133 if log_messages:
134 display.display("jsonrpc request: %s" % data, log_only=True)
135
136 request = json.loads(to_text(data, errors='surrogate_or_strict'))
137 if request.get('method') == "exec_command" and not self.connection.connected:
138 self.connection._connect()
139
140 signal.alarm(self.connection.get_option('persistent_command_timeout'))
141
142 resp = self.srv.handle_request(data)
143 signal.alarm(0)
144
145 if log_messages:
146 display.display("jsonrpc response: %s" % resp, log_only=True)
147
148 send_data(s, to_bytes(resp))
149
150 s.close()
151
152 except Exception as e:
153 # socket.accept() will raise EINTR if the socket.close() is called
154 if hasattr(e, 'errno'):
155 if e.errno != errno.EINTR:
156 self.exception = traceback.format_exc()
157 else:
158 self.exception = traceback.format_exc()
159
160 finally:
161 # allow time for any exception msg send over socket to receive at other end before shutting down
162 time.sleep(0.1)
163
164 # when done, close the connection properly and cleanup the socket file so it can be recreated
165 self.shutdown()
166
167 def connect_timeout(self, signum, frame):
168 msg = 'persistent connection idle timeout triggered, timeout value is %s secs.\nSee the timeout setting options in the Network Debug and ' \
169 'Troubleshooting Guide.' % self.connection.get_option('persistent_connect_timeout')
170 display.display(msg, log_only=True)
171 raise Exception(msg)
172
173 def command_timeout(self, signum, frame):
174 msg = 'command timeout triggered, timeout value is %s secs.\nSee the timeout setting options in the Network Debug and Troubleshooting Guide.'\
175 % self.connection.get_option('persistent_command_timeout')
176 display.display(msg, log_only=True)
177 raise Exception(msg)
178
179 def handler(self, signum, frame):
180 msg = 'signal handler called with signal %s.' % signum
181 display.display(msg, log_only=True)
182 raise Exception(msg)
183
184 def shutdown(self):
185 """ Shuts down the local domain socket
186 """
187 lock_path = unfrackpath("%s/.ansible_pc_lock_%s" % os.path.split(self.socket_path))
188 if os.path.exists(self.socket_path):
189 try:
190 if self.sock:
191 self.sock.close()
192 if self.connection:
193 self.connection.close()
194 if self.connection.get_option("persistent_log_messages"):
195 for _level, message in self.connection.pop_messages():
196 display.display(message, log_only=True)
197 except Exception:
198 pass
199 finally:
200 if os.path.exists(self.socket_path):
201 os.remove(self.socket_path)
202 setattr(self.connection, '_socket_path', None)
203 setattr(self.connection, '_connected', False)
204
205 if os.path.exists(lock_path):
206 os.remove(lock_path)
207
208 display.display('shutdown complete', log_only=True)
209
210
211 def main(args=None):
212 """ Called to initiate the connect to the remote device
213 """
214
215 parser = opt_help.create_base_parser(prog=None)
216 opt_help.add_verbosity_options(parser)
217 parser.add_argument('playbook_pid')
218 parser.add_argument('task_uuid')
219 args = parser.parse_args(args[1:] if args is not None else args)
220 init_plugin_loader()
221
222 # initialize verbosity
223 display.verbosity = args.verbosity
224
225 rc = 0
226 result = {}
227 messages = list()
228 socket_path = None
229
230 # Need stdin as a byte stream
231 stdin = sys.stdin.buffer
232
233 # Note: update the below log capture code after Display.display() is refactored.
234 saved_stdout = sys.stdout
235 sys.stdout = io.StringIO()
236
237 try:
238 # read the play context data via stdin, which means depickling it
239 opts_data = read_stream(stdin)
240 init_data = read_stream(stdin)
241
242 pc_data = pickle.loads(init_data, encoding='bytes')
243 options = pickle.loads(opts_data, encoding='bytes')
244
245 play_context = PlayContext()
246 play_context.from_attrs(pc_data)
247
248 except Exception as e:
249 rc = 1
250 result.update({
251 'error': to_text(e),
252 'exception': traceback.format_exc()
253 })
254
255 if rc == 0:
256 ssh = connection_loader.get('ssh', class_only=True)
257 ansible_playbook_pid = args.playbook_pid
258 task_uuid = args.task_uuid
259 cp = ssh._create_control_path(play_context.remote_addr, play_context.port, play_context.remote_user, play_context.connection, ansible_playbook_pid)
260 # create the persistent connection dir if need be and create the paths
261 # which we will be using later
262 tmp_path = unfrackpath(C.PERSISTENT_CONTROL_PATH_DIR)
263 makedirs_safe(tmp_path)
264
265 socket_path = unfrackpath(cp % dict(directory=tmp_path))
266 lock_path = unfrackpath("%s/.ansible_pc_lock_%s" % os.path.split(socket_path))
267
268 with file_lock(lock_path):
269 if not os.path.exists(socket_path):
270 messages.append(('vvvv', 'local domain socket does not exist, starting it'))
271 original_path = os.getcwd()
272 r, w = os.pipe()
273 pid = fork_process()
274
275 if pid == 0:
276 try:
277 os.close(r)
278 wfd = os.fdopen(w, 'w')
279 process = ConnectionProcess(wfd, play_context, socket_path, original_path, task_uuid, ansible_playbook_pid)
280 process.start(options)
281 except Exception:
282 messages.append(('error', traceback.format_exc()))
283 rc = 1
284
285 if rc == 0:
286 process.run()
287 else:
288 process.shutdown()
289
290 sys.exit(rc)
291
292 else:
293 os.close(w)
294 rfd = os.fdopen(r, 'r')
295 data = json.loads(rfd.read(), cls=_tagless.Decoder)
296 messages.extend(data.pop('messages'))
297 result.update(data)
298
299 else:
300 messages.append(('vvvv', 'found existing local domain socket, using it!'))
301 conn = Connection(socket_path)
302 try:
303 conn.set_options(direct=options)
304 except ConnectionError as exc:
305 messages.append(('debug', to_text(exc)))
306 raise ConnectionError('Unable to decode JSON from response set_options. See the debug log for more information.')
307 pc_data = to_text(init_data)
308 try:
309 conn.update_play_context(pc_data)
310 conn.set_check_prompt(task_uuid)
311 except Exception as exc:
312 # Only network_cli has update_play context and set_check_prompt, so missing this is
313 # not fatal e.g. netconf
314 if isinstance(exc, ConnectionError) and getattr(exc, 'code', None) == -32601:
315 pass
316 else:
317 result.update({
318 'error': to_text(exc),
319 'exception': traceback.format_exc()
320 })
321
322 if os.path.exists(socket_path):
323 messages.extend(Connection(socket_path).pop_messages())
324 messages.append(('vvvv', sys.stdout.getvalue()))
325 result.update({
326 'messages': messages,
327 'socket_path': socket_path
328 })
329
330 sys.stdout = saved_stdout
331 if 'exception' in result:
332 rc = 1
333 sys.stderr.write(json.dumps(result, cls=_tagless.Encoder))
334 else:
335 rc = 0
336 sys.stdout.write(json.dumps(result, cls=_tagless.Encoder))
337
338 sys.exit(rc)
339
340
341 if __name__ == '__main__':
342 main()