| 1 | |
| 2 | |
| 3 | |
| 4 | package qemu |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "net" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 16 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 17 | ) |
| 18 | |
| 19 | func TestMemoryTargetQMPProtocolAndCancellation(t *testing.T) { |
| 20 | for _, stall := range []bool{false, true} { |
| 21 | t.Run(map[bool]string{false: "command", true: "cancelled"}[stall], func(t *testing.T) { |
| 22 | dir, err := os.MkdirTemp("", "cqm-") |
| 23 | if err != nil { |
| 24 | t.Fatal(err) |
| 25 | } |
| 26 | defer os.RemoveAll(dir) |
| 27 | memory := "4GiB" |
| 28 | l := &LimaQemuDriver{Instance: &limatype.Instance{Dir: dir, Config: &limatype.LimaYAML{Memory: &memory}}} |
| 29 | listener, err := net.Listen("unix", filepath.Join(dir, filenames.QMPSock)) |
| 30 | if err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | defer listener.Close() |
| 34 | done := make(chan error, 1) |
| 35 | go func() { |
| 36 | conn, e := listener.Accept() |
| 37 | if e != nil { |
| 38 | done <- e |
| 39 | return |
| 40 | } |
| 41 | defer conn.Close() |
| 42 | _ = conn.SetDeadline(time.Now().Add(time.Second)) |
| 43 | if stall { |
| 44 | var b [1]byte |
| 45 | _, e = conn.Read(b[:]) |
| 46 | done <- e |
| 47 | return |
| 48 | } |
| 49 | enc, dec := json.NewEncoder(conn), json.NewDecoder(conn) |
| 50 | _ = enc.Encode(map[string]any{"QMP": map[string]any{}}) |
| 51 | for i := 1; i <= 2; i++ { |
| 52 | var request struct { |
| 53 | ID int `json:"id"` |
| 54 | Execute string `json:"execute"` |
| 55 | Arguments struct { |
| 56 | Value uint64 `json:"value"` |
| 57 | } `json:"arguments"` |
| 58 | } |
| 59 | if e = dec.Decode(&request); e != nil { |
| 60 | done <- e |
| 61 | return |
| 62 | } |
| 63 | if request.ID != i || (i == 1 && request.Execute != "qmp_capabilities") || (i == 2 && (request.Execute != "balloon" || request.Arguments.Value != 2<<30)) { |
| 64 | t.Error("wrong QMP request", request) |
| 65 | } |
| 66 | _ = enc.Encode(map[string]any{"event": "BALLOON_CHANGE"}) |
| 67 | _ = enc.Encode(map[string]any{"id": i, "return": map[string]any{}}) |
| 68 | } |
| 69 | done <- nil |
| 70 | }() |
| 71 | ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| 72 | defer cancel() |
| 73 | started := time.Now() |
| 74 | err = l.SetMemoryTarget(ctx, 2<<30) |
| 75 | if (err != nil) != stall { |
| 76 | t.Fatal("unexpected command result", err) |
| 77 | } |
| 78 | if time.Since(started) > time.Second { |
| 79 | t.Fatal("deadline ignored") |
| 80 | } |
| 81 | if e := <-done; e != nil && !stall { |
| 82 | t.Fatal(e) |
| 83 | } |
| 84 | if err := l.SetMemoryTarget(context.Background(), 5<<30); err == nil { |
| 85 | t.Fatal("capacity exceeded") |
| 86 | } |
| 87 | }) |
| 88 | } |
| 89 | } |