| 1 | package cage |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "runtime" |
| 13 | "strconv" |
| 14 | "strings" |
| 15 | "time" |
| 16 | |
| 17 | "github.com/sylvinus/agent-vm/internal/host" |
| 18 | "github.com/sylvinus/agent-vm/internal/paths" |
| 19 | ) |
| 20 | |
| 21 | type StorageLocation struct { |
| 22 | Directory string `json:"directory"` |
| 23 | Custom bool `json:"custom"` |
| 24 | HasEnvironment bool `json:"has_environment"` |
| 25 | Backup string `json:"backup,omitempty"` |
| 26 | } |
| 27 | |
| 28 | type storageRecord struct { |
| 29 | Directory string `json:"directory"` |
| 30 | ID string `json:"id"` |
| 31 | Backups []string `json:"backups,omitempty"` |
| 32 | } |
| 33 | |
| 34 | const locationFile = "environment-storage.json" |
| 35 | const pendingFile = "environment-storage-pending.json" |
| 36 | const storageMarker = ".cage-storage-id" |
| 37 | |
| 38 | type storageMove struct { |
| 39 | Next storageRecord |
| 40 | |
| 41 | |
| 42 | PreviousCustom bool |
| 43 | Runtime string `json:",omitempty"` |
| 44 | Transition StorageTransition `json:",omitempty"` |
| 45 | } |
| 46 | |
| 47 | func readStorageRecord(profile string) (storageRecord, error) { |
| 48 | var r storageRecord |
| 49 | b, err := os.ReadFile(filepath.Join(profile, locationFile)) |
| 50 | if errors.Is(err, os.ErrNotExist) { |
| 51 | return r, nil |
| 52 | } |
| 53 | if err != nil { |
| 54 | return r, err |
| 55 | } |
| 56 | if err = json.Unmarshal(b, &r); err != nil || !filepath.IsAbs(r.Directory) || !validStorageID(r.ID) { |
| 57 | return storageRecord{}, errors.New("Cage 环境存储配置损坏,请先恢复配置") |
| 58 | } |
| 59 | return r, nil |
| 60 | } |
| 61 | |
| 62 | func validStorageID(id string) bool { |
| 63 | return len(id) == 32 && strings.Trim(id, "0123456789abcdef") == "" |
| 64 | } |
| 65 | |
| 66 | func writeStorageJSON(path string, value any) error { |
| 67 | data, err := json.Marshal(value) |
| 68 | if err != nil { |
| 69 | return err |
| 70 | } |
| 71 | f, err := os.CreateTemp(filepath.Dir(path), ".storage-config-*") |
| 72 | if err != nil { |
| 73 | return err |
| 74 | } |
| 75 | defer os.Remove(f.Name()) |
| 76 | _, err = f.Write(data) |
| 77 | if err == nil { |
| 78 | err = f.Sync() |
| 79 | } |
| 80 | if err = errors.Join(err, f.Close()); err != nil { |
| 81 | return err |
| 82 | } |
| 83 | return renameStorage(f.Name(), path) |
| 84 | } |
| 85 | |
| 86 | func sameStoragePath(a, b string) bool { |
| 87 | a, b = filepath.Clean(a), filepath.Clean(b) |
| 88 | if runtime.GOOS == "windows" || runtime.GOOS == "darwin" { |
| 89 | return strings.EqualFold(a, b) |
| 90 | } |
| 91 | return a == b |
| 92 | } |
| 93 | |
| 94 | |
| 95 | |
| 96 | func StoragePhysicalPath(path string) (string, error) { |
| 97 | if !filepath.IsAbs(path) { |
| 98 | return "", errors.New("请选择绝对路径") |
| 99 | } |
| 100 | path = filepath.Clean(path) |
| 101 | real, err := paths.Resolve(path) |
| 102 | if err == nil { |
| 103 | return real, nil |
| 104 | } |
| 105 | if !os.IsNotExist(err) || filepath.Dir(path) == path { |
| 106 | return "", err |
| 107 | } |
| 108 | if _, err = os.Lstat(path); err == nil || !os.IsNotExist(err) { |
| 109 | return "", errors.New("目录包含无法解析的链接") |
| 110 | } |
| 111 | parent, err := StoragePhysicalPath(filepath.Dir(path)) |
| 112 | if err != nil { |
| 113 | return "", err |
| 114 | } |
| 115 | return filepath.Join(parent, filepath.Base(path)), nil |
| 116 | } |
| 117 | |
| 118 | func StorageContains(parent, child string) bool { |
| 119 | rel, err := filepath.Rel(paths.Fold(filepath.Clean(parent)), paths.Fold(filepath.Clean(child))) |
| 120 | return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) |
| 121 | } |
| 122 | |
| 123 | func StoragePathsOverlap(a, b string) bool { |
| 124 | return StorageContains(a, b) || StorageContains(b, a) |
| 125 | } |
| 126 | |
| 127 | |
| 128 | func runningApplicationDir() (string, error) { |
| 129 | exe, err := os.Executable() |
| 130 | if err != nil { |
| 131 | return "", err |
| 132 | } |
| 133 | exe, err = paths.Resolve(exe) |
| 134 | if err != nil { |
| 135 | return "", err |
| 136 | } |
| 137 | dir := filepath.Dir(exe) |
| 138 | for parent := dir; parent != filepath.Dir(parent); parent = filepath.Dir(parent) { |
| 139 | if strings.EqualFold(filepath.Ext(parent), ".app") { |
| 140 | return parent, nil |
| 141 | } |
| 142 | } |
| 143 | if strings.EqualFold(filepath.Base(dir), "resources") { |
| 144 | return filepath.Dir(dir), nil |
| 145 | } |
| 146 | return dir, nil |
| 147 | } |
| 148 | |
| 149 | |
| 150 | |
| 151 | func StoragePrivatePaths(profile string) ([]string, error) { |
| 152 | r, err := readStorageRecord(profile) |
| 153 | if err != nil { |
| 154 | return nil, err |
| 155 | } |
| 156 | private := append([]string(nil), r.Backups...) |
| 157 | if r.Directory != "" { |
| 158 | private = append(private, r.Directory) |
| 159 | } else if _, e := os.Readlink(storageAnchor(profile)); e == nil { |
| 160 | real, e := paths.Resolve(storageAnchor(profile)) |
| 161 | if e != nil { |
| 162 | return nil, e |
| 163 | } |
| 164 | private = append(private, real) |
| 165 | } |
| 166 | |
| 167 | b, err := os.ReadFile(filepath.Join(profile, pendingFile)) |
| 168 | if errors.Is(err, os.ErrNotExist) { |
| 169 | return private, nil |
| 170 | } |
| 171 | if err != nil { |
| 172 | return nil, err |
| 173 | } |
| 174 | var p storageMove |
| 175 | if err = json.Unmarshal(b, &p); err != nil { |
| 176 | return nil, err |
| 177 | } |
| 178 | return append(private, p.Next.Directory), nil |
| 179 | } |
| 180 | |
| 181 | func storageAnchor(profile string) string { return filepath.Join(profile, "state") } |
| 182 | |
| 183 | func getStorageLocation(profile string) (StorageLocation, error) { |
| 184 | r, err := readStorageRecord(profile) |
| 185 | if err != nil { |
| 186 | return StorageLocation{}, err |
| 187 | } |
| 188 | anchor := storageAnchor(profile) |
| 189 | loc := StorageLocation{Directory: anchor, Custom: r.Directory != ""} |
| 190 | if loc.Custom { |
| 191 | loc.Directory = r.Directory |
| 192 | real, err := paths.Resolve(anchor) |
| 193 | target, te := paths.Resolve(filepath.Join(r.Directory, "state")) |
| 194 | marker, me := os.ReadFile(filepath.Join(r.Directory, storageMarker)) |
| 195 | if err != nil || te != nil || me != nil || string(marker) != r.ID || !sameStoragePath(real, target) { |
| 196 | return loc, fmt.Errorf("环境存储不可用,请重新连接原磁盘:%s", r.Directory) |
| 197 | } |
| 198 | if err = localStorageVolume(target); err != nil { |
| 199 | return loc, err |
| 200 | } |
| 201 | } else if _, e := os.Readlink(anchor); e == nil { |
| 202 | |
| 203 | |
| 204 | real, e := paths.Resolve(anchor) |
| 205 | if e != nil { |
| 206 | return loc, e |
| 207 | } |
| 208 | fi, e := os.Stat(real) |
| 209 | if e != nil || !fi.IsDir() { |
| 210 | return loc, fmt.Errorf("环境目录不可用:%s", anchor) |
| 211 | } |
| 212 | if _, e = os.Stat(filepath.Join(filepath.Dir(real), storageMarker)); !errors.Is(e, os.ErrNotExist) { |
| 213 | return loc, errors.New("环境存储配置缺失,请恢复原有配置") |
| 214 | } |
| 215 | loc.Directory = real |
| 216 | } else if info, err := os.Lstat(anchor); err == nil && !info.IsDir() { |
| 217 | return loc, fmt.Errorf("环境目录类型异常:%s", anchor) |
| 218 | } else if err != nil && !errors.Is(err, os.ErrNotExist) { |
| 219 | return loc, err |
| 220 | } |
| 221 | if len(r.Backups) > 0 { |
| 222 | loc.Backup = r.Backups[len(r.Backups)-1] |
| 223 | } |
| 224 | entries, err := os.ReadDir(filepath.Join(anchor, "lima")) |
| 225 | if err != nil && !errors.Is(err, os.ErrNotExist) { |
| 226 | return loc, err |
| 227 | } |
| 228 | for _, entry := range entries { |
| 229 | if entry.IsDir() && !strings.HasPrefix(entry.Name(), "_") { |
| 230 | loc.HasEnvironment = true |
| 231 | break |
| 232 | } |
| 233 | } |
| 234 | if _, err := os.Stat(filepath.Join(profile, "windows-guest.json")); err == nil { |
| 235 | loc.HasEnvironment = true |
| 236 | } else if !errors.Is(err, os.ErrNotExist) { |
| 237 | return loc, err |
| 238 | } |
| 239 | return loc, nil |
| 240 | } |
| 241 | |
| 242 | func GetStorageLocation(profile string) (StorageLocation, error) { |
| 243 | lock, err := openStorageLock(profile, false) |
| 244 | if err != nil { |
| 245 | return StorageLocation{}, err |
| 246 | } |
| 247 | defer lock.Close() |
| 248 | return getStorageLocation(profile) |
| 249 | } |
| 250 | |
| 251 | |
| 252 | |
| 253 | func AcquireStorageUse(profile string) (*os.File, StorageLocation, error) { |
| 254 | lock, err := openStorageLock(profile, false) |
| 255 | if err != nil { |
| 256 | return nil, StorageLocation{}, err |
| 257 | } |
| 258 | loc, err := getStorageLocation(profile) |
| 259 | if err != nil { |
| 260 | lock.Close() |
| 261 | return nil, loc, err |
| 262 | } |
| 263 | return lock, loc, nil |
| 264 | } |
| 265 | |
| 266 | func openStorageLock(profile string, exclusive bool) (*os.File, error) { |
| 267 | return openStorageLockWithRuntime(context.Background(), profile, exclusive, nil) |
| 268 | } |
| 269 | |
| 270 | func openStorageLockWithRuntime(ctx context.Context, profile string, exclusive bool, runtime StorageRuntime) (*os.File, error) { |
| 271 | f, err := os.OpenFile(filepath.Join(profile, "environment-storage.lock"), os.O_CREATE|os.O_RDWR, 0600) |
| 272 | if err != nil { |
| 273 | return nil, err |
| 274 | } |
| 275 | ok, err := lockStorageFile(f, exclusive) |
| 276 | if err != nil || !ok { |
| 277 | f.Close() |
| 278 | if err == nil { |
| 279 | err = errors.New("环境正在运行或迁移中,请停止环境并等待当前操作完成") |
| 280 | } |
| 281 | return nil, err |
| 282 | } |
| 283 | if _, err = os.Stat(filepath.Join(profile, pendingFile)); errors.Is(err, os.ErrNotExist) { |
| 284 | return f, nil |
| 285 | } |
| 286 | if err != nil { |
| 287 | f.Close() |
| 288 | return nil, err |
| 289 | } |
| 290 | if !exclusive { |
| 291 | f.Close() |
| 292 | |
| 293 | |
| 294 | w, err := openStorageLockWithRuntime(ctx, profile, true, runtime) |
| 295 | if err != nil { |
| 296 | return nil, err |
| 297 | } |
| 298 | w.Close() |
| 299 | return openStorageLockWithRuntime(ctx, profile, false, runtime) |
| 300 | } |
| 301 | if err = recoverStorageWithRuntime(ctx, profile, runtime); err != nil { |
| 302 | f.Close() |
| 303 | return nil, err |
| 304 | } |
| 305 | return f, nil |
| 306 | } |
| 307 | |
| 308 | func ValidateStorageTarget(profile, directory string) error { |
| 309 | app, err := runningApplicationDir() |
| 310 | if err != nil { |
| 311 | return err |
| 312 | } |
| 313 | return validateStorageTarget(profile, directory, app, runtime.GOOS) |
| 314 | } |
| 315 | |
| 316 | func validateStorageTarget(profile, directory, app, platform string) error { |
| 317 | if _, err := os.Readlink(storageAnchor(profile)); err == nil { |
| 318 | r, err := readStorageRecord(profile) |
| 319 | if err != nil { |
| 320 | return err |
| 321 | } |
| 322 | if r.Directory == "" { |
| 323 | return errors.New("当前环境使用手动配置的目录链接。请先恢复原目录,再使用 Cage 迁移") |
| 324 | } |
| 325 | } |
| 326 | if !filepath.IsAbs(directory) || filepath.Clean(directory) == filepath.VolumeName(directory)+string(os.PathSeparator) { |
| 327 | return errors.New("请选择本地磁盘上的专用绝对路径,不能使用磁盘根目录") |
| 328 | } |
| 329 | target, err := StoragePhysicalPath(directory) |
| 330 | if err != nil { |
| 331 | return err |
| 332 | } |
| 333 | |
| 334 | existing := target |
| 335 | for { |
| 336 | if _, err = os.Stat(existing); err == nil { |
| 337 | break |
| 338 | } |
| 339 | if !errors.Is(err, os.ErrNotExist) || filepath.Dir(existing) == existing { |
| 340 | return err |
| 341 | } |
| 342 | existing = filepath.Dir(existing) |
| 343 | } |
| 344 | if sameStoragePath(existing, target) { |
| 345 | root, e := storageMountRoot(existing) |
| 346 | if e != nil { |
| 347 | return e |
| 348 | } |
| 349 | if root { |
| 350 | return errors.New("请在磁盘内新建专用文件夹,不能使用卷根目录") |
| 351 | } |
| 352 | } |
| 353 | if err = localStorageVolume(existing); err != nil { |
| 354 | return err |
| 355 | } |
| 356 | private, err := StoragePrivatePaths(profile) |
| 357 | if err != nil { |
| 358 | return err |
| 359 | } |
| 360 | private = append(private, profile, EnvironmentDir(profile)) |
| 361 | appData := windowsApplicationDataDirectory(app, platform) |
| 362 | |
| 363 | |
| 364 | if appData == "" || !sameStoragePath(directory, appData) { |
| 365 | private = append(private, app) |
| 366 | } |
| 367 | for _, p := range private { |
| 368 | real, e := StoragePhysicalPath(p) |
| 369 | if e != nil && !errors.Is(e, os.ErrNotExist) { |
| 370 | return e |
| 371 | } |
| 372 | if StoragePathsOverlap(directory, p) || (real != "" && StoragePathsOverlap(target, real)) { |
| 373 | return errors.New("请选择独立空目录,不能与程序、配置、工作区、现有存储或备份重叠") |
| 374 | } |
| 375 | } |
| 376 | if info, e := os.Lstat(directory); e == nil && (!info.IsDir() || info.Mode()&(os.ModeSymlink|os.ModeIrregular) != 0) { |
| 377 | return errors.New("目标必须是本地真实目录") |
| 378 | } else if e != nil && !errors.Is(e, os.ErrNotExist) { |
| 379 | return e |
| 380 | } |
| 381 | entries, err := os.ReadDir(directory) |
| 382 | if errors.Is(err, os.ErrNotExist) { |
| 383 | return nil |
| 384 | } |
| 385 | if err != nil { |
| 386 | return err |
| 387 | } |
| 388 | if len(entries) > 0 { |
| 389 | return errors.New("环境存储需要专用空目录,请新建文件夹") |
| 390 | } |
| 391 | return nil |
| 392 | } |
| 393 | |
| 394 | func stoppedStorage(source string) error { |
| 395 | |
| 396 | instances, err := os.ReadDir(filepath.Join(source, "lima")) |
| 397 | if errors.Is(err, os.ErrNotExist) { |
| 398 | return nil |
| 399 | } |
| 400 | if err != nil { |
| 401 | return err |
| 402 | } |
| 403 | for _, inst := range instances { |
| 404 | if !inst.IsDir() || strings.HasPrefix(inst.Name(), "_") { |
| 405 | continue |
| 406 | } |
| 407 | dir := filepath.Join(source, "lima", inst.Name()) |
| 408 | entries, err := os.ReadDir(dir) |
| 409 | if err != nil { |
| 410 | return err |
| 411 | } |
| 412 | for _, entry := range entries { |
| 413 | name := entry.Name() |
| 414 | if !strings.HasSuffix(name, ".pid") && name != "cage-running.json" { |
| 415 | continue |
| 416 | } |
| 417 | data, err := os.ReadFile(filepath.Join(dir, name)) |
| 418 | if err != nil { |
| 419 | return err |
| 420 | } |
| 421 | var pid int |
| 422 | started := "" |
| 423 | if name == "cage-running.json" { |
| 424 | var record runningProfile |
| 425 | err = json.Unmarshal(data, &record) |
| 426 | pid, started = record.PID, record.Started |
| 427 | } else { |
| 428 | pid, err = strconv.Atoi(strings.TrimSpace(string(data))) |
| 429 | } |
| 430 | if err != nil || pid < 1 { |
| 431 | return fmt.Errorf("无法核验虚拟机进程记录 %s", name) |
| 432 | } |
| 433 | if profileProcessAlive(pid) && ProcessStartMatches(pid, started) { |
| 434 | return fmt.Errorf("请先停止虚拟机 %s,再迁移环境", inst.Name()) |
| 435 | } |
| 436 | } |
| 437 | } |
| 438 | return nil |
| 439 | } |
| 440 | |
| 441 | func MoveStorage(ctx context.Context, profile, directory string, expected StorageLocation, report func(copied, total int64)) (loc StorageLocation, err error) { |
| 442 | return MoveStorageWithRuntime(ctx, profile, directory, expected, nil, report) |
| 443 | } |
| 444 | |
| 445 | func MoveStorageWithRuntime(ctx context.Context, profile, directory string, expected StorageLocation, runtime StorageRuntime, report func(copied, total int64)) (loc StorageLocation, err error) { |
| 446 | lock, err := openStorageLockWithRuntime(ctx, profile, true, runtime) |
| 447 | if err != nil { |
| 448 | return loc, err |
| 449 | } |
| 450 | defer lock.Close() |
| 451 | if _, bindingErr := os.Stat(filepath.Join(profile, "windows-guest.json")); bindingErr == nil && runtime == nil { |
| 452 | return loc, errors.New("Windows 客机迁移需要同步更新系统管理助手的磁盘绑定") |
| 453 | } else if bindingErr != nil && !errors.Is(bindingErr, os.ErrNotExist) { |
| 454 | return loc, bindingErr |
| 455 | } |
| 456 | loc, err = getStorageLocation(profile) |
| 457 | if err != nil { |
| 458 | return loc, err |
| 459 | } |
| 460 | if !sameStoragePath(expected.Directory, loc.Directory) || expected.HasEnvironment != loc.HasEnvironment { |
| 461 | return loc, errors.New("环境或存储位置已改变,请重新选择") |
| 462 | } |
| 463 | if err = ValidateStorageTarget(profile, directory); err != nil { |
| 464 | return loc, err |
| 465 | } |
| 466 | directory, err = StoragePhysicalPath(directory) |
| 467 | if err != nil { |
| 468 | return loc, err |
| 469 | } |
| 470 | anchor := storageAnchor(profile) |
| 471 | if err = stoppedStorage(anchor); err != nil { |
| 472 | return loc, err |
| 473 | } |
| 474 | previous, err := readStorageRecord(profile) |
| 475 | if err != nil { |
| 476 | return loc, err |
| 477 | } |
| 478 | var token [16]byte |
| 479 | if _, err = rand.Read(token[:]); err != nil { |
| 480 | return loc, err |
| 481 | } |
| 482 | id := fmt.Sprintf("%x", token) |
| 483 | next := storageRecord{Directory: directory, ID: id, Backups: append([]string(nil), previous.Backups...)} |
| 484 | anchorBackup := filepath.Join(profile, "state-backup-"+id) |
| 485 | src := anchor |
| 486 | info, statErr := os.Lstat(anchor) |
| 487 | if statErr != nil && !errors.Is(statErr, os.ErrNotExist) { |
| 488 | return loc, statErr |
| 489 | } |
| 490 | if statErr == nil { |
| 491 | backup := anchorBackup |
| 492 | if loc.Custom { |
| 493 | backup = loc.Directory |
| 494 | src = filepath.Join(loc.Directory, "state") |
| 495 | } |
| 496 | next.Backups = append(next.Backups, backup) |
| 497 | } |
| 498 | move := storageMove{Next: next, PreviousCustom: loc.Custom} |
| 499 | var excluded []string |
| 500 | if runtime != nil { |
| 501 | snapshot, snapshotErr := runtime.Snapshot(ctx, src) |
| 502 | if snapshotErr != nil { |
| 503 | return loc, snapshotErr |
| 504 | } |
| 505 | backup := anchorBackup |
| 506 | if loc.Custom { |
| 507 | backup = src |
| 508 | } |
| 509 | move.Runtime = runtime.Name() |
| 510 | move.Transition = StorageTransition{ID: id, Source: src, Destination: filepath.Join(directory, "state"), Backup: backup, State: snapshot.State} |
| 511 | if move.Runtime == "" || !json.Valid(snapshot.State) { |
| 512 | return loc, errors.New("客机存储事务缺少有效的恢复信息") |
| 513 | } |
| 514 | for _, retained := range snapshot.Backups { |
| 515 | if !filepath.IsAbs(retained) || StoragePathsOverlap(retained, directory) { |
| 516 | return loc, errors.New("客机备份路径与迁移目标冲突") |
| 517 | } |
| 518 | move.Next.Backups = append(move.Next.Backups, retained) |
| 519 | } |
| 520 | next = move.Next |
| 521 | for _, path := range snapshot.Excluded { |
| 522 | if !filepath.IsAbs(path) || sameStoragePath(path, src) || !StorageContains(src, path) { |
| 523 | return loc, errors.New("客机管理文件超出当前存储目录") |
| 524 | } |
| 525 | } |
| 526 | excluded = snapshot.Excluded |
| 527 | } |
| 528 | if err = host.EnsurePrivateDir(directory); err != nil { |
| 529 | if errors.Is(err, os.ErrPermission) { |
| 530 | return loc, fmt.Errorf("无法将目标目录设为仅当前用户可访问。请选择自己新建且可以修改权限的空文件夹:%w", err) |
| 531 | } |
| 532 | return loc, err |
| 533 | } |
| 534 | if err = ValidateStorageTarget(profile, directory); err != nil { |
| 535 | return loc, err |
| 536 | } |
| 537 | if err = writeStorageJSON(filepath.Join(profile, pendingFile), move); err != nil { |
| 538 | return loc, err |
| 539 | } |
| 540 | |
| 541 | |
| 542 | defer func() { |
| 543 | |
| 544 | recovery, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Minute) |
| 545 | defer cancel() |
| 546 | if recErr := recoverStorageWithRuntime(recovery, profile, runtime); recErr != nil { |
| 547 | err = errors.Join(err, fmt.Errorf("恢复迁移:%w", recErr)) |
| 548 | } |
| 549 | }() |
| 550 | if err = claimStorageTarget(directory, id); err != nil { |
| 551 | return loc, err |
| 552 | } |
| 553 | destState := filepath.Join(directory, "state") |
| 554 | if err = os.Mkdir(destState, 0700); err != nil { |
| 555 | return loc, err |
| 556 | } |
| 557 | |
| 558 | |
| 559 | if err = claimStorageTarget(destState, id); err != nil { |
| 560 | _ = os.Remove(destState) |
| 561 | return loc, err |
| 562 | } |
| 563 | if runtime != nil { |
| 564 | if err = runtime.Begin(ctx, move.Transition); err != nil { |
| 565 | return loc, err |
| 566 | } |
| 567 | } |
| 568 | if info != nil { |
| 569 | if err = copyStorageExcluding(ctx, src, destState, excluded, report); err != nil { |
| 570 | return loc, err |
| 571 | } |
| 572 | } |
| 573 | staged := filepath.Join(profile, ".storage-link-"+id) |
| 574 | if err = linkStorage(staged, destState); err != nil { |
| 575 | return loc, err |
| 576 | } |
| 577 | if err = syncStorageDir(directory); err != nil { |
| 578 | return loc, err |
| 579 | } |
| 580 | if err = ctx.Err(); err != nil { |
| 581 | return loc, err |
| 582 | } |
| 583 | if runtime != nil { |
| 584 | if err = runtime.Switch(ctx, move.Transition); err != nil { |
| 585 | return loc, err |
| 586 | } |
| 587 | } |
| 588 | if err = ctx.Err(); err != nil { |
| 589 | return loc, err |
| 590 | } |
| 591 | if info != nil { |
| 592 | if err = renameStorage(anchor, anchorBackup); err != nil { |
| 593 | return loc, err |
| 594 | } |
| 595 | } |
| 596 | if err = renameStorage(staged, anchor); err != nil { |
| 597 | return loc, err |
| 598 | } |
| 599 | if err = writeStorageJSON(filepath.Join(profile, locationFile), next); err != nil { |
| 600 | return loc, err |
| 601 | } |
| 602 | return getStorageLocation(profile) |
| 603 | } |
| 604 | |
| 605 | func claimStorageTarget(dir, id string) error { |
| 606 | f, err := os.OpenFile(filepath.Join(dir, storageMarker), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) |
| 607 | if err != nil { |
| 608 | return err |
| 609 | } |
| 610 | _, err = io.WriteString(f, id) |
| 611 | if err == nil { |
| 612 | err = f.Sync() |
| 613 | } |
| 614 | return errors.Join(err, f.Close()) |
| 615 | } |
| 616 | |
| 617 | func recoverStorage(profile string) error { |
| 618 | return recoverStorageWithRuntime(context.Background(), profile, nil) |
| 619 | } |
| 620 | |
| 621 | func recoverStorageWithRuntime(ctx context.Context, profile string, runtime StorageRuntime) error { |
| 622 | journal := filepath.Join(profile, pendingFile) |
| 623 | b, err := os.ReadFile(journal) |
| 624 | if err != nil { |
| 625 | return err |
| 626 | } |
| 627 | var p storageMove |
| 628 | if err = json.Unmarshal(b, &p); err != nil { |
| 629 | return err |
| 630 | } |
| 631 | next := p.Next |
| 632 | if !validStorageID(next.ID) || !filepath.IsAbs(next.Directory) { |
| 633 | return errors.New("存储迁移记录损坏") |
| 634 | } |
| 635 | if p.Runtime != "" && (runtime == nil || runtime.Name() != p.Runtime) { |
| 636 | return ErrStorageRuntimeRecovery |
| 637 | } |
| 638 | if p.Runtime != "" && (p.Transition.ID != next.ID || !sameStoragePath(p.Transition.Destination, filepath.Join(next.Directory, "state")) || !filepath.IsAbs(p.Transition.Source) || !filepath.IsAbs(p.Transition.Backup) || !json.Valid(p.Transition.State)) { |
| 639 | return errors.New("客机存储恢复记录损坏") |
| 640 | } |
| 641 | r, err := readStorageRecord(profile) |
| 642 | if err != nil { |
| 643 | return err |
| 644 | } |
| 645 | old := filepath.Join(profile, "state-backup-"+next.ID) |
| 646 | stage := filepath.Join(profile, ".storage-link-"+next.ID) |
| 647 | anchor := storageAnchor(profile) |
| 648 | dest := filepath.Join(next.Directory, "state") |
| 649 | if r.ID == next.ID { |
| 650 | if p.Runtime != "" { |
| 651 | if err = runtime.Recover(ctx, p.Transition, true); err != nil { |
| 652 | return err |
| 653 | } |
| 654 | } |
| 655 | if token, e := os.ReadFile(filepath.Join(dest, storageMarker)); e == nil && string(token) == next.ID { |
| 656 | if err = os.Remove(filepath.Join(dest, storageMarker)); err != nil { |
| 657 | return err |
| 658 | } |
| 659 | } |
| 660 | if p.PreviousCustom { |
| 661 | if err = os.Remove(old); err != nil && !errors.Is(err, os.ErrNotExist) { |
| 662 | return err |
| 663 | } |
| 664 | } |
| 665 | } else { |
| 666 | if t, e := os.Readlink(anchor); e == nil && sameStoragePath(t, dest) { |
| 667 | if err = os.Remove(anchor); err != nil { |
| 668 | return err |
| 669 | } |
| 670 | } |
| 671 | if _, e := os.Lstat(old); e == nil { |
| 672 | if _, e = os.Lstat(anchor); !errors.Is(e, os.ErrNotExist) { |
| 673 | return fmt.Errorf("请保留旧环境并检查迁移目录:%s", old) |
| 674 | } |
| 675 | if err = renameStorage(old, anchor); err != nil { |
| 676 | return err |
| 677 | } |
| 678 | } else if !errors.Is(e, os.ErrNotExist) { |
| 679 | return e |
| 680 | } |
| 681 | if p.Runtime != "" { |
| 682 | if err = runtime.Recover(ctx, p.Transition, false); err != nil { |
| 683 | return err |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | marker := filepath.Join(next.Directory, storageMarker) |
| 688 | if token, e := os.ReadFile(marker); e == nil && string(token) == next.ID { |
| 689 | if owner, e := os.ReadFile(filepath.Join(dest, storageMarker)); e == nil && string(owner) == next.ID { |
| 690 | if err = os.RemoveAll(dest); err != nil { |
| 691 | return err |
| 692 | } |
| 693 | } |
| 694 | if err = os.Remove(marker); err != nil { |
| 695 | return err |
| 696 | } |
| 697 | } |
| 698 | } |
| 699 | if err = os.Remove(stage); err != nil && !errors.Is(err, os.ErrNotExist) { |
| 700 | return err |
| 701 | } |
| 702 | return os.Remove(journal) |
| 703 | } |