forked from lyft/cni-ipvlan-vpc-k8s
-
Notifications
You must be signed in to change notification settings - Fork 0
/
registry.go
254 lines (216 loc) · 5.41 KB
/
registry.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
package aws
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net"
"os"
"path"
"sync"
"time"
"github.com/lyft/cni-ipvlan-vpc-k8s/lib"
)
const (
registryDir = "cni-ipvlan-vpc-k8s"
registryFile = "registry.json"
registrySchemaVersion = 1
)
func defaultRegistry() registryContents {
return registryContents{
SchemaVersion: registrySchemaVersion,
IPs: map[string]*registryIP{},
}
}
type registryIP struct {
ReleasedOn lib.JSONTime `json:"released_on"`
}
type registryContents struct {
SchemaVersion int `json:"schema_version"`
IPs map[string]*registryIP `json:"ips"`
}
// Registry defines a re-usable IP registry which tracks IPs that are
// free in the system and when they were last released back to the pool.
type Registry struct {
path string
lock sync.Mutex
}
// registryPath gives a default location for the registry
// which varies based on invoking user ID
func registryPath() string {
uid := os.Getuid()
if uid != 0 {
// Non-root users of the registry
return path.Join("/run/user", fmt.Sprintf("%d", uid), registryDir)
}
return path.Join("/run", registryDir)
}
func (r *Registry) ensurePath() (string, error) {
if len(r.path) == 0 {
r.path = registryPath()
}
rpath := r.path
info, err := os.Stat(rpath)
if err != nil || !info.IsDir() {
err = os.MkdirAll(rpath, os.ModeDir|0700)
if err != nil {
return "", err
}
}
rpath = path.Join(rpath, registryFile)
return rpath, nil
}
func (r *Registry) load() (*registryContents, error) {
// Load the pre-versioned schema
contents := defaultRegistry()
rpath, err := r.ensurePath()
if err != nil {
return nil, err
}
file, err := os.Open(rpath)
if os.IsNotExist(err) {
// Return an empty registry, prefilled with IPs
// already existing on all interfaces and timestamped
// at the golang epoch
free, err := FindFreeIPsAtIndex(0, false)
if err == nil {
for _, freeAlloc := range free {
contents.IPs[freeAlloc.IP.String()] = ®istryIP{lib.JSONTime{time.Time{}}}
}
err = r.save(&contents)
return &contents, err
}
return &contents, nil
} else if err != nil {
return nil, err
}
defer file.Close()
decoder := json.NewDecoder(file)
if decoder == nil {
return nil, fmt.Errorf("invalid decoder")
}
err = decoder.Decode(&contents)
if err != nil {
log.Printf("invalid registry format, returning empty registry %v", err)
contents = defaultRegistry()
}
// Reset the registry if the version is not what we can deal with.
// Add more states here, or just let the registry be blown away
// on invalid loads
if contents.SchemaVersion != registrySchemaVersion {
contents = defaultRegistry()
}
if contents.IPs == nil {
contents = defaultRegistry()
}
return &contents, nil
}
func (r *Registry) save(rc *registryContents) error {
rpath, err := r.ensurePath()
if err != nil {
return err
}
file, err := os.OpenFile(rpath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer file.Close()
encoder := json.NewEncoder(file)
if encoder == nil {
return fmt.Errorf("could not make a new encoder")
}
rc.SchemaVersion = registrySchemaVersion
err = encoder.Encode(rc)
return err
}
// TrackIP records an IP in the free registry with the current system
// time as the current freed-time. If an IP is freed again, the time
// will be updated to the new current time.
func (r *Registry) TrackIP(ip net.IP) error {
r.lock.Lock()
defer r.lock.Unlock()
contents, err := r.load()
if err != nil {
return err
}
contents.IPs[ip.String()] = ®istryIP{lib.JSONTime{time.Now()}}
return r.save(contents)
}
// ForgetIP removes an IP from the registry
func (r *Registry) ForgetIP(ip net.IP) error {
r.lock.Lock()
defer r.lock.Unlock()
contents, err := r.load()
if err != nil {
return err
}
delete(contents.IPs, ip.String())
return r.save(contents)
}
// HasIP checks if an IP is in an registry
func (r *Registry) HasIP(ip net.IP) (bool, error) {
r.lock.Lock()
defer r.lock.Unlock()
contents, err := r.load()
if err != nil {
return false, err
}
_, ok := contents.IPs[ip.String()]
return ok, nil
}
// TrackedBefore returns a list of all IPs last recorded time _before_
// the time passed to this function. You probably want to call this
// with time.Now().Add(-duration).
func (r *Registry) TrackedBefore(t time.Time) ([]net.IP, error) {
r.lock.Lock()
defer r.lock.Unlock()
contents, err := r.load()
if err != nil {
return nil, err
}
returned := []net.IP{}
for ipString, entry := range contents.IPs {
if entry.ReleasedOn.Before(t) {
ip := net.ParseIP(ipString)
if ip == nil {
continue
}
returned = append(returned, ip)
}
}
return returned, nil
}
// Clear clears the registry unconditionally
func (r *Registry) Clear() error {
r.lock.Lock()
defer r.lock.Unlock()
rpath, err := r.ensurePath()
if err != nil {
return err
}
err = os.Remove(rpath)
if os.IsNotExist(err) {
return nil
}
return err
}
// List returns a list of all tracked IPs
func (r *Registry) List() (ret []net.IP, err error) {
r.lock.Lock()
defer r.lock.Unlock()
contents, err := r.load()
if err != nil {
return nil, err
}
for stringIP := range contents.IPs {
ret = append(ret, net.ParseIP(stringIP))
}
return
}
// Jitter takes a duration and adjusts it forward by a up to `pct` percent
// uniformly.
func Jitter(d time.Duration, pct float64) time.Duration {
jitter := rand.Int63n(int64(float64(d) * pct))
d += time.Duration(jitter)
return d
}