forked from juju/juju
/
devices.go
634 lines (579 loc) · 21 KB
/
devices.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package maas
import (
"encoding/json"
"fmt"
"net/url"
"path"
"strconv"
"strings"
"github.com/juju/errors"
"github.com/juju/gomaasapi/v2"
"github.com/DavinZhang/juju/core/instance"
corenetwork "github.com/DavinZhang/juju/core/network"
)
// TODO(dimitern): The types below should be part of gomaasapi.
// LKK Card: https://canonical.leankit.com/Boards/View/101652562/119310616
type maasZone struct {
Name string `json:"name"`
Description string `json:"description"`
ResourceURI string `json:"resource_uri"`
}
type maasMACAddress struct {
MACAddress string `json:"mac_address"`
}
type maasDevice struct {
SystemID string `json:"system_id"`
Parent string `json:"parent"`
Hostname string `json:"hostname"`
IPAddresses []string `json:"ip_addresses"`
Owner string `json:"owner"`
Zone maasZone `json:"zone"`
MACAddressSet []maasMACAddress `json:"macaddress_set"`
TagNames []string `json:"tag_names"`
ResourceURI string `json:"resource_uri"`
}
func parseDevice(jsonBytes []byte) (*maasDevice, error) {
var device maasDevice
if err := json.Unmarshal(jsonBytes, &device); err != nil {
return nil, errors.Annotate(err, "parsing device")
}
return &device, nil
}
func getJSONBytes(object json.Marshaler) ([]byte, error) {
rawBytes, err := object.MarshalJSON()
if err != nil {
return nil, errors.Annotate(err, "cannot get JSON bytes")
}
return rawBytes, nil
}
func (env *maasEnviron) createDevice(hostInstanceID instance.Id, hostname string, primaryMACAddress string) (*maasDevice, error) {
devicesAPI := env.getMAASClient().GetSubObject("devices")
params := make(url.Values)
params.Add("hostname", hostname)
params.Add("parent", extractSystemId(hostInstanceID))
params.Add("mac_addresses", primaryMACAddress)
result, err := devicesAPI.CallPost("new", params)
if err != nil {
return nil, errors.Trace(err)
}
deviceJSON, err := getJSONBytes(result)
if err != nil {
return nil, errors.Trace(err)
}
device, err := parseDevice(deviceJSON)
if err != nil {
return nil, errors.Trace(err)
}
logger.Debugf("created device: %+v", device)
return device, nil
}
func parseInterface(jsonBytes []byte) (*maasInterface, error) {
var iface maasInterface
if err := json.Unmarshal(jsonBytes, &iface); err != nil {
return nil, errors.Annotate(err, "parsing interface")
}
return &iface, nil
}
func (env *maasEnviron) createDeviceInterface(deviceID instance.Id, name, macAddress, vlanID string) (*maasInterface, error) {
deviceSystemID := extractSystemId(deviceID)
uri := path.Join("nodes", deviceSystemID, "interfaces")
interfacesAPI := env.getMAASClient().GetSubObject(uri)
params := make(url.Values)
params.Add("name", name)
params.Add("mac_address", macAddress)
params.Add("vlan", vlanID)
result, err := interfacesAPI.CallPost("create_physical", params)
if err != nil {
return nil, errors.Trace(err)
}
interfaceJSON, err := getJSONBytes(result)
if err != nil {
return nil, errors.Trace(err)
}
iface, err := parseInterface(interfaceJSON)
if err != nil {
return nil, errors.Trace(err)
}
return iface, nil
}
func (env *maasEnviron) updateDeviceInterface(deviceID instance.Id, interfaceID, name, macAddress, vlanID string) (*maasInterface, error) {
deviceSystemID := extractSystemId(deviceID)
uri := path.Join("nodes", deviceSystemID, "interfaces", interfaceID)
interfacesAPI := env.getMAASClient().GetSubObject(uri)
params := make(url.Values)
params.Add("name", name)
params.Add("mac_address", macAddress)
params.Add("vlan", vlanID)
result, err := interfacesAPI.Update(params)
if err != nil {
return nil, errors.Trace(err)
}
interfaceJSON, err := getJSONBytes(result)
if err != nil {
return nil, errors.Trace(err)
}
iface, err := parseInterface(interfaceJSON)
if err != nil {
return nil, errors.Trace(err)
}
return iface, nil
}
func (env *maasEnviron) linkDeviceInterfaceToSubnet(deviceID instance.Id, interfaceID, subnetID string, mode maasLinkMode) (*maasInterface, error) {
deviceSystemID := extractSystemId(deviceID)
uri := path.Join("nodes", deviceSystemID, "interfaces", interfaceID)
interfacesAPI := env.getMAASClient().GetSubObject(uri)
params := make(url.Values)
params.Add("mode", string(mode))
params.Add("subnet", subnetID)
result, err := interfacesAPI.CallPost("link_subnet", params)
if err != nil {
return nil, errors.Trace(err)
}
interfaceJSON, err := getJSONBytes(result)
if err != nil {
return nil, errors.Trace(err)
}
iface, err := parseInterface(interfaceJSON)
if err != nil {
return nil, errors.Trace(err)
}
return iface, nil
}
func (env *maasEnviron) deviceInterfaces(deviceID instance.Id) ([]maasInterface, error) {
deviceSystemID := extractSystemId(deviceID)
uri := path.Join("nodes", deviceSystemID, "interfaces")
interfacesAPI := env.getMAASClient().GetSubObject(uri)
result, err := interfacesAPI.CallGet("", nil)
if err != nil {
return nil, errors.Trace(err)
}
interfacesJSON, err := getJSONBytes(result)
if err != nil {
return nil, errors.Trace(err)
}
interfaces, err := parseInterfaces(interfacesJSON)
if err != nil {
return nil, errors.Trace(err)
}
logger.Debugf("device %q interfaces: %+v", deviceSystemID, interfaces)
return interfaces, nil
}
func (env *maasEnviron) deviceInterfaceInfo(deviceID instance.Id, nameToParentName map[string]string) (corenetwork.InterfaceInfos, error) {
interfaces, err := env.deviceInterfaces(deviceID)
if err != nil {
return nil, errors.Trace(err)
}
interfaceInfo := make(corenetwork.InterfaceInfos, 0, len(interfaces))
for _, nic := range interfaces {
nicInfo := corenetwork.InterfaceInfo{
InterfaceName: nic.Name,
InterfaceType: corenetwork.EthernetDevice,
MACAddress: nic.MACAddress,
MTU: nic.EffectveMTU,
VLANTag: nic.VLAN.VID,
ProviderId: corenetwork.Id(strconv.Itoa(nic.ID)),
ProviderVLANId: corenetwork.Id(strconv.Itoa(nic.VLAN.ID)),
Disabled: !nic.Enabled,
NoAutoStart: !nic.Enabled,
ParentInterfaceName: nameToParentName[nic.Name],
Origin: corenetwork.OriginProvider,
}
if len(nic.Links) == 0 {
logger.Debugf("device %q interface %q has no links", deviceID, nic.Name)
interfaceInfo = append(interfaceInfo, nicInfo)
continue
}
for _, link := range nic.Links {
configType := maasLinkToInterfaceConfigType(string(link.Mode))
if link.IPAddress == "" {
logger.Debugf("device %q interface %q has no address", deviceID, nic.Name)
interfaceInfo = append(interfaceInfo, nicInfo)
continue
}
if link.Subnet == nil {
logger.Debugf("device %q interface %q link %d missing subnet", deviceID, nic.Name, link.ID)
interfaceInfo = append(interfaceInfo, nicInfo)
continue
}
// NOTE(achilleasa): this bit of code preserves the
// long-standing last-write-wins behavior that was
// present in the original code. Do we need to revisit
// this in the future and append link addresses to the list?
nicInfo.Addresses = corenetwork.ProviderAddresses{corenetwork.NewProviderAddressInSpace(
link.Subnet.Space,
link.IPAddress,
corenetwork.WithCIDR(link.Subnet.CIDR),
corenetwork.WithConfigType(configType),
)}
nicInfo.ProviderSubnetId = corenetwork.Id(strconv.Itoa(link.Subnet.ID))
nicInfo.ProviderAddressId = corenetwork.Id(strconv.Itoa(link.ID))
if link.Subnet.GatewayIP != "" {
nicInfo.GatewayAddress = corenetwork.NewProviderAddressInSpace(link.Subnet.Space, link.Subnet.GatewayIP)
}
if len(link.Subnet.DNSServers) > 0 {
nicInfo.DNSServers = corenetwork.NewProviderAddressesInSpace(
link.Subnet.Space, link.Subnet.DNSServers...)
}
interfaceInfo = append(interfaceInfo, nicInfo)
}
}
logger.Debugf("device %q has interface info: %+v", deviceID, interfaceInfo)
return interfaceInfo, nil
}
func (env *maasEnviron) deviceInterfaceInfo2(
device gomaasapi.Device,
nameToParentName map[string]string,
subnetToStaticRoutes map[string][]gomaasapi.StaticRoute,
) (corenetwork.InterfaceInfos, error) {
deviceID := device.SystemID()
interfaces := device.InterfaceSet()
interfaceInfo := make(corenetwork.InterfaceInfos, 0, len(interfaces))
for idx, nic := range interfaces {
vlanId := 0
vlanVid := 0
vlan := nic.VLAN()
if vlan != nil {
vlanId = vlan.ID()
vlanVid = vlan.VID()
}
nicInfo := corenetwork.InterfaceInfo{
DeviceIndex: idx,
InterfaceName: nic.Name(),
InterfaceType: corenetwork.EthernetDevice,
MACAddress: nic.MACAddress(),
MTU: nic.EffectiveMTU(),
VLANTag: vlanVid,
ProviderId: corenetwork.Id(strconv.Itoa(nic.ID())),
ProviderVLANId: corenetwork.Id(strconv.Itoa(vlanId)),
Disabled: !nic.Enabled(),
NoAutoStart: !nic.Enabled(),
ParentInterfaceName: nameToParentName[nic.Name()],
Origin: corenetwork.OriginProvider,
}
for _, link := range nic.Links() {
subnet := link.Subnet()
if subnet == nil {
continue
}
routes := subnetToStaticRoutes[subnet.CIDR()]
for _, route := range routes {
nicInfo.Routes = append(nicInfo.Routes, corenetwork.Route{
DestinationCIDR: route.Destination().CIDR(),
GatewayIP: route.GatewayIP(),
Metric: route.Metric(),
})
}
}
if len(nic.Links()) == 0 {
logger.Debugf("device %q interface %q has no links", deviceID, nic.Name())
interfaceInfo = append(interfaceInfo, nicInfo)
continue
}
for _, link := range nic.Links() {
configType := maasLinkToInterfaceConfigType(link.Mode())
subnet := link.Subnet()
if link.IPAddress() == "" || subnet == nil {
logger.Debugf("device %q interface %q has no address", deviceID, nic.Name())
interfaceInfo = append(interfaceInfo, nicInfo)
continue
}
// 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.NewProviderAddressInSpace(
subnet.Space(),
link.IPAddress(),
corenetwork.WithCIDR(subnet.CIDR()),
corenetwork.WithConfigType(configType),
)}
nicInfo.ProviderSubnetId = corenetwork.Id(strconv.Itoa(subnet.ID()))
nicInfo.ProviderAddressId = corenetwork.Id(strconv.Itoa(link.ID()))
if subnet.Gateway() != "" {
nicInfo.GatewayAddress = corenetwork.NewProviderAddressInSpace(subnet.Space(), subnet.Gateway())
}
if len(subnet.DNSServers()) > 0 {
nicInfo.DNSServers = corenetwork.NewProviderAddressesInSpace(subnet.Space(), subnet.DNSServers()...)
}
interfaceInfo = append(interfaceInfo, nicInfo)
}
}
logger.Debugf("device %q has interface info: %+v", deviceID, interfaceInfo)
return interfaceInfo, nil
}
type deviceCreatorParams struct {
Name string
Subnet gomaasapi.Subnet // may be nil
PrimaryMACAddress string
PrimaryNICName string
DesiredInterfaceInfo corenetwork.InterfaceInfos
CIDRToMAASSubnet map[string]gomaasapi.Subnet
CIDRToStaticRoutes map[string][]gomaasapi.StaticRoute
Machine gomaasapi.Machine
}
func (env *maasEnviron) createAndPopulateDevice(params deviceCreatorParams) (gomaasapi.Device, error) {
createDeviceArgs := gomaasapi.CreateMachineDeviceArgs{
Hostname: params.Name,
MACAddress: params.PrimaryMACAddress,
Subnet: params.Subnet, // can be nil
InterfaceName: params.PrimaryNICName,
}
device, err := params.Machine.CreateDevice(createDeviceArgs)
if err != nil {
return nil, errors.Trace(err)
}
defer func() {
if err != nil {
_ = device.Delete()
}
}()
interfaces := device.InterfaceSet()
if len(interfaces) != 1 {
// Shouldn't be possible as machine.CreateDevice always
// returns a device with one interface.
names := make([]string, len(interfaces))
for i, iface := range interfaces {
names[i] = iface.Name()
}
err = errors.Errorf("unexpected number of interfaces "+
"in response from creating device: %v", names)
return nil, err
}
primaryNIC := interfaces[0]
primaryNICVLAN := primaryNIC.VLAN()
interfaceCreated := false
// Populate the rest of the desired interfaces on this device
for _, nic := range params.DesiredInterfaceInfo {
if nic.InterfaceName == params.PrimaryNICName {
// already handled in CreateDevice
continue
}
// We have to register an extra interface for this container
// (aka 'device'), and then link that device to the desired
// subnet so that it can acquire an IP address from MAAS.
createArgs := gomaasapi.CreateInterfaceArgs{
Name: nic.InterfaceName,
MTU: nic.MTU,
MACAddress: nic.MACAddress,
}
subnet, knownSubnet := params.CIDRToMAASSubnet[nic.PrimaryAddress().CIDR]
if !knownSubnet {
logger.Warningf("NIC %v has no subnet - setting to manual and using 'primaryNIC' VLAN %d", nic.InterfaceName, primaryNICVLAN.ID())
createArgs.VLAN = primaryNICVLAN
} else {
createArgs.VLAN = subnet.VLAN()
logger.Infof("linking NIC %v to subnet %v - using static IP", nic.InterfaceName, subnet.CIDR())
}
createdNIC, err := device.CreateInterface(createArgs)
if err != nil {
return nil, errors.Annotate(err, "creating device interface")
}
logger.Debugf("created device interface: %+v", createdNIC)
interfaceCreated = true
if !knownSubnet {
// If we didn't request an explicit subnet, then we
// don't need to link the device to that subnet
continue
}
linkArgs := gomaasapi.LinkSubnetArgs{
Mode: gomaasapi.LinkModeStatic,
Subnet: subnet,
}
if err := createdNIC.LinkSubnet(linkArgs); err != nil {
return nil, errors.Annotatef(err, "linking NIC %v to subnet %v", nic.InterfaceName, subnet.CIDR())
}
logger.Debugf("linked device interface to subnet: %+v", createdNIC)
}
// If we have created any secondary interfaces we need to reload device from maas
// so that the changes are reflected in structure.
if interfaceCreated {
deviceID := device.SystemID()
args := gomaasapi.DevicesArgs{SystemIDs: []string{deviceID}}
devices, err := env.maasController.Devices(args)
if err != nil {
return nil, errors.Trace(err)
}
if len(devices) != 1 {
err = errors.Errorf("unexpected response requesting device %v: %v", deviceID, devices)
return nil, err
}
device = devices[0]
}
return device, nil
}
func (env *maasEnviron) lookupSubnets() (map[string]gomaasapi.Subnet, error) {
subnetCIDRToSubnet := make(map[string]gomaasapi.Subnet)
spaces, err := env.maasController.Spaces()
if err != nil {
return nil, errors.Trace(err)
}
for _, space := range spaces {
for _, subnet := range space.Subnets() {
subnetCIDRToSubnet[subnet.CIDR()] = subnet
}
}
return subnetCIDRToSubnet, nil
}
func (env *maasEnviron) lookupStaticRoutes() (map[string][]gomaasapi.StaticRoute, error) {
// map from the source subnet (what subnet is the device in), to what
// static routes should be used.
subnetToStaticRoutes := make(map[string][]gomaasapi.StaticRoute)
staticRoutes, err := env.maasController.StaticRoutes()
if err != nil {
// MAAS 2.0 does not support static-routes, and will return a 404. MAAS
// does not report support for static-routes in its capabilities, nor
// does it have a different API version between 2.1 and 2.0. So we make
// the attempt, and treat a 404 as not having any configured static
// routes.
// gomaaasapi wraps a ServerError in an UnexpectedError, so we need to
// dig to make sure we have the right cause:
handled := false
if gomaasapi.IsUnexpectedError(err) {
msg := err.Error()
if strings.Contains(msg, "404") &&
strings.Contains(msg, "Unknown API endpoint:") &&
strings.Contains(msg, "/static-routes/") {
logger.Debugf("static-routes not supported: %v", err)
handled = true
staticRoutes = nil
} else {
logger.Warningf("looking up static routes generated IsUnexpectedError, but didn't match: %q %#v", msg, err)
}
} else {
logger.Warningf("not IsUnexpectedError: %#v", err)
}
if !handled {
logger.Warningf("error looking up static-routes: %v", err)
return nil, errors.Annotate(err, "unable to look up static-routes")
}
}
for _, route := range staticRoutes {
source := route.Source()
sourceCIDR := source.CIDR()
subnetToStaticRoutes[sourceCIDR] = append(subnetToStaticRoutes[sourceCIDR], route)
}
logger.Debugf("found static routes: %# v", subnetToStaticRoutes)
return subnetToStaticRoutes, nil
}
func (env *maasEnviron) prepareDeviceDetails(name string, machine gomaasapi.Machine, preparedInfo corenetwork.InterfaceInfos) (deviceCreatorParams, error) {
var zeroParams deviceCreatorParams
subnetCIDRToSubnet, err := env.lookupSubnets()
if err != nil {
return zeroParams, errors.Trace(err)
}
subnetToStaticRoutes, err := env.lookupStaticRoutes()
if err != nil {
return zeroParams, errors.Trace(err)
}
params := deviceCreatorParams{
// Containers always use 'eth0' as their primary NIC
// XXX(jam) 2017-04-13: Except we *don't* do that for KVM containers running Xenial
Name: name,
Machine: machine,
PrimaryNICName: "eth0",
DesiredInterfaceInfo: preparedInfo,
CIDRToMAASSubnet: subnetCIDRToSubnet,
CIDRToStaticRoutes: subnetToStaticRoutes,
}
var primaryNICInfo corenetwork.InterfaceInfo
for _, nic := range preparedInfo {
if nic.InterfaceName == params.PrimaryNICName {
primaryNICInfo = nic
break
}
}
if primaryNICInfo.InterfaceName == "" {
return zeroParams, errors.Errorf("cannot find primary interface for container")
}
logger.Debugf("primary device NIC prepared info: %+v", primaryNICInfo)
primaryNICSubnetCIDR := primaryNICInfo.PrimaryAddress().CIDR
subnet, hasSubnet := subnetCIDRToSubnet[primaryNICSubnetCIDR]
if hasSubnet {
params.Subnet = subnet
} else {
logger.Debugf("primary device NIC %q has no linked subnet - leaving unconfigured", primaryNICInfo.InterfaceName)
}
params.PrimaryMACAddress = primaryNICInfo.MACAddress
return params, nil
}
func validateExistingDevice(netInfo corenetwork.InterfaceInfos, device gomaasapi.Device) (bool, error) {
// Compare the desired device characteristics with the actual device
interfaces := device.InterfaceSet()
if len(interfaces) < len(netInfo) {
logger.Debugf("existing device doesn't have enough interfaces, wanted %d, found %d", len(netInfo), len(interfaces))
return false, nil
}
actualByMAC := make(map[string]gomaasapi.Interface, len(interfaces))
for _, iface := range interfaces {
actualByMAC[iface.MACAddress()] = iface
}
for _, desired := range netInfo {
actual, ok := actualByMAC[desired.MACAddress]
if !ok {
foundMACs := make([]string, 0, len(actualByMAC))
for _, iface := range interfaces {
foundMACs = append(foundMACs, fmt.Sprintf("%s: %s", iface.Name(), iface.MACAddress()))
}
found := strings.Join(foundMACs, ", ")
logger.Debugf("existing device doesn't have device for MAC Address %q, found: %s", desired.MACAddress, found)
// No such network interface
return false, nil
}
// TODO: we should have a way to know what space we are targeting, rather than a desired subnet CIDR
foundCIDR := false
for _, link := range actual.Links() {
subnet := link.Subnet()
if subnet != nil {
cidr := subnet.CIDR()
if cidr == desired.PrimaryAddress().CIDR {
foundCIDR = true
}
}
}
if !foundCIDR {
logger.Debugf("could not find Subnet link for CIDR: %q", desired.PrimaryAddress().CIDR)
return false, nil
}
}
return true, nil
}
// checkForExistingDevice checks to see if we've already registered a device
// with this name, and if its information is appropriately populated. If we
// have, then we just return the existing interface info. If we find it, but
// it doesn't match, then we ask MAAS to remove it, which should cause the
// calling code to create it again.
func (env *maasEnviron) checkForExistingDevice(params deviceCreatorParams) (gomaasapi.Device, error) {
devicesArgs := gomaasapi.DevicesArgs{
Hostname: []string{params.Name},
}
maybeDevices, err := params.Machine.Devices(devicesArgs)
if err != nil {
logger.Warningf("error while trying to lookup %q: %v", params.Name, err)
// not considered fatal, since we'll attempt to create the device if we didn't find it
return nil, nil
}
if len(maybeDevices) == 0 {
logger.Debugf("no existing MAAS devices for container %q, creating", params.Name)
return nil, nil
}
if len(maybeDevices) > 1 {
logger.Warningf("found more than 1 MAAS devices (%d) for container %q", len(maybeDevices),
params.Name)
return nil, errors.Errorf("found more than 1 MAAS device (%d) for container %q",
len(maybeDevices), params.Name)
}
device := maybeDevices[0]
// Now validate that this device has the right interfaces
matches, err := validateExistingDevice(params.DesiredInterfaceInfo, device)
if err != nil {
return nil, err
}
if matches {
logger.Debugf("found MAAS device for container %q using existing device", params.Name)
return device, nil
}
logger.Debugf("found existing MAAS device for container %q but interfaces did not match, removing device", params.Name)
// We found a device, but it doesn't match what we need. remove it and we'll create again.
_ = device.Delete()
return nil, nil
}