Debian Codegraph @

ansible_collections/community/libvirt/tests/utils/shippable/check_matrix.py

raw
1 #!/usr/bin/env python
2 """Verify the currently executing Shippable test matrix matches the one defined in the "shippable.yml" file."""
3 from __future__ import (absolute_import, division, print_function)
4 __metaclass__ = type
5
6 import datetime
7 import json
8 import os
9 import re
10 import sys
11 import time
12
13 try:
14 from typing import NoReturn
15 except ImportError:
16 NoReturn = None
17
18 try:
19 # noinspection PyCompatibility
20 from urllib2 import urlopen # pylint: disable=ansible-bad-import-from
21 except ImportError:
22 # noinspection PyCompatibility
23 from urllib.request import urlopen
24
25
26 def main(): # type: () -> None
27 """Main entry point."""
28 repo_full_name = os.environ['REPO_FULL_NAME']
29 required_repo_full_name = 'ansible-collections/community.libvirt'
30
31 if repo_full_name != required_repo_full_name:
32 sys.stderr.write('Skipping matrix check on repo "%s" which is not "%s".\n' % (repo_full_name, required_repo_full_name))
33 return
34
35 with open('shippable.yml', 'rb') as yaml_file:
36 yaml = yaml_file.read().decode('utf-8').splitlines()
37
38 defined_matrix = [match.group(1) for match in [re.search(r'^ *- env: T=(.*)$', line) for line in yaml] if match and match.group(1) != 'none']
39
40 if not defined_matrix:
41 fail('No matrix entries found in the "shippable.yml" file.',
42 'Did you modify the "shippable.yml" file?')
43
44 run_id = os.environ['SHIPPABLE_BUILD_ID']
45 sleep = 1
46 jobs = []
47
48 for attempts_remaining in range(4, -1, -1):
49 try:
50 jobs = json.loads(urlopen('https://api.shippable.com/jobs?runIds=%s' % run_id).read())
51
52 if not isinstance(jobs, list):
53 raise Exception('Shippable run %s data is not a list.' % run_id)
54
55 break
56 except Exception as ex:
57 if not attempts_remaining:
58 fail('Unable to retrieve Shippable run %s matrix.' % run_id,
59 str(ex))
60
61 sys.stderr.write('Unable to retrieve Shippable run %s matrix: %s\n' % (run_id, ex))
62 sys.stderr.write('Trying again in %d seconds...\n' % sleep)
63 time.sleep(sleep)
64 sleep *= 2
65
66 if len(jobs) != len(defined_matrix):
67 if len(jobs) == 1:
68 hint = '\n\nMake sure you do not use the "Rebuild with SSH" option.'
69 else:
70 hint = ''
71
72 fail('Shippable run %s has %d jobs instead of the expected %d jobs.' % (run_id, len(jobs), len(defined_matrix)),
73 'Try re-running the entire matrix.%s' % hint)
74
75 actual_matrix = dict((job.get('jobNumber'), dict(tuple(line.split('=', 1)) for line in job.get('env', [])).get('T', '')) for job in jobs)
76 errors = [(job_number, test, actual_matrix.get(job_number)) for job_number, test in enumerate(defined_matrix, 1) if actual_matrix.get(job_number) != test]
77
78 if len(errors):
79 error_summary = '\n'.join('Job %s expected "%s" but found "%s" instead.' % (job_number, expected, actual) for job_number, expected, actual in errors)
80
81 fail('Shippable run %s has a job matrix mismatch.' % run_id,
82 'Try re-running the entire matrix.\n\n%s' % error_summary)
83
84
85 def fail(message, output): # type: (str, str) -> NoReturn
86 # Include a leading newline to improve readability on Shippable "Tests" tab.
87 # Without this, the first line becomes indented.
88 output = '\n' + output.strip()
89
90 timestamp = datetime.datetime.utcnow().replace(microsecond=0).isoformat()
91
92 # hack to avoid requiring junit-xml, which isn't pre-installed on Shippable outside our test containers
93 xml = '''
94 <?xml version="1.0" encoding="utf-8"?>
95 <testsuites disabled="0" errors="1" failures="0" tests="1" time="0.0">
96 \t<testsuite disabled="0" errors="1" failures="0" file="None" log="None" name="ansible-test" skipped="0" tests="1" time="0" timestamp="%s" url="None">
97 \t\t<testcase classname="timeout" name="timeout">
98 \t\t\t<error message="%s" type="error">%s</error>
99 \t\t</testcase>
100 \t</testsuite>
101 </testsuites>
102 ''' % (timestamp, message, output)
103
104 path = 'shippable/testresults/check-matrix.xml'
105 dir_path = os.path.dirname(path)
106
107 if not os.path.exists(dir_path):
108 os.makedirs(dir_path)
109
110 with open(path, 'w') as junit_fd:
111 junit_fd.write(xml.lstrip())
112
113 sys.stderr.write(message + '\n')
114 sys.stderr.write(output + '\n')
115
116 sys.exit(1)
117
118
119 if __name__ == '__main__':
120 main()