Debian Codegraph @

test/lib/ansible_test/_internal/ci/azp.py

raw
1 """Support code for working with Azure Pipelines."""
2
3 from __future__ import annotations
4
5 import json
6 import os
7 import tempfile
8 import uuid
9 import typing as t
10 import urllib.parse
11
12 from ..encoding import (
13 to_bytes,
14 )
15
16 from ..config import (
17 CommonConfig,
18 TestConfig,
19 )
20
21 from ..git import (
22 Git,
23 )
24
25 from ..http import (
26 HttpClient,
27 )
28
29 from ..util import (
30 display,
31 ApplicationError,
32 MissingEnvironmentVariable,
33 )
34
35 from . import (
36 AuthContext,
37 ChangeDetectionNotSupported,
38 CIProvider,
39 GeneratingAuthHelper,
40 )
41
42 CODE = 'azp'
43
44
45 class AzurePipelines(CIProvider):
46 """CI provider implementation for Azure Pipelines."""
47
48 def __init__(self) -> None:
49 self.auth = AzurePipelinesAuthHelper()
50
51 self._changes: AzurePipelinesChanges | None = None
52
53 @staticmethod
54 def is_supported() -> bool:
55 """Return True if this provider is supported in the current running environment."""
56 return os.environ.get('SYSTEM_COLLECTIONURI', '').startswith('https://dev.azure.com/')
57
58 @property
59 def code(self) -> str:
60 """Return a unique code representing this provider."""
61 return CODE
62
63 @property
64 def name(self) -> str:
65 """Return descriptive name for this provider."""
66 return 'Azure Pipelines'
67
68 def generate_resource_prefix(self) -> str:
69 """Return a resource prefix specific to this CI provider."""
70 try:
71 prefix = 'azp-%s-%s-%s' % (
72 os.environ['BUILD_BUILDID'],
73 os.environ['SYSTEM_JOBATTEMPT'],
74 os.environ['SYSTEM_JOBIDENTIFIER'],
75 )
76 except KeyError as ex:
77 raise MissingEnvironmentVariable(name=ex.args[0]) from None
78
79 return prefix
80
81 def get_base_commit(self, args: CommonConfig) -> str:
82 """Return the base commit or an empty string."""
83 return self._get_changes(args).base_commit or ''
84
85 def _get_changes(self, args: CommonConfig) -> AzurePipelinesChanges:
86 """Return an AzurePipelinesChanges instance, which will be created on first use."""
87 if not self._changes:
88 self._changes = AzurePipelinesChanges(args)
89
90 return self._changes
91
92 def detect_changes(self, args: TestConfig) -> t.Optional[list[str]]:
93 """Initialize change detection."""
94 result = self._get_changes(args)
95
96 if result.is_pr:
97 job_type = 'pull request'
98 else:
99 job_type = 'merge commit'
100
101 display.info('Processing %s for branch %s commit %s' % (job_type, result.branch, result.commit))
102
103 if not args.metadata.changes:
104 args.metadata.populate_changes(result.diff)
105
106 if result.paths is None:
107 # There are several likely causes of this:
108 # - First run on a new branch.
109 # - Too many pull requests passed since the last merge run passed.
110 display.warning('No successful commit found. All tests will be executed.')
111
112 return result.paths
113
114 def supports_core_ci_auth(self) -> bool:
115 """Return True if Ansible Core CI is supported."""
116 return True
117
118 def prepare_core_ci_request(self, config: dict[str, object], context: AuthContext) -> dict[str, object]:
119 try:
120 request: dict[str, object] = dict(
121 type="azp:ssh",
122 config=config,
123 org_name=os.environ['SYSTEM_COLLECTIONURI'].strip('/').split('/')[-1],
124 project_name=os.environ['SYSTEM_TEAMPROJECT'],
125 build_id=int(os.environ['BUILD_BUILDID']),
126 task_id=str(uuid.UUID(os.environ['SYSTEM_TASKINSTANCEID'])),
127 )
128 except KeyError as ex:
129 raise MissingEnvironmentVariable(name=ex.args[0]) from None
130
131 self.auth.sign_request(request, context)
132
133 return request
134
135 def get_git_details(self, args: CommonConfig) -> t.Optional[dict[str, t.Any]]:
136 """Return details about git in the current environment."""
137 changes = self._get_changes(args)
138
139 details = dict(
140 base_commit=changes.base_commit,
141 commit=changes.commit,
142 )
143
144 return details
145
146
147 class AzurePipelinesAuthHelper(GeneratingAuthHelper):
148 """Authentication helper for Azure Pipelines."""
149
150 def generate_key_pair(self) -> None:
151 super().generate_key_pair()
152
153 public_key_pem = self.public_key_file.read_text()
154
155 try:
156 agent_temp_directory = os.environ['AGENT_TEMPDIRECTORY']
157 except KeyError as ex:
158 raise MissingEnvironmentVariable(name=ex.args[0]) from None
159
160 # the temporary file cannot be deleted because we do not know when the agent has processed it
161 # placing the file in the agent's temp directory allows it to be picked up when the job is running in a container
162 with tempfile.NamedTemporaryFile(prefix='public-key-', suffix='.pem', delete=False, dir=agent_temp_directory) as public_key_file:
163 public_key_file.write(to_bytes(public_key_pem))
164 public_key_file.flush()
165
166 # make the agent aware of the public key by declaring it as an attachment
167 vso_add_attachment('ansible-core-ci', 'public-key.pem', public_key_file.name)
168
169
170 class AzurePipelinesChanges:
171 """Change information for an Azure Pipelines build."""
172
173 def __init__(self, args: CommonConfig) -> None:
174 self.args = args
175 self.git = Git()
176
177 try:
178 self.org_uri = os.environ['SYSTEM_COLLECTIONURI'] # ex: https://dev.azure.com/{org}/
179 self.project = os.environ['SYSTEM_TEAMPROJECT']
180 self.repo_type = os.environ['BUILD_REPOSITORY_PROVIDER'] # ex: GitHub
181 self.source_branch = os.environ['BUILD_SOURCEBRANCH']
182 self.source_branch_name = os.environ['BUILD_SOURCEBRANCHNAME']
183 self.pr_branch_name = os.environ.get('SYSTEM_PULLREQUEST_TARGETBRANCH')
184 except KeyError as ex:
185 raise MissingEnvironmentVariable(name=ex.args[0]) from None
186
187 if self.source_branch.startswith('refs/tags/'):
188 raise ChangeDetectionNotSupported('Change detection is not supported for tags.')
189
190 self.org = self.org_uri.strip('/').split('/')[-1]
191 self.is_pr = self.pr_branch_name is not None
192
193 if self.is_pr:
194 # HEAD is a merge commit of the PR branch into the target branch
195 # HEAD^1 is HEAD of the target branch (first parent of merge commit)
196 # HEAD^2 is HEAD of the PR branch (second parent of merge commit)
197 # see: https://git-scm.com/docs/gitrevisions
198 self.branch = self.pr_branch_name
199 self.base_commit = 'HEAD^1'
200 self.commit = 'HEAD^2'
201 else:
202 commits = self.get_successful_merge_run_commits()
203
204 self.branch = self.source_branch_name
205 self.base_commit = self.get_last_successful_commit(commits)
206 self.commit = 'HEAD'
207
208 self.commit = self.git.run_git(['rev-parse', self.commit]).strip()
209
210 if self.base_commit:
211 self.base_commit = self.git.run_git(['rev-parse', self.base_commit]).strip()
212
213 # <commit>...<commit>
214 # This form is to view the changes on the branch containing and up to the second <commit>, starting at a common ancestor of both <commit>.
215 # see: https://git-scm.com/docs/git-diff
216 dot_range = '%s...%s' % (self.base_commit, self.commit)
217
218 self.paths = sorted(self.git.get_diff_names([dot_range]))
219 self.diff = self.git.get_diff([dot_range])
220 else:
221 self.paths = None # act as though change detection not enabled, do not filter targets
222 self.diff = []
223
224 def get_successful_merge_run_commits(self) -> set[str]:
225 """
226 Return a set of recent successful merge commits from Azure Pipelines.
227 A warning will be displayed and no commits returned if an error occurs.
228 """
229 try:
230 commits = self._get_successful_merge_run_commits()
231 except ApplicationError as ex:
232 commits = set()
233 display.warning(f'Cannot determine changes. All tests will be executed. Reason: {ex}')
234
235 return commits
236
237 def _get_successful_merge_run_commits(self) -> set[str]:
238 """Return a set of recent successful merge commits from Azure Pipelines."""
239 parameters = dict(
240 maxBuildsPerDefinition=100, # max 5000
241 queryOrder='queueTimeDescending', # assumes under normal circumstances that later queued jobs are for later commits
242 resultFilter='succeeded',
243 reasonFilter='batchedCI', # may miss some non-PR reasons, the alternative is to filter the list after receiving it
244 repositoryType=self.repo_type,
245 repositoryId='%s/%s' % (self.org, self.project),
246 )
247
248 url = '%s%s/_apis/build/builds?api-version=7.1&%s' % (self.org_uri, self.project, urllib.parse.urlencode(parameters))
249
250 http = HttpClient(self.args, always=True)
251 response = http.get(url)
252
253 try:
254 result = json.loads(response.response)
255 result_type = 'JSON'
256 except json.JSONDecodeError:
257 result = ...
258 result_type = 'Non-JSON'
259
260 result_description = f'HTTP {response.status_code} {result_type} result'
261
262 if response.status_code != 200 or result is ...:
263 raise ApplicationError(f'Unable to find project due to {result_description}.')
264
265 try:
266 commits = {build['sourceVersion'] for build in result['value']}
267 except KeyError as ex:
268 raise ApplicationError(f'Missing {ex.args[0]!r} key in response from {result_description}.') from ex
269 except (ValueError, TypeError) as ex:
270 raise ApplicationError(f'Unexpected response format from {result_description}: {ex}') from ex
271
272 return commits
273
274 def get_last_successful_commit(self, commits: set[str]) -> t.Optional[str]:
275 """Return the last successful commit from git history that is found in the given commit list, or None."""
276 commit_history = self.git.get_rev_list(max_count=100)
277 ordered_successful_commits = [commit for commit in commit_history if commit in commits]
278 last_successful_commit = ordered_successful_commits[0] if ordered_successful_commits else None
279 return last_successful_commit
280
281
282 def vso_add_attachment(file_type: str, file_name: str, path: str) -> None:
283 """Upload and attach a file to the current timeline record."""
284 vso('task.addattachment', dict(type=file_type, name=file_name), path)
285
286
287 def vso(name: str, data: dict[str, str], message: str) -> None:
288 """
289 Write a logging command for the Azure Pipelines agent to process.
290 See: https://docs.microsoft.com/en-us/azure/devops/pipelines/scripts/logging-commands?view=azure-devops&tabs=bash
291 """
292 display.info('##vso[%s %s]%s' % (name, ';'.join('='.join((key, value)) for key, value in data.items()), message))