/
db.go
98 lines (82 loc) · 1.93 KB
/
db.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
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
)
type ID = string
type DiffID = string
type db struct {
allNodes map[ID]*node
}
func (d *db) Get(id ID) *node {
return d.allNodes[id]
}
func (d *db) GetChild(node *node, diffID DiffID) *node {
id := node.children[diffID]
return d.Get(id)
}
func (d *db) Insert(n *node) {
if prevNode, ok := d.allNodes[n.id]; ok {
n.children = prevNode.children
} else {
n.children = map[string]string{}
}
d.allNodes[n.id] = n
if parentNode, ok := d.allNodes[n.parent]; ok {
parentNode.children[n.diffID] = n.id
} else {
d.allNodes[n.parent] = &node{
children: map[string]string{
n.diffID: n.id,
},
}
}
}
func newDb() (*db, error) {
d := &db{
allNodes: map[string]*node{},
}
basePath := filepath.Join("/var", "lib", "docker", "image", storageDriver, "layerdb", "sha256")
entries, err := os.ReadDir(basePath)
if err != nil {
return nil, fmt.Errorf("read dir %q: %w", basePath, err)
}
for _, entry := range entries {
p := filepath.Join(basePath, entry.Name())
parentPath := filepath.Join(p, "parent")
parent, err := os.ReadFile(parentPath)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("read parent file %q: %w", parentPath, err)
}
if parent == nil {
parent = []byte("")
}
diffIDPath := filepath.Join(p, "diff")
diffID, err := os.ReadFile(diffIDPath)
if err != nil {
return nil, fmt.Errorf("read diffID file %q: %w", parentPath, err)
}
cacheIDPath := filepath.Join(p, "cache-id")
cacheID, err := os.ReadFile(cacheIDPath)
if err != nil {
return nil, fmt.Errorf("read cache-id file %q: %w", cacheIDPath, err)
}
n := &node{
cacheID: string(cacheID),
diffID: string(diffID),
parent: string(parent),
id: fmt.Sprintf("sha256:%s", entry.Name()),
}
d.Insert(n)
}
return d, nil
}
type node struct {
id ID
diffID DiffID
cacheID string
parent ID
children map[DiffID]ID
}