-
Notifications
You must be signed in to change notification settings - Fork 19
/
namespace_checker.go
96 lines (76 loc) · 2.49 KB
/
namespace_checker.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
package groot
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"sort"
"github.com/pkg/errors"
"code.cloudfoundry.org/grootfs/store"
errorspkg "github.com/pkg/errors"
)
const NamespaceFilename = "namespace.json"
type StoreNamespaceChecker struct {
storePath string
}
type mappings struct {
UIDMappings []string `json:"uid-mappings"`
GIDMappings []string `json:"gid-mappings"`
}
func NewNamespaceChecker(storePath string) *StoreNamespaceChecker {
return &StoreNamespaceChecker{
storePath: storePath,
}
}
func (n *StoreNamespaceChecker) Check(uidMappings, gidMappings []IDMappingSpec) (bool, error) {
namespaceStorePath := filepath.Join(n.storePath, store.MetaDirName, NamespaceFilename)
_, err := os.Stat(namespaceStorePath)
if err != nil {
if os.IsNotExist(err) {
return n.writeNamespace(namespaceStorePath, uidMappings, gidMappings)
}
}
return n.validateNamespace(namespaceStorePath, uidMappings, gidMappings)
}
func (n *StoreNamespaceChecker) validateNamespace(namespaceFilePath string, uidMappings, gidMappings []IDMappingSpec) (bool, error) {
namespaceStore, err := os.Open(namespaceFilePath)
if err != nil {
return false, errorspkg.Wrap(err, "opening namespace file")
}
defer namespaceStore.Close()
var namespace mappings
if err := json.NewDecoder(namespaceStore).Decode(&namespace); err != nil {
return false, errors.Wrapf(err, "reading namespace file %s", namespaceStore)
}
if !reflect.DeepEqual(namespace.UIDMappings, n.normalizeMappings(uidMappings)) {
return false, nil
}
if !reflect.DeepEqual(namespace.GIDMappings, n.normalizeMappings(gidMappings)) {
return false, nil
}
return true, nil
}
func (n *StoreNamespaceChecker) writeNamespace(namespaceFilePath string, uidMappings, gidMappings []IDMappingSpec) (bool, error) {
namespaceStore, err := os.Create(namespaceFilePath)
if err != nil {
return false, errorspkg.Wrap(err, "creating namespace file")
}
defer namespaceStore.Close()
namespace := mappings{
UIDMappings: n.normalizeMappings(uidMappings),
GIDMappings: n.normalizeMappings(gidMappings),
}
if err := json.NewEncoder(namespaceStore).Encode(namespace); err != nil {
return false, err
}
return true, nil
}
func (n *StoreNamespaceChecker) normalizeMappings(mappings []IDMappingSpec) []string {
stringMappings := []string{}
for _, mapping := range mappings {
stringMappings = append(stringMappings, fmt.Sprintf("%d:%d:%d", mapping.NamespaceID, mapping.HostID, mapping.Size))
}
sort.Strings(stringMappings)
return stringMappings
}