-
Notifications
You must be signed in to change notification settings - Fork 2
/
ipallocator.go
296 lines (251 loc) · 8 KB
/
ipallocator.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
package ipallocator
import (
"context"
"fmt"
"math"
"net"
"strings"
"sync"
"github.com/Scalingo/go-etcd-lock/v5/lock"
"github.com/Scalingo/go-utils/logger"
"github.com/Scalingo/sand/config"
"github.com/Scalingo/sand/netutils"
"github.com/Scalingo/sand/store"
"github.com/bits-and-blooms/bitset"
"github.com/pkg/errors"
)
const (
lockDuration = 20
IPAllocatorPrefix = "/ipalloc"
IPAllocatorLockPrefix = "/ipalloc-lock"
)
type allocation struct {
ID string `json:"id"`
AddressRange string `json:"address_range"`
AddressCount uint `json:"address_count"`
BitSet *bitset.BitSet `json:"bit_set"`
}
func (a allocation) storageKey() string {
return fmt.Sprintf("%s/%s", IPAllocatorPrefix, a.ID)
}
type AllocateIPOpts struct {
AddressRange string
// If set, will try to allocate this precise IP, error if already taken
Address string
}
type RangeAddresser interface {
GetAddressRange() string
}
type IPAllocator interface {
AllocateIP(ctx context.Context, id string, opts AllocateIPOpts) (string, error)
ReleaseIP(ctx context.Context, id string, address string) error
ReleasePool(ctx context.Context, id string) error
}
type allocator struct {
config *config.Config
store store.Store
locker lock.Locker
m *sync.Mutex
allocations map[string]allocation
}
func New(config *config.Config, store store.Store, locker lock.Locker) *allocator {
return &allocator{
config: config, store: store,
locker: locker,
m: &sync.Mutex{},
allocations: make(map[string]allocation),
}
}
func (a *allocation) GetAddressRange() string {
return a.AddressRange
}
func (a *allocator) lockStorageKey(id string) string {
return fmt.Sprintf("%s/%s", IPAllocatorLockPrefix, id)
}
func (a *allocator) AllocateIP(ctx context.Context, id string, opts AllocateIPOpts) (allocatedAddress string, err error) {
lock, err := a.locker.WaitAcquire(a.lockStorageKey(id), lockDuration)
if err != nil {
return "", errors.Wrapf(err, "fail to lock IP allocation")
}
defer func() {
derr := lock.Release()
if derr != nil {
err = errors.Wrapf(derr, "fail to release lock (err is %v)", err)
}
}()
allocation, err := a.findOrCreateAllocation(ctx, id, opts)
if err != nil {
return "", errors.Wrapf(err, "fail to find or create allocation")
}
allocatedAddress = opts.Address
if allocatedAddress != "" {
if !strings.Contains(allocatedAddress, "/") {
_, addressNet, err := net.ParseCIDR(allocation.AddressRange)
if err != nil {
return "", errors.Wrapf(err, "invalid iprange %v", allocation.AddressRange)
}
ones, _ := addressNet.Mask.Size()
allocatedAddress = fmt.Sprintf("%s/%d", allocatedAddress, ones)
}
err = allocation.allocatePredefinedIP(ctx, allocatedAddress)
} else {
allocatedAddress, err = allocation.allocateNextAvailableIP(ctx)
}
if err != nil {
return "", errors.Wrapf(err, "fail to allocate IP")
}
err = a.store.Set(ctx, allocation.storageKey(), &allocation)
if err != nil {
return "", errors.Wrapf(err, "fail to save updated allocation %v", allocation)
}
return allocatedAddress, err
}
func (a *allocator) findOrCreateAllocation(ctx context.Context, id string, opts AllocateIPOpts) (allocation, error) {
var (
err error
alloc = allocation{
ID: id,
}
)
log := logger.Get(ctx).WithField("allocation_id", id)
log.Info("find or create allocation")
err = a.store.Get(ctx, alloc.storageKey(), false, &alloc)
if err == store.ErrNotFound {
_, addressNet, err := net.ParseCIDR(opts.AddressRange)
if err != nil {
return alloc, errors.Wrapf(err, "invalid iprange %v", opts.AddressRange)
}
mask, bits := addressNet.Mask.Size()
// 0.0.0.0/24 -> mask = 24, bits = 32
// 2^8 -> 256 addresses
addressCount := uint(math.Pow(2.0, float64(bits-mask)))
alloc.AddressRange = opts.AddressRange
alloc.AddressCount = addressCount
// Network and Broadcast addresses are reserved
alloc.BitSet = bitset.New(alloc.AddressCount).Set(0).Set(addressCount - 1)
} else if err != nil {
return alloc, errors.Wrapf(err, "fail to get allocation from storage")
}
return alloc, nil
}
func (a allocation) allocatePredefinedIP(ctx context.Context, address string) error {
log := logger.Get(ctx)
addrIP, addressIpnet, err := net.ParseCIDR(address)
if err != nil {
return errors.Wrapf(err, "fail to parse predefined address ip range '%v'", address)
}
log.WithField("ip", addrIP).WithField("ip-range", a.AddressRange).Info("allocation of predefined IP")
if addressIpnet.String() != a.AddressRange {
return errors.Errorf("predefined address is not in the same ip range: %v != %v", addressIpnet.Network(), a.AddressRange)
}
ordinal := ordinalFromIP4(addrIP, addressIpnet.Mask)
if a.BitSet.Test(ordinal) {
return errors.New("ip is already allocated")
}
a.BitSet.Set(ordinal)
log.WithField("ip", addrIP).WithField("ip-range", a.AddressRange).Infof("allocated predefined IP (bitset %d)", ordinal)
return nil
}
func (a allocation) allocateNextAvailableIP(ctx context.Context) (string, error) {
log := logger.Get(ctx)
i := uint(0)
for ; i < a.AddressCount; i++ {
if !a.BitSet.Test(i) {
a.BitSet.Set(i)
break
}
}
ip, ipnet, err := net.ParseCIDR(a.AddressRange)
if err != nil {
return "", errors.Wrapf(err, "fail to parse allocation address range %v", a.AddressRange)
}
ip = netutils.AddIntToIP(ip, uint64(i))
log.WithField("ip", ip).WithField("ip-range", a.AddressRange).Infof("allocated IP (bitset %d)", i)
ones, _ := ipnet.Mask.Size()
return fmt.Sprintf("%s/%d", ip.String(), ones), nil
}
func (a *allocator) ReleaseIP(ctx context.Context, id string, ipcidr string) (err error) {
log := logger.Get(ctx)
lock, err := a.locker.WaitAcquire(a.lockStorageKey(id), lockDuration)
if err != nil {
return errors.Wrapf(err, "fail to lock IP release")
}
defer func() {
derr := lock.Release()
if derr != nil {
err = errors.Wrapf(err, "fail to release lock when releasing IP (err is %v)", err)
}
}()
alloc := allocation{ID: id}
err = a.store.Get(ctx, alloc.storageKey(), false, &alloc)
if err != nil {
return errors.Wrapf(err, "fail to get ip range from store")
}
_, network, err := net.ParseCIDR(alloc.AddressRange)
if err != nil {
return errors.Wrapf(err, "fail to parse iprange of allocation %v", alloc.AddressRange)
}
if !strings.Contains(ipcidr, "/") {
ones, _ := network.Mask.Size()
ipcidr = fmt.Sprintf("%s/%d", ipcidr, ones)
}
ip, _, err := net.ParseCIDR(ipcidr)
if err != nil {
return errors.Wrapf(err, "fail to parse IP CIDR %v", ipcidr)
}
log = log.WithField("ip", ip).WithField("ip-range", alloc.AddressRange)
i := ordinalFromIP4(ip, network.Mask)
log.WithField("ordinal", i).Debug("IP ordinal")
alloc.BitSet.Clear(i)
log.Infof("release IP (bitset %d)", i)
err = a.store.Set(ctx, alloc.storageKey(), &alloc)
if err != nil {
return errors.Wrapf(err, "fail to store ip range in store")
}
return nil
}
func (a *allocator) ReleasePool(ctx context.Context, id string) (err error) {
log := logger.Get(ctx).WithField("allocation_id", id)
lock, err := a.locker.WaitAcquire(a.lockStorageKey(id), lockDuration)
if err != nil {
return errors.Wrapf(err, "fail to lock IP release pool")
}
defer func() {
derr := lock.Release()
if derr != nil {
err = errors.Wrapf(err, "fail to release lock when releasing pool (err is %v)", err)
}
}()
alloc := allocation{ID: id}
log.Infof("Releasing allocation")
err = a.store.Get(ctx, alloc.storageKey(), false, &alloc)
if err != nil {
return errors.Wrapf(err, "fail to get ip range from store")
}
if err == store.ErrNotFound {
log.Infof("allocation not found %v", alloc)
return nil
}
err = a.store.Delete(ctx, alloc.storageKey())
if err != nil {
return errors.Wrapf(err, "fail to delete ip range reference")
}
log.Info("Allocation deleted")
return nil
}
func ordinalFromIP4(ip net.IP, mask net.IPMask) uint {
var (
ordinal uint = 0
rank uint = 1
)
// inv mask
for i := range mask {
mask[i] = mask[i] ^ 0xff
}
ip = ip.Mask(mask)
for i := len(ip) - 1; i >= 0; i-- {
ordinal += uint(ip[i]) * rank
rank++
}
return ordinal
}