Debian Codegraph @

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