Debian Codegraph @

lib/ansible/module_utils/connection.py

raw
1 #
2 # This code is part of Ansible, but is an independent component.
3 # This particular file snippet, and this file snippet only, is BSD licensed.
4 # Modules you write using this snippet, which is embedded dynamically by Ansible
5 # still belong to the author of the module, and may assign their own license
6 # to the complete work.
7 #
8 # (c) 2017 Red Hat Inc.
9 #
10 # Redistribution and use in source and binary forms, with or without modification,
11 # are permitted provided that the following conditions are met:
12 #
13 # * Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # * Redistributions in binary form must reproduce the above copyright notice,
16 # this list of conditions and the following disclaimer in the documentation
17 # and/or other materials provided with the distribution.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 from __future__ import annotations
30
31 import os
32 import json
33 import pickle
34 import socket
35 import struct
36 import uuid
37
38 from functools import partial
39
40 from ansible.module_utils._internal import _no_six
41 from ansible.module_utils.common.text.converters import to_bytes, to_text
42 from ansible.module_utils.common.json import _get_legacy_encoder
43
44
45 def write_to_stream(stream, obj):
46 """Write a length+newline-prefixed pickled object to a stream."""
47 src = pickle.dumps(obj)
48
49 stream.write(b'%d\n' % len(src))
50 stream.write(src)
51
52
53 def send_data(s, data):
54 packed_len = struct.pack('!Q', len(data))
55 return s.sendall(packed_len + data)
56
57
58 def recv_data(s):
59 header_len = 8 # size of a packed unsigned long long
60 data = to_bytes("")
61 while len(data) < header_len:
62 d = s.recv(header_len - len(data))
63 if not d:
64 return None
65 data += d
66 data_len = struct.unpack('!Q', data[:header_len])[0]
67 data = data[header_len:]
68 while len(data) < data_len:
69 d = s.recv(data_len - len(data))
70 if not d:
71 return None
72 data += d
73 return data
74
75
76 def exec_command(module, command):
77 connection = Connection(module._socket_path)
78 try:
79 out = connection.exec_command(command)
80 except ConnectionError as exc:
81 code = getattr(exc, 'code', 1)
82 message = getattr(exc, 'err', exc)
83 return code, '', to_text(message, errors='surrogate_then_replace')
84 return 0, out, ''
85
86
87 def request_builder(method_, *args, **kwargs):
88 reqid = str(uuid.uuid4())
89 req = {'jsonrpc': '2.0', 'method': method_, 'id': reqid}
90 req['params'] = (args, kwargs)
91
92 return req
93
94
95 class ConnectionError(Exception):
96
97 def __init__(self, message, *args, **kwargs):
98 super(ConnectionError, self).__init__(message)
99 for k, v in kwargs.items():
100 setattr(self, k, v)
101
102
103 class Connection(object):
104
105 def __init__(self, socket_path):
106 if socket_path is None:
107 raise AssertionError('socket_path must be a value')
108 self.socket_path = socket_path
109
110 def __getattr__(self, name):
111 try:
112 return self.__dict__[name]
113 except KeyError:
114 if name.startswith('_'):
115 raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
116 return partial(self.__rpc__, name)
117
118 def _exec_jsonrpc(self, name, *args, **kwargs):
119
120 req = request_builder(name, *args, **kwargs)
121 reqid = req['id']
122
123 if not os.path.exists(self.socket_path):
124 raise ConnectionError(
125 'socket path %s does not exist or cannot be found. See Troubleshooting socket '
126 'path issues in the Network Debug and Troubleshooting Guide' % self.socket_path
127 )
128
129 try:
130 data = json.dumps(req, cls=_get_legacy_encoder(), vault_to_text=True)
131 except TypeError as exc:
132 raise ConnectionError(
133 "Failed to encode some variables as JSON for communication with the persistent connection helper. "
134 "The original exception was: %s" % to_text(exc)
135 )
136
137 try:
138 out = self.send(data)
139 except OSError as ex:
140 raise ConnectionError(
141 f'Unable to connect to socket {self.socket_path!r}. See Troubleshooting socket path issues '
142 'in the Network Debug and Troubleshooting Guide.'
143 ) from ex
144
145 try:
146 response = json.loads(out)
147 except ValueError:
148 # set_option(s) has sensitive info, and the details are unlikely to matter anyway
149 if name.startswith("set_option"):
150 raise ConnectionError(
151 "Unable to decode JSON from response to {0}. Received '{1}'.".format(name, out)
152 )
153 params = [repr(arg) for arg in args] + ['{0}={1!r}'.format(k, v) for k, v in kwargs.items()]
154 params = ', '.join(params)
155 raise ConnectionError(
156 "Unable to decode JSON from response to {0}({1}). Received '{2}'.".format(name, params, out)
157 )
158
159 if response['id'] != reqid:
160 raise ConnectionError('invalid json-rpc id received')
161 if "result_type" in response:
162 # NOTE: while pickle.loads is normally a concern, in this case it is controller code on the same
163 # machine and user in a private restricted path, any substitution would require same privs.
164 response["result"] = pickle.loads(to_bytes(response["result"], errors="surrogateescape"))
165
166 return response
167
168 def __rpc__(self, name, *args, **kwargs):
169 """Executes the json-rpc and returns the output received
170 from remote device.
171 :name: rpc method to be executed over connection plugin that implements jsonrpc 2.0
172 :args: Ordered list of params passed as arguments to rpc method
173 :kwargs: Dict of valid key, value pairs passed as arguments to rpc method
174
175 For usage refer the respective connection plugin docs.
176 """
177
178 response = self._exec_jsonrpc(name, *args, **kwargs)
179
180 if 'error' in response:
181 err = response.get('error')
182 msg = err.get('data') or err['message']
183 code = err['code']
184 raise ConnectionError(to_text(msg, errors='surrogate_then_replace'), code=code)
185
186 return response['result']
187
188 def send(self, data):
189 try:
190 sf = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
191 sf.connect(self.socket_path)
192
193 send_data(sf, to_bytes(data))
194 response = recv_data(sf)
195
196 except OSError as ex:
197 sf.close()
198 raise ConnectionError(
199 f'Unable to connect to socket {self.socket_path!r}. See the socket path issue category in '
200 'Network Debug and Troubleshooting Guide.',
201 ) from ex
202
203 sf.close()
204
205 return to_text(response, errors='surrogate_or_strict')
206
207
208 def __getattr__(importable_name):
209 return _no_six.deprecate(importable_name, __name__, "iteritems")