| 1 | package runnercfg |
| 2 | |
| 3 | import ( |
| 4 | "html/template" |
| 5 | "net/http" |
| 6 | "net/http/httptest" |
| 7 | "net/url" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "gitlab.com/Timfa/bluegit/internal/i18n" |
| 15 | ) |
| 16 | |
| 17 | func TestValidate(t *testing.T) { |
| 18 | s := Defaults() |
| 19 | if err := s.Validate(); err != nil { |
| 20 | t.Fatal(err) |
| 21 | } |
| 22 | bad := []func(*Settings){ |
| 23 | func(s *Settings) { s.Concurrency = 0 }, |
| 24 | func(s *Settings) { s.Concurrency = 65 }, |
| 25 | func(s *Settings) { s.MaxImages = 0 }, |
| 26 | func(s *Settings) { s.MemoryMB = 10 }, |
| 27 | func(s *Settings) { s.CPUs = -1 }, |
| 28 | func(s *Settings) { s.PullPolicy = "sometimes" }, |
| 29 | func(s *Settings) { s.Labels = []string{"bad label!"} }, |
| 30 | func(s *Settings) { s.Name = "<script>" }, |
| 31 | func(s *Settings) { |
| 32 | s.Presets = []Preset{{Name: "team/a", Image: "x:1"}, {Name: "team/a", Image: "y:1"}} |
| 33 | }, |
| 34 | func(s *Settings) { s.Presets = []Preset{{Name: "team/a", Image: "x:1", From: "y"}} }, |
| 35 | func(s *Settings) { s.Presets = []Preset{{Name: "team/a"}} }, |
| 36 | func(s *Settings) { s.Presets = []Preset{{Name: "team/a", From: "debian"}} }, |
| 37 | func(s *Settings) { s.Presets = []Preset{{Name: "team/a", Dockerfile: "RUN true"}} }, |
| 38 | func(s *Settings) { s.Presets = []Preset{{Name: "geenslash", Image: "x:1"}} }, |
| 39 | } |
| 40 | for i, f := range bad { |
| 41 | s := Defaults() |
| 42 | f(&s) |
| 43 | err := s.Validate() |
| 44 | e, ok := err.(Error) |
| 45 | if !ok || !strings.HasPrefix(e.Key, "rui.err.") { |
| 46 | t.Fatalf("geval %d: %v", i, err) |
| 47 | } |
| 48 | if got := i18n.T(i18n.NL, e.Key, e.Args...); got == e.Key { |
| 49 | t.Fatalf("geval %d: geen vertaling voor %s", i, e.Key) |
| 50 | } |
| 51 | } |
| 52 | ok := Defaults() |
| 53 | ok.Labels = []string{" gpu", "gpu", "linux"} |
| 54 | ok.Presets = []Preset{{Name: "bluegit/python", From: "python:3.13-slim"}, {Name: "Team/Tools", Dockerfile: "FROM debian\nRUN true"}} |
| 55 | if err := ok.Validate(); err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | if len(ok.Labels) != 2 || ok.Presets[1].Name != "team/tools" { |
| 59 | t.Fatalf("%+v", ok) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | func TestRecommend(t *testing.T) { |
| 64 | r := Recommend(Hardware{CPUs: 8, MemoryMB: 16384, DiskFree: 200}) |
| 65 | if r.Concurrency != 3 || r.CPUs != 2 || r.MemoryMB != 5120 || r.MaxImages != 50 { |
| 66 | t.Fatalf("8/16/200: %+v", r) |
| 67 | } |
| 68 | small := Recommend(Hardware{CPUs: 1, MemoryMB: 1024, DiskFree: 5}) |
| 69 | if small.Concurrency != 1 || small.CPUs < 1 || small.MemoryMB < 512 { |
| 70 | t.Fatalf("klein: %+v", small) |
| 71 | } |
| 72 | if err := small.Validate(); err != nil { |
| 73 | t.Fatal(err) |
| 74 | } |
| 75 | big := Recommend(Hardware{CPUs: 64, MemoryMB: 262144, DiskFree: 4000}) |
| 76 | if big.Concurrency != 8 { |
| 77 | t.Fatalf("groot: %+v", big) |
| 78 | } |
| 79 | if h := Detect(t.TempDir()); h.CPUs < 1 { |
| 80 | t.Fatalf("detect: %+v", h) |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | func TestRunArgsAndOverrides(t *testing.T) { |
| 85 | s := Defaults() |
| 86 | s.CPUs, s.MemoryMB, s.PidsLimit = 1.5, 2048, 100 |
| 87 | if got := strings.Join(s.RunArgs(), " "); got != "--cpus 1.5 --memory 2048m --pids-limit 100" { |
| 88 | t.Fatal(got) |
| 89 | } |
| 90 | s.Presets = []Preset{{Name: "team/tools", Dockerfile: "FROM alpine"}, {Name: "team/node", Image: "node:22"}} |
| 91 | dir := t.TempDir() |
| 92 | over, err := s.Overrides(dir, nil) |
| 93 | if err != nil { |
| 94 | t.Fatal(err) |
| 95 | } |
| 96 | b, err := os.ReadFile(over["team/tools"].Dockerfile) |
| 97 | if err != nil || !strings.Contains(string(b), "FROM alpine") || over["team/node"].Image != "node:22" { |
| 98 | t.Fatalf("%v %s %+v", err, b, over) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | func TestTracker(t *testing.T) { |
| 103 | var tr Tracker |
| 104 | if !tr.SafeToUpgrade() { |
| 105 | t.Fatal("leeg is veilig") |
| 106 | } |
| 107 | tr.Start(JobInfo{ID: 1, Name: "build", Image: "a"}) |
| 108 | tr.Start(JobInfo{ID: 2, Name: "test", Image: "b"}) |
| 109 | if tr.SafeToUpgrade() || len(tr.Active()) != 2 { |
| 110 | t.Fatal("actief") |
| 111 | } |
| 112 | tr.Finish(1, "success") |
| 113 | tr.Finish(99, "failed") |
| 114 | if len(tr.Active()) != 1 || len(tr.Recent()) != 1 || tr.Recent()[0].Status != "success" { |
| 115 | t.Fatalf("%+v %+v", tr.Active(), tr.Recent()) |
| 116 | } |
| 117 | tr.Finish(2, "failed") |
| 118 | time.Sleep(time.Millisecond) |
| 119 | tr.Start(JobInfo{ID: 3, Image: "c"}) |
| 120 | if st := tr.StaleImages(1); len(st) != 2 { |
| 121 | t.Fatalf("oud: %v", st) |
| 122 | } |
| 123 | tr.SetPaused(true) |
| 124 | if !tr.Paused() { |
| 125 | t.Fatal("pauze") |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | func testHandler(t *testing.T, allow bool) (*Handler, *http.ServeMux) { |
| 130 | dir := t.TempDir() |
| 131 | h := &Handler{ |
| 132 | File: &File{Path: filepath.Join(dir, "settings.json")}, Default: Defaults(), Tracker: &Tracker{}, WorkDir: dir, |
| 133 | Status: func() Status { return Status{Kind: "standalone", Name: "pc", Online: true} }, |
| 134 | Lang: func(r *http.Request) i18n.Lang { return i18n.Parse(r.URL.Query().Get("lang")) }, |
| 135 | Auth: func(w http.ResponseWriter, r *http.Request, write bool) bool { |
| 136 | if !allow { |
| 137 | http.Error(w, "no", http.StatusUnauthorized) |
| 138 | } |
| 139 | return allow |
| 140 | }, |
| 141 | CSRF: func(*http.Request) (string, string) { return "csrf", "goed" }, |
| 142 | CheckCSRF: func(r *http.Request) bool { return r.FormValue("csrf") == "goed" }, |
| 143 | Layout: func(w http.ResponseWriter, r *http.Request, lang i18n.Lang, title string, body template.HTML) { |
| 144 | _, _ = w.Write([]byte(title + "\n" + string(body))) |
| 145 | }, |
| 146 | } |
| 147 | mux := http.NewServeMux() |
| 148 | h.Mount(mux, true) |
| 149 | return h, mux |
| 150 | } |
| 151 | |
| 152 | func post(mux http.Handler, path string, v url.Values) *httptest.ResponseRecorder { |
| 153 | req := httptest.NewRequest("POST", path, strings.NewReader(v.Encode())) |
| 154 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 155 | w := httptest.NewRecorder() |
| 156 | mux.ServeHTTP(w, req) |
| 157 | return w |
| 158 | } |
| 159 | |
| 160 | func TestHandlerPauseSettingsPresets(t *testing.T) { |
| 161 | h, mux := testHandler(t, true) |
| 162 | if w := post(mux, "/pause", url.Values{"csrf": {"fout"}}); w.Code != http.StatusForbidden { |
| 163 | t.Fatalf("csrf: %d", w.Code) |
| 164 | } |
| 165 | if w := post(mux, "/pause", url.Values{"csrf": {"goed"}}); w.Code != http.StatusSeeOther || !h.Tracker.Paused() || !h.Current().Paused { |
| 166 | t.Fatalf("pauze: %d", w.Code) |
| 167 | } |
| 168 | w := post(mux, "/settings", url.Values{"csrf": {"goed"}, "name": {"Mijn PC"}, "concurrency": {"4"}, "max_images": {"9"}, "cpus": {"1,5"}, "labels": {"gpu, linux"}, "pull_policy": {"never"}}) |
| 169 | if !strings.Contains(w.Header().Get("Location"), "ok=rui.ok.saved") { |
| 170 | t.Fatal(w.Header().Get("Location")) |
| 171 | } |
| 172 | s := h.Current() |
| 173 | if s.Name != "Mijn PC" || s.Concurrency != 4 || s.CPUs != 1.5 || len(s.Labels) != 2 || s.PullPolicy != "never" || !s.Paused { |
| 174 | t.Fatalf("%+v", s) |
| 175 | } |
| 176 | w = post(mux, "/settings", url.Values{"csrf": {"goed"}, "concurrency": {"999"}, "max_images": {"9"}}) |
| 177 | if !strings.Contains(w.Header().Get("Location"), "err=rui.err.concurrency") || h.Current().Concurrency != 4 { |
| 178 | t.Fatalf("ongeldig: %s", w.Header().Get("Location")) |
| 179 | } |
| 180 | post(mux, "/presets", url.Values{"csrf": {"goed"}, "name": {"team/tools"}, "image": {"alpine:3.20"}}) |
| 181 | w = post(mux, "/presets", url.Values{"csrf": {"goed"}, "name": {"team/x"}, "image": {"a"}, "from": {"b"}}) |
| 182 | if !strings.Contains(w.Header().Get("Location"), "rui.err.presetBoth") { |
| 183 | t.Fatal(w.Header().Get("Location")) |
| 184 | } |
| 185 | if len(h.Current().Presets) != 1 { |
| 186 | t.Fatal("preset") |
| 187 | } |
| 188 | post(mux, "/recommend", url.Values{"csrf": {"goed"}}) |
| 189 | if h.Current().PidsLimit != 4096 { |
| 190 | t.Fatal("aanbeveling") |
| 191 | } |
| 192 | post(mux, "/presets/delete", url.Values{"csrf": {"goed"}, "name": {"team/tools"}}) |
| 193 | post(mux, "/resume", url.Values{"csrf": {"goed"}}) |
| 194 | if len(h.Current().Presets) != 0 || h.Tracker.Paused() { |
| 195 | t.Fatal("verwijderen/hervatten") |
| 196 | } |
| 197 | for _, l := range []string{"en", "nl", "de", "fr"} { |
| 198 | req := httptest.NewRequest("GET", "/?lang="+l+"&err=rui.err.label|x", nil) |
| 199 | rw := httptest.NewRecorder() |
| 200 | mux.ServeHTTP(rw, req) |
| 201 | page := rw.Body.String() |
| 202 | if rw.Code != 200 || !strings.Contains(page, `class="rui"`) || strings.Contains(page, "rui.") || strings.Contains(page, "rdoc.") { |
| 203 | t.Fatalf("%s: %d onvertaalde sleutel in pagina", l, rw.Code) |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | func TestHandlerAuth(t *testing.T) { |
| 209 | h, mux := testHandler(t, false) |
| 210 | for _, c := range []struct{ m, p string }{{"GET", "/"}, {"GET", "/api/status"}, {"PUT", "/api/settings"}, {"POST", "/api/pause"}, {"GET", "/api/jobs"}} { |
| 211 | req := httptest.NewRequest(c.m, c.p, strings.NewReader(`{"paused":true}`)) |
| 212 | w := httptest.NewRecorder() |
| 213 | mux.ServeHTTP(w, req) |
| 214 | if w.Code != http.StatusUnauthorized { |
| 215 | t.Fatalf("%s %s: %d", c.m, c.p, w.Code) |
| 216 | } |
| 217 | } |
| 218 | if w := post(mux, "/pause", url.Values{"csrf": {"goed"}}); w.Code != http.StatusUnauthorized || h.Current().Paused { |
| 219 | t.Fatal("pauze zonder auth") |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | func TestHandlerAPI(t *testing.T) { |
| 224 | h, mux := testHandler(t, true) |
| 225 | req := httptest.NewRequest("PUT", "/api/settings", strings.NewReader(`{"concurrency":2,"memory_mb":1024}`)) |
| 226 | w := httptest.NewRecorder() |
| 227 | mux.ServeHTTP(w, req) |
| 228 | if w.Code != 200 || h.Current().Concurrency != 2 || h.Current().MaxImages != 20 { |
| 229 | t.Fatalf("%d %s", w.Code, w.Body) |
| 230 | } |
| 231 | req = httptest.NewRequest("PUT", "/api/settings", strings.NewReader(`{"concurrency":0}`)) |
| 232 | w = httptest.NewRecorder() |
| 233 | mux.ServeHTTP(w, req) |
| 234 | if w.Code != http.StatusUnprocessableEntity { |
| 235 | t.Fatal(w.Code) |
| 236 | } |
| 237 | h.Tracker.Start(JobInfo{ID: 5, Name: "build"}) |
| 238 | req = httptest.NewRequest("POST", "/api/pause", nil) |
| 239 | w = httptest.NewRecorder() |
| 240 | mux.ServeHTTP(w, req) |
| 241 | if !strings.Contains(w.Body.String(), `"safe_to_upgrade":false`) || !h.Tracker.Paused() { |
| 242 | t.Fatal(w.Body.String()) |
| 243 | } |
| 244 | h.Tracker.Finish(5, "success") |
| 245 | req = httptest.NewRequest("GET", "/api/status", nil) |
| 246 | w = httptest.NewRecorder() |
| 247 | mux.ServeHTTP(w, req) |
| 248 | if !strings.Contains(w.Body.String(), `"safe_to_upgrade":true`) || !strings.Contains(w.Body.String(), `"paused":true`) { |
| 249 | t.Fatal(w.Body.String()) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | func TestCleanupCache(t *testing.T) { |
| 254 | dir := t.TempDir() |
| 255 | for i, n := range []string{"old", "new"} { |
| 256 | p := filepath.Join(dir, n) |
| 257 | _ = os.MkdirAll(p, 0o755) |
| 258 | _ = os.WriteFile(filepath.Join(p, "f"), make([]byte, 1<<20), 0o644) |
| 259 | _ = os.Chtimes(p, time.Now().Add(time.Duration(i)*time.Hour), time.Now().Add(time.Duration(i)*time.Hour)) |
| 260 | } |
| 261 | got := pruneDir(dir, 1<<20) |
| 262 | if len(got) != 1 || !strings.Contains(got[0], "old") { |
| 263 | t.Fatal(got) |
| 264 | } |
| 265 | } |