Debian Codegraph @

ansible_collections/azure/azcollection/plugins/plugin_utils/connectivity_utils.py

raw symbols SCIP
1 # --------------------------------------------------------------------------------------------
2 # Copyright (c) Microsoft Corporation. All rights reserved.
3 # Licensed under the MIT License. See License.txt in the project root for license information.
4 # --------------------------------------------------------------------------------------------
5
6 import time
7 import os
8 import json
9 import base64
10 import tarfile
11 from glob import glob
12 import traceback
13
14 HAS_ORAS = False
15 HAS_ORAS_EXC = None
16
17 try:
18 import oras.client
19 HAS_ORAS = True
20 except ImportError:
21 oras = None
22 HAS_ORAS_EXC = traceback.format_exc()
23
24 try:
25 from azure.core.exceptions import ResourceNotFoundError, HttpResponseError
26 from azure.mgmt.core.tools import resource_id, parse_resource_id
27 except ImportError:
28 pass
29
30 from ansible_collections.azure.azcollection.plugins.plugin_utils import file_utils
31 from ansible_collections.azure.azcollection.plugins.plugin_utils import constants as consts
32
33 from ansible.errors import AnsibleError
34
35
36 # Get the Access Details to connect to Arc Connectivity platform from the HybridConnectivity RP
37 def get_relay_information(rest_client, subscription_id, resource_group, hostname, resource_type,
38 certificate_validity_in_seconds, port):
39 if not certificate_validity_in_seconds or \
40 certificate_validity_in_seconds > consts.RELAY_INFO_MAXIMUM_DURATION_IN_SECONDS:
41 certificate_validity_in_seconds = consts.RELAY_INFO_MAXIMUM_DURATION_IN_SECONDS
42
43 namespace = resource_type.split('/', 1)[0]
44 arc_type = resource_type.split('/', 1)[1]
45 resource_uri = resource_id(subscription=subscription_id, resource_group=resource_group,
46 namespace=namespace, type=arc_type, name=hostname)
47
48 cred = None
49 new_service_config = False
50 try:
51 cred = _list_credentials(rest_client, resource_uri, certificate_validity_in_seconds)
52 except ResourceNotFoundError:
53 _create_default_endpoint(rest_client, resource_uri)
54 except HttpResponseError as e:
55 if e.reason != "Precondition Failed":
56 raise AnsibleError(f"Unable to retrieve relay information. Failed with error: {str(e)}")
57 except Exception as e:
58 raise AnsibleError(f"Unable to retrieve relay information. Failed with error: {str(e)}")
59
60 if not cred:
61 _create_service_configuration(rest_client, resource_uri, port)
62 new_service_config = True
63 try:
64 cred = _list_credentials(rest_client, resource_uri, certificate_validity_in_seconds)
65 except Exception as e:
66 raise AnsibleError(f"Unable to get relay information. Failed with error: {str(e)}")
67 _handle_relay_connection_delay(rest_client, "Setting up service configuration")
68 else:
69 if not _check_service_configuration(rest_client, resource_uri, port):
70 _create_service_configuration(rest_client, resource_uri, port)
71 new_service_config = True
72 try:
73 cred = _list_credentials(rest_client, resource_uri, certificate_validity_in_seconds)
74 except Exception as e:
75 raise AnsibleError(f"Unable to get relay information. Failed with error: {str(e)}")
76 _handle_relay_connection_delay(rest_client, "Setting up service configuration")
77 return (cred, new_service_config)
78
79
80 def _check_service_configuration(rest_client, resource_uri, port):
81 url = f"/{resource_uri}/providers/Microsoft.HybridConnectivity/endpoints/default/serviceConfigurations/SSH"
82
83 serviceConfig = None
84 # pylint: disable=broad-except
85 try:
86 serviceConfig = resource(rest_client, url, "GET")
87 except Exception:
88 # If for some reason the request for Service Configuration fails,
89 # we will still attempt to get relay information and connect. If the service configuration
90 # is not setup correctly, the connection will fail.
91 # The more likely scenario is that the request failed with a "Authorization Error",
92 # in case the user isn't an owner/contributor.
93 return True
94 serviceConfigPort = serviceConfig and serviceConfig.get('properties', {}).get('port')
95 if port:
96 return int(serviceConfigPort) == int(port)
97
98 return True
99
100
101 def _create_default_endpoint(rest_client, resource_uri):
102 url = f"/{resource_uri}/providers/Microsoft.HybridConnectivity/endpoints/default"
103 body = {'properties': {'type': 'default'}}
104
105 hostname = parse_resource_id(resource_uri)["name"]
106 resource_group = parse_resource_id(resource_uri)["resource_group"]
107 try:
108 endpoint = resource(rest_client, url, "PUT", body=body)
109 except HttpResponseError as e:
110 if e.reason == "Forbidden":
111 raise AnsibleError(f"Client is not authorized to create a default connectivity "
112 f"endpoint for \'{hostname}\' in Resource Group \'{resource_group}\'. "
113 f"This is a one-time operation that must be performed by "
114 f"an account with Owner or Contributor role to allow "
115 f"connections to the target resource.")
116 raise AnsibleError(f"Failed to create default endpoint for the target Arc Server. "
117 f"\nError: {str(e)}")
118 except Exception as e:
119 raise AnsibleError(f"Failed to create default endpoint for the target Arc Server. "
120 f"\nError: {str(e)}")
121
122 return endpoint
123
124
125 def _create_service_configuration(rest_client, resource_uri, port):
126 if not port:
127 port = '22'
128
129 url = f"/{resource_uri}/providers/Microsoft.HybridConnectivity/endpoints/default/serviceConfigurations/SSH"
130 body = {'properties': {'port': int(port), 'serviceName': 'SSH'}}
131
132 hostname = parse_resource_id(resource_uri)["name"]
133 resource_group = parse_resource_id(resource_uri)["resource_group"]
134
135 try:
136 serviceConfig = resource(rest_client, url, "PUT", body=body)
137 except HttpResponseError as e:
138 if e.reason == "Forbidden":
139 raise AnsibleError(f"Client is not authorized to create or update the Service "
140 f"Configuration endpoint for \'{hostname}\' in the Resource "
141 f"Group \'{resource_group}\'. This is an operation that "
142 f"must be performed by an account with Owner or Contributor "
143 f"role to allow SSH connections to the specified port {port}.")
144 raise AnsibleError(f"Failed to create service configuration to allow SSH "
145 f"connections to port {port} on the endpoint for {hostname} "
146 f"in the Resource Group {resource_group}\nError: {str(e)}")
147 except Exception as e:
148 raise AnsibleError(f"Failed to create service configuration to allow SSH connections "
149 f"to port {port} on the endpoint for {hostname} in the Resource "
150 f"Group {resource_group}\nError: {str(e)}")
151 return serviceConfig
152
153
154 def _list_credentials(rest_client, resource_uri, certificate_validity_in_seconds):
155 url = f"/{resource_uri}/providers/Microsoft.HybridConnectivity/endpoints/default/listCredentials"
156 query_parameters = {'expiresin': int(certificate_validity_in_seconds)}
157 body = {'serviceName': 'SSH'}
158
159 response = resource(rest_client, url, "POST", body=body, custom_query=query_parameters)
160 return response and response.get('relay')
161
162
163 def format_relay_info_string(relay_info):
164 relay_info_string = json.dumps(
165 {
166 "relay": {
167 "namespaceName": relay_info['namespaceName'],
168 "namespaceNameSuffix": relay_info['namespaceNameSuffix'],
169 "hybridConnectionName": relay_info['hybridConnectionName'],
170 "accessKey": relay_info['accessKey'],
171 "expiresOn": relay_info['expiresOn'],
172 "serviceConfigurationToken": relay_info['serviceConfigurationToken']
173 }
174 })
175 result_bytes = relay_info_string.encode("ascii")
176 enc = base64.b64encode(result_bytes)
177 base64_result_string = enc.decode("ascii")
178 return base64_result_string
179
180
181 def _handle_relay_connection_delay(rest_client, message):
182 # relay has retry delay after relay connection is lost
183 # must sleep for at least as long as the delay
184 # otherwise the ssh connection will fail
185 for x in range(0, consts.SERVICE_CONNECTION_DELAY_IN_SECONDS + 1):
186 time.sleep(1)
187
188
189 # Downloads client side proxy to connect to Arc Connectivity Platform
190 def install_client_side_proxy(arc_proxy_folder):
191
192 client_operating_system = _get_client_operating_system()
193 client_architecture = _get_client_architeture()
194 install_dir = _get_proxy_install_dir(arc_proxy_folder)
195 proxy_name = _get_proxy_filename(client_operating_system, client_architecture)
196 install_location = os.path.join(install_dir, proxy_name)
197
198 # Only download new proxy if it doesn't exist already
199 if not os.path.isfile(install_location):
200 if not os.path.isdir(install_dir):
201 file_utils.create_directory(install_dir, f"Failed to create client proxy directory '{install_dir}'.")
202 # if directory exists, delete any older versions of the proxy
203 else:
204 older_version_location = _get_older_version_proxy_path(
205 install_dir,
206 client_operating_system,
207 client_architecture)
208 older_version_files = glob(older_version_location)
209 for f in older_version_files:
210 file_utils.delete_file(f, f"failed to delete older version file {f}", warning=True)
211
212 _download_proxy_from_MCR(install_dir, proxy_name, client_operating_system, client_architecture)
213 _check_proxy_installation(install_dir, proxy_name)
214
215 return install_location
216
217
218 def _download_proxy_from_MCR(dest_dir, proxy_name, operating_system, architecture):
219 mar_target = f"{consts.CLIENT_PROXY_MCR_TARGET}/{operating_system.lower()}/{architecture}/ssh-proxy"
220
221 client = oras.client.OrasClient()
222
223 try:
224 response = client.pull(target=f"{mar_target}:{consts.CLIENT_PROXY_VERSION}", outdir=dest_dir)
225 except Exception as e:
226 raise AnsibleError(
227 f"Failed to download Arc Connectivity proxy with error {str(e)}. Please try again.")
228
229 proxy_package_path = _get_proxy_package_path_from_oras_response(response)
230 _extract_proxy_tar_files(proxy_package_path, dest_dir, proxy_name)
231 file_utils.delete_file(proxy_package_path, f"Failed to delete {proxy_package_path}. Please delete manually.", True)
232
233
234 def _get_proxy_package_path_from_oras_response(pull_response):
235 if not isinstance(pull_response, list):
236 raise AnsibleError(
237 "Attempt to download Arc Connectivity Proxy returned unnexpected result. Please try again.")
238
239 if len(pull_response) != 1:
240 for r in pull_response:
241 file_utils.delete_file(r, f"Failed to delete {r}. Please delete it manually.", True)
242 raise AnsibleError(
243 "Attempt to download Arc Connectivity Proxy returned unnexpected result. Please try again.")
244
245 proxy_package_path = pull_response[0]
246
247 if not os.path.isfile(proxy_package_path):
248 raise AnsibleError("Unable to download Arc Connectivity Proxy. Please try again.")
249
250 return proxy_package_path
251
252
253 def _extract_proxy_tar_files(proxy_package_path, install_dir, proxy_name):
254 with tarfile.open(proxy_package_path, 'r:gz') as tar:
255 members = []
256 for member in tar.getmembers():
257 if member.isfile():
258 filenames = member.name.split('/')
259
260 if len(filenames) != 2:
261 tar.close()
262 file_utils.delete_file(
263 proxy_package_path,
264 f"Failed to delete {proxy_package_path}. Please delete it manually.",
265 True)
266 raise AnsibleError(
267 "Attempt to download Arc Connectivity Proxy returned unnexpected result. Please try again.")
268
269 member.name = filenames[1]
270
271 if member.name.startswith('sshproxy'):
272 member.name = proxy_name
273 elif member.name.lower() not in ['license.txt', 'thirdpartynotice.txt']:
274 tar.close()
275 file_utils.delete_file(
276 proxy_package_path,
277 f"Failed to delete {proxy_package_path}. Please delete it manually.",
278 True)
279 raise AnsibleError(
280 "Attempt to download Arc Connectivity Proxy returned unnexpected result. Please try again.")
281
282 members.append(member)
283
284 tar.extractall(members=members, path=install_dir)
285
286
287 def _check_proxy_installation(install_dir, proxy_name):
288 proxy_filepath = os.path.join(install_dir, proxy_name)
289 if not os.path.isfile(proxy_filepath):
290 raise AnsibleError(
291 "Failed to install required SSH Arc Connectivity Proxy. "
292 f"Couldn't find expected file {proxy_filepath}. Please try again.")
293
294
295 def _get_proxy_filename(operating_system, architecture):
296 if operating_system.lower() == 'darwin' and architecture == '386':
297 raise AnsibleError("Unsupported Darwin OS with 386 architecture.")
298 proxy_filename = \
299 f"sshProxy_{operating_system.lower()}_{architecture}_{consts.CLIENT_PROXY_VERSION.replace('.', '_')}"
300 if operating_system.lower() == 'windows':
301 proxy_filename += '.exe'
302 return proxy_filename
303
304
305 def _get_older_version_proxy_path(install_dir, operating_system, architecture):
306 proxy_name = f"sshProxy_{operating_system.lower()}_{architecture}_*"
307 return os.path.join(install_dir, proxy_name)
308
309
310 def _get_proxy_install_dir(arc_proxy_folder):
311 if not arc_proxy_folder:
312 return os.path.expanduser(os.path.join('~', ".clientsshproxy"))
313 return arc_proxy_folder
314
315
316 def _get_client_architeture():
317 import platform
318 machine = platform.machine()
319 architecture = None
320
321 if "arm64" in machine.lower() or "aarch64" in machine.lower():
322 architecture = 'arm64'
323 elif machine.endswith('64'):
324 architecture = 'amd64'
325 elif machine.endswith('86'):
326 architecture = '386'
327 elif machine == '':
328 raise AnsibleError("Couldn't identify the platform architecture.")
329 else:
330 raise AnsibleError(f"Unsuported architecture: {machine} is not currently supported")
331
332 return architecture
333
334
335 def _get_client_operating_system():
336 import platform
337 operating_system = platform.system()
338
339 if operating_system.lower() not in ('linux', 'darwin', 'windows'):
340 raise AnsibleError(f"Unsuported OS: {operating_system} platform is not currently supported")
341 return operating_system
342
343
344 def resource(client,
345 url,
346 method,
347 body=None,
348 custom_query=None,
349 custom_header=None,
350 status_code=None):
351
352 # Construct status_code
353 if status_code is None:
354 status_code = [200, 201, 202]
355
356 # Construct parameters
357 query_parameters = {}
358 query_parameters['api-version'] = '2023-03-15'
359 if custom_query:
360 query_parameters.update(custom_query)
361
362 # Construct headers
363 header_parameters = {}
364 header_parameters['Content-Type'] = 'application/json; charset=utf-8'
365 if custom_header:
366 header_parameters.update(custom_header)
367
368 response = client.query(url,
369 method,
370 query_parameters,
371 header_parameters,
372 body,
373 status_code,
374 600,
375 30)
376
377 if hasattr(response, 'body'):
378 try:
379 response = json.loads(response.body())
380 except Exception:
381 response = response.body()
382 elif hasattr(response, 'context'):
383 response = response.context['deserialized_data']
384 else:
385 response = None
386
387 return response