| 1 | package cage |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | ) |
| 10 | |
| 11 | |
| 12 | |
| 13 | type StorageTransition struct { |
| 14 | ID string `json:"id"` |
| 15 | Source string `json:"source"` |
| 16 | Destination string `json:"destination"` |
| 17 | Backup string `json:"backup"` |
| 18 | State json.RawMessage `json:"state,omitempty"` |
| 19 | } |
| 20 | |
| 21 | type StorageRuntimeSnapshot struct { |
| 22 | State json.RawMessage |
| 23 | Backups []string |
| 24 | Excluded []string |
| 25 | } |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | type StorageRuntime interface { |
| 33 | Name() string |
| 34 | Snapshot(context.Context, string) (StorageRuntimeSnapshot, error) |
| 35 | Begin(context.Context, StorageTransition) error |
| 36 | Switch(context.Context, StorageTransition) error |
| 37 | Recover(context.Context, StorageTransition, bool) error |
| 38 | } |
| 39 | |
| 40 | var ErrStorageRuntimeRecovery = errors.New("环境迁移需要客机管理助手完成恢复,请重新打开原工作台") |
| 41 | |
| 42 | |
| 43 | |
| 44 | func RecoverStorage(ctx context.Context, profile string, runtime StorageRuntime) error { |
| 45 | if _, err := os.Stat(filepath.Join(profile, pendingFile)); errors.Is(err, os.ErrNotExist) { |
| 46 | return nil |
| 47 | } else if err != nil { |
| 48 | return err |
| 49 | } |
| 50 | lock, err := openStorageLockWithRuntime(ctx, profile, true, runtime) |
| 51 | if err != nil { |
| 52 | return err |
| 53 | } |
| 54 | return lock.Close() |
| 55 | } |
| 56 | |
| 57 | |
| 58 | |
| 59 | func CopyStorage(ctx context.Context, source, target string, excluded []string, report func(int64, int64)) error { |
| 60 | for _, path := range excluded { |
| 61 | if !filepath.IsAbs(path) || sameStoragePath(path, source) || !StorageContains(source, path) { |
| 62 | return errors.New("客机管理文件超出当前存储目录") |
| 63 | } |
| 64 | } |
| 65 | if err := os.Mkdir(target, 0700); err != nil { |
| 66 | return err |
| 67 | } |
| 68 | return copyStorageExcluding(ctx, source, target, excluded, report) |
| 69 | } |
| 70 | |
| 71 | func CopyStorageFile(ctx context.Context, source, target string) error { |
| 72 | info, err := os.Lstat(source) |
| 73 | if err != nil { |
| 74 | return err |
| 75 | } |
| 76 | if !info.Mode().IsRegular() { |
| 77 | return errors.New("环境磁盘需要真实本地文件") |
| 78 | } |
| 79 | return copyStorageFile(ctx, source, target, info, make([]byte, 1<<20), make([]byte, 1<<20), func(int) {}) |
| 80 | } |