forked from kubernetes/kubernetes
/
tree.go
337 lines (307 loc) · 9.18 KB
/
tree.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
package store
import (
"archive/tar"
"crypto/sha512"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"syscall"
specaci "github.com/appc/spec/aci"
"github.com/appc/spec/pkg/tarheader"
"github.com/appc/spec/schema/types"
"github.com/coreos/rkt/pkg/aci"
"github.com/coreos/rkt/pkg/sys"
)
const (
hashfilename = "hash"
renderedfilename = "rendered"
)
// TreeStore represents a store of rendered ACIs
// The image's key becomes the name of the directory containing the rendered aci.
type TreeStore struct {
path string
}
// Write renders the ACI with the provided key in the treestore
// Write, to avoid having a rendered ACI with old stale files, requires that
// the destination directory doesn't exist (usually Remove should be called
// before Write)
func (ts *TreeStore) Write(key string, s *Store) error {
treepath := filepath.Join(ts.path, key)
fi, _ := os.Stat(treepath)
if fi != nil {
return fmt.Errorf("treestore: path %s already exists", treepath)
}
imageID, err := types.NewHash(key)
if err != nil {
return fmt.Errorf("treestore: cannot convert key to imageID: %v", err)
}
err = aci.RenderACIWithImageID(*imageID, treepath, s)
if err != nil {
return fmt.Errorf("treestore: cannot render aci: %v", err)
}
hash, err := ts.Hash(key)
if err != nil {
return fmt.Errorf("treestore: cannot calculate tree hash: %v", err)
}
err = ioutil.WriteFile(filepath.Join(treepath, hashfilename), []byte(hash), 0644)
if err != nil {
return fmt.Errorf("treestore: cannot write hash file: %v", err)
}
// before creating the "rendered" flag file we need to ensure that all data is fsynced
dfd, err := syscall.Open(treepath, syscall.O_RDONLY, 0)
if err != nil {
return err
}
defer syscall.Close(dfd)
if err := sys.Syncfs(dfd); err != nil {
return fmt.Errorf("treestore: failed to sync data: %v", err)
}
// Create rendered file
f, err := os.Create(filepath.Join(treepath, renderedfilename))
if err != nil {
return fmt.Errorf("treestore: failed to write rendered file: %v", err)
}
f.Close()
if err := syscall.Fsync(dfd); err != nil {
return fmt.Errorf("treestore: failed to sync tree store directory: %v", err)
}
return nil
}
// Remove cleans the directory for the specified key
func (ts *TreeStore) Remove(key string) error {
treepath := filepath.Join(ts.path, key)
// If tree path doesn't exist we're done
_, err := os.Stat(treepath)
if err != nil && os.IsNotExist(err) {
return nil
}
if err != nil {
return fmt.Errorf("treestore: failed to open tree store directory: %v", err)
}
renderedFilePath := filepath.Join(treepath, renderedfilename)
// The "rendered" flag file should be the firstly removed file. So if
// the removal ends with some error leaving some stale files IsRendered()
// will return false.
_, err = os.Stat(renderedFilePath)
if err != nil && !os.IsNotExist(err) {
return err
}
if !os.IsNotExist(err) {
err := os.Remove(renderedFilePath)
// Ensure that the treepath directory is fsynced after removing the
// "rendered" flag file
f, err := os.Open(treepath)
if err != nil {
return fmt.Errorf("treestore: failed to open tree store directory: %v", err)
}
defer f.Close()
err = f.Sync()
if err != nil {
return fmt.Errorf("treestore: failed to sync tree store directory: %v", err)
}
}
return os.RemoveAll(treepath)
}
// IsRendered checks if the tree store is fully rendered
func (ts *TreeStore) IsRendered(key string) (bool, error) {
// if the "rendered" flag file exists, assume that the store is already
// fully rendered.
treepath := filepath.Join(ts.path, key)
_, err := os.Stat(filepath.Join(treepath, renderedfilename))
if os.IsNotExist(err) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
// GetPath returns the absolute path of the treestore for the specified key.
// It doesn't ensure that the path exists and is fully rendered. This should
// be done calling IsRendered()
func (ts *TreeStore) GetPath(key string) string {
return filepath.Join(ts.path, key)
}
// GetRootFS returns the absolute path of the rootfs for the specified key.
// It doesn't ensure that the rootfs exists and is fully rendered. This should
// be done calling IsRendered()
func (ts *TreeStore) GetRootFS(key string) string {
return filepath.Join(ts.GetPath(key), "rootfs")
}
// TreeStore calculates an hash of the rendered ACI. It uses the same functions
// used to create a tar but instead of writing the full archive is just
// computes the sha512 sum of the file infos and contents.
func (ts *TreeStore) Hash(key string) (string, error) {
treepath := filepath.Join(ts.path, key)
hash := sha512.New()
iw := NewHashWriter(hash)
err := filepath.Walk(treepath, buildWalker(treepath, iw))
if err != nil {
return "", fmt.Errorf("treestore: error walking rootfs: %v", err)
}
hashstring := hashToKey(hash)
return hashstring, nil
}
// Check calculates the actual rendered ACI's hash and verifies that it matches
// the saved value.
func (ts *TreeStore) Check(key string) error {
treepath := filepath.Join(ts.path, key)
hash, err := ioutil.ReadFile(filepath.Join(treepath, hashfilename))
if err != nil {
return fmt.Errorf("treestore: cannot read hash file: %v", err)
}
curhash, err := ts.Hash(key)
if err != nil {
return fmt.Errorf("treestore: cannot calculate tree hash: %v", err)
}
if curhash != string(hash) {
return fmt.Errorf("treestore: wrong tree hash: %s, expected: %s", curhash, hash)
}
return nil
}
type xattr struct {
Name string
Value string
}
// Like tar Header but, to keep json output reproducible:
// * Xattrs as a slice
// * Skip Uname and Gname
// TODO. Should ModTime/AccessTime/ChangeTime be saved? For validation its
// probably enough to hash the file contents and the other infos and avoid
// problems due to them changing.
// TODO(sgotti) Is it possible that json output will change between go
// versions? Use another or our own Marshaller?
type fileInfo struct {
Name string // name of header file entry
Mode int64 // permission and mode bits
Uid int // user id of owner
Gid int // group id of owner
Size int64 // length in bytes
Typeflag byte // type of header entry
Linkname string // target name of link
Devmajor int64 // major number of character or block device
Devminor int64 // minor number of character or block device
Xattrs []xattr
}
func FileInfoFromHeader(hdr *tar.Header) *fileInfo {
fi := &fileInfo{
Name: hdr.Name,
Mode: hdr.Mode,
Uid: hdr.Uid,
Gid: hdr.Gid,
Size: hdr.Size,
Typeflag: hdr.Typeflag,
Linkname: hdr.Linkname,
Devmajor: hdr.Devmajor,
Devminor: hdr.Devminor,
}
keys := make([]string, len(hdr.Xattrs))
for k := range hdr.Xattrs {
keys = append(keys, k)
}
sort.Strings(keys)
xattrs := make([]xattr, 0)
for _, k := range keys {
xattrs = append(xattrs, xattr{Name: k, Value: hdr.Xattrs[k]})
}
fi.Xattrs = xattrs
return fi
}
// TODO(sgotti) this func is copied from appcs/spec/aci/build.go but also
// removes the hashfile and the renderedfile. Find a way to reuse it.
func buildWalker(root string, aw specaci.ArchiveWriter) filepath.WalkFunc {
// cache of inode -> filepath, used to leverage hard links in the archive
inos := map[uint64]string{}
return func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relpath, err := filepath.Rel(root, path)
if err != nil {
return err
}
if relpath == "." {
return nil
}
if relpath == specaci.ManifestFile || relpath == hashfilename || relpath == renderedfilename {
// ignore; this will be written by the archive writer
// TODO(jonboulle): does this make sense? maybe just remove from archivewriter?
return nil
}
link := ""
var r io.Reader
switch info.Mode() & os.ModeType {
case os.ModeSocket:
return nil
case os.ModeNamedPipe:
case os.ModeCharDevice:
case os.ModeDevice:
case os.ModeDir:
case os.ModeSymlink:
target, err := os.Readlink(path)
if err != nil {
return err
}
link = target
default:
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
r = file
}
hdr, err := tar.FileInfoHeader(info, link)
if err != nil {
panic(err)
}
// Because os.FileInfo's Name method returns only the base
// name of the file it describes, it may be necessary to
// modify the Name field of the returned header to provide the
// full path name of the file.
hdr.Name = relpath
tarheader.Populate(hdr, info, inos)
// If the file is a hard link to a file we've already seen, we
// don't need the contents
if hdr.Typeflag == tar.TypeLink {
hdr.Size = 0
r = nil
}
if err := aw.AddFile(hdr, r); err != nil {
return err
}
return nil
}
}
type imageHashWriter struct {
io.Writer
}
func NewHashWriter(w io.Writer) specaci.ArchiveWriter {
return &imageHashWriter{w}
}
func (aw *imageHashWriter) AddFile(hdr *tar.Header, r io.Reader) error {
// Write the json encoding of the FileInfo struct
hdrj, err := json.Marshal(FileInfoFromHeader(hdr))
if err != nil {
return err
}
_, err = aw.Writer.Write(hdrj)
if err != nil {
return err
}
if r != nil {
// Write the file data
_, err := io.Copy(aw.Writer, r)
if err != nil {
return err
}
}
return nil
}
func (aw *imageHashWriter) Close() error {
return nil
}