-
Notifications
You must be signed in to change notification settings - Fork 36
/
machine.go
664 lines (571 loc) · 17.4 KB
/
machine.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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
// Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package gomaasapi
import (
"fmt"
"net/http"
"net/url"
"github.com/juju/errors"
"github.com/juju/schema"
"github.com/juju/version"
)
type machine struct {
controller *controller
resourceURI string
systemID string
hostname string
fqdn string
tags []string
ownerData map[string]string
operatingSystem string
distroSeries string
architecture string
memory int
cpuCount int
hardwareInfo map[string]string
ipAddresses []string
powerState string
// NOTE: consider some form of status struct
statusName string
statusMessage string
bootInterface *interface_
interfaceSet []*interface_
zone *zone
pool *pool
// Don't really know the difference between these two lists:
physicalBlockDevices []*blockdevice
blockDevices []*blockdevice
}
func (m *machine) updateFrom(other *machine) {
m.resourceURI = other.resourceURI
m.systemID = other.systemID
m.hostname = other.hostname
m.fqdn = other.fqdn
m.operatingSystem = other.operatingSystem
m.distroSeries = other.distroSeries
m.architecture = other.architecture
m.memory = other.memory
m.cpuCount = other.cpuCount
m.hardwareInfo = other.hardwareInfo
m.ipAddresses = other.ipAddresses
m.powerState = other.powerState
m.statusName = other.statusName
m.statusMessage = other.statusMessage
m.zone = other.zone
m.pool = other.pool
m.tags = other.tags
m.ownerData = other.ownerData
}
// SystemID implements Machine.
func (m *machine) SystemID() string {
return m.systemID
}
// Hostname implements Machine.
func (m *machine) Hostname() string {
return m.hostname
}
// FQDN implements Machine.
func (m *machine) FQDN() string {
return m.fqdn
}
// Tags implements Machine.
func (m *machine) Tags() []string {
return m.tags
}
// Pool implements Machine
func (m *machine) Pool() Pool {
if m.pool == nil {
return nil
}
return m.pool
}
// IPAddresses implements Machine.
func (m *machine) IPAddresses() []string {
return m.ipAddresses
}
// Memory implements Machine.
func (m *machine) Memory() int {
return m.memory
}
// CPUCount implements Machine.
func (m *machine) CPUCount() int {
return m.cpuCount
}
// HardwareInfo implements Machine.
func (m *machine) HardwareInfo() map[string]string {
if m.hardwareInfo == nil {
return nil
}
info := make(map[string]string, len(m.hardwareInfo))
for k, v := range m.hardwareInfo {
info[k] = v
}
return info
}
// PowerState implements Machine.
func (m *machine) PowerState() string {
return m.powerState
}
// Zone implements Machine.
func (m *machine) Zone() Zone {
if m.zone == nil {
return nil
}
return m.zone
}
// BootInterface implements Machine.
func (m *machine) BootInterface() Interface {
if m.bootInterface == nil {
return nil
}
m.bootInterface.controller = m.controller
return m.bootInterface
}
// InterfaceSet implements Machine.
func (m *machine) InterfaceSet() []Interface {
result := make([]Interface, len(m.interfaceSet))
for i, v := range m.interfaceSet {
v.controller = m.controller
result[i] = v
}
return result
}
// Interface implements Machine.
func (m *machine) Interface(id int) Interface {
for _, iface := range m.interfaceSet {
if iface.ID() == id {
iface.controller = m.controller
return iface
}
}
return nil
}
// OperatingSystem implements Machine.
func (m *machine) OperatingSystem() string {
return m.operatingSystem
}
// DistroSeries implements Machine.
func (m *machine) DistroSeries() string {
return m.distroSeries
}
// Architecture implements Machine.
func (m *machine) Architecture() string {
return m.architecture
}
// StatusName implements Machine.
func (m *machine) StatusName() string {
return m.statusName
}
// StatusMessage implements Machine.
func (m *machine) StatusMessage() string {
return m.statusMessage
}
// PhysicalBlockDevices implements Machine.
func (m *machine) PhysicalBlockDevices() []BlockDevice {
result := make([]BlockDevice, len(m.physicalBlockDevices))
for i, v := range m.physicalBlockDevices {
result[i] = v
}
return result
}
// PhysicalBlockDevice implements Machine.
func (m *machine) PhysicalBlockDevice(id int) BlockDevice {
return blockDeviceById(id, m.PhysicalBlockDevices())
}
// BlockDevices implements Machine.
func (m *machine) BlockDevices() []BlockDevice {
result := make([]BlockDevice, len(m.blockDevices))
for i, v := range m.blockDevices {
result[i] = v
}
return result
}
// BlockDevice implements Machine.
func (m *machine) BlockDevice(id int) BlockDevice {
return blockDeviceById(id, m.BlockDevices())
}
func blockDeviceById(id int, blockDevices []BlockDevice) BlockDevice {
for _, blockDevice := range blockDevices {
if blockDevice.ID() == id {
return blockDevice
}
}
return nil
}
// Partition implements Machine.
func (m *machine) Partition(id int) Partition {
return partitionById(id, m.BlockDevices())
}
func partitionById(id int, blockDevices []BlockDevice) Partition {
for _, blockDevice := range blockDevices {
for _, partition := range blockDevice.Partitions() {
if partition.ID() == id {
return partition
}
}
}
return nil
}
// Devices implements Machine.
func (m *machine) Devices(args DevicesArgs) ([]Device, error) {
// Perhaps in the future, MAAS will give us a way to query just for the
// devices for a particular parent.
devices, err := m.controller.Devices(args)
if err != nil {
return nil, errors.Trace(err)
}
var result []Device
for _, device := range devices {
if device.Parent() == m.SystemID() {
result = append(result, device)
}
}
return result, nil
}
// StartArgs is an argument struct for passing parameters to the Machine.Start
// method.
type StartArgs struct {
// UserData needs to be Base64 encoded user data for cloud-init.
UserData string
DistroSeries string
Kernel string
Comment string
}
// Start implements Machine.
func (m *machine) Start(args StartArgs) error {
params := NewURLParams()
params.MaybeAdd("user_data", args.UserData)
params.MaybeAdd("distro_series", args.DistroSeries)
params.MaybeAdd("hwe_kernel", args.Kernel)
params.MaybeAdd("comment", args.Comment)
result, err := m.controller.post(m.resourceURI, "deploy", params.Values)
if err != nil {
if svrErr, ok := errors.Cause(err).(ServerError); ok {
switch svrErr.StatusCode {
case http.StatusNotFound, http.StatusConflict:
return errors.Wrap(err, NewBadRequestError(svrErr.BodyMessage))
case http.StatusForbidden:
return errors.Wrap(err, NewPermissionError(svrErr.BodyMessage))
case http.StatusServiceUnavailable:
return errors.Wrap(err, NewCannotCompleteError(svrErr.BodyMessage))
}
}
return NewUnexpectedError(err)
}
machine, err := readMachine(m.controller.apiVersion, result)
if err != nil {
return errors.Trace(err)
}
m.updateFrom(machine)
return nil
}
// CreateMachineDeviceArgs is an argument structure for Machine.CreateDevice.
// Only InterfaceName and MACAddress fields are required, the others are only
// used if set. If Subnet and VLAN are both set, Subnet.VLAN() must match the
// given VLAN. On failure, returns an error satisfying errors.IsNotValid().
type CreateMachineDeviceArgs struct {
Hostname string
Domain string
InterfaceName string
MACAddress string
Subnet Subnet
VLAN VLAN
}
// Validate ensures that all required values are non-emtpy.
func (a *CreateMachineDeviceArgs) Validate() error {
if a.InterfaceName == "" {
return errors.NotValidf("missing InterfaceName")
}
if a.MACAddress == "" {
return errors.NotValidf("missing MACAddress")
}
if a.Subnet != nil && a.VLAN != nil && a.Subnet.VLAN() != a.VLAN {
msg := fmt.Sprintf(
"given subnet %q on VLAN %d does not match given VLAN %d",
a.Subnet.CIDR(), a.Subnet.VLAN().ID(), a.VLAN.ID(),
)
return errors.NewNotValid(nil, msg)
}
return nil
}
// CreateDevice implements Machine
func (m *machine) CreateDevice(args CreateMachineDeviceArgs) (_ Device, err error) {
if err := args.Validate(); err != nil {
return nil, errors.Trace(err)
}
device, err := m.controller.CreateDevice(CreateDeviceArgs{
Hostname: args.Hostname,
Domain: args.Domain,
MACAddresses: []string{args.MACAddress},
Parent: m.SystemID(),
})
if err != nil {
return nil, errors.Trace(err)
}
defer func(err *error) {
// If there is an error return, at least try to delete the device we just created.
if *err != nil {
if innerErr := device.Delete(); innerErr != nil {
logger.Warningf("could not delete device %q", device.SystemID())
}
}
}(&err)
// Update the VLAN to use for the interface, if given.
vlanToUse := args.VLAN
if vlanToUse == nil && args.Subnet != nil {
vlanToUse = args.Subnet.VLAN()
}
// There should be one interface created for each MAC Address, and since we
// only specified one, there should just be one response.
interfaces := device.InterfaceSet()
if count := len(interfaces); count != 1 {
err := errors.Errorf("unexpected interface count for device: %d", count)
return nil, NewUnexpectedError(err)
}
iface := interfaces[0]
nameToUse := args.InterfaceName
if err := m.updateDeviceInterface(iface, nameToUse, vlanToUse); err != nil {
return nil, errors.Trace(err)
}
if args.Subnet == nil {
// Nothing further to update.
return device, nil
}
if err := m.linkDeviceInterfaceToSubnet(iface, args.Subnet); err != nil {
return nil, errors.Trace(err)
}
return device, nil
}
func (m *machine) updateDeviceInterface(iface Interface, nameToUse string, vlanToUse VLAN) error {
updateArgs := UpdateInterfaceArgs{}
updateArgs.Name = nameToUse
if vlanToUse != nil {
updateArgs.VLAN = vlanToUse
}
if err := iface.Update(updateArgs); err != nil {
return errors.Annotatef(err, "updating device interface %q failed", iface.Name())
}
return nil
}
func (m *machine) linkDeviceInterfaceToSubnet(iface Interface, subnetToUse Subnet) error {
err := iface.LinkSubnet(LinkSubnetArgs{
Mode: LinkModeStatic,
Subnet: subnetToUse,
})
if err != nil {
return errors.Annotatef(
err, "linking device interface %q to subnet %q failed",
iface.Name(), subnetToUse.CIDR())
}
return nil
}
// OwnerData implements OwnerDataHolder.
func (m *machine) OwnerData() map[string]string {
result := make(map[string]string)
for key, value := range m.ownerData {
result[key] = value
}
return result
}
// SetOwnerData implements OwnerDataHolder.
func (m *machine) SetOwnerData(ownerData map[string]string) error {
params := make(url.Values)
for key, value := range ownerData {
params.Add(key, value)
}
result, err := m.controller.post(m.resourceURI, "set_owner_data", params)
if err != nil {
return errors.Trace(err)
}
machine, err := readMachine(m.controller.apiVersion, result)
if err != nil {
return errors.Trace(err)
}
m.updateFrom(machine)
return nil
}
func readMachine(controllerVersion version.Number, source interface{}) (*machine, error) {
readFunc, err := getMachineDeserializationFunc(controllerVersion)
if err != nil {
return nil, errors.Trace(err)
}
checker := schema.StringMap(schema.Any())
coerced, err := checker.Coerce(source, nil)
if err != nil {
return nil, WrapWithDeserializationError(err, "machine base schema check failed")
}
valid := coerced.(map[string]interface{})
return readFunc(valid)
}
func readMachines(controllerVersion version.Number, source interface{}) ([]*machine, error) {
readFunc, err := getMachineDeserializationFunc(controllerVersion)
if err != nil {
return nil, errors.Trace(err)
}
checker := schema.List(schema.StringMap(schema.Any()))
coerced, err := checker.Coerce(source, nil)
if err != nil {
return nil, WrapWithDeserializationError(err, "machine base schema check failed")
}
valid := coerced.([]interface{})
return readMachineList(valid, readFunc)
}
func getMachineDeserializationFunc(controllerVersion version.Number) (machineDeserializationFunc, error) {
var deserialisationVersion version.Number
for v := range machineDeserializationFuncs {
if v.Compare(deserialisationVersion) > 0 && v.Compare(controllerVersion) <= 0 {
deserialisationVersion = v
}
}
if deserialisationVersion == version.Zero {
return nil, NewUnsupportedVersionError("no machine read func for version %s", controllerVersion)
}
return machineDeserializationFuncs[deserialisationVersion], nil
}
func readMachineList(sourceList []interface{}, readFunc machineDeserializationFunc) ([]*machine, error) {
result := make([]*machine, 0, len(sourceList))
for i, value := range sourceList {
source, ok := value.(map[string]interface{})
if !ok {
return nil, NewDeserializationError("unexpected value for machine %d, %T", i, value)
}
machine, err := readFunc(source)
if err != nil {
return nil, errors.Annotatef(err, "machine %d", i)
}
result = append(result, machine)
}
return result, nil
}
type machineDeserializationFunc func(map[string]interface{}) (*machine, error)
var machineDeserializationFuncs = map[version.Number]machineDeserializationFunc{
twoDotOh: machine_2_0,
}
func machine_2_0(source map[string]interface{}) (*machine, error) {
fields := schema.Fields{
"resource_uri": schema.String(),
"system_id": schema.String(),
"hostname": schema.String(),
"fqdn": schema.String(),
"tag_names": schema.List(schema.String()),
"owner_data": schema.StringMap(schema.String()),
"osystem": schema.String(),
"distro_series": schema.String(),
"architecture": schema.OneOf(schema.Nil(""), schema.String()),
"memory": schema.ForceInt(),
"cpu_count": schema.ForceInt(),
"hardware_info": schema.OneOf(schema.Nil(""), schema.StringMap(schema.String())),
"ip_addresses": schema.List(schema.String()),
"power_state": schema.String(),
"status_name": schema.String(),
"status_message": schema.OneOf(schema.Nil(""), schema.String()),
"boot_interface": schema.OneOf(schema.Nil(""), schema.StringMap(schema.Any())),
"interface_set": schema.List(schema.StringMap(schema.Any())),
"zone": schema.StringMap(schema.Any()),
"pool": schema.OneOf(schema.Nil(""), schema.Any()),
"physicalblockdevice_set": schema.List(schema.StringMap(schema.Any())),
"blockdevice_set": schema.List(schema.StringMap(schema.Any())),
}
defaults := schema.Defaults{
"architecture": "",
}
checker := schema.FieldMap(fields, defaults)
coerced, err := checker.Coerce(source, nil)
if err != nil {
return nil, WrapWithDeserializationError(err, "machine 2.0 schema check failed")
}
valid := coerced.(map[string]interface{})
// From here we know that the map returned from the schema coercion
// contains fields of the right type.
var bootInterface *interface_
if ifaceMap, ok := valid["boot_interface"].(map[string]interface{}); ok {
bootInterface, err = interface_2_0(ifaceMap)
if err != nil {
return nil, errors.Trace(err)
}
}
interfaceSet, err := readInterfaceList(valid["interface_set"].([]interface{}), interface_2_0)
if err != nil {
return nil, errors.Trace(err)
}
zone, err := zone_2_0(valid["zone"].(map[string]interface{}))
if err != nil {
return nil, errors.Trace(err)
}
var pool *pool
if valid["pool"] != nil {
if pool, err = pool_2_0(valid["pool"].(map[string]interface{})); err != nil {
return nil, errors.Trace(err)
}
}
physicalBlockDevices, err := readBlockDeviceList(valid["physicalblockdevice_set"].([]interface{}), blockdevice_2_0)
if err != nil {
return nil, errors.Trace(err)
}
blockDevices, err := readBlockDeviceList(valid["blockdevice_set"].([]interface{}), blockdevice_2_0)
if err != nil {
return nil, errors.Trace(err)
}
var hardwareInfo map[string]string
if validHardwareInfo, ok := valid["hardware_info"].(map[string]interface{}); ok {
hardwareInfo = make(map[string]string, len(validHardwareInfo))
for key, value := range validHardwareInfo {
v, ok := value.(string)
if !ok {
return nil, fmt.Errorf("invalid field %q in \"hardware_info\"", key)
}
hardwareInfo[key] = v
}
}
architecture, _ := valid["architecture"].(string)
statusMessage, _ := valid["status_message"].(string)
result := &machine{
resourceURI: valid["resource_uri"].(string),
systemID: valid["system_id"].(string),
hostname: valid["hostname"].(string),
fqdn: valid["fqdn"].(string),
tags: convertToStringSlice(valid["tag_names"]),
ownerData: convertToStringMap(valid["owner_data"]),
operatingSystem: valid["osystem"].(string),
distroSeries: valid["distro_series"].(string),
architecture: architecture,
memory: valid["memory"].(int),
cpuCount: valid["cpu_count"].(int),
hardwareInfo: hardwareInfo,
ipAddresses: convertToStringSlice(valid["ip_addresses"]),
powerState: valid["power_state"].(string),
statusName: valid["status_name"].(string),
statusMessage: statusMessage,
bootInterface: bootInterface,
interfaceSet: interfaceSet,
zone: zone,
pool: pool,
physicalBlockDevices: physicalBlockDevices,
blockDevices: blockDevices,
}
return result, nil
}
func convertToStringSlice(field interface{}) []string {
if field == nil {
return nil
}
fieldSlice := field.([]interface{})
result := make([]string, len(fieldSlice))
for i, value := range fieldSlice {
result[i] = value.(string)
}
return result
}
func convertToStringMap(field interface{}) map[string]string {
if field == nil {
return nil
}
// This function is only called after a schema Coerce, so it's
// safe.
fieldMap := field.(map[string]interface{})
result := make(map[string]string)
for key, value := range fieldMap {
result[key] = value.(string)
}
return result
}