-
Notifications
You must be signed in to change notification settings - Fork 3
/
subnet.go
352 lines (291 loc) · 7.76 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
package lochness
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math/rand"
"net"
"path/filepath"
"strings"
"github.com/mistifyio/lochness/pkg/kv"
"github.com/pborman/uuid"
)
var (
// SubnetPath is the key prefix for subnets
SubnetPath = "lochness/subnets/"
)
type (
// Subnet is an actual ip subnet for assigning addresses
Subnet struct {
context *Context
modifiedIndex uint64
ID string `json:"id"`
Metadata map[string]string `json:"metadata"`
NetworkID string `json:"network"`
Gateway net.IP `json:"gateway"`
CIDR *net.IPNet `json:"cidr"`
StartRange net.IP `json:"start"` // first usable IP in range
EndRange net.IP `json:"end"` // last usable IP in range
addresses map[uint32]string //all allocated addresses. use int as its quickest to go back and forth
}
// Subnets is an alias to a slice of *Subnet
Subnets []*Subnet
//helper struct for json
subnetJSON struct {
ID string `json:"id"`
Metadata map[string]string `json:"metadata"`
NetworkID string `json:"network"`
Gateway net.IP `json:"gateway"`
CIDR string `json:"cidr"`
StartRange net.IP `json:"start"`
EndRange net.IP `json:"end"`
}
)
// issues with (un)marshal of net.IPnet
// MarshalJSON is used by the json package
func (s *Subnet) MarshalJSON() ([]byte, error) {
data := subnetJSON{
ID: s.ID,
Metadata: s.Metadata,
NetworkID: s.NetworkID,
Gateway: s.Gateway,
CIDR: s.CIDR.String(),
StartRange: s.StartRange,
EndRange: s.EndRange,
}
return json.Marshal(data)
}
// UnmarshalJSON is used by the json package
func (s *Subnet) UnmarshalJSON(input []byte) error {
data := subnetJSON{}
if err := json.Unmarshal(input, &data); err != nil {
return err
}
s.ID = data.ID
s.Metadata = data.Metadata
s.NetworkID = data.NetworkID
s.Gateway = data.Gateway
s.StartRange = data.StartRange
s.EndRange = data.EndRange
_, n, err := net.ParseCIDR(data.CIDR)
if err != nil {
return err
}
s.CIDR = n
return nil
}
func (c *Context) blankSubnet(id string) *Subnet {
s := &Subnet{
context: c,
ID: id,
Metadata: make(map[string]string),
addresses: make(map[uint32]string),
}
if id == "" {
s.ID = uuid.New()
}
return s
}
// NewSubnet creates a new "blank" subnet.
// Fill in the needed values and then call Save.
func (c *Context) NewSubnet() *Subnet {
return c.blankSubnet("")
}
// Subnet fetches a single subnet by ID
func (c *Context) Subnet(id string) (*Subnet, error) {
var err error
id, err = canonicalizeUUID(id)
if err != nil {
return nil, err
}
s := c.blankSubnet(id)
err = s.Refresh()
if err != nil {
return nil, err
}
return s, nil
}
func (s *Subnet) key() string {
return filepath.Join(SubnetPath, s.ID, "metadata")
}
// Refresh reloads the Subnet from the data store.
func (s *Subnet) Refresh() error {
prefix := filepath.Join(SubnetPath, s.ID)
nodes, err := s.context.kv.GetAll(prefix)
if err != nil {
return err
}
// handle metadata
key := filepath.Join(prefix, "metadata")
value, ok := nodes[key]
if !ok {
return errors.New("metadata key is missing")
}
if err := json.Unmarshal(value.Data, &s); err != nil {
return err
}
s.modifiedIndex = value.Index
delete(nodes, key)
for k, v := range nodes {
elements := strings.Split(k, "/")
dir := elements[len(elements)-2]
if dir != "addresses" {
continue
}
if ip := net.ParseIP(elements[len(elements)-1]); ip != nil {
// just skip on error
s.addresses[ipToI32(ip)] = string(v.Data)
}
}
return nil
}
// Delete removes a subnet. It does not ensure it is unused, so use with extreme caution.
func (s *Subnet) Delete() error {
// Unlink network
if s.NetworkID != "" {
network, err := s.context.Network(s.NetworkID)
if err != nil {
return err
}
if err := network.RemoveSubnet(s); err != nil {
return err
}
}
// Delete the subnet
return s.context.kv.Delete(filepath.Join(SubnetPath, s.ID), true)
}
// Validate ensures the values are reasonable.
func (s *Subnet) Validate() error {
if _, err := canonicalizeUUID(s.ID); err != nil {
return errors.New("invalid ID")
}
if s.CIDR == nil {
return errors.New("CIDR cannot be nil")
}
if s.StartRange == nil {
return errors.New("StartRange cannot be nil")
}
if !s.CIDR.Contains(s.StartRange) {
return fmt.Errorf("%s does not contain %s", s.CIDR, s.StartRange)
}
if s.EndRange == nil {
return errors.New("EndRange cannot be nil")
}
if !s.CIDR.Contains(s.EndRange) {
return fmt.Errorf("%s does not contain %s", s.CIDR, s.EndRange)
}
if bytes.Compare(s.StartRange, s.EndRange) > 0 {
return errors.New("EndRange cannot be less than StartRange")
}
return nil
}
// Save persists the subnet to the datastore.
func (s *Subnet) Save() error {
if err := s.Validate(); err != nil {
return err
}
v, err := json.Marshal(s)
if err != nil {
return err
}
index, err := s.context.kv.Update(s.key(), kv.Value{Data: v, Index: s.modifiedIndex})
if err != nil {
return err
}
s.modifiedIndex = index
return nil
}
func (s *Subnet) addressKey(address string) string {
return filepath.Join(SubnetPath, s.ID, "addresses", address)
}
// Addresses returns used IP addresses.
func (s *Subnet) Addresses() map[string]string {
addresses := make(map[string]string)
start := ipToI32(s.StartRange)
end := ipToI32(s.EndRange)
// this is a horrible way to do this. should this be simple set math?
for i := start; i <= end; i++ {
if id, ok := s.addresses[i]; ok {
ip := i32ToIP(i)
addresses[ip.String()] = id
}
}
return addresses
}
// based on https://github.com/ziutek/utils/
func ipToI32(ip net.IP) uint32 {
ip = ip.To4()
return uint32(ip[0])<<24 | uint32(ip[1])<<16 | uint32(ip[2])<<8 | uint32(ip[3])
}
func i32ToIP(a uint32) net.IP {
return net.IPv4(byte(a>>24), byte(a>>16), byte(a>>8), byte(a))
}
// AvailableAddresses returns the available ip addresses.
// this is probably a horrible idea for ipv6.
func (s *Subnet) AvailableAddresses() []net.IP {
addresses := make([]net.IP, 0, 0)
start := ipToI32(s.StartRange)
end := ipToI32(s.EndRange)
// this is a horrible way to do this. should this be simple set math?
for i := start; i <= end; i++ {
if _, ok := s.addresses[i]; !ok {
addresses = append(addresses, i32ToIP(i))
}
}
return addresses
}
func randomizeAddresses(a []net.IP) []net.IP {
for i := range a {
j := rand.Intn(i + 1)
a[i], a[j] = a[j], a[i]
}
return a
}
// ReserveAddress reserves an ip address. The id is a guest id.
func (s *Subnet) ReserveAddress(id string) (net.IP, error) {
// hacky...
//should this lock?? or do we assume lock is held?
avail := s.AvailableAddresses()
if len(avail) == 0 {
return nil, errors.New("no available addresses")
}
avail = randomizeAddresses(avail)
var chosen net.IP
for _, ip := range avail {
v := ip.String()
if _, err := s.context.kv.Update(s.addressKey(v), kv.Value{Data: []byte(id)}); err == nil {
chosen = ip
s.addresses[ipToI32(ip)] = id
break
}
}
// what if nothing was chosen?
return chosen, nil
}
// ReleaseAddress releases an address.
// This does not change any thing that may also be referring to this address.
func (s *Subnet) ReleaseAddress(ip net.IP) error {
if err := s.context.kv.Delete(s.addressKey(ip.String()), false); err != nil {
return err
}
delete(s.addresses, ipToI32(ip))
return nil
}
// ForEachSubnet will run f on each Subnet. It will stop iteration if f returns an error.
func (c *Context) ForEachSubnet(f func(*Subnet) error) error {
keys, err := c.kv.Keys(SubnetPath)
if err != nil {
return err
}
for _, k := range keys {
s, err := c.Subnet(filepath.Base(k))
if err != nil {
return err
}
if err := f(s); err != nil {
return err
}
}
return nil
}