diff --git a/README.en.md b/README.en.md index 0f1c3878..77944068 100644 --- a/README.en.md +++ b/README.en.md @@ -95,6 +95,7 @@ modavd [--root ] [--json] [--quiet] [--verbose] [args] - stdout has exactly one line: `{"ok":true,"data":…}` or `{"ok":false,"error":{"code","message","advice"}}`. The fields of `data` are in `internal/emu/types.go`, in snake_case, and all fields are always present. - Progress logs go to stderr, one JSON object per line: `{"time","level","msg"}`. Callers must not merge stderr into stdout. - `protocol` in `version --json` is the contract version; it is incremented only when a command or a field is removed or changes meaning. From 0.3.0 it is 2: `restart` is gone, `start` takes `--headless`, a running instance asked to start the other way (window / headless) fails with `busy` instead of being taken over, and the fields `window` and `creation_progress` were added; up to 0.2.0 it was 1. +- **Ports** (from 0.3.1): `port_base` in `list` and `check` is the port range the root folder actually uses (see `portBase` under "Conventions" below), and `status` now also gives `serial`, `adb_address` and `ports` (`list` and `info` always had them, for stopped instances too). Scripts that connect to an instance should take these fields instead of computing 20000 + 10 × index. An older modavd without `port_base` only uses the 20000 range. - Running instances gain `started_at_ms` (Unix milliseconds); the original `started_at` stays. `window` (from 0.3.0) is `true` while it runs with the emulator window, `false` when headless or not running. `stop --all` returns `ok:true` and the result list even if some instances failed, and exits with the exit code of the first failure. - **Create (from 0.2.0)**: after creating the files, `create` starts the instance once in the background, headless, and finishes the post-boot setup, the host IME, first-boot initialization and the execution bridge (with one or two cold boots in between). Then it syncs first, shuts down cleanly and confirms that qemu has exited; only then is creation complete. This usually takes a few minutes (`--timeout` covers the whole process, default 1200 seconds; at the deadline it shuts down cleanly first and then records a failure). After that, the first `start` is as fast as usual. Instances created before 0.2.0 are unaffected and still finish this at their first `start`. - During this, `status` in `status` / `list` / `info` is `creating` and `busy` is `creating` (`running` / `booted` of that boot may be `true`; go by `status`), and `creation_progress` (from 0.3.0) is the percentage done (0–100, counted by the steps done, not by time); `start`, `set`, `bridge`, `delete` and a `create` with the same index return instance busy (exit code 5). `stop` is not refused: it ends the creation (recorded as failed). @@ -107,6 +108,11 @@ modavd [--root ] [--json] [--quiet] [--verbose] [args] **Conventions** (the same as AUTO-MAS): - adb only uses the root folder's private server (`adbServerPort` in `mas-avd.json`, default 20050) and never touches 5037. +- Ports: the console port of instance i is 20000 + 10 × i, adb is 1 more and gRPC 2 more; the index is 0–9 without 5. + - A root folder for development or testing can move to its own port range with `"portBase": 21000` in `mas-avd.json` (a key of modavd's own; AUTO-MAS does not know it). Its instances then do not fight over ports with the instances of the same index in the root folder in daily use on the same computer (for example the one AUTO-MAS manages), and are not taken for them. + - `portBase` can only be 20000, or a multiple of 100 between 1100 and 65400. With another range, both `adbServerPort` and `scriptAdbServerPort` must be set, and neither can be 20049 or 20050 or fall on an instance port of the 20000 range. + - When it is not valid, `status`, `list` and `info` still read the instances in the 20000 range, while starting and creating are refused (`invalid_argument`), and `check` shows a 「端口段」 (port range) row saying why. + - Shut down every instance of the root folder before you change it. Do not add a root folder that sets `portBase` to AUTO-MAS. - The emulator, the adb server and logcat are all launched through an intermediate process that exits immediately, so they are not in modavd's process tree: if the caller ends modavd (Ctrl+C, the MCP client disconnects), the emulator is not taken down with it. - After a successful start, each instance also gets a boot guardian that is likewise outside the process tree and exits when qemu exits. After the guest restarts on its own (qemu keeps running), the guardian redoes the post-boot tuning and the Vulkan patch, and never launches a new emulator. - Starts and shutdowns of the same instance queue on `\avd\.mas_.{start,boot,stop}.lock`: a start waits for the previous start and shutdown to finish; a shutdown can interrupt an instance that is starting. diff --git a/README.md b/README.md index 23398230..e49cbd03 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] - stdout 只有一行:`{"ok":true,"data":…}` 或 `{"ok":false,"error":{"code","message","advice"}}`。`data` 的字段见 `internal/emu/types.go`,snake_case,所有字段一直出现。 - 进度日志写 stderr,一行一个 JSON:`{"time","level","msg"}`。调用方不要把 stderr 并进 stdout。 - `version --json` 的 `protocol` 是契约版本,命令或字段删了、改了含义才加一。0.3.0 起是 2:去掉了 `restart`,`start` 加了 `--headless`,运行中的实例和要的开机方式不一样时报 `busy`、不再接管,加了 `window`、`creation_progress` 字段;0.2.0 及以前是 1。 +- **端口**(0.3.1 起):`list`、`check` 的 `port_base` 是这个根目录实际用的端口段(见下面「约定」里的 `portBase`),`status` 也带上了 `serial`、`adb_address`、`ports`(`list`、`info` 本来就有,关机的实例也有)。脚本要连实例时用这几个字段,不要自己按 20000 + 10 × 编号算。没有 `port_base` 的旧版 modavd 只会用 20000 段。 - 运行中的实例增加 `started_at_ms`(Unix 毫秒),原来的 `started_at` 保留。`window`(0.3.0 起):带窗口运行时为 `true`,无头运行或没开机时为 `false`。`stop --all` 即使部分失败也返回 `ok:true` 和结果列表,同时以第一个失败的退出码结束。 - **新建(0.2.0 起)**:`create` 建好文件后在后台无头开机一次,做完开机设置、宿主输入法、首次初始化和执行桥(中间冷启动一两次),再先 sync 后正常关机、确认 qemu 退出,才算新建完成,一般几分钟(`--timeout` 管整个过程,默认 1200 秒,到点先正常关机再记为失败)。之后第一次 `start` 和平常一样快。0.2.0 以前建的实例不受影响,照旧在第一次 `start` 时补做。 - 这期间 `status` / `list` / `info` 的 `status` 是 `creating`、`busy` 是 `creating`(这次开机的 `running` / `booted` 可能是 `true`,以 `status` 为准),`creation_progress`(0.3.0 起)是做完的百分比(0–100,按做完的步骤算,不是按时间);`start`、`set`、`bridge`、`delete`、同编号的 `create` 返回实例忙(退出码 5)。`stop` 不拦,等于中止新建(记为失败)。 @@ -107,6 +108,11 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] **约定**(和 AUTO-MAS 一致): - adb 只走根目录的私有 server(`mas-avd.json` 的 `adbServerPort`,默认 20050),不碰 5037。 +- 端口:实例 i 的控制台端口是 20000 + 10 × i,adb 加 1、gRPC 加 2,编号 0–9、不含 5。 + - 开发、测试用的根目录可以在 `mas-avd.json` 里写 `"portBase": 21000`,换一段端口(这是 modavd 自己的键,AUTO-MAS 不认)。这样它的实例不会和同一台电脑上日常用的根目录(比如 AUTO-MAS 管的那个)里同编号的实例抢端口,也不会被认成那一台。 + - `portBase` 只能是 20000,或者 1100–65400 之间 100 的整数倍。设了别的端口段,`adbServerPort`、`scriptAdbServerPort` 都要配上,而且不能是 20049、20050,也不能落在 20000 段的实例端口上。 + - 不合规时,`status`、`list`、`info` 照常按 20000 段看,开机和新建都拒绝(`invalid_argument`),`check` 多一行「端口段」说明原因。 + - 改之前先关掉这个根目录的所有实例。设了 `portBase` 的根目录不要加进 AUTO-MAS。 - 模拟器、adb server、logcat 都经一个立即退出的中间进程拉起,不在 modavd 的进程树里:调用方结束 modavd(Ctrl+C、MCP 客户端断开)不会带走模拟器。 - 开机成功后,每台实例另有一个同样不在进程树里的开机守护,随 qemu 退出而结束。客体自己重启(qemu 没退)后,它补做开机调优和 Vulkan 补丁,绝不拉起新的模拟器。 - 同一实例的开机、关机按 `<根>\avd\.mas_.{start,boot,stop}.lock` 排队:开机等前一次开机和关机做完;关机可以打断正在开机的实例。 diff --git a/internal/adb/adb.go b/internal/adb/adb.go index b3fc993a..271c9926 100644 --- a/internal/adb/adb.go +++ b/internal/adb/adb.go @@ -276,7 +276,8 @@ func sleepCtx(ctx context.Context, d time.Duration) bool { // the port, and waits up to timeout until it listens (polling the listener table every 100 ms, not waiting for the // start-server client, which takes ~2.1 s; a client that exits non-zero while the port is still closed = failed). // Returns whether it listens. A listener whose process name is not adb.exe is errs.PortConflict with the AUTO-MAS -// message (change adbServerPort in mas-avd.json); an unreadable owner name counts as adb. +// message (change adbServerPort in mas-avd.json); an unreadable owner name counts as adb. A root whose mas-avd.json +// ports root.CheckPorts refuses gets that errs.InvalidArgument error, before anything is looked at or started. func (c *Client) EnsureServer(ctx context.Context, timeout time.Duration) (bool, error) { return c.ensure(ctx, privateServer, c.Root.AdbServerPort(), timeout) } @@ -287,6 +288,12 @@ func (c *Client) EnsureScriptServer(ctx context.Context, timeout time.Duration) } func (c *Client) ensure(ctx context.Context, k serverKind, port int, timeout time.Duration) (bool, error) { + // Every adb run of this root comes through here first (Run, servers, the adb passthrough, status). A root with a + // port plan of its own whose servers are left on the production ones (20050 / 20049, the defaults) must neither + // start nor use those (ModAVD/ModAVD#75); a root without portBase always passes. + if err := c.Root.CheckPorts(); err != nil { + return false, err + } up, pid, name, err := listener(port) if err != nil { return false, err @@ -534,8 +541,8 @@ func serialLock(serial string) chan struct{} { return l.(chan struct{}) } -// consolePortOf maps emulator- to the console port when it is one of our port plan. -func consolePortOf(serial string) (int, bool) { +// consolePortOf maps emulator- to the console port when it is one of plan's. +func consolePortOf(plan root.PortPlan, serial string) (int, bool) { rest, ok := strings.CutPrefix(serial, "emulator-") if !ok || rest == "" || len(rest) > 6 { return 0, false @@ -549,18 +556,21 @@ func consolePortOf(serial string) (int, bool) { if err != nil { return 0, false } - if _, ok := root.IndexOfConsolePort(port); !ok { + if _, ok := plan.IndexOfConsole(port); !ok { return 0, false } return port, true } // Reregister brings serial back onto the private server (AUTO-MAS reregister_emulator): only for emulator- -// serials of our port plan, not while Booting(serial), only when QemuOnAdbPort finds the instance's own qemu (of this -// root) and it is at least 60 s old; then get-state, Register, and up to 5 s of get-state == "device". Serialized per -// serial within this process. Starts OnReregistered on success. +// serials of the root's port plan, not while Booting(serial), only when QemuOnAdbPort finds the instance's own qemu (of +// this root) and it is at least 60 s old; then get-state, Register, and up to 5 s of get-state == "device". +// Serialized per serial within this process. Starts OnReregistered on success. func (c *Client) Reregister(ctx context.Context, serial string) bool { - console, ok := consolePortOf(serial) + if c.Root == nil { + return false // no root, no instance of its own (QemuOnAdbPort says so too) + } + console, ok := consolePortOf(c.Root.Ports(), serial) if !ok || (c.Booting != nil && c.Booting(serial)) { return false } @@ -709,14 +719,18 @@ func (c *Client) registerForClose(ctx context.Context, console int, started time var qemuOnAdbPort = QemuOnAdbPort // QemuOnAdbPort is the process listening on console+1 when it is qemu-system* with "-ports ," -// and "-avd mas_" (i from the console port) on its command line, and QemuBelongsTo says it is instance i of r. +// and "-avd mas_" (i from the console port, in r's port plan) on its command line, and QemuBelongsTo says it is +// instance i of r. // // Somebody listening is not enough: the port may belong to another program, and registering it would hand that // program's port to the private server. Nor are the arguments: the same-numbered instance of another root has the // same ones, and registering it would put one emulator on two private servers. func QemuOnAdbPort(r *root.Root, console int) (win.Process, bool) { - i, ok := root.IndexOfConsolePort(console) - if !ok || r == nil { + if r == nil { + return win.Process{}, false + } + i, ok := r.Ports().IndexOfConsole(console) + if !ok { return win.Process{}, false } pid, up, err := win.ListenerPID(console + 1) diff --git a/internal/adb/adb_test.go b/internal/adb/adb_test.go index e0e9f8c4..8802b59f 100644 --- a/internal/adb/adb_test.go +++ b/internal/adb/adb_test.go @@ -15,6 +15,7 @@ import ( "modavd/internal/errs" "modavd/internal/root" + "modavd/internal/win" ) // tempDir is a fresh directory for one test, removed afterwards: under $MODAVD_TEST_TMP\adb when that is set (to keep @@ -140,15 +141,23 @@ func TestDeviceMissing(t *testing.T) { } func TestConsolePortOf(t *testing.T) { + def, dev := root.PortPlan{Base: root.DefaultPortBase}, root.PortPlan{Base: 21000} ok := map[string]int{"emulator-20000": 20000, "emulator-20040": 20040, "emulator-20090": 20090} for serial, want := range ok { - if got, found := consolePortOf(serial); !found || got != want { + if got, found := consolePortOf(def, serial); !found || got != want { t.Errorf("consolePortOf(%q) = %d, %v; want %d", serial, got, found, want) } + // another root's plan: the production root's serials are not this root's + if got, found := consolePortOf(dev, serial); found { + t.Errorf("plan 21000: consolePortOf(%q) = %d, want not ours", serial, got) + } + } + if got, found := consolePortOf(dev, "emulator-21060"); !found || got != 21060 { + t.Errorf("plan 21000: consolePortOf(emulator-21060) = %d, %v", got, found) } for _, serial := range []string{"emulator-", "emulator-5554", "emulator-20001", "emulator-20100", "emulator-2000x", "emulator-+20000", "127.0.0.1:20001", "EMULATOR-20000", "emulator-0000000020000"} { - if got, found := consolePortOf(serial); found { + if got, found := consolePortOf(def, serial); found { t.Errorf("consolePortOf(%q) = %d, want not ours", serial, got) } } @@ -192,10 +201,59 @@ func TestQemuOnAdbPortNotOurs(t *testing.T) { if !root.ValidIndex(i) { continue } - if p, ok := QemuOnAdbPort(r, root.ConsolePort(i)); ok { - t.Errorf("QemuOnAdbPort(%d) on a fresh root = pid %d", root.ConsolePort(i), p.PID) + if p, ok := QemuOnAdbPort(r, r.Ports().Console(i)); ok { + t.Errorf("QemuOnAdbPort(%d) on a fresh root = pid %d", r.Ports().Console(i), p.PID) + } + } +} + +// TestEnsureServerPortPlan: a root with a port plan of its own whose adb servers are still the production ones is +// refused before any listener is looked at or any server started (ModAVD/ModAVD#75); so is every adb run through it. +func TestEnsureServerPortPlan(t *testing.T) { + dir := tempDir(t) + if err := os.WriteFile(filepath.Join(dir, root.MetadataFile), []byte(`{"portBase": 21000}`), 0o644); err != nil { + t.Fatal(err) + } + r := &root.Root{Dir: dir} + c := New(r, nil) + ctx := context.Background() + for name, ensure := range map[string]func(context.Context, time.Duration) (bool, error){ + "EnsureServer": c.EnsureServer, "EnsureScriptServer": c.EnsureScriptServer, + } { + if up, err := ensure(ctx, time.Second); up || errs.CodeOf(err) != errs.InvalidArgument { + t.Errorf("%s = %v, %v; want invalid_argument", name, up, err) } } + if res := c.Run(ctx, RunOptions{Serial: "emulator-21060", Timeout: time.Second}, "get-state"); res.Code == 0 || + !strings.Contains(res.Out, "portBase") { + t.Errorf("Run = %+v", res) + } +} + +// TestReregisterPortPlan: on a root with portBase 21000, emulator-21060 is its instance 6 (the qemu check is asked +// about console 21060) and emulator-20060, the production root's, is not looked at. +func TestReregisterPortPlan(t *testing.T) { + dir := tempDir(t) + meta := `{"portBase": 21000, "adbServerPort": 21099, "scriptAdbServerPort": 21098}` + if err := os.WriteFile(filepath.Join(dir, root.MetadataFile), []byte(meta), 0o644); err != nil { + t.Fatal(err) + } + var asked []int + saved := qemuOnAdbPort + qemuOnAdbPort = func(_ *root.Root, console int) (win.Process, bool) { + asked = append(asked, console) + return win.Process{}, false + } + t.Cleanup(func() { qemuOnAdbPort = saved }) + c := New(&root.Root{Dir: dir}, nil) + for _, serial := range []string{"emulator-21060", "emulator-20060"} { + if c.Reregister(context.Background(), serial) { + t.Errorf("Reregister(%s) = true without a qemu", serial) + } + } + if len(asked) != 1 || asked[0] != 21060 { + t.Errorf("qemu looked up for consoles %v, want [21060]", asked) + } } func TestReregisterGuards(t *testing.T) { diff --git a/internal/avd/avd.go b/internal/avd/avd.go index 54c1688d..5eee38b4 100644 --- a/internal/avd/avd.go +++ b/internal/avd/avd.go @@ -685,20 +685,21 @@ func pathExists(path string) bool { return err == nil } -// FreeIndex is the smallest valid index that has no instance and whose three ports busy() reports free. -// errs.Busy "魔改 AVD 实例已满(端口段 20000–20100 最多 9 台)" when there is none. A nil busy skips the port check. -func FreeIndex(existing map[int]bool, busy func(ports []int) []int) (int, error) { +// FreeIndex is the smallest valid index that has no instance and whose three ports in plan busy() reports free. +// errs.Busy "魔改 AVD 实例已满(端口段 20000–20100 最多 9 台)" (the root's plan) when there is none. A nil busy skips +// the port check. +func FreeIndex(plan root.PortPlan, existing map[int]bool, busy func(ports []int) []int) (int, error) { for i := 0; i <= root.MaxIndex; i++ { if !root.ValidIndex(i) || existing[i] { continue } - c := root.ConsolePort(i) + c := plan.Console(i) if busy != nil && len(busy([]int{c, c + 1, c + 2})) > 0 { continue } return i, nil } - return 0, errs.New(errs.Busy, "魔改 AVD 实例已满(端口段 20000–20100 最多 9 台)") + return 0, errs.Newf(errs.Busy, "魔改 AVD 实例已满(端口段 %d–%d 最多 9 台)", plan.Base, plan.Base+100) } type UpdateOptions struct { diff --git a/internal/avd/avd_test.go b/internal/avd/avd_test.go index 2a566474..bc3225d5 100644 --- a/internal/avd/avd_test.go +++ b/internal/avd/avd_test.go @@ -783,31 +783,42 @@ func TestFreeIndex(t *testing.T) { } return nil } - i, err := FreeIndex(map[int]bool{0: true, 2: true}, busy) + def := root.PortPlan{Base: root.DefaultPortBase} + i, err := FreeIndex(def, map[int]bool{0: true, 2: true}, busy) if err != nil || i != 4 { t.Fatalf("FreeIndex = %d %v", i, err) } if fmt.Sprint(asked) != "[[20010 20011 20012] [20030 20031 20032] [20040 20041 20042]]" { t.Fatalf("asked %v", asked) } - if i, err := FreeIndex(nil, nil); err != nil || i != 0 { + if i, err := FreeIndex(def, nil, nil); err != nil || i != 0 { t.Fatalf("empty: %d %v", i, err) } all := map[int]bool{} for k := 0; k <= 9; k++ { all[k] = k != 7 } - if i, err := FreeIndex(all, nil); err != nil || i != 7 { + if i, err := FreeIndex(def, all, nil); err != nil || i != 7 { t.Fatalf("only 7 free: %d %v", i, err) } - _, err = FreeIndex(all, func(ports []int) []int { return ports }) + _, err = FreeIndex(def, all, func(ports []int) []int { return ports }) wantCode(t, err, errs.Busy) if err.Error() != "魔改 AVD 实例已满(端口段 20000–20100 最多 9 台)" { t.Fatalf("message %v", err) } + // another plan: the ports asked about and the message are the plan's + asked = nil + if i, err := FreeIndex(root.PortPlan{Base: 21000}, map[int]bool{0: true}, busy); err != nil || i != 1 || + fmt.Sprint(asked) != "[[21010 21011 21012]]" { + t.Fatalf("plan 21000: FreeIndex = %d %v, asked %v", i, err, asked) + } + _, err = FreeIndex(root.PortPlan{Base: 21000}, all, func(ports []int) []int { return ports }) + if err == nil || err.Error() != "魔改 AVD 实例已满(端口段 21000–21100 最多 9 台)" { + t.Fatalf("plan 21000: message %v", err) + } all[7] = true all[5] = false // 5 is never free - _, err = FreeIndex(all, nil) + _, err = FreeIndex(def, all, nil) wantCode(t, err, errs.Busy) } diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 5e8c9515..f0040753 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -9,7 +9,7 @@ // // list emu.ListResult // info emu.InstanceInfo -// status StatusResult {index,name,status,running,booted,window,busy,pid,creation,creation_error,creation_log,creation_progress} +// status StatusResult {index,name,status,running,booted,window,busy,pid,creation,creation_error,creation_log,creation_progress,serial,adb_address,ports} // create [--index N] [--title T] [--memory M] [--cpu N] [--data-gb N] [--fps 30|60] emu.InstanceInfo // set [--title T] [--memory M] [--cpu N] [--fps F] emu.UpdateResult (at least one option) // delete --yes emu.DeleteResult (without --yes: usage error) diff --git a/internal/cli/commands.go b/internal/cli/commands.go index c2002b19..a760759c 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -352,6 +352,11 @@ type StatusResult struct { CreationLog string `json:"creation_log"` // CreationProgress: 0–100 while status is creating (emu.InstanceInfo.CreationProgress) CreationProgress int `json:"creation_progress"` + // Where to reach the instance, in its root's port plan (mas-avd.json portBase): take these rather than counting + // from 20000 (ModAVD/ModAVD#75). + Serial string `json:"serial"` + AdbAddress string `json:"adb_address"` + Ports emu.Ports `json:"ports"` } // ErrorInfo is an error in JSON: the envelope's "error" and each stop --all failure. @@ -508,7 +513,7 @@ func intPtrOpt(inv *invocation, name string) *int { func statusOf(in *emu.InstanceInfo) *StatusResult { return &StatusResult{Index: in.Index, Name: in.Name, Status: in.Status, Running: in.Running, Booted: in.Booted, Window: in.Window, Busy: in.Busy, PID: in.PID, Creation: in.Creation, CreationError: in.CreationError, CreationLog: in.CreationLog, - CreationProgress: in.CreationProgress} + CreationProgress: in.CreationProgress, Serial: in.Serial, AdbAddress: in.AdbAddress, Ports: in.Ports} } // ---- run functions ----------------------------------------------------------------------------------------------- diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index c8ddfed8..8acc75fe 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -59,10 +59,11 @@ func (f *fakeManager) callList() []string { } func sampleInstance(i int) emu.InstanceInfo { + p := root.PortPlan{Base: root.DefaultPortBase} return emu.InstanceInfo{ Index: i, Name: root.AvdName(i), Title: root.AvdName(i), Status: emu.StatusOffline, - Serial: root.Serial(i), AdbAddress: "127.0.0.1:" + itoa(root.AdbPort(i)), - Ports: emu.Ports{Console: root.ConsolePort(i), Adb: root.AdbPort(i), Grpc: root.GrpcPort(i)}, + Serial: p.Serial(i), AdbAddress: "127.0.0.1:" + itoa(p.Adb(i)), + Ports: emu.Ports{Console: p.Console(i), Adb: p.Adb(i), Grpc: p.Grpc(i)}, Config: emu.InstanceConfig{MemoryMB: 6144, CPU: 6, FPS: 60, DataPartitionGB: 64, Width: 1280, Height: 720, DPI: 240}, Path: `D:\r\avd\` + root.AvdName(i) + ".avd", } @@ -953,13 +954,15 @@ func TestStatusSubset(t *testing.T) { return &in, nil } r := h.run(t, nil, "status", "3", "--json") - want := `{"ok":true,"data":{"index":3,"name":"mas_3","status":"online","running":true,"booted":true,"window":true,"busy":"stopping","pid":4242,"creation":"","creation_error":"","creation_log":"","creation_progress":0}}` + "\n" + // where to reach it comes along (ModAVD/ModAVD#75): a root with portBase is not on 20000 + 10 * i + const at = `"serial":"emulator-20030","adb_address":"127.0.0.1:20031","ports":{"console":20030,"adb":20031,"grpc":20032}` + want := `{"ok":true,"data":{"index":3,"name":"mas_3","status":"online","running":true,"booted":true,"window":true,"busy":"stopping","pid":4242,"creation":"","creation_error":"","creation_log":"","creation_progress":0,` + at + `}}` + "\n" if r.stdout != want { t.Errorf("stdout = %s\nwant %s", r.stdout, want) } h.fake.info = nil r = h.run(t, nil, "status", "3", "--json") - want = `{"ok":true,"data":{"index":3,"name":"mas_3","status":"offline","running":false,"booted":false,"window":false,"busy":"","pid":0,"creation":"","creation_error":"","creation_log":"","creation_progress":0}}` + "\n" + want = `{"ok":true,"data":{"index":3,"name":"mas_3","status":"offline","running":false,"booted":false,"window":false,"busy":"","pid":0,"creation":"","creation_error":"","creation_log":"","creation_progress":0,` + at + `}}` + "\n" if r.stdout != want { t.Errorf("offline stdout = %s", r.stdout) } @@ -971,7 +974,7 @@ func TestStatusSubset(t *testing.T) { return &in, nil } r = h.run(t, nil, "status", "3", "--json") - want = `{"ok":true,"data":{"index":3,"name":"mas_3","status":"creating","running":true,"booted":true,"window":false,"busy":"creating","pid":4242,"creation":"creating","creation_error":"","creation_log":"","creation_progress":35}}` + "\n" + want = `{"ok":true,"data":{"index":3,"name":"mas_3","status":"creating","running":true,"booted":true,"window":false,"busy":"creating","pid":4242,"creation":"creating","creation_error":"","creation_log":"","creation_progress":35,` + at + `}}` + "\n" if r.stdout != want { t.Errorf("creating stdout = %s", r.stdout) } diff --git a/internal/emu/adbcmd.go b/internal/emu/adbcmd.go index b5755598..4943ab33 100644 --- a/internal/emu/adbcmd.go +++ b/internal/emu/adbcmd.go @@ -13,7 +13,6 @@ import ( "time" "modavd/internal/errs" - "modavd/internal/root" "modavd/internal/win" ) @@ -51,7 +50,7 @@ func (m *Manager) AdbPassthrough(ctx context.Context, i int, args []string, stdi if !up { return 1, errs.Newf(errs.Internal, "私有 adb server(端口 %d)%.0f 秒内没起来", m.Root.AdbServerPort(), passthroughServerWait.Seconds()) } - serial := root.Serial(i) + serial := m.Root.Ports().Serial(i) // What adb.Run does on "device not found": bring a running instance back onto a restarted private server. if _, running := m.qemuOf(i); running && m.ADB.GetState(ctx, serial, statusAdbTimeout) != "device" { m.ADB.Reregister(ctx, serial) diff --git a/internal/emu/affinity_test.go b/internal/emu/affinity_test.go index 0f0d4dff..1dcf918a 100644 --- a/internal/emu/affinity_test.go +++ b/internal/emu/affinity_test.go @@ -4,6 +4,7 @@ import ( "slices" "testing" + "modavd/internal/root" "modavd/internal/win" ) @@ -230,7 +231,7 @@ func TestQemuCoresCommandLine(t *testing.T) { {[]string{"qemu.exe", "-cores", "0"}, 6}, {[]string{"qemu.exe", "-cores"}, 6}, } { - if got := m.qemuCores(win.Process{}, c.cmdline, nil, 6); got != c.want { + if got := m.qemuCores(win.Process{}, c.cmdline, nil, root.PortPlan{}, 6); got != c.want { t.Errorf("%v: %d, want %d", c.cmdline, got, c.want) } } diff --git a/internal/emu/afterboot.go b/internal/emu/afterboot.go index 2ea06525..286a2001 100644 --- a/internal/emu/afterboot.go +++ b/internal/emu/afterboot.go @@ -82,7 +82,8 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe prog *progressor) (afterBootResult, error) { var r afterBootResult i := inst.Index - port := root.ConsolePort(i) + ports := m.Root.Ports() + port := ports.Console(i) var imeDefault bool cores, ok := inst.CPU() if !ok || cores <= 0 { @@ -115,11 +116,11 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe // 3) disk and screenshot channel state into the log (write_cache is root-only) wc := m.su(ctx, i, "cat /sys/block/vd*/queue/write_cache | sort -u", 0) shm := "缺失" - if win.SharedMemoryExists(shmName(i)) { + if win.SharedMemoryExists(shmName(ports, i)) { shm = "在" } m.Log.Infof("实例 %d 磁盘缓存: %s;截图共享内存 %s: %s", i, orText(joinNonEmptyLines(wc.Out, " / "), "读不到"), - shmName(i), shm) + shmName(ports, i), shm) }, // 3b) data partition raised by `set --data-gb`: the emulator grew the disk, grow the file system (online) func() { m.growData(ctx, i) }, @@ -290,8 +291,10 @@ func (m *Manager) otherQemus(self win.Process, cores int) []otherQemu { return nil } var insts []*avd.Instance + var plan root.PortPlan if m.Root != nil { insts, _ = avd.List(m.Root) + plan = m.Root.Ports() } var out []otherQemu for _, q := range procs { @@ -303,17 +306,17 @@ func (m *Manager) otherQemus(self win.Process, cores int) []otherQemu { o.Mask = mask } if cmdline, err := q.CommandLine(); err == nil { - o.Cores = m.qemuCores(q, cmdline, insts, cores) + o.Cores = m.qemuCores(q, cmdline, insts, plan, cores) } out = append(out, o) } return out } -// qemuCores is the vCPU count of qemu q (see otherQemus). -func (m *Manager) qemuCores(q win.Process, cmdline []string, insts []*avd.Instance, def int) int { +// qemuCores is the vCPU count of qemu q (see otherQemus); insts are this root's instances, plan its port plan. +func (m *Manager) qemuCores(q win.Process, cmdline []string, insts []*avd.Instance, plan root.PortPlan, def int) int { for _, in := range insts { - if cmdlineMatches(cmdline, root.AvdName(in.Index), root.ConsolePort(in.Index)) && + if cmdlineMatches(cmdline, root.AvdName(in.Index), plan.Console(in.Index)) && adb.QemuBelongsTo(m.Root, q, in.Index) { if n, ok := in.CPU(); ok && n > 0 { return n diff --git a/internal/emu/bootwatch.go b/internal/emu/bootwatch.go index e0d45b31..29a97552 100644 --- a/internal/emu/bootwatch.go +++ b/internal/emu/bootwatch.go @@ -71,7 +71,7 @@ func (m *Manager) guestBoot(ctx context.Context, i int, reregister bool) (booted if guestBootRead != nil { return guestBootRead(i, reregister) } - serial := root.Serial(i) + serial := m.Root.Ports().Serial(i) res := m.ADB.Run(ctx, adb.RunOptions{Serial: serial, Timeout: guestBootTimeout, Reregister: reregister}, "shell", guestBootScript) booted, bootID = parseGuestBoot(res.Out) diff --git a/internal/emu/bridge.go b/internal/emu/bridge.go index c2bae226..d3f88663 100644 --- a/internal/emu/bridge.go +++ b/internal/emu/bridge.go @@ -275,7 +275,7 @@ func (m *Manager) runBridgeScript(ctx context.Context, i int, action string, reb WithAdvice("用完整的新包覆盖解压一次") } quote := func(s string) string { return "'" + strings.ReplaceAll(s, "'", "''") + "'" } - call := []string{"&", quote(script), action, "-Serial", quote(root.Serial(i)), + call := []string{"&", quote(script), action, "-Serial", quote(m.Root.Ports().Serial(i)), "-AdbPort", strconv.Itoa(m.Root.AdbServerPort()), "-Adb", quote(m.Root.AdbExe()), "-Payload", quote(m.bridgePayloadDir())} if reboot { diff --git a/internal/emu/check.go b/internal/emu/check.go index ac385282..ea421e2d 100644 --- a/internal/emu/check.go +++ b/internal/emu/check.go @@ -74,6 +74,9 @@ func (m *Manager) Check(ctx context.Context, opt CheckOptions) (*CheckResult, er m.diskItemNow(), memoryItemNow(memoryMB), } + if it, ok := portsItem(m.Root.Ports(), m.Root.CheckPorts()); ok { + items = append(items[:1], append([]CheckItem{it}, items[1:]...)...) + } res := &CheckResult{RootInfo: m.rootInfo(), Ready: true, Items: items, Components: ComponentStatuses(comps)} if _, failed := firstBlockingFailure(items); failed { res.Ready = false @@ -207,6 +210,22 @@ func pathItem(dir string) CheckItem { } } +// portsItem is the root's own port plan (ModAVD/ModAVD#75), right after the path; only for a root whose mas-avd.json +// sets one (a portBase other than 20000, or one that is not valid), so a root without it checks as before. bad is +// root.CheckPorts: a boot refuses those ports, so the item blocks. +func portsItem(plan root.PortPlan, bad *errs.Error) (CheckItem, bool) { + if bad == nil && plan.Base == root.DefaultPortBase { + return CheckItem{}, false + } + it := CheckItem{ID: "ports", Title: "端口段", Blocking: true} + if bad != nil { + it.OK, it.Reason, it.Advice = checkOK(false), bad.Message, bad.Advice + } else { + it.OK, it.Reason = checkOK(true), fmt.Sprintf("%d–%d(mas-avd.json 的 portBase)", plan.Base, plan.Last()) + } + return it, true +} + // requiredComponents are the components of the components item: required ones except the emulator, which has its // own item (AUTO-MAS REQUIRED_COMPONENTS = platform tools, system image). func requiredComponents(comps []root.ComponentStatus) []root.ComponentStatus { diff --git a/internal/emu/check_test.go b/internal/emu/check_test.go index b965a39d..08fedfb8 100644 --- a/internal/emu/check_test.go +++ b/internal/emu/check_test.go @@ -11,6 +11,23 @@ import ( "modavd/internal/root" ) +// TestPortsItem: no item for a root on the default plan; a plan of its own shows its range; what CheckPorts refuses +// blocks, with its message and advice. +func TestPortsItem(t *testing.T) { + if _, ok := portsItem(root.PortPlan{Base: root.DefaultPortBase}, nil); ok { + t.Error("an item for the default plan") + } + it, ok := portsItem(root.PortPlan{Base: 21000}, nil) + if !ok || it.ID != "ports" || it.OK == nil || !*it.OK || !it.Blocking || it.Reason != "21000–21092(mas-avd.json 的 portBase)" { + t.Errorf("plan 21000: %+v", it) + } + bad := errs.New(errs.InvalidArgument, "mas-avd.json 的 portBase 不合规").WithAdvice("改成 21000") + it, ok = portsItem(root.PortPlan{Base: root.DefaultPortBase}, bad) + if !ok || it.OK == nil || *it.OK || !it.Blocking || it.Reason != bad.Message || it.Advice != bad.Advice { + t.Errorf("refused: %+v", it) + } +} + func TestAccelSummaryAndOKText(t *testing.T) { // What emulator.exe -accel-check prints on a WHPX host (frame lines around the explanation). out := "accel:\r\n0\r\nWHPX(10.0.26200) is installed and usable.\r\naccel\r\n" diff --git a/internal/emu/crud.go b/internal/emu/crud.go index 7449d913..93cd191e 100644 --- a/internal/emu/crud.go +++ b/internal/emu/crud.go @@ -38,6 +38,10 @@ func (m *Manager) Create(ctx context.Context, req CreateRequest) (*InstanceInfo, if _, err := m.Root.EnsureMetadata(); err != nil { return nil, err } + // before any file is written: the setup boot would refuse these ports anyway (prepareLaunch) + if err := m.Root.CheckPorts(); err != nil { + return nil, err + } insts, err := avd.List(m.Root) if err != nil { return nil, err @@ -116,8 +120,12 @@ func (m *Manager) FreeIndex() (int, error) { return m.freeIndex(existing) } -// freeIndex is the smallest index that is not in existing, has no leftovers and whose ports are free. +// freeIndex is the smallest index that is not in existing, has no leftovers and whose ports (in the root's plan) are +// free; an errs.InvalidArgument error when mas-avd.json's ports are not ones to start with (root.CheckPorts). func (m *Manager) freeIndex(existing map[int]bool) (int, error) { + if err := m.Root.CheckPorts(); err != nil { + return 0, err + } // Leftovers of a half-deleted instance (an .ini or a directory without the other) do not count as instances, but // avd.Create refuses their index: skip them here instead of failing with "already exists" (Delete clears them). for k := 0; k <= root.MaxIndex; k++ { @@ -126,7 +134,7 @@ func (m *Manager) freeIndex(existing map[int]bool) (int, error) { } } var busyErr error - i, err := avd.FreeIndex(existing, func(ports []int) []int { + i, err := avd.FreeIndex(m.Root.Ports(), existing, func(ports []int) []int { busy, err := win.BusyPorts(ports) if err != nil { busyErr = err diff --git a/internal/emu/firstboot.go b/internal/emu/firstboot.go index 0f234c2d..988045b1 100644 --- a/internal/emu/firstboot.go +++ b/internal/emu/firstboot.go @@ -159,7 +159,7 @@ func (m *Manager) installLauncher(ctx context.Context, i int) string { if !regularFile(apkPath) { return "pixel" } - res := m.ADB.Run(ctx, adb.RunOptions{Serial: root.Serial(i), Timeout: installLauncherTimeout, Reregister: true}, + res := m.ADB.Run(ctx, adb.RunOptions{Serial: m.Root.Ports().Serial(i), Timeout: installLauncherTimeout, Reregister: true}, "install", "-r", apkPath) if res.Code != 0 || !strings.Contains(res.Out, "Success") { m.Log.Warnf("实例 %d 安装轻量桌面失败: %s", i, res.Out) diff --git a/internal/emu/ime.go b/internal/emu/ime.go index 92eaaa13..8303676c 100644 --- a/internal/emu/ime.go +++ b/internal/emu/ime.go @@ -13,7 +13,6 @@ import ( "modavd/internal/adb" "modavd/internal/apk" - "modavd/internal/root" ) // The host input method org.modavd.ime: the guest half of the emulator's modavd_ime channel; what the user types @@ -224,7 +223,8 @@ func (m *Manager) guestIO(ctx context.Context, i int) guestIO { return guestIO{ shell: func(command string, timeout time.Duration) adb.Result { return m.shell(ctx, i, command, timeout) }, adb: func(timeout time.Duration, args ...string) adb.Result { - return m.ADB.Run(ctx, adb.RunOptions{Serial: root.Serial(i), Timeout: timeout, Reregister: true}, args...) + return m.ADB.Run(ctx, adb.RunOptions{Serial: m.Root.Ports().Serial(i), Timeout: timeout, Reregister: true}, + args...) }, } } diff --git a/internal/emu/install.go b/internal/emu/install.go index b90c1b29..9c4a3500 100644 --- a/internal/emu/install.go +++ b/internal/emu/install.go @@ -11,7 +11,6 @@ import ( "modavd/internal/adb" "modavd/internal/apk" "modavd/internal/errs" - "modavd/internal/root" "modavd/internal/win" ) @@ -61,7 +60,7 @@ func (m *Manager) InstallAPK(ctx context.Context, i int, apkPath string) (*Insta } m.Log.Infof("魔改 AVD 实例 %d 安装 APK: %s", i, path) - res := m.ADB.Run(ctx, adb.RunOptions{Serial: root.Serial(i), Timeout: apkInstallTimeout, Reregister: true}, + res := m.ADB.Run(ctx, adb.RunOptions{Serial: m.Root.Ports().Serial(i), Timeout: apkInstallTimeout, Reregister: true}, "install", "-r", path) // The guest is done with the install: a waiting start may restart zygote now (reading the manifest below is local). guestLock.Unlock() diff --git a/internal/emu/launch.go b/internal/emu/launch.go index 8811fe50..48c8cb9c 100644 --- a/internal/emu/launch.go +++ b/internal/emu/launch.go @@ -75,17 +75,23 @@ type launchPlan struct { memoryMB int } -// prepareLaunch is AUTO-MAS _launch up to the Popen: components, host checks against the memory -memory will get, -// free ports, the private adb server, the fixed 720p display, old logs, the log file name. Errors stop the start. +// prepareLaunch is AUTO-MAS _launch up to the Popen: the root's ports, components, another root's instance on our +// ports, host checks against the memory -memory will get, then launchPlanFor. Errors stop the start. func (m *Manager) prepareLaunch(ctx context.Context, inst *avd.Instance, window bool) (*launchPlan, error) { i := inst.Index + // mas-avd.json's portBase and adb server ports (root.CheckPorts): nothing is started on ports that are not this + // root's to use. Every boot comes through here: start, create's setup, the bridge's cold boot. + if err := m.Root.CheckPorts(); err != nil { + return nil, err + } if missing := m.Root.Missing(); len(missing) > 0 { return nil, m.Root.MissingError(missing) } - // The same-numbered instance of another root (production D:\ModAVD next to a test root) runs on exactly our - // ports. Said before the host checks, which would otherwise fail first (it takes the memory) with a message that - // does not name the real cause. - if p, where, found := m.otherRootInstance(i); found { + ports := m.Root.Ports() + // The same-numbered instance of another root without a port plan of its own (production D:\ModAVD next to a test + // root that sets no portBase) runs on exactly our ports. Said before the host checks, which would otherwise fail + // first (it takes the memory) with a message that does not name the real cause. + if p, where, found := m.otherRootInstance(ports, i); found { return nil, otherRootBusy(i, p, where) } // the host check uses exactly the memory -memory passes below: the instance's own, not one guessed per game @@ -96,8 +102,14 @@ func (m *Manager) prepareLaunch(ctx context.Context, inst *avd.Instance, window if err := ctxErr(ctx); err != nil { return nil, err } + return m.launchPlanFor(ctx, inst, memoryMB, window) +} - port := root.ConsolePort(i) +// launchPlanFor is the rest of prepareLaunch, once the checks passed: the instance's ports in the root's plan (free?), +// the private adb server, the fixed 720p display, old logs, the log file name, the emulator's arguments. +func (m *Manager) launchPlanFor(ctx context.Context, inst *avd.Instance, memoryMB int, window bool) (*launchPlan, error) { + i := inst.Index + port := m.Root.Ports().Console(i) busy, err := win.BusyPorts([]int{port, port + 1, port + 2}) if err != nil { return nil, errs.Wrap(errs.Internal, err, fmt.Sprintf("魔改 AVD 实例 %d 读不出系统的 TCP 监听表: %v", i, err)) @@ -149,14 +161,14 @@ func (m *Manager) prepareLaunch(ctx context.Context, inst *avd.Instance, window return &launchPlan{args: args, logPath: logPath, memoryMB: memoryMB}, nil } -// otherRootInstance is the process listening on one of instance i's ports (console, adb, gRPC) when it is the -// same-numbered instance of another root: a qemu-system* whose command line has "-avd mas_" and "-ports -// ,..." (cmdlineMatches) that adb.QemuBelongsTo does not give to m.Root. where names that instance: the -// avd.dir of its emulator runtime file (in adb.EmulatorDiscoveryDir, where qemu writes it and adb.QemuBelongsTo +// otherRootInstance is the process listening on one of instance i's ports in plan (console, adb, gRPC) when it is the +// same-numbered instance of another root on the same ports: a qemu-system* whose command line has "-avd mas_" and +// "-ports ,..." (cmdlineMatches) that adb.QemuBelongsTo does not give to m.Root. where names that instance: +// the avd.dir of its emulator runtime file (in adb.EmulatorDiscoveryDir, where qemu writes it and adb.QemuBelongsTo // reads it), else its executable. found=false also when the listener table or a process cannot be read: the port // check after the host checks still reports busy ports. -func (m *Manager) otherRootInstance(i int) (p win.Process, where string, found bool) { - console := root.ConsolePort(i) +func (m *Manager) otherRootInstance(plan root.PortPlan, i int) (p win.Process, where string, found bool) { + console := plan.Console(i) ls, err := win.Listeners() if err != nil { return win.Process{}, "", false @@ -175,17 +187,17 @@ func (m *Manager) otherRootInstance(i int) (p win.Process, where string, found b if err != nil { continue } - if otherRootQemu(q, cmdline, i, func(q win.Process) bool { return adb.QemuBelongsTo(m.Root, q, i) }) { + if otherRootQemu(q, cmdline, i, console, func(q win.Process) bool { return adb.QemuBelongsTo(m.Root, q, i) }) { return q, qemuWhere(runtimeAvdDir(adb.EmulatorDiscoveryDir(), q), cmdline), true } } return win.Process{}, "", false } -// otherRootQemu: q (with its command line) is instance i of some root by name and ports, and ours says it is not -// m.Root's. -func otherRootQemu(q win.Process, cmdline []string, i int, ours func(win.Process) bool) bool { - return isQemuName(q.Name) && cmdlineMatches(cmdline, root.AvdName(i), root.ConsolePort(i)) && !ours(q) +// otherRootQemu: q (with its command line) is instance i of some root by name and console port, and ours says it is +// not m.Root's. +func otherRootQemu(q win.Process, cmdline []string, i, console int, ours func(win.Process) bool) bool { + return isQemuName(q.Name) && cmdlineMatches(cmdline, root.AvdName(i), console) && !ours(q) } // otherRootBusy is the error of a start whose ports the same-numbered instance of another root holds. diff --git a/internal/emu/launch_test.go b/internal/emu/launch_test.go index fa247e33..ba2e543a 100644 --- a/internal/emu/launch_test.go +++ b/internal/emu/launch_test.go @@ -155,7 +155,7 @@ func TestFileContains(t *testing.T) { // TestOtherRootQemu: only a qemu that is instance i by name and ports and that the root check gives to another root. func TestOtherRootQemu(t *testing.T) { - c := root.ConsolePort(3) + c := root.PortPlan{Base: root.DefaultPortBase}.Console(3) ports := strconv.Itoa(c) + "," + strconv.Itoa(c+1) qemu := win.Process{PID: 4242, Name: "qemu-system-x86_64-headless.exe", Created: 1} exe := `D:\ModAVD\sdk\emulator\qemu\windows-x86_64\qemu-system-x86_64-headless.exe` @@ -178,10 +178,14 @@ func TestOtherRootQemu(t *testing.T) { {"no arguments", qemu, nil, notOurs, false}, } for _, k := range cases { - if got := otherRootQemu(k.q, k.cmdline, 3, k.ours); got != k.want { + if got := otherRootQemu(k.q, k.cmdline, 3, c, k.ours); got != k.want { t.Errorf("%s: otherRootQemu = %v, want %v", k.name, got, k.want) } } + // a root with a plan of its own: the default root's mas_3 is not on its ports + if otherRootQemu(qemu, args, 3, root.PortPlan{Base: 21000}.Console(3), notOurs) { + t.Error("plan 21000: the default root's mas_3 counted as on our ports") + } } func TestOtherRootBusy(t *testing.T) { @@ -278,13 +282,14 @@ func TestOtherRootInstanceFreshRoot(t *testing.T) { t.Skip("set MODAVD_TEST_LIVE=1 to run tests that look at live emulators or start a real adb server") } m := markerTestManager(t) + plan := m.Root.Ports() for _, i := range []int{0, 1, 2, 3, 4, 6, 7, 8, 9} { - p, where, found := m.otherRootInstance(i) + p, where, found := m.otherRootInstance(plan, i) if !found { continue } cmdline, err := p.CommandLine() - if !isQemuName(p.Name) || where == "" || (err == nil && !cmdlineMatches(cmdline, root.AvdName(i), root.ConsolePort(i))) { + if !isQemuName(p.Name) || where == "" || (err == nil && !cmdlineMatches(cmdline, root.AvdName(i), plan.Console(i))) { t.Errorf("instance %d: reported %+v (%s)", i, p, where) } t.Logf("instance %d: another root's qemu pid %d at %s", i, p.PID, where) diff --git a/internal/emu/logs.go b/internal/emu/logs.go index 92f9879c..363f7908 100644 --- a/internal/emu/logs.go +++ b/internal/emu/logs.go @@ -284,7 +284,7 @@ var logcatMu sync.Mutex func (m *Manager) ensureLogcat(ctx context.Context, i int) string { logcatMu.Lock() defer logcatMu.Unlock() - serial := root.Serial(i) + serial := m.Root.Ports().Serial(i) running, err := m.findLogcatProcesses(serial) if err != nil { m.Log.Warnf("实例 %d 读不出宿主进程表,这次不起客体日志落盘(免得起两份): %v", i, err) @@ -354,7 +354,7 @@ func (m *Manager) logcatAfterReregister(serial string) { if !ok { return } - i, ok := root.IndexOfConsolePort(port) + i, ok := m.Root.Ports().IndexOfConsole(port) if !ok || !root.ValidIndex(i) { return } diff --git a/internal/emu/manager.go b/internal/emu/manager.go index 7d254606..667ea084 100644 --- a/internal/emu/manager.go +++ b/internal/emu/manager.go @@ -82,7 +82,7 @@ func New(r *root.Root, log *logx.Logger) *Manager { if !ok { return false } - i, ok := root.IndexOfConsolePort(port) + i, ok := m.Root.Ports().IndexOfConsole(port) return ok && m.booting(i) } m.ADB.OnReregistered = m.logcatAfterReregister @@ -123,14 +123,17 @@ func consolePortOfSerial(serial string) (int, bool) { return port, true } -func shmName(i int) string { return emulatorShmNamePrefix + strconv.Itoa(root.ConsolePort(i)) } +// shmName is the screenshot shared memory of instance i: the emulator names it after its console port. +func shmName(plan root.PortPlan, i int) string { + return emulatorShmNamePrefix + strconv.Itoa(plan.Console(i)) +} // ---- qemu processes ---------------------------------------------------------------------------------------------- // cmdlineMatches: "-avd " and "-ports ,..." both present (AUTO-MAS _cmdline_matches). Neither alone // is enough (an emulator started by another tool may use our ports under another name, or a mas_ name on other -// ports), and both together still do not tell roots apart: every root has the same names and the same port plan. -// adb.QemuBelongsTo does that. +// ports), and both together still do not tell roots apart: every root has the same names, and roots without portBase +// the same port plan. adb.QemuBelongsTo does that. func cmdlineMatches(cmdline []string, avdName string, console int) bool { hasAvd, hasPort := false, false want := strconv.Itoa(console) @@ -157,8 +160,9 @@ func isQemuName(name string) bool { } // scanQemuOf finds, with one process snapshot, the qemu process (qemu-system-x86_64[-headless].exe) of each of the -// indexes whose command line matches and that adb.QemuBelongsTo one of roots. The same-numbered instance of another -// root is not found: it is not ours to stop, re-register or adopt (a start then fails on its busy ports). +// indexes whose command line matches (in the port plan of the root it belongs to) and that adb.QemuBelongsTo one of +// roots. The same-numbered instance of another root is not found: it is not ours to stop, re-register or adopt (a +// start then fails on its busy ports). func scanQemuOf(roots []*root.Root, indexes []int) map[int]win.Process { found := map[int]win.Process{} if len(indexes) == 0 || len(roots) == 0 { @@ -168,6 +172,10 @@ func scanQemuOf(roots []*root.Root, indexes []int) map[int]win.Process { if err != nil { return found } + plans := make([]root.PortPlan, len(roots)) + for k, r := range roots { + plans[k] = r.Ports() + } for _, p := range procs { if !isQemuName(p.Name) { continue @@ -177,11 +185,8 @@ func scanQemuOf(roots []*root.Root, indexes []int) map[int]win.Process { continue } for _, i := range indexes { - if !cmdlineMatches(cmdline, root.AvdName(i), root.ConsolePort(i)) { - continue - } - for _, r := range roots { - if adb.QemuBelongsTo(r, p, i) { + for k, r := range roots { + if cmdlineMatches(cmdline, root.AvdName(i), plans[k].Console(i)) && adb.QemuBelongsTo(r, p, i) { found[i] = p break } @@ -208,7 +213,7 @@ func (m *Manager) findQemu(i int) (win.Process, bool) { // bootCompleted: `getprop sys.boot_completed` says 1. reregister=false while the instance is booting (it has not // registered with the private server yet, which is normal then). func (m *Manager) bootCompleted(ctx context.Context, i int, timeout time.Duration, reregister bool) bool { - res := m.ADB.Run(ctx, adb.RunOptions{Serial: root.Serial(i), Timeout: timeout, Reregister: reregister}, + res := m.ADB.Run(ctx, adb.RunOptions{Serial: m.Root.Ports().Serial(i), Timeout: timeout, Reregister: reregister}, "shell", "getprop", "sys.boot_completed") return res.Code == 0 && strings.TrimSpace(res.Out) == "1" } @@ -219,7 +224,7 @@ func (m *Manager) shell(ctx context.Context, i int, command string, timeout time if timeout == 0 { timeout = 30 * time.Second } - return m.ADB.Shell(ctx, root.Serial(i), command, timeout) + return m.ADB.Shell(ctx, m.Root.Ports().Serial(i), command, timeout) } // su runs a guest script as root. These userdebug images allow `su 0` without `adb root` (which restarts adbd and @@ -233,7 +238,7 @@ func (m *Manager) su(ctx context.Context, i int, script string, timeout time.Dur // push copies a host file into the guest; a failure is logged as a warning. func (m *Manager) push(ctx context.Context, i int, local, remote string) bool { - res := m.ADB.Run(ctx, adb.RunOptions{Serial: root.Serial(i), Timeout: 60 * time.Second, Reregister: true}, + res := m.ADB.Run(ctx, adb.RunOptions{Serial: m.Root.Ports().Serial(i), Timeout: 60 * time.Second, Reregister: true}, "push", local, remote) if res.Code != 0 { m.Log.Warnf("实例 %d 推送 %s 失败: %s", i, filepath.Base(local), tail(res.Out, 300)) @@ -364,6 +369,7 @@ func (m *Manager) rootInfo() RootInfo { AdbExe: m.Root.AdbExe(), AdbServerPort: m.Root.AdbServerPort(), ScriptAdbServerPort: m.Root.ScriptAdbServerPort(), + PortBase: m.Root.Ports().Base, Version: m.Root.VersionText(), } if b, ok := m.Root.ModBuild(); ok { diff --git a/internal/emu/manager_test.go b/internal/emu/manager_test.go index 0ac0d9c8..a06bdcb9 100644 --- a/internal/emu/manager_test.go +++ b/internal/emu/manager_test.go @@ -164,10 +164,11 @@ func TestScanQemuRealInstances(t *testing.T) { } base := filepath.Base(avdDir) i, err := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(base, root.AvdNamePrefix), ".avd")) - if err != nil || !strings.HasPrefix(base, root.AvdNamePrefix) || !cmdlineMatches(cmdline, root.AvdName(i), root.ConsolePort(i)) { + owner := &root.Root{Dir: filepath.Dir(filepath.Dir(avdDir))} // \avd\mas_.avd + if err != nil || !strings.HasPrefix(base, root.AvdNamePrefix) || + !cmdlineMatches(cmdline, root.AvdName(i), owner.Ports().Console(i)) { continue } - owner := &root.Root{Dir: filepath.Dir(filepath.Dir(avdDir))} // \avd\mas_.avd if !adb.QemuBelongsTo(owner, p, i) { t.Errorf("qemu %d (%s) does not belong to its own root %s", p.PID, avdDir, owner.Dir) } diff --git a/internal/emu/ops_root_test.go b/internal/emu/ops_root_test.go index 74db7972..2f3b763a 100644 --- a/internal/emu/ops_root_test.go +++ b/internal/emu/ops_root_test.go @@ -65,8 +65,9 @@ func TestOpsInstanceLifecycle(t *testing.T) { if created.Config != want { t.Fatalf("config = %+v, want %+v", created.Config, want) } - if created.Serial != root.Serial(i) || created.AdbAddress != "127.0.0.1:"+strconv.Itoa(root.AdbPort(i)) || - created.Ports.Grpc != root.GrpcPort(i) || created.Screencap.Shm != shmName(i) || created.Screencap.ShmReady { + def := root.PortPlan{Base: root.DefaultPortBase} + if created.Serial != def.Serial(i) || created.AdbAddress != "127.0.0.1:"+strconv.Itoa(def.Adb(i)) || + created.Ports.Grpc != def.Grpc(i) || created.Screencap.Shm != shmName(def, i) || created.Screencap.ShmReady { t.Fatalf("addresses = %+v", created) } if created.Initialized || !fileOrDirExists(created.Path) { diff --git a/internal/emu/portplan_test.go b/internal/emu/portplan_test.go new file mode 100644 index 00000000..54de1453 --- /dev/null +++ b/internal/emu/portplan_test.go @@ -0,0 +1,508 @@ +//go:build windows + +package emu + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "modavd/internal/adb" + "modavd/internal/avd" + "modavd/internal/errs" + "modavd/internal/logx" + "modavd/internal/root" + "modavd/internal/win" +) + +// The fake adb and qemu of the port plan tests (ModAVD/ModAVD#75): this test binary copied as adb.exe or as +// qemu-system-x86_64-headless.exe. MODAVD_EMU_FAKE_ADB=server listens on MODAVD_EMU_FAKE_ADB_PORT, which is all +// EnsureServer looks for (a listening adb.exe); =client appends its arguments to MODAVD_EMU_FAKE_ADB_LOG and answers +// as a guest that has booted; =qemu just runs with a qemu's command line (-avd mas_ -ports ,), +// listening on MODAVD_EMU_FAKE_ADB_PORT when that is set, as qemu does on its adb port. +const ( + fakeAdbEnv = "MODAVD_EMU_FAKE_ADB" + fakeAdbLogEnv = "MODAVD_EMU_FAKE_ADB_LOG" + fakeAdbPortEnv = "MODAVD_EMU_FAKE_ADB_PORT" +) + +func TestMain(m *testing.M) { + switch os.Getenv(fakeAdbEnv) { + case "server", "qemu": + os.Exit(fakeAdbServerMain()) + case "client": + os.Exit(fakeAdbClientMain(os.Args[1:])) + } + os.Exit(m.Run()) +} + +// fakeAdbServerMain listens on MODAVD_EMU_FAKE_ADB_PORT (if set) and waits, at most 2 minutes, until it is ended. +func fakeAdbServerMain() int { + time.AfterFunc(2*time.Minute, func() { os.Exit(0) }) // never outlives a test that could not end it + port := os.Getenv(fakeAdbPortEnv) + if port == "" { + select {} + } + ln, err := net.Listen("tcp", "127.0.0.1:"+port) + if err != nil { + return 1 + } + for { + c, err := ln.Accept() + if err != nil { + return 0 + } + c.Close() + } +} + +// copyTestExe copies this test binary to path (the fake adb / qemu). +func copyTestExe(t *testing.T, path string) { + t.Helper() + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(self) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, b, 0o755); err != nil { + t.Fatal(err) + } +} + +// startFake starts exe (a copy of this binary) in mode with args, listening on listen when it is not 0, and ends it +// (by its PID) when the test is done. It returns once the process runs (and listens). +func startFake(t *testing.T, exe, mode string, listen int, args ...string) win.Process { + t.Helper() + env := append(os.Environ(), fakeAdbEnv+"="+mode) + if listen != 0 { + if _, up, _ := win.ListenerPID(listen); up { + t.Skipf("port %d is in use on this machine", listen) + } + env = append(env, fakeAdbPortEnv+"="+strconv.Itoa(listen)) + } + p, err := win.StartDetached(exe, args, win.StartOptions{Env: env}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if proc, err := os.FindProcess(int(p.PID)); err == nil { + proc.Kill() + proc.Wait() + } + }) + if listen != 0 { + for deadline := time.Now().Add(10 * time.Second); ; { + if pid, up, _ := win.ListenerPID(listen); up && pid == p.PID { + break + } + if time.Now().After(deadline) { + t.Fatalf("the fake %s does not listen on %d", mode, listen) + } + time.Sleep(50 * time.Millisecond) + } + } + return p +} + +func fakeAdbClientMain(args []string) int { + line, _ := json.Marshal(args) + if f, err := os.OpenFile(os.Getenv(fakeAdbLogEnv), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644); err == nil { + f.Write(append(line, '\n')) + f.Close() + } + all := strings.Join(args, " ") + switch { + case strings.Contains(all, "get-state"): + fmt.Println("device") + case strings.Contains(all, "sys.boot_completed"): + fmt.Println("1") + } + return 0 +} + +func freeTCPPort(t *testing.T) int { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + return ln.Addr().(*net.TCPAddr).Port +} + +// portPlanRoot is a root with portBase 21000 whose SDK (sdkRoot) holds the fake adb.exe, its private server +// listening; adb clients started from here on log their arguments to the returned file. +func portPlanRoot(t *testing.T) (*root.Root, string) { + t.Helper() + dir := opsTestTempDir(t) + adbExe := filepath.Join(dir, "dev-sdk", "platform-tools", "adb.exe") + copyTestExe(t, adbExe) + server, script := freeTCPPort(t), freeTCPPort(t) + sdk, _ := json.Marshal(filepath.Dir(filepath.Dir(adbExe))) + meta := fmt.Sprintf(`{"portBase": 21000, "adbServerPort": %d, "scriptAdbServerPort": %d, "sdkRoot": %s}`, + server, script, 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) + } + if r.AdbExe() != adbExe || r.AdbServerPort() != server || r.Ports().Base != 21000 || r.CheckPorts() != nil { + t.Fatalf("root: adb %s, server %d, plan %d, check %v", r.AdbExe(), r.AdbServerPort(), r.Ports().Base, + r.CheckPorts()) + } + + startFake(t, adbExe, "server", server) + log := filepath.Join(dir, "fake-adb.log") + t.Setenv(fakeAdbEnv, "client") + t.Setenv(fakeAdbLogEnv, log) + return r, log +} + +// TestPortPlanReachesEveryAdbCall: on a root with portBase 21000, everything that names instance 6 to adb names it +// emulator-21060, never emulator-200xx (the default plan's, i.e. the production root's instance of the same number). +// What status reports follows too. +func TestPortPlanReachesEveryAdbCall(t *testing.T) { + r, log := portPlanRoot(t) + ctx := context.Background() + m := New(r, logx.Nop()) + six := 6 + if _, err := m.Create(ctx, CreateRequest{filesOnly: true, Index: &six}); err != nil { + t.Fatal(err) + } + // instance 6 runs: the process scan finds our own process for it (nothing below ends it) + self, ok := win.FindProcess(uint32(os.Getpid())) + if !ok { + t.Fatal("cannot read our own process") + } + saved := qemuScan + qemuScan = func([]int) map[int]win.Process { return map[int]win.Process{6: self} } + t.Cleanup(func() { qemuScan = saved }) + + info, err := m.Info(ctx, 6) + if err != nil { + t.Fatal(err) + } + if info.Serial != "emulator-21060" || info.AdbAddress != "127.0.0.1:21061" || + info.Ports != (Ports{Console: 21060, Adb: 21061, Grpc: 21062}) || info.Screencap.Shm != "SHM_videmulator21060" || + !info.Booted { + t.Fatalf("info = %+v", info) + } + list, err := m.List(ctx) + if err != nil || list.PortBase != 21000 || len(list.Instances) != 1 || list.Instances[0].Serial != "emulator-21060" { + t.Fatalf("list = %+v, %v", list, err) + } + + calls := 0 + call := func(name string, f func()) { f(); calls++ } + call("Shell", func() { + if _, err := m.Shell(ctx, 6, "echo hi", 10*time.Second); err != nil { + t.Errorf("Shell: %v", err) + } + }) + call("AdbPassthrough", func() { + if _, err := m.AdbPassthrough(ctx, 6, []string{"get-serialno"}, nil, io.Discard, io.Discard); err != nil { + t.Errorf("AdbPassthrough: %v", err) + } + }) + call("bootCompleted", func() { m.bootCompleted(ctx, 6, 10*time.Second, false) }) + call("guestBoot", func() { m.guestBoot(ctx, 6, false) }) + call("guestIO", func() { m.guestIO(ctx, 6).adb(10*time.Second, "get-state") }) + local := filepath.Join(r.Dir, "push-me.txt") + if err := os.WriteFile(local, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + call("push", func() { m.push(ctx, 6, local, "/data/local/tmp/push-me.txt") }) + if err := os.MkdirAll(r.ComponentsDir(), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(r.LauncherAPK(), []byte("not really an apk"), 0o644); err != nil { + t.Fatal(err) + } + call("installLauncher", func() { m.installLauncher(ctx, 6) }) + call("ensureLogcat", func() { m.ensureLogcat(ctx, 6) }) + + // the logcat capture is started detached: give it a moment to write its line + var lines []string + for deadline := time.Now().Add(10 * time.Second); ; { + b, _ := os.ReadFile(log) + lines = strings.Split(strings.TrimSpace(string(b)), "\n") + if strings.Contains(string(b), "logcat") || time.Now().After(deadline) { + break + } + time.Sleep(100 * time.Millisecond) + } + serials := map[string]int{} + for _, line := range lines { + var args []string + if err := json.Unmarshal([]byte(line), &args); err != nil { + t.Fatalf("fake adb log line %q: %v", line, err) + } + if len(args) < 2 || args[0] != "-P" || args[1] != strconv.Itoa(r.AdbServerPort()) { + t.Errorf("adb %q: not on the private server %d", args, r.AdbServerPort()) + } + for k := 0; k+1 < len(args); k++ { + if args[k] == "-s" { + serials[args[k+1]]++ + } + if strings.HasPrefix(args[k], "emulator-200") || strings.HasPrefix(args[k+1], "emulator-200") { + t.Errorf("adb %q names the default plan's instance", args) + } + } + } + if len(serials) != 1 || serials["emulator-21060"] < calls { + t.Fatalf("serials %v after %d calls (log: %q)", serials, calls, lines) + } + t.Logf("%d adb runs, serials %v", len(lines), serials) + if !strings.Contains(strings.Join(lines, "\n"), "logcat") { + t.Errorf("no logcat capture was started: %q", lines) + } +} + +// TestPortBaseRefused: an invalid portBase, or a plan of one's own still on the production adb servers, starts +// nothing: create refuses before writing a file, picking an index refuses, and so does a boot. +func TestPortBaseRefused(t *testing.T) { + ctx := context.Background() + for _, meta := range []string{ + `{"portBase": 21050, "adbServerPort": 21099, "scriptAdbServerPort": 21098}`, + `{"portBase": "abc", "adbServerPort": 21099, "scriptAdbServerPort": 21098}`, + `{"portBase": 21000}`, + `{"portBase": 21000, "adbServerPort": 21099, "scriptAdbServerPort": 20049}`, + } { + dir := opsTestTempDir(t) + 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) + } + m := New(r, logx.Nop()) + six := 6 + if _, err := m.Create(ctx, CreateRequest{filesOnly: true, Index: &six}); errs.CodeOf(err) != errs.InvalidArgument { + t.Errorf("%s: Create = %v", meta, err) + } + if left := instanceFilesOnDisk(r, 6); len(left) > 0 { + t.Errorf("%s: Create left %v", meta, left) + } + if _, err := m.FreeIndex(); errs.CodeOf(err) != errs.InvalidArgument { + t.Errorf("%s: FreeIndex = %v", meta, err) + } + } + + // a boot: the instance was made while mas-avd.json was fine + dir := opsTestTempDir(t) + write := func(meta string) { + if err := os.WriteFile(filepath.Join(dir, root.MetadataFile), []byte(meta), 0o644); err != nil { + t.Fatal(err) + } + } + write(`{"portBase": 21000, "adbServerPort": 21099, "scriptAdbServerPort": 21098}`) + r, err := root.New(dir) + if err != nil { + t.Fatal(err) + } + m := New(r, logx.Nop()) + six := 6 + if _, err := m.Create(ctx, CreateRequest{filesOnly: true, Index: &six}); err != nil { + t.Fatal(err) + } + inst, err := m.instance(6) + if err != nil { + t.Fatal(err) + } + write(`{"portBase": 21000, "adbServerPort": 20050, "scriptAdbServerPort": 21098}`) + if _, err := m.prepareLaunch(ctx, inst, false); errs.CodeOf(err) != errs.InvalidArgument { + t.Errorf("prepareLaunch = %v", err) + } + // nor does anything else that would start or use an adb server: the production one, here + if _, err := m.EnsureServers(ctx); errs.CodeOf(err) != errs.InvalidArgument { + t.Errorf("EnsureServers = %v", err) + } + if _, err := m.AdbPassthrough(ctx, 6, []string{"devices"}, nil, io.Discard, io.Discard); errs.CodeOf(err) != errs.InvalidArgument { + t.Errorf("AdbPassthrough = %v", err) + } +} + +// portPlanTestRoot is a root with portBase 21000 (servers 21099 / 21098) and the given instances (files only). +// Nothing here runs adb. +func portPlanTestRoot(t *testing.T, indexes ...int) (*Manager, *root.Root) { + t.Helper() + dir := opsTestTempDir(t) + meta := `{"portBase": 21000, "adbServerPort": 21099, "scriptAdbServerPort": 21098}` + 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) + } + m := New(r, logx.Nop()) + for _, i := range indexes { + if _, err := m.Create(context.Background(), CreateRequest{filesOnly: true, Index: &i}); err != nil { + t.Fatal(err) + } + } + return m, r +} + +// fakeQemu starts a fake qemu of instance i on console (listening on its adb port console+1 when listen) from exeDir. +// When avdDir is not "", it also writes the qemu's emulator runtime file naming avdDir, which is what +// adb.QemuBelongsTo goes by (the test points LOCALAPPDATA, under which that file lives, at a directory of its own). +func fakeQemu(t *testing.T, exeDir string, i, console int, listen bool, avdDir string) win.Process { + t.Helper() + exe := filepath.Join(exeDir, "qemu-system-x86_64-headless.exe") + if _, err := os.Stat(exe); err != nil { + copyTestExe(t, exe) + } + adbPort := 0 + if listen { + adbPort = console + 1 + } + p := startFake(t, exe, "qemu", adbPort, "-avd", root.AvdName(i), "-ports", fmt.Sprintf("%d,%d", console, console+1), + "-grpc", strconv.Itoa(console+2)) + if avdDir != "" { + ini := filepath.Join(adb.EmulatorDiscoveryDir(), fmt.Sprintf("pid_%d.ini", p.PID)) + if err := os.MkdirAll(filepath.Dir(ini), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(ini, []byte("avd.dir="+avdDir+"\r\n"), 0o644); err != nil { + t.Fatal(err) + } + } + return p +} + +// TestLaunchPlanPorts: a boot of instance 6 on a root with portBase 21000 gives the emulator -ports 21060,21061 and +// -grpc 21062: on the default plan's 20060 it would sit on the production root's ports, the very thing portBase is for. +func TestLaunchPlanPorts(t *testing.T) { + r, _ := portPlanRoot(t) + m := New(r, logx.Nop()) + six := 6 + if _, err := m.Create(context.Background(), CreateRequest{filesOnly: true, Index: &six}); err != nil { + t.Fatal(err) + } + inst, err := m.instance(6) + if err != nil { + t.Fatal(err) + } + plan, err := m.launchPlanFor(context.Background(), inst, 3072, false) + if errs.CodeOf(err) == errs.Busy { + t.Skipf("ports of instance 6 in use on this machine: %v", err) + } + if err != nil { + t.Fatal(err) + } + args := " " + strings.Join(plan.args, " ") + " " + if !strings.Contains(args, " -ports 21060,21061 ") || !strings.Contains(args, " -grpc 21062 ") { + t.Errorf("emulator arguments: %s", args) + } +} + +// TestQemuMatchedByPortPlan: on a root with portBase 21000, this root's qemu of instance 6 is the one on -ports 21060 +// (and listening on 21061), not one of mas_6 on the default plan's 20060; a qemu of another root's mas_7 on 21070 is +// that other root's instance on our ports; the host tuning counts our qemu's vCPUs from our instance. +func TestQemuMatchedByPortPlan(t *testing.T) { + t.Setenv("LOCALAPPDATA", t.TempDir()) // the fakes' emulator runtime files + m, r := portPlanTestRoot(t, 6, 7) + exeDir := t.TempDir() + ours := fakeQemu(t, exeDir, 6, 21060, true, filepath.Join(r.AvdHome(), "mas_6.avd")) + fakeQemu(t, exeDir, 6, 20060, false, "") // a mas_6 on the default plan's ports, not under our SDK: not ours + other := fakeQemu(t, exeDir, 7, 21070, true, filepath.Join(t.TempDir(), "avd", "mas_7.avd")) + + if found := scanQemuOf([]*root.Root{r}, []int{6, 7}); found[6].PID != ours.PID || found[7].PID != 0 { + t.Errorf("scanQemuOf = %v, want 6 -> pid %d and no 7", found, ours.PID) + } + if p, ok := adb.QemuOnAdbPort(r, 21060); !ok || p.PID != ours.PID { + t.Errorf("QemuOnAdbPort(21060) = %v %v, want pid %d", p, ok, ours.PID) + } + if p, where, found := m.otherRootInstance(r.Ports(), 7); !found || p.PID != other.PID || !strings.HasSuffix(where, `\mas_7.avd`) { + t.Errorf("otherRootInstance(7) = %v %q %v, want pid %d", p, where, found, other.PID) + } + if p, _, found := m.otherRootInstance(r.Ports(), 6); found { + t.Errorf("otherRootInstance(6) = pid %d: our own qemu taken for another root's", p.PID) + } + counted := 0 + for _, q := range m.otherQemus(win.Process{}, 2) { + if q.Cores == avd.DefaultCPU { + counted++ + } + } + if counted == 0 { + t.Errorf("otherQemus did not count our qemu's %d vCPUs from instance 6", avd.DefaultCPU) + } +} + +// TestBootingPortPlan: the adb client's "is it booting" hook maps emulator-21060 to instance 6 of a root with portBase +// 21000 (and emulator-20060, the default plan's, to none of its instances). +func TestBootingPortPlan(t *testing.T) { + m, _ := portPlanTestRoot(t, 6) + l, ok, err := win.TryLock(m.lockPath(6, "boot")) + if err != nil || !ok { + t.Fatalf("boot lock: %v %v", ok, err) + } + defer l.Unlock() + if !m.ADB.Booting("emulator-21060") { + t.Error("emulator-21060 not booting while instance 6 boots") + } + if m.ADB.Booting("emulator-20060") { + t.Error("emulator-20060 (the default plan's) taken for instance 6") + } +} + +// TestWindowTitlePortPlan: showing or hiding the window looks for the emulator's title "mas_6:21060" on a root with +// portBase 21000 (the emulator puts its console port in the title). +func TestWindowTitlePortPlan(t *testing.T) { + m, _ := portPlanTestRoot(t, 6) + self, ok := win.FindProcess(uint32(os.Getpid())) + if !ok { + t.Fatal("cannot read our own process") + } + saved, savedSet := qemuScan, setEmulatorWindowsVisible + qemuScan = func([]int) map[int]win.Process { return map[int]win.Process{6: self} } + var titles []string + setEmulatorWindowsVisible = func(pid uint32, title string, visible bool) (int, error) { + titles = append(titles, title) + return 1, nil + } + t.Cleanup(func() { qemuScan, setEmulatorWindowsVisible = saved, savedSet }) + if res, err := m.SetWindowVisible(context.Background(), 6, false); err != nil || res.Windows != 1 { + t.Fatalf("SetWindowVisible = %+v, %v", res, err) + } + if len(titles) != 1 || titles[0] != "mas_6:21060" { + t.Errorf("window titles looked for: %q", titles) + } +} + +// TestBridgeScriptPortPlan: the bridge script gets instance 6's serial in the root's plan, and the root's server. +func TestBridgeScriptPortPlan(t *testing.T) { + m, r := portPlanTestRoot(t, 6) + script := filepath.Join(r.Dir, "tools", bridgeScriptName) + if err := os.MkdirAll(filepath.Dir(script), 0o755); err != nil { + t.Fatal(err) + } + fake := "param([Parameter(Position=0)][string]$Action, [string]$Serial, [int]$AdbPort, [string]$Adb, [string]$Payload, [switch]$Reboot)\r\n" + + "\"$Action $Serial $AdbPort\"\r\n" + if err := os.WriteFile(script, []byte(fake), 0o644); err != nil { + t.Fatal(err) + } + run, err := m.runBridgeScript(context.Background(), 6, "verify", false) + if err != nil || run.Code != 0 || run.Last != "verify emulator-21060 21099" { + t.Errorf("runBridgeScript = %+v, %v", run, err) + } +} diff --git a/internal/emu/status.go b/internal/emu/status.go index 133c6b16..3d543b16 100644 --- a/internal/emu/status.go +++ b/internal/emu/status.go @@ -13,7 +13,6 @@ import ( "modavd/internal/avd" "modavd/internal/jsonord" - "modavd/internal/root" "modavd/internal/win" ) @@ -126,15 +125,15 @@ func (m *Manager) Info(ctx context.Context, i int) (*InstanceInfo, error) { // already known boot state (skips the getprop). func (m *Manager) instanceInfo(ctx context.Context, in *avd.Instance, p *win.Process, booted *bool) InstanceInfo { i := in.Index - console := root.ConsolePort(i) + ports := m.Root.Ports() info := InstanceInfo{ Index: i, Name: in.Name, Title: in.Title, - Serial: root.Serial(i), - AdbAddress: fmt.Sprintf("127.0.0.1:%d", root.AdbPort(i)), - Ports: Ports{Console: console, Adb: root.AdbPort(i), Grpc: root.GrpcPort(i)}, - Screencap: Screencap{Shm: shmName(i)}, + Serial: ports.Serial(i), + AdbAddress: fmt.Sprintf("127.0.0.1:%d", ports.Adb(i)), + Ports: Ports{Console: ports.Console(i), Adb: ports.Adb(i), Grpc: ports.Grpc(i)}, + Screencap: Screencap{Shm: shmName(ports, i)}, Path: in.Dir, } // create's setup (createinit.go) is read before the getprop, which may wait up to statusAdbTimeout: its shutdown diff --git a/internal/emu/stop.go b/internal/emu/stop.go index d6afb8f5..805d44d6 100644 --- a/internal/emu/stop.go +++ b/internal/emu/stop.go @@ -42,7 +42,6 @@ import ( "modavd/internal/adb" "modavd/internal/errs" "modavd/internal/logx" - "modavd/internal/root" "modavd/internal/win" ) @@ -296,8 +295,8 @@ func stopCanceled(ctx context.Context, i int) error { // stopOpsFor are the real side effects on qemu process p of instance i. func (m *Manager) stopOpsFor(ctx context.Context, i int, p win.Process) stopOps { - console := root.ConsolePort(i) - serial := root.Serial(i) + ports := m.Root.Ports() + console, serial := ports.Console(i), ports.Serial(i) closeRun := func(timeout time.Duration, args ...string) adb.Result { return m.ADB.Run(ctx, adb.RunOptions{Serial: serial, Timeout: timeout, Reregister: false, TotalTimeout: true}, args...) } diff --git a/internal/emu/types.go b/internal/emu/types.go index f53cc270..cea84ebc 100644 --- a/internal/emu/types.go +++ b/internal/emu/types.go @@ -96,6 +96,7 @@ type RootInfo struct { AdbExe string `json:"adb_exe"` AdbServerPort int `json:"adb_server_port"` // the private server modavd and the emulator use ScriptAdbServerPort int `json:"script_adb_server_port"` // the server scripts should use for these instances + PortBase int `json:"port_base"` // console port of instance i = PortBase + 10*i (portBase) Version string `json:"version"` // "0.35.0"; "" when the emulator's build is unknown Build int `json:"build"` // N of mas-N; 0 when unknown } @@ -232,7 +233,7 @@ type StopResult struct { } // CheckItem is one host check (AUTO-MAS precheck.PrecheckItem). ID: path / components / emulator / acceleration / -// vulkan / disk / memory. +// vulkan / disk / memory; ports (modavd's own) only for a root whose mas-avd.json sets portBase. type CheckItem struct { ID string `json:"id"` Title string `json:"title"` diff --git a/internal/emu/vulkanfix.go b/internal/emu/vulkanfix.go index 58aa875f..95e8c77e 100644 --- a/internal/emu/vulkanfix.go +++ b/internal/emu/vulkanfix.go @@ -447,7 +447,7 @@ func (m *Manager) patchedVulkanLibrary(ctx context.Context, i int) string { original := filepath.Join(dir, fmt.Sprintf("libvulkan_enc-%d.orig.so", i)) defer os.Remove(original) - res := m.ADB.Run(ctx, adb.RunOptions{Serial: root.Serial(i), Timeout: 60 * time.Second, Reregister: true}, + res := m.ADB.Run(ctx, adb.RunOptions{Serial: m.Root.Ports().Serial(i), Timeout: 60 * time.Second, Reregister: true}, "pull", vkfix.GuestPath, original) if res.Code != 0 || !regularFile(original) { m.Log.Warnf("实例 %d 客体 Vulkan 驱动补丁没挂: 从客体拉 %s 失败: %s", i, vkfix.GuestPath, tail(res.Out, 200)) diff --git a/internal/emu/window.go b/internal/emu/window.go index 4a7f7e7e..ff71d9f8 100644 --- a/internal/emu/window.go +++ b/internal/emu/window.go @@ -7,7 +7,6 @@ import ( "strings" "modavd/internal/errs" - "modavd/internal/root" "modavd/internal/win" ) @@ -46,6 +45,10 @@ func windowConflict(i int, opt StartOptions, windowed bool) error { return nil } +// setEmulatorWindowsVisible is win.SetEmulatorWindowsVisible; a test replaces it (the window title it is given names +// the console port, "mas_:"). +var setEmulatorWindowsVisible = win.SetEmulatorWindowsVisible + // SetWindowVisible shows / hides the window of an instance booted with one (AUTO-MAS setVisible): the main window // and the side toolbar get SW_SHOW / SW_HIDE. Hiding does not stop rendering or the screenshot channel (10-04: the // shared-memory frame counter kept going at ~51 fps while hidden). A headless instance has no window and cannot get @@ -65,7 +68,7 @@ func (m *Manager) SetWindowVisible(ctx context.Context, i int, visible bool) (*W if visible { verb = "显示" } - n, err := win.SetEmulatorWindowsVisible(p.PID, fmt.Sprintf("%s:%d", in.Name, root.ConsolePort(i)), visible) + n, err := setEmulatorWindowsVisible(p.PID, fmt.Sprintf("%s:%d", in.Name, m.Root.Ports().Console(i)), visible) if err != nil { m.Log.Warnf("魔改 AVD 实例 %d %s窗口失败: %v", i, verb, err) return res, nil diff --git a/internal/mcp/mcp_test.go b/internal/mcp/mcp_test.go index 004933bc..0a44ef04 100644 --- a/internal/mcp/mcp_test.go +++ b/internal/mcp/mcp_test.go @@ -1523,7 +1523,7 @@ func TestSchemaOf(t *testing.T) { p := jsonRoundTrip(t, schemaOf(reflect.TypeFor[schemaProbe]())).(map[string]any) pp := p["properties"].(map[string]any) if !reflect.DeepEqual(p["required"], []any{"root", "sdk", "local_sdk", "adb_exe", "adb_server_port", - "script_adb_server_port", "version", "build", "a", "c", "d", "e", "nested"}) { + "script_adb_server_port", "port_base", "version", "build", "a", "c", "d", "e", "nested"}) { t.Fatalf("required %v", p["required"]) } for _, k := range []string{"G", "h", "RootInfo"} { diff --git a/internal/report/collect.go b/internal/report/collect.go index 332ffa5e..c4a43e42 100644 --- a/internal/report/collect.go +++ b/internal/report/collect.go @@ -112,6 +112,7 @@ type collector struct { sdkDir string // as mas-avd.json / the root gives it (shown) sdkSource string adbPort int + plan root.PortPlan // mas-avd.json's portBase (ModAVD/ModAVD#75); the script's PORT_BASE otherwise running []liveTarget cmdlineUnreadable bool masFound bool @@ -315,10 +316,20 @@ func (c *collector) rootAndVersions() error { c.L(msg) } + // the port plan: modavd's mas-avd.json portBase (the scripts know only PORT_BASE 20000, so nothing is said for it) + plan, problem := root.PortPlanOf(cfg) + c.plan = plan + if problem != "" { + c.L(fmt.Sprintf("端口段:%d(%s;看状态时按 %d 算,modavd 不让开机)", plan.Base, problem, plan.Base)) + } else if plan.Base != root.DefaultPortBase { + c.L(fmt.Sprintf("端口段:%d–%d(mas-avd.json 的 portBase;实例 i 的控制台端口是 %d + 10 × i)", plan.Base, + plan.Last(), plan.Base)) + } + // the adb server port: the backend's adb_server_port(), back to 20050 when not valid; never 5037 raw := getCI(cfg, "adbServerPort") hasPort := hasCI(cfg, "adbServerPort") - if port, ok := scriptPort(raw); ok { + if port, ok := scriptPort(c.plan, raw); ok { c.adbPort = port c.L(fmt.Sprintf("adb server 端口:%d(mas-avd.json 的 adbServerPort)", port)) } else { @@ -651,6 +662,17 @@ var ( portsArg = regexp.MustCompile(`(?i)(?:^|\s)-ports?\s+"?([0-9]+)`) ) +// otherRootsInstance: a qemu of instance avd on console port is another root's. Only with a plan of its own +// (portBase): then the same-named instance of another root can run at the same time, on that root's ports. Without +// one, as the script: two such instances could not run at once (they would share ports). +func otherRootsInstance(plan root.PortPlan, avd string, port int) bool { + if plan.Base == root.DefaultPortBase { + return false + } + i, err := strconv.Atoi(strings.TrimPrefix(strings.ToLower(avd), root.AvdNamePrefix)) + return err == nil && port != plan.Console(i) +} + func (c *collector) runningAndAdb() error { c.section("正在运行的 qemu-system 进程") qs, err := c.h.Processes(func(name string) bool { return hasPrefixFold(name, "qemu-system") }) @@ -683,6 +705,10 @@ func (c *collector) runningAndAdb() error { port, _ = strconv.Atoi(m[1]) } if avd != "" && containsFold(c.instances, avd) { + if otherRootsInstance(c.plan, avd, port) { + c.L(fmt.Sprintf(" 端口 %d 不是本目录 %s 的(端口段 %d),是别的根目录的同名实例,跳过", port, avd, c.plan.Base)) + continue + } running = append(running, liveTarget{name: avd, pid: q.PID, consolePort: port}) } } @@ -1202,14 +1228,18 @@ func (c *collector) live() error { if known { continue } - off := cport - root.PortBase + off := cport - c.plan.Base if off < 0 || off%root.PortStep != 0 { - c.L(fmt.Sprintf(" emulator-%d:端口不符合 PORT_BASE=%d、PORT_STEP=%d,推算不出实例,跳过", cport, root.PortBase, root.PortStep)) + c.L(fmt.Sprintf(" emulator-%d:端口不符合 PORT_BASE=%d、PORT_STEP=%d,推算不出实例,跳过", cport, c.plan.Base, root.PortStep)) continue } name := root.AvdNamePrefix + strconv.Itoa(off/root.PortStep) - c.L(fmt.Sprintf(" emulator-%[1]d(%[2]s)→ %[3]s:按 (%[1]d - %[4]d) / %[5]d 推算(PORT_BASE、PORT_STEP 是后端 constants.py 的常量)", - cport, state, name, root.PortBase, root.PortStep)) + source := "PORT_BASE、PORT_STEP 是后端 constants.py 的常量" + if c.plan.Base != root.DefaultPortBase { + source = "PORT_BASE 是 mas-avd.json 的 portBase,PORT_STEP 是后端 constants.py 的常量" + } + c.L(fmt.Sprintf(" emulator-%[1]d(%[2]s)→ %[3]s:按 (%[1]d - %[4]d) / %[5]d 推算(%[6]s)", + cport, state, name, c.plan.Base, root.PortStep, source)) if state != "device" { c.L(" 状态不是 device,跳过") continue diff --git a/internal/report/config.go b/internal/report/config.go index b84691f2..d1f4bdd2 100644 --- a/internal/report/config.go +++ b/internal/report/config.go @@ -306,6 +306,9 @@ func buildConfig(ctx context.Context, rootDir string, h Host) *ConfigResult { } // ---- games of the running instances (only those) + // The index from a serial is counted in this root's plan (mas-avd.json portBase), so that the production + // root's instances, also listed by its servers 20050 / 20049, are not taken for this root's. + plan, _ := root.PortPlanOf(cfg) var ports []int cfgPort := 0 if v := getCI(cfg, "adbServerPort"); truthy(v) { @@ -344,11 +347,10 @@ func buildConfig(ctx context.Context, rootDir string, h Host) *ConfigResult { if cport < 0 { continue } - off := cport - root.PortBase - if off < 0 || off%root.PortStep != 0 { + idx, ok := configIndex(plan, cport) + if !ok { continue } - idx := strconv.Itoa(off / root.PortStep) if _, ok := seen[idx]; ok { continue } @@ -394,6 +396,16 @@ func buildConfig(ctx context.Context, rootDir string, h Host) *ConfigResult { var microsoftPrefix = regexp.MustCompile(`(?i)^Microsoft[\s\p{Z}]+`) +// configIndex is the instance index report-config.ps1 infers from a device's console port, counted in the root's +// plan (the script knows only PORT_BASE 20000); ok=false when cport is not on it. +func configIndex(plan root.PortPlan, cport int) (string, bool) { + off := cport - plan.Base + if off < 0 || off%root.PortStep != 0 { + return "", false + } + return strconv.Itoa(off / root.PortStep), true +} + // gamesOf asks one running instance for its third-party packages and their versions. func gamesOf(ctx context.Context, t configTarget) []string { fail := func(err error) []string { return []string{"读不到(" + err.Error() + ")"} } diff --git a/internal/report/report.go b/internal/report/report.go index 019fd7bb..40ea0136 100644 --- a/internal/report/report.go +++ b/internal/report/report.go @@ -542,9 +542,9 @@ func psDouble(v *jsonord.Value) (float64, bool) { var scriptPortText = regexp.MustCompile(`^[+-]?[0-9]+$`) // scriptPort is collect-info.ps1's Resolve-MetadataPort: an integer (fractions truncated, a numeric string, a -// boolean as 0 / 1) of 1024-65535 that is not 5037 and not a console / adb / gRPC port of instances 0-9 (5 is -// reserved). -func scriptPort(v *jsonord.Value) (int, bool) { +// boolean as 0 / 1) of 1024-65535 that is not 5037 and not a console / adb / gRPC port of instances 0-9 in plan (5 is +// reserved; the script knows only the default plan). +func scriptPort(plan root.PortPlan, v *jsonord.Value) (int, bool) { var port int64 switch v.Kind() { case jsonord.Bool: @@ -582,7 +582,7 @@ func scriptPort(v *jsonord.Value) (int, bool) { if i == root.ReservedIndex { continue } - if c := int64(root.ConsolePort(i)); port >= c && port <= c+2 { + if c := int64(plan.Console(i)); port >= c && port <= c+2 { return 0, false } } diff --git a/internal/report/report_test.go b/internal/report/report_test.go index 25f982f1..f170ed0d 100644 --- a/internal/report/report_test.go +++ b/internal/report/report_test.go @@ -11,6 +11,7 @@ import ( "time" "modavd/internal/jsonord" + "modavd/internal/root" ) func TestFormatN(t *testing.T) { @@ -62,7 +63,7 @@ func TestScriptPort(t *testing.T) { if err != nil { t.Fatal(err) } - got, ok := scriptPort(v) + got, ok := scriptPort(root.PortPlan{Base: root.DefaultPortBase}, v) if !ok { got = 0 } @@ -70,6 +71,41 @@ func TestScriptPort(t *testing.T) { t.Errorf("%s: %d, want %d", raw, got, want) } } + // running instances: with portBase 21000, the same-named qemu of another root (on its ports) is not this root's + for _, c := range []struct { + base, port int + avd string + want bool + }{ + {root.DefaultPortBase, 20060, "mas_6", false}, {root.DefaultPortBase, 21060, "mas_6", false}, + {21000, 21060, "mas_6", false}, {21000, 20060, "mas_6", true}, {21000, 20060, "MAS_6", true}, + {21000, 0, "mas_6", true}, {21000, 20060, "mas_x", false}, + } { + if got := otherRootsInstance(root.PortPlan{Base: c.base}, c.avd, c.port); got != c.want { + t.Errorf("otherRootsInstance(%d, %s, %d) = %v", c.base, c.avd, c.port, got) + } + } + // report-config's index of a device: counted in the root's plan, so the production root's emulator-20060 (listed + // by its servers, which report-config also asks) is no instance of a root with portBase 21000 + for _, c := range []struct { + base, port int + want string + ok bool + }{ + {root.DefaultPortBase, 20060, "6", true}, {root.DefaultPortBase, 20065, "", false}, + {21000, 21060, "6", true}, {21000, 20060, "", false}, {21000, 21000, "0", true}, + } { + if got, ok := configIndex(root.PortPlan{Base: c.base}, c.port); got != c.want || ok != c.ok { + t.Errorf("configIndex(%d, %d) = %q %v", c.base, c.port, got, ok) + } + } + // a root with portBase 21000: its own instance ports are refused, the default plan's are not (ModAVD/ModAVD#75) + for raw, want := range map[string]int{`20010`: 20010, `21010`: 0, `21092`: 0, `21093`: 21093} { + v, _ := jsonord.Parse([]byte(raw)) + if got, ok := scriptPort(root.PortPlan{Base: 21000}, v); (ok && got != want) || (!ok && want != 0) { + t.Errorf("plan 21000: %s: %d %v, want %d", raw, got, ok, want) + } + } for raw, want := range map[string]string{`"5037"`: `"5037"`, `5037`: `5037`, `1.5e3`: `1500`, `[1]`: `1`, `[1,"a\ // sdk\emulator\emulator.exe ModAVD's own emulator (the package) @@ -65,33 +66,130 @@ var NoLocalScanEnv = map[string]string{"ADB_LOCAL_TRANSPORT_MAX_PORT": "5554"} func ValidIndex(i int) bool { return i >= 0 && i <= MaxIndex && i != ReservedIndex } -func ConsolePort(i int) int { return PortBase + PortStep*i } -func AdbPort(i int) int { return ConsolePort(i) + 1 } -func GrpcPort(i int) int { return ConsolePort(i) + 2 } -func AvdName(i int) string { return AvdNamePrefix + strconv.Itoa(i) } -func Serial(i int) string { return "emulator-" + strconv.Itoa(ConsolePort(i)) } +func AvdName(i int) string { return AvdNamePrefix + strconv.Itoa(i) } -// IndexOfConsolePort maps 20000 + 10*i back to i; ok=false for any other port. -func IndexOfConsolePort(port int) (int, bool) { - if port < PortBase || (port-PortBase)%PortStep != 0 { +// The ports of an instance depend on its root (portBase): ask the root, r.Ports().Console(i) and so on. There is +// deliberately no package-level ConsolePort / Serial, so that nothing silently counts from 20000. + +// ---- a root's own port plan (ModAVD/ModAVD#75)-------------------------------------------------------------------- + +// MetadataPortBase is the mas-avd.json key of a root's own port plan. Development and test roots set it, so that their +// instances never take the ports of the production root's instance of the same number: AUTO-MAS tells instances +// apart by port and would take one for the other. AUTO-MAS does not read it (its PORT_BASE is a constant), so a root +// that sets it is not one to add to AUTO-MAS. +const MetadataPortBase = "portBase" + +const ( + // DefaultPortBase is the plan of every root without portBase: AUTO-MAS's PORT_BASE. + DefaultPortBase = PortBase + // A portBase other than DefaultPortBase is a multiple of 100 in minPortBase-maxPortBase: each plan then has a + // segment of 100 ports of its own (it uses 93 of them), which never overlaps DefaultPortBase's 20000-20099, and + // stays above the privileged ports and below 65536. + minPortBase = 1100 + maxPortBase = 65400 +) + +// PortPlan is the ports of a root's instances: console Base + PortStep*i, adb +1, gRPC +2. The emulator names its +// screenshot shared memory after the console port (SHM_videmulator), so that follows too. +type PortPlan struct{ Base int } + +func (p PortPlan) Console(i int) int { return p.Base + PortStep*i } +func (p PortPlan) Adb(i int) int { return p.Console(i) + 1 } +func (p PortPlan) Grpc(i int) int { return p.Console(i) + 2 } +func (p PortPlan) Serial(i int) string { return "emulator-" + strconv.Itoa(p.Console(i)) } + +// Last is the highest port of the plan: the gRPC port of MaxIndex. +func (p PortPlan) Last() int { return p.Grpc(MaxIndex) } + +// IndexOfConsole maps Base + PortStep*i back to i; ok=false for any other port. +func (p PortPlan) IndexOfConsole(port int) (int, bool) { + if port < p.Base || (port-p.Base)%PortStep != 0 { return 0, false } - i := (port - PortBase) / PortStep + i := (port - p.Base) / PortStep return i, i <= MaxIndex } -// InstancePorts is every console / adb / gRPC port of every valid index; configured server ports must avoid them. -func InstancePorts() map[int]bool { +// InstancePorts is every console / adb / gRPC port of every valid index. Index 5 stays out of every plan, as in +// AUTO-MAS's, although outside the default plan its ports no longer meet the default private adb server. +func (p PortPlan) InstancePorts() map[int]bool { ports := map[int]bool{} for i := 0; i <= MaxIndex; i++ { if ValidIndex(i) { - c := ConsolePort(i) + c := p.Console(i) ports[c], ports[c+1], ports[c+2] = true, true, true } } return ports } +// Ports is the root's port plan: mas-avd.json's portBase when valid, else DefaultPortBase. Read each time, like +// AdbServerPort: change portBase only while none of the root's instances runs. An invalid portBase reads as +// DefaultPortBase, so that status still finds what runs (an instance is matched by its AVD directory, never by its +// ports alone); CheckPorts keeps anything from being started with it. +func (r *Root) Ports() PortPlan { + p, _ := portPlan(r.MetadataLoose().Obj()) + return p +} + +// PortPlanOf is Ports for a mas-avd.json read already (o nil: none), for the reports, which read the file themselves; +// problem says why portBase is not valid ("" when it is, or is not there). +func PortPlanOf(o *jsonord.Obj) (plan PortPlan, problem string) { return portPlan(o) } + +// CheckPorts is nil when instances of this root may be started, else an errs.InvalidArgument error saying what to fix +// in mas-avd.json: +// - portBase is there but not valid (DefaultPortBase, or a multiple of 100 in minPortBase-maxPortBase); +// - portBase moves the instances off the default plan while the private or the script adb server is still on a +// default port (20050, 20049), or on a port of the default plan's instances: those are the production root's, and +// the point of a plan of one's own is to share nothing with it. +func (r *Root) CheckPorts() *errs.Error { + o := r.MetadataLoose().Obj() + p, problem := portPlan(o) + if problem != "" { + return errs.New(errs.InvalidArgument, problem).WithAdvice(fmt.Sprintf( + "改成 %d(和 AUTO-MAS 一样),或者 %d–%d 之间 100 的整数倍(开发和测试用的根目录用 21000),再试", + DefaultPortBase, minPortBase, maxPortBase)) + } + if p.Base == DefaultPortBase { + return nil + } + production := PortPlan{DefaultPortBase}.InstancePorts() + for _, s := range []struct { + key string + port int + }{{"adbServerPort", adbServerPort(o)}, {"scriptAdbServerPort", scriptAdbServerPort(o)}} { + if s.port == DefaultAdbServerPort || s.port == DefaultScriptAdbServerPort || production[s.port] { + return errs.Newf(errs.InvalidArgument, + "mas-avd.json 设了 %s %d(开发、测试用的端口段),%s 却是 %d:默认的根目录(生产)也用这个端口", + MetadataPortBase, p.Base, s.key, s.port).WithAdvice(fmt.Sprintf( + "在 mas-avd.json 里把 adbServerPort 和 scriptAdbServerPort 都设成别的端口:不是 %d、%d,也不在 %d–%d 的实例端口上", + DefaultAdbServerPort, DefaultScriptAdbServerPort, DefaultPortBase, PortPlan{DefaultPortBase}.Last())) + } + } + return nil +} + +// portPlan is the plan o's portBase gives and, when portBase is there but not valid, why (the plan is then +// DefaultPortBase's). Read as the adb server ports are (Python's int(): "21000" and 21000.0 count too). +func portPlan(o *jsonord.Obj) (PortPlan, string) { + if !o.Has(MetadataPortBase) { + return PortPlan{DefaultPortBase}, "" + } + v := o.Get(MetadataPortBase) + if b, ok := pyIntOfValue(v); ok && (b == DefaultPortBase || (b%100 == 0 && b >= minPortBase && b <= maxPortBase)) { + return PortPlan{int(b)}, "" + } + return PortPlan{DefaultPortBase}, fmt.Sprintf("mas-avd.json 的 %s 不合规(%s):要 %d,或者 %d–%d 之间 100 的整数倍", + MetadataPortBase, jsonOneLine(v), DefaultPortBase, minPortBase, maxPortBase) +} + +var jsonBreak = regexp.MustCompile(`\r?\n\s*`) + +// jsonOneLine is v as mas-avd.json would hold it, on one line (for messages): a string never holds a raw line break. +func jsonOneLine(v *jsonord.Value) string { + return jsonBreak.ReplaceAllString(string(v.MarshalPython()), "") +} + // ---- layout ------------------------------------------------------------------------------------------------------ const ( @@ -559,7 +657,17 @@ func (r *Root) AdbServerPort() int { // ScriptAdbServerPort is mas-avd.json scriptAdbServerPort when valid and different from AdbServerPort, else // DefaultScriptAdbServerPort, or FallbackScriptAdbServerPort when that equals the private port. func (r *Root) ScriptAdbServerPort() int { - o := r.MetadataLoose().Obj() + return scriptAdbServerPort(r.MetadataLoose().Obj()) +} + +func adbServerPort(o *jsonord.Obj) int { + if port, ok := metadataPort(o, "adbServerPort"); ok { + return port + } + return DefaultAdbServerPort +} + +func scriptAdbServerPort(o *jsonord.Obj) int { private := adbServerPort(o) if port, ok := metadataPort(o, "scriptAdbServerPort"); ok && port != private { return port @@ -570,18 +678,14 @@ func (r *Root) ScriptAdbServerPort() int { return FallbackScriptAdbServerPort } -func adbServerPort(o *jsonord.Obj) int { - if port, ok := metadataPort(o, "adbServerPort"); ok { - return port - } - return DefaultAdbServerPort -} - // metadataPort is AUTO-MAS _metadata_port: int(raw) (so "20089" and 20089.0 count too), then 1024-65535, not 5037, -// not an instance port. +// not a port of the root's instances (its own plan's, see portPlan; AUTO-MAS knows only the default plan). func metadataPort(o *jsonord.Obj, key string) (int, bool) { port, ok := pyIntOfValue(o.Get(key)) - if !ok || port < 1024 || port > 65535 || port == 5037 || InstancePorts()[int(port)] { + if !ok || port < 1024 || port > 65535 || port == 5037 { + return 0, false + } + if plan, _ := portPlan(o); plan.InstancePorts()[int(port)] { return 0, false } return int(port), true diff --git a/internal/root/root_test.go b/internal/root/root_test.go index 188b86ba..ddb616ef 100644 --- a/internal/root/root_test.go +++ b/internal/root/root_test.go @@ -90,8 +90,9 @@ func python(t *testing.T, script string, input any) []byte { // ---- ports ------------------------------------------------------------------------------------------------------- func TestPortsAndNames(t *testing.T) { - if ConsolePort(3) != 20030 || AdbPort(3) != 20031 || GrpcPort(3) != 20032 || AvdName(3) != "mas_3" || - Serial(3) != "emulator-20030" { + def := PortPlan{DefaultPortBase} + if def.Console(3) != 20030 || def.Adb(3) != 20031 || def.Grpc(3) != 20032 || AvdName(3) != "mas_3" || + def.Serial(3) != "emulator-20030" { t.Fatal("port plan") } for i, want := range []bool{true, true, true, true, true, false, true, true, true, true, false} { @@ -102,20 +103,110 @@ func TestPortsAndNames(t *testing.T) { if ValidIndex(-1) { t.Error("ValidIndex(-1)") } - if i, ok := IndexOfConsolePort(20090); !ok || i != 9 { + if i, ok := def.IndexOfConsole(20090); !ok || i != 9 { t.Error("20090") } for _, p := range []int{19990, 20001, 20100, 5554} { - if _, ok := IndexOfConsolePort(p); ok { - t.Errorf("IndexOfConsolePort(%d)", p) + if _, ok := def.IndexOfConsole(p); ok { + t.Errorf("IndexOfConsole(%d)", p) } } - ports := InstancePorts() + ports := def.InstancePorts() if len(ports) != 27 || !ports[20000] || !ports[20092] || ports[20050] || ports[20051] || ports[20049] { t.Fatalf("InstancePorts: %d", len(ports)) } } +// TestPortPlan: another base moves every port and the serial, and the index set (0-9 without 5) stays. +func TestPortPlan(t *testing.T) { + def, dev := PortPlan{DefaultPortBase}, PortPlan{21000} + if dev.Console(6) != 21060 || dev.Adb(6) != 21061 || dev.Grpc(6) != 21062 || dev.Serial(6) != "emulator-21060" || + dev.Last() != 21092 || def.Last() != 20092 { + t.Fatal("plan 21000") + } + if i, ok := dev.IndexOfConsole(21090); !ok || i != 9 { + t.Error("21090") + } + for _, p := range []int{20000, 20060, 21001, 21100, 20990} { + if _, ok := dev.IndexOfConsole(p); ok { + t.Errorf("plan 21000: IndexOfConsole(%d)", p) + } + } + ports := dev.InstancePorts() + if len(ports) != 27 || !ports[21000] || !ports[21092] || ports[21050] || ports[20000] { + t.Fatalf("plan 21000: InstancePorts %d", len(ports)) + } +} + +// TestPortBase: mas-avd.json portBase, read as the adb server ports are; the instance ports the server ports must +// avoid are the root's own plan's; CheckPorts refuses an invalid portBase, and a plan of one's own that still shares +// an adb server port with the default root. +func TestPortBase(t *testing.T) { + r := newRoot(t) + if r.Ports().Base != DefaultPortBase || r.CheckPorts() != nil { + t.Fatal("no mas-avd.json") + } + const servers = `, "adbServerPort": 20089, "scriptAdbServerPort": 20088` + for _, c := range []struct { + value string + base int + ok bool + }{ + {`20000`, 20000, true}, {`21000`, 21000, true}, {`"21000"`, 21000, true}, {`21000.0`, 21000, true}, + {`1100`, 1100, true}, {`65400`, 65400, true}, {`19900`, 19900, true}, {`20100`, 20100, true}, + {`21050`, 20000, false}, {`21010`, 20000, false}, {`1000`, 20000, false}, {`65500`, 20000, false}, + {`-21000`, 20000, false}, {`"abc"`, 20000, false}, {`null`, 20000, false}, {`true`, 20000, false}, + {`[21000]`, 20000, false}, {`{}`, 20000, false}, {`""`, 20000, false}, + } { + writeFile(t, r.MetadataPath(), []byte(`{"portBase": `+c.value+servers+`}`)) + if got := r.Ports().Base; got != c.base { + t.Errorf("portBase %s: base %d, want %d", c.value, got, c.base) + } + err := r.CheckPorts() + if c.ok != (err == nil) { + t.Errorf("portBase %s: CheckPorts %v", c.value, err) + } + if err != nil && (err.Code != errs.InvalidArgument || !strings.Contains(err.Message, "portBase 不合规("+c.value+")")) { + t.Errorf("portBase %s: %s %q", c.value, err.Code, err.Message) + } + } + + // the server ports must avoid the root's own instance ports: 21011 is one with portBase 21000, 20011 is not + writeFile(t, r.MetadataPath(), []byte(`{"portBase": 21000, "adbServerPort": 21011, "scriptAdbServerPort": 20011}`)) + if r.AdbServerPort() != DefaultAdbServerPort || r.ScriptAdbServerPort() != 20011 { + t.Fatalf("server ports %d %d", r.AdbServerPort(), r.ScriptAdbServerPort()) + } + writeFile(t, r.MetadataPath(), []byte(`{"adbServerPort": 21011, "scriptAdbServerPort": 20011}`)) + if r.AdbServerPort() != 21011 || r.ScriptAdbServerPort() != DefaultScriptAdbServerPort { + t.Fatalf("default plan: server ports %d %d", r.AdbServerPort(), r.ScriptAdbServerPort()) + } + + // a plan of one's own with an adb server port of the default root's: refused, naming the key + for _, c := range []struct{ meta, key string }{ + {`{"portBase": 21000}`, "adbServerPort"}, + {`{"portBase": 21000, "adbServerPort": 20089}`, "scriptAdbServerPort"}, + {`{"portBase": 21000, "adbServerPort": 20049, "scriptAdbServerPort": 20088}`, "adbServerPort"}, + {`{"portBase": 21000, "adbServerPort": 20089, "scriptAdbServerPort": 20050}`, "scriptAdbServerPort"}, + {`{"portBase": 21000, "adbServerPort": 20011, "scriptAdbServerPort": 20088}`, "adbServerPort"}, + {`{"portBase": 21000, "adbServerPort": 20089, "scriptAdbServerPort": 20092}`, "scriptAdbServerPort"}, + } { + writeFile(t, r.MetadataPath(), []byte(c.meta)) + err := r.CheckPorts() + if err == nil || err.Code != errs.InvalidArgument || !strings.Contains(err.Message, c.key+" 却是") { + t.Errorf("%s: %v", c.meta, err) + } + } + writeFile(t, r.MetadataPath(), []byte(`{"portBase": 21000`+servers+`}`)) + if err := r.CheckPorts(); err != nil { + t.Fatal(err) + } + // the default plan keeps the default servers, as every root has them today + writeFile(t, r.MetadataPath(), []byte(`{"portBase": 20000}`)) + if err := r.CheckPorts(); err != nil { + t.Fatal(err) + } +} + // ---- resolve ----------------------------------------------------------------------------------------------------- func TestResolve(t *testing.T) { diff --git a/internal/ui/backend.go b/internal/ui/backend.go index fac86d56..c49550e7 100644 --- a/internal/ui/backend.go +++ b/internal/ui/backend.go @@ -25,6 +25,8 @@ type backend interface { InstallAPK(ctx context.Context, i int, apkPath string) (*emu.InstallResult, 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. + Serial(i int) string // RootInfo describes the root without asking any instance (GET /api/info). RootInfo() emu.RootInfo } @@ -38,6 +40,8 @@ func (b managerBackend) AdbRun(ctx context.Context, opt adb.RunOptions, args ... return b.ADB.Run(ctx, opt, args...) } +func (b managerBackend) Serial(i int) string { return b.Root.Ports().Serial(i) } + // RootInfo is what emu fills into ListResult / CheckResult (emu's own helper is unexported); List would cost an adb // call per running instance. func (b managerBackend) RootInfo() emu.RootInfo { @@ -49,6 +53,7 @@ func (b managerBackend) RootInfo() emu.RootInfo { AdbExe: r.AdbExe(), AdbServerPort: r.AdbServerPort(), ScriptAdbServerPort: r.ScriptAdbServerPort(), + PortBase: r.Ports().Base, Version: r.VersionText(), } if n, ok := r.ModBuild(); ok { diff --git a/internal/ui/device.go b/internal/ui/device.go index b56b47d3..395a4ee3 100644 --- a/internal/ui/device.go +++ b/internal/ui/device.go @@ -13,7 +13,6 @@ import ( "modavd/internal/adb" "modavd/internal/emu" "modavd/internal/errs" - "modavd/internal/root" ) const ( @@ -133,7 +132,7 @@ func (s *server) captureOnce(ctx context.Context, i int) ([]byte, error) { if in, ok := s.hub.cachedInstance(i, statusMaxAge); ok && !in.Running { return nil, notBooted(i) } - res := s.mgr.AdbRun(ctx, adb.RunOptions{Serial: root.Serial(i), Timeout: shotTimeout, Raw: true}, + res := s.mgr.AdbRun(ctx, adb.RunOptions{Serial: s.mgr.Serial(i), Timeout: shotTimeout, Raw: true}, "exec-out", "screencap", "-p") if res.Code == 0 && bytes.HasPrefix(res.Stdout, pngSignature) { return res.Stdout, nil diff --git a/internal/ui/device_test.go b/internal/ui/device_test.go index 37b94cb1..ae9f3c57 100644 --- a/internal/ui/device_test.go +++ b/internal/ui/device_test.go @@ -21,8 +21,29 @@ import ( "modavd/internal/adb" "modavd/internal/emu" "modavd/internal/errs" + "modavd/internal/root" ) +// TestManagerBackendSerial: the real backend counts the serial of the screenshot from the root's port plan. +func TestManagerBackendSerial(t *testing.T) { + dir := t.TempDir() + meta := `{"portBase": 21000, "adbServerPort": 21099, "scriptAdbServerPort": 21098}` + 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) + } + b := managerBackend{emu.New(r, nil)} + if got := b.Serial(6); got != "emulator-21060" { + t.Errorf("Serial(6) = %s", got) + } + if got := b.RootInfo().PortBase; got != 21000 { + t.Errorf("RootInfo().PortBase = %d", got) + } +} + func TestScreenshot(t *testing.T) { h := newHarness(t, nil) h.f.put(3, emu.StatusOnline) @@ -55,6 +76,13 @@ func TestScreenshot(t *testing.T) { if n := h.f.adbCalls.Load(); n != 1 { t.Fatalf("%d captures for five concurrent requests", n) } + // the serial is the root's (portBase 21000 in the fake), never counted from 20000 here + h.f.mu.Lock() + serials := append([]string(nil), h.f.shotSerials...) + h.f.mu.Unlock() + if len(serials) != 1 || serials[0] != "emulator-21030" { + t.Fatalf("captured serials %q", serials) + } // a capture younger than 300 ms is served again expect(t, h.do("GET", "/api/instances/3/screenshot", nil), 200, nil) if n := h.f.adbCalls.Load(); n != 1 { diff --git a/internal/ui/fake_test.go b/internal/ui/fake_test.go index 19602ea4..9b3b2b59 100644 --- a/internal/ui/fake_test.go +++ b/internal/ui/fake_test.go @@ -45,11 +45,12 @@ type fake struct { startGate chan struct{} // Start waits here (after its first progress) when set stopGate chan struct{} - shot adb.Result - shotDelay time.Duration - adbCalls atomic.Int32 - listCalls atomic.Int32 - checks atomic.Int32 + shot adb.Result + shotDelay time.Duration + shotSerials []string // the serial of each capture + adbCalls atomic.Int32 + listCalls atomic.Int32 + checks atomic.Int32 } type fakeInstall struct { @@ -69,7 +70,7 @@ func (f *fake) put(i int, st emu.Status) { defer f.mu.Unlock() f.instances[i] = emu.InstanceInfo{ Index: i, Name: root.AvdName(i), Title: root.AvdName(i), Status: st, - Running: st != emu.StatusOffline, Booted: st == emu.StatusOnline, Serial: root.Serial(i), + Running: st != emu.StatusOffline, Booted: st == emu.StatusOnline, Serial: fakePorts.Serial(i), Config: emu.InstanceConfig{MemoryMB: 6144, CPU: 6, FPS: 60, Width: 1280, Height: 720, DPI: 240}, } } @@ -81,8 +82,11 @@ func (f *fake) get(i int) (emu.InstanceInfo, bool) { return in, ok } -var fakeRoot = emu.RootInfo{Root: `C:\fake-root`, SDK: `C:\fake-root\sdk`, AdbServerPort: 20050, - ScriptAdbServerPort: 20049, Version: "0.35.0", Build: 35} +// The fake root has a port plan of its own (portBase 21000), so a serial counted from 20000 anywhere shows. +var fakeRoot = emu.RootInfo{Root: `C:\fake-root`, SDK: `C:\fake-root\sdk`, AdbServerPort: 21099, + ScriptAdbServerPort: 21098, PortBase: 21000, Version: "0.35.0", Build: 35} + +var fakePorts = root.PortPlan{Base: fakeRoot.PortBase} // fakeBackend is one backend built by the server (per job, per request kind) over the shared fake. type fakeBackend struct { @@ -237,6 +241,7 @@ func (b fakeBackend) AdbRun(ctx context.Context, opt adb.RunOptions, args ...str b.f.adbCalls.Add(1) b.f.mu.Lock() res, delay := b.f.shot, b.f.shotDelay + b.f.shotSerials = append(b.f.shotSerials, opt.Serial) b.f.mu.Unlock() if delay > 0 { select { @@ -250,6 +255,8 @@ func (b fakeBackend) AdbRun(ctx context.Context, opt adb.RunOptions, args ...str func (b fakeBackend) RootInfo() emu.RootInfo { return fakeRoot } +func (b fakeBackend) Serial(i int) string { return fakePorts.Serial(i) } + // ---- harness ----------------------------------------------------------------------------------------------------- type harness struct { diff --git a/internal/ui/web/js/forms.js b/internal/ui/web/js/forms.js index 2e14be6a..1ffe521c 100644 --- a/internal/ui/web/js/forms.js +++ b/internal/ui/web/js/forms.js @@ -74,10 +74,12 @@ export function openCreate() { const idx = h('select', { class: 'select', id: 'c-index' }, h('option', { value: '', text: `自动(编号 ${free[0]})` }), free.map((i) => h('option', { value: String(i), text: `编号 ${i}` }))); const idxHint = hint(''); + // the root's port plan (mas-avd.json portBase); a manager without port_base only knows 20000 + const base = S.list.port_base || 20000; const sync = () => { const i = idx.value === '' ? free[0] : Number(idx.value); titleHint.textContent = `不填就显示 mas_${i},以后可以随时改`; - idxHint.replaceChildren('编号决定端口,脚本连 ', h('b', { text: `127.0.0.1:${20001 + 10 * i}` })); + idxHint.replaceChildren('编号决定端口,脚本连 ', h('b', { text: `127.0.0.1:${base + 1 + 10 * i}` })); }; idx.addEventListener('change', sync); sync();