From 18171f94e69f6c879525254bbdf8d0f9fdf59394 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Tue, 3 Nov 2026 17:47:08 +0100 Subject: [PATCH 1/9] =?UTF-8?q?=E7=A3=81=E7=9B=98=E5=9B=9E=E6=94=B6=20S3?= =?UTF-8?q?=EF=BC=9Adisk=20trim=20=E5=90=8E=E7=AB=AF=EF=BC=88ModAVD/ModAVD?= =?UTF-8?q?#2=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modavd disk <编号> 的第一步:trim 在运行中的实例上触发客体 FITRIM(vold sm idle-maint run),让模拟器的 virtio-blk discard 路径释放被删文件占的 qcow2 簇。要求实例已开机;先探 /sys/block/vdc/queue/discard_max_bytes,为 0(旧模拟 器没有 discard 回移)就报 errs.Unsupported 并提示更新。info、compact 后续提交。 纯解析函数 parseDiscardMaxBytes 带单测。go build ./... / go vet / go test 均过。 --- internal/emu/disk.go | 106 ++++++++++++++++++++++++++++++++++++++ internal/emu/disk_test.go | 25 +++++++++ 2 files changed, 131 insertions(+) create mode 100644 internal/emu/disk.go create mode 100644 internal/emu/disk_test.go diff --git a/internal/emu/disk.go b/internal/emu/disk.go new file mode 100644 index 00000000..7f385446 --- /dev/null +++ b/internal/emu/disk.go @@ -0,0 +1,106 @@ +package emu + +// modavd disk : reclaim the space the guest freed on /data. `trim` triggers +// a guest FITRIM at runtime so the emulator's virtio-blk discard path frees the +// qcow2 clusters behind deleted files (ModAVD/ModAVD#2). `info` and `compact` +// land in later commits. trim is only useful once the emulator advertises +// discard on the data disk (the mas/discard emulator build); an older build +// reports no discard and trim returns errs.Unsupported with a clear message. + +import ( + "context" + "strconv" + "strings" + "time" + + "modavd/internal/errs" +) + +// userdataOverlay / userdataBacking name the data-disk files inside an instance +// directory (used by info and compact; the backing is read-only). +const ( + userdataOverlay = "userdata-qemu.img.qcow2" + userdataBacking = "userdata-qemu.img" +) + +// diskTrimTimeout bounds the guest idle-maintenance run. A first full trim of a +// large /data walks all the free space and can take a few seconds; later trims +// are quick. Generous so a big first pass does not time out. +const diskTrimTimeout = 2 * time.Minute + +// vdcDiscardMaxPath is the data disk's advertised discard limit in the guest. 0 +// (or the file missing) means the emulator does not advertise +// VIRTIO_BLK_F_DISCARD on /data -- i.e. an emulator without the discard +// backport, where a trim would silently do nothing. +const vdcDiscardMaxPath = "/sys/block/vdc/queue/discard_max_bytes" + +// DiskTrimResult reports what `modavd disk trim` did. +type DiskTrimResult struct { + Index int `json:"index"` + // DiscardMaxBytes is the data disk's advertised discard limit (guest + // /sys/block/vdc/queue/discard_max_bytes); >0 confirms the emulator's + // discard path is live. + DiscardMaxBytes int64 `json:"discardMaxBytes"` +} + +// parseDiscardMaxBytes reads the number printed by cat of a sysfs +// discard_max_bytes file; ok is false when the output is empty or not a number +// (the file was missing, or cat failed). +func parseDiscardMaxBytes(out string) (int64, bool) { + n, err := strconv.ParseInt(strings.TrimSpace(out), 10, 64) + if err != nil { + return 0, false + } + return n, true +} + +// DiskTrim triggers a guest FITRIM on /data (via vold idle maintenance) so the +// virtio-blk discard path frees the qcow2 clusters behind deleted files. The +// instance must be running and booted. errs.Unsupported when the instance is +// not up, or when the emulator does not advertise discard on the data disk (an +// old build); errs.Internal when the guest command fails. +func (m *Manager) DiskTrim(ctx context.Context, i int) (*DiskTrimResult, error) { + if err := requireWindows(); err != nil { + return nil, err + } + if _, err := m.instance(i); err != nil { + return nil, err + } + if _, running := m.qemuOf(i); !running { + return nil, errs.Newf(errs.Unsupported, + "魔改 AVD 实例 %d 没有在运行,请先开机再回收磁盘空间", i) + } + if !m.bootCompleted(ctx, i, statusAdbTimeout, true) { + if err := ctxErr(ctx); err != nil { + return nil, err + } + return nil, errs.Newf(errs.Unsupported, + "魔改 AVD 实例 %d 还没开机完成,请开机后再回收磁盘空间", i) + } + + // Gate on the emulator actually advertising discard on /data: an old build + // reports 0 here, and a trim would silently do nothing. + probe := m.su(ctx, i, "cat "+vdcDiscardMaxPath, 0) + if err := ctxErr(ctx); err != nil { + return nil, err + } + maxBytes, ok := parseDiscardMaxBytes(probe.Out) + if !ok || maxBytes <= 0 { + return nil, errs.Newf(errs.Unsupported, + "这个模拟器版本不支持回收磁盘空间(客体数据盘没有 discard)"). + WithAdvice("请把魔改 AVD 更新到带磁盘回收的版本,实例和游戏数据不受影响") + } + + // vold idle maintenance runs fstrim on the mounted file systems. (The exact + // mechanism may be refined to a targeted FITRIM after on-device testing, + // ModAVD/ModAVD#2 §4.3.) + res := m.su(ctx, i, "sm idle-maint run", diskTrimTimeout) + if err := ctxErr(ctx); err != nil { + return nil, err + } + if res.Code != 0 { + return nil, errs.Newf(errs.Internal, "触发磁盘回收失败: %s", + orText(tail(res.Out, 300), "退出码 "+strconv.Itoa(res.Code))) + } + return &DiskTrimResult{Index: i, DiscardMaxBytes: maxBytes}, nil +} diff --git a/internal/emu/disk_test.go b/internal/emu/disk_test.go new file mode 100644 index 00000000..6ce72dcd --- /dev/null +++ b/internal/emu/disk_test.go @@ -0,0 +1,25 @@ +package emu + +import "testing" + +func TestParseDiscardMaxBytes(t *testing.T) { + cases := []struct { + name string + out string + want int64 + ok bool + }{ + {"typical", "2147483136\n", 2147483136, true}, + {"zero means no discard", "0\n", 0, true}, + {"padded", " 65536 ", 65536, true}, + {"empty", "", 0, false}, + {"cat error", "cat: /sys/...: No such file or directory", 0, false}, + } + for _, c := range cases { + got, ok := parseDiscardMaxBytes(c.out) + if ok != c.ok || (ok && got != c.want) { + t.Errorf("%s: parseDiscardMaxBytes(%q) = (%d, %v), want (%d, %v)", + c.name, c.out, got, ok, c.want, c.ok) + } + } +} From f8a7e07766da0a914590c77f2e4795c1a13b7119 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Tue, 3 Nov 2026 18:05:56 +0100 Subject: [PATCH 2/9] =?UTF-8?q?=E7=A3=81=E7=9B=98=E5=9B=9E=E6=94=B6=20S3?= =?UTF-8?q?=EF=BC=9Adisk=20trim=20=E7=9A=84=20CLI=20=E6=8E=A5=E7=BA=BF?= =?UTF-8?q?=EF=BC=88ModAVD/ModAVD#2=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modavd disk <编号> trim:仿 bridge 的「<编号> <动作>」形状,parseIndex + 动作校验 (目前只认 trim,别的报 Usage)+ 调 emu.Manager.DiskTrim。manager 接口、人类可读 格式化 formatDisk、命令契约注释、命令名列表、README 命令表都补上,加了 TestDiskTrim。 退出码走通用 errs.ExitCode(不支持=4、用法=2),没单独写 exit 函数。 go build ./... / go vet / gofmt -l / go test ./internal/cli ./internal/emu 均过。 --- README.md | 1 + internal/cli/args_test.go | 2 +- internal/cli/cli.go | 4 +++- internal/cli/commands.go | 33 +++++++++++++++++++++++++++++++++ internal/cli/format.go | 4 ++++ internal/cli/run_test.go | 29 +++++++++++++++++++++++++++++ 6 files changed, 71 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 644d2957..d4991d1c 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] | `start [--window \| --headless] [--timeout 300] [--no-bridge]` | 开机(默认无头,`--window` 带窗口),等开完并做完开机后的设置,返回前确认 `/sdcard` 能写进文件(一般这时早已就绪;最多再等 60 秒,到点只警告);实例正在关机时(比如刚点了模拟器窗口的 ×)先等它关完(最多 30 秒)再开机;实例还没有执行桥时接着装上,`--no-bridge` 这次不装。运行中不换方式:实例已经在运行时,给了 `--window` / `--headless` 而它不是这种方式,就报错(退出码 5),不接管也不重启,要换先 `stop` 再 `start`;两个都不给就照原样接管 | | `stop [--force]`、`stop --all` | 关机:前台开着应用时先按 HOME,等 2 秒让它保存;再 sync,让安卓正常关机(前台应用先收到暂停、停止),不成再 sync + kill;`--force` 是 sync + 强杀 | | `bridge install\|uninstall\|verify` | 装、卸、检查 arm64 执行桥;开机时会自动装,一般不用手动跑(见下) | +| `disk trim` | 磁盘回收:在开着的实例里对数据盘触发一次 FITRIM,让模拟器释放已删文件占着的空间;模拟器太旧、不支持回收时返回不支持(退出码 4) | | `check [--memory M]` | 开机前的电脑检查 | | `report-config [--no-clipboard]` | 复制电脑配置和开着实例里的游戏信息(只读) | | `collect-info [--out-dir D] [--stage-dir D] [--keep-stage] [--no-explorer]` | 收集问题信息并打包(只读) | diff --git a/internal/cli/args_test.go b/internal/cli/args_test.go index dc87d570..1db35e4c 100644 --- a/internal/cli/args_test.go +++ b/internal/cli/args_test.go @@ -365,7 +365,7 @@ func TestCommandTable(t *testing.T) { } } for _, name := range []string{"list", "info", "status", "create", "set", "delete", "start", "stop", - "check", "report-config", "collect-info", "window", "install", "shell", "adb", "servers", "version", "mcp", "help"} { + "check", "report-config", "collect-info", "window", "disk", "install", "shell", "adb", "servers", "version", "mcp", "help"} { if !seen[name] { t.Errorf("command %s missing", name) } diff --git a/internal/cli/cli.go b/internal/cli/cli.go index f0040753..a6d7baf8 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -22,6 +22,7 @@ // report-config [--no-clipboard] read-only configuration and installed-game report // collect-info [--out-dir D] [--stage-dir D] ... read-only diagnostics zip // window show|hide emu.WindowResult +// disk trim emu.DiskTrimResult {index,discardMaxBytes} // install emu.InstallResult // shell [--timeout S] emu.ShellResult // adb [--] no envelope: adb's own stdio and exit code @@ -52,7 +53,7 @@ // (errs.Canceled); an emulator that was already launched keeps running (emu guarantees that). A run during which the // context ended fails with errs.Canceled even when the command returned a result, unless the command is final (its // result reports a change that was made: create, set, delete, start, stop, window, install, components fetch; -// or does not depend on the context: version, help, components status): a query whose adb calls were killed half way +// or does not depend on the context: version, help, components status; also bridge and disk trim): a query whose adb calls were killed half way // would report what it saw by then, an online instance as starting. components fetch stops at Ctrl+C with // errs.Canceled itself, between two reads of a download or an unpack and before the next component. // @@ -96,6 +97,7 @@ type manager interface { AdbPassthrough(ctx context.Context, i int, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) InstallAPK(ctx context.Context, i int, apkPath string) (*emu.InstallResult, error) Bridge(ctx context.Context, i int, action string) (*emu.BridgeResult, error) + DiskTrim(ctx context.Context, i int) (*emu.DiskTrimResult, error) EnsureServers(ctx context.Context) (*emu.ServersResult, error) // Running is the indexes whose qemu runs, from the process table only (no adb). Running(ctx context.Context) ([]int, error) diff --git a/internal/cli/commands.go b/internal/cli/commands.go index d559158a..37a8cced 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -236,6 +236,15 @@ func init() { final: true, run: runBridge, human: humanOf(formatBridge), exit: exitBridge, }, + { + name: "disk", args: " trim", summary: "磁盘回收:把客体里已删文件占的空间还给宿主", + details: "trim:在客体的数据盘(/data)上触发一次回收(FITRIM,经 vold 空闲维护)," + + "让模拟器释放已删除文件在数据盘镜像里占着的空间。实例要开着并已开机完成;" + + "模拟器版本太旧、数据盘不支持回收时返回不支持(退出码 4),不会白跑。", + posNames: []string{"实例编号", "trim"}, minPos: 2, maxPos: 2, + final: true, + run: runDisk, human: humanOf(formatDisk), + }, { name: "install", args: " ", summary: "在已开机的实例上安装 APK(adb install -r)", details: "最多等 900 秒(游戏安装包有 1–3 GB)。", @@ -992,6 +1001,30 @@ func runBridge(c *cmdCtx) (any, error) { return m.Bridge(c.ctx, i, action) } +// runDisk dispatches `disk `; only trim exists so far, add a case per new action. +func runDisk(c *cmdCtx) (any, error) { + i, err := parseIndex(c.inv.pos[0]) + if err != nil { + return nil, err + } + action := strings.ToLower(c.inv.pos[1]) + switch action { + case "trim": + default: + return nil, errs.Newf(errs.Usage, "第二个参数只能是 trim,收到「%s」", c.inv.pos[1]). + WithAdvice(findCommand("disk").usageAdvice()) + } + m, err := c.mgr() + if err != nil { + return nil, err + } + switch action { + case "trim": + return m.DiskTrim(c.ctx, i) + } + return nil, errs.Newf(errs.Internal, "disk 动作 %s 没有实现", action) +} + // exitBridge: 1 when the bridge did not end up as asked (installed after install, gone after uninstall), the script's // exit code for verify. --json: 0, the result says it. func exitBridge(data any, json bool) int { diff --git a/internal/cli/format.go b/internal/cli/format.go index 7ca38018..c92f31cd 100644 --- a/internal/cli/format.go +++ b/internal/cli/format.go @@ -590,6 +590,10 @@ func formatBridge(w io.Writer, r *emu.BridgeResult) { } } +func formatDisk(w io.Writer, r *emu.DiskTrimResult) { + fmt.Fprintf(w, "实例 %d 已触发磁盘回收(trim)\n", r.Index) +} + func formatShell(w io.Writer, r *emu.ShellResult) { if r.Output == "" { return diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index 8acc75fe..77e014ad 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -165,6 +165,11 @@ func (f *fakeManager) Bridge(ctx context.Context, i int, action string) (*emu.Br return &emu.BridgeResult{Index: i, Action: action, Installed: action == "install", Warnings: []string{}}, nil } +func (f *fakeManager) DiskTrim(ctx context.Context, i int) (*emu.DiskTrimResult, error) { + f.record("disk-trim " + itoa(i)) + return &emu.DiskTrimResult{Index: i, DiscardMaxBytes: 2147483648}, nil +} + func (f *fakeManager) InstallAPK(ctx context.Context, i int, apkPath string) (*emu.InstallResult, error) { f.record("install " + itoa(i) + " " + apkPath) if f.install != nil { @@ -995,6 +1000,30 @@ func TestInstallMakesPathAbsolute(t *testing.T) { } } +func TestDiskTrim(t *testing.T) { + h := newHarness() + r := h.run(t, nil, "disk", "3", "trim") + if r.code != 0 || r.stdout != "实例 3 已触发磁盘回收(trim)\n" { + t.Errorf("text: code %d stdout %q stderr %q", r.code, r.stdout, r.stderr) + } + if got := h.fake.callList(); len(got) != 1 || got[0] != "disk-trim 3" { + t.Errorf("calls = %q", got) + } + r = h.run(t, nil, "--json", "disk", "mas_3", "TRIM") + if m := envelope(t, r.stdout); m["ok"] != true { + t.Errorf("json: %s", r.stdout) + } + if !strings.Contains(r.stdout, `"discardMaxBytes":2147483648`) { + t.Errorf("json data: %s", r.stdout) + } + // anything but trim is a usage error and reaches no manager + h = newHarness() + r = h.run(t, nil, "disk", "3", "compact") + if r.code != 2 || len(h.fake.callList()) != 0 { + t.Errorf("bad action: code %d calls %q stderr %q", r.code, h.fake.callList(), r.stderr) + } +} + func TestMCP(t *testing.T) { h := newHarness() var got mcp.Options From cb9f75f9e93d65a761f7a566502bcc6471310db5 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Tue, 3 Nov 2026 20:10:00 +0100 Subject: [PATCH 3/9] =?UTF-8?q?=E7=A3=81=E7=9B=98=E5=9B=9E=E6=94=B6=20S3?= =?UTF-8?q?=EF=BC=9Adisk=20info=20=E5=AD=90=E5=91=BD=E4=BB=A4=EF=BC=88ModA?= =?UTF-8?q?VD/ModAVD#2=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modavd disk <编号> info:报数据盘覆盖层的逻辑大小、宿主实际占用 (GetCompressedFileSizeW)、qcow2 已分配(qemu-img check 的 allocated-clusters × 簇大小;簇大小/逻辑大小直接读 qcow2 头)、可回收估计(占用−已分配)。实例在 运行时只读文件头、不跑 qemu-img,已分配/可回收留到关机;qemu-img check 退出码 0/2/3 都解析,文件被占等其他退出码降级成 warning、不让 info 失败。 新增 win.GetCompressedFileSize(+非 Windows 桩)、root.QemuImgExe。纯解析函数 (qcow2 头、qemu-img check JSON、reclaimable)带单测。go build/vet/gofmt/test 均过。 --- README.md | 1 + internal/cli/cli.go | 4 +- internal/cli/commands.go | 18 +-- internal/cli/format.go | 41 +++++++ internal/cli/run_test.go | 48 ++++++++ internal/emu/disk.go | 221 ++++++++++++++++++++++++++++++++++++- internal/emu/disk_test.go | 75 ++++++++++++- internal/root/root.go | 11 ++ internal/root/root_test.go | 18 +++ internal/win/host.go | 26 +++++ internal/win/other.go | 3 + internal/win/win.go | 1 + internal/win/win_test.go | 16 +++ 13 files changed, 472 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index d4991d1c..73e9e2a3 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] | `stop [--force]`、`stop --all` | 关机:前台开着应用时先按 HOME,等 2 秒让它保存;再 sync,让安卓正常关机(前台应用先收到暂停、停止),不成再 sync + kill;`--force` 是 sync + 强杀 | | `bridge install\|uninstall\|verify` | 装、卸、检查 arm64 执行桥;开机时会自动装,一般不用手动跑(见下) | | `disk trim` | 磁盘回收:在开着的实例里对数据盘触发一次 FITRIM,让模拟器释放已删文件占着的空间;模拟器太旧、不支持回收时返回不支持(退出码 4) | +| `disk info` | 看数据盘的大小:逻辑大小、覆盖层在宿主上实际占的空间;实例关机时再给已分配的大小和估计能回收多少(开着时这两个数要关机后才有);只读 | | `check [--memory M]` | 开机前的电脑检查 | | `report-config [--no-clipboard]` | 复制电脑配置和开着实例里的游戏信息(只读) | | `collect-info [--out-dir D] [--stage-dir D] [--keep-stage] [--no-explorer]` | 收集问题信息并打包(只读) | diff --git a/internal/cli/cli.go b/internal/cli/cli.go index a6d7baf8..c2a906f9 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -23,6 +23,7 @@ // collect-info [--out-dir D] [--stage-dir D] ... read-only diagnostics zip // window show|hide emu.WindowResult // disk trim emu.DiskTrimResult {index,discardMaxBytes} +// disk info emu.DiskInfoResult {index,overlay,running,needsShutdown,logicalBytes,onDiskBytes,allocatedBytes?,reclaimableBytes?} // install emu.InstallResult // shell [--timeout S] emu.ShellResult // adb [--] no envelope: adb's own stdio and exit code @@ -53,7 +54,7 @@ // (errs.Canceled); an emulator that was already launched keeps running (emu guarantees that). A run during which the // context ended fails with errs.Canceled even when the command returned a result, unless the command is final (its // result reports a change that was made: create, set, delete, start, stop, window, install, components fetch; -// or does not depend on the context: version, help, components status; also bridge and disk trim): a query whose adb calls were killed half way +// or does not depend on the context: version, help, components status; also bridge and disk trim / info): a query whose adb calls were killed half way // would report what it saw by then, an online instance as starting. components fetch stops at Ctrl+C with // errs.Canceled itself, between two reads of a download or an unpack and before the next component. // @@ -98,6 +99,7 @@ type manager interface { InstallAPK(ctx context.Context, i int, apkPath string) (*emu.InstallResult, error) Bridge(ctx context.Context, i int, action string) (*emu.BridgeResult, error) DiskTrim(ctx context.Context, i int) (*emu.DiskTrimResult, error) + DiskInfo(ctx context.Context, i int) (*emu.DiskInfoResult, error) EnsureServers(ctx context.Context) (*emu.ServersResult, error) // Running is the indexes whose qemu runs, from the process table only (no adb). Running(ctx context.Context) ([]int, error) diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 37a8cced..1fc8617f 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -237,13 +237,15 @@ func init() { run: runBridge, human: humanOf(formatBridge), exit: exitBridge, }, { - name: "disk", args: " trim", summary: "磁盘回收:把客体里已删文件占的空间还给宿主", + name: "disk", args: " trim|info", summary: "磁盘回收:把客体里已删文件占的空间还给宿主;看数据盘的大小", details: "trim:在客体的数据盘(/data)上触发一次回收(FITRIM,经 vold 空闲维护)," + "让模拟器释放已删除文件在数据盘镜像里占着的空间。实例要开着并已开机完成;" + - "模拟器版本太旧、数据盘不支持回收时返回不支持(退出码 4),不会白跑。", - posNames: []string{"实例编号", "trim"}, minPos: 2, maxPos: 2, + "模拟器版本太旧、数据盘不支持回收时返回不支持(退出码 4),不会白跑。" + + "info:报数据盘的逻辑大小、在宿主上实际占的空间,以及(实例关机时)已分配的大小和估计能回收多少;" + + "实例开着时已分配和可回收的数要关机后才有,只读,不改任何东西。", + posNames: []string{"实例编号", "trim 或 info"}, minPos: 2, maxPos: 2, final: true, - run: runDisk, human: humanOf(formatDisk), + run: runDisk, human: formatDiskHuman, }, { name: "install", args: " ", summary: "在已开机的实例上安装 APK(adb install -r)", @@ -1001,7 +1003,7 @@ func runBridge(c *cmdCtx) (any, error) { return m.Bridge(c.ctx, i, action) } -// runDisk dispatches `disk `; only trim exists so far, add a case per new action. +// runDisk dispatches `disk ` (trim, info); add a case per new action. func runDisk(c *cmdCtx) (any, error) { i, err := parseIndex(c.inv.pos[0]) if err != nil { @@ -1009,9 +1011,9 @@ func runDisk(c *cmdCtx) (any, error) { } action := strings.ToLower(c.inv.pos[1]) switch action { - case "trim": + case "trim", "info": default: - return nil, errs.Newf(errs.Usage, "第二个参数只能是 trim,收到「%s」", c.inv.pos[1]). + return nil, errs.Newf(errs.Usage, "第二个参数只能是 trim 或 info,收到「%s」", c.inv.pos[1]). WithAdvice(findCommand("disk").usageAdvice()) } m, err := c.mgr() @@ -1021,6 +1023,8 @@ func runDisk(c *cmdCtx) (any, error) { switch action { case "trim": return m.DiskTrim(c.ctx, i) + case "info": + return m.DiskInfo(c.ctx, i) } return nil, errs.Newf(errs.Internal, "disk 动作 %s 没有实现", action) } diff --git a/internal/cli/format.go b/internal/cli/format.go index c92f31cd..9c5e091f 100644 --- a/internal/cli/format.go +++ b/internal/cli/format.go @@ -594,6 +594,47 @@ func formatDisk(w io.Writer, r *emu.DiskTrimResult) { fmt.Fprintf(w, "实例 %d 已触发磁盘回收(trim)\n", r.Index) } +// formatDiskHuman picks the text form of a `disk` result by its type (trim and info return different results). +func formatDiskHuman(w io.Writer, data any) { + switch r := data.(type) { + case *emu.DiskTrimResult: + if r != nil { + formatDisk(w, r) + } + case *emu.DiskInfoResult: + if r != nil { + formatDiskInfo(w, r) + } + } +} + +// fmtBytesGB is a byte count in GB with one decimal ("12.3 GB"). +func fmtBytesGB(b int64) string { + return fmt.Sprintf("%.1f GB", float64(b)/(1<<30)) +} + +func formatDiskInfo(w io.Writer, r *emu.DiskInfoResult) { + kv := func(k, v string) { fmt.Fprintf(w, "%s:%s\n", k, v) } + state := "已关机" + if r.Running { + state = "运行中" + } + kv("实例", strconv.Itoa(r.Index)+"("+state+")") + if r.LogicalBytes > 0 { + kv("数据盘逻辑大小", fmtBytesGB(r.LogicalBytes)) + } + kv("覆盖层在宿主上占用", fmtBytesGB(r.OnDiskBytes)) + if r.AllocatedBytes != nil { + kv("已分配(客体实际数据)", fmtBytesGB(*r.AllocatedBytes)) + } + if r.ReclaimableBytes != nil { + kv("估计可回收", fmtBytesGB(*r.ReclaimableBytes)) + } + for _, s := range r.Warnings { + fmt.Fprintln(w, "注意:"+s) + } +} + func formatShell(w io.Writer, r *emu.ShellResult) { if r.Output == "" { return diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index 77e014ad..cc61856e 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -170,6 +170,19 @@ func (f *fakeManager) DiskTrim(ctx context.Context, i int) (*emu.DiskTrimResult, return &emu.DiskTrimResult{Index: i, DiscardMaxBytes: 2147483648}, nil } +func (f *fakeManager) DiskInfo(ctx context.Context, i int) (*emu.DiskInfoResult, error) { + f.record("disk-info " + itoa(i)) + const gb = int64(1) << 30 + if i == 4 { // running: no allocated / reclaimable + return &emu.DiskInfoResult{Index: i, Overlay: "x", Running: true, NeedsShutdown: true, + LogicalBytes: 8 * gb, OnDiskBytes: 3 * gb, + Warnings: []string{"实例在运行:已分配和可回收的大小要关机后才能算"}}, nil + } + alloc, rec := 2*gb, gb + return &emu.DiskInfoResult{Index: i, Overlay: "x", LogicalBytes: 8 * gb, OnDiskBytes: 3 * gb, + ClusterBytes: 65536, AllocatedBytes: &alloc, ReclaimableBytes: &rec}, nil +} + func (f *fakeManager) InstallAPK(ctx context.Context, i int, apkPath string) (*emu.InstallResult, error) { f.record("install " + itoa(i) + " " + apkPath) if f.install != nil { @@ -1024,6 +1037,41 @@ func TestDiskTrim(t *testing.T) { } } +func TestDiskInfo(t *testing.T) { + h := newHarness() + r := h.run(t, nil, "disk", "3", "info") + want := "实例:3(已关机)\n数据盘逻辑大小:8.0 GB\n覆盖层在宿主上占用:3.0 GB\n" + + "已分配(客体实际数据):2.0 GB\n估计可回收:1.0 GB\n" + if r.code != 0 || r.stdout != want { + t.Errorf("text: code %d stdout %q stderr %q", r.code, r.stdout, r.stderr) + } + if got := h.fake.callList(); len(got) != 1 || got[0] != "disk-info 3" { + t.Errorf("calls = %q", got) + } + r = h.run(t, nil, "--json", "disk", "mas_3", "INFO") + if m := envelope(t, r.stdout); m["ok"] != true { + t.Errorf("json: %s", r.stdout) + } + for _, s := range []string{`"logicalBytes":8589934592`, `"onDiskBytes":3221225472`, `"allocatedBytes":2147483648`, + `"reclaimableBytes":1073741824`, `"needsShutdown":false`} { + if !strings.Contains(r.stdout, s) { + t.Errorf("json data lacks %s: %s", s, r.stdout) + } + } + // a running instance: no allocated / reclaimable, the flag and the warning say why + h = newHarness() + r = h.run(t, nil, "disk", "4", "info") + if r.code != 0 || strings.Contains(r.stdout, "估计可回收") || strings.Contains(r.stdout, "已分配(") || + !strings.Contains(r.stdout, "要关机后才能算") || !strings.Contains(r.stdout, "运行中") { + t.Errorf("running text: code %d stdout %q", r.code, r.stdout) + } + r = h.run(t, nil, "--json", "disk", "4", "info") + if strings.Contains(r.stdout, "allocatedBytes") || strings.Contains(r.stdout, "reclaimableBytes") || + !strings.Contains(r.stdout, `"needsShutdown":true`) { + t.Errorf("running json: %s", r.stdout) + } +} + func TestMCP(t *testing.T) { h := newHarness() var got mcp.Options diff --git a/internal/emu/disk.go b/internal/emu/disk.go index 7f385446..8b3464fd 100644 --- a/internal/emu/disk.go +++ b/internal/emu/disk.go @@ -2,18 +2,27 @@ package emu // modavd disk : reclaim the space the guest freed on /data. `trim` triggers // a guest FITRIM at runtime so the emulator's virtio-blk discard path frees the -// qcow2 clusters behind deleted files (ModAVD/ModAVD#2). `info` and `compact` -// land in later commits. trim is only useful once the emulator advertises +// qcow2 clusters behind deleted files (ModAVD/ModAVD#2). `info` reports the data +// disk's sizes (what a reclaim could save); `compact` lands in a later commit. trim is only useful once the emulator advertises // discard on the data disk (the mas/discard emulator build); an older build // reports no discard and trim returns errs.Unsupported with a clear message. import ( + "bytes" "context" + "encoding/binary" + "encoding/json" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" "strconv" "strings" "time" "modavd/internal/errs" + "modavd/internal/win" ) // userdataOverlay / userdataBacking name the data-disk files inside an instance @@ -104,3 +113,211 @@ func (m *Manager) DiskTrim(ctx context.Context, i int) (*DiskTrimResult, error) } return &DiskTrimResult{Index: i, DiscardMaxBytes: maxBytes}, nil } + +// diskCheckTimeout bounds one `qemu-img check` of the data disk: it reads the refcount and L1/L2 tables, seconds even +// for a large image, but a slow or busy disk gets room. +const diskCheckTimeout = 5 * time.Minute + +// DiskInfoResult reports `modavd disk info`: the sizes of the instance's data disk (the qcow2 overlay; its +// backing image is read-only and shared), so the user sees what a reclaim would save. +type DiskInfoResult struct { + Index int `json:"index"` + // Overlay is the data disk's qcow2 overlay file. + Overlay string `json:"overlay"` + // Running is true when the instance's qemu is up. The overlay is then open in qemu: AllocatedBytes and + // ReclaimableBytes are left out (NeedsShutdown), qemu-img is not run on it. + Running bool `json:"running"` + NeedsShutdown bool `json:"needsShutdown"` + // LogicalBytes is the virtual size of the disk (qcow2 header); 0 when it could not be read. + LogicalBytes int64 `json:"logicalBytes,omitempty"` + // OnDiskBytes is what the overlay occupies on the host volume (GetCompressedFileSize: a sparse file counts only + // its data). + OnDiskBytes int64 `json:"onDiskBytes"` + // ClusterBytes is the qcow2 cluster size. + ClusterBytes int64 `json:"clusterBytes,omitempty"` + // AllocatedBytes is the guest data the overlay really holds (allocated clusters x cluster size, qemu-img check); + // nil while the instance runs. + AllocatedBytes *int64 `json:"allocatedBytes,omitempty"` + // ReclaimableBytes estimates what a compact would save: OnDiskBytes minus AllocatedBytes (the rewritten image is + // about AllocatedBytes plus a little metadata, so the real saving is slightly less). nil while the instance runs + // or when the image check found errors. + ReclaimableBytes *int64 `json:"reclaimableBytes,omitempty"` + Warnings []string `json:"warnings,omitempty"` +} + +// qcow2Header is the part of a qcow2 header info needs. +type qcow2Header struct { + VirtualSize int64 + ClusterSize int64 +} + +// parseQcow2Header reads the magic, cluster_bits (offset 20) and size (offset 24) of the first bytes of a qcow2 file +// (all big-endian). +func parseQcow2Header(b []byte) (qcow2Header, error) { + if len(b) < 32 { + return qcow2Header{}, errs.New(errs.Internal, "数据盘文件太短,不是 qcow2 镜像") + } + if binary.BigEndian.Uint32(b[0:4]) != 0x514649fb { // "QFI\xfb" + return qcow2Header{}, errs.New(errs.Internal, "数据盘文件不是 qcow2 镜像") + } + bits := binary.BigEndian.Uint32(b[20:24]) + size := binary.BigEndian.Uint64(b[24:32]) + if bits < 9 || bits > 21 || size > 1<<62 { + return qcow2Header{}, errs.New(errs.Internal, "数据盘 qcow2 头里的簇大小或容量不合理") + } + return qcow2Header{VirtualSize: int64(size), ClusterSize: int64(1) << bits}, nil +} + +// qemuImgCheck is the part of `qemu-img check --output=json` info reads. Pointers: a missing field is not 0. +type qemuImgCheck struct { + AllocatedClusters *int64 `json:"allocated-clusters"` + ImageEndOffset *int64 `json:"image-end-offset"` + CheckErrors int64 `json:"check-errors"` + Corruptions int64 `json:"corruptions"` +} + +// parseQemuImgCheck decodes the JSON object of `qemu-img check --output=json`. Anything before its first "{" (a +// warning line) is ignored. errs.Internal when there is no object or no allocated-clusters. +func parseQemuImgCheck(out []byte) (qemuImgCheck, error) { + var c qemuImgCheck + start := bytes.IndexByte(out, '{') + if start < 0 { + return c, errs.Newf(errs.Internal, "qemu-img check 没有输出 JSON: %s", orText(tail(string(out), 200), "(空)")) + } + if err := json.NewDecoder(bytes.NewReader(out[start:])).Decode(&c); err != nil { + return c, errs.Wrap(errs.Internal, err, "读不懂 qemu-img check 的输出: "+err.Error()) + } + if c.AllocatedClusters == nil || *c.AllocatedClusters < 0 { + return c, errs.New(errs.Internal, "qemu-img check 的输出里没有 allocated-clusters") + } + return c, nil +} + +// runQemuImgCheck runs `qemu-img check --output=json ` and returns its stdout. Exit 0 (clean), 2 (corrupt) and +// 3 (leaked clusters) still carry the JSON report; any other exit (the file is open in a qemu, not a qcow2 ...) comes +// back as failure, the text of why, with a nil error. An error means qemu-img did not run to the end (missing, not +// startable, canceled, timed out). The image must not be open in a running qemu. +func (m *Manager) runQemuImgCheck(ctx context.Context, image string) (out []byte, failure string, err error) { + exe, err := m.Root.QemuImgExe() + if err != nil { + return nil, "", err + } + cctx, cancel := context.WithTimeout(ctx, diskCheckTimeout) + defer cancel() + cmd := exec.CommandContext(cctx, exe, "check", "--output=json", image) + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + win.HideConsoleCmd(cmd) + cmd.WaitDelay = 2 * time.Second + err = cmd.Run() + if ctx.Err() != nil { + return nil, "", errs.Wrap(errs.Canceled, ctx.Err(), "已取消(qemu-img 没跑完)") + } + if cctx.Err() == context.DeadlineExceeded { + return nil, "", errs.Newf(errs.Timeout, "qemu-img check %.0f 分钟没跑完", diskCheckTimeout.Minutes()) + } + if cmd.ProcessState == nil { + return nil, "", errs.Wrap(errs.Internal, err, "运行不了 qemu-img: "+err.Error()) + } + switch code := cmd.ProcessState.ExitCode(); code { + case 0, 2, 3: + return stdout.Bytes(), "", nil + default: + return nil, fmt.Sprintf("qemu-img check 失败(退出码 %d): %s", code, + orText(tail(strings.TrimSpace(stderr.String()), 300), "没有输出")), nil + } +} + +// readQcow2Header reads the first bytes of the qcow2 file at path. +func readQcow2Header(path string) (qcow2Header, error) { + f, err := os.Open(path) + if err != nil { + return qcow2Header{}, errs.Wrap(errs.Internal, err, "打不开数据盘文件: "+err.Error()) + } + defer f.Close() + buf := make([]byte, 32) + if _, err := io.ReadFull(f, buf); err != nil { + return qcow2Header{}, errs.Wrap(errs.Internal, err, "读不了数据盘文件头: "+err.Error()) + } + return parseQcow2Header(buf) +} + +// reclaimable is the estimate of what compact saves: the space the overlay occupies beyond the clusters it holds, +// never negative. +func reclaimable(onDisk, allocated int64) int64 { + if onDisk > allocated { + return onDisk - allocated + } + return 0 +} + +// DiskInfo reports the data disk's sizes of instance i (see DiskInfoResult). It works for a running and a stopped +// instance; the allocated and reclaimable figures need qemu-img on the image and so only a stopped instance gets them +// (NeedsShutdown otherwise). errs.NotFound when the instance has no data disk overlay; errs.NotReady when qemu-img is +// missing (stopped instance only). +func (m *Manager) DiskInfo(ctx context.Context, i int) (*DiskInfoResult, error) { + if err := requireWindows(); err != nil { + return nil, err + } + in, err := m.instance(i) + if err != nil { + return nil, err + } + overlay := filepath.Join(in.Dir, userdataOverlay) + if !regularFile(overlay) { + return nil, errs.Newf(errs.NotFound, "实例 %d 没有数据盘覆盖层: %s", i, overlay). + WithAdvice("实例还没开过机,或数据盘不是这种格式") + } + _, running := m.qemuOf(i) + res := &DiskInfoResult{Index: i, Overlay: overlay, Running: running, NeedsShutdown: running} + if err := ctxErr(ctx); err != nil { + return nil, err + } + + onDisk, err := win.GetCompressedFileSize(overlay) + if err != nil { + return nil, err + } + res.OnDiskBytes = int64(onDisk) + + // The header read needs no qemu-img. A running qemu has the file open: if that blocks the read, leave the + // logical size out rather than fail. + hdr, herr := readQcow2Header(overlay) + switch { + case herr == nil: + res.LogicalBytes, res.ClusterBytes = hdr.VirtualSize, hdr.ClusterSize + case !running: + return nil, herr + default: + res.Warnings = append(res.Warnings, "实例在运行,读不到数据盘的逻辑大小") + } + if running { + res.Warnings = append(res.Warnings, "实例在运行:已分配和可回收的大小要关机后才能算") + return res, nil + } + + out, failure, err := m.runQemuImgCheck(ctx, overlay) + if err != nil { + return nil, err + } + if failure != "" { + // e.g. the file is still open in a qemu that is shutting down: the sizes read so far stand + res.Warnings = append(res.Warnings, "算不出已分配和可回收的大小:"+failure) + return res, nil + } + chk, err := parseQemuImgCheck(out) + if err != nil { + return nil, err + } + if chk.CheckErrors > 0 || chk.Corruptions > 0 { + res.Warnings = append(res.Warnings, "数据盘镜像检查发现错误,已分配和可回收的大小不可信,已省略") + return res, nil + } + if res.ClusterBytes == 0 { + return nil, errs.New(errs.Internal, "读不到数据盘的簇大小") + } + alloc := *chk.AllocatedClusters * res.ClusterBytes + rec := reclaimable(res.OnDiskBytes, alloc) + res.AllocatedBytes, res.ReclaimableBytes = &alloc, &rec + return res, nil +} diff --git a/internal/emu/disk_test.go b/internal/emu/disk_test.go index 6ce72dcd..9f4df597 100644 --- a/internal/emu/disk_test.go +++ b/internal/emu/disk_test.go @@ -1,6 +1,9 @@ package emu -import "testing" +import ( + "encoding/binary" + "testing" +) func TestParseDiscardMaxBytes(t *testing.T) { cases := []struct { @@ -23,3 +26,73 @@ func TestParseDiscardMaxBytes(t *testing.T) { } } } + +func TestParseQcow2Header(t *testing.T) { + hdr := func(magic uint32, bits uint32, size uint64) []byte { + b := make([]byte, 72) + binary.BigEndian.PutUint32(b[0:], magic) + binary.BigEndian.PutUint32(b[4:], 3) + binary.BigEndian.PutUint32(b[20:], bits) + binary.BigEndian.PutUint64(b[24:], size) + return b + } + got, err := parseQcow2Header(hdr(0x514649fb, 16, 8<<30)) + if err != nil || got.VirtualSize != 8<<30 || got.ClusterSize != 65536 { + t.Errorf("good header = %+v, %v", got, err) + } + for name, b := range map[string][]byte{ + "short": make([]byte, 31), + "not qcow2": hdr(0x12345678, 16, 8<<30), + "bits tiny": hdr(0x514649fb, 3, 8<<30), + "bits huge": hdr(0x514649fb, 40, 8<<30), + "absurd size": hdr(0x514649fb, 16, 1<<63), + } { + if _, err := parseQcow2Header(b); err == nil { + t.Errorf("%s: no error", name) + } + } +} + +func TestParseQemuImgCheck(t *testing.T) { + // real output of qemu-img check --output=json on a clean image + clean := `{ + "image-end-offset": 2136866816, + "total-clusters": 131072, + "check-errors": 0, + "allocated-clusters": 32586, + "filename": "E:\\private\\avd\\x.avd\\userdata-qemu.img.qcow2", + "format": "qcow2", + "fragmented-clusters": 6736 +} +` + c, err := parseQemuImgCheck([]byte(clean)) + if err != nil || *c.AllocatedClusters != 32586 || *c.ImageEndOffset != 2136866816 || c.CheckErrors != 0 { + t.Errorf("clean = %+v, %v", c, err) + } + // a warning line before the object, and a corrupt image + c, err = parseQemuImgCheck([]byte("qemu-img: warning: x\n{\"check-errors\": 2, \"corruptions\": 2, \"allocated-clusters\": 5}")) + if err != nil || *c.AllocatedClusters != 5 || c.CheckErrors != 2 || c.Corruptions != 2 || c.ImageEndOffset != nil { + t.Errorf("corrupt = %+v, %v", c, err) + } + for name, in := range map[string]string{ + "empty": "", + "no json": "qemu-img: Could not open", + "truncated": `{"allocated-clusters": `, + "no clusters": `{"check-errors": 0}`, + "negative": `{"allocated-clusters": -1}`, + } { + if _, err := parseQemuImgCheck([]byte(in)); err == nil { + t.Errorf("%s: no error", name) + } + } +} + +func TestReclaimable(t *testing.T) { + for _, c := range []struct{ onDisk, alloc, want int64 }{ + {10, 4, 6}, {4, 4, 0}, {3, 4, 0}, {0, 0, 0}, + } { + if got := reclaimable(c.onDisk, c.alloc); got != c.want { + t.Errorf("reclaimable(%d, %d) = %d, want %d", c.onDisk, c.alloc, got, c.want) + } + } +} diff --git a/internal/root/root.go b/internal/root/root.go index f8063a04..8a0e1978 100644 --- a/internal/root/root.go +++ b/internal/root/root.go @@ -315,6 +315,17 @@ func (r *Root) QemuHeadlessExe() string { p := CurrentPlatform() return filepath.Join(r.RuntimeSDK(), "emulator", "qemu", p.QemuDir, p.QEMUHeadless) } + +// QemuImgExe is the SDK's qemu-img (disk info / compact), errs.NotReady when it is not installed. +func (r *Root) QemuImgExe() (string, error) { + exe := filepath.Join(r.RuntimeSDK(), "emulator", "qemu-img.exe") + if fi, err := os.Stat(exe); err != nil || fi.IsDir() { + return exe, errs.Newf(errs.NotReady, "找不到 qemu-img: %s", exe). + WithAdvice("魔改 AVD 的模拟器组件不完整,请更新组件后再试") + } + return exe, nil +} + func (r *Root) AvdHome() string { return filepath.Join(r.Dir, AvdDir) } func (r *Root) LogsDir() string { return filepath.Join(r.Dir, LogsDir) } func (r *Root) ShaderCacheDir() string { return filepath.Join(r.Dir, ShaderCacheDir) } diff --git a/internal/root/root_test.go b/internal/root/root_test.go index ddb616ef..f87fad96 100644 --- a/internal/root/root_test.go +++ b/internal/root/root_test.go @@ -261,6 +261,24 @@ func TestResolve(t *testing.T) { } } +func TestQemuImgExe(t *testing.T) { + r := newRoot(t) + exe := r.Dir + `\sdk\emulator\qemu-img.exe` + got, err := r.QemuImgExe() + if got != exe || errs.CodeOf(err) != errs.NotReady { + t.Errorf("missing: (%q, %v)", got, err) + } + if err := os.MkdirAll(filepath.Dir(exe), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(exe, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if got, err := r.QemuImgExe(); got != exe || err != nil { + t.Errorf("present: (%q, %v)", got, err) + } +} + func TestPaths(t *testing.T) { r := newRoot(t) d := r.Dir diff --git a/internal/win/host.go b/internal/win/host.go index 41cfb722..b8b86b64 100644 --- a/internal/win/host.go +++ b/internal/win/host.go @@ -178,6 +178,32 @@ func DiskFree(path string) (uint64, error) { return free, nil } +// GetCompressedFileSize is the bytes the file at path really occupies on the volume (GetCompressedFileSizeW): for a +// sparse or NTFS-compressed file that is less than its length. For a plain file it is the length rounded up to the +// cluster. +func GetCompressedFileSize(path string) (uint64, error) { + p, err := syscall.UTF16PtrFromString(path) + if err != nil { + return 0, errs.Wrap(errs.Internal, err, fmt.Sprintf("路径 %s 不可用: %v", path, err)) + } + if err := procGetCompressedFileSizeW.Find(); err != nil { + return 0, errs.Wrap(errs.Internal, err, "读不到文件占用的磁盘空间: "+err.Error()) + } + const invalidFileSize = 0xFFFFFFFF + var high uint32 + low, _, e := procGetCompressedFileSizeW.Call(uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(&high))) + // INVALID_FILE_SIZE is also a legal low word of a file larger than 4 GiB: only the last error tells them apart. + if uint32(low) == invalidFileSize { + if en, ok := e.(syscall.Errno); ok && en != 0 { + if en == syscall.ERROR_FILE_NOT_FOUND || en == syscall.ERROR_PATH_NOT_FOUND { + return 0, errs.Wrap(errs.NotFound, e, "找不到文件: "+path) + } + return 0, errs.Wrap(errs.Internal, e, fmt.Sprintf("读不到 %s 占用的磁盘空间: %v", path, e)) + } + } + return uint64(high)<<32 | uint64(uint32(low)), nil +} + type memoryStatusEx struct { Length uint32 MemoryLoad uint32 diff --git a/internal/win/other.go b/internal/win/other.go index d02bb66d..451989f7 100644 --- a/internal/win/other.go +++ b/internal/win/other.go @@ -135,6 +135,9 @@ func SharedMemoryExists(string) bool { return false } // DiskFree calls GetDiskFreeSpaceExW for the Windows volume. func DiskFree(string) (uint64, error) { return 0, errUnsupported } +// GetCompressedFileSize calls GetCompressedFileSizeW for the Windows file. +func GetCompressedFileSize(string) (uint64, error) { return 0, errUnsupported } + // AvailableMemoryMB calls GlobalMemoryStatusEx on Windows. func AvailableMemoryMB() (uint64, error) { return 0, errUnsupported } diff --git a/internal/win/win.go b/internal/win/win.go index ffc82159..db5972ca 100644 --- a/internal/win/win.go +++ b/internal/win/win.go @@ -71,6 +71,7 @@ var ( procGetProcessAffinityMask = modkernel32.NewProc("GetProcessAffinityMask") procOpenFileMappingW = modkernel32.NewProc("OpenFileMappingW") procGetDiskFreeSpaceExW = modkernel32.NewProc("GetDiskFreeSpaceExW") + procGetCompressedFileSizeW = modkernel32.NewProc("GetCompressedFileSizeW") procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx") procLockFileEx = modkernel32.NewProc("LockFileEx") procUnlockFileEx = modkernel32.NewProc("UnlockFileEx") diff --git a/internal/win/win_test.go b/internal/win/win_test.go index 4ac457ea..fa434fc8 100644 --- a/internal/win/win_test.go +++ b/internal/win/win_test.go @@ -703,6 +703,22 @@ func TestDiskFreeAndMemory(t *testing.T) { t.Logf("available memory: %d MiB", mb) } +func TestGetCompressedFileSize(t *testing.T) { + dir := workDir(t) + file := filepath.Join(dir, "sz.bin") + if err := os.WriteFile(file, make([]byte, 100000), 0o644); err != nil { + t.Fatal(err) + } + n, err := GetCompressedFileSize(file) + // a plain file takes at least its length (rounded up to the cluster); a compressed volume may report less + if err != nil || n == 0 || n > 1<<20 { + t.Errorf("GetCompressedFileSize = %d, %v", n, err) + } + if _, err := GetCompressedFileSize(filepath.Join(dir, "missing.bin")); errs.CodeOf(err) != errs.NotFound { + t.Errorf("missing file: %v", err) + } +} + func TestL3Groups(t *testing.T) { raw := cacheTopology() t.Logf("cache topology %d bytes, L3 groups %+v", len(raw), L3Groups()) From d2ce0105d39c02a977cb885d47138dfddb6e5b91 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Wed, 4 Nov 2026 08:13:51 +0100 Subject: [PATCH 4/9] =?UTF-8?q?=E7=A3=81=E7=9B=98=E5=9B=9E=E6=94=B6=20S3?= =?UTF-8?q?=EF=BC=9Adisk=20compact=20=E5=AD=90=E5=91=BD=E4=BB=A4=EF=BC=88R?= =?UTF-8?q?efs=20ModAVD/ModAVD#2=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modavd disk <编号> compact:关机状态下整理数据盘覆盖层。持有实例的 start/stop/bridge/create 锁(没关机或锁被占时报 Busy,不会边整理边开机);有内部 快照或 snapshots 目录非空时拒绝(convert 会丢快照)。流程:qemu-img convert -T none -B -o backing_fmt=... 转到临时文件 → qemu-img check + compare 校验内容一致 → FlushFileBuffers + MoveFileExW(REPLACE|WRITE_THROUGH) 原子换上。 原盘在最后替换成功前一字节不动,中途崩溃留下的 .compact.tmp 下次清掉。 新增 win.MoveFileReplaceThrough(+非 Windows 桩)。CLI 的 disk 命令加 compact 动作、 formatDiskCompact、manager 接口、fakeManager 桩和 TestDiskCompact。go build/vet/ gofmt/test 均过。数据盘改动,待指挥安排另一会话审 + 实机回归。 --- README.md | 1 + internal/cli/cli.go | 2 + internal/cli/commands.go | 16 ++- internal/cli/format.go | 9 ++ internal/cli/run_test.go | 31 ++++- internal/emu/disk.go | 288 ++++++++++++++++++++++++++++++++++++++- internal/win/host.go | 23 ++++ internal/win/other.go | 3 + internal/win/win.go | 1 + 9 files changed, 360 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 73e9e2a3..da31ad1b 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] | `bridge install\|uninstall\|verify` | 装、卸、检查 arm64 执行桥;开机时会自动装,一般不用手动跑(见下) | | `disk trim` | 磁盘回收:在开着的实例里对数据盘触发一次 FITRIM,让模拟器释放已删文件占着的空间;模拟器太旧、不支持回收时返回不支持(退出码 4) | | `disk info` | 看数据盘的大小:逻辑大小、覆盖层在宿主上实际占的空间;实例关机时再给已分配的大小和估计能回收多少(开着时这两个数要关机后才有);只读 | +| `disk compact` | 整理数据盘:关机状态下把覆盖层重写一遍、丢掉已释放的簇、把文件缩小;转换后先校验再原子替换,原盘在替换成功前不动;实例有快照时拒绝 | | `check [--memory M]` | 开机前的电脑检查 | | `report-config [--no-clipboard]` | 复制电脑配置和开着实例里的游戏信息(只读) | | `collect-info [--out-dir D] [--stage-dir D] [--keep-stage] [--no-explorer]` | 收集问题信息并打包(只读) | diff --git a/internal/cli/cli.go b/internal/cli/cli.go index c2a906f9..c26e9683 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -24,6 +24,7 @@ // window show|hide emu.WindowResult // disk trim emu.DiskTrimResult {index,discardMaxBytes} // disk info emu.DiskInfoResult {index,overlay,running,needsShutdown,logicalBytes,onDiskBytes,allocatedBytes?,reclaimableBytes?} +// disk compact emu.DiskCompactResult {index,overlay,beforeOnDiskBytes,afterOnDiskBytes,freedBytes} // install emu.InstallResult // shell [--timeout S] emu.ShellResult // adb [--] no envelope: adb's own stdio and exit code @@ -100,6 +101,7 @@ type manager interface { Bridge(ctx context.Context, i int, action string) (*emu.BridgeResult, error) DiskTrim(ctx context.Context, i int) (*emu.DiskTrimResult, error) DiskInfo(ctx context.Context, i int) (*emu.DiskInfoResult, error) + DiskCompact(ctx context.Context, i int) (*emu.DiskCompactResult, error) EnsureServers(ctx context.Context) (*emu.ServersResult, error) // Running is the indexes whose qemu runs, from the process table only (no adb). Running(ctx context.Context) ([]int, error) diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 1fc8617f..76490052 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -237,13 +237,15 @@ func init() { run: runBridge, human: humanOf(formatBridge), exit: exitBridge, }, { - name: "disk", args: " trim|info", summary: "磁盘回收:把客体里已删文件占的空间还给宿主;看数据盘的大小", + name: "disk", args: " trim|info|compact", summary: "磁盘回收:触发回收或整理把客体已删文件占的空间还给宿主;看数据盘大小", details: "trim:在客体的数据盘(/data)上触发一次回收(FITRIM,经 vold 空闲维护)," + "让模拟器释放已删除文件在数据盘镜像里占着的空间。实例要开着并已开机完成;" + "模拟器版本太旧、数据盘不支持回收时返回不支持(退出码 4),不会白跑。" + "info:报数据盘的逻辑大小、在宿主上实际占的空间,以及(实例关机时)已分配的大小和估计能回收多少;" + - "实例开着时已分配和可回收的数要关机后才有,只读,不改任何东西。", - posNames: []string{"实例编号", "trim 或 info"}, minPos: 2, maxPos: 2, + "实例开着时已分配和可回收的数要关机后才有,只读,不改任何东西。" + + "compact:关机状态下把数据盘覆盖层重写一遍、丢掉已释放的簇、把文件缩小;" + + "转换后先校验(check + compare)再原子替换,原盘在替换成功前不动;实例有快照时拒绝。", + posNames: []string{"实例编号", "trim、info 或 compact"}, minPos: 2, maxPos: 2, final: true, run: runDisk, human: formatDiskHuman, }, @@ -1003,7 +1005,7 @@ func runBridge(c *cmdCtx) (any, error) { return m.Bridge(c.ctx, i, action) } -// runDisk dispatches `disk ` (trim, info); add a case per new action. +// runDisk dispatches `disk ` (trim, info, compact); add a case per new action. func runDisk(c *cmdCtx) (any, error) { i, err := parseIndex(c.inv.pos[0]) if err != nil { @@ -1011,9 +1013,9 @@ func runDisk(c *cmdCtx) (any, error) { } action := strings.ToLower(c.inv.pos[1]) switch action { - case "trim", "info": + case "trim", "info", "compact": default: - return nil, errs.Newf(errs.Usage, "第二个参数只能是 trim 或 info,收到「%s」", c.inv.pos[1]). + return nil, errs.Newf(errs.Usage, "第二个参数只能是 trim、info 或 compact,收到「%s」", c.inv.pos[1]). WithAdvice(findCommand("disk").usageAdvice()) } m, err := c.mgr() @@ -1025,6 +1027,8 @@ func runDisk(c *cmdCtx) (any, error) { return m.DiskTrim(c.ctx, i) case "info": return m.DiskInfo(c.ctx, i) + case "compact": + return m.DiskCompact(c.ctx, i) } return nil, errs.Newf(errs.Internal, "disk 动作 %s 没有实现", action) } diff --git a/internal/cli/format.go b/internal/cli/format.go index 9c5e091f..b5b40746 100644 --- a/internal/cli/format.go +++ b/internal/cli/format.go @@ -605,9 +605,18 @@ func formatDiskHuman(w io.Writer, data any) { if r != nil { formatDiskInfo(w, r) } + case *emu.DiskCompactResult: + if r != nil { + formatDiskCompact(w, r) + } } } +func formatDiskCompact(w io.Writer, r *emu.DiskCompactResult) { + fmt.Fprintf(w, "实例 %d 整理磁盘完成:覆盖层占用 %s → %s,省下 %s\n", + r.Index, fmtBytesGB(r.BeforeOnDiskBytes), fmtBytesGB(r.AfterOnDiskBytes), fmtBytesGB(r.FreedBytes)) +} + // fmtBytesGB is a byte count in GB with one decimal ("12.3 GB"). func fmtBytesGB(b int64) string { return fmt.Sprintf("%.1f GB", float64(b)/(1<<30)) diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index cc61856e..77059e41 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -183,6 +183,13 @@ func (f *fakeManager) DiskInfo(ctx context.Context, i int) (*emu.DiskInfoResult, ClusterBytes: 65536, AllocatedBytes: &alloc, ReclaimableBytes: &rec}, nil } +func (f *fakeManager) DiskCompact(ctx context.Context, i int) (*emu.DiskCompactResult, error) { + f.record("disk-compact " + itoa(i)) + const gb = int64(1) << 30 + return &emu.DiskCompactResult{Index: i, Overlay: "x", BeforeOnDiskBytes: 3 * gb, + AfterOnDiskBytes: 2 * gb, FreedBytes: gb}, nil +} + func (f *fakeManager) InstallAPK(ctx context.Context, i int, apkPath string) (*emu.InstallResult, error) { f.record("install " + itoa(i) + " " + apkPath) if f.install != nil { @@ -1029,14 +1036,34 @@ func TestDiskTrim(t *testing.T) { if !strings.Contains(r.stdout, `"discardMaxBytes":2147483648`) { t.Errorf("json data: %s", r.stdout) } - // anything but trim is a usage error and reaches no manager + // an unknown action is a usage error and reaches no manager h = newHarness() - r = h.run(t, nil, "disk", "3", "compact") + r = h.run(t, nil, "disk", "3", "flatten") if r.code != 2 || len(h.fake.callList()) != 0 { t.Errorf("bad action: code %d calls %q stderr %q", r.code, h.fake.callList(), r.stderr) } } +func TestDiskCompact(t *testing.T) { + h := newHarness() + r := h.run(t, nil, "disk", "3", "compact") + if r.code != 0 || r.stdout != "实例 3 整理磁盘完成:覆盖层占用 3.0 GB → 2.0 GB,省下 1.0 GB\n" { + t.Errorf("text: code %d stdout %q stderr %q", r.code, r.stdout, r.stderr) + } + if got := h.fake.callList(); len(got) != 1 || got[0] != "disk-compact 3" { + t.Errorf("calls = %q", got) + } + r = h.run(t, nil, "--json", "disk", "mas_3", "COMPACT") + if m := envelope(t, r.stdout); m["ok"] != true { + t.Errorf("json: %s", r.stdout) + } + for _, s := range []string{`"freedBytes":1073741824`, `"beforeOnDiskBytes":3221225472`, `"afterOnDiskBytes":2147483648`} { + if !strings.Contains(r.stdout, s) { + t.Errorf("json data lacks %s: %s", s, r.stdout) + } + } +} + func TestDiskInfo(t *testing.T) { h := newHarness() r := h.run(t, nil, "disk", "3", "info") diff --git a/internal/emu/disk.go b/internal/emu/disk.go index 8b3464fd..8febe46e 100644 --- a/internal/emu/disk.go +++ b/internal/emu/disk.go @@ -1,11 +1,12 @@ package emu -// modavd disk : reclaim the space the guest freed on /data. `trim` triggers -// a guest FITRIM at runtime so the emulator's virtio-blk discard path frees the -// qcow2 clusters behind deleted files (ModAVD/ModAVD#2). `info` reports the data -// disk's sizes (what a reclaim could save); `compact` lands in a later commit. trim is only useful once the emulator advertises -// discard on the data disk (the mas/discard emulator build); an older build -// reports no discard and trim returns errs.Unsupported with a clear message. +// modavd disk : reclaim the space the guest freed on /data (ModAVD/ModAVD#2). +// `trim` triggers a guest FITRIM at runtime so the emulator's virtio-blk discard +// path frees the qcow2 clusters behind deleted files; `info` reports the data disk's +// sizes (what a reclaim could save); `compact` rewrites the overlay offline to drop +// the freed clusters and shrink the file. trim is only useful once the emulator +// advertises discard on the data disk (the mas/discard emulator build); an older +// build reports no discard and trim returns errs.Unsupported with a clear message. import ( "bytes" @@ -321,3 +322,278 @@ func (m *Manager) DiskInfo(ctx context.Context, i int) (*DiskInfoResult, error) res.AllocatedBytes, res.ReclaimableBytes = &alloc, &rec return res, nil } + +// ---- compact ----------------------------------------------------------------- + +const ( + // diskInfoTimeout bounds a quick `qemu-img info`. + diskInfoTimeout = time.Minute + // diskConvertTimeout bounds `qemu-img convert` of a multi-GB data disk. + diskConvertTimeout = 30 * time.Minute + // diskCompareTimeout bounds `qemu-img compare` of the before/after images. + diskCompareTimeout = 20 * time.Minute +) + +// userdataCompactTmp is the scratch file compact converts into before swapping it +// over the overlay; a stray one from an interrupted run is removed on the next run. +const userdataCompactTmp = userdataOverlay + ".compact.tmp" + +// DiskCompactResult reports `modavd disk compact`. +type DiskCompactResult struct { + Index int `json:"index"` + Overlay string `json:"overlay"` + BeforeOnDiskBytes int64 `json:"beforeOnDiskBytes"` + AfterOnDiskBytes int64 `json:"afterOnDiskBytes"` + FreedBytes int64 `json:"freedBytes"` +} + +// qemuImgInfoResult is the part of `qemu-img info --output=json` compact reads. +type qemuImgInfoResult struct { + BackingFilename string `json:"backing-filename"` + BackingFilenameFmt string `json:"backing-filename-format"` + Snapshots []json.RawMessage `json:"snapshots"` +} + +// lockInstanceForCompact takes the per-instance locks that keep anyone from booting, +// stopping, bridging or creating instance i while compact rewrites its data disk; +// errs.Busy when any is already held. The returned func releases them; call it once. +func (m *Manager) lockInstanceForCompact(i int) (func(), error) { + kinds := []struct{ kind, what string }{ + {"start", "正在启动"}, + {"stop", "正在关闭"}, + {"bridge", "正在装卸执行桥"}, + {"create", "正在新建"}, + } + var locks []*win.FileLock + unlock := func() { + for k := len(locks) - 1; k >= 0; k-- { + locks[k].Unlock() + } + } + for _, kw := range kinds { + path := m.lockPath(i, kw.kind) + l, ok, err := win.TryLock(path) + if err != nil { + unlock() + return nil, errs.Wrap(errs.Internal, err, "实例锁文件打不开: "+path) + } + if !ok { + unlock() + return nil, errs.Newf(errs.Busy, "魔改 AVD 实例 %d %s,无法整理磁盘", i, kw.what) + } + locks = append(locks, l) + } + return unlock, nil +} + +// runQemuImg runs qemu-img with args and returns its stdout, stderr and the process +// exit code. err is non-nil only when qemu-img did not run to the end (missing, not +// startable, canceled, timed out); a non-zero exit with err==nil is the caller's to +// interpret. The image must not be open in a running qemu. +func (m *Manager) runQemuImg(ctx context.Context, timeout time.Duration, args ...string) (stdout, stderr []byte, code int, err error) { + exe, err := m.Root.QemuImgExe() + if err != nil { + return nil, nil, 0, err + } + cctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + cmd := exec.CommandContext(cctx, exe, args...) + var so, se bytes.Buffer + cmd.Stdout, cmd.Stderr = &so, &se + win.HideConsoleCmd(cmd) + cmd.WaitDelay = 2 * time.Second + runErr := cmd.Run() + if ctx.Err() != nil { + return nil, nil, 0, errs.Wrap(errs.Canceled, ctx.Err(), "已取消(qemu-img 没跑完)") + } + if cctx.Err() == context.DeadlineExceeded { + return nil, nil, 0, errs.Newf(errs.Timeout, "qemu-img %s %.0f 分钟没跑完", args[0], timeout.Minutes()) + } + if cmd.ProcessState == nil { + return nil, nil, 0, errs.Wrap(errs.Internal, runErr, "运行不了 qemu-img: "+runErr.Error()) + } + return so.Bytes(), se.Bytes(), cmd.ProcessState.ExitCode(), nil +} + +// qemuImgFail picks the most useful tail of a failed qemu-img run (stderr first). +func qemuImgFail(stdout, stderr []byte) string { + return orText(tail(strings.TrimSpace(string(stderr)), 300), + orText(tail(strings.TrimSpace(string(stdout)), 300), "没有输出")) +} + +// qemuImgInfo reads the overlay's backing filename, backing format and whether it has +// internal snapshots from `qemu-img info --output=json`. +func (m *Manager) qemuImgInfo(ctx context.Context, image string) (*qemuImgInfoResult, error) { + so, se, code, err := m.runQemuImg(ctx, diskInfoTimeout, "info", "--output=json", image) + if err != nil { + return nil, err + } + if code != 0 { + return nil, errs.Newf(errs.Internal, "qemu-img info 失败(退出码 %d): %s", code, qemuImgFail(so, se)) + } + start := bytes.IndexByte(so, '{') + if start < 0 { + return nil, errs.New(errs.Internal, "qemu-img info 没有输出 JSON") + } + var r qemuImgInfoResult + if err := json.NewDecoder(bytes.NewReader(so[start:])).Decode(&r); err != nil { + return nil, errs.Wrap(errs.Internal, err, "读不懂 qemu-img info 的输出: "+err.Error()) + } + return &r, nil +} + +// verifyCompacted checks the converted image is sound (qemu-img check: no errors or +// corruptions) and holds the same guest-visible content as the original (qemu-img +// compare), before it is swapped in. +func (m *Manager) verifyCompacted(ctx context.Context, orig, tmp string) error { + out, failure, err := m.runQemuImgCheck(ctx, tmp) + if err != nil { + return err + } + if failure != "" { + return errs.Newf(errs.Internal, "整理后的数据盘检查没通过:%s,放弃替换,原盘未动", failure) + } + chk, err := parseQemuImgCheck(out) + if err != nil { + return err + } + if chk.CheckErrors > 0 || chk.Corruptions > 0 { + return errs.Newf(errs.Internal, "整理后的数据盘有 %d 处检查错误、%d 处损坏,放弃替换,原盘未动", + chk.CheckErrors, chk.Corruptions) + } + // compare the effective content (overlay + backing); exit 0 means identical. + so, se, code, err := m.runQemuImg(ctx, diskCompareTimeout, "compare", orig, tmp) + if err != nil { + return err + } + if code != 0 { + return errs.Newf(errs.Internal, + "整理前后的数据盘内容对不上(qemu-img compare 退出码 %d):%s,放弃替换,原盘未动", + code, qemuImgFail(so, se)) + } + return nil +} + +// syncFile flushes the file's pending writes to disk (FlushFileBuffers on Windows). +func syncFile(path string) error { + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + return err + } + serr := f.Sync() + if cerr := f.Close(); serr == nil { + serr = cerr + } + return serr +} + +// dirHasEntries is true when path is a directory with at least one entry. +func dirHasEntries(path string) bool { + es, err := os.ReadDir(path) + return err == nil && len(es) > 0 +} + +// DiskCompact offline-compacts instance i's data disk: it converts the overlay to a +// fresh qcow2 that keeps only the clusters still in use (same backing), checks and +// compares the copy, then atomically swaps it in with a write-through replace. The +// instance must be powered off; compact holds its start/stop/bridge/create locks so +// nothing boots it mid-rewrite. It refuses when the data disk or the instance has +// snapshots (the convert would drop them). The original is untouched until the final +// replace, so a crash at any earlier point leaves a working instance (a stray +// .compact.tmp is removed on the next run). errs.Busy when the instance is running or +// a lock is held; errs.Unsupported for snapshots or a missing backing. +func (m *Manager) DiskCompact(ctx context.Context, i int) (*DiskCompactResult, error) { + if err := requireWindows(); err != nil { + return nil, err + } + in, err := m.instance(i) + if err != nil { + return nil, err + } + overlay := filepath.Join(in.Dir, userdataOverlay) + if !regularFile(overlay) { + return nil, errs.Newf(errs.NotFound, "实例 %d 没有数据盘覆盖层: %s", i, overlay). + WithAdvice("实例还没开过机,或数据盘不是这种格式") + } + unlock, err := m.lockInstanceForCompact(i) + if err != nil { + return nil, err + } + defer unlock() + if _, running := m.qemuOf(i); running { + return nil, errs.Newf(errs.Busy, "魔改 AVD 实例 %d 未关闭,无法整理磁盘", i). + WithAdvice(fmt.Sprintf("先 modavd stop %d,关机后再整理", i)) + } + if err := ctxErr(ctx); err != nil { + return nil, err + } + + info, err := m.qemuImgInfo(ctx, overlay) + if err != nil { + return nil, err + } + if len(info.Snapshots) > 0 { + return nil, errs.Newf(errs.Unsupported, "数据盘里有 %d 个内部快照,整理磁盘会丢掉它们", len(info.Snapshots)). + WithAdvice("先删掉快照再整理") + } + if dirHasEntries(filepath.Join(in.Dir, "snapshots")) { + return nil, errs.New(errs.Unsupported, "实例里有内存快照(snapshots 目录非空),整理磁盘会和它们对不上"). + WithAdvice("先删掉快照再整理") + } + if info.BackingFilename == "" { + return nil, errs.New(errs.Unsupported, "数据盘没有 backing,不整理(避免把整盘复制进来)") + } + if info.BackingFilenameFmt == "" { + return nil, errs.New(errs.Internal, "读不到数据盘 backing 的格式,不整理") + } + backingName := filepath.Base(info.BackingFilename) + + before, err := win.GetCompressedFileSize(overlay) + if err != nil { + return nil, err + } + + tmp := filepath.Join(in.Dir, userdataCompactTmp) + _ = os.Remove(tmp) // clear a stray temp from an interrupted run + + // convert: a fresh overlay holding only the live clusters, same backing. -B skips + // the backing's data; -T none keeps the host cache out of a tens-of-GB copy. + so, se, code, err := m.runQemuImg(ctx, diskConvertTimeout, "convert", "-T", "none", + "-O", "qcow2", "-B", backingName, "-o", "backing_fmt="+info.BackingFilenameFmt, overlay, tmp) + if err != nil { + _ = os.Remove(tmp) + return nil, err + } + if code != 0 { + _ = os.Remove(tmp) + return nil, errs.Newf(errs.Internal, "qemu-img convert 失败(退出码 %d): %s", code, qemuImgFail(so, se)) + } + + if err := m.verifyCompacted(ctx, overlay, tmp); err != nil { + _ = os.Remove(tmp) + return nil, err + } + + // flush the copy's data, then atomically replace the original (write-through). + if err := syncFile(tmp); err != nil { + _ = os.Remove(tmp) + return nil, errs.Wrap(errs.Internal, err, "刷新整理后的数据盘失败") + } + if err := win.MoveFileReplaceThrough(tmp, overlay); err != nil { + _ = os.Remove(tmp) + return nil, err + } + + after, err := win.GetCompressedFileSize(overlay) + if err != nil { + return nil, err + } + m.Log.Infof("魔改 AVD 实例 %d 整理磁盘完成:占用 %s → %s", i, gib(int64(before)), gib(int64(after))) + return &DiskCompactResult{ + Index: i, + Overlay: overlay, + BeforeOnDiskBytes: int64(before), + AfterOnDiskBytes: int64(after), + FreedBytes: reclaimable(int64(before), int64(after)), + }, nil +} diff --git a/internal/win/host.go b/internal/win/host.go index b8b86b64..f5dfdd95 100644 --- a/internal/win/host.go +++ b/internal/win/host.go @@ -204,6 +204,29 @@ func GetCompressedFileSize(path string) (uint64, error) { return uint64(high)<<32 | uint64(uint32(low)), nil } +// MoveFileReplaceThrough renames src over dst (MoveFileExW, REPLACE_EXISTING | +// WRITE_THROUGH): dst is replaced and both the rename and the pending writes are +// flushed to disk before it returns, so a crash leaves either the old file or the +// new one, never a torn mix. Used to swap in a freshly compacted disk image. +func MoveFileReplaceThrough(src, dst string) error { + s, err := syscall.UTF16PtrFromString(src) + if err != nil { + return errs.Wrap(errs.Internal, err, "源路径不可用: "+src) + } + d, err := syscall.UTF16PtrFromString(dst) + if err != nil { + return errs.Wrap(errs.Internal, err, "目标路径不可用: "+dst) + } + const moveReplaceExisting = 0x1 + const moveWriteThrough = 0x8 + r, e := call(procMoveFileExW, uintptr(unsafe.Pointer(s)), uintptr(unsafe.Pointer(d)), + moveReplaceExisting|moveWriteThrough) + if r == 0 { + return errs.Wrap(errs.Internal, e, fmt.Sprintf("换文件失败(%s → %s): %v", src, dst, e)) + } + return nil +} + type memoryStatusEx struct { Length uint32 MemoryLoad uint32 diff --git a/internal/win/other.go b/internal/win/other.go index 451989f7..f3c51c52 100644 --- a/internal/win/other.go +++ b/internal/win/other.go @@ -138,6 +138,9 @@ func DiskFree(string) (uint64, error) { return 0, errUnsupported } // GetCompressedFileSize calls GetCompressedFileSizeW for the Windows file. func GetCompressedFileSize(string) (uint64, error) { return 0, errUnsupported } +// MoveFileReplaceThrough calls MoveFileExW (REPLACE_EXISTING | WRITE_THROUGH). +func MoveFileReplaceThrough(string, string) error { return errUnsupported } + // AvailableMemoryMB calls GlobalMemoryStatusEx on Windows. func AvailableMemoryMB() (uint64, error) { return 0, errUnsupported } diff --git a/internal/win/win.go b/internal/win/win.go index db5972ca..bd706f5e 100644 --- a/internal/win/win.go +++ b/internal/win/win.go @@ -77,6 +77,7 @@ var ( procUnlockFileEx = modkernel32.NewProc("UnlockFileEx") procGetProcessId = modkernel32.NewProc("GetProcessId") procQueryFullProcessImageNameW = modkernel32.NewProc("QueryFullProcessImageNameW") + procMoveFileExW = modkernel32.NewProc("MoveFileExW") procNtQueryInformationProcess = modntdll.NewProc("NtQueryInformationProcess") procRtlNtStatusToDosError = modntdll.NewProc("RtlNtStatusToDosError") From ee4bb3d16bd592484684cc2ed9ffc76a5a030063 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Wed, 4 Nov 2026 08:40:37 +0100 Subject: [PATCH 5/9] =?UTF-8?q?=E7=A3=81=E7=9B=98=E5=9B=9E=E6=94=B6=20S3?= =?UTF-8?q?=EF=BC=9A=E5=BC=80=E6=9C=BA=E5=90=8E=E6=AF=8F=2024=20=E5=B0=8F?= =?UTF-8?q?=E6=97=B6=E8=87=AA=E5=8A=A8=20trim=EF=BC=88Refs=20ModAVD/ModAVD?= =?UTF-8?q?#2=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit afterBoot 在 Vulkan 修复前加一步:实例开机完成、模拟器数据盘支持 discard、且离上次 ≥24h 时,自动 trim 一次(复用 DiskTrim 的探测 + sm idle-maint)。严格尽力而为,绝不 弄坏或拖慢开机:defer recover 吞 panic、只记日志不返回错误、非 trim 日只读一次时间戳不 碰 adb、探测/trim 各有 10s/30s 短超时、ctx 取消即静默返回、接管已在跑的实例 (setupAdopted)跳过。上次时间存 mas-avd.json 的 diskTrimAt(unix 秒),失败或超时也写 (下次隔 24h 再试,不每次开机都等)。把 DiskTrim 的探测/trim 抽成 probeDiscardMax、 runIdleMaint 共用,DiskTrim 行为不变。shouldAutoTrim 带单测。 go build/vet/gofmt/test 均过。sm idle-maint 的实际阻塞时长待实机核。 --- internal/emu/afterboot.go | 3 + internal/emu/autotrim.go | 101 ++++++++++++++++++++++++++++++++++ internal/emu/autotrim_test.go | 27 +++++++++ internal/emu/disk.go | 20 ++++++- 4 files changed, 148 insertions(+), 3 deletions(-) create mode 100644 internal/emu/autotrim.go create mode 100644 internal/emu/autotrim_test.go diff --git a/internal/emu/afterboot.go b/internal/emu/afterboot.go index 286a2001..b7476a11 100644 --- a/internal/emu/afterboot.go +++ b/internal/emu/afterboot.go @@ -182,6 +182,9 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe }, // 10) orientation: the display stays landscape (persistent; set every boot so old instances get it) func() { m.setupOrientation(ctx, i) }, + // 10b) hand the clusters the guest freed back to the host, at most once a day (best effort, see autotrim.go); + // before the Vulkan fix, whose zygote restart is deliberately the last step + func() { m.autoTrim(ctx, i, mode) }, func() { // 11) the guest Vulkan fix. Must be last: mounting it restarts zygote, system_server and every app prog.emit("vulkan_fix", fmt.Sprintf("实例 %d 客体 Vulkan 驱动补丁", i), progressVulkanFix) diff --git a/internal/emu/autotrim.go b/internal/emu/autotrim.go new file mode 100644 index 00000000..4014e96c --- /dev/null +++ b/internal/emu/autotrim.go @@ -0,0 +1,101 @@ +package emu + +// The automatic trim of the data disk after boot (ModAVD/ModAVD#2, design §3.3 / §3.6): once the boot setup is done +// and the emulator advertises discard on /data, the clusters the guest freed are handed back (the same guest trim as +// `modavd disk trim`), at most once per 24 hours per instance, so nobody has to run it by hand. +// +// Strictly best effort and never in the boot's way: every problem (no discard, su failed, mas-avd.json unreadable or +// unwritable) is one log line and the step returns; nothing is returned to the start, nothing can panic out of it, and +// the guest commands have short timeouts of their own. + +import ( + "context" + "fmt" + "time" + + "modavd/internal/jsonord" +) + +const ( + // autoTrimInterval is the least time between two automatic trims of an instance. + autoTrimInterval = 24 * time.Hour + // autoTrimProbeTimeout bounds the read of the discard limit. + autoTrimProbeTimeout = 10 * time.Second + // autoTrimTimeout bounds the trim itself, which the start waits for. Far shorter than the manual diskTrimTimeout: + // a boot must not wait minutes for it. A trim that did not finish in time is not tried again before the interval + // is over (see autoTrim). + autoTrimTimeout = 30 * time.Second +) + +// diskTrimAtKey is instances..diskTrimAt in mas-avd.json: the Unix time in seconds of the last automatic trim +// attempt (an integer; absent or anything else: never). +const diskTrimAtKey = "diskTrimAt" + +// shouldAutoTrim: an automatic trim is due when none has run yet (lastUnix <= 0), the interval has passed since the +// last one, or the clock stands before it (it was set back: waiting for the future would never end). +func shouldAutoTrim(lastUnix, nowUnix int64) bool { + if lastUnix <= 0 || nowUnix < lastUnix { + return true + } + return time.Duration(nowUnix-lastUnix)*time.Second >= autoTrimInterval +} + +// readDiskTrimAt is the Unix time stored for instance i; 0 when there is none or it cannot be read. +func (m *Manager) readDiskTrimAt(i int) int64 { + meta := m.Root.InstanceMeta(i) + if meta == nil { + return 0 + } + n, _ := meta.Get(diskTrimAtKey).Int() + return n +} + +func (m *Manager) writeDiskTrimAt(i int, unix int64) error { + return m.Root.EditInstanceMeta(i, func(meta *jsonord.Obj) error { + meta.Set(diskTrimAtKey, jsonord.NewInt(unix)) + return nil + }) +} + +// autoTrim is the boot step: trim instance i's data disk when it is due. It only logs. An instance this start merely +// adopted (setupAdopted) is left alone: a game may be running there, and a trim can stall the guest's disk for a +// moment (design §3.6: only after boot, before a game is up). +// +// The time is stored after the attempt whatever came of it (unless the start was canceled): a trim that fails or times +// out is retried after the interval, not at every boot, so the most a boot ever waits for it is autoTrimProbeTimeout + +// autoTrimTimeout once a day. +func (m *Manager) autoTrim(ctx context.Context, i int, mode bootSetup) { + defer func() { + if r := recover(); r != nil { + m.Log.Warnf("实例 %d 开机后自动回收磁盘空间出错,已跳过: %v", i, r) + } + }() + if mode == setupAdopted || ctx.Err() != nil || m.Root == nil { + return + } + if !shouldAutoTrim(m.readDiskTrimAt(i), time.Now().Unix()) { + return + } + maxBytes, ok := m.probeDiscardMax(ctx, i, autoTrimProbeTimeout) + if ctx.Err() != nil { + return + } + if !ok || maxBytes <= 0 { + m.Log.Debugf("实例 %d 数据盘没有 discard(旧版模拟器),不自动回收磁盘空间", i) + return + } + started := time.Now() + res := m.runIdleMaint(ctx, i, autoTrimTimeout) + if ctx.Err() != nil { + return + } + if res.Code == 0 { + m.Log.Infof("实例 %d 开机后自动回收磁盘空间(%.1f 秒)", i, time.Since(started).Seconds()) + } else { + m.Log.Warnf("实例 %d 开机后自动回收磁盘空间没成功,%.0f 小时后再试: %s", i, autoTrimInterval.Hours(), + orText(tail(res.Out, 200), fmt.Sprintf("退出码 %d", res.Code))) + } + if err := m.writeDiskTrimAt(i, time.Now().Unix()); err != nil { + m.Log.Warnf("实例 %d 记不下这次自动回收的时间(下次开机会再回收一次): %v", i, err) + } +} diff --git a/internal/emu/autotrim_test.go b/internal/emu/autotrim_test.go new file mode 100644 index 00000000..0e4f0f6e --- /dev/null +++ b/internal/emu/autotrim_test.go @@ -0,0 +1,27 @@ +package emu + +import "testing" + +func TestShouldAutoTrim(t *testing.T) { + const now = int64(1_800_000_000) + const day = int64(24 * 60 * 60) + cases := []struct { + name string + last int64 + want bool + }{ + {"never trimmed", 0, true}, + {"negative is garbage", -5, true}, + {"just now", now, false}, + {"an hour ago", now - 3600, false}, + {"one second short of the interval", now - day + 1, false}, + {"exactly the interval", now - day, true}, + {"two days ago", now - 2*day, true}, + {"clock set back", now + 3600, true}, + } + for _, c := range cases { + if got := shouldAutoTrim(c.last, now); got != c.want { + t.Errorf("%s: shouldAutoTrim(%d, %d) = %v, want %v", c.name, c.last, now, got, c.want) + } + } +} diff --git a/internal/emu/disk.go b/internal/emu/disk.go index 8febe46e..92e14e25 100644 --- a/internal/emu/disk.go +++ b/internal/emu/disk.go @@ -22,6 +22,7 @@ import ( "strings" "time" + "modavd/internal/adb" "modavd/internal/errs" "modavd/internal/win" ) @@ -64,6 +65,20 @@ func parseDiscardMaxBytes(out string) (int64, bool) { return n, true } +// probeDiscardMax reads the data disk's advertised discard limit in the guest (vdcDiscardMaxPath, root-only). ok is +// false when it could not be read (adb failed, the file is missing); the caller checks ctx itself. timeout 0 is the +// default of m.su. +func (m *Manager) probeDiscardMax(ctx context.Context, i int, timeout time.Duration) (int64, bool) { + probe := m.su(ctx, i, "cat "+vdcDiscardMaxPath, timeout) + return parseDiscardMaxBytes(probe.Out) +} + +// runIdleMaint triggers the guest's vold idle maintenance (it runs fstrim on the mounted file systems). Shared by +// DiskTrim and the best-effort trim after boot (autotrim.go). +func (m *Manager) runIdleMaint(ctx context.Context, i int, timeout time.Duration) adb.Result { + return m.su(ctx, i, "sm idle-maint run", timeout) +} + // DiskTrim triggers a guest FITRIM on /data (via vold idle maintenance) so the // virtio-blk discard path frees the qcow2 clusters behind deleted files. The // instance must be running and booted. errs.Unsupported when the instance is @@ -90,11 +105,10 @@ func (m *Manager) DiskTrim(ctx context.Context, i int) (*DiskTrimResult, error) // Gate on the emulator actually advertising discard on /data: an old build // reports 0 here, and a trim would silently do nothing. - probe := m.su(ctx, i, "cat "+vdcDiscardMaxPath, 0) + maxBytes, ok := m.probeDiscardMax(ctx, i, 0) if err := ctxErr(ctx); err != nil { return nil, err } - maxBytes, ok := parseDiscardMaxBytes(probe.Out) if !ok || maxBytes <= 0 { return nil, errs.Newf(errs.Unsupported, "这个模拟器版本不支持回收磁盘空间(客体数据盘没有 discard)"). @@ -104,7 +118,7 @@ func (m *Manager) DiskTrim(ctx context.Context, i int) (*DiskTrimResult, error) // vold idle maintenance runs fstrim on the mounted file systems. (The exact // mechanism may be refined to a targeted FITRIM after on-device testing, // ModAVD/ModAVD#2 §4.3.) - res := m.su(ctx, i, "sm idle-maint run", diskTrimTimeout) + res := m.runIdleMaint(ctx, i, diskTrimTimeout) if err := ctxErr(ctx); err != nil { return nil, err } From f4bb688decbdeeb9177f97c73472a3f041507041 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Wed, 4 Nov 2026 08:49:39 +0100 Subject: [PATCH 6/9] =?UTF-8?q?=E7=A3=81=E7=9B=98=E5=9B=9E=E6=94=B6=20S3?= =?UTF-8?q?=EF=BC=9AMCP=20=E5=B7=A5=E5=85=B7=20+=20=E8=BE=93=E5=87=BA?= =?UTF-8?q?=E5=AD=97=E6=AE=B5=E7=BB=9F=E4=B8=80=20snake=5Fcase=EF=BC=88Ref?= =?UTF-8?q?s=20ModAVD/ModAVD#2=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MCP 加三个工具(仿 stop_instance):disk_info(只读)、trim_disk(mutating 非破坏幂等)、 compact_disk(finishing + 破坏性,关机态整理)。backend 接口加三个方法(emu.Manager 已实现), mcp_test 的工具名/数/annotations 跟上,描述英文、和现有工具一致。 顺带把 disk 结果结构体(DiskTrimResult/DiskInfoResult/DiskCompactResult)的 json tag 从 camelCase 统一改成 snake_case,和 types.go 其余结果一致(发版前、无兼容负担);同步改了 cli 契约注释、CLI 单测断言、disk_info 描述里的字段名。 go build/vet/gofmt/test 均过。 --- README.en.md | 2 +- README.md | 2 +- internal/cli/cli.go | 6 +++--- internal/cli/run_test.go | 12 +++++------ internal/emu/disk.go | 20 +++++++++---------- internal/mcp/backend.go | 3 +++ internal/mcp/mcp.go | 5 +++-- internal/mcp/mcp_test.go | 36 ++++++++++++++++++++++++++++----- internal/mcp/tools.go | 43 ++++++++++++++++++++++++++++++++++++++++ 9 files changed, 101 insertions(+), 28 deletions(-) diff --git a/README.en.md b/README.en.md index a5fa9292..eee3acdf 100644 --- a/README.en.md +++ b/README.en.md @@ -134,7 +134,7 @@ modavd [--root ] [--json] [--quiet] [--verbose] [args] modavd mcp --root D:\ModAVD ``` -It supports both MCP 2026-07-28 (stateless, `server/discover`) and 2025-11-25 / 2025-06-18 (`initialize` handshake). The root folder is fixed at startup and is not a tool parameter. Tools: `list_instances`, `get_instance`, `check_host`, `create_instance`, `update_instance`, `delete_instance`, `start_instance` (with progress), `stop_instance`, `set_window_visible`, `shell`, `install_apk`. +It supports both MCP 2026-07-28 (stateless, `server/discover`) and 2025-11-25 / 2025-06-18 (`initialize` handshake). The root folder is fixed at startup and is not a tool parameter. Tools: `list_instances`, `get_instance`, `check_host`, `create_instance`, `update_instance`, `delete_instance`, `start_instance` (with progress), `stop_instance`, `set_window_visible`, `shell`, `install_apk`, `disk_info` (data disk size), `trim_disk` (reclaim space while running; the emulator must support discard), `compact_disk` (shrink the data disk; the instance must be stopped). To register it in Claude Code (in PowerShell, `--` needs quotes, or it gets swallowed): diff --git a/README.md b/README.md index da31ad1b..10e5e571 100644 --- a/README.md +++ b/README.md @@ -137,7 +137,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] modavd mcp --root D:\ModAVD ``` -同时支持 MCP 2026-07-28(无状态,`server/discover`)和 2025-11-25 / 2025-06-18(`initialize` 握手)。根目录在启动时定,不是工具参数。工具:`list_instances`、`get_instance`、`check_host`、`create_instance`、`update_instance`、`delete_instance`、`start_instance`(带进度)、`stop_instance`、`set_window_visible`、`shell`、`install_apk`。 +同时支持 MCP 2026-07-28(无状态,`server/discover`)和 2025-11-25 / 2025-06-18(`initialize` 握手)。根目录在启动时定,不是工具参数。工具:`list_instances`、`get_instance`、`check_host`、`create_instance`、`update_instance`、`delete_instance`、`start_instance`(带进度)、`stop_instance`、`set_window_visible`、`shell`、`install_apk`、`disk_info`(数据盘大小)、`trim_disk`(开机态回收空间,模拟器要支持 discard)、`compact_disk`(关机态整理数据盘,实例须已关机)。 在 Claude Code 里注册(PowerShell 里 `--` 要加引号,否则会被吞掉): diff --git a/internal/cli/cli.go b/internal/cli/cli.go index c26e9683..c228f68e 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -22,9 +22,9 @@ // report-config [--no-clipboard] read-only configuration and installed-game report // collect-info [--out-dir D] [--stage-dir D] ... read-only diagnostics zip // window show|hide emu.WindowResult -// disk trim emu.DiskTrimResult {index,discardMaxBytes} -// disk info emu.DiskInfoResult {index,overlay,running,needsShutdown,logicalBytes,onDiskBytes,allocatedBytes?,reclaimableBytes?} -// disk compact emu.DiskCompactResult {index,overlay,beforeOnDiskBytes,afterOnDiskBytes,freedBytes} +// disk trim emu.DiskTrimResult {index,discard_max_bytes} +// disk info emu.DiskInfoResult {index,overlay,running,needs_shutdown,logical_bytes,on_disk_bytes,allocated_bytes?,reclaimable_bytes?} +// disk compact emu.DiskCompactResult {index,overlay,before_on_disk_bytes,after_on_disk_bytes,freed_bytes} // install emu.InstallResult // shell [--timeout S] emu.ShellResult // adb [--] no envelope: adb's own stdio and exit code diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index 77059e41..4412d956 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -1033,7 +1033,7 @@ func TestDiskTrim(t *testing.T) { if m := envelope(t, r.stdout); m["ok"] != true { t.Errorf("json: %s", r.stdout) } - if !strings.Contains(r.stdout, `"discardMaxBytes":2147483648`) { + if !strings.Contains(r.stdout, `"discard_max_bytes":2147483648`) { t.Errorf("json data: %s", r.stdout) } // an unknown action is a usage error and reaches no manager @@ -1057,7 +1057,7 @@ func TestDiskCompact(t *testing.T) { if m := envelope(t, r.stdout); m["ok"] != true { t.Errorf("json: %s", r.stdout) } - for _, s := range []string{`"freedBytes":1073741824`, `"beforeOnDiskBytes":3221225472`, `"afterOnDiskBytes":2147483648`} { + for _, s := range []string{`"freed_bytes":1073741824`, `"before_on_disk_bytes":3221225472`, `"after_on_disk_bytes":2147483648`} { if !strings.Contains(r.stdout, s) { t.Errorf("json data lacks %s: %s", s, r.stdout) } @@ -1079,8 +1079,8 @@ func TestDiskInfo(t *testing.T) { if m := envelope(t, r.stdout); m["ok"] != true { t.Errorf("json: %s", r.stdout) } - for _, s := range []string{`"logicalBytes":8589934592`, `"onDiskBytes":3221225472`, `"allocatedBytes":2147483648`, - `"reclaimableBytes":1073741824`, `"needsShutdown":false`} { + for _, s := range []string{`"logical_bytes":8589934592`, `"on_disk_bytes":3221225472`, `"allocated_bytes":2147483648`, + `"reclaimable_bytes":1073741824`, `"needs_shutdown":false`} { if !strings.Contains(r.stdout, s) { t.Errorf("json data lacks %s: %s", s, r.stdout) } @@ -1093,8 +1093,8 @@ func TestDiskInfo(t *testing.T) { t.Errorf("running text: code %d stdout %q", r.code, r.stdout) } r = h.run(t, nil, "--json", "disk", "4", "info") - if strings.Contains(r.stdout, "allocatedBytes") || strings.Contains(r.stdout, "reclaimableBytes") || - !strings.Contains(r.stdout, `"needsShutdown":true`) { + if strings.Contains(r.stdout, "allocated_bytes") || strings.Contains(r.stdout, "reclaimable_bytes") || + !strings.Contains(r.stdout, `"needs_shutdown":true`) { t.Errorf("running json: %s", r.stdout) } } diff --git a/internal/emu/disk.go b/internal/emu/disk.go index 92e14e25..80d12716 100644 --- a/internal/emu/disk.go +++ b/internal/emu/disk.go @@ -51,7 +51,7 @@ type DiskTrimResult struct { // DiscardMaxBytes is the data disk's advertised discard limit (guest // /sys/block/vdc/queue/discard_max_bytes); >0 confirms the emulator's // discard path is live. - DiscardMaxBytes int64 `json:"discardMaxBytes"` + DiscardMaxBytes int64 `json:"discard_max_bytes"` } // parseDiscardMaxBytes reads the number printed by cat of a sysfs @@ -142,21 +142,21 @@ type DiskInfoResult struct { // Running is true when the instance's qemu is up. The overlay is then open in qemu: AllocatedBytes and // ReclaimableBytes are left out (NeedsShutdown), qemu-img is not run on it. Running bool `json:"running"` - NeedsShutdown bool `json:"needsShutdown"` + NeedsShutdown bool `json:"needs_shutdown"` // LogicalBytes is the virtual size of the disk (qcow2 header); 0 when it could not be read. - LogicalBytes int64 `json:"logicalBytes,omitempty"` + LogicalBytes int64 `json:"logical_bytes,omitempty"` // OnDiskBytes is what the overlay occupies on the host volume (GetCompressedFileSize: a sparse file counts only // its data). - OnDiskBytes int64 `json:"onDiskBytes"` + OnDiskBytes int64 `json:"on_disk_bytes"` // ClusterBytes is the qcow2 cluster size. - ClusterBytes int64 `json:"clusterBytes,omitempty"` + ClusterBytes int64 `json:"cluster_bytes,omitempty"` // AllocatedBytes is the guest data the overlay really holds (allocated clusters x cluster size, qemu-img check); // nil while the instance runs. - AllocatedBytes *int64 `json:"allocatedBytes,omitempty"` + AllocatedBytes *int64 `json:"allocated_bytes,omitempty"` // ReclaimableBytes estimates what a compact would save: OnDiskBytes minus AllocatedBytes (the rewritten image is // about AllocatedBytes plus a little metadata, so the real saving is slightly less). nil while the instance runs // or when the image check found errors. - ReclaimableBytes *int64 `json:"reclaimableBytes,omitempty"` + ReclaimableBytes *int64 `json:"reclaimable_bytes,omitempty"` Warnings []string `json:"warnings,omitempty"` } @@ -356,9 +356,9 @@ const userdataCompactTmp = userdataOverlay + ".compact.tmp" type DiskCompactResult struct { Index int `json:"index"` Overlay string `json:"overlay"` - BeforeOnDiskBytes int64 `json:"beforeOnDiskBytes"` - AfterOnDiskBytes int64 `json:"afterOnDiskBytes"` - FreedBytes int64 `json:"freedBytes"` + BeforeOnDiskBytes int64 `json:"before_on_disk_bytes"` + AfterOnDiskBytes int64 `json:"after_on_disk_bytes"` + FreedBytes int64 `json:"freed_bytes"` } // qemuImgInfoResult is the part of `qemu-img info --output=json` compact reads. diff --git a/internal/mcp/backend.go b/internal/mcp/backend.go index c6c3c80e..924311f4 100644 --- a/internal/mcp/backend.go +++ b/internal/mcp/backend.go @@ -20,6 +20,9 @@ type backend interface { SetWindowVisible(ctx context.Context, i int, visible bool) (*emu.WindowResult, error) Shell(ctx context.Context, i int, command string, timeout time.Duration) (*emu.ShellResult, error) InstallAPK(ctx context.Context, i int, apkPath string) (*emu.InstallResult, error) + DiskInfo(ctx context.Context, i int) (*emu.DiskInfoResult, error) + DiskTrim(ctx context.Context, i int) (*emu.DiskTrimResult, error) + DiskCompact(ctx context.Context, i int) (*emu.DiskCompactResult, error) // Wait waits up to timeout for the background work the manager started (the logcat restart after a // re-registration). Called after each call's result is sent; Serve waits for those waits before it returns. Wait(timeout time.Duration) diff --git a/internal/mcp/mcp.go b/internal/mcp/mcp.go index 71dcaa61..4fabc686 100644 --- a/internal/mcp/mcp.go +++ b/internal/mcp/mcp.go @@ -16,7 +16,7 @@ // // Shutdown, at EOF on in or when ctx ends: nothing more is written, and every call is canceled (start / stop just stop // waiting) except the tools that write files without stopping half way (create / update / delete_instance, -// install_apk). The process exits right after Serve returns, so those get up to shutdownWait (30 s) to finish first: +// install_apk, compact_disk). The process exits right after Serve returns, so those get up to shutdownWait (30 s) to finish first: // an avd.Delete cut in the middle leaves an instance directory without config.ini that modavd no longer lists nor // deletes, an update cut between config.ini and mas-avd.json leaves the two out of step. Within the same bound Serve // waits for the canceled calls to return and for their managers' background work (backend.Wait, at most hookWait each @@ -62,7 +62,8 @@ var instructions = fmt.Sprintf("Manages the ModAVD (patched Android Emulator) in "is fixed by the server's --root; instances are numbered 0-%d except %d. Always shut instances down with "+ "stop_instance, which syncs the guest disk first: never kill emulator or qemu processes, that loses recently "+ "written game data. start_instance can take minutes and reports progress; delete_instance permanently removes "+ - "an instance with all its game data.", root.MaxIndex, root.ReservedIndex) + "an instance with all its game data. disk_info shows how big an instance's data disk is; trim_disk reclaims "+ + "unused space of a running instance, compact_disk shrinks the file of a stopped one.", root.MaxIndex, root.ReservedIndex) // progressEvery throttles progress notifications that do not complete a step. const progressEvery = time.Second diff --git a/internal/mcp/mcp_test.go b/internal/mcp/mcp_test.go index 0a44ef04..5f871208 100644 --- a/internal/mcp/mcp_test.go +++ b/internal/mcp/mcp_test.go @@ -196,6 +196,25 @@ func (f *fake) InstallAPK(ctx context.Context, i int, apkPath string) (*emu.Inst return &emu.InstallResult{Index: i, APK: apkPath, Package: "com.example", Output: "Success"}, nil } +func (f *fake) DiskInfo(ctx context.Context, i int) (*emu.DiskInfoResult, error) { + f.record("disk info %d", i) + allocated, reclaim := int64(8<<30), int64(4<<30) + return &emu.DiskInfoResult{Index: i, Overlay: fmt.Sprintf(`D:\r1\avd\mas_%d.avd\userdata-qemu.img.qcow2`, i), + LogicalBytes: 64 << 30, OnDiskBytes: 12 << 30, ClusterBytes: 65536, AllocatedBytes: &allocated, + ReclaimableBytes: &reclaim}, nil +} + +func (f *fake) DiskTrim(ctx context.Context, i int) (*emu.DiskTrimResult, error) { + f.record("disk trim %d", i) + return &emu.DiskTrimResult{Index: i, DiscardMaxBytes: 4 << 20}, nil +} + +func (f *fake) DiskCompact(ctx context.Context, i int) (*emu.DiskCompactResult, error) { + f.record("disk compact %d", i) + return &emu.DiskCompactResult{Index: i, Overlay: fmt.Sprintf(`D:\r1\avd\mas_%d.avd\userdata-qemu.img.qcow2`, i), + BeforeOnDiskBytes: 12 << 30, AfterOnDiskBytes: 8 << 30, FreedBytes: 4 << 30}, nil +} + // fakeConn is what one tool call gets: the shared fake plus that call's logger. type fakeConn struct { *fake @@ -480,7 +499,7 @@ func TestLegacySession(t *testing.T) { t.Fatalf("legacy tools/list has %s", k) } } - if n := len(r["tools"].([]any)); n != 11 { + if n := len(r["tools"].([]any)); n != 14 { t.Fatalf("%d tools", n) } @@ -545,7 +564,7 @@ func TestModernSession(t *testing.T) { r := result(t, h.request(1, "tools/list", modernParams(nil, nil))) if r["resultType"] != "complete" || r["ttlMs"] != float64(listTTLMs) || r["cacheScope"] != "public" || - r["_meta"] == nil || len(r["tools"].([]any)) != 11 { + r["_meta"] == nil || len(r["tools"].([]any)) != 14 { t.Fatalf("tools/list %v", r) } @@ -743,6 +762,9 @@ func TestToolCalls(t *testing.T) { {"set_window_visible", map[string]any{"index": 1, "visible": false}, "window 1 false"}, {"shell", map[string]any{"index": 1, "command": "getprop sys.boot_completed", "timeout_s": 10}, "shell 1"}, {"install_apk", map[string]any{"index": 1, "apk_path": `D:\apk\game.apk`}, "install 1 D:\\apk\\game.apk"}, + {"disk_info", map[string]any{"index": 1}, "disk info 1"}, + {"trim_disk", map[string]any{"index": 1}, "disk trim 1"}, + {"compact_disk", map[string]any{"index": 1}, "disk compact 1"}, } for n, c := range cases { tool := tools[c.name] @@ -1092,7 +1114,7 @@ func TestCancelStart(t *testing.T) { <-started // the read loop is free while the instance boots - if r := result(t, h.request(2, "tools/list", nil)); len(r["tools"].([]any)) != 11 { + if r := result(t, h.request(2, "tools/list", nil)); len(r["tools"].([]any)) != 14 { t.Fatal("tools/list during boot") } @@ -1374,7 +1396,7 @@ func TestWaitsForManagerAfterCall(t *testing.T) { func TestKeptTools(t *testing.T) { for _, tool := range toolDefs() { want := tool.Name == "create_instance" || tool.Name == "update_instance" || tool.Name == "delete_instance" || - tool.Name == "install_apk" + tool.Name == "install_apk" || tool.Name == "compact_disk" if tool.keep != want { t.Errorf("%s: keep %v", tool.Name, tool.keep) } @@ -1433,7 +1455,8 @@ func TestToolDefinitions(t *testing.T) { t.Fatal("tool list differs between eras / calls") } want := []string{"list_instances", "get_instance", "check_host", "create_instance", "update_instance", - "delete_instance", "start_instance", "stop_instance", "set_window_visible", "shell", "install_apk"} + "delete_instance", "start_instance", "stop_instance", "set_window_visible", "shell", "install_apk", + "disk_info", "trim_disk", "compact_disk"} if len(tools) != len(want) { t.Fatalf("%d tools", len(tools)) } @@ -1491,6 +1514,9 @@ func TestToolDefinitions(t *testing.T) { "delete_instance": {false, true, true}, "start_instance": {false, false, true}, "stop_instance": {false, true, true}, + "disk_info": {true, nil, nil}, + "trim_disk": {false, false, true}, + "compact_disk": {false, true, false}, } { ann := byName[name]["annotations"].(map[string]any) if ann["readOnlyHint"] != hints[0] || ann["destructiveHint"] != hints[1] || ann["idempotentHint"] != hints[2] { diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go index ea545311..d6484ae7 100644 --- a/internal/mcp/tools.go +++ b/internal/mcp/tools.go @@ -438,6 +438,49 @@ func toolDefs() []*toolDef { } return b.InstallAPK(ctx, i, *path) })), + + newTool("disk_info", "Get data disk size", + "Report the size of an instance's data disk (the qcow2 overlay): virtual size, what it occupies on the "+ + "host, and, for a stopped instance, the guest data it really holds and the estimated saving of "+ + "compact_disk. A running instance only gets the host size (needs_shutdown=true): the allocated and "+ + "reclaimable figures need the instance offline. Read-only.", + readOnly(), reflect.TypeFor[emu.DiskInfoResult](), []prop{indexProp(true)}, + func(ctx context.Context, b backend, a args, _ func(emu.Progress)) (any, error) { + i, err := a.reqInt("index") + if err != nil { + return nil, err + } + return b.DiskInfo(ctx, i) + }), + + newTool("trim_disk", "Trim data disk", + "Trigger one reclaim of the unused space in a running, booted instance's data disk (guest fstrim via "+ + "idle maintenance), so the host file can shrink as deleted game data is discarded. The instance "+ + "must be online and the emulator must support discard (an old emulator build without it fails "+ + "with unsupported). Safe to repeat; takes up to about 2 minutes. To shrink the file fully, stop "+ + "the instance and use compact_disk.", + mutating(false, true), reflect.TypeFor[emu.DiskTrimResult](), []prop{indexProp(true)}, + func(ctx context.Context, b backend, a args, _ func(emu.Progress)) (any, error) { + i, err := a.reqInt("index") + if err != nil { + return nil, err + } + return b.DiskTrim(ctx, i) + }), + + finishing(newTool("compact_disk", "Compact data disk", + "Rewrite a stopped instance's data disk so it keeps only the clusters still in use, then swap it in "+ + "(the original stays untouched until the final replace). The instance must be offline (stop it "+ + "with stop_instance first; a running one fails with busy) and must have no snapshots. Can take "+ + "several minutes for a large disk; use disk_info first to see what it would save.", + mutating(true, false), reflect.TypeFor[emu.DiskCompactResult](), []prop{indexProp(true)}, + func(ctx context.Context, b backend, a args, _ func(emu.Progress)) (any, error) { + i, err := a.reqInt("index") + if err != nil { + return nil, err + } + return b.DiskCompact(ctx, i) + })), } } From bc47c38e1fa6eb69d00fe2f1ccf7fc1ef8360155 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Wed, 4 Nov 2026 08:58:55 +0100 Subject: [PATCH 7/9] =?UTF-8?q?=E7=A3=81=E7=9B=98=E5=9B=9E=E6=94=B6=20S3?= =?UTF-8?q?=EF=BC=9A=E7=95=8C=E9=9D=A2=E5=8A=A0=20=E7=A3=81=E7=9B=98?= =?UTF-8?q?=E5=8D=A0=E7=94=A8/=E5=9B=9E=E6=94=B6=E7=A9=BA=E9=97=B4/?= =?UTF-8?q?=E6=95=B4=E7=90=86=E7=A3=81=E7=9B=98=20=E6=8C=89=E9=92=AE?= =?UTF-8?q?=EF=BC=88Refs=20ModAVD/ModAVD#2=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GUI 每实例加三个动作(仿安装 APK 那条链):磁盘占用(只读、随时可用)、回收磁盘空间 (在线时可用,trim)、整理磁盘(关机时可用,compact,耗时 job)。菜单按实例状态门控, 服务端只起 job、状态规则交给 emu。新增 internal/ui/disk.go(三个 handler + humanBytes)、 backend 接口加三方法、http 路由、job kind、前端 cards/actions/format/panels/dom/mock、API.md。 带 TestDiskJobs/TestDiskJobError/TestDiskCompactBusy/TestDiskBadRequests 等测试。 go build/vet/gofmt/test 均过(子代理还在浏览器窗格 mock 实跑了门控和三动作)。 --- internal/ui/API.md | 9 ++- internal/ui/backend.go | 5 ++ internal/ui/disk.go | 79 ++++++++++++++++++++ internal/ui/disk_test.go | 137 ++++++++++++++++++++++++++++++++++ internal/ui/fake_test.go | 53 +++++++++++++ internal/ui/http.go | 3 + internal/ui/jobs.go | 10 +++ internal/ui/jobs_test.go | 1 + internal/ui/ui.go | 2 +- internal/ui/web/dev/mock.js | 33 +++++++- internal/ui/web/js/actions.js | 15 +++- internal/ui/web/js/cards.js | 12 ++- internal/ui/web/js/dom.js | 1 + internal/ui/web/js/format.js | 33 +++++++- internal/ui/web/js/panels.js | 10 ++- 15 files changed, 388 insertions(+), 15 deletions(-) create mode 100644 internal/ui/disk.go create mode 100644 internal/ui/disk_test.go diff --git a/internal/ui/API.md b/internal/ui/API.md index 9ea20122..0ae52656 100644 --- a/internal/ui/API.md +++ b/internal/ui/API.md @@ -41,6 +41,9 @@ HTTP 4xx / 5xx,体为 `{"error":{"code":"…","message":"…","advice":"…"}} | POST | `/api/instances/{i}/start` | `{}` | 202 `Job`:一律带窗口开机(管理器不开无头的,无头开机只走命令行);实例已经以无头方式在运行时,任务失败,code 是 `busy`(运行中不切换) | | POST | `/api/instances/{i}/stop` | `{force?: bool}` | 202 `Job` | | POST | `/api/instances/{i}/install` | `multipart/form-data`,文件字段 `apk` | 202 `Job`(服务端存到临时文件,任务结束删掉) | +| POST | `/api/instances/{i}/disk-info` | `{}` | 202 `Job`(`kind` 是 `disk-info`):数据盘的占用,随时可以查(开机时 `allocated_bytes`、`reclaimable_bytes` 不返回,`needs_shutdown` 为 `true`);结果是 emu 的 `DiskInfoResult` | +| POST | `/api/instances/{i}/disk-trim` | `{}` | 202 `Job`(`kind` 是 `disk-trim`):让开着的安卓把删掉的文件占的空间还给模拟器(电脑上的文件要整理后才变小);实例没开机完成、或模拟器版本不支持时任务失败,code 是 `unsupported`;结果是 `DiskTrimResult` | +| POST | `/api/instances/{i}/disk-compact` | `{}` | 202 `Job`(`kind` 是 `disk-compact`):重写已关机实例的数据盘文件,只留在用的部分,要几分钟;实例没关机时任务失败,code 是 `busy`;结果是 `DiskCompactResult` | | POST | `/api/instances/{i}/resume` | `{}` | 202 `Job`(`kind` 是 `create`):重做新建失败的那台的初始化 | | POST | `/api/instances/{i}/input` | `{type:"tap", x, y}`(坐标是 1280×720 显示的像素)或 `{type:"key", key:"back"\|"home"\|"recents"}` | `{}` | | GET | `/api/instances/{i}/screenshot` | | `image/png`(`adb exec-out screencap -p`),`Cache-Control: no-store`;没开机回 409 | @@ -69,11 +72,11 @@ HTTP 4xx / 5xx,体为 `{"error":{"code":"…","message":"…","advice":"…"}} "result":null,"error":null,"warnings":[]} ``` -- `kind`:`start` / `stop` / `install` / `create`(0.3.0 起没有重启,也没有显示 / 隐藏窗口)。 +- `kind`:`start` / `stop` / `install` / `create` / `disk-info` / `disk-trim` / `disk-compact`(0.3.0 起没有重启,也没有显示 / 隐藏窗口)。 - `state`:`running` / `done` / `failed` / `canceled`。 -- `progress.step`:开机用 emu 的 `launch` / `boot` / `tune` / `ime` / `first_boot` / `vulkan_fix` / `done`;关机(含等被取消的开机停下)是 `stop`,安装是 `install`,这两种做完是 `done`;装执行桥的每一轮是 `bridge`;新建是 `create`、其中几次开机的上述各步(开机做完是 `setup`)、`create_stop`、`done`,几次开机合成一条不回退的进度。`total` 一律 1000。 +- `progress.step`:开机用 emu 的 `launch` / `boot` / `tune` / `ime` / `first_boot` / `vulkan_fix` / `done`;关机(含等被取消的开机停下)是 `stop`,安装是 `install`,这两种做完是 `done`;磁盘任务进行中是 `disk_info` / `disk_trim` / `disk_compact`、做完是 `done`(进行中没有百分比,`total` 为 0,页面显示不定长进度条;做完 `done` = `total` = 1000);装执行桥的每一轮是 `bridge`;新建是 `create`、其中几次开机的上述各步(开机做完是 `setup`)、`create_stop`、`done`,几次开机合成一条不回退的进度。`total` 一律 1000。 - 安装任务的 `result.apk` 是用户上传的文件名,不是服务端的临时路径(临时文件任务结束就删了)。 -- `progress` 在没有进度时为 `null`;`result` 是 `StartResult` / `StopResult` / `InstallResult` / `InstanceInfo`(新建),没完成时为 `null`;`error` 失败时是错误对象,否则 `null`。 +- `progress` 在没有进度时为 `null`;`result` 是 `StartResult` / `StopResult` / `InstallResult` / `DiskInfoResult` / `DiskTrimResult` / `DiskCompactResult` / `InstanceInfo`(新建),没完成时为 `null`;`error` 失败时是错误对象,否则 `null`。 - 同一实例同时只能有一个任务在跑;第二个回 409 `busy`。**例外**:开机任务进行中可以发关机(和 emu 一致:开机中照样能关)。 - 取消开机:只停止等待,模拟器继续开机,不会被强制结束。 diff --git a/internal/ui/backend.go b/internal/ui/backend.go index c49550e7..ac3d1898 100644 --- a/internal/ui/backend.go +++ b/internal/ui/backend.go @@ -23,6 +23,11 @@ type backend interface { Check(ctx context.Context, opt emu.CheckOptions) (*emu.CheckResult, error) Shell(ctx context.Context, i int, command string, timeout time.Duration) (*emu.ShellResult, error) InstallAPK(ctx context.Context, i int, apkPath string) (*emu.InstallResult, error) + // DiskTrim / DiskInfo / DiskCompact are the data-disk reclaim (modavd disk): trim needs the instance booted, + // info works either way, compact needs it shut down. + DiskTrim(ctx context.Context, i int) (*emu.DiskTrimResult, error) + DiskInfo(ctx context.Context, i int) (*emu.DiskInfoResult, error) + DiskCompact(ctx context.Context, i int) (*emu.DiskCompactResult, error) // AdbRun is Manager.ADB.Run (the screenshot: exec-out screencap -p with Raw). AdbRun(ctx context.Context, opt adb.RunOptions, args ...string) adb.Result // Serial is instance i's adb serial in the root's port plan. diff --git a/internal/ui/disk.go b/internal/ui/disk.go new file mode 100644 index 00000000..a38fdf50 --- /dev/null +++ b/internal/ui/disk.go @@ -0,0 +1,79 @@ +package ui + +import ( + "context" + "fmt" + "net/http" +) + +// The data-disk reclaim of an instance (emu disk.go, `modavd disk`) as jobs. emu checks the instance state itself +// (trim wants it booted, compact wants it shut down, info works either way) and answers with its own errors, so the +// handlers only start the job; the page greys the menu items by status but the server does not repeat the rule. + +// handleDiskInfo is POST /api/instances/{i}/disk-info: the sizes of the data disk (logical, on the host, allocated, +// reclaimable). Read-only, so it is allowed while the instance runs; the last two are then left out (needs_shutdown). +func (s *server) handleDiskInfo(w http.ResponseWriter, r *http.Request) { + i, ok := pathIndex(w, r) + if !ok || !decode(w, r, &struct{}{}) { + return + } + s.respondJob(w)(s.startJob(kindDiskInfo, i, func(ctx context.Context, j *job, b backend) (any, error) { + s.setProgress(j, jobProgress{Step: "disk_info", Message: fmt.Sprintf("实例 %d 正在查看磁盘占用", i)}) + res, err := b.DiskInfo(ctx, i) + if err != nil { + return nil, err + } + s.setProgress(j, jobProgress{Step: "done", Message: fmt.Sprintf("实例 %d 的磁盘占用已查看", i), Done: progressTotal, Total: progressTotal}) + return res, nil + })) +} + +// handleDiskTrim is POST /api/instances/{i}/disk-trim: asks the booted guest to hand the space of deleted files back +// to the emulator (the file on the PC shrinks only after a compact). +func (s *server) handleDiskTrim(w http.ResponseWriter, r *http.Request) { + i, ok := pathIndex(w, r) + if !ok || !decode(w, r, &struct{}{}) { + return + } + s.respondJob(w)(s.startJob(kindDiskTrim, i, func(ctx context.Context, j *job, b backend) (any, error) { + s.setProgress(j, jobProgress{Step: "disk_trim", Message: fmt.Sprintf("实例 %d 正在回收磁盘空间", i)}) + res, err := b.DiskTrim(ctx, i) + if err != nil { + return nil, err + } + s.setProgress(j, jobProgress{Step: "done", Message: fmt.Sprintf("实例 %d 已回收磁盘空间", i), Done: progressTotal, Total: progressTotal}) + return res, nil + })) +} + +// handleDiskCompact is POST /api/instances/{i}/disk-compact: rewrites the shut-down instance's data disk file without +// the freed clusters. It copies the whole disk, so it takes minutes (the page offers no cancel; POST /api/jobs/{id}/cancel still ends it). +func (s *server) handleDiskCompact(w http.ResponseWriter, r *http.Request) { + i, ok := pathIndex(w, r) + if !ok || !decode(w, r, &struct{}{}) { + return + } + s.respondJob(w)(s.startJob(kindDiskCompact, i, func(ctx context.Context, j *job, b backend) (any, error) { + s.setProgress(j, jobProgress{Step: "disk_compact", Message: fmt.Sprintf("实例 %d 正在整理磁盘(重写数据盘文件,要几分钟)", i)}) + res, err := b.DiskCompact(ctx, i) + if err != nil { + return nil, err + } + s.setProgress(j, jobProgress{Step: "done", Message: fmt.Sprintf("实例 %d 已整理磁盘,释放 %s", i, humanBytes(res.FreedBytes)), Done: progressTotal, Total: progressTotal}) + return res, nil + })) +} + +// humanBytes is a size for a message: "1.5 GB", "320 MB", "12 KB". +func humanBytes(n int64) string { + const k = 1024 + switch { + case n >= k*k*k: + return fmt.Sprintf("%.1f GB", float64(n)/(k*k*k)) + case n >= k*k: + return fmt.Sprintf("%.0f MB", float64(n)/(k*k)) + case n >= k: + return fmt.Sprintf("%.0f KB", float64(n)/k) + } + return fmt.Sprintf("%d B", n) +} diff --git a/internal/ui/disk_test.go b/internal/ui/disk_test.go new file mode 100644 index 00000000..c82161aa --- /dev/null +++ b/internal/ui/disk_test.go @@ -0,0 +1,137 @@ +//go:build windows + +package ui + +import ( + "net/http" + "slices" + "strconv" + "testing" + + "modavd/internal/emu" + "modavd/internal/errs" +) + +// diskJob runs POST /api/instances/{i}/{kind} to the end and returns the finished job with its result decoded into out. +func diskJob(t *testing.T, h *harness, i int, kind string, out any) jobView { + t.Helper() + var j jobView + expect(t, h.do("POST", "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/api/instances/"+strconv.Itoa(i)+"/"+kind, `{}`), http.StatusAccepted, &j) + if j.Kind != kind || j.Index != i || j.State != stateRunning { + t.Fatalf("%s job %+v", kind, j) + } + h.waitJob(j.ID, func(v jobView) bool { return v.State != stateRunning }) + done := struct { + jobView + Result any `json:"result"` + }{Result: out} + expect(t, h.do("GET", "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/api/jobs/"+j.ID, nil), http.StatusOK, &done) + return done.jobView +} + +func TestDiskJobs(t *testing.T) { + h := newHarness(t, nil) + + // info works while the instance is off: every size is there + var info emu.DiskInfoResult + v := diskJob(t, h, 3, kindDiskInfo, &info) + if v.State != stateDone || v.Error != nil || v.Progress == nil || v.Progress.Step != "done" { + t.Fatalf("info job %+v", v) + } + if info.Index != 3 || info.LogicalBytes != 64<<30 || info.OnDiskBytes != 12<<30 || info.NeedsShutdown || + info.AllocatedBytes == nil || *info.AllocatedBytes != 10<<30 || info.ReclaimableBytes == nil || *info.ReclaimableBytes != 2<<30 { + t.Fatalf("info result %+v", info) + } + + // ... and while it runs: allocated and reclaimable are left out + h.f.put(4, emu.StatusOnline) + var running emu.DiskInfoResult + v = diskJob(t, h, 4, kindDiskInfo, &running) + if v.State != stateDone || !running.Running || !running.NeedsShutdown || running.AllocatedBytes != nil || running.ReclaimableBytes != nil { + t.Fatalf("info of a running instance %+v (%+v)", running, v) + } + + var trim emu.DiskTrimResult + v = diskJob(t, h, 4, kindDiskTrim, &trim) + if v.State != stateDone || trim.Index != 4 || trim.DiscardMaxBytes != 2<<30 || v.Progress == nil || v.Progress.Step != "done" { + t.Fatalf("trim job %+v (%+v)", v, trim) + } + + var compact emu.DiskCompactResult + v = diskJob(t, h, 3, kindDiskCompact, &compact) + if v.State != stateDone || compact.FreedBytes != 2<<30 || compact.BeforeOnDiskBytes != 12<<30 || compact.AfterOnDiskBytes != 10<<30 { + t.Fatalf("compact job %+v (%+v)", v, compact) + } + if v.Progress == nil || v.Progress.Message != "实例 3 已整理磁盘,释放 2.0 GB" { + t.Fatalf("compact progress %+v", v.Progress) + } + + h.f.mu.Lock() + calls := slices.Clone(h.f.disk) + h.f.mu.Unlock() + if !slices.Equal(calls, []string{"info 3", "info 4", "trim 4", "compact 3"}) { + t.Fatalf("backend calls %v", calls) + } + + // the result keeps emu's snake_case names (the page reads them) + var raw map[string]any + j := diskJob(t, h, 3, kindDiskInfo, &raw) + for _, k := range []string{"logical_bytes", "on_disk_bytes", "allocated_bytes", "reclaimable_bytes"} { + if _, ok := raw[k]; !ok { + t.Errorf("job %s: result has no %q: %v", j.ID, k, raw) + } + } +} + +// emu refuses a trim of an instance that is not booted and a compact of one that runs; the job fails with its error. +func TestDiskJobError(t *testing.T) { + h := newHarness(t, nil) + h.f.diskErr = errs.New(errs.Unsupported, "实例没有在运行").WithAdvice("先开机") + + v := diskJob(t, h, 3, kindDiskTrim, nil) + if v.State != stateFailed || v.Error == nil || v.Error.Code != errs.Unsupported || v.Error.Message != "实例没有在运行" || + v.Error.Advice != "先开机" { + t.Fatalf("failed trim job %+v (error %+v)", v, v.Error) + } +} + +func TestDiskCompactBusy(t *testing.T) { + h := newHarness(t, nil) + gate := make(chan struct{}) + h.f.diskGate = gate + + var j jobView + expect(t, h.do("POST", "/api/instances/3/disk-compact", `{}`), http.StatusAccepted, &j) + e := expectError(t, h.do("POST", "/api/instances/3/disk-info", `{}`), http.StatusConflict, errs.Busy) + t.Logf("busy message: %s", e.Message) + expectError(t, h.do("POST", "/api/instances/3/start", `{}`), http.StatusConflict, errs.Busy) + expectError(t, h.do("DELETE", "/api/instances/3?confirm=1", nil), http.StatusConflict, errs.Busy) + // another instance is not affected + expect(t, h.do("POST", "/api/instances/4/disk-info", `{}`), http.StatusAccepted, nil) + + close(gate) + h.waitJob(j.ID, stateIs(stateDone)) +} + +func TestDiskBadRequests(t *testing.T) { + h := newHarness(t, nil) + for _, kind := range []string{kindDiskInfo, kindDiskTrim, kindDiskCompact} { + expectError(t, h.do("POST", "/api/instances/3/"+kind, `{"force":true}`), 400, errs.Usage) + expectError(t, h.do("POST", "/api/instances/5/"+kind, `{}`), 400, errs.InvalidArgument) + } + h.f.mu.Lock() + n := len(h.f.disk) + h.f.mu.Unlock() + if n != 0 { + t.Fatalf("refused requests still called the backend %d times", n) + } +} + +func TestHumanBytes(t *testing.T) { + cases := map[int64]string{0: "0 B", 1023: "1023 B", 2048: "2 KB", 5 << 20: "5 MB", 3 << 30: "3.0 GB", 3<<30 + 512<<20: "3.5 GB"} + for in, want := range cases { + if got := humanBytes(in); got != want { + t.Errorf("humanBytes(%d) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/ui/fake_test.go b/internal/ui/fake_test.go index 9b3b2b59..ee499c73 100644 --- a/internal/ui/fake_test.go +++ b/internal/ui/fake_test.go @@ -8,6 +8,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "io" "net" "net/http" @@ -42,6 +43,9 @@ type fake struct { shells []string shellCode int installs []fakeInstall + disk []string // "info 3", "trim 3", "compact 3" in call order + diskErr error // returned by every disk call when set + diskGate chan struct{} // DiskCompact waits here when set startGate chan struct{} // Start waits here (after its first progress) when set stopGate chan struct{} @@ -237,6 +241,55 @@ func (b fakeBackend) InstallAPK(ctx context.Context, i int, apkPath string) (*em return &emu.InstallResult{Index: i, APK: apkPath, Package: "com.example", Output: "Success"}, nil } +// diskCall records one disk call and returns the injected error, if any. +func (b fakeBackend) diskCall(what string, i int) error { + b.f.mu.Lock() + defer b.f.mu.Unlock() + b.f.disk = append(b.f.disk, fmt.Sprintf("%s %d", what, i)) + return b.f.diskErr +} + +func (b fakeBackend) DiskInfo(ctx context.Context, i int) (*emu.DiskInfoResult, error) { + if err := b.diskCall("info", i); err != nil { + return nil, err + } + in, _ := b.f.get(i) + allocated, reclaimable := int64(10<<30), int64(2<<30) + res := &emu.DiskInfoResult{Index: i, Overlay: `C:\fake\userdata-qemu.img.qcow2`, Running: in.Running, + LogicalBytes: 64 << 30, OnDiskBytes: 12 << 30, ClusterBytes: 65536} + if in.Running { + res.NeedsShutdown = true + } else { + res.AllocatedBytes, res.ReclaimableBytes = &allocated, &reclaimable + } + return res, nil +} + +func (b fakeBackend) DiskTrim(ctx context.Context, i int) (*emu.DiskTrimResult, error) { + if err := b.diskCall("trim", i); err != nil { + return nil, err + } + return &emu.DiskTrimResult{Index: i, DiscardMaxBytes: 2 << 30}, nil +} + +func (b fakeBackend) DiskCompact(ctx context.Context, i int) (*emu.DiskCompactResult, error) { + if err := b.diskCall("compact", i); err != nil { + return nil, err + } + b.f.mu.Lock() + gate := b.f.diskGate + b.f.mu.Unlock() + if gate != nil { + select { + case <-gate: + case <-ctx.Done(): + return nil, canceledErr(ctx) + } + } + return &emu.DiskCompactResult{Index: i, Overlay: `C:\fake\userdata-qemu.img.qcow2`, + BeforeOnDiskBytes: 12 << 30, AfterOnDiskBytes: 10 << 30, FreedBytes: 2 << 30}, nil +} + func (b fakeBackend) AdbRun(ctx context.Context, opt adb.RunOptions, args ...string) adb.Result { b.f.adbCalls.Add(1) b.f.mu.Lock() diff --git a/internal/ui/http.go b/internal/ui/http.go index 87742fd5..02f07f36 100644 --- a/internal/ui/http.go +++ b/internal/ui/http.go @@ -32,6 +32,9 @@ func (s *server) routes() { m.HandleFunc("POST /api/instances/{i}/start", s.handleStart) m.HandleFunc("POST /api/instances/{i}/stop", s.handleStop) m.HandleFunc("POST /api/instances/{i}/install", s.handleInstall) + m.HandleFunc("POST /api/instances/{i}/disk-info", s.handleDiskInfo) + m.HandleFunc("POST /api/instances/{i}/disk-trim", s.handleDiskTrim) + m.HandleFunc("POST /api/instances/{i}/disk-compact", s.handleDiskCompact) m.HandleFunc("POST /api/instances/{i}/resume", s.handleResumeCreate) m.HandleFunc("POST /api/instances/{i}/input", s.handleInput) m.HandleFunc("GET /api/instances/{i}/screenshot", s.handleScreenshot) diff --git a/internal/ui/jobs.go b/internal/ui/jobs.go index 8cfeea5c..f1dedb2d 100644 --- a/internal/ui/jobs.go +++ b/internal/ui/jobs.go @@ -20,6 +20,10 @@ const ( kindInstall = "install" kindCreate = "create" + kindDiskInfo = "disk-info" + kindDiskTrim = "disk-trim" + kindDiskCompact = "disk-compact" + stateRunning = "running" stateDone = "done" stateFailed = "failed" @@ -40,6 +44,12 @@ func kindLabel(kind string) string { return "安装 APK" case kindCreate: return "新建" + case kindDiskInfo: + return "查看磁盘占用" + case kindDiskTrim: + return "回收磁盘空间" + case kindDiskCompact: + return "整理磁盘" } return kind } diff --git a/internal/ui/jobs_test.go b/internal/ui/jobs_test.go index a92f637c..240ec4e9 100644 --- a/internal/ui/jobs_test.go +++ b/internal/ui/jobs_test.go @@ -123,6 +123,7 @@ func TestBusyAndStopWhileStart(t *testing.T) { expectError(t, h.do("POST", "/api/instances/3/install", nil, withHeader("Content-Type", "multipart/form-data; boundary=x")), http.StatusConflict, errs.Busy) expectError(t, h.do("DELETE", "/api/instances/3?confirm=1", nil), http.StatusConflict, errs.Busy) + expectError(t, h.do("POST", "/api/instances/3/disk-trim", "{}"), http.StatusConflict, errs.Busy) // another instance is not affected expect(t, h.do("POST", "/api/instances/4/start", nil), http.StatusAccepted, nil) diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 125eb3d9..5126393f 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -3,7 +3,7 @@ // // One server manages one root. Every request must carry our own Host (127.0.0.1 or localhost with our port), so a // DNS-rebound name never reaches the API; /api/* also needs the login cookie and, unless GET, our own Origin. Long -// operations (create, start, stop, install) run as jobs and report through the event stream (/api/events). The manager +// operations (create, start, stop, install, disk-info / disk-trim / disk-compact) run as jobs and report through the event stream (/api/events). The manager // boots instances with their window only and has no restart: headless boots, and switching between the two, are not // its to do (the CLI boots headless; a running instance is never switched). // diff --git a/internal/ui/web/dev/mock.js b/internal/ui/web/dev/mock.js index 78d64575..f5861590 100644 --- a/internal/ui/web/dev/mock.js +++ b/internal/ui/web/dev/mock.js @@ -638,7 +638,7 @@ async function handle(url, init) { } return json(clone(j)); } - m = /^\/api\/instances\/(\d+)(?:\/([a-z]+))?$/.exec(p); + m = /^\/api\/instances\/(\d+)(?:\/([a-z-]+))?$/.exec(p); if (!m) return errResp('not_found', '没有这个接口:' + p); const i = Number(m[1]); const inst = db.insts.get(i); @@ -698,6 +698,37 @@ async function handle(url, init) { setTimeout(() => finishJob(j, { index: i, apk: f.name, package: 'com.example.' + f.name.replace(/\.apk$/i, '').replace(/\W+/g, '').toLowerCase(), output: 'Success' }), 3000); return json(j, 202); } + if (act === 'disk-info' || act === 'disk-trim' || act === 'disk-compact') { + if (busyJob) return errResp('busy', `实例 ${i} 正在${busyJob.kind === 'stop' ? '关机' : '做别的事'}(任务 ${busyJob.id}),等它做完再试`); + const GB = 2 ** 30; + const d = (inst._.disk ||= { logical: 64 * GB, onDisk: 12 * GB, alloc: 9.6 * GB }); + const j = newJob(act, i); + // like the real job: emu decides by the instance state, so a trim of a stopped instance (or a compact of a running one) fails in the job + if (act === 'disk-info') { + step(j, 'disk_info', `实例 ${i} 正在查看磁盘占用`, 0); + setTimeout(() => { + const running = inst.running; + finishJob(j, { index: i, overlay: `${inst.path}\\userdata-qemu.img.qcow2`, running, needs_shutdown: running, logical_bytes: d.logical, on_disk_bytes: d.onDisk, cluster_bytes: 65536, + ...(running ? {} : { allocated_bytes: Math.round(d.alloc), reclaimable_bytes: Math.max(0, Math.round(d.onDisk - d.alloc)) }) }); + }, 500); + } else if (act === 'disk-trim') { + step(j, 'disk_trim', `实例 ${i} 正在回收磁盘空间`, 0); + setTimeout(() => { + if (inst.status !== 'online') return failJob(j, 'unsupported', `魔改 AVD 实例 ${i} 没有在运行,请先开机再回收磁盘空间`, ''); + d.alloc = Math.max(3 * GB, d.alloc - 1.5 * GB); + finishJob(j, { index: i, discard_max_bytes: 2 * GB }); + }, 1800); + } else { + step(j, 'disk_compact', `实例 ${i} 正在整理磁盘(重写数据盘文件,要几分钟)`, 0); + setTimeout(() => { + if (inst.running) return failJob(j, 'busy', `魔改 AVD 实例 ${i} 未关闭,无法整理磁盘`, `先 modavd stop ${i},关机后再整理`); + const before = d.onDisk; + d.onDisk = Math.min(before, d.alloc + 0.1 * GB); + finishJob(j, { index: i, overlay: `${inst.path}\\userdata-qemu.img.qcow2`, before_on_disk_bytes: Math.round(before), after_on_disk_bytes: Math.round(d.onDisk), freed_bytes: Math.round(before - d.onDisk) }); + }, 5000); + } + return json(j, 202); + } if (act === 'input') { if (inst.status !== 'online') return errResp('busy', `魔改 AVD 实例 ${i} 没有开机`); if (body.type === 'tap') { diff --git a/internal/ui/web/js/actions.js b/internal/ui/web/js/actions.js index 7cb6f96c..19182524 100644 --- a/internal/ui/web/js/actions.js +++ b/internal/ui/web/js/actions.js @@ -3,10 +3,10 @@ import { api } from './api.js'; import { S, update, instance } from './store.js'; import { toast, toastError, copyText } from './ui.js'; -import { quoted, dur } from './format.js'; +import { quoted, dur, diskInfoText, diskTrimText, diskCompactText } from './format.js'; import { openActivity } from './panels.js'; -const VERB = { start: '开机', stop: '关机', install: '安装 APK', create: '新建' }; +const VERB = { start: '开机', stop: '关机', install: '安装 APK', create: '新建', 'disk-info': '查看磁盘占用', 'disk-trim': '回收磁盘空间', 'disk-compact': '整理磁盘' }; const isBoot = (j) => j.kind === 'start'; const activity = { label: '查看活动', run: () => openActivity() }; // wraps an API action: errors become a toast with the message and advice @@ -39,6 +39,10 @@ function notify(job) { } else if (job.kind === 'create') toast({ title: `${who}新建好了`, text: '初始化已做完,已关机;第一次开机和平常一样快。' }); else if (job.kind === 'stop') toast({ title: `${who}已关机` }); else if (job.kind === 'install') toast({ title: '安装完成', text: `${who}装好了 ${r.package || 'APK'}` }); + // the sizes are the answer, so they stay long enough to read + else if (job.kind === 'disk-info') toast({ tone: 'info', title: `${who}的磁盘占用`, text: diskInfoText(r), timeout: 9000 }); + else if (job.kind === 'disk-trim') toast({ title: `${who}已回收磁盘空间`, text: diskTrimText(), timeout: 6000 }); + else if (job.kind === 'disk-compact') toast({ title: `${who}磁盘整理好了`, text: diskCompactText(r), timeout: 6000 }); } async function run(i, kind, body) { @@ -73,6 +77,13 @@ export async function install(i, file) { if (await run(i, 'install', fd)) toast({ tone: 'info', title: '正在安装', text: `${file.name} → ${quoted(instance(i), i)}` }); } +// 磁盘占用 reads only and works on or off; 回收磁盘空间 needs the instance booted; 整理磁盘 (copies the whole data disk, minutes) needs it off +export const diskInfo = (i) => run(i, 'disk-info', {}); +export const diskTrim = (i) => run(i, 'disk-trim', {}); +export async function diskCompact(i) { + if (await run(i, 'disk-compact', {})) toast({ tone: 'info', title: '正在整理磁盘', text: `${quoted(instance(i), i)}要几分钟,期间不能开机`, timeout: 5000 }); +} + export const cancelJob = safe(async (id) => onJob(await api.post(`/api/jobs/${encodeURIComponent(id)}/cancel`))); export const openFolder = safe((what, index) => api.post('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/api/open', index == null ? { what } : { what, index })); export const input = safe((i, body) => api.post(`/api/instances/${i}/input`, body)); diff --git a/internal/ui/web/js/cards.js b/internal/ui/web/js/cards.js index 9db96009..1bd03af6 100644 --- a/internal/ui/web/js/cards.js +++ b/internal/ui/web/js/cards.js @@ -85,7 +85,7 @@ export function viewState(inst) { const PILL = { online: ['运行中', 'ok'], starting: ['开机中', 'warn'], stopping: ['关机中', 'warn'], offline: ['已关机', 'idle'], error: ['开机失败', 'err'], creating: ['新建中', 'warn'], createfail: ['新建失败', 'err'] }; -const FAIL = { start: '开机失败', stop: '关机失败', install: '安装失败', create: '新建失败' }; +const FAIL = { start: '开机失败', stop: '关机失败', install: '安装失败', create: '新建失败', 'disk-info': '查看磁盘占用失败', 'disk-trim': '回收磁盘空间失败', 'disk-compact': '整理磁盘失败' }; function skeletonFor(v) { const sk = (cls) => h('div', { class: 'sk ' + cls }); @@ -203,14 +203,15 @@ function updateCard(c, inst) { c.next = 0; c.hold = null; } - const busy = v.key === 'starting' || v.key === 'stopping' || v.key === 'creating' || v.kind === 'install'; + const busy = v.key === 'starting' || v.key === 'stopping' || v.key === 'creating' || v.kind === 'install' || v.kind === 'disk-trim' || v.kind === 'disk-compact'; c.el.classList.toggle('is-busy', busy); c.screen.classList.toggle('has-shot', live && !!c.url); c.screen.classList.toggle('busy', busy); setText(c.phText, v.key === 'error' ? '上次开机没有成功' : v.key === 'createfail' ? '新建时的初始化没做完' : live ? '正在取画面…' : '未开机'); if (busy) { const p = v.job && v.job.progress; - const msg = (p && stripInst(p.message)) || (v.key === 'stopping' ? '正在关机…' : v.key === 'creating' ? '正在新建:后台开机做初始化…' : v.kind === 'install' ? '正在安装 APK…' : '正在开机…'); + const msg = (p && stripInst(p.message)) || (v.key === 'stopping' ? '正在关机…' : v.key === 'creating' ? '正在新建:后台开机做初始化…' : v.kind === 'install' ? '正在安装 APK…' + : v.kind === 'disk-trim' ? '正在回收磁盘空间…' : v.kind === 'disk-compact' ? '正在整理磁盘…' : '正在开机…'); setText(c.progMsg, msg); setText(c.lmsg, msg); const n = cp ?? pct(p); @@ -288,6 +289,11 @@ function menuItems(c) { : { label: '强制关机', icon: 'bolt', disabled: !running || v.key === 'stopping', run: () => A.stop(i, true) }, { sep: true }, { label: '安装 APK…', icon: 'download', disabled: inst.status !== 'online' || v.kind === 'install', run: () => pickApk(i) }, + // 磁盘占用 reads only (on or off); 回收 needs the guest booted; 整理 rewrites the data disk file, so the instance must be off. + // Any job running on the instance blocks all three (the server would answer busy). + { label: '磁盘占用', icon: 'info', disabled: !!v.kind, run: () => A.diskInfo(i) }, + { label: '回收磁盘空间', icon: 'refresh', disabled: inst.status !== 'online' || !!v.kind, hint: inst.status !== 'online' ? '开机后可用' : '', run: () => A.diskTrim(i) }, + { label: '整理磁盘', icon: 'disk', disabled: inst.status !== 'offline' || !!v.kind, hint: inst.status !== 'offline' ? '关机后可用' : '', run: () => A.diskCompact(i) }, { label: '查看日志', icon: 'file', run: () => openLogs(i) }, { label: '打开目录', icon: 'folder', run: () => A.openFolder('instance', i) }, { sep: true }, diff --git a/internal/ui/web/js/dom.js b/internal/ui/web/js/dom.js index d38554e3..20c85cba 100644 --- a/internal/ui/web/js/dom.js +++ b/internal/ui/web/js/dom.js @@ -89,6 +89,7 @@ const I = { eye: '', eyeOff: '', download: '', + disk: '', file: '', sliders: '', trash: '', diff --git a/internal/ui/web/js/format.js b/internal/ui/web/js/format.js index 01ac12e8..44bf14c2 100644 --- a/internal/ui/web/js/format.js +++ b/internal/ui/web/js/format.js @@ -1,7 +1,7 @@ // Formatting for people (zh-CN). -export const KIND = { start: '开机', stop: '关机', install: '安装 APK', create: '新建' }; -export const KIND_ICON = { start: 'power', stop: 'stop', install: 'download', create: 'plus' }; +export const KIND = { start: '开机', stop: '关机', install: '安装 APK', create: '新建', 'disk-info': '磁盘占用', 'disk-trim': '回收磁盘空间', 'disk-compact': '整理磁盘' }; +export const KIND_ICON = { start: 'power', stop: 'stop', install: 'download', create: 'plus', 'disk-info': 'disk', 'disk-trim': 'disk', 'disk-compact': 'disk' }; export const STATE = { running: '进行中', done: '完成', failed: '失败', canceled: '已取消' }; export const STATE_TONE = { running: 'warn', done: 'ok', failed: 'err', canceled: 'idle' }; @@ -47,6 +47,35 @@ export function dur(sec) { return `${Math.floor(m / 60)} 小时 ${m % 60} 分`; } +export function fmtBytes(n) { + if (n == null || !(n >= 0)) return '—'; + if (n >= 2 ** 30) return (n / 2 ** 30).toFixed(1) + ' GB'; + if (n >= 2 ** 20) return Math.round(n / 2 ** 20) + ' MB'; + if (n >= 2 ** 10) return Math.round(n / 2 ** 10) + ' KB'; + return n + ' B'; +} + +// 磁盘占用 (DiskInfoResult). A running instance has the disk open: allocated and reclaimable are not known then. +export function diskInfoText(r) { + const parts = []; + if (r.logical_bytes) parts.push(`逻辑大小 ${fmtBytes(r.logical_bytes)}`); + parts.push(`宿主占用 ${fmtBytes(r.on_disk_bytes)}`); + if (r.allocated_bytes != null) parts.push(`已分配 ${fmtBytes(r.allocated_bytes)}`); + if (r.reclaimable_bytes != null) parts.push(`可回收约 ${fmtBytes(r.reclaimable_bytes)}`); + let text = parts.join(' · '); + if (r.needs_shutdown) text += '。开机时算不出已分配和可回收,关机后再看'; + else if (r.reclaimable_bytes != null) text += r.reclaimable_bytes > 0 ? '。用「整理磁盘」可以收回' :'。没有可以回收的'; + return text + '。'; +} + +export function diskTrimText() { + return '已让安卓把删掉的文件占的空间还回来;电脑上的磁盘文件要关机后用「整理磁盘」才会变小。'; +} + +export function diskCompactText(r) { + return `磁盘文件从 ${fmtBytes(r.before_on_disk_bytes)} 缩到 ${fmtBytes(r.after_on_disk_bytes)},释放 ${fmtBytes(r.freed_bytes)}。`; +} + export function uptime(started) { const t = parseTime(started); if (t == null) return ''; diff --git a/internal/ui/web/js/panels.js b/internal/ui/web/js/panels.js index 8099dbbf..c1250d80 100644 --- a/internal/ui/web/js/panels.js +++ b/internal/ui/web/js/panels.js @@ -4,7 +4,7 @@ import { h, icon, btn, keyed, showError, setText, attr } from './dom.js'; import { api } from './api.js'; import { S, update, subscribe, instance, jobsSorted, runningCount } from './store.js'; import { openDialog } from './ui.js'; -import { KIND, KIND_ICON, STATE, STATE_TONE, clock, dur, label, parseTime, pct, stripInst, stopMethod } from './format.js'; +import { KIND, KIND_ICON, STATE, STATE_TONE, clock, dur, label, parseTime, pct, stripInst, stopMethod, diskInfoText, diskTrimText, diskCompactText } from './format.js'; import * as A from './actions.js'; const advice = (text) => h('div', { class: 'advice' }, icon('bulb'), h('span', { text })); @@ -179,7 +179,7 @@ export function openActivity() { if (actCtl) return; const list = h('ul', { class: 'jobs' }); const empty = h('div', { class: 'act-empty' }, icon('pulse'), h('p', { text: '还没有任务' }), - h('p', { class: 'muted', text: '新建、开机、关机和安装 APK 都会显示在这里。' })); + h('p', { class: 'muted', text: '新建、开机、关机、安装 APK 和磁盘操作都会显示在这里。' })); const logBox = h('div', { class: 'loglines', role: 'log', 'aria-label': '最近的消息' }); const ctl = openDialog({ title: '活动', sub: ' ', cls: 'drawer', light: true, @@ -261,7 +261,8 @@ function updateJob(r, j) { if (running) { const p = j.progress; const n = pct(p); - setText(r.msg, (p && stripInst(p.message)) || (j.kind === 'stop' ? '正在关机…' : j.kind === 'install' ? '正在安装…' : '进行中…')); + setText(r.msg, (p && stripInst(p.message)) || (j.kind === 'stop' ? '正在关机…' : j.kind === 'install' ? '正在安装…' + : j.kind === 'disk-info' ? '正在查看磁盘占用…' : j.kind === 'disk-trim' ? '正在回收磁盘空间…' : j.kind === 'disk-compact' ? '正在整理磁盘…' : '进行中…')); setText(r.pctEl, n == null ? '' : Math.round(n) + '%'); r.bar.classList.toggle('indet', n == null); r.fill.style.width = n == null ? '' : n.toFixed(1) + '%'; @@ -309,6 +310,9 @@ function resultText(j) { if (!r) return ''; if (j.kind === 'stop') return `${stopMethod(r.method)}${r.seconds ? `,${dur(r.seconds)}` : ''}。`; if (j.kind === 'install') return `已装好 ${r.package || r.apk || 'APK'}${r.output ? `(${r.output.trim()})` : ''}`; + if (j.kind === 'disk-info') return diskInfoText(r); + if (j.kind === 'disk-trim') return diskTrimText(); + if (j.kind === 'disk-compact') return diskCompactText(r); if (!r.launched) return '模拟器本来就在运行,只重做了开机后的设置。'; return [`安卓开机 ${dur(r.boot_seconds || 0)},共 ${dur(r.total_seconds || 0)}`, r.first_boot && '完成了首次初始化', r.zygote_restarted && '装了 Vulkan 补丁(安卓框架重启过一次)'].filter(Boolean).join(',') + '。'; From 003629f37ddfd112d685f53568e34c05708c8e84 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Wed, 4 Nov 2026 09:40:19 +0100 Subject: [PATCH 8/9] =?UTF-8?q?emu:=20=E4=BF=AE=20compact=20=E5=AE=A1?= =?UTF-8?q?=E6=9F=A5=E7=9A=84=E5=BF=85=E6=94=B9=E9=A1=B9=EF=BC=88#2=20S3?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按 compact 复核意见改: - P1-1:convert 去掉 -T none。qcow2 源在 2.12 的 file-win32 上用 cache=none 读文件头不对齐,一律 I/O error,compact 从来跑不起来;走缓存读安全(复核 实测缓存只碰被引用的簇、不碰洞,NTFS 预留不涨)。 - P1-2:convert 前查剩余空间。按 qemu-img check 的已分配大小 ×1.05 + 2 GiB 估新文件,空间不够就拒绝并提示腾出多少;否则 convert 写满卷会把同卷上开着 的其他实例拖进 io-error。 - P2-1:只在 NTFS/ReFS 上整理(换文件在别处不是原子操作),残留临时文件不再 盲删——打不开就删、能打开且和当前盘一致就删、对不上就停下两个都留,删时记 日志。新增 win.VolumeFileSystem。 - P3-8:disk info 读盘前 TryLock start 锁,拿不到(正在开机)就只报文件头的数, 不和开机抢覆盖层。 - P3-3:临时文件改名 userdata-qemu.cmp,不比覆盖层长,避免长路径建不了文件。 - P3-7:compare 退出码 1 才是内容不一致,≥2 当出错;backing 格式读不到改成 Unsupported,和「没有 backing」一致。 加真 qemu-img 集成测试(设 MODAVD_TEST_SDK_ROOT 才跑,CI 无 SDK 跳过),覆盖 compact 在真实 qcow2 覆盖层上 convert→check→compare→替换走通、内容不变、幂等。 其余 P3(P3-1/2/4/5/6/9/10)待挂 issue。 Refs ModAVD/ModAVD#2 --- README.md | 2 +- internal/emu/disk.go | 202 +++++++++++++++++++++++--- internal/emu/disk_integration_test.go | 159 ++++++++++++++++++++ internal/win/host.go | 25 ++++ internal/win/other.go | 3 + internal/win/win.go | 2 + 6 files changed, 373 insertions(+), 20 deletions(-) create mode 100644 internal/emu/disk_integration_test.go diff --git a/README.md b/README.md index 10e5e571..abe23764 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] | `bridge install\|uninstall\|verify` | 装、卸、检查 arm64 执行桥;开机时会自动装,一般不用手动跑(见下) | | `disk trim` | 磁盘回收:在开着的实例里对数据盘触发一次 FITRIM,让模拟器释放已删文件占着的空间;模拟器太旧、不支持回收时返回不支持(退出码 4) | | `disk info` | 看数据盘的大小:逻辑大小、覆盖层在宿主上实际占的空间;实例关机时再给已分配的大小和估计能回收多少(开着时这两个数要关机后才有);只读 | -| `disk compact` | 整理数据盘:关机状态下把覆盖层重写一遍、丢掉已释放的簇、把文件缩小;转换后先校验再原子替换,原盘在替换成功前不动;实例有快照时拒绝 | +| `disk compact` | 整理数据盘:关机状态下把覆盖层重写一遍、丢掉已释放的簇、把文件缩小;转换后先校验再原子替换,原盘在替换成功前不动;仅在 NTFS/ReFS 卷上进行,实例有快照、或剩余空间不够放下新文件时拒绝 | | `check [--memory M]` | 开机前的电脑检查 | | `report-config [--no-clipboard]` | 复制电脑配置和开着实例里的游戏信息(只读) | | `collect-info [--out-dir D] [--stage-dir D] [--keep-stage] [--no-explorer]` | 收集问题信息并打包(只读) | diff --git a/internal/emu/disk.go b/internal/emu/disk.go index 80d12716..3fc1bcaa 100644 --- a/internal/emu/disk.go +++ b/internal/emu/disk.go @@ -311,6 +311,26 @@ func (m *Manager) DiskInfo(ctx context.Context, i int) (*DiskInfoResult, error) return res, nil } + // Not seen running, but a start may be launching qemu right now (it holds the start lock for the whole start, + // before qemuOf can see the process). Take that lock so qemu-img does not read the overlay while a launch opens + // it; if a start holds it, report the header-only numbers rather than fail or stall a boot (ModAVD/ModAVD#2 P3-8). + startLock, ok, err := win.TryLock(m.lockPath(i, "start")) + if err != nil { + return nil, errs.Wrap(errs.Internal, err, "实例锁文件打不开: "+m.lockPath(i, "start")) + } + if !ok { + res.NeedsShutdown = true + res.Warnings = append(res.Warnings, "实例正在启动:已分配和可回收的大小要关机后才能算") + return res, nil + } + defer startLock.Unlock() + // With the lock held, re-check: a start that finished between the first scan and the lock leaves qemu running. + if _, running := m.qemuOf(i); running { + res.Running, res.NeedsShutdown = true, true + res.Warnings = append(res.Warnings, "实例在运行:已分配和可回收的大小要关机后才能算") + return res, nil + } + out, failure, err := m.runQemuImgCheck(ctx, overlay) if err != nil { return nil, err @@ -346,11 +366,35 @@ const ( diskConvertTimeout = 30 * time.Minute // diskCompareTimeout bounds `qemu-img compare` of the before/after images. diskCompareTimeout = 20 * time.Minute + // compactSpaceSlack is the headroom required on the volume beyond the estimated new overlay (allocated x 1.05), + // so a convert cannot fill the volume and stall other instances sharing it (ModAVD/ModAVD#2 P1-2). + compactSpaceSlack = 2 << 30 // 2 GiB ) -// userdataCompactTmp is the scratch file compact converts into before swapping it -// over the overlay; a stray one from an interrupted run is removed on the next run. -const userdataCompactTmp = userdataOverlay + ".compact.tmp" +// userdataCompactTmp is the scratch file compact converts into before swapping it over the overlay. Its name is no +// longer than the overlay's, so the temp path can never overflow MAX_PATH where the overlay path itself fits +// (ModAVD/ModAVD#2 P3-3). A stray one from an interrupted run is validated and cleared on the next run +// (clearStrayCompactTmp), never deleted unseen. +const userdataCompactTmp = "userdata-qemu.cmp" + +// compactFileSystems are the journaled file systems compact runs on: a write-through replace is one transaction +// there, so the final swap is atomic and a crash never leaves the overlay missing with only the temp file behind. +var compactFileSystems = map[string]bool{"NTFS": true, "REFS": true} + +// requireCompactFS refuses to compact on a file system where the final rename is not atomic (exFAT, FAT32): a crash +// mid-rename could leave only the temp file, and the emulator would then build an empty overlay over the backing, +// so a later run would delete the one good copy (ModAVD/ModAVD#2 P2-1). +func requireCompactFS(overlay string) error { + fs, err := win.VolumeFileSystem(overlay) + if err != nil { + return err + } + if !compactFileSystems[strings.ToUpper(fs)] { + return errs.Newf(errs.Unsupported, "数据盘所在卷是 %s,只能在 NTFS 或 ReFS 卷上整理磁盘", fs). + WithAdvice("在这种文件系统上换文件不是原子操作,中途断电可能丢数据;请把实例放到 NTFS 卷上再整理") + } + return nil +} // DiskCompactResult reports `modavd disk compact`. type DiskCompactResult struct { @@ -475,19 +519,36 @@ func (m *Manager) verifyCompacted(ctx context.Context, orig, tmp string) error { return errs.Newf(errs.Internal, "整理后的数据盘有 %d 处检查错误、%d 处损坏,放弃替换,原盘未动", chk.CheckErrors, chk.Corruptions) } - // compare the effective content (overlay + backing); exit 0 means identical. - so, se, code, err := m.runQemuImg(ctx, diskCompareTimeout, "compare", orig, tmp) + // compare the effective content (overlay + backing); equal means the swap is safe. + equal, err := m.compareEqual(ctx, orig, tmp) if err != nil { return err } - if code != 0 { - return errs.Newf(errs.Internal, - "整理前后的数据盘内容对不上(qemu-img compare 退出码 %d):%s,放弃替换,原盘未动", - code, qemuImgFail(so, se)) + if !equal { + return errs.New(errs.Internal, "整理前后的数据盘内容对不上,放弃替换,原盘未动") } return nil } +// compareEqual runs `qemu-img compare a b` and reports whether they hold identical guest-visible content (whole +// backing chain, both sides). compare exits 0 when identical and 1 when they differ; any other exit (>=2, or a +// killed process) is a real failure, returned as err so a mismatch is never mistaken for a compare that could not +// run (ModAVD/ModAVD#2 P3-7). +func (m *Manager) compareEqual(ctx context.Context, a, b string) (bool, error) { + so, se, code, err := m.runQemuImg(ctx, diskCompareTimeout, "compare", a, b) + if err != nil { + return false, err + } + switch code { + case 0: + return true, nil + case 1: + return false, nil + default: + return false, errs.Newf(errs.Internal, "qemu-img compare 没跑完(退出码 %d): %s", code, qemuImgFail(so, se)) + } +} + // syncFile flushes the file's pending writes to disk (FlushFileBuffers on Windows). func syncFile(path string) error { f, err := os.OpenFile(path, os.O_RDWR, 0) @@ -507,15 +568,87 @@ func dirHasEntries(path string) bool { return err == nil && len(es) > 0 } +// probeCompactAllocated runs `qemu-img check` on the overlay and returns the bytes its live clusters hold +// (allocated clusters x cluster size), used to size the volume headroom compact needs (ModAVD/ModAVD#2 P1-2). It +// refuses a disk whose check reports errors or corruption: the size would be unreliable and compacting a damaged +// image is unsafe. The overlay must not be open in a running qemu (compact holds the locks that guarantee that). +func (m *Manager) probeCompactAllocated(ctx context.Context, overlay string, clusterBytes int64) (int64, error) { + out, failure, err := m.runQemuImgCheck(ctx, overlay) + if err != nil { + return 0, err + } + if failure != "" { + return 0, errs.Newf(errs.Internal, "整理前检查数据盘没通过:%s,没有整理", failure) + } + chk, err := parseQemuImgCheck(out) + if err != nil { + return 0, err + } + if chk.CheckErrors > 0 || chk.Corruptions > 0 { + return 0, errs.Newf(errs.Unsupported, + "数据盘镜像有 %d 处检查错误、%d 处损坏,先修复再整理", chk.CheckErrors, chk.Corruptions). + WithAdvice("可以先用 modavd disk info 看一下,修复镜像后再整理") + } + return *chk.AllocatedClusters * clusterBytes, nil +} + +// clearStrayCompactTmp deals with a temp file left by an interrupted earlier compact, before a new run reuses the +// path. On the journaled file systems compact runs on the overlay is always the intact disk when a temp is present +// (the swap is atomic), so the temp is at most a half-written or stale copy; it is still never deleted unseen +// (ModAVD/ModAVD#2 P2-1): a temp that will not open as qcow2 is dropped, one that opens and matches the current +// overlay is dropped, and one that opens but differs stops the run with both files kept for the user to resolve. +func (m *Manager) clearStrayCompactTmp(ctx context.Context, overlay, tmp string) error { + if _, err := os.Stat(tmp); err != nil { + if os.IsNotExist(err) { + return nil + } + return errs.Wrap(errs.Internal, err, "查看整理临时文件失败: "+err.Error()) + } + m.Log.Infof("发现上次整理遗留的临时文件 %s,先检查再决定去留", tmp) + out, failure, err := m.runQemuImgCheck(ctx, tmp) + if err != nil { + return err + } + if failure != "" { + m.Log.Infof("整理临时文件打不开(上次转换没写完),删除:%s", tmp) + return removeCompactTmp(tmp) + } + if chk, perr := parseQemuImgCheck(out); perr != nil || chk.CheckErrors > 0 || chk.Corruptions > 0 { + m.Log.Infof("整理临时文件检查没通过,删除:%s", tmp) + return removeCompactTmp(tmp) + } + equal, err := m.compareEqual(ctx, overlay, tmp) + if err != nil { + return err + } + if equal { + m.Log.Infof("整理临时文件和当前数据盘内容一致,删除:%s", tmp) + return removeCompactTmp(tmp) + } + return errs.New(errs.Internal, "发现上次整理遗留的临时文件,和当前数据盘内容不一致,为安全起见没有删除任何文件"). + WithAdvice(fmt.Sprintf("请确认数据盘 %s 能正常开机后,手动删除 %s 再重试整理", overlay, tmp)) +} + +// removeCompactTmp deletes a compact temp file; a missing file is not an error. +func removeCompactTmp(tmp string) error { + if err := os.Remove(tmp); err != nil && !os.IsNotExist(err) { + return errs.Wrap(errs.Internal, err, "删除整理临时文件失败: "+err.Error()) + } + return nil +} + // DiskCompact offline-compacts instance i's data disk: it converts the overlay to a // fresh qcow2 that keeps only the clusters still in use (same backing), checks and // compares the copy, then atomically swaps it in with a write-through replace. The // instance must be powered off; compact holds its start/stop/bridge/create locks so -// nothing boots it mid-rewrite. It refuses when the data disk or the instance has -// snapshots (the convert would drop them). The original is untouched until the final -// replace, so a crash at any earlier point leaves a working instance (a stray -// .compact.tmp is removed on the next run). errs.Busy when the instance is running or -// a lock is held; errs.Unsupported for snapshots or a missing backing. +// nothing boots it mid-rewrite. It runs only on NTFS/ReFS (where the swap is atomic), +// refuses when the data disk or the instance has snapshots (the convert would drop +// them), and refuses when the volume lacks room for the copy (so a convert cannot fill +// it and stall other instances). The original is untouched until the final replace, so +// a crash at any earlier point leaves a working instance (a stray temp from an +// interrupted run is validated and cleared on the next run, never deleted unseen). +// errs.Busy when the instance is running or a lock is held; errs.Unsupported for a +// non-journaled volume, snapshots, a missing backing or too little free space. func (m *Manager) DiskCompact(ctx context.Context, i int) (*DiskCompactResult, error) { if err := requireWindows(); err != nil { return nil, err @@ -529,6 +662,9 @@ func (m *Manager) DiskCompact(ctx context.Context, i int) (*DiskCompactResult, e return nil, errs.Newf(errs.NotFound, "实例 %d 没有数据盘覆盖层: %s", i, overlay). WithAdvice("实例还没开过机,或数据盘不是这种格式") } + if err := requireCompactFS(overlay); err != nil { + return nil, err + } unlock, err := m.lockInstanceForCompact(i) if err != nil { return nil, err @@ -558,7 +694,7 @@ func (m *Manager) DiskCompact(ctx context.Context, i int) (*DiskCompactResult, e return nil, errs.New(errs.Unsupported, "数据盘没有 backing,不整理(避免把整盘复制进来)") } if info.BackingFilenameFmt == "" { - return nil, errs.New(errs.Internal, "读不到数据盘 backing 的格式,不整理") + return nil, errs.New(errs.Unsupported, "读不到数据盘 backing 的格式,不整理") } backingName := filepath.Base(info.BackingFilename) @@ -567,12 +703,40 @@ func (m *Manager) DiskCompact(ctx context.Context, i int) (*DiskCompactResult, e return nil, err } + // Clear a temp left by an interrupted earlier run first, so the space it would free counts toward the room check + // below (it may be as large as the whole copy); it is validated, not deleted unseen (ModAVD/ModAVD#2 P2-1). tmp := filepath.Join(in.Dir, userdataCompactTmp) - _ = os.Remove(tmp) // clear a stray temp from an interrupted run + if err := m.clearStrayCompactTmp(ctx, overlay, tmp); err != nil { + return nil, err + } + + // Size the rewrite and refuse if the volume cannot hold the copy: a convert that fills the volume would stall + // other instances sharing it in io-error (ModAVD/ModAVD#2 P1-2). The new overlay is about the live-cluster size + // plus a little metadata; keep headroom beyond that. + hdr, err := readQcow2Header(overlay) + if err != nil { + return nil, err + } + allocated, err := m.probeCompactAllocated(ctx, overlay, hdr.ClusterSize) + if err != nil { + return nil, err + } + free, err := win.DiskFree(in.Dir) + if err != nil { + return nil, err + } + need := allocated + allocated/20 + compactSpaceSlack // ~ allocated x 1.05 + 2 GiB + if free < uint64(need) { + return nil, errs.Newf(errs.Unsupported, + "整理磁盘大约需要 %s 可用空间,%s 所在磁盘只剩 %s,请先腾出约 %s 再整理", + gib(need), in.Dir, gib(int64(free)), gib(need-int64(free))). + WithAdvice("整理会先写一份新的数据盘,空间不够会写满磁盘、拖累同一个磁盘上开着的其他实例") + } - // convert: a fresh overlay holding only the live clusters, same backing. -B skips - // the backing's data; -T none keeps the host cache out of a tens-of-GB copy. - so, se, code, err := m.runQemuImg(ctx, diskConvertTimeout, "convert", "-T", "none", + // convert: a fresh overlay holding only the live clusters, same backing. -B skips the backing's data. The source + // is read through the host cache: a qcow2 source with cache=none (-T none) fails on 2.12's file-win32 because the + // header read is not sector-aligned, and the cache only touches referenced clusters, not the holes (#2 P1-1). + so, se, code, err := m.runQemuImg(ctx, diskConvertTimeout, "convert", "-O", "qcow2", "-B", backingName, "-o", "backing_fmt="+info.BackingFilenameFmt, overlay, tmp) if err != nil { _ = os.Remove(tmp) diff --git a/internal/emu/disk_integration_test.go b/internal/emu/disk_integration_test.go new file mode 100644 index 00000000..0c1f151c --- /dev/null +++ b/internal/emu/disk_integration_test.go @@ -0,0 +1,159 @@ +//go:build windows + +package emu + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + + "modavd/internal/root" + "modavd/internal/win" +) + +// TestDiskCompactIntegration runs compact end to end against a real qemu-img -- the path the fake-manager unit tests +// cannot reach, and the one the `-T none` bug failed on for every real qcow2 overlay (ModAVD/ModAVD#2 P1-1). It is +// skipped unless MODAVD_TEST_SDK_ROOT points at an SDK whose emulator\qemu-img.exe exists, so CI without an SDK just +// skips it. Run it with, e.g., MODAVD_TEST_SDK_ROOT=E:\aosp\sdk-mas37. +func TestDiskCompactIntegration(t *testing.T) { + sdk := os.Getenv("MODAVD_TEST_SDK_ROOT") + if sdk == "" { + t.Skip("set MODAVD_TEST_SDK_ROOT to an SDK with emulator\\qemu-img.exe to run the compact integration test") + } + qemuImg := filepath.Join(sdk, "emulator", "qemu-img.exe") + if fi, err := os.Stat(qemuImg); err != nil || fi.IsDir() { + t.Skipf("no qemu-img at %s: %v", qemuImg, err) + } + + // A temp root whose SDK is the real one, with one powered-off instance. + dir := opsTestTempDir(t) + meta := `{"adbServerPort":20391,"scriptAdbServerPort":20392,"sdkRoot":` + strconv.Quote(sdk) + `}` + if err := os.WriteFile(filepath.Join(dir, root.MetadataFile), []byte(meta), 0o644); err != nil { + t.Fatal(err) + } + r, err := root.New(dir) + if err != nil { + t.Fatal(err) + } + const i = 2 + avdDir := filepath.Join(r.AvdHome(), root.AvdName(i)+".avd") + if err := os.MkdirAll(avdDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(r.AvdHome(), root.AvdName(i)+".ini"), []byte("path="+avdDir+"\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(avdDir, "config.ini"), []byte("hw.cpu.ncore=4\n"), 0o644); err != nil { + t.Fatal(err) + } + if fs, _ := win.VolumeFileSystem(avdDir); !compactFileSystems[strings.ToUpper(fs)] { + t.Skipf("compact runs only on NTFS/ReFS; %s is on %s", avdDir, fs) + } + if free, _ := win.DiskFree(avdDir); free < 3<<30 { + t.Skipf("need >3 GiB free on the volume of %s for the compact integration test", avdDir) + } + + // Build a real backing + overlay: the backing is empty, the overlay holds a pattern (clusters that differ from + // the backing), so compact has a genuine qcow2 to convert, check, compare and swap. + backing := filepath.Join(avdDir, userdataBacking) + overlay := filepath.Join(avdDir, userdataOverlay) + src := filepath.Join(dir, "src.raw") + writePattern(t, src, 64<<20) + qemu := func(args ...string) { + t.Helper() + cmd := exec.Command(qemuImg, args...) + cmd.Dir = avdDir // so the relative -B backing name resolves next to the output + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("qemu-img %v: %v\n%s", args, err, out) + } + } + qemu("create", "-f", "qcow2", userdataBacking, "64M") + qemu("convert", "-O", "qcow2", "-B", userdataBacking, "-o", "backing_fmt=qcow2", src, userdataOverlay) + + // Keep a pristine copy (overlay + its backing) to confirm the guest-visible content survives the rewrite. + pristineDir := filepath.Join(dir, "pristine") + if err := os.MkdirAll(pristineDir, 0o755); err != nil { + t.Fatal(err) + } + pristineOverlay := filepath.Join(pristineDir, userdataOverlay) + copyFile(t, overlay, pristineOverlay) + copyFile(t, backing, filepath.Join(pristineDir, userdataBacking)) + + // The instance is powered off for the whole test. + saved := qemuScan + qemuScan = func([]int) map[int]win.Process { return map[int]win.Process{} } + t.Cleanup(func() { qemuScan = saved }) + + m := New(r, nil) + ctx := context.Background() + + // info first: with a real qemu-img it computes the allocated/reclaimable figures. + ires, err := m.DiskInfo(ctx, i) + if err != nil { + t.Fatalf("DiskInfo: %v", err) + } + if ires.AllocatedBytes == nil { + t.Fatalf("DiskInfo did not compute allocated for a stopped instance: %+v", ires) + } + + // compact: the whole convert -> check -> compare -> swap pipeline must succeed on a real qcow2 overlay. + res, err := m.DiskCompact(ctx, i) + if err != nil { + t.Fatalf("DiskCompact: %v", err) + } + if res.Overlay != overlay { + t.Errorf("result overlay = %q, want %q", res.Overlay, overlay) + } + if res.FreedBytes < 0 { + t.Errorf("freed bytes negative: %d", res.FreedBytes) + } + if _, err := os.Stat(filepath.Join(avdDir, userdataCompactTmp)); !os.IsNotExist(err) { + t.Errorf("temp file left behind after a successful compact: %v", err) + } + + // The swapped-in overlay is a sound qcow2 ... + if out, failure, err := m.runQemuImgCheck(ctx, overlay); err != nil || failure != "" { + t.Fatalf("qemu-img check after compact: failure=%q err=%v\n%s", failure, err, out) + } + // ... and holds exactly the content it had before the rewrite. + equal, err := m.compareEqual(ctx, pristineOverlay, overlay) + if err != nil { + t.Fatalf("compare after compact: %v", err) + } + if !equal { + t.Fatal("content changed across compact") + } + + // A second compact on the already-compact overlay still succeeds (idempotent, nothing corrupted). + if _, err := m.DiskCompact(ctx, i); err != nil { + t.Fatalf("second DiskCompact: %v", err) + } +} + +// writePattern writes n bytes of a deterministic non-zero pattern, so a convert onto an empty backing allocates +// clusters for all of it. +func writePattern(t *testing.T, path string, n int) { + t.Helper() + buf := make([]byte, n) + for k := range buf { + buf[k] = byte(k*31 + 7) + } + if err := os.WriteFile(path, buf, 0o644); err != nil { + t.Fatal(err) + } +} + +func copyFile(t *testing.T, src, dst string) { + t.Helper() + b, err := os.ReadFile(src) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(dst, b, 0o644); err != nil { + t.Fatal(err) + } +} diff --git a/internal/win/host.go b/internal/win/host.go index f5dfdd95..f4a2a4a0 100644 --- a/internal/win/host.go +++ b/internal/win/host.go @@ -178,6 +178,31 @@ func DiskFree(path string) (uint64, error) { return free, nil } +// VolumeFileSystem is the file-system name of the volume that holds path ("NTFS", "ReFS", "exFAT", "FAT32", ...), +// via GetVolumePathNameW (path -> the volume's mount point) then GetVolumeInformationW. Compact uses it to run only +// on journaled file systems, where a write-through replace is a single transaction and the swap is atomic. +func VolumeFileSystem(path string) (string, error) { + abs, err := filepath.Abs(path) + if err != nil { + return "", errs.Wrap(errs.Internal, err, fmt.Sprintf("路径 %s 不可用: %v", path, err)) + } + p, err := syscall.UTF16PtrFromString(abs) + if err != nil { + return "", errs.Wrap(errs.Internal, err, fmt.Sprintf("路径 %s 不可用: %v", path, err)) + } + mount := make([]uint16, syscall.MAX_PATH+1) + if r, e := call(procGetVolumePathNameW, uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(&mount[0])), + uintptr(len(mount))); r == 0 { + return "", errs.Wrap(errs.Internal, e, fmt.Sprintf("找不到 %s 所在的卷: %v", path, e)) + } + fsName := make([]uint16, 64) + if r, e := call(procGetVolumeInformationW, uintptr(unsafe.Pointer(&mount[0])), 0, 0, 0, 0, 0, + uintptr(unsafe.Pointer(&fsName[0])), uintptr(len(fsName))); r == 0 { + return "", errs.Wrap(errs.Internal, e, fmt.Sprintf("读不到 %s 所在卷的文件系统: %v", path, e)) + } + return syscall.UTF16ToString(fsName), nil +} + // GetCompressedFileSize is the bytes the file at path really occupies on the volume (GetCompressedFileSizeW): for a // sparse or NTFS-compressed file that is less than its length. For a plain file it is the length rounded up to the // cluster. diff --git a/internal/win/other.go b/internal/win/other.go index f3c51c52..d093008f 100644 --- a/internal/win/other.go +++ b/internal/win/other.go @@ -138,6 +138,9 @@ func DiskFree(string) (uint64, error) { return 0, errUnsupported } // GetCompressedFileSize calls GetCompressedFileSizeW for the Windows file. func GetCompressedFileSize(string) (uint64, error) { return 0, errUnsupported } +// VolumeFileSystem calls GetVolumePathNameW + GetVolumeInformationW on Windows. +func VolumeFileSystem(string) (string, error) { return "", errUnsupported } + // MoveFileReplaceThrough calls MoveFileExW (REPLACE_EXISTING | WRITE_THROUGH). func MoveFileReplaceThrough(string, string) error { return errUnsupported } diff --git a/internal/win/win.go b/internal/win/win.go index bd706f5e..99ca1574 100644 --- a/internal/win/win.go +++ b/internal/win/win.go @@ -71,6 +71,8 @@ var ( procGetProcessAffinityMask = modkernel32.NewProc("GetProcessAffinityMask") procOpenFileMappingW = modkernel32.NewProc("OpenFileMappingW") procGetDiskFreeSpaceExW = modkernel32.NewProc("GetDiskFreeSpaceExW") + procGetVolumePathNameW = modkernel32.NewProc("GetVolumePathNameW") + procGetVolumeInformationW = modkernel32.NewProc("GetVolumeInformationW") procGetCompressedFileSizeW = modkernel32.NewProc("GetCompressedFileSizeW") procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx") procLockFileEx = modkernel32.NewProc("LockFileEx") From bfc4a4dc30d8efdb90da93b5b4968e9019d5dd8f Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Wed, 4 Nov 2026 09:54:43 +0100 Subject: [PATCH 9/9] =?UTF-8?q?emu:=20compact=20=E5=A4=8D=E6=A0=B8?= =?UTF-8?q?=E4=BA=8C=E8=BD=AE=EF=BC=88R-1/R-2/R-3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - R-1:残留临时文件直接删 + 记日志,去掉 check/compare。只在 NTFS/ReFS 整理、替换是原子的,临时文件还在就说明没换成、原盘完整,临时文件不可能是 唯一的好盘;原来「对不上就停、让用户手删」反而让人去删一个和数据盘很像的 文件,有删错风险。 - R-2:clearStrayCompactTmp 用 os.Lstat,临时文件名上是悬空符号链接时也能看到、 删掉链接本身,不让 convert 顺着它写到实例目录外。 - R-3:parseQemuImgCheck 把缺失的 allocated-clusters 当 0(qemu-img 对空镜像 不输出该字段),不再当出错——否则全空的覆盖层上 compact / info 会报 Internal。 单测跟着改。 集成测试加一例:残留临时文件存在时 compact 照常跑通、临时文件被清掉。 build/vet/gofmt/test、真 qemu-img 集成测试、linux/darwin 交叉编译全过。 Refs ModAVD/ModAVD#2 --- internal/emu/disk.go | 59 ++++++++++----------------- internal/emu/disk_integration_test.go | 11 ++++- internal/emu/disk_test.go | 14 ++++--- 3 files changed, 40 insertions(+), 44 deletions(-) diff --git a/internal/emu/disk.go b/internal/emu/disk.go index 3fc1bcaa..6cafa71f 100644 --- a/internal/emu/disk.go +++ b/internal/emu/disk.go @@ -202,8 +202,13 @@ func parseQemuImgCheck(out []byte) (qemuImgCheck, error) { if err := json.NewDecoder(bytes.NewReader(out[start:])).Decode(&c); err != nil { return c, errs.Wrap(errs.Internal, err, "读不懂 qemu-img check 的输出: "+err.Error()) } - if c.AllocatedClusters == nil || *c.AllocatedClusters < 0 { - return c, errs.New(errs.Internal, "qemu-img check 的输出里没有 allocated-clusters") + // qemu-img omits allocated-clusters when it is 0 (an empty image); a clean decode with it missing means 0, not an + // error (ModAVD/ModAVD#2 R-3). Callers gate on check-errors/corruptions before they use the count. + if c.AllocatedClusters == nil { + zero := int64(0) + c.AllocatedClusters = &zero + } else if *c.AllocatedClusters < 0 { + return c, errs.New(errs.Internal, "qemu-img check 的 allocated-clusters 不合理") } return c, nil } @@ -373,8 +378,8 @@ const ( // userdataCompactTmp is the scratch file compact converts into before swapping it over the overlay. Its name is no // longer than the overlay's, so the temp path can never overflow MAX_PATH where the overlay path itself fits -// (ModAVD/ModAVD#2 P3-3). A stray one from an interrupted run is validated and cleared on the next run -// (clearStrayCompactTmp), never deleted unseen. +// (ModAVD/ModAVD#2 P3-3). A stray one from an interrupted run is removed on the next run (clearStrayCompactTmp); on +// NTFS/ReFS the original overlay is intact whenever a temp is present, so the temp is never the only copy. const userdataCompactTmp = "userdata-qemu.cmp" // compactFileSystems are the journaled file systems compact runs on: a write-through replace is one transaction @@ -592,41 +597,20 @@ func (m *Manager) probeCompactAllocated(ctx context.Context, overlay string, clu return *chk.AllocatedClusters * clusterBytes, nil } -// clearStrayCompactTmp deals with a temp file left by an interrupted earlier compact, before a new run reuses the -// path. On the journaled file systems compact runs on the overlay is always the intact disk when a temp is present -// (the swap is atomic), so the temp is at most a half-written or stale copy; it is still never deleted unseen -// (ModAVD/ModAVD#2 P2-1): a temp that will not open as qcow2 is dropped, one that opens and matches the current -// overlay is dropped, and one that opens but differs stops the run with both files kept for the user to resolve. -func (m *Manager) clearStrayCompactTmp(ctx context.Context, overlay, tmp string) error { - if _, err := os.Stat(tmp); err != nil { +// clearStrayCompactTmp removes a temp file left by an interrupted earlier compact, before a new run reuses the path. +// Compact runs only on NTFS/ReFS, where the final swap is one atomic transaction, so whenever a temp is present the +// overlay is still the intact original (the swap never completed): the temp is at most a half-written or stale copy +// and is always safe to drop (ModAVD/ModAVD#2 P2-1, R-1). os.Lstat (not Stat) so a symlink at the name -- even a +// dangling one -- is seen and its link entry removed here, never followed by the convert below (R-2). +func (m *Manager) clearStrayCompactTmp(tmp string) error { + if _, err := os.Lstat(tmp); err != nil { if os.IsNotExist(err) { return nil } return errs.Wrap(errs.Internal, err, "查看整理临时文件失败: "+err.Error()) } - m.Log.Infof("发现上次整理遗留的临时文件 %s,先检查再决定去留", tmp) - out, failure, err := m.runQemuImgCheck(ctx, tmp) - if err != nil { - return err - } - if failure != "" { - m.Log.Infof("整理临时文件打不开(上次转换没写完),删除:%s", tmp) - return removeCompactTmp(tmp) - } - if chk, perr := parseQemuImgCheck(out); perr != nil || chk.CheckErrors > 0 || chk.Corruptions > 0 { - m.Log.Infof("整理临时文件检查没通过,删除:%s", tmp) - return removeCompactTmp(tmp) - } - equal, err := m.compareEqual(ctx, overlay, tmp) - if err != nil { - return err - } - if equal { - m.Log.Infof("整理临时文件和当前数据盘内容一致,删除:%s", tmp) - return removeCompactTmp(tmp) - } - return errs.New(errs.Internal, "发现上次整理遗留的临时文件,和当前数据盘内容不一致,为安全起见没有删除任何文件"). - WithAdvice(fmt.Sprintf("请确认数据盘 %s 能正常开机后,手动删除 %s 再重试整理", overlay, tmp)) + m.Log.Infof("删除上次整理遗留的临时文件(数据盘是完整的原盘,未受影响):%s", tmp) + return removeCompactTmp(tmp) } // removeCompactTmp deletes a compact temp file; a missing file is not an error. @@ -646,7 +630,7 @@ func removeCompactTmp(tmp string) error { // them), and refuses when the volume lacks room for the copy (so a convert cannot fill // it and stall other instances). The original is untouched until the final replace, so // a crash at any earlier point leaves a working instance (a stray temp from an -// interrupted run is validated and cleared on the next run, never deleted unseen). +// interrupted run is removed on the next run; the original is intact on NTFS/ReFS). // errs.Busy when the instance is running or a lock is held; errs.Unsupported for a // non-journaled volume, snapshots, a missing backing or too little free space. func (m *Manager) DiskCompact(ctx context.Context, i int) (*DiskCompactResult, error) { @@ -704,9 +688,10 @@ func (m *Manager) DiskCompact(ctx context.Context, i int) (*DiskCompactResult, e } // Clear a temp left by an interrupted earlier run first, so the space it would free counts toward the room check - // below (it may be as large as the whole copy); it is validated, not deleted unseen (ModAVD/ModAVD#2 P2-1). + // below (it may be as large as the whole copy). On NTFS/ReFS the original is intact whenever a temp is present, + // so the temp is never the only copy (ModAVD/ModAVD#2 P2-1). tmp := filepath.Join(in.Dir, userdataCompactTmp) - if err := m.clearStrayCompactTmp(ctx, overlay, tmp); err != nil { + if err := m.clearStrayCompactTmp(tmp); err != nil { return nil, err } diff --git a/internal/emu/disk_integration_test.go b/internal/emu/disk_integration_test.go index 0c1f151c..e05887f2 100644 --- a/internal/emu/disk_integration_test.go +++ b/internal/emu/disk_integration_test.go @@ -128,9 +128,16 @@ func TestDiskCompactIntegration(t *testing.T) { t.Fatal("content changed across compact") } - // A second compact on the already-compact overlay still succeeds (idempotent, nothing corrupted). + // A stray temp from an interrupted run is removed and compact still runs (ModAVD/ModAVD#2 P2-1, R-1). + strayTmp := filepath.Join(avdDir, userdataCompactTmp) + if err := os.WriteFile(strayTmp, []byte("half-written junk"), 0o644); err != nil { + t.Fatal(err) + } if _, err := m.DiskCompact(ctx, i); err != nil { - t.Fatalf("second DiskCompact: %v", err) + t.Fatalf("DiskCompact with a stray temp present: %v", err) + } + if _, err := os.Stat(strayTmp); !os.IsNotExist(err) { + t.Errorf("stray temp not cleared: %v", err) } } diff --git a/internal/emu/disk_test.go b/internal/emu/disk_test.go index 9f4df597..15503fc8 100644 --- a/internal/emu/disk_test.go +++ b/internal/emu/disk_test.go @@ -74,12 +74,16 @@ func TestParseQemuImgCheck(t *testing.T) { if err != nil || *c.AllocatedClusters != 5 || c.CheckErrors != 2 || c.Corruptions != 2 || c.ImageEndOffset != nil { t.Errorf("corrupt = %+v, %v", c, err) } + // qemu-img omits allocated-clusters for an empty image: a clean decode without it means 0, not an error (R-3). + c, err = parseQemuImgCheck([]byte(`{"check-errors": 0, "total-clusters": 131072}`)) + if err != nil || c.AllocatedClusters == nil || *c.AllocatedClusters != 0 { + t.Errorf("no clusters = %+v, %v", c, err) + } for name, in := range map[string]string{ - "empty": "", - "no json": "qemu-img: Could not open", - "truncated": `{"allocated-clusters": `, - "no clusters": `{"check-errors": 0}`, - "negative": `{"allocated-clusters": -1}`, + "empty": "", + "no json": "qemu-img: Could not open", + "truncated": `{"allocated-clusters": `, + "negative": `{"allocated-clusters": -1}`, } { if _, err := parseQemuImgCheck([]byte(in)); err == nil { t.Errorf("%s: no error", name)