This repository has been archived by the owner on Aug 8, 2023. It is now read-only.
/
cidrpool.go
112 lines (96 loc) · 2.5 KB
/
cidrpool.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
package leaser
import (
cryptoRand "crypto/rand"
"fmt"
"github.com/ziutek/utils/netaddr"
"math"
"math/big"
mathRand "math/rand"
"net"
)
type CIDRPool struct {
blockPool map[string]struct{}
singlePool map[string]struct{}
}
func NewCIDRPool(subnetRange string, subnetMask int) *CIDRPool {
_, ipCIDR, err := net.ParseCIDR(subnetRange)
if err != nil {
panic(err)
}
cidrMask, _ := ipCIDR.Mask.Size()
mathRand.Seed(getRandomSeed())
return &CIDRPool{
blockPool: generateBlockPool(ipCIDR.IP, uint(cidrMask), uint(subnetMask)),
singlePool: generateSingleIPPool(ipCIDR.IP, uint(subnetMask)),
}
}
func (c *CIDRPool) GetBlockPool() map[string] struct{} {
return c.blockPool
}
func (c *CIDRPool) GetSinglePool() map[string] struct{} {
return c.singlePool
}
func (c *CIDRPool) BlockPoolSize() int {
return len(c.blockPool)
}
func (c *CIDRPool) SingleIPPoolSize() int {
return len(c.singlePool)
}
func (c *CIDRPool) GetAvailableBlock(taken []string) string {
return getAvailable(taken, c.blockPool)
}
func (c *CIDRPool) GetAvailableSingleIP(taken []string) string {
return getAvailable(taken, c.singlePool)
}
func (c *CIDRPool) IsMember(subnet string) bool {
_, blockOk := c.blockPool[subnet]
_, singleOk := c.singlePool[subnet]
return blockOk || singleOk
}
func getAvailable(taken []string, pool map[string]struct{}) string {
available := make(map[string]struct{})
for k, v := range pool {
available[k] = v
}
for _, subnet := range taken {
delete(available, subnet)
}
if len(available) == 0 {
return ""
}
i := mathRand.Intn(len(available))
n := 0
for subnet := range available {
if i == n {
return subnet
}
n++
}
return ""
}
func generateBlockPool(ipStart net.IP, cidrMask, cidrMaskBlock uint) map[string]struct{} {
pool := make(map[string]struct{})
fullRange := 1 << (32 - cidrMask)
blockSize := 1 << (32 - cidrMaskBlock)
for i := blockSize; i < fullRange; i += blockSize {
subnet := fmt.Sprintf("%s/%d", netaddr.IPAdd(ipStart, i), cidrMaskBlock)
pool[subnet] = struct{}{}
}
return pool
}
func generateSingleIPPool(ipStart net.IP, cidrMaskBlock uint) map[string]struct{} {
pool := make(map[string]struct{})
blockSize := 1 << (32 - cidrMaskBlock)
for i := 1; i < blockSize; i++ {
singleCIDR := fmt.Sprintf("%s/32", netaddr.IPAdd(ipStart, i))
pool[singleCIDR] = struct{}{}
}
return pool
}
func getRandomSeed() int64 {
num, err := cryptoRand.Int(cryptoRand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
panic("generating random seed: " + err.Error())
}
return num.Int64()
}