67 lines
2.6 KiB
Python

"""Stamp the build-node placement granted by the API server's match conditions."""
import base64
import json
import ssl
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
KEY = "atlas.bstein.dev/ci-reserved"
ARCHES = {"arm64": ("arm64",), "amd64": ("amd64",), "both": ("arm64", "amd64")}
def patches(pod, arches):
labels = dict(pod["metadata"].get("labels") or {})
tolerations = list(pod["spec"].get("tolerations") or [])
for arch in arches:
labels[f"atlas.bstein.dev/ci-{arch}-eligible"] = "true"
rule = {"key": KEY, "operator": "Equal", "value": arch, "effect": "PreferNoSchedule"}
if rule not in tolerations:
tolerations.append(rule)
return [
{"op": "add", "path": "/metadata/labels", "value": labels},
{"op": "add", "path": "/spec/tolerations", "value": tolerations},
]
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200 if self.path == "/ready" else 404)
self.end_headers()
def do_POST(self):
try:
size = int(self.headers["Content-Length"])
if not 0 < size <= 4 * 1024 * 1024:
raise ValueError("invalid size")
req = json.loads(self.rfile.read(size))["request"]
patch = patches(req["object"], ARCHES[self.path.lstrip("/")])
response = {"uid": req["uid"], "allowed": True, "patchType": "JSONPatch",
"patch": base64.b64encode(json.dumps(patch).encode()).decode()}
body = json.dumps({"apiVersion": "admission.k8s.io/v1", "kind": "AdmissionReview",
"response": response}).encode()
except (KeyError, ValueError, TypeError):
self.send_error(400)
return
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args):
if self.path != "/ready":
super().log_message(fmt, *args)
class Server(ThreadingHTTPServer):
def finish_request(self, request, address):
# The projected secret changes on renewal. Read it in the worker thread.
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain("/tls/tls.crt", "/tls/tls.key")
request.settimeout(5)
with ctx.wrap_socket(request, server_side=True) as tls:
super().finish_request(tls, address)
if __name__ == "__main__":
Server(("0.0.0.0", 8443), Handler).serve_forever()