-
Notifications
You must be signed in to change notification settings - Fork 0
/
layer.go
109 lines (90 loc) · 2.23 KB
/
layer.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
package main
import (
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"fmt"
"hash"
"io"
"os"
"path/filepath"
"strings"
"github.com/vbatts/tar-split/tar/asm"
"github.com/vbatts/tar-split/tar/storage"
)
type LayerReader interface {
io.ReadCloser
Size() uint64
Hash() string
}
type noopLayer struct {
size uint64
hash string
}
func (n noopLayer) Size() uint64 {
return n.size
}
func (n noopLayer) Hash() string {
return n.hash
}
func (n noopLayer) Close() error { return nil }
func (n noopLayer) Read(b []byte) (int, error) {
return int(n.size), io.EOF
}
type layerReader struct {
sha256 hash.Hash
tarReader io.Reader
clean []func()
bytes uint64
}
func (l layerReader) Size() uint64 {
return l.bytes
}
func (l *layerReader) deferClean(f func()) {
l.clean = append(l.clean, f)
}
func (l layerReader) Close() error {
for i := len(l.clean) - 1; i >= 0; i-- {
l.clean[i]()
}
return nil
}
func (l layerReader) Hash() string {
hash := l.sha256.Sum([]byte{})
return fmt.Sprintf("sha256:%s", string(hex.EncodeToString(hash)))
}
func (l *layerReader) Read(b []byte) (int, error) {
n, err := l.tarReader.Read(b)
l.sha256.Write(b[:n])
l.bytes += uint64(n)
return n, err
}
func newLayerReader(n *node) (*layerReader, error) {
p := filepath.Join("/var", "lib", "docker", "image", storageDriver, "layerdb", "sha256", strings.Split(n.id, ":")[1])
cacheIDPath := filepath.Join(p, "cache-id")
cacheBytes, err := os.ReadFile(cacheIDPath)
if err != nil {
return nil, fmt.Errorf("read file %q: %w", cacheIDPath, err)
}
cache := string(cacheBytes)
pTar := filepath.Join("/var/lib/docker", storageDriver, cache, "diff")
tarPath := filepath.Join(p, "tar-split.json.gz")
fdJSON, err := os.Open(tarPath)
if err != nil {
return nil, fmt.Errorf("open %q: %w", tarPath, err)
}
l := &layerReader{}
l.deferClean(func() { fdJSON.Close() })
mfz, err := gzip.NewReader(fdJSON)
if err != nil {
return nil, fmt.Errorf("new reader json: %w", err)
}
l.deferClean(func() { mfz.Close() })
metaUnpacker := storage.NewJSONUnpacker(mfz)
fileGetter := storage.NewPathFileGetter(pTar)
ots := asm.NewOutputTarStream(fileGetter, metaUnpacker)
l.deferClean(func() { ots.Close() })
l.tarReader = ots
l.sha256 = sha256.New()
return l, nil
}