deploy-on-vps/vps.py

202 lines
8.5 KiB
Python
Executable file

#!/usr/bin/env python3
"""Finds the Interweb Mozambique VPS to deploy to and makes sure it is running.
Called by deploy.sh. Asks the API for the server (by id, by name or the only one on the account),
checks it is active and running (starts it first when asked) and writes id, name, ip and power
state to the file given as the first argument. Only the Python standard library is used.
"""
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
API_URL = "https://api.interweb.co.mz"
VERSION = "1.0.1"
USER_AGENT = "interweb-mz-deploy-on-vps/" + VERSION
KEY_ENV = "INTERWEB_API_KEY"
BUSY = ("starting", "restarting", "stopping", "reinstalling", "backing_up")
HINTS = {
"unauthorized": "The API key is missing or invalid. Check the secret passed in api-key.",
"insufficient_scope": "The API key needs vps:read (and vps:write to start a stopped server).",
"ip_not_allowed": "The API key only accepts some IP addresses. GitHub runners change IP: allow them or use a self-hosted runner.",
"not_found": "The server is not on this account, or is not active.",
"rate_limited": "Too many requests. Wait a little and run the workflow again.",
}
class ApiError(Exception):
def __init__(self, status, code, message, details=None, correlation_id=None):
Exception.__init__(self, message)
self.status, self.code, self.message = status, code, message
self.details, self.correlation_id = details or {}, correlation_id
def log(msg):
print(msg, flush=True)
def fail(msg):
print("::error::" + msg.replace("\n", "%0A"), flush=True)
sys.exit(1)
def env(name, default=""):
return os.environ.get("INPUT_" + name, default).strip()
def api(key, method, path, attempts=3):
url = API_URL.rstrip("/") + path
headers = {"Authorization": "Bearer " + key, "Accept": "application/json", "Accept-Language": "en",
"User-Agent": USER_AGENT}
if method == "POST":
headers["Idempotency-Key"] = "gh-deploy-" + uuid.uuid4().hex
for attempt in range(1, attempts + 1):
req = urllib.request.Request(url, method=method, headers=headers, data=b"" if method == "POST" else None)
try:
with urllib.request.urlopen(req, timeout=60) as resp:
raw = resp.read().decode("utf-8")
return json.loads(raw) if raw else {}
except urllib.error.HTTPError as e:
raw = e.read().decode("utf-8", "replace")
try:
err = json.loads(raw).get("error", {})
except ValueError:
err = {}
retry_after = e.headers.get("Retry-After") if e.headers else None
if attempt < attempts and (e.code == 429 or e.code >= 500):
wait = min(int(retry_after) if (retry_after or "").isdigit() else 5 * attempt, 60)
log("The API answered %d, trying again in %d s..." % (e.code, wait))
time.sleep(wait)
continue
raise ApiError(e.code, err.get("code", "http_%d" % e.code), err.get("message", raw[:300] or e.reason),
err.get("details"), err.get("correlation_id"))
except (urllib.error.URLError, OSError) as e:
if attempt < attempts:
time.sleep(5 * attempt)
continue
raise ApiError(0, "network_error", "Could not reach the API: %s" % e)
raise ApiError(0, "network_error", "Could not reach the API.")
def q(s):
return urllib.parse.quote(str(s), safe="")
def check_key(key, need):
"""Checks the key with GET /v1/token before anything else, and stops early when it cannot do the job."""
try:
data = api(key, "GET", "/v1/token").get("data") or {}
except ApiError as e:
if e.status == 401:
fail("The API key is not valid: it was deleted, has expired or was copied wrong. "
"Check the secret passed in api-key, or create a new key in the API Center.")
if e.status == 403:
fail("The API refused the key (%s): %s%s" % (e.code, e.message, "\n" + HINTS[e.code] if e.code in HINTS else ""))
raise
perms = data.get("permissions") or []
missing = [p for p in need if p not in perms]
if missing:
fail("The API key does not have the permissions this action needs: %s. "
"Add them to the key in the API Center and run the workflow again." % ", ".join(missing))
return data
def find_server(key):
sid = env("SERVER_ID")
if sid:
return sid
name = env("SERVER_NAME").lower()
servers, page = [], 1
while True:
res = api(key, "GET", "/v1/servers?status=active&per_page=100&page=%d" % page)
servers += res.get("data") or []
meta = res.get("meta") or {}
if page >= int(meta.get("total_pages") or 1):
break
page += 1
if name:
found = [s for s in servers if str(s.get("name", "")).lower() == name or str(s.get("ip", "")) == name]
if not found:
fail("No active server named %s on this account. Servers: %s"
% (name, ", ".join("%s (id %s)" % (s.get("name"), s.get("id")) for s in servers) or "none"))
return str(found[0]["id"])
if len(servers) == 1:
return str(servers[0]["id"])
if not servers:
fail("There is no active server on this account.")
fail("The account has %d servers. Say which one with server-id or server-name: %s"
% (len(servers), ", ".join("%s (id %s)" % (s.get("name"), s.get("id")) for s in servers)))
def wait_running(key, sid, timeout):
deadline = time.time() + timeout
while True:
srv = api(key, "GET", "/v1/servers/%s" % q(sid)).get("data") or {}
state = srv.get("power_state")
if state == "running":
return srv
if time.time() > deadline:
fail("The server is still %s after %d s. Check it in the account dashboard." % (state, timeout))
log("Server state: %s, waiting..." % state)
time.sleep(20)
def main():
out = sys.argv[1]
key = env("API_KEY") or os.environ.get(KEY_ENV, "").strip()
if not key:
fail("api-key is empty. Save your API key as a repository secret and pass it in api-key.")
start = env("START_IF_STOPPED", "false").lower() == "true"
try:
timeout = int(env("WAIT_TIMEOUT", "600") or 600)
except ValueError:
fail("wait-timeout must be a number of seconds.")
sandbox = key.startswith("sandbox_")
try:
token = check_key(key, ["vps:read", "vps:write"] if start else ["vps:read"])
sandbox = token.get("mode", "sandbox" if sandbox else "production") == "sandbox"
sid = find_server(key)
srv = api(key, "GET", "/v1/servers/%s" % q(sid)).get("data") or {}
if srv.get("status") != "active":
fail("The server %s is %s. Only active servers can receive a deploy." % (srv.get("name", sid), srv.get("status")))
state = srv.get("power_state")
log("Server %s (id %s), IP %s, state %s." % (srv.get("name"), srv.get("id"), srv.get("ip"), state))
if srv.get("state_stale"):
log("::warning::The server state could not be read just now: this is the last known state.")
if state == "stopped":
if not start:
fail("The server is stopped. Start it in the account dashboard, or set start-if-stopped: true.")
res = api(key, "POST", "/v1/servers/%s/start" % q(sid)).get("data") or {}
if res.get("simulated") or sandbox:
log("Sandbox key: the start was simulated, the server was not touched.")
else:
log("Starting the server (action %s). This usually takes about 2 minutes." % res.get("action_id"))
srv = wait_running(key, sid, timeout)
elif state in BUSY:
srv = wait_running(key, sid, timeout)
elif state != "running":
log("::warning::The server state is %s. Trying the deploy anyway." % state)
except ApiError as e:
msg = "%s (HTTP %s, %s)" % (e.message, e.status, e.code)
if e.code in HINTS:
msg += "\n" + HINTS[e.code]
if e.correlation_id:
msg += "\nCorrelation id: " + e.correlation_id
fail(msg)
if not srv.get("ip"):
fail("The API did not return an IP for this server.")
with open(out, "w", encoding="utf-8") as f:
f.write("SERVER_ID=%s\nSERVER_NAME=%s\nSERVER_IP=%s\nPOWER_STATE=%s\n"
% (srv.get("id", sid), srv.get("name", ""), srv.get("ip"), srv.get("power_state", "")))
if __name__ == "__main__":
main()