feat(datamigrate): version the data folder and migrate it on startup

The data folder had no record of which layout wrote it, so a new release
could not tell old data from current data. <DataRoot>\.reims-go-data.json
now records data_version and the app version that last raised it. It is
kept out of reims-go.json, which is rewritten whole on every save and
would drop the field under an older build.

Each build carries every step from older layouts to its own; the GUI and
CLI run them in order before reading the folder, so users can jump
straight from any old version. A failed step leaves the version at the
last success and resumes next launch; a folder from a newer build is left
untouched.

Step v1 writes the driver ownership marker into every reims-ctl VM.
driver.RenamedDriverIDs maps old driver IDs to new ones for when a driver
moves to another plugin; markers are not rewritten, so downgrades still
resolve.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
千川白浪andClaude Opus 5.5 committed 2026-11-30 05:16:38 -07:00
1 parent 9baa1e341c
commit 809ce68cf3
9 files changed
+427 -5

No files matched your search

+7
View File
@@ -108,6 +108,13 @@ flowchart TB
- 日志监视器对单行无换行输出设 **64 KiB** 内存上限(原始日志文件完整保留);已结束任务在 10 分钟后从前后端状态中清理。
- 4K 屏幕预览采用按行流式缩放降低单帧分配;手动复制截图仍保留全分辨率。不在热路径中人为调用 `debug.FreeOSMemory`。
### 4.7 数据目录版本与迁移
- `<DataRoot>\.reims-go-data.json` 记录数据布局版本 `data_version`,以及最后一次提升它的应用版本 `written_by`。它不放进 `reims-go.json`,因为配置每次保存都会按结构体整体重写,旧版本会丢掉不认识的字段。
- 每个版本都带着从旧布局升到自身布局的全部迁移步骤(`internal/datamigrate`),GUI 与 CLI 启动时、读取数据之前按版本号依次执行。步骤必须可重复执行;某步失败时,版本号停在最后一个成功的步骤,下次启动从那里继续。用户可以从任意旧版本直接升到新版本。
- 数据目录的版本高于本程序所知时(降级运行),不做任何改动,只记一条日志。
- 只有删除很老的迁移步骤之后,才需要「最低迁移版本」:新版本根据 `data_version` 判断,并提示先安装某个中间版本。这个判断看的是数据本身,所以直接下载新版本运行也会生效。
- 现有步骤:v1 为 reims-ctl 管理的每台 VM(目录含 `vm.toml`)补写驱动归属标记,见 [plugin-architecture.md](plugin-architecture.md) 的「VM 归属」。
---
## 5. 与上游 `reims-vgpu` 的边界
+1 -1
View File
@@ -237,7 +237,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
| 能力位 | `snapshot`、`cow_clone`、`resize`、`qmp`、`ssh`、`guest_tools`、`affinity`、`opencore`、`recovery`、`cloud_init`、`uefi_iso` 等;UI 与 CLI 按能力位显隐操作 |
| 驱动动作 | `List / Show / ValidateCreate / Create / ValidateSet / Set / Start / Stop / Delete`,可选快照、派生、扩容与通用 `InvokeAction` |
- **VM 归属**:VM 目录内标记文件记录驱动 id;无标记的存量 VM 自动归属 `builtin.driver.reims-macos`,零迁移。CLI 增加 `vm create --driver <id>`,其余 `vm` 子命令按归属自动路由。
- **VM 归属**:VM 目录内的标记文件 `.reims-go-driver` 记录驱动 id;无标记的存量 VM 归属 `builtin.driver.reims-macos`,并由数据迁移补写标记([architecture.md](architecture.md) §4.7)。有标记的 VM 在其驱动缺席时仍以「驱动不可用」列出。驱动迁到另一个插件、id 随之改变时(市场插件不能使用 `builtin.` 前缀),在 `driver.RenamedDriverIDs` 登记旧 id 到新 id 的映射;标记文件不改写,降级后旧版本仍能识别。CLI 增加 `vm create --driver <id>`,其余 `vm` 子命令按归属自动路由。
- **宿主共享服务**(驱动经反向调用复用):体检报告、提交内存预检、大小核绑核、QMP 截屏与键入、缩略图、Guest Tools 注册、进程退出监视、任务进度、日志通道、托盘菜单。
- **VM 进程归宿主托管**:驱动不直接派生 QEMU,而是请求宿主代为启动并返回 PID。这样 VM 进程不随驱动进程的 Job Object 被回收(驱动崩溃或重启不误杀 VM),绑核、退出监视与冷重启补偿也只在宿主实现一份。
- **配置写入**:`reims-ctl set` 铁律约束 reims 管理的 VM;Linux 驱动自管配置文件,同样不允许 UI 拼接原始命令行。
+10
View File
@@ -13,6 +13,7 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/datamigrate"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/guesttools"
@@ -51,6 +52,15 @@ func (a *App) initPlugins() {
safeMode := a.launch.SafeMode
a.mu.Unlock()
// Bring the data folder to this build's layout before anything reads it.
if res, err := datamigrate.Run(dataRoot, version.Version); err != nil {
a.emitLog("app", "Data migration failed: "+err.Error())
} else if res.Newer {
a.emitLog("app", fmt.Sprintf("Data folder uses layout v%d from a newer Reims-Go (this build knows v%d); leaving it unchanged", res.From, datamigrate.CurrentVersion))
} else if len(res.Applied) > 0 {
a.emitLog("app", fmt.Sprintf("Data folder upgraded from layout v%d to v%d (%s)", res.From, res.To, strings.Join(res.Applied, ", ")))
}
mgr, err := plugin.NewManager(plugin.ManagerOptions{
DataRoot: dataRoot,
HostVersion: version.Version,
+5
View File
@@ -12,6 +12,7 @@ import (
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/datamigrate"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
@@ -69,6 +70,10 @@ func run(args []string) (i18n.Locale, error) {
if *dataRootFlag != "" {
cfg.DataRoot = *dataRootFlag
}
// Same data-folder upgrade the GUI runs on startup.
if _, err := datamigrate.Run(cfg.DataRoot, version.Version); err != nil {
fmt.Fprintln(os.Stderr, "warning:", err)
}
// Load enabled static language packs from <DataRoot>/plugins before resolving
// effective locale so "auto" and custom --lang tags (e.g. ja-JP, zh-TW) work in CLI.
plugin.LoadStaticLocalePacks(cfg.DataRoot)
+146
View File
@@ -0,0 +1,146 @@
// Package datamigrate versions the data folder and upgrades it in place.
//
// The data folder records the data layout version it is at in StampFile.
// Every release carries the steps from older layouts to its own and runs
// them on startup, so users can jump straight from an old release to a new
// one. A release that has dropped the steps for very old layouts can tell
// from the stamp that an intermediate release is needed.
//
// The stamp lives in its own file, not in reims-go.json, because
// config.Save rewrites that file from its struct and an older release
// would drop a field it does not know.
package datamigrate
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"time"
)
// StampFile sits at the root of the data folder.
const StampFile = ".reims-go-data.json"
// CurrentVersion is the data layout this build writes. Bump it together
// with a new Step.
const CurrentVersion = 1
// Stamp is the content of StampFile.
type Stamp struct {
DataVersion int `json:"data_version"`
WrittenBy string `json:"written_by,omitempty"` // app version that last raised DataVersion
UpdatedAt time.Time `json:"updated_at"`
}
// Step upgrades the data folder to layout To. Steps must be idempotent: a
// step that fails part way is run again on the next start.
type Step struct {
To int
Name string
Run func(dataRoot string) error
}
// steps lists every upgrade in ascending To order.
var steps = []Step{
{To: 1, Name: "vm-owner-markers", Run: backfillOwnerMarkers},
}
// Result reports what Run did.
type Result struct {
From int // version found on disk (0 when unstamped)
To int // version on disk afterwards
Applied []string // names of the steps that ran
// Newer is true when the folder was written by a newer release. Nothing
// is changed then; the newer release owns the layout.
Newer bool
}
// Run brings the data folder at dataRoot up to CurrentVersion. A missing or
// empty dataRoot is not an error: there is nothing to migrate yet.
func Run(dataRoot, appVersion string) (Result, error) {
return run(dataRoot, appVersion, steps, CurrentVersion, time.Now)
}
func run(dataRoot, appVersion string, steps []Step, current int, now func() time.Time) (Result, error) {
if dataRoot == "" {
return Result{}, nil
}
if st, err := os.Stat(dataRoot); err != nil || !st.IsDir() {
return Result{}, nil
}
stamp, readErr := ReadStamp(dataRoot)
if readErr != nil {
// Steps are idempotent, so a damaged stamp is safe to rebuild from 0.
stamp = Stamp{}
}
res := Result{From: stamp.DataVersion, To: stamp.DataVersion}
if stamp.DataVersion > current {
res.Newer = true
return res, nil
}
for _, s := range steps {
if s.To <= res.To || s.To > current {
continue
}
if err := s.Run(dataRoot); err != nil {
if res.To > res.From {
_ = writeStamp(dataRoot, Stamp{DataVersion: res.To, WrittenBy: appVersion, UpdatedAt: now()})
}
return res, fmt.Errorf("data migration %q (to v%d): %w", s.Name, s.To, err)
}
res.To = s.To
res.Applied = append(res.Applied, s.Name)
}
// A folder already stamped at this layout is left untouched; anything
// else (steps ran, no stamp yet, damaged stamp) gets a fresh stamp.
if stamp.DataVersion == current && readErr == nil && stampExists(dataRoot) {
return res, nil
}
res.To = current
if err := writeStamp(dataRoot, Stamp{DataVersion: current, WrittenBy: appVersion, UpdatedAt: now()}); err != nil {
return res, err
}
return res, nil
}
// ReadStamp reads StampFile. A folder without one is at version 0.
func ReadStamp(dataRoot string) (Stamp, error) {
raw, err := os.ReadFile(filepath.Join(dataRoot, StampFile))
if errors.Is(err, os.ErrNotExist) {
return Stamp{}, nil
}
if err != nil {
return Stamp{}, err
}
var s Stamp
if err := json.Unmarshal(raw, &s); err != nil {
return Stamp{}, fmt.Errorf("parse %s: %w", StampFile, err)
}
if s.DataVersion < 0 {
return Stamp{}, fmt.Errorf("%s: negative data_version", StampFile)
}
return s, nil
}
func stampExists(dataRoot string) bool {
_, err := os.Stat(filepath.Join(dataRoot, StampFile))
return err == nil
}
func writeStamp(dataRoot string, s Stamp) error {
raw, err := json.MarshalIndent(s, "", " ")
if err != nil {
return err
}
path := filepath.Join(dataRoot, StampFile)
tmp := path + ".tmp"
if err := os.WriteFile(tmp, append(raw, '\n'), 0o644); err != nil {
return err
}
return os.Rename(tmp, path)
}
+154
View File
@@ -0,0 +1,154 @@
package datamigrate
import (
"errors"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/driver"
)
func mkVM(t *testing.T, dataRoot, name string, files map[string]string) string {
t.Helper()
dir := filepath.Join(VMRoot(dataRoot), name)
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
for f, body := range files {
if err := os.WriteFile(filepath.Join(dir, f), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
return dir
}
func marker(t *testing.T, dir string) string {
t.Helper()
raw, err := os.ReadFile(filepath.Join(dir, driver.OwnerMarkerFile))
if errors.Is(err, os.ErrNotExist) {
return ""
}
if err != nil {
t.Fatal(err)
}
return strings.TrimSpace(string(raw))
}
func TestRunStampsAndMarksLegacyVMs(t *testing.T) {
root := t.TempDir()
legacy := mkVM(t, root, "macos-tahoe", map[string]string{"vm.toml": "name = 'x'"})
sidecar := mkVM(t, root, "linux-box", map[string]string{"vm.toml": "", driver.OwnerMarkerFile: "community.driver.linux\n"})
junk := mkVM(t, root, "half-created", nil)
res, err := Run(root, "0.2.12")
if err != nil {
t.Fatalf("Run: %v", err)
}
if res.From != 0 || res.To != CurrentVersion || !reflect.DeepEqual(res.Applied, []string{"vm-owner-markers"}) {
t.Fatalf("result = %+v", res)
}
if got := marker(t, legacy); got != driver.BuiltinReimsMacOSDriverID {
t.Fatalf("legacy VM marker = %q", got)
}
if got := marker(t, sidecar); got != "community.driver.linux" {
t.Fatalf("sidecar marker overwritten: %q", got)
}
if got := marker(t, junk); got != "" {
t.Fatalf("folder without vm.toml got a marker: %q", got)
}
st, err := ReadStamp(root)
if err != nil || st.DataVersion != CurrentVersion || st.WrittenBy != "0.2.12" {
t.Fatalf("stamp = %+v, err %v", st, err)
}
// Second start: already current, nothing rewritten.
before, _ := os.ReadFile(filepath.Join(root, StampFile))
res, err = Run(root, "0.2.13")
if err != nil || len(res.Applied) != 0 || res.From != CurrentVersion {
t.Fatalf("second Run = %+v, %v", res, err)
}
after, _ := os.ReadFile(filepath.Join(root, StampFile))
if string(before) != string(after) {
t.Fatalf("stamp rewritten on a no-op start")
}
}
func TestRunLeavesNewerLayoutAlone(t *testing.T) {
root := t.TempDir()
legacy := mkVM(t, root, "old", map[string]string{"vm.toml": ""})
if err := writeStamp(root, Stamp{DataVersion: CurrentVersion + 5, WrittenBy: "9.0.0"}); err != nil {
t.Fatal(err)
}
res, err := Run(root, "0.2.12")
if err != nil || !res.Newer || len(res.Applied) != 0 {
t.Fatalf("Run on newer layout = %+v, %v", res, err)
}
if got := marker(t, legacy); got != "" {
t.Fatalf("migrated a newer layout: marker %q", got)
}
if st, _ := ReadStamp(root); st.DataVersion != CurrentVersion+5 || st.WrittenBy != "9.0.0" {
t.Fatalf("newer stamp changed: %+v", st)
}
}
func TestRunRebuildsDamagedStamp(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, StampFile), []byte("{not json"), 0o644); err != nil {
t.Fatal(err)
}
if _, err := Run(root, "0.2.12"); err != nil {
t.Fatalf("Run: %v", err)
}
if st, err := ReadStamp(root); err != nil || st.DataVersion != CurrentVersion {
t.Fatalf("stamp after rebuild = %+v, %v", st, err)
}
}
func TestRunStopsAtFailedStep(t *testing.T) {
root := t.TempDir()
var ran []string
ok := func(name string) func(string) error {
return func(string) error { ran = append(ran, name); return nil }
}
steps := []Step{
{To: 1, Name: "one", Run: ok("one")},
{To: 2, Name: "two", Run: func(string) error { return errors.New("disk full") }},
{To: 3, Name: "three", Run: ok("three")},
}
now := func() time.Time { return time.Unix(0, 0) }
res, err := run(root, "1.0.0", steps, 3, now)
if err == nil || !strings.Contains(err.Error(), `"two"`) {
t.Fatalf("expected failure in step two, got %v", err)
}
if res.To != 1 || !reflect.DeepEqual(ran, []string{"one"}) {
t.Fatalf("result %+v, ran %v", res, ran)
}
if st, _ := ReadStamp(root); st.DataVersion != 1 {
t.Fatalf("stamp should hold the last good layout, got %+v", st)
}
// Next start resumes from layout 1 once the problem is gone.
steps[1].Run = ok("two")
ran = nil
res, err = run(root, "1.0.0", steps, 3, now)
if err != nil || res.From != 1 || res.To != 3 || !reflect.DeepEqual(ran, []string{"two", "three"}) {
t.Fatalf("resume = %+v, ran %v, err %v", res, ran, err)
}
}
func TestRunWithoutDataFolderIsNoop(t *testing.T) {
missing := filepath.Join(t.TempDir(), "not-created-yet")
if res, err := Run(missing, "0.2.12"); err != nil || !reflect.DeepEqual(res, Result{}) {
t.Fatalf("Run on missing folder = %+v, %v", res, err)
}
if _, err := os.Stat(missing); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("Run created the data folder")
}
if res, err := Run("", "0.2.12"); err != nil || !reflect.DeepEqual(res, Result{}) {
t.Fatalf("Run with empty root = %+v, %v", res, err)
}
}
+50
View File
@@ -0,0 +1,50 @@
package datamigrate
import (
"errors"
"os"
"path/filepath"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
)
// VMRoot is where reims-ctl keeps VM folders; the driver router scans the
// same folder.
func VMRoot(dataRoot string) string {
return filepath.Join((&config.Config{DataRoot: dataRoot}).XDGDataDir(), "reims-ctl", "vms")
}
// backfillOwnerMarkers writes driver.OwnerMarkerFile into every VM folder
// that lacks one. Those VMs predate the marker and belong to the built-in
// macOS driver. With the marker on disk, a release that no longer ships
// that driver still lists them as needing a driver instead of losing them.
func backfillOwnerMarkers(dataRoot string) error {
root := VMRoot(dataRoot)
entries, err := os.ReadDir(root)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
var errs []error
for _, e := range entries {
if !e.IsDir() {
continue
}
dir := filepath.Join(root, e.Name())
if _, err := os.Stat(filepath.Join(dir, driver.OwnerMarkerFile)); err == nil {
continue
}
// Only real VMs: reims-ctl writes vm.toml for each one. Leftover or
// half-created folders stay unmarked.
if _, err := os.Stat(filepath.Join(dir, "vm.toml")); err != nil {
continue
}
if err := driver.WriteOwnerDriver(dir, driver.BuiltinReimsMacOSDriverID); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
+20 -4
View File
@@ -116,21 +116,36 @@ type ActionDriver interface {
InvokeAction(ctx context.Context, vmName, action string, params map[string]any) (any, error)
}
// RenamedDriverIDs maps a driver ID that VM owner markers may still carry
// to the ID that now provides that driver, for when a driver moves to
// another plugin (e.g. the built-in macOS driver becoming a market plugin,
// which cannot keep the reserved "builtin." prefix). Markers are not
// rewritten, so a downgrade still finds its own ID.
var RenamedDriverIDs = map[string]string{}
// CanonicalDriverID follows RenamedDriverIDs.
func CanonicalDriverID(id string) string {
if to, ok := RenamedDriverIDs[id]; ok && to != "" {
return to
}
return id
}
// ReadOwnerDriver returns the owning driver ID recorded in `<vmDir>/.reims-go-driver`.
// Unmarked legacy VMs automatically belong to builtin.driver.reims-macos (§5.3).
func ReadOwnerDriver(vmDir string) string {
if strings.TrimSpace(vmDir) == "" {
return BuiltinReimsMacOSDriverID
return CanonicalDriverID(BuiltinReimsMacOSDriverID)
}
raw, err := os.ReadFile(filepath.Join(vmDir, OwnerMarkerFile))
if err != nil {
return BuiltinReimsMacOSDriverID
return CanonicalDriverID(BuiltinReimsMacOSDriverID)
}
id := strings.TrimSpace(string(raw))
if id == "" {
return BuiltinReimsMacOSDriverID
return CanonicalDriverID(BuiltinReimsMacOSDriverID)
}
return id
return CanonicalDriverID(id)
}
// WriteOwnerDriver records driverID in `<vmDir>/.reims-go-driver`.
@@ -203,6 +218,7 @@ func (rt *Router) DriverByID(id string) (Driver, error) {
if strings.TrimSpace(id) == "" {
id = BuiltinReimsMacOSDriverID
}
id = CanonicalDriverID(id)
if rt == nil || rt.reg == nil {
return nil, fmt.Errorf("driver %q unavailable: registry not initialized", id)
}
+34
View File
@@ -5,6 +5,7 @@ import (
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/plugin"
@@ -87,3 +88,36 @@ func TestOwnerMarkerZeroMigrationAndRouterUnavailable(t *testing.T) {
t.Fatalf("expected reims.driver.linux in use, got inUse=%v err=%v", inUse, err)
}
}
// Simulates the release that moves the macOS driver into a market plugin:
// VMs stamped with the old built-in ID resolve to the new ID, and while
// that plugin is missing they stay listed as needing a driver.
func TestRenamedDriverKeepsMarkedVMsVisible(t *testing.T) {
const newID = "community.driver.reims-macos"
RenamedDriverIDs[BuiltinReimsMacOSDriverID] = newID
t.Cleanup(func() { delete(RenamedDriverIDs, BuiltinReimsMacOSDriverID) })
vmRoot := t.TempDir()
vmDir := filepath.Join(vmRoot, "macos-tahoe")
if err := WriteOwnerDriver(vmDir, BuiltinReimsMacOSDriverID); err != nil {
t.Fatal(err)
}
if got := ReadOwnerDriver(vmDir); got != newID {
t.Fatalf("renamed owner = %q, want %q", got, newID)
}
router := NewRouter(plugin.NewRegistry(nil), func() string { return vmRoot })
all, err := router.ListAllVMs(context.Background())
if err != nil {
t.Fatal(err)
}
if len(all) != 1 || !all[0].DriverUnavailable || all[0].DriverID != newID {
t.Fatalf("expected macos-tahoe as unavailable under %s, got %+v", newID, all)
}
if inUse, _, err := router.CheckDriverInUse(context.Background(), newID); err != nil || !inUse {
t.Fatalf("new driver ID should count the VM as in use: inUse=%v err=%v", inUse, err)
}
if _, err := router.DriverByID(BuiltinReimsMacOSDriverID); err == nil || !strings.Contains(err.Error(), newID) {
t.Fatalf("DriverByID(old ID) should look up %s, got %v", newID, err)
}
}