diff --git a/infrastructure/core/ci-capacity/admission-service.yaml b/infrastructure/core/ci-capacity/admission-service.yaml new file mode 100644 index 00000000..ff2788f0 --- /dev/null +++ b/infrastructure/core/ci-capacity/admission-service.yaml @@ -0,0 +1,81 @@ +# infrastructure/core/ci-capacity/admission-service.yaml +apiVersion: v1 +kind: Service +metadata: + name: ci-placement +spec: + selector: + app: ci-placement + ports: + - port: 443 + targetPort: 8443 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ci-placement +spec: + replicas: 2 + strategy: + rollingUpdate: + maxUnavailable: 0 + maxSurge: 1 + selector: + matchLabels: + app: ci-placement + template: + metadata: + labels: + app: ci-placement + spec: + automountServiceAccountToken: false + nodeSelector: + kubernetes.io/arch: arm64 + atlas.bstein.dev/spillover: "true" + affinity: + podAntiAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: + matchLabels: + app: ci-placement + topologyKey: kubernetes.io/hostname + securityContext: + runAsNonRoot: true + runAsUser: 65532 + seccompProfile: + type: RuntimeDefault + containers: + - name: webhook + image: docker.io/library/python@sha256:4ce45e8acd11d49ee07aa736cd7ca2950df75033b946f3a5d9eca1cb4aae2ab7 + command: [python3, -B, /app/admit.py] + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + resources: + requests: {cpu: 10m, memory: 24Mi} + limits: {cpu: 200m, memory: 64Mi} + readinessProbe: + httpGet: {path: /ready, scheme: HTTPS, port: 8443} + periodSeconds: 5 + volumeMounts: + - {name: code, mountPath: /app, readOnly: true} + - {name: tls, mountPath: /tls, readOnly: true} + volumes: + - name: code + configMap: + name: ci-placement-code + - name: tls + secret: + secretName: ci-placement-tls +--- +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: ci-placement +spec: + minAvailable: 1 + selector: + matchLabels: + app: ci-placement diff --git a/infrastructure/core/ci-capacity/admit.py b/infrastructure/core/ci-capacity/admit.py new file mode 100644 index 00000000..81cae1ae --- /dev/null +++ b/infrastructure/core/ci-capacity/admit.py @@ -0,0 +1,66 @@ +"""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() diff --git a/infrastructure/core/ci-capacity/certificates.yaml b/infrastructure/core/ci-capacity/certificates.yaml new file mode 100644 index 00000000..d323598c --- /dev/null +++ b/infrastructure/core/ci-capacity/certificates.yaml @@ -0,0 +1,39 @@ +# infrastructure/core/ci-capacity/certificates.yaml +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + name: ci-placement-bootstrap +spec: + selfSigned: {} +--- +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: ci-placement-ca +spec: + isCA: true + commonName: ci-placement-ca + secretName: ci-placement-ca + duration: 87600h + issuerRef: + name: ci-placement-bootstrap +--- +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + name: ci-placement +spec: + ca: + secretName: ci-placement-ca +--- +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: ci-placement +spec: + secretName: ci-placement-tls + dnsNames: + - ci-placement.kube-system.svc + - ci-placement.kube-system.svc.cluster.local + issuerRef: + name: ci-placement diff --git a/infrastructure/core/ci-capacity/kustomization.yaml b/infrastructure/core/ci-capacity/kustomization.yaml new file mode 100644 index 00000000..52f9f7f9 --- /dev/null +++ b/infrastructure/core/ci-capacity/kustomization.yaml @@ -0,0 +1,11 @@ +# infrastructure/core/ci-capacity/kustomization.yaml +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: kube-system +resources: + - certificates.yaml + - admission-service.yaml +configMapGenerator: + - name: ci-placement-code + files: + - admit.py diff --git a/infrastructure/core/kustomization.yaml b/infrastructure/core/kustomization.yaml index bd0e95bd..9b61d8bc 100644 --- a/infrastructure/core/kustomization.yaml +++ b/infrastructure/core/kustomization.yaml @@ -3,6 +3,7 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - node-maintenance.yaml + - ci-capacity - storageclass-ci-scratch.yaml - ../modules/base - ../modules/profiles/atlas-ha