72 lines
1.8 KiB
Go
72 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net"
|
|
"net/http"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestDockerControllerOnlyControlsLabelledContainers(t *testing.T) {
|
|
sock := filepath.Join(t.TempDir(), "docker.sock")
|
|
ln, err := net.Listen("unix", sock)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer ln.Close()
|
|
|
|
controlled := false
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /containers/json", func(w http.ResponseWriter, r *http.Request) {
|
|
_ = json.NewEncoder(w).Encode([]dockerContainerSummary{
|
|
{
|
|
ID: "allowed123",
|
|
Names: []string{"/skill-python"},
|
|
Image: "worker",
|
|
State: "exited",
|
|
Status: "Exited",
|
|
Labels: map[string]string{
|
|
"com.jarvis.skill-service": "true",
|
|
"com.jarvis.skill-runtime": "python",
|
|
},
|
|
},
|
|
{
|
|
ID: "other999",
|
|
Names: []string{"/db"},
|
|
Image: "db",
|
|
State: "running",
|
|
Labels: map[string]string{"other": "true"},
|
|
},
|
|
})
|
|
})
|
|
mux.HandleFunc("POST /containers/allowed123/start", func(w http.ResponseWriter, r *http.Request) {
|
|
controlled = true
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
srv := &http.Server{Handler: mux}
|
|
go srv.Serve(ln)
|
|
defer srv.Close()
|
|
|
|
t.Setenv("JARVIS_DOCKER_CONTROLLER_ENABLED", "true")
|
|
t.Setenv("JARVIS_DOCKER_SOCKET", sock)
|
|
t.Setenv("JARVIS_DOCKER_SKILL_LABEL", "com.jarvis.skill-service")
|
|
t.Setenv("JARVIS_DOCKER_SKILL_LABEL_VALUE", "true")
|
|
|
|
d := newDockerSkillController(nil)
|
|
st := d.Status(context.Background())
|
|
if !st.Available || len(st.Services) != 1 || st.Services[0].ID != "allowed123" {
|
|
t.Fatalf("bad status: %+v", st)
|
|
}
|
|
if err := d.control(context.Background(), "other999", "start"); err == nil {
|
|
t.Fatalf("unlabelled container was controllable")
|
|
}
|
|
if err := d.control(context.Background(), "allowed123", "start"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !controlled {
|
|
t.Fatalf("start not called")
|
|
}
|
|
}
|