From 409619cf9eb7281019c761386afd97dce6abe7e3 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sun, 29 Nov 2026 22:02:35 +0100 Subject: [PATCH 1/6] =?UTF-8?q?=E5=85=B3=E6=9C=BA=E5=89=8D=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E6=B8=B8=E6=88=8F=E6=98=AF=E5=90=A6=E5=9C=A8=E4=B8=8B?= =?UTF-8?q?=E8=BD=BD=E5=B9=B6=E5=AD=98=E5=AE=A2=E4=BD=93=E5=86=85=E6=A0=B8?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 正常关机在按 HOME 之前查明日方舟(两个包)和终末地的 HGDownloadService 是否在跑,在跑就记一条警告;再把客体内核日志存到 logs\mas_-<时间>-kernel.txt(最多 4 MiB,留最新的,每实例最多 5 份)。这一步只占在最坏情况下仍给安卓留 14 秒的时间,最多 4 秒,失败只记日志,强制关机、私有 adb 不可用、刚拉起的模拟器都不做。 Refs ModAVD/ModAVD#89 --- internal/emu/stop.go | 17 +- internal/emu/stop_record.go | 286 +++++++++++++++++ internal/emu/stop_record_test.go | 374 +++++++++++++++++++++++ internal/emu/stop_record_windows_test.go | 143 +++++++++ internal/i18n/locales/en/emu.json | 11 + 5 files changed, 830 insertions(+), 1 deletion(-) create mode 100644 internal/emu/stop_record.go create mode 100644 internal/emu/stop_record_test.go create mode 100644 internal/emu/stop_record_windows_test.go diff --git a/internal/emu/stop.go b/internal/emu/stop.go index b8ae1db3..ddb44b39 100644 --- a/internal/emu/stop.go +++ b/internal/emu/stop.go @@ -25,7 +25,9 @@ package emu // look at the guest (guestShutdownProbe, at most shutdownProbeTimeout), inside that same window, so it moves no limit. // Making the private adb usable (adb.Client.PrepareForClose) takes at most adbServerStartOnClose, the try to bring an // offline instance back (ModAVD/ModAVD#292) included. adb commands here never re-register (that costs 5 s more), -// and starting the private server counts against the command's own limit (TotalTimeout). +// and starting the private server counts against the command's own limit (TotalTimeout). Between prepare and HOME, +// the normal path records whether a game is downloading and saves the guest kernel log (stop_record.go, +// ModAVD/ModAVD#89), within beforeShutdownBudget: only what leaves Android its worst-case 14 s, so no limit moves. // // A stop that comes while a start holds the start lock but has not launched qemu yet (prechecks, the private server // ...) waits for that qemu, up to startingQemuWait (10 s), and keeps holding the stop lock all the while. A start @@ -269,6 +271,9 @@ type stopOps struct { // prepare makes the private adb server usable for this instance (adb.Client.PrepareForClose): what the server had // of it (StopResult.AdbState), and "" when it is usable, else why not. prepare func() (state, problem string) + // beforeShutdown records what a later look at the instance needs (ModAVD/ModAVD#89, stop_record.go: whether a game + // is downloading, the guest kernel log) within budget; best effort, never fails. nil: nothing to record. + beforeShutdown func(budget time.Duration) // home sends an app in the foreground home within timeout (guestHomeScript): sent, and adb's output when the // command failed ("" when it ran). home func(timeout time.Duration) (bool, string) @@ -396,6 +401,11 @@ func runStop(ctx context.Context, log *logx.Logger, i int, force bool, started t log.Warnf("ModAVD 实例 %d 私有 adb 用不了,不能正常关机也不能 sync,直接用控制台关: %s", i, problem) return endQemu(ctx, log, i, "console_kill", false, consoleKillTimeout+closeTimeout, forceKillWait, ops) } + // While the game is still in front and its downloader still runs; within a budget that leaves Android's window its + // worst-case minimum (stop_record.go). Only a cancel stops the shutdown here. + if err := beforeShutdown(ctx, log, i, time.Since(started), ops.beforeShutdown); err != nil { + return "graceful", false, err + } // The foreground app goes home first and gets homeWait; the sync below takes what it wrote along (see the header // comment). A failure is only a warning. if err := sendHome(ctx, log, i, ops.home); err != nil { @@ -518,6 +528,11 @@ func (m *Manager) stopOpsFor(ctx context.Context, i int, p host.Process) stopOps } return stopOps{ prepare: func() (string, string) { return m.ADB.PrepareForClose(ctx, console, adbServerStartOnClose) }, + beforeShutdown: func(budget time.Duration) { + m.recordBeforeShutdown(i, budget, func(command string, timeout time.Duration) adb.Result { + return closeRun(timeout, "shell", command) + }, time.Now) + }, home: func(timeout time.Duration) (bool, string) { res := closeRun(timeout, "shell", guestHomeScript) if res.Code != 0 { diff --git a/internal/emu/stop_record.go b/internal/emu/stop_record.go new file mode 100644 index 00000000..ab9736c4 --- /dev/null +++ b/internal/emu/stop_record.go @@ -0,0 +1,286 @@ +package emu + +// What a normal stop records before it shuts the guest down (ModAVD/ModAVD#89). Arknights now and then fails to reload +// its assets after START ("[ResourceManager] Init failed"), judges its local resources invalid and downloads all +// 14 GB again on the next start. Why is not known: the guest storage may have handed it wrong data, the game may have +// broken its own index, or a download may have been cut off by a shutdown. End users do not look into the guest, so a +// stop leaves two pieces of evidence on the host, while the game is still in front and its download service still +// runs (before sendHome): +// +// - whether Arknights (both packages) or Endfield, which uses the same downloader, has its HGDownloadService +// running: a warning when it does, since the shutdown then cuts that download off; +// - the guest kernel log, saved to \logs\mas_--kernel.txt (at most shutdownKernelLogMax +// bytes, the newest kept; the newest shutdownKernelLogKeep per instance), so storage errors of the session that +// ends here survive the reboot that clears the guest's buffer. The problem report takes these files along; the name +// deliberately does not match report.logName (the stamp is followed by -kernel), like -clocksource.txt. +// +// Both are best effort: each command has its own timeout, every problem is a log line, and the stop goes on. Only the +// normal path does this (adb usable, not Force, not a qemu that is still launching): a forced stop must be quick and a +// guest that is not up has nothing to tell. +// +// Time: this step comes right after prepare and counts against the graceful window, which runs until gracefulDeadline +// from the first look. It gets beforeShutdownBudget: at most beforeShutdownMax, and only what keeps Android's window at +// gracefulWindowMin even when HOME, the wait after it and the sync before the shutdown command all take their full +// time afterwards. The existing worst case (prepare 4 s + HOME 2 + homeWait 2 + sync 2 => 14 s for Android) therefore +// stays as it was: a prepare that used all of adbServerStartOnClose leaves this step nothing and it is skipped. The +// fallback after gracefulDeadline (fallbackKillTimeout) is not affected at all, since the graceful window still ends at +// gracefulDeadline. With a prepare that takes tens of ms (the usual case) the step may use about 4 s, and both commands +// are usually answered in well under one; Android's window then shrinks by what they really took. + +import ( + "context" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "time" + + "modavd/internal/adb" + "modavd/internal/logx" + "modavd/internal/root" +) + +const ( + // hgDownloadCommand lists the running services of the Hypergryph games: dumpsys activity services takes component + // specs, and a plain word matches every service whose flattened component name (package/class) contains it, so + // com.hypergryph.arknights also covers com.hypergryph.arknights.bilibili. One fixed command line, no variables or + // pipes: the output is read here, on the host. Runs as shell (it holds DUMP), no su. + hgDownloadCommand = "dumpsys activity services com.hypergryph.arknights com.hypergryph.endfield" + // hgDownloadService is the downloader's service class (its simple name, matched case-insensitively). + hgDownloadService = "HGDownloadService" + // hgDownloadTimeout bounds hgDownloadCommand (answered in tens of ms by a guest that runs normally). + hgDownloadTimeout = 1500 * time.Millisecond + + // shutdownKernelLogMax bounds a saved kernel log, header included; shutdownKernelLogKeep: saved per instance. + shutdownKernelLogMax = 4 << 20 + shutdownKernelLogKeep = 5 + shutdownKernelSuffix = "-kernel.txt" + // shutdownKernelMinTime: a kernel log read with less time left than this is not tried. + shutdownKernelMinTime = 500 * time.Millisecond + + // gracefulWindowMin is what Android gets at least in the worst case of the graceful path (see TestGracefulBudget); + // beforeShutdownBudget keeps it. + gracefulWindowMin = 14 * time.Second + // beforeShutdownMin: with a budget below this the step is skipped. + beforeShutdownMin = time.Second +) + +// beforeShutdownMax caps the step; beforeShutdownGrace is how much longer runStop waits for a step that overran its +// budget (its adb commands have their own timeouts, so this only guards against a hang). Variables for tests. +var ( + beforeShutdownMax = 4 * time.Second + beforeShutdownGrace = time.Second +) + +// beforeShutdownBudget is the step's time when it starts elapsed after the first look: at most beforeShutdownMax, and +// no more than leaves Android gracefulWindowMin after HOME, the wait after it and the sync take their full time (see +// the header comment). Below beforeShutdownMin (or negative) the step is skipped. +func beforeShutdownBudget(elapsed time.Duration) time.Duration { + return min(beforeShutdownMax, + gracefulDeadline-gracefulWindowMin-homeTimeout-homeWait-shutdownSyncTimeout-elapsed) +} + +// beforeShutdown runs step (stopOps.beforeShutdown) with its budget, elapsed after the first look, and waits for it at +// most budget + beforeShutdownGrace: a step that hangs is left behind and the stop goes on. errs.Canceled when ctx is +// canceled by the end of it (the stop then sends no HOME and no shutdown, like a cancel anywhere else); nil otherwise. +// A nil step (tests that do not care) does nothing. +func beforeShutdown(ctx context.Context, log *logx.Logger, i int, elapsed time.Duration, step func(budget time.Duration)) error { + if step == nil { + return nil + } + budget := beforeShutdownBudget(elapsed) + if budget < beforeShutdownMin { + log.Debugf("ModAVD 实例 %d 关机前前面已经用了 %.1f 秒,不再查下载和存内核日志", i, elapsed.Seconds()) + return nil + } + done := make(chan struct{}) + go func() { + defer close(done) + step(budget) + }() + timer := time.NewTimer(budget + beforeShutdownGrace) + defer timer.Stop() + select { + case <-done: + case <-ctx.Done(): + case <-timer.C: + log.Debugf("ModAVD 实例 %d 关机前查下载、存内核日志 %.0f 秒内没做完,不等了,照常关机", i, budget.Seconds()) + } + return stopCanceled(ctx, i) +} + +// recordBeforeShutdown is the real step: the download check, then the kernel log with what is left of budget. run is +// a guest shell command line on the instance's private adb. Never fails: every problem is a log line. +func (m *Manager) recordBeforeShutdown(i int, budget time.Duration, run func(command string, timeout time.Duration) adb.Result, + now func() time.Time) { + started := time.Now() + m.logHGDownloads(i, run(hgDownloadCommand, min(hgDownloadTimeout, budget))) + left := budget - time.Since(started) + if left < shutdownKernelMinTime { + m.Log.Debugf("ModAVD 实例 %d 关机前没时间存内核日志了(剩 %.1f 秒)", i, left.Seconds()) + return + } + res := run(clocksourceKernelCommand, left) + path, err := m.saveShutdownKernelLog(i, res, now()) + if err != nil { + m.Log.Debugf("ModAVD 实例 %d 关机前的客体内核日志没存下: %v", i, err) + return + } + m.Log.Debugf("ModAVD 实例 %d 关机前的客体内核日志已存到 %s", i, path) +} + +// hgDownload is one running HGDownloadService (parseHGDownloads). +type hgDownload struct { + Package string // the package before "/" in the component + Component string // as dumpsys prints it, e.g. com.hypergryph.arknights/com.hg.sdk.HGDownloadService + Foreground bool // isForeground=true seen in its record (dumpsys prints it only in some modes) +} + +// logHGDownloads logs what parseHGDownloads finds in hgDownloadCommand's result: a warning per running download. +func (m *Manager) logHGDownloads(i int, res adb.Result) { + running, known := parseHGDownloads(res.Out) + switch { + case res.Code != 0 || !known: + m.Log.Debugf("ModAVD 实例 %d 关机前查不了游戏是不是在下载: %s", i, + orText(tail(strings.Join(strings.Fields(res.Out), " "), 200), fmt.Sprintf("退出码 %d", res.Code))) + case len(running) == 0: + m.Log.Debugf("ModAVD 实例 %d 关机时没有游戏在下载(没有 %s 在跑)", i, hgDownloadService) + default: + for _, d := range running { + m.Log.Warnf("ModAVD 实例 %d 关机时 %s 正在下载(%s 在跑),这次下载会被打断", i, d.Package, hgDownloadService) + m.Log.Debugf("ModAVD 实例 %d 关机时在跑的下载服务: %s,前台服务 %v", i, d.Component, d.Foreground) + } + } +} + +// serviceRecordLine is a service in dumpsys activity services: " * ServiceRecord{1a2b3c u0 pkg/.Class}" (the hash, +// the user, the short component, optionally more words before "}"). +var serviceRecordLine = regexp.MustCompile(`^\s*\*\s*ServiceRecord\{[0-9a-fA-F]+\s+u\d+\s+([^\s}]+)[^}]*\}`) + +// parseHGDownloads reads hgDownloadCommand's output (ActiveServices' dump; the exact text differs between Android +// versions, so this only relies on the section headers and the ServiceRecord lines). known: it looks like that dump +// (its "ACTIVITY MANAGER SERVICES" header, a "... services:" section or "(nothing)"); an error text is not. running: +// the HGDownloadService records outside the "Restarting" and "Destroying" sections, which list services that do not +// run; one listed twice (e.g. active and pending) counts once. +func parseHGDownloads(out string) (running []hgDownload, known bool) { + section := "" + var current *hgDownload + seen := map[string]bool{} + for _, line := range outputLines(out) { + trimmed := strings.TrimSpace(line) + lower := strings.ToLower(trimmed) + switch { + case strings.HasPrefix(trimmed, "ACTIVITY MANAGER SERVICES") || trimmed == "(nothing)": + known, current = true, nil + continue + case !strings.HasPrefix(trimmed, "*") && strings.HasSuffix(lower, "services:"): + // "User 0 active services:", "Pending services:", "Restarting services:", "Destroying services:", + // "Connection bindings to services:" + known, section, current = true, lower, nil + continue + } + if mm := serviceRecordLine.FindStringSubmatch(line); mm != nil { + current = nil + component := mm[1] + if !strings.Contains(strings.ToLower(component), strings.ToLower(hgDownloadService)) || + strings.Contains(section, "restarting") || strings.Contains(section, "destroying") { + continue + } + pkg, _, _ := strings.Cut(component, "/") + if seen[component] { + for k := range running { + if running[k].Component == component { + current = &running[k] + } + } + continue + } + seen[component] = true + running = append(running, hgDownload{Package: pkg, Component: component}) + current = &running[len(running)-1] + continue + } + if strings.HasPrefix(trimmed, "*") { + current = nil // another record (a ConnectionRecord ...) + continue + } + if current != nil && strings.Contains(trimmed, "isForeground=true") { + current.Foreground = true + } + } + return running, known +} + +// saveShutdownKernelLog writes the kernel log in res (clocksourceKernelCommand's result) to +// \mas_--kernel.txt: a comment line, a line on what was cut when it did not fit, an empty line, then the +// log (LF), at most shutdownKernelLogMax bytes in all, the newest part kept. Then keeps the newest +// shutdownKernelLogKeep of instance i. +func (m *Manager) saveShutdownKernelLog(i int, res adb.Result, now time.Time) (string, error) { + if res.Code != 0 || strings.TrimSpace(res.Out) == "" { + return "", fmt.Errorf("logcat -b kernel -d: %s", orText(tail(res.Out, 200), fmt.Sprintf("退出码 %d", res.Code))) + } + b := shutdownKernelLogContent(i, res.Out, now, shutdownKernelLogMax) + dir := m.Root.LogsDir() + if err := os.MkdirAll(dir, 0o755); err != nil { + return "", err + } + path := filepath.Join(dir, root.AvdName(i)+"-"+now.Format("20060102-150405")+shutdownKernelSuffix) + if err := os.WriteFile(path, b, 0o644); err != nil { + return "", err + } + pruneInstanceLogs(dir, i, shutdownKernelSuffix, shutdownKernelLogKeep) + return path, nil +} + +// shutdownKernelLogContent is the file saveShutdownKernelLog writes, at most limit bytes: when the log does not fit, +// its oldest part is cut at a line start (or, in one huge line, at a character start) and a second comment line says +// how many bytes were cut. +func shutdownKernelLogContent(i int, out string, now time.Time, limit int) []byte { + full := strings.ReplaceAll(out, "\r\n", "\n") + head := fmt.Sprintf("# 实例 %d 关机前的客体内核日志,读于 %s;来源 adb shell %s\n", i, now.Format(time.RFC3339), + clocksourceKernelCommand) + const note = "# 原文 %d 字节,超过上限 %d 字节,截掉了最旧的 %d 字节\n" + var b strings.Builder + b.WriteString(head) + if len(head)+1+len(full) <= limit { + b.WriteString("\n") + b.WriteString(full) + return []byte(b.String()) + } + // room for the log: the note is sized for len(full) bytes cut, which no real cut exceeds + room := max(limit-len(head)-len(fmt.Sprintf(note, len(full), limit, len(full)))-1, 0) + start := len(full) - room + if nl := strings.IndexByte(full[start:], '\n'); nl >= 0 && start+nl+1 < len(full) { + start += nl + 1 + } else { + for start < len(full) && (full[start]&0xC0) == 0x80 { + start++ + } + } + fmt.Fprintf(&b, note, len(full), limit, start) + b.WriteString("\n") + b.WriteString(full[start:]) + return []byte(b.String()) +} + +// pruneInstanceLogs keeps the newest keep files - in dir (by the time in the +// name); best effort. pruneClocksourceLogs is the same for -clocksource.txt. +func pruneInstanceLogs(dir string, i int, suffix string, keep int) { + entries, err := os.ReadDir(dir) + if err != nil { + return + } + re := regexp.MustCompile(`^` + regexp.QuoteMeta(root.AvdName(i)) + `-[0-9]{8}-[0-9]{6}` + regexp.QuoteMeta(suffix) + `$`) + var names []string + for _, e := range entries { + if e.Type().IsRegular() && re.MatchString(e.Name()) { + names = append(names, e.Name()) + } + } + sort.Sort(sort.Reverse(sort.StringSlice(names))) + for _, n := range names[min(keep, len(names)):] { + os.Remove(filepath.Join(dir, n)) + } +} diff --git a/internal/emu/stop_record_test.go b/internal/emu/stop_record_test.go new file mode 100644 index 00000000..4790454c --- /dev/null +++ b/internal/emu/stop_record_test.go @@ -0,0 +1,374 @@ +package emu + +import ( + "context" + "fmt" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" + "time" + "unicode/utf8" + + "modavd/internal/adb" + "modavd/internal/errs" + "modavd/internal/logx" +) + +// A trimmed dumpsys activity services dump (shape of ActiveServices.ServiceDumper; the class names are made up, only +// HGDownloadService is what the step looks for). +const hgDumpRunning = `ACTIVITY MANAGER SERVICES (dumpsys activity services) + User 0 active services: + * ServiceRecord{3f2a1b u0 com.hypergryph.arknights/com.hg.sdk.download.HGDownloadService} + intent={cmp=com.hypergryph.arknights/com.hg.sdk.download.HGDownloadService} + packageName=com.hypergryph.arknights + app=ProcessRecord{77aa 4321:com.hypergryph.arknights:download/u0a120} + isForeground=true foregroundId=1001 foregroundNoti=Notification(channel=download) + * ServiceRecord{4b5c6d u0 com.hypergryph.arknights/com.hg.sdk.push.PushService} + isForeground=false + * ServiceRecord{5c6d7e u0 com.hypergryph.endfield/com.hg.sdk.download.HGDownloadService} + app=ProcessRecord{88bb 5555:com.hypergryph.endfield/u0a130} + + Connection bindings to services: + * ConnectionRecord{99cc u0 CR com.hypergryph.arknights/com.hg.sdk.download.HGDownloadService:@1234} +` + +func TestParseHGDownloads(t *testing.T) { + for _, c := range []struct { + name string + out string + want []hgDownload + unknown bool + }{ + {"two running", hgDumpRunning, []hgDownload{ + {"com.hypergryph.arknights", "com.hypergryph.arknights/com.hg.sdk.download.HGDownloadService", true}, + {"com.hypergryph.endfield", "com.hypergryph.endfield/com.hg.sdk.download.HGDownloadService", false}, + }, false}, + {"bilibili, short class, CRLF", "ACTIVITY MANAGER SERVICES (dumpsys activity services)\r\n User 0 active services:\r\n" + + " * ServiceRecord{a1 u0 com.hypergryph.arknights.bilibili/.HGDownloadService}\r\n", + []hgDownload{{"com.hypergryph.arknights.bilibili", "com.hypergryph.arknights.bilibili/.HGDownloadService", false}}, false}, + {"not downloading", "ACTIVITY MANAGER SERVICES (dumpsys activity services)\n (nothing)\n", nil, false}, + {"other services only", "ACTIVITY MANAGER SERVICES (dumpsys activity services)\n User 0 active services:\n" + + " * ServiceRecord{4b5c6d u0 com.hypergryph.arknights/com.hg.sdk.push.PushService}\n", nil, false}, + // listed only as restarting / being destroyed: not running + {"restarting", "ACTIVITY MANAGER SERVICES (dumpsys activity services)\n Restarting services:\n" + + " * ServiceRecord{a1 u0 com.hypergryph.arknights/.HGDownloadService}\n Destroying services:\n" + + " * ServiceRecord{a2 u0 com.hypergryph.endfield/.HGDownloadService}\n", nil, false}, + // active and pending: once + {"twice", "ACTIVITY MANAGER SERVICES (dumpsys activity services)\n User 0 active services:\n" + + " * ServiceRecord{a1 u0 com.hypergryph.arknights/.HGDownloadService}\n Pending services:\n" + + " * ServiceRecord{a1 u0 com.hypergryph.arknights/.HGDownloadService}\n isForeground=true\n", + []hgDownload{{"com.hypergryph.arknights", "com.hypergryph.arknights/.HGDownloadService", true}}, false}, + {"error text", "error: device offline", nil, true}, + {"cannot run", "/system/bin/sh: dumpsys: inaccessible or not found", nil, true}, + {"empty", "", nil, true}, + } { + running, known := parseHGDownloads(c.out) + if !slices.Equal(running, c.want) || known == c.unknown { + t.Errorf("%s: %+v known %v; want %+v known %v", c.name, running, known, c.want, !c.unknown) + } + } +} + +// fakeShutdownGuest answers the two guest commands of recordBeforeShutdown and records what ran with which timeout. +type fakeShutdownGuest struct { + downloads, kernel adb.Result + delay time.Duration // each command takes this long + ran []string + timeouts []time.Duration +} + +func (g *fakeShutdownGuest) run(command string, timeout time.Duration) adb.Result { + g.ran = append(g.ran, command) + g.timeouts = append(g.timeouts, timeout) + time.Sleep(min(g.delay, timeout)) + switch command { + case hgDownloadCommand: + return g.downloads + case clocksourceKernelCommand: + return g.kernel + } + return adb.Result{Code: 127, Out: "unexpected " + command} +} + +var shutdownNow = time.Date(2026, 11, 29, 21, 5, 7, 0, time.Local) + +func linesAt(lines []clockLine, level logx.Level) []string { + var out []string + for _, l := range lines { + if l.level == level { + out = append(out, l.msg) + } + } + return out +} + +// A running download is a warning per game; none, or an answer that is not the dump, only a debug line. The kernel +// log is saved either way, with what the download check left of the budget. +func TestRecordBeforeShutdownDownloads(t *testing.T) { + kernel := adb.Result{Out: "<6>[ 0.000000] Linux version 6.1\n"} + for _, c := range []struct { + name string + res adb.Result + warns []string + debug string + }{ + {"downloading", adb.Result{Out: hgDumpRunning}, []string{ + "ModAVD 实例 2 关机时 com.hypergryph.arknights 正在下载(HGDownloadService 在跑),这次下载会被打断", + "ModAVD 实例 2 关机时 com.hypergryph.endfield 正在下载(HGDownloadService 在跑),这次下载会被打断"}, + "关机时在跑的下载服务: com.hypergryph.arknights/com.hg.sdk.download.HGDownloadService,前台服务 true"}, + {"not downloading", adb.Result{Out: "ACTIVITY MANAGER SERVICES (dumpsys activity services)\n (nothing)\n"}, nil, + "ModAVD 实例 2 关机时没有游戏在下载(没有 HGDownloadService 在跑)"}, + {"unreadable", adb.Result{Out: "something else entirely"}, nil, + "ModAVD 实例 2 关机前查不了游戏是不是在下载: something else entirely"}, + {"adb failed", adb.Result{Code: 1, Out: "error: closed\n"}, nil, "ModAVD 实例 2 关机前查不了游戏是不是在下载: error: closed"}, + {"adb failed, no output", adb.Result{Code: 255}, nil, "ModAVD 实例 2 关机前查不了游戏是不是在下载: 退出码 255"}, + } { + m, lines := clockManager(t) + g := &fakeShutdownGuest{downloads: c.res, kernel: kernel} + m.recordBeforeShutdown(2, 3*time.Second, g.run, func() time.Time { return shutdownNow }) + if !slices.Equal(linesAt(*lines, logx.Warn), c.warns) { + t.Errorf("%s: warnings %q", c.name, linesAt(*lines, logx.Warn)) + } + if debug := strings.Join(linesAt(*lines, logx.Debug), "\n"); !strings.Contains(debug, c.debug) || + !strings.Contains(debug, "关机前的客体内核日志已存到 ") { + t.Errorf("%s: debug lines %q", c.name, debug) + } + if !slices.Equal(g.ran, []string{hgDownloadCommand, clocksourceKernelCommand}) { + t.Errorf("%s: ran %q", c.name, g.ran) + } + if g.timeouts[0] != hgDownloadTimeout || g.timeouts[1] > 3*time.Second || g.timeouts[1] < 2*time.Second { + t.Errorf("%s: timeouts %v", c.name, g.timeouts) + } + } + // A guest command that is a fixed line: nothing for the outer shell to expand, nothing piped in the guest. + if strings.ContainsAny(hgDownloadCommand, "$|;&'\"`") { + t.Errorf("hgDownloadCommand = %q", hgDownloadCommand) + } +} + +// The budget bounds both commands: a small one goes to the download check alone, and a slow download check leaves +// the kernel log out rather than overrunning. +func TestRecordBeforeShutdownBudget(t *testing.T) { + m, lines := clockManager(t) + g := &fakeShutdownGuest{downloads: adb.Result{Out: "(nothing)"}, kernel: adb.Result{Out: "x\n"}} + m.recordBeforeShutdown(2, 400*time.Millisecond, g.run, time.Now) + if !slices.Equal(g.ran, []string{hgDownloadCommand}) || g.timeouts[0] != 400*time.Millisecond { + t.Fatalf("small budget: ran %q %v", g.ran, g.timeouts) + } + if !strings.Contains(strings.Join(linesAt(*lines, logx.Debug), "\n"), "关机前没时间存内核日志了") { + t.Fatalf("small budget: %v", *lines) + } + if _, err := os.Stat(m.Root.LogsDir()); !os.IsNotExist(err) { + t.Fatalf("small budget: logs dir %v", err) + } + + m, lines = clockManager(t) + g = &fakeShutdownGuest{downloads: adb.Result{Out: "(nothing)"}, delay: time.Second} + started := time.Now() + m.recordBeforeShutdown(2, 1200*time.Millisecond, g.run, time.Now) + if d := time.Since(started); d > 1500*time.Millisecond || !slices.Equal(g.ran, []string{hgDownloadCommand}) { + t.Fatalf("slow check: %v, ran %q", d, g.ran) + } + if len(linesAt(*lines, logx.Warn)) != 0 { + t.Fatalf("slow check warned: %v", *lines) + } +} + +// A kernel log that cannot be read (adb failed, an empty answer) is a debug line and leaves no file. +func TestRecordBeforeShutdownKernelUnread(t *testing.T) { + for _, kernel := range []adb.Result{{Code: 1, Out: "su: not found"}, {Out: " \n"}} { + m, lines := clockManager(t) + g := &fakeShutdownGuest{downloads: adb.Result{Out: "(nothing)"}, kernel: kernel} + m.recordBeforeShutdown(2, 3*time.Second, g.run, time.Now) + if debug := strings.Join(linesAt(*lines, logx.Debug), "\n"); !strings.Contains(debug, "ModAVD 实例 2 关机前的客体内核日志没存下: logcat -b kernel -d: ") { + t.Errorf("%+v: %q", kernel, debug) + } + if len(linesAt(*lines, logx.Warn)) != 0 { + t.Errorf("%+v: warned %v", kernel, *lines) + } + if entries, _ := os.ReadDir(m.Root.LogsDir()); len(entries) != 0 { + t.Errorf("%+v: wrote %v", kernel, entries) + } + } +} + +// The file: the agreed name (the problem report collects it), the comment line, an empty line, the log with LF. +func TestSaveShutdownKernelLog(t *testing.T) { + m, _ := clockManager(t) + path, err := m.saveShutdownKernelLog(3, adb.Result{Out: "<6>[ 0.000000] a\r\n<3>[ 12.5] EXT4-fs error\r\n"}, shutdownNow) + if err != nil { + t.Fatal(err) + } + if want := filepath.Join(m.Root.LogsDir(), "mas_3-20261129-210507-kernel.txt"); path != want { + t.Fatalf("path %s, want %s", path, want) + } + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + want := "# 实例 3 关机前的客体内核日志,读于 " + shutdownNow.Format(time.RFC3339) + ";来源 adb shell su 0 logcat -b kernel -d\n" + + "\n<6>[ 0.000000] a\n<3>[ 12.5] EXT4-fs error\n" + if string(b) != want { + t.Fatalf("content %q\nwant %q", b, want) + } + // not one of the start logs the problem report takes by name (report.logName), nor a clock source log + // (report.logName, copied: the report package is not imported here) + logName := regexp.MustCompile(`(?i)^(?:logcat-)?(.+)-[0-9]{8}-[0-9]{6}\.(?:log|txt)$`) + if logName.MatchString(filepath.Base(path)) { + t.Fatalf("%s matches the start log pattern", filepath.Base(path)) + } +} + +// More than 4 MiB: the newest part stays, cut at a line start, with a line saying how much was cut; the whole file +// stays within the limit. +func TestShutdownKernelLogContentTruncates(t *testing.T) { + var log strings.Builder + for k := 0; log.Len() < shutdownKernelLogMax+300<<10; k++ { + fmt.Fprintf(&log, "<6>[%10d.000000] 第 %d 行 kernel line\n", k, k) + } + full := log.String() + b := shutdownKernelLogContent(1, full, shutdownNow, shutdownKernelLogMax) + if len(b) > shutdownKernelLogMax { + t.Fatalf("%d bytes, over %d", len(b), shutdownKernelLogMax) + } + if len(b) < shutdownKernelLogMax-200 { + t.Fatalf("%d bytes, wasted room", len(b)) + } + lines := strings.SplitN(string(b), "\n", 4) + if !strings.HasPrefix(lines[0], "# 实例 1 关机前的客体内核日志,读于 ") || lines[2] != "" { + t.Fatalf("head %q", lines[:3]) + } + body := lines[3] + cut := len(full) - len(body) + if wantNote := fmt.Sprintf("# 原文 %d 字节,超过上限 %d 字节,截掉了最旧的 %d 字节", len(full), shutdownKernelLogMax, cut); lines[1] != wantNote { + t.Fatalf("note %q, want %q", lines[1], wantNote) + } + if !strings.HasSuffix(full, body) || !strings.HasPrefix(body, "<6>[") || full[cut-1] != '\n' { + t.Fatalf("kept part does not start at a line of the newest part: %q", body[:40]) + } + + // one huge line: cut at a character start, still within the limit + huge := strings.Repeat("内核", 200) + b = shutdownKernelLogContent(1, huge, shutdownNow, 600) + if len(b) > 600 || !strings.HasSuffix(huge, string(b[strings.LastIndex(string(b), "\n\n")+2:])) { + t.Fatalf("huge line: %d bytes %q", len(b), b) + } + if s := string(b); !strings.Contains(s, "截掉了最旧的") || !utf8.ValidString(s) { + t.Fatalf("huge line: %q", s) + } +} + +// Five per instance are kept, by the time in the name; other instances, the clock source logs and other files stay. +func TestShutdownKernelLogKeepsFive(t *testing.T) { + m, _ := clockManager(t) + dir := m.Root.LogsDir() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + others := []string{"mas_4-20261101-000000-kernel.txt", "mas_3-20261101-000000-clocksource.txt", + "mas_3-20261101-000000.log", "mas_3-x-kernel.txt"} + for _, n := range others { + if err := os.WriteFile(filepath.Join(dir, n), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + } + for k := range 7 { + if _, err := m.saveShutdownKernelLog(3, adb.Result{Out: "k\n"}, shutdownNow.Add(time.Duration(k)*time.Second)); err != nil { + t.Fatal(err) + } + } + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + var kept []string + for _, e := range entries { + kept = append(kept, e.Name()) + } + want := append([]string{}, others...) + for k := 2; k < 7; k++ { + want = append(want, "mas_3-"+shutdownNow.Add(time.Duration(k)*time.Second).Format("20060102-150405")+"-kernel.txt") + } + slices.Sort(kept) + slices.Sort(want) + if !slices.Equal(kept, want) { + t.Fatalf("kept %q\nwant %q", kept, want) + } +} + +// The step's budget leaves Android at least its worst-case window whatever prepare, HOME (and the wait after it) and +// the sync before the shutdown command take, and the whole graceful path still fits stopBudget (TestGracefulBudget's +// arithmetic is unchanged: the fallback starts at gracefulDeadline at the latest). +func TestBeforeShutdownBudget(t *testing.T) { + if homeWait != 2*time.Second || beforeShutdownMax != 4*time.Second { + t.Fatalf("homeWait %v, beforeShutdownMax %v; check the shutdown constants", homeWait, beforeShutdownMax) + } + for _, c := range []struct{ elapsed, want time.Duration }{ + {0, 4 * time.Second}, + {50 * time.Millisecond, 3950 * time.Millisecond}, + {3 * time.Second, time.Second}, + {adbServerStartOnClose, 0}, + } { + if got := beforeShutdownBudget(c.elapsed); got != c.want { + t.Errorf("beforeShutdownBudget(%v) = %v, want %v", c.elapsed, got, c.want) + } + } + after := homeTimeout + homeWait + shutdownSyncTimeout + for prepare := time.Duration(0); prepare <= adbServerStartOnClose; prepare += 100 * time.Millisecond { + step := beforeShutdownBudget(prepare) + if step < beforeShutdownMin { + step = 0 // skipped + } else { + step += beforeShutdownGrace / 10 // the step returning a little after its budget + } + if window := gracefulWindow(prepare + step + after); window < gracefulWindowMin-beforeShutdownGrace/10 { + t.Errorf("prepare %v, step %v: Android gets %v", prepare, step, window) + } + } +} + +// beforeShutdown: a step that overruns is left behind after budget + grace and the stop goes on; a nil step and a +// budget below the minimum do nothing; a cancel is errs.Canceled. +func TestBeforeShutdownStep(t *testing.T) { + savedMax, savedGrace := beforeShutdownMax, beforeShutdownGrace + t.Cleanup(func() { beforeShutdownMax, beforeShutdownGrace = savedMax, savedGrace }) + beforeShutdownMax, beforeShutdownGrace = 1200*time.Millisecond, 200*time.Millisecond + + release := make(chan struct{}) + defer close(release) + var got time.Duration + c := &logx.Collector{} + var debug []string + log := logx.New(c.Sink(), func(level logx.Level, msg string) { + if level == logx.Debug { + debug = append(debug, msg) + } + }) + started := time.Now() + err := beforeShutdown(context.Background(), log, 3, 0, func(budget time.Duration) { got = budget; <-release }) + if d := time.Since(started); err != nil || d < 1400*time.Millisecond || d > 2500*time.Millisecond { + t.Fatalf("hung step: %v after %v", err, d) + } + if got != 1200*time.Millisecond || len(c.Messages()) != 0 || len(debug) != 1 || !strings.Contains(debug[0], "没做完,不等了,照常关机") { + t.Fatalf("hung step: budget %v, warnings %q, debug %q", got, c.Messages(), debug) + } + + if err := beforeShutdown(context.Background(), logx.Nop(), 3, 0, nil); err != nil { + t.Fatalf("nil step: %v", err) + } + ran := false + if err := beforeShutdown(context.Background(), logx.Nop(), 3, 10*time.Second, func(time.Duration) { ran = true }); err != nil || ran { + t.Fatalf("no time left: %v, ran %v", err, ran) + } + + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(50*time.Millisecond, cancel) + started = time.Now() + err = beforeShutdown(ctx, logx.Nop(), 3, 0, func(time.Duration) { <-release }) + if errs.CodeOf(err) != errs.Canceled || time.Since(started) > time.Second { + t.Fatalf("canceled: %v after %v", err, time.Since(started)) + } +} diff --git a/internal/emu/stop_record_windows_test.go b/internal/emu/stop_record_windows_test.go new file mode 100644 index 00000000..567ebc27 --- /dev/null +++ b/internal/emu/stop_record_windows_test.go @@ -0,0 +1,143 @@ +package emu + +import ( + "context" + "encoding/json" + "fmt" + "os" + "slices" + "strings" + "testing" + "time" + + "modavd/internal/logx" + "modavd/internal/win" +) + +// withBeforeShutdown is f's side effects plus a beforeShutdown that is recorded in f.calls (as "before_shutdown") and +// then runs step (nil: returns at once); budget receives its budget. +func withBeforeShutdown(f *stopFake, budget *time.Duration, step func()) stopOps { + ops := f.ops() + ops.beforeShutdown = func(b time.Duration) { + f.calls = append(f.calls, "before_shutdown") + if f.at == nil { + f.at = map[string]time.Time{} + } + f.at["before_shutdown"] = time.Now() + *budget = b + if step != nil { + step() + } + } + return ops +} + +func runStopOps(ctx context.Context, force bool, ops stopOps) (string, bool, error, []string) { + c := &logx.Collector{} + method, synced, err := runStop(ctx, logx.New(c.Sink()), 3, force, time.Now(), ops) + return method, synced, err, c.Messages() +} + +// The normal path records before HOME (the game still in front), with the budget for a prepare that took no time; +// Force, an unusable private adb and the launching path never do. +func TestRunStopBeforeShutdownPaths(t *testing.T) { + var budget time.Duration + f := &stopFake{syncOK: true} + method, synced, err, warns := runStopOps(context.Background(), false, withBeforeShutdown(f, &budget, nil)) + if err != nil || method != "graceful" || !synced || len(warns) != 0 { + t.Fatalf("normal: %s %v %v %q", method, synced, err, warns) + } + if got := strings.Join(f.calls, ","); got != "prepare,before_shutdown,home,sync,graceful" { + t.Fatalf("normal: calls %s", got) + } + if budget > beforeShutdownMax || budget < beforeShutdownMax-500*time.Millisecond { + t.Fatalf("normal: budget %v", budget) + } + + f = &stopFake{syncOK: true} + if _, _, err, _ := runStopOps(context.Background(), true, withBeforeShutdown(f, &budget, nil)); err != nil || + slices.Contains(f.calls, "before_shutdown") { + t.Fatalf("force: %v %v", err, f.calls) + } + + f = &stopFake{problem: "私有 adb server(端口 20050)4 秒内没起来"} + if _, _, err, _ := runStopOps(context.Background(), false, withBeforeShutdown(f, &budget, nil)); err != nil || + slices.Contains(f.calls, "before_shutdown") { + t.Fatalf("console: %v %v", err, f.calls) + } + + f = &stopFake{} + if _, _, err := runLaunchingStop(context.Background(), logx.Nop(), 3, 13*time.Second, withBeforeShutdown(f, &budget, nil)); err != nil || + slices.Contains(f.calls, "before_shutdown") { + t.Fatalf("launching: %v %v", err, f.calls) + } +} + +// A step that hangs costs at most its budget + grace: the stop goes on with HOME, the sync and the shutdown, the same +// method and no warning, and Android's window is shorter only by that. +func TestRunStopBeforeShutdownHangs(t *testing.T) { + savedMax, savedGrace := beforeShutdownMax, beforeShutdownGrace + t.Cleanup(func() { beforeShutdownMax, beforeShutdownGrace = savedMax, savedGrace }) + beforeShutdownMax, beforeShutdownGrace = 1100*time.Millisecond, 200*time.Millisecond + + release := make(chan struct{}) + defer close(release) + var budget time.Duration + f := &stopFake{syncOK: true} + started := time.Now() + method, synced, err, warns := runStopOps(context.Background(), false, withBeforeShutdown(f, &budget, func() { <-release })) + if err != nil || method != "graceful" || !synced || len(warns) != 0 { + t.Fatalf("got %s %v %v %q", method, synced, err, warns) + } + if got := strings.Join(f.calls, ","); got != "prepare,before_shutdown,home,sync,graceful" { + t.Fatalf("calls %s", got) + } + if d := f.at["home"].Sub(started); d < 1300*time.Millisecond || d > 2500*time.Millisecond { + t.Fatalf("HOME %v after the first look", d) + } + if f.window > gracefulDeadline-1300*time.Millisecond || f.window < gracefulDeadline-3*time.Second { + t.Fatalf("graceful window %v", f.window) + } + + // a cancel while it runs: no HOME, no shutdown + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(50*time.Millisecond, cancel) + f = &stopFake{syncOK: true} + if _, _, err, _ := runStopOps(ctx, false, withBeforeShutdown(f, &budget, func() { <-release })); err == nil || + strings.Join(f.calls, ",") != "prepare,before_shutdown" { + t.Fatalf("canceled: %v %v", err, f.calls) + } +} + +// The real side effects send the two fixed command lines to the instance on the private server. +func TestStopOpsBeforeShutdownCommands(t *testing.T) { + r, log := 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) + } + ops := m.stopOpsFor(context.Background(), 6, win.Process{PID: 0xFFFFFFFC}) + ops.beforeShutdown(3 * time.Second) + b, err := os.ReadFile(log) + if err != nil { + t.Fatal(err) + } + var cmds []string + for _, line := range strings.Split(strings.TrimSpace(string(b)), "\n") { + var args []string + if err := json.Unmarshal([]byte(line), &args); err != nil { + t.Fatalf("fake adb log line %q: %v", line, err) + } + all := strings.Join(args, " ") + if !strings.Contains(all, "-s emulator-21060 ") || !strings.HasPrefix(all, fmt.Sprintf("-P %d ", r.AdbServerPort())) { + t.Errorf("adb %q: not instance 6 on the private server", args) + } + if i := slices.Index(args, "shell"); i >= 0 { + cmds = append(cmds, strings.Join(args[i+1:], " ")) + } + } + if !slices.Equal(cmds, []string{hgDownloadCommand, clocksourceKernelCommand}) { + t.Fatalf("shell commands %q", cmds) + } +} diff --git a/internal/i18n/locales/en/emu.json b/internal/i18n/locales/en/emu.json index e6c1a7b0..e514531c 100644 --- a/internal/i18n/locales/en/emu.json +++ b/internal/i18n/locales/en/emu.json @@ -60,6 +60,17 @@ "ModAVD 实例 %d 关机前 sync 失败,照常关机: %s": "ModAVD instance %d: sync failed before shutdown, shutting down anyway: %s", "ModAVD 实例 %d 关机前 sync 完成(%.0f ms)": "ModAVD instance %d: sync before shutdown finished (%.0f ms)", "ModAVD 实例 %d 关机前按 HOME 失败,照常关机: %s": "ModAVD instance %d: pressing HOME failed before shutdown, shutting down anyway: %s", + "# 原文 %d 字节,超过上限 %d 字节,截掉了最旧的 %d 字节\n": null, + "# 实例 %d 关机前的客体内核日志,读于 %s;来源 adb shell %s\n": null, + "ModAVD 实例 %d 关机前前面已经用了 %.1f 秒,不再查下载和存内核日志": "ModAVD instance %d: %.1f s already used before shutdown, skipping the download check and the kernel log", + "ModAVD 实例 %d 关机前查下载、存内核日志 %.0f 秒内没做完,不等了,照常关机": "ModAVD instance %d: the download check and kernel log did not finish within %.0f s before shutdown, shutting down anyway", + "ModAVD 实例 %d 关机前查不了游戏是不是在下载: %s": "ModAVD instance %d: could not check before shutdown whether a game is downloading: %s", + "ModAVD 实例 %d 关机前没时间存内核日志了(剩 %.1f 秒)": "ModAVD instance %d: no time left before shutdown to save the kernel log (%.1f s left)", + "ModAVD 实例 %d 关机前的客体内核日志已存到 %s": "ModAVD instance %d: guest kernel log before shutdown saved to %s", + "ModAVD 实例 %d 关机前的客体内核日志没存下: %v": "ModAVD instance %d: guest kernel log before shutdown not saved: %v", + "ModAVD 实例 %d 关机时 %s 正在下载(%s 在跑),这次下载会被打断": "ModAVD instance %d: %s was downloading at shutdown (%s running); this download will be interrupted", + "ModAVD 实例 %d 关机时在跑的下载服务: %s,前台服务 %v": "ModAVD instance %d: download service running at shutdown: %s, foreground service %v", + "ModAVD 实例 %d 关机时没有游戏在下载(没有 %s 在跑)": "ModAVD instance %d: no game was downloading at shutdown (no %s running)", "ModAVD 实例 %d 准备阶段无头开机已做完,关机后按要求带窗口开机": "ModAVD instance %d: the headless start for preparation is done; after shutdown it will start with a window as requested", "ModAVD 实例 %d 初始化完成(桌面: %s)": "ModAVD instance %d: initial setup finished (launcher: %s)", "ModAVD 实例 %d 初始化有失败项,下次开机重试: %s": "ModAVD instance %d: some initial setup steps failed, will retry at the next start: %s", From 88e9168ff457807bdef2eb7e4c784aa136f77c0b Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sun, 29 Nov 2026 22:06:22 +0100 Subject: [PATCH 2/6] =?UTF-8?q?=E6=98=8E=E6=97=A5=E6=96=B9=E8=88=9F?= =?UTF-8?q?=E8=B5=84=E6=BA=90=E6=96=87=E4=BB=B6=E7=9B=91=E8=A7=86=EF=BC=9A?= =?UTF-8?q?=E8=AE=B0=E4=B8=8B=E7=B4=A2=E5=BC=95=E5=92=8C=E6=B8=85=E5=8D=95?= =?UTF-8?q?=E7=9A=84=E6=AF=8F=E6=AC=A1=E5=8F=98=E5=8C=96=E4=B8=8E=E5=87=BA?= =?UTF-8?q?=E9=94=99=E5=BD=93=E5=9C=BA=E7=9A=84=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新客体脚本 modavd-reswatch.sh(只读,root):每 3 秒 stat 一轮 Bundles/*.idx、hot_update_list.json、persistent_res_list.json,变了才算 md5 往 logcat 记一行(带变化前的值),守护起来那轮记全量基线;另起循环读 logcat 的 Unity 错误,读到 [ResourceManager] Init failed 或 Failed to deserialize manifest 就记现场:三处视图的大小、时间、md5,和上一轮比、视图之间比,有不一致就丢页缓存再读一次,再加内存状态和内核日志末尾 40 行;同一包 10 秒内只记一次。开机后设置里在下载盘之后启动它,MODAVD_RES_WATCH=off 可关。 Refs ModAVD/ModAVD#89 --- changelog.d/89-reswatch.feat.md | 2 + internal/emu/afterboot.go | 4 + internal/emu/reswatch.go | 96 ++++ internal/emu/reswatch_test.go | 40 ++ internal/guest/guest.go | 3 + internal/guest/guest_test.go | 2 +- internal/guest/reswatch_sh_test.go | 559 ++++++++++++++++++++++ internal/guest/scripts/modavd-reswatch.sh | 331 +++++++++++++ internal/i18n/locales/en/emu.json | 9 +- 9 files changed, 1044 insertions(+), 2 deletions(-) create mode 100644 changelog.d/89-reswatch.feat.md create mode 100644 internal/emu/reswatch.go create mode 100644 internal/emu/reswatch_test.go create mode 100644 internal/guest/reswatch_sh_test.go create mode 100644 internal/guest/scripts/modavd-reswatch.sh diff --git a/changelog.d/89-reswatch.feat.md b/changelog.d/89-reswatch.feat.md new file mode 100644 index 00000000..3e592335 --- /dev/null +++ b/changelog.d/89-reswatch.feat.md @@ -0,0 +1,2 @@ +问题包记下明日方舟出错当场的资源文件、内核日志和关机时的下载状态,便于查整包重下 (ModAVD/ModAVD#89) +Problem reports keep Arknights' resource files at a load error, the kernel log, and downloads cut by a shutdown diff --git a/internal/emu/afterboot.go b/internal/emu/afterboot.go index 2b360d9a..21cc3a18 100644 --- a/internal/emu/afterboot.go +++ b/internal/emu/afterboot.go @@ -260,6 +260,10 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe // 12) download disks (dldisk.go). After the guest library fixes (0a): the framework restart there remounts the // shared storage, and a disk mounted on it before would be gone with it func() { m.setupDownloadDisk(ctx, i) }, + // 12a) Arknights' resource files watched, and what they hold when the game cannot load them (reswatch.go, + // ModAVD/ModAVD#89). Also after 0a: a scene compares /data/media with the FUSE view, which the framework + // restart there mounts anew. Every mode, an adopted instance too: the script starts no second watcher + func() { m.setupResWatch(ctx, i) }, // 12b) listed games that have not chosen a display mode start in Vulkan (vkmode.go, ModAVD#222) func() { m.setupVulkanMode(ctx, i) }, // 13) the guest's clock source into the log, its kernel log's clock lines saved when an x86_64 guest is not on diff --git a/internal/emu/reswatch.go b/internal/emu/reswatch.go new file mode 100644 index 00000000..15bcdb59 --- /dev/null +++ b/internal/emu/reswatch.go @@ -0,0 +1,96 @@ +package emu + +import ( + "context" + "fmt" + "os" + "strings" + "time" + + "modavd/internal/guest" + "modavd/internal/root" +) + +// The resource file watch (guest.ResWatch, ModAVD/ModAVD#89). Now and then Arknights fails right after START on its +// title page ("[ResourceManager] Init failed"), takes its local resources for invalid and downloads all of them again +// at the next start. The cause is unknown; what decides between the emulator's storage and the game is what the game +// read at that moment. A guest watcher logs every change of the game's resource index and manifests (size, mtime, +// md5), and on the game's error what those files hold in each view of the storage, against the last pass, plus the +// memory state and the kernel log: all in logcat, which the problem report carries. Read-only; the script's header has +// the details. +// +// On by default: it is for the user's machine, where the failure happens and where nobody would turn on a switch +// beforehand. Windows only so far, like the download disk next to it. + +// envResWatch set to "off" stops the watcher and starts none. +const envResWatch = "MODAVD_RES_WATCH" + +// resWatchTimeout: daemon only starts the two loops in the background and waits up to a second for them (the +// baseline pass with its md5s runs in the watcher, not here). +const resWatchTimeout = 20 * time.Second + +// setupResWatch starts the watcher and the logcat reader of the resource files, unless they run already (an adopted +// instance: the script starts at most one of each). +func (m *Manager) setupResWatch(ctx context.Context, i int) { + if !root.CurrentPlatform().Windows() { + return + } + remote, ok := m.pushGuestScript(ctx, i, guest.ResWatch) + if !ok { + return + } + if strings.EqualFold(strings.TrimSpace(os.Getenv(envResWatch)), "off") { + m.shell(ctx, i, "su 0 sh "+remote+" off", resWatchTimeout) + m.Log.Infof("实例 %d 资源文件监视: 已按 %s=off 关闭", i, envResWatch) + return + } + started := m.shell(ctx, i, "su 0 sh "+remote+" daemon", resWatchTimeout).Out + status := m.shell(ctx, i, "su 0 sh "+remote+" status", 0).Out + if warn, msg := resWatchReport(i, started, status); warn { + m.Log.Warnf("%s", msg) + } else { + m.Log.Infof("%s", msg) + } +} + +// resWatchReport judges `modavd-reswatch.sh daemon` + `status`: running when both the pass loop and the logcat loop +// list a pid. The message names the listed games that are installed and what the script says about each. +func resWatchReport(i int, started, status string) (warn bool, msg string) { + lines := parseStatusLines(status) + if lines["watchers"] == "" || lines["errwatch"] == "" { + return true, fmt.Sprintf("实例 %d 资源文件监视没起来: %s", i, tail(strings.TrimSpace(started)+" / "+status, 300)) + } + var games []string + for _, line := range outputLines(status) { + pkg, state, ok := strings.Cut(line, ":") + state = strings.TrimSpace(state) + if !ok || pkg == "watchers" || pkg == "errwatch" || state == "" || state == "not installed" { + continue + } + games = append(games, pkg+"("+resWatchState(state)+")") + } + if len(games) == 0 { + return false, fmt.Sprintf("实例 %d 资源文件监视: 守护已起(pid %s,读日志 pid %s),名单里的游戏都没装", i, + lines["watchers"], lines["errwatch"]) + } + return false, fmt.Sprintf("实例 %d 资源文件监视: 守护已起(pid %s,读日志 pid %s);%s", i, lines["watchers"], + lines["errwatch"], strings.Join(games, ",")) +} + +// resWatchState puts the script's status of a package into the log's language: "not scanned yet", or "watching N +// files, M missing" with "; last scene at