|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +""" |
| 4 | +Script to generate user defined unique ID which can be used to |
| 5 | +check the status of the regression test run to be reported to the CI. |
| 6 | +""" |
| 7 | +import argparse |
| 8 | +from datetime import datetime, timedelta, timezone |
| 9 | +import random |
| 10 | +import string |
| 11 | +import time |
| 12 | +import requests |
| 13 | +from requests.auth import HTTPBasicAuth, AuthBase |
| 14 | + |
| 15 | +# This should be set to a known good version of regression test repo |
| 16 | +GITHUB_API_URL = "https://api.github.com/repos/NHSDigital/eligibility-signposting-api-regression-tests/actions" |
| 17 | +GITHUB_RUN_URL = "https://github.com/NHSDigital/eligibility-signposting-api-regression-tests/actions/runs" |
| 18 | + |
| 19 | + |
| 20 | +class BearerAuth(AuthBase): |
| 21 | + def __init__(self, token): |
| 22 | + self.token = token |
| 23 | + |
| 24 | + def __call__(self, r): |
| 25 | + r.headers["authorization"] = "Bearer " + self.token |
| 26 | + return r |
| 27 | + |
| 28 | + |
| 29 | +def get_headers(): |
| 30 | + return { |
| 31 | + "Accept": "application/vnd.github+json", |
| 32 | + "X-GitHub-Api-Version": "2022-11-28", |
| 33 | + } |
| 34 | + |
| 35 | + |
| 36 | +def generate_unique_run_id(length=15): |
| 37 | + return "".join(random.choices(string.ascii_uppercase + string.digits, k=length)) |
| 38 | + |
| 39 | + |
| 40 | +def generate_timestamp(): |
| 41 | + delta_time = timedelta(minutes=2) |
| 42 | + date_time = (datetime.now(timezone.utc) - delta_time).strftime("%Y-%m-%dT%H:%M") |
| 43 | + print(f"Generated Date as: {date_time}") |
| 44 | + return date_time |
| 45 | + |
| 46 | + |
| 47 | +def trigger_test_run( |
| 48 | + env, |
| 49 | + pr_label, |
| 50 | + auth_header, |
| 51 | + run_id, |
| 52 | + regression_test_repo_tag, |
| 53 | + regression_test_workflow_tag, |
| 54 | +): |
| 55 | + body = { |
| 56 | + "ref": regression_test_workflow_tag, |
| 57 | + "inputs": { |
| 58 | + "id": run_id, |
| 59 | + "tags": "@regression", |
| 60 | + "environment": env.lower(), |
| 61 | + "pull_request_id": pr_label, |
| 62 | + "github_tag": regression_test_repo_tag, |
| 63 | + }, |
| 64 | + } |
| 65 | + |
| 66 | + response = requests.post( |
| 67 | + url=f"{GITHUB_API_URL}/workflows/regression_tests.yml/dispatches", |
| 68 | + headers=get_headers(), |
| 69 | + auth=auth_header, |
| 70 | + json=body, |
| 71 | + timeout=120, |
| 72 | + ) |
| 73 | + |
| 74 | + print(f"Dispatch workflow. Unique workflow identifier: {run_id}") |
| 75 | + assert ( |
| 76 | + response.status_code == 204 |
| 77 | + ), f"Failed to trigger test run. Expected 204, got {response.status_code}. Response: {response.text}" |
| 78 | + |
| 79 | + |
| 80 | +def get_workflow_runs(auth_header, run_date_filter): |
| 81 | + print(f"Getting workflow runs after date: {run_date_filter}") |
| 82 | + response = requests.get( |
| 83 | + f"{GITHUB_API_URL}/runs?created=%3E{run_date_filter}", |
| 84 | + headers=get_headers(), |
| 85 | + auth=auth_header, |
| 86 | + timeout=120, |
| 87 | + ) |
| 88 | + assert ( |
| 89 | + response.status_code == 200 |
| 90 | + ), f"Unable to get workflow runs. Expected 200, got {response.status_code}" |
| 91 | + return response.json()["workflow_runs"] |
| 92 | + |
| 93 | + |
| 94 | +def get_jobs_for_workflow(jobs_url, auth_header): |
| 95 | + print("Getting jobs for workflow...") |
| 96 | + response = requests.get(jobs_url, auth=auth_header, timeout=120) |
| 97 | + assert ( |
| 98 | + response.status_code == 200 |
| 99 | + ), f"Unable to get workflow jobs. Expected 200, got {response.status_code}" |
| 100 | + return response.json()["jobs"] |
| 101 | + |
| 102 | + |
| 103 | +def find_workflow(auth_header, run_id, run_date_filter): |
| 104 | + max_attempts = 5 |
| 105 | + current_attempt = 0 |
| 106 | + |
| 107 | + while current_attempt < max_attempts: |
| 108 | + time.sleep(10) |
| 109 | + current_attempt = current_attempt + 1 |
| 110 | + print(f"Attempt {current_attempt}") |
| 111 | + |
| 112 | + workflow_runs = get_workflow_runs(auth_header, run_date_filter) |
| 113 | + for workflow in workflow_runs: |
| 114 | + time.sleep(3) |
| 115 | + current_workflow_id = workflow["id"] |
| 116 | + jobs_url = workflow["jobs_url"] |
| 117 | + |
| 118 | + list_of_jobs = get_jobs_for_workflow(jobs_url, auth_header) |
| 119 | + |
| 120 | + if list_of_jobs: |
| 121 | + job = list_of_jobs[0] # this is fine to get the first job |
| 122 | + steps = job["steps"] |
| 123 | + |
| 124 | + if len(steps) >= 2: |
| 125 | + third_step = steps[2] |
| 126 | + if third_step["name"] == run_id: |
| 127 | + print(f"Workflow Job found! Using ID: {current_workflow_id}") |
| 128 | + return current_workflow_id |
| 129 | + else: |
| 130 | + print("Not enough steps have been executed for this run yet...") |
| 131 | + else: |
| 132 | + print("Jobs for this workflow run haven't populated yet...") |
| 133 | + print( |
| 134 | + "Processed all available workflows but no jobs were matching the Unique ID were found!" |
| 135 | + ) |
| 136 | + return None |
| 137 | + |
| 138 | + |
| 139 | +def get_auth_header(token): |
| 140 | + return BearerAuth(token) |
| 141 | + |
| 142 | + |
| 143 | +def get_job(auth_header, workflow_id): |
| 144 | + job_request_url = f"{GITHUB_API_URL}/runs/{workflow_id}/jobs" |
| 145 | + job_response = requests.get( |
| 146 | + job_request_url, |
| 147 | + headers=get_headers(), |
| 148 | + auth=auth_header, |
| 149 | + ) |
| 150 | + return job_response.json()["jobs"][0] |
| 151 | + |
| 152 | + |
| 153 | +def check_job(auth_header, workflow_id): |
| 154 | + print("Checking job status, please wait...") |
| 155 | + print("Current status:", end=" ") |
| 156 | + job = get_job(auth_header, workflow_id) |
| 157 | + job_status = job["status"] |
| 158 | + |
| 159 | + while job_status != "completed": |
| 160 | + print(job_status) |
| 161 | + time.sleep(10) |
| 162 | + job = get_job(auth_header, workflow_id) |
| 163 | + job_status = job["status"] |
| 164 | + |
| 165 | + return job["conclusion"] |
| 166 | + |
| 167 | + |
| 168 | +def main(): |
| 169 | + parser = argparse.ArgumentParser() |
| 170 | + |
| 171 | + parser.add_argument( |
| 172 | + "--pr_label", |
| 173 | + required=False, |
| 174 | + default="None", |
| 175 | + help="Please provide the PR number.", |
| 176 | + ) |
| 177 | + parser.add_argument( |
| 178 | + "--env", |
| 179 | + required=True, |
| 180 | + help="Please provide the environment you wish to run in.", |
| 181 | + ) |
| 182 | + parser.add_argument( |
| 183 | + "--token", required=False, help="Please provide the authentication token." |
| 184 | + ) |
| 185 | + parser.add_argument( |
| 186 | + "--regression_test_repo_tag", |
| 187 | + required=True, |
| 188 | + help="Please provide the tag to run regression tests from.", |
| 189 | + ) |
| 190 | + parser.add_argument( |
| 191 | + "--regression_test_workflow_tag", |
| 192 | + required=False, |
| 193 | + default="main", |
| 194 | + help="Please provide the tag to for the run_regression_test workflow.", |
| 195 | + ) |
| 196 | + |
| 197 | + arguments = parser.parse_args() |
| 198 | + |
| 199 | + print(f"pr_label: {arguments.pr_label}") |
| 200 | + print(f"env: {arguments.env}") |
| 201 | + print(f"regression_tests_repo_tag: {arguments.regression_test_repo_tag}") |
| 202 | + print(f"regression_test_workflow_tag: {arguments.regression_test_workflow_tag}") |
| 203 | + |
| 204 | + run_id = generate_unique_run_id() |
| 205 | + run_date_filter = generate_timestamp() |
| 206 | + auth_header = get_auth_header(arguments.token) |
| 207 | + |
| 208 | + pr_label = arguments.pr_label.lower() |
| 209 | + trigger_test_run( |
| 210 | + arguments.env, |
| 211 | + pr_label, |
| 212 | + auth_header, |
| 213 | + run_id, |
| 214 | + arguments.regression_test_repo_tag, |
| 215 | + arguments.regression_test_workflow_tag, |
| 216 | + ) |
| 217 | + |
| 218 | + workflow_id = find_workflow(auth_header, run_id, run_date_filter) |
| 219 | + print(f"See {GITHUB_RUN_URL}/{workflow_id}/ for run details") |
| 220 | + job_status = check_job(auth_header, workflow_id) |
| 221 | + if job_status != "success": |
| 222 | + print("The regressions test step failed! There are likely test failures.") |
| 223 | + raise SystemError("Regression test failed") |
| 224 | + print("Success!") |
| 225 | + |
| 226 | + |
| 227 | +if __name__ == "__main__": |
| 228 | + main() |
0 commit comments