| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "os" |
| 6 | "testing" |
| 7 | |
| 8 | "github.com/sylvinus/agent-vm/internal/cage" |
| 9 | "github.com/sylvinus/agent-vm/internal/host" |
| 10 | ) |
| 11 | |
| 12 | func TestResourceAllocationSaveAndStartup(t *testing.T) { |
| 13 | oldMem, oldCPU := host.MemGiB, host.CPUs |
| 14 | t.Cleanup(func() { host.MemGiB, host.CPUs = oldMem, oldCPU }) |
| 15 | host.MemGiB = func() int { return 24 } |
| 16 | host.CPUs = func() int { return 10 } |
| 17 | t.Setenv("AGENT_VM_HOST_SHARE", "2") |
| 18 | s := testServer(t) |
| 19 | check := func(memory, cpus int) { |
| 20 | t.Helper() |
| 21 | m, c, err := cage.ConfiguredResourceLimits(s.configPath) |
| 22 | if err != nil || m != memory || c != cpus { |
| 23 | t.Fatalf("startup limits = %d/%d, %v", m, c, err) |
| 24 | } |
| 25 | } |
| 26 | check(12, 5) |
| 27 | for _, body := range []string{ |
| 28 | `{"allocation":{"automatic":false,"memory_gib":0,"cpus":2}}`, |
| 29 | `{"allocation":{"automatic":false,"memory_gib":13,"cpus":2}}`, |
| 30 | `{"allocation":{"automatic":false,"memory_gib":4,"cpus":6}}`, |
| 31 | `{"allocation":{"automatic":false,"memory_gib":4.5,"cpus":2}}`, |
| 32 | } { |
| 33 | if w := request(s, "POST", "/api/environment/resources", s.origin, body, true); w.Code == 200 { |
| 34 | t.Fatalf("accepted invalid allocation: %s", body) |
| 35 | } |
| 36 | check(12, 5) |
| 37 | } |
| 38 | before, _ := os.ReadFile(s.configPath) |
| 39 | if w := request(s, "POST", "/api/environment/resources", s.origin, `{"allocation":{"automatic":false,"memory_gib":4,"cpus":2}}`, true); w.Code != 200 { |
| 40 | t.Fatal(w.Code, w.Body.String()) |
| 41 | } |
| 42 | check(4, 2) |
| 43 | after, _ := os.ReadFile(s.configPath) |
| 44 | if string(before) != string(after) { |
| 45 | t.Fatal("resource save changed network configuration") |
| 46 | } |
| 47 | w := request(s, "GET", "/api/environment/resources", "", "", true) |
| 48 | var status struct { |
| 49 | Automatic bool `json:"automatic"` |
| 50 | Memory int `json:"memory_gib"` |
| 51 | CPUs int `json:"cpus"` |
| 52 | } |
| 53 | if err := json.Unmarshal(w.Body.Bytes(), &status); err != nil || status.Automatic || status.Memory != 4 || status.CPUs != 2 { |
| 54 | t.Fatal(w.Body.String(), err) |
| 55 | } |
| 56 | s.op.Lock() |
| 57 | w = request(s, "POST", "/api/environment/resources", s.origin, `{"allocation":{"automatic":true}}`, true) |
| 58 | s.op.Unlock() |
| 59 | if w.Code != 409 { |
| 60 | t.Fatal("save must not race an environment operation", w.Code) |
| 61 | } |
| 62 | check(4, 2) |
| 63 | if w = request(s, "POST", "/api/environment/resources", s.origin, `{"allocation":{"automatic":true}}`, true); w.Code != 200 { |
| 64 | t.Fatal(w.Body.String()) |
| 65 | } |
| 66 | check(12, 5) |
| 67 | } |