/
interfaces.go
302 lines (261 loc) · 9.01 KB
/
interfaces.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package maas
import (
"encoding/json"
"fmt"
"strings"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/juju/core/instance"
corenetwork "github.com/juju/juju/core/network"
"github.com/juju/juju/environs"
"github.com/juju/juju/environs/context"
)
// TODO(dimitern): The types below should be part of gomaasapi.
// LKK Card: https://canonical.leankit.com/Boards/View/101652562/119310616
type maasLinkMode string
const (
modeUnknown maasLinkMode = ""
modeStatic maasLinkMode = "static"
modeDHCP maasLinkMode = "dhcp"
modeLinkUp maasLinkMode = "link_up"
modeAuto maasLinkMode = "auto"
)
type maasInterfaceLink struct {
ID int `json:"id"`
Subnet *maasSubnet `json:"subnet,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
Mode maasLinkMode `json:"mode"`
}
type maasInterfaceType string
const (
typePhysical maasInterfaceType = "physical"
typeVLAN maasInterfaceType = "vlan"
typeBond maasInterfaceType = "bond"
typeBridge maasInterfaceType = "bridge"
)
type maasInterface struct {
ID int `json:"id"`
Name string `json:"name"`
Type maasInterfaceType `json:"type"`
Enabled bool `json:"enabled"`
MACAddress string `json:"mac_address"`
VLAN maasVLAN `json:"vlan"`
EffectveMTU int `json:"effective_mtu"`
Links []maasInterfaceLink `json:"links"`
Parents []string `json:"parents"`
Children []string `json:"children"`
ResourceURI string `json:"resource_uri"`
}
type maasVLAN struct {
ID int `json:"id"`
Name string `json:"name"`
VID int `json:"vid"`
MTU int `json:"mtu"`
Fabric string `json:"fabric"`
ResourceURI string `json:"resource_uri"`
}
type maasSubnet struct {
ID int `json:"id"`
Name string `json:"name"`
Space string `json:"space"`
VLAN maasVLAN `json:"vlan"`
GatewayIP string `json:"gateway_ip"`
DNSServers []string `json:"dns_servers"`
CIDR string `json:"cidr"`
ResourceURI string `json:"resource_uri"`
}
// NetworkInterfaces implements Environ.NetworkInterfaces.
func (env *maasEnviron) NetworkInterfaces(ctx context.ProviderCallContext, ids []instance.Id) ([]corenetwork.InterfaceInfos, error) {
switch len(ids) {
case 0:
return nil, environs.ErrNoInstances
case 1: // short-cut
ifList, err := env.networkInterfacesForInstance(ctx, ids[0])
if err != nil {
return nil, err
}
return []corenetwork.InterfaceInfos{ifList}, nil
}
// Fetch instance information for the IDs we are interested in.
insts, err := env.Instances(ctx, ids)
partialInfo := err == environs.ErrPartialInstances
if err != nil && err != environs.ErrPartialInstances {
if err == environs.ErrNoInstances {
return nil, err
}
return nil, errors.Trace(err)
}
subnetsMap, err := env.subnetToSpaceIds(ctx)
if err != nil {
return nil, errors.Trace(err)
}
infos := make([]corenetwork.InterfaceInfos, len(ids))
dnsSearchDomains, err := env.Domains(ctx)
if err != nil {
return nil, errors.Trace(err)
}
for idx, inst := range insts {
if inst == nil {
continue // unknown instance ID
}
ifList, err := maasNetworkInterfaces(ctx, inst.(*maasInstance), subnetsMap, dnsSearchDomains...)
if err != nil {
return nil, errors.Annotatef(err, "obtaining network interfaces for instance %v", ids[idx])
}
infos[idx] = ifList
}
if partialInfo {
err = environs.ErrPartialInstances
}
return infos, err
}
func (env *maasEnviron) networkInterfacesForInstance(ctx context.ProviderCallContext, instId instance.Id) (corenetwork.InterfaceInfos, error) {
inst, err := env.getInstance(ctx, instId)
if err != nil {
return nil, errors.Trace(err)
}
subnetsMap, err := env.subnetToSpaceIds(ctx)
if err != nil {
return nil, errors.Trace(err)
}
dnsSearchDomains, err := env.Domains(ctx)
if err != nil {
return nil, errors.Trace(err)
}
return maasNetworkInterfaces(ctx, inst.(*maasInstance), subnetsMap, dnsSearchDomains...)
}
func maasNetworkInterfaces(
_ context.ProviderCallContext,
instance *maasInstance,
subnetsMap map[string]corenetwork.Id,
dnsSearchDomains ...string,
) (corenetwork.InterfaceInfos, error) {
interfaces := instance.machine.InterfaceSet()
infos := make(corenetwork.InterfaceInfos, 0, len(interfaces))
bonds := set.NewStrings()
for _, iface := range interfaces {
if maasInterfaceType(iface.Type()) == typeBond {
bonds.Add(iface.Name())
}
}
for i, iface := range interfaces {
// The below works for all types except bonds and their members.
parentName := strings.Join(iface.Parents(), "")
var nicType corenetwork.LinkLayerDeviceType
switch maasInterfaceType(iface.Type()) {
case typePhysical:
nicType = corenetwork.EthernetDevice
children := strings.Join(iface.Children(), "")
if parentName == "" && len(iface.Children()) == 1 && bonds.Contains(children) {
parentName = children
}
case typeBond:
parentName = ""
nicType = corenetwork.BondDevice
case typeVLAN:
nicType = corenetwork.VLAN8021QDevice
case typeBridge:
nicType = corenetwork.BridgeDevice
}
vlanTag := 0
if iface.VLAN() != nil {
vlanTag = iface.VLAN().VID()
}
nicInfo := corenetwork.InterfaceInfo{
DeviceIndex: i,
MACAddress: iface.MACAddress(),
ProviderId: corenetwork.Id(fmt.Sprintf("%v", iface.ID())),
VLANTag: vlanTag,
InterfaceName: iface.Name(),
InterfaceType: nicType,
ParentInterfaceName: parentName,
Disabled: !iface.Enabled(),
NoAutoStart: !iface.Enabled(),
Origin: corenetwork.OriginProvider,
}
if len(iface.Links()) == 0 {
logger.Debugf("interface %q has no links", iface.Name())
infos = append(infos, nicInfo)
continue
}
for _, link := range iface.Links() {
configType := maasLinkToInterfaceConfigType(link.Mode())
if link.IPAddress() == "" && link.Subnet() == nil {
logger.Debugf("interface %q link %d has neither subnet nor address", iface.Name(), link.ID())
infos = append(infos, nicInfo)
} else {
// We set it here initially without a space, just so we don't
// lose it when we have no linked subnet below.
//
// NOTE(achilleasa): the original code used a last-write-wins
// policy. Do we need to append link addresses to the list?
nicInfo.Addresses = corenetwork.ProviderAddresses{
corenetwork.NewMachineAddress(link.IPAddress(), corenetwork.WithConfigType(configType)).AsProviderAddress(),
}
nicInfo.ProviderAddressId = corenetwork.Id(fmt.Sprintf("%v", link.ID()))
}
sub := link.Subnet()
if sub == nil {
logger.Debugf("interface %q link %d missing subnet", iface.Name(), link.ID())
infos = append(infos, nicInfo)
continue
}
nicInfo.ProviderSubnetId = corenetwork.Id(fmt.Sprintf("%v", sub.ID()))
nicInfo.ProviderVLANId = corenetwork.Id(fmt.Sprintf("%v", sub.VLAN().ID()))
// Provider addresses are created with a space name massaged
// to conform to Juju's space name rules.
space := corenetwork.ConvertSpaceName(sub.Space(), nil)
// Now we know the subnet and space, we can update the address to
// store the space with it.
nicInfo.Addresses[0] = corenetwork.NewMachineAddress(
link.IPAddress(), corenetwork.WithCIDR(sub.CIDR()), corenetwork.WithConfigType(configType),
).AsProviderAddress(corenetwork.WithSpaceName(space))
spaceId, ok := subnetsMap[sub.CIDR()]
if !ok {
// The space we found is not recognised.
// No provider space info is available.
logger.Warningf("interface %q link %d has unrecognised space %q", iface.Name(), link.ID(), sub.Space())
} else {
nicInfo.Addresses[0].ProviderSpaceID = spaceId
nicInfo.ProviderSpaceId = spaceId
}
gwAddr := corenetwork.NewMachineAddress(sub.Gateway()).AsProviderAddress(corenetwork.WithSpaceName(space))
nicInfo.DNSServers = corenetwork.NewMachineAddresses(sub.DNSServers()).AsProviderAddresses(corenetwork.WithSpaceName(space))
if ok {
gwAddr.ProviderSpaceID = spaceId
for i := range nicInfo.DNSServers {
nicInfo.DNSServers[i].ProviderSpaceID = spaceId
}
}
nicInfo.DNSSearchDomains = dnsSearchDomains
nicInfo.GatewayAddress = gwAddr
nicInfo.MTU = sub.VLAN().MTU()
// Each link we represent as a separate InterfaceInfo, but with the
// same name and device index, just different address, subnet, etc.
infos = append(infos, nicInfo)
}
}
return infos, nil
}
func parseInterfaces(jsonBytes []byte) ([]maasInterface, error) {
var interfaces []maasInterface
if err := json.Unmarshal(jsonBytes, &interfaces); err != nil {
return nil, errors.Annotate(err, "parsing interfaces")
}
return interfaces, nil
}
func maasLinkToInterfaceConfigType(mode string) corenetwork.AddressConfigType {
switch maasLinkMode(mode) {
case modeUnknown:
return corenetwork.ConfigUnknown
case modeDHCP:
return corenetwork.ConfigDHCP
case modeStatic, modeAuto:
return corenetwork.ConfigStatic
case modeLinkUp:
default:
}
return corenetwork.ConfigManual
}