Debian Codegraph @

hacking/azp/download.py

raw
1 #!/usr/bin/env python
2 # PYTHON_ARGCOMPLETE_OK
3
4 # (c) 2016 Red Hat, Inc.
5 #
6 # This file is part of Ansible
7 #
8 # Ansible is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Ansible is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
20 """CLI tool for downloading results from Azure Pipelines CI runs."""
21
22 from __future__ import annotations
23
24 # noinspection PyCompatibility
25 import argparse
26 import json
27 import os
28 import re
29 import io
30 import shutil
31 import zipfile
32 import urllib.request
33 import urllib.error
34
35 try:
36 import argcomplete
37 except ImportError:
38 argcomplete = None
39
40
41 def main():
42 """Main program body."""
43
44 args = parse_args()
45 download_run(args)
46
47
48 def run_id_arg(arg):
49 m = re.fullmatch(r"(?:https:\/\/dev\.azure\.com\/ansible\/ansible\/_build\/results\?buildId=)?(\d+)", arg)
50 if not m:
51 raise ValueError("run does not seems to be a URI or an ID")
52 return m.group(1)
53
54
55 def parse_args():
56 """Parse and return args."""
57
58 parser = argparse.ArgumentParser(description='Download results from a CI run.')
59
60 parser.add_argument('run', metavar='RUN', type=run_id_arg, help='AZP run id or URI')
61
62 parser.add_argument('-v', '--verbose',
63 dest='verbose',
64 action='store_true',
65 help='show what is being downloaded')
66
67 parser.add_argument('-t', '--test',
68 dest='test',
69 action='store_true',
70 help='show what would be downloaded without downloading')
71
72 parser.add_argument('-p', '--pipeline-id', type=int, default=20, help='pipeline to download the job from')
73
74 parser.add_argument('--artifacts',
75 action='store_true',
76 help='download artifacts')
77
78 parser.add_argument('--console-logs',
79 action='store_true',
80 help='download console logs')
81
82 parser.add_argument('--run-metadata',
83 action='store_true',
84 help='download run metadata')
85
86 parser.add_argument('--all',
87 action='store_true',
88 help='download everything')
89
90 parser.add_argument('--match-artifact-name',
91 default=re.compile('.*'),
92 type=re.compile,
93 help='only download artifacts which names match this regex')
94
95 parser.add_argument('--match-job-name',
96 default=re.compile('.*'),
97 type=re.compile,
98 help='only download artifacts from jobs which names match this regex')
99
100 if argcomplete:
101 argcomplete.autocomplete(parser)
102
103 args = parser.parse_args()
104
105 if args.all:
106 args.artifacts = True
107 args.run_metadata = True
108 args.console_logs = True
109
110 selections = (
111 args.artifacts,
112 args.run_metadata,
113 args.console_logs
114 )
115
116 if not any(selections):
117 parser.error('At least one download option is required.')
118
119 return args
120
121
122 def download_run(args):
123 """Download a run."""
124
125 output_dir = '%s' % args.run
126
127 if not args.test and not os.path.exists(output_dir):
128 os.makedirs(output_dir)
129
130 if args.run_metadata:
131 run_url = 'https://dev.azure.com/ansible/ansible/_apis/pipelines/%s/runs/%s?api-version=6.0-preview.1' % (args.pipeline_id, args.run)
132 with urllib.request.urlopen(run_url) as run_info_response:
133 run = json.load(run_info_response)
134
135 path = os.path.join(output_dir, 'run.json')
136 contents = json.dumps(run, sort_keys=True, indent=4)
137
138 if args.verbose:
139 print(path)
140
141 if not args.test:
142 with open(path, 'w') as metadata_fd:
143 metadata_fd.write(contents)
144
145 with urllib.request.urlopen('https://dev.azure.com/ansible/ansible/_apis/build/builds/%s/timeline?api-version=6.0' % args.run) as timeline_response:
146 timeline = json.load(timeline_response)
147 roots = set()
148 by_id = {}
149 children_of = {}
150 parent_of = {}
151 for r in timeline['records']:
152 thisId = r['id']
153 parentId = r['parentId']
154
155 by_id[thisId] = r
156
157 if parentId is None:
158 roots.add(thisId)
159 else:
160 parent_of[thisId] = parentId
161 children_of[parentId] = children_of.get(parentId, []) + [thisId]
162
163 allowed = set()
164
165 def allow_recursive(ei):
166 allowed.add(ei)
167 for ci in children_of.get(ei, []):
168 allow_recursive(ci)
169
170 for ri in roots:
171 r = by_id[ri]
172 allowed.add(ri)
173 for ci in children_of.get(r['id'], []):
174 c = by_id[ci]
175 if not args.match_job_name.match("%s %s" % (r['name'], c['name'])):
176 continue
177 allow_recursive(c['id'])
178
179 if args.artifacts:
180 artifact_list_url = 'https://dev.azure.com/ansible/ansible/_apis/build/builds/%s/artifacts?api-version=6.0' % args.run
181 with urllib.request.urlopen(artifact_list_url) as artifact_list_response:
182 artifact_list = json.load(artifact_list_response)
183
184 for artifact in artifact_list['value']:
185 if artifact['source'] not in allowed or not args.match_artifact_name.match(artifact['name']):
186 continue
187 if args.verbose:
188 print('%s/%s' % (output_dir, artifact['name']))
189 if not args.test:
190 with urllib.request.urlopen(artifact['resource']['downloadUrl']) as response:
191 with io.BytesIO() as buffer:
192 shutil.copyfileobj(response, buffer)
193 buffer.seek(0)
194 with zipfile.ZipFile(buffer) as archive:
195 archive.extractall(path=output_dir)
196
197 if args.console_logs:
198 for r in timeline['records']:
199 if not r['log'] or r['id'] not in allowed or not args.match_artifact_name.match(r['name']):
200 continue
201 names = []
202 parent_id = r['id']
203 while parent_id is not None:
204 p = by_id[parent_id]
205 name = p['name']
206 if name not in names:
207 names = [name] + names
208 parent_id = parent_of.get(p['id'], None)
209
210 path = " ".join(names)
211
212 # Some job names have the separator in them.
213 path = path.replace(os.sep, '_')
214
215 log_path = os.path.join(output_dir, '%s.log' % path)
216 if args.verbose:
217 print(log_path)
218 if not args.test:
219 with urllib.request.urlopen(r['log']['url']) as log:
220 with open(log_path, 'wb') as log_file:
221 shutil.copyfileobj(log, log_file)
222
223
224 if __name__ == '__main__':
225 main()