-
Notifications
You must be signed in to change notification settings - Fork 300
/
image_file_cache.go
156 lines (128 loc) · 4.31 KB
/
image_file_cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package controllers
import (
"bytes"
"context"
"crypto/sha256"
"fmt"
"io"
"os"
"path/filepath"
"sync"
"github.com/openshift/hypershift/support/releaseinfo/registryclient"
ctrl "sigs.k8s.io/controller-runtime"
)
var log = ctrl.Log.WithName("image-cache")
func NewImageFileCache(workDir string) (*imageFileCache, error) {
cacheDir, err := os.MkdirTemp(workDir, "cache-*")
if err != nil {
return nil, fmt.Errorf("failed to create cache directory: %w", err)
}
return &imageFileCache{
cacheMap: make(map[cacheKey]cacheValue),
cacheDir: cacheDir,
regClient: registryclient.ExtractImageFile,
mutex: sync.RWMutex{},
}, nil
}
// Caching wrapper around the registry client function "regClient".
// All files returned by the function are cached as files in a sub-directory of "cacheDir".
// The cached files never expire, but can be automatically re-downloaded if they become corrupted.
type imageFileCache struct {
cacheMap map[cacheKey]cacheValue
cacheDir string
regClient regClient // wrapped registryclient function
mutex sync.RWMutex
}
type checksum []byte
type regClient func(ctx context.Context, imageRef string, pullSecret []byte, file string, out io.Writer) error
type cacheKey struct {
imageRef string
imageFile string
}
type cacheValue struct {
fileName string
fileSha checksum
}
func (c *imageFileCache) extractImageFile(ctx context.Context, imageRef string, pullSecret []byte, imageFile string, out io.Writer) error {
key := cacheKey{imageRef: imageRef, imageFile: imageFile}
c.mutex.RLock()
file, ok := c.cacheMap[key]
c.mutex.RUnlock()
if ok && cacheFileIsValid(file) {
log.Info("retrieved cached file", "imageRef", imageRef, "file", imageFile)
return returnCacheFile(file.fileName, out)
}
// Image file does not seem to be in the cache, begin critical section to add it...
c.mutex.Lock()
defer c.mutex.Unlock()
// Another thread could have added the file to cache while we were waiting for exclusive lock, check again...
if file, ok := c.cacheMap[key]; ok && cacheFileIsValid(file) {
log.Info("retrieved cached file", "imageRef", imageRef, "file", imageFile)
return returnCacheFile(file.fileName, out)
}
// No, image file really is not in the cache or checksum test failed - download from the registry...
newFileName, err := downloadImageFile(ctx, c.regClient, imageRef, pullSecret, imageFile, c.cacheDir)
if err != nil {
return err
}
newFileSha, err := calcFileChecksum(newFileName)
if err != nil {
return err
}
c.cacheMap[key] = cacheValue{newFileName, newFileSha}
log.Info("downloaded and cached file", "imageRef", imageRef, "file", imageFile)
return returnCacheFile(newFileName, out)
}
func cacheFileIsValid(file cacheValue) bool {
checksum, err := calcFileChecksum(file.fileName)
if err != nil {
log.Error(err, "failed to calculate checksum of cached file", "file", file.fileName)
return false
}
if !bytes.Equal(checksum, file.fileSha) {
log.Error(err, "cache file is corrupted", "file", file.fileName)
return false
}
return true
}
func calcFileChecksum(file string) (checksum, error) {
f, err := os.Open(file)
if err != nil {
log.Error(err, "failed to open file", "file", file)
return nil, err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
log.Error(err, "failed to calculate checksum of file", "file", file)
return nil, err
}
return h.Sum(nil), nil
}
func returnCacheFile(fullCacheFileName string, out io.Writer) error {
file, err := os.Open(fullCacheFileName)
if err != nil {
return fmt.Errorf("failed to open cache file: %w", err)
}
defer file.Close()
if _, err := io.Copy(out, file); err != nil {
return fmt.Errorf("failed to copy cache file: %w", err)
}
return nil
}
func downloadImageFile(ctx context.Context, regClient regClient, imageRef string, pullSecret []byte, imageFile string, cacheDir string) (_ string, err error) {
newFile, err := os.CreateTemp(cacheDir, filepath.Base(imageFile)+"-*")
if err != nil {
return "", fmt.Errorf("failed to create cache file: %w", err)
}
defer func() {
closeErr := newFile.Close()
if closeErr != nil && err == nil {
err = fmt.Errorf("failed to close cache file: %w", closeErr)
}
}()
if err = regClient(ctx, imageRef, pullSecret, imageFile, newFile); err != nil {
return "", fmt.Errorf("failed to extract image file: %w", err)
}
return newFile.Name(), nil
}