Files

169 lines
5.1 KiB
Go

package container
import (
"encoding/binary"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/moby/moby/client"
)
// TestPoolReapsOnlyOwnInstance runs the reaper against a fake Engine that
// applies label filters the way Docker does, so instances sharing a host
// never remove each other's containers.
func TestPoolReapsOnlyOwnInstance(t *testing.T) {
containers := map[string]string{ // ID -> archie-daemon label value
"own000000000": "archie",
"other0000000": "staging",
"legacy000000": "true",
}
tests := []struct {
name string
reap func(*Pool)
}{
{"close", func(p *Pool) { _ = p.Close() }},
{"orphan recovery", func(p *Pool) { p.recoverOrphans(t.Context()) }},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var (
mu sync.Mutex
removed []string
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
var filters map[string]map[string]bool
if err := json.Unmarshal([]byte(r.URL.Query().Get("filters")), &filters); err != nil {
t.Error(err)
}
var items []map[string]any
for id, value := range containers {
if filters["label"]["archie-daemon="+value] {
items = append(items, map[string]any{"Id": id})
}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(items)
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/stop"):
w.WriteHeader(http.StatusNoContent)
case r.Method == http.MethodDelete:
mu.Lock()
removed = append(removed, r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:])
mu.Unlock()
w.WriteHeader(http.StatusNoContent)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
cli, err := client.New(client.WithHost(server.URL), client.WithAPIVersion("1.54"))
if err != nil {
t.Fatal(err)
}
defer func() { _ = cli.Close() }()
tt.reap(&Pool{cli: cli, cfg: Config{Instance: "archie"}, log: slog.New(slog.DiscardHandler)})
if !slices.Equal(removed, []string{"own000000000"}) {
t.Fatalf("removed %v, want only the own instance's container", removed)
}
})
}
}
// TestExitDetailCarriesCrashStderr runs the exit watch against a fake Engine: a
// container that fails writes its panic trace to stderr, and the panic line has
// to reach the exit detail before Release removes the container, without the
// rest of its output.
func TestExitDetailCarriesCrashStderr(t *testing.T) {
tests := []struct {
name string
code int64
stderr []string
want []string
reject []string
wantLogs bool
}{
{
name: "crash keeps only the panic line",
code: 2,
stderr: []string{"token=s3cret", "panic: runtime error: boom", "goroutine 1 [running]:"},
want: []string{"exit code 2", "panic: runtime error: boom"},
reject: []string{"s3cret", "goroutine"},
wantLogs: true,
},
{
name: "clean exit asks for no log",
code: 0,
stderr: []string{"finished"},
want: []string{"exit code 0"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var logsRequested bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/wait"):
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprintf(w, `{"StatusCode":%d}`, tt.code)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/logs"):
logsRequested = true
for _, line := range tt.stderr {
writeStderrFrame(t, w, line)
}
default:
http.NotFound(w, r)
}
}))
defer server.Close()
cli, err := client.New(client.WithHost(server.URL), client.WithAPIVersion("1.54"))
if err != nil {
t.Fatal(err)
}
defer func() { _ = cli.Close() }()
p := &Pool{cli: cli, log: slog.New(slog.DiscardHandler)}
detail := new(string)
exited := p.watchExit(t.Context(), "crash00000000", detail)
select {
case <-exited:
case <-time.After(5 * time.Second):
t.Fatal("exit watch did not report the container's exit")
}
for _, want := range tt.want {
if !strings.Contains(*detail, want) {
t.Fatalf("exit detail %q does not contain %q", *detail, want)
}
}
for _, reject := range tt.reject {
if strings.Contains(*detail, reject) {
t.Fatalf("exit detail %q carries %q, which belongs only in the daemon log", *detail, reject)
}
}
if logsRequested != tt.wantLogs {
t.Fatalf("log requested = %v, want %v", logsRequested, tt.wantLogs)
}
})
}
}
// writeStderrFrame writes one line as a Docker multiplexed stderr frame, the
// shape ContainerLogs returns for a container without a TTY.
func writeStderrFrame(t *testing.T, w io.Writer, line string) {
t.Helper()
payload := []byte(line + "\n")
frame := [8]byte{2}
binary.BigEndian.PutUint32(frame[4:], uint32(len(payload)))
if _, err := w.Write(append(frame[:], payload...)); err != nil {
t.Error(err)
}
}