-
Notifications
You must be signed in to change notification settings - Fork 9
/
unpackfs.go
210 lines (173 loc) · 5.41 KB
/
unpackfs.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package unpack
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"hash"
"io"
"io/fs"
"os"
"path/filepath"
"golang.org/x/exp/slices"
"namespacelabs.dev/foundation/internal/bytestream"
"namespacelabs.dev/foundation/internal/compute"
"namespacelabs.dev/foundation/internal/executor"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/fnfs"
"namespacelabs.dev/foundation/internal/workspace/dirs"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/std/tasks"
)
type Unpacked struct {
Files string // Points to the unpacked filesystem.
}
func Unpack(what string, fsys compute.Computable[fs.FS], opts ...UnpackOpt) compute.Computable[Unpacked] {
u := &unpackFS{what: what, fsys: fsys}
for _, opt := range opts {
opt(u)
}
return u
}
// Rather than checksum all files, checksum only the specified ones.
func WithChecksumPaths(paths ...string) UnpackOpt {
return func(uf *unpackFS) {
uf.checksumPaths = append(uf.checksumPaths, paths...)
}
}
func SkipChecksumCheck() UnpackOpt {
return func(uf *unpackFS) {
uf.skipChecksums = true
}
}
type UnpackOpt func(*unpackFS)
type unpackFS struct {
what string
fsys compute.Computable[fs.FS]
checksumPaths []string
skipChecksums bool
compute.LocalScoped[Unpacked]
}
var _ compute.Computable[Unpacked] = &unpackFS{}
func (u *unpackFS) Action() *tasks.ActionEvent { return tasks.Action(fmt.Sprintf("unpack.%s", u.what)) }
func (u *unpackFS) Inputs() *compute.In {
return compute.Inputs().Computable("fsys", u.fsys).Str("what", u.what)
}
func (u *unpackFS) Output() compute.Output {
// This node is not cacheable as we always want to validate the contents of the resulting path.
return compute.Output{NotCacheable: true}
}
func (u *unpackFS) Compute(ctx context.Context, deps compute.Resolved) (Unpacked, error) {
fsysv, _ := compute.GetDep(deps, u.fsys, "fsys")
dir, err := dirs.Ensure(dirs.UnpackCache())
if err != nil {
return Unpacked{}, err
}
baseDir := filepath.Join(dir, fsysv.Digest.Algorithm, fsysv.Digest.Hex)
targetDir := filepath.Join(baseDir, u.what)
targetChecksum := filepath.Join(baseDir, "checksums.json")
tasks.Attachments(ctx).AddResult("dir", targetDir)
if checksumsBytes, err := os.ReadFile(targetChecksum); err == nil {
// Target exists, verify contents.
var checksums []checksumEntry
if err := json.Unmarshal(checksumsBytes, &checksums); err == nil {
// If unmarshal fails, we'll just remove and replace below.
eg := executor.New(ctx, "unpack.check-digests")
for _, cksum := range checksums {
cksum := cksum // Close cksum.
eg.Go(func(ctx context.Context) error {
if u.skipChecksums {
_, err := os.Stat(filepath.Join(targetDir, cksum.Path))
return err
}
f, err := os.Open(filepath.Join(targetDir, cksum.Path))
if err != nil {
return err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return err
}
if !cksum.Digest.Equals(schema.FromHash("sha256", h)) {
// Use a regular error here as we never pass this to the user, and we can keep it cheap.
return errors.New("digest doesn't match")
}
return nil
})
}
if err := eg.Wait(); err == nil {
return Unpacked{targetDir}, nil
}
}
}
if err := os.RemoveAll(baseDir); err != nil {
if !os.IsNotExist(err) {
return Unpacked{}, fnerrors.New("failed to remove existing unpack directory: %w", err)
}
}
if err := os.MkdirAll(targetDir, 0755); err != nil {
return Unpacked{}, fnerrors.New("failed to create target unpack directory: %w", err)
}
var checksums []checksumEntry
// XXX parallelism.
if err := fnfs.VisitFiles(ctx, fsysv.Value, func(path string, blob bytestream.ByteStream, de fs.DirEntry) error {
dir := filepath.Dir(path)
if dir != "." {
if err := os.MkdirAll(filepath.Join(targetDir, dir), 0755); err != nil {
return fnerrors.New("failed to create %q: %w", dir, err)
}
}
fi, err := de.Info()
if err != nil {
return err
}
contents, err := blob.Reader()
if err != nil {
return err
}
defer contents.Close()
file, err := os.OpenFile(filepath.Join(targetDir, path), os.O_CREATE|os.O_WRONLY, fi.Mode())
if err != nil {
return err
}
checksum := len(u.checksumPaths) == 0 || slices.Contains(u.checksumPaths, path)
var w io.Writer
var h hash.Hash
if checksum {
h = sha256.New()
w = io.MultiWriter(file, h)
} else {
w = file
}
_, writeErr := io.Copy(w, contents)
closeErr := file.Close()
if writeErr != nil {
return writeErr
} else if closeErr != nil {
return closeErr
}
if h != nil {
checksums = append(checksums, checksumEntry{Path: path, Digest: schema.FromHash("sha256", h)})
}
return nil
}); err != nil {
return Unpacked{}, err
}
serializedChecksums, err := json.Marshal(checksums)
if err != nil {
return Unpacked{}, fnerrors.InternalError("failed to serialize checksums: %w", err)
}
if err := os.WriteFile(targetChecksum, serializedChecksums, 0444); err != nil {
return Unpacked{}, fnerrors.InternalError("failed to write checksum file: %w", err)
}
return Unpacked{targetDir}, nil
}
type checksumEntry struct {
Path string `json:"path"`
Digest schema.Digest `json:"digest"`
}