Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ modavd [--root <dir>] [--json] [--quiet] [--verbose] <command> [args]
| `set <i> [--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.<i>.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 <i> [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 <i> --yes` | Delete a stopped instance, together with its game data |
| `clone <i> [--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 <i> [--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 <i> [--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 <i> 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) |
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数]
| `set <i> [--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.<i>.sound`。`--boss-key` 是这台的老板键(见「管理器 ModAVD.exe」一节),比如 `Ctrl+Alt+Shift+1`,`none` 是不要,只有 Windows。 |
| `proxy <i> [on\|off\|test] [--server URL\|auto] [--add 包名] [--remove 包名] [--apps 包名]` | 按应用走代理:名单里的应用走代理,其余直连(见下) |
| `delete <i> --yes` | 删除已关机的实例,连同游戏数据 |
| `clone <i> [--title T]` | 把已关机的实例整份复制成一台新实例(游戏、登录状态、设置都带上):新实例用最小的空闲编号和它的端口,其余设置照源实例;数据盘整份复制,两台互不影响,可用空间不够时报错(`precheck_failed`)、什么都不复制;失败或取消时复制到一半的会删掉。两台的安卓设备标识(Android ID、GSF ID)相同 |
| `start <i> [--window \| --headless] [--timeout 300] [--no-bridge]` | 开机(默认无头,`--window` 带窗口),等开完并做完开机后的设置,返回前确认 `/sdcard` 能写进文件(一般这时早已就绪;最多再等 60 秒,到点只警告);实例正在关机时(比如刚点了模拟器窗口的 ×)先等它关完(最多 30 秒)再开机;实例还没有执行桥时接着装上,`--no-bridge` 这次不装;装桥要冷启动一两次,带 `--window` 时这几次准备用的开机都无头,装好后正常关机,最后一次才带窗口开机(实例还没有开机标记、一定要装桥时,第一次开机就无头;有标记的要开起来才知道装没装,第一次照样带窗口)。运行中不换方式:实例已经在运行时,给了 `--window` / `--headless` 而它不是这种方式,就报错(退出码 5),不接管也不重启,要换先 `stop` 再 `start`;两个都不给就照原样接管 |
| `stop <i> [--force] [--cancel-create]`、`stop --all [--force]` | 关机:前台开着应用时先按 HOME,等 2 秒让它保存;再 sync,让安卓正常关机(前台应用先收到暂停、停止),不成再 sync + kill;`--force` 是 sync + 强杀。新建中默认拒绝,`--cancel-create` 显式取消;`--all` 也关闭新建中的实例,结果标记 `interrupted_create: true` |
| `bridge <i> install\|uninstall\|verify` | 装、卸、检查 arm64 执行桥;开机时会自动装,一般不用手动跑(见下) |
Expand Down
1 change: 1 addition & 0 deletions changelog.d/239-clone-instance.feat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
管理器和命令行能复制实例,新实例带着游戏、登录状态和设置 (ModAVD/ModAVD#239)
74 changes: 74 additions & 0 deletions internal/avd/avd.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.<i> becomes meta (replacing whatever was there), and mas_<i>.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_<i>.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
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/args_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
// proxy <i> [on|off] [--server URL|auto] [--add P] [--remove P] [--apps P] emu.AppProxyResult
// proxy <i> test emu.AppProxyTestResult
// delete <i> --yes emu.DeleteResult (without --yes: usage error)
// clone <i> [--title T] emu.CloneResult {source,instance,copied_bytes}
// start <i> [--window|--headless] [--timeout 300] emu.StartResult (running the other way than asked: busy)
// stop <i> [--force] emu.StopResult
// stop --all [--force] StopAllResult {"results":[StopResult],"failed":[{index,error}]}
Expand Down Expand Up @@ -133,6 +134,7 @@ type manager interface {
CreateSpaceError() 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)
Expand Down
31 changes: 31 additions & 0 deletions internal/cli/clone_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
31 changes: 31 additions & 0 deletions internal/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,17 @@ func init() {
final: true,
run: runDelete, human: humanDelete, exit: exitBatch,
},
{
name: "clone", args: "<i> [--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: "<i> [--window | --headless] [--timeout 300] [--no-bridge]", summary: "开机,等 Android 开完并做好开机后的设置",
details: "默认无头启动,--window 带窗口。运行中不能换:实例已经在运行(或正被另一次 start 开着)时," +
Expand Down Expand Up @@ -869,6 +880,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)
}

// ---- batch create and delete (ModAVD/ModAVD#240) ----------------------------------------------------------------

// InstanceFailure is one instance a batch create or delete did not do.
Expand Down
7 changes: 7 additions & 0 deletions internal/cli/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,13 @@ 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)
}

// formatCreateBatch: each new instance as create prints it, then the ones not made.
func formatCreateBatch(w io.Writer, r *CreateBatchResult) {
fmt.Fprintf(w, "新建了 %d 台,%d 台没建成\n", len(r.Results), len(r.Failed))
Expand Down
8 changes: 8 additions & 0 deletions internal/cli/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,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 {
Expand Down
Loading
Loading