snapshot with prefault=true faults in full hotplug memory size with virtio-mem

Abierto
#9,393 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
30/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
linux, rust

Línea de trabajo

Start from the vm.restore API path with prefault set, and check how the restore maps guest memory for the virtio-mem region. The reproducer shows the restored process's RssAnon peak with prefault on, so reproduce it by running the attached Go program against a local build. Done means the prefaulted restore peaks near boot memory plus plugged memory, not the full hotplug_size, and the program's PASS line appears.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Describe the bug

  1. Boot a kernel with a non-zero hotplug_size using virtio-mem
  2. Resize the VM memory to use a portion of the hotplug size
  3. Pause and snapshot the VM
  4. Restore the VM from the snapshot with prefault=true

If I do this, the restored VM will fault in the full hotplug size, not just the allocated size. The memory allocation is only temporary, as cloud-hypervisor will release it after the restore completes. But the temporary allocation can blow past any existing memory limits on the VM.

To Reproduce

Here is a Go program that can be used to reproduce the problem. This program was written by Claude.

// Command ch-virtio-mem-prefault shows that restoring a Cloud Hypervisor // snapshot with prefault faults in the whole virtio-mem region (hotplug_size), // not only the memory the guest had plugged (hotplugged_size). // // It boots a guest with boot memory and a virtio-mem region, has the guest plug // part of the region, pauses it and takes a snapshot. It then restores the // snapshot in a new cloud-hypervisor process through PUT /api/v1/vm.restore, // once with prefault off and once with it on, sampling the process's anonymous // RSS from the moment it starts. Cloud Hypervisor gives the unplugged part back // once the restore is done, so only the peak shows the problem. // // Expected: both restores peak at about the guest's memory, boot memory plus // what it plugged. Actual: the prefaulted restore peaks at boot memory plus the // whole region. With a large region (hotplug_size of tens of GiB) that is // enough to run the host out of memory. // // It needs root (for /dev/kvm), a guest kernel with CONFIG_VIRTIO_MEM, and an // initramfs whose init keeps the guest running (any idle loop will do). To be // safe, run it in a memory-capped scope: // // sudo systemd-run --scope -p MemoryMax=8G -p MemorySwapMax=0 \ // go run . -ch /path/to/cloud-hypervisor -kernel bzImage -initramfs initramfs.cpio.gz // // It exits 1 if a restore peaks above the guest's memory plus -slack MiB. package main

import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)

const mib = 1 << 20

func main() {
ch := flag.String("ch", "", "cloud-hypervisor binary")
kernel := flag.String("kernel", "", "guest kernel")
initramfs := flag.String("initramfs", "", "guest initramfs")
bootMiB := flag.Int64("boot", 512, "boot memory, MiB")
hotplugMiB := flag.Int64("hotplug", 4096, "virtio-mem region (hotplug_size), MiB")
plugMiB := flag.Int64("plug", 256, "memory the guest plugs into the region, MiB")
slackMiB := flag.Int64("slack", 256, "RSS over the guest's memory still counted as a pass, MiB")
flag.Parse()
if *ch == "" || *kernel == "" || *initramfs == "" {
flag.Usage()
os.Exit(2)
}
boot, hotplug, plug := bootMiBmib, hotplugMiBmib, plugMiBmib
guest := boot + plug

work, err := os.MkdirTemp("", "ch-virtio-mem-prefault-")
if err != nil {
	log.Fatal(err)
}
defer os.RemoveAll(work)
snapshot := filepath.Join(work, "snapshot")
if err := os.Mkdir(snapshot, 0o700); err != nil {
	log.Fatal(err)
}

// Boot, plug, pause, snapshot.
vmm := start(*ch, work, "boot",
	"--kernel", *kernel, "--initramfs", *initramfs, "--cmdline", "console=hvc0",
	"--cpus", "boot=1",
	"--memory", fmt.Sprintf("size=%d,hotplug_method=virtio-mem,hotplug_size=%d", boot, hotplug),
	"--console", "file="+filepath.Join(work, "console.log"), "--serial", "off")
vmm.put("vm.resize", map[string]any{"desired_ram": guest})
waitFor("the guest to plug its memory", func() bool { return vmm.info().MemoryActualSize == guest })
memory := vmm.info().Config.Memory
vmm.put("vm.pause", nil)
vmm.put("vm.snapshot", map[string]any{"destination_url": "file://" + snapshot})
vmm.kill()

// Restore without and with prefault.
peaks := map[bool]int64{}
for _, prefault := range []bool{false, true} {
	vmm := start(*ch, work, fmt.Sprintf("restore-prefault-%v", prefault))
	peak := sampleRSS(vmm.cmd.Process.Pid)
	vmm.put("vm.restore", map[string]any{"source_url": "file://" + snapshot, "prefault": prefault})
	waitFor("the restore", func() bool { return vmm.info().State == "Paused" })
	peaks[prefault] = peak.stop()
	vmm.kill()
}

version, _ := exec.Command(*ch, "--version").Output()
fmt.Println(strings.TrimSpace(string(version)))
fmt.Printf("memory config: size=%d hotplug_size=%d hotplugged_size=%d\n", memory.Size, memory.HotplugSize, memory.HotpluggedSize)
fmt.Printf("guest memory (boot + plugged):            %6d MiB\n", guest/mib)
fmt.Printf("virtio-mem region (hotplug_size):         %6d MiB\n", hotplug/mib)
fmt.Printf("peak RssAnon during restore, prefault=off: %6d MiB\n", peaks[false]/mib)
fmt.Printf("peak RssAnon during restore, prefault=on:  %6d MiB\n", peaks[true]/mib)
if peaks[true] > guest+*slackMiB*mib {
	fmt.Printf("FAIL: the prefaulted restore held %d MiB, more than the guest's %d MiB: the unplugged virtio-mem region was faulted in\n",
		peaks[true]/mib, guest/mib)
	os.Exit(1)
}
fmt.Println("PASS: the prefaulted restore faulted in only the guest's memory")

}

// vmm is a cloud-hypervisor process and a client of its API.
type vmm struct {
cmd *exec.Cmd
client *http.Client
}

// start runs cloud-hypervisor with args and waits for its API.
func start(ch, work, name string, args ...string) *vmm {
sock := filepath.Join(work, name+".sock")
logFile, err := os.Create(filepath.Join(work, name+".log"))
if err != nil {
log.Fatal(err)
}
cmd := exec.Command(ch, append([]string{"--api-socket", "path=" + sock}, args...)...)
cmd.Stdout, cmd.Stderr = logFile, logFile
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
v := &vmm{cmd: cmd, client: &http.Client{
Timeout: time.Minute,
Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, "unix", sock)
}},
}}
waitFor("the API socket of "+name, func() bool {
_, err := v.call(http.MethodGet, "vmm.ping", nil)
return err == nil
})
return v
}

func (v *vmm) kill() {
v.cmd.Process.Kill()
v.cmd.Wait()
}

func (v *vmm) call(method, endpoint string, body any) ([]byte, error) {
var r io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return nil, err
}
r = bytes.NewReader(b)
}
req, err := http.NewRequest(method, "http://localhost/api/v1/"+endpoint, r)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := v.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode >= 300 {
return nil, fmt.Errorf("%s %s: %s %s", method, endpoint, resp.Status, data)
}
return data, nil
}

func (v *vmm) put(endpoint string, body any) {
if _, err := v.call(http.MethodPut, endpoint, body); err != nil {
log.Fatal(err)
}
}

type vmInfo struct {
State string json:"state"
MemoryActualSize int64 json:"memory_actual_size"
Config struct {
Memory struct {
Size int64 json:"size"
HotplugSize int64 json:"hotplug_size"
HotpluggedSize int64 json:"hotplugged_size"
} json:"memory"
} json:"config"
}

func (v *vmm) info() vmInfo {
data, err := v.call(http.MethodGet, "vm.info", nil)
if err != nil {
log.Fatal(err)
}
var info vmInfo
if err := json.Unmarshal(data, &info); err != nil {
log.Fatal(err)
}
return info
}

func waitFor(what string, done func() bool) {
deadline := time.Now().Add(time.Minute)
for !done() {
if time.Now().After(deadline) {
log.Fatalf("timed out waiting for %s", what)
}
time.Sleep(100 * time.Millisecond)
}
}

// rssSampler records a process's peak anonymous RSS.
type rssSampler struct {
stopped chan struct{}
wg sync.WaitGroup
peak int64
}

// sampleRSS samples pid's RssAnon every 20 ms until stop.
func sampleRSS(pid int) *rssSampler {
s := &rssSampler{stopped: make(chan struct{})}
s.wg.Go(func() {
for {
if rss, err := rssAnon(pid); err == nil {
s.peak = max(s.peak, rss)
}
select {
case <-s.stopped:
return
case <-time.After(20 * time.Millisecond):
}
}
})
return s
}

// stop waits a moment more for the restore to settle, then returns the peak.
func (s *rssSampler) stop() int64 {
time.Sleep(2 * time.Second)
close(s.stopped)
s.wg.Wait()
return s.peak
}

func rssAnon(pid int) (int64, error) {
f, err := os.Open(fmt.Sprintf("/proc/%d/status", pid))
if err != nil {
return 0, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if rest, ok := strings.CutPrefix(scanner.Text(), "RssAnon:"); ok {
kb, err := strconv.ParseInt(strings.TrimSuffix(strings.TrimSpace(rest), " kB"), 10, 64)
return kb * 1024, err
}
}
return 0, errors.New("no RssAnon")
}

Version

Output of cloud-hypervisor --version:

Tested on v53, v54, and HEAD. HEAD --version output is cloud-hypervisor v54.0-710-gd58e108b2.

Did you build from source, if so build command line (e.g. features):

Built from source using dev_cli.sh --release

VM configuration

What command line did you run (or JSON config data):

See the reproducer.

Lenguaje dominante
Rust
Estrellas
6.3k
Forks
786
Merge medio
1 d 3 h
PR fusionados (30 d)
195

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de cloud-hypervisor/cloud-hypervisor

Todos los issues de cloud-hypervisor/cloud-hypervisor

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.