forked from hashicorp/otto
/
db.go
366 lines (312 loc) · 8.3 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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package localaddr
import (
"bytes"
"container/heap"
"encoding/binary"
"encoding/gob"
"fmt"
"log"
"math/rand"
"net"
"os"
"path/filepath"
"time"
"github.com/boltdb/bolt"
)
var (
boltLocalAddrBucket = []byte("localaddr")
boltBuckets = [][]byte{
boltLocalAddrBucket,
}
boltVersionKey = []byte("version")
boltAddrMapKey = []byte("addr_map")
boltAddrHeapKey = []byte("addr_heap")
boltSubnetKey = []byte("subnet")
)
var (
boltDataVersion byte = 2
)
var boltCidr *net.IPNet
func init() {
_, cidr, err := net.ParseCIDR("100.64.0.0/10")
if err != nil {
panic(err)
}
boltCidr = cidr
}
// DB is a database of local addresses, and provides operations to find
// the next available address, release an address, etc.
//
// DB will act as an LRU: if there are no available IP addresses, it will find
// the oldest IP address and give that to you. This is to combat the fact that
// the things that use IP addresses can often be killed outside of our control,
// and the oldest one is most likely to be stale. This should be an edge
// case.
//
// The first time DB is used, it will find a usable subnet space and
// allocate that as its own. After it allocates that space, it will use
// that for the duration of this DBs existence. The usable subnet space
// is randomized to try to make it unlikely to have a collision.
//
// DB uses a /24 so the entire space of available IP addresses is only
// 256, but these IPs are meant to be local, so they shouldn't overflow
// (it would mean more than 256 VMs are up... or that each of those VMs
// has a lot of network interfaces. Both cases are unlikely in Otto).
//
// FUTURE TODO:
//
// * Allocate additional subnets once we run out of IP space (vs. LRU)
//
type DB struct {
// Path is the path to the IP database. This file doesn't need to
// exist but needs to be a writable path. The parent directory will
// be made.
Path string
}
// Next returns the next IP that is not allocated.
func (this *DB) Next() (net.IP, error) {
db, err := this.db()
if err != nil {
return nil, err
}
defer db.Close()
var result net.IP
err = db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(boltLocalAddrBucket)
data := bucket.Get(boltSubnetKey)
if data == nil {
panic("no subnet")
}
// Get the existing IP addresses that we've mapped
addrMap, addrQ, err := this.getData(bucket)
if err != nil {
return err
}
// Parse the subnet
ip, ipnet, err := net.ParseCIDR(string(data))
if err != nil {
return err
}
ip = ip.To4()
// Generate a random IP in our subnet and try to use it
found := false
for {
// Create a random address in the subnet
ipRaw := make([]byte, 4)
binary.LittleEndian.PutUint32(ipRaw, rand.Uint32())
for i, v := range ipRaw {
ip[i] = ip[i] + (v &^ ipnet.Mask[i])
}
// If this IP exists, then try again
if _, ok := addrMap[ip.String()]; ok {
continue
}
// We found an IP!
found = true
break
}
// If we didn't find an IP, we just use the oldest one available
if !found {
result = heap.Pop(&addrQ).(*ipEntry).Value
}
// Set the result
result = ip
// Add the IP to the map
entry := &ipEntry{LeaseTime: time.Now().UTC(), Value: ip}
heap.Push(&addrQ, entry)
addrMap[ip.String()] = entry.Index
// Store the data
return this.putData(bucket, addrMap, addrQ)
})
return result, err
}
// Release releases the given IP, removing it from the database.
func (this *DB) Release(ip net.IP) error {
db, err := this.db()
if err != nil {
return err
}
defer db.Close()
return db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(boltLocalAddrBucket)
// Get the existing IP addresses that we've mapped
addrMap, addrQ, err := this.getData(bucket)
if err != nil {
return err
}
// If it isn't in there, we're done
idx, ok := addrMap[ip.String()]
if !ok {
return nil
}
// Delete and save
delete(addrMap, ip.String())
addrQ, addrQ[len(addrQ)-1] = append(addrQ[:idx], addrQ[idx+1:]...), nil
heap.Init(&addrQ)
return this.putData(bucket, addrMap, addrQ)
})
}
// Renew updates the last used time of the given IP to right now.
//
// This should be called whenever a DB-given IP is used to make sure
// it isn't chosen as the LRU if we run out of IPs.
func (this *DB) Renew(ip net.IP) error {
db, err := this.db()
if err != nil {
return err
}
defer db.Close()
return db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(boltLocalAddrBucket)
// Get the existing IP addresses that we've mapped
addrMap, addrQ, err := this.getData(bucket)
if err != nil {
return err
}
// If it isn't in there, we're done
idx, ok := addrMap[ip.String()]
if !ok {
return nil
}
entry := addrQ[idx]
entry.LeaseTime = time.Now().UTC()
addrQ.Update(entry)
return nil
})
}
// db returns the database handle, and sets up the DB if it has never
// been created.
func (this *DB) db() (*bolt.DB, error) {
// Make the directory to store our DB
if err := os.MkdirAll(filepath.Dir(this.Path), 0755); err != nil {
return nil, err
}
// Create/Open the DB
db, err := bolt.Open(this.Path, 0644, nil)
if err != nil {
return nil, err
}
// Create the buckets
err = db.Update(func(tx *bolt.Tx) error {
for _, b := range boltBuckets {
if _, err := tx.CreateBucketIfNotExists(b); err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, err
}
// Check the DB version
var version byte
bootstrap := false
err = db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(boltLocalAddrBucket)
data := bucket.Get([]byte("version"))
if data == nil || len(data) == 0 {
version = boltDataVersion
bootstrap = true
return bucket.Put([]byte("version"), []byte{boltDataVersion})
}
version = data[0]
return nil
})
if err != nil {
return nil, err
}
if version > boltDataVersion {
return nil, fmt.Errorf(
"IP data version is higher than this version of Otto knows how\n"+
"to handle! This version of Otto can read up to version %d,\n"+
"but version %d data file found.\n\n"+
"This means that a newer version of Otto touched this data,\n"+
"or the data was corrupted in some other way.",
boltDataVersion, version)
}
// Map of update functions
updateMap := map[byte]func(*bolt.DB) error{
1: this.v1_to_v2,
}
for version < boltDataVersion {
log.Printf(
"[INFO] upgrading lease DB from v%d to v%d", version, version+1)
err := updateMap[version](db)
if err != nil {
return nil, fmt.Errorf(
"Error upgrading data from v%d to v%d: %s",
version, version+1, err)
}
version++
}
// Bootstrap if we have to
if bootstrap {
if err := this.v1_to_v2(db); err != nil {
return nil, err
}
}
// Just call the upgrade to init
return db, nil
}
func (this *DB) v1_to_v2(db *bolt.DB) error {
return db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(boltLocalAddrBucket)
// Replace the subnet with the fixed CIDR we're using. The old CIDR
// doesn't matter...
err := bucket.Put(boltSubnetKey, []byte(boltCidr.String()))
if err != nil {
return err
}
boltAddrBucket := []byte("addrs")
if b := bucket.Bucket(boltAddrBucket); b != nil {
// And delete all the addresses, we start over
err = bucket.DeleteBucket(boltAddrBucket)
if err != nil {
return err
}
}
return bucket.Put(boltVersionKey, []byte{byte(2)})
})
}
func (this *DB) putData(
bucket *bolt.Bucket,
addrMap map[string]int,
addrQ ipQueue) error {
var buf, buf2 bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(addrMap); err != nil {
return err
}
if err := bucket.Put(boltAddrMapKey, buf.Bytes()); err != nil {
return err
}
if err := gob.NewEncoder(&buf2).Encode(addrQ); err != nil {
return err
}
if err := bucket.Put(boltAddrHeapKey, buf2.Bytes()); err != nil {
return err
}
return nil
}
func (this *DB) getData(bucket *bolt.Bucket) (map[string]int, ipQueue, error) {
var addrQ ipQueue
heapRaw := bucket.Get(boltAddrHeapKey)
if heapRaw == nil {
addrQ = ipQueue(make([]*ipEntry, 0, 1))
} else {
dec := gob.NewDecoder(bytes.NewReader(heapRaw))
if err := dec.Decode(&addrQ); err != nil {
return nil, nil, err
}
}
var addrMap map[string]int
mapRaw := bucket.Get(boltAddrMapKey)
if mapRaw == nil {
addrMap = make(map[string]int)
} else {
dec := gob.NewDecoder(bytes.NewReader(mapRaw))
if err := dec.Decode(&addrMap); err != nil {
return nil, nil, err
}
}
return addrMap, addrQ, nil
}