-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathvmhost.go
More file actions
406 lines (352 loc) · 10.1 KB
/
Copy pathvmhost.go
File metadata and controls
406 lines (352 loc) · 10.1 KB
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
// Copyright 2026 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package gomaasapi
import (
"fmt"
"net/http"
"net/url"
"strings"
"github.com/juju/errors"
"github.com/juju/schema"
"github.com/juju/version"
)
// vmHost represents a VM host in MAAS.
type vmHost struct {
controller *controller
resourceURI string
id int
name string
type_ string
zone *zone
pool *pool
}
// ID implements VmHost.
func (p *vmHost) ID() int {
return p.id
}
// Name implements VmHost.
func (p *vmHost) Name() string {
return p.name
}
// Type implements VmHost.
func (p *vmHost) Type() string {
return p.type_
}
// Zone implements VmHost.
func (p *vmHost) Zone() Zone {
if p.zone == nil {
return nil
}
return p.zone
}
// Pool implements VmHost.
func (p *vmHost) Pool() Pool {
if p.pool == nil {
return nil
}
return p.pool
}
// ComposeMachineArgs holds the arguments for composing a machine in a VM host.
type ComposeMachineArgs struct {
// Hostname is the desired hostname for the composed machine (optional).
Hostname string
// MinCPUCount is the minimum number of CPU cores (optional).
MinCPUCount int
// MinMemory is the minimum RAM in MiB (optional).
MinMemory int
// Storage is the list of storage specs for the machine (optional).
// The first entry is treated as the root disk by MAAS.
Storage []StorageSpec
// Interfaces is the list of network interface specs (optional).
Interfaces []InterfaceSpec
// Zone is the desired zone name (optional).
Zone string
// Pool is the desired pool name (optional).
Pool string
}
// ComposeMachine implements VmHost.
func (p *vmHost) ComposeMachine(args ComposeMachineArgs) (Machine, error) {
return p.controller.ComposeMachine(p.id, args)
}
func (a *ComposeMachineArgs) storage() string {
var values []string
for _, spec := range a.Storage {
values = append(values, spec.String())
}
return strings.Join(values, ",")
}
func (a *ComposeMachineArgs) interfaces() string {
var values []string
for _, spec := range a.Interfaces {
values = append(values, spec.String())
}
return strings.Join(values, ";")
}
func readVmHosts(apiVersion version.Number, source any) ([]*vmHost, error) {
checker := schema.List(schema.StringMap(schema.Any()))
coerced, err := checker.Coerce(source, nil)
if err != nil {
return nil, WrapWithDeserializationError(err, "vm host schema check failed")
}
valid := coerced.([]any)
var deserialisationVersion version.Number
for v := range vmHostDeserializationFuncs {
if v.Compare(deserialisationVersion) > 0 && v.Compare(apiVersion) <= 0 {
deserialisationVersion = v
}
}
if deserialisationVersion == version.Zero {
return nil, errors.Errorf("no vm host read func for version %s", apiVersion)
}
readFunc := vmHostDeserializationFuncs[deserialisationVersion]
var result []*vmHost
for i, value := range valid {
src, ok := value.(map[string]any)
if !ok {
return nil, errors.Errorf("unexpected value for vm host %d, %T", i, value)
}
p, err := readFunc(src)
if err != nil {
return nil, errors.Annotatef(err, "vm host %d", i)
}
result = append(result, p)
}
return result, nil
}
type vmHostDeserializationFunc func(map[string]any) (*vmHost, error)
var vmHostDeserializationFuncs = map[version.Number]vmHostDeserializationFunc{
twoDotOh: vmHost_2_0,
}
func vmHost_2_0(source map[string]any) (*vmHost, error) {
fields := schema.Fields{
"resource_uri": schema.String(),
"id": schema.ForceInt(),
"name": schema.String(),
"type": schema.String(),
"zone": schema.StringMap(schema.Any()),
"pool": schema.StringMap(schema.Any()),
}
defaults := schema.Defaults{
"zone": schema.Omit,
"pool": schema.Omit,
"type": "",
}
checker := schema.FieldMap(fields, defaults)
coerced, err := checker.Coerce(source, nil)
if err != nil {
return nil, WrapWithDeserializationError(err, "vm host 2.0 schema check failed")
}
valid := coerced.(map[string]any)
id, err := toIntValue(valid["id"])
if err != nil {
return nil, errors.Annotate(err, "vm host id")
}
result := &vmHost{
resourceURI: valid["resource_uri"].(string),
id: id,
name: valid["name"].(string),
type_: valid["type"].(string),
}
if zoneMap, ok := valid["zone"].(map[string]any); ok {
z, err := zone_2_0(zoneMap)
if err != nil {
return nil, errors.Annotate(err, "vm host zone")
}
result.zone = z
}
if poolMap, ok := valid["pool"].(map[string]any); ok {
p, err := pool_2_0(poolMap)
if err != nil {
return nil, errors.Annotate(err, "vm host pool")
}
result.pool = p
}
return result, nil
}
func toIntValue(v any) (int, error) {
switch val := v.(type) {
case int:
return val, nil
case int64:
return int(val), nil
case float64:
return int(val), nil
default:
return 0, fmt.Errorf("cannot convert %T to int", v)
}
}
// VmHosts implements Controller.
// It returns the list of VM hosts known to the MAAS controller.
func (c *controller) VmHosts() ([]VmHost, error) {
source, err := c.getVmHosts()
if err != nil {
return nil, err
}
vmHosts, err := readVmHosts(c.apiVersion, source)
if err != nil {
return nil, errors.Trace(err)
}
var result []VmHost
for _, p := range vmHosts {
p.controller = c
result = append(result, p)
}
return result, nil
}
var vmHostEndpointUnavailableError = errors.ConstError("vm-host endpoint unavailable")
func isVmHostEndpointUnavailable(err error) bool {
if err == nil {
return false
}
return errors.Cause(err) == vmHostEndpointUnavailableError
}
func (c *controller) getVmHosts() (any, error) {
source, err := c.maybeGetVmHosts("vm-hosts")
if err != nil {
if !isVmHostEndpointUnavailable(err) {
return nil, err
}
} else {
return source, err
}
source, err = c.maybeGetVmHosts("pods")
if err != nil {
if isVmHostEndpointUnavailable(err) {
return nil, errors.New("vm-hosts/pods API not available on this MAAS controller")
}
return nil, err
}
return source, nil
}
func (c *controller) maybeGetVmHosts(path string) (any, error) {
source, err := c.get(path)
if err == nil {
return source, nil
}
svrErr, ok := errors.Cause(err).(ServerError)
if !ok {
return nil, NewUnexpectedError(err)
}
switch svrErr.StatusCode {
case http.StatusNotFound, http.StatusGone:
return nil, vmHostEndpointUnavailableError
default:
return nil, NewUnexpectedError(err)
}
}
// ComposeMachine implements Controller.
// It composes (creates) a new machine in the VM host specified by vmHostID.
// Returns an error that satisfies IsNoMatchError if the VM host cannot satisfy
// the requested constraints.
func (c *controller) ComposeMachine(vmHostID int, args ComposeMachineArgs) (result Machine, err error) {
params := NewURLParams()
params.MaybeAdd("hostname", args.Hostname)
params.MaybeAddInt("cores", args.MinCPUCount)
params.MaybeAddInt("memory", args.MinMemory)
params.MaybeAdd("storage", args.storage())
params.MaybeAdd("interfaces", args.interfaces())
if args.Zone != "" {
zoneID, err := c.zoneIDByName(args.Zone)
if err != nil {
return nil, errors.Trace(err)
}
params.MaybeAddInt("zone", zoneID)
}
params.MaybeAdd("pool", args.Pool)
composeResult, err := c.composeMachine(vmHostID, params.Values)
if err != nil {
return nil, err
}
systemID, hasSystemID := composedMachineSystemID(composeResult)
defer func() {
if err == nil || !hasSystemID {
return
}
if deleteErr := c.DeleteMachine(systemID); deleteErr != nil {
logger.Warningf("failed deleting composed machine %q after compose response parse error: %v", systemID, deleteErr)
}
}()
machine, err := c.readComposedMachine(composeResult)
if err != nil {
return nil, errors.Trace(err)
}
machine.controller = c
return machine, nil
}
func composedMachineSystemID(result any) (string, bool) {
rawMachine, ok := result.(map[string]any)
if !ok {
return "", false
}
if wrappedMachine, ok := rawMachine["machine"].(map[string]any); ok {
rawMachine = wrappedMachine
}
systemID, ok := rawMachine["system_id"].(string)
if !ok || systemID == "" {
return "", false
}
return systemID, true
}
func (c *controller) readComposedMachine(result any) (*machine, error) {
rawMachine, ok := result.(map[string]any)
if !ok {
return nil, errors.Errorf("unexpected compose response type %T", result)
}
if wrappedMachine, ok := rawMachine["machine"].(map[string]any); ok {
rawMachine = wrappedMachine
}
// MAAS could return a full machine object or only machine identity fields.
// We can use "hostname" as the sentinel.
if _, hasHostname := rawMachine["hostname"]; hasHostname {
return readMachine(c.apiVersion, rawMachine)
}
checker := schema.FieldMap(schema.Fields{
"system_id": schema.String(),
"resource_uri": schema.String(),
}, nil)
coerced, err := checker.Coerce(rawMachine, nil)
if err != nil {
return nil, WrapWithDeserializationError(err, "compose response schema check failed")
}
valid := coerced.(map[string]any)
return &machine{
systemID: valid["system_id"].(string),
resourceURI: valid["resource_uri"].(string),
}, nil
}
func (c *controller) composeMachine(vmHostID int, params url.Values) (any, error) {
result, err := c.maybeComposeMachine(fmt.Sprintf("vm-hosts/%d", vmHostID), params)
if err != nil {
if !isVmHostEndpointUnavailable(err) {
return nil, err
}
result, err = c.maybeComposeMachine(fmt.Sprintf("pods/%d", vmHostID), params)
if err != nil {
if isVmHostEndpointUnavailable(err) {
return nil, errors.New("vm-hosts/pods API not available on this MAAS controller")
}
return nil, err
}
}
return result, nil
}
func (c *controller) maybeComposeMachine(path string, params url.Values) (any, error) {
result, err := c.post(path, "compose", params)
if err == nil {
return result, nil
}
svrErr, ok := errors.Cause(err).(ServerError)
if !ok {
return nil, NewUnexpectedError(err)
}
switch svrErr.StatusCode {
case http.StatusConflict:
return nil, errors.Wrap(err, NewNoMatchError(svrErr.BodyMessage))
case http.StatusBadRequest:
return nil, errors.Wrap(err, NewBadRequestError(svrErr.BodyMessage))
case http.StatusNotFound, http.StatusGone:
return nil, vmHostEndpointUnavailableError
default:
return nil, NewUnexpectedError(err)
}
}