forked from cockpit-project/bots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests-scan
executable file
·444 lines (370 loc) · 16.6 KB
/
tests-scan
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
#!/usr/bin/env python3
# This file is part of Cockpit.
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
import argparse
import json
import pipes
import sys
import time
import logging
import itertools
sys.dont_write_bytecode = True
logging.basicConfig(level=logging.INFO)
from task import github, redhat_network, labels_of_pull, distributed_queue, testmap
no_amqp = False
try:
import pika
except ImportError:
no_amqp = True
def build_policy(repo, context):
policy = testmap.tests_for_project(repo)
if context:
short_contexts = []
for c in context:
short_contexts.append(c.split("@")[0])
new_policy = {}
for (branch, contexts) in policy.items():
branch_context = []
for c in short_contexts:
if c in contexts:
branch_context.append(c)
if branch_context:
new_policy[branch] = branch_context
policy = new_policy
return policy
def main():
parser = argparse.ArgumentParser(description='Bot: scan and update status of pull requests on GitHub')
parser.add_argument('-v', '--human-readable', action="store_true", default=False,
help='Display human readable output rather than tasks')
parser.add_argument('-d', '--dry', action="store_true", default=False,
help='Don''t actually change anything on GitHub')
parser.add_argument('--repo', default=None,
help='Repository to scan and checkout.')
parser.add_argument('-c', '--context', action="append", default=[],
help='Test contexts to use.')
parser.add_argument('-p', '--pull-number', default=None,
help='Single pull request to scan for tasks')
parser.add_argument('--pull-data', default=None,
help='pull_request event GitHub JSON data to evaluate; mutualy exclusive with -p and -s')
parser.add_argument('-s', '--sha', default=None,
help='SHA beloging to pull request to scan for tasks')
parser.add_argument('--amqp', default=None,
help='The host:port of the AMQP server to publish to (format host:port)')
opts = parser.parse_args()
if opts.amqp and no_amqp:
logging.error("AMQP host:port specified but python-amqp not available")
return 1
if opts.pull_data and (opts.pull_number or opts.sha):
parser.error("--pull-data and --pull-number/--sha are mutually exclusive")
api = github.GitHub(repo=opts.repo)
# HACK: The `repo` option is used throughout the code, for example repo from
# opts is needed in `tests_invoke`, `tests_human`, `queue_test` etc.
# Would be better to use api.repo everywhere
opts.repo = api.repo
try:
results = scan_for_pull_tasks(api, opts.context, opts, opts.repo)
except RuntimeError as ex:
logging.error("tests-scan: " + str(ex))
return 1
for result in results:
if result:
sys.stdout.write(result + "\n")
return 0
# Prepare a human readable output
def tests_human(priority, name, number, revision, ref, context, base, repo, bots_ref, github_context):
if not priority:
return
try:
priority = int(priority)
except (ValueError, TypeError):
pass
return "{name:11} {context:25} {revision:10} {priority:2}{repo}{bots_ref}{branches}".format(
priority=priority,
revision=revision[0:7],
context=context,
name=name,
repo=repo and " (%s)" % repo or "",
bots_ref=bots_ref and (" [bots@%s]" % bots_ref) or "",
branches=base != ref and (" {%s}" % base) or ""
)
def is_internal_context(context):
for pattern in ["rhel", "edge", "vmware", "openstack"]:
if pattern in context:
return True
return False
# Prepare a test invocation command
def tests_invoke(priority, name, number, revision, ref, context, base,
repo, bots_ref, github_context, options):
if not options.amqp and not redhat_network() and is_internal_context(context):
return ''
try:
priority = int(priority)
except (ValueError, TypeError):
priority = 0
if priority <= 0:
return
current = time.strftime('%Y%m%d-%H%M%S')
(image, _, scenario) = context.partition("/")
checkout = "PRIORITY={priority:04d} ./make-checkout --verbose --repo={repo}"
invoke = "../tests-invoke --pull-number {pull_number} --revision {revision} --repo {github_base}"
test_env = "TEST_OS={image}"
wrapper = "./publish-wrapper --repo {github_base} --test-name {name}-{current} " \
"--github-context {github_context} --revision {revision}"
if base != ref:
checkout += " --rebase={base}"
if bots_ref:
# we are checking the external repo on a cockpit PR, so stay on the project's master
checkout += " {ref}"
test_env += " COCKPIT_BOTS_REF={bots_ref}"
else:
# we are testing the repo itself, checkout revision from the PR
checkout += " {ref} {revision}"
if scenario:
test_env += " TEST_SCENARIO={scenario}"
cmd = " ".join([checkout, "&& cd make-checkout-workdir &&", test_env, invoke])
return (wrapper + ' "' + cmd + '"').format(
priority=priority,
name=pipes.quote(name),
revision=pipes.quote(revision),
base=pipes.quote(str(base)),
ref=pipes.quote(ref),
bots_ref=pipes.quote(bots_ref),
image=pipes.quote(image),
scenario=(pipes.quote(scenario)),
github_context=github_context,
current=current,
pull_number=number,
repo=pipes.quote(repo),
github_base=pipes.quote(options.repo),
)
def queue_test(priority, name, number, revision, ref, context, base,
repo, bots_ref, github_context, channel, options):
command = tests_invoke(priority, name, number, revision, ref, context, base,
repo, bots_ref, github_context, options)
if command:
if priority > distributed_queue.MAX_PRIORITY:
priority = distributed_queue.MAX_PRIORITY
body = {
"command": command,
"type": "test",
"sha": revision,
"ref": ref,
"name": name,
}
queue = 'rhel' if is_internal_context(context) else 'public'
channel.basic_publish('', queue, json.dumps(body), properties=pika.BasicProperties(priority=priority))
logging.info("Published '{0}' on '{1}' with command: '{2}'".format(name, revision, command))
def prioritize(status, title, labels, priority, context, number):
state = status.get("state", None)
update = {"state": "pending"}
# This commit definitively succeeded or failed
if state in ["success", "failure"]:
logging.info("Skipping '{0}' on #{1} because it has already finished".format(context, number))
priority = 0
update = None
# This test errored, we try again but low priority
elif state in ["error"]:
priority -= 2
elif state in ["pending"]:
logging.info("Not updating status for '{0}' on #{1} because it is pending".format(context, number))
update = None
# Ignore context when the PR has [no-test] in the title or as label, unless
# the context was directly triggered
if (('no-test' in labels or '[no-test]' in title) and status.get("description", "") != github.NOT_TESTED_DIRECT):
logging.info("Skipping '{0}' on #{1} because it is no-test".format(context, number))
priority = 0
update = None
if priority > 0:
if "priority" in labels:
priority += 2
if "blocked" in labels:
priority -= 1
# Pull requests where the title starts with WIP get penalized
if title.startswith("WIP") or "needswork" in labels:
priority -= 1
# Is testing already in progress?
description = status.get("description", "")
if description.startswith(github.TESTING):
logging.info("Skipping '{0}' on #{1} because it is already running".format(context, number))
priority = description
update = None
if update:
if priority <= 0:
logging.info("Not updating status for '{0}' on #{1} because of low priority".format(context, number))
update = None
else:
update["description"] = github.NOT_TESTED
return [priority, update]
def dict_is_subset(full, check):
for (key, value) in check.items():
if key not in full or full[key] != value:
return False
return True
def update_status(api, revision, context, last, changes):
if changes:
changes["context"] = context
if changes and not dict_is_subset(last, changes):
response = api.post("statuses/" + revision, changes, accept=[422]) # 422 Unprocessable Entity
errors = response.get("errors", None)
if not errors:
return True
for error in response.get("errors", []):
sys.stderr.write("{0}: {1}\n".format(revision, error.get('message', json.dumps(error))))
sys.stderr.write(json.dumps(changes))
return False
return True
def cockpit_tasks(api, update, contexts, repo, pull_data, pull_number, sha, amqp):
results = []
pulls = []
branch_contexts = testmap.tests_for_project(repo).values()
repo_contexts = set(itertools.chain(*branch_contexts))
if pull_data:
pulls.append(json.loads(pull_data)['pull_request'])
elif pull_number:
pull = api.get("pulls/{0}".format(pull_number))
if pull:
pulls.append(pull)
else:
logging.error("Can't find pull request {0}".format(pull_number))
return 1
else:
pulls = api.pulls()
whitelist = api.whitelist()
for pull in pulls:
title = pull["title"]
number = pull["number"]
revision = pull["head"]["sha"]
statuses = api.statuses(revision)
login = pull["head"]["user"]["login"]
base = pull["base"]["ref"] # The branch this pull request targets
logging.info("Processing #{0} titled '{1}' on revision {2}".format(number, title, revision))
# If sha is present only scan PR with selected sha
if sha and revision != sha and not revision.startswith(sha):
continue
labels = labels_of_pull(pull)
baseline = distributed_queue.BASELINE_PRIORITY
# amqp automatically prioritizes on age
if not amqp:
# modify the baseline slightly to favor older pull requests, so that we don't
# end up with a bunch of half tested pull requests
baseline += 1.0 - (min(100000, float(number)) / 100000)
def split_context(context):
os_scenario = ""
bots_pr = ""
repo_branch = ""
context_parts = context.split("@")
os_scenario = context_parts[0]
# Second part can be be either `bots#<pr_number>` or repo specification
if len(context_parts) > 1:
if context_parts[1].startswith("bots#"):
bots_pr = int(context_parts[1][5:])
else:
repo_branch = context_parts[1]
if len(context_parts) > 2:
repo_branch = context_parts[2]
return (os_scenario, bots_pr, repo_branch)
def is_valid_context(context):
os_scenario, bots_pr, repo_branch = split_context(context)
# If contexts were specified on commandline, only those are valid
# Of course if you specify invalid context in `tests-scan` it will be happy about it
# But this can be used when want to try new context which does not yet exists in map
if contexts:
for c in contexts:
c = c.split("@")[0]
if c == os_scenario:
return True
return False
# If repo in context, consider only contexts from the given repo
if repo_branch:
repo_branch = "/".join(repo_branch.split("/")[:2])
repo_cs = testmap.tests_for_project(repo_branch).values()
return os_scenario in set(itertools.chain(*repo_cs))
# Valid contexts are the ones that exist in the current repo
return os_scenario in repo_contexts
# Create list of statuses to process
todos = {}
for status in statuses: # Firstly add all valid contexts that already exist in github
if is_valid_context(status):
todos[status] = statuses[status]
if not statuses: # If none defined in github add basic set of contexts
for context in build_policy(repo, contexts).get(base, []):
todos[context] = {}
# there are 3 different HEADs
# ref: the PR that we are testing
# base: the target branch of that PR
# branch: the branch of the external project that we are testing
# against this PR (only applies to cockpit-project/bots PRs)
for context in todos:
# Get correct project and branch. Ones from test name have priority
project = repo
branch = base
os_scenario, bots_pr, repo_branch = split_context(context)
repo_branch = repo_branch.split("/")
if len(repo_branch) == 2:
project = "/".join(repo_branch)
branch = "master"
elif len(repo_branch) == 3:
project = "/".join(repo_branch[:2])
branch = repo_branch[2]
ref = "pull/%d/head" % number
# For unmarked and untested status, user must be in whitelist
# Not this only applies to this specific commit. A new status
# will apply if the user pushes a new commit.
status = todos[context]
if login not in whitelist and status.get("description", github.NO_TESTING) == github.NO_TESTING:
priority = github.NO_TESTING
changes = {"description": github.NO_TESTING, "context": context, "state": "pending"}
else:
(priority, changes) = prioritize(status, title, labels, baseline, context, number)
if not update or update_status(api, revision, context, status, changes):
checkout_ref = ref
if project != repo:
checkout_ref = "master"
if base != branch:
checkout_ref = branch
if repo == "cockpit-project/bots":
# bots own test doesn't need bots/ setup as there is a permanent symlink to itself there
# otherwise if we're testing an external project (repo != project) then checkout bots from the PR
bots_ref = None if repo == project else ref
else:
if bots_pr:
bots_ref = "pull/%d/head" % bots_pr
else:
bots_ref = "master"
results.append((priority,
"pull-%d" % number,
number,
revision,
checkout_ref,
os_scenario,
branch,
project,
bots_ref,
context
))
return results
def scan_for_pull_tasks(api, contexts, opts, repo):
results = cockpit_tasks(api, not opts.dry, contexts, repo, opts.pull_data, opts.pull_number, opts.sha, opts.amqp)
if opts.human_readable:
results.sort(reverse=True, key=lambda x: str(x))
return list([tests_human(*x) for x in results])
if not opts.amqp:
return list([tests_invoke(*x, options=opts) for x in results])
with distributed_queue.DistributedQueue(opts.amqp, ['rhel', 'public']) as q:
return list([queue_test(*x, channel=q.channel, options=opts) for x in results])
if __name__ == '__main__':
sys.exit(main())