mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 21:17:28 +00:00
the timeout by exit code 124. artex-exec-wrap returns 124 when it enforces timeout_ms, but the command can also exit 124 itself: coreutils `timeout 1 sleep 5` does. The runner then removed the worker and stopped the task's background jobs after an ordinary inner timeout. Count an exit 124 as the runner's timeout only when the exec ran for at least timeout_ms, which is the only way the wrapper can return it.
311 lines
10 KiB
Go
311 lines
10 KiB
Go
package sandbox
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net"
|
|
"net/http"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// fakeDocker is a minimal Docker Engine API stub over a unix socket. It records
|
|
// the request sequence so tests can assert cleanup ordering, and lets each test
|
|
// fail specific delete calls.
|
|
type fakeDocker struct {
|
|
mu sync.Mutex
|
|
calls []string
|
|
execStatus int // POST /containers/{id}/exec, 0 means 200
|
|
deleteCode map[string]int // container name -> status, 0 means 204
|
|
networkCode int // 0 means 204
|
|
requireWorkerRemoval bool // model Docker rejecting a network with a live worker endpoint
|
|
execExitCode int
|
|
execRunning bool
|
|
execStream []byte
|
|
execStartCode int
|
|
inspectCode int
|
|
inspectBody string
|
|
streamReady chan struct{}
|
|
streamStarted bool
|
|
execDelay time.Duration // delay before the exec stream answers, as a running command would
|
|
}
|
|
|
|
func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
p := r.URL.Path
|
|
f.mu.Lock()
|
|
f.calls = append(f.calls, r.Method+" "+p)
|
|
f.mu.Unlock()
|
|
|
|
switch {
|
|
case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/start"):
|
|
w.WriteHeader(http.StatusNoContent)
|
|
case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/exec"):
|
|
if f.execStatus != 0 {
|
|
w.WriteHeader(f.execStatus)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]string{"Id": "exec-1"})
|
|
case r.Method == http.MethodPost && strings.HasPrefix(p, "/exec/") && strings.HasSuffix(p, "/start"):
|
|
if f.execStartCode != 0 {
|
|
w.WriteHeader(f.execStartCode)
|
|
return
|
|
}
|
|
time.Sleep(f.execDelay)
|
|
w.WriteHeader(http.StatusOK)
|
|
f.mu.Lock()
|
|
firstStream := f.streamReady != nil && !f.streamStarted
|
|
if firstStream {
|
|
f.streamStarted = true
|
|
}
|
|
f.mu.Unlock()
|
|
if firstStream {
|
|
w.(http.Flusher).Flush()
|
|
close(f.streamReady)
|
|
<-r.Context().Done()
|
|
return
|
|
}
|
|
_, _ = w.Write(f.execStream)
|
|
case r.Method == http.MethodGet && strings.HasPrefix(p, "/exec/"):
|
|
if f.inspectBody != "" {
|
|
if f.inspectCode != 0 {
|
|
w.WriteHeader(f.inspectCode)
|
|
}
|
|
_, _ = w.Write([]byte(f.inspectBody))
|
|
return
|
|
}
|
|
if f.inspectCode != 0 {
|
|
w.WriteHeader(f.inspectCode)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"ExitCode": f.execExitCode, "Running": f.execRunning})
|
|
case r.Method == http.MethodDelete && strings.HasPrefix(p, "/containers/"):
|
|
name := strings.TrimPrefix(p, "/containers/")
|
|
if code := f.deleteCode[name]; code >= 300 {
|
|
w.WriteHeader(code)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
case r.Method == http.MethodDelete && strings.HasPrefix(p, "/networks/"):
|
|
if f.requireWorkerRemoval && !f.seen("DELETE /containers/worker-1") {
|
|
http.Error(w, "network has active endpoints", http.StatusForbidden)
|
|
return
|
|
}
|
|
if f.networkCode >= 300 {
|
|
w.WriteHeader(f.networkCode)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
default:
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
}
|
|
|
|
func (f *fakeDocker) seen(prefix string) bool {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
for _, c := range f.calls {
|
|
if strings.HasPrefix(c, prefix) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func newFakeDockerBackend(t *testing.T, f http.Handler) *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 seedTask(b *DockerBackend, taskID, workerID, proxyID, netName string) *taskContainers {
|
|
tc := &taskContainers{taskID: taskID, workerID: workerID, proxyID: proxyID, netName: netName}
|
|
b.tasks[taskID] = tc
|
|
return tc
|
|
}
|
|
|
|
// TestKillKeepsStateWhenContainerRemovalFails is the regression for the
|
|
// fail-open cleanup: a Docker 500 on force-removal must not clear the worker ID
|
|
// or report success, otherwise a surviving worker becomes unreachable.
|
|
func TestKillKeepsStateWhenContainerRemovalFails(t *testing.T) {
|
|
f := &fakeDocker{execStatus: http.StatusInternalServerError, deleteCode: map[string]int{"dead-worker": http.StatusInternalServerError}}
|
|
b := newFakeDockerBackend(t, f)
|
|
tc := seedTask(b, "t1", "dead-worker", "proxy-1", "artex-task-t1")
|
|
|
|
if err := b.Kill(context.Background(), "t1"); err == nil {
|
|
t.Fatal("Kill reported success although the worker container could not be removed")
|
|
}
|
|
if tc.workerID != "dead-worker" {
|
|
t.Fatalf("Kill cleared workerID after a failed removal: %q", tc.workerID)
|
|
}
|
|
if b.tasks["t1"] != tc {
|
|
t.Fatal("Kill unpublished the task after a failed removal")
|
|
}
|
|
}
|
|
|
|
// TestKillClearsWorkerOnlyWhenRemovalProven covers the successful fallback path.
|
|
func TestKillClearsWorkerOnlyWhenRemovalProven(t *testing.T) {
|
|
f := &fakeDocker{execStatus: http.StatusInternalServerError}
|
|
b := newFakeDockerBackend(t, f)
|
|
tc := seedTask(b, "t1", "dead-worker", "proxy-1", "artex-task-t1")
|
|
|
|
if err := b.Kill(context.Background(), "t1"); err != nil {
|
|
t.Fatalf("Kill: %v", err)
|
|
}
|
|
if tc.workerID != "" {
|
|
t.Fatalf("workerID not cleared after a proven removal: %q", tc.workerID)
|
|
}
|
|
if !f.seen("DELETE /containers/dead-worker") {
|
|
t.Fatal("Kill never issued the force-removal")
|
|
}
|
|
}
|
|
|
|
// TestKillTreatsAbsentWorkerAsStopped: a 404 on the kill exec means the worker
|
|
// container is already gone, which proves no process can survive it.
|
|
func TestKillTreatsAbsentWorkerAsStopped(t *testing.T) {
|
|
f := &fakeDocker{execStatus: http.StatusNotFound}
|
|
b := newFakeDockerBackend(t, f)
|
|
tc := seedTask(b, "t1", "gone-worker", "", "")
|
|
|
|
if err := b.Kill(context.Background(), "t1"); err != nil {
|
|
t.Fatalf("Kill on an absent worker: %v", err)
|
|
}
|
|
if tc.workerID != "" {
|
|
t.Fatalf("workerID retained for an absent worker: %q", tc.workerID)
|
|
}
|
|
}
|
|
|
|
// TestKillUsesFreshContextAfterCancellation: the caller's cancelled request
|
|
// context must not turn the cleanup into a silent no-op.
|
|
func TestKillUsesFreshContextAfterCancellation(t *testing.T) {
|
|
f := &fakeDocker{}
|
|
b := newFakeDockerBackend(t, f)
|
|
tc := seedTask(b, "t1", "dead-worker", "", "")
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
|
|
if err := b.Kill(ctx, "t1"); err != nil {
|
|
t.Fatalf("Kill with a cancelled context: %v", err)
|
|
}
|
|
if !f.seen("DELETE /containers/dead-worker") {
|
|
t.Fatal("Kill skipped the removal because the caller context was cancelled")
|
|
}
|
|
if tc.workerID != "" {
|
|
t.Fatalf("workerID not cleared: %q", tc.workerID)
|
|
}
|
|
}
|
|
|
|
// TestDeleteKeepsStateWhenProxyRemovalFails: Delete must unpublish only after
|
|
// every resource is proven stopped or absent, and must keep the identifiers a
|
|
// retry needs.
|
|
func TestDeleteKeepsStateWhenProxyRemovalFails(t *testing.T) {
|
|
f := &fakeDocker{deleteCode: map[string]int{"proxy-1": http.StatusInternalServerError}}
|
|
b := newFakeDockerBackend(t, f)
|
|
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
|
|
|
|
if err := b.Delete(context.Background(), "t1"); err == nil {
|
|
t.Fatal("Delete reported success although the proxy container could not be removed")
|
|
}
|
|
if b.tasks["t1"] != tc {
|
|
t.Fatal("Delete unpublished the task after a failed proxy removal")
|
|
}
|
|
if tc.proxyID != "proxy-1" {
|
|
t.Fatalf("Delete cleared proxyID after a failed removal: %q", tc.proxyID)
|
|
}
|
|
if !f.seen("DELETE /containers/proxy-1") {
|
|
t.Fatal("Delete never attempted the proxy removal")
|
|
}
|
|
// Removing the worker stops its processes before the proxy is removed.
|
|
f.mu.Lock()
|
|
workerIdx, proxyIdx := -1, -1
|
|
for i, c := range f.calls {
|
|
if c == "DELETE /containers/worker-1" {
|
|
workerIdx = i
|
|
}
|
|
if c == "DELETE /containers/proxy-1" {
|
|
proxyIdx = i
|
|
}
|
|
}
|
|
f.mu.Unlock()
|
|
if workerIdx == -1 || proxyIdx == -1 || workerIdx > proxyIdx {
|
|
t.Fatalf("Delete did not remove the worker before removing the proxy: %v", f.calls)
|
|
}
|
|
}
|
|
|
|
// TestDeleteUnpublishesOnlyAfterFullSuccess covers the happy path.
|
|
func TestDeleteUnpublishesOnlyAfterFullSuccess(t *testing.T) {
|
|
f := &fakeDocker{requireWorkerRemoval: true}
|
|
b := newFakeDockerBackend(t, f)
|
|
seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
|
|
|
|
if err := b.Delete(context.Background(), "t1"); err != nil {
|
|
t.Fatalf("Delete: %v", err)
|
|
}
|
|
if _, ok := b.tasks["t1"]; ok {
|
|
t.Fatal("Delete left the task in the map after full success")
|
|
}
|
|
if !f.seen("DELETE /containers/worker-1") || !f.seen("DELETE /containers/proxy-1") || !f.seen("DELETE /networks/artex-task-t1") {
|
|
t.Fatalf("Delete skipped resources: %v", f.calls)
|
|
}
|
|
}
|
|
|
|
func TestDeleteRetainsWorkerAfterRemovalFailure(t *testing.T) {
|
|
f := &fakeDocker{deleteCode: map[string]int{"worker-1": http.StatusInternalServerError}}
|
|
b := newFakeDockerBackend(t, f)
|
|
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
|
|
if err := b.Delete(context.Background(), "t1"); err == nil {
|
|
t.Fatal("Delete succeeded although the worker could not be removed")
|
|
}
|
|
if b.tasks["t1"] != tc || tc.workerID != "worker-1" {
|
|
t.Fatal("Delete lost the worker needed for a cleanup retry")
|
|
}
|
|
if f.seen("DELETE /networks/") {
|
|
t.Fatal("network deletion attempted while worker is still attached")
|
|
}
|
|
}
|
|
|
|
// TestDeleteUsesFreshContextAfterCancellation: deletion from a cancelled HTTP
|
|
// request must still stop the containers.
|
|
func TestDeleteUsesFreshContextAfterCancellation(t *testing.T) {
|
|
f := &fakeDocker{}
|
|
b := newFakeDockerBackend(t, f)
|
|
seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
|
|
if err := b.Delete(ctx, "t1"); err != nil {
|
|
t.Fatalf("Delete with a cancelled context: %v", err)
|
|
}
|
|
if _, ok := b.tasks["t1"]; ok {
|
|
t.Fatal("Delete did not complete with a cancelled caller context")
|
|
}
|
|
}
|
|
|
|
// TestDeleteTreatsAbsentResourcesAsSuccess: a retry after a partial cleanup
|
|
// sees 404s for the already-removed resources and must still succeed.
|
|
func TestDeleteTreatsAbsentResourcesAsSuccess(t *testing.T) {
|
|
f := &fakeDocker{execStatus: http.StatusNotFound, deleteCode: map[string]int{
|
|
"proxy-1": http.StatusNotFound,
|
|
}, networkCode: http.StatusNotFound}
|
|
b := newFakeDockerBackend(t, f)
|
|
seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
|
|
|
|
if err := b.Delete(context.Background(), "t1"); err != nil {
|
|
t.Fatalf("Delete on already-absent resources: %v", err)
|
|
}
|
|
if _, ok := b.tasks["t1"]; ok {
|
|
t.Fatal("Delete left the task in the map after proving every resource absent")
|
|
}
|
|
}
|