mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 12:24:44 +00:00
- Each worker and proxy pod gets a new name per generation (artex-w-<hash>-<6 hex>). Exec targets the exact pod of the task state, so an exec delayed at the API server fails with 404 instead of running in a replacement pod before that pod passed its network probes. - setupTask lists the task's pods by label and deletes every pod except the ones it keeps, with a UID precondition, before it creates new ones. Same-named pods are no longer deleted without an ownership check. - Recover adopts only pods whose name matches artex-[wp]-<32 hex>-<6 hex> and whose name, labels and task annotation agree. - podAlive returns an error for API failures. Only 404, a UID mismatch, a deletion timestamp, or a pod that is not running and ready count as dead. On other errors (a cancelled request too) the exec fails and the task's pods and policies stay. - waitPodReady fails fast on CrashLoopBackOff and on exited containers. - The deny probes print one token per outcome. Only timed out, refused or unroutable connections count as blocked. Any other result (missing timeout binary, failed fork, no API env) fails setup at once. - Probe output, stderr and HTTP client errors go to the runner log only. The returned errors are generic. A cancelled API request returns a cancellation error, not "runner unavailable". - Add fd20:ce::254/128 (GCE IPv6 metadata) to the never-reachable ranges. - Document that ARTEX_KUBE_CLUSTER_CIDRS must also list the API server endpoint addresses when they lie outside the cluster ranges (managed clusters). - Exec, Kill and Delete reject task IDs with surrounding whitespace. - go.mod: gopkg.in/yaml.v3 back to indirect (go mod tidy). - Test: a cancelled exec keeps the task. The scope and probe tests move to the test PR to stay inside the size limit.
189 lines
6.3 KiB
Go
189 lines
6.3 KiB
Go
package sandbox
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func newTestKubeBackend(t *testing.T, f *fakeKubeAPI, srv *httptest.Server, mods ...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)
|
|
}
|
|
cfg := 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,
|
|
allowPlainHTTP: true,
|
|
}
|
|
for _, m := range mods {
|
|
m(&cfg)
|
|
}
|
|
b, err := NewKubernetesBackend(cfg)
|
|
if err != nil {
|
|
t.Fatalf("NewKubernetesBackend: %v", err)
|
|
}
|
|
return b
|
|
}
|
|
|
|
func execReq(argv ...string) ExecRequest {
|
|
req := ExecRequest{Argv: argv}
|
|
if err := ValidateExecRequest(&req); err != nil {
|
|
panic(err)
|
|
}
|
|
return req
|
|
}
|
|
|
|
func TestKubeDeleteRemovesPoliciesOnlyAfterPodsAreGone(t *testing.T) {
|
|
f, srv := newFakeKubeAPI(t)
|
|
b := newTestKubeBackend(t, f, srv)
|
|
ctx := context.Background()
|
|
f.podLinger = 3 // a deleted pod stays visible (terminating) for 3 GETs
|
|
for _, id := range []string{"t1", "t2"} {
|
|
if _, err := b.Exec(ctx, id, execReq("true")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
mark := len(f.opsSnapshot())
|
|
if err := b.Delete(ctx, "t1"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
h := kubeTaskHash("t1")
|
|
ops := f.opsSnapshot()[mark:]
|
|
firstPol, gone := -1, 0
|
|
for i, op := range ops {
|
|
if strings.HasPrefix(op, "gone pods/") {
|
|
gone++
|
|
}
|
|
if strings.HasPrefix(op, "delete networkpolicies/") && firstPol < 0 {
|
|
firstPol = i
|
|
if gone != 2 {
|
|
t.Fatalf("policy deleted while a pod still ran: %v", ops)
|
|
}
|
|
}
|
|
}
|
|
if firstPol < 0 || f.obj("networkpolicies", "artex-p-"+h) != nil || f.count("pods") != 2 {
|
|
t.Fatalf("delete incomplete: %v", ops)
|
|
}
|
|
|
|
// A pod that cannot be deleted keeps its policies, and the task stays tracked.
|
|
h2 := kubeTaskHash("t2")
|
|
f.failDelete[b.getTask("t2").workerPod] = true
|
|
err := b.Delete(ctx, "t2")
|
|
if err == nil || strings.Contains(err.Error(), "etcd") {
|
|
t.Fatalf("failed pod delete = %v (want error without the API body)", err)
|
|
}
|
|
if f.obj("networkpolicies", "artex-w-"+h2) == nil || f.obj("networkpolicies", "artex-p-"+h2) == nil || b.WorkerCount() != 1 {
|
|
t.Fatal("policies removed although the worker pod is still running")
|
|
}
|
|
f.failDelete = map[string]bool{}
|
|
if err := b.Delete(ctx, "t2"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if f.count("pods")+f.count("services")+f.count("networkpolicies") != 0 {
|
|
t.Fatalf("objects left: %v", f.opsSnapshot())
|
|
}
|
|
if err := b.Delete(ctx, "t2"); !errors.Is(err, ErrNotFound) {
|
|
t.Fatalf("delete of nothing = %v", err)
|
|
}
|
|
b.mu.Lock()
|
|
locks := len(b.locks)
|
|
b.mu.Unlock()
|
|
if locks != 0 {
|
|
t.Fatalf("%d task locks left after Delete", locks)
|
|
}
|
|
}
|
|
|
|
func TestKubeApplyPolicyUpdatesWithResourceVersionOnlyOwnPolicy(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)
|
|
}
|
|
// The fake enforces the API server rule: an update without resourceVersion is 422.
|
|
pol := b.workerPolicyObj("artex-w-"+h, &kubeTask{taskID: "t1", hash: h})
|
|
if err := b.do(ctx, http.MethodPut, b.nsPath("networkpolicies")+"/artex-w-"+h, pol, nil); !isKubeStatus(err, http.StatusUnprocessableEntity) {
|
|
t.Fatalf("PUT without resourceVersion = %v", err)
|
|
}
|
|
rv := dig(f.obj("networkpolicies", "artex-w-"+h), "metadata", "resourceVersion")
|
|
if err := b.applyPolicy(ctx, pol); err != nil {
|
|
t.Fatalf("409 -> PUT: %v", err)
|
|
}
|
|
if got := dig(f.obj("networkpolicies", "artex-w-"+h), "metadata", "resourceVersion"); got == rv {
|
|
t.Fatal("policy not replaced")
|
|
}
|
|
|
|
// A same-named policy without the runner's labels is never overwritten, and the
|
|
// failed setup leaves nothing of its own behind.
|
|
h2 := kubeTaskHash("t2")
|
|
f.mu.Lock()
|
|
f.objs["networkpolicies"]["artex-p-"+h2] = map[string]any{
|
|
"metadata": map[string]any{"name": "artex-p-" + h2, "labels": map[string]any{"app": "x"}, "resourceVersion": "1"},
|
|
"spec": map[string]any{"podSelector": map[string]any{"foreign": true}}}
|
|
f.mu.Unlock()
|
|
_, err := b.Exec(ctx, "t2", execReq("true"))
|
|
if err == nil || !strings.Contains(err.Error(), "not managed by the runner") {
|
|
t.Fatalf("foreign policy = %v", err)
|
|
}
|
|
if dig(f.obj("networkpolicies", "artex-p-"+h2), "spec", "podSelector", "foreign") != true || f.obj("networkpolicies", "artex-w-"+h2) != nil {
|
|
t.Fatal("foreign policy replaced or own policy left behind")
|
|
}
|
|
}
|
|
|
|
func TestKubeDeniedCIDRsExtendDefaults(t *testing.T) {
|
|
f, srv := newFakeKubeAPI(t)
|
|
cfg := newTestKubeBackend(t, f, srv).cfg
|
|
cfg.ProxyDeniedCIDRs = []string{"198.51.100.7/24", "10.0.0.0/8"}
|
|
nb, err := NewKubernetesBackend(cfg)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := strings.Join(append(slices.Clone(DefaultProxyDeniedCIDRs), "198.51.100.0/24"), ",")
|
|
if got := strings.Join(nb.cfg.ProxyDeniedCIDRs, ","); got != want {
|
|
t.Fatalf("denied CIDRs = %s\nwant %s", got, want)
|
|
}
|
|
cfg.ProxyDeniedCIDRs = []string{"fc00::/7"}
|
|
if _, err := NewKubernetesBackend(cfg); err == nil {
|
|
t.Fatal("IPv6 denied CIDR accepted")
|
|
}
|
|
// An empty label map must not select every pod in the DNS namespace.
|
|
cfg.ProxyDeniedCIDRs, cfg.DNSPodLabels = nil, map[string]string{}
|
|
if nb, err = NewKubernetesBackend(cfg); err != nil || nb.cfg.DNSPodLabels["k8s-app"] != "kube-dns" {
|
|
t.Fatalf("empty DNS labels: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestKubeCancelledExecKeepsTask(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)
|
|
}
|
|
// A failed pod lookup (here a cancelled request) says nothing about the pods:
|
|
// only this exec fails, and it is not reported as the runner being unavailable.
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
_, err := b.Exec(ctx, "t1", execReq("true"))
|
|
if !errors.Is(err, context.Canceled) || errors.Is(err, ErrDockerUnavailable) || f.count("pods")+f.count("networkpolicies") != 4 || b.WorkerCount() != 1 {
|
|
t.Fatalf("cancelled exec = %v; %d pods, %d tasks", err, f.count("pods"), b.WorkerCount())
|
|
}
|
|
}
|