From 0383994728b666493a6f763862acaf654d0ab396 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 21 Nov 2026 17:48:07 +0100 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20=E5=A4=8D=E5=88=B6=E5=AE=9E?= =?UTF-8?q?=E4=BE=8B=EF=BC=88modavd=20clone=E3=80=81=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E5=99=A8=E3=80=8C=E5=A4=8D=E5=88=B6=E5=AE=9E=E4=BE=8B=E3=80=8D?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 把一台已关机的实例整份复制成新实例,带着游戏、登录状态和设置:新编号和端口, 其余配置和 mas-avd.json 里的记录照源实例(去掉新建状态、诊断、老板键)。 数据盘整份拷,目录里相对的 qcow2 链原样带过去;源目录内写成绝对路径的 backing 改成相对的,目录外的拍平成独立的一张。复制前查剩余空间,失败或取消时删掉半成品、 不留登记和锁文件。 Refs ModAVD/ModAVD#239 --- README.en.md | 1 + README.md | 1 + changelog.d/239-clone-instance.feat.md | 1 + internal/avd/avd.go | 74 ++++ internal/cli/args_test.go | 2 +- internal/cli/cli.go | 2 + internal/cli/clone_test.go | 31 ++ internal/cli/commands.go | 31 ++ internal/cli/format.go | 6 + internal/cli/run_test.go | 8 + internal/emu/clone.go | 473 +++++++++++++++++++++++++ internal/emu/clone_test.go | 369 +++++++++++++++++++ internal/emu/disk.go | 5 + internal/i18n/locales/en/avd.json | 1 + internal/i18n/locales/en/cli.json | 4 + internal/i18n/locales/en/emu.json | 25 ++ internal/i18n/locales/en/ui.json | 1 + internal/i18n/locales/en/web.json | 9 + internal/ui/API.en.md | 5 +- internal/ui/API.md | 5 +- internal/ui/backend.go | 2 + internal/ui/fake_test.go | 18 + internal/ui/handlers.go | 22 ++ internal/ui/http.go | 1 + internal/ui/jobs.go | 3 + internal/ui/web/js/actions.js | 8 +- internal/ui/web/js/cards.js | 8 +- internal/ui/web/js/format.js | 4 +- internal/ui/web/js/panels.js | 11 +- 29 files changed, 1115 insertions(+), 16 deletions(-) create mode 100644 changelog.d/239-clone-instance.feat.md create mode 100644 internal/cli/clone_test.go create mode 100644 internal/emu/clone.go create mode 100644 internal/emu/clone_test.go diff --git a/README.en.md b/README.en.md index d3c5357..982c250 100644 --- a/README.en.md +++ b/README.en.md @@ -66,6 +66,7 @@ modavd [--root ] [--json] [--quiet] [--verbose] [args] | `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--boss-key combination\|none]` | Change settings. Diagnostics and the boss key apply immediately; other settings take effect at the next start. `--data-gb auto` makes the data disk automatic, `--data-gb N` gives it a fixed size (see below); the size can only be increased, and game data is untouched: the emulator (from 0.36) grows the disk image at start and grows the file system online after boot. A disk created before 0.36 at 16 GB or smaller can only be grown to just below the next backup group (a 16 GB disk to about 30 GB). `--sound on` gives this instance sound from its next start (windowed and headless, at some extra CPU); the default `off` boots without a sound card; stored as `instances..sound` in `mas-avd.json`. `--boss-key` is this instance's boss key (see the ModAVD.exe manager section), for example `Ctrl+Alt+Shift+1`; `none` means no boss key; Windows only. | | `proxy [on\|off\|test] [--server URL\|auto] [--add PKG] [--remove PKG] [--apps PKG]` | Per-app proxy: the listed apps go through a proxy, the others direct (see below) | | `delete --yes` | Delete a stopped instance, together with its game data | +| `clone [--title T]` | Copy a stopped instance whole into a new one (games, logins and settings included): the new one takes the smallest free index and its ports, everything else follows the source. The data disk is copied whole, so the two do not affect each other; without enough free space the command fails (`precheck_failed`) and copies nothing, and a failed or canceled copy is deleted. Both have the same Android device IDs (Android ID, GSF ID) | | `start [--window \| --headless] [--timeout 300] [--no-bridge]` | Start (headless by default, with the window for `--window`), wait until boot finishes and the post-boot setup is done, and before returning confirm that files can be written to `/sdcard` (normally it is ready long before this; it waits up to 60 more seconds and only warns at the deadline). If the instance is shutting down (for example, right after a click on the emulator window's ×), it first waits for the shutdown to finish (up to 30 seconds) and then starts it. If the instance has no execution bridge yet, install it afterward; `--no-bridge` skips that this time. The install takes a cold boot or two: with `--window`, the boots that only prepare it are headless, and after a normal shutdown the last boot has the window (when the instance has no boot marker yet, so the bridge is surely to be installed, the first boot is headless too; with the marker there, whether the bridge is installed is only known once it runs, so the first boot has the window). No switch while it runs: if the instance is already running and `--window` / `--headless` asks for the other way, it fails (exit code 5) without taking it over or restarting it; to switch, `stop` and then `start`. With neither, it is taken over as it runs | | `stop [--force] [--cancel-create]`, `stop --all [--force]` | Shut down: an app in the foreground is first sent home and given 2 s to save; then sync and ask Android for a clean shutdown (the foreground app is paused and stopped first), and if that fails, sync + kill; `--force` is sync + force-kill. Creating instances are refused unless `--cancel-create` is given. `--all` also stops creating instances and marks their results with `interrupted_create: true` | | `bridge install\|uninstall\|verify` | Install, uninstall or check the arm64 execution bridge; it is installed automatically at start, so you normally do not run it by hand (see below) | diff --git a/README.md b/README.md index 596e044..b351eb3 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] | `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--boss-key 组合\|none]` | 修改;诊断模式和老板键立即生效,其余设置下次开机生效。`--data-gb auto` 改成自动扩盘,`--data-gb N` 改成指定大小(见下);大小只能改大,游戏数据不动:模拟器(0.36 起)开机时扩磁盘镜像,开机后在线扩文件系统。0.36 之前按 16 GB 及以下建的盘只能扩到下一个备份组之前(16 GB 约到 30 GB)。`--sound on` 让这台下次开机起有声音(带窗口和无头都是,会多占一些 CPU),默认 `off` 不带声卡;记在 `mas-avd.json` 的 `instances..sound`。`--boss-key` 是这台的老板键(见「管理器 ModAVD.exe」一节),比如 `Ctrl+Alt+Shift+1`,`none` 是不要,只有 Windows。 | | `proxy [on\|off\|test] [--server URL\|auto] [--add 包名] [--remove 包名] [--apps 包名]` | 按应用走代理:名单里的应用走代理,其余直连(见下) | | `delete --yes` | 删除已关机的实例,连同游戏数据 | +| `clone [--title T]` | 把已关机的实例整份复制成一台新实例(游戏、登录状态、设置都带上):新实例用最小的空闲编号和它的端口,其余设置照源实例;数据盘整份复制,两台互不影响,可用空间不够时报错(`precheck_failed`)、什么都不复制;失败或取消时复制到一半的会删掉。两台的安卓设备标识(Android ID、GSF ID)相同 | | `start [--window \| --headless] [--timeout 300] [--no-bridge]` | 开机(默认无头,`--window` 带窗口),等开完并做完开机后的设置,返回前确认 `/sdcard` 能写进文件(一般这时早已就绪;最多再等 60 秒,到点只警告);实例正在关机时(比如刚点了模拟器窗口的 ×)先等它关完(最多 30 秒)再开机;实例还没有执行桥时接着装上,`--no-bridge` 这次不装;装桥要冷启动一两次,带 `--window` 时这几次准备用的开机都无头,装好后正常关机,最后一次才带窗口开机(实例还没有开机标记、一定要装桥时,第一次开机就无头;有标记的要开起来才知道装没装,第一次照样带窗口)。运行中不换方式:实例已经在运行时,给了 `--window` / `--headless` 而它不是这种方式,就报错(退出码 5),不接管也不重启,要换先 `stop` 再 `start`;两个都不给就照原样接管 | | `stop [--force] [--cancel-create]`、`stop --all [--force]` | 关机:前台开着应用时先按 HOME,等 2 秒让它保存;再 sync,让安卓正常关机(前台应用先收到暂停、停止),不成再 sync + kill;`--force` 是 sync + 强杀。新建中默认拒绝,`--cancel-create` 显式取消;`--all` 也关闭新建中的实例,结果标记 `interrupted_create: true` | | `bridge install\|uninstall\|verify` | 装、卸、检查 arm64 执行桥;开机时会自动装,一般不用手动跑(见下) | diff --git a/changelog.d/239-clone-instance.feat.md b/changelog.d/239-clone-instance.feat.md new file mode 100644 index 0000000..3b097fe --- /dev/null +++ b/changelog.d/239-clone-instance.feat.md @@ -0,0 +1 @@ +管理器和命令行能复制实例,新实例带着游戏、登录状态和设置 (ModAVD/ModAVD#239) diff --git a/internal/avd/avd.go b/internal/avd/avd.go index 7a30537..b4d3d7e 100644 --- a/internal/avd/avd.go +++ b/internal/avd/avd.go @@ -763,6 +763,80 @@ func Create(r *root.Root, i int, opt CreateOptions) (*Instance, error) { return &Instance{Index: i, Name: name, Title: title, Dir: dir, Config: cfg}, nil } +// ValidateTitle refuses a title Create and Update would refuse (line breaks). +func ValidateTitle(title string) error { return validateTitle(title) } + +// RegisterCopy makes instance i out of a directory the caller already copied to Dir(r, i) (emu's Clone, +// ModAVD/ModAVD#239): config.ini becomes src's keys with avd.id / avd.name of i and avd.ini.displayname title ("" = +// the AVD name), instances. becomes meta (replacing whatever was there), and mas_.ini is written last, which +// makes the instance listed. Like Create, a failure takes back the metadata and the .ini; the directory is the +// caller's to remove. errs.AlreadyExists when mas_.ini exists, errs.NotFound when the directory does not. +func RegisterCopy(r *root.Root, i int, src *Ini, title string, meta *jsonord.Obj) (*Instance, error) { + if !root.ValidIndex(i) { + return nil, errs.Newf(errs.InvalidArgument, "实例编号 %d 不可用(只能是 0–9,5 除外)", i) + } + if err := validateTitle(title); err != nil { + return nil, err + } + name := root.AvdName(i) + dir, iniPath := Dir(r, i), IniPath(r, i) + if title == "" { + title = name + } + cfg := NewIni() + for _, k := range src.Keys() { + cfg.Set(k, src.Value(k)) + } + cfg.Set("avd.id", name) + cfg.Set("avd.name", name) + cfg.Set("avd.ini.displayname", title) + target := cfg.Value("target") + if target == "" { + target = root.CurrentPlatform().TargetAPI + } + ini := NewIni() + ini.Set("avd.ini.encoding", "UTF-8") + ini.Set("path", dir) + ini.Set("path.rel", filepath.Join(root.AvdDir, name+".avd")) + ini.Set("target", target) + + l, err := r.LockInstanceConfig(i) + if err != nil { + return nil, err + } + defer l.Unlock() + if pathExists(iniPath) { + return nil, errs.Newf(errs.AlreadyExists, "实例 %s 已存在", name) + } + if fi, err := os.Stat(dir); err != nil || !fi.IsDir() { + return nil, errs.Newf(errs.NotFound, "实例目录 %s 不存在", dir) + } + if err := WriteIni(filepath.Join(dir, "config.ini"), cfg); err != nil { + return nil, err + } + err = r.EditInstanceMeta(i, func(o *jsonord.Obj) error { + for _, k := range o.Keys() { + o.Delete(k) + } + for _, k := range meta.Keys() { + o.Set(k, meta.Get(k).Clone()) + } + return nil + }) + if err != nil { + return nil, err + } + if err := WriteIni(iniPath, ini); err != nil { + os.Remove(iniPath) + r.RemoveInstanceMeta(i) + return nil, err + } + if in, err := Get(r, i); err == nil { + return in, nil + } + return &Instance{Index: i, Name: name, Title: title, Dir: dir, Config: cfg}, nil +} + func pathExists(path string) bool { _, err := os.Stat(path) return err == nil diff --git a/internal/cli/args_test.go b/internal/cli/args_test.go index 0872853..191acdd 100644 --- a/internal/cli/args_test.go +++ b/internal/cli/args_test.go @@ -429,7 +429,7 @@ func TestCommandTable(t *testing.T) { } } } - for _, name := range []string{"list", "info", "status", "create", "set", "delete", "start", "stop", + for _, name := range []string{"list", "info", "status", "create", "set", "delete", "clone", "start", "stop", "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 08cfd8d..2e5326e 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -15,6 +15,7 @@ // proxy [on|off] [--server URL|auto] [--add P] [--remove P] [--apps P] emu.AppProxyResult // proxy test emu.AppProxyTestResult // delete --yes emu.DeleteResult (without --yes: usage error) +// clone [--title T] emu.CloneResult {source,instance,copied_bytes} // start [--window|--headless] [--timeout 300] emu.StartResult (running the other way than asked: busy) // stop [--force] emu.StopResult // stop --all [--force] StopAllResult {"results":[StopResult],"failed":[{index,error}]} @@ -130,6 +131,7 @@ type manager interface { Create(ctx context.Context, req emu.CreateRequest) (*emu.InstanceInfo, error) Update(ctx context.Context, i int, req emu.UpdateRequest) (*emu.UpdateResult, error) Delete(ctx context.Context, i int) (*emu.DeleteResult, error) + Clone(ctx context.Context, i int, req emu.CloneRequest) (*emu.CloneResult, error) Start(ctx context.Context, i int, opt emu.StartOptions) (*emu.StartResult, error) Stop(ctx context.Context, i int, opt emu.StopOptions) (*emu.StopResult, error) Check(ctx context.Context, opt emu.CheckOptions) (*emu.CheckResult, error) diff --git a/internal/cli/clone_test.go b/internal/cli/clone_test.go new file mode 100644 index 0000000..7f7db16 --- /dev/null +++ b/internal/cli/clone_test.go @@ -0,0 +1,31 @@ +//go:build windows + +package cli + +import ( + "strings" + "testing" +) + +func TestRunClone(t *testing.T) { + h := newHarness() + r := h.run(t, nil, "clone", "mas_1", "--title", "副本") + if r.code != 0 || !strings.Contains(r.stdout, "已把实例 1 复制成") || !strings.Contains(r.stdout, "复制了 3.0 GB") { + t.Fatalf("clone: %+v", r) + } + if len(h.fake.calls) != 1 || h.fake.calls[0] != "clone 1 副本" { + t.Fatalf("calls %v", h.fake.calls) + } + if !strings.Contains(r.stderr, "复制中 50%") { + t.Errorf("progress not logged: %q", r.stderr) + } + r = h.run(t, nil, "clone", "1", "--json") + env := envelope(t, r.stdout) + data, _ := env["data"].(map[string]any) + if env["ok"] != true || data["source"] != float64(1) || data["copied_bytes"] != float64(3<<30) { + t.Fatalf("json %v", env) + } + if r := h.run(t, nil, "clone"); r.code == 0 { + t.Fatal("no index accepted") + } +} \ No newline at end of file diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 6981f00..cc2e986 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -239,6 +239,17 @@ func init() { final: true, run: runDelete, human: humanOf(formatDelete), }, + { + name: "clone", args: " [--title T]", summary: "把一台已关机的实例复制成一台新实例(连同游戏、登录状态和设置)", + details: "新实例用最小的空闲编号(所以有自己的端口和 adb 序列号),其余设置照源实例:内存、核数、帧率、分辨率、声音、语言、时区、数据盘方式等;" + + "--title 给新实例起名,不给就叫它的实例名。数据盘整份复制,两台互不影响,所以要和源实例差不多大的可用空间;不够就报错(precheck_failed),什么都不复制。" + + "源实例在运行或正在开关机时拒绝(busy)。复制失败或按 Ctrl+C 取消时,复制到一半的新实例会删掉。" + + "两台的安卓设备标识(Android ID、GSF ID)一样,同时开着登同一个游戏账号可能被顶掉。", + flags: []flagSpec{optTitle}, + posNames: []string{"实例编号"}, minPos: 1, maxPos: 1, + final: true, + run: runClone, human: humanOf(formatClone), + }, { name: "start", args: " [--window | --headless] [--timeout 300] [--no-bridge]", summary: "开机,等 Android 开完并做好开机后的设置", details: "默认无头启动,--window 带窗口。运行中不能换:实例已经在运行(或正被另一次 start 开着)时," + @@ -844,6 +855,26 @@ func runDelete(c *cmdCtx) (any, error) { return r, nil } +func runClone(c *cmdCtx) (any, error) { + i, err := parseIndex(c.inv.pos[0]) + if err != nil { + return nil, err + } + m, err := c.mgr() + if err != nil { + return nil, err + } + last := -5 // so 0 % gets its line + req := emu.CloneRequest{Title: c.inv.strOpt("title"), Progress: func(p emu.Progress) { + // one line per 5 %: a copy of 100 GB takes minutes + if pct := p.Percent(); pct/5 != last/5 { + last = pct + c.log.Infof("复制中 %d%%:%s", pct, p.Message) + } + }} + return m.Clone(c.ctx, i, req) +} + func runStart(c *cmdCtx) (any, error) { i, err := parseIndex(c.inv.pos[0]) if err != nil { diff --git a/internal/cli/format.go b/internal/cli/format.go index 45401ec..d15bcc0 100644 --- a/internal/cli/format.go +++ b/internal/cli/format.go @@ -479,6 +479,12 @@ func formatDelete(w io.Writer, r *emu.DeleteResult) { fmt.Fprintf(w, "已删除实例 %d(%s),连同数据目录 %s\n", r.Index, r.Name, r.Path) } +func formatClone(w io.Writer, r *emu.CloneResult) { + in := r.Instance + fmt.Fprintf(w, "已把实例 %d 复制成%s,复制了 %.1f GB\n", r.Source, instLabel(in.Index, in.Name, in.Title), float64(r.CopiedBytes)/(1<<30)) + fmt.Fprintf(w, "adb 地址:%s\n", in.AdbAddress) + fmt.Fprintf(w, "路径:%s\n", in.Path) +} func formatStart(w io.Writer, r *emu.StartResult) { in := r.Instance label := subject(in.Index, in.Name, in.Title) diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index 144dee0..5e779ff 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -120,6 +120,14 @@ func (f *fakeManager) Delete(ctx context.Context, i int) (*emu.DeleteResult, err return &emu.DeleteResult{Index: i, Name: root.AvdName(i), Path: `D:\r\avd\` + root.AvdName(i) + ".avd"}, nil } +func (f *fakeManager) Clone(ctx context.Context, i int, req emu.CloneRequest) (*emu.CloneResult, error) { + f.record("clone " + itoa(i) + " " + req.Title) + if req.Progress != nil { + req.Progress(emu.Progress{Step: "copy", Message: "m", Done: 500, Total: 1000}) + } + return &emu.CloneResult{Source: i, Instance: sampleInstance(2), CopiedBytes: 3 << 30}, nil +} + func (f *fakeManager) Start(ctx context.Context, i int, opt emu.StartOptions) (*emu.StartResult, error) { f.record("start " + itoa(i)) if f.start != nil { diff --git a/internal/emu/clone.go b/internal/emu/clone.go new file mode 100644 index 0000000..37e1561 --- /dev/null +++ b/internal/emu/clone.go @@ -0,0 +1,473 @@ +package emu + +// modavd clone (ModAVD/ModAVD#239): a new instance that is a full copy of a stopped one, with its games, logins +// and settings. The new one gets the next free index (so its own ports and adb serial); everything else is the +// source's: its config.ini (memory, cores, frame rate, resolution, sound ...) and its part of mas-avd.json +// (language, time zone, bridge, data disk mode ...), less what belongs to one instance only (creation state, +// diagnostics, boss key: the copy gets the default of its index). +// +// The disks are copied whole, so the two never share a file. Inside an instance the data disk is a qcow2 overlay over +// a base image next to it, named relatively (userdata-qemu.img.qcow2 -> userdata-qemu.img): copying the directory +// keeps that chain inside the copy. A backing named by an absolute path inside the source directory is renamed to the +// relative name in the copy (qemu-img rebase -u: same bytes, only the header changes). The system and vendor +// overlays sit on the root's read-only system image like every instance's (the bridge keeps that path right, +// bridge_backing.go); any other disk whose backing is outside the source directory is flattened into a standalone +// image (qemu-img convert), so the copy never depends on someone else's file. +// +// Not copied: snapshots (every boot is cold), the emulator's per-launch files (hardware-qemu.ini and +// emu-launch-params.txt, written again at each launch with the instance's own paths), lock files and leftovers of an +// interrupted compact. The device identity inside the guest (Android ID, GSF ID) is copied as it is: changing it +// would log the games out, which is what the copy is for. +// +// Before anything is written the volume must have room for the copy plus cloneHeadroom; a failed or canceled clone +// removes the half-made directory, its metadata and its lock files, so nothing of it is listed or left behind. + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "time" + + "modavd/internal/avd" + "modavd/internal/bosskey" + "modavd/internal/errs" + "modavd/internal/host" + "modavd/internal/jsonord" + "modavd/internal/root" +) + +// CloneRequest is `modavd clone `'s options. +type CloneRequest struct { + Title string // "" = the new AVD name, like create + Progress func(Progress) +} + +// CloneResult is the new instance and where it came from. +type CloneResult struct { + Source int `json:"source"` + Instance InstanceInfo `json:"instance"` + CopiedBytes int64 `json:"copied_bytes"` +} + +// cloneHeadroom is kept free on the volume beyond the copy itself: a volume filled to the last byte would stall the +// instances running from it. +const cloneHeadroom = 2 << 30 + +// cloneQemuImgTimeout bounds one qemu-img info / rebase; a convert (flattening) gets cloneConvertTimeout. +const ( + cloneQemuImgTimeout = 2 * time.Minute + cloneConvertTimeout = 3 * time.Hour +) + +// Hooks for the tests: qemu-img (a fake answers in tests; nothing real is started) and the free space. +var ( + cloneRunQemuImg = (*Manager).runQemuImg + cloneDiskFree = func(path string) (uint64, error) { return hostDiskFree(path) } +) + +// cloneSkipDirs and cloneSkipFiles are left out of the copy (names inside the instance directory, any case). +var ( + cloneSkipDirs = []string{"snapshots", "tmpAdbCmds"} + cloneSkipFiles = []string{"hardware-qemu.ini", "emu-launch-params.txt", userdataCompactTmp} +) + +// cloneMetaDrop are the keys of instances. that belong to the source alone. +var cloneMetaDrop = []string{"creationState", "creationError", "creationLog", "diagnostics", "diagnosticsSince", + bosskey.MetaKey} + +// cloneFile is one file of the copy: rel inside the instance directory, size in bytes (what the copy writes), and how +// a qcow2 disk is carried over. +type cloneFile struct { + rel string + size int64 + // rebase: the backing is the absolute path of a file inside the source directory; the copy gets this relative + // name instead (qemu-img rebase -u). flatten: the backing is outside; the copy is a standalone image. + rebase string + rebaseFmt string + flatten bool + isDir bool // a directory (created, not copied) +} + +func cloneSkipped(rel string, dir bool) bool { + base := filepath.Base(rel) + if dir { + for _, d := range cloneSkipDirs { + if strings.EqualFold(rel, d) { + return true + } + } + return false + } + if strings.EqualFold(filepath.Ext(base), ".lock") { + return true + } + if strings.Contains(strings.ToLower(base), ".modavd-") && strings.EqualFold(filepath.Ext(base), ".tmp") { + return true // a WriteIni temp of a writer that died + } + for _, f := range cloneSkipFiles { + if strings.EqualFold(rel, f) { + return true + } + } + return false +} + +// insideDir: path is dir or below it (both cleaned, any case on Windows). +func insideDir(dir, path string) bool { + rel, err := filepath.Rel(dir, path) + if err != nil { + return false + } + return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel) +} + +// sharedSystemOverlay: the system and vendor overlays, whose backing is the root's read-only system image. +func sharedSystemOverlay(rel string) bool { + return strings.EqualFold(rel, "system.img.qcow2") || strings.EqualFold(rel, "vendor.img.qcow2") +} + +// clonePlan lists what to copy from src and how; need is the bytes the copy writes. +func (m *Manager) clonePlan(ctx context.Context, src string) (files []cloneFile, need int64, err error) { + err = filepath.WalkDir(src, func(path string, d fs.DirEntry, werr error) error { + if werr != nil { + return errs.Wrap(errs.Internal, werr, "读不了实例目录: "+werr.Error()) + } + if path == src { + return nil + } + rel, _ := filepath.Rel(src, path) + if cloneSkipped(rel, d.IsDir()) { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + if d.IsDir() { + files = append(files, cloneFile{rel: rel, isDir: true}) + return nil + } + // a link to a file is copied as the file it points to (a standalone copy); anything else that is not a plain + // file (a link to a directory, a device) is not something an instance has + fi, err := os.Stat(path) + if err != nil { + return errs.Wrap(errs.Internal, err, "读不了 "+path+": "+err.Error()) + } + if !fi.Mode().IsRegular() { + return errs.Newf(errs.Unsupported, "实例目录里有不是普通文件的 %s,不能复制", path) + } + f := cloneFile{rel: rel, size: fi.Size()} + if strings.EqualFold(filepath.Ext(rel), ".qcow2") && !sharedSystemOverlay(rel) { + if err := m.cloneBacking(ctx, src, &f); err != nil { + return err + } + } + files = append(files, f) + need += f.size + return nil + }) + return files, need, err +} + +// cloneBacking decides how the disk f (rel set) is carried over, from its backing file name. +func (m *Manager) cloneBacking(ctx context.Context, src string, f *cloneFile) error { + path := filepath.Join(src, f.rel) + info, err := m.cloneQemuImgInfo(ctx, path) + if err != nil { + return err + } + if len(info.Snapshots) > 0 { + return errs.Newf(errs.Unsupported, "%s 里有 %d 个内部快照,不能复制", path, len(info.Snapshots)). + WithAdvice("先删掉快照再复制") + } + b := info.BackingFilename + if b == "" { + return nil + } + if !filepath.IsAbs(b) { + if insideDir(src, filepath.Join(filepath.Dir(path), b)) { + return nil // relative inside: the copy keeps the chain + } + } else if insideDir(src, filepath.Clean(b)) { + rel, err := filepath.Rel(filepath.Dir(path), filepath.Clean(b)) + if err != nil { + return errs.Wrap(errs.Internal, err, "算不出 "+b+" 的相对路径") + } + f.rebase, f.rebaseFmt = rel, info.BackingFilenameFmt + return nil + } + // outside the instance: the copy is flattened, which may need up to the backing's size more + f.flatten = true + if fi, err := os.Stat(b); err == nil { + f.size += fi.Size() + } else if !filepath.IsAbs(b) { + if fi, err := os.Stat(filepath.Join(filepath.Dir(path), b)); err == nil { + f.size += fi.Size() + } + } + return nil +} + +func (m *Manager) cloneQemuImgInfo(ctx context.Context, image string) (*qemuImgInfoResult, error) { + so, se, code, err := cloneRunQemuImg(m, ctx, cloneQemuImgTimeout, "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)) + } + return decodeQemuImgInfo(so) +} + +// lockInstanceForClone takes the source's locks so nobody boots, stops, bridges, creates or compacts it while it is +// copied (the same set as compact). errs.Busy when one is held; the func releases them. +func (m *Manager) lockInstanceForClone(i int) (func(), error) { + kinds := []struct{ kind, what string }{ + {"disk", "正在整理磁盘"}, + {"start", "正在启动"}, + {"stop", "正在关闭"}, + {"bridge", "正在装卸执行桥"}, + {"create", "正在新建"}, + } + var locks []*host.FileLock + unlock := func() { + for k := len(locks) - 1; k >= 0; k-- { + locks[k].Unlock() + } + } + for _, kw := range kinds { + l, ok, err := host.TryLock(m.lockPath(i, kw.kind)) + if err != nil { + unlock() + return nil, errs.Wrap(errs.Internal, err, "实例锁文件打不开: "+m.lockPath(i, kw.kind)) + } + if !ok { + unlock() + return nil, errs.WithDetails(errs.Newf(errs.Busy, "ModAVD 实例 %d %s,无法复制", i, kw.what), + map[string]string{errs.Reason: "locked", errs.Lock: kw.kind}) + } + locks = append(locks, l) + } + return unlock, nil +} + +// Clone copies stopped instance src into a new instance (see the top of this file). errs.Busy while src runs or is +// being started, stopped, bridged, created or compacted; errs.PrecheckFailed when the volume has no room for the copy; +// errs.Canceled when ctx ends (the half-made copy is removed). +func (m *Manager) Clone(ctx context.Context, src int, req CloneRequest) (*CloneResult, error) { + if err := requireLifecycle(); err != nil { + return nil, err + } + in, err := m.instance(src) + if err != nil { + return nil, err + } + if err := m.notCreated(src, "不能复制"); err != nil { + return nil, err + } + if err := avd.ValidateTitle(req.Title); err != nil { + return nil, err + } + if _, err := m.Root.EnsureMetadata(); err != nil { + return nil, err + } + unlockSrc, err := m.lockInstanceForClone(src) + if err != nil { + return nil, err + } + defer unlockSrc() + if _, running, err := m.qemuOf(src); err != nil { + return nil, err + } else if running { + return nil, errs.WithDetails(errs.Newf(errs.Busy, "ModAVD 实例 %d 未关闭,无法复制", src). + WithAdvice(fmt.Sprintf("先 modavd stop %d,关机后再复制", src)), map[string]string{errs.Reason: "running"}) + } + + files, need, err := m.clonePlan(ctx, in.Dir) + if err != nil { + return nil, err + } + free, err := cloneDiskFree(m.Root.AvdHome()) + if err != nil { + return nil, errs.Wrap(errs.Internal, err, "读不了剩余空间: "+err.Error()) + } + if want := uint64(need) + cloneHeadroom; free < want { + return nil, errs.WithDetails(errs.Newf(errs.PrecheckFailed, + "复制实例 %d 要约 %s 可用空间,%s 所在磁盘只剩 %s", src, gib(int64(want)), m.Root.AvdHome(), gib(int64(free))). + WithAdvice(fmt.Sprintf("先腾出约 %s 再复制", gib(int64(want-free)))), map[string]string{errs.Reason: "disk_space"}) + } + + insts, err := avd.List(m.Root) + if err != nil { + return nil, err + } + existing := map[int]bool{} + for _, x := range insts { + existing[x.Index] = true + } + dst, err := m.freeIndex(existing) + if err != nil { + return nil, err + } + lock, err := m.lockCreation(ctx, dst) + if err != nil { + return nil, err + } + dstDir := avd.Dir(m.Root, dst) + // Mkdir: a create racing for the same index loses here (or we do) instead of sharing the directory. + if err := os.Mkdir(dstDir, 0o755); err != nil { + lock.Unlock() + if errors.Is(err, fs.ErrExist) { + return nil, errs.Newf(errs.AlreadyExists, "实例 %s 已存在", root.AvdName(dst)) + } + return nil, errs.Wrap(errs.Internal, err, fmt.Sprintf("建不了目录 %s:%v", dstDir, err)) + } + rollback := func() { + os.RemoveAll(dstDir) + os.Remove(avd.IniPath(m.Root, dst)) + m.Root.RemoveInstanceMeta(dst) + lock.Unlock() + m.removeLockFiles(dst) + } + m.Log.Infof("正在把 ModAVD 实例 %d 复制成实例 %d(约 %s)", src, dst, gib(need)) + copied, err := m.cloneCopy(ctx, src, in.Dir, dstDir, files, need, req.Progress) + if err != nil { + rollback() + if ctx.Err() != nil { + return nil, errs.Wrap(errs.Canceled, ctx.Err(), "已取消复制,没复制完的实例已删掉") + } + return nil, err + } + + meta := m.Root.InstanceMeta(src) + if meta == nil { + meta = jsonord.NewObject().Obj() + } + for _, k := range cloneMetaDrop { + meta.Delete(k) + } + meta.Set("createdAt", jsonord.NewString(root.NowISO())) + if _, err := avd.RegisterCopy(m.Root, dst, in.Config, req.Title, meta); err != nil { + rollback() + return nil, err + } + lock.Unlock() + m.Log.Infof("已把 ModAVD 实例 %d 复制成实例 %d", src, dst) + newIn, err := m.instance(dst) + if err != nil { + return nil, err + } + return &CloneResult{Source: src, Instance: m.instanceInfo(ctx, newIn, nil, nil), CopiedBytes: copied}, nil +} + +// cloneCopy copies files from srcDir to dstDir (which exists), reporting progress by bytes. +func (m *Manager) cloneCopy(ctx context.Context, src int, srcDir, dstDir string, files []cloneFile, need int64, + progress func(Progress)) (int64, error) { + var done int64 + last := time.Time{} + report := func(force bool) { + if progress == nil || (!force && time.Since(last) < 500*time.Millisecond) { + return + } + last = time.Now() + permille := 1000 + if need > 0 { + permille = int(done * 1000 / need) + } + progress(Progress{Step: "copy", Message: fmt.Sprintf("正在复制实例 %d(%s / %s)", src, gib(done), gib(need)), + Done: min(permille, 1000), Total: 1000}) + } + report(true) + buf := make([]byte, 4<<20) + for _, f := range files { + if err := ctxErr(ctx); err != nil { + return done, err + } + from, to := filepath.Join(srcDir, f.rel), filepath.Join(dstDir, f.rel) + if f.isDir { + if err := os.Mkdir(to, 0o755); err != nil { + return done, errs.Wrap(errs.Internal, err, fmt.Sprintf("建不了目录 %s:%v", to, err)) + } + continue + } + if f.flatten { + so, se, code, err := cloneRunQemuImg(m, ctx, cloneConvertTimeout, "convert", "-O", "qcow2", from, to) + if err != nil { + return done, err + } + if code != 0 { + return done, errs.Newf(errs.Internal, "qemu-img convert 失败(退出码 %d): %s", code, qemuImgFail(so, se)) + } + if err := syncFile(to); err != nil { + return done, errs.Wrap(errs.Internal, err, "刷新复制的磁盘失败: "+to) + } + done += f.size + report(false) + continue + } + if err := copyFileSync(ctx, from, to, buf, func(n int64) { done += n; report(false) }); err != nil { + return done, err + } + if f.rebase != "" { + args := []string{"rebase", "-u", "-b", f.rebase} + if f.rebaseFmt != "" { + args = append(args, "-F", f.rebaseFmt) + } + so, se, code, err := cloneRunQemuImg(m, ctx, cloneQemuImgTimeout, append(args, to)...) + if err != nil { + return done, err + } + if code != 0 { + return done, errs.Newf(errs.Internal, "qemu-img rebase 失败(退出码 %d): %s", code, qemuImgFail(so, se)) + } + } + } + report(true) + return done, nil +} + +// copyFileSync copies one file (a new file at to) and flushes it to disk; added is called with each chunk's size. +func copyFileSync(ctx context.Context, from, to string, buf []byte, added func(int64)) error { + in, err := os.Open(from) + if err != nil { + return errs.Wrap(errs.Internal, err, fmt.Sprintf("读不了 %s:%v", from, err)) + } + defer in.Close() + out, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) + if err != nil { + return errs.Wrap(errs.Internal, err, fmt.Sprintf("写不了 %s:%v", to, err)) + } + fail := func(err error) error { + out.Close() + return err + } + for { + if err := ctxErr(ctx); err != nil { + return fail(err) + } + n, rerr := in.Read(buf) + if n > 0 { + if _, werr := out.Write(buf[:n]); werr != nil { + return fail(errs.Wrap(errs.Internal, werr, fmt.Sprintf("写 %s 失败:%v", to, werr))) + } + added(int64(n)) + } + if rerr == io.EOF { + break + } + if rerr != nil { + return fail(errs.Wrap(errs.Internal, rerr, fmt.Sprintf("读 %s 失败:%v", from, rerr))) + } + } + if err := out.Sync(); err != nil { + return fail(errs.Wrap(errs.Internal, err, fmt.Sprintf("刷新 %s 失败:%v", to, err))) + } + if err := out.Close(); err != nil { + return errs.Wrap(errs.Internal, err, fmt.Sprintf("写 %s 失败:%v", to, err)) + } + return nil +} diff --git a/internal/emu/clone_test.go b/internal/emu/clone_test.go new file mode 100644 index 0000000..23f83a3 --- /dev/null +++ b/internal/emu/clone_test.go @@ -0,0 +1,369 @@ +//go:build windows + +package emu + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "modavd/internal/avd" + "modavd/internal/bosskey" + "modavd/internal/errs" + "modavd/internal/jsonord" + "modavd/internal/win" +) + +// fakeCloneQemuImg stands in for qemu-img (nothing is started): info answers from backing (by file base name), +// convert writes the target, rebase fails when rebaseCode is not 0. calls records every run. +type fakeCloneQemuImg struct { + mu sync.Mutex + backing map[string]string // base name -> backing-filename + snapshots map[string]bool + rebaseCode int + calls [][]string +} + +func (f *fakeCloneQemuImg) run(_ *Manager, _ context.Context, _ time.Duration, args ...string) ([]byte, []byte, int, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, append([]string(nil), args...)) + switch args[0] { + case "info": + img := args[len(args)-1] + b := f.backing[filepath.Base(img)] + snaps := "[]" + if f.snapshots[filepath.Base(img)] { + snaps = `[{"id":"1"}]` + } + js := fmt.Sprintf(`{"format":"qcow2","virtual-size":1024,"backing-filename":%q,"backing-filename-format":"qcow2","snapshots":%s}`, + b, snaps) + return []byte(js), nil, 0, nil + case "convert": + if err := os.WriteFile(args[len(args)-1], []byte("flattened"), 0o644); err != nil { + return nil, nil, 0, err + } + return nil, nil, 0, nil + case "rebase": + return nil, []byte("rebase says no"), f.rebaseCode, nil + } + return nil, []byte("unexpected"), 1, nil +} + +func (f *fakeCloneQemuImg) ran(verb string) [][]string { + f.mu.Lock() + defer f.mu.Unlock() + var out [][]string + for _, c := range f.calls { + if c[0] == verb { + out = append(out, c) + } + } + return out +} + +// cloneTestSetup is a test root (never the real one) with instance 0 holding a small fake instance directory, a fake +// qemu-img and plenty of fake free space. +func cloneTestSetup(t *testing.T) (*Manager, *fakeCloneQemuImg, *avd.Instance) { + t.Helper() + m, _ := opsTestManager(t) + zero := 0 + if _, err := m.Create(context.Background(), CreateRequest{filesOnly: true, Index: &zero, Title: "源实例"}); err != nil { + opsSkipIfNotImplemented(t, err) + t.Fatal(err) + } + in, err := m.instance(0) + if err != nil { + t.Fatal(err) + } + for name, content := range map[string]string{ + "userdata-qemu.img": "base", + "userdata-qemu.img.qcow2": strings.Repeat("game data ", 1000), + "cache.img.qcow2": "cache", + "system.img.qcow2": "system overlay", + "encryptionkey.img": "key", + "hardware-qemu.ini": `disk.dataPartition.path = C:\elsewhere\mas_0.avd\userdata-qemu.img`, + "emu-launch-params.txt": "mas_0", + "multiinstance.lock": "", + "config.ini.modavd-99.tmp": "dead writer", + filepath.Join("snapshots", "default_boot", "ram.img"): "ram", + filepath.Join("data", "misc", "pstore", "pstore.bin"): "pstore", + } { + writeTestFile(t, filepath.Join(in.Dir, name), content) + } + if err := m.Root.EditInstanceMeta(0, func(o *jsonord.Obj) error { + o.Set("sound", jsonord.NewBool(true)) + o.Set("bridge", jsonord.NewBool(true)) + o.Set(bosskey.MetaKey, jsonord.NewString("Ctrl+Alt+0")) + o.Set("diagnostics", jsonord.NewBool(false)) + o.Set("initialized", jsonord.NewBool(true)) + return nil + }); err != nil { + t.Fatal(err) + } + fake := &fakeCloneQemuImg{backing: map[string]string{"userdata-qemu.img.qcow2": "userdata-qemu.img"}} + savedRun, savedFree := cloneRunQemuImg, cloneDiskFree + cloneRunQemuImg = fake.run + cloneDiskFree = func(string) (uint64, error) { return 1 << 40, nil } + t.Cleanup(func() { cloneRunQemuImg, cloneDiskFree = savedRun, savedFree }) + return m, fake, in +} + +// nothingOf1: no trace of instance 1 (the clone's index) is left: files, metadata, lock files. +func nothingOf1(t *testing.T, m *Manager, label string) { + t.Helper() + if left := instanceLeftovers(m.Root, 1); len(left) != 0 { + t.Errorf("%s: left %v", label, left) + } + for _, kind := range []string{"create", "stop"} { + if fileOrDirExists(m.lockPath(1, kind)) { + t.Errorf("%s: lock file %s left", label, kind) + } + } +} + +func TestCloneCopiesInstance(t *testing.T) { + m, fake, src := cloneTestSetup(t) + var steps []Progress + res, err := m.Clone(context.Background(), 0, CloneRequest{Title: "副本", Progress: func(p Progress) { steps = append(steps, p) }}) + if err != nil { + t.Fatal(err) + } + if res.Source != 0 || res.Instance.Index != 1 || res.Instance.Title != "副本" || res.Instance.Status != StatusOffline { + t.Fatalf("result %+v", res) + } + dst := avd.Dir(m.Root, 1) + for _, name := range []string{"userdata-qemu.img", "userdata-qemu.img.qcow2", "cache.img.qcow2", "system.img.qcow2", + "encryptionkey.img", filepath.Join("data", "misc", "pstore", "pstore.bin")} { + a, err := os.ReadFile(filepath.Join(src.Dir, name)) + if err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(filepath.Join(dst, name)) + if err != nil || !bytes.Equal(a, b) { + t.Errorf("%s not copied: %v", name, err) + } + } + for _, name := range []string{"hardware-qemu.ini", "emu-launch-params.txt", "multiinstance.lock", "snapshots", + "config.ini.modavd-99.tmp"} { + if fileOrDirExists(filepath.Join(dst, name)) { + t.Errorf("%s copied", name) + } + } + // what is in the copy, config.ini as copied (RegisterCopy rewrites it afterwards) and the bridge marker included + var copiedFiles uint64 + filepathWalkSizes(t, dst, &copiedFiles) + cfgSize := func(dir string) int64 { fi, _ := os.Stat(filepath.Join(dir, "config.ini")); return fi.Size() } + want := int64(copiedFiles) - cfgSize(dst) + cfgSize(src.Dir) + if res.CopiedBytes != want { + t.Errorf("copied %d bytes, want %d", res.CopiedBytes, want) + } + // the system overlay is the shared image's (not asked), the relative data disk chain needs nothing + for _, c := range fake.ran("info") { + if strings.EqualFold(filepath.Base(c[len(c)-1]), "system.img.qcow2") { + t.Errorf("system overlay inspected: %v", c) + } + } + if len(fake.ran("rebase"))+len(fake.ran("convert")) != 0 { + t.Errorf("relative backing rewritten: %v", fake.calls) + } + + cfg, err := avd.ReadIni(avd.ConfigPath(m.Root, 1)) + if err != nil { + t.Fatal(err) + } + if cfg.Value("avd.name") != "mas_1" || cfg.Value("avd.id") != "mas_1" || cfg.Value("avd.ini.displayname") != "副本" || + cfg.Value("hw.ramSize") != src.Config.Value("hw.ramSize") || cfg.Value("hw.lcd.vsync") != src.Config.Value("hw.lcd.vsync") { + t.Errorf("config.ini %v", cfg.Encode()) + } + ini, err := avd.ReadIni(avd.IniPath(m.Root, 1)) + if err != nil || ini.Value("path") != dst || ini.Value("path.rel") != filepath.Join("avd", "mas_1.avd") { + t.Errorf("mas_1.ini %v %v", ini, err) + } + meta := m.Root.InstanceMeta(1) + if s, _ := meta.Get("sound").BoolVal(); !s { + t.Error("sound not carried over") + } + if b, _ := meta.Get("initialized").BoolVal(); !b { + t.Error("initialized not carried over") + } + for _, k := range []string{bosskey.MetaKey, "diagnostics", "creationState"} { + if meta.Has(k) { + t.Errorf("%s carried over", k) + } + } + if c, _ := meta.Get("createdAt").Str(); c == "" { + t.Error("no createdAt") + } + // the source is as it was + if s, _ := m.Root.InstanceMeta(0).Get(bosskey.MetaKey).Str(); s != "Ctrl+Alt+0" { + t.Error("source metadata changed") + } + if in0, _ := m.instance(0); in0.Config.Value("avd.name") != "mas_0" || in0.Title != "源实例" { + t.Errorf("source config changed: %+v", in0) + } + if len(steps) < 2 || steps[len(steps)-1].Done != 1000 || steps[0].Step != "copy" { + t.Errorf("progress %+v", steps) + } + // no title: the AVD name, like create + res, err = m.Clone(context.Background(), 0, CloneRequest{}) + if err != nil || res.Instance.Index != 2 || res.Instance.Title != "mas_2" { + t.Fatalf("second clone: %+v %v", res, err) + } +} + +func TestCloneRefusesBusySource(t *testing.T) { + m, _, _ := cloneTestSetup(t) + ctx := context.Background() + + saved := qemuScan + qemuScan = func([]int) map[int]win.Process { return map[int]win.Process{0: {PID: 4242}} } + _, err := m.Clone(ctx, 0, CloneRequest{}) + qemuScan = saved + if errs.CodeOf(err) != errs.Busy { + t.Fatalf("running: %v", err) + } + wantErrorDetails(t, err, map[string]string{errs.Reason: "running"}) + nothingOf1(t, m, "running") + + for _, kind := range []string{"start", "stop", "bridge", "create", "disk"} { + l, ok, err := win.TryLock(m.lockPath(0, kind)) + if err != nil || !ok { + t.Fatalf("TryLock %s: %v %v", kind, ok, err) + } + _, err = m.Clone(ctx, 0, CloneRequest{}) + l.Unlock() + if errs.CodeOf(err) != errs.Busy { + t.Fatalf("%s lock held: %v", kind, err) + } + wantErrorDetails(t, err, map[string]string{errs.Reason: "locked", errs.Lock: kind}) + nothingOf1(t, m, kind) + } + + if _, err := m.Clone(ctx, 3, CloneRequest{}); errs.CodeOf(err) != errs.NotFound { + t.Fatalf("missing source: %v", err) + } + if _, err := m.Clone(ctx, 0, CloneRequest{Title: "a\nb"}); errs.CodeOf(err) != errs.InvalidArgument { + t.Fatalf("bad title: %v", err) + } + nothingOf1(t, m, "bad title") + // a source whose setup failed is refused + if err := m.setCreation(0, creationFailed, "boom", ""); err != nil { + t.Fatal(err) + } + if _, err := m.Clone(ctx, 0, CloneRequest{}); errs.CodeOf(err) != errs.NotReady { + t.Fatalf("create_failed source: %v", err) + } + nothingOf1(t, m, "create_failed") +} + +func TestCloneRefusesWithoutRoom(t *testing.T) { + m, _, src := cloneTestSetup(t) + _, n, err := m.clonePlan(context.Background(), src.Dir) + if err != nil { + t.Fatal(err) + } + var all uint64 + filepathWalkSizes(t, src.Dir, &all) + need := uint64(n) + if need == 0 || need >= all { + t.Fatalf("plan %d bytes of %d: the skipped files must not count", need, all) + } + cloneDiskFree = func(string) (uint64, error) { return need + cloneHeadroom - 1, nil } + _, err = m.Clone(context.Background(), 0, CloneRequest{}) + if errs.CodeOf(err) != errs.PrecheckFailed { + t.Fatalf("no room: %v", err) + } + wantErrorDetails(t, err, map[string]string{errs.Reason: "disk_space"}) + nothingOf1(t, m, "no room") + // exactly enough: it goes through + cloneDiskFree = func(string) (uint64, error) { return need + cloneHeadroom, nil } + if _, err := m.Clone(context.Background(), 0, CloneRequest{}); err != nil { + t.Fatalf("just enough room: %v", err) + } +} + +// filepathWalkSizes adds up every file below dir (more than the clone copies: the skipped files count too). +func filepathWalkSizes(t *testing.T, dir string, total *uint64) { + t.Helper() + err := filepath.Walk(dir, func(_ string, fi os.FileInfo, err error) error { + if err == nil && fi.Mode().IsRegular() { + *total += uint64(fi.Size()) + } + return err + }) + if err != nil { + t.Fatal(err) + } +} + +func TestCloneRollsBack(t *testing.T) { + m, fake, src := cloneTestSetup(t) + + // a failing step half way (the data disk's absolute backing inside the source cannot be renamed) + fake.backing["userdata-qemu.img.qcow2"] = filepath.Join(src.Dir, "userdata-qemu.img") + fake.rebaseCode = 1 + _, err := m.Clone(context.Background(), 0, CloneRequest{}) + if err == nil || !strings.Contains(err.Error(), "rebase") { + t.Fatalf("rebase failure: %v", err) + } + nothingOf1(t, m, "rebase failed") + if r := fake.ran("rebase"); len(r) != 1 || r[0][2] != "-b" || r[0][3] != "userdata-qemu.img" || + filepath.Dir(r[0][len(r[0])-1]) != avd.Dir(m.Root, 1) { + t.Fatalf("rebase %v", r) + } + + // canceled half way + fake.rebaseCode = 0 + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + calls := 0 + _, err = m.Clone(ctx, 0, CloneRequest{Progress: func(Progress) { + if calls++; calls == 1 { + cancel() + } + }}) + if errs.CodeOf(err) != errs.Canceled { + t.Fatalf("canceled: %v", err) + } + nothingOf1(t, m, "canceled") + +} + +func TestCloneBackings(t *testing.T) { + m, fake, src := cloneTestSetup(t) + outside := filepath.Join(t.TempDir(), "base.img") + writeTestFile(t, outside, strings.Repeat("x", 4096)) + fake.backing["userdata-qemu.img.qcow2"] = strings.ToUpper(filepath.Join(src.Dir, "userdata-qemu.img")) // any case + fake.backing["cache.img.qcow2"] = outside + res, err := m.Clone(context.Background(), 0, CloneRequest{}) + if err != nil { + t.Fatal(err) + } + dst := res.Instance.Path + if r := fake.ran("rebase"); len(r) != 1 || !strings.EqualFold(r[0][3], "userdata-qemu.img") || r[0][len(r[0])-1] != filepath.Join(dst, "userdata-qemu.img.qcow2") { + t.Errorf("rebase %v", r) + } + c := fake.ran("convert") + if len(c) != 1 || c[0][len(c[0])-2] != filepath.Join(src.Dir, "cache.img.qcow2") || c[0][len(c[0])-1] != filepath.Join(dst, "cache.img.qcow2") { + t.Errorf("convert %v", c) + } + if b, _ := os.ReadFile(filepath.Join(dst, "cache.img.qcow2")); string(b) != "flattened" { + t.Errorf("flattened copy %q", b) + } + + // internal snapshots in a disk: refused before anything is written + fake.snapshots = map[string]bool{"userdata-qemu.img.qcow2": true} + if _, err := m.Clone(context.Background(), 0, CloneRequest{}); errs.CodeOf(err) != errs.Unsupported { + t.Fatalf("snapshots: %v", err) + } + if left := instanceLeftovers(m.Root, 2); len(left) != 0 { + t.Errorf("snapshots: left %v", left) + } +} diff --git a/internal/emu/disk.go b/internal/emu/disk.go index 440fbc5..28bc9a6 100644 --- a/internal/emu/disk.go +++ b/internal/emu/disk.go @@ -519,6 +519,11 @@ func (m *Manager) qemuImgInfo(ctx context.Context, image string) (*qemuImgInfoRe if code != 0 { return nil, errs.Newf(errs.Internal, "qemu-img info 失败(退出码 %d): %s", code, qemuImgFail(so, se)) } + return decodeQemuImgInfo(so) +} + +// decodeQemuImgInfo reads the JSON object of `qemu-img info --output=json` (anything before its "{" is ignored). +func decodeQemuImgInfo(so []byte) (*qemuImgInfoResult, error) { start := bytes.IndexByte(so, '{') if start < 0 { return nil, errs.New(errs.Internal, "qemu-img info 没有输出 JSON") diff --git a/internal/i18n/locales/en/avd.json b/internal/i18n/locales/en/avd.json index f07a44f..7e265ef 100644 --- a/internal/i18n/locales/en/avd.json +++ b/internal/i18n/locales/en/avd.json @@ -14,6 +14,7 @@ "实例 %s 已存在": "Instance %s already exists", "实例 %s 的配置读不出": "Cannot read the configuration of instance %s", "实例标题不能包含换行": "The instance title cannot contain line breaks", + "实例目录 %s 不存在": "The instance folder %s does not exist", "实例目录 %s 是链接,不能跟着它删除": "Instance folder %s is a link; it will not be deleted through the link", "实例编号 %d 不可用(只能是 0–9,5 除外)": "Instance number %d is not available (must be 0-9, except 5)", "帧率只能在 %d–%d 之间": "Frame rate must be between %d and %d", diff --git a/internal/i18n/locales/en/cli.json b/internal/i18n/locales/en/cli.json index e5490ee..d78f39a 100644 --- a/internal/i18n/locales/en/cli.json +++ b/internal/i18n/locales/en/cli.json @@ -173,6 +173,7 @@ "声音 %v": "Sound %v", "声音:on 下次开机起带声卡、电脑出声(会多占一些 CPU),off 照旧不带(默认)": "Sound: on starts with a sound card from the next start and plays through the PC (uses some more CPU), off stays as before, without it (default)", "备注": "Notes", + "复制中 %d%%:%s": "Copying %d%%: %s", "复制电脑配置和实例里装的游戏": "Copy the PC configuration and the games installed in the instance", "多余的参数(%d 个)": "Extra arguments (%d)", "多余的参数:%s": "Extra arguments: %s", @@ -239,6 +240,7 @@ "已完成首次初始化": "Initial setup done", "已强制关机(先 sync 再结束)": "Force stopped (sync first, then ended)", "已把 %s 装到实例 %d": "Installed %s on instance %d", + "已把实例 %d 复制成%s,复制了 %.1f GB\n": "Copied instance %d to %s, %.1f GB copied\n", "已有:%s(版本 %s),跳过\n": "Already present: %s (version %s), skipped\n", "已正常关机": "Shut down normally", "已生效": "In effect", @@ -263,6 +265,7 @@ "待应用语言:%s\n": "Language to apply: %s\n", "截图共享内存": "Screenshot shared memory", "打成「ModAVD-问题信息-<时间>.zip」,默认放桌面,再打开资源管理器选中它(--no-explorer 不打开)。--stage-dir 是暂存目录的父目录(默认 %TEMP%),--keep-stage 保留暂存目录。每一节单独收,出错写进 summary.txt 接着收下一节。只读:不收磁盘镜像,不收 AUTO-MAS 的配置和账号数据,不起 adb server、不碰 5037。目前只支持 Windows。": "Packs a zip named \"ModAVD-problem-report-