-
Notifications
You must be signed in to change notification settings - Fork 42
/
file.go
307 lines (274 loc) · 8.05 KB
/
file.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
package ipam
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path"
"sync"
"time"
)
type file struct {
// path location of the state file
path string
// prettyJSON is always true, but up for being configurable
prettyJSON bool
// modTime helps with tracking external file changes
// usages of modTime will be deprecated after implementing filesystem-level locking
modTime time.Time
// parent implements internal state management, currently it is always NewMemory()
parent Storage
// lock at some point should be replaced with filesystem lock
lock sync.RWMutex
}
var (
nullModTime time.Time
DefaultLocalFilePath string
)
// fileJSONData is a representation of JSON file's structure
type fileJSONData map[string]map[string]prefixJSON
func init() {
nullModTime = time.Unix(0, 0)
DefaultLocalFilePath = path.Join(getXDGDataHome(), "go-ipam", "ipam-db.json")
}
// getXDGDataHome() is an utility for finding the most suitable data directory:
// 1) $XDG_DATA_HOME
// 2) $HOME/.local/share
// 3) current directory
func getXDGDataHome() string {
if val := os.Getenv("XDG_DATA_HOME"); val != "" {
return val
}
val, err := os.UserHomeDir()
if err != nil {
val = "."
} else {
val = path.Join(val, ".local", "share")
}
return val
}
// NewLocalFile creates a JSON file storage for ipam
func NewLocalFile(ctx context.Context, path string) Storage {
return &file{
path: path,
prettyJSON: true,
parent: NewMemory(ctx),
modTime: nullModTime,
lock: sync.RWMutex{},
}
}
// clearParent() empties the internal state
func (f *file) clearParent(ctx context.Context) (err error) {
namespaces, err := f.parent.ListNamespaces(ctx)
if err != nil {
return fmt.Errorf("failed to list namespaces: %w", err)
}
for _, namespace := range namespaces {
if err = f.parent.DeleteAllPrefixes(ctx, namespace); err != nil {
return fmt.Errorf("failed to delete prefixes for %s namespace: %w", namespace, err)
}
if namespace == defaultNamespace {
// skip deletion instead of replicating NewMemory behavior
continue
}
if err = f.parent.DeleteNamespace(ctx, namespace); err != nil {
return fmt.Errorf("failed to delete %s namespace: %w", namespace, err)
}
}
return nil
}
// getModTime() returns file's modification time without failure (defaulting to nullModTime).
func (f *file) getModTime() time.Time {
info, err := os.Stat(f.path)
if err != nil {
return nullModTime
}
return info.ModTime()
}
// reload() is meant to synchronize from the file to internal state representation,
// currently it bases decision solely on the modification time of the file
//
// see ipamer.NamespacedLoad for alternative implementation candidate
// after https://github.com/metal-stack/go-ipam/issues/111 is addressed
func (f *file) reload(ctx context.Context) (err error) {
// don't do anything when file modification time didn't changed
if modTime := f.getModTime(); modTime != nullModTime && modTime == f.modTime {
return nil
}
var data []byte
storage := make(fileJSONData)
if _, err = os.Stat(f.path); !errors.Is(err, fs.ErrNotExist) {
data, err = os.ReadFile(f.path)
if err != nil {
return fmt.Errorf("failed to read state file %q: %w", f.path, err)
}
}
f.modTime = f.getModTime()
// smallest valid piece of data is "{}"
if len(data) >= 2 {
err = json.Unmarshal(data, &storage)
if err != nil {
return fmt.Errorf("failed to parse state file %q: %w", f.path, err)
}
}
if err = f.clearParent(ctx); err != nil {
return fmt.Errorf("failed to clear memory storage: %w", err)
}
for namespace, prefixes := range storage {
if err = f.parent.CreateNamespace(ctx, namespace); err != nil {
return fmt.Errorf("failed to reload a %s namespace: %w", namespace, err)
}
for _, prefix := range prefixes {
if _, err = f.parent.CreatePrefix(ctx, prefix.toPrefix(), namespace); err != nil {
return fmt.Errorf("failed to reload a %s prefix in %s namespace: %w", prefix.Cidr, namespace, err)
}
}
}
return nil
}
// persist() dumps current internal state to file
//
// see ipamer.NamespacedDump for alternative implementation candidate
// after https://github.com/metal-stack/go-ipam/issues/111 is addressed
func (f *file) persist(ctx context.Context) (err error) {
storage := make(fileJSONData)
var (
prefixes map[string]prefixJSON
ok bool
data []byte
)
namespaces, err := f.parent.ListNamespaces(ctx)
if err != nil {
return fmt.Errorf("failed to list namespaces while building external state representation: %w", err)
}
for _, namespace := range namespaces {
if prefixes, ok = storage[namespace]; !ok {
prefixes = make(map[string]prefixJSON)
storage[namespace] = prefixes
}
ps, err := f.parent.ReadAllPrefixes(ctx, namespace)
if err != nil {
return fmt.Errorf("failed to read prefixes of %s namespace while building external state representation: %w", namespace, err)
}
for _, prefix := range ps {
prefixes[prefix.Cidr] = prefix.toPrefixJSON()
}
}
if f.prettyJSON {
data, err = json.MarshalIndent(storage, "", " ")
} else {
data, err = json.Marshal(storage)
}
if err != nil {
return fmt.Errorf("failed to serialize JSON: %w", err)
}
err = os.WriteFile(f.path, data, 0600)
if err != nil {
return fmt.Errorf("error storing state at %q: %w", f.path, err)
}
f.modTime = f.getModTime()
return err
}
func (f *file) Name() string {
return "file"
}
func (f *file) CreatePrefix(ctx context.Context, prefix Prefix, namespace string) (p Prefix, err error) {
f.lock.Lock()
defer f.lock.Unlock()
if err = f.reload(ctx); err != nil {
return p, err
}
if p, err = f.parent.CreatePrefix(ctx, prefix, namespace); err != nil {
return p, err
}
return p, f.persist(ctx)
}
func (f *file) ReadPrefix(ctx context.Context, prefix, namespace string) (p Prefix, err error) {
f.lock.RLock()
defer f.lock.RUnlock()
if err = f.reload(ctx); err != nil {
return p, err
}
return f.parent.ReadPrefix(ctx, prefix, namespace)
}
func (f *file) DeleteAllPrefixes(ctx context.Context, namespace string) (err error) {
f.lock.RLock()
defer f.lock.RUnlock()
if err = f.reload(ctx); err != nil {
return err
}
if err = f.parent.DeleteAllPrefixes(ctx, namespace); err != nil {
return err
}
return f.persist(ctx)
}
func (f *file) ReadAllPrefixes(ctx context.Context, namespace string) (ps Prefixes, err error) {
f.lock.RLock()
defer f.lock.RUnlock()
if err = f.reload(ctx); err != nil {
return ps, err
}
return f.parent.ReadAllPrefixes(ctx, namespace)
}
func (f *file) ReadAllPrefixCidrs(ctx context.Context, namespace string) (cidrs []string, err error) {
f.lock.RLock()
defer f.lock.RUnlock()
if err = f.reload(ctx); err != nil {
return cidrs, err
}
return f.parent.ReadAllPrefixCidrs(ctx, namespace)
}
func (f *file) UpdatePrefix(ctx context.Context, prefix Prefix, namespace string) (p Prefix, err error) {
f.lock.Lock()
defer f.lock.Unlock()
if err = f.reload(ctx); err != nil {
return p, err
}
if p, err = f.parent.UpdatePrefix(ctx, prefix, namespace); err != nil {
return p, err
}
return p, f.persist(ctx)
}
func (f *file) DeletePrefix(ctx context.Context, prefix Prefix, namespace string) (p Prefix, err error) {
f.lock.Lock()
defer f.lock.Unlock()
if err = f.reload(ctx); err != nil {
return p, err
}
if p, err = f.parent.DeletePrefix(ctx, prefix, namespace); err != nil {
return p, err
}
return p, f.persist(ctx)
}
func (f *file) CreateNamespace(ctx context.Context, namespace string) (err error) {
f.lock.Lock()
defer f.lock.Unlock()
if err = f.reload(ctx); err != nil {
return err
}
if err = f.parent.CreateNamespace(ctx, namespace); err != nil {
return err
}
return f.persist(ctx)
}
func (f *file) ListNamespaces(ctx context.Context) (result []string, err error) {
f.lock.Lock()
defer f.lock.Unlock()
if err = f.reload(ctx); err != nil {
return result, err
}
return f.parent.ListNamespaces(ctx)
}
func (f *file) DeleteNamespace(ctx context.Context, namespace string) (err error) {
f.lock.Lock()
defer f.lock.Unlock()
if err = f.reload(ctx); err != nil {
return err
}
if err = f.parent.DeleteNamespace(ctx, namespace); err != nil {
return err
}
return f.persist(ctx)
}