| 1 | package cage |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 14 | "github.com/sylvinus/agent-vm/internal/host" |
| 15 | ) |
| 16 | |
| 17 | func TestResourceLimitsUseExistingHostShare(t *testing.T) { |
| 18 | oldMem, oldCPU := host.MemGiB, host.CPUs |
| 19 | t.Cleanup(func() { host.MemGiB, host.CPUs = oldMem, oldCPU }) |
| 20 | for _, tc := range []struct{ memory, cpu, wantMemory, wantCPU int }{{24, 10, 12, 5}, {8, 4, 4, 2}, {4, 2, 2, 1}, {0, 0, 4, 2}} { |
| 21 | host.MemGiB = func() int { return tc.memory } |
| 22 | host.CPUs = func() int { return tc.cpu } |
| 23 | t.Setenv("AGENT_VM_HOST_SHARE", "2") |
| 24 | memory, cpus := ResourceLimits() |
| 25 | if memory != tc.wantMemory || cpus != tc.wantCPU { |
| 26 | t.Fatal(tc, memory, cpus) |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | func TestResourceFailuresKeepDiagnosticCausePrivate(t *testing.T) { |
| 32 | profile := t.TempDir() |
| 33 | previous := diagnostics.Default() |
| 34 | diagnostics.SetDefault(diagnostics.New(profile)) |
| 35 | t.Cleanup(func() { diagnostics.SetDefault(previous) }) |
| 36 | dir := t.TempDir() |
| 37 | var attempts int |
| 38 | stop := StartResourceManager(context.Background(), dir, 4<<30, 2, func(context.Context, string) ([]byte, error) { |
| 39 | attempts++ |
| 40 | if attempts <= 2 { |
| 41 | return nil, errors.New("resource probe execution failed: exit status 255; stderr=getsockname failed: Not a socket; token=private-probe-token") |
| 42 | } |
| 43 | return []byte("invalid metrics"), nil |
| 44 | }, func(context.Context, uint64) error { t.Error("failed sample changed memory target"); return nil }) |
| 45 | defer stop() |
| 46 | deadline := time.Now().Add(9 * time.Second) |
| 47 | var log []byte |
| 48 | for time.Now().Before(deadline) { |
| 49 | log, _ = os.ReadFile(filepath.Join(profile, "logs", "events.jsonl")) |
| 50 | if strings.Contains(string(log), "incomplete guest resource observation") { |
| 51 | break |
| 52 | } |
| 53 | time.Sleep(25 * time.Millisecond) |
| 54 | } |
| 55 | if !strings.Contains(string(log), "Not a socket") || !strings.Contains(string(log), "incomplete guest resource observation") { |
| 56 | t.Fatalf("failure causes missing from diagnostics: %s", log) |
| 57 | } |
| 58 | if strings.Contains(string(log), "private-probe-token") || strings.Count(string(log), "Not a socket") != 1 { |
| 59 | t.Fatalf("secret leaked or repeated failure flooded log: %s", log) |
| 60 | } |
| 61 | status, err := ReadResourceStatus(dir) |
| 62 | if err != nil || !strings.Contains(status.Error, "自动回收内存已暂停") || strings.Contains(status.Error, "Not a socket") || strings.Contains(status.Error, "private-probe-token") { |
| 63 | t.Fatalf("technical detail escaped to resource status: %+v %v", status, err) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | func TestMemoryPolicyBurstIdleAndHostPressure(t *testing.T) { |
| 68 | now := time.Now() |
| 69 | gib := uint64(1 << 30) |
| 70 | p := memoryPolicy{maximum: 12 * gib, target: 4 * gib} |
| 71 | busy := ResourceSample{Total: 4*gib - 128<<20, Available: 128 << 20} |
| 72 | if got := p.next(now, busy, false); got != 12*gib { |
| 73 | t.Fatalf("burst gets %d", got) |
| 74 | } |
| 75 | if got := p.next(now, busy, true); got != 4*gib { |
| 76 | t.Fatalf("host pressure grows to %d", got) |
| 77 | } |
| 78 | p.target = p.maximum |
| 79 | idle := ResourceSample{Total: 12*gib - 128<<20, Available: 10 * gib} |
| 80 | if got := p.next(now, idle, false); got != p.maximum { |
| 81 | t.Fatal("immediate shrink", got) |
| 82 | } |
| 83 | if got := p.next(now.Add(29*time.Second), idle, false); got != p.maximum { |
| 84 | t.Fatal("premature shrink", got) |
| 85 | } |
| 86 | next := p.next(now.Add(31*time.Second), idle, false) |
| 87 | if next != p.maximum-256<<20 { |
| 88 | t.Fatalf("reclamation step %d", next) |
| 89 | } |
| 90 | p.target = next |
| 91 | if got := p.next(now.Add(33*time.Second), idle, false); got != next { |
| 92 | t.Fatal("repeated shrink before guest acknowledgement", got) |
| 93 | } |
| 94 | idle.Total -= 256 << 20 |
| 95 | idle.Available -= 256 << 20 |
| 96 | idle.Balloon = 256 << 20 |
| 97 | if got := p.next(now.Add(35*time.Second), idle, false); got >= next { |
| 98 | t.Fatal("no reclamation after acknowledgement", got) |
| 99 | } |
| 100 | |
| 101 | p.next(now.Add(36*time.Second), busy, false) |
| 102 | if got := p.next(now.Add(37*time.Second), idle, false); got != p.target { |
| 103 | t.Fatal("shrunk after burst", got) |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | func TestResourcesRejectIncompleteOrImpossibleObservation(t *testing.T) { |
| 108 | valid := "MemTotal: 4000000\nMemAvailable: 2000000\nSwapTotal: 1000\nSwapFree: 500\noom_kill 3\nsome avg10=0.50 avg60=0.0 total=2\ncpu 10 0 5 20 2 0 0 0 0 0\nboot 12345678-1234-1234-1234-123456789012\n" |
| 109 | s, err := parseResources([]byte(valid)) |
| 110 | if err != nil || s.Available != 2000000<<10 || s.OOMKills != 3 || s.Stall != .5 { |
| 111 | t.Fatal(s, err) |
| 112 | } |
| 113 | balloon, err := parseResources([]byte(valid + "balloon_inflate 131072\nballoon_deflate 65536\npage_size 4096\n")) |
| 114 | if err != nil || balloon.Balloon != 256<<20 { |
| 115 | t.Fatal("balloon acknowledgement lost", balloon, err) |
| 116 | } |
| 117 | for _, invalid := range []string{strings.Replace(valid, "MemAvailable: 2000000", "MemAvailable: 5000000", 1), strings.Replace(valid, "MemAvailable: 2000000\n", "", 1), strings.Replace(valid, "oom_kill 3\n", "", 1), strings.Replace(valid, "SwapFree: 500", "SwapFree: 1001", 1)} { |
| 118 | if _, err := parseResources([]byte(invalid)); err == nil { |
| 119 | t.Fatal("accepted invalid sample") |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | func TestResourceManagerCancellationAndFreshness(t *testing.T) { |
| 125 | ctx, cancel := context.WithCancel(context.Background()) |
| 126 | cancel() |
| 127 | stop := StartResourceManager(ctx, t.TempDir(), 4<<30, 2, func(context.Context, string) ([]byte, error) { |
| 128 | t.Error("read after cancellation") |
| 129 | return nil, fmt.Errorf("unused") |
| 130 | }, func(context.Context, uint64) error { t.Error("change after cancellation"); return nil }) |
| 131 | done := make(chan struct{}) |
| 132 | go func() { stop(); stop(); close(done) }() |
| 133 | select { |
| 134 | case <-done: |
| 135 | case <-time.After(time.Second): |
| 136 | t.Fatal("stop did not join") |
| 137 | } |
| 138 | dir := t.TempDir() |
| 139 | for _, age := range []time.Duration{0, 11 * time.Second} { |
| 140 | if err := writeResourceStatus(dir, ResourceStatus{Version: 1, UpdatedAt: time.Now().Add(-age)}); err != nil { |
| 141 | t.Fatal(err) |
| 142 | } |
| 143 | _, err := ReadResourceStatus(dir) |
| 144 | if (err != nil) != (age > 0) { |
| 145 | t.Fatal(age, err) |
| 146 | } |
| 147 | } |
| 148 | } |