|
| 1 | +import json |
| 2 | +import requests |
| 3 | +import sys |
| 4 | +import logging |
| 5 | +import pprint |
| 6 | +import time |
| 7 | +import os |
| 8 | +import functools |
| 9 | + |
| 10 | +# this script is executed in a github actions container |
| 11 | + |
| 12 | +DEBUG_MODE = int(os.environ["DEBUG"]) |
| 13 | +CLEANUP = [] |
| 14 | + |
| 15 | +def run(): |
| 16 | + gh_owner = os.environ["GITHUB_OWNER"] |
| 17 | + gh_owner_repo = os.environ["GITHUB_REPO"] |
| 18 | + gh_repo = gh_owner_repo[len(gh_owner)+1:] |
| 19 | + |
| 20 | + cp_repo = os.environ["CPANEL_REPO_PATTERN"].format(owner=gh_owner, repo=gh_repo) |
| 21 | + gh_deploy = "repos/{}/deployments".format(gh_owner_repo) |
| 22 | + |
| 23 | + # add some logging about web requests that we make |
| 24 | + if DEBUG_MODE: |
| 25 | + logging.basicConfig(level=logging.DEBUG) |
| 26 | + |
| 27 | + # make a new deployment in github |
| 28 | + res = github_api("POST", gh_deploy, { |
| 29 | + "ref": os.environ["GITHUB_SHA"], |
| 30 | + "task": "deploy", |
| 31 | + "required_contexts": [], |
| 32 | + "auto_merge": False, |
| 33 | + "environment": os.environ["CPANEL_ENV"] |
| 34 | + }) |
| 35 | + |
| 36 | + gh_deploy_status = "{}/{}/statuses".format(gh_deploy, res["id"]) |
| 37 | + gh_status_url = "https://github.com/{}/actions/runs/{}".format(gh_owner_repo, os.environ["GITHUB_RUN_ID"]) |
| 38 | + res = github_api("POST", gh_deploy_status, { |
| 39 | + "state": "pending", |
| 40 | + "target_url": gh_status_url, |
| 41 | + "description": "Initializing deployment" |
| 42 | + }) |
| 43 | + |
| 44 | + CLEANUP.append(functools.partial(github_api, "POST", gh_deploy_status, { |
| 45 | + "state": "error", |
| 46 | + "target_url": gh_status_url, |
| 47 | + "description": "Aborted due to error in GitHub Actions run" |
| 48 | + })) |
| 49 | + |
| 50 | + # Updates the repo to the latest master revision |
| 51 | + res = cpanel_api("VersionControl", "update", { |
| 52 | + "repository_root": cp_repo, |
| 53 | + "branch": "master" |
| 54 | + }) |
| 55 | + |
| 56 | + # check if we can execute a deploy |
| 57 | + # if this fails, it's because the repo on the webserver has changes |
| 58 | + # or is missing a .cpanel.yml file with deployment steps |
| 59 | + if not res["data"]["deployable"]: |
| 60 | + raise RuntimeError("Repository is not deployable, aborting!") |
| 61 | + |
| 62 | + # create a deployment |
| 63 | + res = cpanel_api("VersionControlDeployment", "create", { |
| 64 | + "repository_root": cp_repo |
| 65 | + }) |
| 66 | + cp_deploy_id = res["data"]["deploy_id"] |
| 67 | + |
| 68 | + # mark deployment as queued |
| 69 | + res = github_api("POST", gh_deploy_status, { |
| 70 | + "state": "queued", |
| 71 | + "target_url": gh_status_url, |
| 72 | + "description": "Deployment {} queued at {} (task {})".format(res["data"]["deploy_id"], |
| 73 | + res["data"]["timestamps"]["queued"], |
| 74 | + res["data"]["task_id"]) |
| 75 | + }) |
| 76 | + |
| 77 | + # fetch deployment status (note: uses a custom API module since built-in |
| 78 | + # one doesn't let us filter on a specific deployment id) |
| 79 | + # Custom API module source code is available at: |
| 80 | + # https://gist.github.com/skizzerz/85a0a2d4a6176ffa67004cd22c507799 |
| 81 | + cur_state = "queued" |
| 82 | + success = False |
| 83 | + i = 0 |
| 84 | + while True: |
| 85 | + i += 1 |
| 86 | + # if the deployment is taking forever, give up on checking status |
| 87 | + if i > 60: |
| 88 | + res = github_api("POST", gh_deploy_status, { |
| 89 | + "state": "error", |
| 90 | + "target_url": gh_status_url, |
| 91 | + "description": "No deployment response after 5 minutes, aborting action" |
| 92 | + }) |
| 93 | + break |
| 94 | + print("Sleeping for 5 seconds then checking status", flush=True) |
| 95 | + time.sleep(5) |
| 96 | + res = cpanel_api("VCDeployStatus", "retrieve", query={ |
| 97 | + "deploy_id": cp_deploy_id |
| 98 | + }) |
| 99 | + |
| 100 | + if res["data"]["timestamps"].get("succeeded", None): |
| 101 | + res = github_api("POST", gh_deploy_status, { |
| 102 | + "state": "success", |
| 103 | + "auto_inactive": True, |
| 104 | + "target_url": gh_status_url, |
| 105 | + "description": "Deployment {} succeeded at {} (task {})".format(res["data"]["deploy_id"], |
| 106 | + res["data"]["timestamps"]["succeeded"], |
| 107 | + res["data"]["task_id"]) |
| 108 | + }) |
| 109 | + success = True |
| 110 | + break |
| 111 | + if res["data"]["timestamps"].get("failed", None): |
| 112 | + res = github_api("POST", gh_deploy_status, { |
| 113 | + "state": "failure", |
| 114 | + "target_url": gh_status_url, |
| 115 | + "description": "Deployment {} FAILED at {} (task {})".format(res["data"]["deploy_id"], |
| 116 | + res["data"]["timestamps"]["failed"], |
| 117 | + res["data"]["task_id"]) |
| 118 | + }) |
| 119 | + break |
| 120 | + if res["data"]["timestamps"].get("canceled", None): |
| 121 | + res = github_api("POST", gh_deploy_status, { |
| 122 | + "state": "failure", |
| 123 | + "target_url": gh_status_url, |
| 124 | + "description": "Deployment {} CANCELED at {} (task {})".format(res["data"]["deploy_id"], |
| 125 | + res["data"]["timestamps"]["canceled"], |
| 126 | + res["data"]["task_id"]) |
| 127 | + }) |
| 128 | + break |
| 129 | + if cur_state == "queued" and res["data"]["timestamps"].get("active", None): |
| 130 | + res = github_api("POST", gh_deploy_status, { |
| 131 | + "state": "in_progress", |
| 132 | + "target_url": gh_status_url, |
| 133 | + "description": "Deployment {} began running at {} (task {})".format(res["data"]["deploy_id"], |
| 134 | + res["data"]["timestamps"]["active"], |
| 135 | + res["data"]["task_id"]) |
| 136 | + }) |
| 137 | + cur_state = "in_progress" |
| 138 | + else: |
| 139 | + print("No new deployment status updates", flush=True) |
| 140 | + |
| 141 | + CLEANUP.clear() |
| 142 | + return success |
| 143 | + |
| 144 | +def cpanel_api(module, endpoint, body=None, query=None): |
| 145 | + headers = { |
| 146 | + "Authorization": "cpanel {}:{}".format(os.environ["CPANEL_API_USER"], os.environ["CPANEL_TOKEN"]) |
| 147 | + } |
| 148 | + |
| 149 | + url = "{}/execute/{}/{}".format(os.environ["CPANEL_API_URL"], module, endpoint) |
| 150 | + method = "POST" if body else "GET" |
| 151 | + print(method, url, flush=True) |
| 152 | + r = requests.request(method, url, headers=headers, params=query, data=body) |
| 153 | + r.raise_for_status() |
| 154 | + data = r.json() |
| 155 | + if DEBUG_MODE or not data["status"]: |
| 156 | + pprint.pprint(data) |
| 157 | + print("", flush=True) |
| 158 | + if not data["status"]: |
| 159 | + raise RuntimeError("API call was unsuccessful, aborting!") |
| 160 | + return data |
| 161 | + |
| 162 | +def github_api(method, endpoint, body=None): |
| 163 | + headers = { |
| 164 | + "Authorization": "Bearer {}".format(os.environ["GITHUB_TOKEN"]), |
| 165 | + # opt into preview letting us set additional deployment status types |
| 166 | + # remove this line once it hits stable API |
| 167 | + "Accept": "application/vnd.github.flash-preview+json, aplication/vnd.github.ant-man-preview+json" |
| 168 | + } |
| 169 | + |
| 170 | + url = "https://api.github.com/{}".format(endpoint) |
| 171 | + print(method, url, flush=True) |
| 172 | + r = requests.request(method, url, headers=headers, json=body) |
| 173 | + data = r.json() |
| 174 | + if DEBUG_MODE or r.status_code >= 400: |
| 175 | + pprint.pprint(data) |
| 176 | + print("", flush=True) |
| 177 | + r.raise_for_status() |
| 178 | + return data |
| 179 | + |
| 180 | +if __name__ == "__main__": |
| 181 | + try: |
| 182 | + if not run(): |
| 183 | + sys.exit(1) |
| 184 | + finally: |
| 185 | + for callback in CLEANUP: |
| 186 | + callback() |
0 commit comments