| 1 | package engine |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "io/fs" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | func prepareCacheStage(src fs.FS, cacheDir, version string) (string, *os.File, error) { |
| 13 | publication, err := openPublicationLock(cacheDir, true) |
| 14 | if err != nil { |
| 15 | return "", nil, fmt.Errorf("engine: lock cache staging: %w", err) |
| 16 | } |
| 17 | defer publication.Close() |
| 18 | if err := reclaimCacheStages(cacheDir); err != nil { |
| 19 | return "", nil, fmt.Errorf("engine: reclaim cache staging: %w", err) |
| 20 | } |
| 21 | if verifyCachedTree(src, cacheDir, version) { |
| 22 | return "", nil, nil |
| 23 | } |
| 24 | owner, err := os.CreateTemp(filepath.Dir(cacheDir), filepath.Base(cacheDir)+".tmp-*.lock") |
| 25 | if err != nil { |
| 26 | return "", nil, fmt.Errorf("engine: create staging ownership file: %w", err) |
| 27 | } |
| 28 | stage := strings.TrimSuffix(owner.Name(), ".lock") |
| 29 | locked, err := tryLockCacheFile(owner) |
| 30 | if !locked && err == nil { |
| 31 | err = errors.New("new staging ownership file is already locked") |
| 32 | } |
| 33 | if err == nil { |
| 34 | err = mkdirPrivate(stage) |
| 35 | } |
| 36 | if err != nil { |
| 37 | _ = owner.Close() |
| 38 | _ = os.Remove(owner.Name()) |
| 39 | return "", nil, fmt.Errorf("engine: create cache staging: %w", err) |
| 40 | } |
| 41 | return stage, owner, nil |
| 42 | } |
| 43 | |
| 44 | // Registration and reclamation both hold the publication lock. A stage's |
| 45 | // separate ownership lock stays held until extraction and publication finish. |
| 46 | func reclaimCacheStages(cacheDir string) error { |
| 47 | parent := filepath.Dir(cacheDir) |
| 48 | entries, err := os.ReadDir(parent) |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | prefix := filepath.Base(cacheDir) + ".tmp-" |
| 53 | for _, entry := range entries { |
| 54 | if !entry.Type().IsRegular() || !strings.HasPrefix(entry.Name(), prefix) || !strings.HasSuffix(entry.Name(), ".lock") { |
| 55 | continue |
| 56 | } |
| 57 | path := filepath.Join(parent, entry.Name()) |
| 58 | owner, err := openNoFollowFile(path, os.O_RDWR, 0o600) |
| 59 | if errors.Is(err, os.ErrNotExist) { |
| 60 | continue |
| 61 | } |
| 62 | if err != nil { |
| 63 | return err |
| 64 | } |
| 65 | locked, err := tryLockCacheFile(owner) |
| 66 | if err != nil || !locked { |
| 67 | _ = owner.Close() |
| 68 | if err != nil { |
| 69 | return err |
| 70 | } |
| 71 | continue |
| 72 | } |
| 73 | err = os.RemoveAll(strings.TrimSuffix(path, ".lock")) |
| 74 | _ = owner.Close() |
| 75 | if err != nil { |
| 76 | return err |
| 77 | } |
| 78 | if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { |
| 79 | return err |
| 80 | } |
| 81 | } |
| 82 | return nil |
| 83 | } |
| 84 |