From 5fe94b67ec55c76c3d8a9b42a2247fa0075aec74 Mon Sep 17 00:00:00 2001 From: Marco Azarmaneche <306425250+thecorporatetractor@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:35:48 +0200 Subject: [PATCH 1/6] feat(sandbox): Kubernetes backend for artex-runner ARTEX_RUNNER_BACKEND=kubernetes runs each task in a worker pod behind its own egress-proxy pod, created through the Kubernetes API with no container runtime socket. Per-task NetworkPolicies are applied before the pods and removed after them; the runner waits until they are in effect before the first command, runs commands through pods/exec under env -i and artex-exec-wrap, and re-adopts task pods after a restart. Unit tests run against a fake API server; a live test (TestKubeSandboxE2E) drives a deployed runner. --- CHANGELOG.md | 4 + cmd/artex-runner/main.go | 67 ++- go.mod | 2 +- sandbox/kube.go | 1238 ++++++++++++++++++++++++++++++++++++++ sandbox/kube_e2e_test.go | 323 ++++++++++ sandbox/kube_test.go | 1115 ++++++++++++++++++++++++++++++++++ sandbox/types.go | 4 + 7 files changed, 2733 insertions(+), 20 deletions(-) create mode 100644 sandbox/kube.go create mode 100644 sandbox/kube_e2e_test.go create mode 100644 sandbox/kube_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 928afa0a6..47d865941 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project are documented in this file. The format is b ## [Unreleased] +### Added + +- **Kubernetes sandbox backend for `artex-runner`.** With `ARTEX_RUNNER_BACKEND=kubernetes` each task runs in a worker pod behind its own egress-proxy pod, created through the Kubernetes API with no container runtime socket. The worker runs as uid/gid 10001 with `runAsNonRoot`, a read-only root filesystem, all capabilities dropped, `seccomp: RuntimeDefault`, no service-account token and no service links, and mounts only its task directory. Per-task NetworkPolicies are created before the pods and deleted after them: the worker can reach only its own proxy, and the proxy only cluster DNS, public addresses and the task's scope CIDRs. The runner waits until the policies are in effect before the first command, runs commands through `pods/exec`, and re-adopts task pods after a restart. + ### Security - **Company egress is promoted only from operator-approved company scope.** A sandboxed worker could register assets with `insert_assets` (an attacker IP or domain attributed to the company through its domain or ICP rule), and the agent could add rules with `add_company_scope`; the next operator selection or re-approval of the company copied those hosts into `task_scope_egress`, persistently widening the approved sandbox egress. The approval snapshot now copies only `company_scope` domain and IP/CIDR rules with the new `approved_by_operator` flag (migration `0025_company_scope_approved.sql`), which only the operator company API sets; `add_company_scope` and the ScopeSentry sync store rules with the flag off. Existing rules are backfilled as approved. Behaviour change: a domain or IP discovered only in assets is no longer reachable from the sandbox until it is added explicitly to the company scope (operator) or to the task scope. Egress rows already frozen by earlier approvals are not purged by this change, and re-approving the company does not remove them (the snapshot only adds rows); removing the company from the task scope drops its rows, and approving it again rebuilds them from approved rules only. diff --git a/cmd/artex-runner/main.go b/cmd/artex-runner/main.go index 830313124..9f3a77ad0 100644 --- a/cmd/artex-runner/main.go +++ b/cmd/artex-runner/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "fmt" "log" "net/http" "os" @@ -22,33 +23,61 @@ func envOr(k, def string) string { return def } +// buildBackend selects the container backend from ARTEX_RUNNER_BACKEND +// ("docker", the default, or "kubernetes"). +func buildBackend() (sandbox.Backend, error) { + wsRoot := envOr(sandbox.EnvWorkspaceRoot, sandbox.DefaultWorkspaceRoot) + auditRoot := envOr(sandbox.EnvAuditRoot, sandbox.DefaultAuditRoot) + workerImage := envOr(sandbox.EnvWorkerImage, sandbox.DefaultWorkerImage) + proxyImage := envOr(sandbox.EnvProxyImage, sandbox.DefaultProxyImage) + + switch kind := strings.ToLower(envOr(sandbox.EnvRunnerBackend, sandbox.BackendDocker)); kind { + case sandbox.BackendDocker: + sock := envOr("DOCKER_SOCK", "/var/run/docker.sock") + if dh := strings.TrimSpace(os.Getenv("DOCKER_HOST")); strings.HasPrefix(dh, "unix://") { + sock = strings.TrimPrefix(dh, "unix://") + } + log.Printf("[runner] backend=docker socket=%s", sock) + return sandbox.NewDockerBackend(sandbox.DockerConfig{ + SocketPath: sock, + WorkerImage: workerImage, + ProxyImage: proxyImage, + WorkspaceRoot: wsRoot, + HostWorkspaceRoot: envOr("ARTEX_HOST_WORKSPACE_ROOT", wsRoot), + AuditRoot: auditRoot, + HostAuditRoot: envOr("ARTEX_HOST_AUDIT_ROOT", auditRoot), + TaskNetPrefix: envOr(sandbox.EnvTaskNetPrefix, sandbox.DefaultTaskNetPrefix), + EgressNet: envOr(sandbox.EnvEgressNet, sandbox.DefaultEgressNet), + }), nil + case sandbox.BackendKubernetes: + cfg, err := sandbox.KubeConfigFromEnv() + if err != nil { + return nil, err + } + cfg.WorkerImage, cfg.ProxyImage = workerImage, proxyImage + cfg.WorkspaceRoot, cfg.AuditRoot = wsRoot, auditRoot + b, err := sandbox.NewKubernetesBackend(cfg) + if err != nil { + return nil, err + } + log.Printf("[runner] backend=kubernetes namespace=%s claim=%s", b.Namespace(), cfg.DataClaim) + return b, nil + default: + return nil, fmt.Errorf("invalid %s=%q (want %q or %q)", sandbox.EnvRunnerBackend, kind, sandbox.BackendDocker, sandbox.BackendKubernetes) + } +} + func main() { token := strings.TrimSpace(os.Getenv(sandbox.EnvRunnerToken)) if token == "" { log.Fatalf("[runner] %s is required (refusing to start unauthenticated)", sandbox.EnvRunnerToken) } addr := envOr("ARTEX_RUNNER_ADDR", sandbox.DefaultRunnerAddr) - sock := envOr("DOCKER_SOCK", "/var/run/docker.sock") - if dh := strings.TrimSpace(os.Getenv("DOCKER_HOST")); strings.HasPrefix(dh, "unix://") { - sock = strings.TrimPrefix(dh, "unix://") + backend, err := buildBackend() + if err != nil { + log.Fatalf("[runner] %v", err) } - wsRoot := envOr(sandbox.EnvWorkspaceRoot, sandbox.DefaultWorkspaceRoot) - hostWSRoot := envOr("ARTEX_HOST_WORKSPACE_ROOT", wsRoot) - auditRoot := envOr(sandbox.EnvAuditRoot, sandbox.DefaultAuditRoot) - hostAuditRoot := envOr("ARTEX_HOST_AUDIT_ROOT", auditRoot) - backend := sandbox.NewDockerBackend(sandbox.DockerConfig{ - SocketPath: sock, - WorkerImage: envOr(sandbox.EnvWorkerImage, sandbox.DefaultWorkerImage), - ProxyImage: envOr(sandbox.EnvProxyImage, sandbox.DefaultProxyImage), - WorkspaceRoot: wsRoot, - HostWorkspaceRoot: hostWSRoot, - AuditRoot: auditRoot, - HostAuditRoot: hostAuditRoot, - TaskNetPrefix: envOr(sandbox.EnvTaskNetPrefix, sandbox.DefaultTaskNetPrefix), - EgressNet: envOr(sandbox.EnvEgressNet, sandbox.DefaultEgressNet), - }) - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() diff --git a/go.mod b/go.mod index c5183b75c..d773029a2 100644 --- a/go.mod +++ b/go.mod @@ -74,7 +74,7 @@ require ( golang.org/x/sync v0.25.0 // indirect golang.org/x/sys v0.50.0 golang.org/x/tools v0.52.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect + gopkg.in/yaml.v3 v3.0.1 modernc.org/libc v1.72.3 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.11.0 // indirect diff --git a/sandbox/kube.go b/sandbox/kube.go new file mode 100644 index 000000000..35ca52708 --- /dev/null +++ b/sandbox/kube.go @@ -0,0 +1,1238 @@ +package sandbox + +import ( + "bytes" + "context" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net" + "net/http" + "net/netip" + "net/url" + "os" + "path" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/gorilla/websocket" +) + +// Kubernetes-specific labels and annotations. Task IDs may contain characters or +// lengths that Kubernetes names and label values reject, so objects are keyed by a +// short hash of the task ID (LabelTaskHash) and carry the real ID in an annotation. +const ( + LabelTaskHash = "artex.task_hash" + AnnotationTaskID = "artex.task" + AnnotationScope = "artex.scope_hash" + kubeSATokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token" + kubeSACAPath = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" + kubeSANSPath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace" + kubeWorkerName = "worker" + kubeProxyName = "egress-proxy" + kubeDefaultTimeout = 2 * time.Minute +) + +// KubeConfig configures the KubernetesBackend for artex-runner. +type KubeConfig struct { + APIServer string // default https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT + TokenPath string // default service-account token path (re-read on every request: bound tokens rotate) + CAPath string // default service-account CA path + Namespace string // default: the runner's own namespace + + WorkerImage string + ProxyImage string + ImagePullPolicy string // IfNotPresent by default + RuntimeClassName string // optional, e.g. gvisor or kata + ServiceAccount string // service account for worker/proxy pods (token is never mounted) + + // DataClaim is the PersistentVolumeClaim shared with the panel and the runner. + // Workers mount / at /workspace; proxies mount + // / at /audit. + DataClaim string + TasksSubPath string // default "tasks" + AuditSubPath string // default "egress-audit" + + // WorkspaceRoot and AuditRoot are where the runner itself mounts the same two + // directories, so it can create and chown per-task directories before a pod + // mounts them (kubelet would otherwise create them root:root 0755). + WorkspaceRoot string + AuditRoot string + + // ProxyDeniedCIDRs is the egress "except" list on the proxy's per-task + // NetworkPolicy (defence in depth below the proxy's own allowlist). Scope CIDRs + // of the task are added back as explicit allow rules. + ProxyDeniedCIDRs []string + // DNSNamespace/DNSPodLabels select the cluster DNS pods the proxy may query. + DNSNamespace string + DNSPodLabels map[string]string + + PodReadyTimeout time.Duration + + // PinNode, when set, schedules task pods onto that node (nodeAffinity on + // metadata.name). Needed when DataClaim is ReadWriteOnce: every pod mounting it + // must share a node. + PinNode string + + // Worker resources; defaults mirror DockerBackend (2 CPU, 2Gi). + WorkerCPULimit string + WorkerMemoryLimit string +} + +type kubeTask struct { + taskID string + hash string + scopeHash string + workerPod string + proxyPod string + proxyIP string // ClusterIP of the per-task proxy Service +} + +// KubernetesBackend implements Backend by creating per-task worker and egress-proxy +// pods through the Kubernetes API. It needs no container runtime socket: isolation +// comes from pod security settings and per-task NetworkPolicies. +type KubernetesBackend struct { + cfg KubeConfig + http *http.Client + tls *tls.Config + mu sync.Mutex + tasks map[string]*kubeTask + // locks serialises ensureTask per task so concurrent execs never race to + // delete and recreate each other's pods. + locks map[string]*sync.Mutex + // tokenOverride is used by tests instead of reading TokenPath. + tokenOverride string +} + +// DefaultProxyDeniedCIDRs mirrors the proxy's default-denied IPv4 prefixes that a +// NetworkPolicy ipBlock can express inside 0.0.0.0/0. +var DefaultProxyDeniedCIDRs = []string{ + "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "100.100.100.200/32", "127.0.0.0/8", + "168.63.129.16/32", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", + "224.0.0.0/4", "240.0.0.0/4", +} + +// NewKubernetesBackend builds a backend from cfg, filling defaults from the +// in-cluster environment. +func NewKubernetesBackend(cfg KubeConfig) (*KubernetesBackend, error) { + if cfg.APIServer == "" { + host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT") + if host == "" || port == "" { + return nil, errors.New("kubernetes backend: KUBERNETES_SERVICE_HOST/PORT unset and no API server configured") + } + cfg.APIServer = "https://" + net.JoinHostPort(host, port) + } + cfg.APIServer = strings.TrimRight(cfg.APIServer, "/") + if cfg.TokenPath == "" { + cfg.TokenPath = kubeSATokenPath + } + if cfg.CAPath == "" { + cfg.CAPath = kubeSACAPath + } + if cfg.Namespace == "" { + raw, err := os.ReadFile(kubeSANSPath) + if err != nil { + return nil, fmt.Errorf("kubernetes backend: namespace not set and %s unreadable: %w", kubeSANSPath, err) + } + cfg.Namespace = strings.TrimSpace(string(raw)) + } + if cfg.WorkerImage == "" { + cfg.WorkerImage = DefaultWorkerImage + } + if cfg.ProxyImage == "" { + cfg.ProxyImage = DefaultProxyImage + } + if cfg.ImagePullPolicy == "" { + cfg.ImagePullPolicy = "IfNotPresent" + } + if cfg.DataClaim == "" { + return nil, errors.New("kubernetes backend: data PersistentVolumeClaim name is required") + } + if cfg.TasksSubPath == "" { + cfg.TasksSubPath = "tasks" + } + if cfg.AuditSubPath == "" { + cfg.AuditSubPath = "egress-audit" + } + for _, p := range []string{cfg.TasksSubPath, cfg.AuditSubPath} { + if path.IsAbs(p) || strings.Contains(p, "..") { + return nil, fmt.Errorf("kubernetes backend: sub path %q must be relative without ..", p) + } + } + if cfg.WorkspaceRoot == "" { + cfg.WorkspaceRoot = DefaultWorkspaceRoot + } + if cfg.AuditRoot == "" { + cfg.AuditRoot = DefaultAuditRoot + } + if cfg.ProxyDeniedCIDRs == nil { + cfg.ProxyDeniedCIDRs = DefaultProxyDeniedCIDRs + } + if cfg.DNSNamespace == "" { + cfg.DNSNamespace = "kube-system" + } + if cfg.DNSPodLabels == nil { + cfg.DNSPodLabels = map[string]string{"k8s-app": "kube-dns"} + } + if cfg.WorkerCPULimit == "" { + cfg.WorkerCPULimit = "2" + } + if cfg.WorkerMemoryLimit == "" { + cfg.WorkerMemoryLimit = "2Gi" + } + if cfg.PodReadyTimeout <= 0 { + cfg.PodReadyTimeout = kubeDefaultTimeout + } + + tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12} + if strings.HasPrefix(cfg.APIServer, "https://") { + ca, err := os.ReadFile(cfg.CAPath) + if err != nil { + return nil, fmt.Errorf("kubernetes backend: read CA %s: %w", cfg.CAPath, err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(ca) { + return nil, fmt.Errorf("kubernetes backend: no certificates in %s", cfg.CAPath) + } + tlsCfg.RootCAs = pool + } + return &KubernetesBackend{ + cfg: cfg, + tls: tlsCfg, + http: &http.Client{Transport: &http.Transport{Proxy: nil, TLSClientConfig: tlsCfg}, Timeout: 30 * time.Second}, + tasks: map[string]*kubeTask{}, + locks: map[string]*sync.Mutex{}, + }, nil +} + +// Namespace returns the namespace task pods are created in. +func (b *KubernetesBackend) Namespace() string { return b.cfg.Namespace } + +// KubeConfigFromEnv reads the Kubernetes backend settings: +// +// ARTEX_KUBE_NAMESPACE namespace for task pods (default: the runner's own) +// ARTEX_KUBE_DATA_CLAIM shared data PersistentVolumeClaim (required) +// ARTEX_KUBE_TASKS_SUBPATH default "tasks" +// ARTEX_KUBE_AUDIT_SUBPATH default "egress-audit" +// ARTEX_KUBE_IMAGE_PULL_POLICY default IfNotPresent +// ARTEX_KUBE_RUNTIME_CLASS optional RuntimeClass (gvisor, kata, ...) +// ARTEX_KUBE_SERVICE_ACCOUNT service account for task pods (token never mounted) +// ARTEX_KUBE_PROXY_DENIED_CIDRS comma list; default DefaultProxyDeniedCIDRs +// ARTEX_KUBE_DNS_NAMESPACE default kube-system +// ARTEX_KUBE_DNS_LABELS comma list of k=v; default k8s-app=kube-dns +// ARTEX_KUBE_POD_READY_TIMEOUT Go duration; default 2m +// ARTEX_KUBE_PIN_NODE node name task pods must run on (ReadWriteOnce data volume) +// ARTEX_KUBE_WORKER_CPU_LIMIT default "2" +// ARTEX_KUBE_WORKER_MEMORY_LIMIT default "2Gi" +func KubeConfigFromEnv() (KubeConfig, error) { + get := func(k string) string { return strings.TrimSpace(os.Getenv(k)) } + cfg := KubeConfig{ + Namespace: get("ARTEX_KUBE_NAMESPACE"), + DataClaim: get("ARTEX_KUBE_DATA_CLAIM"), + TasksSubPath: get("ARTEX_KUBE_TASKS_SUBPATH"), + AuditSubPath: get("ARTEX_KUBE_AUDIT_SUBPATH"), + ImagePullPolicy: get("ARTEX_KUBE_IMAGE_PULL_POLICY"), + RuntimeClassName: get("ARTEX_KUBE_RUNTIME_CLASS"), + ServiceAccount: get("ARTEX_KUBE_SERVICE_ACCOUNT"), + DNSNamespace: get("ARTEX_KUBE_DNS_NAMESPACE"), + PinNode: get("ARTEX_KUBE_PIN_NODE"), + + WorkerCPULimit: get("ARTEX_KUBE_WORKER_CPU_LIMIT"), + WorkerMemoryLimit: get("ARTEX_KUBE_WORKER_MEMORY_LIMIT"), + } + if v := get("ARTEX_KUBE_PROXY_DENIED_CIDRS"); v != "" { + for _, c := range ParseCSV(v) { + p, err := netip.ParsePrefix(c) + if err != nil || !p.Addr().Is4() { + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_PROXY_DENIED_CIDRS: %q is not an IPv4 CIDR", c) + } + cfg.ProxyDeniedCIDRs = append(cfg.ProxyDeniedCIDRs, p.Masked().String()) + } + } + if v := get("ARTEX_KUBE_DNS_LABELS"); v != "" { + cfg.DNSPodLabels = map[string]string{} + for _, kv := range ParseCSV(v) { + k, val, ok := strings.Cut(kv, "=") + if !ok || k == "" { + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_DNS_LABELS: %q is not key=value", kv) + } + cfg.DNSPodLabels[k] = val + } + } + if v := get("ARTEX_KUBE_POD_READY_TIMEOUT"); v != "" { + d, err := time.ParseDuration(v) + if err != nil || d <= 0 { + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_POD_READY_TIMEOUT: %q is not a positive duration", v) + } + cfg.PodReadyTimeout = d + } + switch cfg.ImagePullPolicy { + case "", "Always", "IfNotPresent", "Never": + default: + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_IMAGE_PULL_POLICY: %q (want Always, IfNotPresent or Never)", cfg.ImagePullPolicy) + } + return cfg, nil +} + +func kubeTaskHash(taskID string) string { + sum := sha256.Sum256([]byte(taskID)) + return hex.EncodeToString(sum[:])[:16] +} + +func (b *KubernetesBackend) token() (string, error) { + if b.tokenOverride != "" { + return b.tokenOverride, nil + } + raw, err := os.ReadFile(b.cfg.TokenPath) + if err != nil { + return "", fmt.Errorf("%w: read service account token: %v", ErrDockerUnavailable, err) + } + return strings.TrimSpace(string(raw)), nil +} + +// kubeAPIError carries the HTTP status of a failed API call. +type kubeAPIError struct { + Code int + Body string +} + +func (e *kubeAPIError) Error() string { + return fmt.Sprintf("kubernetes API HTTP %d: %s", e.Code, e.Body) +} + +func isKubeStatus(err error, code int) bool { + var ae *kubeAPIError + return errors.As(err, &ae) && ae.Code == code +} + +func (b *KubernetesBackend) do(ctx context.Context, method, apiPath string, body, out any) error { + var r io.Reader + if body != nil { + raw, err := json.Marshal(body) + if err != nil { + return err + } + r = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, method, b.cfg.APIServer+apiPath, r) + if err != nil { + return err + } + tok, err := b.token() + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+tok) + req.Header.Set("Accept", "application/json") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := b.http.Do(req) + if err != nil { + return fmt.Errorf("%w: %v", ErrDockerUnavailable, err) + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return &kubeAPIError{Code: resp.StatusCode, Body: strings.TrimSpace(string(raw))} + } + if out != nil { + return json.NewDecoder(resp.Body).Decode(out) + } + _, _ = io.Copy(io.Discard, resp.Body) + return nil +} + +func (b *KubernetesBackend) nsPath(kind string) string { + switch kind { + case "networkpolicies": + return "/apis/networking.k8s.io/v1/namespaces/" + url.PathEscape(b.cfg.Namespace) + "/networkpolicies" + default: + return "/api/v1/namespaces/" + url.PathEscape(b.cfg.Namespace) + "/" + kind + } +} + +func (b *KubernetesBackend) create(ctx context.Context, kind string, obj any) error { + return b.do(ctx, http.MethodPost, b.nsPath(kind), obj, nil) +} + +// deleteObj deletes an object; a missing object is not an error. +func (b *KubernetesBackend) deleteObj(ctx context.Context, kind, name string, grace *int) error { + var body any + if grace != nil { + body = map[string]any{"gracePeriodSeconds": *grace, "propagationPolicy": "Background"} + } + err := b.do(ctx, http.MethodDelete, b.nsPath(kind)+"/"+url.PathEscape(name), body, nil) + if isKubeStatus(err, http.StatusNotFound) { + return nil + } + return err +} + +// Ping verifies the API server is reachable and the runner may list pods. +func (b *KubernetesBackend) Ping(ctx context.Context) error { + err := b.do(ctx, http.MethodGet, b.nsPath("pods")+"?limit=1&labelSelector="+url.QueryEscape(LabelManagedBy+"="+ManagedByRunner), nil, nil) + if err != nil && !errors.Is(err, ErrDockerUnavailable) { + return fmt.Errorf("%w: %v", ErrDockerUnavailable, err) + } + return err +} + +// WorkerCount returns the number of tracked tasks. +func (b *KubernetesBackend) WorkerCount() int { + b.mu.Lock() + defer b.mu.Unlock() + return len(b.tasks) +} + +type kubeObjectMeta struct { + Name string `json:"name"` + Labels map[string]string `json:"labels"` + Annotations map[string]string `json:"annotations"` + Deletion *string `json:"deletionTimestamp,omitempty"` +} + +type kubePod struct { + Metadata kubeObjectMeta `json:"metadata"` + Status struct { + Phase string `json:"phase"` + ContainerStatuses []struct { + Ready bool `json:"ready"` + State struct { + Waiting *struct { + Reason string `json:"reason"` + Message string `json:"message"` + } `json:"waiting"` + Terminated *struct { + Reason string `json:"reason"` + } `json:"terminated"` + } `json:"state"` + } `json:"containerStatuses"` + } `json:"status"` +} + +// Recover rebuilds task state from pods carrying artex.managed_by=artex-runner. +// Only pods that also carry a valid task annotation whose hash matches their label +// are adopted. +func (b *KubernetesBackend) Recover(ctx context.Context) (int, error) { + var list struct { + Items []kubePod `json:"items"` + } + sel := url.QueryEscape(LabelManagedBy + "=" + ManagedByRunner) + if err := b.do(ctx, http.MethodGet, b.nsPath("pods")+"?labelSelector="+sel, nil, &list); err != nil { + return 0, err + } + var svcs struct { + Items []struct { + Metadata kubeObjectMeta `json:"metadata"` + Spec struct { + ClusterIP string `json:"clusterIP"` + } `json:"spec"` + } `json:"items"` + } + if err := b.do(ctx, http.MethodGet, b.nsPath("services")+"?labelSelector="+sel, nil, &svcs); err != nil { + return 0, err + } + svcIP := map[string]string{} + for _, s := range svcs.Items { + svcIP[s.Metadata.Labels[LabelTaskHash]] = s.Spec.ClusterIP + } + b.mu.Lock() + defer b.mu.Unlock() + for _, p := range list.Items { + if p.Metadata.Deletion != nil || p.Metadata.Labels[LabelManagedBy] != ManagedByRunner { + continue + } + tid := p.Metadata.Annotations[AnnotationTaskID] + if ValidateTaskID(tid) != nil || kubeTaskHash(tid) != p.Metadata.Labels[LabelTaskHash] { + continue + } + kt := b.tasks[tid] + if kt == nil { + kt = &kubeTask{taskID: tid, hash: kubeTaskHash(tid), proxyIP: svcIP[kubeTaskHash(tid)]} + b.tasks[tid] = kt + } + switch p.Metadata.Labels[LabelComponent] { + case ComponentWorker: + kt.workerPod = p.Metadata.Name + case ComponentProxy: + kt.proxyPod = p.Metadata.Name + kt.scopeHash = p.Metadata.Annotations[AnnotationScope] + } + } + return len(b.tasks), nil +} + +func (b *KubernetesBackend) taskLabels(kt *kubeTask, component string) map[string]string { + return map[string]string{ + LabelManagedBy: ManagedByRunner, + LabelTaskHash: kt.hash, + LabelComponent: component, + } +} + +func (b *KubernetesBackend) meta(name string, kt *kubeTask, component string, extra map[string]string) map[string]any { + ann := map[string]string{AnnotationTaskID: kt.taskID} + for k, v := range extra { + ann[k] = v + } + m := map[string]any{"name": name, "annotations": ann} + labels := map[string]string{LabelManagedBy: ManagedByRunner, LabelTaskHash: kt.hash} + if component != "" { + labels[LabelComponent] = component + } + m["labels"] = labels + return m +} + +// prepareDirs creates the per-task workspace and audit directories owned by the +// worker uid, mirroring DockerBackend (best effort: the runner may lack CAP_CHOWN +// when the volume is already owned by 10001). +func (b *KubernetesBackend) prepareDirs(taskID string) { + for _, dir := range []string{filepath.Join(b.cfg.WorkspaceRoot, taskID), filepath.Join(b.cfg.AuditRoot, taskID)} { + if err := os.MkdirAll(dir, 0o775); err != nil { + log.Printf("[runner] mkdir %s: %v", dir, err) + continue + } + _ = os.Chown(dir, WorkerUID, WorkerGID) + } +} + +func (b *KubernetesBackend) podSecurity() (map[string]any, map[string]any) { + pod := map[string]any{ + "runAsUser": WorkerUID, + "runAsGroup": WorkerGID, + "runAsNonRoot": true, + "seccompProfile": map[string]any{ + "type": "RuntimeDefault", + }, + } + ctr := map[string]any{ + "allowPrivilegeEscalation": false, + "readOnlyRootFilesystem": true, + "privileged": false, + "capabilities": map[string]any{"drop": []string{"ALL"}}, + } + return pod, ctr +} + +func (b *KubernetesBackend) basePodSpec() map[string]any { + podSec, _ := b.podSecurity() + spec := map[string]any{ + "restartPolicy": "Always", + "automountServiceAccountToken": false, + "enableServiceLinks": false, + "hostNetwork": false, + "hostPID": false, + "hostIPC": false, + "shareProcessNamespace": false, + "terminationGracePeriodSeconds": 5, + "securityContext": podSec, + } + if b.cfg.ServiceAccount != "" { + spec["serviceAccountName"] = b.cfg.ServiceAccount + } + if b.cfg.RuntimeClassName != "" { + spec["runtimeClassName"] = b.cfg.RuntimeClassName + } + if b.cfg.PinNode != "" { + spec["affinity"] = map[string]any{"nodeAffinity": map[string]any{ + "requiredDuringSchedulingIgnoredDuringExecution": map[string]any{ + "nodeSelectorTerms": []any{map[string]any{"matchFields": []any{map[string]any{ + "key": "metadata.name", "operator": "In", "values": []string{b.cfg.PinNode}, + }}}}, + }, + }} + } + return spec +} + +func (b *KubernetesBackend) proxyPodObj(name string, kt *kubeTask, scopeDomains, scopeCIDRs []string) map[string]any { + _, ctrSec := b.podSecurity() + spec := b.basePodSpec() + spec["containers"] = []any{map[string]any{ + "name": kubeProxyName, + "image": b.cfg.ProxyImage, + "imagePullPolicy": b.cfg.ImagePullPolicy, + "env": []any{ + map[string]any{"name": "ARTEX_TASK_ID", "value": kt.taskID}, + map[string]any{"name": "ARTEX_SCOPE_DOMAINS", "value": strings.Join(scopeDomains, ",")}, + map[string]any{"name": "ARTEX_SCOPE_CIDRS", "value": strings.Join(scopeCIDRs, ",")}, + map[string]any{"name": "ARTEX_PROXY_PORT", "value": strconv.Itoa(DefaultProxyPort)}, + map[string]any{"name": "ARTEX_SOCKS_PORT", "value": strconv.Itoa(DefaultSocksPort)}, + map[string]any{"name": "ARTEX_EGRESS_LOG_PATH", "value": "/audit/egress.jsonl"}, + }, + "ports": []any{ + map[string]any{"name": "http-proxy", "containerPort": DefaultProxyPort, "protocol": "TCP"}, + map[string]any{"name": "socks", "containerPort": DefaultSocksPort, "protocol": "TCP"}, + }, + "readinessProbe": map[string]any{ + "tcpSocket": map[string]any{"port": DefaultProxyPort}, + "periodSeconds": 2, + }, + "securityContext": ctrSec, + "resources": map[string]any{ + "requests": map[string]string{"cpu": "50m", "memory": "32Mi"}, + "limits": map[string]string{"cpu": "500m", "memory": "256Mi"}, + }, + "volumeMounts": []any{map[string]any{ + "name": "data", "mountPath": "/audit", "subPath": path.Join(b.cfg.AuditSubPath, kt.taskID), + }}, + }} + spec["volumes"] = []any{map[string]any{ + "name": "data", "persistentVolumeClaim": map[string]any{"claimName": b.cfg.DataClaim}, + }} + return map[string]any{ + "apiVersion": "v1", + "kind": "Pod", + "metadata": b.meta(name, kt, ComponentProxy, map[string]string{AnnotationScope: kt.scopeHash}), + "spec": spec, + } +} + +// workerBaseEnv is the environment every worker command runs with, matching the +// DockerBackend worker container. +func workerBaseEnv(proxyIP string) [][2]string { + proxyURL := fmt.Sprintf("http://%s:%d", proxyIP, DefaultProxyPort) + socksURL := fmt.Sprintf("socks5h://%s:%d", proxyIP, DefaultSocksPort) + return [][2]string{ + {"PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}, + {"HOME", "/home/exec"}, {"LANG", "C.UTF-8"}, {"TERM", "xterm"}, + {"HTTP_PROXY", proxyURL}, {"HTTPS_PROXY", proxyURL}, {"ALL_PROXY", socksURL}, {"NO_PROXY", "localhost,127.0.0.1"}, + {"http_proxy", proxyURL}, {"https_proxy", proxyURL}, {"all_proxy", socksURL}, {"no_proxy", "localhost,127.0.0.1"}, + } +} + +func (b *KubernetesBackend) workerPodObj(name string, kt *kubeTask) map[string]any { + _, ctrSec := b.podSecurity() + env := []any{} + for _, kv := range workerBaseEnv(kt.proxyIP) { + env = append(env, map[string]any{"name": kv[0], "value": kv[1]}) + } + spec := b.basePodSpec() + // The worker never talks to cluster DNS (its NetworkPolicy only reaches the + // proxy ClusterIP); a resolver pointing nowhere keeps lookups from leaking. + spec["dnsPolicy"] = "None" + spec["dnsConfig"] = map[string]any{"nameservers": []string{"127.0.0.1"}} + spec["containers"] = []any{map[string]any{ + "name": kubeWorkerName, + "image": b.cfg.WorkerImage, + "imagePullPolicy": b.cfg.ImagePullPolicy, + "command": []string{"/usr/local/bin/artex-exec-wrap", "--init"}, + "workingDir": "/workspace", + "env": env, + "securityContext": ctrSec, + "resources": map[string]any{ + "requests": map[string]string{"cpu": "100m", "memory": "128Mi"}, + "limits": map[string]string{"cpu": b.cfg.WorkerCPULimit, "memory": b.cfg.WorkerMemoryLimit, "ephemeral-storage": "1Gi"}, + }, + "volumeMounts": []any{ + map[string]any{"name": "data", "mountPath": "/workspace", "subPath": path.Join(b.cfg.TasksSubPath, kt.taskID)}, + map[string]any{"name": "tmp", "mountPath": "/tmp"}, + map[string]any{"name": "home", "mountPath": "/home/exec"}, + }, + }} + spec["volumes"] = []any{ + map[string]any{"name": "data", "persistentVolumeClaim": map[string]any{"claimName": b.cfg.DataClaim}}, + map[string]any{"name": "tmp", "emptyDir": map[string]any{"medium": "Memory", "sizeLimit": "512Mi"}}, + map[string]any{"name": "home", "emptyDir": map[string]any{"medium": "Memory", "sizeLimit": "128Mi"}}, + } + return map[string]any{ + "apiVersion": "v1", + "kind": "Pod", + "metadata": b.meta(name, kt, ComponentWorker, nil), + "spec": spec, + } +} + +func (b *KubernetesBackend) proxyServiceObj(name string, kt *kubeTask) map[string]any { + return map[string]any{ + "apiVersion": "v1", + "kind": "Service", + "metadata": b.meta(name, kt, ComponentProxy, nil), + "spec": map[string]any{ + "type": "ClusterIP", + "selector": b.taskLabels(kt, ComponentProxy), + "ports": []any{ + map[string]any{"name": "http-proxy", "port": DefaultProxyPort, "targetPort": DefaultProxyPort, "protocol": "TCP"}, + map[string]any{"name": "socks", "port": DefaultSocksPort, "targetPort": DefaultSocksPort, "protocol": "TCP"}, + }, + }, + } +} + +func proxyPorts() []any { + return []any{ + map[string]any{"protocol": "TCP", "port": DefaultProxyPort}, + map[string]any{"protocol": "TCP", "port": DefaultSocksPort}, + } +} + +// workerPolicyObj lets the task's worker reach only its own proxy. Together with the +// chart's default-deny policy for every runner-managed pod, a worker whose per-task +// policy is missing has no network at all (fail closed). +func (b *KubernetesBackend) workerPolicyObj(name string, kt *kubeTask) map[string]any { + return map[string]any{ + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": b.meta(name, kt, ComponentWorker, nil), + "spec": map[string]any{ + "podSelector": map[string]any{"matchLabels": b.taskLabels(kt, ComponentWorker)}, + "policyTypes": []string{"Ingress", "Egress"}, + "ingress": []any{}, + "egress": []any{map[string]any{ + "to": []any{map[string]any{"podSelector": map[string]any{"matchLabels": b.taskLabels(kt, ComponentProxy)}}}, + "ports": proxyPorts(), + }}, + }, + } +} + +// proxyPolicyObj admits only the task's worker and lets the proxy reach cluster DNS, +// public addresses, and the task's scope CIDRs. +func (b *KubernetesBackend) proxyPolicyObj(name string, kt *kubeTask, scopeCIDRs []string) map[string]any { + egress := []any{ + map[string]any{ + "to": []any{map[string]any{ + "namespaceSelector": map[string]any{"matchLabels": map[string]string{"kubernetes.io/metadata.name": b.cfg.DNSNamespace}}, + "podSelector": map[string]any{"matchLabels": b.cfg.DNSPodLabels}, + }}, + "ports": []any{ + map[string]any{"protocol": "UDP", "port": 53}, + map[string]any{"protocol": "TCP", "port": 53}, + }, + }, + map[string]any{"to": []any{map[string]any{"ipBlock": map[string]any{"cidr": "0.0.0.0/0", "except": b.cfg.ProxyDeniedCIDRs}}}}, + } + var scopeBlocks []any + for _, c := range scopeCIDRs { + if p, err := netip.ParsePrefix(strings.TrimSpace(c)); err == nil { + scopeBlocks = append(scopeBlocks, map[string]any{"ipBlock": map[string]any{"cidr": p.Masked().String()}}) + } else if a, err := netip.ParseAddr(strings.TrimSpace(c)); err == nil { + scopeBlocks = append(scopeBlocks, map[string]any{"ipBlock": map[string]any{"cidr": netip.PrefixFrom(a, a.BitLen()).String()}}) + } + } + if len(scopeBlocks) > 0 { + egress = append(egress, map[string]any{"to": scopeBlocks}) + } + return map[string]any{ + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": b.meta(name, kt, ComponentProxy, nil), + "spec": map[string]any{ + "podSelector": map[string]any{"matchLabels": b.taskLabels(kt, ComponentProxy)}, + "policyTypes": []string{"Ingress", "Egress"}, + "ingress": []any{map[string]any{ + "from": []any{map[string]any{"podSelector": map[string]any{"matchLabels": b.taskLabels(kt, ComponentWorker)}}}, + "ports": proxyPorts(), + }}, + "egress": egress, + }, + } +} + +// applyPolicy creates a NetworkPolicy or replaces an existing one. +func (b *KubernetesBackend) applyPolicy(ctx context.Context, obj map[string]any) error { + name := obj["metadata"].(map[string]any)["name"].(string) + err := b.create(ctx, "networkpolicies", obj) + if isKubeStatus(err, http.StatusConflict) { + return b.do(ctx, http.MethodPut, b.nsPath("networkpolicies")+"/"+url.PathEscape(name), obj, nil) + } + return err +} + +func (b *KubernetesBackend) getPod(ctx context.Context, name string) (*kubePod, error) { + var p kubePod + if err := b.do(ctx, http.MethodGet, b.nsPath("pods")+"/"+url.PathEscape(name), nil, &p); err != nil { + return nil, err + } + return &p, nil +} + +// waitPodReady polls until every container of the pod is ready. It fails fast on +// image pull errors and terminated containers. +func (b *KubernetesBackend) waitPodReady(ctx context.Context, name string) error { + ctx, cancel := context.WithTimeout(ctx, b.cfg.PodReadyTimeout) + defer cancel() + for { + p, err := b.getPod(ctx, name) + if err != nil && !isKubeStatus(err, http.StatusNotFound) { + return err + } + if p != nil { + if p.Status.Phase == "Failed" || p.Status.Phase == "Succeeded" { + return fmt.Errorf("pod %s ended in phase %s", name, p.Status.Phase) + } + ready := p.Status.Phase == "Running" && len(p.Status.ContainerStatuses) > 0 + for _, cs := range p.Status.ContainerStatuses { + if w := cs.State.Waiting; w != nil { + switch w.Reason { + case "ErrImagePull", "ImagePullBackOff", "InvalidImageName", "CreateContainerConfigError", "CreateContainerError": + return fmt.Errorf("pod %s: %s: %s", name, w.Reason, w.Message) + } + } + if !cs.Ready { + ready = false + } + } + if ready { + return nil + } + } + select { + case <-ctx.Done(): + return fmt.Errorf("pod %s not ready after %s: %w", name, b.cfg.PodReadyTimeout, ctx.Err()) + case <-time.After(500 * time.Millisecond): + } + } +} + +func (b *KubernetesBackend) podAlive(ctx context.Context, name string) bool { + if name == "" { + return false + } + p, err := b.getPod(ctx, name) + if err != nil || p.Metadata.Deletion != nil { + return false + } + if p.Status.Phase != "Running" { + return false + } + for _, cs := range p.Status.ContainerStatuses { + if !cs.Ready { + return false + } + } + return true +} + +// deletePod removes a pod immediately and waits until it is gone, so a pod with the +// same name can be created again. +func (b *KubernetesBackend) deletePodAndWait(ctx context.Context, name string) error { + zero := 0 + if err := b.deleteObj(ctx, "pods", name, &zero); err != nil { + return err + } + wctx, cancel := context.WithTimeout(ctx, 60*time.Second) + defer cancel() + for { + _, err := b.getPod(wctx, name) + if isKubeStatus(err, http.StatusNotFound) { + return nil + } + select { + case <-wctx.Done(): + return fmt.Errorf("pod %s still present after delete: %w", name, wctx.Err()) + case <-time.After(300 * time.Millisecond): + } + } +} + +func (b *KubernetesBackend) taskLock(taskID string) *sync.Mutex { + b.mu.Lock() + defer b.mu.Unlock() + l := b.locks[taskID] + if l == nil { + l = &sync.Mutex{} + b.locks[taskID] = l + } + return l +} + +func (b *KubernetesBackend) ensureTask(ctx context.Context, taskID string, scopeDomains, scopeCIDRs []string) (*kubeTask, error) { + l := b.taskLock(taskID) + l.Lock() + defer l.Unlock() + + b.mu.Lock() + kt := b.tasks[taskID] + b.mu.Unlock() + if kt != nil { + cp := *kt + kt = &cp + } + + sh := kubeTaskHash(scopeFingerprint(scopeDomains, scopeCIDRs))[:8] + if kt == nil { + kt = &kubeTask{taskID: taskID, hash: kubeTaskHash(taskID)} + } + if kt.scopeHash == sh && kt.proxyIP != "" && b.podAlive(ctx, kt.proxyPod) && b.podAlive(ctx, kt.workerPod) { + return kt, nil + } + + b.prepareDirs(taskID) + + workerPolicy := "artex-w-" + kt.hash + proxyPolicy := "artex-p-" + kt.hash + svcName := "artex-p-" + kt.hash + proxyPod := "artex-p-" + kt.hash + workerPod := "artex-w-" + kt.hash + + // Policies first: a pod must never run before its isolation exists. + if err := b.applyPolicy(ctx, b.workerPolicyObj(workerPolicy, kt)); err != nil { + return nil, fmt.Errorf("worker network policy: %w", err) + } + if err := b.applyPolicy(ctx, b.proxyPolicyObj(proxyPolicy, kt, scopeCIDRs)); err != nil { + return nil, fmt.Errorf("proxy network policy: %w", err) + } + + if kt.proxyIP == "" { + err := b.create(ctx, "services", b.proxyServiceObj(svcName, kt)) + if err != nil && !isKubeStatus(err, http.StatusConflict) { + return nil, fmt.Errorf("proxy service: %w", err) + } + var svc struct { + Metadata kubeObjectMeta `json:"metadata"` + Spec struct { + ClusterIP string `json:"clusterIP"` + } `json:"spec"` + } + if err := b.do(ctx, http.MethodGet, b.nsPath("services")+"/"+url.PathEscape(svcName), nil, &svc); err != nil { + return nil, fmt.Errorf("proxy service: %w", err) + } + if svc.Metadata.Labels[LabelManagedBy] != ManagedByRunner || svc.Metadata.Labels[LabelTaskHash] != kt.hash { + return nil, fmt.Errorf("existing service %s has untrusted labels %v (refusing to route worker through it)", svcName, svc.Metadata.Labels) + } + if ip := net.ParseIP(svc.Spec.ClusterIP); ip == nil { + return nil, fmt.Errorf("proxy service %s has no ClusterIP (%q)", svcName, svc.Spec.ClusterIP) + } + kt.proxyIP = svc.Spec.ClusterIP + } + + // (Re)create the proxy when missing, dead, or the scope changed. + if kt.scopeHash != sh || !b.podAlive(ctx, kt.proxyPod) { + if err := b.deletePodAndWait(ctx, proxyPod); err != nil { + return nil, err + } + kt.scopeHash = sh + if err := b.create(ctx, "pods", b.proxyPodObj(proxyPod, kt, scopeDomains, scopeCIDRs)); err != nil { + return nil, fmt.Errorf("create proxy pod: %w", err) + } + kt.proxyPod = proxyPod + } + if !b.podAlive(ctx, kt.workerPod) { + if err := b.deletePodAndWait(ctx, workerPod); err != nil { + return nil, err + } + if err := b.create(ctx, "pods", b.workerPodObj(workerPod, kt)); err != nil { + return nil, fmt.Errorf("create worker pod: %w", err) + } + kt.workerPod = workerPod + } + if err := b.waitPodReady(ctx, kt.proxyPod); err != nil { + return nil, err + } + if err := b.waitPodReady(ctx, kt.workerPod); err != nil { + return nil, err + } + if err := b.waitNetworkReady(ctx, kt); err != nil { + return nil, err + } + + b.mu.Lock() + b.tasks[taskID] = kt + b.mu.Unlock() + return kt, nil +} + +// waitNetworkReady blocks until the task's NetworkPolicies are in effect for its +// current pods. A pod becomes Ready before the CNI has programmed policy for its +// new IP (seconds on k3s/kube-router), and until then the worker cannot reach its +// proxy and the proxy cannot reach DNS. Running the first command in that window +// would fail spuriously, so probe both paths first. +func (b *KubernetesBackend) waitNetworkReady(ctx context.Context, kt *kubeTask) error { + ctx, cancel := context.WithTimeout(ctx, b.cfg.PodReadyTimeout) + defer cancel() + workerProbe := []string{"/usr/local/bin/artex-exec-wrap", "3000", "--", "bash", "-c", + fmt.Sprintf("exec 3<>/dev/tcp/%s/%d", kt.proxyIP, DefaultProxyPort)} + proxyProbe := []string{"getent", "hosts", "kubernetes.default.svc"} + for _, p := range []struct { + pod, container string + argv []string + what string + }{ + {kt.workerPod, kubeWorkerName, workerProbe, "worker to proxy"}, + {kt.proxyPod, kubeProxyName, proxyProbe, "proxy to cluster DNS"}, + } { + var last string + for { + pctx, pcancel := context.WithTimeout(ctx, 10*time.Second) + _, serr, _, code, err := b.containerExec(pctx, p.pod, p.container, p.argv, 4096) + pcancel() + if err == nil && code == 0 { + break + } + last = fmt.Sprintf("exit %d err %v %s", code, err, strings.TrimSpace(serr)) + select { + case <-ctx.Done(): + return fmt.Errorf("network path %s not open after %s (network policy not applied? last: %s)", p.what, b.cfg.PodReadyTimeout, last) + case <-time.After(500 * time.Millisecond): + } + } + } + return nil +} + +// kubeExecStatus is the metav1.Status sent on the exec error channel. +type kubeExecStatus struct { + Status string `json:"status"` + Message string `json:"message"` + Reason string `json:"reason"` + Details struct { + Causes []struct { + Reason string `json:"reason"` + Message string `json:"message"` + } `json:"causes"` + } `json:"details"` +} + +// cappedBuffer keeps the first max bytes written and records truncation. +type cappedBuffer struct { + buf bytes.Buffer + max int + truncated bool +} + +func (c *cappedBuffer) Write(p []byte) { + rem := c.max - c.buf.Len() + if rem <= 0 { + if len(p) > 0 { + c.truncated = true + } + return + } + if len(p) > rem { + p = p[:rem] + c.truncated = true + } + c.buf.Write(p) +} + +// podExec runs argv in the pod's worker container over the Kubernetes exec +// WebSocket (channel.k8s.io v5/v4) and returns stdout, stderr and the exit code. +func (b *KubernetesBackend) podExec(ctx context.Context, pod string, argv []string, maxBytes int) (stdout, stderr string, truncated bool, exitCode int, err error) { + return b.containerExec(ctx, pod, kubeWorkerName, argv, maxBytes) +} + +func (b *KubernetesBackend) containerExec(ctx context.Context, pod, container string, argv []string, maxBytes int) (stdout, stderr string, truncated bool, exitCode int, err error) { + q := url.Values{} + q.Set("container", container) + q.Set("stdout", "true") + q.Set("stderr", "true") + for _, a := range argv { + q.Add("command", a) + } + u, err := url.Parse(b.cfg.APIServer + b.nsPath("pods") + "/" + url.PathEscape(pod) + "/exec?" + q.Encode()) + if err != nil { + return "", "", false, -1, err + } + switch u.Scheme { + case "https": + u.Scheme = "wss" + case "http": + u.Scheme = "ws" + } + tok, err := b.token() + if err != nil { + return "", "", false, -1, err + } + dialer := websocket.Dialer{ + Proxy: nil, + TLSClientConfig: b.tls, + HandshakeTimeout: 30 * time.Second, + Subprotocols: []string{"v5.channel.k8s.io", "v4.channel.k8s.io"}, + } + hdr := http.Header{} + hdr.Set("Authorization", "Bearer "+tok) + conn, resp, err := dialer.DialContext(ctx, u.String(), hdr) + if err != nil { + if resp != nil { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + resp.Body.Close() + if resp.StatusCode == http.StatusNotFound { + return "", "", false, -1, fmt.Errorf("%w: pod %s", ErrNotFound, pod) + } + return "", "", false, -1, &kubeAPIError{Code: resp.StatusCode, Body: strings.TrimSpace(string(raw))} + } + return "", "", false, -1, fmt.Errorf("%w: exec dial: %v", ErrDockerUnavailable, err) + } + defer conn.Close() + stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) + defer stop() + + out := &cappedBuffer{max: maxBytes} + errb := &cappedBuffer{max: maxBytes} + exitCode = -1 + var status *kubeExecStatus + for { + _, msg, rerr := conn.ReadMessage() + if rerr != nil { + if ctx.Err() != nil { + return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, -1, ctx.Err() + } + break + } + if len(msg) == 0 { + continue + } + switch msg[0] { + case 1: + out.Write(msg[1:]) + case 2: + errb.Write(msg[1:]) + case 3: + var st kubeExecStatus + if json.Unmarshal(msg[1:], &st) == nil { + status = &st + } + } + } + if status == nil { + return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, -1, errors.New("exec stream ended without a status") + } + switch { + case status.Status == "Success": + exitCode = 0 + case status.Reason == "NonZeroExitCode": + for _, c := range status.Details.Causes { + if c.Reason == "ExitCode" { + if n, perr := strconv.Atoi(c.Message); perr == nil { + exitCode = n + } + } + } + default: + return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, -1, fmt.Errorf("exec failed: %s", status.Message) + } + return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, exitCode, nil +} + +// kubeExecArgv builds the exec argv. Kubernetes exec has no working-directory or +// environment options, so env(1) applies both before handing off to +// artex-exec-wrap. It starts from an empty environment (-i): kubelet injects +// KUBERNETES_SERVICE_* into every container whatever enableServiceLinks says, and +// the command must see exactly what DockerBackend gives it — the worker base env +// plus the request's variables. Env names are validated by ValidateEnv (no '='), +// workdir by ValidateExecRequest (inside /workspace), and nothing passes through a +// shell. +func kubeExecArgv(req ExecRequest, proxyIP string) []string { + envList := make([]string, 0, len(req.Env)) + for k, v := range req.Env { + envList = append(envList, k+"="+v) + } + sort.Strings(envList) + workdir := req.Workdir + if workdir == "" { + workdir = "/workspace" + } + base := workerBaseEnv(proxyIP) + out := make([]string, 0, len(base)+len(envList)+len(req.Argv)+8) + out = append(out, "/usr/bin/env", "-i", "-C", workdir) + for _, kv := range base { + out = append(out, kv[0]+"="+kv[1]) + } + out = append(out, envList...) + out = append(out, "/usr/local/bin/artex-exec-wrap", strconv.Itoa(req.TimeoutMS), "--") + return append(out, req.Argv...) +} + +// Exec runs req.Argv inside the task's worker pod through artex-exec-wrap. +func (b *KubernetesBackend) Exec(ctx context.Context, taskID string, req ExecRequest) (ExecResponse, error) { + start := time.Now() + kt, err := b.ensureTask(ctx, taskID, req.ScopeDomains, req.ScopeCIDRs) + if err != nil { + return ExecResponse{}, err + } + execCtx, cancel := context.WithTimeout(ctx, time.Duration(req.TimeoutMS)*time.Millisecond+12*time.Second) + defer cancel() + stdout, stderr, truncated, code, err := b.podExec(execCtx, kt.workerPod, kubeExecArgv(req, kt.proxyIP), MaxOutputBytes) + if err != nil { + if ctx.Err() != nil || execCtx.Err() != nil { + _ = b.Kill(context.Background(), taskID) + } + return ExecResponse{}, err + } + return ExecResponse{ + ExitCode: code, + Stdout: stdout, + Stderr: stderr, + Truncated: truncated, + TimedOut: code == 124, + DurationMS: time.Since(start).Milliseconds(), + }, nil +} + +// Kill terminates every worker-uid process in the task's worker pod (PID 1 excluded) +// with artex-exec-wrap --kill-uid. If that fails, the worker pod is deleted so no +// process survives; /workspace stays on the volume for the next exec. +func (b *KubernetesBackend) Kill(ctx context.Context, taskID string) error { + b.mu.Lock() + kt := b.tasks[taskID] + b.mu.Unlock() + if kt == nil || kt.workerPod == "" { + return fmt.Errorf("%w: task %s", ErrNotFound, taskID) + } + kctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + _, _, _, code, err := b.podExec(kctx, kt.workerPod, []string{"/usr/local/bin/artex-exec-wrap", "--kill-uid", strconv.Itoa(WorkerUID)}, 4096) + if err == nil && code == 0 { + return nil + } + log.Printf("[runner] kill-uid for task %s failed (code=%d err=%v); deleting worker pod", taskID, code, err) + zero := 0 + if derr := b.deleteObj(context.Background(), "pods", kt.workerPod, &zero); derr != nil { + return derr + } + b.mu.Lock() + if cur := b.tasks[taskID]; cur != nil { + cur.workerPod = "" + } + b.mu.Unlock() + return nil +} + +// Delete removes the task's pods, proxy service and network policies, keeping the +// workspace directory on the volume. Policies go last so no pod outlives them. +func (b *KubernetesBackend) Delete(ctx context.Context, taskID string) error { + l := b.taskLock(taskID) + l.Lock() + defer l.Unlock() + b.mu.Lock() + kt := b.tasks[taskID] + delete(b.tasks, taskID) + b.mu.Unlock() + if kt == nil { + return fmt.Errorf("%w: task %s", ErrNotFound, taskID) + } + zero := 0 + var errs []error + for _, obj := range [][2]string{ + {"pods", "artex-w-" + kt.hash}, + {"pods", "artex-p-" + kt.hash}, + {"services", "artex-p-" + kt.hash}, + } { + g := &zero + if obj[0] != "pods" { + g = nil + } + if err := b.deleteObj(ctx, obj[0], obj[1], g); err != nil { + errs = append(errs, err) + } + } + for _, name := range []string{"artex-w-" + kt.hash, "artex-p-" + kt.hash} { + if err := b.deleteObj(ctx, "networkpolicies", name, nil); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} diff --git a/sandbox/kube_e2e_test.go b/sandbox/kube_e2e_test.go new file mode 100644 index 000000000..2121d5aad --- /dev/null +++ b/sandbox/kube_e2e_test.go @@ -0,0 +1,323 @@ +package sandbox + +import ( + "context" + "fmt" + "net" + "os" + "os/exec" + "regexp" + "strings" + "sync" + "testing" + "time" +) + +// TestKubeSandboxE2E drives a real artex-runner deployed by the Helm chart with +// backend=kubernetes, through its HTTP API, and inspects the cluster with kubectl. +// scripts/k3d-e2e.sh sets everything up. Enable with: +// +// ARTEX_SANDBOX_KUBE_E2E=1 +// ARTEX_RUNNER_TOKEN=... (the release's ARTEX_RUNNER_TOKEN) +// ARTEX_E2E_NAMESPACE=artex +// ARTEX_E2E_KUBECONTEXT=k3d-artex (optional) +// ARTEX_E2E_INTERNET=1 (optional: test allowed egress to example.com) +func TestKubeSandboxE2E(t *testing.T) { + if os.Getenv("ARTEX_SANDBOX_KUBE_E2E") != "1" { + t.Skip("set ARTEX_SANDBOX_KUBE_E2E=1 (see scripts/k3d-e2e.sh)") + } + ns := envDefault("ARTEX_E2E_NAMESPACE", "artex") + kctx := os.Getenv("ARTEX_E2E_KUBECONTEXT") + kubectl := func(args ...string) (string, error) { + full := []string{"-n", ns} + if kctx != "" { + full = append(full, "--context", kctx) + } + out, err := exec.Command("kubectl", append(full, args...)...).CombinedOutput() + return strings.TrimSpace(string(out)), err + } + // The test owns its port-forward: a forward to a Service is pinned to one pod + // and dies when that pod does, which the runner-restart case causes. + const pfPort = "18799" + var pf *exec.Cmd + startPF := func() { + args := []string{"-n", ns, "port-forward", "svc/" + envDefault("ARTEX_E2E_RUNNER_SVC", "artex-runner"), pfPort + ":8789"} + if kctx != "" { + args = append([]string{"--context", kctx}, args...) + } + pf = exec.Command("kubectl", args...) + if err := pf.Start(); err != nil { + t.Fatalf("port-forward: %v", err) + } + for i := 0; i < 50; i++ { + if conn, err := net.DialTimeout("tcp", "127.0.0.1:"+pfPort, 200*time.Millisecond); err == nil { + conn.Close() + return + } + time.Sleep(200 * time.Millisecond) + } + t.Fatal("port-forward did not come up") + } + stopPF := func() { + if pf != nil && pf.Process != nil { + _ = pf.Process.Kill() + _ = pf.Wait() + } + } + startPF() + t.Cleanup(stopPF) + + c := NewClient("http://127.0.0.1:"+pfPort, os.Getenv(EnvRunnerToken)) + ctx := context.Background() + + health, err := c.Health(ctx) + if err != nil || !health.OK { + t.Fatalf("runner health = %+v, %v", health, err) + } + + // A unique task per run; IDs with uppercase and '_' exercise the name hashing. + taskID := fmt.Sprintf("E2E_task.%d", time.Now().UnixNano()) + h := kubeTaskHash(taskID) + t.Cleanup(func() { _, _ = c.Delete(context.Background(), taskID) }) + + run := func(t *testing.T, req ExecRequest) ExecResponse { + t.Helper() + if req.TimeoutMS == 0 { + req.TimeoutMS = 60000 + } + res, err := c.Exec(ctx, taskID, req) + if err != nil { + t.Fatalf("exec %v: %v", req.Argv, err) + } + return res + } + sh := func(t *testing.T, script string) ExecResponse { + t.Helper() + return run(t, ExecRequest{Argv: []string{"bash", "-c", script}}) + } + + t.Run("identity and hardening", func(t *testing.T) { + res := sh(t, `id -u; id -g; cat /proc/self/status | grep -E '^(NoNewPrivs|CapEff)'`) + if res.ExitCode != 0 { + t.Fatalf("%+v", res) + } + lines := strings.Fields(res.Stdout) + if lines[0] != "10001" || lines[1] != "10001" { + t.Fatalf("uid/gid = %v", lines[:2]) + } + if !regexpMatch(`NoNewPrivs:\s+1`, res.Stdout) { + t.Errorf("no_new_privs not set: %q", res.Stdout) + } + if !regexpMatch(`CapEff:\s+0000000000000000`, res.Stdout) { + t.Errorf("effective capabilities not empty: %q", res.Stdout) + } + if r := sh(t, `touch /etc/x 2>&1; echo rc=$?`); !strings.Contains(r.Stdout, "rc=1") { + t.Errorf("root filesystem writable: %q", r.Stdout) + } + if r := sh(t, `ls /var/run/secrets/kubernetes.io/serviceaccount 2>&1; echo rc=$?`); strings.Contains(r.Stdout, "token") { + t.Errorf("service account token mounted: %q", r.Stdout) + } + if r := sh(t, `env`); strings.Contains(r.Stdout, "KUBERNETES_") || strings.Contains(r.Stdout, "ARTEX_") || strings.Contains(r.Stdout, "ANTHROPIC") { + t.Errorf("worker env leaks cluster or server values: %q", r.Stdout) + } + }) + + t.Run("workspace persists and workdir and env apply", func(t *testing.T) { + if r := sh(t, `mkdir -p sub && echo persisted > sub/f.txt`); r.ExitCode != 0 { + t.Fatalf("%+v", r) + } + r := run(t, ExecRequest{Argv: []string{"bash", "-c", `pwd; cat f.txt; printf '%s' "$WEIRD"`}, Workdir: "/workspace/sub", + Env: map[string]string{"WEIRD": `a b;$(id) "q"`}}) + if r.ExitCode != 0 || r.Stdout != "/workspace/sub\npersisted\na b;$(id) \"q\"" { + t.Fatalf("%+v", r) + } + }) + + t.Run("exit codes, timeout, truncation", func(t *testing.T) { + if r := sh(t, `exit 7`); r.ExitCode != 7 || r.TimedOut { + t.Fatalf("%+v", r) + } + r := run(t, ExecRequest{Argv: []string{"sleep", "60"}, TimeoutMS: 1500}) + if r.ExitCode != 124 || !r.TimedOut || r.DurationMS > 15000 { + t.Fatalf("timeout: %+v", r) + } + r = sh(t, `head -c 3000000 /dev/zero | tr '\0' A`) + if len(r.Stdout) != MaxOutputBytes || !r.Truncated { + t.Fatalf("truncation: len=%d truncated=%v", len(r.Stdout), r.Truncated) + } + }) + + t.Run("cluster objects", func(t *testing.T) { + out, err := kubectl("get", "pods,svc,networkpolicy", "-l", LabelTaskHash+"="+h, "-o", "name") + if err != nil { + t.Fatal(out) + } + for _, want := range []string{"pod/artex-w-" + h, "pod/artex-p-" + h, "service/artex-p-" + h, + "networkpolicy.networking.k8s.io/artex-w-" + h, "networkpolicy.networking.k8s.io/artex-p-" + h} { + if !strings.Contains(out, want) { + t.Errorf("missing %s in:\n%s", want, out) + } + } + out, _ = kubectl("get", "pod", "artex-w-"+h, "-o", "jsonpath={.metadata.annotations.artex\\.task}") + if out != taskID { + t.Errorf("task annotation = %q", out) + } + }) + + t.Run("network isolation", func(t *testing.T) { + lookup := func(args ...string) string { + out, err := kubectl(args...) + if err != nil { + return "" + } + return out + } + apiIP := lookup("get", "svc", "kubernetes", "-n", "default", "-o", "jsonpath={.spec.clusterIP}") + panelIP := lookup("get", "svc", "-l", "app.kubernetes.io/component=panel", "-o", "jsonpath={.items[0].spec.clusterIP}") + pgPod := lookup("get", "pod", "-l", "app.kubernetes.io/component=postgres", "-o", "jsonpath={.items[0].status.podIP}") + dnsIP := lookup("get", "svc", "kube-dns", "-n", "kube-system", "-o", "jsonpath={.spec.clusterIP}") + targets := map[string]string{ + "internet": "1.1.1.1:443", + "kube-api": apiIP + ":443", + "panel": panelIP + ":8787", + "postgres": pgPod + ":5432", + "kube-dns": dnsIP + ":53", + "metadata": "169.254.169.254:80", + } + for name, addr := range targets { + if strings.HasPrefix(addr, ":") { + t.Logf("skip %s: address unknown", name) + continue + } + host, port, _ := strings.Cut(addr, ":") + // Direct TCP connect, bypassing the proxy: must fail. + r := sh(t, fmt.Sprintf(`timeout 6 bash -c 'exec 3<>/dev/tcp/%s/%s' 2>/dev/null && echo OPEN || echo BLOCKED`, host, port)) + if !strings.Contains(r.Stdout, "BLOCKED") { + t.Errorf("worker reached %s (%s) directly: %q", name, addr, r.Stdout) + } + } + // Through the proxy: cluster addresses are refused BY THE PROXY (403), which + // also proves the worker reaches its proxy (a connect failure would hide it). + if panelIP != "" { + r := sh(t, fmt.Sprintf(`curl -s -o /dev/null -w '%%{http_code}' --max-time 10 http://%s:8787/api/health`, panelIP)) + if r.Stdout != "403" { + t.Errorf("panel via proxy: got %q, want the proxy's 403", r.Stdout) + } + } + // Out-of-scope domain: the proxy answers the CONNECT with 403. + r := sh(t, `curl -s -o /dev/null -w '%{http_connect}' --max-time 15 https://example.org`) + if r.Stdout != "403" { + t.Errorf("out-of-scope CONNECT: got %q, want the proxy's 403", r.Stdout) + } + // SOCKS5 path refuses too. + r = sh(t, `curl -s -o /dev/null -w '%{http_code}' --max-time 15 --socks5-hostname "${ALL_PROXY#socks5h://}" https://example.org; echo " rc=$?"`) + if strings.HasPrefix(r.Stdout, "200") { + t.Errorf("out-of-scope host reachable over SOCKS5: %q", r.Stdout) + } + }) + + t.Run("in-scope egress through proxy", func(t *testing.T) { + if os.Getenv("ARTEX_E2E_INTERNET") != "1" { + t.Skip("set ARTEX_E2E_INTERNET=1 to test egress to example.com") + } + r := run(t, ExecRequest{Argv: []string{"bash", "-c", `curl -s -o /dev/null -w '%{http_code}' --max-time 20 https://example.com`}, + ScopeDomains: []string{"example.com"}}) + if r.Stdout != "200" { + t.Fatalf("in-scope request: %+v", r) + } + // The proxy logs the decision to the per-task audit file on the volume. + audit, err := kubectl("logs", "artex-p-"+h) + if err != nil || !strings.Contains(audit, "example.com") { + t.Errorf("proxy decision not logged: %v %q", err, audit) + } + // Scope change replaced the proxy; the worker kept its workspace. + if r := sh(t, `cat sub/f.txt`); r.Stdout != "persisted\n" { + t.Errorf("workspace lost across scope change: %+v", r) + } + }) + + t.Run("kill stops running commands", func(t *testing.T) { + var wg sync.WaitGroup + var res ExecResponse + wg.Add(1) + go func() { + defer wg.Done() + res, _ = c.Exec(ctx, taskID, ExecRequest{Argv: []string{"sleep", "300"}, TimeoutMS: 600000}) + }() + time.Sleep(3 * time.Second) + start := time.Now() + if _, err := c.Kill(ctx, taskID); err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(30 * time.Second): + t.Fatal("exec still running 30s after Kill") + } + if res.ExitCode == 0 { + t.Errorf("killed exec exit code 0: %+v", res) + } + t.Logf("kill returned the exec in %s (exit %d)", time.Since(start), res.ExitCode) + if r := sh(t, `pgrep -u 10001 sleep || echo none`); !strings.Contains(r.Stdout, "none") { + t.Errorf("sleep survived Kill: %q", r.Stdout) + } + }) + + t.Run("runner restart recovers tasks", func(t *testing.T) { + before, _ := kubectl("get", "pod", "artex-w-"+h, "-o", "jsonpath={.metadata.uid}") + if out, err := kubectl("rollout", "restart", "deploy", "-l", "app.kubernetes.io/component=runner"); err != nil { + t.Fatal(out) + } + if out, err := kubectl("rollout", "status", "deploy", "-l", "app.kubernetes.io/component=runner", "--timeout=120s"); err != nil { + t.Fatal(out) + } + stopPF() + startPF() + var r ExecResponse + var err error + for i := 0; i < 30; i++ { + r, err = c.Exec(ctx, taskID, ExecRequest{Argv: []string{"cat", "sub/f.txt"}, TimeoutMS: 30000}) + if err == nil { + break + } + time.Sleep(2 * time.Second) + } + if err != nil || r.Stdout != "persisted\n" { + t.Fatalf("exec after runner restart: %+v %v", r, err) + } + after, _ := kubectl("get", "pod", "artex-w-"+h, "-o", "jsonpath={.metadata.uid}") + if before == "" || before != after { + t.Errorf("worker pod replaced across runner restart (%s -> %s): recovery did not adopt it", before, after) + } + }) + + t.Run("delete removes task objects", func(t *testing.T) { + if _, err := c.Delete(ctx, taskID); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(60 * time.Second) + for { + out, _ := kubectl("get", "pods,svc,networkpolicy", "-l", LabelTaskHash+"="+h, "-o", "name") + if out == "" || strings.Contains(out, "No resources") { + break + } + if time.Now().After(deadline) { + t.Fatalf("objects left after delete:\n%s", out) + } + time.Sleep(2 * time.Second) + } + }) +} + +func envDefault(k, def string) string { + if v := strings.TrimSpace(os.Getenv(k)); v != "" { + return v + } + return def +} + +func regexpMatch(pattern, s string) bool { + return regexp.MustCompile(pattern).MatchString(s) +} diff --git a/sandbox/kube_test.go b/sandbox/kube_test.go new file mode 100644 index 000000000..20af60f15 --- /dev/null +++ b/sandbox/kube_test.go @@ -0,0 +1,1115 @@ +package sandbox + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +// fakeKubeAPI is an in-memory stand-in for the parts of the Kubernetes API the +// backend uses: pods, services, networkpolicies (CRUD + label-selector list) and +// the pods/exec WebSocket. +type fakeKubeAPI struct { + t *testing.T + ns string + token string + + mu sync.Mutex + objs map[string]map[string]map[string]any // kind -> name -> object + ops []string // "create pods/artex-w-..." in order + execs [][]string // argv of every exec + // container of every exec, parallel to execs + execContainers []string + nextIP int + podMode map[string]string // pod name -> "ready" (default) | "pull-error" | "pending" + + // execFn answers an exec; default echoes argv to stdout with exit 0. + execFn func(pod string, argv []string) (stdout, stderr string, exit int) + // failPing makes pod list return 403. + failPing atomic.Bool +} + +func newFakeKubeAPI(t *testing.T) (*fakeKubeAPI, *httptest.Server) { + f := &fakeKubeAPI{ + t: t, + ns: "artex", + token: "test-sa-token", + objs: map[string]map[string]map[string]any{"pods": {}, "services": {}, "networkpolicies": {}}, + podMode: map[string]string{}, + nextIP: 10, + } + srv := httptest.NewServer(http.HandlerFunc(f.serve)) + t.Cleanup(srv.Close) + return f, srv +} + +var fakeKubePathRE = regexp.MustCompile(`^/(?:api/v1|apis/networking\.k8s\.io/v1)/namespaces/([^/]+)/(pods|services|networkpolicies)(?:/([^/]+))?(?:/(exec))?$`) + +func (f *fakeKubeAPI) serve(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer "+f.token { + http.Error(w, `{"reason":"Unauthorized"}`, http.StatusUnauthorized) + return + } + m := fakeKubePathRE.FindStringSubmatch(r.URL.Path) + if m == nil { + http.Error(w, "no route "+r.URL.Path, http.StatusNotFound) + return + } + ns, kind, name, sub := m[1], m[2], m[3], m[4] + if ns != f.ns { + http.Error(w, "forbidden namespace "+ns, http.StatusForbidden) + return + } + if sub == "exec" { + f.serveExec(w, r, name) + return + } + f.mu.Lock() + defer f.mu.Unlock() + store := f.objs[kind] + switch { + case r.Method == http.MethodGet && name == "": + if kind == "pods" && f.failPing.Load() { + http.Error(w, `{"reason":"Forbidden"}`, http.StatusForbidden) + return + } + sel := r.URL.Query().Get("labelSelector") + items := []any{} + for _, o := range store { + if matchSelector(o, sel) { + items = append(items, o) + } + } + writeJSON(w, map[string]any{"items": items}) + case r.Method == http.MethodGet: + o, ok := store[name] + if !ok { + http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound) + return + } + writeJSON(w, o) + case r.Method == http.MethodPost: + var o map[string]any + if err := json.NewDecoder(r.Body).Decode(&o); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + meta := o["metadata"].(map[string]any) + n := meta["name"].(string) + if !dnsLabelRE.MatchString(n) { + http.Error(w, "invalid name "+n, http.StatusUnprocessableEntity) + return + } + if _, exists := store[n]; exists { + http.Error(w, `{"reason":"AlreadyExists"}`, http.StatusConflict) + return + } + f.finalize(kind, n, o) + store[n] = o + f.ops = append(f.ops, "create "+kind+"/"+n) + writeJSON(w, o) + case r.Method == http.MethodPut: + var o map[string]any + if err := json.NewDecoder(r.Body).Decode(&o); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if _, exists := store[name]; !exists { + http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound) + return + } + store[name] = o + f.ops = append(f.ops, "update "+kind+"/"+name) + writeJSON(w, o) + case r.Method == http.MethodDelete: + if _, ok := store[name]; !ok { + http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound) + return + } + delete(store, name) + f.ops = append(f.ops, "delete "+kind+"/"+name) + writeJSON(w, map[string]any{"status": "Success"}) + default: + http.Error(w, "method", http.StatusMethodNotAllowed) + } +} + +// finalize fills in server-side fields (pod status, service ClusterIP). +func (f *fakeKubeAPI) finalize(kind, name string, o map[string]any) { + switch kind { + case "services": + f.nextIP++ + o["spec"].(map[string]any)["clusterIP"] = fmt.Sprintf("10.43.0.%d", f.nextIP) + case "pods": + switch f.podMode[name] { + case "pull-error": + o["status"] = map[string]any{"phase": "Pending", "containerStatuses": []any{map[string]any{ + "ready": false, "state": map[string]any{"waiting": map[string]any{"reason": "ImagePullBackOff", "message": "pull access denied"}}, + }}} + case "pending": + o["status"] = map[string]any{"phase": "Pending"} + default: + o["status"] = map[string]any{"phase": "Running", "containerStatuses": []any{map[string]any{"ready": true, "state": map[string]any{}}}} + } + } +} + +func (f *fakeKubeAPI) setPodPhase(name, phase string, ready bool) { + f.mu.Lock() + defer f.mu.Unlock() + if p := f.objs["pods"][name]; p != nil { + p["status"] = map[string]any{"phase": phase, "containerStatuses": []any{map[string]any{"ready": ready, "state": map[string]any{}}}} + } +} + +func (f *fakeKubeAPI) serveExec(w http.ResponseWriter, r *http.Request, pod string) { + f.mu.Lock() + _, ok := f.objs["pods"][pod] + f.mu.Unlock() + if !ok { + http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound) + return + } + q := r.URL.Query() + if c := q.Get("container"); c != kubeWorkerName && c != kubeProxyName { + http.Error(w, "unexpected container "+c, http.StatusBadRequest) + return + } + if q.Get("stdout") != "true" || q.Get("stderr") != "true" || q.Has("stdin") || q.Has("tty") { + http.Error(w, "unexpected exec query "+r.URL.RawQuery, http.StatusBadRequest) + return + } + argv := q["command"] + f.mu.Lock() + f.execs = append(f.execs, argv) + f.execContainers = append(f.execContainers, q.Get("container")) + fn := f.execFn + f.mu.Unlock() + up := websocket.Upgrader{Subprotocols: []string{"v5.channel.k8s.io", "v4.channel.k8s.io"}} + conn, err := up.Upgrade(w, r, nil) + if err != nil { + return + } + defer conn.Close() + if conn.Subprotocol() == "" { + f.t.Errorf("exec negotiated no channel subprotocol") + return + } + stdout, stderr, exit := strings.Join(argv, " "), "", 0 + if fn != nil { + stdout, stderr, exit = fn(pod, argv) + } + send := func(ch byte, data string) { + // Split large payloads into frames like the API server does. + for len(data) > 0 { + n := min(len(data), 32*1024) + _ = conn.WriteMessage(websocket.BinaryMessage, append([]byte{ch}, data[:n]...)) + data = data[n:] + } + } + send(1, stdout) + send(2, stderr) + var st map[string]any + switch { + case exit == 0: + st = map[string]any{"status": "Success"} + case exit < 0: + st = map[string]any{"status": "Failure", "reason": "InternalError", "message": "container not found"} + default: + st = map[string]any{"status": "Failure", "reason": "NonZeroExitCode", "message": "command terminated with non-zero exit code", + "details": map[string]any{"causes": []any{map[string]any{"reason": "ExitCode", "message": strconv.Itoa(exit)}}}} + } + raw, _ := json.Marshal(st) + _ = conn.WriteMessage(websocket.BinaryMessage, append([]byte{3}, raw...)) + _ = conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) +} + +var dnsLabelRE = regexp.MustCompile(`^[a-z]([-a-z0-9]{0,61}[a-z0-9])?$`) + +func matchSelector(o map[string]any, sel string) bool { + if sel == "" { + return true + } + labels, _ := o["metadata"].(map[string]any)["labels"].(map[string]any) + for _, term := range strings.Split(sel, ",") { + k, v, _ := strings.Cut(term, "=") + if labels[k] != v { + return false + } + } + return true +} + +func writeJSON(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(v) +} + +func (f *fakeKubeAPI) obj(kind, name string) map[string]any { + f.mu.Lock() + defer f.mu.Unlock() + return f.objs[kind][name] +} + +func (f *fakeKubeAPI) count(kind string) int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.objs[kind]) +} + +func (f *fakeKubeAPI) opsSnapshot() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.ops...) +} + +func (f *fakeKubeAPI) lastExec() []string { + f.mu.Lock() + defer f.mu.Unlock() + if len(f.execs) == 0 { + return nil + } + return f.execs[len(f.execs)-1] +} + +func newTestKubeBackend(t *testing.T, f *fakeKubeAPI, srv *httptest.Server) *KubernetesBackend { + t.Helper() + dir := t.TempDir() + tok := filepath.Join(dir, "token") + if err := os.WriteFile(tok, []byte(f.token+"\n"), 0o600); err != nil { + t.Fatal(err) + } + b, err := NewKubernetesBackend(KubeConfig{ + APIServer: srv.URL, + TokenPath: tok, + Namespace: f.ns, + DataClaim: "artex-data", + WorkerImage: "artex-worker:test", + ProxyImage: "artex-egress-proxy:test", + WorkspaceRoot: filepath.Join(dir, "tasks"), + AuditRoot: filepath.Join(dir, "audit"), + PodReadyTimeout: 3 * time.Second, + }) + if err != nil { + t.Fatalf("NewKubernetesBackend: %v", err) + } + return b +} + +// dig walks nested map/slice JSON values: dig(o, "spec", "containers", 0, "name"). +func dig(v any, path ...any) any { + for _, p := range path { + switch k := p.(type) { + case string: + m, ok := v.(map[string]any) + if !ok { + return nil + } + v = m[k] + case int: + s, ok := v.([]any) + if !ok || k >= len(s) { + return nil + } + v = s[k] + } + } + return v +} + +func envOf(container any) map[string]string { + out := map[string]string{} + for _, e := range dig(container, "env").([]any) { + out[e.(map[string]any)["name"].(string)] = e.(map[string]any)["value"].(string) + } + return out +} + +func execReq(argv ...string) ExecRequest { + req := ExecRequest{Argv: argv} + if err := ValidateExecRequest(&req); err != nil { + panic(err) + } + return req +} + +func TestKubeConfigFromEnv(t *testing.T) { + t.Setenv("ARTEX_KUBE_DATA_CLAIM", "data") + t.Setenv("ARTEX_KUBE_NAMESPACE", "ns1") + t.Setenv("ARTEX_KUBE_DNS_LABELS", "k8s-app=kube-dns,tier=dns") + t.Setenv("ARTEX_KUBE_PROXY_DENIED_CIDRS", "10.0.0.0/8, 192.168.1.7/16") + t.Setenv("ARTEX_KUBE_POD_READY_TIMEOUT", "45s") + t.Setenv("ARTEX_KUBE_IMAGE_PULL_POLICY", "Never") + t.Setenv("ARTEX_KUBE_RUNTIME_CLASS", "gvisor") + cfg, err := KubeConfigFromEnv() + if err != nil { + t.Fatal(err) + } + if cfg.DataClaim != "data" || cfg.Namespace != "ns1" || cfg.ImagePullPolicy != "Never" || cfg.RuntimeClassName != "gvisor" { + t.Fatalf("cfg = %+v", cfg) + } + if cfg.DNSPodLabels["tier"] != "dns" || cfg.DNSPodLabels["k8s-app"] != "kube-dns" { + t.Fatalf("dns labels = %v", cfg.DNSPodLabels) + } + if strings.Join(cfg.ProxyDeniedCIDRs, " ") != "10.0.0.0/8 192.168.0.0/16" { + t.Fatalf("denied CIDRs not masked: %v", cfg.ProxyDeniedCIDRs) + } + if cfg.PodReadyTimeout != 45*time.Second { + t.Fatalf("timeout = %v", cfg.PodReadyTimeout) + } + + for k, v := range map[string]string{ + "ARTEX_KUBE_PROXY_DENIED_CIDRS": "not-a-cidr", + "ARTEX_KUBE_DNS_LABELS": "novalue", + "ARTEX_KUBE_POD_READY_TIMEOUT": "-1s", + "ARTEX_KUBE_IMAGE_PULL_POLICY": "Sometimes", + } { + t.Run(k, func(t *testing.T) { + t.Setenv(k, v) + if _, err := KubeConfigFromEnv(); err == nil { + t.Fatalf("%s=%q accepted", k, v) + } + }) + } + t.Run("ipv6 denied cidr", func(t *testing.T) { + t.Setenv("ARTEX_KUBE_PROXY_DENIED_CIDRS", "fc00::/7") + if _, err := KubeConfigFromEnv(); err == nil { + t.Fatal("IPv6 prefix accepted inside the 0.0.0.0/0 ipBlock") + } + }) +} + +func TestNewKubernetesBackendValidation(t *testing.T) { + base := KubeConfig{APIServer: "http://127.0.0.1:1", Namespace: "ns", DataClaim: "c"} + if _, err := NewKubernetesBackend(base); err != nil { + t.Fatalf("valid config rejected: %v", err) + } + noClaim := base + noClaim.DataClaim = "" + if _, err := NewKubernetesBackend(noClaim); err == nil { + t.Fatal("missing data claim accepted") + } + for _, sp := range []string{"/abs", "../up", "a/../../b"} { + c := base + c.TasksSubPath = sp + if _, err := NewKubernetesBackend(c); err == nil { + t.Fatalf("sub path %q accepted", sp) + } + } + noAPI := base + noAPI.APIServer = "" + t.Setenv("KUBERNETES_SERVICE_HOST", "") + if _, err := NewKubernetesBackend(noAPI); err == nil { + t.Fatal("no API server and no in-cluster env accepted") + } + httpsNoCA := base + httpsNoCA.APIServer = "https://127.0.0.1:6443" + httpsNoCA.CAPath = filepath.Join(t.TempDir(), "missing.crt") + if _, err := NewKubernetesBackend(httpsNoCA); err == nil { + t.Fatal("https API server without a readable CA accepted") + } +} + +func TestKubeTaskNamesAreValidForAnyTaskID(t *testing.T) { + for _, id := range []string{"a", "Task_ABC.1-x", strings.Repeat("Z", 64), "0.-_"} { + if err := ValidateTaskID(id); err != nil { + continue + } + h := kubeTaskHash(id) + for _, n := range []string{"artex-w-" + h, "artex-p-" + h} { + if !dnsLabelRE.MatchString(n) { + t.Errorf("task %q -> name %q is not a DNS-1035 label", id, n) + } + } + } + if kubeTaskHash("a") == kubeTaskHash("A") { + t.Fatal("task hash is case-insensitive: distinct tasks would share pods") + } +} + +func TestKubeExecCreatesIsolatedTaskAndRunsCommand(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + taskID := "Task_1" + h := kubeTaskHash(taskID) + + req := execReq("sh", "-c", "echo hi; echo err >&2") + req.Env = map[string]string{"FOO": "a b; $(rm -rf /)", "BAR": "x=y"} + req.Workdir = "/workspace/sub" + req.ScopeDomains = []string{"example.com"} + req.ScopeCIDRs = []string{"203.0.113.0/24", "10.1.2.3"} + f.execFn = func(_ string, argv []string) (string, string, int) { return "hi\n", "err\n", 0 } + + res, err := b.Exec(ctx, taskID, req) + if err != nil { + t.Fatalf("Exec: %v", err) + } + if res.ExitCode != 0 || res.Stdout != "hi\n" || res.Stderr != "err\n" || res.TimedOut || res.Truncated { + t.Fatalf("result = %+v", res) + } + + // Ordering: both NetworkPolicies exist before any pod is created. + ops := f.opsSnapshot() + firstPod := -1 + policies := 0 + for i, op := range ops { + if strings.HasPrefix(op, "create pods/") && firstPod < 0 { + firstPod = i + } + if strings.HasPrefix(op, "create networkpolicies/") { + if firstPod >= 0 { + t.Fatalf("network policy created after a pod: %v", ops) + } + policies++ + } + } + if policies != 2 || firstPod < 0 { + t.Fatalf("ops = %v", ops) + } + + svc := f.obj("services", "artex-p-"+h) + clusterIP := dig(svc, "spec", "clusterIP").(string) + + // Exec argv: env(1) clears the environment, sets workdir, the worker base env and + // the request env, then artex-exec-wrap; every value is one argv element. + wantArgv := []string{"/usr/bin/env", "-i", "-C", "/workspace/sub"} + for _, kv := range workerBaseEnv(clusterIP) { + wantArgv = append(wantArgv, kv[0]+"="+kv[1]) + } + wantArgv = append(wantArgv, "BAR=x=y", "FOO=a b; $(rm -rf /)", + "/usr/local/bin/artex-exec-wrap", strconv.Itoa(DefaultTimeoutMS), "--", "sh", "-c", "echo hi; echo err >&2") + if got := f.lastExec(); strings.Join(got, "\x00") != strings.Join(wantArgv, "\x00") { + t.Fatalf("exec argv\n got %q\nwant %q", got, wantArgv) + } + // Before the first command, the network paths were probed in both pods. + f.mu.Lock() + probes := strings.Join(f.execContainers, ",") + firstProbe := strings.Join(f.execs[0], " ") + f.mu.Unlock() + if probes != "worker,egress-proxy,worker" || !strings.Contains(firstProbe, "/dev/tcp/"+clusterIP+"/3128") { + t.Fatalf("network probes = %s (%s)", probes, firstProbe) + } + if sel := dig(svc, "spec", "selector").(map[string]any); sel[LabelComponent] != ComponentProxy || sel[LabelTaskHash] != h { + t.Fatalf("service selector = %v", sel) + } + + // Worker pod hardening. + w := f.obj("pods", "artex-w-"+h) + if w == nil { + t.Fatal("worker pod missing") + } + spec := dig(w, "spec") + for k, want := range map[string]any{ + "automountServiceAccountToken": false, "enableServiceLinks": false, "hostNetwork": false, + "hostPID": false, "hostIPC": false, "dnsPolicy": "None", + } { + if got := dig(spec, k); got != want { + t.Errorf("worker spec.%s = %v, want %v", k, got, want) + } + } + if dig(spec, "securityContext", "runAsNonRoot") != true || dig(spec, "securityContext", "runAsUser") != float64(WorkerUID) || + dig(spec, "securityContext", "seccompProfile", "type") != "RuntimeDefault" { + t.Errorf("worker pod securityContext = %v", dig(spec, "securityContext")) + } + c := dig(spec, "containers", 0) + if dig(c, "securityContext", "readOnlyRootFilesystem") != true || dig(c, "securityContext", "allowPrivilegeEscalation") != false || + dig(c, "securityContext", "privileged") != false || dig(c, "securityContext", "capabilities", "drop", 0) != "ALL" { + t.Errorf("worker container securityContext = %v", dig(c, "securityContext")) + } + if dig(c, "image") != "artex-worker:test" || dig(c, "command", 0) != "/usr/local/bin/artex-exec-wrap" { + t.Errorf("worker image/command = %v %v", dig(c, "image"), dig(c, "command")) + } + if dig(c, "volumeMounts", 0, "subPath") != "tasks/"+taskID || dig(c, "volumeMounts", 0, "mountPath") != "/workspace" { + t.Errorf("worker workspace mount = %v", dig(c, "volumeMounts", 0)) + } + if dig(spec, "volumes", 0, "persistentVolumeClaim", "claimName") != "artex-data" { + t.Errorf("worker data volume = %v", dig(spec, "volumes", 0)) + } + if len(dig(c, "volumeMounts").([]any)) != 3 { + t.Errorf("worker has unexpected mounts: %v", dig(c, "volumeMounts")) + } + env := envOf(c) + if env["HTTP_PROXY"] != "http://"+clusterIP+":3128" || env["ALL_PROXY"] != "socks5h://"+clusterIP+":1080" { + t.Errorf("worker proxy env = %v (clusterIP %s)", env, clusterIP) + } + for k := range env { + if IsForbiddenEnvName(k) { + t.Errorf("worker env carries forbidden %s", k) + } + } + if dig(w, "metadata", "annotations", AnnotationTaskID) != taskID { + t.Errorf("worker annotations = %v", dig(w, "metadata", "annotations")) + } + + // Proxy pod: scope in env, audit sub path, same hardening. + p := f.obj("pods", "artex-p-"+h) + pc := dig(p, "spec", "containers", 0) + penv := envOf(pc) + if penv["ARTEX_SCOPE_DOMAINS"] != "example.com" || penv["ARTEX_SCOPE_CIDRS"] != "203.0.113.0/24,10.1.2.3" || penv["ARTEX_TASK_ID"] != taskID { + t.Errorf("proxy env = %v", penv) + } + if dig(pc, "volumeMounts", 0, "subPath") != "egress-audit/"+taskID || dig(pc, "volumeMounts", 0, "mountPath") != "/audit" { + t.Errorf("proxy audit mount = %v", dig(pc, "volumeMounts", 0)) + } + if dig(p, "spec", "automountServiceAccountToken") != false || dig(pc, "securityContext", "readOnlyRootFilesystem") != true { + t.Errorf("proxy pod not hardened") + } + + // Worker policy: egress only to own proxy on proxy ports, no ingress. + wp := f.obj("networkpolicies", "artex-w-"+h) + if dig(wp, "spec", "podSelector", "matchLabels", LabelComponent) != ComponentWorker || + dig(wp, "spec", "podSelector", "matchLabels", LabelTaskHash) != h { + t.Errorf("worker policy selector = %v", dig(wp, "spec", "podSelector")) + } + if n := len(dig(wp, "spec", "ingress").([]any)); n != 0 { + t.Errorf("worker policy allows ingress: %v", dig(wp, "spec", "ingress")) + } + eg := dig(wp, "spec", "egress").([]any) + if len(eg) != 1 || dig(eg[0], "to", 0, "podSelector", "matchLabels", LabelTaskHash) != h || + dig(eg[0], "to", 0, "podSelector", "matchLabels", LabelComponent) != ComponentProxy || len(dig(eg[0], "ports").([]any)) != 2 { + t.Errorf("worker policy egress = %v", eg) + } + + // Proxy policy: ingress only from own worker; egress DNS + public minus private + scope CIDRs. + pp := f.obj("networkpolicies", "artex-p-"+h) + if dig(pp, "spec", "ingress", 0, "from", 0, "podSelector", "matchLabels", LabelTaskHash) != h || + dig(pp, "spec", "ingress", 0, "from", 0, "podSelector", "matchLabels", LabelComponent) != ComponentWorker { + t.Errorf("proxy policy ingress = %v", dig(pp, "spec", "ingress")) + } + peg := dig(pp, "spec", "egress").([]any) + if dig(peg[0], "to", 0, "podSelector", "matchLabels", "k8s-app") != "kube-dns" { + t.Errorf("proxy DNS rule = %v", peg[0]) + } + except := dig(peg[1], "to", 0, "ipBlock", "except").([]any) + if dig(peg[1], "to", 0, "ipBlock", "cidr") != "0.0.0.0/0" || len(except) != len(DefaultProxyDeniedCIDRs) { + t.Errorf("proxy public rule = %v", peg[1]) + } + var scope []string + for _, blk := range dig(peg[2], "to").([]any) { + scope = append(scope, dig(blk, "ipBlock", "cidr").(string)) + } + if strings.Join(scope, ",") != "203.0.113.0/24,10.1.2.3/32" { + t.Errorf("proxy scope rule = %v", scope) + } + + // Per-task directories prepared for the mounts. + for _, d := range []string{filepath.Join(b.cfg.WorkspaceRoot, taskID), filepath.Join(b.cfg.AuditRoot, taskID)} { + if st, err := os.Stat(d); err != nil || !st.IsDir() { + t.Errorf("dir %s not prepared: %v", d, err) + } + } + if b.WorkerCount() != 1 { + t.Fatalf("WorkerCount = %d", b.WorkerCount()) + } +} + +func TestKubePinNodeAndWorkerLimits(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + b.cfg.PinNode = "k3d-artex-server-0" + b.cfg.WorkerCPULimit, b.cfg.WorkerMemoryLimit = "500m", "1Gi" + if _, err := b.Exec(context.Background(), "t1", execReq("true")); err != nil { + t.Fatal(err) + } + h := kubeTaskHash("t1") + for _, name := range []string{"artex-w-" + h, "artex-p-" + h} { + term := dig(f.obj("pods", name), "spec", "affinity", "nodeAffinity", "requiredDuringSchedulingIgnoredDuringExecution", "nodeSelectorTerms", 0, "matchFields", 0) + if dig(term, "key") != "metadata.name" || dig(term, "operator") != "In" || dig(term, "values", 0) != "k3d-artex-server-0" { + t.Errorf("%s node affinity = %v", name, term) + } + } + lim := dig(f.obj("pods", "artex-w-"+h), "spec", "containers", 0, "resources", "limits") + if dig(lim, "cpu") != "500m" || dig(lim, "memory") != "1Gi" { + t.Errorf("worker limits = %v", lim) + } + // Without PinNode there is no affinity at all. + f2, srv2 := newFakeKubeAPI(t) + b2 := newTestKubeBackend(t, f2, srv2) + if _, err := b2.Exec(context.Background(), "t1", execReq("true")); err != nil { + t.Fatal(err) + } + if a := dig(f2.obj("pods", "artex-w-"+h), "spec", "affinity"); a != nil { + t.Errorf("unpinned worker has affinity %v", a) + } +} + +func TestKubeExecReusesTaskAndReportsExitCodes(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + creates := len(f.opsSnapshot()) + + f.execFn = func(string, []string) (string, string, int) { return "", "boom", 3 } + res, err := b.Exec(ctx, "t1", execReq("false")) + if err != nil || res.ExitCode != 3 || res.Stderr != "boom" || res.TimedOut { + t.Fatalf("nonzero exit: res=%+v err=%v", res, err) + } + f.execFn = func(string, []string) (string, string, int) { return "", "timeout", 124 } + res, err = b.Exec(ctx, "t1", execReq("sleep", "999")) + if err != nil || res.ExitCode != 124 || !res.TimedOut { + t.Fatalf("timeout: res=%+v err=%v", res, err) + } + f.execFn = func(string, []string) (string, string, int) { return "", "", -1 } + if _, err := b.Exec(ctx, "t1", execReq("x")); err == nil { + t.Fatal("exec failure status (no exit code) not reported as error") + } + if got := len(f.opsSnapshot()); got != creates { + t.Fatalf("second exec mutated cluster: %v", f.opsSnapshot()[creates:]) + } +} + +func TestKubeExecTruncatesOutput(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + big := strings.Repeat("A", MaxOutputBytes+100*1024) + f.execFn = func(string, []string) (string, string, int) { return big, "small", 0 } + res, err := b.Exec(context.Background(), "t1", execReq("cat", "big")) + if err != nil { + t.Fatal(err) + } + if len(res.Stdout) != MaxOutputBytes || !res.Truncated || res.Stderr != "small" { + t.Fatalf("stdout=%d truncated=%v stderr=%q", len(res.Stdout), res.Truncated, res.Stderr) + } +} + +func TestKubeScopeChangeRecreatesOnlyProxy(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + h := kubeTaskHash("t1") + req := execReq("true") + req.ScopeDomains = []string{"a.example"} + if _, err := b.Exec(ctx, "t1", req); err != nil { + t.Fatal(err) + } + ip := dig(f.obj("services", "artex-p-"+h), "spec", "clusterIP") + mark := len(f.opsSnapshot()) + + req.ScopeDomains = []string{"b.example"} + req.ScopeCIDRs = []string{"198.51.100.0/24"} + if _, err := b.Exec(ctx, "t1", req); err != nil { + t.Fatal(err) + } + ops := strings.Join(f.opsSnapshot()[mark:], ",") + if !strings.Contains(ops, "delete pods/artex-p-"+h) || !strings.Contains(ops, "create pods/artex-p-"+h) { + t.Fatalf("proxy not recreated: %s", ops) + } + if strings.Contains(ops, "pods/artex-w-") || strings.Contains(ops, "services/") { + t.Fatalf("worker or service touched on scope change: %s", ops) + } + if !strings.Contains(ops, "update networkpolicies/artex-p-"+h) { + t.Fatalf("proxy policy not updated: %s", ops) + } + if penv := envOf(dig(f.obj("pods", "artex-p-"+h), "spec", "containers", 0)); penv["ARTEX_SCOPE_DOMAINS"] != "b.example" { + t.Fatalf("proxy scope env = %v", penv) + } + if dig(f.obj("services", "artex-p-"+h), "spec", "clusterIP") != ip { + t.Fatal("service ClusterIP changed: worker proxy env would be stale") + } + peg := dig(f.obj("networkpolicies", "artex-p-"+h), "spec", "egress").([]any) + if len(peg) != 3 || dig(peg[2], "to", 0, "ipBlock", "cidr") != "198.51.100.0/24" { + t.Fatalf("proxy policy scope = %v", peg) + } +} + +func TestKubeWaitsForNetworkPolicyToApply(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + var probes atomic.Int32 + f.execFn = func(_ string, argv []string) (string, string, int) { + if strings.Contains(strings.Join(argv, " "), "/dev/tcp/") { + // The CNI has not programmed the policy yet for the first few probes. + if probes.Add(1) <= 3 { + return "", "connection refused", 1 + } + } + return "ok", "", 0 + } + res, err := b.Exec(context.Background(), "t1", execReq("true")) + if err != nil || res.Stdout != "ok" { + t.Fatalf("exec = %+v, %v", res, err) + } + if probes.Load() != 4 { + t.Fatalf("worker probe attempts = %d, want 4", probes.Load()) + } +} + +func TestKubeNetworkNeverReadyFails(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + b.cfg.PodReadyTimeout = 1500 * time.Millisecond + f.execFn = func(_ string, argv []string) (string, string, int) { + if argv[0] == "getent" { + return "", "", 2 // DNS blocked: the proxy policy never applied + } + return "", "", 0 + } + _, err := b.Exec(context.Background(), "t1", execReq("true")) + if err == nil || !strings.Contains(err.Error(), "proxy to cluster DNS") { + t.Fatalf("err = %v", err) + } + if b.WorkerCount() != 0 { + t.Fatal("task registered although its network never came up") + } +} + +func TestKubeRecreatesDeadWorker(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + h := kubeTaskHash("t1") + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + f.setPodPhase("artex-w-"+h, "Failed", false) + mark := len(f.opsSnapshot()) + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + // Policies are re-asserted (repairing any tampering) before the pod returns; + // the proxy and the service are left alone. + ops := strings.Join(f.opsSnapshot()[mark:], ",") + want := "update networkpolicies/artex-w-" + h + ",update networkpolicies/artex-p-" + h + + ",delete pods/artex-w-" + h + ",create pods/artex-w-" + h + if ops != want { + t.Fatalf("ops\n got %s\nwant %s", ops, want) + } +} + +func TestKubeImagePullErrorFailsFast(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + b.cfg.PodReadyTimeout = 30 * time.Second + f.podMode["artex-w-"+kubeTaskHash("t1")] = "pull-error" + start := time.Now() + _, err := b.Exec(context.Background(), "t1", execReq("true")) + if err == nil || !strings.Contains(err.Error(), "ImagePullBackOff") { + t.Fatalf("err = %v", err) + } + if time.Since(start) > 5*time.Second { + t.Fatal("pull error waited for the full readiness timeout") + } + if b.WorkerCount() != 0 { + t.Fatal("failed task tracked as a worker") + } +} + +func TestKubePodReadyTimeout(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + b.cfg.PodReadyTimeout = 700 * time.Millisecond + f.podMode["artex-p-"+kubeTaskHash("t1")] = "pending" + if _, err := b.Exec(context.Background(), "t1", execReq("true")); err == nil || !strings.Contains(err.Error(), "not ready") { + t.Fatalf("err = %v", err) + } +} + +func TestKubeRefusesForeignService(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + h := kubeTaskHash("t1") + f.objs["services"]["artex-p-"+h] = map[string]any{ + "metadata": map[string]any{"name": "artex-p-" + h, "labels": map[string]any{"app": "evil"}}, + "spec": map[string]any{"clusterIP": "10.43.9.9"}, + } + _, err := b.Exec(context.Background(), "t1", execReq("true")) + if err == nil || !strings.Contains(err.Error(), "untrusted labels") { + t.Fatalf("err = %v", err) + } + if f.count("pods") != 0 { + t.Fatal("pods created behind a foreign service") + } +} + +func TestKubeKill(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + h := kubeTaskHash("t1") + if err := b.Kill(ctx, "t1"); !errors.Is(err, ErrNotFound) { + t.Fatalf("kill unknown = %v", err) + } + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + f.execFn = nil + if err := b.Kill(ctx, "t1"); err != nil { + t.Fatal(err) + } + if got := strings.Join(f.lastExec(), " "); got != "/usr/local/bin/artex-exec-wrap --kill-uid 10001" { + t.Fatalf("kill argv = %q", got) + } + if f.obj("pods", "artex-w-"+h) == nil { + t.Fatal("successful kill-uid removed the worker") + } + + // kill-uid fails: fall back to deleting the worker pod; next exec recreates it. + f.execFn = func(string, []string) (string, string, int) { return "", "survivors", 1 } + if err := b.Kill(ctx, "t1"); err != nil { + t.Fatal(err) + } + if f.obj("pods", "artex-w-"+h) != nil { + t.Fatal("worker pod survived a failed kill-uid") + } + if f.obj("pods", "artex-p-"+h) == nil { + t.Fatal("proxy pod removed by Kill") + } + f.execFn = nil + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + if f.obj("pods", "artex-w-"+h) == nil { + t.Fatal("worker not recreated after kill fallback") + } +} + +func TestKubeExecCancelKillsTask(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + if _, err := b.Exec(context.Background(), "t1", execReq("true")); err != nil { + t.Fatal(err) + } + release := make(chan struct{}) + var killed atomic.Bool + f.execFn = func(_ string, argv []string) (string, string, int) { + if len(argv) > 1 && argv[1] == "--kill-uid" { + killed.Store(true) + return "", "", 0 + } + <-release + return "", "", 0 + } + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + _, err := b.Exec(ctx, "t1", execReq("sleep", "100")) + close(release) + if err == nil { + t.Fatal("cancelled exec returned no error") + } + if !killed.Load() { + t.Fatal("cancelled exec did not kill the task's processes") + } +} + +func TestKubeDelete(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + if err := b.Delete(ctx, "t1"); !errors.Is(err, ErrNotFound) { + t.Fatalf("delete unknown = %v", err) + } + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + if _, err := b.Exec(ctx, "t2", execReq("true")); err != nil { + t.Fatal(err) + } + if err := b.Delete(ctx, "t1"); err != nil { + t.Fatal(err) + } + h1, h2 := kubeTaskHash("t1"), kubeTaskHash("t2") + for _, kind := range []string{"pods", "services", "networkpolicies"} { + for _, pfx := range []string{"artex-w-", "artex-p-"} { + if f.obj(kind, pfx+h1) != nil { + t.Errorf("%s/%s%s survived Delete", kind, pfx, h1) + } + } + } + if f.obj("pods", "artex-w-"+h2) == nil || f.obj("networkpolicies", "artex-w-"+h2) == nil { + t.Fatal("Delete removed another task's objects") + } + // Policies go after pods: no window where a pod exists without its policy. + ops := f.opsSnapshot() + lastPod, firstPol := -1, len(ops) + for i, op := range ops { + if strings.HasPrefix(op, "delete pods/") && strings.HasSuffix(op, h1) { + lastPod = i + } + if strings.HasPrefix(op, "delete networkpolicies/") && i < firstPol { + firstPol = i + } + } + if lastPod > firstPol { + t.Fatalf("policy deleted before pod: %v", ops) + } + if _, err := os.Stat(filepath.Join(b.cfg.WorkspaceRoot, "t1")); err != nil { + t.Fatalf("workspace removed by Delete: %v", err) + } + if b.WorkerCount() != 1 { + t.Fatalf("WorkerCount = %d", b.WorkerCount()) + } +} + +func TestKubeRecoverAdoptsOnlyManagedPods(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + if _, err := b.Exec(ctx, "good", execReq("true")); err != nil { + t.Fatal(err) + } + // A pod with runner labels whose annotation does not hash to its label, a pod with + // an invalid task id, and an unlabelled pod: none may be adopted. + f.objs["pods"]["artex-w-forged"] = map[string]any{"metadata": map[string]any{"name": "artex-w-forged", + "labels": map[string]any{LabelManagedBy: ManagedByRunner, LabelComponent: ComponentWorker, LabelTaskHash: "0000000000000000"}, + "annotations": map[string]any{AnnotationTaskID: "victim"}}} + f.objs["pods"]["artex-w-bad"] = map[string]any{"metadata": map[string]any{"name": "artex-w-bad", + "labels": map[string]any{LabelManagedBy: ManagedByRunner, LabelComponent: ComponentWorker, LabelTaskHash: kubeTaskHash("../x")}, + "annotations": map[string]any{AnnotationTaskID: "../x"}}} + f.objs["pods"]["other"] = map[string]any{"metadata": map[string]any{"name": "other", "labels": map[string]any{"app": "x"}}} + + fresh := newTestKubeBackend(t, f, srv) + n, err := fresh.Recover(ctx) + if err != nil || n != 1 { + t.Fatalf("Recover = %d, %v", n, err) + } + kt := fresh.tasks["good"] + h := kubeTaskHash("good") + if kt == nil || kt.workerPod != "artex-w-"+h || kt.proxyPod != "artex-p-"+h || kt.proxyIP == "" || kt.scopeHash == "" { + t.Fatalf("recovered task = %+v", kt) + } + // After recovery the same scope needs no cluster changes, and Kill/Delete work. + mark := len(f.opsSnapshot()) + if _, err := fresh.Exec(ctx, "good", execReq("true")); err != nil { + t.Fatal(err) + } + if ops := f.opsSnapshot()[mark:]; len(ops) != 0 { + t.Fatalf("exec after recover mutated cluster: %v", ops) + } + if err := fresh.Delete(ctx, "good"); err != nil { + t.Fatal(err) + } +} + +func TestKubeConcurrentExecSameTaskCreatesOnce(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + var wg sync.WaitGroup + errs := make(chan error, 8) + for range 8 { + wg.Add(1) + go func() { + defer wg.Done() + if _, err := b.Exec(context.Background(), "t1", execReq("true")); err != nil { + errs <- err + } + }() + } + wg.Wait() + close(errs) + for err := range errs { + t.Fatal(err) + } + creates := 0 + for _, op := range f.opsSnapshot() { + if strings.HasPrefix(op, "create pods/") || strings.HasPrefix(op, "delete pods/") { + creates++ + } + } + if creates != 2 { + t.Fatalf("pod create/delete ops = %d: %v", creates, f.opsSnapshot()) + } +} + +func TestKubePingAndRunnerHealth(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + if err := b.Ping(context.Background()); err != nil { + t.Fatalf("ping: %v", err) + } + f.failPing.Store(true) + if err := b.Ping(context.Background()); !errors.Is(err, ErrDockerUnavailable) { + t.Fatalf("ping with RBAC denied = %v, want ErrDockerUnavailable", err) + } + + rs, err := NewRunnerServer("tok", "v", b) + if err != nil { + t.Fatal(err) + } + h := httptest.NewServer(rs.Handler()) + defer h.Close() + get := func() int { + req, _ := http.NewRequest(http.MethodGet, h.URL+"/v1/health", nil) + req.Header.Set("Authorization", "Bearer tok") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + _, _ = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + return resp.StatusCode + } + if code := get(); code != http.StatusConflict { + t.Fatalf("health with API denied = %d", code) + } + f.failPing.Store(false) + if code := get(); code != http.StatusOK { + t.Fatalf("health = %d", code) + } +} + +func TestKubeRunnerHTTPEndToEnd(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + rs, _ := NewRunnerServer("tok", "v", b) + h := httptest.NewServer(rs.Handler()) + defer h.Close() + c := NewClient(h.URL, "tok") + ctx := context.Background() + f.execFn = func(_ string, argv []string) (string, string, int) { return "out:" + argv[len(argv)-1], "", 0 } + res, err := c.Exec(ctx, "Task.HTTP", ExecRequest{Argv: []string{"echo", "x"}}) + if err != nil || res.Stdout != "out:x" { + t.Fatalf("exec via client = %+v, %v", res, err) + } + if _, err := c.Exec(ctx, "Task.HTTP", ExecRequest{Argv: []string{"x"}, Workdir: "/etc"}); !errors.Is(err, ErrBadRequest) { + t.Fatalf("workdir escape = %v", err) + } + if _, err := c.Exec(ctx, "Task.HTTP", ExecRequest{Argv: []string{"x"}, Env: map[string]string{"AWS_SECRET": "x"}}); !errors.Is(err, ErrBadRequest) { + t.Fatalf("forbidden env = %v", err) + } + if _, err := c.Kill(ctx, "Task.HTTP"); err != nil { + t.Fatal(err) + } + if _, err := c.Delete(ctx, "Task.HTTP"); err != nil { + t.Fatal(err) + } + if _, err := c.Delete(ctx, "Task.HTTP"); !errors.Is(err, ErrNotFound) { + t.Fatalf("second delete = %v", err) + } +} + +func TestKubeAPIUnauthorizedIsUnavailable(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + if err := os.WriteFile(b.cfg.TokenPath, []byte("wrong"), 0o600); err != nil { + t.Fatal(err) + } + if err := b.Ping(context.Background()); !IsUnavailable(err) { + t.Fatalf("ping with bad token = %v", err) + } + // Token is re-read per request: rotating it back restores access. + if err := os.WriteFile(b.cfg.TokenPath, []byte(f.token), 0o600); err != nil { + t.Fatal(err) + } + if err := b.Ping(context.Background()); err != nil { + t.Fatalf("ping after token rotation: %v", err) + } +} diff --git a/sandbox/types.go b/sandbox/types.go index 9995e26d1..4cee149a9 100644 --- a/sandbox/types.go +++ b/sandbox/types.go @@ -21,6 +21,10 @@ const ( EnvAuditRoot = "ARTEX_AUDIT_ROOT" EnvTaskNetPrefix = "ARTEX_TASK_NET_PREFIX" EnvEgressNet = "ARTEX_EGRESS_NET" + EnvRunnerBackend = "ARTEX_RUNNER_BACKEND" + + BackendDocker = "docker" + BackendKubernetes = "kubernetes" DefaultRunnerURL = "http://artex-runner:8789" DefaultRunnerAddr = ":8789" From f8d6a2b2ec7fb03ea031a8af256c9f0ac15af83a Mon Sep 17 00:00:00 2001 From: Marco Azarmaneche <306425250+thecorporatetractor@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:36:21 +0200 Subject: [PATCH 2/6] feat(deploy): Helm chart with the Kubernetes sandbox deploy/helm/artex deploys the panel, PostgreSQL and artex-runner with a namespace-scoped Role, default-deny NetworkPolicies and a values schema. A volume-permissions init container restores root ownership of /app/data and /app/keys, fixing the isolation self-test failure on world-writable volumes (#620). scripts/k3d-e2e.sh and the kubernetes CI job test it live on k3d. --- .github/workflows/ci.yml | 50 +- CHANGELOG.md | 1 + INSTALL.md | 4 + deploy/helm/artex/Chart.yaml | 14 + deploy/helm/artex/README.md | 143 +++++ deploy/helm/artex/templates/NOTES.txt | 26 + deploy/helm/artex/templates/_helpers.tpl | 74 +++ deploy/helm/artex/templates/ingress.yaml | 31 + .../helm/artex/templates/networkpolicy.yaml | 87 +++ deploy/helm/artex/templates/panel.yaml | 217 +++++++ deploy/helm/artex/templates/postgres.yaml | 108 ++++ deploy/helm/artex/templates/pvc.yaml | 37 ++ deploy/helm/artex/templates/runner.yaml | 205 +++++++ deploy/helm/artex/templates/secret.yaml | 28 + .../artex/templates/tests/test-panel.yaml | 38 ++ deploy/helm/artex/values.schema.json | 73 +++ deploy/helm/artex/values.yaml | 154 +++++ sandbox/helmchart_test.go | 568 ++++++++++++++++++ scripts/k3d-e2e.sh | 103 ++++ 19 files changed, 1960 insertions(+), 1 deletion(-) create mode 100644 deploy/helm/artex/Chart.yaml create mode 100644 deploy/helm/artex/README.md create mode 100644 deploy/helm/artex/templates/NOTES.txt create mode 100644 deploy/helm/artex/templates/_helpers.tpl create mode 100644 deploy/helm/artex/templates/ingress.yaml create mode 100644 deploy/helm/artex/templates/networkpolicy.yaml create mode 100644 deploy/helm/artex/templates/panel.yaml create mode 100644 deploy/helm/artex/templates/postgres.yaml create mode 100644 deploy/helm/artex/templates/pvc.yaml create mode 100644 deploy/helm/artex/templates/runner.yaml create mode 100644 deploy/helm/artex/templates/secret.yaml create mode 100644 deploy/helm/artex/templates/tests/test-panel.yaml create mode 100644 deploy/helm/artex/values.schema.json create mode 100644 deploy/helm/artex/values.yaml create mode 100644 sandbox/helmchart_test.go create mode 100755 scripts/k3d-e2e.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5aaf7a9dc..0012a95e6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,7 @@ jobs: web: ${{ steps.filter.outputs.web }} python: ${{ steps.filter.outputs.python }} shell: ${{ steps.filter.outputs.shell }} + kubernetes: ${{ steps.filter.outputs.kubernetes }} steps: - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 id: filter @@ -40,6 +41,19 @@ jobs: - '**/*.py' - 'scripts/benchmark/**' - '.github/**' + kubernetes: + - 'sandbox/**' + - 'deploy/**' + - 'cmd/artex-runner/**' + - 'cmd/artex-exec-wrap/**' + - 'cmd/artex-egress-proxy/**' + - 'Dockerfile.runner' + - 'Dockerfile.worker' + - 'Dockerfile.egress-proxy' + - 'scripts/k3d-e2e.sh' + - 'go.mod' + - 'go.sum' + - '.github/workflows/ci.yml' # Added files too: a new top-level directory must appear in the bot summary. shell: - '**/*.sh' @@ -188,7 +202,7 @@ jobs: # shellcheck is preinstalled on the ubuntu runners. -S warning: the scripts # currently have only info-level notes (intentional A && B || C chains in # update.sh, an unquoted glob in backup.sh's prune), so fail on warnings. - - run: shellcheck -S warning install.sh update.sh start.sh scripts/backup.sh scripts/verify.sh reset-password.sh scripts/extract-changelog-section.sh scripts/test-extract-changelog-section.sh .github/scripts/bot.sh scripts/test-bot-context.sh scripts/test-start-sh.sh + - run: shellcheck -S warning install.sh update.sh start.sh scripts/backup.sh scripts/verify.sh reset-password.sh scripts/extract-changelog-section.sh scripts/test-extract-changelog-section.sh .github/scripts/bot.sh scripts/test-bot-context.sh scripts/test-start-sh.sh scripts/k3d-e2e.sh - run: bash scripts/test-extract-changelog-section.sh # start.sh is the Docker ENTRYPOINT and runs under dash there, as /bin/sh does here. - run: bash scripts/test-start-sh.sh @@ -197,6 +211,40 @@ jobs: # scripts/benchmark/ exist. - run: bash scripts/test-bot-context.sh + # Live test of the Kubernetes sandbox backend and the Helm chart on k3d: the runner, + # worker and egress-proxy images are built from this checkout, the chart is installed + # runner-only (the panel image is not needed), and TestKubeSandboxE2E checks pod + # hardening, NetworkPolicy isolation, the egress proxy, kill, recovery and cleanup. + kubernetes: + needs: changes + if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.result != 'success' || needs.changes.outputs.kubernetes == 'true') }} + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + K3D_VERSION: v5.9.0 + # Pinned here, not taken from the release's own checksums file (see the + # Dockerfile tools stage for why). + K3D_SHA256: 06d8f25bc3a971c4eb29e0ff08429b180402db0f4dec838c9eac427e296800a0 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 + with: + go-version-file: go.mod + - name: install k3d + run: | + curl -fsSL -o /tmp/k3d "https://github.com/k3d-io/k3d/releases/download/${K3D_VERSION}/k3d-linux-amd64" + echo "${K3D_SHA256} /tmp/k3d" | sha256sum -c - + sudo install -m 0755 /tmp/k3d /usr/local/bin/k3d + k3d version + helm version --short + - name: helm lint + run: helm lint --strict deploy/helm/artex + - name: k3d sandbox e2e + env: + RUNNER_ONLY: "1" + ARTEX_E2E_INTERNET: "1" + run: bash scripts/k3d-e2e.sh + web: needs: changes if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.result != 'success' || needs.changes.outputs.web == 'true') }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 47d865941..14b467fbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to this project are documented in this file. The format is b ### Added - **Kubernetes sandbox backend for `artex-runner`.** With `ARTEX_RUNNER_BACKEND=kubernetes` each task runs in a worker pod behind its own egress-proxy pod, created through the Kubernetes API with no container runtime socket. The worker runs as uid/gid 10001 with `runAsNonRoot`, a read-only root filesystem, all capabilities dropped, `seccomp: RuntimeDefault`, no service-account token and no service links, and mounts only its task directory. Per-task NetworkPolicies are created before the pods and deleted after them: the worker can reach only its own proxy, and the proxy only cluster DNS, public addresses and the task's scope CIDRs. The runner waits until the policies are in effect before the first command, runs commands through `pods/exec`, and re-adopts task pods after a restart. +- **Helm chart for Kubernetes.** `deploy/helm/artex` deploys the panel, PostgreSQL and `artex-runner` with the Kubernetes sandbox backend, a namespace-scoped Role, NetworkPolicies and a values schema. A chart-level default-deny covers every runner-managed pod, so a missing per-task policy fails closed. The `volume-permissions` init container fixes the `Bash can create files in /app/data` self-test failure on world-writable volumes (#620). `scripts/k3d-e2e.sh` and the new `kubernetes` CI job test the chart live on k3d. ### Security diff --git a/INSTALL.md b/INSTALL.md index ff99d47e6..521f941c4 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -109,6 +109,10 @@ not the console afterwards. - Prebuilt GHCR images: the image is published from the next tagged release. Until then, `docker-compose.ghcr.yml` and `docker pull ghcr.io/baarai/artex` return `denied`; use the checkout build above. +- Kubernetes: the Helm chart in [`deploy/helm/artex`](deploy/helm/artex/README.md) runs the panel, + PostgreSQL and the sandbox runner with its Kubernetes backend: every agent command runs in a + per-task pod, with no Docker socket. It needs a CNI that enforces NetworkPolicy. + `scripts/k3d-e2e.sh` installs and tests it on a local k3d cluster. ## Troubleshooting diff --git a/deploy/helm/artex/Chart.yaml b/deploy/helm/artex/Chart.yaml new file mode 100644 index 000000000..5ba9ab412 --- /dev/null +++ b/deploy/helm/artex/Chart.yaml @@ -0,0 +1,14 @@ +apiVersion: v2 +name: artex +description: ARTEX autonomous pentest platform with the per-task Kubernetes sandbox (no Docker socket). +type: application +version: 0.1.0 +appVersion: "0.7.1" +kubeVersion: ">=1.25.0-0" +home: https://github.com/BaaRai/ARTEX +sources: + - https://github.com/BaaRai/ARTEX +keywords: + - pentest + - security + - sandbox diff --git a/deploy/helm/artex/README.md b/deploy/helm/artex/README.md new file mode 100644 index 000000000..56b18e9fe --- /dev/null +++ b/deploy/helm/artex/README.md @@ -0,0 +1,143 @@ +# ARTEX Helm chart + +Deploys ARTEX on Kubernetes: the panel (web UI, API, agent engine), PostgreSQL, and +`artex-runner` with the **Kubernetes sandbox backend**. Every agent command runs in +a per-task worker pod behind a per-task egress-proxy pod. The runner creates them +through the Kubernetes API. No Docker socket is mounted anywhere. + +## Requirements + +- Kubernetes 1.25 or later. +- **A CNI that enforces NetworkPolicy**, such as k3s/k3d (embedded kube-router), + Calico, Cilium or Antrea. Task isolation depends on it: + without enforcement a worker can reach the panel, the database and the internet + directly. The runner refuses to run a command until it has observed the per-task + policies in effect (see [Network readiness](#network-readiness)). +- A StorageClass for the data volume. See [Storage](#storage). +- A runner image that includes the Kubernetes backend: ARTEX after 0.7.1, or the + images built from this repository. + +## Quick start + +```sh +helm install artex deploy/helm/artex -n artex --create-namespace \ + --set-file secrets.anthropicApiKey=./anthropic.key + +kubectl -n artex port-forward svc/artex-panel 8787:8787 +kubectl -n artex logs deploy/artex-panel -c artex | grep "Setup token" # first start only +``` + +Open http://127.0.0.1:8787/setup and set the admin password with the setup token. + +To try it on a local k3d cluster with images built from this checkout, run +`scripts/k3d-e2e.sh`. It creates the cluster, builds and imports the four images, +installs the chart, runs `helm test` and the live sandbox test suite, and deletes +the cluster afterwards (`KEEP=1` keeps it). + +## What gets deployed + +| Object | Purpose | +|---|---| +| `Deployment/-panel` | ARTEX panel. Starts as root and drops every agent process to uid/gid 10001 itself. Its startup self-test refuses to run if that isolation fails. Capabilities: `CHOWN DAC_OVERRIDE FOWNER SETUID SETGID KILL` only, `allowPrivilegeEscalation: false`, no service-account token. | +| `Deployment/-runner` | `artex-runner` with `ARTEX_RUNNER_BACKEND=kubernetes`. Root only for `CAP_CHOWN` (per-task directories are handed to uid 10001), read-only root filesystem. | +| `Role/-runner` | Namespace-scoped: pods (get/list/create/delete), pods/exec, services, and networkpolicies. No secrets, no cluster-wide access. | +| `ServiceAccount/-task` | Identity of task pods. Its token is never mounted. | +| `StatefulSet/-postgres` | Bundled PostgreSQL 16 with SCRAM auth (`postgres.enabled=false` for an external database). | +| `NetworkPolicy` × 4 | Default-deny for every runner-managed pod. Only the panel may reach the runner and PostgreSQL. Panel ingress on 8787. | +| `Secret/-secrets` | Runner token and database password (generated once and kept across upgrades), plus LLM keys. | +| PVCs | `data` (shared: panel, runner, task pods) and `keys` (panel only). Both have `helm.sh/resource-policy: keep`. | + +### Per task (created by the runner) + +| Object | Spec | +|---|---| +| `NetworkPolicy/artex-w-` | Worker: no ingress. Egress only to its own proxy on 3128/1080. | +| `NetworkPolicy/artex-p-` | Proxy: ingress only from its own worker. Egress to cluster DNS, `0.0.0.0/0` minus RFC1918, CGNAT, loopback, link-local, metadata and multicast (`sandbox.proxyDeniedCIDRs`), plus the task's scope CIDRs. | +| `Service/artex-p-` | Stable ClusterIP for the proxy. The worker uses the IP, never DNS. | +| `Pod/artex-p-` | `artex-egress-proxy`: the task's domain/CIDR allowlist, with an audit log at `egress-audit//egress.jsonl` on the data volume. | +| `Pod/artex-w-` | `artex-worker`: uid/gid 10001, `runAsNonRoot`, read-only root filesystem, all capabilities dropped, no privilege escalation, `seccomp: RuntimeDefault`, no service-account token, no service links, `dnsPolicy: None`. Mounts only `tasks/` at `/workspace` plus in-memory `/tmp` and `$HOME`. Limits: 2 CPU, 2Gi memory, 1Gi ephemeral storage (configurable). | + +Policies are created **before** pods and deleted **after** them. `` is the +first 16 hex characters of the SHA-256 of the task ID: task IDs may contain +characters Kubernetes names reject. The real ID is in the `artex.task` annotation. + +Commands run through `pods/exec` as +`env -i -C artex-exec-wrap -- `. +That gives each command a clean environment, its own process group, and a +SIGTERM → 5 s → SIGKILL timeout. Kill scans `/proc` for uid 10001. If that scan +fails, the worker pod is deleted and the workspace survives. + +## Storage + +The data volume is shared. The panel mounts all of it, the runner mounts `tasks/` +and `egress-audit/`, and task pods mount their own sub-directories. + +- `persistence.data.accessMode: ReadWriteOnce` (default) works with any block or + local-path storage. The panel is scheduled on the runner's node, and the runner + pins every task pod to that node (`nodeAffinity` on `metadata.name`). Use it for + single-node clusters and k3d. +- `ReadWriteMany` (NFS, CephFS, Longhorn RWX, EFS, Azure Files, ...) lets task pods + schedule anywhere. + +`ReadWriteOncePod` is rejected: several pods must mount the volume. + +## Configuration + +| Value | Default | | +|---|---|---| +| `images.*.repository` / `tag` | `ghcr.io/baarai/artex*` / appVersion | Four images: `artex`, `runner`, `worker`, `egressProxy`. | +| `images.pullPolicy` | `IfNotPresent` | `Never` for side-loaded images. The PostgreSQL image has its own `postgres.pullPolicy`. | +| `secrets.existingSecret` | `""` | Use your own Secret with keys `ARTEX_RUNNER_TOKEN`, `POSTGRES_PASSWORD`, and optionally `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `ARTEX_SECRET_KEY`. | +| `secrets.anthropicApiKey` / `openaiApiKey` | `""` | Prefer `--set-file` or `existingSecret` over putting keys on the command line. | +| `panel.env` | `{}` | Plain settings (`ARTEX_LLM_MODEL`, ...). The schema rejects names ending in `_KEY`, `_TOKEN`, `_PASSWORD` or `_SECRET`. | +| `sandbox.mode` | `required` | `off` runs agents inside the panel container. Not recommended. | +| `sandbox.runtimeClassName` | `""` | Run task pods under gVisor or Kata for kernel isolation. | +| `sandbox.worker.cpuLimit` / `memoryLimit` | `2` / `2Gi` | | +| `sandbox.podReadyTimeout` | `2m` | Image pull, scheduling and policy programming must finish within it. | +| `sandbox.proxyDeniedCIDRs` | built-in | IPv4 only (it sits inside the `0.0.0.0/0` ipBlock). | +| `sandbox.dns.namespace` / `podLabels` | `kube-system` / `k8s-app: kube-dns` | Cluster DNS the proxy may query. | +| `persistence.data.accessMode` | `ReadWriteOnce` | See [Storage](#storage). | +| `postgres.enabled` | `true` | `false` plus `postgres.external.*` for a managed database. | +| `networkPolicy.enabled` | `true` | Turning it off removes the sandbox's network isolation. | +| `networkPolicy.panelIngressFrom` | `[]` (any) | NetworkPolicy peers allowed to reach the UI, for example your ingress controller. | +| `ingress.*` | disabled | | + +`values.schema.json` validates the values. Invalid modes, pull policies, access +modes, replica counts above 1, and IPv6 deny ranges fail at install time. + +## Network readiness + +A pod becomes Ready before the CNI has programmed NetworkPolicy for its new IP. +On k3s this takes a few seconds. After it creates or replaces a task's pods, the +runner probes two paths before it runs a command: + +- worker → proxy (TCP to the proxy ClusterIP); +- proxy → cluster DNS (`getent hosts kubernetes.default.svc`). + +If either path stays closed for `sandbox.podReadyTimeout`, the exec fails with +`network path ... not open (network policy not applied? ...)`. That usually means +the CNI does not enforce NetworkPolicy the way the chart expects, or the DNS pods +do not match `sandbox.dns.*`. + +## Troubleshooting + +- **`agent isolation self-test failed: Bash can create files in /app/data`** + (issue #620). The volume root was created world-writable, as local-path and many + other provisioners do. The chart's `volume-permissions` init container resets + `/app/data` to `root:root 0755` and `/app/keys` to `0700` before the panel starts. + The panel itself must run as root with the capabilities above. With + `runAsNonRoot`, or with `fsGroup` set on the panel, the self-test fails by design. +- **Runner health returns 409.** The runner cannot list pods. Check the Role + binding and `kubectl -n logs deploy/-runner`. +- **Task pods stay Pending.** With `ReadWriteOnce`, the node the runner runs on + needs capacity for the task pods. + +## Limitations + +- One panel and one runner (single-writer data, in-memory task state in the + runner, which re-adopts existing task pods by label after a restart). +- There is no per-pod PID limit in the pod API. Set `--pod-max-pids` on the kubelet + to bound fork bombs, as the Docker backend's `PidsLimit` does. +- The opt-in DNS egress guard (`docker-compose.egress.yml`) has no Kubernetes + equivalent. Agent egress is governed by the per-task proxies and their + NetworkPolicies. diff --git a/deploy/helm/artex/templates/NOTES.txt b/deploy/helm/artex/templates/NOTES.txt new file mode 100644 index 000000000..25ae59b9c --- /dev/null +++ b/deploy/helm/artex/templates/NOTES.txt @@ -0,0 +1,26 @@ +ARTEX {{ .Chart.AppVersion }} is deployed in namespace {{ .Release.Namespace }}. + +1. Open the console: + + kubectl -n {{ .Release.Namespace }} port-forward svc/{{ include "artex.fullname" . }}-panel 8787:{{ .Values.panel.service.port }} + then browse to http://127.0.0.1:8787 + +2. First start only: the one-time setup token for the /setup page is printed on the + panel's stderr: + + kubectl -n {{ .Release.Namespace }} logs deploy/{{ include "artex.fullname" . }}-panel | grep "Setup token" + +{{- if eq .Values.sandbox.mode "required" }} + +3. Agent commands run in per-task pods created by the runner: + + kubectl -n {{ .Release.Namespace }} get pods -l artex.managed_by=artex-runner +{{- if not .Values.networkPolicy.enabled }} + +WARNING: networkPolicy.enabled=false. Task pods are NOT network-isolated: a worker can +reach the panel, the database and the internet directly, bypassing the egress proxy. +{{- end }} +{{- else }} + +WARNING: sandbox.mode=off. Agent commands run inside the panel container. +{{- end }} diff --git a/deploy/helm/artex/templates/_helpers.tpl b/deploy/helm/artex/templates/_helpers.tpl new file mode 100644 index 000000000..a15a412dd --- /dev/null +++ b/deploy/helm/artex/templates/_helpers.tpl @@ -0,0 +1,74 @@ +{{/* Chart name, truncated to fit Kubernetes name limits. */}} +{{- define "artex.name" -}} +{{- .Chart.Name | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* Release-scoped base name for every object. */}} +{{- define "artex.fullname" -}} +{{- if contains .Chart.Name .Release.Name -}} +{{- .Release.Name | trunc 40 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 40 | trimSuffix "-" -}} +{{- end -}} +{{- end -}} + +{{- define "artex.labels" -}} +helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" }} +app.kubernetes.io/name: {{ include "artex.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end -}} + +{{/* Selector labels for one component: include "artex.selector" (list . "panel") */}} +{{- define "artex.selector" -}} +{{- $root := index . 0 -}} +app.kubernetes.io/name: {{ include "artex.name" $root }} +app.kubernetes.io/instance: {{ $root.Release.Name }} +app.kubernetes.io/component: {{ index . 1 }} +{{- end -}} + +{{- define "artex.secretName" -}} +{{- default (printf "%s-secrets" (include "artex.fullname" .)) .Values.secrets.existingSecret -}} +{{- end -}} + +{{- define "artex.dataClaim" -}} +{{- default (printf "%s-data" (include "artex.fullname" .)) .Values.persistence.data.existingClaim -}} +{{- end -}} + +{{- define "artex.keysClaim" -}} +{{- default (printf "%s-keys" (include "artex.fullname" .)) .Values.persistence.keys.existingClaim -}} +{{- end -}} + +{{- define "artex.runnerURL" -}} +{{- printf "http://%s-runner:%d" (include "artex.fullname" .) (int .Values.runner.port) -}} +{{- end -}} + +{{/* Image reference: include "artex.image" (list . .Values.images.runner) */}} +{{- define "artex.image" -}} +{{- $root := index . 0 -}} +{{- $img := index . 1 -}} +{{- printf "%s:%s" $img.repository (default $root.Chart.AppVersion $img.tag) -}} +{{- end -}} + +{{- define "artex.pgHost" -}} +{{- if .Values.postgres.enabled -}} +{{- printf "%s-postgres" (include "artex.fullname" .) -}} +{{- else -}} +{{- required "postgres.external.host is required when postgres.enabled=false" .Values.postgres.external.host -}} +{{- end -}} +{{- end -}} + +{{/* True when the data volume is ReadWriteOnce and all mounting pods must share a node. */}} +{{- define "artex.pinToNode" -}} +{{- if eq .Values.persistence.data.accessMode "ReadWriteOnce" -}}true{{- end -}} +{{- end -}} + +{{- define "artex.pullSecrets" -}} +{{- with .Values.images.pullSecrets }} +imagePullSecrets: +{{- range . }} + - name: {{ . }} +{{- end }} +{{- end }} +{{- end -}} diff --git a/deploy/helm/artex/templates/ingress.yaml b/deploy/helm/artex/templates/ingress.yaml new file mode 100644 index 000000000..2f2e42691 --- /dev/null +++ b/deploy/helm/artex/templates/ingress.yaml @@ -0,0 +1,31 @@ +{{- if .Values.ingress.enabled }} +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ include "artex.fullname" . }} + labels: + {{- include "artex.labels" . | nindent 4 }} + {{- with .Values.ingress.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + {{- with .Values.ingress.className }} + ingressClassName: {{ . }} + {{- end }} + {{- with .Values.ingress.tls }} + tls: + {{- toYaml . | nindent 4 }} + {{- end }} + rules: + - host: {{ .Values.ingress.host | quote }} + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: {{ include "artex.fullname" . }}-panel + port: + name: http +{{- end }} diff --git a/deploy/helm/artex/templates/networkpolicy.yaml b/deploy/helm/artex/templates/networkpolicy.yaml new file mode 100644 index 000000000..9c9768165 --- /dev/null +++ b/deploy/helm/artex/templates/networkpolicy.yaml @@ -0,0 +1,87 @@ +{{- if .Values.networkPolicy.enabled }} +# Baseline for every pod the runner creates: no traffic at all. The runner adds a +# per-task policy pair (worker -> own proxy; proxy -> DNS + internet + scope) before +# it creates a task's pods, so a missing per-task policy fails closed. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "artex.fullname" . }}-sandbox-default-deny + labels: + {{- include "artex.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + artex.managed_by: artex-runner + policyTypes: ["Ingress", "Egress"] +{{- if eq .Values.sandbox.mode "required" }} +--- +# Only the panel may call the runner API. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + {{- include "artex.selector" (list . "runner") | nindent 6 }} + policyTypes: ["Ingress"] + ingress: + - from: + - podSelector: + matchLabels: + {{- include "artex.selector" (list . "panel") | nindent 14 }} + ports: + - protocol: TCP + port: {{ .Values.runner.port }} +{{- end }} +{{- if .Values.postgres.enabled }} +--- +# Only the panel may reach the database. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "artex.fullname" . }}-postgres + labels: + {{- include "artex.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + {{- include "artex.selector" (list . "postgres") | nindent 6 }} + policyTypes: ["Ingress", "Egress"] + ingress: + - from: + - podSelector: + matchLabels: + {{- include "artex.selector" (list . "panel") | nindent 14 }} + ports: + - protocol: TCP + port: 5432 + egress: [] +{{- end }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "artex.fullname" . }}-panel + labels: + {{- include "artex.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + {{- include "artex.selector" (list . "panel") | nindent 6 }} + policyTypes: ["Ingress"] + ingress: + - ports: + - protocol: TCP + port: 8787 + {{- if .Values.panel.recordingProxy.enabled }} + - protocol: TCP + port: {{ .Values.panel.recordingProxy.port }} + {{- end }} + {{- with .Values.networkPolicy.panelIngressFrom }} + from: + {{- toYaml . | nindent 8 }} + {{- end }} +{{- end }} diff --git a/deploy/helm/artex/templates/panel.yaml b/deploy/helm/artex/templates/panel.yaml new file mode 100644 index 000000000..94a0c8604 --- /dev/null +++ b/deploy/helm/artex/templates/panel.yaml @@ -0,0 +1,217 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "artex.fullname" . }}-panel + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: panel +spec: + replicas: {{ .Values.panel.replicas }} + # The data and keys volumes are single-writer: never run two panels at once. + strategy: + type: Recreate + selector: + matchLabels: + {{- include "artex.selector" (list . "panel") | nindent 6 }} + template: + metadata: + labels: + {{- include "artex.labels" . | nindent 8 }} + app.kubernetes.io/component: panel + annotations: + checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }} + spec: + {{- include "artex.pullSecrets" . | nindent 6 }} + # The panel never talks to the Kubernetes API: the runner does. + automountServiceAccountToken: false + enableServiceLinks: false + terminationGracePeriodSeconds: 30 + securityContext: + seccompProfile: + type: RuntimeDefault + {{- with .Values.panel.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.panel.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- if and (include "artex.pinToNode" .) (eq .Values.sandbox.mode "required") }} + # ReadWriteOnce data volume: every pod mounting it shares the runner's node + # (the runner pins task pods there). + affinity: + podAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - topologyKey: kubernetes.io/hostname + labelSelector: + matchLabels: + {{- include "artex.selector" (list . "runner") | nindent 18 }} + {{- else if .Values.panel.affinity }} + affinity: + {{- toYaml .Values.panel.affinity | nindent 8 }} + {{- end }} + initContainers: + # Volume provisioners often create the volume root world-writable (local-path + # uses 0777). The panel's isolation self-test then fails ("Bash can create + # files in /app/data", issue #620), correctly: agent processes (uid 10001) + # must not create entries at the top of the data directory or read the keys. + # Restore the ownership ARTEX expects before it starts. + - name: volume-permissions + image: {{ include "artex.image" (list . .Values.images.artex) }} + imagePullPolicy: {{ .Values.images.pullPolicy }} + command: + - sh + - -c + - | + set -eu + chown 0:0 /app/data /app/keys + chmod 0755 /app/data + chmod 0700 /app/keys + securityContext: + runAsUser: 0 + runAsGroup: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + add: ["CHOWN", "FOWNER"] + resources: + limits: + cpu: 100m + memory: 64Mi + volumeMounts: + - name: data + mountPath: /app/data + - name: keys + mountPath: /app/keys + containers: + - name: artex + image: {{ include "artex.image" (list . .Values.images.artex) }} + imagePullPolicy: {{ .Values.images.pullPolicy }} + args: + - -addr + - ":8787" + - -proxy + - {{ if .Values.panel.recordingProxy.enabled }}{{ printf ":%d" (int .Values.panel.recordingProxy.port) | quote }}{{ else }}""{{ end }} + env: + - name: ARTEX_PG_HOST + value: {{ include "artex.pgHost" . | quote }} + - name: ARTEX_PG_PORT + value: {{ ternary "5432" (toString .Values.postgres.external.port) .Values.postgres.enabled | quote }} + - name: ARTEX_PG_USER + value: {{ ternary .Values.postgres.user .Values.postgres.external.user .Values.postgres.enabled | quote }} + - name: ARTEX_PG_DBNAME + value: {{ ternary .Values.postgres.database .Values.postgres.external.database .Values.postgres.enabled | quote }} + - name: ARTEX_PG_SSLMODE + value: {{ ternary "disable" .Values.postgres.external.sslMode .Values.postgres.enabled | quote }} + - name: ARTEX_PG_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: POSTGRES_PASSWORD + - name: ANTHROPIC_API_KEY + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: ANTHROPIC_API_KEY + optional: true + - name: OPENAI_API_KEY + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: OPENAI_API_KEY + optional: true + - name: ARTEX_SECRET_KEY + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: ARTEX_SECRET_KEY + optional: true + - name: ARTEX_JWT_KEY_DIR + value: /app/keys + - name: ARTEX_SANDBOX + value: {{ .Values.sandbox.mode | quote }} + {{- if eq .Values.sandbox.mode "required" }} + - name: ARTEX_RUNNER_URL + value: {{ include "artex.runnerURL" . | quote }} + - name: ARTEX_RUNNER_TOKEN + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: ARTEX_RUNNER_TOKEN + {{- end }} + {{- range $k, $v := .Values.panel.env }} + - name: {{ $k }} + value: {{ $v | quote }} + {{- end }} + ports: + - name: http + containerPort: 8787 + {{- if .Values.panel.recordingProxy.enabled }} + - name: recording + containerPort: {{ .Values.panel.recordingProxy.port }} + {{- end }} + startupProbe: + httpGet: + path: /api/health + port: http + periodSeconds: 5 + failureThreshold: 60 + readinessProbe: + httpGet: + path: /api/ready + port: http + periodSeconds: 10 + livenessProbe: + httpGet: + path: /api/health + port: http + periodSeconds: 20 + failureThreshold: 3 + # The panel starts as root and drops every agent process to uid/gid 10001 + # itself (-exec-uid). Its startup self-test refuses to run when that drop + # cannot isolate agents, so it cannot run with runAsNonRoot. It keeps only + # the capabilities the drop and the shared run directories need. + securityContext: + runAsUser: 0 + runAsGroup: 0 + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + add: ["CHOWN", "DAC_OVERRIDE", "FOWNER", "SETUID", "SETGID", "KILL"] + resources: + {{- toYaml .Values.panel.resources | nindent 12 }} + volumeMounts: + - name: data + mountPath: /app/data + - name: keys + mountPath: /app/keys + volumes: + - name: data + persistentVolumeClaim: + claimName: {{ include "artex.dataClaim" . }} + - name: keys + persistentVolumeClaim: + claimName: {{ include "artex.keysClaim" . }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ include "artex.fullname" . }}-panel + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: panel +spec: + type: {{ .Values.panel.service.type }} + selector: + {{- include "artex.selector" (list . "panel") | nindent 4 }} + ports: + - name: http + port: {{ .Values.panel.service.port }} + targetPort: http + {{- if .Values.panel.recordingProxy.enabled }} + - name: recording + port: {{ .Values.panel.recordingProxy.port }} + targetPort: recording + {{- end }} diff --git a/deploy/helm/artex/templates/postgres.yaml b/deploy/helm/artex/templates/postgres.yaml new file mode 100644 index 000000000..5e87f2d29 --- /dev/null +++ b/deploy/helm/artex/templates/postgres.yaml @@ -0,0 +1,108 @@ +{{- if .Values.postgres.enabled }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "artex.fullname" . }}-postgres + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: postgres +spec: + clusterIP: None + selector: + {{- include "artex.selector" (list . "postgres") | nindent 4 }} + ports: + - name: postgres + port: 5432 + targetPort: postgres +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: {{ include "artex.fullname" . }}-postgres + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: postgres +spec: + serviceName: {{ include "artex.fullname" . }}-postgres + replicas: 1 + selector: + matchLabels: + {{- include "artex.selector" (list . "postgres") | nindent 6 }} + template: + metadata: + labels: + {{- include "artex.labels" . | nindent 8 }} + app.kubernetes.io/component: postgres + spec: + {{- include "artex.pullSecrets" . | nindent 6 }} + automountServiceAccountToken: false + enableServiceLinks: false + securityContext: + runAsUser: 70 # postgres user in the alpine image + runAsGroup: 70 + fsGroup: 70 + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + containers: + - name: postgres + image: {{ .Values.postgres.image }} + imagePullPolicy: {{ .Values.postgres.pullPolicy }} + env: + - name: POSTGRES_USER + value: {{ .Values.postgres.user | quote }} + - name: POSTGRES_DB + value: {{ .Values.postgres.database | quote }} + - name: POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: POSTGRES_PASSWORD + # Password (SCRAM) for every TCP connection, as in docker-compose.yml. + - name: POSTGRES_HOST_AUTH_METHOD + value: scram-sha-256 + - name: PGDATA + value: /var/lib/postgresql/data/pgdata + ports: + - name: postgres + containerPort: 5432 + readinessProbe: + exec: + command: ["sh", "-c", "pg_isready -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\" -h 127.0.0.1"] + periodSeconds: 5 + livenessProbe: + exec: + command: ["sh", "-c", "pg_isready -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\" -h 127.0.0.1"] + initialDelaySeconds: 30 + periodSeconds: 10 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + resources: + {{- toYaml .Values.postgres.resources | nindent 12 }} + volumeMounts: + - name: pgdata + mountPath: /var/lib/postgresql/data + - name: run + mountPath: /var/run/postgresql + - name: tmp + mountPath: /tmp + volumes: + - name: run + emptyDir: {} + - name: tmp + emptyDir: {} + volumeClaimTemplates: + - metadata: + name: pgdata + spec: + accessModes: ["ReadWriteOnce"] + {{- with .Values.postgres.storage.storageClass }} + storageClassName: {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.postgres.storage.size }} +{{- end }} diff --git a/deploy/helm/artex/templates/pvc.yaml b/deploy/helm/artex/templates/pvc.yaml new file mode 100644 index 000000000..7bccc5bfe --- /dev/null +++ b/deploy/helm/artex/templates/pvc.yaml @@ -0,0 +1,37 @@ +{{- if not .Values.persistence.data.existingClaim }} +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: {{ include "artex.dataClaim" . }} + labels: + {{- include "artex.labels" . | nindent 4 }} + annotations: + helm.sh/resource-policy: keep +spec: + accessModes: [{{ .Values.persistence.data.accessMode | quote }}] + {{- with .Values.persistence.data.storageClass }} + storageClassName: {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.persistence.data.size }} +{{- end }} +{{- if not .Values.persistence.keys.existingClaim }} +--- +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: {{ include "artex.keysClaim" . }} + labels: + {{- include "artex.labels" . | nindent 4 }} + annotations: + helm.sh/resource-policy: keep +spec: + accessModes: ["ReadWriteOnce"] + {{- with .Values.persistence.keys.storageClass }} + storageClassName: {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.persistence.keys.size }} +{{- end }} diff --git a/deploy/helm/artex/templates/runner.yaml b/deploy/helm/artex/templates/runner.yaml new file mode 100644 index 000000000..facb24f47 --- /dev/null +++ b/deploy/helm/artex/templates/runner.yaml @@ -0,0 +1,205 @@ +{{- if eq .Values.sandbox.mode "required" }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: runner + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +--- +# Task pods run under this account; its token is never mounted. +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "artex.fullname" . }}-task + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: task +automountServiceAccountToken: false +--- +# Namespace-scoped and limited to what the KubernetesBackend calls. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: runner +rules: + - apiGroups: [""] + resources: ["pods"] + verbs: ["get", "list", "create", "delete"] + # Exec over WebSocket is a GET on pods/exec; create covers SPDY clients. + - apiGroups: [""] + resources: ["pods/exec"] + verbs: ["get", "create"] + - apiGroups: [""] + resources: ["services"] + verbs: ["get", "list", "create", "delete"] + - apiGroups: ["networking.k8s.io"] + resources: ["networkpolicies"] + verbs: ["get", "list", "create", "update", "delete"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: runner +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ include "artex.fullname" . }}-runner +subjects: + - kind: ServiceAccount + name: {{ include "artex.fullname" . }}-runner + namespace: {{ .Release.Namespace }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: runner +spec: + replicas: {{ .Values.runner.replicas }} + strategy: + type: Recreate + selector: + matchLabels: + {{- include "artex.selector" (list . "runner") | nindent 6 }} + template: + metadata: + labels: + {{- include "artex.labels" . | nindent 8 }} + app.kubernetes.io/component: runner + annotations: + checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }} + spec: + {{- include "artex.pullSecrets" . | nindent 6 }} + serviceAccountName: {{ include "artex.fullname" . }}-runner + enableServiceLinks: false + securityContext: + seccompProfile: + type: RuntimeDefault + {{- with .Values.runner.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.runner.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: runner + image: {{ include "artex.image" (list . .Values.images.runner) }} + imagePullPolicy: {{ .Values.images.pullPolicy }} + env: + - name: ARTEX_RUNNER_BACKEND + value: kubernetes + - name: ARTEX_RUNNER_ADDR + value: {{ printf ":%d" (int .Values.runner.port) | quote }} + - name: ARTEX_RUNNER_TOKEN + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: ARTEX_RUNNER_TOKEN + - name: ARTEX_KUBE_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: ARTEX_KUBE_DATA_CLAIM + value: {{ include "artex.dataClaim" . | quote }} + - name: ARTEX_KUBE_SERVICE_ACCOUNT + value: {{ include "artex.fullname" . }}-task + - name: ARTEX_KUBE_IMAGE_PULL_POLICY + value: {{ .Values.images.pullPolicy | quote }} + - name: ARTEX_WORKER_IMAGE + value: {{ include "artex.image" (list . .Values.images.worker) | quote }} + - name: ARTEX_EGRESS_PROXY_IMAGE + value: {{ include "artex.image" (list . .Values.images.egressProxy) | quote }} + - name: ARTEX_WORKSPACE_ROOT + value: /app/data/tasks + - name: ARTEX_AUDIT_ROOT + value: /app/data/egress-audit + - name: ARTEX_KUBE_POD_READY_TIMEOUT + value: {{ .Values.sandbox.podReadyTimeout | quote }} + - name: ARTEX_KUBE_WORKER_CPU_LIMIT + value: {{ .Values.sandbox.worker.cpuLimit | quote }} + - name: ARTEX_KUBE_WORKER_MEMORY_LIMIT + value: {{ .Values.sandbox.worker.memoryLimit | quote }} + - name: ARTEX_KUBE_DNS_NAMESPACE + value: {{ .Values.sandbox.dns.namespace | quote }} + - name: ARTEX_KUBE_DNS_LABELS + value: {{ $l := list }}{{ range $k, $v := .Values.sandbox.dns.podLabels }}{{ $l = append $l (printf "%s=%s" $k $v) }}{{ end }}{{ join "," $l | quote }} + {{- with .Values.sandbox.proxyDeniedCIDRs }} + - name: ARTEX_KUBE_PROXY_DENIED_CIDRS + value: {{ join "," . | quote }} + {{- end }} + {{- with .Values.sandbox.runtimeClassName }} + - name: ARTEX_KUBE_RUNTIME_CLASS + value: {{ . | quote }} + {{- end }} + {{- if include "artex.pinToNode" . }} + - name: ARTEX_KUBE_PIN_NODE + valueFrom: + fieldRef: + fieldPath: spec.nodeName + {{- end }} + ports: + - name: runner + containerPort: {{ .Values.runner.port }} + readinessProbe: + exec: + command: ["sh", "-c", "curl -fsS -H \"Authorization: Bearer $ARTEX_RUNNER_TOKEN\" http://127.0.0.1:{{ .Values.runner.port }}/v1/health"] + periodSeconds: 10 + timeoutSeconds: 5 + livenessProbe: + tcpSocket: + port: runner + periodSeconds: 20 + # Root only to create and chown per-task directories to 10001 (CAP_CHOWN); + # no other capability, read-only root filesystem. + securityContext: + runAsUser: 0 + runAsGroup: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + add: ["CHOWN"] + resources: + {{- toYaml .Values.runner.resources | nindent 12 }} + volumeMounts: + - name: data + mountPath: /app/data/tasks + subPath: tasks + - name: data + mountPath: /app/data/egress-audit + subPath: egress-audit + volumes: + - name: data + persistentVolumeClaim: + claimName: {{ include "artex.dataClaim" . }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: runner +spec: + selector: + {{- include "artex.selector" (list . "runner") | nindent 4 }} + ports: + - name: runner + port: {{ .Values.runner.port }} + targetPort: runner +{{- end }} diff --git a/deploy/helm/artex/templates/secret.yaml b/deploy/helm/artex/templates/secret.yaml new file mode 100644 index 000000000..4ef281826 --- /dev/null +++ b/deploy/helm/artex/templates/secret.yaml @@ -0,0 +1,28 @@ +{{- if not .Values.secrets.existingSecret }} +{{- /* Generated values are kept across upgrades: a new runner token or database + password on every upgrade would break the running release. */}} +{{- $name := include "artex.secretName" . }} +{{- $existing := (lookup "v1" "Secret" .Release.Namespace $name) | default dict }} +{{- $data := get $existing "data" | default dict }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ $name }} + labels: + {{- include "artex.labels" . | nindent 4 }} + annotations: + helm.sh/resource-policy: keep +type: Opaque +data: + ARTEX_RUNNER_TOKEN: {{ .Values.secrets.runnerToken | default (get $data "ARTEX_RUNNER_TOKEN" | default "" | b64dec) | default (randAlphaNum 48) | b64enc | quote }} + POSTGRES_PASSWORD: {{ .Values.secrets.postgresPassword | default (get $data "POSTGRES_PASSWORD" | default "" | b64dec) | default (randAlphaNum 32) | b64enc | quote }} + {{- with (.Values.secrets.anthropicApiKey | default (get $data "ANTHROPIC_API_KEY" | default "" | b64dec)) }} + ANTHROPIC_API_KEY: {{ . | b64enc | quote }} + {{- end }} + {{- with (.Values.secrets.openaiApiKey | default (get $data "OPENAI_API_KEY" | default "" | b64dec)) }} + OPENAI_API_KEY: {{ . | b64enc | quote }} + {{- end }} + {{- with (.Values.secrets.secretKey | default (get $data "ARTEX_SECRET_KEY" | default "" | b64dec)) }} + ARTEX_SECRET_KEY: {{ . | b64enc | quote }} + {{- end }} +{{- end }} diff --git a/deploy/helm/artex/templates/tests/test-panel.yaml b/deploy/helm/artex/templates/tests/test-panel.yaml new file mode 100644 index 000000000..ceff9d322 --- /dev/null +++ b/deploy/helm/artex/templates/tests/test-panel.yaml @@ -0,0 +1,38 @@ +apiVersion: v1 +kind: Pod +metadata: + name: {{ include "artex.fullname" . }}-test-panel + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: test + annotations: + helm.sh/hook: test + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +spec: + restartPolicy: Never + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 65534 + seccompProfile: + type: RuntimeDefault + containers: + # The runner image ships curl; reusing it avoids pulling another image. + - name: health + image: {{ include "artex.image" (list . .Values.images.runner) }} + imagePullPolicy: {{ .Values.images.pullPolicy }} + command: + - sh + - -c + - | + set -eu + base=http://{{ include "artex.fullname" . }}-panel:{{ .Values.panel.service.port }} + curl -fsS "$base/api/health" + echo + curl -fsS "$base/api/ready" + echo + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] diff --git a/deploy/helm/artex/values.schema.json b/deploy/helm/artex/values.schema.json new file mode 100644 index 000000000..b4779c359 --- /dev/null +++ b/deploy/helm/artex/values.schema.json @@ -0,0 +1,73 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["images", "sandbox", "persistence", "postgres", "networkPolicy"], + "properties": { + "images": { + "type": "object", + "properties": { + "pullPolicy": { "enum": ["Always", "IfNotPresent", "Never"] }, + "pullSecrets": { "type": "array", "items": { "type": "string" } } + } + }, + "panel": { + "type": "object", + "properties": { + "replicas": { "type": "integer", "minimum": 0, "maximum": 1 }, + "env": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", "not": { "pattern": "(?i)(_KEY|_TOKEN|_PASSWORD|_SECRET)$" } }, + "additionalProperties": { "type": ["string", "number", "boolean"] } + } + } + }, + "runner": { + "type": "object", + "properties": { + "replicas": { "type": "integer", "minimum": 0, "maximum": 1 }, + "port": { "type": "integer", "minimum": 1, "maximum": 65535 } + } + }, + "sandbox": { + "type": "object", + "required": ["mode"], + "properties": { + "mode": { "enum": ["required", "off"] }, + "runtimeClassName": { "type": "string" }, + "podReadyTimeout": { "type": "string", "pattern": "^[0-9]+(ms|s|m|h)$" }, + "proxyDeniedCIDRs": { + "type": "array", + "items": { "type": "string", "pattern": "^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$" } + } + } + }, + "persistence": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { "accessMode": { "enum": ["ReadWriteOnce", "ReadWriteMany"] } } + } + } + }, + "postgres": { + "type": "object", + "properties": { + "enabled": { "type": "boolean" }, + "external": { + "type": "object", + "properties": { + "sslMode": { "enum": ["disable", "allow", "prefer", "require", "verify-ca", "verify-full"] } + } + } + } + }, + "networkPolicy": { + "type": "object", + "properties": { + "enabled": { "type": "boolean" }, + "panelIngressFrom": { "type": "array" } + } + } + } +} diff --git a/deploy/helm/artex/values.yaml b/deploy/helm/artex/values.yaml new file mode 100644 index 000000000..148f59f4c --- /dev/null +++ b/deploy/helm/artex/values.yaml @@ -0,0 +1,154 @@ +# Default values for the ARTEX chart. See README.md in this directory. + +# Release images published to GHCR. An empty tag means the chart's appVersion. +# Locally built images: set repository to artex, artex-runner, ... and tag to +# local, and pullPolicy to Never after importing them (see scripts/k3d-e2e.sh). +images: + # Panel (web UI + API + agent engine). + artex: + repository: ghcr.io/baarai/artex + tag: "" + # Sandbox runner: creates per-task pods through the Kubernetes API. + runner: + repository: ghcr.io/baarai/artex-runner + tag: "" + # Per-task worker (runs agent commands) and egress proxy. + worker: + repository: ghcr.io/baarai/artex-worker + tag: "" + egressProxy: + repository: ghcr.io/baarai/artex-egress-proxy + tag: "" + pullPolicy: IfNotPresent + pullSecrets: [] + +# Secrets. Either name an existing Secret (existingSecret) holding the keys below, +# or let the chart create one. Values left empty are generated once and kept across +# upgrades (runnerToken, postgresPassword), or simply omitted (LLM keys). +secrets: + existingSecret: "" + # Keys in the Secret: + # ARTEX_RUNNER_TOKEN, POSTGRES_PASSWORD, ANTHROPIC_API_KEY, OPENAI_API_KEY, ARTEX_SECRET_KEY + runnerToken: "" + postgresPassword: "" + anthropicApiKey: "" + openaiApiKey: "" + # Optional key for secrets at rest; empty = generated by ARTEX in the keys volume. + secretKey: "" + +panel: + replicas: 1 # ARTEX is a single-writer service; keep 1. + # Extra plain environment for the panel (ARTEX_LLM_PROVIDER, ARTEX_LLM_MODEL, ...). + # Never put secrets here: use the secrets block. + env: {} + resources: + requests: + cpu: 250m + memory: 512Mi + limits: + memory: 4Gi + service: + type: ClusterIP + port: 8787 + # The recording proxy (8788) is exposed only inside the cluster when enabled. + recordingProxy: + enabled: false + port: 8788 + nodeSelector: {} + tolerations: [] + # Ignored when the data volume is ReadWriteOnce and the sandbox is on: the panel + # must then share the runner's node. + affinity: {} + +runner: + replicas: 1 # Task state is kept per runner; keep 1. + port: 8789 + resources: + requests: + cpu: 50m + memory: 64Mi + limits: + memory: 256Mi + nodeSelector: {} + tolerations: [] + +sandbox: + # "required": every agent command runs in a per-task pod (recommended). + # "off": agents run inside the panel container (not recommended on shared clusters). + mode: required + # Optional RuntimeClass for task pods (gvisor, kata, ...) for kernel isolation. + runtimeClassName: "" + podReadyTimeout: 2m + worker: + cpuLimit: "2" + memoryLimit: 2Gi + # IPv4 ranges the egress proxy pods may never reach (NetworkPolicy, in addition to + # the proxy's own allowlist). Task scope CIDRs are allowed back explicitly. + # Empty = built-in default (RFC1918, CGNAT, loopback, link-local, metadata, multicast). + proxyDeniedCIDRs: [] + # Cluster DNS the egress proxy may query. + dns: + namespace: kube-system + podLabels: + k8s-app: kube-dns + +persistence: + # Shared data volume: the panel mounts all of it, the runner mounts tasks/ and + # egress-audit/, task pods mount their own sub-directories. + data: + existingClaim: "" + size: 20Gi + storageClass: "" + # ReadWriteOnce: every pod is pinned to the panel's node (single-node, k3d, + # local-path). ReadWriteMany (NFS, CephFS, Longhorn RWX, EFS, ...) lets task pods + # schedule anywhere. + accessMode: ReadWriteOnce + keys: + existingClaim: "" + size: 64Mi + storageClass: "" + +postgres: + # Bundled single-instance PostgreSQL. Disable to use an external database. + enabled: true + image: postgres:16-alpine@sha256:f2f98726820d0342055351c6e9d36e705f5bfffb3dd53ff556325114b08afb6d + # Separate from images.pullPolicy: the ARTEX images may be side-loaded (Never), + # the database image is public. + pullPolicy: IfNotPresent + user: artex + database: artex + storage: + size: 10Gi + storageClass: "" + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + memory: 1Gi + # Used when enabled=false. + external: + host: "" + port: 5432 + user: artex + database: artex + sslMode: require + +networkPolicy: + # Requires a CNI that enforces NetworkPolicy (k3s/kube-router, Calico, Cilium, ...). + # The sandbox relies on it: without enforcement task pods are NOT network-isolated. + enabled: true + # Namespaces/pods allowed to reach the panel UI (an ingress controller, for + # example). Empty = any source. Entries are NetworkPolicy "from" peers. + panelIngressFrom: [] + +ingress: + enabled: false + className: "" + annotations: {} + host: artex.example.com + tls: [] + +serviceAccount: + # Extra annotations for the runner's service account. + annotations: {} diff --git a/sandbox/helmchart_test.go b/sandbox/helmchart_test.go new file mode 100644 index 000000000..b9689458a --- /dev/null +++ b/sandbox/helmchart_test.go @@ -0,0 +1,568 @@ +package sandbox + +import ( + "bytes" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +// These tests render deploy/helm/artex with `helm template` and check the security +// and wiring invariants the KubernetesBackend depends on. They skip when helm is not +// installed. + +const chartDir = "../deploy/helm/artex" + +type k8sObj = map[string]any + +func renderChart(t *testing.T, set ...string) []k8sObj { + t.Helper() + helm := helmOrSkip(t) + args := []string{"template", "rel", chartDir, "--namespace", "artex-ns"} + for _, s := range set { + args = append(args, "--set", s) + } + cmd := exec.Command(helm, args...) + var stderr bytes.Buffer + cmd.Stderr = &stderr + out, err := cmd.Output() + if err != nil { + t.Fatalf("helm template %v: %v\n%s", set, err, stderr.String()) + } + var objs []k8sObj + dec := yaml.NewDecoder(bytes.NewReader(out)) + for { + var o k8sObj + err := dec.Decode(&o) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + t.Fatalf("decode rendered chart: %v", err) + } + if o != nil { + objs = append(objs, o) + } + } + return objs +} + +func findObj(objs []k8sObj, kind, name string) k8sObj { + for _, o := range objs { + if o["kind"] == kind && dig(o, "metadata", "name") == name { + return o + } + } + return nil +} + +func objsOfKind(objs []k8sObj, kind string) []k8sObj { + var out []k8sObj + for _, o := range objs { + if o["kind"] == kind { + out = append(out, o) + } + } + return out +} + +// podSpecOf returns the pod spec of a workload or a bare Pod. +func podSpecOf(o k8sObj) any { + if o["kind"] == "Pod" { + return o["spec"] + } + return dig(o, "spec", "template", "spec") +} + +func containerEnv(c any) (plain map[string]string, refs map[string]any) { + plain, refs = map[string]string{}, map[string]any{} + env, _ := dig(c, "env").([]any) + for _, e := range env { + name := dig(e, "name").(string) + if v, ok := dig(e, "value").(string); ok { + plain[name] = v + } else { + refs[name] = dig(e, "valueFrom") + } + } + return plain, refs +} + +func strList(v any) []string { + var out []string + s, _ := v.([]any) + for _, x := range s { + out = append(out, x.(string)) + } + return out +} + +func TestHelmChartPodSecurityBaseline(t *testing.T) { + objs := renderChart(t) + workloads := append(append(objsOfKind(objs, "Deployment"), objsOfKind(objs, "StatefulSet")...), objsOfKind(objs, "Pod")...) + if len(workloads) != 4 { // panel, runner, postgres, helm test pod + t.Fatalf("workloads = %d", len(workloads)) + } + for _, w := range workloads { + name := dig(w, "metadata", "name").(string) + spec := podSpecOf(w) + if dig(spec, "securityContext", "seccompProfile", "type") != "RuntimeDefault" { + t.Errorf("%s: pod seccompProfile = %v", name, dig(spec, "securityContext", "seccompProfile")) + } + for _, k := range []string{"hostNetwork", "hostPID", "hostIPC"} { + if dig(spec, k) == true { + t.Errorf("%s: %s=true", name, k) + } + } + vols, _ := dig(spec, "volumes").([]any) + for _, v := range vols { + if dig(v, "hostPath") != nil { + t.Errorf("%s: hostPath volume %v", name, v) + } + } + isRunner := strings.HasSuffix(name, "-runner") + if dig(spec, "automountServiceAccountToken") != false && !isRunner { + t.Errorf("%s: service account token mounted", name) + } + if !isRunner && dig(w, "kind") != "Pod" && dig(spec, "enableServiceLinks") != false { + t.Errorf("%s: enableServiceLinks not false", name) + } + all := dig(spec, "containers").([]any) + if ics, ok := dig(spec, "initContainers").([]any); ok { + all = append(all, ics...) + } + for _, c := range all { + sc := dig(c, "securityContext") + if dig(sc, "allowPrivilegeEscalation") != false { + t.Errorf("%s: allowPrivilegeEscalation = %v", name, dig(sc, "allowPrivilegeEscalation")) + } + if dig(sc, "privileged") == true { + t.Errorf("%s: privileged", name) + } + if d := strList(dig(sc, "capabilities", "drop")); !slices.Equal(d, []string{"ALL"}) { + t.Errorf("%s: capabilities.drop = %v", name, d) + } + for _, cap := range strList(dig(sc, "capabilities", "add")) { + if slices.Contains([]string{"SYS_ADMIN", "NET_ADMIN", "NET_RAW", "SYS_PTRACE", "SYS_MODULE", "ALL"}, cap) { + t.Errorf("%s: dangerous capability %s", name, cap) + } + } + } + } + + panel := findObj(objs, "Deployment", "rel-artex-panel") + pc := dig(podSpecOf(panel), "containers", 0) + if got := strList(dig(pc, "securityContext", "capabilities", "add")); !slices.Equal(got, []string{"CHOWN", "DAC_OVERRIDE", "FOWNER", "SETUID", "SETGID", "KILL"}) { + t.Errorf("panel capabilities = %v", got) + } + // Init container restores root ownership of the volume roots (issue #620). + ic := dig(podSpecOf(panel), "initContainers", 0) + script := strings.Join(strList(dig(ic, "command")), " ") + for _, want := range []string{"chown 0:0 /app/data /app/keys", "chmod 0755 /app/data", "chmod 0700 /app/keys"} { + if !strings.Contains(script, want) { + t.Errorf("panel init container missing %q: %s", want, script) + } + } + if got := strList(dig(ic, "securityContext", "capabilities", "add")); !slices.Equal(got, []string{"CHOWN", "FOWNER"}) { + t.Errorf("init container capabilities = %v", got) + } + runner := findObj(objs, "Deployment", "rel-artex-runner") + rc := dig(podSpecOf(runner), "containers", 0) + if got := strList(dig(rc, "securityContext", "capabilities", "add")); !slices.Equal(got, []string{"CHOWN"}) { + t.Errorf("runner capabilities = %v", got) + } + if dig(rc, "securityContext", "readOnlyRootFilesystem") != true { + t.Error("runner root filesystem writable") + } + // The runner never mounts a container runtime socket. + for _, m := range dig(rc, "volumeMounts").([]any) { + if strings.Contains(dig(m, "mountPath").(string), ".sock") { + t.Errorf("runner mounts a socket: %v", m) + } + } + for _, o := range objs { + if o["kind"] == "Deployment" && dig(o, "spec", "strategy", "type") != "Recreate" { + t.Errorf("%s: strategy %v (single-writer volumes need Recreate)", dig(o, "metadata", "name"), dig(o, "spec", "strategy", "type")) + } + } +} + +func TestHelmChartRunnerEnvMatchesBackend(t *testing.T) { + objs := renderChart(t) + runner := findObj(objs, "Deployment", "rel-artex-runner") + rc := dig(podSpecOf(runner), "containers", 0) + plain, refs := containerEnv(rc) + + if plain[EnvRunnerBackend] != BackendKubernetes { + t.Fatalf("runner backend env = %q", plain[EnvRunnerBackend]) + } + // Every ARTEX_KUBE_* name the chart sets must be one the backend reads. + src, err := os.ReadFile("kube.go") + if err != nil { + t.Fatal(err) + } + for name := range plain { + if strings.HasPrefix(name, "ARTEX_KUBE_") && !bytes.Contains(src, []byte(`"`+name+`"`)) { + t.Errorf("chart sets %s but kube.go never reads it", name) + } + } + for name := range refs { + if strings.HasPrefix(name, "ARTEX_KUBE_") && !bytes.Contains(src, []byte(`"`+name+`"`)) { + t.Errorf("chart sets %s but kube.go never reads it", name) + } + } + // The rendered plain values parse with the backend's own config reader. + for k, v := range plain { + t.Setenv(k, v) + } + t.Setenv("ARTEX_KUBE_NAMESPACE", "artex-ns") + cfg, err := KubeConfigFromEnv() + if err != nil { + t.Fatalf("KubeConfigFromEnv on rendered env: %v", err) + } + if cfg.DataClaim != "rel-artex-data" || findObj(objs, "PersistentVolumeClaim", cfg.DataClaim) == nil { + t.Errorf("data claim %q not rendered", cfg.DataClaim) + } + if cfg.DNSPodLabels["k8s-app"] != "kube-dns" || cfg.DNSNamespace != "kube-system" { + t.Errorf("dns = %s %v", cfg.DNSNamespace, cfg.DNSPodLabels) + } + if cfg.ServiceAccount != "rel-artex-task" { + t.Errorf("task service account = %q", cfg.ServiceAccount) + } + taskSA := findObj(objs, "ServiceAccount", cfg.ServiceAccount) + if taskSA == nil || taskSA["automountServiceAccountToken"] != false { + t.Errorf("task service account %v", taskSA) + } + if plain[EnvWorkerImage] != "ghcr.io/baarai/artex-worker:"+chartAppVersion(t) || plain[EnvProxyImage] != "ghcr.io/baarai/artex-egress-proxy:"+chartAppVersion(t) { + t.Errorf("images = %s %s", plain[EnvWorkerImage], plain[EnvProxyImage]) + } + // Runner mounts exactly the sub paths the backend hands to task pods. + mounts := map[string]string{} + for _, m := range dig(rc, "volumeMounts").([]any) { + mounts[dig(m, "mountPath").(string)] = dig(m, "subPath").(string) + } + if mounts[plain[EnvWorkspaceRoot]] != "tasks" || mounts[plain[EnvAuditRoot]] != "egress-audit" { + t.Errorf("runner mounts %v vs roots %s %s", mounts, plain[EnvWorkspaceRoot], plain[EnvAuditRoot]) + } + if dig(refs["ARTEX_KUBE_NAMESPACE"], "fieldRef", "fieldPath") != "metadata.namespace" { + t.Errorf("namespace env = %v", refs["ARTEX_KUBE_NAMESPACE"]) + } + + // Panel talks to the runner service with the same secret key. + panel := findObj(objs, "Deployment", "rel-artex-panel") + pplain, prefs := containerEnv(dig(podSpecOf(panel), "containers", 0)) + if pplain[EnvSandboxMode] != ModeRequired { + t.Errorf("panel sandbox mode = %q", pplain[EnvSandboxMode]) + } + svc := findObj(objs, "Service", "rel-artex-runner") + if svc == nil || pplain[EnvRunnerURL] != "http://rel-artex-runner:8789" { + t.Errorf("runner URL %q / service %v", pplain[EnvRunnerURL], svc != nil) + } + if dig(prefs[EnvRunnerToken], "secretKeyRef", "key") != dig(refs[EnvRunnerToken], "secretKeyRef", "key") { + t.Error("panel and runner read different token keys") + } + // The panel never carries Kubernetes credentials or the runner backend's settings. + for k := range pplain { + if strings.HasPrefix(k, "ARTEX_KUBE_") { + t.Errorf("panel env has %s", k) + } + } +} + +func chartAppVersion(t *testing.T) string { + t.Helper() + raw, err := os.ReadFile(filepath.Join(chartDir, "Chart.yaml")) + if err != nil { + t.Fatal(err) + } + m := regexp.MustCompile(`(?m)^appVersion:\s*"?([^"\n]+)"?`).FindSubmatch(raw) + if m == nil { + t.Fatal("no appVersion in Chart.yaml") + } + return string(m[1]) +} + +func TestHelmChartImageOverrides(t *testing.T) { + objs := renderChart(t, "images.runner.repository=artex-runner", "images.runner.tag=local", "images.worker.tag=9.9.9") + runner := dig(podSpecOf(findObj(objs, "Deployment", "rel-artex-runner")), "containers", 0) + if dig(runner, "image") != "artex-runner:local" { + t.Errorf("runner image = %v", dig(runner, "image")) + } + plain, _ := containerEnv(runner) + if plain[EnvWorkerImage] != "ghcr.io/baarai/artex-worker:9.9.9" { + t.Errorf("worker image = %v", plain[EnvWorkerImage]) + } + panel := podSpecOf(findObj(objs, "Deployment", "rel-artex-panel")) + if dig(panel, "containers", 0, "image") != dig(panel, "initContainers", 0, "image") { + t.Error("panel init container uses a different image than the panel") + } +} + +func TestHelmChartSecretsWiring(t *testing.T) { + objs := renderChart(t, "secrets.anthropicApiKey=sk-test") + sec := findObj(objs, "Secret", "rel-artex-secrets") + if sec == nil { + t.Fatal("secret not rendered") + } + keys := sec["data"].(map[string]any) + for _, k := range []string{"ARTEX_RUNNER_TOKEN", "POSTGRES_PASSWORD", "ANTHROPIC_API_KEY"} { + if keys[k] == nil || keys[k] == "" { + t.Errorf("secret missing %s", k) + } + } + if keys["OPENAI_API_KEY"] != nil { + t.Error("empty OpenAI key rendered") + } + // Every non-optional secretKeyRef resolves to a key the chart renders. + for _, w := range append(objsOfKind(objs, "Deployment"), objsOfKind(objs, "StatefulSet")...) { + for _, c := range dig(podSpecOf(w), "containers").([]any) { + _, refs := containerEnv(c) + for name, ref := range refs { + sk := dig(ref, "secretKeyRef") + if sk == nil { + continue + } + if dig(sk, "name") != "rel-artex-secrets" { + t.Errorf("%s reads secret %v", name, dig(sk, "name")) + } + if dig(sk, "optional") != true && keys[dig(sk, "key").(string)] == nil { + t.Errorf("%s needs missing key %v", name, dig(sk, "key")) + } + } + } + } + // No secret value ever appears as a plain env value. + for _, w := range objsOfKind(objs, "Deployment") { + for _, c := range dig(podSpecOf(w), "containers").([]any) { + plain, _ := containerEnv(c) + for k, v := range plain { + if IsForbiddenEnvName(k) && strings.HasSuffix(k, "_TOKEN") || v == "sk-test" { + t.Errorf("secret-looking env %s in plain text", k) + } + } + } + } + + existing := renderChart(t, "secrets.existingSecret=mine") + if len(objsOfKind(existing, "Secret")) != 0 { + t.Error("secret rendered despite existingSecret") + } + _, refs := containerEnv(dig(podSpecOf(findObj(existing, "Deployment", "rel-artex-runner")), "containers", 0)) + if dig(refs[EnvRunnerToken], "secretKeyRef", "name") != "mine" { + t.Errorf("existingSecret not used: %v", refs[EnvRunnerToken]) + } +} + +func TestHelmChartRunnerRBACIsMinimal(t *testing.T) { + objs := renderChart(t) + if len(objsOfKind(objs, "ClusterRole"))+len(objsOfKind(objs, "ClusterRoleBinding")) != 0 { + t.Fatal("chart grants cluster-wide RBAC") + } + role := findObj(objs, "Role", "rel-artex-runner") + want := map[string][]string{ + "/pods": {"get", "list", "create", "delete"}, + "/pods/exec": {"get", "create"}, + "/services": {"get", "list", "create", "delete"}, + "networking.k8s.io/networkpolicies": {"get", "list", "create", "update", "delete"}, + } + got := map[string][]string{} + for _, r := range role["rules"].([]any) { + groups, res, verbs := strList(dig(r, "apiGroups")), strList(dig(r, "resources")), strList(dig(r, "verbs")) + for _, g := range groups { + for _, rs := range res { + if g == "*" || rs == "*" || slices.Contains(verbs, "*") { + t.Fatalf("wildcard rule %v", r) + } + if rs == "secrets" || rs == "pods/attach" || rs == "serviceaccounts/token" { + t.Errorf("runner may access %s", rs) + } + got[g+"/"+rs] = verbs + } + } + } + for k, v := range want { + if !slices.Equal(got[k], v) { + t.Errorf("rule %s = %v, want %v", k, got[k], v) + } + } + if len(got) != len(want) { + t.Errorf("extra rules: %v", got) + } + rb := findObj(objs, "RoleBinding", "rel-artex-runner") + if dig(rb, "subjects", 0, "name") != "rel-artex-runner" || dig(rb, "subjects", 0, "namespace") != "artex-ns" { + t.Errorf("binding subjects = %v", dig(rb, "subjects")) + } + if dig(podSpecOf(findObj(objs, "Deployment", "rel-artex-runner")), "serviceAccountName") != "rel-artex-runner" { + t.Error("runner not using its service account") + } +} + +func TestHelmChartNetworkPolicies(t *testing.T) { + objs := renderChart(t) + deny := findObj(objs, "NetworkPolicy", "rel-artex-sandbox-default-deny") + if deny == nil { + t.Fatal("sandbox default-deny missing") + } + sel := dig(deny, "spec", "podSelector", "matchLabels").(map[string]any) + if len(sel) != 1 || sel[LabelManagedBy] != ManagedByRunner { + t.Errorf("default-deny selector %v does not match runner-managed pods", sel) + } + if pt := strList(dig(deny, "spec", "policyTypes")); !slices.Equal(pt, []string{"Ingress", "Egress"}) { + t.Errorf("default-deny policyTypes %v", pt) + } + if dig(deny, "spec", "ingress") != nil || dig(deny, "spec", "egress") != nil { + t.Error("default-deny has allow rules") + } + runnerNP := findObj(objs, "NetworkPolicy", "rel-artex-runner") + if dig(runnerNP, "spec", "ingress", 0, "from", 0, "podSelector", "matchLabels", "app.kubernetes.io/component") != "panel" { + t.Errorf("runner ingress %v", dig(runnerNP, "spec", "ingress")) + } + pgNP := findObj(objs, "NetworkPolicy", "rel-artex-postgres") + if dig(pgNP, "spec", "ingress", 0, "from", 0, "podSelector", "matchLabels", "app.kubernetes.io/component") != "panel" { + t.Errorf("postgres ingress %v", dig(pgNP, "spec", "ingress")) + } + + off := renderChart(t, "networkPolicy.enabled=false") + if n := len(objsOfKind(off, "NetworkPolicy")); n != 0 { + t.Errorf("networkPolicy.enabled=false rendered %d policies", n) + } +} + +func TestHelmChartAccessModePinning(t *testing.T) { + // ReadWriteOnce: the panel follows the runner's node and task pods are pinned to + // it, so a runner-only install (panel.replicas=0) still schedules. + rwo := renderChart(t) + runner := podSpecOf(findObj(rwo, "Deployment", "rel-artex-runner")) + if dig(runner, "affinity") != nil { + t.Errorf("runner has affinity %v: it would not schedule without a panel", dig(runner, "affinity")) + } + panel := podSpecOf(findObj(rwo, "Deployment", "rel-artex-panel")) + if dig(panel, "affinity", "podAffinity", "requiredDuringSchedulingIgnoredDuringExecution", 0, "labelSelector", "matchLabels", "app.kubernetes.io/component") != "runner" { + t.Errorf("RWO panel not co-located with runner: %v", dig(panel, "affinity")) + } + _, refs := containerEnv(dig(runner, "containers", 0)) + if dig(refs["ARTEX_KUBE_PIN_NODE"], "fieldRef", "fieldPath") != "spec.nodeName" { + t.Errorf("RWO pin node env = %v", refs["ARTEX_KUBE_PIN_NODE"]) + } + if am := strList(dig(findObj(rwo, "PersistentVolumeClaim", "rel-artex-data"), "spec", "accessModes")); !slices.Equal(am, []string{"ReadWriteOnce"}) { + t.Errorf("data access modes %v", am) + } + + rwx := renderChart(t, "persistence.data.accessMode=ReadWriteMany") + runner = podSpecOf(findObj(rwx, "Deployment", "rel-artex-runner")) + if a := dig(podSpecOf(findObj(rwx, "Deployment", "rel-artex-panel")), "affinity"); a != nil { + t.Errorf("RWX panel pinned: %v", a) + } + // sandbox off has no runner to follow. + if a := dig(podSpecOf(findObj(renderChart(t, "sandbox.mode=off"), "Deployment", "rel-artex-panel")), "affinity"); a != nil { + t.Errorf("sandbox off panel has affinity %v", a) + } + _, refs = containerEnv(dig(runner, "containers", 0)) + if refs["ARTEX_KUBE_PIN_NODE"] != nil { + t.Error("RWX still pins task pods") + } +} + +func TestHelmChartModesAndOptions(t *testing.T) { + off := renderChart(t, "sandbox.mode=off") + for _, kind := range []string{"Role", "RoleBinding", "ServiceAccount"} { + if n := len(objsOfKind(off, kind)); n != 0 { + t.Errorf("sandbox off renders %d %s", n, kind) + } + } + if findObj(off, "Deployment", "rel-artex-runner") != nil { + t.Error("sandbox off renders the runner") + } + pplain, prefs := containerEnv(dig(podSpecOf(findObj(off, "Deployment", "rel-artex-panel")), "containers", 0)) + if pplain[EnvSandboxMode] != ModeOff || pplain[EnvRunnerURL] != "" || prefs[EnvRunnerToken] != nil { + t.Errorf("sandbox off panel env %v %v", pplain, prefs) + } + + never := renderChart(t, "images.pullPolicy=Never") + pg := dig(podSpecOf(findObj(never, "StatefulSet", "rel-artex-postgres")), "containers", 0) + if dig(pg, "imagePullPolicy") != "IfNotPresent" { + t.Errorf("postgres follows the side-loaded ARTEX pull policy: %v", dig(pg, "imagePullPolicy")) + } + + ext := renderChart(t, "postgres.enabled=false", "postgres.external.host=db.example", "postgres.external.sslMode=verify-full") + if len(objsOfKind(ext, "StatefulSet")) != 0 || findObj(ext, "NetworkPolicy", "rel-artex-postgres") != nil { + t.Error("external postgres still renders the bundled database") + } + pplain, _ = containerEnv(dig(podSpecOf(findObj(ext, "Deployment", "rel-artex-panel")), "containers", 0)) + if pplain["ARTEX_PG_HOST"] != "db.example" || pplain["ARTEX_PG_SSLMODE"] != "verify-full" { + t.Errorf("external pg env %v", pplain) + } + + opts := renderChart(t, "sandbox.runtimeClassName=gvisor", "sandbox.proxyDeniedCIDRs={10.0.0.0/8,192.168.0.0/16}", + "ingress.enabled=true", "ingress.host=artex.test", "panel.recordingProxy.enabled=true", "panel.env.ARTEX_LLM_MODEL=claude-opus-5-5") + rplain, _ := containerEnv(dig(podSpecOf(findObj(opts, "Deployment", "rel-artex-runner")), "containers", 0)) + if rplain["ARTEX_KUBE_RUNTIME_CLASS"] != "gvisor" || rplain["ARTEX_KUBE_PROXY_DENIED_CIDRS"] != "10.0.0.0/8,192.168.0.0/16" { + t.Errorf("runner options env %v", rplain) + } + if ing := findObj(opts, "Ingress", "rel-artex"); dig(ing, "spec", "rules", 0, "host") != "artex.test" { + t.Errorf("ingress %v", ing) + } + panel := dig(podSpecOf(findObj(opts, "Deployment", "rel-artex-panel")), "containers", 0) + pplain, _ = containerEnv(panel) + if pplain["ARTEX_LLM_MODEL"] != "claude-opus-5-5" { + t.Errorf("panel.env not applied: %v", pplain) + } + if args := strList(dig(panel, "args")); !slices.Equal(args, []string{"-addr", ":8787", "-proxy", ":8788"}) { + t.Errorf("panel args %v", args) + } + defArgs := strList(dig(podSpecOf(findObj(renderChart(t), "Deployment", "rel-artex-panel")), "containers", 0, "args")) + if !slices.Equal(defArgs, []string{"-addr", ":8787", "-proxy", ""}) { + t.Errorf("default panel args %v (recording proxy must be off)", defArgs) + } +} + +// helmOrSkip returns the helm binary. Locally a missing helm skips the chart tests; +// in CI it fails them, so they can never pass by not running. +func helmOrSkip(t *testing.T) string { + t.Helper() + helm, err := exec.LookPath("helm") + if err != nil { + if os.Getenv("CI") == "true" { + t.Fatal("helm not installed in CI: the chart tests would silently skip") + } + t.Skip("helm not installed") + } + return helm +} + +func TestHelmChartSchemaRejectsUnsafeValues(t *testing.T) { + helm := helmOrSkip(t) + for _, set := range []string{ + "sandbox.mode=permissive", + "panel.env.MY_API_KEY=x", + "panel.replicas=2", + "runner.replicas=3", + "persistence.data.accessMode=ReadWriteOncePod", + "sandbox.proxyDeniedCIDRs={fc00::/7}", + "images.pullPolicy=Sometimes", + "postgres.enabled=false", + } { + out, err := exec.Command(helm, "template", "rel", chartDir, "--set", set).CombinedOutput() + if err == nil { + t.Errorf("--set %s accepted", set) + } else if !regexp.MustCompile(`schema|required`).Match(out) { + t.Errorf("--set %s failed for an unexpected reason: %s", set, out) + } + } +} + +func TestHelmChartLint(t *testing.T) { + helm := helmOrSkip(t) + abs, _ := filepath.Abs(chartDir) + if out, err := exec.Command(helm, "lint", "--strict", abs).CombinedOutput(); err != nil { + t.Fatalf("helm lint: %v\n%s", err, out) + } +} diff --git a/scripts/k3d-e2e.sh b/scripts/k3d-e2e.sh new file mode 100755 index 000000000..195c57051 --- /dev/null +++ b/scripts/k3d-e2e.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# End-to-end test of the Helm chart and the Kubernetes sandbox backend on a local +# k3d cluster. +# +# scripts/k3d-e2e.sh create cluster, build + import images, install, test +# SKIP_BUILD=1 scripts/k3d-e2e.sh reuse images already built locally +# KEEP=1 scripts/k3d-e2e.sh leave the cluster running afterwards +# RUNNER_ONLY=1 scripts/k3d-e2e.sh sandbox only (panel.replicas=0): builds the three +# small sandbox images, skips the panel checks (CI) +# +# Optional: ANTHROPIC_API_KEY is passed to the chart Secret (never echoed). +# ARTEX_E2E_INTERNET=1 also tests allowed egress to example.com. +# Requires: docker, k3d, kubectl, helm, go. +set -euo pipefail + +CLUSTER=${CLUSTER:-artex-e2e} +NS=${NS:-artex} +RELEASE=${RELEASE:-artex} +CTX="k3d-${CLUSTER}" +ROOT=$(cd "$(dirname "$0")/.." && pwd) +IMAGES=(artex-runner:local artex-worker:local artex-egress-proxy:local) +[ "${RUNNER_ONLY:-0}" = "1" ] || IMAGES+=(artex:local) + +log() { printf '\n==> %s\n' "$*"; } + +cleanup() { + if [ "${KEEP:-0}" != "1" ]; then + log "deleting cluster ${CLUSTER} (KEEP=1 keeps it)" + k3d cluster delete "$CLUSTER" >/dev/null 2>&1 || true + fi +} +trap cleanup EXIT + +if ! k3d cluster get "$CLUSTER" >/dev/null 2>&1; then + log "creating k3d cluster ${CLUSTER}" + # k3s enforces NetworkPolicy with its embedded controller; traefik is not needed. + k3d cluster create "$CLUSTER" --servers 1 --agents 0 --wait --timeout 180s \ + --k3s-arg "--disable=traefik@server:0" +fi + +if [ "${SKIP_BUILD:-0}" != "1" ]; then + log "building images" + docker build -t artex-runner:local -f "$ROOT/Dockerfile.runner" "$ROOT" + docker build -t artex-worker:local -f "$ROOT/Dockerfile.worker" "$ROOT" + docker build -t artex-egress-proxy:local -f "$ROOT/Dockerfile.egress-proxy" "$ROOT" + if [ "${RUNNER_ONLY:-0}" != "1" ]; then + docker build -t artex:local -f "$ROOT/Dockerfile" "$ROOT" + fi +fi + +log "importing images into ${CLUSTER}" +k3d image import -c "$CLUSTER" "${IMAGES[@]}" + +log "installing chart" +kubectl --context "$CTX" create namespace "$NS" --dry-run=client -o yaml | kubectl --context "$CTX" apply -f - +set_args=(--set images.pullPolicy=Never + --set images.artex.repository=artex --set images.artex.tag=local + --set images.runner.repository=artex-runner --set images.runner.tag=local + --set images.worker.repository=artex-worker --set images.worker.tag=local + --set images.egressProxy.repository=artex-egress-proxy --set images.egressProxy.tag=local) +if [ "${RUNNER_ONLY:-0}" = "1" ]; then + # No panel: the keys volume never binds (WaitForFirstConsumer), so wait on the + # workloads instead of helm --wait. + helm upgrade --install "$RELEASE" "$ROOT/deploy/helm/artex" --kube-context "$CTX" -n "$NS" \ + "${set_args[@]}" --set panel.replicas=0 + kubectl --context "$CTX" -n "$NS" rollout status deploy/"$RELEASE"-runner --timeout=300s + kubectl --context "$CTX" -n "$NS" rollout status sts/"$RELEASE"-postgres --timeout=300s +elif [ -n "${ANTHROPIC_API_KEY:-}" ]; then + # Through a values file on a pipe, so the key never appears in the process list. + helm upgrade --install "$RELEASE" "$ROOT/deploy/helm/artex" --kube-context "$CTX" -n "$NS" \ + "${set_args[@]}" -f <(printf 'secrets:\n anthropicApiKey: %s\n' "$ANTHROPIC_API_KEY") --wait --timeout 10m +else + helm upgrade --install "$RELEASE" "$ROOT/deploy/helm/artex" --kube-context "$CTX" -n "$NS" \ + "${set_args[@]}" --wait --timeout 10m +fi + +if [ "${RUNNER_ONLY:-0}" != "1" ]; then +log "helm test" +helm test "$RELEASE" --kube-context "$CTX" -n "$NS" --logs + +log "checking panel isolation self-test" +# Read the log first: with pipefail, grep -q exiting early can fail the pipe. +panel_log=$(kubectl --context "$CTX" -n "$NS" logs deploy/"$RELEASE"-panel) +if ! grep -q "\[isolation\] self-test passed" <<<"$panel_log"; then + tail -40 <<<"$panel_log" + echo "panel did not start with agent isolation" >&2 + exit 1 +fi +fi + +TOKEN=$(kubectl --context "$CTX" -n "$NS" get secret "$RELEASE"-secrets -o jsonpath='{.data.ARTEX_RUNNER_TOKEN}' | base64 -d) + +log "running sandbox e2e tests" +( + cd "$ROOT" + ARTEX_SANDBOX_KUBE_E2E=1 \ + ARTEX_RUNNER_TOKEN="$TOKEN" \ + ARTEX_E2E_RUNNER_SVC="${RELEASE}-runner" \ + ARTEX_E2E_NAMESPACE="$NS" \ + ARTEX_E2E_KUBECONTEXT="$CTX" \ + go test ./sandbox -run TestKubeSandboxE2E -count=1 -v -timeout 20m +) +log "e2e passed" From b65c4fd59bdeedef62e4811b5af5ac1d12e7a749 Mon Sep 17 00:00:00 2001 From: Marco Azarmaneche <306425250+thecorporatetractor@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:46:05 +0200 Subject: [PATCH 3/6] feat(sandbox): read-only task status on the runner and a panel overview API The runner gains GET /v1/tasks (same bearer auth) backed by an optional StatusReporter interface, implemented for the Kubernetes backend (one label-selected pod list) and the Docker backend (list + inspect). sandbox.Client gains Tasks(). The panel exposes GET /api/sandbox/overview: sandbox mode, runner health, the runner task list, and per task a bounded tail of the egress audit log. Audit reads go through os.Root, refuse symlinked task directories and log files, and cap the bytes, line length and entry count. The panel still talks to the cluster only through the runner. ValidateTaskID no longer trims: " 42" was accepted by the runner and became a different task from "42". Ids are checked as given; the runner answers 400 and the client refuses before sending. --- docs/SANDBOX.md | 4 + sandbox/runner.go | 1 + sandbox/sandbox_test.go | 56 +++ sandbox/status.go | 413 ++++++++++++++++++++ sandbox/status_test.go | 651 ++++++++++++++++++++++++++++++++ sandbox/validate.go | 4 +- server/sandbox_overview.go | 314 +++++++++++++++ server/sandbox_overview_test.go | 614 ++++++++++++++++++++++++++++++ server/server.go | 5 + 9 files changed, 2061 insertions(+), 1 deletion(-) create mode 100644 sandbox/status.go create mode 100644 sandbox/status_test.go create mode 100644 server/sandbox_overview.go create mode 100644 server/sandbox_overview_test.go diff --git a/docs/SANDBOX.md b/docs/SANDBOX.md index 6afe9f63c..e1f8ec9af 100644 --- a/docs/SANDBOX.md +++ b/docs/SANDBOX.md @@ -13,6 +13,10 @@ from disposable per-task **worker** containers (`artex-worker:local`). mounting `/var/run/docker.sock`. Requires `Authorization: Bearer $ARTEX_RUNNER_TOKEN` on every endpoint including `GET /v1/health`. Creates and tracks one worker + one egress proxy per task by Docker label (`artex.task=`). + `GET /v1/tasks` is a read-only status listing (worker and proxy state, + scope, proxy address) that the panel's **System > Sandbox** page polls + through `GET /api/sandbox/overview`; the panel still holds no Docker or + Kubernetes credentials. 3. **`artex-worker-` (`artex-worker:local`)**: Runs as `10001:10001`, `--read-only`, `--cap-drop ALL`, `--security-opt no-new-privileges:true`, `--pids-limit 512`, `--memory 2g`, `--cpus 2`, bounded `tmpfs` on `/tmp` and diff --git a/sandbox/runner.go b/sandbox/runner.go index 6f8803af9..56f0e429f 100644 --- a/sandbox/runner.go +++ b/sandbox/runner.go @@ -47,6 +47,7 @@ func NewRunnerServer(token, version string, backend Backend) (*RunnerServer, err mux: http.NewServeMux(), } rs.mux.HandleFunc("GET /v1/health", rs.withAuth(rs.handleHealth)) + rs.mux.HandleFunc("GET /v1/tasks", rs.withAuth(rs.handleTasks)) rs.mux.HandleFunc("POST /v1/tasks/{id}/exec", rs.withAuth(rs.handleExec)) rs.mux.HandleFunc("POST /v1/tasks/{id}/kill", rs.withAuth(rs.handleKill)) rs.mux.HandleFunc("DELETE /v1/tasks/{id}", rs.withAuth(rs.handleDelete)) diff --git a/sandbox/sandbox_test.go b/sandbox/sandbox_test.go index 2b1da01e2..ec973e616 100644 --- a/sandbox/sandbox_test.go +++ b/sandbox/sandbox_test.go @@ -515,3 +515,59 @@ func TestDockerBackendRecreatesDeadWorker(t *testing.T) { t.Fatalf("expected 1 worker create call, got %d", workerCreates.Load()) } } + +// TestValidateTaskIDRejectsSurroundingWhitespace: the ID is used unchanged for +// container and pod names, the Kubernetes hash and the workspace directory, so +// " 42" passing as "42" would create a second task with its own pods and +// workspace that the panel (which refuses such ids) never shows. +func TestValidateTaskIDRejectsSurroundingWhitespace(t *testing.T) { + for _, id := range []string{" 42", "42 ", "\t42", "42\n", "42\r", " ", " 42"} { + if err := ValidateTaskID(id); !errors.Is(err, ErrBadRequest) { + t.Errorf("ValidateTaskID(%q) = %v, want ErrBadRequest", id, err) + } + } + for _, id := range []string{"42", "Task_1", "a.b-c"} { + if err := ValidateTaskID(id); err != nil { + t.Errorf("ValidateTaskID(%q) = %v", id, err) + } + } + if kubeTaskHash(" 42") == kubeTaskHash("42") { + t.Fatal("hash ignores whitespace; the rejection above would be moot") + } + + // Through the runner API (path-escaped) the backend never sees such an id. + fb := newFakeBackend() + rs, err := NewRunnerServer("tok", "v", fb) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(rs.Handler()) + defer srv.Close() + for _, p := range []string{"/v1/tasks/%2042/exec", "/v1/tasks/42%20/exec", "/v1/tasks/%0942/kill", "/v1/tasks/42%0A"} { + method := http.MethodPost + if !strings.Contains(p, "/exec") && !strings.Contains(p, "/kill") { + method = http.MethodDelete + } + req, _ := http.NewRequest(method, srv.URL+p, strings.NewReader(`{"argv":["true"]}`)) + req.Header.Set("Authorization", "Bearer tok") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusBadRequest { + t.Errorf("%s %s = %d, want 400", method, p, resp.StatusCode) + } + } + fb.mu.Lock() + seen := len(fb.workers) + len(fb.killed) + len(fb.deleted) + fb.mu.Unlock() + if seen != 0 { + t.Fatalf("backend saw %d calls with whitespace ids", seen) + } + // The client refuses before sending. + cl := NewClient(srv.URL, "tok") + if _, err := cl.Exec(context.Background(), "42 ", ExecRequest{Argv: []string{"true"}}); !errors.Is(err, ErrBadRequest) { + t.Fatalf("client exec = %v", err) + } +} diff --git a/sandbox/status.go b/sandbox/status.go new file mode 100644 index 000000000..9c44e429c --- /dev/null +++ b/sandbox/status.go @@ -0,0 +1,413 @@ +package sandbox + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "sort" + "strings" +) + +// Component states reported when the backing object is absent or going away. +const ( + StateMissing = "Missing" + StateTerminating = "Terminating" +) + +// ComponentStatus describes one sandbox object of a task: the worker or the +// egress proxy (a pod on Kubernetes, a container on Docker). +type ComponentStatus struct { + Name string `json:"name"` + State string `json:"state"` + Ready bool `json:"ready"` + Reason string `json:"reason,omitempty"` + StartedAt string `json:"started_at,omitempty"` + Node string `json:"node,omitempty"` + IP string `json:"ip,omitempty"` +} + +// TaskStatus is the read-only view of one task's sandbox. +type TaskStatus struct { + TaskID string `json:"task_id"` + // Tracked is false for a task whose objects exist but that the runner has + // not adopted (for example pods created after the last Recover). + Tracked bool `json:"tracked"` + Worker ComponentStatus `json:"worker"` + Proxy ComponentStatus `json:"proxy"` + // ProxyIP is the address the worker reaches its proxy on (the Service + // ClusterIP on Kubernetes, the proxy container address on Docker). + ProxyIP string `json:"proxy_ip,omitempty"` + ScopeDomains []string `json:"scope_domains"` + ScopeCIDRs []string `json:"scope_cidrs"` + ScopeHash string `json:"scope_hash,omitempty"` + NetworkPolicies []string `json:"network_policies,omitempty"` + Network string `json:"network,omitempty"` +} + +// TasksResponse is the response body for GET /v1/tasks. +type TasksResponse struct { + Backend string `json:"backend"` + // Supported is false when the runner's backend cannot report status. + Supported bool `json:"supported"` + Namespace string `json:"namespace,omitempty"` + Tasks []TaskStatus `json:"tasks"` +} + +// StatusReporter is an optional Backend capability: a read-only snapshot of the +// sandbox objects the backend manages. It never mutates backend state. +type StatusReporter interface { + Status(ctx context.Context) (TasksResponse, error) +} + +func (rs *RunnerServer) handleTasks(w http.ResponseWriter, r *http.Request) { + sr, ok := rs.backend.(StatusReporter) + if !ok { + writeRunnerJSON(w, http.StatusOK, TasksResponse{Tasks: []TaskStatus{}}) + return + } + res, err := sr.Status(r.Context()) + if err != nil { + rs.writeBackendErr(w, err) + return + } + res.Supported = true + if res.Tasks == nil { + res.Tasks = []TaskStatus{} + } + for i := range res.Tasks { + if res.Tasks[i].ScopeDomains == nil { + res.Tasks[i].ScopeDomains = []string{} + } + if res.Tasks[i].ScopeCIDRs == nil { + res.Tasks[i].ScopeCIDRs = []string{} + } + } + writeRunnerJSON(w, http.StatusOK, res) +} + +// Tasks calls GET /v1/tasks. A runner that predates the endpoint answers 404, +// which surfaces as ErrNotFound. +func (c *Client) Tasks(ctx context.Context) (TasksResponse, error) { + var out TasksResponse + err := c.doJSON(ctx, http.MethodGet, "/v1/tasks", nil, &out) + if out.Tasks == nil { + out.Tasks = []TaskStatus{} + } + return out, err +} + +func splitScopeEnv(v string) []string { + out := []string{} + for _, s := range strings.Split(v, ",") { + if s = strings.TrimSpace(s); s != "" { + out = append(out, s) + } + } + return out +} + +func sortTaskStatuses(tasks []TaskStatus) { + sort.Slice(tasks, func(i, j int) bool { return tasks[i].TaskID < tasks[j].TaskID }) +} + +// kubeStatusPod is the part of a Pod that Status reads. +type kubeStatusPod struct { + Metadata kubeObjectMeta `json:"metadata"` + Spec struct { + NodeName string `json:"nodeName"` + Containers []struct { + Name string `json:"name"` + Env []struct { + Name string `json:"name"` + Value string `json:"value"` + } `json:"env"` + } `json:"containers"` + } `json:"spec"` + Status struct { + Phase string `json:"phase"` + PodIP string `json:"podIP"` + StartTime string `json:"startTime"` + Reason string `json:"reason"` + ContainerStatuses []struct { + Ready bool `json:"ready"` + State struct { + Waiting *struct { + Reason string `json:"reason"` + } `json:"waiting"` + Terminated *struct { + Reason string `json:"reason"` + } `json:"terminated"` + } `json:"state"` + } `json:"containerStatuses"` + } `json:"status"` +} + +func (p *kubeStatusPod) component() ComponentStatus { + cs := ComponentStatus{ + Name: p.Metadata.Name, + State: p.Status.Phase, + Reason: p.Status.Reason, + StartedAt: p.Status.StartTime, + Node: p.Spec.NodeName, + IP: p.Status.PodIP, + } + if cs.State == "" { + cs.State = "Unknown" + } + ready := p.Status.Phase == "Running" && len(p.Status.ContainerStatuses) > 0 + for _, c := range p.Status.ContainerStatuses { + if !c.Ready { + ready = false + } + if c.State.Waiting != nil && c.State.Waiting.Reason != "" { + cs.Reason = c.State.Waiting.Reason + } else if c.State.Terminated != nil && c.State.Terminated.Reason != "" { + cs.Reason = c.State.Terminated.Reason + } + } + if p.Metadata.Deletion != nil { + cs.State = StateTerminating + ready = false + } + cs.Ready = ready + return cs +} + +// Status lists the runner-managed pods once and reports every task that is +// tracked or has a pod. Pods are trusted on the same terms as Recover: the +// managed-by label, a valid task annotation and a matching task hash label. +func (b *KubernetesBackend) Status(ctx context.Context) (TasksResponse, error) { + var list struct { + Items []kubeStatusPod `json:"items"` + } + sel := url.QueryEscape(LabelManagedBy + "=" + ManagedByRunner) + if err := b.do(ctx, http.MethodGet, b.nsPath("pods")+"?labelSelector="+sel, nil, &list); err != nil { + if !errors.Is(err, ErrDockerUnavailable) { + return TasksResponse{}, fmt.Errorf("%w: %v", ErrDockerUnavailable, err) + } + return TasksResponse{}, err + } + byID := map[string]*TaskStatus{} + get := func(tid string) *TaskStatus { + ts := byID[tid] + if ts == nil { + h := kubeTaskHash(tid) + ts = &TaskStatus{ + TaskID: tid, + Worker: ComponentStatus{Name: "artex-w-" + h, State: StateMissing}, + Proxy: ComponentStatus{Name: "artex-p-" + h, State: StateMissing}, + ScopeDomains: []string{}, + ScopeCIDRs: []string{}, + NetworkPolicies: []string{"artex-w-" + h, "artex-p-" + h}, + } + byID[tid] = ts + } + return ts + } + b.mu.Lock() + for tid, kt := range b.tasks { + ts := get(tid) + ts.Tracked = true + ts.ProxyIP = kt.proxyIP + ts.ScopeHash = kt.scopeHash + } + b.mu.Unlock() + for i := range list.Items { + p := &list.Items[i] + if p.Metadata.Labels[LabelManagedBy] != ManagedByRunner { + continue + } + tid := p.Metadata.Annotations[AnnotationTaskID] + if ValidateTaskID(tid) != nil || kubeTaskHash(tid) != p.Metadata.Labels[LabelTaskHash] { + continue + } + comp := p.Metadata.Labels[LabelComponent] + if comp != ComponentWorker && comp != ComponentProxy { + continue + } + ts := get(tid) + if comp == ComponentWorker { + ts.Worker = p.component() + continue + } + ts.Proxy = p.component() + if h := p.Metadata.Annotations[AnnotationScope]; h != "" { + ts.ScopeHash = h + } + for _, c := range p.Spec.Containers { + for _, e := range c.Env { + switch e.Name { + case "ARTEX_SCOPE_DOMAINS": + ts.ScopeDomains = splitScopeEnv(e.Value) + case "ARTEX_SCOPE_CIDRS": + ts.ScopeCIDRs = splitScopeEnv(e.Value) + } + } + } + } + out := TasksResponse{Backend: BackendKubernetes, Namespace: b.cfg.Namespace, Tasks: make([]TaskStatus, 0, len(byID))} + for _, ts := range byID { + out.Tasks = append(out.Tasks, *ts) + } + sortTaskStatuses(out.Tasks) + return out, nil +} + +// dockerInspect is the part of a container inspect that Status reads. +type dockerInspect struct { + Name string `json:"Name"` + State struct { + Status string `json:"Status"` + Running bool `json:"Running"` + StartedAt string `json:"StartedAt"` + Error string `json:"Error"` + } `json:"State"` + Config struct { + Env []string `json:"Env"` + } `json:"Config"` + NetworkSettings struct { + Networks map[string]struct { + IPAddress string `json:"IPAddress"` + } `json:"Networks"` + } `json:"NetworkSettings"` +} + +func (b *DockerBackend) inspectContainer(ctx context.Context, id string) (*dockerInspect, error) { + resp, err := b.dockerDo(ctx, http.MethodGet, "/containers/"+url.PathEscape(id)+"/json", nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) + return nil, fmt.Errorf("inspect container HTTP %d", resp.StatusCode) + } + var in dockerInspect + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&in); err != nil { + return nil, err + } + return &in, nil +} + +// Status lists the runner-managed containers by label and inspects each one. +// Containers are trusted on the same terms as Recover. +func (b *DockerBackend) Status(ctx context.Context) (TasksResponse, error) { + filters, _ := json.Marshal(map[string][]string{ + "label": {LabelManagedBy + "=" + ManagedByRunner}, + }) + resp, err := b.dockerDo(ctx, http.MethodGet, "/containers/json?all=true&filters="+url.QueryEscape(string(filters)), nil) + if err != nil { + return TasksResponse{}, err + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return TasksResponse{}, fmt.Errorf("%w: list containers HTTP %d: %s", ErrDockerUnavailable, resp.StatusCode, string(raw)) + } + var list []struct { + ID string `json:"Id"` + Names []string `json:"Names"` + Labels map[string]string `json:"Labels"` + State string `json:"State"` + } + if err := json.NewDecoder(resp.Body).Decode(&list); err != nil { + return TasksResponse{}, err + } + byID := map[string]*TaskStatus{} + get := func(tid string) *TaskStatus { + ts := byID[tid] + if ts == nil { + ts = &TaskStatus{ + TaskID: tid, + Worker: ComponentStatus{Name: "artex-worker-" + tid, State: StateMissing}, + Proxy: ComponentStatus{Name: "artex-egress-" + tid, State: StateMissing}, + ScopeDomains: []string{}, + ScopeCIDRs: []string{}, + Network: b.cfg.TaskNetPrefix + tid, + } + byID[tid] = ts + } + return ts + } + b.mu.Lock() + for tid := range b.tasks { + get(tid).Tracked = true + } + b.mu.Unlock() + for _, c := range list { + if c.Labels[LabelManagedBy] != ManagedByRunner { + continue + } + tid := c.Labels[LabelTask] + if ValidateTaskID(tid) != nil { + continue + } + comp := c.Labels[LabelComponent] + if comp != ComponentWorker && comp != ComponentProxy { + continue + } + ts := get(tid) + cs := ComponentStatus{State: c.State} + if len(c.Names) > 0 { + cs.Name = strings.TrimPrefix(c.Names[0], "/") + } + in, ierr := b.inspectContainer(ctx, c.ID) + if ierr == nil { + if cs.Name == "" { + cs.Name = strings.TrimPrefix(in.Name, "/") + } + if in.State.Status != "" { + cs.State = in.State.Status + } + cs.Ready = in.State.Running + cs.Reason = in.State.Error + if in.State.Running { + cs.StartedAt = in.State.StartedAt + } + if n, ok := in.NetworkSettings.Networks[ts.Network]; ok { + cs.IP = n.IPAddress + } + } else { + cs.Ready = c.State == "running" + cs.Reason = "inspect failed" + } + if cs.State == "" { + cs.State = "unknown" + } + if comp == ComponentWorker { + if cs.Name == "" { + cs.Name = ts.Worker.Name + } + ts.Worker = cs + continue + } + if cs.Name == "" { + cs.Name = ts.Proxy.Name + } + ts.Proxy = cs + ts.ProxyIP = cs.IP + if ierr != nil { + continue + } + for _, kv := range in.Config.Env { + k, v, _ := strings.Cut(kv, "=") + switch k { + case "ARTEX_SCOPE_DOMAINS": + ts.ScopeDomains = splitScopeEnv(v) + case "ARTEX_SCOPE_CIDRS": + ts.ScopeCIDRs = splitScopeEnv(v) + } + } + ts.ScopeHash = kubeTaskHash(scopeFingerprint(ts.ScopeDomains, ts.ScopeCIDRs))[:8] + } + out := TasksResponse{Backend: BackendDocker, Tasks: make([]TaskStatus, 0, len(byID))} + for _, ts := range byID { + out.Tasks = append(out.Tasks, *ts) + } + sortTaskStatuses(out.Tasks) + return out, nil +} diff --git a/sandbox/status_test.go b/sandbox/status_test.go new file mode 100644 index 000000000..5e52a32a3 --- /dev/null +++ b/sandbox/status_test.go @@ -0,0 +1,651 @@ +package sandbox + +import ( + "context" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "path/filepath" + "reflect" + "strings" + "sync" + "sync/atomic" + "testing" +) + +// statusBackend is a fakeBackend that also reports status. +type statusBackend struct { + *fakeBackend + res TasksResponse + err error + calls atomic.Int32 +} + +func (s *statusBackend) Status(context.Context) (TasksResponse, error) { + s.calls.Add(1) + return s.res, s.err +} + +func rawGet(t *testing.T, url, token string) (int, []byte) { + t.Helper() + req, _ := http.NewRequest(http.MethodGet, url, nil) + if token != "" { + req.Header.Set("Authorization", token) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + return resp.StatusCode, raw +} + +func TestRunnerTasksRequiresAuth(t *testing.T) { + sb := &statusBackend{fakeBackend: newFakeBackend(), res: TasksResponse{Backend: BackendDocker}} + rs, err := NewRunnerServer("tok", "v", sb) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(rs.Handler()) + defer srv.Close() + + for name, hdr := range map[string]string{ + "none": "", + "wrong": "Bearer nope", + "basic": "Basic dG9r", + "prefix-only": "Bearer ", + "token-prefix": "Bearer to", + "token-suffix": "Bearer tok2", + } { + code, raw := rawGet(t, srv.URL+"/v1/tasks", hdr) + if code != http.StatusUnauthorized { + t.Fatalf("%s: code = %d body=%s", name, code, raw) + } + if strings.Contains(string(raw), "tasks") { + t.Fatalf("%s: unauthorized body leaks task data: %s", name, raw) + } + } + if n := sb.calls.Load(); n != 0 { + t.Fatalf("backend Status called %d times without valid auth", n) + } + for _, c := range []*Client{NewClient(srv.URL, "wrong"), NewClient(srv.URL, "")} { + if _, err := c.Tasks(context.Background()); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("client Tasks err = %v, want ErrUnauthorized", err) + } + } + // The endpoint is read-only: other methods on the collection are not routed. + for _, m := range []string{http.MethodPost, http.MethodDelete, http.MethodPut} { + req, _ := http.NewRequest(m, srv.URL+"/v1/tasks", nil) + req.Header.Set("Authorization", "Bearer tok") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusMethodNotAllowed && resp.StatusCode != http.StatusNotFound { + t.Fatalf("%s /v1/tasks = %d", m, resp.StatusCode) + } + } +} + +func TestRunnerTasksShapeAndClient(t *testing.T) { + sb := &statusBackend{fakeBackend: newFakeBackend(), res: TasksResponse{ + Backend: BackendKubernetes, + Namespace: "artex", + Tasks: []TaskStatus{{ + TaskID: "7", + Tracked: true, + Worker: ComponentStatus{Name: "artex-w-x", State: "Running", Ready: true, StartedAt: "2026-01-02T03:04:05Z", Node: "n1", IP: "10.42.0.7"}, + Proxy: ComponentStatus{Name: "artex-p-x", State: "Pending", Reason: "ContainerCreating"}, + ProxyIP: "10.43.0.9", + ScopeDomains: []string{"example.com"}, + ScopeHash: "abcd1234", + NetworkPolicies: []string{"artex-w-x", "artex-p-x"}, + }}, + }} + rs, _ := NewRunnerServer("tok", "v", sb) + srv := httptest.NewServer(rs.Handler()) + defer srv.Close() + + code, raw := rawGet(t, srv.URL+"/v1/tasks", "Bearer tok") + if code != http.StatusOK { + t.Fatalf("code = %d body=%s", code, raw) + } + var wire map[string]any + if err := json.Unmarshal(raw, &wire); err != nil { + t.Fatal(err) + } + if wire["backend"] != "kubernetes" || wire["supported"] != true || wire["namespace"] != "artex" { + t.Fatalf("wire = %s", raw) + } + task := wire["tasks"].([]any)[0].(map[string]any) + for _, k := range []string{"task_id", "tracked", "worker", "proxy", "proxy_ip", "scope_domains", "scope_cidrs", "scope_hash", "network_policies"} { + if _, ok := task[k]; !ok { + t.Fatalf("task is missing %q: %s", k, raw) + } + } + // A nil scope list is sent as [] so a client can always iterate it. + if c, ok := task["scope_cidrs"].([]any); !ok || len(c) != 0 { + t.Fatalf("scope_cidrs = %#v, want []", task["scope_cidrs"]) + } + worker := task["worker"].(map[string]any) + for _, k := range []string{"name", "state", "ready", "started_at", "node", "ip"} { + if _, ok := worker[k]; !ok { + t.Fatalf("worker is missing %q: %s", k, raw) + } + } + + got, err := NewClient(srv.URL, "tok").Tasks(context.Background()) + if err != nil { + t.Fatal(err) + } + want := sb.res + want.Supported = true + want.Tasks[0].ScopeCIDRs = []string{} + if !reflect.DeepEqual(got, want) { + t.Fatalf("client Tasks\n got %+v\nwant %+v", got, want) + } + + // Backend failure -> 409, mapped to ErrDockerUnavailable by the client. + sb.err = ErrDockerUnavailable + if _, err := NewClient(srv.URL, "tok").Tasks(context.Background()); !errors.Is(err, ErrDockerUnavailable) { + t.Fatalf("Tasks with backend down = %v", err) + } + sb.err = errors.New("boom") + if _, err := NewClient(srv.URL, "tok").Tasks(context.Background()); !errors.Is(err, ErrRunnerUnavailable) { + t.Fatalf("Tasks with backend error = %v", err) + } +} + +func TestRunnerTasksWithoutStatusReporter(t *testing.T) { + rs, _ := NewRunnerServer("tok", "v", newFakeBackend()) + srv := httptest.NewServer(rs.Handler()) + defer srv.Close() + code, raw := rawGet(t, srv.URL+"/v1/tasks", "Bearer tok") + if code != http.StatusOK || !strings.Contains(string(raw), `"tasks":[]`) || !strings.Contains(string(raw), `"supported":false`) { + t.Fatalf("code = %d body = %s", code, raw) + } + got, err := NewClient(srv.URL, "tok").Tasks(context.Background()) + if err != nil || got.Supported || got.Tasks == nil || len(got.Tasks) != 0 { + t.Fatalf("Tasks = %+v, %v", got, err) + } +} + +func TestClientTasksEdgeCases(t *testing.T) { + // A runner that predates the endpoint answers 404. + old := httptest.NewServer(http.NotFoundHandler()) + defer old.Close() + got, err := NewClient(old.URL, "tok").Tasks(context.Background()) + if !errors.Is(err, ErrNotFound) || got.Tasks == nil { + t.Fatalf("old runner: %+v, %v", got, err) + } + // Unreachable runner. + old.Close() + if _, err := NewClient(old.URL, "tok").Tasks(context.Background()); !errors.Is(err, ErrRunnerUnavailable) { + t.Fatalf("unreachable runner = %v", err) + } + if _, err := NewClient("", "tok").Tasks(context.Background()); !errors.Is(err, ErrRunnerUnavailable) { + t.Fatalf("empty URL = %v", err) + } + var nilClient *Client + if _, err := nilClient.Tasks(context.Background()); !errors.Is(err, ErrRunnerUnavailable) { + t.Fatalf("nil client = %v", err) + } + // Garbage body. + bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("")) })) + defer bad.Close() + if _, err := NewClient(bad.URL, "tok").Tasks(context.Background()); err == nil { + t.Fatal("garbage body decoded without error") + } +} + +func findTask(t *testing.T, res TasksResponse, id string) TaskStatus { + t.Helper() + for _, ts := range res.Tasks { + if ts.TaskID == id { + return ts + } + } + t.Fatalf("task %q not in %+v", id, res.Tasks) + return TaskStatus{} +} + +func TestKubeStatus(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + + // No tasks: an empty, non-nil list. + res, err := b.Status(ctx) + if err != nil || res.Backend != BackendKubernetes || res.Namespace != "artex" || res.Tasks == nil || len(res.Tasks) != 0 { + t.Fatalf("empty Status = %+v, %v", res, err) + } + + reqA := execReq("true") + reqA.ScopeDomains = []string{"example.com", "api.example.com"} + reqA.ScopeCIDRs = []string{"203.0.113.0/24"} + for id, req := range map[string]ExecRequest{"alpha": reqA, "beta": execReq("true"), "gamma": execReq("true"), "Delta.4": execReq("true")} { + if _, err := b.Exec(ctx, id, req); err != nil { + t.Fatalf("exec %s: %v", id, err) + } + } + hA, hB, hG := kubeTaskHash("alpha"), kubeTaskHash("beta"), kubeTaskHash("gamma") + + f.mu.Lock() + // alpha: server-populated fields on both pods. + wa := f.objs["pods"]["artex-w-"+hA] + wa["spec"].(map[string]any)["nodeName"] = "node-1" + wa["status"].(map[string]any)["startTime"] = "2026-11-30T10:00:00Z" + wa["status"].(map[string]any)["podIP"] = "10.42.0.21" + pa := f.objs["pods"]["artex-p-"+hA] + pa["spec"].(map[string]any)["nodeName"] = "node-2" + pa["status"].(map[string]any)["podIP"] = "10.42.1.5" + // beta: the proxy pod is gone. + delete(f.objs["pods"], "artex-p-"+hB) + // gamma: the worker is pending on an image pull, the proxy is terminating. + f.objs["pods"]["artex-w-"+hG]["status"] = map[string]any{"phase": "Pending", "containerStatuses": []any{map[string]any{ + "ready": false, "state": map[string]any{"waiting": map[string]any{"reason": "ImagePullBackOff", "message": "secret-registry-detail"}}, + }}} + f.objs["pods"]["artex-p-"+hG]["metadata"].(map[string]any)["deletionTimestamp"] = "2026-11-30T10:05:00Z" + // Foreign pods: forged hash, invalid task id, unknown component, unlabelled, + // and a managed-by label with a different value. + f.objs["pods"]["artex-w-forged"] = map[string]any{"metadata": map[string]any{"name": "artex-w-forged", + "labels": map[string]any{LabelManagedBy: ManagedByRunner, LabelComponent: ComponentWorker, LabelTaskHash: "0000000000000000"}, + "annotations": map[string]any{AnnotationTaskID: "victim"}}, "status": map[string]any{"phase": "Running"}} + f.objs["pods"]["artex-w-bad"] = map[string]any{"metadata": map[string]any{"name": "artex-w-bad", + "labels": map[string]any{LabelManagedBy: ManagedByRunner, LabelComponent: ComponentWorker, LabelTaskHash: kubeTaskHash("../x")}, + "annotations": map[string]any{AnnotationTaskID: "../x"}}} + f.objs["pods"]["artex-x-odd"] = map[string]any{"metadata": map[string]any{"name": "artex-x-odd", + "labels": map[string]any{LabelManagedBy: ManagedByRunner, LabelComponent: "sidecar", LabelTaskHash: kubeTaskHash("odd")}, + "annotations": map[string]any{AnnotationTaskID: "odd"}}} + f.objs["pods"]["other"] = map[string]any{"metadata": map[string]any{"name": "other", "labels": map[string]any{"app": "x"}}} + f.objs["pods"]["imposter"] = map[string]any{"metadata": map[string]any{"name": "imposter", + "labels": map[string]any{LabelManagedBy: "someone-else", LabelComponent: ComponentWorker, LabelTaskHash: kubeTaskHash("imp")}, + "annotations": map[string]any{AnnotationTaskID: "imp"}}} + f.mu.Unlock() + + mark := len(f.opsSnapshot()) + res, err = b.Status(ctx) + if err != nil { + t.Fatal(err) + } + if ops := f.opsSnapshot()[mark:]; len(ops) != 0 { + t.Fatalf("Status mutated the cluster: %v", ops) + } + var ids []string + for _, ts := range res.Tasks { + ids = append(ids, ts.TaskID) + } + if want := []string{"Delta.4", "alpha", "beta", "gamma"}; !reflect.DeepEqual(ids, want) { + t.Fatalf("task ids = %v, want %v (sorted, foreign pods ignored)", ids, want) + } + + a := findTask(t, res, "alpha") + if !a.Tracked || a.ProxyIP == "" || net.ParseIP(a.ProxyIP) == nil || len(a.ScopeHash) != 8 { + t.Fatalf("alpha = %+v", a) + } + if want := (ComponentStatus{Name: "artex-w-" + hA, State: "Running", Ready: true, StartedAt: "2026-11-30T10:00:00Z", Node: "node-1", IP: "10.42.0.21"}); a.Worker != want { + t.Fatalf("alpha worker = %+v, want %+v", a.Worker, want) + } + if want := (ComponentStatus{Name: "artex-p-" + hA, State: "Running", Ready: true, Node: "node-2", IP: "10.42.1.5"}); a.Proxy != want { + t.Fatalf("alpha proxy = %+v, want %+v", a.Proxy, want) + } + if !reflect.DeepEqual(a.ScopeDomains, []string{"example.com", "api.example.com"}) || !reflect.DeepEqual(a.ScopeCIDRs, []string{"203.0.113.0/24"}) { + t.Fatalf("alpha scope = %v %v", a.ScopeDomains, a.ScopeCIDRs) + } + if !reflect.DeepEqual(a.NetworkPolicies, []string{"artex-w-" + hA, "artex-p-" + hA}) { + t.Fatalf("alpha policies = %v", a.NetworkPolicies) + } + for _, name := range a.NetworkPolicies { + if f.obj("networkpolicies", name) == nil { + t.Fatalf("reported policy %s does not exist", name) + } + } + + be := findTask(t, res, "beta") + if be.Worker.State != "Running" || !be.Worker.Ready { + t.Fatalf("beta worker = %+v", be.Worker) + } + if want := (ComponentStatus{Name: "artex-p-" + hB, State: StateMissing}); be.Proxy != want { + t.Fatalf("beta proxy = %+v, want %+v", be.Proxy, want) + } + if be.ScopeDomains == nil || be.ScopeCIDRs == nil || len(be.ScopeDomains) != 0 { + t.Fatalf("beta scope = %#v %#v", be.ScopeDomains, be.ScopeCIDRs) + } + + g := findTask(t, res, "gamma") + if g.Worker.State != "Pending" || g.Worker.Ready || g.Worker.Reason != "ImagePullBackOff" { + t.Fatalf("gamma worker = %+v", g.Worker) + } + if g.Proxy.State != StateTerminating || g.Proxy.Ready { + t.Fatalf("gamma proxy = %+v", g.Proxy) + } + raw, _ := json.Marshal(res) + if strings.Contains(string(raw), "secret-registry-detail") { + t.Fatal("Status leaked a container waiting message") + } + + // Not ready while running. + f.setPodPhase("artex-w-"+hA, "Running", false) + res, _ = b.Status(ctx) + if w := findTask(t, res, "alpha").Worker; w.State != "Running" || w.Ready { + t.Fatalf("unready worker = %+v", w) + } + + // A fresh runner (nothing tracked) still reports pods it has not adopted, + // and scope comes from the proxy pod rather than runner memory. + fresh := newTestKubeBackend(t, f, srv) + res, err = fresh.Status(ctx) + if err != nil || len(res.Tasks) != 4 { + t.Fatalf("fresh Status = %+v, %v", res, err) + } + fa := findTask(t, res, "alpha") + if fa.Tracked || fa.ProxyIP != "" || !reflect.DeepEqual(fa.ScopeDomains, a.ScopeDomains) || fa.ScopeHash != a.ScopeHash { + t.Fatalf("fresh alpha = %+v", fa) + } + if fresh.WorkerCount() != 0 { + t.Fatal("Status adopted tasks") + } + + // A tracked task whose pods are all gone is still listed. + f.mu.Lock() + delete(f.objs["pods"], "artex-w-"+hB) + f.mu.Unlock() + res, _ = b.Status(ctx) + if be := findTask(t, res, "beta"); be.Worker.State != StateMissing || be.Proxy.State != StateMissing || !be.Tracked { + t.Fatalf("beta without pods = %+v", be) + } + + // Delete removes it from the status. + if err := b.Delete(ctx, "beta"); err != nil { + t.Fatal(err) + } + res, _ = b.Status(ctx) + if len(res.Tasks) != 3 { + t.Fatalf("after delete: %+v", res.Tasks) + } +} + +func TestKubeStatusUsesOnePodList(t *testing.T) { + f, api := newFakeKubeAPI(t) + var mu sync.Mutex + var reqs []string + counting := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + reqs = append(reqs, r.Method+" "+r.URL.Path+"?"+r.URL.RawQuery) + mu.Unlock() + f.serve(w, r) + })) + defer counting.Close() + _ = api + b := newTestKubeBackend(t, f, counting) + ctx := context.Background() + for _, id := range []string{"a", "b", "c"} { + if _, err := b.Exec(ctx, id, execReq("true")); err != nil { + t.Fatal(err) + } + } + mu.Lock() + reqs = nil + mu.Unlock() + if _, err := b.Status(ctx); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if len(reqs) != 1 || !strings.HasPrefix(reqs[0], "GET /api/v1/namespaces/artex/pods?") || !strings.Contains(reqs[0], "artex.managed_by%3Dartex-runner") { + t.Fatalf("Status requests = %v, want one label-selected pod list", reqs) + } +} + +func TestKubeStatusAPIFailure(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + f.failPing.Store(true) + if _, err := b.Status(context.Background()); !errors.Is(err, ErrDockerUnavailable) { + t.Fatalf("Status with RBAC denied = %v, want ErrDockerUnavailable", err) + } + rs, _ := NewRunnerServer("tok", "v", b) + h := httptest.NewServer(rs.Handler()) + defer h.Close() + if code, _ := rawGet(t, h.URL+"/v1/tasks", "Bearer tok"); code != http.StatusConflict { + t.Fatalf("/v1/tasks with API denied = %d", code) + } + f.failPing.Store(false) + srv.Close() + if _, err := b.Status(context.Background()); !errors.Is(err, ErrDockerUnavailable) { + t.Fatalf("Status with API down = %v", err) + } +} + +func TestKubeStatusOverRunnerHTTP(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + rs, _ := NewRunnerServer("tok", "v", b) + h := httptest.NewServer(rs.Handler()) + defer h.Close() + c := NewClient(h.URL, "tok") + ctx := context.Background() + req := ExecRequest{Argv: []string{"true"}, ScopeDomains: []string{"example.org"}} + if _, err := c.Exec(ctx, "42", req); err != nil { + t.Fatal(err) + } + res, err := c.Tasks(ctx) + if err != nil || !res.Supported || res.Backend != BackendKubernetes || len(res.Tasks) != 1 { + t.Fatalf("Tasks = %+v, %v", res, err) + } + ts := res.Tasks[0] + if ts.TaskID != "42" || !ts.Worker.Ready || !ts.Proxy.Ready || !reflect.DeepEqual(ts.ScopeDomains, []string{"example.org"}) { + t.Fatalf("task = %+v", ts) + } +} + +func TestKubeStatusConcurrentWithExec(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + var wg sync.WaitGroup + for i := range 4 { + wg.Add(2) + go func() { + defer wg.Done() + if _, err := b.Exec(ctx, "t"+string(rune('a'+i)), execReq("true")); err != nil { + t.Error(err) + } + }() + go func() { + defer wg.Done() + for range 5 { + if _, err := b.Status(ctx); err != nil { + t.Error(err) + } + } + }() + } + wg.Wait() + res, err := b.Status(ctx) + if err != nil || len(res.Tasks) != 4 { + t.Fatalf("Status = %+v, %v", res, err) + } +} + +// fakeDockerStatus serves the container list and inspect calls Status makes. +type fakeDockerStatus struct { + mu sync.Mutex + list []map[string]any + inspect map[string]map[string]any + listCode int + listFilters []string + other []string +} + +func (f *fakeDockerStatus) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + p := r.URL.Path + switch { + case r.Method == http.MethodGet && p == "/containers/json": + f.listFilters = append(f.listFilters, r.URL.Query().Get("filters")+"|all="+r.URL.Query().Get("all")) + if f.listCode != 0 { + w.WriteHeader(f.listCode) + return + } + _ = json.NewEncoder(w).Encode(f.list) + case r.Method == http.MethodGet && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/json"): + id := strings.TrimSuffix(strings.TrimPrefix(p, "/containers/"), "/json") + in, ok := f.inspect[id] + if !ok { + w.WriteHeader(http.StatusNotFound) + return + } + _ = json.NewEncoder(w).Encode(in) + default: + f.other = append(f.other, r.Method+" "+p) + w.WriteHeader(http.StatusTeapot) + } +} + +func newFakeDockerStatusBackend(t *testing.T, f *fakeDockerStatus) *DockerBackend { + t.Helper() + sock := filepath.Join(t.TempDir(), "docker.sock") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: f} + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { + _ = srv.Close() + _ = ln.Close() + }) + return NewDockerBackend(DockerConfig{SocketPath: sock}) +} + +func dockerLabels(task, component string) map[string]string { + return map[string]string{LabelManagedBy: ManagedByRunner, LabelTask: task, LabelComponent: component} +} + +func TestDockerStatus(t *testing.T) { + f := &fakeDockerStatus{ + list: []map[string]any{ + {"Id": "w1", "Names": []string{"/artex-worker-1"}, "State": "running", "Labels": dockerLabels("1", ComponentWorker)}, + {"Id": "p1", "Names": []string{"/artex-egress-1"}, "State": "running", "Labels": dockerLabels("1", ComponentProxy)}, + // Task 2: exited worker, no proxy. + {"Id": "w2", "Names": []string{"/artex-worker-2"}, "State": "exited", "Labels": dockerLabels("2", ComponentWorker)}, + // Task 3: inspect fails for the proxy. + {"Id": "p3", "Names": []string{"/artex-egress-3"}, "State": "running", "Labels": dockerLabels("3", ComponentProxy)}, + // Foreign: wrong managed-by, invalid task id, unknown component. + {"Id": "x1", "Names": []string{"/x1"}, "State": "running", "Labels": map[string]string{LabelManagedBy: "other", LabelTask: "9", LabelComponent: ComponentWorker}}, + {"Id": "x2", "Names": []string{"/x2"}, "State": "running", "Labels": dockerLabels("../etc", ComponentWorker)}, + {"Id": "x3", "Names": []string{"/x3"}, "State": "running", "Labels": dockerLabels("8", "sidecar")}, + {"Id": "x4", "Names": []string{"/x4"}, "State": "running", "Labels": map[string]string{}}, + }, + inspect: map[string]map[string]any{ + "w1": {"Name": "/artex-worker-1", + "State": map[string]any{"Status": "running", "Running": true, "StartedAt": "2026-11-30T09:00:00.5Z"}, + "Config": map[string]any{"Env": []string{"HOME=/home/exec"}}, + "NetworkSettings": map[string]any{"Networks": map[string]any{"artex-task-1": map[string]any{"IPAddress": "172.30.0.3"}}}}, + "p1": {"Name": "/artex-egress-1", + "State": map[string]any{"Status": "running", "Running": true, "StartedAt": "2026-11-30T08:59:00Z"}, + "Config": map[string]any{"Env": []string{"ARTEX_TASK_ID=1", "ARTEX_SCOPE_DOMAINS=example.com, b.example.com,", "ARTEX_SCOPE_CIDRS=198.51.100.0/24", "ARTEX_PROXY_PORT=3128"}}, + "NetworkSettings": map[string]any{"Networks": map[string]any{ + "artex-task-1": map[string]any{"IPAddress": "172.30.0.2"}, + "egress-net": map[string]any{"IPAddress": "172.31.0.9"}, + }}}, + "w2": {"Name": "/artex-worker-2", + "State": map[string]any{"Status": "exited", "Running": false, "StartedAt": "2026-11-29T00:00:00Z", "Error": "oom"}, + "Config": map[string]any{}}, + }, + } + b := newFakeDockerStatusBackend(t, f) + seedTask(b, "1", "w1", "p1", "artex-task-1") + seedTask(b, "ghost", "", "", "artex-task-ghost") + + res, err := b.Status(context.Background()) + if err != nil { + t.Fatal(err) + } + if res.Backend != BackendDocker || res.Namespace != "" { + t.Fatalf("res = %+v", res) + } + var ids []string + for _, ts := range res.Tasks { + ids = append(ids, ts.TaskID) + } + if want := []string{"1", "2", "3", "ghost"}; !reflect.DeepEqual(ids, want) { + t.Fatalf("ids = %v, want %v", ids, want) + } + + t1 := findTask(t, res, "1") + if want := (ComponentStatus{Name: "artex-worker-1", State: "running", Ready: true, StartedAt: "2026-11-30T09:00:00.5Z", IP: "172.30.0.3"}); t1.Worker != want { + t.Fatalf("worker 1 = %+v, want %+v", t1.Worker, want) + } + if want := (ComponentStatus{Name: "artex-egress-1", State: "running", Ready: true, StartedAt: "2026-11-30T08:59:00Z", IP: "172.30.0.2"}); t1.Proxy != want { + t.Fatalf("proxy 1 = %+v, want %+v", t1.Proxy, want) + } + if !t1.Tracked || t1.ProxyIP != "172.30.0.2" || t1.Network != "artex-task-1" || len(t1.NetworkPolicies) != 0 { + t.Fatalf("task 1 = %+v", t1) + } + if !reflect.DeepEqual(t1.ScopeDomains, []string{"example.com", "b.example.com"}) || !reflect.DeepEqual(t1.ScopeCIDRs, []string{"198.51.100.0/24"}) || len(t1.ScopeHash) != 8 { + t.Fatalf("task 1 scope = %v %v %q", t1.ScopeDomains, t1.ScopeCIDRs, t1.ScopeHash) + } + + t2 := findTask(t, res, "2") + if want := (ComponentStatus{Name: "artex-worker-2", State: "exited", Reason: "oom"}); t2.Worker != want { + t.Fatalf("worker 2 = %+v, want %+v", t2.Worker, want) + } + if want := (ComponentStatus{Name: "artex-egress-2", State: StateMissing}); t2.Proxy != want || t2.Tracked { + t.Fatalf("task 2 = %+v", t2) + } + + t3 := findTask(t, res, "3") + if t3.Proxy.Name != "artex-egress-3" || t3.Proxy.State != "running" || !t3.Proxy.Ready || t3.Proxy.Reason != "inspect failed" || t3.Worker.State != StateMissing { + t.Fatalf("task 3 = %+v", t3) + } + if t3.ScopeDomains == nil || len(t3.ScopeDomains) != 0 || t3.ScopeHash != "" { + t.Fatalf("task 3 scope = %#v %q", t3.ScopeDomains, t3.ScopeHash) + } + + gh := findTask(t, res, "ghost") + if !gh.Tracked || gh.Worker.State != StateMissing || gh.Proxy.State != StateMissing { + t.Fatalf("ghost = %+v", gh) + } + + f.mu.Lock() + defer f.mu.Unlock() + if len(f.other) != 0 { + t.Fatalf("Status made non-read calls: %v", f.other) + } + if len(f.listFilters) != 1 || !strings.Contains(f.listFilters[0], `"artex.managed_by=artex-runner"`) || !strings.HasSuffix(f.listFilters[0], "|all=true") { + t.Fatalf("list filters = %v", f.listFilters) + } +} + +func TestDockerStatusEmptyAndFailures(t *testing.T) { + f := &fakeDockerStatus{list: []map[string]any{}} + b := newFakeDockerStatusBackend(t, f) + res, err := b.Status(context.Background()) + if err != nil || res.Tasks == nil || len(res.Tasks) != 0 { + t.Fatalf("empty = %+v, %v", res, err) + } + f.mu.Lock() + f.listCode = http.StatusInternalServerError + f.mu.Unlock() + if _, err := b.Status(context.Background()); !errors.Is(err, ErrDockerUnavailable) { + t.Fatalf("list 500 = %v", err) + } + gone := NewDockerBackend(DockerConfig{SocketPath: filepath.Join(t.TempDir(), "nope.sock")}) + if _, err := gone.Status(context.Background()); !errors.Is(err, ErrDockerUnavailable) { + t.Fatalf("no socket = %v", err) + } +} + +// Both backends must satisfy the optional interface. +var ( + _ StatusReporter = (*KubernetesBackend)(nil) + _ StatusReporter = (*DockerBackend)(nil) +) diff --git a/sandbox/validate.go b/sandbox/validate.go index 9061b7702..3d13515cc 100644 --- a/sandbox/validate.go +++ b/sandbox/validate.go @@ -13,8 +13,10 @@ var ( ) // ValidateTaskID verifies a task ID is safe for Docker names, labels, and workspace paths. +// The ID is checked exactly as given, never trimmed: callers use it unchanged for +// object names, hashes and directories, so " 42" must not pass as "42" (it would +// be a different task with its own pods and workspace, invisible to the panel). func ValidateTaskID(id string) error { - id = strings.TrimSpace(id) if id == "" || !taskIDRE.MatchString(id) || strings.Contains(id, "..") { return fmt.Errorf("%w: invalid task id %q", ErrBadRequest, id) } diff --git a/server/sandbox_overview.go b/server/sandbox_overview.go new file mode 100644 index 000000000..d8e473edc --- /dev/null +++ b/server/sandbox_overview.go @@ -0,0 +1,314 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "syscall" + "time" + "unicode/utf8" + + "github.com/Autumn-27/artex/sandbox" +) + +// Bounds for GET /api/sandbox/overview. The audit files are written by the +// per-task proxies and grow without limit, so every read is a capped tail. +const ( + sandboxOverviewTimeout = 5 * time.Second + sandboxOverviewMaxTasks = 200 + sandboxEgressTailBytes = 256 << 10 + sandboxEgressMaxEntries = 50 + sandboxEgressMaxLineBytes = 4096 + sandboxEgressMaxField = 255 + sandboxEgressFile = "egress.jsonl" + sandboxAuditDirName = "egress-audit" +) + +// sandboxTasksLister is the optional runner-client capability behind the +// overview. *sandbox.Client implements it. +type sandboxTasksLister interface { + Tasks(ctx context.Context) (sandbox.TasksResponse, error) +} + +type sandboxRunnerDTO struct { + Configured bool `json:"configured"` + OK bool `json:"ok"` + BackendOK bool `json:"backend_ok"` + Workers int `json:"workers"` + Version string `json:"version,omitempty"` + Error string `json:"error,omitempty"` +} + +type sandboxEgressEntryDTO struct { + TS string `json:"ts"` + Host string `json:"host"` + Port int `json:"port"` + ResolvedIP string `json:"resolved_ip,omitempty"` + Protocol string `json:"protocol,omitempty"` + Decision string `json:"decision"` + Bytes int64 `json:"bytes"` +} + +// sandboxEgressDTO is the tail of one task's egress audit log. Allow and Deny +// count the connections in the tail that was read, not the whole file: +// Truncated says the file is longer than that tail. +type sandboxEgressDTO struct { + Available bool `json:"available"` + Allow int `json:"allow"` + Deny int `json:"deny"` + Truncated bool `json:"truncated"` + Entries []sandboxEgressEntryDTO `json:"entries"` +} + +type sandboxTaskDTO struct { + sandbox.TaskStatus + TaskName string `json:"task_name,omitempty"` + TaskState string `json:"task_status,omitempty"` + Egress sandboxEgressDTO `json:"egress"` +} + +type sandboxOverviewDTO struct { + Mode string `json:"mode"` + Runner sandboxRunnerDTO `json:"runner"` + Backend string `json:"backend,omitempty"` + Namespace string `json:"namespace,omitempty"` + StatusSupported bool `json:"status_supported"` + StatusError string `json:"status_error,omitempty"` + Tasks []sandboxTaskDTO `json:"tasks"` + TasksTruncated bool `json:"tasks_truncated"` + GeneratedAt string `json:"generated_at"` +} + +// sandboxErrorCode maps a runner client error to a stable code. The raw error +// is not sent: it can carry the runner URL and response bodies. +func sandboxErrorCode(err error) string { + switch { + case err == nil: + return "" + case errors.Is(err, sandbox.ErrUnauthorized): + return "unauthorized" + case errors.Is(err, sandbox.ErrDockerUnavailable): + return "backend_unavailable" + case errors.Is(err, sandbox.ErrNotFound): + return "unsupported" + case errors.Is(err, context.DeadlineExceeded): + return "timeout" + default: + return "unreachable" + } +} + +// GET /api/sandbox/overview — live view of the execution sandbox for the UI. +// Everything about the cluster comes from the runner API: the panel holds no +// Kubernetes or Docker credentials. It always answers 200 with whatever could +// be gathered, so the page can show a degraded state. +func (s *Server) sandboxOverview(w http.ResponseWriter, r *http.Request) { + mode := s.sandboxMode + if mode == "" { + mode = sandbox.ModeOff + } + out := sandboxOverviewDTO{ + Mode: mode, + Tasks: []sandboxTaskDTO{}, + GeneratedAt: time.Now().UTC().Format(time.RFC3339), + } + if mode != sandbox.ModeRequired || s.sandboxClient == nil { + writeJSON(w, 200, out) + return + } + out.Runner.Configured = true + ctx, cancel := context.WithTimeout(r.Context(), sandboxOverviewTimeout) + defer cancel() + + h, err := s.sandboxClient.Health(ctx) + out.Runner.Workers = h.Workers + out.Runner.Version = h.Version + out.Runner.BackendOK = h.Docker + out.Runner.OK = err == nil && h.OK + out.Runner.Error = sandboxErrorCode(err) + // A 409 from /v1/health means the runner answered but its backend is down: + // its task list would fail the same way. Anything else unreachable is final. + if err != nil && !errors.Is(err, sandbox.ErrDockerUnavailable) { + writeJSON(w, 200, out) + return + } + + lister, ok := s.sandboxClient.(sandboxTasksLister) + if !ok { + out.StatusError = "unsupported" + writeJSON(w, 200, out) + return + } + res, err := lister.Tasks(ctx) + if err != nil { + out.StatusError = sandboxErrorCode(err) + writeJSON(w, 200, out) + return + } + out.Backend = res.Backend + out.Namespace = res.Namespace + out.StatusSupported = res.Supported + if !res.Supported { + out.StatusError = "unsupported" + } + + names := s.sandboxTaskNames() + root := s.openAuditRoot() + if root != nil { + defer root.Close() + } + for _, ts := range res.Tasks { + // The runner is trusted, but its ids become file paths below. + if !validAuditTaskID(ts.TaskID) { + continue + } + if len(out.Tasks) >= sandboxOverviewMaxTasks { + out.TasksTruncated = true + break + } + if ts.ScopeDomains == nil { + ts.ScopeDomains = []string{} + } + if ts.ScopeCIDRs == nil { + ts.ScopeCIDRs = []string{} + } + dto := sandboxTaskDTO{TaskStatus: ts, Egress: readEgressTail(root, ts.TaskID)} + if n, ok := names[ts.TaskID]; ok { + dto.TaskName = n.name + dto.TaskState = n.status + } + out.Tasks = append(out.Tasks, dto) + } + writeJSON(w, 200, out) +} + +// validAuditTaskID reports whether id may be used as a directory name under +// the audit root: exactly the ids the runner accepts. +func validAuditTaskID(id string) bool { + return sandbox.ValidateTaskID(id) == nil +} + +type sandboxTaskName struct{ name, status string } + +// sandboxTaskNames maps ARTEX task ids to their name and status from memory. +func (s *Server) sandboxTaskNames() map[string]sandboxTaskName { + out := map[string]sandboxTaskName{} + if s.m == nil || s.engine == nil { + return out + } + for _, t := range s.m.List() { + out[t.ID] = sandboxTaskName{name: t.Name, status: s.resolvedTaskStatus(t)} + } + return out +} + +// openAuditRoot opens the egress audit directory as an os.Root, so no path +// built from a task id can resolve outside it. nil when it does not exist. +func (s *Server) openAuditRoot() *os.Root { + if s.auditRoot == "" { + return nil + } + root, err := os.OpenRoot(s.auditRoot) + if err != nil { + return nil + } + return root +} + +// readEgressTail reads the end of //egress.jsonl. The task +// directory and the log are written by the task's proxy, so neither may be a +// symbolic link and the log must be a regular file; os.Root additionally +// refuses any path that would leave the audit directory. +func readEgressTail(root *os.Root, taskID string) sandboxEgressDTO { + out := sandboxEgressDTO{Entries: []sandboxEgressEntryDTO{}} + if root == nil || !validAuditTaskID(taskID) { + return out + } + if fi, err := root.Lstat(taskID); err != nil || !fi.IsDir() { + return out + } + name := taskID + "/" + sandboxEgressFile + if fi, err := root.Lstat(name); err != nil || !fi.Mode().IsRegular() { + return out + } + f, err := root.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK, 0) + if err != nil { + return out + } + defer f.Close() + // Stat the open file: the path could have been swapped after Lstat. + fi, err := f.Stat() + if err != nil || !fi.Mode().IsRegular() { + return out + } + size := fi.Size() + off := max(size-sandboxEgressTailBytes, 0) + buf, err := io.ReadAll(io.NewSectionReader(f, off, sandboxEgressTailBytes)) + if err != nil { + return out + } + out.Available = true + if off > 0 { + out.Truncated = true + // Drop the line the window starts in the middle of. + i := bytes.IndexByte(buf, '\n') + if i < 0 { + return out + } + buf = buf[i+1:] + } + for len(buf) > 0 { + var line []byte + if i := bytes.IndexByte(buf, '\n'); i >= 0 { + line, buf = buf[:i], buf[i+1:] + } else { + // No newline: the proxy is still writing this line. + break + } + if len(line) == 0 || len(line) > sandboxEgressMaxLineBytes { + continue + } + var e sandbox.EgressLogEntry + if json.Unmarshal(line, &e) != nil { + continue + } + switch e.Decision { + case "allow": + out.Allow++ + case "deny": + out.Deny++ + default: + continue + } + out.Entries = append(out.Entries, sandboxEgressEntryDTO{ + TS: clipField(e.TS), + Host: clipField(e.Host), + Port: e.Port, + ResolvedIP: clipField(e.ResolvedIP), + Protocol: clipField(e.Protocol), + Decision: e.Decision, + Bytes: e.Bytes, + }) + if len(out.Entries) > sandboxEgressMaxEntries { + out.Entries = out.Entries[1:] + } + } + return out +} + +// clipField bounds a string taken from an audit line, which carries values the +// sandboxed command chose (the requested host). +func clipField(s string) string { + if len(s) <= sandboxEgressMaxField { + return s + } + s = s[:sandboxEgressMaxField] + for len(s) > 0 && !utf8.ValidString(s) { + s = s[:len(s)-1] + } + return s +} diff --git a/server/sandbox_overview_test.go b/server/sandbox_overview_test.go new file mode 100644 index 000000000..14a7cc845 --- /dev/null +++ b/server/sandbox_overview_test.go @@ -0,0 +1,614 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "github.com/Autumn-27/artex/sandbox" +) + +// tasksSandboxClient is a stub runner client that also lists tasks. +type tasksSandboxClient struct { + stubSandboxClient + tasks sandbox.TasksResponse + tasksErr error + tasksCalls int +} + +func (c *tasksSandboxClient) Tasks(context.Context) (sandbox.TasksResponse, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.tasksCalls++ + return c.tasks, c.tasksErr +} + +func getOverview(t *testing.T, s *Server) (sandboxOverviewDTO, string) { + t.Helper() + rec := httptest.NewRecorder() + s.sandboxOverview(rec, httptest.NewRequest(http.MethodGet, "/api/sandbox/overview", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("overview code = %d body = %s", rec.Code, rec.Body.String()) + } + if ct := rec.Header().Get("Content-Type"); ct != "application/json" { + t.Fatalf("content type = %q", ct) + } + var out sandboxOverviewDTO + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatalf("decode: %v: %s", err, rec.Body.String()) + } + return out, rec.Body.String() +} + +func egressLine(host, decision string, n int64) string { + raw, _ := json.Marshal(sandbox.EgressLogEntry{ + TaskID: "ignored", TS: "2026-11-30T10:00:00Z", Host: host, Port: 443, + ResolvedIP: "93.184.216.34", Protocol: "connect", Decision: decision, Bytes: n, + }) + return string(raw) + "\n" +} + +func writeAudit(t *testing.T, root, taskID, content string) string { + t.Helper() + dir := filepath.Join(root, taskID) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + p := filepath.Join(dir, sandboxEgressFile) + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + return p +} + +func readTail(t *testing.T, root, taskID string) sandboxEgressDTO { + t.Helper() + r, err := os.OpenRoot(root) + if err != nil { + t.Fatal(err) + } + defer r.Close() + return readEgressTail(r, taskID) +} + +func healthyClient(tasks ...sandbox.TaskStatus) *tasksSandboxClient { + return &tasksSandboxClient{ + stubSandboxClient: stubSandboxClient{health: sandbox.HealthResponse{OK: true, Docker: true, Workers: len(tasks), Version: "v-test"}}, + tasks: sandbox.TasksResponse{Backend: sandbox.BackendKubernetes, Supported: true, Namespace: "artex", Tasks: tasks}, + } +} + +func TestSandboxOverviewRequiresAuth(t *testing.T) { + s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef"), sandboxMode: sandbox.ModeRequired} + client := healthyClient(sandbox.TaskStatus{TaskID: "1"}) + s.sandboxClient = client + mux := http.NewServeMux() + mux.HandleFunc("GET /api/sandbox/overview", s.sandboxOverview) + h := s.requireAuth(mux) + + for name, hdr := range map[string]string{"none": "", "garbage": "Bearer not-a-jwt", "basic": "Basic QVJURVg6eA=="} { + r := httptest.NewRequest(http.MethodGet, "/api/sandbox/overview", nil) + if hdr != "" { + r.Header.Set("Authorization", hdr) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, r) + if rec.Code != http.StatusUnauthorized || strings.Contains(rec.Body.String(), "tasks") { + t.Fatalf("%s: code = %d body = %s", name, rec.Code, rec.Body.String()) + } + } + other, _ := signJWT([]byte("another-key-another-key-another-k")) + r := httptest.NewRequest(http.MethodGet, "/api/sandbox/overview", nil) + r.Header.Set("Authorization", "Bearer "+other) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, r) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("token signed with another key: code = %d", rec.Code) + } + if client.tasksCalls != 0 { + t.Fatalf("runner was queried %d times for unauthenticated requests", client.tasksCalls) + } + + tok, err := signJWT(s.jwtKey) + if err != nil { + t.Fatal(err) + } + r = httptest.NewRequest(http.MethodGet, "/api/sandbox/overview", nil) + r.Header.Set("Authorization", "Bearer "+tok) + rec = httptest.NewRecorder() + h.ServeHTTP(rec, r) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"task_id":"1"`) { + t.Fatalf("authenticated: code = %d body = %s", rec.Code, rec.Body.String()) + } +} + +// TestSandboxOverviewRouteRegistered guards the wiring in Handler(): the route +// must be on the main mux, which requireAuth wraps. +func TestSandboxOverviewRouteRegistered(t *testing.T) { + src, err := os.ReadFile("server.go") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(src), `mux.HandleFunc("GET /api/sandbox/overview", s.sandboxOverview)`) { + t.Fatal("GET /api/sandbox/overview is not registered in Handler()") + } +} + +func TestSandboxOverviewSandboxOff(t *testing.T) { + for _, mode := range []string{sandbox.ModeOff, ""} { + client := healthyClient(sandbox.TaskStatus{TaskID: "1"}) + s := &Server{sandboxMode: mode, sandboxClient: client} + out, raw := getOverview(t, s) + if out.Mode != sandbox.ModeOff || out.Runner.Configured || out.Runner.OK || out.StatusSupported || len(out.Tasks) != 0 { + t.Fatalf("mode %q: %+v", mode, out) + } + if !strings.Contains(raw, `"tasks":[]`) { + t.Fatalf("tasks must be [] not null: %s", raw) + } + if client.tasksCalls != 0 { + t.Fatal("runner queried while the sandbox is off") + } + } + // required but no client configured (nil interface). + out, _ := getOverview(t, &Server{sandboxMode: sandbox.ModeRequired}) + if out.Mode != sandbox.ModeRequired || out.Runner.Configured || len(out.Tasks) != 0 { + t.Fatalf("no client: %+v", out) + } +} + +func TestSandboxOverviewRunnerDown(t *testing.T) { + cases := []struct { + name string + healthErr error + wantErr string + wantTasks int // Tasks() calls + }{ + {"unreachable", fmt.Errorf("%w: dial tcp 10.0.0.9:8789: connection refused", sandbox.ErrRunnerUnavailable), "unreachable", 0}, + {"unauthorized", fmt.Errorf("%w: invalid bearer token", sandbox.ErrUnauthorized), "unauthorized", 0}, + {"backend down", fmt.Errorf("%w: {}", sandbox.ErrDockerUnavailable), "backend_unavailable", 1}, + } + for _, tc := range cases { + client := healthyClient(sandbox.TaskStatus{TaskID: "1"}) + client.health = sandbox.HealthResponse{} + client.healthEr = tc.healthErr + client.tasksErr = tc.healthErr + s := &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: client} + out, raw := getOverview(t, s) + if !out.Runner.Configured || out.Runner.OK || out.Runner.Error != tc.wantErr || len(out.Tasks) != 0 || out.StatusSupported { + t.Fatalf("%s: %+v", tc.name, out) + } + if client.tasksCalls != tc.wantTasks { + t.Fatalf("%s: Tasks calls = %d, want %d", tc.name, client.tasksCalls, tc.wantTasks) + } + // Raw runner errors (addresses, bodies) never reach the browser. + if strings.Contains(raw, "10.0.0.9") || strings.Contains(raw, "bearer") { + t.Fatalf("%s: overview leaks the raw runner error: %s", tc.name, raw) + } + } + + // Healthy runner whose task list fails, and one that predates the endpoint. + for err, want := range map[error]string{ + fmt.Errorf("%w: HTTP 500", sandbox.ErrRunnerUnavailable): "unreachable", + fmt.Errorf("%w: 404 page not found", sandbox.ErrNotFound): "unsupported", + } { + client := healthyClient() + client.tasksErr = err + out, _ := getOverview(t, &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: client}) + if !out.Runner.OK || out.Runner.Version != "v-test" || out.StatusError != want || out.StatusSupported || len(out.Tasks) != 0 { + t.Fatalf("tasks err %v: %+v", err, out) + } + } + + // A client without the optional Tasks capability, and a backend without Status. + out, _ := getOverview(t, &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: &stubSandboxClient{health: sandbox.HealthResponse{OK: true, Docker: true}}}) + if !out.Runner.OK || out.StatusError != "unsupported" || out.StatusSupported { + t.Fatalf("client without Tasks: %+v", out) + } + client := healthyClient() + client.tasks.Supported = false + out, _ = getOverview(t, &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: client}) + if out.StatusSupported || out.StatusError != "unsupported" { + t.Fatalf("backend without Status: %+v", out) + } + + // health ok=false without an error. + client = healthyClient() + client.health = sandbox.HealthResponse{OK: false, Docker: false, Version: "v"} + out, _ = getOverview(t, &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: client}) + if out.Runner.OK || out.Runner.BackendOK || out.Runner.Error != "" { + t.Fatalf("unhealthy: %+v", out.Runner) + } +} + +func TestSandboxOverviewTasksAndEgress(t *testing.T) { + root := t.TempDir() + writeAudit(t, root, "1", egressLine("example.com", "deny", 0)+egressLine("api.example.org", "allow", 1234)+egressLine("evil.test", "deny", 0)) + client := healthyClient( + sandbox.TaskStatus{ + TaskID: "1", Tracked: true, + Worker: sandbox.ComponentStatus{Name: "artex-w-a", State: "Running", Ready: true, Node: "n1", StartedAt: "2026-11-30T09:00:00Z"}, + Proxy: sandbox.ComponentStatus{Name: "artex-p-a", State: "Running", Ready: true}, + ProxyIP: "10.43.0.5", + ScopeDomains: []string{"example.org"}, + NetworkPolicies: []string{"artex-w-a", "artex-p-a"}, + }, + sandbox.TaskStatus{TaskID: "2", Worker: sandbox.ComponentStatus{Name: "artex-w-b", State: "Pending"}, Proxy: sandbox.ComponentStatus{Name: "artex-p-b", State: sandbox.StateMissing}}, + ) + s := &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: client, auditRoot: root} + out, raw := getOverview(t, s) + + if out.Mode != sandbox.ModeRequired || !out.Runner.Configured || !out.Runner.OK || !out.Runner.BackendOK || out.Runner.Workers != 2 || out.Runner.Version != "v-test" { + t.Fatalf("runner = %+v", out.Runner) + } + if out.Backend != sandbox.BackendKubernetes || out.Namespace != "artex" || !out.StatusSupported || out.StatusError != "" || out.TasksTruncated { + t.Fatalf("overview = %+v", out) + } + if _, err := time.Parse(time.RFC3339, out.GeneratedAt); err != nil { + t.Fatalf("generated_at = %q", out.GeneratedAt) + } + if len(out.Tasks) != 2 { + t.Fatalf("tasks = %+v", out.Tasks) + } + t1 := out.Tasks[0] + if t1.TaskID != "1" || !t1.Worker.Ready || t1.Worker.Node != "n1" || t1.ProxyIP != "10.43.0.5" || len(t1.NetworkPolicies) != 2 { + t.Fatalf("task 1 = %+v", t1) + } + if !t1.Egress.Available || t1.Egress.Allow != 1 || t1.Egress.Deny != 2 || t1.Egress.Truncated || len(t1.Egress.Entries) != 3 { + t.Fatalf("task 1 egress = %+v", t1.Egress) + } + // Oldest first, as written. + if e := t1.Egress.Entries[1]; e.Host != "api.example.org" || e.Decision != "allow" || e.Bytes != 1234 || e.Port != 443 || e.Protocol != "connect" || e.ResolvedIP != "93.184.216.34" || e.TS == "" { + t.Fatalf("entry = %+v", e) + } + t2 := out.Tasks[1] + if t2.Egress.Available || t2.Egress.Allow != 0 || t2.Egress.Deny != 0 || t2.Egress.Entries == nil { + t.Fatalf("task 2 egress = %+v", t2.Egress) + } + // Lists are arrays even when empty, and the flattened task keeps its wire names. + for _, want := range []string{`"scope_cidrs":[]`, `"entries":[]`, `"task_id":"2"`, `"worker":{"name":"artex-w-b","state":"Pending","ready":false}`} { + if !strings.Contains(raw, want) { + t.Fatalf("overview is missing %s: %s", want, raw) + } + } + // The per-line task_id is not echoed (the directory is authoritative). + if strings.Contains(raw, "ignored") { + t.Fatalf("entry task_id leaked: %s", raw) + } +} + +func TestSandboxOverviewMissingAuditRoot(t *testing.T) { + for _, root := range []string{"", filepath.Join(t.TempDir(), "does-not-exist")} { + s := &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: healthyClient(sandbox.TaskStatus{TaskID: "1"}), auditRoot: root} + out, _ := getOverview(t, s) + if len(out.Tasks) != 1 || out.Tasks[0].Egress.Available || out.Tasks[0].Egress.Entries == nil { + t.Fatalf("root %q: %+v", root, out.Tasks) + } + } +} + +func TestSandboxOverviewHostileTaskIDs(t *testing.T) { + base := t.TempDir() + root := filepath.Join(base, "egress-audit") + if err := os.MkdirAll(root, 0o755); err != nil { + t.Fatal(err) + } + // Files a traversal would reach if an id were joined into a path unchecked. + secret := egressLine("SECRET-OUTSIDE", "allow", 1) + writeAudit(t, base, "outside", secret) + if err := os.WriteFile(filepath.Join(base, sandboxEgressFile), []byte(secret), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, sandboxEgressFile), []byte(secret), 0o644); err != nil { + t.Fatal(err) + } + writeAudit(t, root, "good", egressLine("ok.test", "allow", 1)) + + hostile := []string{ + "", " ", ".", "..", "../outside", "..%2foutside", "good/../../outside", "/etc", filepath.Join(base, "outside"), + "good/", "./good", "a..b", "-rf", ".hidden", "good\x00", "good\n", "a b", "töst", `..\outside`, + strings.Repeat("a", 65), "good/egress.jsonl", "*", "~", " good", "good ", "\tgood", "good\r", + } + var tasks []sandbox.TaskStatus + for _, id := range hostile { + tasks = append(tasks, sandbox.TaskStatus{TaskID: id}) + } + tasks = append(tasks, sandbox.TaskStatus{TaskID: "good"}) + s := &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: healthyClient(tasks...), auditRoot: root} + out, raw := getOverview(t, s) + if len(out.Tasks) != 1 || out.Tasks[0].TaskID != "good" || out.Tasks[0].Egress.Allow != 1 { + t.Fatalf("hostile ids were not dropped: %s", raw) + } + if strings.Contains(raw, "SECRET-OUTSIDE") { + t.Fatalf("overview read a file outside the audit root: %s", raw) + } + // The reader itself refuses them too, independent of the handler's filter. + for _, id := range hostile { + if got := readTail(t, root, id); got.Available || len(got.Entries) != 0 { + t.Fatalf("readEgressTail(%q) = %+v", id, got) + } + } + if got := readEgressTail(nil, "good"); got.Available || got.Entries == nil { + t.Fatalf("nil root = %+v", got) + } +} + +func TestSandboxOverviewRefusesSymlinks(t *testing.T) { + base := t.TempDir() + root := filepath.Join(base, "egress-audit") + if err := os.MkdirAll(root, 0o755); err != nil { + t.Fatal(err) + } + secret := egressLine("SECRET-OUTSIDE", "allow", 1) + outsideFile := writeAudit(t, base, "outside", secret) + insideFile := writeAudit(t, root, "real", egressLine("SECRET-OTHER-TASK", "allow", 1)) + + mk := func(id string) string { + d := filepath.Join(root, id) + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + return d + } + link := func(target, name string) { + if err := os.Symlink(target, name); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + } + // The task directory is a symlink out of the root (absolute and relative). + link(filepath.Join(base, "outside"), filepath.Join(root, "dirabs")) + link("../outside", filepath.Join(root, "dirrel")) + // The task directory is a symlink to another task inside the root. + link("real", filepath.Join(root, "dirinside")) + // The log file is a symlink: out of the root, to /etc/passwd, to another task, dangling, and a loop. + link(outsideFile, filepath.Join(mk("fileabs"), sandboxEgressFile)) + link("../../outside/"+sandboxEgressFile, filepath.Join(mk("filerel"), sandboxEgressFile)) + link("/etc/passwd", filepath.Join(mk("passwd"), sandboxEgressFile)) + link(insideFile, filepath.Join(mk("fileinside"), sandboxEgressFile)) + link("nowhere", filepath.Join(mk("dangling"), sandboxEgressFile)) + link(sandboxEgressFile, filepath.Join(mk("loop"), sandboxEgressFile)) + // The log "file" is a directory, and a FIFO (which must not block the handler). + if err := os.MkdirAll(filepath.Join(mk("isdir"), sandboxEgressFile), 0o755); err != nil { + t.Fatal(err) + } + fifoOK := syscall.Mkfifo(filepath.Join(mk("fifo"), sandboxEgressFile), 0o644) == nil + + ids := []string{"dirabs", "dirrel", "dirinside", "fileabs", "filerel", "passwd", "fileinside", "dangling", "loop", "isdir"} + if fifoOK { + ids = append(ids, "fifo") + } + var tasks []sandbox.TaskStatus + for _, id := range append(ids, "real") { + tasks = append(tasks, sandbox.TaskStatus{TaskID: id}) + } + s := &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: healthyClient(tasks...), auditRoot: root} + + done := make(chan struct{}) + var out sandboxOverviewDTO + var raw string + go func() { + defer close(done) + out, raw = getOverview(t, s) + }() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("overview blocked (FIFO or symlink loop)") + } + if len(out.Tasks) != len(ids)+1 { + t.Fatalf("tasks = %d, want %d", len(out.Tasks), len(ids)+1) + } + for _, task := range out.Tasks { + if task.TaskID == "real" { + if !task.Egress.Available || task.Egress.Allow != 1 { + t.Fatalf("real task egress = %+v", task.Egress) + } + continue + } + if task.Egress.Available || len(task.Egress.Entries) != 0 || task.Egress.Allow != 0 { + t.Fatalf("task %s followed a symlink or read a non-regular file: %+v", task.TaskID, task.Egress) + } + } + if strings.Contains(raw, "SECRET-OUTSIDE") || strings.Contains(raw, "root:") || strings.Count(raw, "SECRET-OTHER-TASK") != 1 { + t.Fatalf("overview leaked through a symlink: %s", raw) + } + + // The audit root itself being a symlink is the operator's choice and works. + alias := filepath.Join(base, "alias") + link(root, alias) + if got := readTail(t, alias, "real"); !got.Available || got.Allow != 1 { + t.Fatalf("symlinked audit root = %+v", got) + } +} + +func TestReadEgressTailBounds(t *testing.T) { + root := t.TempDir() + + // More entries than the cap: only the last N are returned, counts cover the tail read. + var sb strings.Builder + for i := range 120 { + d := "allow" + if i%3 == 0 { + d = "deny" + } + sb.WriteString(egressLine(fmt.Sprintf("h%03d.test", i), d, int64(i))) + } + writeAudit(t, root, "many", sb.String()) + got := readTail(t, root, "many") + if len(got.Entries) != sandboxEgressMaxEntries || got.Truncated || got.Allow != 80 || got.Deny != 40 { + t.Fatalf("many: entries=%d truncated=%v allow=%d deny=%d", len(got.Entries), got.Truncated, got.Allow, got.Deny) + } + if got.Entries[0].Host != "h070.test" || got.Entries[sandboxEgressMaxEntries-1].Host != "h119.test" { + t.Fatalf("many: window = %s .. %s", got.Entries[0].Host, got.Entries[sandboxEgressMaxEntries-1].Host) + } + + // A file far larger than the byte cap: only the tail is read. + sb.Reset() + line := egressLine("old.test", "allow", 1) + total := (4 << 20) / len(line) + for range total { + sb.WriteString(line) + } + sb.WriteString(egressLine("newest.test", "deny", 0)) + p := writeAudit(t, root, "huge", sb.String()) + fi, _ := os.Stat(p) + if fi.Size() < 4<<20 { + t.Fatalf("test file is only %d bytes", fi.Size()) + } + got = readTail(t, root, "huge") + if !got.Available || !got.Truncated || len(got.Entries) != sandboxEgressMaxEntries { + t.Fatalf("huge: %+v", got) + } + if got.Entries[len(got.Entries)-1].Host != "newest.test" { + t.Fatalf("huge: last entry = %+v", got.Entries[len(got.Entries)-1]) + } + // The counts can only cover what fits in the byte window. + if max := sandboxEgressTailBytes/len(line) + 1; got.Allow+got.Deny > max || got.Allow+got.Deny < max/2 || got.Deny != 1 { + t.Fatalf("huge: allow=%d deny=%d, window holds at most %d lines", got.Allow, got.Deny, max) + } + + // The window starts mid-line: that partial line is dropped, not misparsed. + // The padding ends in a JSON fragment that would parse if it were treated as a line start. + frag := `{"decision":"allow","host":"PARTIAL"}` + "\n" + pad := strings.Repeat("x", sandboxEgressTailBytes) // one oversized garbage line + writeAudit(t, root, "partial", pad[:len(pad)-10]+frag+egressLine("after.test", "deny", 0)) + got = readTail(t, root, "partial") + if !got.Truncated || got.Allow != 0 || got.Deny != 1 || len(got.Entries) != 1 || got.Entries[0].Host != "after.test" { + t.Fatalf("partial: %+v", got) + } + + // One giant line with no newline at all. + writeAudit(t, root, "oneline", strings.Repeat("y", sandboxEgressTailBytes*2)) + got = readTail(t, root, "oneline") + if !got.Available || !got.Truncated || len(got.Entries) != 0 { + t.Fatalf("oneline: %+v", got) + } + + // Garbage, unknown decisions, oversized lines, an unterminated last line, blank lines. + long := egressLine(strings.Repeat("h", sandboxEgressMaxLineBytes), "allow", 1) + content := "not json\n" + "\n" + `{"decision":"maybe","host":"x"}` + "\n" + `[1,2,3]` + "\n" + `{"decision":"ALLOW","host":"case"}` + "\n" + + long + egressLine("good.test", "allow", 7) + "\x00\xff\xfe\n" + + strings.TrimSuffix(egressLine("unterminated.test", "deny", 0), "\n") + writeAudit(t, root, "messy", content) + got = readTail(t, root, "messy") + if got.Allow != 1 || got.Deny != 0 || len(got.Entries) != 1 || got.Entries[0].Host != "good.test" || got.Truncated { + t.Fatalf("messy: %+v", got) + } + + // Long attacker-chosen fields are clipped on a rune boundary. + host := strings.Repeat("é", 300) + raw, _ := json.Marshal(map[string]any{"decision": "deny", "host": host, "protocol": strings.Repeat("p", 1000), "ts": "t", "port": 1}) + writeAudit(t, root, "clip", string(raw)+"\n") + got = readTail(t, root, "clip") + if len(got.Entries) != 1 { + t.Fatalf("clip: %+v", got) + } + if h := got.Entries[0].Host; len(h) > sandboxEgressMaxField || len(h) < sandboxEgressMaxField-4 || !strings.HasPrefix(host, h) || strings.ContainsRune(h, '�') { + t.Fatalf("clip: host len=%d", len(h)) + } + if len(got.Entries[0].Protocol) != sandboxEgressMaxField { + t.Fatalf("clip: protocol len=%d", len(got.Entries[0].Protocol)) + } + + // Empty file and missing file. + writeAudit(t, root, "empty", "") + if got = readTail(t, root, "empty"); !got.Available || len(got.Entries) != 0 || got.Truncated { + t.Fatalf("empty: %+v", got) + } + if err := os.MkdirAll(filepath.Join(root, "nofile"), 0o755); err != nil { + t.Fatal(err) + } + if got = readTail(t, root, "nofile"); got.Available { + t.Fatalf("nofile: %+v", got) + } + if got = readTail(t, root, "nodir"); got.Available { + t.Fatalf("nodir: %+v", got) + } +} + +func TestSandboxOverviewCapsTaskCount(t *testing.T) { + var tasks []sandbox.TaskStatus + for i := range sandboxOverviewMaxTasks + 25 { + tasks = append(tasks, sandbox.TaskStatus{TaskID: fmt.Sprintf("t%d", i)}) + } + out, _ := getOverview(t, &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: healthyClient(tasks...)}) + if len(out.Tasks) != sandboxOverviewMaxTasks || !out.TasksTruncated { + t.Fatalf("tasks = %d truncated = %v", len(out.Tasks), out.TasksTruncated) + } +} + +func TestSandboxErrorCode(t *testing.T) { + for err, want := range map[error]string{ + nil: "", + sandbox.ErrUnauthorized: "unauthorized", + sandbox.ErrDockerUnavailable: "backend_unavailable", + sandbox.ErrNotFound: "unsupported", + sandbox.ErrRunnerUnavailable: "unreachable", + context.DeadlineExceeded: "timeout", + errors.New("anything else"): "unreachable", + } { + if got := sandboxErrorCode(err); got != want { + t.Fatalf("sandboxErrorCode(%v) = %q, want %q", err, got, want) + } + } +} + +// The real runner client must satisfy the optional capability the handler uses. +var _ sandboxTasksLister = (*sandbox.Client)(nil) + +// TestSandboxOverviewEndToEndWithRunner drives the handler through the real +// sandbox.Client against a real RunnerServer. +func TestSandboxOverviewEndToEndWithRunner(t *testing.T) { + root := t.TempDir() + writeAudit(t, root, "55", egressLine("example.com", "deny", 0)) + rs, err := sandbox.NewRunnerServer("tok", "v9", &overviewBackend{}) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(rs.Handler()) + s := &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: sandbox.NewClient(srv.URL, "tok"), auditRoot: root} + out, _ := getOverview(t, s) + if !out.Runner.OK || out.Runner.Version != "v9" || out.Backend != "fake" || !out.StatusSupported || len(out.Tasks) != 1 { + t.Fatalf("overview = %+v", out) + } + if task := out.Tasks[0]; task.TaskID != "55" || task.Egress.Deny != 1 || task.Worker.Name != "w55" { + t.Fatalf("task = %+v", task) + } + + // Wrong token: the panel reports it without task data. + s.sandboxClient = sandbox.NewClient(srv.URL, "wrong") + out, _ = getOverview(t, s) + if out.Runner.OK || out.Runner.Error != "unauthorized" || len(out.Tasks) != 0 { + t.Fatalf("wrong token = %+v", out) + } + + // Runner gone. + s.sandboxClient = sandbox.NewClient(srv.URL, "tok") + srv.Close() + out, _ = getOverview(t, s) + if out.Runner.OK || out.Runner.Error != "unreachable" || len(out.Tasks) != 0 { + t.Fatalf("runner gone = %+v", out) + } +} + +type overviewBackend struct{} + +func (overviewBackend) Ping(context.Context) error { return nil } +func (overviewBackend) Recover(context.Context) (int, error) { return 0, nil } +func (overviewBackend) WorkerCount() int { return 1 } +func (overviewBackend) Exec(context.Context, string, sandbox.ExecRequest) (sandbox.ExecResponse, error) { + return sandbox.ExecResponse{}, nil +} +func (overviewBackend) Kill(context.Context, string) error { return nil } +func (overviewBackend) Delete(context.Context, string) error { return nil } +func (overviewBackend) Status(context.Context) (sandbox.TasksResponse, error) { + return sandbox.TasksResponse{Backend: "fake", Tasks: []sandbox.TaskStatus{{TaskID: "55", Worker: sandbox.ComponentStatus{Name: "w55", State: "Running", Ready: true}}}}, nil +} diff --git a/server/server.go b/server/server.go index 20601a7c4..db0f8d307 100644 --- a/server/server.go +++ b/server/server.go @@ -60,6 +60,9 @@ type Server struct { isolation IsolationStatus sandboxMode string sandboxClient SandboxClient // result of the startup isolation self-test (isolation.go); zero when not run + // auditRoot is the egress audit directory the per-task proxies write to + // (/egress-audit); read-only for the panel (sandbox_overview.go). + auditRoot string chatBridges *chatBridgeRunner // inbound chat bridges (issue #5); nil without PostgreSQL @@ -223,6 +226,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi } s.engine.SetKillSwitchConfig(dataDir, s.execPriv) s.engine.SetSandbox(s.sandboxClient, s.sandboxMode, dataDir) + s.auditRoot = filepath.Join(dataDir, sandboxAuditDirName) if s.sandboxMode != "" { agent.SetSandboxExecutor(&agent.SandboxExecutor{ Mode: s.sandboxMode, @@ -819,6 +823,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /api/health", s.health) mux.HandleFunc("GET /api/ready", s.ready) mux.HandleFunc("GET /api/stats", s.stats) + mux.HandleFunc("GET /api/sandbox/overview", s.sandboxOverview) mux.HandleFunc("GET /api/logs", s.getLogs) mux.HandleFunc("GET /api/logs/history", s.getLogsHistory) mux.HandleFunc("GET /api/logs/stream", s.streamLogs) From 64653b239842a66c3ae0ccef0e8aeb71d3b4eb07 Mon Sep 17 00:00:00 2001 From: Marco Azarmaneche <306425250+thecorporatetractor@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:46:15 +0200 Subject: [PATCH 4/6] feat(sandbox): scale-to-zero, capacity cap and placement for the Kubernetes backend The runner scales an idle task to zero after ARTEX_KUBE_IDLE_TIMEOUT: its worker and proxy pods are deleted, the proxy Service, NetworkPolicies and workspace stay, and the next command starts the pods again. ARTEX_KUBE_MAX_ACTIVE caps the tasks with pods: at the cap the least recently used idle task is scaled to zero, otherwise the command waits in arrival order for ARTEX_KUBE_QUEUE_TIMEOUT and fails with 429 sandbox at capacity. Capacity slots: a deleted task holds its slot until its pods are gone, and a start that fails after creating pods deletes them, frees the slot and records a scale_up_failed event. A pod still unschedulable at the ready timeout (a cluster autoscaler adding a node) fails with ErrCapacity (429, the task is not paused) and keeps its pods and slot; the next command reuses pending or ready pods instead of recreating them. If no command comes, the idle reaper removes the pods, and for a start that never succeeded also its Service and policies. GET /v1/tasks and /api/sandbox/overview report per-task scaling state, health, the scope last applied to the proxy NetworkPolicy for tasks scaled to zero (scope_known, scope_source), a summary, the last 100 scale events, totals and cold start p50/p95. With ARTEX_KUBE_STATE_DIR (chart: runner-state on the data volume) events, totals and cold-start samples survive a runner restart. The overview honours ARTEX_AUDIT_ROOT. Chart: sandbox.scaling.*, worker requests, sandbox.nodeSelector, tolerations, priorityClassName, postgres nodeSelector/tolerations and podAnnotations. scripts/capd-autoscaler-e2e.sh tests the official cluster-autoscaler on a Cluster API (CAPD) cluster; the chart README documents the measured timings and recommended values. --- cmd/artex-runner/main.go | 13 +- deploy/helm/artex/README.md | 179 ++- deploy/helm/artex/templates/_helpers.tpl | 8 + deploy/helm/artex/templates/panel.yaml | 3 + deploy/helm/artex/templates/postgres.yaml | 12 + deploy/helm/artex/templates/runner.yaml | 36 + deploy/helm/artex/values.schema.json | 16 + deploy/helm/artex/values.yaml | 39 + docs/SANDBOX.md | 81 +- sandbox/client.go | 2 + sandbox/helmchart_placement_test.go | 61 + sandbox/helmchart_test.go | 88 ++ sandbox/kube.go | 631 +++++++- sandbox/kube_e2e_test.go | 290 +++- sandbox/kube_placement_test.go | 80 + sandbox/kube_scale.go | 497 ++++++ sandbox/kube_scale_order_test.go | 292 ++++ sandbox/kube_scale_test.go | 1669 +++++++++++++++++++++ sandbox/kube_scope_status_test.go | 145 ++ sandbox/kube_state.go | 216 +++ sandbox/kube_state_test.go | 267 ++++ sandbox/kube_test.go | 150 +- sandbox/runner.go | 2 + sandbox/status.go | 190 ++- sandbox/status_test.go | 4 + sandbox/types.go | 4 + scripts/capd-autoscaler-e2e.sh | 615 ++++++++ scripts/k3d-e2e.sh | 4 +- server/sandbox_overview.go | 67 +- server/sandbox_overview_summary_test.go | 42 + server/sandbox_overview_test.go | 119 ++ server/server.go | 5 +- 32 files changed, 5727 insertions(+), 100 deletions(-) create mode 100644 sandbox/helmchart_placement_test.go create mode 100644 sandbox/kube_placement_test.go create mode 100644 sandbox/kube_scale.go create mode 100644 sandbox/kube_scale_order_test.go create mode 100644 sandbox/kube_scale_test.go create mode 100644 sandbox/kube_scope_status_test.go create mode 100644 sandbox/kube_state.go create mode 100644 sandbox/kube_state_test.go create mode 100755 scripts/capd-autoscaler-e2e.sh create mode 100644 server/sandbox_overview_summary_test.go diff --git a/cmd/artex-runner/main.go b/cmd/artex-runner/main.go index 9f3a77ad0..653ecbcaa 100644 --- a/cmd/artex-runner/main.go +++ b/cmd/artex-runner/main.go @@ -60,7 +60,7 @@ func buildBackend() (sandbox.Backend, error) { if err != nil { return nil, err } - log.Printf("[runner] backend=kubernetes namespace=%s claim=%s", b.Namespace(), cfg.DataClaim) + log.Printf("[runner] backend=kubernetes namespace=%s claim=%s idle_timeout=%s max_active=%d state_dir=%q", b.Namespace(), cfg.DataClaim, cfg.IdleTimeout, cfg.MaxActive, cfg.StateDir) return b, nil default: return nil, fmt.Errorf("invalid %s=%q (want %q or %q)", sandbox.EnvRunnerBackend, kind, sandbox.BackendDocker, sandbox.BackendKubernetes) @@ -87,6 +87,11 @@ func main() { log.Printf("[runner] recovered %d managed task container(s) by label", n) } + // Backends that scale idle tasks to zero run their reaper for the process lifetime. + if sc, ok := backend.(interface{ RunScaler(context.Context) }); ok { + go sc.RunScaler(ctx) + } + rs, err := sandbox.NewRunnerServer(token, version, backend) if err != nil { log.Fatalf("[runner] init failed: %v", err) @@ -108,4 +113,10 @@ func main() { sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() _ = srv.Shutdown(sctx) + // Backends that keep scaling history write it out before exiting. + if fs, ok := backend.(interface{ FlushState() error }); ok { + if err := fs.FlushState(); err != nil { + log.Printf("[runner] save scaling state: %v", err) + } + } } diff --git a/deploy/helm/artex/README.md b/deploy/helm/artex/README.md index 56b18e9fe..730e62e86 100644 --- a/deploy/helm/artex/README.md +++ b/deploy/helm/artex/README.md @@ -69,8 +69,9 @@ fails, the worker pod is deleted and the workspace survives. ## Storage -The data volume is shared. The panel mounts all of it, the runner mounts `tasks/` -and `egress-audit/`, and task pods mount their own sub-directories. +The data volume is shared. The panel mounts all of it, the runner mounts `tasks/`, +`egress-audit/` and `runner-state/` (its scaling history), and task pods mount +their own sub-directories of `tasks/` and `egress-audit/` only. - `persistence.data.accessMode: ReadWriteOnce` (default) works with any block or local-path storage. The panel is scheduled on the runner's node, and the runner @@ -93,7 +94,14 @@ and `egress-audit/`, and task pods mount their own sub-directories. | `sandbox.mode` | `required` | `off` runs agents inside the panel container. Not recommended. | | `sandbox.runtimeClassName` | `""` | Run task pods under gVisor or Kata for kernel isolation. | | `sandbox.worker.cpuLimit` / `memoryLimit` | `2` / `2Gi` | | -| `sandbox.podReadyTimeout` | `2m` | Image pull, scheduling and policy programming must finish within it. | +| `sandbox.worker.cpuRequest` / `memoryRequest` | `100m` / `128Mi` | What the scheduler reserves per worker pod. Must not exceed the limits. See [Scaling](#scaling). | +| `sandbox.scaling.idleTimeout` | `15m` | A task with no command for this long is scaled to zero. `0` never scales down. | +| `sandbox.scaling.maxActive` | `10` | Tasks that may have pods at the same time. `0` removes the cap. | +| `sandbox.scaling.queueTimeout` | `""` (= `podReadyTimeout`) | How long a command waits for a free slot when every active task is busy. | +| `sandbox.podReadyTimeout` | `2m` | Scheduling, image pull and policy programming must finish within it. With a cluster autoscaler it must also cover adding a node: see [Cluster autoscaler](#cluster-autoscaler). | +| `sandbox.nodeSelector` / `tolerations` / `priorityClassName` | none | Placement of task pods (worker and proxy), for example on a dedicated, tainted node pool. | +| `panel` / `runner` / `postgres` `.podAnnotations` | `{}` | Extra pod annotations (values are always quoted). | +| `postgres.nodeSelector` / `tolerations` | none | Placement of the bundled database. | | `sandbox.proxyDeniedCIDRs` | built-in | IPv4 only (it sits inside the `0.0.0.0/0` ipBlock). | | `sandbox.dns.namespace` / `podLabels` | `kube-system` / `k8s-app: kube-dns` | Cluster DNS the proxy may query. | | `persistence.data.accessMode` | `ReadWriteOnce` | See [Storage](#storage). | @@ -103,7 +111,155 @@ and `egress-audit/`, and task pods mount their own sub-directories. | `ingress.*` | disabled | | `values.schema.json` validates the values. Invalid modes, pull policies, access -modes, replica counts above 1, and IPv6 deny ranges fail at install time. +modes, replica counts above 1, IPv6 deny ranges, malformed durations and resource +quantities, and unknown `sandbox.scaling` keys fail at install time. + +## Scaling + +The runner scales each task's pods itself. Nothing here uses an HPA. + +- **Scale to zero.** A task whose last command ended more than + `sandbox.scaling.idleTimeout` ago, and that has no command running, loses its + worker and proxy pods. Its proxy Service (so the proxy address stays the same), + its NetworkPolicies and its workspace on the data volume are kept. The next + command creates the pods again and waits for the same readiness and + [network checks](#network-readiness) as a first start, so it takes a cold start + (seconds) longer. Files outside `/workspace` (`/tmp`, `$HOME`) and background + processes do not survive. +- **Capacity cap.** At most `sandbox.scaling.maxActive` tasks have pods. When a + task needs pods at the cap, the runner scales the least recently used task + that is not running a command to zero and gives its slot away. When every + active task is running a command, the new command waits in arrival order for + up to `sandbox.scaling.queueTimeout`, then fails with + `sandbox at capacity: N of N sandbox slots are in use ...` (HTTP 429 from the + runner). The agent sees that as a failed command it can retry. The task is not + paused, because the runner is healthy. +- **Resource requests.** `sandbox.worker.cpuRequest` and `memoryRequest` are what + each worker pod reserves on a node. With a `ReadWriteMany` data volume, task + pods schedule on any node, so a cluster autoscaler adds nodes when the + requests of pending worker pods do not fit; size the requests to what a task + really uses and size `maxActive` to the node pool's limit. With + `ReadWriteOnce` (the default) every task pod is pinned to the runner's node: + new nodes cannot take task pods, node autoscaling does not help, and + `maxActive` multiplied by the requests has to fit on that one node. See + [Cluster autoscaler](#cluster-autoscaler). +- **Failed starts and deletes.** A start that fails after creating pods (image + pull error, pods never ready, network never ready) deletes them and frees its + slot at once, recorded as `scale_up_failed`. A pod that is still unschedulable + at `sandbox.podReadyTimeout` is the exception: the command fails with HTTP 429, + and the pods keep their slot so the next command waits on them instead of + starting over (see [Cluster autoscaler](#cluster-autoscaler)). A deleted task + holds its slot until its pods are gone, so the cap is never exceeded while they + terminate. +- **Runner restart.** Live scaling state is rebuilt from the cluster: after a + restart the runner adopts existing pods and the Services of scaled-to-zero + tasks, and every adopted task's idle timer starts again from the restart. The + scale history, totals and cold-start samples are kept in + `runner-state/scaling.json` on the data volume (`ARTEX_KUBE_STATE_DIR`, + mounted at `/app/data/runner-state`) and survive the restart. +- **Visibility.** `GET /v1/tasks` on the runner and the panel's + **System > Sandbox** page show, per task, the state (`active`, `starting`, + `queued`, `scaled_to_zero`), commands in flight and the time it will be scaled + down, plus the capacity in use, the last 100 scale events with their reason + (`first_exec`, `resume`, `recreate`, `idle`, `evicted`, `deleted`) including + failed scale-ups and their error, totals, and the cold start time (last, p50, + p95). Each task also has a `health` + (`healthy`, `degraded`, `starting`, `queued`, `scaled_to_zero`), and + `summary` counts them: "N of M healthy" is `summary.healthy` of + `summary.expected`, so tasks scaled to zero count as neither. The scope of a + task scaled to zero is the one last applied to its proxy NetworkPolicy + (`scope_source: last_applied`; `live` while its proxy runs; `scope_known` + is false when neither is available). + +The runner itself is not horizontally scalable and the chart ships no +HorizontalPodAutoscaler for it: it is the single writer of task pods and keeps +their state in memory, so `runner.replicas` above 1 is rejected. It is a small +control-plane process that only makes API calls; the load is in the task pods. + +## Cluster autoscaler + +Verified with the official cluster-autoscaler (v1.36.2, `clusterapi` provider) +on a Cluster API cluster with kubeadm nodes, Calico and an NFS (`ReadWriteMany`) +data volume: `scripts/capd-autoscaler-e2e.sh` reproduces it locally with the +Docker infrastructure provider. + +**What happens.** A task's first command creates its worker and proxy pods. +When no node has room for their requests they stay `Pending` +(`Unschedulable`), the autoscaler adds nodes, the pods start there, and the +command runs; worker and proxy may land on different nodes, and the +NetworkPolicies hold across nodes. When the task has been idle for +`sandbox.scaling.idleTimeout` its pods are deleted and the autoscaler removes +the empty nodes. Task pods are bare pods (no controller), so the autoscaler +never evicts them: a node with an active task stays until the task is scaled +to zero, and a running command is never cut by a scale-down. + +**Timings measured locally** (nodes are containers, so a cloud provider is +slower to boot but similar otherwise): from the pods being created to the +command running, 112-117 s with a scale-up of an existing pool (about 70 s for +the autoscaler to decide and the node to become Ready, 45 s for image pull, +volume mount and network policy on the new node), 139-166 s with a pool that +scaled from zero, against 3-4 s on a node with room. After the last task +went idle, nodes were removed 1.5 min later (with +`--unremovable-node-recheck-timeout=1m`) or 5 min later (its default, 5m: the +autoscaler does not look at a node again for that long after a task pod made +it unremovable). + +Recommended settings: + +| Setting | Value | Why | +|---|---|---| +| `persistence.data.accessMode` | `ReadWriteMany` | With `ReadWriteOnce` every task pod is pinned to the runner's node (see below). | +| `sandbox.podReadyTimeout` | node provisioning time + image pull, with margin: `5m` locally, `5m`-`10m` on most clouds | The first command waits for the new node. With the default `2m`, 6 of 8 commands in a burst failed during a scale-up. | +| `sandbox.worker.cpuRequest` / `memoryRequest` | what a task really uses | The autoscaler sizes nodes from requests, not limits. | +| `sandbox.scaling.maxActive` | about pool max nodes × tasks per node | Above that, pods wait for nodes the pool cannot add. | +| `sandbox.scaling.idleTimeout` | `15m` (default) or shorter | Nodes can only drain after their tasks scale to zero. | +| `sandbox.nodeSelector` / `tolerations` | a dedicated, tainted pool | Keeps task pods off the nodes that run the panel, runner and database, and lets that pool scale to zero. | +| `panel`/`runner`/`postgres` `.podAnnotations` | `cluster-autoscaler.kubernetes.io/safe-to-evict: "false"` | Single replicas: moving the panel interrupts running agents, moving the runner cuts the command streams. Or run them on a pool the autoscaler does not scale. | +| autoscaler `--scale-down-unneeded-time` / `--unremovable-node-recheck-timeout` | e.g. `5m` / `1m` | How soon an emptied node goes. | + +A pod still `Unschedulable` when `sandbox.podReadyTimeout` expires fails the +command with HTTP 429, `sandbox at capacity: pod ... found no node with room +for it within ...` (the scheduler's reason follows), like a full capacity +queue: the panel reports a failed command and does not pause the task. The +pods are kept with their capacity slot, and the next command for the task +waits for them instead of starting over; without one they are removed after +`sandbox.scaling.idleTimeout` like the pods of any idle task. + +A dedicated pool that scales from zero needs the autoscaler to know what a +node of it will look like. With Cluster API, annotate the MachineDeployment +(values for a 2 CPU / 4 GiB node): + +```yaml +cluster.x-k8s.io/cluster-api-autoscaler-node-group-min-size: "0" +cluster.x-k8s.io/cluster-api-autoscaler-node-group-max-size: "3" +capacity.cluster-autoscaler.kubernetes.io/cpu: "2" +capacity.cluster-autoscaler.kubernetes.io/memory: "4042Mi" +capacity.cluster-autoscaler.kubernetes.io/ephemeral-disk: "100Gi" # workers request 1Gi +capacity.cluster-autoscaler.kubernetes.io/labels: "node.cluster.x-k8s.io/pool=sandbox" +capacity.cluster-autoscaler.kubernetes.io/taints: "artex.io/sandbox=true:NoSchedule" +``` + +and install with: + +```yaml +sandbox: + nodeSelector: + node.cluster.x-k8s.io/pool: sandbox + tolerations: + - {key: artex.io/sandbox, operator: Equal, value: "true", effect: NoSchedule} +``` + +The autoscaler's service account must be able to read the infrastructure +machine templates (`dockermachinetemplates`, `awsmachinetemplates`, ...): the +cluster-autoscaler Helm chart 9.61.0 does not grant it, and without it the +`clusterapi` provider never finishes its cache sync and never scales up. + +**ReadWriteOnce.** Task pods are pinned to the runner's node with a +`metadata.name` node affinity, which no new node can satisfy. The autoscaler +correctly does not scale up for them (`NotTriggerScaleUp`, "predicate +NodeAffinity didn't pass ... No expansion options"); they wait for room on +that one node and fail with the 429 above at `sandbox.podReadyTimeout`. Use +`ReadWriteMany` storage on autoscaled clusters. ## Network readiness @@ -130,12 +286,21 @@ do not match `sandbox.dns.*`. - **Runner health returns 409.** The runner cannot list pods. Check the Role binding and `kubectl -n logs deploy/-runner`. - **Task pods stay Pending.** With `ReadWriteOnce`, the node the runner runs on - needs capacity for the task pods. + needs capacity for the task pods. Lower `sandbox.scaling.maxActive` or the + worker requests, or move to a `ReadWriteMany` volume. +- **`sandbox at capacity: pod ... found no node with room for it`.** No node + had room for a task pod within `sandbox.podReadyTimeout`. With a cluster + autoscaler, raise the timeout above the node provisioning time; see + [Cluster autoscaler](#cluster-autoscaler). +- **`sandbox at capacity`.** Every slot stayed busy for the whole queue timeout. + Raise `sandbox.scaling.maxActive` if the nodes have room, or + `sandbox.scaling.queueTimeout` if waiting longer is acceptable. ## Limitations -- One panel and one runner (single-writer data, in-memory task state in the - runner, which re-adopts existing task pods by label after a restart). +- One panel and one runner (single-writer data, in-memory task and scaling state + in the runner, which re-adopts existing task pods by label after a restart). + No HPA for either; see [Scaling](#scaling). - There is no per-pod PID limit in the pod API. Set `--pod-max-pids` on the kubelet to bound fork bombs, as the Docker backend's `PidsLimit` does. - The opt-in DNS egress guard (`docker-compose.egress.yml`) has no Kubernetes diff --git a/deploy/helm/artex/templates/_helpers.tpl b/deploy/helm/artex/templates/_helpers.tpl index a15a412dd..fdd133011 100644 --- a/deploy/helm/artex/templates/_helpers.tpl +++ b/deploy/helm/artex/templates/_helpers.tpl @@ -64,6 +64,14 @@ app.kubernetes.io/component: {{ index . 1 }} {{- if eq .Values.persistence.data.accessMode "ReadWriteOnce" -}}true{{- end -}} {{- end -}} +{{/* Extra pod annotations, every value quoted: annotation values must be strings, + and --set safe-to-evict=false would otherwise render a YAML boolean. */}} +{{- define "artex.podAnnotations" -}} +{{- range $k, $v := . }} +{{ $k }}: {{ $v | toString | quote }} +{{- end }} +{{- end -}} + {{- define "artex.pullSecrets" -}} {{- with .Values.images.pullSecrets }} imagePullSecrets: diff --git a/deploy/helm/artex/templates/panel.yaml b/deploy/helm/artex/templates/panel.yaml index 94a0c8604..b93454e64 100644 --- a/deploy/helm/artex/templates/panel.yaml +++ b/deploy/helm/artex/templates/panel.yaml @@ -20,6 +20,9 @@ spec: app.kubernetes.io/component: panel annotations: checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }} + {{- with .Values.panel.podAnnotations }} + {{- include "artex.podAnnotations" . | nindent 8 }} + {{- end }} spec: {{- include "artex.pullSecrets" . | nindent 6 }} # The panel never talks to the Kubernetes API: the runner does. diff --git a/deploy/helm/artex/templates/postgres.yaml b/deploy/helm/artex/templates/postgres.yaml index 5e87f2d29..7b75eb702 100644 --- a/deploy/helm/artex/templates/postgres.yaml +++ b/deploy/helm/artex/templates/postgres.yaml @@ -33,10 +33,22 @@ spec: labels: {{- include "artex.labels" . | nindent 8 }} app.kubernetes.io/component: postgres + {{- with .Values.postgres.podAnnotations }} + annotations: + {{- include "artex.podAnnotations" . | nindent 8 }} + {{- end }} spec: {{- include "artex.pullSecrets" . | nindent 6 }} automountServiceAccountToken: false enableServiceLinks: false + {{- with .Values.postgres.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.postgres.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} securityContext: runAsUser: 70 # postgres user in the alpine image runAsGroup: 70 diff --git a/deploy/helm/artex/templates/runner.yaml b/deploy/helm/artex/templates/runner.yaml index facb24f47..b6479b5a9 100644 --- a/deploy/helm/artex/templates/runner.yaml +++ b/deploy/helm/artex/templates/runner.yaml @@ -81,6 +81,9 @@ spec: app.kubernetes.io/component: runner annotations: checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }} + {{- with .Values.runner.podAnnotations }} + {{- include "artex.podAnnotations" . | nindent 8 }} + {{- end }} spec: {{- include "artex.pullSecrets" . | nindent 6 }} serviceAccountName: {{ include "artex.fullname" . }}-runner @@ -128,12 +131,30 @@ spec: value: /app/data/tasks - name: ARTEX_AUDIT_ROOT value: /app/data/egress-audit + # Scale history, totals and cold-start samples survive a runner restart. + - name: ARTEX_KUBE_STATE_DIR + value: /app/data/runner-state - name: ARTEX_KUBE_POD_READY_TIMEOUT value: {{ .Values.sandbox.podReadyTimeout | quote }} - name: ARTEX_KUBE_WORKER_CPU_LIMIT value: {{ .Values.sandbox.worker.cpuLimit | quote }} - name: ARTEX_KUBE_WORKER_MEMORY_LIMIT value: {{ .Values.sandbox.worker.memoryLimit | quote }} + {{- /* Defaults repeated here: "helm upgrade --reuse-values" from a release + that predates these values does not pick them up from values.yaml. */}} + {{- $scaling := .Values.sandbox.scaling | default dict }} + - name: ARTEX_KUBE_WORKER_CPU_REQUEST + value: {{ .Values.sandbox.worker.cpuRequest | default "100m" | toString | quote }} + - name: ARTEX_KUBE_WORKER_MEMORY_REQUEST + value: {{ .Values.sandbox.worker.memoryRequest | default "128Mi" | toString | quote }} + - name: ARTEX_KUBE_IDLE_TIMEOUT + value: {{ hasKey $scaling "idleTimeout" | ternary $scaling.idleTimeout "15m" | toString | quote }} + - name: ARTEX_KUBE_MAX_ACTIVE + value: {{ hasKey $scaling "maxActive" | ternary $scaling.maxActive 10 | int | quote }} + {{- with $scaling.queueTimeout }} + - name: ARTEX_KUBE_QUEUE_TIMEOUT + value: {{ . | quote }} + {{- end }} - name: ARTEX_KUBE_DNS_NAMESPACE value: {{ .Values.sandbox.dns.namespace | quote }} - name: ARTEX_KUBE_DNS_LABELS @@ -146,6 +167,18 @@ spec: - name: ARTEX_KUBE_RUNTIME_CLASS value: {{ . | quote }} {{- end }} + {{- with .Values.sandbox.nodeSelector }} + - name: ARTEX_KUBE_NODE_SELECTOR + value: {{ $l := list }}{{ range $k, $v := . }}{{ $l = append $l (printf "%s=%s" $k $v) }}{{ end }}{{ join "," $l | quote }} + {{- end }} + {{- with .Values.sandbox.tolerations }} + - name: ARTEX_KUBE_TOLERATIONS + value: {{ toJson . | quote }} + {{- end }} + {{- with .Values.sandbox.priorityClassName }} + - name: ARTEX_KUBE_PRIORITY_CLASS + value: {{ . | quote }} + {{- end }} {{- if include "artex.pinToNode" . }} - name: ARTEX_KUBE_PIN_NODE valueFrom: @@ -183,6 +216,9 @@ spec: - name: data mountPath: /app/data/egress-audit subPath: egress-audit + - name: data + mountPath: /app/data/runner-state + subPath: runner-state volumes: - name: data persistentVolumeClaim: diff --git a/deploy/helm/artex/values.schema.json b/deploy/helm/artex/values.schema.json index b4779c359..a70c8dd4e 100644 --- a/deploy/helm/artex/values.schema.json +++ b/deploy/helm/artex/values.schema.json @@ -35,6 +35,22 @@ "mode": { "enum": ["required", "off"] }, "runtimeClassName": { "type": "string" }, "podReadyTimeout": { "type": "string", "pattern": "^[0-9]+(ms|s|m|h)$" }, + "worker": { + "type": "object", + "properties": { + "cpuRequest": { "type": ["string", "integer", "number"], "pattern": "^[0-9]+(\\.[0-9]+)?(m|k|M|G|T|Ki|Mi|Gi|Ti)?$", "exclusiveMinimum": 0 }, + "memoryRequest": { "type": ["string", "integer", "number"], "pattern": "^[0-9]+(\\.[0-9]+)?(m|k|M|G|T|Ki|Mi|Gi|Ti)?$", "exclusiveMinimum": 0 } + } + }, + "scaling": { + "type": "object", + "additionalProperties": false, + "properties": { + "idleTimeout": { "type": ["string", "integer"], "pattern": "^(0|[0-9]+(ms|s|m|h))$", "minimum": 0, "maximum": 0 }, + "maxActive": { "type": "integer", "minimum": 0 }, + "queueTimeout": { "type": "string", "pattern": "^([1-9][0-9]*(ms|s|m|h))?$" } + } + }, "proxyDeniedCIDRs": { "type": "array", "items": { "type": "string", "pattern": "^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$" } diff --git a/deploy/helm/artex/values.yaml b/deploy/helm/artex/values.yaml index 148f59f4c..8330a165d 100644 --- a/deploy/helm/artex/values.yaml +++ b/deploy/helm/artex/values.yaml @@ -59,6 +59,10 @@ panel: # Ignored when the data volume is ReadWriteOnce and the sandbox is on: the panel # must then share the runner's node. affinity: {} + # Extra pod annotations. On an autoscaled cluster, + # cluster-autoscaler.kubernetes.io/safe-to-evict: "false" keeps the cluster + # autoscaler from moving the panel (and its running agents) to drain a node. + podAnnotations: {} runner: replicas: 1 # Task state is kept per runner; keep 1. @@ -71,6 +75,9 @@ runner: memory: 256Mi nodeSelector: {} tolerations: [] + # Extra pod annotations (see panel.podAnnotations). Moving the runner cuts the + # exec streams of running commands; it re-adopts the task pods on restart. + podAnnotations: {} sandbox: # "required": every agent command runs in a per-task pod (recommended). @@ -78,10 +85,37 @@ sandbox: mode: required # Optional RuntimeClass for task pods (gvisor, kata, ...) for kernel isolation. runtimeClassName: "" + # How long a task's first command waits for its pods: scheduling, image pull + # and network readiness. With a cluster autoscaler it must also cover adding a + # node (see README "Cluster autoscaler"; 5m-10m is typical). A pod still + # unschedulable at the timeout fails the command as "sandbox at capacity". podReadyTimeout: 2m + # Placement of task pods (worker and proxy), for example on a dedicated, + # tainted node pool that a cluster autoscaler scales. Ignored for scheduling + # purposes with a ReadWriteOnce data volume, which pins task pods to the + # runner's node. + nodeSelector: {} + tolerations: [] + priorityClassName: "" worker: cpuLimit: "2" memoryLimit: 2Gi + # What the scheduler (and a cluster autoscaler) reserves per worker pod. Must + # not exceed the limits. + cpuRequest: 100m + memoryRequest: 128Mi + # Per-task pods are scaled by the runner, not by an HPA. + scaling: + # A task with no command for this long is scaled to zero: its worker and proxy + # pods are deleted, its Service, NetworkPolicies and workspace are kept, and the + # next command starts the pods again. "0" never scales down. + idleTimeout: 15m + # Tasks that may have pods at the same time. At the cap a task that needs pods + # takes the place of the least recently used idle task, or waits when every + # task is running a command. 0 = no cap. + maxActive: 10 + # How long a command waits for a free slot before it fails. Empty = podReadyTimeout. + queueTimeout: "" # IPv4 ranges the egress proxy pods may never reach (NetworkPolicy, in addition to # the proxy's own allowlist). Task scope CIDRs are allowed back explicitly. # Empty = built-in default (RFC1918, CGNAT, loopback, link-local, metadata, multicast). @@ -126,6 +160,11 @@ postgres: memory: 256Mi limits: memory: 1Gi + nodeSelector: {} + tolerations: [] + # Extra pod annotations (see panel.podAnnotations). Its emptyDir volumes + # already keep the cluster autoscaler from draining its node by default. + podAnnotations: {} # Used when enabled=false. external: host: "" diff --git a/docs/SANDBOX.md b/docs/SANDBOX.md index e1f8ec9af..25d326494 100644 --- a/docs/SANDBOX.md +++ b/docs/SANDBOX.md @@ -16,7 +16,10 @@ from disposable per-task **worker** containers (`artex-worker:local`). `GET /v1/tasks` is a read-only status listing (worker and proxy state, scope, proxy address) that the panel's **System > Sandbox** page polls through `GET /api/sandbox/overview`; the panel still holds no Docker or - Kubernetes credentials. + Kubernetes credentials. The page's egress feed is read by the panel from + `ARTEX_AUDIT_ROOT` when that is set in the panel's environment too, else + from `/egress-audit`. Task IDs are validated exactly as sent (no + trimming): an ID with surrounding whitespace is rejected with HTTP 400. 3. **`artex-worker-` (`artex-worker:local`)**: Runs as `10001:10001`, `--read-only`, `--cap-drop ALL`, `--security-opt no-new-privileges:true`, `--pids-limit 512`, `--memory 2g`, `--cpus 2`, bounded `tmpfs` on `/tmp` and @@ -30,6 +33,82 @@ from disposable per-task **worker** containers (`artex-worker:local`). (`:3128`) and SOCKS5 (`:1080`) with DNS pinning (no rebinding window). Logs one JSON line per connection to `/app/data/egress-audit//egress.jsonl` and stdout. +## Scaling on Kubernetes + +With `ARTEX_RUNNER_BACKEND=kubernetes` (the Helm chart) the runner scales each +task's pods. The Docker backend keeps a task's containers until the task is +deleted and reports scaling as unsupported. + +| Runner env | Chart value | Default (chart) | | +|---|---|---|---| +| `ARTEX_KUBE_IDLE_TIMEOUT` | `sandbox.scaling.idleTimeout` | `15m` | No command for this long: the worker and proxy pods are deleted. `0` disables it. Unset on a hand-run runner means disabled. | +| `ARTEX_KUBE_MAX_ACTIVE` | `sandbox.scaling.maxActive` | `10` | Tasks with pods at the same time. `0` is unlimited. | +| `ARTEX_KUBE_QUEUE_TIMEOUT` | `sandbox.scaling.queueTimeout` | pod ready timeout | Longest wait for a free slot. | +| `ARTEX_KUBE_WORKER_CPU_REQUEST` / `_MEMORY_REQUEST` | `sandbox.worker.cpuRequest` / `memoryRequest` | `100m` / `128Mi` | Worker pod resource requests. | +| `ARTEX_KUBE_STATE_DIR` | always set: `/app/data/runner-state` (data volume sub path `runner-state`) | unset (history in memory only) | Directory for `scaling.json`: scale history, totals and cold-start samples that survive a runner restart. | + +- **Scale to zero** keeps the per-task proxy Service, both NetworkPolicies and the + workspace. The next `exec` goes through the same path as a first start (pods, + readiness, network probes) and is recorded as a `resume`. An `exec` that + arrives during a scale-down waits for it and then resumes the task; it does + not fail. +- **At the cap** a scale-up evicts the least recently used task that has no + command in flight. If there is none, it waits first-in first-out and then + fails with HTTP 429 (`sandbox at capacity`). The panel reports that to the + agent as a failed command and does not pause the task. + A deleted task keeps its slot until its pods are confirmed gone, so the cap + holds while they terminate. +- **Failed scale-up.** When a start fails after creating pods (image pull error, + pods never ready, network never ready), the runner deletes those pods, frees + the slot at once and records a `scale_up_failed` event with the error. The + task keeps its Service and policies (shown as scaled to zero) and the next + `exec` retries. If the pods cannot be deleted the slot stays taken until the + idle reaper or a `Delete` removes them. A pod still unschedulable at the ready + timeout is the exception (see Node autoscaling): its pods keep the slot, the + next `exec` waits on them, and the idle reaper removes them if none comes. +- **Status.** `GET /v1/tasks` adds per task `scaling_state`, `in_flight`, + `last_activity` and `idle_expires_at`, and a `scaling` object: configuration, + `active` / `starting` / `queued` / `scaled_to_zero` counts, `cold_start` + (`count`, `last_ms`, `p50_ms`, `p95_ms`, `samples_ms`) and the last 100 + `events` (`time`, `task_id`, `kind` (`scale_up`, `scale_down`, + `scale_up_failed`), `reason`, and for a scale-up `duration_ms` from the first + API call to open network paths, plus `queue_ms` when it waited for a slot and + `error` when it failed), `totals` (`scale_ups`, `scale_downs`, + `scale_up_failures` since `since`) and `persisted`. `active` counts slots in + use, including deleted tasks whose pods are still terminating. +- **History across restarts.** With `ARTEX_KUBE_STATE_DIR` set the runner keeps + events, totals and cold-start samples in `scaling.json` there (schema + `version` 1, at most 100 events and 100 samples). It writes the file at most + every 2 seconds after an event and on shutdown, through a temporary file and + a rename, so a crash leaves the previous version. A missing, unreadable, + corrupt or other-version file is logged and the runner starts with an empty + history. Live state (which tasks have pods) is never read from the file: it + is rebuilt from the cluster at startup. No extra RBAC is needed. +- **Node autoscaling.** Worker requests let a cluster autoscaler add nodes for + pending worker pods when the data volume is `ReadWriteMany`. A `ReadWriteOnce` + volume pins every task pod to the runner's node, so the autoscaler (correctly) + adds nothing there. Verified with the official cluster-autoscaler on Cluster + API (`scripts/capd-autoscaler-e2e.sh`); the chart README's "Cluster + autoscaler" section has the measured timings and recommended values. In + short: raise `ARTEX_KUBE_POD_READY_TIMEOUT` (`sandbox.podReadyTimeout`) above + the node provisioning time; a task pod still unschedulable at that timeout + fails the command with HTTP 429 (`sandbox at capacity`), the panel does not + pause the task, and the next command waits for the same pods. Task pods are + bare pods that the autoscaler never evicts, so nodes drain when their tasks + scale to zero. `ARTEX_KUBE_NODE_SELECTOR` (`k=v,...`), + `ARTEX_KUBE_TOLERATIONS` (JSON) and `ARTEX_KUBE_PRIORITY_CLASS` + (`sandbox.nodeSelector` / `tolerations` / `priorityClassName`) place task + pods on a dedicated pool. +- **Status fields.** Each task in `GET /v1/tasks` also has `health` + (`healthy`, `degraded`, `starting`, `queued`, `scaled_to_zero`), + `scope_known` and `scope_source` (`live` from the running proxy, + `last_applied` from the proxy NetworkPolicy of a task scaled to zero), and + the response has a `summary` (`total`, `expected`, `healthy`, `degraded`, + `starting`, `queued`, `scaled_to_zero`). The panel's + `/api/sandbox/overview` carries the same. +- **No HPA for the runner.** It is the single writer of task pods and holds task + and scaling state in memory; run exactly one replica. + ## Running with the sandbox The runner, worker and proxy are part of `docker-compose.yml` and diff --git a/sandbox/client.go b/sandbox/client.go index 42593b82b..1386ee0e0 100644 --- a/sandbox/client.go +++ b/sandbox/client.go @@ -79,6 +79,8 @@ func (c *Client) doJSON(ctx context.Context, method, path string, reqBody, out a return fmt.Errorf("%w: %s", ErrNotFound, msg) case http.StatusConflict: return fmt.Errorf("%w: %s", ErrDockerUnavailable, msg) + case http.StatusTooManyRequests: + return fmt.Errorf("%w: %s", ErrCapacity, msg) default: return fmt.Errorf("%w: HTTP %d: %s", ErrRunnerUnavailable, resp.StatusCode, msg) } diff --git a/sandbox/helmchart_placement_test.go b/sandbox/helmchart_placement_test.go new file mode 100644 index 000000000..23d148c50 --- /dev/null +++ b/sandbox/helmchart_placement_test.go @@ -0,0 +1,61 @@ +package sandbox + +import ( + "reflect" + "testing" +) + +// Values for an autoscaled cluster: task pod placement reaches the runner in +// a form KubeConfigFromEnv accepts, and the control components take a node +// selector, tolerations and pod annotations. +func TestHelmChartAutoscalerPlacement(t *testing.T) { + objs := renderChart(t, + "persistence.data.accessMode=ReadWriteMany", + "sandbox.nodeSelector.pool=sandbox", + "sandbox.tolerations[0].key=artex.io/sandbox", "sandbox.tolerations[0].operator=Exists", "sandbox.tolerations[0].effect=NoSchedule", + "sandbox.priorityClassName=artex-sandbox", + `panel.podAnnotations.cluster-autoscaler\.kubernetes\.io/safe-to-evict=false`, + `runner.podAnnotations.cluster-autoscaler\.kubernetes\.io/safe-to-evict=false`, + `postgres.podAnnotations.cluster-autoscaler\.kubernetes\.io/safe-to-evict=false`, + "postgres.nodeSelector.pool=base", + "postgres.tolerations[0].key=base", "postgres.tolerations[0].operator=Exists", + ) + runner := findObj(objs, "Deployment", "rel-artex-runner") + env, _ := containerEnv(dig(podSpecOf(runner), "containers", 0)) + for k, v := range env { + t.Setenv(k, v) + } + cfg, err := KubeConfigFromEnv() + if err != nil { + t.Fatalf("runner env from the chart: %v", err) + } + if !reflect.DeepEqual(cfg.NodeSelector, map[string]string{"pool": "sandbox"}) || cfg.PriorityClassName != "artex-sandbox" || + len(cfg.Tolerations) != 1 || cfg.Tolerations[0]["key"] != "artex.io/sandbox" || cfg.Tolerations[0]["effect"] != "NoSchedule" { + t.Fatalf("task placement from the chart: %+v %+v %q", cfg.NodeSelector, cfg.Tolerations, cfg.PriorityClassName) + } + for _, o := range []struct{ kind, name string }{{"Deployment", "rel-artex-panel"}, {"Deployment", "rel-artex-runner"}, {"StatefulSet", "rel-artex-postgres"}} { + ann := dig(findObj(objs, o.kind, o.name), "spec", "template", "metadata", "annotations", "cluster-autoscaler.kubernetes.io/safe-to-evict") + if ann != "false" { + t.Errorf("%s safe-to-evict = %v", o.name, ann) + } + } + pg := podSpecOf(findObj(objs, "StatefulSet", "rel-artex-postgres")) + if dig(pg, "nodeSelector", "pool") != "base" || dig(pg, "tolerations", 0, "key") != "base" { + t.Errorf("postgres placement = %v %v", dig(pg, "nodeSelector"), dig(pg, "tolerations")) + } + + // Defaults: none of it. + def := renderChart(t) + denv, _ := containerEnv(dig(podSpecOf(findObj(def, "Deployment", "rel-artex-runner")), "containers", 0)) + for _, k := range []string{"ARTEX_KUBE_NODE_SELECTOR", "ARTEX_KUBE_TOLERATIONS", "ARTEX_KUBE_PRIORITY_CLASS"} { + if v, ok := denv[k]; ok { + t.Errorf("default runner env has %s=%q", k, v) + } + } + if a := dig(findObj(def, "StatefulSet", "rel-artex-postgres"), "spec", "template", "metadata", "annotations"); a != nil { + t.Errorf("default postgres pod annotations %v", a) + } + if s := dig(podSpecOf(findObj(def, "StatefulSet", "rel-artex-postgres")), "nodeSelector"); s != nil { + t.Errorf("default postgres nodeSelector %v", s) + } +} diff --git a/sandbox/helmchart_test.go b/sandbox/helmchart_test.go index b9689458a..e68c34362 100644 --- a/sandbox/helmchart_test.go +++ b/sandbox/helmchart_test.go @@ -11,6 +11,7 @@ import ( "slices" "strings" "testing" + "time" "gopkg.in/yaml.v3" ) @@ -252,6 +253,10 @@ func TestHelmChartRunnerEnvMatchesBackend(t *testing.T) { if mounts[plain[EnvWorkspaceRoot]] != "tasks" || mounts[plain[EnvAuditRoot]] != "egress-audit" { t.Errorf("runner mounts %v vs roots %s %s", mounts, plain[EnvWorkspaceRoot], plain[EnvAuditRoot]) } + // Scaling history lives in its own sub path of the data volume. + if cfg.StateDir == "" || mounts[cfg.StateDir] != "runner-state" { + t.Errorf("state dir %q not mounted from runner-state (mounts %v)", cfg.StateDir, mounts) + } if dig(refs["ARTEX_KUBE_NAMESPACE"], "fieldRef", "fieldPath") != "metadata.namespace" { t.Errorf("namespace env = %v", refs["ARTEX_KUBE_NAMESPACE"]) } @@ -277,6 +282,78 @@ func TestHelmChartRunnerEnvMatchesBackend(t *testing.T) { } } +// The chart's scaling values reach the runner as the env the backend parses, and +// its defaults are a backend that scales to zero and is capped. +func TestHelmChartScalingValues(t *testing.T) { + runnerCfg := func(t *testing.T, set ...string) (map[string]string, KubeConfig) { + t.Helper() + objs := renderChart(t, set...) + plain, _ := containerEnv(dig(podSpecOf(findObj(objs, "Deployment", "rel-artex-runner")), "containers", 0)) + for _, k := range []string{"ARTEX_KUBE_IDLE_TIMEOUT", "ARTEX_KUBE_MAX_ACTIVE", "ARTEX_KUBE_QUEUE_TIMEOUT", "ARTEX_KUBE_WORKER_CPU_REQUEST", "ARTEX_KUBE_WORKER_MEMORY_REQUEST"} { + t.Setenv(k, "") + } + for k, v := range plain { + t.Setenv(k, v) + } + cfg, err := KubeConfigFromEnv() + if err != nil { + t.Fatalf("KubeConfigFromEnv on rendered env (%v): %v", set, err) + } + // The backend accepts the combination (request against limit included). + cfg.APIServer, cfg.Namespace = "http://127.0.0.1:1", "ns" + if _, err := NewKubernetesBackend(cfg); err != nil { + t.Fatalf("NewKubernetesBackend on rendered env (%v): %v", set, err) + } + return plain, cfg + } + + t.Run("defaults", func(t *testing.T) { + plain, cfg := runnerCfg(t) + if cfg.IdleTimeout != 15*time.Minute || cfg.MaxActive != 10 || cfg.QueueTimeout != 0 { + t.Fatalf("default scaling = idle %s, max %d, queue %s", cfg.IdleTimeout, cfg.MaxActive, cfg.QueueTimeout) + } + if _, set := plain["ARTEX_KUBE_QUEUE_TIMEOUT"]; set { + t.Error("empty queueTimeout rendered: the backend default (pod ready timeout) must apply") + } + if cfg.WorkerCPURequest != "100m" || cfg.WorkerMemoryRequest != "128Mi" { + t.Fatalf("default worker requests = %s %s", cfg.WorkerCPURequest, cfg.WorkerMemoryRequest) + } + }) + t.Run("overrides", func(t *testing.T) { + _, cfg := runnerCfg(t, "sandbox.scaling.idleTimeout=45s", "sandbox.scaling.maxActive=1", "sandbox.scaling.queueTimeout=30s", + "sandbox.worker.cpuRequest=500m", "sandbox.worker.memoryRequest=1Gi") + if cfg.IdleTimeout != 45*time.Second || cfg.MaxActive != 1 || cfg.QueueTimeout != 30*time.Second || cfg.WorkerCPURequest != "500m" || cfg.WorkerMemoryRequest != "1Gi" { + t.Fatalf("cfg = %+v", cfg) + } + }) + // --set turns bare numbers into integers; they must still render as strings. + t.Run("disabled and numeric", func(t *testing.T) { + plain, cfg := runnerCfg(t, "sandbox.scaling.idleTimeout=0", "sandbox.scaling.maxActive=0", "sandbox.worker.cpuRequest=1") + if cfg.IdleTimeout != 0 || cfg.MaxActive != 0 || cfg.WorkerCPURequest != "1" { + t.Fatalf("cfg = %+v", cfg) + } + if plain["ARTEX_KUBE_IDLE_TIMEOUT"] != "0" || plain["ARTEX_KUBE_MAX_ACTIVE"] != "0" { + t.Fatalf("env = %q %q", plain["ARTEX_KUBE_IDLE_TIMEOUT"], plain["ARTEX_KUBE_MAX_ACTIVE"]) + } + }) + // "helm upgrade --reuse-values" from a release that predates these values + // renders without them: the template must fall back to the same defaults. + t.Run("values missing as after reuse-values", func(t *testing.T) { + _, cfg := runnerCfg(t, "sandbox.scaling=null", "sandbox.worker.cpuRequest=null", "sandbox.worker.memoryRequest=null") + if cfg.IdleTimeout != 15*time.Minute || cfg.MaxActive != 10 || cfg.QueueTimeout != 0 || cfg.WorkerCPURequest != "100m" || cfg.WorkerMemoryRequest != "128Mi" { + t.Fatalf("cfg = %+v", cfg) + } + }) + // No HPA and a single runner: the scaling state lives in that one process. + objs := renderChart(t) + if n := len(objsOfKind(objs, "HorizontalPodAutoscaler")); n != 0 { + t.Errorf("chart renders %d HorizontalPodAutoscaler(s)", n) + } + if got := dig(findObj(objs, "Deployment", "rel-artex-runner"), "spec", "replicas"); got != 1 && got != 1.0 { + t.Errorf("runner replicas = %v", got) + } +} + func chartAppVersion(t *testing.T) string { t.Helper() raw, err := os.ReadFile(filepath.Join(chartDir, "Chart.yaml")) @@ -549,6 +626,17 @@ func TestHelmChartSchemaRejectsUnsafeValues(t *testing.T) { "sandbox.proxyDeniedCIDRs={fc00::/7}", "images.pullPolicy=Sometimes", "postgres.enabled=false", + "sandbox.scaling.idleTimeout=5", + "sandbox.scaling.idleTimeout=soon", + "sandbox.scaling.idleTimeout=-15m", + "sandbox.scaling.maxActive=-1", + "sandbox.scaling.maxActive=1.5", + "sandbox.scaling.queueTimeout=0s", + "sandbox.scaling.queueTimeout=never", + "sandbox.scaling.minReplicas=1", + "sandbox.worker.cpuRequest=lots", + "sandbox.worker.cpuRequest=0", + "sandbox.worker.memoryRequest=1GB", } { out, err := exec.Command(helm, "template", "rel", chartDir, "--set", set).CombinedOutput() if err == nil { diff --git a/sandbox/kube.go b/sandbox/kube.go index 35ca52708..ae5dd5752 100644 --- a/sandbox/kube.go +++ b/sandbox/kube.go @@ -32,15 +32,20 @@ import ( // lengths that Kubernetes names and label values reject, so objects are keyed by a // short hash of the task ID (LabelTaskHash) and carry the real ID in an annotation. const ( - LabelTaskHash = "artex.task_hash" - AnnotationTaskID = "artex.task" - AnnotationScope = "artex.scope_hash" - kubeSATokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token" - kubeSACAPath = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" - kubeSANSPath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace" - kubeWorkerName = "worker" - kubeProxyName = "egress-proxy" - kubeDefaultTimeout = 2 * time.Minute + LabelTaskHash = "artex.task_hash" + AnnotationTaskID = "artex.task" + AnnotationScope = "artex.scope_hash" + // The scope last applied to a task, as JSON string arrays, on its proxy + // NetworkPolicy. It outlives the proxy pod, so status can report the scope of + // a task that was scaled to zero, also after a runner restart. + AnnotationScopeDomains = "artex.scope_domains" + AnnotationScopeCIDRs = "artex.scope_cidrs" + kubeSATokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token" + kubeSACAPath = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" + kubeSANSPath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace" + kubeWorkerName = "worker" + kubeProxyName = "egress-proxy" + kubeDefaultTimeout = 2 * time.Minute ) // KubeConfig configures the KubernetesBackend for artex-runner. @@ -84,9 +89,34 @@ type KubeConfig struct { // must share a node. PinNode string + // Placement of task pods: a node selector, tolerations (Kubernetes + // Toleration objects) and a PriorityClass, for example to keep them on a + // dedicated, tainted node pool that a cluster autoscaler scales. + NodeSelector map[string]string + Tolerations []map[string]any + PriorityClassName string + // Worker resources; defaults mirror DockerBackend (2 CPU, 2Gi). WorkerCPULimit string WorkerMemoryLimit string + // Worker resource requests (defaults 100m, 128Mi): what the scheduler and a + // cluster autoscaler reserve per worker. + WorkerCPURequest string + WorkerMemoryRequest string + + // IdleTimeout scales a task to zero (worker and proxy pods deleted; Service, + // NetworkPolicies and workspace kept) once it has had no exec for this long. + // Zero disables idle scale-down. + IdleTimeout time.Duration + // MaxActive caps the tasks that have pods at the same time. At the cap a + // scale-up evicts the least recently used idle task or waits. Zero is unlimited. + MaxActive int + // QueueTimeout bounds that wait; default PodReadyTimeout. + QueueTimeout time.Duration + + // StateDir, when set, keeps the scale history, totals and cold-start samples + // in StateDir/scaling.json so they survive a runner restart. + StateDir string } type kubeTask struct { @@ -96,6 +126,12 @@ type kubeTask struct { workerPod string proxyPod string proxyIP string // ClusterIP of the per-task proxy Service + // The scope last applied to the task's proxy NetworkPolicy. It stays known + // after the proxy pod is gone (scaled to zero). scopeKnown is false for a + // task adopted without a readable proxy policy. + scopeDomains []string + scopeCIDRs []string + scopeKnown bool } // KubernetesBackend implements Backend by creating per-task worker and egress-proxy @@ -112,6 +148,29 @@ type KubernetesBackend struct { locks map[string]*sync.Mutex // tokenOverride is used by tests instead of reading TokenPath. tokenOverride string + + // Scaling state, guarded by mu (see kube_scale.go). now is the clock, replaced + // in tests. + now func() time.Time + scale map[string]*kubeScaleState + waiters []*kubeSlotWaiter + events []ScaleEvent + coldStarts []int64 + totals ScaleTotals + // draining counts capacity slots of deleted tasks whose pods are still + // being removed. + draining int + + // State file (see kube_state.go). saveMu serialises writes and is never + // taken with mu held; saveTimer is the pending debounced save, guarded by mu. + saveMu sync.Mutex + saveTimer *time.Timer + + queueRetry time.Duration + + // testHook, set only by tests, runs at the named points of the scaling code + // (no lock held) so a test can interleave work deterministically. + testHook func(point, taskID string) } // DefaultProxyDeniedCIDRs mirrors the proxy's default-denied IPv4 prefixes that a @@ -193,6 +252,24 @@ func NewKubernetesBackend(cfg KubeConfig) (*KubernetesBackend, error) { if cfg.PodReadyTimeout <= 0 { cfg.PodReadyTimeout = kubeDefaultTimeout } + if cfg.WorkerCPURequest == "" { + cfg.WorkerCPURequest = "100m" + } + if cfg.WorkerMemoryRequest == "" { + cfg.WorkerMemoryRequest = "128Mi" + } + if err := checkKubeRequest("CPU", cfg.WorkerCPURequest, cfg.WorkerCPULimit); err != nil { + return nil, err + } + if err := checkKubeRequest("memory", cfg.WorkerMemoryRequest, cfg.WorkerMemoryLimit); err != nil { + return nil, err + } + if cfg.IdleTimeout < 0 || cfg.MaxActive < 0 || cfg.QueueTimeout < 0 { + return nil, errors.New("kubernetes backend: idle timeout, max active and queue timeout must not be negative") + } + if cfg.QueueTimeout == 0 { + cfg.QueueTimeout = cfg.PodReadyTimeout + } tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12} if strings.HasPrefix(cfg.APIServer, "https://") { @@ -206,13 +283,19 @@ func NewKubernetesBackend(cfg KubeConfig) (*KubernetesBackend, error) { } tlsCfg.RootCAs = pool } - return &KubernetesBackend{ + b := &KubernetesBackend{ cfg: cfg, tls: tlsCfg, http: &http.Client{Transport: &http.Transport{Proxy: nil, TLSClientConfig: tlsCfg}, Timeout: 30 * time.Second}, tasks: map[string]*kubeTask{}, locks: map[string]*sync.Mutex{}, - }, nil + now: time.Now, + scale: map[string]*kubeScaleState{}, + + queueRetry: kubeQueueRetry, + } + b.loadState() + return b, nil } // Namespace returns the namespace task pods are created in. @@ -234,6 +317,12 @@ func (b *KubernetesBackend) Namespace() string { return b.cfg.Namespace } // ARTEX_KUBE_PIN_NODE node name task pods must run on (ReadWriteOnce data volume) // ARTEX_KUBE_WORKER_CPU_LIMIT default "2" // ARTEX_KUBE_WORKER_MEMORY_LIMIT default "2Gi" +// ARTEX_KUBE_WORKER_CPU_REQUEST default "100m" +// ARTEX_KUBE_WORKER_MEMORY_REQUEST default "128Mi" +// ARTEX_KUBE_IDLE_TIMEOUT Go duration; scale an idle task to zero after it. Default 0 (never) +// ARTEX_KUBE_MAX_ACTIVE tasks with pods at the same time. Default 0 (unlimited) +// ARTEX_KUBE_QUEUE_TIMEOUT Go duration; wait for a free slot at the cap. Default: the pod ready timeout +// ARTEX_KUBE_STATE_DIR directory for scaling.json (history across restarts). Default: none func KubeConfigFromEnv() (KubeConfig, error) { get := func(k string) string { return strings.TrimSpace(os.Getenv(k)) } cfg := KubeConfig{ @@ -246,9 +335,44 @@ func KubeConfigFromEnv() (KubeConfig, error) { ServiceAccount: get("ARTEX_KUBE_SERVICE_ACCOUNT"), DNSNamespace: get("ARTEX_KUBE_DNS_NAMESPACE"), PinNode: get("ARTEX_KUBE_PIN_NODE"), + StateDir: get("ARTEX_KUBE_STATE_DIR"), + + PriorityClassName: get("ARTEX_KUBE_PRIORITY_CLASS"), WorkerCPULimit: get("ARTEX_KUBE_WORKER_CPU_LIMIT"), WorkerMemoryLimit: get("ARTEX_KUBE_WORKER_MEMORY_LIMIT"), + + WorkerCPURequest: get("ARTEX_KUBE_WORKER_CPU_REQUEST"), + WorkerMemoryRequest: get("ARTEX_KUBE_WORKER_MEMORY_REQUEST"), + } + for k, v := range map[string]string{"ARTEX_KUBE_WORKER_CPU_REQUEST": cfg.WorkerCPURequest, "ARTEX_KUBE_WORKER_MEMORY_REQUEST": cfg.WorkerMemoryRequest} { + if v == "" { + continue + } + if _, err := parseKubeQuantity(v); err != nil { + return KubeConfig{}, fmt.Errorf("%s: %w", k, err) + } + } + if v := get("ARTEX_KUBE_IDLE_TIMEOUT"); v != "" { + d, err := time.ParseDuration(v) + if err != nil || d < 0 { + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_IDLE_TIMEOUT: %q is not a duration (0 disables idle scale-down)", v) + } + cfg.IdleTimeout = d + } + if v := get("ARTEX_KUBE_MAX_ACTIVE"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 0 { + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_MAX_ACTIVE: %q is not a non-negative integer (0 is unlimited)", v) + } + cfg.MaxActive = n + } + if v := get("ARTEX_KUBE_QUEUE_TIMEOUT"); v != "" { + d, err := time.ParseDuration(v) + if err != nil || d <= 0 { + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_QUEUE_TIMEOUT: %q is not a positive duration", v) + } + cfg.QueueTimeout = d } if v := get("ARTEX_KUBE_PROXY_DENIED_CIDRS"); v != "" { for _, c := range ParseCSV(v) { @@ -269,6 +393,23 @@ func KubeConfigFromEnv() (KubeConfig, error) { cfg.DNSPodLabels[k] = val } } + if v := get("ARTEX_KUBE_NODE_SELECTOR"); v != "" { + cfg.NodeSelector = map[string]string{} + for _, kv := range ParseCSV(v) { + k, val, ok := strings.Cut(kv, "=") + if !ok || k == "" { + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_NODE_SELECTOR: %q is not key=value", kv) + } + cfg.NodeSelector[k] = val + } + } + if v := get("ARTEX_KUBE_TOLERATIONS"); v != "" { + t, err := parseKubeTolerations(v) + if err != nil { + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_TOLERATIONS: %w", err) + } + cfg.Tolerations = t + } if v := get("ARTEX_KUBE_POD_READY_TIMEOUT"); v != "" { d, err := time.ParseDuration(v) if err != nil || d <= 0 { @@ -388,11 +529,18 @@ func (b *KubernetesBackend) Ping(ctx context.Context) error { return err } -// WorkerCount returns the number of tracked tasks. +// WorkerCount returns the number of tracked tasks that have pods; tasks scaled +// to zero do not count. func (b *KubernetesBackend) WorkerCount() int { b.mu.Lock() defer b.mu.Unlock() - return len(b.tasks) + n := 0 + for _, kt := range b.tasks { + if kt.workerPod != "" || kt.proxyPod != "" { + n++ + } + } + return n } type kubeObjectMeta struct { @@ -405,7 +553,13 @@ type kubeObjectMeta struct { type kubePod struct { Metadata kubeObjectMeta `json:"metadata"` Status struct { - Phase string `json:"phase"` + Phase string `json:"phase"` + Conditions []struct { + Type string `json:"type"` + Status string `json:"status"` + Reason string `json:"reason"` + Message string `json:"message"` + } `json:"conditions"` ContainerStatuses []struct { Ready bool `json:"ready"` State struct { @@ -421,9 +575,11 @@ type kubePod struct { } `json:"status"` } -// Recover rebuilds task state from pods carrying artex.managed_by=artex-runner. -// Only pods that also carry a valid task annotation whose hash matches their label -// are adopted. +// Recover rebuilds task state from pods and proxy Services carrying +// artex.managed_by=artex-runner. Only objects that also carry a valid task +// annotation whose hash matches their label are adopted. A Service without pods +// is a task that was scaled to zero. Adopted tasks start their idle timer now: +// the runner does not know when they last ran a command. func (b *KubernetesBackend) Recover(ctx context.Context) (int, error) { var list struct { Items []kubePod `json:"items"` @@ -447,8 +603,41 @@ func (b *KubernetesBackend) Recover(ctx context.Context) (int, error) { for _, s := range svcs.Items { svcIP[s.Metadata.Labels[LabelTaskHash]] = s.Spec.ClusterIP } + // The last-applied scope of each task, from its proxy policy. Best effort: a + // task without it still recovers, and its scope is known again after its next + // command. + var pols struct { + Items []struct { + Metadata kubeObjectMeta `json:"metadata"` + } `json:"items"` + } + if err := b.do(ctx, http.MethodGet, b.nsPath("networkpolicies")+"?labelSelector="+sel, nil, &pols); err != nil { + log.Printf("[runner] recover: list network policies: %v (task scopes unknown until their next command)", err) + } + type lastScope struct{ domains, cidrs []string } + scopes := map[string]lastScope{} + for _, p := range pols.Items { + tid := p.Metadata.Annotations[AnnotationTaskID] + if p.Metadata.Deletion != nil || p.Metadata.Labels[LabelManagedBy] != ManagedByRunner || p.Metadata.Labels[LabelComponent] != ComponentProxy || + ValidateTaskID(tid) != nil || kubeTaskHash(tid) != p.Metadata.Labels[LabelTaskHash] { + continue + } + if d, c, ok := parseScopeAnnotations(p.Metadata.Annotations); ok { + scopes[tid] = lastScope{d, c} + } + } b.mu.Lock() defer b.mu.Unlock() + for _, s := range svcs.Items { + tid := s.Metadata.Annotations[AnnotationTaskID] + if s.Metadata.Deletion != nil || s.Metadata.Labels[LabelManagedBy] != ManagedByRunner || + ValidateTaskID(tid) != nil || kubeTaskHash(tid) != s.Metadata.Labels[LabelTaskHash] || net.ParseIP(s.Spec.ClusterIP) == nil { + continue + } + if b.tasks[tid] == nil { + b.tasks[tid] = &kubeTask{taskID: tid, hash: kubeTaskHash(tid), proxyIP: s.Spec.ClusterIP} + } + } for _, p := range list.Items { if p.Metadata.Deletion != nil || p.Metadata.Labels[LabelManagedBy] != ManagedByRunner { continue @@ -470,6 +659,14 @@ func (b *KubernetesBackend) Recover(ctx context.Context) (int, error) { kt.scopeHash = p.Metadata.Annotations[AnnotationScope] } } + for tid, kt := range b.tasks { + if sc, ok := scopes[tid]; ok && !kt.scopeKnown { + kt.scopeDomains, kt.scopeCIDRs, kt.scopeKnown = sc.domains, sc.cidrs, true + } + st := b.stateLocked(tid) + st.lastActive = b.now() + st.active = kt.workerPod != "" || kt.proxyPod != "" + } return len(b.tasks), nil } @@ -545,6 +742,15 @@ func (b *KubernetesBackend) basePodSpec() map[string]any { if b.cfg.RuntimeClassName != "" { spec["runtimeClassName"] = b.cfg.RuntimeClassName } + if len(b.cfg.NodeSelector) > 0 { + spec["nodeSelector"] = b.cfg.NodeSelector + } + if len(b.cfg.Tolerations) > 0 { + spec["tolerations"] = b.cfg.Tolerations + } + if b.cfg.PriorityClassName != "" { + spec["priorityClassName"] = b.cfg.PriorityClassName + } if b.cfg.PinNode != "" { spec["affinity"] = map[string]any{"nodeAffinity": map[string]any{ "requiredDuringSchedulingIgnoredDuringExecution": map[string]any{ @@ -633,7 +839,7 @@ func (b *KubernetesBackend) workerPodObj(name string, kt *kubeTask) map[string]a "env": env, "securityContext": ctrSec, "resources": map[string]any{ - "requests": map[string]string{"cpu": "100m", "memory": "128Mi"}, + "requests": map[string]string{"cpu": b.cfg.WorkerCPURequest, "memory": b.cfg.WorkerMemoryRequest}, "limits": map[string]string{"cpu": b.cfg.WorkerCPULimit, "memory": b.cfg.WorkerMemoryLimit, "ephemeral-storage": "1Gi"}, }, "volumeMounts": []any{ @@ -700,7 +906,7 @@ func (b *KubernetesBackend) workerPolicyObj(name string, kt *kubeTask) map[strin // proxyPolicyObj admits only the task's worker and lets the proxy reach cluster DNS, // public addresses, and the task's scope CIDRs. -func (b *KubernetesBackend) proxyPolicyObj(name string, kt *kubeTask, scopeCIDRs []string) map[string]any { +func (b *KubernetesBackend) proxyPolicyObj(name string, kt *kubeTask, scopeDomains, scopeCIDRs []string) map[string]any { egress := []any{ map[string]any{ "to": []any{map[string]any{ @@ -728,7 +934,7 @@ func (b *KubernetesBackend) proxyPolicyObj(name string, kt *kubeTask, scopeCIDRs return map[string]any{ "apiVersion": "networking.k8s.io/v1", "kind": "NetworkPolicy", - "metadata": b.meta(name, kt, ComponentProxy, nil), + "metadata": b.meta(name, kt, ComponentProxy, scopeAnnotations(scopeDomains, scopeCIDRs)), "spec": map[string]any{ "podSelector": map[string]any{"matchLabels": b.taskLabels(kt, ComponentProxy)}, "policyTypes": []string{"Ingress", "Egress"}, @@ -741,6 +947,82 @@ func (b *KubernetesBackend) proxyPolicyObj(name string, kt *kubeTask, scopeCIDRs } } +// scopeAnnotations records a task scope on its proxy NetworkPolicy. +func scopeAnnotations(domains, cidrs []string) map[string]string { + enc := func(v []string) string { + if v == nil { + v = []string{} + } + raw, _ := json.Marshal(v) + return string(raw) + } + return map[string]string{AnnotationScopeDomains: enc(domains), AnnotationScopeCIDRs: enc(cidrs)} +} + +// parseScopeAnnotations reads what scopeAnnotations wrote. ok is false when +// either annotation is missing or malformed (a policy written by an older +// runner, or edited by hand). +func parseScopeAnnotations(ann map[string]string) (domains, cidrs []string, ok bool) { + dec := func(key string) ([]string, bool) { + raw, found := ann[key] + if !found { + return nil, false + } + var v []string + if json.Unmarshal([]byte(raw), &v) != nil { + return nil, false + } + out := []string{} + for _, s := range v { + if s = strings.TrimSpace(s); s != "" { + out = append(out, s) + } + } + return out, true + } + d, okD := dec(AnnotationScopeDomains) + c, okC := dec(AnnotationScopeCIDRs) + if !okD || !okC { + return nil, nil, false + } + return d, c, true +} + +// parseKubeTolerations reads a JSON array of Kubernetes Toleration objects and +// rejects unknown fields and malformed values, so a typo fails at startup +// instead of on every task pod the API server refuses. +func parseKubeTolerations(raw string) ([]map[string]any, error) { + var in []map[string]any + if err := json.Unmarshal([]byte(raw), &in); err != nil { + return nil, fmt.Errorf("not a JSON array of tolerations: %v", err) + } + for i, t := range in { + for k, v := range t { + switch k { + case "key", "value": + if _, ok := v.(string); !ok { + return nil, fmt.Errorf("toleration %d: %s must be a string", i, k) + } + case "operator": + if v != "Exists" && v != "Equal" { + return nil, fmt.Errorf("toleration %d: operator %v (want Exists or Equal)", i, v) + } + case "effect": + if v != "NoSchedule" && v != "PreferNoSchedule" && v != "NoExecute" { + return nil, fmt.Errorf("toleration %d: effect %v (want NoSchedule, PreferNoSchedule or NoExecute)", i, v) + } + case "tolerationSeconds": + if n, ok := v.(float64); !ok || n != float64(int64(n)) { + return nil, fmt.Errorf("toleration %d: tolerationSeconds must be an integer", i) + } + default: + return nil, fmt.Errorf("toleration %d: unknown field %q", i, k) + } + } + } + return in, nil +} + // applyPolicy creates a NetworkPolicy or replaces an existing one. func (b *KubernetesBackend) applyPolicy(ctx context.Context, obj map[string]any) error { name := obj["metadata"].(map[string]any)["name"].(string) @@ -759,17 +1041,37 @@ func (b *KubernetesBackend) getPod(ctx context.Context, name string) (*kubePod, return &p, nil } +// unschedulable returns the scheduler's message when the pod is waiting for a +// node with room for it (PodScheduled=False, reason Unschedulable), which on an +// autoscaled cluster is what a pending scale-up looks like. +func (p *kubePod) unschedulable() (string, bool) { + for _, c := range p.Status.Conditions { + if c.Type == "PodScheduled" && c.Status == "False" && c.Reason == "Unschedulable" { + return c.Message, true + } + } + return "", false +} + // waitPodReady polls until every container of the pod is ready. It fails fast on -// image pull errors and terminated containers. +// image pull errors and terminated containers. A pod still unschedulable at the +// timeout is a capacity condition, not a runner failure: the error wraps +// ErrCapacity (HTTP 429), so the panel reports a failed command the agent may +// retry instead of pausing the task as if the runner were down. func (b *KubernetesBackend) waitPodReady(ctx context.Context, name string) error { ctx, cancel := context.WithTimeout(ctx, b.cfg.PodReadyTimeout) defer cancel() + var last *kubePod for { p, err := b.getPod(ctx, name) if err != nil && !isKubeStatus(err, http.StatusNotFound) { - return err + if ctx.Err() == nil || last == nil { + return err + } + p = nil // the deadline hit the request: decide on the last state seen } if p != nil { + last = p if p.Status.Phase == "Failed" || p.Status.Phase == "Succeeded" { return fmt.Errorf("pod %s ended in phase %s", name, p.Status.Phase) } @@ -791,6 +1093,12 @@ func (b *KubernetesBackend) waitPodReady(ctx context.Context, name string) error } select { case <-ctx.Done(): + if last != nil { + if msg, ok := last.unschedulable(); ok { + return fmt.Errorf("%w: pod %s found no node with room for it within %s (%s); on an autoscaled cluster raise sandbox.podReadyTimeout above the node provisioning time", + ErrCapacity, name, b.cfg.PodReadyTimeout, msg) + } + } return fmt.Errorf("pod %s not ready after %s: %w", name, b.cfg.PodReadyTimeout, ctx.Err()) case <-time.After(500 * time.Millisecond): } @@ -816,6 +1124,39 @@ func (b *KubernetesBackend) podAlive(ctx context.Context, name string) bool { return true } +// reusablePod reports whether name is this task's pod (by label, and for the +// proxy with the wanted scope) that can serve the task without being replaced: +// running with every container ready, or still coming up (phase Pending, not +// being deleted, no container in a state that waiting cannot fix). +func (b *KubernetesBackend) reusablePod(ctx context.Context, name string, kt *kubeTask, component, scopeHash string) bool { + if name == "" { + return false + } + p, err := b.getPod(ctx, name) + if err != nil || p.Metadata.Deletion != nil || (p.Status.Phase != "Pending" && p.Status.Phase != "Running") { + return false + } + l := p.Metadata.Labels + if l[LabelManagedBy] != ManagedByRunner || l[LabelTaskHash] != kt.hash || l[LabelComponent] != component { + return false + } + if component == ComponentProxy && p.Metadata.Annotations[AnnotationScope] != scopeHash { + return false + } + for _, cs := range p.Status.ContainerStatuses { + if w := cs.State.Waiting; w != nil { + switch w.Reason { + case "ErrImagePull", "ImagePullBackOff", "InvalidImageName", "CreateContainerConfigError", "CreateContainerError": + return false + } + } + if cs.State.Terminated != nil || (p.Status.Phase == "Running" && !cs.Ready) { + return false + } + } + return p.Status.Phase == "Pending" || len(p.Status.ContainerStatuses) > 0 +} + // deletePod removes a pod immediately and waits until it is gone, so a pod with the // same name can be created again. func (b *KubernetesBackend) deletePodAndWait(ctx context.Context, name string) error { @@ -849,15 +1190,24 @@ func (b *KubernetesBackend) taskLock(taskID string) *sync.Mutex { return l } -func (b *KubernetesBackend) ensureTask(ctx context.Context, taskID string, scopeDomains, scopeCIDRs []string) (*kubeTask, error) { +// ensureTask returns the task with a ready worker and proxy, creating or +// recreating pods as needed. A task without pods (new, or scaled to zero) first +// takes a capacity slot. +func (b *KubernetesBackend) ensureTask(ctx context.Context, taskID string, st *kubeScaleState, scopeDomains, scopeCIDRs []string) (*kubeTask, error) { l := b.taskLock(taskID) l.Lock() defer l.Unlock() b.mu.Lock() + if st.deleted { + b.mu.Unlock() + return nil, fmt.Errorf("%w: task %s was deleted", ErrNotFound, taskID) + } kt := b.tasks[taskID] + wasActive := st.active b.mu.Unlock() - if kt != nil { + known := kt != nil + if known { cp := *kt kt = &cp } @@ -870,7 +1220,104 @@ func (b *KubernetesBackend) ensureTask(ctx context.Context, taskID string, scope return kt, nil } - b.prepareDirs(taskID) + reason := ScaleReasonRecreate + var queued time.Duration + if !wasActive { + reason = ScaleReasonResume + if !known { + reason = ScaleReasonFirstExec + } + var err error + if queued, err = b.acquireSlot(ctx, taskID, st); err != nil { + return nil, err + } + } + b.mu.Lock() + st.starting = true + b.mu.Unlock() + start := b.now() + created, err := b.startTask(ctx, kt, sh, scopeDomains, scopeCIDRs) + if err != nil { + b.failStart(ctx, taskID, st, kt, known, reason, b.now().Sub(start), queued, created, err) + return nil, err + } + + b.mu.Lock() + defer b.mu.Unlock() + st.starting = false + b.tasks[taskID] = kt + b.recordEventLocked(ScaleEvent{ + Time: b.now().UTC().Format(time.RFC3339Nano), TaskID: taskID, Kind: ScaleKindUp, Reason: reason, + DurationMS: b.now().Sub(start).Milliseconds(), QueueMS: queued.Milliseconds(), + }) + return kt, nil +} + +// kubeEventErrMax bounds the error text kept in a scale_up_failed event. +const kubeEventErrMax = 300 + +// failStart undoes a scale-up that failed (image pull error, pods never ready, +// network never ready, API error): it deletes whatever pods the attempt left and +// gives the capacity slot back, then records a scale_up_failed event. The task +// keeps its Service and NetworkPolicies, so it is tracked as scaled to zero when +// the Service exists and the next exec simply tries again. If the pods cannot be +// removed the task keeps its slot and the idle reaper or Delete retries. +// +// A start that failed with ErrCapacity (a pod still unschedulable at the ready +// timeout, typically waiting for a node the cluster autoscaler is adding) keeps +// its pods and its slot: the pods will use that node, and the next exec waits on +// them (startTask reuses pending pods) instead of restarting the wait. If no exec +// comes, the idle reaper removes them like the pods of any idle task. The caller +// holds the task's lock. +func (b *KubernetesBackend) failStart(ctx context.Context, taskID string, st *kubeScaleState, kt *kubeTask, known bool, reason string, took, queued time.Duration, created bool, cause error) { + keep := errors.Is(cause, ErrCapacity) + var cleanupErr error + if !keep { + // The request may be gone (client disconnect): clean up regardless. + cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 90*time.Second) + defer cancel() + for _, pod := range []string{"artex-w-" + kt.hash, "artex-p-" + kt.hash} { + if err := b.deletePodAndWait(cctx, pod); err != nil { + cleanupErr = errors.Join(cleanupErr, err) + } + } + } + msg := cause.Error() + if len(msg) > kubeEventErrMax { + msg = msg[:kubeEventErrMax] + "…" + } + + b.mu.Lock() + defer b.mu.Unlock() + st.starting = false + switch { + case keep: + log.Printf("[runner] task %s: start failed (%v); its pending pods and slot are kept for the next exec", taskID, cause) + case cleanupErr != nil: + log.Printf("[runner] task %s: start failed (%v) and its pods could not be removed: %v", taskID, cause, cleanupErr) + default: + st.active = false + cp := *kt + cp.workerPod, cp.proxyPod = "", "" + // Keep the task when it was known or its Service exists: it is then + // scaled to zero, and Delete and Recover see the same objects. + if known || cp.proxyIP != "" { + b.tasks[taskID] = &cp + } + } + b.recordEventLocked(ScaleEvent{ + Time: b.now().UTC().Format(time.RFC3339Nano), TaskID: taskID, Kind: ScaleKindUpFailed, Reason: reason, + DurationMS: took.Milliseconds(), QueueMS: queued.Milliseconds(), Error: msg, + }) + b.wakeHeadLocked() + log.Printf("[runner] task %s: scale-up (%s) failed, created=%v: %v", taskID, reason, created, cause) +} + +// startTask applies the task's policies and Service, (re)creates the pods that +// are missing, dead or out of scope, and waits until they are ready and their +// network paths are open. created reports whether a pod was created. +func (b *KubernetesBackend) startTask(ctx context.Context, kt *kubeTask, sh string, scopeDomains, scopeCIDRs []string) (created bool, err error) { + b.prepareDirs(kt.taskID) workerPolicy := "artex-w-" + kt.hash proxyPolicy := "artex-p-" + kt.hash @@ -880,16 +1327,20 @@ func (b *KubernetesBackend) ensureTask(ctx context.Context, taskID string, scope // Policies first: a pod must never run before its isolation exists. if err := b.applyPolicy(ctx, b.workerPolicyObj(workerPolicy, kt)); err != nil { - return nil, fmt.Errorf("worker network policy: %w", err) + return false, fmt.Errorf("worker network policy: %w", err) } - if err := b.applyPolicy(ctx, b.proxyPolicyObj(proxyPolicy, kt, scopeCIDRs)); err != nil { - return nil, fmt.Errorf("proxy network policy: %w", err) + if err := b.applyPolicy(ctx, b.proxyPolicyObj(proxyPolicy, kt, scopeDomains, scopeCIDRs)); err != nil { + return false, fmt.Errorf("proxy network policy: %w", err) } + // The policy now carries this scope; status reports it while no proxy pod runs. + kt.scopeDomains = append([]string{}, scopeDomains...) + kt.scopeCIDRs = append([]string{}, scopeCIDRs...) + kt.scopeKnown = true if kt.proxyIP == "" { err := b.create(ctx, "services", b.proxyServiceObj(svcName, kt)) if err != nil && !isKubeStatus(err, http.StatusConflict) { - return nil, fmt.Errorf("proxy service: %w", err) + return false, fmt.Errorf("proxy service: %w", err) } var svc struct { Metadata kubeObjectMeta `json:"metadata"` @@ -898,51 +1349,62 @@ func (b *KubernetesBackend) ensureTask(ctx context.Context, taskID string, scope } `json:"spec"` } if err := b.do(ctx, http.MethodGet, b.nsPath("services")+"/"+url.PathEscape(svcName), nil, &svc); err != nil { - return nil, fmt.Errorf("proxy service: %w", err) + return false, fmt.Errorf("proxy service: %w", err) } if svc.Metadata.Labels[LabelManagedBy] != ManagedByRunner || svc.Metadata.Labels[LabelTaskHash] != kt.hash { - return nil, fmt.Errorf("existing service %s has untrusted labels %v (refusing to route worker through it)", svcName, svc.Metadata.Labels) + return false, fmt.Errorf("existing service %s has untrusted labels %v (refusing to route worker through it)", svcName, svc.Metadata.Labels) } if ip := net.ParseIP(svc.Spec.ClusterIP); ip == nil { - return nil, fmt.Errorf("proxy service %s has no ClusterIP (%q)", svcName, svc.Spec.ClusterIP) + return false, fmt.Errorf("proxy service %s has no ClusterIP (%q)", svcName, svc.Spec.ClusterIP) } kt.proxyIP = svc.Spec.ClusterIP } + // Pods of an earlier start that failed on the ready timeout are kept, whether + // they are still coming up (typically waiting for a node the cluster + // autoscaler is adding) or became ready since: replacing them would start that + // wait over and make the autoscaler see new pending pods. Such pods count as + // created: they hold node resources like new ones. + proxyOK := kt.scopeHash == sh && b.podAlive(ctx, kt.proxyPod) + if !proxyOK && b.reusablePod(ctx, proxyPod, kt, ComponentProxy, sh) { + kt.scopeHash, kt.proxyPod = sh, proxyPod + proxyOK, created = true, true + } + workerOK := b.podAlive(ctx, kt.workerPod) + if !workerOK && b.reusablePod(ctx, workerPod, kt, ComponentWorker, "") { + kt.workerPod = workerPod + workerOK, created = true, true + } + // (Re)create the proxy when missing, dead, or the scope changed. - if kt.scopeHash != sh || !b.podAlive(ctx, kt.proxyPod) { + if !proxyOK { if err := b.deletePodAndWait(ctx, proxyPod); err != nil { - return nil, err + return created, err } kt.scopeHash = sh if err := b.create(ctx, "pods", b.proxyPodObj(proxyPod, kt, scopeDomains, scopeCIDRs)); err != nil { - return nil, fmt.Errorf("create proxy pod: %w", err) + return created, fmt.Errorf("create proxy pod: %w", err) } + created = true kt.proxyPod = proxyPod } - if !b.podAlive(ctx, kt.workerPod) { + if !workerOK { if err := b.deletePodAndWait(ctx, workerPod); err != nil { - return nil, err + return created, err } if err := b.create(ctx, "pods", b.workerPodObj(workerPod, kt)); err != nil { - return nil, fmt.Errorf("create worker pod: %w", err) + return created, fmt.Errorf("create worker pod: %w", err) } + created = true kt.workerPod = workerPod } if err := b.waitPodReady(ctx, kt.proxyPod); err != nil { - return nil, err + return created, err } if err := b.waitPodReady(ctx, kt.workerPod); err != nil { - return nil, err + return created, err } - if err := b.waitNetworkReady(ctx, kt); err != nil { - return nil, err - } - - b.mu.Lock() - b.tasks[taskID] = kt - b.mu.Unlock() - return kt, nil + return created, b.waitNetworkReady(ctx, kt) } // waitNetworkReady blocks until the task's NetworkPolicies are in effect for its @@ -1149,7 +1611,9 @@ func kubeExecArgv(req ExecRequest, proxyIP string) []string { // Exec runs req.Argv inside the task's worker pod through artex-exec-wrap. func (b *KubernetesBackend) Exec(ctx context.Context, taskID string, req ExecRequest) (ExecResponse, error) { start := time.Now() - kt, err := b.ensureTask(ctx, taskID, req.ScopeDomains, req.ScopeCIDRs) + st := b.beginExec(taskID) + defer b.endExec(taskID, st) + kt, err := b.ensureTask(ctx, taskID, st, req.ScopeDomains, req.ScopeCIDRs) if err != nil { return ExecResponse{}, err } @@ -1177,25 +1641,31 @@ func (b *KubernetesBackend) Exec(ctx context.Context, taskID string, req ExecReq // process survives; /workspace stays on the volume for the next exec. func (b *KubernetesBackend) Kill(ctx context.Context, taskID string) error { b.mu.Lock() - kt := b.tasks[taskID] + var worker string + if kt := b.tasks[taskID]; kt != nil { + worker = kt.workerPod + } b.mu.Unlock() - if kt == nil || kt.workerPod == "" { + // No worker pod (unknown task, or scaled to zero): nothing is running. + if worker == "" { return fmt.Errorf("%w: task %s", ErrNotFound, taskID) } kctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() - _, _, _, code, err := b.podExec(kctx, kt.workerPod, []string{"/usr/local/bin/artex-exec-wrap", "--kill-uid", strconv.Itoa(WorkerUID)}, 4096) + _, _, _, code, err := b.podExec(kctx, worker, []string{"/usr/local/bin/artex-exec-wrap", "--kill-uid", strconv.Itoa(WorkerUID)}, 4096) if err == nil && code == 0 { return nil } log.Printf("[runner] kill-uid for task %s failed (code=%d err=%v); deleting worker pod", taskID, code, err) zero := 0 - if derr := b.deleteObj(context.Background(), "pods", kt.workerPod, &zero); derr != nil { + if derr := b.deleteObj(context.Background(), "pods", worker, &zero); derr != nil { return derr } b.mu.Lock() if cur := b.tasks[taskID]; cur != nil { - cur.workerPod = "" + cp := *cur + cp.workerPod = "" + b.tasks[taskID] = &cp } b.mu.Unlock() return nil @@ -1203,33 +1673,60 @@ func (b *KubernetesBackend) Kill(ctx context.Context, taskID string) error { // Delete removes the task's pods, proxy service and network policies, keeping the // workspace directory on the volume. Policies go last so no pod outlives them. +// The task's capacity slot stays taken until its pods are gone, so a queued +// scale-up never runs while the deleted pods still use the node. func (b *KubernetesBackend) Delete(ctx context.Context, taskID string) error { + // Mark the task deleted before waiting for its lock: an exec queued for a + // capacity slot holds that lock and gives up on this signal. A slot it holds + // moves to draining so it stays counted. + b.mu.Lock() + st := b.scale[taskID] + held := false + if st != nil { + st.deleted = true + close(st.cancel) + delete(b.scale, taskID) + if st.active { + st.active = false + b.draining++ + held = true + } + } + b.mu.Unlock() l := b.taskLock(taskID) l.Lock() defer l.Unlock() b.mu.Lock() kt := b.tasks[taskID] delete(b.tasks, taskID) + // No start can take a slot after the mark: acquireSlot checks deleted under + // the same lock it sets active with. b.mu.Unlock() - if kt == nil { + if held { + defer func() { + b.mu.Lock() + b.draining-- + b.recordEventLocked(ScaleEvent{Time: b.now().UTC().Format(time.RFC3339Nano), TaskID: taskID, Kind: ScaleKindDown, Reason: ScaleReasonDeleted}) + b.wakeHeadLocked() + b.mu.Unlock() + }() + } + // Untracked but holding a slot: pods of a start that could not be cleaned up. + if kt == nil && !held { return fmt.Errorf("%w: task %s", ErrNotFound, taskID) } - zero := 0 + hash := kubeTaskHash(taskID) var errs []error - for _, obj := range [][2]string{ - {"pods", "artex-w-" + kt.hash}, - {"pods", "artex-p-" + kt.hash}, - {"services", "artex-p-" + kt.hash}, - } { - g := &zero - if obj[0] != "pods" { - g = nil - } - if err := b.deleteObj(ctx, obj[0], obj[1], g); err != nil { + // Wait for the pods to be gone before the slot is released (deferred above). + for _, pod := range []string{"artex-w-" + hash, "artex-p-" + hash} { + if err := b.deletePodAndWait(ctx, pod); err != nil { errs = append(errs, err) } } - for _, name := range []string{"artex-w-" + kt.hash, "artex-p-" + kt.hash} { + if err := b.deleteObj(ctx, "services", "artex-p-"+hash, nil); err != nil { + errs = append(errs, err) + } + for _, name := range []string{"artex-w-" + hash, "artex-p-" + hash} { if err := b.deleteObj(ctx, "networkpolicies", name, nil); err != nil { errs = append(errs, err) } diff --git a/sandbox/kube_e2e_test.go b/sandbox/kube_e2e_test.go index 2121d5aad..a46a6aadd 100644 --- a/sandbox/kube_e2e_test.go +++ b/sandbox/kube_e2e_test.go @@ -1,9 +1,9 @@ package sandbox import ( + "bufio" "context" "fmt" - "net" "os" "os/exec" "regexp" @@ -22,6 +22,11 @@ import ( // ARTEX_E2E_NAMESPACE=artex // ARTEX_E2E_KUBECONTEXT=k3d-artex (optional) // ARTEX_E2E_INTERNET=1 (optional: test allowed egress to example.com) +// +// The scaling subtests read the idle timeout and the capacity cap from the +// runner's own status. Scale-to-zero needs an idle timeout of at most two +// minutes and the capacity tests a cap of at most three, as k3d-e2e.sh installs +// (sandbox.scaling.idleTimeout=30s, maxActive=2); otherwise they skip. func TestKubeSandboxE2E(t *testing.T) { if os.Getenv("ARTEX_SANDBOX_KUBE_E2E") != "1" { t.Skip("set ARTEX_SANDBOX_KUBE_E2E=1 (see scripts/k3d-e2e.sh)") @@ -38,25 +43,42 @@ func TestKubeSandboxE2E(t *testing.T) { } // The test owns its port-forward: a forward to a Service is pinned to one pod // and dies when that pod does, which the runner-restart case causes. - const pfPort = "18799" + // kubectl picks a free local port and prints it: a fixed port could already + // be a forward to another cluster's runner, which the test would then drive. var pf *exec.Cmd + var c *Client startPF := func() { - args := []string{"-n", ns, "port-forward", "svc/" + envDefault("ARTEX_E2E_RUNNER_SVC", "artex-runner"), pfPort + ":8789"} + args := []string{"-n", ns, "port-forward", "--address", "127.0.0.1", "svc/" + envDefault("ARTEX_E2E_RUNNER_SVC", "artex-runner"), ":8789"} if kctx != "" { args = append([]string{"--context", kctx}, args...) } pf = exec.Command("kubectl", args...) + out, err := pf.StdoutPipe() + if err != nil { + t.Fatalf("port-forward: %v", err) + } if err := pf.Start(); err != nil { t.Fatalf("port-forward: %v", err) } - for i := 0; i < 50; i++ { - if conn, err := net.DialTimeout("tcp", "127.0.0.1:"+pfPort, 200*time.Millisecond); err == nil { - conn.Close() - return + port := make(chan string, 1) + go func() { + sc := bufio.NewScanner(out) + re := regexp.MustCompile(`^Forwarding from 127\.0\.0\.1:(\d+) -> `) + for sc.Scan() { + if m := re.FindStringSubmatch(sc.Text()); m != nil { + select { + case port <- m[1]: + default: + } + } } - time.Sleep(200 * time.Millisecond) + }() + select { + case p := <-port: + c = NewClient("http://127.0.0.1:"+p, os.Getenv(EnvRunnerToken)) + case <-time.After(15 * time.Second): + t.Fatal("port-forward did not come up") } - t.Fatal("port-forward did not come up") } stopPF := func() { if pf != nil && pf.Process != nil { @@ -67,7 +89,6 @@ func TestKubeSandboxE2E(t *testing.T) { startPF() t.Cleanup(stopPF) - c := NewClient("http://127.0.0.1:"+pfPort, os.Getenv(EnvRunnerToken)) ctx := context.Background() health, err := c.Health(ctx) @@ -164,6 +185,36 @@ func TestKubeSandboxE2E(t *testing.T) { } }) + t.Run("scaling status", func(t *testing.T) { + res, err := c.Tasks(ctx) + if err != nil { + t.Fatal(err) + } + sc := res.Scaling + if sc == nil || !sc.Supported { + t.Fatalf("runner reports no scaling support: %+v", sc) + } + t.Logf("runner scaling: idle timeout %ds, max active %d, queue timeout %ds", sc.IdleTimeoutSeconds, sc.MaxActive, sc.QueueTimeoutSeconds) + ts := findTask(t, res, taskID) + if ts.ScalingState != ScaleStateActive || ts.InFlight != 0 || ts.LastActivity == "" { + t.Fatalf("task scaling fields = %+v", ts) + } + if (sc.IdleTimeoutSeconds > 0) != (ts.IdleExpiresAt != "") { + t.Errorf("idle expiry %q with idle timeout %ds", ts.IdleExpiresAt, sc.IdleTimeoutSeconds) + } + ev := lastScaleEvent(sc, taskID, ScaleKindUp) + if ev == nil || ev.Reason != ScaleReasonFirstExec || ev.DurationMS <= 0 { + t.Fatalf("first scale-up event = %+v", ev) + } + if sc.ColdStart.Count < 1 || sc.ColdStart.P50MS <= 0 || sc.ColdStart.P95MS < sc.ColdStart.P50MS { + t.Fatalf("cold start stats = %+v", sc.ColdStart) + } + if sc.MaxActive > 0 && sc.Active > sc.MaxActive { + t.Errorf("%d active tasks with max active %d", sc.Active, sc.MaxActive) + } + t.Logf("first cold start: %d ms (create to open network paths)", ev.DurationMS) + }) + t.Run("network isolation", func(t *testing.T) { lookup := func(args ...string) string { out, err := kubectl(args...) @@ -293,6 +344,215 @@ func TestKubeSandboxE2E(t *testing.T) { } }) + scaling := func(t *testing.T) *ScalingStatus { + t.Helper() + res, err := c.Tasks(ctx) + if err != nil || res.Scaling == nil { + t.Fatalf("runner status: %+v %v", res.Scaling, err) + } + return res.Scaling + } + taskState := func(t *testing.T, id string) string { + t.Helper() + res, err := c.Tasks(ctx) + if err != nil { + t.Fatal(err) + } + for _, ts := range res.Tasks { + if ts.TaskID == id { + return ts.ScalingState + } + } + return "" + } + podsOf := func(id string) string { + out, _ := kubectl("get", "pods", "-l", LabelTaskHash+"="+kubeTaskHash(id), "-o", "name") + return out + } + waitState := func(t *testing.T, id, want string, within time.Duration) { + t.Helper() + deadline := time.Now().Add(within) + for taskState(t, id) != want { + if time.Now().After(deadline) { + t.Fatalf("task %s is %q, not %q after %s", id, taskState(t, id), want, within) + } + time.Sleep(time.Second) + } + } + // The isolation a resumed task must have again before its first command. + assertIsolated := func(t *testing.T) { + t.Helper() + if r := sh(t, `timeout 6 bash -c 'exec 3<>/dev/tcp/1.1.1.1/443' 2>/dev/null && echo OPEN || echo BLOCKED`); !strings.Contains(r.Stdout, "BLOCKED") { + t.Errorf("resumed worker reaches the internet directly: %q", r.Stdout) + } + if r := sh(t, `curl -s -o /dev/null -w '%{http_connect}' --max-time 15 https://example.org`); r.Stdout != "403" { + t.Errorf("resumed worker does not reach its proxy (want the proxy's 403): %q", r.Stdout) + } + } + + t.Run("scale to zero on idle and resume", func(t *testing.T) { + sc := scaling(t) + if sc.IdleTimeoutSeconds == 0 || sc.IdleTimeoutSeconds > 120 { + t.Skipf("runner idle timeout is %ds: install with sandbox.scaling.idleTimeout <= 2m to test scale-to-zero", sc.IdleTimeoutSeconds) + } + idle := time.Duration(sc.IdleTimeoutSeconds) * time.Second + if r := sh(t, `echo survives > sub/scale.txt; echo gone > /tmp/scale.txt`); r.ExitCode != 0 { + t.Fatalf("%+v", r) + } + uid, _ := kubectl("get", "pod", "artex-w-"+h, "-o", "jsonpath={.metadata.uid}") + svcIP, _ := kubectl("get", "svc", "artex-p-"+h, "-o", "jsonpath={.spec.clusterIP}") + idleFrom := time.Now() + + // A running command holds the task up past the idle timeout. + hold := idle + 10*time.Second + if r := run(t, ExecRequest{Argv: []string{"sleep", fmt.Sprint(int(hold.Seconds()))}, TimeoutMS: int((hold + 30*time.Second).Milliseconds())}); r.ExitCode != 0 { + t.Fatalf("long command: %+v", r) + } + if now, _ := kubectl("get", "pod", "artex-w-"+h, "-o", "jsonpath={.metadata.uid}"); now != uid { + t.Fatalf("worker replaced while a command ran for %s (idle timeout %s, idle since %s)", hold, idle, time.Since(idleFrom)) + } + + start := time.Now() + waitState(t, taskID, ScaleStateZero, idle+90*time.Second) + t.Logf("scaled to zero %s after the last command (idle timeout %s)", time.Since(start).Round(time.Second), idle) + if time.Since(start) < idle-2*time.Second { + t.Errorf("scaled down after %s, before the idle timeout %s", time.Since(start), idle) + } + if out := podsOf(taskID); out != "" && !strings.Contains(out, "No resources") { + t.Fatalf("pods left after scale-to-zero:\n%s", out) + } + out, _ := kubectl("get", "svc,networkpolicy", "-l", LabelTaskHash+"="+h, "-o", "name") + for _, want := range []string{"service/artex-p-" + h, "networkpolicy.networking.k8s.io/artex-w-" + h, "networkpolicy.networking.k8s.io/artex-p-" + h} { + if !strings.Contains(out, want) { + t.Errorf("scale-to-zero removed %s:\n%s", want, out) + } + } + if ev := lastScaleEvent(scaling(t), taskID, ScaleKindDown); ev == nil || ev.Reason != ScaleReasonIdle { + t.Fatalf("scale-down event = %+v", ev) + } + if _, err := c.Kill(ctx, taskID); err != nil && !strings.Contains(err.Error(), "not found") { + t.Errorf("kill on a scaled-to-zero task: %v", err) + } + + // Resume: the workspace is back, in-memory files are not, isolation holds. + start = time.Now() + r := sh(t, `cat sub/scale.txt; cat /tmp/scale.txt 2>/dev/null || echo tmp-reset`) + took := time.Since(start) + if r.Stdout != "survives\ntmp-reset\n" { + t.Fatalf("after resume: %+v", r) + } + if now, _ := kubectl("get", "pod", "artex-w-"+h, "-o", "jsonpath={.metadata.uid}"); now == "" || now == uid { + t.Errorf("worker pod uid %q -> %q: not a new pod", uid, now) + } + if ip, _ := kubectl("get", "svc", "artex-p-"+h, "-o", "jsonpath={.spec.clusterIP}"); ip != svcIP { + t.Errorf("proxy ClusterIP changed across scale-to-zero: %s -> %s", svcIP, ip) + } + ev := lastScaleEvent(scaling(t), taskID, ScaleKindUp) + if ev == nil || ev.Reason != ScaleReasonResume || ev.DurationMS <= 0 { + t.Fatalf("resume event = %+v", ev) + } + t.Logf("resume: exec returned in %s, cold start %d ms", took.Round(time.Millisecond), ev.DurationMS) + assertIsolated(t) + }) + + t.Run("capacity cap evicts and queues", func(t *testing.T) { + sc := scaling(t) + if sc.MaxActive == 0 || sc.MaxActive > 3 { + t.Skipf("runner max active is %d: install with sandbox.scaling.maxActive between 1 and 3 to test the cap", sc.MaxActive) + } + n := sc.MaxActive + extra := make([]string, n+1) + for i := range extra { + extra[i] = fmt.Sprintf("E2E_cap%d.%d", i, time.Now().UnixNano()) + id := extra[i] + t.Cleanup(func() { _, _ = c.Delete(context.Background(), id) }) + } + workers := func() int { + out, _ := kubectl("get", "pods", "-l", LabelManagedBy+"="+ManagedByRunner+","+LabelComponent+"="+ComponentWorker, + "--field-selector=status.phase=Running", "-o", "name") + return len(strings.Fields(out)) + } + sh(t, `echo before-eviction > sub/cap.txt`) + + // n new tasks used after ours: ours is the least recently used and goes. + for _, id := range extra[:n] { + if r, err := c.Exec(ctx, id, ExecRequest{Argv: []string{"true"}, TimeoutMS: 60000}); err != nil || r.ExitCode != 0 { + t.Fatalf("exec on %s: %+v %v", id, r, err) + } + if w := workers(); w > n { + t.Errorf("%d running worker pods with max active %d", w, n) + } + } + if st := taskState(t, taskID); st != ScaleStateZero { + t.Fatalf("our task is %q after %d newer tasks took the %d slot(s)", st, n, n) + } + if ev := lastScaleEvent(scaling(t), taskID, ScaleKindDown); ev == nil || ev.Reason != ScaleReasonEvicted { + t.Fatalf("eviction event = %+v", ev) + } + if out := podsOf(taskID); out != "" && !strings.Contains(out, "No resources") { + t.Fatalf("evicted task still has pods:\n%s", out) + } + if got := scaling(t); got.Active != n { + t.Errorf("active = %d, want %d", got.Active, n) + } + + // Every slot busy: one more task has to wait until a command ends. + const busyFor = 15 + var wg sync.WaitGroup + for _, id := range extra[:n] { + wg.Add(1) + go func() { + defer wg.Done() + if _, err := c.Exec(ctx, id, ExecRequest{Argv: []string{"sleep", fmt.Sprint(busyFor)}, TimeoutMS: 60000}); err != nil { + t.Errorf("busy exec on %s: %v", id, err) + } + }() + } + time.Sleep(3 * time.Second) + waiter := extra[n] + start := time.Now() + done := make(chan error, 1) + go func() { + _, err := c.Exec(ctx, waiter, ExecRequest{Argv: []string{"true"}, TimeoutMS: 60000}) + done <- err + }() + waitState(t, waiter, ScaleStateQueued, 10*time.Second) + if q := scaling(t).Queued; q != 1 { + t.Errorf("queued = %d while one task waits", q) + } + if out := podsOf(waiter); out != "" && !strings.Contains(out, "No resources") { + t.Errorf("a queued task has pods:\n%s", out) + } + err := <-done + waited := time.Since(start) + wg.Wait() + if err != nil { + t.Fatalf("queued exec: %v", err) + } + ev := lastScaleEvent(scaling(t), waiter, ScaleKindUp) + if ev == nil || ev.QueueMS < 1000 { + t.Fatalf("queued scale-up event = %+v", ev) + } + if waited < (busyFor-5)*time.Second { + t.Errorf("queued exec returned after %s although every slot was busy for %ds", waited, busyFor) + } + t.Logf("queued exec: waited %d ms for a slot, cold start %d ms, returned after %s", ev.QueueMS, ev.DurationMS, waited.Round(time.Millisecond)) + if w := workers(); w > n { + t.Errorf("%d running worker pods with max active %d", w, n) + } + + // Our task comes back with its workspace by evicting someone else. + if r := sh(t, `cat sub/cap.txt`); r.Stdout != "before-eviction\n" { + t.Fatalf("workspace after eviction and resume: %+v", r) + } + assertIsolated(t) + for _, id := range extra { + if _, err := c.Delete(ctx, id); err != nil { + t.Errorf("delete %s: %v", id, err) + } + } + }) + t.Run("delete removes task objects", func(t *testing.T) { if _, err := c.Delete(ctx, taskID); err != nil { t.Fatal(err) @@ -311,6 +571,16 @@ func TestKubeSandboxE2E(t *testing.T) { }) } +// lastScaleEvent returns the newest event of the given kind for a task. +func lastScaleEvent(sc *ScalingStatus, taskID, kind string) *ScaleEvent { + for i := len(sc.Events) - 1; i >= 0; i-- { + if e := sc.Events[i]; e.TaskID == taskID && e.Kind == kind { + return &e + } + } + return nil +} + func envDefault(k, def string) string { if v := strings.TrimSpace(os.Getenv(k)); v != "" { return v diff --git a/sandbox/kube_placement_test.go b/sandbox/kube_placement_test.go new file mode 100644 index 000000000..fa727d79e --- /dev/null +++ b/sandbox/kube_placement_test.go @@ -0,0 +1,80 @@ +package sandbox + +import ( + "context" + "reflect" + "strings" + "testing" +) + +// Task pods carry the configured node selector, tolerations and priority +// class (both the worker and the proxy), and none of them by default. +func TestKubeTaskPodPlacement(t *testing.T) { + t.Setenv("ARTEX_KUBE_NODE_SELECTOR", "pool=sandbox, topology.kubernetes.io/zone=a") + t.Setenv("ARTEX_KUBE_TOLERATIONS", `[{"key":"artex.io/sandbox","operator":"Exists","effect":"NoSchedule"},{"key":"x","operator":"Equal","value":"y","effect":"NoExecute","tolerationSeconds":30}]`) + t.Setenv("ARTEX_KUBE_PRIORITY_CLASS", "artex-sandbox") + cfg, err := KubeConfigFromEnv() + if err != nil { + t.Fatal(err) + } + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + b.cfg.NodeSelector, b.cfg.Tolerations, b.cfg.PriorityClassName = cfg.NodeSelector, cfg.Tolerations, cfg.PriorityClassName + if _, err := b.Exec(context.Background(), "t1", execReq("true")); err != nil { + t.Fatal(err) + } + h := kubeTaskHash("t1") + for _, name := range []string{"artex-w-" + h, "artex-p-" + h} { + spec := f.obj("pods", name)["spec"].(map[string]any) + if !reflect.DeepEqual(spec["nodeSelector"], map[string]any{"pool": "sandbox", "topology.kubernetes.io/zone": "a"}) { + t.Errorf("%s nodeSelector = %v", name, spec["nodeSelector"]) + } + tol, _ := spec["tolerations"].([]any) + if len(tol) != 2 || dig(tol, 0, "key") != "artex.io/sandbox" || dig(tol, 1, "tolerationSeconds") != float64(30) { + t.Errorf("%s tolerations = %v", name, spec["tolerations"]) + } + if spec["priorityClassName"] != "artex-sandbox" { + t.Errorf("%s priorityClassName = %v", name, spec["priorityClassName"]) + } + } + + f2, srv2 := newFakeKubeAPI(t) + b2 := newTestKubeBackend(t, f2, srv2) + if _, err := b2.Exec(context.Background(), "t1", execReq("true")); err != nil { + t.Fatal(err) + } + spec := f2.obj("pods", "artex-w-"+h)["spec"].(map[string]any) + for _, k := range []string{"nodeSelector", "tolerations", "priorityClassName"} { + if _, ok := spec[k]; ok { + t.Errorf("default worker has %s = %v", k, spec[k]) + } + } +} + +func TestKubePlacementEnvRejectsMalformedValues(t *testing.T) { + for env, val := range map[string]string{ + "ARTEX_KUBE_NODE_SELECTOR": "pool", + "ARTEX_KUBE_TOLERATIONS": `{"key":"a"}`, + } { + t.Run(env, func(t *testing.T) { + t.Setenv(env, val) + if _, err := KubeConfigFromEnv(); err == nil || !strings.Contains(err.Error(), env) { + t.Fatalf("%s=%s: err = %v", env, val, err) + } + }) + } + for _, bad := range []string{ + `[{"key":"a","operator":"In"}]`, + `[{"key":"a","effect":"Never"}]`, + `[{"key":1}]`, + `[{"key":"a","tolerationSeconds":1.5}]`, + `[{"key":"a","nodeName":"x"}]`, + } { + if _, err := parseKubeTolerations(bad); err == nil { + t.Errorf("accepted %s", bad) + } + } + if got, err := parseKubeTolerations(`[]`); err != nil || len(got) != 0 { + t.Errorf("empty list = %v, %v", got, err) + } +} diff --git a/sandbox/kube_scale.go b/sandbox/kube_scale.go new file mode 100644 index 000000000..cf5cc968c --- /dev/null +++ b/sandbox/kube_scale.go @@ -0,0 +1,497 @@ +package sandbox + +import ( + "context" + "fmt" + "log" + "regexp" + "sort" + "strconv" + "time" +) + +// Scaling states, event kinds and reasons reported by GET /v1/tasks. +const ( + ScaleStateActive = "active" + ScaleStateStarting = "starting" + ScaleStateQueued = "queued" + ScaleStateZero = "scaled_to_zero" + + ScaleKindUp = "scale_up" + ScaleKindDown = "scale_down" + ScaleKindUpFailed = "scale_up_failed" + + ScaleReasonFirstExec = "first_exec" + ScaleReasonResume = "resume" + ScaleReasonRecreate = "recreate" + ScaleReasonIdle = "idle" + ScaleReasonEvicted = "evicted" + ScaleReasonDeleted = "deleted" + + // kubeScaleEventCap and kubeColdStartCap bound the history (in memory and + // in the state file). + kubeScaleEventCap = 100 + kubeColdStartCap = 100 + // kubeQueueRetry re-checks a queued scale-up when no wake-up arrived (a + // failed eviction leaves no signal). KubernetesBackend.queueRetry; tests + // raise it so that wake-ups are the only way forward. + kubeQueueRetry = time.Second +) + +// kubeScaleState is the scaling bookkeeping of one task, guarded by +// KubernetesBackend.mu. An Exec holds a pointer to it from start to end, so a +// Delete in between marks the state instead of losing the in-flight count. +type kubeScaleState struct { + inflight int + lastActive time.Time + // active is true while the task holds a capacity slot: it has pods or is + // about to get them. + active bool + starting bool + queued bool + // deleted is set by Delete; cancel is closed with it to abort a queued wait. + deleted bool + cancel chan struct{} +} + +// kubeSlotWaiter is one scale-up waiting for capacity. The queue is FIFO: only +// its head may take a slot or evict another task. +type kubeSlotWaiter struct { + wake chan struct{} +} + +func (b *KubernetesBackend) stateLocked(taskID string) *kubeScaleState { + st := b.scale[taskID] + if st == nil { + st = &kubeScaleState{cancel: make(chan struct{}), lastActive: b.now()} + b.scale[taskID] = st + } + return st +} + +// beginExec counts an exec as in flight before it waits for the task lock, so a +// scale-down that is checking the task either sees it or has already taken the +// lock (the exec then scales the task back up). +func (b *KubernetesBackend) beginExec(taskID string) *kubeScaleState { + b.mu.Lock() + defer b.mu.Unlock() + st := b.stateLocked(taskID) + st.inflight++ + st.lastActive = b.now() + return st +} + +func (b *KubernetesBackend) endExec(taskID string, st *kubeScaleState) { + b.mu.Lock() + defer b.mu.Unlock() + st.inflight-- + st.lastActive = b.now() + if st.inflight > 0 { + return + } + // Nothing was created for it (bad request, capacity timeout): forget it. + if !st.active && b.tasks[taskID] == nil && b.scale[taskID] == st { + delete(b.scale, taskID) + } + // The task became evictable. + b.wakeHeadLocked() +} + +// hook runs the test hook, if any, at a named point. The caller holds no lock. +func (b *KubernetesBackend) hook(point, taskID string) { + if b.testHook != nil { + b.testHook(point, taskID) + } +} + +func (b *KubernetesBackend) wakeHeadLocked() { + if len(b.waiters) == 0 { + return + } + select { + case b.waiters[0].wake <- struct{}{}: + default: + } +} + +// activeLocked counts the capacity slots in use: tasks with pods or about to +// get them, plus deleted tasks whose pods are still going away. +func (b *KubernetesBackend) activeLocked() int { + n := b.draining + for _, st := range b.scale { + if st.active { + n++ + } + } + return n +} + +func (b *KubernetesBackend) recordEventLocked(ev ScaleEvent) { + switch ev.Kind { + case ScaleKindUp: + b.totals.ScaleUps++ + case ScaleKindDown: + b.totals.ScaleDowns++ + case ScaleKindUpFailed: + b.totals.ScaleUpFailures++ + } + b.events = append(b.events, ev) + if len(b.events) > kubeScaleEventCap { + b.events = append(b.events[:0], b.events[len(b.events)-kubeScaleEventCap:]...) + } + if ev.Kind == ScaleKindUp && (ev.Reason == ScaleReasonFirstExec || ev.Reason == ScaleReasonResume) { + b.coldStarts = append(b.coldStarts, ev.DurationMS) + if len(b.coldStarts) > kubeColdStartCap { + b.coldStarts = append(b.coldStarts[:0], b.coldStarts[len(b.coldStarts)-kubeColdStartCap:]...) + } + } + b.markStateDirtyLocked() +} + +// evictableLocked lists active tasks with no exec in flight, least recently +// used first. +func (b *KubernetesBackend) evictableLocked(except string) []string { + var ids []string + for id, st := range b.scale { + if id != except && st.active && st.inflight == 0 && !st.starting { + ids = append(ids, id) + } + } + sort.Slice(ids, func(i, j int) bool { + a, c := b.scale[ids[i]], b.scale[ids[j]] + if !a.lastActive.Equal(c.lastActive) { + return a.lastActive.Before(c.lastActive) + } + return ids[i] < ids[j] + }) + return ids +} + +// acquireSlot reserves a capacity slot for a task that is about to get pods. The +// caller holds the task's lock. At the cap it scales the least recently used +// idle task to zero; when every active task is busy it waits in FIFO order for +// up to QueueTimeout. +func (b *KubernetesBackend) acquireSlot(ctx context.Context, taskID string, st *kubeScaleState) (time.Duration, error) { + if b.cfg.MaxActive <= 0 { + b.mu.Lock() + defer b.mu.Unlock() + if st.deleted { + return 0, fmt.Errorf("%w: task %s was deleted", ErrNotFound, taskID) + } + st.active = true + return 0, nil + } + begin := b.now() + var w *kubeSlotWaiter + var timeout <-chan time.Time + // leave runs with b.mu held on every way out of the queue. + leave := func() { + st.queued = false + if w == nil { + return + } + for i, q := range b.waiters { + if q == w { + b.waiters = append(b.waiters[:i], b.waiters[i+1:]...) + break + } + } + b.wakeHeadLocked() + } + for { + b.mu.Lock() + if st.deleted { + leave() + b.mu.Unlock() + return 0, fmt.Errorf("%w: task %s was deleted while waiting for a sandbox slot", ErrNotFound, taskID) + } + if w == nil { + if len(b.waiters) == 0 && b.activeLocked() < b.cfg.MaxActive { + st.active = true + b.mu.Unlock() + return 0, nil + } + w = &kubeSlotWaiter{wake: make(chan struct{}, 1)} + b.waiters = append(b.waiters, w) + st.queued = true + timer := time.NewTimer(b.cfg.QueueTimeout) + defer timer.Stop() + timeout = timer.C + } + var victims []string + if b.waiters[0] == w { + if b.activeLocked() < b.cfg.MaxActive { + st.active = true + leave() + b.mu.Unlock() + return b.now().Sub(begin), nil + } + victims = b.evictableLocked(taskID) + } + b.mu.Unlock() + evicted := false + for _, v := range victims { + if evicted = b.evict(ctx, v); evicted { + break + } + } + if evicted { + continue + } + select { + case <-w.wake: + b.hook("slot-woken", taskID) + case <-st.cancel: + case <-time.After(b.queueRetry): + case <-ctx.Done(): + b.mu.Lock() + leave() + b.mu.Unlock() + return 0, fmt.Errorf("waiting for a sandbox slot: %w", ctx.Err()) + case <-timeout: + b.mu.Lock() + leave() + n := b.activeLocked() + b.mu.Unlock() + return 0, fmt.Errorf("%w: %d of %d sandbox slots are in use and none became free within %s (raise ARTEX_KUBE_MAX_ACTIVE or retry later)", + ErrCapacity, n, b.cfg.MaxActive, b.cfg.QueueTimeout) + } + } +} + +// evict scales an idle task to zero to make room. It never blocks on the +// victim's lock: a task that is being started or deleted is not a candidate. +func (b *KubernetesBackend) evict(ctx context.Context, victim string) bool { + b.hook("evict", victim) + l := b.taskLock(victim) + if !l.TryLock() { + return false + } + defer l.Unlock() + b.mu.Lock() + st := b.scale[victim] + ok := st != nil && st.active && st.inflight == 0 && !st.starting + b.mu.Unlock() + if !ok { + return false + } + if err := b.scaleDown(ctx, victim, st, ScaleReasonEvicted); err != nil { + log.Printf("[runner] evict task %s: %v", victim, err) + return false + } + return true +} + +// scaleDown deletes the task's worker and proxy pods and waits until they are +// gone. The proxy Service (its ClusterIP is in the worker's environment), the +// NetworkPolicies and the workspace stay, so the next exec only recreates the +// pods. The caller holds the task's lock. +func (b *KubernetesBackend) scaleDown(ctx context.Context, taskID string, st *kubeScaleState, reason string) error { + h := kubeTaskHash(taskID) + for _, pod := range []string{"artex-w-" + h, "artex-p-" + h} { + if err := b.deletePodAndWait(ctx, pod); err != nil { + return err + } + } + b.mu.Lock() + untracked := b.tasks[taskID] == nil + b.mu.Unlock() + if untracked { + // Pods of a start that never succeeded: the task is forgotten below, so + // its Service and policies (created before the pods) go too, or nothing + // could delete them until a runner restart re-adopted the Service. + for _, obj := range [][2]string{{"services", "artex-p-" + h}, {"networkpolicies", "artex-w-" + h}, {"networkpolicies", "artex-p-" + h}} { + if err := b.deleteObj(ctx, obj[0], obj[1], nil); err != nil { + return err + } + } + } + b.mu.Lock() + defer b.mu.Unlock() + if kt := b.tasks[taskID]; kt != nil { + cp := *kt + cp.workerPod, cp.proxyPod = "", "" + b.tasks[taskID] = &cp + } else if st.inflight == 0 && b.scale[taskID] == st { + // Pods of a start that failed: nothing else is kept for the task. + delete(b.scale, taskID) + } + st.active = false + b.recordEventLocked(ScaleEvent{Time: b.now().UTC().Format(time.RFC3339Nano), TaskID: taskID, Kind: ScaleKindDown, Reason: reason}) + b.wakeHeadLocked() + log.Printf("[runner] task %s scaled to zero (%s)", taskID, reason) + return nil +} + +// reapIdle scales to zero every task with no exec in flight whose last activity +// is older than IdleTimeout, and returns how many it scaled down. +func (b *KubernetesBackend) reapIdle(ctx context.Context) int { + if b.cfg.IdleTimeout <= 0 { + return 0 + } + idle := func(st *kubeScaleState) bool { + return st != nil && st.active && st.inflight == 0 && !st.starting && b.now().Sub(st.lastActive) >= b.cfg.IdleTimeout + } + b.mu.Lock() + var ids []string + for id, st := range b.scale { + if idle(st) { + ids = append(ids, id) + } + } + b.mu.Unlock() + sort.Strings(ids) + n := 0 + for _, id := range ids { + b.hook("reap", id) + l := b.taskLock(id) + // Busy lock: the task is being started, evicted or deleted right now. + if !l.TryLock() { + continue + } + b.mu.Lock() + st := b.scale[id] + ok := idle(st) + b.mu.Unlock() + if ok { + if err := b.scaleDown(ctx, id, st, ScaleReasonIdle); err != nil { + log.Printf("[runner] idle scale-down of task %s: %v", id, err) + } else { + n++ + } + } + l.Unlock() + } + return n +} + +// RunScaler runs the idle reaper until ctx is done. It returns at once when +// idle scale-down is disabled. +func (b *KubernetesBackend) RunScaler(ctx context.Context) { + if b.cfg.IdleTimeout <= 0 { + return + } + every := min(max(b.cfg.IdleTimeout/10, time.Second), 15*time.Second) + t := time.NewTicker(every) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + rctx, cancel := context.WithTimeout(ctx, 2*time.Minute) + b.reapIdle(rctx) + cancel() + } + } +} + +// kubePercentile is the nearest-rank percentile (p in 1..100) of samples. +func kubePercentile(samples []int64, p int) int64 { + if len(samples) == 0 { + return 0 + } + s := append([]int64(nil), samples...) + sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) + rank := (len(s)*p + 99) / 100 + return s[min(max(rank, 1), len(s))-1] +} + +// scalingStatusLocked snapshots the scaling configuration, counters and history. +func (b *KubernetesBackend) scalingStatusLocked() *ScalingStatus { + out := &ScalingStatus{ + Supported: true, + IdleTimeoutSeconds: int64(b.cfg.IdleTimeout / time.Second), + MaxActive: b.cfg.MaxActive, + QueueTimeoutSeconds: int64(b.cfg.QueueTimeout / time.Second), + Events: append([]ScaleEvent{}, b.events...), + Totals: b.totals, + Persisted: b.cfg.StateDir != "", + // Slots still held by deleted tasks whose pods are going away. + Active: b.draining, + } + for id, st := range b.scale { + switch b.scaleStateLocked(id, st) { + case ScaleStateQueued: + out.Queued++ + case ScaleStateStarting: + out.Active++ + out.Starting++ + case ScaleStateActive: + out.Active++ + case ScaleStateZero: + out.ScaledToZero++ + } + } + cs := ColdStartStats{Count: len(b.coldStarts), SamplesMS: append([]int64{}, b.coldStarts...)} + if cs.Count > 0 { + cs.LastMS = b.coldStarts[cs.Count-1] + cs.P50MS = kubePercentile(b.coldStarts, 50) + cs.P95MS = kubePercentile(b.coldStarts, 95) + } + out.ColdStart = cs + return out +} + +func (b *KubernetesBackend) scaleStateLocked(taskID string, st *kubeScaleState) string { + switch { + case st == nil: + return "" + case st.queued: + return ScaleStateQueued + case st.starting: + return ScaleStateStarting + case st.active: + return ScaleStateActive + case b.tasks[taskID] != nil: + return ScaleStateZero + } + return "" +} + +// applyScaleLocked fills the per-task scaling fields of ts. +func (b *KubernetesBackend) applyScaleLocked(ts *TaskStatus, st *kubeScaleState) { + ts.ScalingState = b.scaleStateLocked(ts.TaskID, st) + if st == nil { + return + } + ts.InFlight = st.inflight + ts.LastActivity = st.lastActive.UTC().Format(time.RFC3339) + if b.cfg.IdleTimeout > 0 && st.active && !st.starting && st.inflight == 0 { + ts.IdleExpiresAt = st.lastActive.Add(b.cfg.IdleTimeout).UTC().Format(time.RFC3339) + } +} + +var kubeQuantityRE = regexp.MustCompile(`^([0-9]+(?:\.[0-9]+)?)(m|k|M|G|T|Ki|Mi|Gi|Ti)?$`) + +// parseKubeQuantity converts the common Kubernetes quantity forms ("250m", "2", +// "512Mi", "1.5Gi") to thousandths of the base unit. +func parseKubeQuantity(s string) (int64, error) { + m := kubeQuantityRE.FindStringSubmatch(s) + if m == nil { + return 0, fmt.Errorf("%q is not a resource quantity (examples: 250m, 2, 512Mi, 2Gi)", s) + } + v, err := strconv.ParseFloat(m[1], 64) + if err != nil { + return 0, err + } + mult := map[string]float64{"": 1, "m": 1e-3, "k": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, + "Ki": 1 << 10, "Mi": 1 << 20, "Gi": 1 << 30, "Ti": 1 << 40}[m[2]] + return int64(v*mult*1000 + 0.5), nil +} + +// checkKubeRequest validates a resource request and that it does not exceed its +// limit: the API server would otherwise reject every worker pod. +func checkKubeRequest(what, request, limit string) error { + r, err := parseKubeQuantity(request) + if err != nil { + return fmt.Errorf("kubernetes backend: worker %s request: %w", what, err) + } + if r <= 0 { + return fmt.Errorf("kubernetes backend: worker %s request %q must be positive", what, request) + } + if l, lerr := parseKubeQuantity(limit); lerr == nil && r > l { + return fmt.Errorf("kubernetes backend: worker %s request %s exceeds the limit %s", what, request, limit) + } + return nil +} diff --git a/sandbox/kube_scale_order_test.go b/sandbox/kube_scale_order_test.go new file mode 100644 index 000000000..1bdf650d6 --- /dev/null +++ b/sandbox/kube_scale_order_test.go @@ -0,0 +1,292 @@ +package sandbox + +import ( + "context" + "net/http" + "reflect" + "strings" + "sync" + "testing" + "time" +) + +// These tests pin the interleavings the scaling code must get right. Each one +// was written against a deliberate mutation of kube_scale.go that the other +// tests let through (see the mutation check in the branch history): a missing +// re-check under the task lock, a blocking lock where TryLock is needed, a +// queue that is not FIFO, and wake-ups that are not sent. testHook places the +// competing work exactly in the window that matters, and queueRetry is raised +// so the 1s fallback poll cannot hide a missing wake-up. + +func waitUntil(what string, cond func() bool) error { + deadline := time.Now().Add(10 * time.Second) + for !cond() { + if time.Now().After(deadline) { + return &timeoutErr{what} + } + time.Sleep(2 * time.Millisecond) + } + return nil +} + +type timeoutErr struct{ what string } + +func (e *timeoutErr) Error() string { return "timed out waiting for " + e.what } + +// The reaper lists idle tasks, then takes each task's lock. A command that +// starts in between must stop that task's scale-down. +func TestKubeReaperRechecksAfterTaskLock(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.IdleTimeout = time.Minute }) + g := newExecGate(f) + mustExec(t, b, "a") + mustExec(t, b, "b") + clk.Advance(2 * time.Minute) + var finishB func() error + var once sync.Once + b.testHook = func(point, id string) { + if point == "reap" && id == "b" { + once.Do(func() { finishB = g.run(t, b, "b", "hold-b") }) + } + } + if n := b.reapIdle(context.Background()); n != 1 { + t.Fatalf("reaped %d, want only the idle task", n) + } + b.testHook = nil + if w, p := hasPods(f, "b"); !w || !p { + t.Fatal("reaper scaled down a task whose command had just started") + } + if err := finishB(); err != nil { + t.Fatal(err) + } + if got := scaleEvents(b); !reflect.DeepEqual(got[len(got)-1:], []string{"scale_down/idle/a"}) { + t.Fatalf("events = %v", got) + } +} + +// An eviction picks its victim, then takes the victim's lock. A command that +// starts on the victim in between must make it pick the next one. +func TestKubeEvictRechecksAfterVictimLock(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 2 }) + g := newExecGate(f) + mustExec(t, b, "a") + clk.Advance(time.Second) + mustExec(t, b, "b") + clk.Advance(time.Second) + var finishA func() error + var once sync.Once + b.testHook = func(point, id string) { + if point == "evict" && id == "a" { + once.Do(func() { finishA = g.run(t, b, "a", "hold-a") }) + } + } + mustExec(t, b, "c") + b.testHook = nil + if w, p := hasPods(f, "a"); !w || !p { + t.Fatal("evicted a task whose command had just started") + } + if err := finishA(); err != nil { + t.Fatal(err) + } + want := map[string]string{"a": ScaleStateActive, "b": ScaleStateZero, "c": ScaleStateActive} + if got := scaleStates(t, b); !reflect.DeepEqual(got, want) { + t.Fatalf("states = %v", got) + } +} + +// A victim whose lock is held (here: the reaper is deleting its pods) is +// skipped, not waited for: the scale-up evicts the next task at once. +func TestKubeEvictSkipsLockedVictim(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 2; c.IdleTimeout = time.Minute }) + mustExec(t, b, "a") + clk.Advance(2 * time.Minute) + mustExec(t, b, "b") + release := make(chan struct{}) + blocked := make(chan struct{}) + var once sync.Once + ha := kubeTaskHash("a") + hook := func(method, kind, name string) int { + if method == http.MethodDelete && kind == "pods" && strings.HasSuffix(name, ha) { + once.Do(func() { close(blocked) }) + <-release + } + return 0 + } + f.hook.Store(&hook) + reaped := make(chan int, 1) + go func() { reaped <- b.reapIdle(context.Background()) }() + <-blocked + done := make(chan error, 1) + go func() { _, err := b.Exec(context.Background(), "c", execReq("true")); done <- err }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + close(release) + t.Fatal("scale-up waited for a victim locked by the reaper instead of evicting the next task") + } + close(release) + if n := <-reaped; n != 1 { + t.Fatalf("reaped %d", n) + } + want := map[string]string{"a": ScaleStateZero, "b": ScaleStateZero, "c": ScaleStateActive} + if got := scaleStates(t, b); !reflect.DeepEqual(got, want) { + t.Fatalf("states = %v", got) + } +} + +// When a slot frees up while tasks are queued, a newcomer must queue behind +// them (it must not take the slot), and only the head of the queue may take +// it, even when the head is slow to react. +func TestKubeQueueStaysFIFOWhenSlotFrees(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.QueueTimeout = 30 * time.Second }) + b.queueRetry = 50 * time.Millisecond // non-head waiters poll often: they must still not jump the queue + g := newExecGate(f) + finishA := g.run(t, b, "a", "hold-a") + errs := map[string]chan error{"b": make(chan error, 1), "c": make(chan error, 1), "d": make(chan error, 1)} + start := func(id string) { + go func() { _, err := b.Exec(context.Background(), id, execReq("true")); errs[id] <- err }() + } + start("b") + waitFor(t, "b to queue", func() bool { _, w, _ := scaleCounts(b); return w == 1 }) + start("c") + waitFor(t, "c to queue", func() bool { _, w, _ := scaleCounts(b); return w == 2 }) + var hookErr error + var once sync.Once + b.testHook = func(point, id string) { + if point != "slot-woken" || id != "b" { + return + } + once.Do(func() { + // The slot is free and b, the head, has not taken it yet. A newcomer + // arrives, and c's poll fires a few times. + start("d") + hookErr = waitUntil("d to queue or start", func() bool { + _, w, _ := scaleCounts(b) + dw, _ := hasPods(f, "d") + return w == 3 || dw + }) + time.Sleep(300 * time.Millisecond) + }) + } + // Deleting a frees its slot (once its pods are gone) and wakes b. + if err := b.Delete(context.Background(), "a"); err != nil { + t.Fatal(err) + } + for _, id := range []string{"b", "c", "d"} { + select { + case err := <-errs[id]: + if err != nil { + t.Fatalf("exec %s: %v", id, err) + } + case <-time.After(10 * time.Second): + t.Fatalf("exec %s never finished", id) + } + } + b.testHook = nil + _ = finishA() + if hookErr != nil { + t.Fatal(hookErr) + } + var ups []string + for _, e := range scaleEvents(b) { + if strings.HasPrefix(e, "scale_up/") { + ups = append(ups, strings.TrimPrefix(e, "scale_up/first_exec/")) + } + } + if want := []string{"a", "b", "c", "d"}; !reflect.DeepEqual(ups, want) { + t.Fatalf("scale-up order = %v, want %v (queue not FIFO)", ups, want) + } +} + +// A queued scale-up is woken when a busy task's command ends, without relying +// on the fallback poll. +func TestKubeQueueWokenWhenExecEnds(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.QueueTimeout = 30 * time.Second }) + b.queueRetry = time.Hour + g := newExecGate(f) + finishA := g.run(t, b, "a", "hold-a") + done := make(chan error, 1) + go func() { _, err := b.Exec(context.Background(), "b", execReq("true")); done <- err }() + waitFor(t, "b to queue", func() bool { _, w, _ := scaleCounts(b); return w == 1 }) + if err := finishA(); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("queued exec not woken when the busy task's command ended") + } +} + +// A queued scale-up that could not evict (the victim was locked by the reaper) +// is woken when the reaper's scale-down frees the slot. +func TestKubeQueueWokenByScaleDown(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { + c.MaxActive = 1 + c.IdleTimeout = time.Minute + c.QueueTimeout = 30 * time.Second + }) + b.queueRetry = time.Hour + mustExec(t, b, "a") + clk.Advance(2 * time.Minute) + release := make(chan struct{}) + blocked := make(chan struct{}) + var once sync.Once + hook := func(method, kind, name string) int { + if method == http.MethodDelete && kind == "pods" && strings.HasSuffix(name, kubeTaskHash("a")) { + once.Do(func() { close(blocked) }) + <-release + } + return 0 + } + f.hook.Store(&hook) + reaped := make(chan int, 1) + go func() { reaped <- b.reapIdle(context.Background()) }() + <-blocked + done := make(chan error, 1) + go func() { _, err := b.Exec(context.Background(), "b", execReq("true")); done <- err }() + waitFor(t, "b to queue", func() bool { _, w, _ := scaleCounts(b); return w == 1 }) + time.Sleep(50 * time.Millisecond) // b tried to evict a, failed, and waits + close(release) + <-reaped + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("queued exec not woken by the scale-down that freed its slot") + } +} + +// A Delete wakes a queued exec of the same task at once (it does not wait for +// the queue timeout or the fallback poll). +func TestKubeDeleteWakesQueuedExecOfSameTask(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.QueueTimeout = time.Hour }) + b.queueRetry = time.Hour + g := newExecGate(f) + finishA := g.run(t, b, "a", "hold-a") + done := make(chan error, 1) + go func() { _, err := b.Exec(context.Background(), "q", execReq("true")); done <- err }() + waitFor(t, "q to queue", func() bool { _, w, _ := scaleCounts(b); return w == 1 }) + delErr := make(chan error, 1) + go func() { delErr <- b.Delete(context.Background(), "q") }() + select { + case err := <-done: + if err == nil || !strings.Contains(err.Error(), "deleted") { + t.Fatalf("queued exec of a deleted task = %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("queued exec not released by Delete") + } + <-delErr + _ = finishA() + if _, w, _ := scaleCounts(b); w != 0 { + t.Fatalf("waiters = %d", w) + } +} diff --git a/sandbox/kube_scale_test.go b/sandbox/kube_scale_test.go new file mode 100644 index 000000000..f16089dda --- /dev/null +++ b/sandbox/kube_scale_test.go @@ -0,0 +1,1669 @@ +package sandbox + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// fakeClock is the injectable clock of the scaling tests. +type fakeClock struct { + mu sync.Mutex + t time.Time +} + +func (c *fakeClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *fakeClock) Advance(d time.Duration) { + c.mu.Lock() + c.t = c.t.Add(d) + c.mu.Unlock() +} + +func newScaleBackend(t *testing.T, mod func(*KubeConfig)) (*fakeKubeAPI, *httptest.Server, *KubernetesBackend, *fakeClock) { + t.Helper() + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackendCfg(t, f, srv, mod) + clk := &fakeClock{t: time.Date(2026, 12, 1, 10, 0, 0, 0, time.UTC)} + b.now = clk.Now + return f, srv, b, clk +} + +// execGate blocks the execs whose argv carries a held word until released. +type execGate struct { + mu sync.Mutex + holds map[string]*execHold +} + +type execHold struct { + started chan struct{} + release chan struct{} + once sync.Once +} + +func newExecGate(f *fakeKubeAPI) *execGate { + g := &execGate{holds: map[string]*execHold{}} + f.execFn = func(_ string, argv []string) (string, string, int) { + for _, a := range argv { + g.mu.Lock() + h := g.holds[a] + g.mu.Unlock() + if h != nil { + h.once.Do(func() { close(h.started) }) + <-h.release + } + } + return strings.Join(argv, " "), "", 0 + } + return g +} + +// run starts Exec(taskID, word) in the background, waits until the command is +// running in the worker, and returns a function that lets it finish and +// returns the Exec error. +func (g *execGate) run(t *testing.T, b *KubernetesBackend, taskID, word string) func() error { + t.Helper() + h := &execHold{started: make(chan struct{}), release: make(chan struct{})} + g.mu.Lock() + g.holds[word] = h + g.mu.Unlock() + done := make(chan error, 1) + go func() { + _, err := b.Exec(context.Background(), taskID, execReq(word)) + done <- err + }() + select { + case <-h.started: + case err := <-done: + t.Fatalf("exec %s on %s ended before running: %v", word, taskID, err) + case <-time.After(10 * time.Second): + t.Fatalf("exec %s on %s never started", word, taskID) + } + var once sync.Once + finish := func() error { + once.Do(func() { close(h.release) }) + select { + case err := <-done: + done <- err + return err + case <-time.After(10 * time.Second): + t.Errorf("exec %s on %s never returned", word, taskID) + return errors.New("timeout") + } + } + t.Cleanup(func() { once.Do(func() { close(h.release) }) }) + return finish +} + +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(5 * time.Millisecond) + } +} + +func mustExec(t *testing.T, b *KubernetesBackend, taskID string) { + t.Helper() + if _, err := b.Exec(context.Background(), taskID, execReq("true")); err != nil { + t.Fatalf("exec %s: %v", taskID, err) + } +} + +// scaleStates maps task id to its scaling state as GET /v1/tasks reports it. +func scaleStates(t *testing.T, b *KubernetesBackend) map[string]string { + t.Helper() + res, err := b.Status(context.Background()) + if err != nil { + t.Fatal(err) + } + out := map[string]string{} + for _, ts := range res.Tasks { + out[ts.TaskID] = ts.ScalingState + } + return out +} + +func scaleEvents(b *KubernetesBackend) []string { + b.mu.Lock() + defer b.mu.Unlock() + out := []string{} + for _, e := range b.events { + out = append(out, e.Kind+"/"+e.Reason+"/"+e.TaskID) + } + return out +} + +func scaleCounts(b *KubernetesBackend) (active, waiters, states int) { + b.mu.Lock() + defer b.mu.Unlock() + return b.activeLocked(), len(b.waiters), len(b.scale) +} + +func hasPods(f *fakeKubeAPI, taskID string) (worker, proxy bool) { + h := kubeTaskHash(taskID) + return f.obj("pods", "artex-w-"+h) != nil, f.obj("pods", "artex-p-"+h) != nil +} + +func TestKubeIdleScaleToZeroAndResume(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.IdleTimeout = 10 * time.Minute }) + ctx := context.Background() + h := kubeTaskHash("t1") + mustExec(t, b, "t1") + keep := filepath.Join(b.cfg.WorkspaceRoot, "t1", "keep.txt") + if err := os.WriteFile(keep, []byte("state"), 0o600); err != nil { + t.Fatal(err) + } + svcIP := dig(f.obj("services", "artex-p-"+h), "spec", "clusterIP") + + // Not idle long enough: nothing happens. + clk.Advance(10*time.Minute - time.Second) + if n := b.reapIdle(ctx); n != 0 { + t.Fatalf("reaped %d before the idle timeout", n) + } + if w, p := hasPods(f, "t1"); !w || !p { + t.Fatal("pods removed before the idle timeout") + } + + clk.Advance(time.Second) + if n := b.reapIdle(ctx); n != 1 { + t.Fatalf("reaped %d at the idle timeout, want 1", n) + } + if w, p := hasPods(f, "t1"); w || p { + t.Fatalf("pods survive scale-to-zero: worker=%v proxy=%v", w, p) + } + if f.obj("services", "artex-p-"+h) == nil || f.obj("networkpolicies", "artex-w-"+h) == nil || f.obj("networkpolicies", "artex-p-"+h) == nil { + t.Fatal("scale-to-zero removed the Service or a NetworkPolicy") + } + if raw, err := os.ReadFile(keep); err != nil || string(raw) != "state" { + t.Fatalf("workspace lost: %q %v", raw, err) + } + if b.WorkerCount() != 0 { + t.Fatalf("WorkerCount = %d after scale-to-zero", b.WorkerCount()) + } + if st := scaleStates(t, b)["t1"]; st != ScaleStateZero { + t.Fatalf("state = %q", st) + } + // Nothing runs in a task without pods; a second reap is a no-op. + if err := b.Kill(ctx, "t1"); !errors.Is(err, ErrNotFound) { + t.Fatalf("Kill on a scaled-to-zero task = %v", err) + } + if n := b.reapIdle(ctx); n != 0 { + t.Fatalf("second reap = %d", n) + } + + // The next exec scales it back up through the normal path. + mark := len(f.opsSnapshot()) + execsBefore := len(f.execs) + mustExec(t, b, "t1") + ops := f.opsSnapshot()[mark:] + want := []string{"update networkpolicies/artex-w-" + h, "update networkpolicies/artex-p-" + h, "create pods/artex-p-" + h, "create pods/artex-w-" + h} + if !reflect.DeepEqual(ops, want) { + t.Fatalf("resume ops = %v, want %v", ops, want) + } + // Both network probes ran again before the command. + f.mu.Lock() + resumed := f.execContainers[execsBefore:] + f.mu.Unlock() + if !reflect.DeepEqual(resumed, []string{kubeWorkerName, kubeProxyName, kubeWorkerName}) { + t.Fatalf("resume execs ran in %v", resumed) + } + if got := dig(f.obj("services", "artex-p-"+h), "spec", "clusterIP"); got != svcIP { + t.Fatalf("proxy ClusterIP changed across scale-to-zero: %v -> %v", svcIP, got) + } + env := envOf(dig(f.obj("pods", "artex-w-"+h), "spec", "containers", 0)) + if env["HTTP_PROXY"] != fmt.Sprintf("http://%v:%d", svcIP, DefaultProxyPort) { + t.Fatalf("resumed worker proxy env = %q", env["HTTP_PROXY"]) + } + if raw, err := os.ReadFile(keep); err != nil || string(raw) != "state" { + t.Fatalf("workspace lost on resume: %q %v", raw, err) + } + if got, want := scaleEvents(b), []string{"scale_up/first_exec/t1", "scale_down/idle/t1", "scale_up/resume/t1"}; !reflect.DeepEqual(got, want) { + t.Fatalf("events = %v", got) + } + if st := scaleStates(t, b)["t1"]; st != ScaleStateActive || b.WorkerCount() != 1 { + t.Fatalf("state after resume = %q, workers %d", st, b.WorkerCount()) + } +} + +func TestKubeIdleTimeoutZeroDisablesReaper(t *testing.T) { + f, _, b, clk := newScaleBackend(t, nil) + mustExec(t, b, "t1") + clk.Advance(1000 * time.Hour) + if n := b.reapIdle(context.Background()); n != 0 { + t.Fatalf("reaped %d with idle scale-down disabled", n) + } + if w, p := hasPods(f, "t1"); !w || !p { + t.Fatal("pods removed with idle scale-down disabled") + } + // RunScaler has nothing to do and returns. + done := make(chan struct{}) + go func() { b.RunScaler(context.Background()); close(done) }() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("RunScaler keeps running with idle scale-down disabled") + } + res, _ := b.Status(context.Background()) + if res.Tasks[0].IdleExpiresAt != "" || res.Scaling.IdleTimeoutSeconds != 0 { + t.Fatalf("idle expiry reported while disabled: %+v", res.Tasks[0]) + } +} + +func TestKubeRunScalerReapsAndStops(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.IdleTimeout = time.Second }) + mustExec(t, b, "t1") + clk.Advance(time.Minute) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { b.RunScaler(ctx); close(done) }() + waitFor(t, "the reaper loop to scale t1 down", func() bool { w, p := hasPods(f, "t1"); return !w && !p }) + cancel() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("RunScaler did not stop on context cancel") + } +} + +func TestKubeNoReapWithInFlightExec(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.IdleTimeout = time.Minute }) + g := newExecGate(f) + finish := g.run(t, b, "t1", "long") + clk.Advance(time.Hour) + if n := b.reapIdle(context.Background()); n != 0 { + t.Fatalf("reaped %d task(s) with a command running", n) + } + res, _ := b.Status(context.Background()) + if ts := res.Tasks[0]; ts.InFlight != 1 || ts.IdleExpiresAt != "" || ts.ScalingState != ScaleStateActive { + t.Fatalf("running task status = %+v", ts) + } + if err := finish(); err != nil { + t.Fatal(err) + } + // The idle timer starts when the command ends, not when it began. + if n := b.reapIdle(context.Background()); n != 0 { + t.Fatal("reaped right after a long command finished") + } + res, _ = b.Status(context.Background()) + if want := clk.Now().Add(time.Minute).Format(time.RFC3339); res.Tasks[0].IdleExpiresAt != want || res.Tasks[0].InFlight != 0 { + t.Fatalf("idle expiry = %q, want %q (%+v)", res.Tasks[0].IdleExpiresAt, want, res.Tasks[0]) + } + clk.Advance(time.Minute) + if n := b.reapIdle(context.Background()); n != 1 { + t.Fatalf("reaped %d after the timeout", n) + } +} + +// An exec that arrives while its task is being scaled down waits for the +// scale-down and then brings the task back: it never fails and never runs in a +// pod that is going away. +func TestKubeExecRacingScaleDown(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.IdleTimeout = time.Minute }) + mustExec(t, b, "t1") + clk.Advance(2 * time.Minute) + + blocked, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + hook := func(method, kind, _ string) int { + if method == http.MethodDelete && kind == "pods" { + once.Do(func() { close(blocked) }) + <-release + } + return 0 + } + f.hook.Store(&hook) + reaped := make(chan int, 1) + go func() { reaped <- b.reapIdle(context.Background()) }() + <-blocked + + execErr := make(chan error, 1) + go func() { + _, err := b.Exec(context.Background(), "t1", execReq("echo", "mid-scale-down")) + execErr <- err + }() + waitFor(t, "the exec to be counted in flight", func() bool { + b.mu.Lock() + defer b.mu.Unlock() + return b.scale["t1"].inflight == 1 + }) + select { + case err := <-execErr: + t.Fatalf("exec returned while the scale-down held the task: %v", err) + case <-time.After(100 * time.Millisecond): + } + close(release) + if n := <-reaped; n != 1 { + t.Fatalf("reaper scaled %d task(s) down", n) + } + if err := <-execErr; err != nil { + t.Fatalf("exec racing a scale-down failed: %v", err) + } + if got := f.lastExec(); got[len(got)-1] != "mid-scale-down" { + t.Fatalf("last exec = %v", got) + } + if got, want := scaleEvents(b), []string{"scale_up/first_exec/t1", "scale_down/idle/t1", "scale_up/resume/t1"}; !reflect.DeepEqual(got, want) { + t.Fatalf("events = %v", got) + } + if w, p := hasPods(f, "t1"); !w || !p { + t.Fatal("task has no pods after the racing exec") + } +} + +// The other order: the exec is already counted when the reaper looks. +func TestKubeReaperSkipsTaskLockedByExec(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.IdleTimeout = time.Minute }) + mustExec(t, b, "t1") + h := kubeTaskHash("t1") + // Kill the worker so the next exec holds the task lock while recreating it. + f.setPodPhase("artex-w-"+h, "Failed", false) + blocked, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + hook := func(method, kind, name string) int { + if method == http.MethodPost && kind == "pods" { + once.Do(func() { close(blocked) }) + <-release + } + return 0 + } + f.hook.Store(&hook) + clk.Advance(time.Hour) + execErr := make(chan error, 1) + go func() { + _, err := b.Exec(context.Background(), "t1", execReq("true")) + execErr <- err + }() + <-blocked + if n := b.reapIdle(context.Background()); n != 0 { + t.Fatalf("reaper scaled down a task that is starting (%d)", n) + } + if st := scaleStates(t, b)["t1"]; st != ScaleStateStarting { + t.Fatalf("state while starting = %q", st) + } + close(release) + if err := <-execErr; err != nil { + t.Fatal(err) + } + if got := scaleEvents(b); got[len(got)-1] != "scale_up/recreate/t1" { + t.Fatalf("events = %v", got) + } + // A recreate is not a cold start. + b.mu.Lock() + n := len(b.coldStarts) + b.mu.Unlock() + if n != 1 { + t.Fatalf("cold starts = %d, want 1 (first exec only)", n) + } +} + +func TestKubeMaxActiveEvictsLeastRecentlyUsed(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 2 }) + for _, id := range []string{"a", "b"} { + mustExec(t, b, id) + clk.Advance(time.Second) + } + // a is the least recently used: c takes its slot. + mustExec(t, b, "c") + clk.Advance(time.Second) + if got, want := scaleStates(t, b), map[string]string{"a": ScaleStateZero, "b": ScaleStateActive, "c": ScaleStateActive}; !reflect.DeepEqual(got, want) { + t.Fatalf("states = %v", got) + } + if w, p := hasPods(f, "a"); w || p { + t.Fatal("evicted task still has pods") + } + if f.obj("services", "artex-p-"+kubeTaskHash("a")) == nil || f.obj("networkpolicies", "artex-w-"+kubeTaskHash("a")) == nil { + t.Fatal("eviction removed the Service or NetworkPolicy") + } + // Using b makes c the least recently used. + mustExec(t, b, "b") + clk.Advance(time.Second) + mustExec(t, b, "a") + if got, want := scaleStates(t, b), map[string]string{"a": ScaleStateActive, "b": ScaleStateActive, "c": ScaleStateZero}; !reflect.DeepEqual(got, want) { + t.Fatalf("states after second eviction = %v", got) + } + want := []string{"scale_up/first_exec/a", "scale_up/first_exec/b", "scale_down/evicted/a", "scale_up/first_exec/c", "scale_down/evicted/c", "scale_up/resume/a"} + if got := scaleEvents(b); !reflect.DeepEqual(got, want) { + t.Fatalf("events = %v", got) + } + if f.count("pods") != 4 { + t.Fatalf("pods = %d, want 4 (two active tasks)", f.count("pods")) + } + res, _ := b.Status(context.Background()) + if s := res.Scaling; s.MaxActive != 2 || s.Active != 2 || s.ScaledToZero != 1 || s.Queued != 0 || s.Starting != 0 { + t.Fatalf("scaling = %+v", s) + } +} + +func TestKubeMaxActiveZeroIsUnlimited(t *testing.T) { + f, _, b, _ := newScaleBackend(t, nil) + for i := range 6 { + mustExec(t, b, fmt.Sprintf("t%d", i)) + } + if f.count("pods") != 12 { + t.Fatalf("pods = %d", f.count("pods")) + } + for _, e := range scaleEvents(b) { + if !strings.HasPrefix(e, "scale_up/first_exec/") { + t.Fatalf("unexpected event %s", e) + } + } + res, _ := b.Status(context.Background()) + if s := res.Scaling; !s.Supported || s.MaxActive != 0 || s.Active != 6 { + t.Fatalf("scaling = %+v", s) + } +} + +func TestKubeQueueWaitsForBusySlotFIFO(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.QueueTimeout = 30 * time.Second }) + g := newExecGate(f) + finishA := g.run(t, b, "a", "hold-a") + + // b then c queue behind the busy slot, in that order. + errs := map[string]chan error{"b": make(chan error, 1), "c": make(chan error, 1)} + for i, id := range []string{"b", "c"} { + go func() { + _, err := b.Exec(context.Background(), id, execReq("true")) + errs[id] <- err + }() + waitFor(t, id+" to queue", func() bool { _, w, _ := scaleCounts(b); return w == i+1 }) + } + res, _ := b.Status(context.Background()) + if s := res.Scaling; s.Queued != 2 || s.Active != 1 { + t.Fatalf("scaling while queued = %+v", s) + } + states := scaleStates(t, b) + if states["b"] != ScaleStateQueued || states["c"] != ScaleStateQueued || states["a"] != ScaleStateActive { + t.Fatalf("states = %v", states) + } + if qb := findTask(t, res, "b"); qb.Tracked || qb.Worker.State != StateMissing || qb.InFlight != 1 { + t.Fatalf("queued task status = %+v", qb) + } + // Nothing was created for the queued tasks. + if f.count("pods") != 2 || f.count("services") != 1 { + t.Fatalf("queued tasks created objects: %d pods, %d services", f.count("pods"), f.count("services")) + } + select { + case err := <-errs["b"]: + t.Fatalf("queued exec returned early: %v", err) + case <-time.After(50 * time.Millisecond): + } + + if err := finishA(); err != nil { + t.Fatal(err) + } + for _, id := range []string{"b", "c"} { + if err := <-errs[id]; err != nil { + t.Fatalf("queued exec %s: %v", id, err) + } + } + want := []string{"scale_up/first_exec/a", "scale_down/evicted/a", "scale_up/first_exec/b", "scale_down/evicted/b", "scale_up/first_exec/c"} + if got := scaleEvents(b); !reflect.DeepEqual(got, want) { + t.Fatalf("events = %v (queue is not FIFO?)", got) + } + if a, w, _ := scaleCounts(b); a != 1 || w != 0 { + t.Fatalf("active=%d waiters=%d after the queue drained", a, w) + } +} + +func TestKubeQueueTimeout(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.QueueTimeout = 150 * time.Millisecond }) + g := newExecGate(f) + finishA := g.run(t, b, "a", "hold-a") + + start := time.Now() + _, err := b.Exec(context.Background(), "b", execReq("true")) + if !errors.Is(err, ErrCapacity) { + t.Fatalf("exec at capacity = %v, want ErrCapacity", err) + } + if IsUnavailable(err) { + t.Fatal("a capacity timeout must not read as an unavailable runner") + } + for _, part := range []string{"1 of 1 sandbox slots", "150ms", "ARTEX_KUBE_MAX_ACTIVE"} { + if !strings.Contains(err.Error(), part) { + t.Errorf("error %q does not mention %q", err, part) + } + } + if d := time.Since(start); d < 150*time.Millisecond || d > 5*time.Second { + t.Fatalf("queue wait took %s", d) + } + if a, w, n := scaleCounts(b); a != 1 || w != 0 || n != 1 { + t.Fatalf("after timeout: active=%d waiters=%d states=%d", a, w, n) + } + if f.count("pods") != 2 || f.count("services") != 1 { + t.Fatal("the timed-out task left objects behind") + } + + // Over HTTP it is a 429 that the client maps back to ErrCapacity. + rs, rerr := NewRunnerServer("tok", "v", b) + if rerr != nil { + t.Fatal(rerr) + } + hs := httptest.NewServer(rs.Handler()) + defer hs.Close() + c := NewClient(hs.URL, "tok") + _, err = c.Exec(context.Background(), "b", execReq("true")) + if !errors.Is(err, ErrCapacity) || IsUnavailable(err) || !strings.Contains(err.Error(), "sandbox slots") { + t.Fatalf("client exec at capacity = %v", err) + } + // The busy task is unaffected, and b gets in once a is idle. + if err := finishA(); err != nil { + t.Fatal(err) + } + mustExec(t, b, "b") +} + +func TestKubeQueueHonoursContext(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.QueueTimeout = time.Minute }) + g := newExecGate(f) + finishA := g.run(t, b, "a", "hold-a") + + ctx, cancel := context.WithCancel(context.Background()) + errc := make(chan error, 1) + go func() { + _, err := b.Exec(ctx, "b", execReq("true")) + errc <- err + }() + waitFor(t, "b to queue", func() bool { _, w, _ := scaleCounts(b); return w == 1 }) + cancel() + select { + case err := <-errc: + if !errors.Is(err, context.Canceled) || errors.Is(err, ErrCapacity) { + t.Fatalf("cancelled queued exec = %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("queued exec ignored its context") + } + if a, w, n := scaleCounts(b); a != 1 || w != 0 || n != 1 { + t.Fatalf("after cancel: active=%d waiters=%d states=%d", a, w, n) + } + // A cancelled head hands the queue on: c is served when a finishes. + errC := make(chan error, 1) + go func() { + _, err := b.Exec(context.Background(), "c", execReq("true")) + errC <- err + }() + waitFor(t, "c to queue", func() bool { _, w, _ := scaleCounts(b); return w == 1 }) + if err := finishA(); err != nil { + t.Fatal(err) + } + if err := <-errC; err != nil { + t.Fatal(err) + } +} + +func TestKubeDeleteDuringQueue(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.QueueTimeout = time.Minute }) + g := newExecGate(f) + ctx := context.Background() + + // old exists and was evicted; fresh was never created. + mustExec(t, b, "old") + clk.Advance(time.Second) + finishA := g.run(t, b, "a", "hold-a") + if st := scaleStates(t, b)["old"]; st != ScaleStateZero { + t.Fatalf("old = %q", st) + } + errs := map[string]chan error{"old": make(chan error, 1), "fresh": make(chan error, 1)} + for i, id := range []string{"old", "fresh"} { + go func() { + _, err := b.Exec(ctx, id, execReq("true")) + errs[id] <- err + }() + waitFor(t, id+" to queue", func() bool { _, w, _ := scaleCounts(b); return w == i+1 }) + } + + // Deleting a queued task ends its wait at once and removes what it had. + done := make(chan error, 1) + go func() { done <- b.Delete(ctx, "old") }() + select { + case err := <-done: + if err != nil { + t.Fatalf("Delete(old) = %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("Delete blocked behind the queued exec") + } + if err := <-errs["old"]; !errors.Is(err, ErrNotFound) || !strings.Contains(err.Error(), "deleted") { + t.Fatalf("queued exec of a deleted task = %v", err) + } + hOld := kubeTaskHash("old") + if f.obj("services", "artex-p-"+hOld) != nil || f.obj("networkpolicies", "artex-w-"+hOld) != nil || f.obj("networkpolicies", "artex-p-"+hOld) != nil { + t.Fatal("Delete left the Service or policies of a scaled-to-zero task") + } + + // A task that never got pods: Delete reports not found, the exec still ends. + if err := b.Delete(ctx, "fresh"); !errors.Is(err, ErrNotFound) { + t.Fatalf("Delete(fresh) = %v", err) + } + if err := <-errs["fresh"]; !errors.Is(err, ErrNotFound) { + t.Fatalf("queued exec of a deleted new task = %v", err) + } + if a, w, n := scaleCounts(b); a != 1 || w != 0 || n != 1 { + t.Fatalf("after deletes: active=%d waiters=%d states=%d", a, w, n) + } + if err := finishA(); err != nil { + t.Fatal(err) + } + // A new exec after the delete starts from scratch. + mustExec(t, b, "old") + if got := scaleEvents(b); got[len(got)-1] != "scale_up/first_exec/old" { + t.Fatalf("events = %v", got) + } +} + +func TestKubeDeleteFreesSlotAndRecordsEvent(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.QueueTimeout = time.Minute }) + g := newExecGate(f) + finishA := g.run(t, b, "a", "hold-a") + errc := make(chan error, 1) + go func() { + _, err := b.Exec(context.Background(), "b", execReq("true")) + errc <- err + }() + waitFor(t, "b to queue", func() bool { _, w, _ := scaleCounts(b); return w == 1 }) + // Deleting the busy task frees its slot for the queue. + if err := b.Delete(context.Background(), "a"); err != nil { + t.Fatal(err) + } + if err := <-errc; err != nil { + t.Fatalf("queued exec after the slot was freed by Delete: %v", err) + } + _ = finishA() + want := []string{"scale_up/first_exec/a", "scale_down/deleted/a", "scale_up/first_exec/b"} + if got := scaleEvents(b); !reflect.DeepEqual(got, want) { + t.Fatalf("events = %v", got) + } + // Deleting a scaled-to-zero task records no scale-down: it had no pods. + if _, ok := scaleStates(t, b)["a"]; ok { + t.Fatal("deleted task still listed") + } +} + +func TestKubeFailedStartSlotAccounting(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { + c.MaxActive = 1 + c.IdleTimeout = time.Minute + c.QueueTimeout = 100 * time.Millisecond + }) + ctx := context.Background() + + // Nothing created (the policy write fails): the slot is free again. + hook := func(method, kind, _ string) int { + if method == http.MethodPost && kind == "networkpolicies" { + return http.StatusInternalServerError + } + return 0 + } + f.hook.Store(&hook) + if _, err := b.Exec(ctx, "p", execReq("true")); err == nil { + t.Fatal("exec succeeded without network policies") + } + f.hook.Store(nil) + if a, w, n := scaleCounts(b); a != 0 || w != 0 || n != 0 { + t.Fatalf("after a start that created nothing: active=%d waiters=%d states=%d", a, w, n) + } + + // Pods created but never ready: they are deleted and the slot released at + // once, so the next task gets it without waiting for the reaper. + f.podMode["artex-w-"+kubeTaskHash("q")] = "pull-error" + if _, err := b.Exec(ctx, "q", execReq("true")); err == nil { + t.Fatal("exec succeeded with an unpullable image") + } + if a, _, _ := scaleCounts(b); a != 0 { + t.Fatalf("active = %d after a failed start", a) + } + if w, p := hasPods(f, "q"); w || p { + t.Fatal("failed start left pods behind") + } + // Its Service exists, so it is tracked as scaled to zero. + if st := scaleStates(t, b)["q"]; st != ScaleStateZero { + t.Fatalf("failed task state = %q", st) + } + want := []string{"scale_up_failed/first_exec/p", "scale_up_failed/first_exec/q"} + if got := scaleEvents(b); !reflect.DeepEqual(got, want) { + t.Fatalf("events = %v", got) + } + mustExec(t, b, "ok") + // Delete still removes what the failed start left (Service, policies). + if err := b.Delete(ctx, "q"); err != nil { + t.Fatalf("Delete of a failed start = %v", err) + } + if f.obj("services", "artex-p-"+kubeTaskHash("q")) != nil || f.obj("networkpolicies", "artex-w-"+kubeTaskHash("q")) != nil { + t.Fatal("Delete left objects of a failed start") + } + // A retry after fixing the image resumes the task. + delete(f.podMode, "artex-w-"+kubeTaskHash("q")) + mustExec(t, b, "q") +} + +// TestKubeFailedStartReleasesSlot covers each way a scale-up can fail after +// creating pods: the pods are deleted, the slot is free for a queued task, a +// scale_up_failed event carries the error and no cold-start sample is taken. +func TestKubeFailedStartReleasesSlot(t *testing.T) { + cases := []struct { + name string + setup func(f *fakeKubeAPI, b *KubernetesBackend) + want string + }{ + {"pull error", func(f *fakeKubeAPI, _ *KubernetesBackend) { + f.podMode["artex-w-"+kubeTaskHash("bad")] = "pull-error" + }, "ImagePullBackOff"}, + {"never ready", func(f *fakeKubeAPI, _ *KubernetesBackend) { + f.podMode["artex-p-"+kubeTaskHash("bad")] = "pending" + }, "not ready"}, + {"network never ready", func(f *fakeKubeAPI, _ *KubernetesBackend) { + bad := "artex-p-" + kubeTaskHash("bad") + f.execFn = func(pod string, argv []string) (string, string, int) { + if pod == bad && argv[0] == "getent" { + return "", "", 2 + } + return "", "", 0 + } + }, "proxy to cluster DNS"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { + c.MaxActive = 1 + c.QueueTimeout = 30 * time.Second + c.PodReadyTimeout = 700 * time.Millisecond + }) + tc.setup(f, b) + // The failing start holds its slot (it is creating its first pod) + // until a second task has queued behind it. + starting, queued := make(chan struct{}), make(chan struct{}) + var once sync.Once + hook := func(method, kind, name string) int { + if method == http.MethodPost && kind == "pods" && name == "" { + once.Do(func() { close(starting); <-queued }) + } + return 0 + } + f.hook.Store(&hook) + bad := make(chan error, 1) + go func() { _, err := b.Exec(context.Background(), "bad", execReq("true")); bad <- err }() + <-starting + good := make(chan error, 1) + go func() { + _, err := b.Exec(context.Background(), "good", execReq("true")) + good <- err + }() + waitFor(t, "good to queue", func() bool { _, w, _ := scaleCounts(b); return w == 1 }) + close(queued) + if err := <-bad; err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("bad exec err = %v, want %q", err, tc.want) + } + select { + case err := <-good: + if err != nil { + t.Fatalf("queued exec after a failed start: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("queued exec never got the slot of the failed start") + } + if w, p := hasPods(f, "bad"); w || p { + t.Fatal("failed start left pods behind") + } + res, _ := b.Status(context.Background()) + var failed *ScaleEvent + for i, ev := range res.Scaling.Events { + if ev.Kind == ScaleKindUpFailed { + failed = &res.Scaling.Events[i] + } + } + if failed == nil || failed.TaskID != "bad" || failed.Reason != ScaleReasonFirstExec || !strings.Contains(failed.Error, tc.want) { + t.Fatalf("scale_up_failed event = %+v (events %v)", failed, scaleEvents(b)) + } + if res.Scaling.ColdStart.Count != 1 || res.Scaling.Totals.ScaleUpFailures != 1 || res.Scaling.Totals.ScaleUps != 1 { + t.Fatalf("cold starts %d totals %+v", res.Scaling.ColdStart.Count, res.Scaling.Totals) + } + if a, w, _ := scaleCounts(b); a != 1 || w != 0 { + t.Fatalf("active=%d waiters=%d", a, w) + } + }) + } +} + +// TestKubeFailedStartCleanupFailureKeepsSlot: when the pods of a failed start +// cannot be deleted the slot stays taken (they still use the node) and the +// reaper removes them later. +func TestKubeFailedStartCleanupFailureKeepsSlot(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.IdleTimeout = time.Minute }) + ctx := context.Background() + f.podMode["artex-w-"+kubeTaskHash("bad")] = "pull-error" + var failDel atomic.Bool + failDel.Store(true) + hook := func(method, kind, _ string) int { + if method == http.MethodDelete && kind == "pods" && failDel.Load() { + return http.StatusInternalServerError + } + return 0 + } + f.hook.Store(&hook) + if _, err := b.Exec(ctx, "bad", execReq("true")); err == nil { + t.Fatal("exec succeeded with an unpullable image") + } + if a, _, _ := scaleCounts(b); a != 1 { + t.Fatalf("active = %d while the failed pods could not be removed", a) + } + failDel.Store(false) + clk.Advance(time.Minute) + if n := b.reapIdle(ctx); n != 1 { + t.Fatalf("reaped %d", n) + } + if a, _, n := scaleCounts(b); a != 0 || n != 0 || f.count("pods") != 0 { + t.Fatalf("after reaping: active=%d states=%d pods=%d", a, n, f.count("pods")) + } + // Its Service and policies go too: the forgotten task could not delete them. + hb := kubeTaskHash("bad") + if f.obj("services", "artex-p-"+hb) != nil || f.obj("networkpolicies", "artex-w-"+hb) != nil || f.obj("networkpolicies", "artex-p-"+hb) != nil { + t.Fatal("reaping a failed start left its Service or network policies") + } + if err := b.Delete(ctx, "bad"); !errors.Is(err, ErrNotFound) { + t.Fatalf("Delete of a reaped failed start = %v", err) + } +} + +// TestKubeDeleteHoldsSlotUntilPodsGone: a queued scale-up must not start while +// the deleted task's pods still exist, or the cap is exceeded by one. +func TestKubeDeleteHoldsSlotUntilPodsGone(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.QueueTimeout = time.Minute }) + g := newExecGate(f) + finishA := g.run(t, b, "a", "hold-a") + // Pod deletions of a hang (the kubelet is slow to stop them) until released. + release := make(chan struct{}) + ha := kubeTaskHash("a") + var blocked atomic.Int32 + hook := func(method, kind, name string) int { + if method == http.MethodDelete && kind == "pods" && strings.HasSuffix(name, ha) { + blocked.Add(1) + <-release + } + return 0 + } + f.hook.Store(&hook) + errc := make(chan error, 1) + go func() { _, err := b.Exec(context.Background(), "b", execReq("true")); errc <- err }() + waitFor(t, "b to queue", func() bool { _, w, _ := scaleCounts(b); return w == 1 }) + delErr := make(chan error, 1) + go func() { delErr <- b.Delete(context.Background(), "a") }() + waitFor(t, "delete to reach the pods", func() bool { return blocked.Load() > 0 }) + // While a's pods are going away the slot is still taken: b keeps waiting. + time.Sleep(200 * time.Millisecond) + if w, _ := hasPods(f, "b"); w { + t.Fatal("queued task started while the deleted task's pods still exist") + } + if a, w, _ := scaleCounts(b); a != 1 || w != 1 { + t.Fatalf("during delete: active=%d waiters=%d", a, w) + } + if res, _ := b.Status(context.Background()); res.Scaling.Active != 1 { + t.Fatalf("status active = %d during delete", res.Scaling.Active) + } + close(release) + if err := <-delErr; err != nil { + t.Fatal(err) + } + if err := <-errc; err != nil { + t.Fatalf("queued exec after delete: %v", err) + } + _ = finishA() + want := []string{"scale_up/first_exec/a", "scale_down/deleted/a", "scale_up/first_exec/b"} + if got := scaleEvents(b); !reflect.DeepEqual(got, want) { + t.Fatalf("events = %v", got) + } + if a, w, _ := scaleCounts(b); a != 1 || w != 0 { + t.Fatalf("after: active=%d waiters=%d", a, w) + } +} + +// TestKubeDeleteWaitsForTerminatingPods: with pods that take a while to +// terminate (as on a real kubelet), a queued scale-up starts only after the +// deleted task's pods have left the API. +func TestKubeDeleteWaitsForTerminatingPods(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.QueueTimeout = time.Minute }) + f.podTerminate.Store(int64(400 * time.Millisecond)) + g := newExecGate(f) + finishA := g.run(t, b, "a", "hold-a") + errc := make(chan error, 1) + go func() { _, err := b.Exec(context.Background(), "b", execReq("true")); errc <- err }() + waitFor(t, "b to queue", func() bool { _, w, _ := scaleCounts(b); return w == 1 }) + if err := b.Delete(context.Background(), "a"); err != nil { + t.Fatal(err) + } + if w, p := hasPods(f, "a"); w || p { + t.Fatal("Delete returned while the pods were still terminating") + } + if err := <-errc; err != nil { + t.Fatal(err) + } + _ = finishA() +} + +// TestKubeCapNeverExceededUnderChurn races execs, deletes and the reaper with a +// cap of 2 while sampling the live pod count from the fake API server: there are +// never more than MaxActive tasks with pods. +func TestKubeCapNeverExceededUnderChurn(t *testing.T) { + const maxActive = 2 + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { + c.MaxActive = maxActive + c.IdleTimeout = time.Second + c.QueueTimeout = 20 * time.Second + }) + // Pods take a while to terminate, as on a real kubelet: the window the old + // Delete released its slot in. + f.podTerminate.Store(int64(5 * time.Millisecond)) + stop := make(chan struct{}) + var maxSeen atomic.Int32 + var sampler sync.WaitGroup + sampler.Add(1) + go func() { + defer sampler.Done() + for { + select { + case <-stop: + return + default: + } + f.mu.Lock() + tasks := map[string]bool{} + for _, p := range f.objs["pods"] { + if ann, ok := dig(p, "metadata", "annotations", AnnotationTaskID).(string); ok { + tasks[ann] = true + } + } + f.mu.Unlock() + if n := int32(len(tasks)); n > maxSeen.Load() { + maxSeen.Store(n) + } + time.Sleep(200 * time.Microsecond) + } + }() + var wg sync.WaitGroup + for w := range 6 { + wg.Add(1) + go func() { + defer wg.Done() + for i := range 12 { + id := fmt.Sprintf("c%d", (w+i)%5) + switch i % 4 { + case 3: + _ = b.Delete(context.Background(), id) + case 2: + clk.Advance(2 * time.Second) + b.reapIdle(context.Background()) + default: + _, _ = b.Exec(context.Background(), id, execReq("true")) + } + } + }() + } + wg.Wait() + close(stop) + sampler.Wait() + if m := maxSeen.Load(); m > maxActive { + t.Fatalf("saw %d tasks with pods at once, cap is %d", m, maxActive) + } + if a, w, _ := scaleCounts(b); w != 0 || a > maxActive { + t.Fatalf("end: active=%d waiters=%d", a, w) + } + b.mu.Lock() + d := b.draining + b.mu.Unlock() + if d != 0 { + t.Fatalf("draining = %d after all deletes returned", d) + } +} + +func TestKubeRecoverSeedsScalingState(t *testing.T) { + f, srv, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.IdleTimeout = 10 * time.Minute }) + ctx := context.Background() + mustExec(t, b, "live") + mustExec(t, b, "zero") + clk.Advance(9 * time.Minute) + mustExec(t, b, "live") + clk.Advance(time.Minute) + if n := b.reapIdle(ctx); n != 1 { + t.Fatalf("reaped %d", n) + } + + // A new runner process, a day later. + fresh := newTestKubeBackendCfg(t, f, srv, func(c *KubeConfig) { c.IdleTimeout = 10 * time.Minute }) + clk2 := &fakeClock{t: clk.Now().Add(24 * time.Hour)} + fresh.now = clk2.Now + n, err := fresh.Recover(ctx) + if err != nil || n != 2 { + t.Fatalf("Recover = %d, %v (a scaled-to-zero task is adopted from its Service)", n, err) + } + if fresh.WorkerCount() != 1 { + t.Fatalf("WorkerCount = %d", fresh.WorkerCount()) + } + res, _ := fresh.Status(ctx) + live, zero := findTask(t, res, "live"), findTask(t, res, "zero") + now := clk2.Now().Format(time.RFC3339) + if live.ScalingState != ScaleStateActive || live.LastActivity != now || live.IdleExpiresAt != clk2.Now().Add(10*time.Minute).Format(time.RFC3339) { + t.Fatalf("recovered live task = %+v", live) + } + if zero.ScalingState != ScaleStateZero || !zero.Tracked || zero.ProxyIP == "" || zero.LastActivity != now || zero.IdleExpiresAt != "" { + t.Fatalf("recovered scaled-to-zero task = %+v", zero) + } + if s := res.Scaling; s.Active != 1 || s.ScaledToZero != 1 || len(s.Events) != 0 || s.ColdStart.Count != 0 { + t.Fatalf("scaling after recover = %+v", s) + } + // Adopted tasks are not reaped on the first tick: their idle timer starts at Recover. + if n := fresh.reapIdle(ctx); n != 0 { + t.Fatalf("reaped %d right after Recover", n) + } + clk2.Advance(10 * time.Minute) + if n := fresh.reapIdle(ctx); n != 1 { + t.Fatalf("reaped %d after the idle timeout", n) + } + // The scaled-to-zero task resumes on its existing Service. + mark := len(f.opsSnapshot()) + mustExec(t, fresh, "zero") + for _, op := range f.opsSnapshot()[mark:] { + if strings.Contains(op, "services/") { + t.Fatalf("resume touched the Service: %s", op) + } + } + if got := scaleEvents(fresh); !reflect.DeepEqual(got, []string{"scale_down/idle/live", "scale_up/resume/zero"}) { + t.Fatalf("events = %v", got) + } + // And a scaled-to-zero task adopted from its Service can be deleted. + if err := fresh.Delete(ctx, "live"); err != nil { + t.Fatal(err) + } + h := kubeTaskHash("live") + if f.obj("services", "artex-p-"+h) != nil || f.obj("networkpolicies", "artex-w-"+h) != nil { + t.Fatal("Delete left objects of a task adopted without pods") + } +} + +func TestKubeRecoverIgnoresForeignServices(t *testing.T) { + f, srv, _, _ := newScaleBackend(t, nil) + svc := func(name, hash, task, ip string) { + f.objs["services"][name] = map[string]any{ + "metadata": map[string]any{"name": name, + "labels": map[string]any{LabelManagedBy: ManagedByRunner, LabelComponent: ComponentProxy, LabelTaskHash: hash}, + "annotations": map[string]any{AnnotationTaskID: task}}, + "spec": map[string]any{"clusterIP": ip}, + } + } + svc("artex-p-forged", "0000000000000000", "victim", "10.43.0.50") + svc("artex-p-bad", kubeTaskHash("../x"), "../x", "10.43.0.51") + svc("artex-p-noip", kubeTaskHash("noip"), "noip", "None") + svc("artex-p-"+kubeTaskHash("good"), kubeTaskHash("good"), "good", "10.43.0.52") + fresh := newTestKubeBackend(t, f, srv) + n, err := fresh.Recover(context.Background()) + if err != nil || n != 1 || fresh.tasks["good"] == nil || fresh.tasks["good"].proxyIP != "10.43.0.52" { + t.Fatalf("Recover = %d, %v, tasks %v", n, err, fresh.tasks) + } +} + +func TestKubeScaleEventRingIsBounded(t *testing.T) { + _, _, b, clk := newScaleBackend(t, nil) + b.mu.Lock() + for i := range 3*kubeScaleEventCap + 7 { + clk.Advance(time.Second) + b.recordEventLocked(ScaleEvent{Time: clk.Now().Format(time.RFC3339), TaskID: fmt.Sprintf("t%d", i), Kind: ScaleKindUp, Reason: ScaleReasonResume, DurationMS: int64(i)}) + b.recordEventLocked(ScaleEvent{TaskID: fmt.Sprintf("t%d", i), Kind: ScaleKindDown, Reason: ScaleReasonIdle}) + } + events, cold := len(b.events), len(b.coldStarts) + last, firstCold, lastCold := b.events[events-1], b.coldStarts[0], b.coldStarts[cold-1] + st := b.scalingStatusLocked() + b.mu.Unlock() + total := 3*kubeScaleEventCap + 7 + if events != kubeScaleEventCap || cold != kubeColdStartCap { + t.Fatalf("events=%d cold=%d, want %d and %d", events, cold, kubeScaleEventCap, kubeColdStartCap) + } + if last.TaskID != fmt.Sprintf("t%d", total-1) || last.Kind != ScaleKindDown { + t.Fatalf("newest event dropped: %+v", last) + } + if lastCold != int64(total-1) || firstCold != int64(total-kubeColdStartCap) { + t.Fatalf("cold-start window = %d..%d", firstCold, lastCold) + } + if len(st.Events) != kubeScaleEventCap || st.ColdStart.Count != kubeColdStartCap || len(st.ColdStart.SamplesMS) != kubeColdStartCap || st.ColdStart.LastMS != int64(total-1) { + t.Fatalf("status history = %d events, cold %+v", len(st.Events), st.ColdStart) + } + // The status copy is detached from the ring. + st.Events[0].TaskID = "mutated" + st.ColdStart.SamplesMS[0] = -1 + b.mu.Lock() + defer b.mu.Unlock() + if b.events[0].TaskID == "mutated" || b.coldStarts[0] == -1 { + t.Fatal("status shares memory with the event ring") + } +} + +func TestKubePercentile(t *testing.T) { + seq := make([]int64, 100) + for i := range seq { + seq[i] = int64(100 - i) // 100..1, unsorted + } + for _, tc := range []struct { + in []int64 + p int + want int64 + }{ + {nil, 50, 0}, + {[]int64{}, 95, 0}, + {[]int64{7}, 50, 7}, + {[]int64{7}, 95, 7}, + {[]int64{40, 10, 30, 20}, 50, 20}, + {[]int64{40, 10, 30, 20}, 95, 40}, + {[]int64{40, 10, 30, 20}, 100, 40}, + {[]int64{40, 10, 30, 20}, 1, 10}, + {seq, 50, 50}, + {seq, 95, 95}, + {seq, 99, 99}, + {[]int64{1, 1, 1, 1000}, 50, 1}, + {[]int64{1, 1, 1, 1000}, 95, 1000}, + } { + if got := kubePercentile(tc.in, tc.p); got != tc.want { + t.Errorf("p%d of %v = %d, want %d", tc.p, tc.in, got, tc.want) + } + } + if seq[0] != 100 { + t.Fatal("kubePercentile sorted its input in place") + } +} + +func TestKubeColdStartDurationsAndStats(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.IdleTimeout = time.Minute }) + // Every proxy DNS probe (the last step of a start) takes a scripted time. + steps := []time.Duration{4 * time.Second, 2 * time.Second, 9 * time.Second} + var i atomic.Int32 + f.execFn = func(_ string, argv []string) (string, string, int) { + if argv[0] == "getent" { + clk.Advance(steps[i.Add(1)-1]) + } + return "", "", 0 + } + ctx := context.Background() + for range steps { + mustExec(t, b, "t1") + clk.Advance(time.Minute) + if n := b.reapIdle(ctx); n != 1 { + t.Fatalf("reaped %d", n) + } + } + res, _ := b.Status(ctx) + cs := res.Scaling.ColdStart + if cs.Count != 3 || cs.LastMS != 9000 || cs.P50MS != 4000 || cs.P95MS != 9000 || !reflect.DeepEqual(cs.SamplesMS, []int64{4000, 2000, 9000}) { + t.Fatalf("cold start stats = %+v", cs) + } + var ups, downs []ScaleEvent + for _, e := range res.Scaling.Events { + if e.Kind == ScaleKindUp { + ups = append(ups, e) + } else { + downs = append(downs, e) + } + } + if len(ups) != 3 || ups[0].Reason != ScaleReasonFirstExec || ups[1].Reason != ScaleReasonResume || ups[1].DurationMS != 2000 { + t.Fatalf("scale-ups = %+v", ups) + } + for _, d := range downs { + if d.DurationMS != 0 || d.Reason != ScaleReasonIdle { + t.Fatalf("scale-down = %+v", d) + } + if _, err := time.Parse(time.RFC3339Nano, d.Time); err != nil { + t.Fatalf("event time %q: %v", d.Time, err) + } + } +} + +func TestKubeScalingConfigFromEnv(t *testing.T) { + t.Setenv("ARTEX_KUBE_DATA_CLAIM", "data") + cfg, err := KubeConfigFromEnv() + if err != nil { + t.Fatal(err) + } + if cfg.IdleTimeout != 0 || cfg.MaxActive != 0 || cfg.QueueTimeout != 0 || cfg.WorkerCPURequest != "" { + t.Fatalf("unset scaling env is not the zero value: %+v", cfg) + } + t.Setenv("ARTEX_KUBE_IDLE_TIMEOUT", "15m") + t.Setenv("ARTEX_KUBE_MAX_ACTIVE", "10") + t.Setenv("ARTEX_KUBE_QUEUE_TIMEOUT", "90s") + t.Setenv("ARTEX_KUBE_WORKER_CPU_REQUEST", "250m") + t.Setenv("ARTEX_KUBE_WORKER_MEMORY_REQUEST", "512Mi") + cfg, err = KubeConfigFromEnv() + if err != nil { + t.Fatal(err) + } + if cfg.IdleTimeout != 15*time.Minute || cfg.MaxActive != 10 || cfg.QueueTimeout != 90*time.Second || cfg.WorkerCPURequest != "250m" || cfg.WorkerMemoryRequest != "512Mi" { + t.Fatalf("cfg = %+v", cfg) + } + // Explicit zero: disabled / unlimited. + t.Run("zero", func(t *testing.T) { + t.Setenv("ARTEX_KUBE_IDLE_TIMEOUT", "0") + t.Setenv("ARTEX_KUBE_MAX_ACTIVE", "0") + cfg, err := KubeConfigFromEnv() + if err != nil || cfg.IdleTimeout != 0 || cfg.MaxActive != 0 { + t.Fatalf("cfg = %+v, %v", cfg, err) + } + }) + for k, bad := range map[string][]string{ + "ARTEX_KUBE_IDLE_TIMEOUT": {"-1s", "soon", "15"}, + "ARTEX_KUBE_MAX_ACTIVE": {"-1", "1.5", "many"}, + "ARTEX_KUBE_QUEUE_TIMEOUT": {"0", "-5s", "x"}, + "ARTEX_KUBE_WORKER_CPU_REQUEST": {"lots", "-1", "100 m"}, + "ARTEX_KUBE_WORKER_MEMORY_REQUEST": {"128MB", "1Gi;rm"}, + } { + for _, v := range bad { + t.Run(k+"="+v, func(t *testing.T) { + t.Setenv(k, v) + if _, err := KubeConfigFromEnv(); err == nil || !strings.Contains(err.Error(), k) { + t.Fatalf("%s=%q: err = %v", k, v, err) + } + }) + } + } +} + +func TestKubeScalingConfigValidationAndDefaults(t *testing.T) { + base := KubeConfig{APIServer: "http://127.0.0.1:1", Namespace: "ns", DataClaim: "c", PodReadyTimeout: 40 * time.Second} + b, err := NewKubernetesBackend(base) + if err != nil { + t.Fatal(err) + } + if b.cfg.QueueTimeout != 40*time.Second || b.cfg.WorkerCPURequest != "100m" || b.cfg.WorkerMemoryRequest != "128Mi" || b.cfg.IdleTimeout != 0 || b.cfg.MaxActive != 0 { + t.Fatalf("defaults = %+v", b.cfg) + } + for name, mod := range map[string]func(*KubeConfig){ + "negative idle": func(c *KubeConfig) { c.IdleTimeout = -time.Second }, + "negative max": func(c *KubeConfig) { c.MaxActive = -1 }, + "negative queue": func(c *KubeConfig) { c.QueueTimeout = -time.Second }, + "cpu request > limit": func(c *KubeConfig) { c.WorkerCPURequest = "3" }, + "mem request > limit": func(c *KubeConfig) { c.WorkerMemoryRequest = "4Gi" }, + "cpu request > limit2": func(c *KubeConfig) { c.WorkerCPURequest = "600m"; c.WorkerCPULimit = "0.5" }, + "zero cpu request": func(c *KubeConfig) { c.WorkerCPURequest = "0" }, + "bad memory request": func(c *KubeConfig) { c.WorkerMemoryRequest = "big" }, + } { + c := base + mod(&c) + if _, err := NewKubernetesBackend(c); err == nil { + t.Errorf("%s accepted", name) + } + } + ok := base + ok.WorkerCPURequest, ok.WorkerCPULimit = "2", "2" + ok.WorkerMemoryRequest, ok.WorkerMemoryLimit = "1024Mi", "1Gi" + ok.QueueTimeout = 5 * time.Second + if b, err := NewKubernetesBackend(ok); err != nil || b.cfg.QueueTimeout != 5*time.Second { + t.Fatalf("request equal to limit rejected: %v", err) + } + for in, want := range map[string]int64{"250m": 250, "2": 2000, "0.5": 500, "1Ki": 1024000, "128Mi": 128 << 20 * 1000, "1G": 1e12, "1.5Gi": 3 << 29 * 1000} { + if got, err := parseKubeQuantity(in); err != nil || got != want { + t.Errorf("parseKubeQuantity(%q) = %d, %v; want %d", in, got, err, want) + } + } + for _, in := range []string{"", "m", "1 Gi", "1e3", "-1", "1MiB", "0x10"} { + if _, err := parseKubeQuantity(in); err == nil { + t.Errorf("parseKubeQuantity(%q) accepted", in) + } + } +} + +func TestKubeWorkerResourceRequests(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.WorkerCPURequest = "750m"; c.WorkerMemoryRequest = "1Gi" }) + mustExec(t, b, "t1") + h := kubeTaskHash("t1") + res := dig(f.obj("pods", "artex-w-"+h), "spec", "containers", 0, "resources") + if dig(res, "requests", "cpu") != "750m" || dig(res, "requests", "memory") != "1Gi" || dig(res, "limits", "cpu") != "2" || dig(res, "limits", "memory") != "2Gi" { + t.Fatalf("worker resources = %v", res) + } + // The proxy keeps its fixed small footprint. + if got := dig(f.obj("pods", "artex-p-"+h), "spec", "containers", 0, "resources", "requests", "cpu"); got != "50m" { + t.Fatalf("proxy cpu request = %v", got) + } +} + +func TestKubeScalingStatusJSON(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { + c.IdleTimeout = 15 * time.Minute + c.MaxActive = 3 + c.QueueTimeout = 45 * time.Second + }) + g := newExecGate(f) + mustExec(t, b, "idle") + mustExec(t, b, "gone") + clk.Advance(15 * time.Minute) + mustExec(t, b, "idle") + // "gone" is past the timeout, "idle" was just used. + b.mu.Lock() + b.scale["idle"].lastActive = clk.Now() + b.mu.Unlock() + if n := b.reapIdle(context.Background()); n != 1 { + t.Fatalf("reaped %d", n) + } + finish := g.run(t, b, "busy", "hold-busy") + defer func() { _ = finish() }() + + rs, err := NewRunnerServer("tok", "v", b) + if err != nil { + t.Fatal(err) + } + hs := httptest.NewServer(rs.Handler()) + defer hs.Close() + code, raw := rawGet(t, hs.URL+"/v1/tasks", "Bearer tok") + if code != 200 { + t.Fatalf("GET /v1/tasks = %d %s", code, raw) + } + var doc struct { + Supported bool `json:"supported"` + Tasks []map[string]any `json:"tasks"` + Scaling map[string]any `json:"scaling"` + } + if err := json.Unmarshal(raw, &doc); err != nil { + t.Fatal(err) + } + wantScaling := map[string]any{ + "supported": true, "idle_timeout_seconds": 900.0, "max_active": 3.0, "queue_timeout_seconds": 45.0, + "active": 2.0, "starting": 0.0, "queued": 0.0, "scaled_to_zero": 1.0, + } + for k, v := range wantScaling { + if doc.Scaling[k] != v { + t.Errorf("scaling.%s = %v, want %v", k, doc.Scaling[k], v) + } + } + cold, _ := doc.Scaling["cold_start"].(map[string]any) + for _, k := range []string{"count", "last_ms", "p50_ms", "p95_ms", "samples_ms"} { + if _, ok := cold[k]; !ok { + t.Errorf("scaling.cold_start.%s missing: %v", k, cold) + } + } + if cold["count"] != 3.0 { + t.Errorf("cold_start.count = %v", cold["count"]) + } + events, _ := doc.Scaling["events"].([]any) + if len(events) != 4 { + t.Fatalf("events = %v", events) + } + first, down := events[0].(map[string]any), events[2].(map[string]any) + if first["kind"] != "scale_up" || first["reason"] != "first_exec" || first["task_id"] != "idle" || first["time"] == "" { + t.Errorf("first event = %v", first) + } + if down["kind"] != "scale_down" || down["reason"] != "idle" || down["task_id"] != "gone" { + t.Errorf("scale-down event = %v", down) + } + if _, has := down["duration_ms"]; has { + t.Errorf("scale-down carries a duration: %v", down) + } + byID := map[string]map[string]any{} + for _, tk := range doc.Tasks { + byID[tk["task_id"].(string)] = tk + } + now := clk.Now().Format(time.RFC3339) + if tk := byID["idle"]; tk["scaling_state"] != "active" || tk["in_flight"] != 0.0 || tk["last_activity"] != now || + tk["idle_expires_at"] != clk.Now().Add(15*time.Minute).Format(time.RFC3339) { + t.Errorf("idle task = %v", tk) + } + if tk := byID["busy"]; tk["scaling_state"] != "active" || tk["in_flight"] != 1.0 || tk["idle_expires_at"] != nil { + t.Errorf("busy task = %v", tk) + } + if tk := byID["gone"]; tk["scaling_state"] != "scaled_to_zero" || tk["in_flight"] != 0.0 || tk["idle_expires_at"] != nil || tk["tracked"] != true || + dig(tk, "worker", "state") != StateMissing || tk["proxy_ip"] == nil { + t.Errorf("scaled-to-zero task = %v", tk) + } + + // The typed client reads the same document. + res, err := NewClient(hs.URL, "tok").Tasks(context.Background()) + if err != nil || res.Scaling == nil || !res.Scaling.Supported || res.Scaling.MaxActive != 3 || len(res.Scaling.Events) != 4 { + t.Fatalf("client Tasks = %+v, %v", res.Scaling, err) + } +} + +func TestScalingStatusBackwardCompatible(t *testing.T) { + // A runner that predates scaling: no scaling object, no per-task fields. + old := `{"backend":"kubernetes","supported":true,"namespace":"artex","tasks":[{"task_id":"t1","tracked":true, + "worker":{"name":"w","state":"Running","ready":true},"proxy":{"name":"p","state":"Running","ready":true},"scope_domains":[],"scope_cidrs":[]}]}` + var res TasksResponse + if err := json.Unmarshal([]byte(old), &res); err != nil { + t.Fatal(err) + } + if res.Scaling != nil || res.Tasks[0].ScalingState != "" || res.Tasks[0].InFlight != 0 || res.Tasks[0].IdleExpiresAt != "" { + t.Fatalf("old payload decoded as %+v", res) + } + // And a response without scaling omits the key instead of sending null. + raw, _ := json.Marshal(TasksResponse{Backend: BackendDocker, Tasks: []TaskStatus{}}) + if strings.Contains(string(raw), "scaling") { + t.Fatalf("nil scaling serialised: %s", raw) + } +} + +func TestDockerStatusReportsScalingUnsupported(t *testing.T) { + b := newFakeDockerStatusBackend(t, &fakeDockerStatus{}) + res, err := b.Status(context.Background()) + if err != nil { + t.Fatal(err) + } + if res.Scaling == nil || res.Scaling.Supported { + t.Fatalf("docker scaling = %+v", res.Scaling) + } + raw, _ := json.Marshal(res) + if !strings.Contains(string(raw), `"scaling":{"supported":false`) || !strings.Contains(string(raw), `"events":[]`) || !strings.Contains(string(raw), `"samples_ms":[]`) { + t.Fatalf("docker scaling JSON = %s", raw) + } +} + +// Many execs over more tasks than slots, with the reaper running against a +// moving clock. No exec may fail, a command never runs without its pods, and the +// cap is never exceeded. Run with -race. +func TestKubeScalingStress(t *testing.T) { + const maxActive, tasks, perTask = 2, 6, 8 + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { + c.MaxActive = maxActive + c.IdleTimeout = time.Second + c.QueueTimeout = time.Minute + }) + var peak atomic.Int32 + f.execFn = func(pod string, argv []string) (string, string, int) { + // Called for probes and commands alike; the store lock is not held here. + n := int32(0) + f.mu.Lock() + for name := range f.objs["pods"] { + if strings.HasPrefix(name, "artex-w-") { + n++ + } + } + _, alive := f.objs["pods"][pod] + f.mu.Unlock() + for { + cur := peak.Load() + if n <= cur || peak.CompareAndSwap(cur, n) { + break + } + } + if !alive { + return "", "pod gone", 97 + } + return "ok", "", 0 + } + stop := make(chan struct{}) + var reaper sync.WaitGroup + reaper.Add(1) + go func() { + defer reaper.Done() + for { + select { + case <-stop: + return + default: + } + clk.Advance(700 * time.Millisecond) + b.reapIdle(context.Background()) + time.Sleep(time.Millisecond) + } + }() + var wg sync.WaitGroup + errs := make(chan error, tasks*perTask) + for i := range tasks { + for j := range perTask { + wg.Add(1) + go func() { + defer wg.Done() + time.Sleep(time.Duration(j) * 3 * time.Millisecond) + res, err := b.Exec(context.Background(), fmt.Sprintf("s%d", i), execReq("true")) + if err != nil { + errs <- fmt.Errorf("s%d/%d: %w", i, j, err) + } else if res.ExitCode != 0 { + errs <- fmt.Errorf("s%d/%d: exit %d %s", i, j, res.ExitCode, res.Stderr) + } + }() + } + } + wg.Wait() + close(stop) + reaper.Wait() + close(errs) + for err := range errs { + t.Error(err) + } + if p := peak.Load(); p > maxActive { + t.Fatalf("%d worker pods existed at once with max active %d", p, maxActive) + } + a, w, _ := scaleCounts(b) + if a > maxActive || w != 0 { + t.Fatalf("active=%d waiters=%d at the end", a, w) + } + b.mu.Lock() + for id, st := range b.scale { + if st.inflight != 0 || st.queued || st.starting { + t.Errorf("task %s left inflight=%d queued=%v starting=%v", id, st.inflight, st.queued, st.starting) + } + } + b.mu.Unlock() + // Bookkeeping matches the cluster: pods exist exactly for the active tasks. + if got := f.count("pods"); got != 2*a { + t.Fatalf("%d pods for %d active task(s)", got, a) + } +} + +// TestKubeCapacityFailureKeepsPendingPodsAndSlot: a start that fails because its +// pods are still unschedulable at the ready timeout (a node is being added) +// keeps the pods and the capacity slot, unlike other failed starts. The retry +// waits on the same pods, the reaper removes them with their Service and +// policies when no retry comes, and a queued task can evict them like any idle +// task. +func TestKubeCapacityFailureKeepsPendingPodsAndSlot(t *testing.T) { + ctx := context.Background() + pending := func(f *fakeKubeAPI, id string) { + f.podMode["artex-w-"+kubeTaskHash(id)] = "unschedulable" + f.podMode["artex-p-"+kubeTaskHash(id)] = "unschedulable" + } + gone := func(t *testing.T, f *fakeKubeAPI, id string) { + t.Helper() + h := kubeTaskHash(id) + if w, p := hasPods(f, id); w || p { + t.Fatalf("%s: pods left", id) + } + if f.obj("services", "artex-p-"+h) != nil || f.obj("networkpolicies", "artex-w-"+h) != nil || f.obj("networkpolicies", "artex-p-"+h) != nil { + t.Fatalf("%s: Service or network policies left", id) + } + } + + t.Run("retry reuses the pods and the slot", func(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.PodReadyTimeout = 300 * time.Millisecond }) + pending(f, "a") + if _, err := b.Exec(ctx, "a", execReq("true")); !errors.Is(err, ErrCapacity) { + t.Fatalf("first exec: %v", err) + } + if w, p := hasPods(f, "a"); !w || !p { + t.Fatal("pending pods were deleted after a capacity failure") + } + if a, _, _ := scaleCounts(b); a != 1 { + t.Fatalf("active = %d, want the pending pods to hold the slot", a) + } + res, _ := b.Status(ctx) + if res.Scaling.Totals.ScaleUpFailures != 1 { + t.Fatalf("totals %+v", res.Scaling.Totals) + } + h := kubeTaskHash("a") + f.setPodPhase("artex-w-"+h, "Running", true) + f.setPodPhase("artex-p-"+h, "Running", true) + mark := len(f.opsSnapshot()) + if _, err := b.Exec(ctx, "a", execReq("true")); err != nil { + t.Fatalf("exec after the node arrived: %v", err) + } + for _, op := range f.opsSnapshot()[mark:] { + if strings.Contains(op, "pods/") { + t.Fatalf("retry replaced a pod: %s", op) + } + } + if a, w, _ := scaleCounts(b); a != 1 || w != 0 { + t.Fatalf("active=%d waiters=%d", a, w) + } + }) + + t.Run("reaper removes an abandoned first start", func(t *testing.T) { + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { + c.MaxActive = 1 + c.IdleTimeout = time.Minute + c.PodReadyTimeout = 300 * time.Millisecond + }) + pending(f, "a") + if _, err := b.Exec(ctx, "a", execReq("true")); !errors.Is(err, ErrCapacity) { + t.Fatalf("first exec: %v", err) + } + clk.Advance(time.Minute) + if n := b.reapIdle(ctx); n != 1 { + t.Fatalf("reaped %d", n) + } + gone(t, f, "a") + if a, _, n := scaleCounts(b); a != 0 || n != 0 { + t.Fatalf("after reaping: active=%d states=%d", a, n) + } + }) + + t.Run("queued task evicts the pending pods", func(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { + c.MaxActive = 1 + c.QueueTimeout = time.Minute + c.PodReadyTimeout = 300 * time.Millisecond + }) + pending(f, "a") + if _, err := b.Exec(ctx, "a", execReq("true")); !errors.Is(err, ErrCapacity) { + t.Fatalf("first exec: %v", err) + } + if _, err := b.Exec(ctx, "b", execReq("true")); err != nil { + t.Fatalf("exec b: %v", err) + } + gone(t, f, "a") + if a, _, n := scaleCounts(b); a != 1 || n != 1 { + t.Fatalf("active=%d states=%d", a, n) + } + }) + + t.Run("delete frees the slot after the pods are gone", func(t *testing.T) { + f, _, b, _ := newScaleBackend(t, func(c *KubeConfig) { c.MaxActive = 1; c.PodReadyTimeout = 300 * time.Millisecond }) + pending(f, "a") + if _, err := b.Exec(ctx, "a", execReq("true")); !errors.Is(err, ErrCapacity) { + t.Fatalf("first exec: %v", err) + } + if err := b.Delete(ctx, "a"); err != nil { + t.Fatalf("Delete: %v", err) + } + gone(t, f, "a") + if a, _, n := scaleCounts(b); a != 0 || n != 0 { + t.Fatalf("after Delete: active=%d states=%d", a, n) + } + }) +} diff --git a/sandbox/kube_scope_status_test.go b/sandbox/kube_scope_status_test.go new file mode 100644 index 000000000..01b31917f --- /dev/null +++ b/sandbox/kube_scope_status_test.go @@ -0,0 +1,145 @@ +package sandbox + +import ( + "context" + "net/http/httptest" + "reflect" + "testing" + "time" +) + +// A task scaled to zero has no proxy pod to read its scope from: status reports +// the scope last applied to its proxy NetworkPolicy instead, marked as such, in +// the same runner and in a new one that recovers the task. Health and the +// summary count it as scaled to zero, not as an unhealthy task. +func TestKubeStatusScaledToZeroKeepsLastAppliedScope(t *testing.T) { + f, srv, b, clk := newScaleBackend(t, func(c *KubeConfig) { c.IdleTimeout = 10 * time.Minute }) + ctx := context.Background() + req := execReq("true") + req.ScopeDomains = []string{"app.example.net", "api.example.com"} + req.ScopeCIDRs = []string{"203.0.113.0/24"} + if _, err := b.Exec(ctx, "scoped", req); err != nil { + t.Fatal(err) + } + mustExec(t, b, "open") + h := kubeTaskHash("scoped") + f.mu.Lock() + ann := f.objs["networkpolicies"]["artex-p-"+h]["metadata"].(map[string]any)["annotations"].(map[string]any) + gotD, gotC := ann[AnnotationScopeDomains], ann[AnnotationScopeCIDRs] + f.mu.Unlock() + if gotD != `["app.example.net","api.example.com"]` || gotC != `["203.0.113.0/24"]` { + t.Fatalf("proxy policy annotations = %v %v", gotD, gotC) + } + + check := func(t *testing.T, res TasksResponse, wantSource string) { + t.Helper() + ts := findTask(t, res, "scoped") + if !reflect.DeepEqual(ts.ScopeDomains, req.ScopeDomains) || !reflect.DeepEqual(ts.ScopeCIDRs, req.ScopeCIDRs) || ts.ScopeSource != wantSource || !ts.ScopeKnown { + t.Fatalf("scope = %v %v from %q, want %v %v from %q", ts.ScopeDomains, ts.ScopeCIDRs, ts.ScopeSource, req.ScopeDomains, req.ScopeCIDRs, wantSource) + } + } + res, _ := b.Status(ctx) + check(t, res, ScopeSourceLive) + + clk.Advance(10 * time.Minute) + mustExec(t, b, "open") + if n := b.reapIdle(ctx); n != 1 { + t.Fatalf("reaped %d", n) + } + if w, p := hasPods(f, "scoped"); w || p { + t.Fatal("scaled-to-zero task still has pods") + } + res, _ = b.Status(ctx) + check(t, res, ScopeSourceLastApplied) + if ts := findTask(t, res, "scoped"); TaskHealth(ts) != HealthScaledToZero { + t.Fatalf("health of a scaled-to-zero task = %q", TaskHealth(ts)) + } + if ts := findTask(t, res, "open"); TaskHealth(ts) != HealthHealthy || ts.ScopeSource != ScopeSourceLive || len(ts.ScopeDomains) != 0 { + t.Fatalf("open task = %+v", ts) + } + wantSum := TaskSummary{Total: 2, Expected: 1, Healthy: 1, ScaledToZero: 1} + if got := SummarizeTasks(res.Tasks); got != wantSum { + t.Fatalf("summary = %+v, want %+v", got, wantSum) + } + + // Over HTTP the runner fills health and the summary. + rs, _ := NewRunnerServer("tok", "v", b) + hs := httptest.NewServer(rs.Handler()) + defer hs.Close() + wire, err := NewClient(hs.URL, "tok").Tasks(ctx) + if err != nil { + t.Fatal(err) + } + if ts := findTask(t, wire, "scoped"); ts.Health != HealthScaledToZero || ts.ScopeSource != ScopeSourceLastApplied { + t.Fatalf("wire task = %+v", ts) + } + if wire.Summary != wantSum { + t.Fatalf("wire summary = %+v", wire.Summary) + } + + // A new runner process recovers the scope from the policy annotations. + fresh := newTestKubeBackendCfg(t, f, srv, func(c *KubeConfig) { c.IdleTimeout = 10 * time.Minute }) + fresh.now = clk.Now + if _, err := fresh.Recover(ctx); err != nil { + t.Fatal(err) + } + res, _ = fresh.Status(ctx) + check(t, res, ScopeSourceLastApplied) + + // A policy from an older runner (no annotations): the scope is unknown, which + // is reported as such rather than as "all egress denied". + f.mu.Lock() + delete(ann, AnnotationScopeDomains) + f.mu.Unlock() + older := newTestKubeBackendCfg(t, f, srv, nil) + if _, err := older.Recover(ctx); err != nil { + t.Fatal(err) + } + res, _ = older.Status(ctx) + if ts := findTask(t, res, "scoped"); ts.ScopeSource != "" || ts.ScopeKnown || len(ts.ScopeDomains) != 0 { + t.Fatalf("scope without annotations = %v from %q", ts.ScopeDomains, ts.ScopeSource) + } + + // Resuming applies, and reports, the scope of the new command. + req2 := execReq("true") + req2.ScopeDomains = []string{"example.org"} + if _, err := fresh.Exec(ctx, "scoped", req2); err != nil { + t.Fatal(err) + } + res, _ = fresh.Status(ctx) + if ts := findTask(t, res, "scoped"); !reflect.DeepEqual(ts.ScopeDomains, []string{"example.org"}) || ts.ScopeSource != ScopeSourceLive { + t.Fatalf("after resume = %v from %q", ts.ScopeDomains, ts.ScopeSource) + } +} + +func TestTaskHealthAndSummary(t *testing.T) { + ready := ComponentStatus{State: "Running", Ready: true} + cases := []struct { + ts TaskStatus + want string + }{ + {TaskStatus{Worker: ready, Proxy: ready}, HealthHealthy}, + {TaskStatus{Worker: ready, Proxy: ready, ScalingState: ScaleStateActive}, HealthHealthy}, + {TaskStatus{Worker: ready, Proxy: ComponentStatus{State: StateMissing}, ScalingState: ScaleStateActive}, HealthDegraded}, + {TaskStatus{Worker: ComponentStatus{State: StateMissing}, Proxy: ComponentStatus{State: StateMissing}}, HealthDegraded}, + {TaskStatus{ScalingState: ScaleStateZero}, HealthScaledToZero}, + {TaskStatus{ScalingState: ScaleStateQueued}, HealthQueued}, + {TaskStatus{ScalingState: ScaleStateStarting}, HealthStarting}, + } + var tasks []TaskStatus + for _, c := range cases { + if got := TaskHealth(c.ts); got != c.want { + t.Errorf("TaskHealth(%+v) = %q, want %q", c.ts, got, c.want) + } + tasks = append(tasks, c.ts) + } + // A health set by the runner wins over the local classification. + tasks = append(tasks, TaskStatus{Health: HealthScaledToZero, Worker: ready, Proxy: ready}) + want := TaskSummary{Total: 8, Expected: 4, Healthy: 2, Degraded: 2, Starting: 1, Queued: 1, ScaledToZero: 2} + if got := SummarizeTasks(tasks); got != want { + t.Fatalf("summary = %+v, want %+v", got, want) + } + if got := SummarizeTasks(nil); got != (TaskSummary{}) { + t.Fatalf("empty summary = %+v", got) + } +} diff --git a/sandbox/kube_state.go b/sandbox/kube_state.go new file mode 100644 index 000000000..794aba6d1 --- /dev/null +++ b/sandbox/kube_state.go @@ -0,0 +1,216 @@ +package sandbox + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "log" + "os" + "path/filepath" + "time" +) + +// The Kubernetes backend keeps its scale history, totals and cold-start samples +// in KubeConfig.StateDir/scaling.json so a runner restart (upgrade, eviction, +// node drain) does not wipe them. Only this bookkeeping is persisted: which +// tasks exist and whether they have pods is always rebuilt from the cluster by +// Recover. The file is written atomically (temp file, fsync, rename), at most +// once per kubeStateDebounce, and is bounded by the in-memory caps. +const ( + kubeStateFileName = "scaling.json" + kubeStateVersion = 1 + // kubeStateMaxBytes is far above what the caps can produce; a larger file + // is treated as corrupt rather than read into memory. + kubeStateMaxBytes = 1 << 20 +) + +// kubeStateDebounce delays a save after an event so a burst costs one write. +// A variable so tests can shorten it. +var kubeStateDebounce = 2 * time.Second + +// kubeStateFile is the on-disk schema. Version is bumped on any incompatible +// change; a file with another version is ignored (logged), never misread. +type kubeStateFile struct { + Version int `json:"version"` + SavedAt string `json:"saved_at"` + Totals ScaleTotals `json:"totals"` + Events []ScaleEvent `json:"events"` + ColdStartsMS []int64 `json:"cold_starts_ms"` +} + +func (b *KubernetesBackend) statePath() string { + return filepath.Join(b.cfg.StateDir, kubeStateFileName) +} + +// loadState reads the state file at construction. A missing file starts empty; +// an unreadable, oversized, corrupt or other-version file is logged and the +// backend starts empty (the next save replaces it). +func (b *KubernetesBackend) loadState() { + if b.cfg.StateDir == "" { + b.totals.Since = b.now().UTC().Format(time.RFC3339) + return + } + st, err := readKubeState(b.statePath()) + if err != nil { + if !errors.Is(err, fs.ErrNotExist) { + log.Printf("[runner] scaling state %s ignored, starting with empty history: %v", b.statePath(), err) + } + b.totals = ScaleTotals{Since: b.now().UTC().Format(time.RFC3339)} + return + } + b.mu.Lock() + defer b.mu.Unlock() + b.events, b.coldStarts, b.totals = st.Events, st.ColdStartsMS, st.Totals + if b.totals.Since == "" { + b.totals.Since = b.now().UTC().Format(time.RFC3339) + } + log.Printf("[runner] scaling state loaded from %s: %d events, %d cold starts", b.statePath(), len(b.events), len(b.coldStarts)) +} + +// readKubeState reads and sanitises a state file: entries that could not have +// been written by the runner are dropped and the history is cut to the caps. +func readKubeState(path string) (*kubeStateFile, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + raw, err := io.ReadAll(io.LimitReader(f, kubeStateMaxBytes+1)) + if err != nil { + return nil, err + } + if len(raw) > kubeStateMaxBytes { + return nil, fmt.Errorf("larger than %d bytes", kubeStateMaxBytes) + } + var st kubeStateFile + if err := json.Unmarshal(raw, &st); err != nil { + return nil, fmt.Errorf("corrupt: %w", err) + } + if st.Version != kubeStateVersion { + return nil, fmt.Errorf("schema version %d, this runner reads %d", st.Version, kubeStateVersion) + } + events := make([]ScaleEvent, 0, len(st.Events)) + for _, ev := range st.Events { + if _, err := time.Parse(time.RFC3339Nano, ev.Time); err != nil || ValidateTaskID(ev.TaskID) != nil { + continue + } + switch ev.Kind { + case ScaleKindUp, ScaleKindDown, ScaleKindUpFailed: + default: + continue + } + if len(ev.Reason) > 32 || ev.DurationMS < 0 || ev.QueueMS < 0 { + continue + } + if len(ev.Error) > kubeEventErrMax+8 { + ev.Error = ev.Error[:kubeEventErrMax] + } + events = append(events, ev) + } + if len(events) > kubeScaleEventCap { + events = events[len(events)-kubeScaleEventCap:] + } + cold := make([]int64, 0, len(st.ColdStartsMS)) + for _, v := range st.ColdStartsMS { + if v >= 0 { + cold = append(cold, v) + } + } + if len(cold) > kubeColdStartCap { + cold = cold[len(cold)-kubeColdStartCap:] + } + st.Events, st.ColdStartsMS = events, cold + if st.Totals.ScaleUps < 0 || st.Totals.ScaleDowns < 0 || st.Totals.ScaleUpFailures < 0 { + st.Totals = ScaleTotals{} + } + if _, err := time.Parse(time.RFC3339, st.Totals.Since); err != nil { + st.Totals.Since = "" + } + return &st, nil +} + +// markStateDirtyLocked schedules a debounced save. The caller holds b.mu. +func (b *KubernetesBackend) markStateDirtyLocked() { + if b.cfg.StateDir == "" || b.saveTimer != nil { + return + } + b.saveTimer = time.AfterFunc(kubeStateDebounce, func() { + if err := b.FlushState(); err != nil { + log.Printf("[runner] save scaling state: %v", err) + } + }) +} + +// FlushState writes the state file now (the runner calls it on shutdown). It +// is a no-op without a state directory. +func (b *KubernetesBackend) FlushState() error { + if b.cfg.StateDir == "" { + return nil + } + // saveMu before mu: the snapshot written last is always the newest. + b.saveMu.Lock() + defer b.saveMu.Unlock() + b.mu.Lock() + if b.saveTimer != nil { + b.saveTimer.Stop() + b.saveTimer = nil + } + st := kubeStateFile{ + Version: kubeStateVersion, + SavedAt: b.now().UTC().Format(time.RFC3339Nano), + Totals: b.totals, + Events: append([]ScaleEvent{}, b.events...), + ColdStartsMS: append([]int64{}, b.coldStarts...), + } + b.mu.Unlock() + b.hook("state-snapshot", "") + raw, err := json.Marshal(st) + if err != nil { + return err + } + return writeFileAtomic(b.statePath(), raw) +} + +// writeFileAtomic replaces path with data so a reader (or a crash) sees either +// the old or the new content, never a partial file. +func writeFileAtomic(path string, data []byte) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + tmp, err := os.CreateTemp(dir, "."+filepath.Base(path)+".*.tmp") + if err != nil { + return err + } + name := tmp.Name() + ok := false + defer func() { + if !ok { + _ = tmp.Close() + _ = os.Remove(name) + } + }() + if err := tmp.Chmod(0o600); err != nil { + return err + } + if _, err := tmp.Write(data); err != nil { + return err + } + if err := tmp.Sync(); err != nil { + return err + } + if err := tmp.Close(); err != nil { + return err + } + if err := os.Rename(name, path); err != nil { + return err + } + ok = true + if d, err := os.Open(dir); err == nil { + _ = d.Sync() + _ = d.Close() + } + return nil +} diff --git a/sandbox/kube_state_test.go b/sandbox/kube_state_test.go new file mode 100644 index 000000000..85dddc852 --- /dev/null +++ b/sandbox/kube_state_test.go @@ -0,0 +1,267 @@ +package sandbox + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "reflect" + "strings" + "sync/atomic" + "testing" + "time" +) + +func newStateBackend(t *testing.T, dir string, mod func(*KubeConfig)) (*fakeKubeAPI, *KubernetesBackend, *fakeClock) { + t.Helper() + f, _, b, clk := newScaleBackend(t, func(c *KubeConfig) { + c.StateDir = dir + if mod != nil { + mod(c) + } + }) + return f, b, clk +} + +// TestKubeStateSurvivesRestart: history, totals and cold-start samples written +// by one backend are what a new backend (a restarted runner) reports. +func TestKubeStateSurvivesRestart(t *testing.T) { + dir := filepath.Join(t.TempDir(), "runner-state") + f, b, clk := newStateBackend(t, dir, func(c *KubeConfig) { c.IdleTimeout = time.Minute }) + ctx := context.Background() + mustExec(t, b, "a") + mustExec(t, b, "b") + clk.Advance(time.Minute) + if n := b.reapIdle(ctx); n != 2 { + t.Fatalf("reaped %d", n) + } + mustExec(t, b, "a") + f.podMode["artex-w-"+kubeTaskHash("bad")] = "pull-error" + if _, err := b.Exec(ctx, "bad", execReq("true")); err == nil { + t.Fatal("exec succeeded with an unpullable image") + } + if err := b.FlushState(); err != nil { + t.Fatal(err) + } + before, _ := b.Status(ctx) + if !before.Scaling.Persisted || before.Scaling.Totals.ScaleUps != 3 || before.Scaling.Totals.ScaleDowns != 2 || before.Scaling.Totals.ScaleUpFailures != 1 { + t.Fatalf("before restart: %+v", before.Scaling.Totals) + } + if fi, err := os.Stat(filepath.Join(dir, kubeStateFileName)); err != nil || fi.Mode().Perm() != 0o600 { + t.Fatalf("state file: %v %v", fi, err) + } + // No temp files are left next to it. + ents, _ := os.ReadDir(dir) + if len(ents) != 1 { + t.Fatalf("state dir has %d entries", len(ents)) + } + + _, b2, _ := newStateBackend(t, dir, nil) + after, _ := b2.Status(ctx) + if !reflect.DeepEqual(after.Scaling.Events, before.Scaling.Events) { + t.Fatalf("events after restart\n got %+v\nwant %+v", after.Scaling.Events, before.Scaling.Events) + } + if !reflect.DeepEqual(after.Scaling.ColdStart, before.Scaling.ColdStart) { + t.Fatalf("cold start after restart %+v, want %+v", after.Scaling.ColdStart, before.Scaling.ColdStart) + } + if after.Scaling.Totals != before.Scaling.Totals { + t.Fatalf("totals after restart %+v, want %+v", after.Scaling.Totals, before.Scaling.Totals) + } + // Live state is not persisted: it comes from the cluster through Recover. + if after.Scaling.Active != 0 || len(after.Tasks) != 0 { + t.Fatalf("restored live state: active=%d tasks=%d", after.Scaling.Active, len(after.Tasks)) + } + // New events append to the restored history. + mustExec(t, b2, "c") + if got := scaleEvents(b2); got[len(got)-1] != "scale_up/first_exec/c" || len(got) != len(before.Scaling.Events)+1 { + t.Fatalf("events = %v", got) + } +} + +func TestKubeStateDebouncedSave(t *testing.T) { + old := kubeStateDebounce + kubeStateDebounce = 50 * time.Millisecond + t.Cleanup(func() { kubeStateDebounce = old }) + dir := t.TempDir() + _, b, _ := newStateBackend(t, dir, nil) + path := filepath.Join(dir, kubeStateFileName) + for _, id := range []string{"a", "b", "c"} { + mustExec(t, b, id) + } + waitFor(t, "debounced save", func() bool { + st, err := readKubeState(path) + return err == nil && len(st.Events) == 3 + }) + b.mu.Lock() + pending := b.saveTimer != nil + b.mu.Unlock() + if pending { + t.Fatal("a save is still pending after the burst was written") + } +} + +func TestKubeStateWithoutDirWritesNothing(t *testing.T) { + _, _, b, _ := newScaleBackend(t, nil) + mustExec(t, b, "a") + if err := b.FlushState(); err != nil { + t.Fatal(err) + } + b.mu.Lock() + defer b.mu.Unlock() + if b.saveTimer != nil { + t.Fatal("save scheduled without a state directory") + } + if res := b.scalingStatusLocked(); res.Persisted || res.Totals.Since == "" { + t.Fatalf("persisted=%v since=%q", res.Persisted, res.Totals.Since) + } +} + +func TestKubeStateCorruptOrMissingStartsEmpty(t *testing.T) { + cases := map[string]string{ + "garbage": "{not json", + "wrong version": `{"version":99,"events":[{"time":"2026-12-01T10:00:00Z","task_id":"a","kind":"scale_up","reason":"first_exec"}]}`, + "empty": "", + "oversized": `{"version":1,"x":"` + strings.Repeat("a", kubeStateMaxBytes) + `"}`, + } + for name, content := range cases { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, kubeStateFileName), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + _, b, _ := newStateBackend(t, dir, nil) + res, _ := b.Status(context.Background()) + if len(res.Scaling.Events) != 0 || res.Scaling.ColdStart.Count != 0 || res.Scaling.Totals.ScaleUps != 0 { + t.Fatalf("state from a bad file: %+v", res.Scaling) + } + // The next save replaces the bad file. + mustExec(t, b, "a") + if err := b.FlushState(); err != nil { + t.Fatal(err) + } + if st, err := readKubeState(filepath.Join(dir, kubeStateFileName)); err != nil || len(st.Events) != 1 { + t.Fatalf("after save: %+v %v", st, err) + } + }) + } + t.Run("missing dir", func(t *testing.T) { + dir := filepath.Join(t.TempDir(), "not", "yet") + _, b, _ := newStateBackend(t, dir, nil) + mustExec(t, b, "a") + if err := b.FlushState(); err != nil { + t.Fatalf("save into a missing dir: %v", err) + } + }) +} + +// TestKubeStateLoadIsBoundedAndSanitised: a hand-edited or foreign file cannot +// grow the history past the caps or inject entries the runner never writes. +func TestKubeStateLoadIsBoundedAndSanitised(t *testing.T) { + dir := t.TempDir() + st := kubeStateFile{Version: kubeStateVersion, Totals: ScaleTotals{ScaleUps: 5, Since: "2026-11-01T00:00:00Z"}} + for i := range kubeScaleEventCap + 50 { + st.Events = append(st.Events, ScaleEvent{Time: "2026-12-01T10:00:00Z", TaskID: "t" + string(rune('a'+i%26)), Kind: ScaleKindUp, Reason: ScaleReasonFirstExec, DurationMS: int64(i)}) + } + st.Events = append(st.Events, + ScaleEvent{Time: "yesterday", TaskID: "a", Kind: ScaleKindUp, Reason: "x"}, + ScaleEvent{Time: "2026-12-01T10:00:00Z", TaskID: "../etc", Kind: ScaleKindUp, Reason: "x"}, + ScaleEvent{Time: "2026-12-01T10:00:00Z", TaskID: "a", Kind: "rm -rf", Reason: "x"}, + ScaleEvent{Time: "2026-12-01T10:00:00Z", TaskID: "a", Kind: ScaleKindUp, Reason: "x", DurationMS: -1}, + ) + for i := range kubeColdStartCap + 7 { + st.ColdStartsMS = append(st.ColdStartsMS, int64(i)) + } + st.ColdStartsMS = append(st.ColdStartsMS, -5) + raw, _ := json.Marshal(st) + if err := os.WriteFile(filepath.Join(dir, kubeStateFileName), raw, 0o600); err != nil { + t.Fatal(err) + } + _, b, _ := newStateBackend(t, dir, nil) + res, _ := b.Status(context.Background()) + if n := len(res.Scaling.Events); n != kubeScaleEventCap { + t.Fatalf("events = %d", n) + } + if last := res.Scaling.Events[len(res.Scaling.Events)-1]; last.DurationMS != kubeScaleEventCap+49 { + t.Fatalf("kept the wrong end of the history: %+v", last) + } + if res.Scaling.ColdStart.Count != kubeColdStartCap || res.Scaling.ColdStart.LastMS != kubeColdStartCap+6 { + t.Fatalf("cold start = %+v", res.Scaling.ColdStart) + } + if res.Scaling.Totals.ScaleUps != 5 || res.Scaling.Totals.Since != "2026-11-01T00:00:00Z" { + t.Fatalf("totals = %+v", res.Scaling.Totals) + } +} + +// TestKubeStateConcurrentSaves races debounced saves, explicit flushes and +// scale events: the file on disk is always complete and the last flush wins. +func TestKubeStateConcurrentSaves(t *testing.T) { + old := kubeStateDebounce + kubeStateDebounce = time.Millisecond + t.Cleanup(func() { kubeStateDebounce = old }) + dir := t.TempDir() + _, b, _ := newStateBackend(t, dir, nil) + path := filepath.Join(dir, kubeStateFileName) + done := make(chan struct{}) + go func() { + defer close(done) + for i := range 40 { + mustExec(t, b, "t"+string(rune('a'+i%5))) + _ = b.FlushState() + } + }() + for { + select { + case <-done: + if err := b.FlushState(); err != nil { + t.Fatal(err) + } + st, err := readKubeState(path) + if err != nil || len(st.Events) != 5 || st.Totals.ScaleUps != 5 { + t.Fatalf("final state %+v %v", st, err) + } + return + default: + if _, err := os.Stat(path); err == nil { + if _, err := readKubeState(path); err != nil { + t.Fatalf("partial state file: %v", err) + } + } + } + } +} + +// TestKubeStateNewestSnapshotWins: a flush that took its snapshot first must +// not overwrite a newer one written by a later flush (writes are serialised +// from snapshot to rename). +func TestKubeStateNewestSnapshotWins(t *testing.T) { + dir := t.TempDir() + _, b, _ := newStateBackend(t, dir, nil) + mustExec(t, b, "a") + release := make(chan struct{}) + var calls atomic.Int32 + b.testHook = func(point, _ string) { + // Only the first flush parks; the second must not block here. + if point == "state-snapshot" && calls.Add(1) == 1 { + <-release + } + } + old := make(chan error, 1) + go func() { old <- b.FlushState() }() + time.Sleep(50 * time.Millisecond) // the first flush is parked after its snapshot + mustExec(t, b, "b") + newer := make(chan error, 1) + go func() { newer <- b.FlushState() }() + time.Sleep(100 * time.Millisecond) + close(release) + if err := <-old; err != nil { + t.Fatal(err) + } + if err := <-newer; err != nil { + t.Fatal(err) + } + b.testHook = nil + st, err := readKubeState(filepath.Join(dir, kubeStateFileName)) + if err != nil || len(st.Events) != 2 { + t.Fatalf("state on disk has %d events (want the newest snapshot, 2): %v", len(st.Events), err) + } +} diff --git a/sandbox/kube_test.go b/sandbox/kube_test.go index 20af60f15..f5850a7a8 100644 --- a/sandbox/kube_test.go +++ b/sandbox/kube_test.go @@ -42,6 +42,13 @@ type fakeKubeAPI struct { execFn func(pod string, argv []string) (stdout, stderr string, exit int) // failPing makes pod list return 403. failPing atomic.Bool + // hook, when set, sees every non-exec request before it is served (without + // the store lock held, so it may block) and fails it with the returned HTTP + // status when that is not zero. + hook atomic.Pointer[func(method, kind, name string) int] + // podTerminate, when set, makes a pod DELETE behave like a real kubelet: + // the pod gets a deletionTimestamp and is only removed after this long. + podTerminate atomic.Int64 } func newFakeKubeAPI(t *testing.T) (*fakeKubeAPI, *httptest.Server) { @@ -79,6 +86,12 @@ func (f *fakeKubeAPI) serve(w http.ResponseWriter, r *http.Request) { f.serveExec(w, r, name) return } + if h := f.hook.Load(); h != nil { + if code := (*h)(r.Method, kind, name); code != 0 { + http.Error(w, `{"reason":"Injected"}`, code) + return + } + } f.mu.Lock() defer f.mu.Unlock() store := f.objs[kind] @@ -137,10 +150,27 @@ func (f *fakeKubeAPI) serve(w http.ResponseWriter, r *http.Request) { f.ops = append(f.ops, "update "+kind+"/"+name) writeJSON(w, o) case r.Method == http.MethodDelete: - if _, ok := store[name]; !ok { + o, ok := store[name] + if !ok { http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound) return } + if d := time.Duration(f.podTerminate.Load()); kind == "pods" && d > 0 { + meta := o["metadata"].(map[string]any) + if _, terminating := meta["deletionTimestamp"]; !terminating { + meta["deletionTimestamp"] = time.Now().UTC().Format(time.RFC3339) + time.AfterFunc(d, func() { + f.mu.Lock() + defer f.mu.Unlock() + if f.objs["pods"][name] != nil && f.objs["pods"][name]["metadata"].(map[string]any)["deletionTimestamp"] != nil { + delete(f.objs["pods"], name) + } + }) + f.ops = append(f.ops, "delete "+kind+"/"+name) + } + writeJSON(w, map[string]any{"status": "Success"}) + return + } delete(store, name) f.ops = append(f.ops, "delete "+kind+"/"+name) writeJSON(w, map[string]any{"status": "Success"}) @@ -163,6 +193,11 @@ func (f *fakeKubeAPI) finalize(kind, name string, o map[string]any) { }}} case "pending": o["status"] = map[string]any{"phase": "Pending"} + case "unschedulable": + o["status"] = map[string]any{"phase": "Pending", "conditions": []any{map[string]any{ + "type": "PodScheduled", "status": "False", "reason": "Unschedulable", + "message": "0/2 nodes are available: 1 Insufficient cpu.", + }}} default: o["status"] = map[string]any{"phase": "Running", "containerStatuses": []any{map[string]any{"ready": true, "state": map[string]any{}}}} } @@ -288,13 +323,19 @@ func (f *fakeKubeAPI) lastExec() []string { } func newTestKubeBackend(t *testing.T, f *fakeKubeAPI, srv *httptest.Server) *KubernetesBackend { + t.Helper() + return newTestKubeBackendCfg(t, f, srv, nil) +} + +// newTestKubeBackendCfg lets a test adjust the config before the backend is built. +func newTestKubeBackendCfg(t *testing.T, f *fakeKubeAPI, srv *httptest.Server, mod func(*KubeConfig)) *KubernetesBackend { t.Helper() dir := t.TempDir() tok := filepath.Join(dir, "token") if err := os.WriteFile(tok, []byte(f.token+"\n"), 0o600); err != nil { t.Fatal(err) } - b, err := NewKubernetesBackend(KubeConfig{ + cfg := KubeConfig{ APIServer: srv.URL, TokenPath: tok, Namespace: f.ns, @@ -304,7 +345,11 @@ func newTestKubeBackend(t *testing.T, f *fakeKubeAPI, srv *httptest.Server) *Kub WorkspaceRoot: filepath.Join(dir, "tasks"), AuditRoot: filepath.Join(dir, "audit"), PodReadyTimeout: 3 * time.Second, - }) + } + if mod != nil { + mod(&cfg) + } + b, err := NewKubernetesBackend(cfg) if err != nil { t.Fatalf("NewKubernetesBackend: %v", err) } @@ -356,11 +401,12 @@ func TestKubeConfigFromEnv(t *testing.T) { t.Setenv("ARTEX_KUBE_POD_READY_TIMEOUT", "45s") t.Setenv("ARTEX_KUBE_IMAGE_PULL_POLICY", "Never") t.Setenv("ARTEX_KUBE_RUNTIME_CLASS", "gvisor") + t.Setenv("ARTEX_KUBE_STATE_DIR", " /var/lib/artex-runner ") cfg, err := KubeConfigFromEnv() if err != nil { t.Fatal(err) } - if cfg.DataClaim != "data" || cfg.Namespace != "ns1" || cfg.ImagePullPolicy != "Never" || cfg.RuntimeClassName != "gvisor" { + if cfg.DataClaim != "data" || cfg.Namespace != "ns1" || cfg.ImagePullPolicy != "Never" || cfg.RuntimeClassName != "gvisor" || cfg.StateDir != "/var/lib/artex-runner" { t.Fatalf("cfg = %+v", cfg) } if cfg.DNSPodLabels["tier"] != "dns" || cfg.DNSPodLabels["k8s-app"] != "kube-dns" { @@ -823,6 +869,102 @@ func TestKubePodReadyTimeout(t *testing.T) { } } +// A task pod that no node has room for (an autoscaler scale-up still under way) +// is a capacity condition: the exec fails with ErrCapacity, which the runner +// answers with 429 and the panel does not treat as the runner being down. +func TestKubePodUnschedulableAtTimeoutIsCapacity(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + b.cfg.PodReadyTimeout = 700 * time.Millisecond + f.podMode["artex-w-"+kubeTaskHash("t1")] = "unschedulable" + _, err := b.Exec(context.Background(), "t1", execReq("true")) + if !errors.Is(err, ErrCapacity) || IsUnavailable(err) || !strings.Contains(err.Error(), "Insufficient cpu") || + !strings.Contains(err.Error(), "sandbox.podReadyTimeout") { + t.Fatalf("err = %v", err) + } + + rs, _ := NewRunnerServer("tok", "v", b) + hs := httptest.NewServer(rs.Handler()) + defer hs.Close() + _, err = NewClient(hs.URL, "tok").Exec(context.Background(), "t1", execReq("true")) + if !errors.Is(err, ErrCapacity) || IsUnavailable(err) { + t.Fatalf("client err = %v (want ErrCapacity, not unavailable)", err) + } + + // Scheduled but slow (pending without the Unschedulable condition) stays a + // plain timeout. + f.podMode["artex-w-"+kubeTaskHash("t2")] = "pending" + if _, err := b.Exec(context.Background(), "t2", execReq("true")); err == nil || errors.Is(err, ErrCapacity) || !strings.Contains(err.Error(), "not ready") { + t.Fatalf("pending err = %v", err) + } +} + +// After a start timed out on pods that are still Pending (waiting for a node), +// the next exec keeps those pods and waits for them instead of deleting and +// recreating them, which would restart the wait for the autoscaler's node. +func TestKubeRetryKeepsPendingPods(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + b.cfg.PodReadyTimeout = 500 * time.Millisecond + h := kubeTaskHash("t1") + f.podMode["artex-w-"+h] = "unschedulable" + f.podMode["artex-p-"+h] = "unschedulable" + if _, err := b.Exec(context.Background(), "t1", execReq("true")); !errors.Is(err, ErrCapacity) { + t.Fatalf("first exec: %v", err) + } + wUID := f.obj("pods", "artex-w-"+h) + + // Still pending: the retry waits on the same pods and creates nothing. + mark := len(f.opsSnapshot()) + if _, err := b.Exec(context.Background(), "t1", execReq("true")); !errors.Is(err, ErrCapacity) { + t.Fatalf("retry while pending: %v", err) + } + for _, op := range f.opsSnapshot()[mark:] { + if strings.Contains(op, "pods/") { + t.Fatalf("retry replaced a pending pod: %s", op) + } + } + + // The node arrived: the pods run, and the next exec uses them. + f.setPodPhase("artex-w-"+h, "Running", true) + f.setPodPhase("artex-p-"+h, "Running", true) + mark = len(f.opsSnapshot()) + if _, err := b.Exec(context.Background(), "t1", execReq("true")); err != nil { + t.Fatalf("exec after the node arrived: %v", err) + } + for _, op := range f.opsSnapshot()[mark:] { + if strings.Contains(op, "pods/") { + t.Fatalf("exec replaced a pod that became ready: %s", op) + } + } + if f.obj("pods", "artex-w-"+h) == nil || wUID == nil { + t.Fatal("worker pod gone") + } + + // A pending proxy with another scope, or a pending pod that cannot start, is + // replaced as before. + f.podMode["artex-w-"+kubeTaskHash("t2")] = "pull-error" + if _, err := b.Exec(context.Background(), "t2", execReq("true")); err == nil { + t.Fatal("pull error not reported") + } + mark = len(f.opsSnapshot()) + _, _ = b.Exec(context.Background(), "t2", execReq("true")) + if ops := strings.Join(f.opsSnapshot()[mark:], " "); !strings.Contains(ops, "delete pods/artex-w-"+kubeTaskHash("t2")) { + t.Fatalf("pod with an image pull error was not replaced: %s", ops) + } + f.podMode["artex-p-"+kubeTaskHash("t3")] = "unschedulable" + f.podMode["artex-w-"+kubeTaskHash("t3")] = "unschedulable" + _, _ = b.Exec(context.Background(), "t3", execReq("true")) + mark = len(f.opsSnapshot()) + req := execReq("true") + req.ScopeDomains = []string{"example.com"} + _, _ = b.Exec(context.Background(), "t3", req) + ops := strings.Join(f.opsSnapshot()[mark:], " ") + if !strings.Contains(ops, "delete pods/artex-p-"+kubeTaskHash("t3")) || strings.Contains(ops, "delete pods/artex-w-"+kubeTaskHash("t3")) { + t.Fatalf("scope change: want the pending proxy replaced and the pending worker kept: %s", ops) + } +} + func TestKubeRefusesForeignService(t *testing.T) { f, srv := newFakeKubeAPI(t) b := newTestKubeBackend(t, f, srv) diff --git a/sandbox/runner.go b/sandbox/runner.go index 56f0e429f..5e56df629 100644 --- a/sandbox/runner.go +++ b/sandbox/runner.go @@ -150,6 +150,8 @@ func (rs *RunnerServer) writeBackendErr(w http.ResponseWriter, err error) { writeRunnerErr(w, http.StatusNotFound, err.Error()) case errors.Is(err, ErrDockerUnavailable): writeRunnerErr(w, http.StatusConflict, err.Error()) + case errors.Is(err, ErrCapacity): + writeRunnerErr(w, http.StatusTooManyRequests, err.Error()) default: log.Printf("[runner] backend error: %v", err) writeRunnerErr(w, http.StatusInternalServerError, fmt.Sprintf("runner error: %v", err)) diff --git a/sandbox/status.go b/sandbox/status.go index 9c44e429c..e63ed4148 100644 --- a/sandbox/status.go +++ b/sandbox/status.go @@ -40,12 +40,155 @@ type TaskStatus struct { Proxy ComponentStatus `json:"proxy"` // ProxyIP is the address the worker reaches its proxy on (the Service // ClusterIP on Kubernetes, the proxy container address on Docker). - ProxyIP string `json:"proxy_ip,omitempty"` - ScopeDomains []string `json:"scope_domains"` - ScopeCIDRs []string `json:"scope_cidrs"` - ScopeHash string `json:"scope_hash,omitempty"` + ProxyIP string `json:"proxy_ip,omitempty"` + ScopeDomains []string `json:"scope_domains"` + ScopeCIDRs []string `json:"scope_cidrs"` + ScopeHash string `json:"scope_hash,omitempty"` + // ScopeKnown is false when the runner does not know the task's scope (no + // proxy pod and no recorded scope): the lists are then empty because nothing + // is known, not because all egress is denied. ScopeSource says where a known + // scope comes from: "live" is the running proxy's own configuration; + // "last_applied" is the scope last applied to the task's proxy + // NetworkPolicy while no proxy runs (a task scaled to zero). + ScopeKnown bool `json:"scope_known"` + ScopeSource string `json:"scope_source,omitempty"` NetworkPolicies []string `json:"network_policies,omitempty"` Network string `json:"network,omitempty"` + + // Scaling fields; empty on a backend without scaling. ScalingState is one of + // active, starting, queued or scaled_to_zero. IdleExpiresAt is when an idle + // task will be scaled to zero (RFC 3339), absent while a command runs. + ScalingState string `json:"scaling_state,omitempty"` + InFlight int `json:"in_flight"` + LastActivity string `json:"last_activity,omitempty"` + IdleExpiresAt string `json:"idle_expires_at,omitempty"` + + // Health is the task's condition against what it should be (see + // TaskHealth): healthy, degraded, starting, queued or scaled_to_zero. + Health string `json:"health,omitempty"` +} + +// Task health values. A task scaled to zero or queued has no pods by design and +// is neither healthy nor degraded. +const ( + HealthHealthy = "healthy" + HealthDegraded = "degraded" + HealthStarting = "starting" + HealthQueued = "queued" + HealthScaledToZero = "scaled_to_zero" +) + +// TaskHealth classifies a task: scaled_to_zero and queued tasks are expected to +// have no pods, starting ones to be coming up; any other task is healthy when +// both its worker and its proxy are ready, degraded otherwise. +func TaskHealth(ts TaskStatus) string { + switch ts.ScalingState { + case ScaleStateZero: + return HealthScaledToZero + case ScaleStateQueued: + return HealthQueued + case ScaleStateStarting: + return HealthStarting + } + if ts.Worker.Ready && ts.Proxy.Ready { + return HealthHealthy + } + return HealthDegraded +} + +// TaskSummary counts tasks by Health. Expected is the number of tasks that +// should have running pods (healthy + degraded): the denominator of +// "N of M healthy". Total also counts starting, queued and scaled-to-zero tasks. +type TaskSummary struct { + Total int `json:"total"` + Expected int `json:"expected"` + Healthy int `json:"healthy"` + Degraded int `json:"degraded"` + Starting int `json:"starting"` + Queued int `json:"queued"` + ScaledToZero int `json:"scaled_to_zero"` +} + +// SummarizeTasks counts tasks by health, classifying those without a Health +// (from a runner that predates it) with TaskHealth. +func SummarizeTasks(tasks []TaskStatus) TaskSummary { + var s TaskSummary + for _, ts := range tasks { + h := ts.Health + if h == "" { + h = TaskHealth(ts) + } + s.Total++ + switch h { + case HealthHealthy: + s.Healthy++ + case HealthDegraded: + s.Degraded++ + case HealthStarting: + s.Starting++ + case HealthQueued: + s.Queued++ + case HealthScaledToZero: + s.ScaledToZero++ + } + } + s.Expected = s.Healthy + s.Degraded + return s +} + +// ScaleEvent is one scale-up, failed scale-up or scale-down of a task. +// DurationMS is set on a scale-up: from the first API call to the network paths +// being open (on a failed one: until it gave up). QueueMS is how long that +// scale-up waited for a capacity slot first. Error is set on a failed scale-up. +type ScaleEvent struct { + Time string `json:"time"` + TaskID string `json:"task_id"` + Kind string `json:"kind"` + Reason string `json:"reason"` + DurationMS int64 `json:"duration_ms,omitempty"` + QueueMS int64 `json:"queue_ms,omitempty"` + Error string `json:"error,omitempty"` +} + +// ScaleTotals counts every scale event since Since (when the runner first +// kept history in its state directory, or its start without one). +type ScaleTotals struct { + ScaleUps int64 `json:"scale_ups"` + ScaleDowns int64 `json:"scale_downs"` + ScaleUpFailures int64 `json:"scale_up_failures"` + Since string `json:"since,omitempty"` +} + +// ColdStartStats summarises the scale-ups from zero (first_exec and resume) +// the runner remembers. SamplesMS is oldest first. +type ColdStartStats struct { + Count int `json:"count"` + LastMS int64 `json:"last_ms"` + P50MS int64 `json:"p50_ms"` + P95MS int64 `json:"p95_ms"` + SamplesMS []int64 `json:"samples_ms"` +} + +// ScalingStatus is the scaling view of the runner. Active counts the capacity +// slots in use (tasks with pods, plus deleted tasks whose pods are still going +// away), Starting the tasks still coming up. A zero +// IdleTimeoutSeconds means idle scale-down is off, a zero MaxActive no cap. +type ScalingStatus struct { + Supported bool `json:"supported"` + IdleTimeoutSeconds int64 `json:"idle_timeout_seconds"` + MaxActive int `json:"max_active"` + QueueTimeoutSeconds int64 `json:"queue_timeout_seconds"` + Active int `json:"active"` + Starting int `json:"starting"` + Queued int `json:"queued"` + ScaledToZero int `json:"scaled_to_zero"` + ColdStart ColdStartStats `json:"cold_start"` + Totals ScaleTotals `json:"totals"` + // Persisted is true when history, totals and cold starts survive a runner + // restart (a state directory is configured). + Persisted bool `json:"persisted"` + // Events is the bounded scale history, oldest first. + Events []ScaleEvent `json:"events"` } // TasksResponse is the response body for GET /v1/tasks. @@ -55,8 +198,19 @@ type TasksResponse struct { Supported bool `json:"supported"` Namespace string `json:"namespace,omitempty"` Tasks []TaskStatus `json:"tasks"` + // Summary counts Tasks by Health. + Summary TaskSummary `json:"summary"` + // Scaling is absent on a runner that predates it; Supported is false on a + // backend that keeps every task running (Docker). + Scaling *ScalingStatus `json:"scaling,omitempty"` } +// ScopeSource values (TaskStatus.ScopeSource). +const ( + ScopeSourceLive = "live" + ScopeSourceLastApplied = "last_applied" +) + // StatusReporter is an optional Backend capability: a read-only snapshot of the // sandbox objects the backend manages. It never mutates backend state. type StatusReporter interface { @@ -85,7 +239,11 @@ func (rs *RunnerServer) handleTasks(w http.ResponseWriter, r *http.Request) { if res.Tasks[i].ScopeCIDRs == nil { res.Tasks[i].ScopeCIDRs = []string{} } + if res.Tasks[i].Health == "" { + res.Tasks[i].Health = TaskHealth(res.Tasks[i]) + } } + res.Summary = SummarizeTasks(res.Tasks) writeRunnerJSON(w, http.StatusOK, res) } @@ -214,7 +372,22 @@ func (b *KubernetesBackend) Status(ctx context.Context) (TasksResponse, error) { ts.Tracked = true ts.ProxyIP = kt.proxyIP ts.ScopeHash = kt.scopeHash + if kt.scopeKnown { + ts.ScopeDomains = append([]string{}, kt.scopeDomains...) + ts.ScopeCIDRs = append([]string{}, kt.scopeCIDRs...) + ts.ScopeSource, ts.ScopeKnown = ScopeSourceLastApplied, true + } + } + // A task waiting for a slot or coming up for the first time is not tracked yet. + for tid, st := range b.scale { + if st.queued || st.starting || st.active { + get(tid) + } + } + for tid, ts := range byID { + b.applyScaleLocked(ts, b.scale[tid]) } + scaling := b.scalingStatusLocked() b.mu.Unlock() for i := range list.Items { p := &list.Items[i] @@ -238,6 +411,8 @@ func (b *KubernetesBackend) Status(ctx context.Context) (TasksResponse, error) { if h := p.Metadata.Annotations[AnnotationScope]; h != "" { ts.ScopeHash = h } + // The running proxy's own configuration wins over the remembered scope. + ts.ScopeDomains, ts.ScopeCIDRs, ts.ScopeSource, ts.ScopeKnown = []string{}, []string{}, ScopeSourceLive, true for _, c := range p.Spec.Containers { for _, e := range c.Env { switch e.Name { @@ -249,7 +424,7 @@ func (b *KubernetesBackend) Status(ctx context.Context) (TasksResponse, error) { } } } - out := TasksResponse{Backend: BackendKubernetes, Namespace: b.cfg.Namespace, Tasks: make([]TaskStatus, 0, len(byID))} + out := TasksResponse{Backend: BackendKubernetes, Namespace: b.cfg.Namespace, Tasks: make([]TaskStatus, 0, len(byID)), Scaling: scaling} for _, ts := range byID { out.Tasks = append(out.Tasks, *ts) } @@ -403,8 +578,11 @@ func (b *DockerBackend) Status(ctx context.Context) (TasksResponse, error) { } } ts.ScopeHash = kubeTaskHash(scopeFingerprint(ts.ScopeDomains, ts.ScopeCIDRs))[:8] + ts.ScopeSource, ts.ScopeKnown = ScopeSourceLive, true } - out := TasksResponse{Backend: BackendDocker, Tasks: make([]TaskStatus, 0, len(byID))} + // Docker keeps every task's containers until the task is deleted. + out := TasksResponse{Backend: BackendDocker, Tasks: make([]TaskStatus, 0, len(byID)), + Scaling: &ScalingStatus{Events: []ScaleEvent{}, ColdStart: ColdStartStats{SamplesMS: []int64{}}}} for _, ts := range byID { out.Tasks = append(out.Tasks, *ts) } diff --git a/sandbox/status_test.go b/sandbox/status_test.go index 5e52a32a3..329504701 100644 --- a/sandbox/status_test.go +++ b/sandbox/status_test.go @@ -146,6 +146,10 @@ func TestRunnerTasksShapeAndClient(t *testing.T) { want := sb.res want.Supported = true want.Tasks[0].ScopeCIDRs = []string{} + // The runner classifies a task the backend left without a health: the proxy + // is not ready, so the task is degraded. + want.Tasks[0].Health = HealthDegraded + want.Summary = TaskSummary{Total: 1, Expected: 1, Degraded: 1} if !reflect.DeepEqual(got, want) { t.Fatalf("client Tasks\n got %+v\nwant %+v", got, want) } diff --git a/sandbox/types.go b/sandbox/types.go index 4cee149a9..36ae23ba9 100644 --- a/sandbox/types.go +++ b/sandbox/types.go @@ -62,6 +62,10 @@ var ( ErrBadRequest = errors.New("sandbox runner invalid request") ErrNotFound = errors.New("sandbox task not found") ErrDockerUnavailable = errors.New("sandbox runner cannot reach docker") + // ErrCapacity: every sandbox slot stayed busy for the whole queue timeout, or + // (Kubernetes) no node had room for a task pod within the pod ready timeout. The + // runner is healthy, so IsUnavailable is false and the command may be retried. + ErrCapacity = errors.New("sandbox at capacity") ) // ExecRequest is the request body for POST /v1/tasks/{id}/exec. diff --git a/scripts/capd-autoscaler-e2e.sh b/scripts/capd-autoscaler-e2e.sh new file mode 100755 index 000000000..dc97c3586 --- /dev/null +++ b/scripts/capd-autoscaler-e2e.sh @@ -0,0 +1,615 @@ +#!/usr/bin/env bash +# End-to-end test of the Kubernetes sandbox under a real cluster-autoscaler. +# +# Builds a Cluster API management cluster (kind + the Docker infrastructure +# provider, CAPD), a workload cluster with real kubeadm nodes (containers), +# Calico (NetworkPolicy), an in-cluster NFS server with csi-driver-nfs +# (ReadWriteMany), and the official cluster-autoscaler (clusterapi provider) +# scaling two MachineDeployments: +# -md-0 base pool, 1..4 nodes: panel, runner, PostgreSQL +# -sandbox task pool, 0..3 nodes, tainted: task pods only +# Images are built from this checkout and served to every node (also nodes the +# autoscaler adds later) by a registry container on the kind network. +# +# Then it checks, with timings in $WORKDIR/results.txt: +# 1. helm test and TestKubeSandboxE2E on Calico (network isolation); +# 2. scale-up: a burst of tasks makes the task pool grow from zero, every +# command runs on the new nodes (workspace on RWX, egress via the proxy, +# direct egress blocked); +# 3. scale-down: idle tasks scale to zero and the pool goes back to zero +# nodes; a task resumes (pool from zero again) with its workspace; +# 4. ReadWriteOnce: task pods pinned to the runner's node; the autoscaler +# does not scale up and the commands fail with HTTP 429. +# +# scripts/capd-autoscaler-e2e.sh run everything, then delete it all +# KEEP=1 scripts/capd-autoscaler-e2e.sh leave the clusters and registry running +# SKIP_BUILD=1 ... reuse images already in the registry +# CLEANUP_ONLY=1 ... delete what an earlier KEEP=1 run left +# +# Requires: docker, kind, kubectl, helm, go, curl, jq, sha256sum. clusterctl is +# downloaded (pinned, checksum verified) into $WORKDIR/bin. No LLM key is used. +# Nodes are containers that see the whole host: kubelet system-reserved +# limits each worker node to NODE_CPU CPUs and NODE_MEM of memory for pods. +set -euo pipefail + +MGMT=${MGMT:-artex-capd-mgmt} +CLUSTER=${CLUSTER:-artex-ca} +REGISTRY=${REGISTRY:-artex-ca-registry} +REGISTRY_PORT=${REGISTRY_PORT:-5101} +TAG=${TAG:-ca} +NS=${NS:-artex} +RELEASE=${RELEASE:-artex} +NODE_CPU=${NODE_CPU:-2} +NODE_MEM_GI=${NODE_MEM_GI:-4} +WORKDIR=${WORKDIR:-${XDG_CACHE_HOME:-$HOME/.cache}/artex-capd-e2e} +ROOT=$(cd "$(dirname "$0")/.." && pwd) + +# Pinned versions. +K8S_VERSION=v1.36.4 +KIND_NODE_IMAGE=kindest/node:v1.36.4@sha256:099e049362a1526b2db71494e1947aae99bd16290d7c895f2b7ea312e3cbfaed +CAPI_VERSION=v1.14.4 +CLUSTERCTL_SHA256=c7301a8515ed329562b06c958463051dd55d9649fac591393f5df54a868fa79b +CALICO_VERSION=v3.33.1 +CALICO_SHA256=3368e62807b949438842e31f46c9b6df741731b4c755d0a622dd062b2cb20495 +CSI_NFS_CHART_VERSION=4.13.6 +NFS_SERVER_IMAGE=itsthenetwork/nfs-server-alpine@sha256:7fa99ae65c23c5af87dd4300e543a86b119ed15ba61422444207efc7abd0ba20 +CA_CHART_VERSION=9.61.0 +CA_IMAGE_TAG=v1.36.2 +REGISTRY_IMAGE=registry:3@sha256:ddf754342cfc8acc51a56d5d0ab6af06826461864460636d8bd5c546dab2a7b8 + +MGMT_KC=$WORKDIR/mgmt.kubeconfig +WL_KC=$WORKDIR/workload.kubeconfig +RESULTS=$WORKDIR/results.txt +CLUSTERCTL=$WORKDIR/bin/clusterctl-$CAPI_VERSION +IMG=$REGISTRY:5000 # image prefix as the nodes see it +PF_PIDS=() + +log() { printf '\n==> %s\n' "$*"; } +note() { printf '%s\n' "$*" | tee -a "$RESULTS"; } +fail() { + printf 'FAIL: %s\n' "$*" | tee -a "$RESULTS" >&2 + exit 1 +} +now() { date +%s; } +mk() { kubectl --kubeconfig "$MGMT_KC" "$@"; } +wk() { kubectl --kubeconfig "$WL_KC" "$@"; } + +# wait_for SECONDS DESCRIPTION COMMAND...: retry COMMAND every 5 s. +wait_for() { + local limit=$1 what=$2 start + shift 2 + start=$(now) + until "$@" >/dev/null 2>&1; do + if (($(now) - start > limit)); then + fail "timed out after ${limit}s waiting for $what" + fi + sleep 5 + done +} + +teardown() { + log "deleting workload cluster $CLUSTER, management cluster $MGMT and registry $REGISTRY" + if [ -f "$MGMT_KC" ] && kind get clusters 2>/dev/null | grep -qx "$MGMT"; then + # Cluster API removes the node containers and the load balancer. + mk delete cluster "$CLUSTER" --ignore-not-found --timeout=5m || true + fi + kind delete cluster --name "$MGMT" || true + docker rm -f "$REGISTRY" >/dev/null 2>&1 || true + # Node containers CAPD had not finished removing, or left behind when the + # management cluster was already gone (Docker may still be removing one). + local i + for i in 1 2 3 4 5 6; do + [ -z "$(docker ps -aq --filter "label=io.x-k8s.kind.cluster=$CLUSTER")" ] && break + docker ps -aq --filter "label=io.x-k8s.kind.cluster=$CLUSTER" | xargs -r docker rm -f >/dev/null 2>&1 || true + sleep 5 + done +} + +cleanup() { + local pid + for pid in "${PF_PIDS[@]}"; do + kill "$pid" 2>/dev/null || true + done + if [ "${KEEP:-0}" = "1" ]; then + log "KEEP=1: left running. Workload cluster: KUBECONFIG=$WL_KC kubectl get nodes" + log "management cluster: KUBECONFIG=$MGMT_KC kubectl get machinedeployments,machines" + return + fi + teardown +} + +mkdir -p "$WORKDIR/bin" "$WORKDIR/manifests" "$WORKDIR/dl" +if [ "${CLEANUP_ONLY:-0}" = "1" ]; then + teardown + exit 0 +fi +trap cleanup EXIT +: >"$RESULTS" +note "capd-autoscaler-e2e $(date -u +%Y-%m-%dT%H:%M:%SZ) commit $(git -C "$ROOT" rev-parse --short HEAD)" +note "versions: kubernetes $K8S_VERSION, cluster-api/CAPD $CAPI_VERSION, cluster-autoscaler $CA_IMAGE_TAG (chart $CA_CHART_VERSION), calico $CALICO_VERSION, csi-driver-nfs $CSI_NFS_CHART_VERSION" + +for tool in docker kind kubectl helm go curl jq sha256sum; do + command -v "$tool" >/dev/null || fail "$tool is required" +done + +# --- tools ------------------------------------------------------------------- +if [ ! -x "$CLUSTERCTL" ]; then + log "downloading clusterctl $CAPI_VERSION" + curl -fsSLo "$CLUSTERCTL.tmp" "https://github.com/kubernetes-sigs/cluster-api/releases/download/$CAPI_VERSION/clusterctl-linux-amd64" + echo "$CLUSTERCTL_SHA256 $CLUSTERCTL.tmp" | sha256sum -c - >/dev/null || fail "clusterctl checksum mismatch" + chmod +x "$CLUSTERCTL.tmp" + mv "$CLUSTERCTL.tmp" "$CLUSTERCTL" +fi +CALICO_YAML=$WORKDIR/dl/calico-$CALICO_VERSION.yaml +if [ ! -f "$CALICO_YAML" ]; then + curl -fsSLo "$CALICO_YAML.tmp" "https://raw.githubusercontent.com/projectcalico/calico/$CALICO_VERSION/manifests/calico.yaml" + # Calico publishes no checksum for the manifest: this pins the file reviewed + # for this script. + echo "$CALICO_SHA256 $CALICO_YAML.tmp" | sha256sum -c - >/dev/null || fail "calico manifest checksum mismatch" + mv "$CALICO_YAML.tmp" "$CALICO_YAML" +fi + +# --- management cluster ------------------------------------------------------ +if ! kind get clusters 2>/dev/null | grep -qx "$MGMT"; then + log "creating kind management cluster $MGMT" + cat >"$WORKDIR/manifests/kind-mgmt.yaml" <<-EOF + kind: Cluster + apiVersion: kind.x-k8s.io/v1alpha4 + nodes: + - role: control-plane + extraMounts: + - hostPath: /var/run/docker.sock + containerPath: /var/run/docker.sock + EOF + kind create cluster --name "$MGMT" --image "$KIND_NODE_IMAGE" --config "$WORKDIR/manifests/kind-mgmt.yaml" \ + --kubeconfig "$MGMT_KC" --wait 3m +fi +kind get kubeconfig --name "$MGMT" >"$MGMT_KC" +if ! mk get ns capi-system >/dev/null 2>&1; then + log "installing Cluster API $CAPI_VERSION with the Docker provider" + "$CLUSTERCTL" init --kubeconfig "$MGMT_KC" --core "cluster-api:$CAPI_VERSION" --bootstrap "kubeadm:$CAPI_VERSION" \ + --control-plane "kubeadm:$CAPI_VERSION" --infrastructure "docker:$CAPI_VERSION" --wait-providers +fi + +# --- registry ---------------------------------------------------------------- +if ! docker inspect "$REGISTRY" >/dev/null 2>&1; then + log "starting registry $REGISTRY on the kind network" + docker run -d --restart=unless-stopped --name "$REGISTRY" --network kind \ + -p "127.0.0.1:$REGISTRY_PORT:5000" "$REGISTRY_IMAGE" >/dev/null +fi +if [ "${SKIP_BUILD:-0}" != "1" ]; then + log "building and pushing images (tag $TAG)" + for pair in artex:Dockerfile artex-runner:Dockerfile.runner artex-worker:Dockerfile.worker artex-egress-proxy:Dockerfile.egress-proxy; do + name=${pair%%:*} + docker build -q -t "$name:$TAG" -f "$ROOT/${pair#*:}" "$ROOT" >/dev/null + docker tag "$name:$TAG" "localhost:$REGISTRY_PORT/$name:$TAG" + docker push -q "localhost:$REGISTRY_PORT/$name:$TAG" >/dev/null + done +fi + +# --- workload cluster ---------------------------------------------------------- +log "applying workload cluster $CLUSTER" +# docker info reports what the Docker VM has, which is what node containers see. +reserved_cpu=$(($(docker info --format '{{.NCPU}}') - NODE_CPU)) +reserved_mem=$(($(docker info --format '{{.MemTotal}}') / 1073741824 - NODE_MEM_GI)) +if [ "$reserved_cpu" -le 0 ] || [ "$reserved_mem" -le 0 ]; then + fail "Docker has too little CPU or memory for NODE_CPU=$NODE_CPU NODE_MEM_GI=$NODE_MEM_GI" +fi +cat >"$WORKDIR/manifests/workload.yaml" <<-EOF + apiVersion: cluster.x-k8s.io/v1beta2 + kind: Cluster + metadata: {name: $CLUSTER, namespace: default} + spec: + clusterNetwork: + pods: {cidrBlocks: ["192.168.0.0/16"]} + services: {cidrBlocks: ["10.128.0.0/12"]} + serviceDomain: cluster.local + controlPlaneRef: {apiGroup: controlplane.cluster.x-k8s.io, kind: KubeadmControlPlane, name: $CLUSTER-control-plane} + infrastructureRef: {apiGroup: infrastructure.cluster.x-k8s.io, kind: DockerCluster, name: $CLUSTER} + --- + apiVersion: infrastructure.cluster.x-k8s.io/v1beta2 + kind: DockerCluster + metadata: {name: $CLUSTER, namespace: default} + spec: {} + --- + apiVersion: infrastructure.cluster.x-k8s.io/v1beta2 + kind: DockerMachineTemplate + metadata: {name: $CLUSTER-node, namespace: default} + spec: + template: + spec: {customImage: "kindest/node:$K8S_VERSION"} + --- + apiVersion: controlplane.cluster.x-k8s.io/v1beta2 + kind: KubeadmControlPlane + metadata: {name: $CLUSTER-control-plane, namespace: default} + spec: + replicas: 1 + version: $K8S_VERSION + machineTemplate: + spec: + infrastructureRef: {apiGroup: infrastructure.cluster.x-k8s.io, kind: DockerMachineTemplate, name: $CLUSTER-node} + kubeadmConfigSpec: + clusterConfiguration: + apiServer: {certSANs: [localhost, 127.0.0.1, 0.0.0.0, host.docker.internal]} + initConfiguration: + nodeRegistration: + kubeletExtraArgs: [{name: eviction-hard, value: "nodefs.available<0%,nodefs.inodesFree<0%,imagefs.available<0%"}] + EOF +# One bootstrap template per pool: both trust the registry (containerd reads +# hosts.toml once config_path is set), the task pool is tainted. +for pool in md-0 sandbox; do + taints="[]" + [ "$pool" = sandbox ] && taints='[{key: artex.io/sandbox, value: "true", effect: NoSchedule}]' + cat >>"$WORKDIR/manifests/workload.yaml" <<-EOF + --- + apiVersion: bootstrap.cluster.x-k8s.io/v1beta2 + kind: KubeadmConfigTemplate + metadata: {name: $CLUSTER-$pool, namespace: default} + spec: + template: + spec: + files: + - path: /etc/containerd/certs.d/$REGISTRY:5000/hosts.toml + content: | + server = "http://$REGISTRY:5000" + [host."http://$REGISTRY:5000"] + capabilities = ["pull", "resolve"] + skip_verify = true + preKubeadmCommands: + - printf '\n[plugins."io.containerd.grpc.v1.cri".registry]\n config_path = "/etc/containerd/certs.d"\n' >> /etc/containerd/config.toml + - systemctl restart containerd + joinConfiguration: + nodeRegistration: + taints: $taints + kubeletExtraArgs: + - {name: eviction-hard, value: "nodefs.available<0%,nodefs.inodesFree<0%,imagefs.available<0%"} + - {name: system-reserved, value: "cpu=$reserved_cpu,memory=${reserved_mem}Gi"} + EOF +done +cat >>"$WORKDIR/manifests/workload.yaml" <<-EOF + --- + apiVersion: cluster.x-k8s.io/v1beta2 + kind: MachineDeployment + metadata: + name: $CLUSTER-md-0 + namespace: default + annotations: + cluster.x-k8s.io/cluster-api-autoscaler-node-group-min-size: "1" + cluster.x-k8s.io/cluster-api-autoscaler-node-group-max-size: "4" + spec: + clusterName: $CLUSTER + replicas: 1 + selector: {matchLabels: {}} + template: + spec: + clusterName: $CLUSTER + version: $K8S_VERSION + bootstrap: {configRef: {apiGroup: bootstrap.cluster.x-k8s.io, kind: KubeadmConfigTemplate, name: $CLUSTER-md-0}} + infrastructureRef: {apiGroup: infrastructure.cluster.x-k8s.io, kind: DockerMachineTemplate, name: $CLUSTER-node} + --- + # Task pods only. Scales from zero: the capacity annotations describe a node + # of this pool to the autoscaler when none exists. + apiVersion: cluster.x-k8s.io/v1beta2 + kind: MachineDeployment + metadata: + name: $CLUSTER-sandbox + namespace: default + annotations: + cluster.x-k8s.io/cluster-api-autoscaler-node-group-min-size: "0" + cluster.x-k8s.io/cluster-api-autoscaler-node-group-max-size: "3" + capacity.cluster-autoscaler.kubernetes.io/cpu: "$NODE_CPU" + capacity.cluster-autoscaler.kubernetes.io/memory: "$((NODE_MEM_GI * 1024 - 100))Mi" + capacity.cluster-autoscaler.kubernetes.io/maxPods: "110" + capacity.cluster-autoscaler.kubernetes.io/ephemeral-disk: "100Gi" + capacity.cluster-autoscaler.kubernetes.io/labels: "node.cluster.x-k8s.io/pool=sandbox" + capacity.cluster-autoscaler.kubernetes.io/taints: "artex.io/sandbox=true:NoSchedule" + spec: + clusterName: $CLUSTER + replicas: 0 + selector: {matchLabels: {}} + template: + metadata: + labels: {node.cluster.x-k8s.io/pool: sandbox} + spec: + clusterName: $CLUSTER + version: $K8S_VERSION + bootstrap: {configRef: {apiGroup: bootstrap.cluster.x-k8s.io, kind: KubeadmConfigTemplate, name: $CLUSTER-sandbox}} + infrastructureRef: {apiGroup: infrastructure.cluster.x-k8s.io, kind: DockerMachineTemplate, name: $CLUSTER-node} +EOF +# Replicas belong to the autoscaler once it runs: a rerun keeps the cluster as +# it is (delete it, or run CLEANUP_ONLY=1, to apply changed manifests). +if mk get cluster "$CLUSTER" >/dev/null 2>&1; then + log "workload cluster $CLUSTER exists; not reapplying it" +else + mk apply -f "$WORKDIR/manifests/workload.yaml" 2>&1 | grep -v Warning +fi +wait_for 600 "the control plane of $CLUSTER" \ + sh -c "[ \"\$(kubectl --kubeconfig '$MGMT_KC' get kcp '$CLUSTER-control-plane' -o jsonpath='{.status.initialization.controlPlaneInitialized}')\" = true ]" +"$CLUSTERCTL" get kubeconfig "$CLUSTER" --kubeconfig "$MGMT_KC" >"$WL_KC" +# The kubeconfig names the load balancer's address on the kind network; from the +# host (Docker Desktop included) use its published port. +lb_port=$(docker port "$CLUSTER-lb" 6443/tcp | head -1 | sed 's/.*://') +sed -i "s#server: https://.*#server: https://127.0.0.1:$lb_port#" "$WL_KC" +wait_for 300 "the workload API server" kubectl --kubeconfig "$WL_KC" get --raw /readyz + +log "installing Calico $CALICO_VERSION" +wk apply --server-side -f "$CALICO_YAML" >/dev/null +wait_for 600 "nodes Ready" kubectl --kubeconfig "$WL_KC" wait --for=condition=Ready node --all --timeout=10s + +log "installing the NFS server and csi-driver-nfs $CSI_NFS_CHART_VERSION" +cat >"$WORKDIR/manifests/nfs.yaml" <<-EOF + apiVersion: v1 + kind: Namespace + metadata: {name: nfs} + --- + apiVersion: v1 + kind: Service + metadata: {name: nfs-server, namespace: nfs} + spec: + selector: {app: nfs-server} + ports: + - {name: tcp-2049, port: 2049, protocol: TCP} + - {name: udp-111, port: 111, protocol: UDP} + --- + apiVersion: apps/v1 + kind: Deployment + metadata: {name: nfs-server, namespace: nfs} + spec: + replicas: 1 + selector: {matchLabels: {app: nfs-server}} + template: + metadata: {labels: {app: nfs-server}} + spec: + # On the control plane: never on a node the autoscaler may remove. + nodeSelector: {node-role.kubernetes.io/control-plane: ""} + tolerations: [{key: node-role.kubernetes.io/control-plane, operator: Exists, effect: NoSchedule}] + containers: + - name: nfs-server + image: $NFS_SERVER_IMAGE + env: [{name: SHARED_DIRECTORY, value: /exports}] + securityContext: {privileged: true} + volumeMounts: [{name: data, mountPath: /exports}] + volumes: + # /var is a real filesystem on kind/CAPD nodes; their overlayfs root + # cannot be exported by knfsd. + - {name: data, hostPath: {path: /var/lib/artex-nfs, type: DirectoryOrCreate}} + --- + apiVersion: storage.k8s.io/v1 + kind: StorageClass + metadata: + name: nfs-csi + annotations: {storageclass.kubernetes.io/is-default-class: "true"} + provisioner: nfs.csi.k8s.io + parameters: {server: nfs-server.nfs.svc.cluster.local, share: /} + reclaimPolicy: Delete + volumeBindingMode: Immediate + mountOptions: [nfsvers=4.1] +EOF +wk apply -f "$WORKDIR/manifests/nfs.yaml" >/dev/null +helm upgrade --install csi-driver-nfs csi-driver-nfs --repo https://raw.githubusercontent.com/kubernetes-csi/csi-driver-nfs/master/charts \ + --version "$CSI_NFS_CHART_VERSION" --kubeconfig "$WL_KC" -n kube-system --set controller.runOnControlPlane=true --wait --timeout 5m >/dev/null +wk -n nfs rollout status deploy/nfs-server --timeout=300s >/dev/null + +log "installing cluster-autoscaler $CA_IMAGE_TAG in the management cluster" +helm upgrade --install "$CLUSTER-autoscaler" cluster-autoscaler --repo https://kubernetes.github.io/autoscaler \ + --version "$CA_CHART_VERSION" --kubeconfig "$MGMT_KC" -n default \ + --set cloudProvider=clusterapi --set clusterAPIMode=kubeconfig-incluster \ + --set "clusterAPIKubeconfigSecret=$CLUSTER-kubeconfig" \ + --set "autoDiscovery.clusterName=$CLUSTER" --set autoDiscovery.namespace=default \ + --set "image.tag=$CA_IMAGE_TAG" \ + --set extraArgs.scan-interval=10s --set extraArgs.scale-down-unneeded-time=1m \ + --set extraArgs.scale-down-delay-after-add=1m --set extraArgs.scale-down-delay-after-delete=0s \ + --set extraArgs.unremovable-node-recheck-timeout=1m --set extraArgs.v=4 --wait --timeout 5m >/dev/null +ca_sa=$(mk get sa -n default -o name | grep cluster-autoscaler | head -1 | sed 's#serviceaccount/##') +# The chart does not grant read access to infrastructure machine templates; +# without it the clusterapi provider never finishes its cache sync. +cat >"$WORKDIR/manifests/ca-rbac.yaml" <<-EOF + apiVersion: rbac.authorization.k8s.io/v1 + kind: ClusterRole + metadata: {name: $CLUSTER-autoscaler-infra-templates} + rules: + - apiGroups: [infrastructure.cluster.x-k8s.io] + resources: [dockermachinetemplates, devmachinetemplates] + verbs: [get, list, watch] + --- + apiVersion: rbac.authorization.k8s.io/v1 + kind: ClusterRoleBinding + metadata: {name: $CLUSTER-autoscaler-infra-templates} + roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: $CLUSTER-autoscaler-infra-templates} + subjects: [{kind: ServiceAccount, name: $ca_sa, namespace: default}] +EOF +mk apply -f "$WORKDIR/manifests/ca-rbac.yaml" >/dev/null +ca_deploy=$(mk get deploy -n default -o name | grep cluster-autoscaler | head -1) +mk -n default rollout restart "$ca_deploy" >/dev/null +mk -n default rollout status "$ca_deploy" --timeout=180s >/dev/null + +# --- ARTEX --------------------------------------------------------------------- +base_values=(--kubeconfig "$WL_KC" -n "$NS" + --set "images.artex.repository=$IMG/artex" --set "images.artex.tag=$TAG" + --set "images.runner.repository=$IMG/artex-runner" --set "images.runner.tag=$TAG" + --set "images.worker.repository=$IMG/artex-worker" --set "images.worker.tag=$TAG" + --set "images.egressProxy.repository=$IMG/artex-egress-proxy" --set "images.egressProxy.tag=$TAG" + --set images.pullPolicy=Always + --set persistence.data.accessMode=ReadWriteMany --set persistence.data.storageClass=nfs-csi + --set-string 'panel.podAnnotations.cluster-autoscaler\.kubernetes\.io/safe-to-evict=false' + --set-string 'runner.podAnnotations.cluster-autoscaler\.kubernetes\.io/safe-to-evict=false' + --set-string 'postgres.podAnnotations.cluster-autoscaler\.kubernetes\.io/safe-to-evict=false') +pool_values=(--set sandbox.nodeSelector.node\\.cluster\\.x-k8s\\.io/pool=sandbox + --set 'sandbox.tolerations[0].key=artex.io/sandbox' --set 'sandbox.tolerations[0].operator=Equal' + --set-string 'sandbox.tolerations[0].value=true' --set 'sandbox.tolerations[0].effect=NoSchedule' + --set sandbox.podReadyTimeout=5m --set sandbox.worker.cpuRequest=500m) + +log "installing the chart (ReadWriteMany, task pods on the autoscaled task pool)" +wk create namespace "$NS" --dry-run=client -o yaml | wk apply -f - >/dev/null +helm upgrade --install "$RELEASE" "$ROOT/deploy/helm/artex" "${base_values[@]}" "${pool_values[@]}" \ + --set sandbox.scaling.idleTimeout=30s --set sandbox.scaling.maxActive=2 --wait --timeout 15m >/dev/null +helm test "$RELEASE" --kubeconfig "$WL_KC" -n "$NS" --logs >"$WORKDIR/helm-test.log" 2>&1 || { + cat "$WORKDIR/helm-test.log" + fail "helm test" +} +note "helm test: passed" +TOKEN=$(wk -n "$NS" get secret "$RELEASE-secrets" -o jsonpath='{.data.ARTEX_RUNNER_TOKEN}' | base64 -d) + +log "running TestKubeSandboxE2E (Calico; task pods on the task pool, which scales from zero)" +e2e_rc=0 +( + cd "$ROOT" + ARTEX_SANDBOX_KUBE_E2E=1 ARTEX_RUNNER_TOKEN="$TOKEN" ARTEX_E2E_RUNNER_SVC="$RELEASE-runner" \ + ARTEX_E2E_NAMESPACE="$NS" KUBECONFIG="$WL_KC" ARTEX_E2E_INTERNET="${ARTEX_E2E_INTERNET:-1}" \ + go test ./sandbox -run TestKubeSandboxE2E -count=1 -v -timeout 30m +) >"$WORKDIR/e2e.log" 2>&1 || e2e_rc=$? +grep -E '^(=== RUN|--- | |ok|FAIL|PASS)' "$WORKDIR/e2e.log" | tee -a "$RESULTS" || true +[ "$e2e_rc" -eq 0 ] || fail "TestKubeSandboxE2E (full output: $WORKDIR/e2e.log)" + +# --- runner API helpers -------------------------------------------------------- +pf_port= +# start_pf NAMESPACE SERVICE: forward a kubectl-chosen local port (a fixed one +# may already be another cluster's forward) and set pf_port. kubectl runs as a +# direct child, so its PID is the one cleanup kills. +start_pf() { + local log=$WORKDIR/pf-$2.log i + kubectl --kubeconfig "$WL_KC" -n "$1" port-forward --address 127.0.0.1 "svc/$2" :8789 >"$log" 2>&1 & + PF_PIDS+=("$!") + pf_port= + for i in $(seq 1 60); do + pf_port=$(sed -n 's/^Forwarding from 127\.0\.0\.1:\([0-9]*\) .*/\1/p' "$log" | head -1) + [ -n "$pf_port" ] && break + sleep 0.5 + done + [ -n "$pf_port" ] || fail "port-forward to $2 ($i tries): $(cat "$log")" + wait_for 30 "the runner via port-forward to $2" curl -fsS -H "Authorization: Bearer $TOKEN" "http://127.0.0.1:$pf_port/v1/health" +} +stop_pf() { + local pid + for pid in "${PF_PIDS[@]}"; do kill "$pid" 2>/dev/null || true; done + PF_PIDS=() +} +# exec_task ID SCRIPT -> " " on stdout +exec_task() { + local body out + body=$(jq -nc --arg s "$2" '{argv: ["bash", "-c", $s], timeout_ms: 600000, scope_domains: ["example.com"]}') + out=$(curl -s --max-time 900 -w '\n%{http_code}' -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ + -d "$body" "http://127.0.0.1:$pf_port/v1/tasks/$1/exec") + printf '%s %s\n' "$(tail -n1 <<<"$out")" "$(head -n -1 <<<"$out" | tr -d '\n')" +} +md_replicas() { mk get md "$CLUSTER-$1" -o jsonpath='{.spec.replicas}'; } +# snapshot NAME: nodes, machines and task pods to $WORKDIR/ca-NAME.txt +snapshot() { + { + echo "# $1 at $(date -u +%H:%M:%SZ)" + echo "\$ kubectl get machinedeployments,machines (management cluster)" + mk get machinedeployments,machines -o wide 2>&1 | cut -c1-200 + echo "\$ kubectl get nodes -o wide" + wk get nodes -o wide -L node.cluster.x-k8s.io/pool 2>&1 | cut -c1-200 + echo "\$ kubectl get pods -A -l artex.managed_by=artex-runner -o wide" + wk get pods -A -l artex.managed_by=artex-runner -o wide 2>&1 | cut -c1-200 + } >"$WORKDIR/ca-$1.txt" +} +# wait_jobs PID...: wait for the given background jobs only (not port-forwards). +wait_jobs() { + local pid + for pid in "$@"; do wait "$pid" || true; done +} +# shellcheck disable=SC2016 # expanded by bash inside the worker +PROBE='echo "marker=$(cat /workspace/marker 2>/dev/null || echo missing)"; +timeout 6 bash -c "exec 3<>/dev/tcp/1.1.1.1/443" 2>/dev/null && echo direct=OPEN || echo direct=BLOCKED; +echo "out_of_scope=$(curl -s -o /dev/null -w "%{http_connect}" --max-time 15 https://example.org)"; +echo "in_scope=$(curl -s -o /dev/null -w "%{http_code}" --max-time 20 https://example.com)"' + +# --- 2. scale-up ----------------------------------------------------------------- +log "scale-up: a burst of tasks on the task pool (from $(md_replicas sandbox) nodes)" +helm upgrade "$RELEASE" "$ROOT/deploy/helm/artex" "${base_values[@]}" "${pool_values[@]}" \ + --set sandbox.scaling.idleTimeout=60s --set sandbox.scaling.maxActive=10 --wait --timeout 10m >/dev/null +wk -n "$NS" rollout status "deploy/$RELEASE-runner" --timeout=180s >/dev/null +start_pf "$NS" "$RELEASE-runner" +run=$(date +%s) +BURST=${BURST:-6} +snapshot 1-before-scale-up +start=$(now) +jobs_=() +for i in $(seq 1 "$BURST"); do + exec_task "su-$run-$i" "echo su-$run-$i > /workspace/marker; $PROBE" >"$WORKDIR/burst-$i.out" & + jobs_+=("$!") +done +(sleep 45 && snapshot 2-during-scale-up-pending) & +jobs_+=("$!") +wait_jobs "${jobs_[@]}" +took=$(($(now) - start)) +snapshot 3-after-scale-up +ok=0 +for i in $(seq 1 "$BURST"); do + read -r code json <"$WORKDIR/burst-$i.out" + if [ "$code" = 200 ] && grep -q 'direct=BLOCKED' <<<"$json" && grep -q 'out_of_scope=403' <<<"$json" && + grep -q "marker=su-$run-$i" <<<"$json"; then + ok=$((ok + 1)) + else + note "burst task $i: $code $json" + fi +done +peak=$(md_replicas sandbox) +nodes_used=$(wk -n "$NS" get pods -l artex.managed_by=artex-runner -o jsonpath='{range .items[*]}{.spec.nodeName}{"\n"}{end}' | sort -u | tr '\n' ' ') +cold=$(curl -s -H "Authorization: Bearer $TOKEN" "http://127.0.0.1:$pf_port/v1/tasks" | jq -c '.scaling.cold_start | {count, p50_ms, p95_ms}') +note "scale-up: $ok/$BURST commands ran (isolated, workspace written) in ${took}s; task pool at $peak nodes; task pods on: $nodes_used; cold start $cold" +[ "$ok" = "$BURST" ] || fail "scale-up: only $ok of $BURST commands succeeded" +[ "$peak" -gt 0 ] || fail "scale-up: the task pool did not grow" +for n in $nodes_used; do + [ "$(wk get node "$n" -o jsonpath='{.metadata.labels.node\.cluster\.x-k8s\.io/pool}')" = sandbox ] || fail "task pod on non-pool node $n" +done + +# --- 3. scale-down and resume ---------------------------------------------------- +log "scale-down: idle tasks scale to zero, then the task pool goes back to zero nodes" +start=$(now) +wait_for 300 "idle scale-to-zero" sh -c "[ -z \"\$(kubectl --kubeconfig '$WL_KC' -n '$NS' get pods -l artex.managed_by=artex-runner -o name)\" ]" +pods_gone=$(($(now) - start)) +snapshot 4-tasks-scaled-to-zero +wait_for 900 "the task pool at zero nodes" sh -c "[ \"\$(kubectl --kubeconfig '$MGMT_KC' get machines -l cluster.x-k8s.io/deployment-name=$CLUSTER-sandbox -o name | wc -l)\" -eq 0 ]" +note "scale-down: task pods gone ${pods_gone}s after the burst ended (idle timeout 60s); task pool at 0 machines $(($(now) - start))s after the burst ended" +snapshot 5-after-scale-down +start=$(now) +read -r code json < <(exec_task "su-$run-1" "$PROBE") +if ! grep -q "marker=su-$run-1" <<<"$json" || ! grep -q "direct=BLOCKED" <<<"$json"; then + fail "resume: $code $json" +fi +note "resume from a zero-node pool: workspace intact, isolation holds, $(($(now) - start))s" +stop_pf + +# --- 4. ReadWriteOnce --------------------------------------------------------------- +log "ReadWriteOnce: task pods pinned to the runner's node" +rwo=$RELEASE-rwo +wk create namespace "$rwo" --dry-run=client -o yaml | wk apply -f - >/dev/null +helm upgrade --install "$rwo" "$ROOT/deploy/helm/artex" --kubeconfig "$WL_KC" -n "$rwo" \ + --set "images.runner.repository=$IMG/artex-runner" --set "images.runner.tag=$TAG" \ + --set "images.worker.repository=$IMG/artex-worker" --set "images.worker.tag=$TAG" \ + --set "images.egressProxy.repository=$IMG/artex-egress-proxy" --set "images.egressProxy.tag=$TAG" \ + --set "images.artex.repository=$IMG/artex" --set "images.artex.tag=$TAG" --set images.pullPolicy=Always \ + --set panel.replicas=0 --set persistence.data.accessMode=ReadWriteOnce --set persistence.data.storageClass=nfs-csi \ + --set sandbox.podReadyTimeout=90s --set sandbox.worker.cpuRequest=500m >/dev/null +wk -n "$rwo" rollout status "deploy/$rwo-runner" --timeout=300s >/dev/null +TOKEN=$(wk -n "$rwo" get secret "$rwo-secrets" -o jsonpath='{.data.ARTEX_RUNNER_TOKEN}' | base64 -d) +start_pf "$rwo" "$rwo-runner" +md0_before=$(md_replicas md-0) +jobs_=() +for i in 1 2 3 4 5; do + exec_task "rwo-$run-$i" 'true' >"$WORKDIR/rwo-$i.out" & + jobs_+=("$!") +done +(sleep 60 && snapshot 6-rwo-pending) & +jobs_+=("$!") +wait_jobs "${jobs_[@]}" +codes=$(cut -d' ' -f1 "$WORKDIR"/rwo-*.out | sort | uniq -c | tr -s ' ' | tr '\n' ';') +md0_after=$(md_replicas md-0) +nottrig=$(wk -n "$rwo" get events --field-selector reason=NotTriggerScaleUp -o name | wc -l) +note "ReadWriteOnce: HTTP codes [$codes] md-0 replicas $md0_before -> $md0_after, NotTriggerScaleUp events: $nottrig" +grep -h '^429' "$WORKDIR"/rwo-*.out | head -1 | cut -c1-300 | tee -a "$RESULTS" +[ "$md0_after" = "$md0_before" ] || fail "ReadWriteOnce: the autoscaler added base nodes for pinned pods" +grep -q '^429' "$WORKDIR"/rwo-*.out || fail "ReadWriteOnce: expected HTTP 429 for pods with no room on the runner's node" +stop_pf +helm uninstall "$rwo" --kubeconfig "$WL_KC" -n "$rwo" >/dev/null +wk delete namespace "$rwo" --wait=false >/dev/null + +ca_deploy=$(mk get deploy -n default -o name | grep cluster-autoscaler | head -1) +mk -n default logs "$ca_deploy" --since=2h | + grep -E 'Final scale-up plan|Scale-up: setting|Scale-down: removing|cannot be removed|is unneeded since|No expansion options|NodeAffinity. didn.t pass' | + grep -v reflector | cut -c1-260 >"$WORKDIR/ca-autoscaler-log.txt" || true + +log "all checks passed; results in $RESULTS, snapshots and autoscaler log in $WORKDIR/ca-*.txt" diff --git a/scripts/k3d-e2e.sh b/scripts/k3d-e2e.sh index 195c57051..7096eec0d 100755 --- a/scripts/k3d-e2e.sh +++ b/scripts/k3d-e2e.sh @@ -57,7 +57,9 @@ set_args=(--set images.pullPolicy=Never --set images.artex.repository=artex --set images.artex.tag=local --set images.runner.repository=artex-runner --set images.runner.tag=local --set images.worker.repository=artex-worker --set images.worker.tag=local - --set images.egressProxy.repository=artex-egress-proxy --set images.egressProxy.tag=local) + --set images.egressProxy.repository=artex-egress-proxy --set images.egressProxy.tag=local + # Short enough for the scaling subtests of TestKubeSandboxE2E to run. + --set "sandbox.scaling.idleTimeout=${E2E_IDLE_TIMEOUT:-30s}" --set "sandbox.scaling.maxActive=${E2E_MAX_ACTIVE:-2}") if [ "${RUNNER_ONLY:-0}" = "1" ]; then # No panel: the keys volume never binds (WaitForFirstConsumer), so wait on the # workloads instead of helm --wait. diff --git a/server/sandbox_overview.go b/server/sandbox_overview.go index d8e473edc..de49dd7c3 100644 --- a/server/sandbox_overview.go +++ b/server/sandbox_overview.go @@ -8,6 +8,8 @@ import ( "io" "net/http" "os" + "path/filepath" + "strings" "syscall" "time" "unicode/utf8" @@ -26,6 +28,10 @@ const ( sandboxEgressMaxField = 255 sandboxEgressFile = "egress.jsonl" sandboxAuditDirName = "egress-audit" + // The runner already bounds its scale history; the panel bounds it again + // rather than relay whatever a newer or misbehaving runner sends. + sandboxScaleMaxEvents = 100 + sandboxScaleMaxSamples = 100 ) // sandboxTasksLister is the optional runner-client capability behind the @@ -80,7 +86,47 @@ type sandboxOverviewDTO struct { StatusError string `json:"status_error,omitempty"` Tasks []sandboxTaskDTO `json:"tasks"` TasksTruncated bool `json:"tasks_truncated"` - GeneratedAt string `json:"generated_at"` + // Summary counts the listed tasks by health (sandbox.TaskSummary): use + // summary.healthy of summary.expected for "N of M healthy", so tasks scaled + // to zero or queued count neither as healthy nor as failing. + Summary sandbox.TaskSummary `json:"summary"` + // Scaling is absent when the runner predates scaling; its Supported is false + // on a backend without it (Docker). + Scaling *sandbox.ScalingStatus `json:"scaling,omitempty"` + GeneratedAt string `json:"generated_at"` +} + +// boundScaling copies the runner's scaling status with its lists capped (the +// newest entries win), never nil, and without events whose task id or kind the +// panel would not accept. +func boundScaling(in *sandbox.ScalingStatus) *sandbox.ScalingStatus { + if in == nil { + return nil + } + out := *in + out.Events = []sandbox.ScaleEvent{} + for _, e := range in.Events { + switch e.Kind { + case sandbox.ScaleKindUp, sandbox.ScaleKindDown, sandbox.ScaleKindUpFailed: + default: + continue + } + if !validAuditTaskID(e.TaskID) { + continue + } + e.Time, e.Reason, e.Error = clipField(e.Time), clipField(e.Reason), clipField(e.Error) + out.Events = append(out.Events, e) + } + if n := len(out.Events); n > sandboxScaleMaxEvents { + out.Events = out.Events[n-sandboxScaleMaxEvents:] + } + samples := in.ColdStart.SamplesMS + if n := len(samples); n > sandboxScaleMaxSamples { + samples = samples[n-sandboxScaleMaxSamples:] + } + out.ColdStart.SamplesMS = append([]int64{}, samples...) + out.Totals.Since = clipField(out.Totals.Since) + return &out } // sandboxErrorCode maps a runner client error to a stable code. The raw error @@ -152,6 +198,7 @@ func (s *Server) sandboxOverview(w http.ResponseWriter, r *http.Request) { out.Backend = res.Backend out.Namespace = res.Namespace out.StatusSupported = res.Supported + out.Scaling = boundScaling(res.Scaling) if !res.Supported { out.StatusError = "unsupported" } @@ -176,6 +223,9 @@ func (s *Server) sandboxOverview(w http.ResponseWriter, r *http.Request) { if ts.ScopeCIDRs == nil { ts.ScopeCIDRs = []string{} } + if ts.Health == "" { + ts.Health = sandbox.TaskHealth(ts) // runner predates health + } dto := sandboxTaskDTO{TaskStatus: ts, Egress: readEgressTail(root, ts.TaskID)} if n, ok := names[ts.TaskID]; ok { dto.TaskName = n.name @@ -183,6 +233,11 @@ func (s *Server) sandboxOverview(w http.ResponseWriter, r *http.Request) { } out.Tasks = append(out.Tasks, dto) } + listed := make([]sandbox.TaskStatus, len(out.Tasks)) + for i := range out.Tasks { + listed[i] = out.Tasks[i].TaskStatus + } + out.Summary = sandbox.SummarizeTasks(listed) writeJSON(w, 200, out) } @@ -192,6 +247,16 @@ func validAuditTaskID(id string) bool { return sandbox.ValidateTaskID(id) == nil } +// sandboxAuditRoot is the egress audit directory the panel reads: the runner's +// ARTEX_AUDIT_ROOT when it is set for the panel too (a deployment that moves the +// audit logs off /egress-audit), else /egress-audit. +func sandboxAuditRoot(dataDir string) string { + if v := strings.TrimSpace(os.Getenv(sandbox.EnvAuditRoot)); v != "" { + return filepath.Clean(v) + } + return filepath.Join(dataDir, sandboxAuditDirName) +} + type sandboxTaskName struct{ name, status string } // sandboxTaskNames maps ARTEX task ids to their name and status from memory. diff --git a/server/sandbox_overview_summary_test.go b/server/sandbox_overview_summary_test.go new file mode 100644 index 000000000..4ccd0f0c1 --- /dev/null +++ b/server/sandbox_overview_summary_test.go @@ -0,0 +1,42 @@ +package server + +import ( + "reflect" + "strings" + "testing" + + "github.com/Autumn-27/artex/sandbox" +) + +// A scaled-to-zero task keeps its last-applied scope and counts neither as +// healthy nor as failing: "N of M healthy" uses summary.expected. +func TestSandboxOverviewSummaryAndLastAppliedScope(t *testing.T) { + ready := sandbox.ComponentStatus{State: "Running", Ready: true} + client := healthyClient( + sandbox.TaskStatus{TaskID: "1", Tracked: true, Worker: ready, Proxy: ready, ScalingState: sandbox.ScaleStateActive, + ScopeSource: sandbox.ScopeSourceLive, Health: sandbox.HealthHealthy}, + sandbox.TaskStatus{TaskID: "2", Tracked: true, ScalingState: sandbox.ScaleStateZero, + Worker: sandbox.ComponentStatus{State: sandbox.StateMissing}, Proxy: sandbox.ComponentStatus{State: sandbox.StateMissing}, + ScopeDomains: []string{"app.example.net"}, ScopeKnown: true, ScopeSource: sandbox.ScopeSourceLastApplied, Health: sandbox.HealthScaledToZero}, + // From a runner that predates health: the panel classifies it. + sandbox.TaskStatus{TaskID: "3", Tracked: true, ScalingState: sandbox.ScaleStateActive, Worker: ready, + Proxy: sandbox.ComponentStatus{State: "Pending"}}, + ) + s := &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: client, auditRoot: t.TempDir()} + out, raw := getOverview(t, s) + want := sandbox.TaskSummary{Total: 3, Expected: 2, Healthy: 1, Degraded: 1, ScaledToZero: 1} + if out.Summary != want { + t.Fatalf("summary = %+v, want %+v", out.Summary, want) + } + if t2 := out.Tasks[1]; !reflect.DeepEqual(t2.ScopeDomains, []string{"app.example.net"}) || t2.ScopeSource != sandbox.ScopeSourceLastApplied || t2.Health != sandbox.HealthScaledToZero { + t.Fatalf("task 2 = %+v", t2.TaskStatus) + } + if out.Tasks[2].Health != sandbox.HealthDegraded { + t.Fatalf("task 3 health = %q", out.Tasks[2].Health) + } + for _, k := range []string{`"summary":{"total":3,"expected":2,"healthy":1,"degraded":1,"starting":0,"queued":0,"scaled_to_zero":1}`, `"scope_known":true,"scope_source":"last_applied"`, `"health":"scaled_to_zero"`} { + if !strings.Contains(raw, k) { + t.Fatalf("overview is missing %s: %s", k, raw) + } + } +} diff --git a/server/sandbox_overview_test.go b/server/sandbox_overview_test.go index 14a7cc845..a5de9b502 100644 --- a/server/sandbox_overview_test.go +++ b/server/sandbox_overview_test.go @@ -295,6 +295,28 @@ func TestSandboxOverviewMissingAuditRoot(t *testing.T) { } } +// TestSandboxAuditRootHonoursEnv: the panel reads the egress logs where +// ARTEX_AUDIT_ROOT says, like the runner, and /egress-audit without it. +func TestSandboxAuditRootHonoursEnv(t *testing.T) { + data := t.TempDir() + t.Setenv(sandbox.EnvAuditRoot, "") + if got := sandboxAuditRoot(data); got != filepath.Join(data, "egress-audit") { + t.Fatalf("default audit root = %q", got) + } + custom := filepath.Join(t.TempDir(), "audit") + t.Setenv(sandbox.EnvAuditRoot, " "+custom+"/ ") + if got := sandboxAuditRoot(data); got != custom { + t.Fatalf("audit root with %s = %q", sandbox.EnvAuditRoot, got) + } + // End to end through the handler: logs under the custom root are read. + writeAudit(t, custom, "7", egressLine("custom.test", "allow", 1)) + s := &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: healthyClient(sandbox.TaskStatus{TaskID: "7"}), auditRoot: sandboxAuditRoot(data)} + out, _ := getOverview(t, s) + if len(out.Tasks) != 1 || !out.Tasks[0].Egress.Available || out.Tasks[0].Egress.Allow != 1 { + t.Fatalf("custom audit root not read: %+v", out.Tasks) + } +} + func TestSandboxOverviewHostileTaskIDs(t *testing.T) { base := t.TempDir() root := filepath.Join(base, "egress-audit") @@ -612,3 +634,100 @@ func (overviewBackend) Delete(context.Context, string) error { return nil } func (overviewBackend) Status(context.Context) (sandbox.TasksResponse, error) { return sandbox.TasksResponse{Backend: "fake", Tasks: []sandbox.TaskStatus{{TaskID: "55", Worker: sandbox.ComponentStatus{Name: "w55", State: "Running", Ready: true}}}}, nil } + +func TestSandboxOverviewScaling(t *testing.T) { + // A runner without scaling: the key is absent, not null. + client := healthyClient(sandbox.TaskStatus{TaskID: "1"}) + s := &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: client} + out, raw := getOverview(t, s) + if out.Scaling != nil || strings.Contains(raw, `"scaling"`) { + t.Fatalf("scaling without runner support: %s", raw) + } + + // Docker: present and unsupported. + client.tasks.Scaling = &sandbox.ScalingStatus{} + out, raw = getOverview(t, s) + if out.Scaling == nil || out.Scaling.Supported || !strings.Contains(raw, `"events":[]`) || !strings.Contains(string(raw), `"samples_ms":[]`) { + t.Fatalf("unsupported scaling = %s", raw) + } + + client.tasks.Tasks = []sandbox.TaskStatus{ + {TaskID: "1", ScalingState: sandbox.ScaleStateActive, InFlight: 2, LastActivity: "2026-12-01T10:00:00Z"}, + {TaskID: "2", ScalingState: sandbox.ScaleStateActive, LastActivity: "2026-12-01T09:50:00Z", IdleExpiresAt: "2026-12-01T10:05:00Z"}, + {TaskID: "3", ScalingState: sandbox.ScaleStateZero}, + } + client.tasks.Scaling = &sandbox.ScalingStatus{ + Supported: true, IdleTimeoutSeconds: 900, MaxActive: 10, QueueTimeoutSeconds: 120, + Active: 2, Starting: 1, Queued: 3, ScaledToZero: 1, + ColdStart: sandbox.ColdStartStats{Count: 2, LastMS: 9000, P50MS: 4000, P95MS: 9000, SamplesMS: []int64{4000, 9000}}, + Events: []sandbox.ScaleEvent{ + {Time: "2026-12-01T09:00:00Z", TaskID: "3", Kind: sandbox.ScaleKindUp, Reason: sandbox.ScaleReasonFirstExec, DurationMS: 4000}, + {Time: "2026-12-01T09:30:00Z", TaskID: "3", Kind: sandbox.ScaleKindDown, Reason: sandbox.ScaleReasonIdle}, + {Time: "2026-12-01T09:31:00Z", TaskID: "../etc", Kind: sandbox.ScaleKindDown, Reason: sandbox.ScaleReasonIdle}, + {Time: "2026-12-01T09:32:00Z", TaskID: "3", Kind: "explode", Reason: "x"}, + {Time: "2026-12-01T09:33:00Z", TaskID: "2", Kind: sandbox.ScaleKindUp, Reason: strings.Repeat("r", 1000), DurationMS: 9000, QueueMS: 1500}, + {Time: "2026-12-01T09:34:00Z", TaskID: " 3", Kind: sandbox.ScaleKindDown, Reason: sandbox.ScaleReasonIdle}, + {Time: "2026-12-01T09:35:00Z", TaskID: "4", Kind: sandbox.ScaleKindUpFailed, Reason: sandbox.ScaleReasonFirstExec, DurationMS: 700, Error: strings.Repeat("e", 1000)}, + }, + Totals: sandbox.ScaleTotals{ScaleUps: 7, ScaleDowns: 5, ScaleUpFailures: 1, Since: "2026-11-01T00:00:00Z"}, + Persisted: true, + } + out, raw = getOverview(t, s) + sc := out.Scaling + if sc == nil || !sc.Supported || sc.IdleTimeoutSeconds != 900 || sc.MaxActive != 10 || sc.QueueTimeoutSeconds != 120 || + sc.Active != 2 || sc.Starting != 1 || sc.Queued != 3 || sc.ScaledToZero != 1 { + t.Fatalf("scaling = %+v", sc) + } + if sc.ColdStart.Count != 2 || sc.ColdStart.P50MS != 4000 || sc.ColdStart.P95MS != 9000 || len(sc.ColdStart.SamplesMS) != 2 { + t.Fatalf("cold start = %+v", sc.ColdStart) + } + if len(sc.Events) != 4 || sc.Events[0].DurationMS != 4000 || sc.Events[1].Reason != sandbox.ScaleReasonIdle || + sc.Events[2].QueueMS != 1500 || len(sc.Events[2].Reason) != sandboxEgressMaxField { + t.Fatalf("events = %+v", sc.Events) + } + // Failed scale-ups are relayed with a bounded error; totals and persisted too. + if f := sc.Events[3]; f.Kind != sandbox.ScaleKindUpFailed || f.TaskID != "4" || len(f.Error) != sandboxEgressMaxField { + t.Fatalf("failed event = %+v", f) + } + if !sc.Persisted || sc.Totals.ScaleUps != 7 || sc.Totals.ScaleUpFailures != 1 || sc.Totals.Since != "2026-11-01T00:00:00Z" { + t.Fatalf("totals = %+v persisted=%v", sc.Totals, sc.Persisted) + } + if strings.Contains(raw, "../etc") || strings.Contains(string(raw), "explode") { + t.Fatalf("unvalidated event relayed: %s", raw) + } + // Per-task scaling fields travel with the task. + var doc struct { + Tasks []map[string]any `json:"tasks"` + } + if err := json.Unmarshal([]byte(raw), &doc); err != nil { + t.Fatal(err) + } + if tk := doc.Tasks[0]; tk["scaling_state"] != "active" || tk["in_flight"] != 2.0 || tk["last_activity"] != "2026-12-01T10:00:00Z" { + t.Fatalf("task 1 = %v", tk) + } + if tk := doc.Tasks[1]; tk["idle_expires_at"] != "2026-12-01T10:05:00Z" { + t.Fatalf("task 2 = %v", tk) + } + if tk := doc.Tasks[2]; tk["scaling_state"] != "scaled_to_zero" { + t.Fatalf("task 3 = %v", tk) + } + + // Oversized history is cut to the newest entries; the runner's copy is untouched. + big := &sandbox.ScalingStatus{Supported: true} + for i := range 3 * sandboxScaleMaxEvents { + big.Events = append(big.Events, sandbox.ScaleEvent{TaskID: "1", Kind: sandbox.ScaleKindUp, Reason: "resume", DurationMS: int64(i)}) + big.ColdStart.SamplesMS = append(big.ColdStart.SamplesMS, int64(i)) + } + client.tasks.Scaling = big + out, _ = getOverview(t, s) + last := int64(3*sandboxScaleMaxEvents - 1) + if n := len(out.Scaling.Events); n != sandboxScaleMaxEvents || out.Scaling.Events[n-1].DurationMS != last { + t.Fatalf("bounded events = %d", n) + } + if n := len(out.Scaling.ColdStart.SamplesMS); n != sandboxScaleMaxSamples || out.Scaling.ColdStart.SamplesMS[n-1] != last { + t.Fatalf("bounded samples = %d", n) + } + if len(big.Events) != 3*sandboxScaleMaxEvents { + t.Fatal("boundScaling modified its input") + } +} diff --git a/server/server.go b/server/server.go index db0f8d307..ae9453133 100644 --- a/server/server.go +++ b/server/server.go @@ -61,7 +61,8 @@ type Server struct { sandboxMode string sandboxClient SandboxClient // result of the startup isolation self-test (isolation.go); zero when not run // auditRoot is the egress audit directory the per-task proxies write to - // (/egress-audit); read-only for the panel (sandbox_overview.go). + // (ARTEX_AUDIT_ROOT, else /egress-audit); read-only for the panel + // (sandbox_overview.go). auditRoot string chatBridges *chatBridgeRunner // inbound chat bridges (issue #5); nil without PostgreSQL @@ -226,7 +227,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi } s.engine.SetKillSwitchConfig(dataDir, s.execPriv) s.engine.SetSandbox(s.sandboxClient, s.sandboxMode, dataDir) - s.auditRoot = filepath.Join(dataDir, sandboxAuditDirName) + s.auditRoot = sandboxAuditRoot(dataDir) if s.sandboxMode != "" { agent.SetSandboxExecutor(&agent.SandboxExecutor{ Mode: s.sandboxMode, From db730115fc544569a5784a7d24dc55c4e2a8a682 Mon Sep 17 00:00:00 2001 From: Marco Azarmaneche <306425250+thecorporatetractor@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:46:35 +0200 Subject: [PATCH 5/6] feat(web): Sandbox page under System System > Sandbox shows the panel, the runner, each task with its worker and egress proxy, and the internet, from /api/sandbox/overview every 3 s. The graph view (xyflow) can be panned and zoomed; links move while a command runs or traffic passes, refused egress goes to a Blocked node, and scaled-to-zero tasks are dimmed. The list view is an operator table with per-task health, scope, policies and recent egress, and is what phones get. Every node and row opens a details drawer. The Scaling section shows capacity against the cap, cold start p50/p95 and trend, per-task idle countdowns and the scale event timeline. The page also fits the Docker backend (which does not scale) and a runner that is down. The topology and summary logic lives in lib/sandbox-topology.ts with node tests (test:sandbox-topology, added to CI). The mock backend serves Kubernetes and Docker overviews, and ?tasks=N for a crowded graph. Strings are translated for tr, vi, zh-CN and pt-BR. --- .github/workflows/ci.yml | 1 + CHANGELOG.md | 1 + web/package.json | 3 +- .../sandbox/_components/details-sheet.tsx | 347 +++++ .../sandbox/_components/egress-table.tsx | 362 +++++ .../sandbox/_components/scaling-panel.tsx | 450 ++++++ .../system/sandbox/_components/shared.tsx | 497 ++++++ .../sandbox/_components/summary-strip.tsx | 123 ++ .../system/sandbox/_components/task-table.tsx | 451 ++++++ .../sandbox/_components/topology-graph.tsx | 464 ++++++ web/src/app/(main)/system/sandbox/page.tsx | 350 +++++ web/src/i18n/locales/pt-BR.json | 199 ++- web/src/i18n/locales/tr.json | 199 ++- web/src/i18n/locales/vi.json | 199 ++- web/src/i18n/locales/zh-CN.json | 199 ++- web/src/lib/api.ts | 4 + web/src/lib/mock/handler.ts | 9 + web/src/lib/mock/sandbox.ts | 377 +++++ web/src/lib/sandbox-topology.test.mjs | 1364 +++++++++++++++++ web/src/lib/sandbox-topology.ts | 1109 ++++++++++++++ web/src/navigation/sidebar/sidebar-items.ts | 2 + 21 files changed, 6705 insertions(+), 5 deletions(-) create mode 100644 web/src/app/(main)/system/sandbox/_components/details-sheet.tsx create mode 100644 web/src/app/(main)/system/sandbox/_components/egress-table.tsx create mode 100644 web/src/app/(main)/system/sandbox/_components/scaling-panel.tsx create mode 100644 web/src/app/(main)/system/sandbox/_components/shared.tsx create mode 100644 web/src/app/(main)/system/sandbox/_components/summary-strip.tsx create mode 100644 web/src/app/(main)/system/sandbox/_components/task-table.tsx create mode 100644 web/src/app/(main)/system/sandbox/_components/topology-graph.tsx create mode 100644 web/src/app/(main)/system/sandbox/page.tsx create mode 100644 web/src/lib/mock/sandbox.ts create mode 100644 web/src/lib/sandbox-topology.test.mjs create mode 100644 web/src/lib/sandbox-topology.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0012a95e6..d35299705 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -279,6 +279,7 @@ jobs: - run: npm run test:chat-mentions - run: npm run test:format - run: npm run test:http-href + - run: npm run test:sandbox-topology - run: npm run build:static python: diff --git a/CHANGELOG.md b/CHANGELOG.md index 14b467fbf..e2969b072 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented in this file. The format is b - **Kubernetes sandbox backend for `artex-runner`.** With `ARTEX_RUNNER_BACKEND=kubernetes` each task runs in a worker pod behind its own egress-proxy pod, created through the Kubernetes API with no container runtime socket. The worker runs as uid/gid 10001 with `runAsNonRoot`, a read-only root filesystem, all capabilities dropped, `seccomp: RuntimeDefault`, no service-account token and no service links, and mounts only its task directory. Per-task NetworkPolicies are created before the pods and deleted after them: the worker can reach only its own proxy, and the proxy only cluster DNS, public addresses and the task's scope CIDRs. The runner waits until the policies are in effect before the first command, runs commands through `pods/exec`, and re-adopts task pods after a restart. - **Helm chart for Kubernetes.** `deploy/helm/artex` deploys the panel, PostgreSQL and `artex-runner` with the Kubernetes sandbox backend, a namespace-scoped Role, NetworkPolicies and a values schema. A chart-level default-deny covers every runner-managed pod, so a missing per-task policy fails closed. The `volume-permissions` init container fixes the `Bash can create files in /app/data` self-test failure on world-writable volumes (#620). `scripts/k3d-e2e.sh` and the new `kubernetes` CI job test the chart live on k3d. +- **Sandbox page and Kubernetes sandbox scaling.** The runner's new `GET /v1/tasks` and the panel's `GET /api/sandbox/overview` report each task's pods, scope, network policies, health and recent egress, and **System > Sandbox** shows them as a graph or a list for the Docker and Kubernetes backends. On Kubernetes the runner scales a task to zero after `sandbox.scaling.idleTimeout` (`ARTEX_KUBE_IDLE_TIMEOUT`, default 15 minutes) without a command and starts its pods again on the next one. `sandbox.scaling.maxActive` (`ARTEX_KUBE_MAX_ACTIVE`, default 10) caps the tasks with pods: the least recently used idle task is scaled to zero, or the command waits for `sandbox.scaling.queueTimeout` and fails with HTTP 429 `sandbox at capacity`, which does not pause the task. A task pod still unschedulable at `sandbox.podReadyTimeout` also fails with 429 and is kept for the next command. Scale events, totals and cold-start times survive a runner restart (`ARTEX_KUBE_STATE_DIR`, `runner-state` on the data volume). `sandbox.nodeSelector`, `tolerations`, `priorityClassName` and `podAnnotations` support autoscaled node pools; the chart README documents cluster-autoscaler settings, tested with `scripts/capd-autoscaler-e2e.sh`. ### Security diff --git a/web/package.json b/web/package.json index 807e14a5f..99feeb5ca 100644 --- a/web/package.json +++ b/web/package.json @@ -29,7 +29,8 @@ "test:activity-merge": "node --test src/lib/activity-merge.test.mjs", "test:chat-mentions": "node --test src/lib/chat-mentions.test.mjs", "test:format": "node --test src/lib/format.test.mjs", - "test:http-href": "node --test src/lib/http-href.test.mjs" + "test:http-href": "node --test src/lib/http-href.test.mjs", + "test:sandbox-topology": "node --test src/lib/sandbox-topology.test.mjs" }, "lint-staged": { "*.{js,ts,jsx,tsx}": ["biome check --write --no-errors-on-unmatched"] diff --git a/web/src/app/(main)/system/sandbox/_components/details-sheet.tsx b/web/src/app/(main)/system/sandbox/_components/details-sheet.tsx new file mode 100644 index 000000000..b7cb8d8e0 --- /dev/null +++ b/web/src/app/(main)/system/sandbox/_components/details-sheet.tsx @@ -0,0 +1,347 @@ +"use client"; + +import * as React from "react"; + +import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"; +import { t } from "@/i18n"; +import { formatDurationMs } from "@/lib/format"; +import { + type ComponentModel, + egressRows, + filterEgress, + groupDestinations, + idleRemaining, + lastActivityAt, + type TaskModel, + type TopologyModel, +} from "@/lib/sandbox-topology"; +import { cn } from "@/lib/utils"; + +import { + DecisionMark, + DestinationList, + formatCountdown, + HealthBadge, + RelativeTime, + ScalingBadge, + ScopeChips, + StatusDot, + stateLabel, + TaskStatusBadge, + toneText, + unitWords, +} from "./shared"; +import type { Selection } from "./topology-graph"; + +function Section({ + title, + highlight = false, + children, +}: { + title: string; + highlight?: boolean; + children: React.ReactNode; +}) { + return ( +
+

{title}

+ {children} +
+ ); +} + +function Row({ label, children, mono = false }: { label: string; children: React.ReactNode; mono?: boolean }) { + return ( +
+
{label}
+
{children}
+
+ ); +} + +function PodFacts({ c, ghost, docker }: { c: ComponentModel; ghost: boolean; docker: boolean }) { + return ( +
+ + {c.name || "–"} + + + + + {stateLabel(c, ghost)} + + + {c.tone !== "missing" && {c.ready ? t("Yes") : t("No")}} + {c.ageMs !== null && {formatDurationMs(c.ageMs)}} + {c.node && ( + + {c.node} + + )} + {c.ip && ( + + {c.ip} + + )} +
+ ); +} + +function TaskDetails({ + task, + focus, + elapsedMs, + refMs, + docker, + scales, +}: { + docker: boolean; + /** The backend scales sandboxes: only then are scaling facts worth a row. */ + scales: boolean; + task: TaskModel; + focus: Selection["kind"]; + elapsedMs: number; + refMs: number; +}) { + const remaining = idleRemaining(task, elapsedMs); + const now = refMs + elapsedMs; + const destinations = React.useMemo(() => groupDestinations(egressRows([task])), [task]); + const activity = lastActivityAt(task, refMs); + return ( + <> +
+
+ + + + {task.scaling.state !== "unknown" && task.scaling.state !== task.health && ( + + + + )} + {scales && {task.scaling.inFlight}} + {activity !== null && ( + + + + )} + {remaining !== null && {formatCountdown(remaining)}} + {!task.tracked && {t("Not tracked by the runner")}} +
+
+
+ +
+
+ +
+ {task.proxyAddr && ( + + {task.proxyAddr} + + )} +
+
+
+
+ +
+ {task.scope.state === "unknown" && ( +

+ {t("The runner reports the scope of a running egress proxy. This sandbox has none right now.")} +

+ )} + {task.scope.stale && ( +

+ {t("Last applied scope; no proxy is running to enforce it now.")} +

+ )} + {task.scope.hash && ( +
+ + {task.scope.hash} + +
+ )} +
+ {(task.policies.length > 0 || task.network) && ( +
+
+ {task.policies.map((p) => ( + + {p} + + ))} + {task.network && ( + + {task.network} + + )} +
+
+ )} +
+

+ + + {t("{count} allowed", { count: task.egress.allow })} + + + + {t("{count} denied", { count: task.egress.deny })} + + {task.egress.truncated && ( + {t("counted over the most recent log tail")} + )} +

+ {destinations.length === 0 ? ( +

+ {task.egress.available ? t("No connections recorded yet") : t("No egress log for this task yet")} +

+ ) : ( + + )} +
+ + ); +} + +function ControlPlane({ model, focus }: { model: TopologyModel; focus: Selection["kind"] }) { + const s = model.scaling; + return ( + <> +
+

+ {t("API, UI and database. Holds no cluster credentials.")}{" "} + {t("It reaches the sandbox only through the runner API.")} +

+
+
+
+ + + + {model.runner.tone === "ok" ? t("Healthy") : t("Unavailable")} + + + {model.backend && {model.backend}} + {model.namespace && ( + + {model.namespace} + + )} + {model.runner.version && ( + + {model.runner.version} + + )} + + {model.runner.workers} + + {s.supported && ( + <> + + {s.idleTimeoutMs > 0 ? formatDurationMs(s.idleTimeoutMs) : t("never scales down")} + + {s.capacity.max ?? t("no cap")} + {formatDurationMs(s.queueTimeoutMs)} + + )} +
+
+ + ); +} + +function EgressSink({ model, allowed, now }: { model: TopologyModel; allowed: boolean; now: number }) { + const destinations = React.useMemo( + () => groupDestinations(filterEgress(egressRows(model.tasks), { decision: allowed ? "allow" : "deny" })), + [model.tasks, allowed], + ); + return ( +
+

+ {allowed + ? t("Connections the egress proxies let through because the destination is in the task's scope.") + : t("Connections the egress proxies refused: out of scope, or a private or metadata address.")} +

+ {destinations.length === 0 ? ( +

{t("No connections recorded yet")}

+ ) : ( + + )} +
+ ); +} + +function titleOf(sel: Selection, task: TaskModel | undefined): { title: string; description: string } { + if (task) { + return { + title: `${t("Task #{id}", { id: task.id })}${task.name ? ` · ${task.name}` : ""}`, + description: t("Worker, egress proxy, scope and recent egress of this task's sandbox"), + }; + } + if (sel.kind === "internet") return { title: t("Internet"), description: t("Allowed egress across every sandbox") }; + if (sel.kind === "blocked") return { title: t("Blocked"), description: t("Refused egress across every sandbox") }; + return { title: t("Control plane"), description: t("The panel and the sandbox runner") }; +} + +/** Details of the clicked node. It reads the live model, so it keeps updating while open. */ +export function DetailsSheet({ + selection, + model, + elapsedMs, + opener, + onClose, +}: { + selection: Selection | null; + model: TopologyModel; + elapsedMs: number; + /** What had the focus when the drawer was opened; it gets the focus back on close. */ + opener: React.RefObject; + onClose: () => void; +}) { + const task = selection?.taskId ? model.tasks.find((x) => x.id === selection.taskId) : undefined; + const head = selection ? titleOf(selection, task) : { title: "", description: "" }; + const gone = !!selection?.taskId && !task; + return ( + !open && onClose()}> + { + const el = opener.current; + if (!el?.isConnected) return; + event.preventDefault(); + el.focus(); + }} + > + + + {task && } + {head.title} + {task?.status && } + + {head.description} + +
+ {gone &&

{t("This sandbox no longer exists.")}

} + {selection && task && ( + + )} + {selection && !selection.taskId && (selection.kind === "panel" || selection.kind === "runner") && ( + + )} + {selection?.kind === "internet" && } + {selection?.kind === "blocked" && } +
+
+
+ ); +} diff --git a/web/src/app/(main)/system/sandbox/_components/egress-table.tsx b/web/src/app/(main)/system/sandbox/_components/egress-table.tsx new file mode 100644 index 000000000..8ce7e0e74 --- /dev/null +++ b/web/src/app/(main)/system/sandbox/_components/egress-table.tsx @@ -0,0 +1,362 @@ +"use client"; + +import * as React from "react"; + +import { ChevronRight, Search, X } from "lucide-react"; + +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { SortableHead } from "@/components/ui/sortable-head"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { t } from "@/i18n"; +import { formatShortDateTime } from "@/lib/format"; +import { + DESTINATION_SORT_FIELDS, + type DecisionFilter, + type DestinationModel, + type DestinationSortField, + destinationTotals, + egressRows, + filterEgress, + groupDestinations, + sortDestinations, + type TopologyModel, +} from "@/lib/sandbox-topology"; +import { useStoredSortPreference } from "@/lib/sort-preference"; +import { cn } from "@/lib/utils"; + +import { bytesLabel, CountBar, DecisionMark, RelativeTime, Segmented } from "./shared"; + +const PAGE = 15; +const MAX_CONNECTIONS = 12; +const ALL_TASKS = "__all__"; + +function Destination({ d }: { d: DestinationModel }) { + return ( + + {d.host} + :{d.port} + + ); +} + +function Tasks({ d, names }: { d: DestinationModel; names: Map }) { + const title = d.taskIds.map((id) => `#${id} ${names.get(id) ?? ""}`.trim()).join(", "); + const shown = d.taskIds.slice(0, 3); + return ( + + {shown.map((id) => `#${id}`).join(" ")} + {d.taskIds.length > shown.length && ( + +{d.taskIds.length - shown.length} + )} + + ); +} + +/** The individual decisions behind one destination row. */ +function Connections({ d, names }: { d: DestinationModel; names: Map }) { + const shown = d.entries.slice(0, MAX_CONNECTIONS); + return ( +
+
    + {shown.map((e) => ( +
  • + + + #{e.taskId} + + + {[e.resolvedIp, e.protocol, e.bytes > 0 ? bytesLabel(e.bytes) : ""].filter(Boolean).join(" · ")} + +
  • + ))} +
+ {d.entries.length > shown.length && ( +

+ {t("and {count} earlier connections", { count: d.entries.length - shown.length })} +

+ )} +
+ ); +} + +/** + * Egress decisions of every sandbox, folded into one row per destination and outcome, + * with filters for the outcome, the task and free text. + */ +export function EgressTable({ + model, + elapsedMs, + compact, + taskId, + onTaskId, +}: { + model: TopologyModel; + elapsedMs: number; + compact: boolean; + /** The task filter lives with the page: a task row can set it. Empty for every task. */ + taskId: string; + onTaskId: (taskId: string) => void; +}) { + const [decision, setDecision] = React.useState("all"); + const [query, setQuery] = React.useState(""); + const [limit, setLimit] = React.useState(PAGE); + const [expanded, setExpanded] = React.useState>(() => new Set()); + const [sort, setSort] = useStoredSortPreference( + "artex.sandbox.egress-sort", + DESTINATION_SORT_FIELDS, + "last", + "desc", + ); + const now = model.ref + elapsedMs; + const names = React.useMemo(() => new Map(model.tasks.map((task) => [task.id, task.name])), [model.tasks]); + const rows = React.useMemo(() => egressRows(model.tasks), [model.tasks]); + // The outcome counts ignore the outcome filter itself, so each button says what it would show. + const scoped = React.useMemo(() => groupDestinations(filterEgress(rows, { taskId, query })), [rows, taskId, query]); + const counts = React.useMemo( + () => ({ + all: scoped.length, + allow: scoped.filter((d) => d.allowed).length, + deny: scoped.filter((d) => !d.allowed).length, + }), + [scoped], + ); + const list = React.useMemo(() => { + const filtered = decision === "all" ? scoped : scoped.filter((d) => d.allowed === (decision === "allow")); + return sortDestinations(filtered, sort.field, sort.direction); + }, [scoped, decision, sort]); + const totals = React.useMemo(() => destinationTotals(list), [list]); + const shown = list.slice(0, limit); + const filtered = decision !== "all" || taskId !== "" || query.trim() !== ""; + const tailed = model.tasks.some( + (task) => task.egress.truncated || task.egress.entries.length < task.egress.allow + task.egress.deny, + ); + + const onSort = (field: DestinationSortField) => + setSort((prev) => + prev.field === field + ? { field, direction: prev.direction === "asc" ? "desc" : "asc" } + : { field, direction: field === "destination" || field === "decision" ? "asc" : "desc" }, + ); + const toggle = (key: string) => + setExpanded((prev) => { + const next = new Set(prev); + if (!next.delete(key)) next.add(key); + return next; + }); + const reset = () => { + setDecision("all"); + setQuery(""); + onTaskId(""); + }; + const head = { activeField: sort.field, direction: sort.direction, onSort }; + + const emptyMessage = + rows.length === 0 + ? t("No connections recorded yet. Decisions appear here when a sandbox reaches for the network.") + : t("No destination matches these filters."); + + return ( +
+
+

+ {t("Egress")} +

+

+ {t("Where sandboxes tried to connect, one row per destination and outcome.")} + {tailed && + ` ${t("Rows cover the most recent decisions of each task; the totals above cover its whole log.")}`} +

+
+ +
+
+ + { + setQuery(e.target.value); + setLimit(PAGE); + }} + placeholder={t("Search host, port, address…")} + aria-label={t("Search destinations")} + className="h-8 pl-8" + /> +
+ { + setDecision(v); + setLimit(PAGE); + }} + options={[ + { id: "all", label: t("All"), count: counts.all }, + { id: "allow", label: t("Allowed"), count: counts.allow }, + { id: "deny", label: t("Denied"), count: counts.deny }, + ]} + /> + + {filtered && ( + + )} + + {/* The result count is announced when a filter changes it; the connection count moves with every poll. */} + {t("{count} destinations", { count: totals.destinations })} + {" · "} + {t("{count} connections", { count: totals.allow + totals.deny })} + +
+ + {list.length === 0 && ( +
+

{emptyMessage}

+ {rows.length > 0 && ( + + )} +
+ )} + {list.length > 0 && compact && ( +
    + {shown.map((d) => ( +
  • +
    + + + + + ×{d.count} +
    +
    + + {d.bytes > 0 && {bytesLabel(d.bytes)}} + {d.protocols.length > 0 && {d.protocols.join(", ")}} + +
    +
  • + ))} +
+ )} + {list.length > 0 && !compact && ( +
+ + + + + + {t("Expand")} + + + + {t("Tasks")} + + + {t("Protocol")} + {t("Resolved address")} + + + + + {shown.map((d) => { + const open = expanded.has(d.key); + const panel = `sandbox-destination-${d.key.replace(/[^a-z0-9]+/gi, "-")}`; + return ( + + toggle(d.key)} + > + + + + + + + + + + + + + + + + + {bytesLabel(d.bytes)} + + + {d.protocols.join(", ") || "–"} + + + {d.resolvedIps[0] ?? "–"} + {d.resolvedIps.length > 1 && ` +${d.resolvedIps.length - 1}`} + + + + + + {open && ( + + + + + + )} + + ); + })} + +
+ {t("Egress destinations with their outcome, connection count and last use")} +
+
+ )} + {list.length > shown.length && ( +
+ +
+ )} +
+ ); +} diff --git a/web/src/app/(main)/system/sandbox/_components/scaling-panel.tsx b/web/src/app/(main)/system/sandbox/_components/scaling-panel.tsx new file mode 100644 index 000000000..43667c228 --- /dev/null +++ b/web/src/app/(main)/system/sandbox/_components/scaling-panel.tsx @@ -0,0 +1,450 @@ +"use client"; + +import * as React from "react"; + +import { + ArrowDownToLine, + ArrowUpFromLine, + CircleAlert, + Gauge, + Hourglass, + Info, + Loader, + Moon, + Timer, +} from "lucide-react"; + +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { t } from "@/i18n"; +import { formatDurationMs, formatShortDateTime } from "@/lib/format"; +import { type CapacityLevel, type ScalingModel, sparkline, type TopologyModel } from "@/lib/sandbox-topology"; +import { cn } from "@/lib/utils"; + +import { formatMs, HealthBadge, IdleCell, RelativeTime, reasonLabel } from "./shared"; +import type { Selection } from "./topology-graph"; + +function Card({ title, icon: Icon, children, className }: React.ComponentProps<"section"> & { icon: typeof Gauge }) { + return ( +
+

+ + {title} +

+ {children} +
+ ); +} + +// The fill carries severity; the track is a lighter step of the same hue. +const meterFill: Record = { + ok: "bg-sky-600 dark:bg-sky-500", + high: "bg-amber-500", + full: "bg-red-500", +}; +const meterTrack: Record = { + ok: "bg-sky-500/15", + high: "bg-amber-500/20", + full: "bg-red-500/20", +}; + +function levelNote(s: ScalingModel): string { + if (s.capacity.max === null) return t("No cap: every task that runs a command gets pods."); + if (s.queued > 0) return t("Full and every sandbox is busy: new commands wait for a free slot."); + if (s.capacity.level === "full") + return t("Full: the next task takes the slot of the least recently used idle sandbox."); + if (s.capacity.level === "high") return t("Close to the cap."); + return t("Room for more sandboxes."); +} + +function Count({ icon: Icon, value, label }: { icon: typeof Gauge; value: number; label: string }) { + return ( +
+ + {value} + {label} +
+ ); +} + +function CapacityCard({ s }: { s: ScalingModel }) { + const { used, max, ratio, level } = s.capacity; + return ( + +
+ {used} + + {max === null ? t("sandboxes with pods") : t("of {max} sandboxes with pods", { max })} + +
+ {ratio !== null && max !== null && ( + <> + {/* The native meter is the accessible value; the bar below is its drawing. */} + + {t("Sandbox capacity in use")} + +