77 lines
2.2 KiB
Go
77 lines
2.2 KiB
Go
package container
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"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 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)
|
|
}
|
|
})
|
|
}
|
|
}
|