Debian Codegraph @

test/lib/ansible_test/_internal/core_ci.py

raw
1 """Access Ansible Core CI remote services."""
2
3 from __future__ import annotations
4
5 import abc
6 import dataclasses
7 import json
8 import os
9 import re
10 import stat
11 import traceback
12 import uuid
13 import time
14 import typing as t
15
16 from .http import (
17 HttpClient,
18 HttpResponse,
19 HttpError,
20 )
21
22 from .io import (
23 make_dirs,
24 read_text_file,
25 write_json_file,
26 write_text_file,
27 )
28
29 from .util import (
30 ApplicationError,
31 display,
32 mutex,
33 )
34
35 from .util_common import (
36 run_command,
37 ResultType,
38 )
39
40 from .config import (
41 EnvironmentConfig,
42 )
43
44 from .ci import (
45 AuthContext,
46 get_ci_provider,
47 )
48
49 from .data import (
50 data_context,
51 PayloadConfig,
52 )
53
54
55 @dataclasses.dataclass(frozen=True)
56 class Resource(metaclass=abc.ABCMeta):
57 """Base class for Ansible Core CI resources."""
58
59 @abc.abstractmethod
60 def as_tuple(self) -> tuple[str, str, str, str]:
61 """Return the resource as a tuple of platform, version, architecture and provider."""
62
63 @abc.abstractmethod
64 def get_label(self) -> str:
65 """Return a user-friendly label for this resource."""
66
67 @property
68 @abc.abstractmethod
69 def persist(self) -> bool:
70 """True if the resource is persistent, otherwise false."""
71
72 @abc.abstractmethod
73 def get_config(self, core_ci: AnsibleCoreCI) -> dict[str, object]:
74 """Return the configuration for this resource."""
75
76
77 @dataclasses.dataclass(frozen=True)
78 class VmResource(Resource):
79 """Details needed to request a VM from Ansible Core CI."""
80
81 platform: str
82 version: str
83 architecture: str
84 provider: str
85 tag: str
86
87 def as_tuple(self) -> tuple[str, str, str, str]:
88 """Return the resource as a tuple of platform, version, architecture and provider."""
89 return self.platform, self.version, self.architecture, self.provider
90
91 def get_label(self) -> str:
92 """Return a user-friendly label for this resource."""
93 return f'{self.platform} {self.version} ({self.architecture}) [{self.tag}] @{self.provider}'
94
95 @property
96 def persist(self) -> bool:
97 """True if the resource is persistent, otherwise false."""
98 return True
99
100 def get_config(self, core_ci: AnsibleCoreCI) -> dict[str, object]:
101 """Return the configuration for this resource."""
102 return dict(
103 type="vm",
104 platform=self.platform,
105 version=self.version,
106 architecture=self.architecture,
107 public_key=core_ci.ssh_key.pub_contents,
108 )
109
110
111 @dataclasses.dataclass(frozen=True)
112 class CloudResource(Resource):
113 """Details needed to request cloud credentials from Ansible Core CI."""
114
115 platform: str
116
117 def as_tuple(self) -> tuple[str, str, str, str]:
118 """Return the resource as a tuple of platform, version, architecture and provider."""
119 return self.platform, '', '', self.platform
120
121 def get_label(self) -> str:
122 """Return a user-friendly label for this resource."""
123 return self.platform
124
125 @property
126 def persist(self) -> bool:
127 """True if the resource is persistent, otherwise false."""
128 return False
129
130 def get_config(self, core_ci: AnsibleCoreCI) -> dict[str, object]:
131 """Return the configuration for this resource."""
132 return dict(
133 type="cloud",
134 )
135
136
137 class AnsibleCoreCI:
138 """Client for Ansible Core CI services."""
139
140 DEFAULT_ENDPOINT = 'https://api.ci.core.ansible.com'
141
142 def __init__(
143 self,
144 args: EnvironmentConfig,
145 resource: Resource,
146 load: bool = True,
147 ) -> None:
148 self.args = args
149 self.resource = resource
150 self.platform, self.version, self.arch, self.provider = self.resource.as_tuple()
151 self.stage = args.remote_stage
152 self.client = HttpClient(args)
153 self.connection = None
154 self.instance_id = None
155 self.endpoint = None
156 self.default_endpoint = args.remote_endpoint or self.DEFAULT_ENDPOINT
157 self.retries = 3
158 self.ci_provider = get_ci_provider()
159 self.label = self.resource.get_label()
160
161 stripped_label = re.sub('[^A-Za-z0-9_.]+', '-', self.label).strip('-')
162
163 self.name = f"{stripped_label}-{self.stage}" # turn the label into something suitable for use as a filename
164
165 self.path = os.path.expanduser(f'~/.ansible/test/instances/{self.name}')
166 self.ssh_key = SshKey(args)
167
168 if self.resource.persist and load and self._load():
169 try:
170 display.info(f'Checking existing {self.label} instance using: {self._uri}', verbosity=1)
171
172 self.connection = self.get(always_raise_on=[404])
173
174 display.info(f'Loaded existing {self.label} instance.', verbosity=1)
175 except HttpError as ex:
176 if ex.status != 404:
177 raise
178
179 self._clear()
180
181 display.info(f'Cleared stale {self.label} instance.', verbosity=1)
182
183 self.instance_id = None
184 self.endpoint = None
185 elif not self.resource.persist:
186 self.instance_id = None
187 self.endpoint = None
188 self._clear()
189
190 if self.instance_id:
191 self.started: bool = True
192 else:
193 self.started = False
194 self.instance_id = str(uuid.uuid4())
195 self.endpoint = None
196
197 display.sensitive.add(self.instance_id)
198
199 if not self.endpoint:
200 self.endpoint = self.default_endpoint
201
202 @property
203 def available(self) -> bool:
204 """Return True if Ansible Core CI is supported."""
205 return self.ci_provider.supports_core_ci_auth()
206
207 def start(self) -> t.Optional[dict[str, t.Any]]:
208 """Start instance."""
209 if self.started:
210 display.info(f'Skipping started {self.label} instance.', verbosity=1)
211 return None
212
213 return self._start()
214
215 def stop(self) -> None:
216 """Stop instance."""
217 if not self.started:
218 display.info(f'Skipping invalid {self.label} instance.', verbosity=1)
219 return
220
221 response = self.client.delete(self._uri)
222
223 if response.status_code == 404:
224 self._clear()
225 display.info(f'Cleared invalid {self.label} instance.', verbosity=1)
226 return
227
228 if response.status_code == 200:
229 self._clear()
230 display.info(f'Stopped running {self.label} instance.', verbosity=1)
231 return
232
233 raise self._create_http_error(response)
234
235 def get(self, tries: int = 3, sleep: int = 15, always_raise_on: t.Optional[list[int]] = None) -> t.Optional[InstanceConnection]:
236 """Get instance connection information."""
237 if not self.started:
238 display.info(f'Skipping invalid {self.label} instance.', verbosity=1)
239 return None
240
241 if not always_raise_on:
242 always_raise_on = []
243
244 if self.connection and self.connection.running:
245 return self.connection
246
247 while True:
248 tries -= 1
249 response = self.client.get(self._uri)
250
251 if response.status_code == 200:
252 break
253
254 error = self._create_http_error(response)
255
256 if not tries or response.status_code in always_raise_on:
257 raise error
258
259 display.warning(f'{error}. Trying again after {sleep} seconds.')
260 time.sleep(sleep)
261
262 if self.args.explain:
263 self.connection = InstanceConnection(
264 running=True,
265 hostname='cloud.example.com',
266 port=12345,
267 username='root',
268 password='password' if self.platform == 'windows' else None,
269 )
270 else:
271 response_json = response.json()
272 status = response_json['status']
273 con = response_json.get('connection')
274
275 if con:
276 self.connection = InstanceConnection(
277 running=status == 'running',
278 hostname=con['hostname'],
279 port=int(con['port']),
280 username=con['username'],
281 password=con.get('password'),
282 response_json=response_json,
283 )
284 else:
285 self.connection = InstanceConnection(
286 running=status == 'running',
287 response_json=response_json,
288 )
289
290 if self.connection.password:
291 display.sensitive.add(str(self.connection.password))
292
293 status = 'running' if self.connection.running else 'starting'
294
295 display.info(f'The {self.label} instance is {status}.', verbosity=1)
296
297 return self.connection
298
299 def wait(self, iterations: t.Optional[int] = 90) -> None:
300 """Wait for the instance to become ready."""
301 for _iteration in range(1, iterations):
302 if self.get().running:
303 return
304 time.sleep(10)
305
306 raise ApplicationError(f'Timeout waiting for {self.label} instance.')
307
308 @property
309 def _uri(self) -> str:
310 return f'{self.endpoint}/{self.stage}/{self.provider}/{self.instance_id}'
311
312 def _start(self) -> dict[str, t.Any]:
313 """Start instance."""
314 display.info(f'Initializing new {self.label} instance using: {self._uri}', verbosity=1)
315
316 config = self.resource.get_config(self)
317
318 context = AuthContext(
319 request_id=self.instance_id,
320 stage=self.stage,
321 provider=self.provider,
322 )
323
324 request = self.ci_provider.prepare_core_ci_request(config, context)
325
326 headers = {
327 'Content-Type': 'application/json',
328 }
329
330 response = self._start_endpoint(request, headers)
331
332 self.started = True
333 self._save()
334
335 display.info(f'Started {self.label} instance.', verbosity=1)
336
337 if self.args.explain:
338 return {}
339
340 return response.json()
341
342 def _start_endpoint(self, data: dict[str, t.Any], headers: dict[str, str]) -> HttpResponse:
343 tries = self.retries
344 sleep = 15
345
346 while True:
347 tries -= 1
348 response = self.client.put(self._uri, data=json.dumps(data), headers=headers)
349
350 if response.status_code == 200:
351 return response
352
353 error = self._create_http_error(response)
354
355 if response.status_code == 503:
356 raise error
357
358 if not tries:
359 raise error
360
361 display.warning(f'{error}. Trying again after {sleep} seconds.')
362 time.sleep(sleep)
363
364 def _clear(self) -> None:
365 """Clear instance information."""
366 try:
367 self.connection = None
368 os.remove(self.path)
369 except FileNotFoundError:
370 pass
371
372 def _load(self) -> bool:
373 """Load instance information."""
374 try:
375 data = read_text_file(self.path)
376 except FileNotFoundError:
377 return False
378
379 if not data.startswith('{'):
380 return False # legacy format
381
382 config = json.loads(data)
383
384 return self.load(config)
385
386 def load(self, config: dict[str, str]) -> bool:
387 """Load the instance from the provided dictionary."""
388 self.instance_id = str(config['instance_id'])
389 self.endpoint = config['endpoint']
390 self.started = True
391
392 display.sensitive.add(self.instance_id)
393
394 return True
395
396 def _save(self) -> None:
397 """Save instance information."""
398 if self.args.explain:
399 return
400
401 config = self.save()
402
403 write_json_file(self.path, config, create_directories=True)
404
405 def save(self) -> dict[str, str]:
406 """Save instance details and return as a dictionary."""
407 return dict(
408 label=self.resource.get_label(),
409 instance_id=self.instance_id,
410 endpoint=self.endpoint,
411 )
412
413 @staticmethod
414 def _create_http_error(response: HttpResponse) -> ApplicationError:
415 """Return an exception created from the given HTTP response."""
416 response_json = response.json()
417 stack_trace = ''
418
419 if 'message' in response_json:
420 message = response_json['message']
421 elif 'errorMessage' in response_json:
422 message = response_json['errorMessage'].strip()
423 if 'stackTrace' in response_json:
424 traceback_lines = response_json['stackTrace']
425
426 # AWS Lambda on Python 2.7 returns a list of tuples
427 # AWS Lambda on Python 3.7 returns a list of strings
428 if traceback_lines and isinstance(traceback_lines[0], list):
429 traceback_lines = traceback.format_list(traceback_lines)
430
431 trace = '\n'.join([x.rstrip() for x in traceback_lines])
432 stack_trace = f'\nTraceback (from remote server):\n{trace}'
433 else:
434 message = str(response_json)
435
436 return CoreHttpError(response.status_code, message, stack_trace)
437
438
439 class CoreHttpError(HttpError):
440 """HTTP response as an error."""
441
442 def __init__(self, status: int, remote_message: str, remote_stack_trace: str) -> None:
443 super().__init__(status, f'{remote_message}{remote_stack_trace}')
444
445 self.remote_message = remote_message
446 self.remote_stack_trace = remote_stack_trace
447
448
449 class SshKey:
450 """Container for SSH key used to connect to remote instances."""
451
452 KEY_TYPE = 'rsa' # RSA is used to maintain compatibility with paramiko and EC2
453 KEY_NAME = f'id_{KEY_TYPE}'
454 PUB_NAME = f'{KEY_NAME}.pub'
455
456 @mutex
457 def __init__(self, args: EnvironmentConfig) -> None:
458 key_pair = self.get_key_pair()
459
460 if not key_pair:
461 key_pair = self.generate_key_pair(args)
462
463 key, pub = key_pair
464 key_dst, pub_dst = self.get_in_tree_key_pair_paths()
465
466 def ssh_key_callback(payload_config: PayloadConfig) -> None:
467 """
468 Add the SSH keys to the payload file list.
469 They are either outside the source tree or in the cache dir which is ignored by default.
470 """
471 files = payload_config.files
472 permissions = payload_config.permissions
473
474 files.append((key, os.path.relpath(key_dst, data_context().content.root)))
475 files.append((pub, os.path.relpath(pub_dst, data_context().content.root)))
476
477 permissions[os.path.relpath(key_dst, data_context().content.root)] = stat.S_IRUSR | stat.S_IWUSR
478
479 data_context().register_payload_callback(ssh_key_callback)
480
481 self.key, self.pub = key, pub
482
483 if args.explain:
484 self.pub_contents = None
485 self.key_contents = None
486 else:
487 self.pub_contents = read_text_file(self.pub).strip()
488 self.key_contents = read_text_file(self.key).strip()
489
490 @staticmethod
491 def get_relative_in_tree_private_key_path() -> str:
492 """Return the ansible-test SSH private key path relative to the content tree."""
493 temp_dir = ResultType.TMP.relative_path
494
495 key = os.path.join(temp_dir, SshKey.KEY_NAME)
496
497 return key
498
499 def get_in_tree_key_pair_paths(self) -> t.Optional[tuple[str, str]]:
500 """Return the ansible-test SSH key pair paths from the content tree."""
501 temp_dir = ResultType.TMP.path
502
503 key = os.path.join(temp_dir, self.KEY_NAME)
504 pub = os.path.join(temp_dir, self.PUB_NAME)
505
506 return key, pub
507
508 def get_source_key_pair_paths(self) -> t.Optional[tuple[str, str]]:
509 """Return the ansible-test SSH key pair paths for the current user."""
510 base_dir = os.path.expanduser('~/.ansible/test/')
511
512 key = os.path.join(base_dir, self.KEY_NAME)
513 pub = os.path.join(base_dir, self.PUB_NAME)
514
515 return key, pub
516
517 def get_key_pair(self) -> t.Optional[tuple[str, str]]:
518 """Return the ansible-test SSH key pair paths if present, otherwise return None."""
519 key, pub = self.get_in_tree_key_pair_paths()
520
521 if os.path.isfile(key) and os.path.isfile(pub):
522 return key, pub
523
524 key, pub = self.get_source_key_pair_paths()
525
526 if os.path.isfile(key) and os.path.isfile(pub):
527 return key, pub
528
529 return None
530
531 def generate_key_pair(self, args: EnvironmentConfig) -> tuple[str, str]:
532 """Generate an SSH key pair for use by all ansible-test invocations for the current user."""
533 key, pub = self.get_source_key_pair_paths()
534
535 if not args.explain:
536 make_dirs(os.path.dirname(key))
537
538 if not os.path.isfile(key) or not os.path.isfile(pub):
539 run_command(args, ['ssh-keygen', '-m', 'PEM', '-q', '-t', self.KEY_TYPE, '-N', '', '-f', key], capture=True)
540
541 if args.explain:
542 return key, pub
543
544 # newer ssh-keygen PEM output (such as on RHEL 8.1) is not recognized by paramiko
545 key_contents = read_text_file(key)
546 key_contents = re.sub(r'(BEGIN|END) PRIVATE KEY', r'\1 RSA PRIVATE KEY', key_contents)
547
548 write_text_file(key, key_contents)
549
550 return key, pub
551
552
553 class InstanceConnection:
554 """Container for remote instance status and connection details."""
555
556 def __init__(
557 self,
558 running: bool,
559 hostname: t.Optional[str] = None,
560 port: t.Optional[int] = None,
561 username: t.Optional[str] = None,
562 password: t.Optional[str] = None,
563 response_json: t.Optional[dict[str, t.Any]] = None,
564 ) -> None:
565 self.running = running
566 self.hostname = hostname
567 self.port = port
568 self.username = username
569 self.password = password
570 self.response_json = response_json or {}
571
572 def __str__(self):
573 if self.password:
574 return f'{self.hostname}:{self.port} [{self.username}:{self.password}]'
575
576 return f'{self.hostname}:{self.port} [{self.username}]'