diff --git a/changelog.d/280-notification-sound.change.md b/changelog.d/280-notification-sound.change.md new file mode 100644 index 0000000..0980fad --- /dev/null +++ b/changelog.d/280-notification-sound.change.md @@ -0,0 +1,2 @@ +实例默认关掉通知提示音,通知照常显示 (ModAVD/ModAVD#280) +Instances now have the notification sound off by default; notifications still show (ModAVD/ModAVD#280) diff --git a/internal/emu/afterboot.go b/internal/emu/afterboot.go index 06f6ce6..c50dcd0 100644 --- a/internal/emu/afterboot.go +++ b/internal/emu/afterboot.go @@ -106,6 +106,10 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe } steps := []func(){ + // 0) the notification tone off, once per instance and not in the first boot of a new one (notifysound.go, + // ModAVD/ModAVD#280): first of all, before the guest posts a notification the sound would play for (the + // Safety Center's, about 18 s after the boot) + func() { m.setupNotificationSound(ctx, i) }, func() { // 0a) the guest library fixes (Vulkan driver, ARM translation layer). A launched boot of an initialized // instance has mounted them during the boot animation already (earlyGuestFixes): this only finds them diff --git a/internal/emu/notifysound.go b/internal/emu/notifysound.go new file mode 100644 index 0000000..ff0a6b3 --- /dev/null +++ b/internal/emu/notifysound.go @@ -0,0 +1,99 @@ +package emu + +// The guest's notification sound off by default (ModAVD/ModAVD#280): with sound on, the system plays the default +// notification tone for every notification, e.g. the Safety Center's "no screen lock" one about 18 s after a boot, and +// nobody is at an unattended instance to want it. +// +// What the default tone is: the channels' sound is the URI content://settings/system/notification_sound, which the +// player resolves through the system setting of that name. The setting unset (`settings delete`, `settings get` then +// prints "null") resolves to nothing, so no track is played at all. `settings put system notification_sound ''` does +// not do it (the empty value is ignored and the old one stays). This needs no sound card and leaves the media volume, +// the touch sounds and the ringtone alone; the notifications themselves still show. +// +// Once per instance, recorded in mas-avd.json: an instance set up before this existed gets it at its next boot too, +// and a tone the user chose afterwards is not overwritten at every boot. Not during the first boot of a new instance +// (before the first-boot setup has recorded initialized): the system sets its default tones when its first media scan +// finishes, which can be after this step and then puts the default back (measured 11-27: a create that muted at its +// first boot read the default again at the next start). The next boot is the first one nobody can have heard the tone +// at: the Safety Center posts its notification only 12 hours after it first saw the issue. + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "modavd/internal/adb" + "modavd/internal/jsonord" +) + +// notificationSoundMutedKey is instances..notificationSoundMuted in mas-avd.json: true once the notification sound +// was turned off. +const notificationSoundMutedKey = "notificationSoundMuted" + +const notificationSoundTimeout = 15 * time.Second + +// muteNotificationSoundCommand unsets the setting and reads it back (an unset one reads "null"). +const muteNotificationSoundCommand = "settings delete system notification_sound && settings get system notification_sound" + +// notificationSoundUnset judges the output of muteNotificationSoundCommand: the read-back (its last line) is "null". +func notificationSoundUnset(out string) bool { + return lastNonEmptyLine(out) == "null" +} + +// setupNotificationSound is the first step of afterBoot: it runs before the guest can post anything the user would +// hear. Only warnings: a failure leaves the marker unset and the next boot tries again. +func (m *Manager) setupNotificationSound(ctx context.Context, i int) { + m.muteNotificationSound(ctx, i, func(ctx context.Context, command string) adb.Result { return m.shell(ctx, i, command, 0) }) +} + +// muteNotificationSound bounds the whole step, including adb cleanup and metadata I/O. +func (m *Manager) muteNotificationSound(ctx context.Context, i int, run func(context.Context, string) adb.Result) { + ctx, cancel := context.WithTimeout(ctx, notificationSoundTimeout) + defer cancel() + type result struct { + muted bool + err error + } + done := make(chan result, 1) + go func() { + muted, err := m.tryMuteNotificationSound(ctx, i, run) + done <- result{muted, err} + }() + select { + case res := <-done: + switch { + case res.err != nil && res.muted: + m.Log.Warnf("实例 %d 通知提示音已关,但结果没写进 mas-avd.json,下次开机再关一次: %v", i, res.err) + case res.err != nil: + m.Log.Warnf("实例 %d 没关掉通知提示音(下次开机重试): %s", i, res.err.Error()) + case res.muted: + m.Log.Infof("实例 %d 已关掉通知提示音(通知照常显示)", i) + } + case <-ctx.Done(): + m.Log.Warnf("实例 %d 没关掉通知提示音(下次开机重试): %s", i, ctx.Err().Error()) + } +} + +func (m *Manager) tryMuteNotificationSound(ctx context.Context, i int, run func(context.Context, string) adb.Result) (bool, error) { + meta, err := m.Root.ReadInstanceMeta(i) + if err != nil { + return false, err + } + if !jsonTruthy(meta.Get("initialized")) || jsonTruthy(meta.Get(notificationSoundMutedKey)) { + return false, nil + } + if err := ctx.Err(); err != nil { + return false, err + } + res := run(ctx, muteNotificationSoundCommand) + if res.Code != 0 || !notificationSoundUnset(res.Out) { + return false, errors.New(orText(tail(strings.Join(strings.Fields(res.Out), " "), 200), fmt.Sprintf("退出码 %d", res.Code))) + } + err = m.Root.EditInstanceMetaContext(ctx, i, func(meta *jsonord.Obj) error { + meta.Set(notificationSoundMutedKey, jsonord.NewBool(true)) + return nil + }) + return true, err +} diff --git a/internal/emu/notifysound_windows_test.go b/internal/emu/notifysound_windows_test.go new file mode 100644 index 0000000..0653db1 --- /dev/null +++ b/internal/emu/notifysound_windows_test.go @@ -0,0 +1,260 @@ +//go:build windows + +package emu + +import ( + "context" + "os" + "strings" + "sync" + "testing" + "time" + + "modavd/internal/adb" + "modavd/internal/jsonord" + "modavd/internal/logx" + "modavd/internal/win" +) + +func TestNotificationSoundUnset(t *testing.T) { + for out, want := range map[string]bool{ + "Deleted 1 rows\nnull\n": true, + "Deleted 0 rows\r\nnull\r\n": true, + "null": true, + "Deleted 1 rows\ncontent://media/internal/audio/media/184?title=Pixie%20Dust&canonical=1\n": false, + "": false, + "Error: Unknown command: delete\n": false, + "null\nsomething\n": false, + } { + if got := notificationSoundUnset(out); got != want { + t.Errorf("notificationSoundUnset(%q) = %v, want %v", out, got, want) + } + } +} + +// fakeSoundGuest is the guest shell of the tests: it answers the mute command with out / code and counts the calls. +type fakeSoundGuest struct { + mu sync.Mutex + out string + code int + commands []string +} + +func (f *fakeSoundGuest) run(_ context.Context, command string) adb.Result { + f.mu.Lock() + defer f.mu.Unlock() + f.commands = append(f.commands, command) + return adb.Result{Code: f.code, Out: f.out} +} + +func (f *fakeSoundGuest) calls() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.commands) +} + +func newSoundTestManager(t *testing.T) (*Manager, *[]string) { + t.Helper() + var mu sync.Mutex + var warnings []string + m := New(managerTestRoot(t, 1), logx.New(func(level logx.Level, message string) { + if level == logx.Warn { + mu.Lock() + warnings = append(warnings, message) + mu.Unlock() + } + })) + setInitialized(t, m, 1, true) + return m, &warnings +} + +func setInitialized(t *testing.T, m *Manager, i int, on bool) { + t.Helper() + if err := m.Root.EditInstanceMeta(i, func(meta *jsonord.Obj) error { + meta.Set("initialized", jsonord.NewBool(on)) + return nil + }); err != nil { + t.Fatal(err) + } +} + +func (m *Manager) notificationSoundDone(i int) bool { + return jsonTruthy(m.Root.InstanceMeta(i).Get(notificationSoundMutedKey)) +} + +// The first boot of a new instance (not initialized yet) leaves the setting alone: the system sets its default tones +// when its first media scan ends, which may put the default back. The next boot does it. +func TestMuteNotificationSoundWaitsForFirstBoot(t *testing.T) { + m, _ := newSoundTestManager(t) + setInitialized(t, m, 1, false) + guest := &fakeSoundGuest{out: "Deleted 1 rows\nnull\n"} + m.muteNotificationSound(context.Background(), 1, guest.run) + if guest.calls() != 0 || m.notificationSoundDone(1) { + t.Fatalf("first boot: commands %q, marker %v", guest.commands, m.notificationSoundDone(1)) + } + setInitialized(t, m, 1, true) + m.muteNotificationSound(context.Background(), 1, guest.run) + if guest.calls() != 1 || !m.notificationSoundDone(1) { + t.Fatalf("next boot: commands %q, marker %v", guest.commands, m.notificationSoundDone(1)) + } +} + +// The sound is turned off once: the marker is written, and a later boot does not touch the setting again (a tone the +// user chose meanwhile stays). +func TestMuteNotificationSoundOnce(t *testing.T) { + m, warnings := newSoundTestManager(t) + ctx := context.Background() + guest := &fakeSoundGuest{out: "Deleted 1 rows\nnull\n"} + if m.notificationSoundDone(1) { + t.Fatal("a new instance is marked as done") + } + m.muteNotificationSound(ctx, 1, func(ctx context.Context, command string) adb.Result { + if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > notificationSoundTimeout { + t.Errorf("adb has no short deadline: %v", deadline) + } + return guest.run(ctx, command) + }) + if guest.calls() != 1 || guest.commands[0] != muteNotificationSoundCommand { + t.Fatalf("first boot: commands %q", guest.commands) + } + if !m.notificationSoundDone(1) { + t.Fatal("no marker after success") + } + m.muteNotificationSound(ctx, 1, guest.run) + m.muteNotificationSound(ctx, 1, guest.run) + if guest.calls() != 1 { + t.Fatalf("later boots ran the guest command again: %q", guest.commands) + } + if m.notificationSoundDone(0) || len(*warnings) != 0 { + t.Fatalf("other instance done %v, warnings %q", m.notificationSoundDone(0), *warnings) + } +} + +// An instance whose setting is already unset is only marked; a failed attempt (the setting is still there, a non-zero +// exit, a cancelled start) leaves no marker, so the next boot tries again. +func TestMuteNotificationSoundRetries(t *testing.T) { + ctx := context.Background() + still := "Deleted 0 rows\ncontent://media/internal/audio/media/184?title=Pixie%20Dust&canonical=1\n" + for name, c := range map[string]struct { + out string + code int + cancel bool + done bool + warn string + }{ + "already unset": {out: "Deleted 0 rows\nnull\n", done: true}, + "setting still set": {out: still, warn: "没关掉通知提示音"}, + "adb failed": {out: "adb: device offline", code: 1, warn: "device offline"}, + "no output": {code: 255, warn: "退出码 255"}, + "canceled": {out: "Deleted 1 rows\nnull\n", cancel: true, warn: context.Canceled.Error()}, + } { + t.Run(name, func(t *testing.T) { + m, warnings := newSoundTestManager(t) + guest := &fakeSoundGuest{out: c.out, code: c.code} + runCtx, cancel := context.WithCancel(ctx) + defer cancel() + if c.cancel { + cancel() + } + m.muteNotificationSound(runCtx, 1, guest.run) + if got := m.notificationSoundDone(1); got != c.done { + t.Fatalf("marker = %v, want %v", got, c.done) + } + if c.warn == "" && len(*warnings) != 0 || + c.warn != "" && (len(*warnings) != 1 || !strings.Contains((*warnings)[0], c.warn)) { + t.Fatalf("warnings %q, want one with %q", *warnings, c.warn) + } + if !c.done { + before := guest.calls() + guest.out, guest.code = "Deleted 1 rows\nnull\n", 0 + m.muteNotificationSound(ctx, 1, guest.run) + if !m.notificationSoundDone(1) || guest.calls() != before+1 { + t.Fatalf("the next boot did not mute: done %v, calls %d", m.notificationSoundDone(1), guest.calls()) + } + } + }) + } +} + +func TestMuteNotificationSoundDeadline(t *testing.T) { + t.Run("adb", func(t *testing.T) { + m, warnings := newSoundTestManager(t) + started := make(chan struct{}) + release := make(chan struct{}) + defer close(release) + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + done := make(chan struct{}) + go func() { + defer close(done) + m.muteNotificationSound(ctx, 1, func(_ context.Context, _ string) adb.Result { + close(started) + // Simulate adb cleanup still waiting on its pipes when the deadline expires. + <-release + return adb.Result{Out: "null"} + }) + }() + select { + case <-started: + case <-done: + t.Fatal("returned before calling adb") + } + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("waited for adb cleanup past the deadline") + } + if m.notificationSoundDone(1) || len(*warnings) != 1 || !strings.Contains((*warnings)[0], context.DeadlineExceeded.Error()) { + t.Fatalf("after timeout: marker %v, warnings %q", m.notificationSoundDone(1), *warnings) + } + }) + + t.Run("metadata lock", func(t *testing.T) { + m, _ := newSoundTestManager(t) + lock, ok, err := win.TryLock(m.Root.MetadataPath() + ".lock") + if err != nil || !ok { + t.Fatalf("lock metadata: held %v, error %v", ok, err) + } + defer lock.Unlock() + guest := &fakeSoundGuest{out: "null"} + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + start := time.Now() + muted, err := m.tryMuteNotificationSound(ctx, 1, guest.run) + if elapsed := time.Since(start); elapsed > 2*time.Second { + t.Fatalf("metadata lock blocked the step for %s", elapsed) + } + if guest.calls() != 1 || !muted || m.notificationSoundDone(1) || err != context.DeadlineExceeded { + t.Fatalf("after timeout: commands %d, marker %v, error %v", guest.calls(), m.notificationSoundDone(1), err) + } + }) +} + +func TestMuteNotificationSoundSkipsUnreadableMetadata(t *testing.T) { + m, warnings := newSoundTestManager(t) + guest := &fakeSoundGuest{out: "null"} + path := m.Root.MetadataPath() + partial := `{"instances":{"1":{"initialized":true,` + if err := os.WriteFile(path, []byte(partial), 0o644); err != nil { + t.Fatal(err) + } + m.muteNotificationSound(context.Background(), 1, guest.run) + got, err := os.ReadFile(path) + if err != nil || string(got) != partial || guest.calls() != 0 || len(*warnings) != 1 { + t.Fatalf("after read failure: file %q, error %v, commands %d, warnings %q", got, err, guest.calls(), *warnings) + } +} + +func TestMuteNotificationSoundDeleteFailure(t *testing.T) { + m, warnings := newSoundTestManager(t) + m.muteNotificationSound(context.Background(), 1, func(_ context.Context, command string) adb.Result { + // Model a failed delete when get alone would return "null" and exit successfully. + if command == "settings delete system notification_sound && settings get system notification_sound" { + return adb.Result{Code: 1, Out: "delete failed"} + } + return adb.Result{Out: "null"} + }) + if m.notificationSoundDone(1) || len(*warnings) != 1 || !strings.Contains((*warnings)[0], "delete failed") { + t.Fatalf("after delete failure: marker %v, warnings %q", m.notificationSoundDone(1), *warnings) + } +} diff --git a/internal/i18n/locales/en/emu.json b/internal/i18n/locales/en/emu.json index 634f57d..b84f442 100644 --- a/internal/i18n/locales/en/emu.json +++ b/internal/i18n/locales/en/emu.json @@ -330,6 +330,7 @@ "实例 %d 密集读写加速: 守护已起(pid %s,数据盘 %s,忙等上限 %s)": "Instance %d intensive I/O acceleration: daemon started (pid %s, data disk %s, busy-wait limit %s)", "实例 %d 密集读写加速: 客体等读写时自己忙等(acpi_idle),不起忙等守护": "Instance %d intensive I/O acceleration: the guest busy-waits for I/O itself (acpi_idle); not starting the busy-wait daemon", "实例 %d 密集读写加速没起来: %s": "Instance %d: intensive I/O acceleration did not start: %s", + "实例 %d 已关掉通知提示音(通知照常显示)": "Instance %d: notification sound turned off (notifications still show)", "实例 %d 已在本机生成%s补丁版(sha256 %s): %s": "Instance %d: generated the patched %s locally (sha256 %s): %s", "实例 %d 已在运行(pid %d),不重新开机": "Instance %d is already running (pid %d); not starting again", "实例 %d 已就绪(共 %.1f 秒)": "Instance %d is ready (%.1f s in total)", @@ -405,6 +406,7 @@ "实例 %d 正在挂驱动补丁,稍后再装": "Instance %d is mounting the driver patch; install later", "实例 %d 正由另一次启动开机或做开机后设置": "Instance %d is being started or finishing post-boot setup by another start", "实例 %d 没%s好 Google Play 商店(%s)": "Instance %d: Google Play Store %s did not finish (%s)", + "实例 %d 没关掉通知提示音(下次开机重试): %s": "Instance %d: could not turn off the notification sound (will retry at the next boot): %s", "实例 %d 没取到 GSF ID(%s)": "Instance %d: could not get the GSF ID (%s)", "实例 %d 没开机": "Instance %d is not started", "实例 %d 没放上执行桥的开机标记: %v": "Instance %d: could not place the execution bridge boot marker: %v", @@ -493,6 +495,7 @@ "实例 %d 这次开机后的设置做完了": "Instance %d: post-boot setup of this start is done", "实例 %d 这次开机后的设置还没做完(拉起它的那次启动被取消或超时了),这次接着做完": "Instance %d: post-boot setup of this start was not finished (the start that began it was cancelled or timed out); finishing it now", "实例 %d 这次开机的客体库补丁还没做,前台是 %s、没有应用在用,也没有安装在进行,接着挂(会重启 zygote)": "Instance %d: the guest library patch of this start is not done yet; the foreground is %s, no app is in use and no install is in progress, so mounting now (zygote will restart)", + "实例 %d 通知提示音已关,但结果没写进 mas-avd.json,下次开机再关一次: %v": "Instance %d: notification sound is off, but the result was not written to mas-avd.json; turning it off once more at the next boot: %v", "实例 %d 里建不了 %s:%s": "Instance %d: cannot create %s: %s", "实例 %d 里没有按应用走代理的客体程序": "Instance %d has no guest program for per-app proxy", "实例 %d 里的 %s 和这个 modavd 带的不一样,不以 root 运行它": "Instance %d: %s differs from the one this modavd carries; not running it as root", diff --git a/internal/root/root.go b/internal/root/root.go index f728f47..c4bdff7 100644 --- a/internal/root/root.go +++ b/internal/root/root.go @@ -22,6 +22,7 @@ package root import ( "bytes" + "context" "errors" "fmt" "io" @@ -383,12 +384,17 @@ const metadataAdvice = "这份文件没有被改动;请修好它(JSON 格式 // ReadMetadata reads mas-avd.json: a missing file is an empty object; a file that exists but cannot be read, is not // JSON or is not an object is an errs.MetadataUnreadable error (callers that write must stop then, never overwrite). func (r *Root) ReadMetadata() (*jsonord.Value, error) { + v, err := r.readMetadata() + if errors.Is(err, fs.ErrNotExist) { + return jsonord.NewObject(), nil + } + return v, err +} + +func (r *Root) readMetadata() (*jsonord.Value, error) { path := r.MetadataPath() data, err := ReadFileShared(path) if err != nil { - if errors.Is(err, fs.ErrNotExist) { - return jsonord.NewObject(), nil - } reason := err.Error() if errors.Is(err, fs.ErrPermission) { reason = "拒绝访问(可能正被别的程序独占)" @@ -434,7 +440,11 @@ func (r *Root) EditMetadata(fn func(o *jsonord.Obj) (bool, error)) error { retur // editMetadata is UpdateMetadata where fn also says whether it changed anything (no write when not). func (r *Root) editMetadata(fn func(o *jsonord.Obj) (bool, error)) error { - l, err := r.lockMetadata() + return r.editMetadataContext(context.Background(), fn) +} + +func (r *Root) editMetadataContext(ctx context.Context, fn func(o *jsonord.Obj) (bool, error)) error { + l, err := r.lockMetadata(ctx) if err != nil { return err } @@ -447,12 +457,23 @@ func (r *Root) editMetadata(fn func(o *jsonord.Obj) (bool, error)) error { if err != nil || !changed { return err } - return r.writeMetadata(v) + return r.writeMetadata(ctx, v) } -func (r *Root) lockMetadata() (*fileLock, error) { +func (r *Root) lockMetadata(ctx context.Context) (*fileLock, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + wait := metadataLockWait + if deadline, ok := ctx.Deadline(); ok { + wait = min(wait, time.Until(deadline)) + } path := r.MetadataPath() + ".lock" - l, ok, err := lockFile(path, metadataLockWait) + l, ok, err := lockFile(path, wait) + if ctxErr := ctx.Err(); ctxErr != nil { + l.unlock() + return nil, ctxErr + } if err != nil { return nil, errs.Wrap(errs.Internal, err, "mas-avd.json 的锁文件打不开: "+path) } @@ -470,7 +491,10 @@ func metadataBytes(v *jsonord.Value) []byte { } // writeMetadata writes the temp file (flushed to disk) and renames it over mas-avd.json. Caller holds the lock. -func (r *Root) writeMetadata(v *jsonord.Value) error { +func (r *Root) writeMetadata(ctx context.Context, v *jsonord.Value) error { + if err := ctx.Err(); err != nil { + return err + } path := r.MetadataPath() if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return errs.Wrap(errs.Internal, err, "建不了目录: "+filepath.Dir(path)) @@ -480,7 +504,7 @@ func (r *Root) writeMetadata(v *jsonord.Value) error { os.Remove(tmp) return errs.Wrap(errs.Internal, err, fmt.Sprintf("写 %s 失败:%v", tmp, err)) } - if err := ReplaceWithRetry(tmp, path); err != nil { + if err := replaceWithRetry(ctx, tmp, path); err != nil { os.Remove(tmp) return errs.Wrap(errs.Internal, err, fmt.Sprintf("替换 %s 失败:%v", path, err)). WithAdvice("可能正被别的程序独占;关掉占用它的程序后再试") @@ -506,13 +530,27 @@ func writeFileSync(path string, data []byte) error { // ReplaceWithRetry renames source over target, retrying for up to 3 s while target (or source) is open somewhere // (AUTO-MAS replace_with_retry). Any open handle blocks the rename, delete sharing or not (see OpenShared). func ReplaceWithRetry(source, target string) error { + return replaceWithRetry(context.Background(), source, target) +} + +func replaceWithRetry(ctx context.Context, source, target string) error { deadline := time.Now().Add(replaceRetry) for { + // The rename commits the write. A timed-out retry must never publish the staged file. + if err := ctx.Err(); err != nil { + return err + } err := os.Rename(source, target) if err == nil || !retryableReplaceError(err) || !time.Now().Before(deadline) { return err } - time.Sleep(50 * time.Millisecond) + timer := time.NewTimer(50 * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } } } @@ -533,7 +571,7 @@ func (r *Root) EnsureMetadata() (bool, error) { if ok, err := exists(); ok || err != nil { return false, err } - l, err := r.lockMetadata() + l, err := r.lockMetadata(context.Background()) if err != nil { return false, err } @@ -550,7 +588,7 @@ func (r *Root) EnsureMetadata() (bool, error) { v := jsonord.NewObject() v.Obj().Set("components", components) v.Obj().Set("addedAt", jsonord.NewString(NowISO())) - if err := r.writeMetadata(v); err != nil { + if err := r.writeMetadata(context.Background(), v); err != nil { return false, err } return true, nil @@ -564,6 +602,15 @@ func (r *Root) InstanceMeta(i int) *jsonord.Obj { return r.MetadataLoose().Obj().Get("instances").Obj().Get(strconv.Itoa(i)).Obj().Clone() } +// ReadInstanceMeta reads instances. from one snapshot, reporting even a missing mas-avd.json as an error. +func (r *Root) ReadInstanceMeta(i int) (*jsonord.Obj, error) { + v, err := r.readMetadata() + if err != nil { + return nil, err + } + return v.Obj().Get("instances").Obj().Get(strconv.Itoa(i)).Obj(), nil +} + // instanceKeyOrder is the order AUTO-MAS's keyword arguments add these keys in (create: memoryMb, initialized, // createdAt; first boot: initialized, initializedAt, launcher, renderer, softwareRenderer, initErrors). A map has no // order, so UpdateInstanceMeta appends new keys in this order, then any others sorted, which gives the same file. @@ -605,8 +652,14 @@ func (r *Root) UpdateInstanceMeta(i int, changes map[string]*jsonord.Value) erro // and stores the result back in place; for changes whose new keys must come in a given order. fn returning an error // aborts without writing. func (r *Root) EditInstanceMeta(i int, fn func(meta *jsonord.Obj) error) error { + return r.EditInstanceMetaContext(context.Background(), i, fn) +} + +// EditInstanceMetaContext is EditInstanceMeta with a deadline on lock acquisition and a cancellation check +// before committing the update. +func (r *Root) EditInstanceMetaContext(ctx context.Context, i int, fn func(meta *jsonord.Obj) error) error { key := strconv.Itoa(i) - return r.UpdateMetadata(func(o *jsonord.Obj) error { + return r.editMetadataContext(ctx, func(o *jsonord.Obj) (bool, error) { instances := o.Get("instances") if instances.Kind() != jsonord.Object { instances = jsonord.NewObject() @@ -616,11 +669,11 @@ func (r *Root) EditInstanceMeta(i int, fn func(meta *jsonord.Obj) error) error { meta = jsonord.NewObject() } if err := fn(meta.Obj()); err != nil { - return err + return false, err } instances.Obj().Set(key, meta) o.Set("instances", instances) - return nil + return true, nil }) }