-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstore.go
359 lines (286 loc) · 7.97 KB
/
store.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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package binny
import (
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"sync"
"github.com/OneOfOne/xxhash"
"github.com/anchore/binny/internal"
"github.com/anchore/binny/internal/log"
)
var ErrMultipleInstallations = fmt.Errorf("too many installations found")
type ErrDigestMismatch struct {
Path string
Algorithm string
Expected string
Actual string
}
func (e *ErrDigestMismatch) Error() string {
return fmt.Sprintf("digest mismatch: path=%q algorithm=%q expected=%q actual=%q", e.Path, e.Algorithm, e.Expected, e.Actual)
}
type Store struct {
root string
entries []StoreEntry
lock *sync.RWMutex
}
type state struct {
Entries []StoreEntry `json:"entries"`
}
type StoreEntry struct {
root string
Name string `json:"name"`
InstalledVersion string `json:"version"`
Digests map[string]string `json:"digests"`
PathInRoot string `json:"path"`
}
func (e StoreEntry) Path() string {
return filepath.Join(e.root, e.PathInRoot)
}
func NewStore(root string) (*Store, error) {
s := &Store{
root: root,
entries: []StoreEntry{},
lock: &sync.RWMutex{},
}
return s, s.loadState()
}
func (s Store) Root() string {
return s.root
}
// Get returns the store entry for the given tool name and version
func (s *Store) Get(name string, version string) (*StoreEntry, error) {
// check if the tool is already installed...
// if the version matches the desired version, skip
nameVersionEntries := s.GetByName(name, version)
switch len(nameVersionEntries) {
case 0:
nameEntries := s.GetByName(name)
if len(nameEntries) > 0 {
return nil, fmt.Errorf("tool already installed with different configuration")
}
return nil, fmt.Errorf("tool not installed")
case 1:
// pass
default:
return nil, ErrMultipleInstallations
}
entry := nameVersionEntries[0]
if entry.InstalledVersion != version {
return nil, fmt.Errorf("tool %q has different version: %s", name, entry.InstalledVersion)
}
return &entry, nil
}
// GetByName returns all entries with the given name, optionally filtered by one or more versions.
func (s Store) GetByName(name string, versions ...string) []StoreEntry {
var entries []StoreEntry
for _, en := range s.entries {
if en.Name == name {
if len(versions) == 0 {
entries = append(entries, en)
} else {
for _, version := range versions {
if en.InstalledVersion == version {
entries = append(entries, en)
}
}
}
}
}
return entries
}
func (s Store) Entries() (entries []StoreEntry) {
s.lock.RLock()
defer s.lock.RUnlock()
return append(entries, s.entries...)
}
func (s *Store) AddTool(toolName string, resolvedVersion, pathOutsideRoot string) error {
log.WithFields("tool", toolName, "from", pathOutsideRoot).Trace("adding tool to store")
err := s.loadState()
if err != nil {
return err
}
if _, err := os.Stat(s.root); os.IsNotExist(err) {
if err := os.MkdirAll(s.root, 0755); err != nil {
return err
}
}
digests, err := getDigestsForFile(pathOutsideRoot)
if err != nil {
return err
}
sha256Hash, ok := digests[internal.SHA256Algorithm]
if !ok {
return fmt.Errorf("failed to get sha256 hash for %q", pathOutsideRoot)
}
// move the file into the store at root/basename
targetName := toolName
targetPath := filepath.Join(s.root, toolName)
if err := os.Rename(pathOutsideRoot, targetPath); err != nil {
return err
}
// chmod 755 the file
if err := os.Chmod(targetPath, 0755); err != nil {
return fmt.Errorf("failed to chmod %q: %w", targetPath, err)
}
fileInfo := StoreEntry{
root: s.root,
Name: toolName,
InstalledVersion: resolvedVersion,
Digests: digests,
PathInRoot: targetName, // path in the store relative to the root
}
// if entry name exists, replace it, otherwise add it
for i, entry := range s.entries {
if entry.Name == toolName {
log.WithFields("tool", toolName, "sha256", sha256Hash, pathOutsideRoot).Trace("replacing existing tool store entry")
s.entries[i] = fileInfo
return s.saveState()
}
}
log.WithFields("tool", toolName, "sha256", sha256Hash, pathOutsideRoot).Trace("adding new tool store entry")
s.entries = append(s.entries, fileInfo)
return s.saveState()
}
func (s *Store) stateFilePath() string {
return filepath.Join(s.root, ".binny.state.json")
}
func (s *Store) loadState() error {
s.lock.RLock()
defer s.lock.RUnlock()
stateFilePath := s.stateFilePath()
log.WithFields("path", stateFilePath).Trace("loading state")
if _, err := os.Stat(stateFilePath); os.IsNotExist(err) {
return nil
}
stateFile, err := os.Open(stateFilePath)
if err != nil {
return err
}
defer stateFile.Close()
var encodeState state
decoder := json.NewDecoder(stateFile)
if err := decoder.Decode(&encodeState); err != nil {
return err
}
var entries []StoreEntry
for _, entry := range encodeState.Entries {
entry.root = s.root
entries = append(entries, entry)
}
s.entries = entries
return nil
}
func (s Store) saveState() error {
s.lock.Lock()
defer s.lock.Unlock()
stateFilePath := s.stateFilePath()
log.WithFields("path", stateFilePath).Trace("saving state")
stateFile, err := os.OpenFile(stateFilePath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer stateFile.Close()
var encodeState state
for _, entry := range s.entries {
// check if bin exists on disk
if _, err := os.Stat(entry.Path()); os.IsNotExist(err) {
log.WithFields("name", entry.Name, "path", entry.PathInRoot).Trace("binary missing, removing from store")
continue
}
encodeState.Entries = append(encodeState.Entries, entry)
}
encoder := json.NewEncoder(stateFile)
encoder.SetIndent("", " ")
return encoder.Encode(encodeState)
}
func (e *StoreEntry) Verify(useXxh64, useSha256 bool) error {
// at least the file must exist
if _, err := os.Stat(e.Path()); err != nil {
return err
}
if useXxh64 {
expect, ok := e.Digests[internal.XXH64Algorithm]
if !ok {
return fmt.Errorf("no xxh64 digest found for %q", e.Path())
}
actual, err := xxh64File(e.Path())
if err != nil {
return fmt.Errorf("failed to calculate xxh64 of %q: %w", e.Path(), err)
}
if expect != actual {
return &ErrDigestMismatch{
Path: e.Path(),
Algorithm: internal.XXH64Algorithm,
Expected: expect,
Actual: actual,
}
}
}
if useSha256 {
expect, ok := e.Digests[internal.SHA256Algorithm]
if !ok {
return fmt.Errorf("no sha256 digest found for %q", e.Path())
}
actual, err := sha256File(e.Path())
if err != nil {
return fmt.Errorf("failed to calculate sha256 of %q: %w", e.Path(), err)
}
if expect != actual {
return &ErrDigestMismatch{
Path: e.Path(),
Algorithm: internal.SHA256Algorithm,
Expected: expect,
Actual: actual,
}
}
}
return nil
}
func sha256File(path string) (string, error) {
fh, err := os.Open(path)
if err != nil {
return "", err
}
defer fh.Close()
hash := sha256.New()
if _, err := io.Copy(hash, fh); err != nil {
return "", err
}
return fmt.Sprintf("%x", hash.Sum(nil)), nil
}
func xxh64File(path string) (string, error) {
fh, err := os.Open(path)
if err != nil {
return "", err
}
defer fh.Close()
hash := xxhash.New64()
if _, err := io.Copy(hash, fh); err != nil {
return "", err
}
return fmt.Sprintf("%x", hash.Sum(nil)), nil
}
func getDigestsForFile(filePath string) (map[string]string, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("failed to open temp copy of binary %q: %w", filePath, err)
}
defer file.Close()
return getDigestsForReader(file)
}
func getDigestsForReader(r io.Reader) (map[string]string, error) {
sha256Hash := sha256.New()
xxhHash := xxhash.New64()
if _, err := io.Copy(io.MultiWriter(sha256Hash, xxhHash), r); err != nil {
return nil, err
}
sha256Str := fmt.Sprintf("%x", sha256Hash.Sum(nil))
xxhStr := fmt.Sprintf("%x", xxhHash.Sum(nil))
return map[string]string{
internal.SHA256Algorithm: sha256Str,
internal.XXH64Algorithm: xxhStr,
}, nil
}