| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | @@ -525,6 +525,10 @@ func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err er |
| 6 | } |
| 7 | memBytes = adjustMemBytesDarwinARM64HVF(memBytes, accel) |
| 8 | args = appendArgsIfNoConflict(args, "-m", strconv.Itoa(int(memBytes>>20))) |
| 9 | + // A balloon returns guest pages to the host without restarting the VM. |
| 10 | + if *y.OS == limatype.LINUX { |
| 11 | + args = append(args, "-device", "virtio-balloon") |
| 12 | + } |
| 13 | |
| 14 | if *y.MountType == limatype.VIRTIOFS { |
| 15 | args = appendArgsIfNoConflict(args, "-object", |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | @@ -448,6 +448,9 @@ func (a *HostAgent) Run(ctx context.Context) error { |
| 21 | if err := a.driver.AdditionalSetupForSSH(ctx); err != nil { |
| 22 | return err |
| 23 | } |
| 24 | + stopResources := a.startResourceManager(ctx) |
| 25 | + defer stopResources() |
| 26 | + a.cleanUp(func() error { stopResources(); return nil }) |
| 27 | |
| 28 | // WSL instance SSH address isn't known until after VM start |
| 29 | if a.driver.Info(ctx).Features.DynamicSSHAddress { |
| 30 | |
| 31 | new file mode 100644 |
| 32 | |
| 33 | |
| 34 | |
| 35 | @@ -0,0 +1,12 @@ |
| 36 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 37 | +// SPDX-License-Identifier: Apache-2.0 |
| 38 | + |
| 39 | +package driver |
| 40 | + |
| 41 | +import "context" |
| 42 | + |
| 43 | +// MemoryBalloon adjusts guest memory within the configured boot capacity. |
| 44 | +// Acceptance is asynchronous; callers must observe the guest before reclaiming more. |
| 45 | +type MemoryBalloon interface { |
| 46 | + SetMemoryTarget(context.Context, uint64) error |
| 47 | +} |
| 48 | |
| 49 | new file mode 100644 |
| 50 | |
| 51 | |
| 52 | |
| 53 | @@ -0,0 +1,81 @@ |
| 54 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 55 | +// SPDX-License-Identifier: Apache-2.0 |
| 56 | + |
| 57 | +package qemu |
| 58 | + |
| 59 | +import ( |
| 60 | + "context" |
| 61 | + "encoding/json" |
| 62 | + "errors" |
| 63 | + "fmt" |
| 64 | + "io" |
| 65 | + "net" |
| 66 | + "path/filepath" |
| 67 | + "time" |
| 68 | + |
| 69 | + "github.com/docker/go-units" |
| 70 | + "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 71 | +) |
| 72 | + |
| 73 | +func (l *LimaQemuDriver) SetMemoryTarget(ctx context.Context, target uint64) error { |
| 74 | + if err := ctx.Err(); err != nil { |
| 75 | + return err |
| 76 | + } |
| 77 | + maximum, err := units.RAMInBytes(*l.Instance.Config.Memory) |
| 78 | + if err != nil { |
| 79 | + return err |
| 80 | + } |
| 81 | + if target < 512<<20 || target > uint64(maximum) || target%(1<<20) != 0 { |
| 82 | + return errors.New("memory target is outside the VM capacity") |
| 83 | + } |
| 84 | + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| 85 | + defer cancel() |
| 86 | + conn, err := (&net.Dialer{}).DialContext(ctx, "unix", filepath.Join(l.Instance.Dir, filenames.QMPSock)) |
| 87 | + if err != nil { |
| 88 | + return err |
| 89 | + } |
| 90 | + defer conn.Close() |
| 91 | + stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) |
| 92 | + defer stop() |
| 93 | + deadline, _ := ctx.Deadline() |
| 94 | + if err := conn.SetDeadline(deadline); err != nil { |
| 95 | + return err |
| 96 | + } |
| 97 | + decoder := json.NewDecoder(io.LimitReader(conn, 64<<10)) |
| 98 | + var greeting map[string]json.RawMessage |
| 99 | + if err := decoder.Decode(&greeting); err != nil { |
| 100 | + return err |
| 101 | + } |
| 102 | + if greeting["QMP"] == nil { |
| 103 | + return errors.New("invalid QMP greeting") |
| 104 | + } |
| 105 | + encoder := json.NewEncoder(conn) |
| 106 | + for i, command := range []string{"qmp_capabilities", "balloon"} { |
| 107 | + request := map[string]any{"execute": command, "id": i + 1} |
| 108 | + if command == "balloon" { |
| 109 | + request["arguments"] = map[string]uint64{"value": target} |
| 110 | + } |
| 111 | + if err := encoder.Encode(request); err != nil { |
| 112 | + return err |
| 113 | + } |
| 114 | + for { |
| 115 | + var response struct { |
| 116 | + ID int `json:"id"` |
| 117 | + Error *struct { |
| 118 | + Class string `json:"class"` |
| 119 | + } `json:"error"` |
| 120 | + } |
| 121 | + if err := decoder.Decode(&response); err != nil { |
| 122 | + return err |
| 123 | + } |
| 124 | + if response.ID != i+1 { |
| 125 | + continue |
| 126 | + } |
| 127 | + if response.Error != nil { |
| 128 | + return fmt.Errorf("QMP memory adjustment failed: %s", response.Error.Class) |
| 129 | + } |
| 130 | + break |
| 131 | + } |
| 132 | + } |
| 133 | + return nil |
| 134 | +} |
| 135 | |
| 136 | new file mode 100644 |
| 137 | |
| 138 | |
| 139 | |
| 140 | @@ -0,0 +1,89 @@ |
| 141 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 142 | +// SPDX-License-Identifier: Apache-2.0 |
| 143 | + |
| 144 | +package qemu |
| 145 | + |
| 146 | +import ( |
| 147 | + "context" |
| 148 | + "encoding/json" |
| 149 | + "net" |
| 150 | + "os" |
| 151 | + "path/filepath" |
| 152 | + "testing" |
| 153 | + "time" |
| 154 | + |
| 155 | + "github.com/lima-vm/lima/v2/pkg/limatype" |
| 156 | + "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 157 | +) |
| 158 | + |
| 159 | +func TestMemoryTargetQMPProtocolAndCancellation(t *testing.T) { |
| 160 | + for _, stall := range []bool{false, true} { |
| 161 | + t.Run(map[bool]string{false: "command", true: "cancelled"}[stall], func(t *testing.T) { |
| 162 | + dir, err := os.MkdirTemp("", "cqm-") |
| 163 | + if err != nil { |
| 164 | + t.Fatal(err) |
| 165 | + } |
| 166 | + defer os.RemoveAll(dir) |
| 167 | + memory := "4GiB" |
| 168 | + l := &LimaQemuDriver{Instance: &limatype.Instance{Dir: dir, Config: &limatype.LimaYAML{Memory: &memory}}} |
| 169 | + listener, err := net.Listen("unix", filepath.Join(dir, filenames.QMPSock)) |
| 170 | + if err != nil { |
| 171 | + t.Fatal(err) |
| 172 | + } |
| 173 | + defer listener.Close() |
| 174 | + done := make(chan error, 1) |
| 175 | + go func() { |
| 176 | + conn, e := listener.Accept() |
| 177 | + if e != nil { |
| 178 | + done <- e |
| 179 | + return |
| 180 | + } |
| 181 | + defer conn.Close() |
| 182 | + _ = conn.SetDeadline(time.Now().Add(time.Second)) |
| 183 | + if stall { |
| 184 | + var b [1]byte |
| 185 | + _, e = conn.Read(b[:]) |
| 186 | + done <- e |
| 187 | + return |
| 188 | + } |
| 189 | + enc, dec := json.NewEncoder(conn), json.NewDecoder(conn) |
| 190 | + _ = enc.Encode(map[string]any{"QMP": map[string]any{}}) |
| 191 | + for i := 1; i <= 2; i++ { |
| 192 | + var request struct { |
| 193 | + ID int `json:"id"` |
| 194 | + Execute string `json:"execute"` |
| 195 | + Arguments struct { |
| 196 | + Value uint64 `json:"value"` |
| 197 | + } `json:"arguments"` |
| 198 | + } |
| 199 | + if e = dec.Decode(&request); e != nil { |
| 200 | + done <- e |
| 201 | + return |
| 202 | + } |
| 203 | + if request.ID != i || (i == 1 && request.Execute != "qmp_capabilities") || (i == 2 && (request.Execute != "balloon" || request.Arguments.Value != 2<<30)) { |
| 204 | + t.Error("wrong QMP request", request) |
| 205 | + } |
| 206 | + _ = enc.Encode(map[string]any{"event": "BALLOON_CHANGE"}) |
| 207 | + _ = enc.Encode(map[string]any{"id": i, "return": map[string]any{}}) |
| 208 | + } |
| 209 | + done <- nil |
| 210 | + }() |
| 211 | + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| 212 | + defer cancel() |
| 213 | + started := time.Now() |
| 214 | + err = l.SetMemoryTarget(ctx, 2<<30) |
| 215 | + if (err != nil) != stall { |
| 216 | + t.Fatal("unexpected command result", err) |
| 217 | + } |
| 218 | + if time.Since(started) > time.Second { |
| 219 | + t.Fatal("deadline ignored") |
| 220 | + } |
| 221 | + if e := <-done; e != nil && !stall { |
| 222 | + t.Fatal(e) |
| 223 | + } |
| 224 | + if err := l.SetMemoryTarget(context.Background(), 5<<30); err == nil { |
| 225 | + t.Fatal("capacity exceeded") |
| 226 | + } |
| 227 | + }) |
| 228 | + } |
| 229 | +} |
| 230 | |
| 231 | new file mode 100644 |
| 232 | |
| 233 | |
| 234 | |
| 235 | @@ -0,0 +1,43 @@ |
| 236 | +//go:build darwin && !no_vz |
| 237 | + |
| 238 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 239 | +// SPDX-License-Identifier: Apache-2.0 |
| 240 | + |
| 241 | +package vz |
| 242 | + |
| 243 | +import ( |
| 244 | + "context" |
| 245 | + "errors" |
| 246 | + "runtime" |
| 247 | + |
| 248 | + "github.com/Code-Hex/vz/v3" |
| 249 | + "github.com/docker/go-units" |
| 250 | +) |
| 251 | + |
| 252 | +func (l *LimaVzDriver) SetMemoryTarget(ctx context.Context, target uint64) error { |
| 253 | + if err := ctx.Err(); err != nil { |
| 254 | + return err |
| 255 | + } |
| 256 | + maximum, err := units.RAMInBytes(*l.Instance.Config.Memory) |
| 257 | + if err != nil { |
| 258 | + return err |
| 259 | + } |
| 260 | + if target < 512<<20 || target > uint64(maximum) || target%(1<<20) != 0 { |
| 261 | + return errors.New("memory target is outside the VM capacity") |
| 262 | + } |
| 263 | + if l.machine == nil || l.machine.State() != vz.VirtualMachineStateRunning { |
| 264 | + return errors.New("VM is not running") |
| 265 | + } |
| 266 | + for _, device := range l.machine.MemoryBalloonDevices() { |
| 267 | + if balloon := vz.AsVirtioTraditionalMemoryBalloonDevice(device); balloon != nil { |
| 268 | + // go-vz v3.7.1 wraps a borrowed NSArray member without retaining it, |
| 269 | + // but installs a releasing finalizer. The VM owns this native device. |
| 270 | + // Do not let temporary wrappers release the VM's reference. |
| 271 | + runtime.SetFinalizer(balloon, nil) |
| 272 | + balloon.SetTargetVirtualMachineMemorySize(target) |
| 273 | + runtime.KeepAlive(l.machine) |
| 274 | + return nil |
| 275 | + } |
| 276 | + } |
| 277 | + return errors.New("memory balloon is unavailable") |
| 278 | +} |
| 279 | |
| 280 | new file mode 100644 |
| 281 | |
| 282 | |
| 283 | |
| 284 | @@ -0,0 +1,59 @@ |
| 285 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 286 | +// SPDX-License-Identifier: Apache-2.0 |
| 287 | + |
| 288 | +package hostagent |
| 289 | + |
| 290 | +import ( |
| 291 | + "context" |
| 292 | + "errors" |
| 293 | + "io" |
| 294 | + "os/exec" |
| 295 | + "strconv" |
| 296 | + "sync" |
| 297 | + "time" |
| 298 | + |
| 299 | + "github.com/lima-vm/lima/v2/pkg/driver" |
| 300 | + "github.com/lima-vm/lima/v2/pkg/limatype" |
| 301 | +) |
| 302 | + |
| 303 | +// ManageResources is an optional embedding hook. It starts after the driver and |
| 304 | +// stops before it. Guest observations use the existing private SSH transport. |
| 305 | +var ManageResources func(context.Context, string, *limatype.LimaYAML, driver.MemoryBalloon, func(context.Context, string) ([]byte, error)) func() |
| 306 | + |
| 307 | +func (a *HostAgent) startResourceManager(ctx context.Context) func() { |
| 308 | + if ManageResources == nil { |
| 309 | + return func() {} |
| 310 | + } |
| 311 | + d := a.driver |
| 312 | + if configured, ok := d.(*driver.ConfiguredDriver); ok { |
| 313 | + d = configured.Driver |
| 314 | + } |
| 315 | + balloon, ok := d.(driver.MemoryBalloon) |
| 316 | + if !ok { |
| 317 | + return func() {} |
| 318 | + } |
| 319 | + read := func(ctx context.Context, script string) ([]byte, error) { |
| 320 | + args := append([]string{}, a.sshConfig.Args()...) |
| 321 | + args = append(args, "-o", "ConnectTimeout=2", "-o", "ClearAllForwardings=yes", "-T", "-p", strconv.Itoa(a.sshLocalPort), a.instSSHAddress, "--", script) |
| 322 | + cmd := exec.CommandContext(ctx, a.sshConfig.Binary(), args...) |
| 323 | + hideResourceProbe(cmd) |
| 324 | + cmd.WaitDelay = time.Second |
| 325 | + pipe, err := cmd.StdoutPipe() |
| 326 | + if err != nil { |
| 327 | + return nil, err |
| 328 | + } |
| 329 | + if err = cmd.Start(); err != nil { |
| 330 | + return nil, err |
| 331 | + } |
| 332 | + out, readErr := io.ReadAll(io.LimitReader(pipe, 16385)) |
| 333 | + if readErr != nil || len(out) > 16384 { |
| 334 | + _ = cmd.Process.Kill() |
| 335 | + _ = cmd.Wait() |
| 336 | + return nil, errors.New("resource observation exceeded its limit") |
| 337 | + } |
| 338 | + return out, cmd.Wait() |
| 339 | + } |
| 340 | + stop := ManageResources(ctx, a.instDir, a.instConfig, balloon, read) |
| 341 | + var once sync.Once |
| 342 | + return func() { once.Do(stop) } |
| 343 | +} |
| 344 | |
| 345 | new file mode 100644 |
| 346 | |
| 347 | |
| 348 | |
| 349 | @@ -0,0 +1,10 @@ |
| 350 | +//go:build !windows |
| 351 | + |
| 352 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 353 | +// SPDX-License-Identifier: Apache-2.0 |
| 354 | + |
| 355 | +package hostagent |
| 356 | + |
| 357 | +import "os/exec" |
| 358 | + |
| 359 | +func hideResourceProbe(*exec.Cmd) {} |
| 360 | |
| 361 | new file mode 100644 |
| 362 | |
| 363 | |
| 364 | |
| 365 | @@ -0,0 +1,13 @@ |
| 366 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 367 | +// SPDX-License-Identifier: Apache-2.0 |
| 368 | + |
| 369 | +package hostagent |
| 370 | + |
| 371 | +import ( |
| 372 | + "os/exec" |
| 373 | + "syscall" |
| 374 | +) |
| 375 | + |
| 376 | +func hideResourceProbe(cmd *exec.Cmd) { |
| 377 | + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: 0x08000000} |
| 378 | +} |