forked from juju/juju
/
linklayerdevices_ipaddresses.go
354 lines (291 loc) · 10.6 KB
/
linklayerdevices_ipaddresses.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
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"fmt"
"github.com/juju/errors"
"gopkg.in/mgo.v2/bson"
"gopkg.in/mgo.v2/txn"
"github.com/juju/juju/network"
)
// ipAddressDoc describes the persistent state of an IP address assigned to a
// link-layer network device (a.k.a network interface card - NIC).
type ipAddressDoc struct {
// DocID is the IP address global key, prefixed by ModelUUID.
DocID string `bson:"_id"`
// ModelUUID is the UUID of the model this IP address belongs to.
ModelUUID string `bson:"model-uuid"`
// ProviderID is a provider-specific ID of the IP address, prefixed by
// ModelUUID. Empty when not supported by the provider.
ProviderID string `bson:"providerid,omitempty"`
// DeviceName is the name of the link-layer device this IP address is
// assigned to.
DeviceName string `bson:"device-name"`
// MachineID is the ID of the machine this IP address's device belongs to.
MachineID string `bson:"machine-id"`
// SubnetCIDR is the CIDR of the subnet this IP address belongs to. The CIDR
// will either match a known provider subnet or a machine-local subnet (like
// 10.0.3.0/24 or 127.0.0.0/8).
SubnetCIDR string `bson:"subnet-cidr"`
// ConfigMethod is the method used to configure this IP address.
ConfigMethod AddressConfigMethod `bson:"config-method"`
// Value is the value of the configured IP address, e.g. 192.168.1.2 or
// 2001:db8::/64.
Value string `bson:"value"`
// DNSServers contains a list of DNS nameservers that apply to this IP
// address's device. Can be empty.
DNSServers []string `bson:"dns-servers,omitempty"`
// DNSSearchDomains contains a list of DNS domain names used to qualify
// hostnames, and can be empty.
DNSSearchDomains []string `bson:"dns-search-domains,omitempty"`
// GatewayAddress is the IP address of the gateway this IP address's device
// uses. Can be empty.
GatewayAddress string `bson:"gateway-address,omitempty"`
}
// AddressConfigMethod is the method used to configure a link-layer device's IP
// address.
type AddressConfigMethod string
const (
// LoopbackAddress is used for IP addresses of LoopbackDevice types.
LoopbackAddress AddressConfigMethod = "loopback"
// StaticAddress is used for statically configured addresses.
StaticAddress AddressConfigMethod = "static"
// DynamicAddress is used for addresses dynamically configured via DHCP.
DynamicAddress AddressConfigMethod = "dynamic"
// ManualAddress is used for manually configured addresses.
ManualAddress AddressConfigMethod = "manual"
)
// IsValidAddressConfigMethod returns whether the given value is a valid method
// to configure a link-layer network device's IP address.
func IsValidAddressConfigMethod(value string) bool {
switch AddressConfigMethod(value) {
case LoopbackAddress, StaticAddress, DynamicAddress, ManualAddress:
return true
}
return false
}
// Address represents the state of an IP address assigned to a link-layer
// network device on a machine.
type Address struct {
st *State
doc ipAddressDoc
}
func newIPAddress(st *State, doc ipAddressDoc) *Address {
return &Address{st: st, doc: doc}
}
// NetworkAddress returns the address transformed to a network.Address.
func (addr *Address) NetworkAddress() network.Address {
return network.NewAddress(addr.Value())
}
// DocID returns the globally unique ID of the IP address, including the model
// UUID as prefix.
func (addr *Address) DocID() string {
return addr.st.docID(addr.doc.DocID)
}
// ProviderID returns the provider-specific IP address ID, if set.
func (addr *Address) ProviderID() network.Id {
return network.Id(addr.doc.ProviderID)
}
// MachineID returns the ID of the machine this IP address belongs to.
func (addr *Address) MachineID() string {
return addr.doc.MachineID
}
// Machine returns the Machine this IP address belongs to.
func (addr *Address) Machine() (*Machine, error) {
return addr.st.Machine(addr.doc.MachineID)
}
// machineProxy is a convenience wrapper for calling Machine methods from an
// *Address.
func (addr *Address) machineProxy() *Machine {
return &Machine{st: addr.st, doc: machineDoc{Id: addr.doc.MachineID}}
}
// DeviceName returns the name of the link-layer device this IP address is
// assigned to.
func (addr *Address) DeviceName() string {
return addr.doc.DeviceName
}
// Device returns the LinkLayeyDevice this IP address is assigned to.
func (addr *Address) Device() (*LinkLayerDevice, error) {
return addr.machineProxy().LinkLayerDevice(addr.doc.DeviceName)
}
// SubnetCIDR returns the CIDR of the subnet this IP address comes from.
func (addr *Address) SubnetCIDR() string {
return addr.doc.SubnetCIDR
}
// Subnet returns the Subnet this IP address comes from. Returns nil and
// errors.NotFoundError if the address comes from an unknown subnet (i.e.
// machine-local one).
func (addr *Address) Subnet() (*Subnet, error) {
return addr.st.Subnet(addr.doc.SubnetCIDR)
}
// ConfigMethod returns the AddressConfigMethod used for this IP address.
func (addr *Address) ConfigMethod() AddressConfigMethod {
return addr.doc.ConfigMethod
}
// LoopbackConfigMethod returns whether AddressConfigMethod used for this IP
// address was loopback.
func (addr *Address) LoopbackConfigMethod() bool {
return addr.doc.ConfigMethod == LoopbackAddress
}
// Value returns the value of this IP address.
func (addr *Address) Value() string {
return addr.doc.Value
}
// DNSServers returns the list of DNS nameservers to use, which can be empty.
func (addr *Address) DNSServers() []string {
return addr.doc.DNSServers
}
// DNSSearchDomains returns the list of DNS domains to use for qualifying
// hostnames. Can be empty.
func (addr *Address) DNSSearchDomains() []string {
return addr.doc.DNSSearchDomains
}
// GatewayAddress returns the gateway address to use, which can be empty.
func (addr *Address) GatewayAddress() string {
return addr.doc.GatewayAddress
}
// String returns a human-readable representation of the IP address.
func (addr *Address) String() string {
return fmt.Sprintf(
"%s address %q of device %q on machine %q",
addr.doc.ConfigMethod, addr.doc.Value,
addr.doc.DeviceName, addr.doc.MachineID,
)
}
func (addr *Address) globalKey() string {
return ipAddressGlobalKey(addr.doc.MachineID, addr.doc.DeviceName, addr.doc.Value)
}
func ipAddressGlobalKey(machineID, deviceName, address string) string {
deviceGlobalKey := linkLayerDeviceGlobalKey(machineID, deviceName)
if deviceGlobalKey == "" || address == "" {
return ""
}
return deviceGlobalKey + "#ip#" + address
}
// Remove removes the IP address, if it exists. No error is returned when the
// address was already removed.
func (addr *Address) Remove() (err error) {
defer errors.DeferredAnnotatef(&err, "cannot remove %s", addr)
removeOp := removeIPAddressDocOp(addr.doc.DocID)
ops := []txn.Op{removeOp}
if addr.ProviderID() != "" {
op := addr.st.networkEntityGlobalKeyRemoveOp("address", addr.ProviderID())
ops = append(ops, op)
}
return addr.st.runTransaction(ops)
}
// removeIPAddressDocOpOp returns an operation to remove the ipAddressDoc
// matching the given ipAddressDocID, without asserting it still exists.
func removeIPAddressDocOp(ipAddressDocID string) txn.Op {
return txn.Op{
C: ipAddressesC,
Id: ipAddressDocID,
Remove: true,
}
}
// insertIPAddressDocOp returns an operation inserting the given newDoc,
// asserting it does not exist yet.
func insertIPAddressDocOp(newDoc *ipAddressDoc) txn.Op {
return txn.Op{
C: ipAddressesC,
Id: newDoc.DocID,
Assert: txn.DocMissing,
Insert: *newDoc,
}
}
// updateIPAddressDocOp returns an operation updating the fields of existingDoc
// with the respective values of those fields in newDoc. DocID, ModelUUID,
// Value, MachineID, and DeviceName cannot be changed. ProviderID cannot be
// changed once set. DNSServers and DNSSearchDomains are deleted when nil. In
// all other cases newDoc values overwrites existingDoc values.
func updateIPAddressDocOp(existingDoc, newDoc *ipAddressDoc) txn.Op {
changes := make(bson.M)
deletes := make(bson.M)
if existingDoc.ProviderID == "" && newDoc.ProviderID != "" {
// Only allow changing the ProviderID if it was empty.
changes["providerid"] = newDoc.ProviderID
}
if existingDoc.ConfigMethod != newDoc.ConfigMethod {
changes["config-method"] = newDoc.ConfigMethod
}
if existingDoc.SubnetCIDR != newDoc.SubnetCIDR {
changes["subnet-cidr"] = newDoc.SubnetCIDR
}
if newDoc.DNSServers == nil {
deletes["dns-servers"] = 1
} else {
changes["dns-servers"] = newDoc.DNSServers
}
if newDoc.DNSSearchDomains == nil {
deletes["dns-search-domains"] = 1
} else {
changes["dns-search-domains"] = newDoc.DNSSearchDomains
}
if existingDoc.GatewayAddress != newDoc.GatewayAddress {
changes["gateway-address"] = newDoc.GatewayAddress
}
var updates bson.D
if len(changes) > 0 {
updates = append(updates, bson.DocElem{Name: "$set", Value: changes})
}
if len(deletes) > 0 {
updates = append(updates, bson.DocElem{Name: "$unset", Value: deletes})
}
return txn.Op{
C: ipAddressesC,
Id: existingDoc.DocID,
Assert: txn.DocExists,
Update: updates,
}
}
func findAddressesQuery(machineID, deviceName string) bson.D {
var query bson.D
if machineID != "" {
query = append(query, bson.DocElem{Name: "machine-id", Value: machineID})
}
if deviceName != "" {
query = append(query, bson.DocElem{Name: "device-name", Value: deviceName})
}
return query
}
func (st *State) removeMatchingIPAddressesDocOps(findQuery bson.D) ([]txn.Op, error) {
var ops []txn.Op
callbackFunc := func(resultDoc *ipAddressDoc) {
ops = append(ops, removeIPAddressDocOp(resultDoc.DocID))
if resultDoc.ProviderID != "" {
addrID := network.Id(resultDoc.ProviderID)
op := st.networkEntityGlobalKeyRemoveOp("address", addrID)
ops = append(ops, op)
}
}
err := st.forEachIPAddressDoc(findQuery, callbackFunc)
if err != nil {
return nil, errors.Trace(err)
}
return ops, nil
}
func (st *State) forEachIPAddressDoc(findQuery bson.D, callbackFunc func(resultDoc *ipAddressDoc)) error {
addresses, closer := st.getCollection(ipAddressesC)
defer closer()
query := addresses.Find(findQuery)
iter := query.Iter()
var resultDoc ipAddressDoc
for iter.Next(&resultDoc) {
callbackFunc(&resultDoc)
}
return errors.Trace(iter.Close())
}
// AllIPAddresses returns all ip addresses in the model.
func (st *State) AllIPAddresses() (addresses []*Address, err error) {
addressesCollection, closer := st.getCollection(ipAddressesC)
defer closer()
sdocs := []ipAddressDoc{}
err = addressesCollection.Find(bson.D{}).All(&sdocs)
if err != nil {
return nil, errors.Errorf("cannot get all ip addresses")
}
for _, a := range sdocs {
addresses = append(addresses, newIPAddress(st, a))
}
return addresses, nil
}