forked from danderson/provision
/
subnet.go
597 lines (567 loc) · 15.1 KB
/
subnet.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
package backend
import (
"encoding/binary"
"errors"
"fmt"
"math/big"
"net"
"sort"
"time"
"github.com/digitalrebar/provision/backend/index"
"github.com/digitalrebar/provision/models"
"github.com/digitalrebar/store"
dhcp "github.com/krolaw/dhcp4"
)
type picker func(*Subnet, map[string]models.Model, string, net.IP) (*Lease, bool)
func pickNone(s *Subnet, usedAddrs map[string]models.Model, token string, hint net.IP) (*Lease, bool) {
// There are no free addresses, and don't fall through to using the most expired one.
return nil, false
}
func pickMostExpired(s *Subnet, usedAddrs map[string]models.Model, token string, hint net.IP) (*Lease, bool) {
currLeases := []*Lease{}
for _, obj := range usedAddrs {
lease, ok := obj.(*Lease)
if ok {
currLeases = append(currLeases, lease)
}
}
sort.Slice(currLeases,
func(i, j int) bool {
return currLeases[i].ExpireTime.Before(currLeases[j].ExpireTime)
})
for _, lease := range currLeases {
if !lease.Expired() {
// If we got to a non-expired lease, we are done
break
}
// Because if how usedAddrs is built, we are guaranteed that an expired
// lease here is not associated with a reservation.
lease.Token = token
lease.Strategy = s.Strategy
return lease, false
}
return nil, true
}
func pickHint(s *Subnet, usedAddrs map[string]models.Model, token string, hint net.IP) (*Lease, bool) {
if hint == nil || !s.InActiveRange(hint) {
return nil, true
}
hex := models.Hexaddr(hint)
res, found := usedAddrs[hex]
if !found {
lease := &Lease{}
Fill(lease)
lease.Addr, lease.Token, lease.Strategy = hint, token, s.Strategy
return lease, false
}
if lease, ok := res.(*Lease); ok {
if lease.Token == token && lease.Strategy == s.Strategy {
// hey, we already have a lease. How nice.
return lease, false
}
if lease.Expired() {
// We don't own this lease, but it is
// expired, so we can steal it.
lease.Token = token
lease.Strategy = s.Strategy
return lease, false
}
}
return nil, false
}
func pickNextFree(s *Subnet, usedAddrs map[string]models.Model, token string, hint net.IP) (*Lease, bool) {
if s.nextLeasableIP == nil {
s.nextLeasableIP = net.IP(make([]byte, 4))
copy(s.nextLeasableIP, s.ActiveStart.To4())
}
one := big.NewInt(1)
end := &big.Int{}
curr := &big.Int{}
end.SetBytes(s.ActiveEnd.To4())
curr.SetBytes(s.nextLeasableIP.To4())
// First, check from nextLeasableIp to ActiveEnd
for curr.Cmp(end) < 1 {
addr := net.IP(curr.Bytes()).To4()
hex := models.Hexaddr(addr)
curr.Add(curr, one)
if _, ok := usedAddrs[hex]; !ok {
s.nextLeasableIP = addr
lease := &Lease{}
Fill(lease)
lease.Addr, lease.Token, lease.Strategy = addr, token, s.Strategy
return lease, false
}
}
// Next, check from ActiveStart to nextLeasableIP
end.SetBytes(s.nextLeasableIP.To4())
curr.SetBytes(s.ActiveStart.To4())
for curr.Cmp(end) < 1 {
addr := net.IP(curr.Bytes()).To4()
hex := models.Hexaddr(addr)
curr.Add(curr, one)
if _, ok := usedAddrs[hex]; !ok {
s.nextLeasableIP = addr
lease := &Lease{}
Fill(lease)
lease.Addr, lease.Token, lease.Strategy = addr, token, s.Strategy
return lease, false
}
}
// No free address, but we can use the most expired one.
return nil, true
}
var (
pickStrategies = map[string]picker{}
)
func init() {
pickStrategies["none"] = pickNone
pickStrategies["hint"] = pickHint
pickStrategies["nextFree"] = pickNextFree
pickStrategies["mostExpired"] = pickMostExpired
}
// Subnet represents a DHCP Subnet
//
// swagger:model
type Subnet struct {
*models.Subnet
validate
nextLeasableIP net.IP
sn *net.IPNet
}
func (obj *Subnet) SetReadOnly(b bool) {
obj.ReadOnly = b
}
func (obj *Subnet) SaveClean() store.KeySaver {
mod := *obj.Subnet
mod.ClearValidation()
return toBackend(&mod, obj.rt)
}
func (s *Subnet) Indexes() map[string]index.Maker {
fix := AsSubnet
res := index.MakeBaseIndexes(s)
res["Name"] = index.Make(
true,
"string",
func(i, j models.Model) bool { return fix(i).Name < fix(j).Name },
func(ref models.Model) (gte, gt index.Test) {
refName := fix(ref).Name
return func(s models.Model) bool {
return fix(s).Name >= refName
},
func(s models.Model) bool {
return fix(s).Name > refName
}
},
func(st string) (models.Model, error) {
sub := fix(s.New())
sub.Name = st
return sub, nil
})
res["Strategy"] = index.Make(
false,
"string",
func(i, j models.Model) bool { return fix(i).Strategy < fix(j).Strategy },
func(ref models.Model) (gte, gt index.Test) {
strategy := fix(ref).Strategy
return func(s models.Model) bool {
return fix(s).Strategy >= strategy
},
func(s models.Model) bool {
return fix(s).Strategy > strategy
}
},
func(st string) (models.Model, error) {
sub := fix(s.New())
sub.Strategy = st
return sub, nil
})
res["NextServer"] = index.Make(
false,
"IP Address",
func(i, j models.Model) bool {
n, o := big.Int{}, big.Int{}
n.SetBytes(fix(i).NextServer.To16())
o.SetBytes(fix(j).NextServer.To16())
return n.Cmp(&o) == -1
},
func(ref models.Model) (gte, gt index.Test) {
addr := &big.Int{}
addr.SetBytes(fix(ref).NextServer.To16())
return func(s models.Model) bool {
o := big.Int{}
o.SetBytes(fix(s).NextServer.To16())
return o.Cmp(addr) != -1
},
func(s models.Model) bool {
o := big.Int{}
o.SetBytes(fix(s).NextServer.To16())
return o.Cmp(addr) == 1
}
},
func(st string) (models.Model, error) {
addr := net.ParseIP(st)
if addr == nil {
return nil, fmt.Errorf("Invalid Address: %s", st)
}
sub := fix(s.New())
sub.NextServer = addr
return sub, nil
})
res["Subnet"] = index.Make(
true,
"CIDR Address",
func(i, j models.Model) bool {
a, _, errA := net.ParseCIDR(fix(i).Subnet.Subnet)
b, _, errB := net.ParseCIDR(fix(j).Subnet.Subnet)
if errA != nil || errB != nil {
fix(i).rt.Panicf("Illegal Subnets '%s', '%s'", fix(i).Subnet.Subnet, fix(j).Subnet.Subnet)
}
n, o := big.Int{}, big.Int{}
n.SetBytes(a.To16())
o.SetBytes(b.To16())
return n.Cmp(&o) == -1
},
func(ref models.Model) (gte, gt index.Test) {
cidr, _, err := net.ParseCIDR(fix(ref).Subnet.Subnet)
if err != nil {
fix(ref).rt.Panicf("Illegal subnet %s: %v", fix(ref).Subnet.Subnet, err)
}
addr := &big.Int{}
addr.SetBytes(cidr.To16())
return func(s models.Model) bool {
cidr, _, err := net.ParseCIDR(fix(s).Subnet.Subnet)
if err != nil {
fix(s).rt.Panicf("Illegal subnet %s: %v", fix(s).Subnet.Subnet, err)
}
o := big.Int{}
o.SetBytes(cidr.To16())
return o.Cmp(addr) != -1
},
func(s models.Model) bool {
cidr, _, err := net.ParseCIDR(fix(s).Subnet.Subnet)
if err != nil {
fix(s).rt.Panicf("Illegal subnet %s: %v", fix(s).Subnet.Subnet, err)
}
o := big.Int{}
o.SetBytes(cidr.To16())
return o.Cmp(addr) == 1
}
},
func(st string) (models.Model, error) {
if _, _, err := net.ParseCIDR(st); err != nil {
return nil, fmt.Errorf("Invalid subnet CIDR: %s", st)
}
sub := fix(s.New())
sub.Subnet.Subnet = st
return sub, nil
})
res["Address"] = index.Make(
false,
"IP Address",
func(i, j models.Model) bool {
a, _, errA := net.ParseCIDR(fix(i).Subnet.Subnet)
b, _, errB := net.ParseCIDR(fix(j).Subnet.Subnet)
if errA != nil || errB != nil {
fix(i).rt.Panicf("Illegal Subnets '%s', '%s'", fix(i).Subnet.Subnet, fix(j).Subnet.Subnet)
}
n, o := big.Int{}, big.Int{}
n.SetBytes(a.To16())
o.SetBytes(b.To16())
return n.Cmp(&o) == -1
},
func(ref models.Model) (gte, gt index.Test) {
addr := fix(ref).Subnet.Subnet
if net.ParseIP(addr) == nil {
fix(ref).rt.Panicf("Illegal IP Address: %s", addr)
}
return func(s models.Model) bool {
l, _ := fix(s).sBounds()
return l(addr)
},
func(s models.Model) bool {
_, u := fix(s).sBounds()
return u(addr)
}
},
func(st string) (models.Model, error) {
addr := net.ParseIP(st)
if addr == nil {
return nil, fmt.Errorf("Invalid IP address: %s", st)
}
sub := fix(s.New())
sub.Subnet.Subnet = st
return sub, nil
})
res["ActiveAddress"] = index.Make(
false,
"IP Address",
func(i, j models.Model) bool {
a, _, errA := net.ParseCIDR(fix(i).Subnet.Subnet)
b, _, errB := net.ParseCIDR(fix(j).Subnet.Subnet)
if errA != nil || errB != nil {
fix(i).rt.Panicf("Illegal Subnets '%s', '%s'", fix(i).Subnet.Subnet, fix(j).Subnet.Subnet)
}
n, o := big.Int{}, big.Int{}
n.SetBytes(a.To16())
o.SetBytes(b.To16())
return n.Cmp(&o) == -1
},
func(ref models.Model) (gte, gt index.Test) {
addr := fix(ref).Subnet.Subnet
if net.ParseIP(addr) == nil {
fix(ref).rt.Panicf("Illegal IP Address: %s", addr)
}
return func(s models.Model) bool {
l, _ := fix(s).aBounds()
return l(addr)
},
func(s models.Model) bool {
_, u := fix(s).aBounds()
return u(addr)
}
},
func(st string) (models.Model, error) {
addr := net.ParseIP(st)
if addr == nil {
return nil, fmt.Errorf("Invalid IP address: %s", st)
}
sub := fix(s.New())
sub.Subnet.Subnet = st
return sub, nil
})
res["Enabled"] = index.Make(
false,
"boolean",
func(i, j models.Model) bool {
return (!fix(i).Enabled) && fix(j).Enabled
},
func(ref models.Model) (gte, gt index.Test) {
avail := fix(ref).Enabled
return func(s models.Model) bool {
v := fix(s).Enabled
return v || (v == avail)
},
func(s models.Model) bool {
return fix(s).Enabled && !avail
}
},
func(st string) (models.Model, error) {
res := &Subnet{Subnet: &models.Subnet{}}
switch st {
case "true":
res.Enabled = true
case "false":
res.Enabled = false
default:
return nil, errors.New("Enabled must be true or false")
}
return res, nil
})
res["Proxy"] = index.Make(
false,
"boolean",
func(i, j models.Model) bool {
return (!fix(i).Proxy) && fix(j).Proxy
},
func(ref models.Model) (gte, gt index.Test) {
avail := fix(ref).Proxy
return func(s models.Model) bool {
v := fix(s).Proxy
return v || (v == avail)
},
func(s models.Model) bool {
return fix(s).Proxy && !avail
}
},
func(st string) (models.Model, error) {
res := &Subnet{Subnet: &models.Subnet{}}
switch st {
case "true":
res.Proxy = true
case "false":
res.Proxy = false
default:
return nil, errors.New("Proxy must be true or false")
}
return res, nil
})
return res
}
func (s *Subnet) subnet() *net.IPNet {
if s.sn != nil {
return s.sn
}
_, res, err := net.ParseCIDR(s.Subnet.Subnet)
if err != nil {
panic(err.Error())
}
s.sn = res
return res
}
func (s *Subnet) New() store.KeySaver {
res := &Subnet{Subnet: &models.Subnet{}}
if s.Subnet != nil && s.ChangeForced() {
res.ForceChange()
}
res.rt = s.rt
return res
}
func (s *Subnet) sBounds() (func(string) bool, func(string) bool) {
sub := s.subnet()
first := big.NewInt(0)
mask := big.NewInt(0)
last := big.NewInt(0)
first.SetBytes([]byte(sub.IP.Mask(sub.Mask)))
notBits := make([]byte, len(sub.Mask))
for i, b := range sub.Mask {
notBits[i] = ^b
}
mask.SetBytes(notBits)
last.Or(first, mask)
firstBytes := first.Bytes()
lastBytes := last.Bytes()
// first "address" in this range is the network address, which cannot be handed out.
lower := func(key string) bool {
return key > models.Hexaddr(net.IP(firstBytes))
}
// last "address" in this range is the broadcast address, which also cannot be handed out.
upper := func(key string) bool {
return key >= models.Hexaddr(net.IP(lastBytes))
}
return lower, upper
}
func (s *Subnet) aBounds() (func(string) bool, func(string) bool) {
return func(key string) bool {
return key >= models.Hexaddr(s.ActiveStart)
},
func(key string) bool {
return key > models.Hexaddr(s.ActiveEnd)
}
}
func (s *Subnet) idxABounds() (index.Test, index.Test) {
return func(o models.Model) bool {
return o.Key() >= models.Hexaddr(s.ActiveStart)
},
func(o models.Model) bool {
return o.Key() > models.Hexaddr(s.ActiveStart)
}
}
func (s *Subnet) InSubnetRange(ip net.IP) bool {
lower, upper := s.sBounds()
hex := models.Hexaddr(ip)
return lower(hex) && !upper(hex)
}
func (s *Subnet) InActiveRange(ip net.IP) bool {
lower, upper := s.aBounds()
hex := models.Hexaddr(ip)
return lower(hex) && !upper(hex)
}
func (s *Subnet) LeaseTimeFor(ip net.IP) time.Duration {
if s.Proxy {
return 0
} else if s.InActiveRange(ip) {
return time.Duration(s.ActiveLeaseTime) * time.Second
} else if s.InSubnetRange(ip) {
return time.Duration(s.ReservedLeaseTime) * time.Second
} else {
return 0
}
}
func AsSubnet(o models.Model) *Subnet {
return o.(*Subnet)
}
func AsSubnets(o []models.Model) []*Subnet {
res := make([]*Subnet, len(o))
for i := range o {
res[i] = AsSubnet(o[i])
}
return res
}
func (s *Subnet) Validate() {
s.Subnet.Fill()
s.Subnet.Validate()
_, subnet, err := net.ParseCIDR(s.Subnet.Subnet)
if err != nil {
s.Errorf("Invalid subnet %s: %v", s.Subnet.Subnet, err)
return
} else {
validateIP4(s, subnet.IP)
}
// Build mask and broadcast for always
mask := net.IP([]byte(net.IP(subnet.Mask).To4()))
bcastBits := binary.BigEndian.Uint32(subnet.IP) | ^binary.BigEndian.Uint32(mask)
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, bcastBits)
// Make sure that options have the correct netmask and broadcast options enabled
needMask := true
needBCast := true
for i, opt := range s.Options {
if opt.Code == byte(dhcp.OptionBroadcastAddress) {
s.Options[i].Value = net.IP(buf).String()
needBCast = false
}
if opt.Code == byte(dhcp.OptionSubnetMask) {
s.Options[i].Value = mask.String()
needMask = false
}
}
if needMask {
s.Options = append(s.Options, models.DhcpOption{byte(dhcp.OptionSubnetMask), mask.String()})
}
if needBCast {
s.Options = append(s.Options, models.DhcpOption{byte(dhcp.OptionBroadcastAddress), net.IP(buf).String()})
}
for _, p := range s.Pickers {
_, ok := pickStrategies[p]
if !ok {
s.Errorf("Picker %s is not a valid lease picking strategy", p)
}
}
s.AddError(index.CheckUnique(s, s.rt.stores("subnets").Items()))
s.SetValid()
if !s.Useable() {
return
}
subnets := AsSubnets(s.rt.stores("subnets").Items())
for i := range subnets {
if subnets[i].Name == s.Name {
continue
}
if subnets[i].subnet().Contains(s.subnet().IP) {
s.Errorf("Overlaps subnet %s", subnets[i].Name)
}
}
s.SetAvailable()
}
func (s *Subnet) BeforeSave() error {
s.Validate()
if !s.Useable() {
return s.MakeError(422, ValidationError, s)
}
return nil
}
func (s *Subnet) OnLoad() error {
defer func() { s.rt = nil }()
s.Fill()
return s.BeforeSave()
}
func (s *Subnet) next(used map[string]models.Model, token string, hint net.IP) (*Lease, bool) {
for _, p := range s.Pickers {
l, f := pickStrategies[p](s, used, token, hint)
if !f {
return l, f
}
}
return nil, false
}
var subnetLockMap = map[string][]string{
"get": []string{"subnets"},
"create": []string{"subnets"},
"update": []string{"subnets"},
"patch": []string{"subnets"},
"delete": []string{"subnets"},
"actions": []string{"subnets", "profiles", "params"},
}
func (s *Subnet) Locks(action string) []string {
return subnetLockMap[action]
}