2022-10-27 10:27:04 +00:00
|
|
|
#!/bin/python3
|
|
|
|
|
2022-10-28 02:00:37 +00:00
|
|
|
# A simple script to trigger Cirrus CI builds and download the release artifacts
|
|
|
|
# through Cirrus CI's GraphQL interface.
|
|
|
|
#
|
|
|
|
# Expects the Cirrus CI API key to be set in the CIRRUS_KEY environment variable.
|
2024-01-28 23:11:05 +00:00
|
|
|
#
|
|
|
|
# TODO: Explain this in docs how the heck this works.
|
2022-10-27 10:27:04 +00:00
|
|
|
|
|
|
|
import os
|
|
|
|
import json
|
|
|
|
import sys
|
2022-11-10 05:46:45 +00:00
|
|
|
import traceback
|
2022-10-27 10:27:04 +00:00
|
|
|
from textwrap import dedent
|
|
|
|
from time import sleep, time
|
|
|
|
from pathlib import Path
|
2024-01-28 23:11:05 +00:00
|
|
|
from typing import List, Optional, Tuple
|
2022-10-27 10:27:04 +00:00
|
|
|
|
|
|
|
from urllib.request import Request, urlopen, urlretrieve
|
|
|
|
|
2024-01-28 23:11:05 +00:00
|
|
|
# Form of each task is (TASK_ALIAS, FILE_NAME).
|
|
|
|
TASKS: List[Tuple[str, str]] = [
|
2024-03-03 06:17:14 +00:00
|
|
|
("freebsd_13_3_build", "bottom_x86_64-unknown-freebsd-13-3.tar.gz"),
|
2024-01-28 23:11:05 +00:00
|
|
|
("freebsd_14_0_build", "bottom_x86_64-unknown-freebsd-14-0.tar.gz"),
|
|
|
|
("linux_2_17_build", "bottom_x86_64-unknown-linux-gnu-2-17.tar.gz"),
|
2022-10-27 10:27:04 +00:00
|
|
|
]
|
2024-01-28 23:11:05 +00:00
|
|
|
URL = "https://api.cirrus-ci.com/graphql"
|
2022-10-27 10:27:04 +00:00
|
|
|
DL_URL_TEMPLATE = "https://api.cirrus-ci.com/v1/artifact/build/%s/%s/binaries/%s"
|
|
|
|
|
|
|
|
|
2024-08-02 04:49:53 +00:00
|
|
|
def make_query_request(key: str, branch: str, mutation_id: str):
|
2022-10-27 10:27:04 +00:00
|
|
|
print("Creating query request.")
|
2023-01-02 20:18:05 +00:00
|
|
|
|
|
|
|
# Dumb but if it works...
|
|
|
|
config_override = (
|
2024-08-01 23:52:11 +00:00
|
|
|
Path(".cirrus.yml")
|
|
|
|
.read_text()
|
|
|
|
.replace("# -PLACEHOLDER FOR CI-", 'BTM_BUILD_RELEASE_CALLER: "ci"')
|
2023-01-02 20:18:05 +00:00
|
|
|
)
|
2024-08-02 04:49:53 +00:00
|
|
|
|
2022-10-27 10:27:04 +00:00
|
|
|
query = """
|
|
|
|
mutation CreateCirrusCIBuild (
|
|
|
|
$repo: ID!,
|
|
|
|
$branch: String!,
|
2023-01-02 20:18:05 +00:00
|
|
|
$mutation_id: String!,
|
|
|
|
$config_override: String,
|
2022-10-27 10:27:04 +00:00
|
|
|
) {
|
2024-08-01 23:52:11 +00:00
|
|
|
createBuild (
|
2022-10-27 10:27:04 +00:00
|
|
|
input: {
|
|
|
|
repositoryId: $repo,
|
|
|
|
branch: $branch,
|
|
|
|
clientMutationId: $mutation_id,
|
2023-01-02 20:18:05 +00:00
|
|
|
configOverride: $config_override
|
2022-10-27 10:27:04 +00:00
|
|
|
}
|
|
|
|
) {
|
|
|
|
build {
|
|
|
|
id,
|
|
|
|
status
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"""
|
2024-08-02 04:49:53 +00:00
|
|
|
|
2022-10-27 10:27:04 +00:00
|
|
|
params = {
|
|
|
|
"repo": "6646638922956800",
|
|
|
|
"branch": branch,
|
|
|
|
"mutation_id": mutation_id,
|
2023-01-02 20:18:05 +00:00
|
|
|
"config_override": dedent(config_override),
|
2022-10-27 10:27:04 +00:00
|
|
|
}
|
2024-08-02 04:49:53 +00:00
|
|
|
|
2022-10-27 10:27:04 +00:00
|
|
|
data = {"query": dedent(query), "variables": params}
|
|
|
|
data = json.dumps(data).encode()
|
|
|
|
|
|
|
|
request = Request(URL, data=data, method="POST")
|
|
|
|
request.add_header("Authorization", "Bearer {}".format(key))
|
|
|
|
|
|
|
|
return request
|
|
|
|
|
|
|
|
|
2024-08-02 04:49:53 +00:00
|
|
|
def check_build_status(key: str, build_id: str) -> Optional[str]:
|
2022-10-27 10:27:04 +00:00
|
|
|
query = """
|
|
|
|
query BuildStatus($id: ID!) {
|
|
|
|
build(id: $id) {
|
|
|
|
status
|
2024-08-02 04:49:53 +00:00
|
|
|
}
|
2022-10-27 10:27:04 +00:00
|
|
|
}
|
|
|
|
"""
|
2024-08-02 04:49:53 +00:00
|
|
|
|
2022-10-27 10:27:04 +00:00
|
|
|
params = {
|
2024-08-02 04:49:53 +00:00
|
|
|
"id": build_id,
|
2022-10-27 10:27:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
data = {"query": dedent(query), "variables": params}
|
|
|
|
data = json.dumps(data).encode()
|
|
|
|
|
|
|
|
request = Request(URL, data=data, method="POST")
|
|
|
|
request.add_header("Authorization", "Bearer {}".format(key))
|
|
|
|
with urlopen(request) as response:
|
|
|
|
response = json.load(response)
|
|
|
|
if response.get("errors") is not None:
|
|
|
|
print("There was an error in the returned response.")
|
|
|
|
return None
|
|
|
|
|
|
|
|
try:
|
|
|
|
status = response["data"]["build"]["status"]
|
|
|
|
return status
|
|
|
|
except KeyError:
|
2024-08-02 04:49:53 +00:00
|
|
|
print("There was an issue with checking the build status.")
|
2022-10-27 10:27:04 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
2024-08-02 04:49:53 +00:00
|
|
|
def check_build_tasks(key: str, build_id: str) -> Optional[List[str]]:
|
|
|
|
query = """
|
|
|
|
query Build($id:ID!) {
|
|
|
|
build(id:$id){
|
|
|
|
tasks {
|
|
|
|
id
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"""
|
|
|
|
|
|
|
|
params = {
|
|
|
|
"id": build_id,
|
|
|
|
}
|
|
|
|
|
|
|
|
data = {"query": dedent(query), "variables": params}
|
|
|
|
data = json.dumps(data).encode()
|
|
|
|
|
|
|
|
request = Request(URL, data=data, method="POST")
|
|
|
|
request.add_header("Authorization", "Bearer {}".format(key))
|
|
|
|
with urlopen(request) as response:
|
|
|
|
response = json.load(response)
|
|
|
|
|
|
|
|
if response.get("errors") is not None:
|
|
|
|
print("There was an error in the returned response.")
|
|
|
|
return None
|
|
|
|
|
|
|
|
try:
|
|
|
|
tasks = [task["id"] for task in response["data"]["build"]["tasks"]]
|
|
|
|
return tasks
|
|
|
|
except KeyError:
|
|
|
|
print("There was an issue with getting the list of task ids.")
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def stop_build_tasks(key: str, task_ids: List[str], mutation_id: str) -> bool:
|
|
|
|
query = """
|
|
|
|
mutation StopCirrusCiTasks (
|
|
|
|
$task_ids: [ID!]!,
|
|
|
|
$mutation_id: String!,
|
|
|
|
) {
|
|
|
|
batchAbort (
|
|
|
|
input: {
|
|
|
|
taskIds: $task_ids,
|
|
|
|
clientMutationId: $mutation_id
|
|
|
|
}
|
|
|
|
) {
|
|
|
|
tasks {
|
|
|
|
id
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"""
|
|
|
|
|
|
|
|
params = {
|
|
|
|
"task_ids": task_ids,
|
|
|
|
"mutation_id": mutation_id,
|
|
|
|
}
|
|
|
|
|
|
|
|
data = {"query": dedent(query), "variables": params}
|
|
|
|
data = json.dumps(data).encode()
|
|
|
|
|
|
|
|
request = Request(URL, data=data, method="POST")
|
|
|
|
request.add_header("Authorization", "Bearer {}".format(key))
|
|
|
|
|
|
|
|
with urlopen(request) as response:
|
|
|
|
response = json.load(response)
|
|
|
|
return len(response["data"]["batchAbort"]["tasks"]) == len(task_ids)
|
|
|
|
|
|
|
|
|
2022-10-27 10:27:04 +00:00
|
|
|
def try_download(build_id: str, dl_path: Path):
|
2023-04-11 08:57:29 +00:00
|
|
|
for task, file in TASKS:
|
2022-10-27 10:27:04 +00:00
|
|
|
url = DL_URL_TEMPLATE % (build_id, task, file)
|
2024-01-28 23:11:05 +00:00
|
|
|
out = os.path.join(dl_path, file)
|
2024-08-01 23:52:11 +00:00
|
|
|
print(f"Downloading {file} to {out}")
|
2022-10-27 10:27:04 +00:00
|
|
|
urlretrieve(url, out)
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
args = sys.argv
|
|
|
|
env = os.environ
|
|
|
|
|
|
|
|
key = env["CIRRUS_KEY"]
|
|
|
|
branch = args[1]
|
2023-01-01 08:18:47 +00:00
|
|
|
dl_path = args[2] if len(args) >= 3 else ""
|
2022-10-27 10:27:04 +00:00
|
|
|
dl_path = Path(dl_path)
|
2023-01-01 08:18:47 +00:00
|
|
|
build_type = args[3] if len(args) >= 4 else "build"
|
|
|
|
build_id = args[4] if len(args) >= 5 else None
|
|
|
|
|
|
|
|
print(f"Running Cirrus script with branch '{branch}'")
|
2022-10-27 10:27:04 +00:00
|
|
|
|
|
|
|
# Check if this build has already been completed before.
|
|
|
|
if build_id is not None:
|
|
|
|
print("Previous build ID was provided, checking if complete.")
|
|
|
|
status = check_build_status(key, build_id)
|
|
|
|
if status.startswith("COMPLETE"):
|
|
|
|
print("Starting download of previous build ID")
|
|
|
|
try_download(build_id, dl_path)
|
|
|
|
else:
|
|
|
|
# Try up to three times
|
2022-11-10 05:46:45 +00:00
|
|
|
MAX_ATTEMPTS = 5
|
2022-10-27 10:27:04 +00:00
|
|
|
success = False
|
2024-08-02 04:49:53 +00:00
|
|
|
tasks = []
|
|
|
|
mutation_id = None
|
2022-10-27 10:27:04 +00:00
|
|
|
|
|
|
|
for i in range(MAX_ATTEMPTS):
|
|
|
|
if success:
|
|
|
|
break
|
2024-08-02 04:49:53 +00:00
|
|
|
|
2024-08-01 23:52:11 +00:00
|
|
|
print(f"Attempt {i + 1}:")
|
2022-10-27 10:27:04 +00:00
|
|
|
|
2024-08-02 04:49:53 +00:00
|
|
|
if tasks and mutation_id:
|
|
|
|
print("Killing previous tasks first...")
|
|
|
|
|
|
|
|
if stop_build_tasks(key, tasks, mutation_id):
|
|
|
|
print("All previous tasks successfully stopped.")
|
|
|
|
else:
|
|
|
|
print(
|
|
|
|
"Not all previous tasks stopped. This isn't a problem but it is a waste."
|
|
|
|
)
|
|
|
|
|
|
|
|
tasks = []
|
|
|
|
mutation_id = "Cirrus CI Build {}-{}-{}".format(
|
|
|
|
build_type, branch, int(time())
|
|
|
|
)
|
|
|
|
|
|
|
|
with urlopen(make_query_request(key, branch, mutation_id)) as response:
|
2022-10-27 10:27:04 +00:00
|
|
|
response = json.load(response)
|
2024-08-02 04:49:53 +00:00
|
|
|
errors = response.get("errors")
|
2022-10-27 10:27:04 +00:00
|
|
|
|
2024-08-02 04:49:53 +00:00
|
|
|
if errors is not None:
|
|
|
|
print(f"There was an error in the returned response: {str(errors)}")
|
2022-10-27 10:27:04 +00:00
|
|
|
continue
|
|
|
|
|
|
|
|
try:
|
|
|
|
build_id = response["data"]["createBuild"]["build"]["id"]
|
2024-08-01 23:52:11 +00:00
|
|
|
print(f"Created build job {build_id}.")
|
2022-10-27 10:27:04 +00:00
|
|
|
except KeyError:
|
|
|
|
print("There was an issue with creating a build job.")
|
|
|
|
continue
|
|
|
|
|
2024-08-02 04:49:53 +00:00
|
|
|
# First, sleep X minutes total, as it's unlikely it'll finish before then.
|
2022-10-27 10:27:04 +00:00
|
|
|
SLEEP_MINUTES = 4
|
2024-08-01 23:52:11 +00:00
|
|
|
print(f"Sleeping for {SLEEP_MINUTES} minutes.")
|
2024-08-02 04:49:53 +00:00
|
|
|
|
|
|
|
# Sleep and check for tasks out every 10 seconds
|
|
|
|
for _ in range(SLEEP_MINUTES * 6):
|
|
|
|
sleep(10)
|
|
|
|
if not tasks:
|
|
|
|
tasks = check_build_tasks(key, build_id)
|
2022-10-27 10:27:04 +00:00
|
|
|
|
|
|
|
MINUTES = 10
|
|
|
|
SLEEP_SEC = 30
|
|
|
|
TRIES = int(MINUTES * (60 / SLEEP_SEC)) # Works out to 20 tries.
|
|
|
|
|
2024-08-02 04:49:53 +00:00
|
|
|
print(f"Mandatory nap over. Checking for completion for {MINUTES} min.")
|
|
|
|
|
2022-10-27 10:27:04 +00:00
|
|
|
for attempt in range(TRIES):
|
|
|
|
print("Checking...")
|
2022-11-10 05:46:45 +00:00
|
|
|
try:
|
|
|
|
status = check_build_status(key, build_id)
|
|
|
|
if status.startswith("COMPLETE"):
|
|
|
|
print("Build complete. Downloading artifact files.")
|
|
|
|
sleep(5)
|
|
|
|
try_download(build_id, dl_path)
|
|
|
|
success = True
|
2022-10-27 10:27:04 +00:00
|
|
|
break
|
2022-11-10 05:46:45 +00:00
|
|
|
else:
|
2024-08-02 04:49:53 +00:00
|
|
|
print(f"Build status: {(status or 'unknown')}")
|
|
|
|
|
2022-11-10 05:46:45 +00:00
|
|
|
if status == "ABORTED":
|
|
|
|
print("Build aborted, bailing.")
|
|
|
|
break
|
|
|
|
elif status.lower().startswith("fail"):
|
|
|
|
print("Build failed, bailing.")
|
|
|
|
break
|
|
|
|
elif attempt + 1 < TRIES:
|
|
|
|
sleep(SLEEP_SEC)
|
|
|
|
except Exception as ex:
|
|
|
|
print("Unexpected error:")
|
|
|
|
print(ex)
|
|
|
|
print(traceback.format_exc())
|
2023-04-11 08:57:29 +00:00
|
|
|
# Sleep for a minute if something went wrong, just in case.
|
|
|
|
sleep(60)
|
2022-10-27 10:27:04 +00:00
|
|
|
else:
|
2024-08-01 23:52:11 +00:00
|
|
|
print(f"Build failed to complete after {MINUTES} minutes, bailing.")
|
2022-10-27 10:27:04 +00:00
|
|
|
|
|
|
|
if not success:
|
|
|
|
exit(2)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|