/
environ.go
2411 lines (2201 loc) · 73.8 KB
/
environ.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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package maas
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/gomaasapi"
"github.com/juju/os"
"github.com/juju/os/series"
"github.com/juju/utils"
"github.com/juju/version"
"gopkg.in/juju/names.v2"
"github.com/juju/juju/cloudconfig/cloudinit"
"github.com/juju/juju/cloudconfig/instancecfg"
"github.com/juju/juju/cloudconfig/providerinit"
"github.com/juju/juju/core/constraints"
"github.com/juju/juju/core/instance"
corenetwork "github.com/juju/juju/core/network"
"github.com/juju/juju/core/status"
"github.com/juju/juju/environs"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/environs/context"
"github.com/juju/juju/environs/instances"
"github.com/juju/juju/environs/storage"
"github.com/juju/juju/environs/tags"
"github.com/juju/juju/network"
"github.com/juju/juju/provider/common"
"github.com/juju/juju/state/multiwatcher"
"github.com/juju/juju/tools"
)
const (
// The version strings indicating the MAAS API version.
apiVersion1 = "1.0"
apiVersion2 = "2.0"
)
// A request may fail to due "eventual consistency" semantics, which
// should resolve fairly quickly. A request may also fail due to a slow
// state transition (for instance an instance taking a while to release
// a security group after termination). The former failure mode is
// dealt with by shortAttempt, the latter by LongAttempt.
var shortAttempt = utils.AttemptStrategy{
Total: 5 * time.Second,
Delay: 200 * time.Millisecond,
}
const statusPollInterval = 5 * time.Second
var (
ReleaseNodes = releaseNodes
DeploymentStatusCall = deploymentStatusCall
GetMAAS2Controller = getMAAS2Controller
)
func getMAAS2Controller(maasServer, apiKey string) (gomaasapi.Controller, error) {
return gomaasapi.NewController(gomaasapi.ControllerArgs{
BaseURL: maasServer,
APIKey: apiKey,
})
}
func releaseNodes(nodes gomaasapi.MAASObject, ids url.Values) error {
_, err := nodes.CallPost("release", ids)
return err
}
type maasEnviron struct {
name string
uuid string
// archMutex gates access to supportedArchitectures
archMutex sync.Mutex
// ecfgMutex protects the *Unlocked fields below.
ecfgMutex sync.Mutex
ecfgUnlocked *maasModelConfig
maasClientUnlocked *gomaasapi.MAASObject
storageUnlocked storage.Storage
// maasController provides access to the MAAS 2.0 API.
maasController gomaasapi.Controller
// namespace is used to create the machine and device hostnames.
namespace instance.Namespace
availabilityZonesMutex sync.Mutex
availabilityZones []common.AvailabilityZone
// apiVersion tells us if we are using the MAAS 1.0 or 2.0 api.
apiVersion string
// GetCapabilities is a function that connects to MAAS to return its set of
// capabilities.
GetCapabilities MaasCapabilities
}
var _ environs.Environ = (*maasEnviron)(nil)
var _ environs.Networking = (*maasEnviron)(nil)
// MaasCapabilities represents a function that gets the capabilities of a MAAS
// installation.
type MaasCapabilities func(client *gomaasapi.MAASObject, serverURL string) (set.Strings, error)
func NewEnviron(cloud environs.CloudSpec, cfg *config.Config, getCaps MaasCapabilities) (*maasEnviron, error) {
if getCaps == nil {
getCaps = getCapabilities
}
env := &maasEnviron{
name: cfg.Name(),
uuid: cfg.UUID(),
GetCapabilities: getCaps,
}
if err := env.SetConfig(cfg); err != nil {
return nil, errors.Trace(err)
}
if err := env.SetCloudSpec(cloud); err != nil {
return nil, errors.Trace(err)
}
var err error
env.namespace, err = instance.NewNamespace(cfg.UUID())
if err != nil {
return nil, errors.Trace(err)
}
return env, nil
}
func (env *maasEnviron) usingMAAS2() bool {
return env.apiVersion == apiVersion2
}
// PrepareForBootstrap is part of the Environ interface.
func (env *maasEnviron) PrepareForBootstrap(ctx environs.BootstrapContext, controllerName string) error {
if ctx.ShouldVerifyCredentials() {
if err := verifyCredentials(env, nil); err != nil {
return err
}
}
return nil
}
// Create is part of the Environ interface.
func (env *maasEnviron) Create(ctx context.ProviderCallContext, p environs.CreateParams) error {
if err := verifyCredentials(env, ctx); err != nil {
return err
}
return nil
}
// Bootstrap is part of the Environ interface.
func (env *maasEnviron) Bootstrap(
ctx environs.BootstrapContext, callCtx context.ProviderCallContext, args environs.BootstrapParams,
) (*environs.BootstrapResult, error) {
result, series, finalizer, err := common.BootstrapInstance(ctx, env, callCtx, args)
if err != nil {
return nil, err
}
// We want to destroy the started instance if it doesn't transition to Deployed.
defer func() {
if err != nil {
if err := env.StopInstances(callCtx, result.Instance.Id()); err != nil {
logger.Errorf("error releasing bootstrap instance: %v", err)
}
}
}()
waitingFinalizer := func(
ctx environs.BootstrapContext,
icfg *instancecfg.InstanceConfig,
dialOpts environs.BootstrapDialOpts,
) error {
// Wait for bootstrap instance to change to deployed state.
if err := env.waitForNodeDeployment(callCtx, result.Instance.Id(), dialOpts.Timeout); err != nil {
return errors.Annotate(err, "bootstrap instance started but did not change to Deployed state")
}
return finalizer(ctx, icfg, dialOpts)
}
bsResult := &environs.BootstrapResult{
Arch: *result.Hardware.Arch,
Series: series,
CloudBootstrapFinalizer: waitingFinalizer,
}
return bsResult, nil
}
// ControllerInstances is specified in the Environ interface.
func (env *maasEnviron) ControllerInstances(ctx context.ProviderCallContext, controllerUUID string) ([]instance.Id, error) {
if !env.usingMAAS2() {
return env.controllerInstances1(ctx, controllerUUID)
}
return env.controllerInstances2(ctx, controllerUUID)
}
func (env *maasEnviron) controllerInstances1(ctx context.ProviderCallContext, controllerUUID string) ([]instance.Id, error) {
return common.ProviderStateInstances(env.Storage())
}
func (env *maasEnviron) controllerInstances2(ctx context.ProviderCallContext, controllerUUID string) ([]instance.Id, error) {
instances, err := env.instances2(ctx, gomaasapi.MachinesArgs{
OwnerData: map[string]string{
tags.JujuIsController: "true",
tags.JujuController: controllerUUID,
},
})
if err != nil {
return nil, errors.Trace(err)
}
if len(instances) == 0 {
return nil, environs.ErrNotBootstrapped
}
ids := make([]instance.Id, len(instances))
for i := range instances {
ids[i] = instances[i].Id()
}
return ids, nil
}
// ecfg returns the environment's maasModelConfig, and protects it with a
// mutex.
func (env *maasEnviron) ecfg() *maasModelConfig {
env.ecfgMutex.Lock()
cfg := *env.ecfgUnlocked
env.ecfgMutex.Unlock()
return &cfg
}
// Config is specified in the Environ interface.
func (env *maasEnviron) Config() *config.Config {
return env.ecfg().Config
}
// SetConfig is specified in the Environ interface.
func (env *maasEnviron) SetConfig(cfg *config.Config) error {
env.ecfgMutex.Lock()
defer env.ecfgMutex.Unlock()
// The new config has already been validated by itself, but now we
// validate the transition from the old config to the new.
var oldCfg *config.Config
if env.ecfgUnlocked != nil {
oldCfg = env.ecfgUnlocked.Config
}
cfg, err := env.Provider().Validate(cfg, oldCfg)
if err != nil {
return errors.Trace(err)
}
ecfg, err := providerInstance.newConfig(cfg)
if err != nil {
return errors.Trace(err)
}
env.ecfgUnlocked = ecfg
return nil
}
// SetCloudSpec is specified in the environs.Environ interface.
func (env *maasEnviron) SetCloudSpec(spec environs.CloudSpec) error {
env.ecfgMutex.Lock()
defer env.ecfgMutex.Unlock()
maasServer, err := parseCloudEndpoint(spec.Endpoint)
if err != nil {
return errors.Trace(err)
}
maasOAuth, err := parseOAuthToken(*spec.Credential)
if err != nil {
return errors.Trace(err)
}
// We need to know the version of the server we're on. We support 1.9
// and 2.0. MAAS 1.9 uses the 1.0 api version and 2.0 uses the 2.0 api
// version.
apiVersion := apiVersion2
controller, err := GetMAAS2Controller(maasServer, maasOAuth)
switch {
case gomaasapi.IsUnsupportedVersionError(err):
apiVersion = apiVersion1
_, _, includesVersion := gomaasapi.SplitVersionedURL(maasServer)
versionURL := maasServer
if !includesVersion {
versionURL = gomaasapi.AddAPIVersionToURL(maasServer, apiVersion1)
}
authClient, err := gomaasapi.NewAuthenticatedClient(versionURL, maasOAuth)
if err != nil {
return errors.Trace(err)
}
env.maasClientUnlocked = gomaasapi.NewMAAS(*authClient)
caps, err := env.GetCapabilities(env.maasClientUnlocked, maasServer)
if err != nil {
return errors.Trace(err)
}
if !caps.Contains(capNetworkDeploymentUbuntu) {
return errors.NewNotSupported(nil, "MAAS 1.9 or more recent is required")
}
case err != nil:
return errors.Trace(err)
default:
env.maasController = controller
}
env.apiVersion = apiVersion
env.storageUnlocked = NewStorage(env)
return nil
}
func (env *maasEnviron) getSupportedArchitectures(ctx context.ProviderCallContext) ([]string, error) {
env.archMutex.Lock()
defer env.archMutex.Unlock()
fetchArchitectures := env.allArchitecturesWithFallback
if env.usingMAAS2() {
fetchArchitectures = env.allArchitectures2
}
return fetchArchitectures(ctx)
}
// SupportsSpaces is specified on environs.Networking.
func (env *maasEnviron) SupportsSpaces(ctx context.ProviderCallContext) (bool, error) {
return true, nil
}
// SupportsSpaceDiscovery is specified on environs.Networking.
func (env *maasEnviron) SupportsSpaceDiscovery(ctx context.ProviderCallContext) (bool, error) {
return true, nil
}
// SupportsContainerAddresses is specified on environs.Networking.
func (env *maasEnviron) SupportsContainerAddresses(ctx context.ProviderCallContext) (bool, error) {
return true, nil
}
// allArchitectures2 uses the MAAS2 controller to get architectures from boot
// resources.
func (env *maasEnviron) allArchitectures2(ctx context.ProviderCallContext) ([]string, error) {
resources, err := env.maasController.BootResources()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
architectures := set.NewStrings()
for _, resource := range resources {
architectures.Add(strings.Split(resource.Architecture(), "/")[0])
}
return architectures.SortedValues(), nil
}
// allArchitectureWithFallback queries MAAS for all of the boot-images
// across all registered nodegroups and collapses them down to unique
// architectures.
func (env *maasEnviron) allArchitecturesWithFallback(ctx context.ProviderCallContext) ([]string, error) {
architectures, err := env.allArchitectures(ctx)
if err != nil || len(architectures) == 0 {
logger.Debugf("error querying boot-images: %v", err)
logger.Debugf("falling back to listing nodes")
architectures, err := env.nodeArchitectures(ctx)
if err != nil {
return nil, errors.Trace(err)
}
return architectures, nil
} else {
return architectures, nil
}
}
func (env *maasEnviron) allArchitectures(ctx context.ProviderCallContext) ([]string, error) {
nodegroups, err := env.getNodegroups(ctx)
if err != nil {
return nil, err
}
architectures := set.NewStrings()
for _, nodegroup := range nodegroups {
bootImages, err := env.nodegroupBootImages(ctx, nodegroup)
if err != nil {
return nil, errors.Annotatef(err, "cannot get boot images for nodegroup %v", nodegroup)
}
for _, image := range bootImages {
architectures.Add(image.architecture)
}
}
return architectures.SortedValues(), nil
}
// getNodegroups returns the UUID corresponding to each nodegroup
// in the MAAS installation.
func (env *maasEnviron) getNodegroups(ctx context.ProviderCallContext) ([]string, error) {
nodegroupsListing := env.getMAASClient().GetSubObject("nodegroups")
nodegroupsResult, err := nodegroupsListing.CallGet("list", nil)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
list, err := nodegroupsResult.GetArray()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
nodegroups := make([]string, len(list))
for i, obj := range list {
nodegroup, err := obj.GetMap()
if err != nil {
return nil, err
}
uuid, err := nodegroup["uuid"].GetString()
if err != nil {
return nil, err
}
nodegroups[i] = uuid
}
return nodegroups, nil
}
type bootImage struct {
architecture string
release string
}
// nodegroupBootImages returns the set of boot-images for the specified nodegroup.
func (env *maasEnviron) nodegroupBootImages(ctx context.ProviderCallContext, nodegroupUUID string) ([]bootImage, error) {
nodegroupObject := env.getMAASClient().GetSubObject("nodegroups").GetSubObject(nodegroupUUID)
bootImagesObject := nodegroupObject.GetSubObject("boot-images/")
result, err := bootImagesObject.CallGet("", nil)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
list, err := result.GetArray()
if err != nil {
return nil, err
}
var bootImages []bootImage
for _, obj := range list {
bootimage, err := obj.GetMap()
if err != nil {
return nil, err
}
arch, err := bootimage["architecture"].GetString()
if err != nil {
return nil, err
}
release, err := bootimage["release"].GetString()
if err != nil {
return nil, err
}
bootImages = append(bootImages, bootImage{
architecture: arch,
release: release,
})
}
return bootImages, nil
}
// nodeArchitectures returns the architectures of all
// available nodes in the system.
//
// Note: this should only be used if we cannot query
// boot-images.
func (env *maasEnviron) nodeArchitectures(ctx context.ProviderCallContext) ([]string, error) {
filter := make(url.Values)
filter.Add("status", gomaasapi.NodeStatusDeclared)
filter.Add("status", gomaasapi.NodeStatusCommissioning)
filter.Add("status", gomaasapi.NodeStatusReady)
filter.Add("status", gomaasapi.NodeStatusReserved)
filter.Add("status", gomaasapi.NodeStatusAllocated)
// This is fine - nodeArchitectures is only used in MAAS 1 cases.
allInstances, err := env.instances1(ctx, filter)
if err != nil {
return nil, err
}
architectures := make(set.Strings)
for _, inst := range allInstances {
inst := inst.(*maas1Instance)
arch, _, err := inst.architecture()
if err != nil {
return nil, err
}
architectures.Add(arch)
}
// TODO(dfc) why is this sorted
return architectures.SortedValues(), nil
}
type maasAvailabilityZone struct {
name string
}
func (z maasAvailabilityZone) Name() string {
return z.name
}
func (z maasAvailabilityZone) Available() bool {
// MAAS' physical zone attributes only include name and description;
// there is no concept of availability.
return true
}
// AvailabilityZones returns a slice of availability zones
// for the configured region.
func (env *maasEnviron) AvailabilityZones(ctx context.ProviderCallContext) ([]common.AvailabilityZone, error) {
env.availabilityZonesMutex.Lock()
defer env.availabilityZonesMutex.Unlock()
if env.availabilityZones == nil {
var availabilityZones []common.AvailabilityZone
var err error
if env.usingMAAS2() {
availabilityZones, err = env.availabilityZones2(ctx)
if err != nil {
return nil, errors.Trace(err)
}
} else {
availabilityZones, err = env.availabilityZones1(ctx)
if err != nil {
return nil, errors.Trace(err)
}
}
env.availabilityZones = availabilityZones
}
return env.availabilityZones, nil
}
func (env *maasEnviron) availabilityZones1(ctx context.ProviderCallContext) ([]common.AvailabilityZone, error) {
zonesObject := env.getMAASClient().GetSubObject("zones")
result, err := zonesObject.CallGet("", nil)
if err, ok := errors.Cause(err).(gomaasapi.ServerError); ok && err.StatusCode == http.StatusNotFound {
return nil, errors.NewNotImplemented(nil, "the MAAS server does not support zones")
}
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Annotate(err, "cannot query ")
}
list, err := result.GetArray()
if err != nil {
return nil, err
}
logger.Debugf("availability zones: %+v", list)
availabilityZones := make([]common.AvailabilityZone, len(list))
for i, obj := range list {
zone, err := obj.GetMap()
if err != nil {
return nil, err
}
name, err := zone["name"].GetString()
if err != nil {
return nil, err
}
availabilityZones[i] = maasAvailabilityZone{name}
}
return availabilityZones, nil
}
func (env *maasEnviron) availabilityZones2(ctx context.ProviderCallContext) ([]common.AvailabilityZone, error) {
zones, err := env.maasController.Zones()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
availabilityZones := make([]common.AvailabilityZone, len(zones))
for i, zone := range zones {
availabilityZones[i] = maasAvailabilityZone{zone.Name()}
}
return availabilityZones, nil
}
// InstanceAvailabilityZoneNames returns the availability zone names for each
// of the specified instances.
func (env *maasEnviron) InstanceAvailabilityZoneNames(ctx context.ProviderCallContext, ids []instance.Id) ([]string, error) {
instances, err := env.Instances(ctx, ids)
if err != nil && err != environs.ErrPartialInstances {
return nil, err
}
zones := make([]string, len(instances))
for i, inst := range instances {
if inst == nil {
continue
}
z, err := inst.(maasInstance).zone()
if err != nil {
logger.Errorf("could not get availability zone %v", err)
continue
}
zones[i] = z
}
return zones, nil
}
// DeriveAvailabilityZones is part of the common.ZonedEnviron interface.
func (env *maasEnviron) DeriveAvailabilityZones(ctx context.ProviderCallContext, args environs.StartInstanceParams) ([]string, error) {
if args.Placement != "" {
placement, err := env.parsePlacement(ctx, args.Placement)
if err != nil {
return nil, errors.Trace(err)
}
if placement.zoneName != "" {
return []string{placement.zoneName}, nil
}
}
return nil, nil
}
type maasPlacement struct {
nodeName string
zoneName string
systemId string
}
func (env *maasEnviron) parsePlacement(ctx context.ProviderCallContext, placement string) (*maasPlacement, error) {
pos := strings.IndexRune(placement, '=')
if pos == -1 {
// If there's no '=' delimiter, assume it's a node name.
return &maasPlacement{nodeName: placement}, nil
}
switch key, value := placement[:pos], placement[pos+1:]; key {
case "zone":
availabilityZone := value
err := common.ValidateAvailabilityZone(env, ctx, availabilityZone)
if err != nil {
return nil, err
}
return &maasPlacement{zoneName: availabilityZone}, nil
case "system-id":
return &maasPlacement{systemId: value}, nil
}
return nil, errors.Errorf("unknown placement directive: %v", placement)
}
func (env *maasEnviron) PrecheckInstance(ctx context.ProviderCallContext, args environs.PrecheckInstanceParams) error {
if args.Placement == "" {
return nil
}
_, err := env.parsePlacement(ctx, args.Placement)
return err
}
const (
capNetworkDeploymentUbuntu = "network-deployment-ubuntu"
)
// getCapabilities asks the MAAS server for its capabilities, if
// supported by the server.
func getCapabilities(client *gomaasapi.MAASObject, serverURL string) (set.Strings, error) {
caps := make(set.Strings)
var result gomaasapi.JSONObject
var err error
for a := shortAttempt.Start(); a.Next(); {
version := client.GetSubObject("version/")
result, err = version.CallGet("", nil)
if err == nil {
break
}
if err, ok := errors.Cause(err).(gomaasapi.ServerError); ok && err.StatusCode == 404 {
logger.Debugf("Failed attempting to get capabilities from maas endpoint %q: %v", serverURL, err)
message := "could not connect to MAAS controller - check the endpoint is correct"
trimmedURL := strings.TrimRight(serverURL, "/")
if !strings.HasSuffix(trimmedURL, "/MAAS") {
message += " (it normally ends with /MAAS)"
}
return caps, errors.NewNotSupported(nil, message)
}
}
if err != nil {
logger.Debugf("Can't connect to maas server at endpoint %q: %v", serverURL, err)
return caps, err
}
info, err := result.GetMap()
if err != nil {
logger.Debugf("Invalid data returned from maas endpoint %q: %v", serverURL, err)
// invalid data of some sort, probably not a MAAS server.
return caps, errors.New("failed to get expected data from server")
}
capsObj, ok := info["capabilities"]
if !ok {
return caps, fmt.Errorf("MAAS does not report capabilities")
}
items, err := capsObj.GetArray()
if err != nil {
logger.Debugf("Invalid data returned from maas endpoint %q: %v", serverURL, err)
return caps, errors.New("failed to get expected data from server")
}
for _, item := range items {
val, err := item.GetString()
if err != nil {
logger.Debugf("Invalid data returned from maas endpoint %q: %v", serverURL, err)
return set.NewStrings(), errors.New("failed to get expected data from server")
}
caps.Add(val)
}
return caps, nil
}
// getMAASClient returns a MAAS client object to use for a request, in a
// lock-protected fashion.
func (env *maasEnviron) getMAASClient() *gomaasapi.MAASObject {
env.ecfgMutex.Lock()
defer env.ecfgMutex.Unlock()
return env.maasClientUnlocked
}
var dashSuffix = regexp.MustCompile("^(.*)-\\d+$")
func spaceNamesToSpaceInfo(
spaces []string, spaceMap map[string]corenetwork.SpaceInfo,
) ([]corenetwork.SpaceInfo, error) {
var spaceInfos []corenetwork.SpaceInfo
for _, name := range spaces {
info, ok := spaceMap[name]
if !ok {
matches := dashSuffix.FindAllStringSubmatch(name, 1)
if matches == nil {
return nil, errors.Errorf("unrecognised space in constraint %q", name)
}
// A -number was added to the space name when we
// converted to a juju name, we found
info, ok = spaceMap[matches[0][1]]
if !ok {
return nil, errors.Errorf("unrecognised space in constraint %q", name)
}
}
spaceInfos = append(spaceInfos, info)
}
return spaceInfos, nil
}
func (env *maasEnviron) buildSpaceMap(ctx context.ProviderCallContext) (map[string]corenetwork.SpaceInfo, error) {
spaces, err := env.Spaces(ctx)
if err != nil {
return nil, errors.Trace(err)
}
spaceMap := make(map[string]corenetwork.SpaceInfo)
empty := set.Strings{}
for _, space := range spaces {
jujuName := network.ConvertSpaceName(space.Name, empty)
spaceMap[jujuName] = space
}
return spaceMap, nil
}
func (env *maasEnviron) spaceNamesToSpaceInfo(
ctx context.ProviderCallContext, positiveSpaces, negativeSpaces []string,
) ([]corenetwork.SpaceInfo, []corenetwork.SpaceInfo, error) {
spaceMap, err := env.buildSpaceMap(ctx)
if err != nil {
return nil, nil, errors.Trace(err)
}
positiveSpaceIds, err := spaceNamesToSpaceInfo(positiveSpaces, spaceMap)
if err != nil {
return nil, nil, errors.Trace(err)
}
negativeSpaceIds, err := spaceNamesToSpaceInfo(negativeSpaces, spaceMap)
if err != nil {
return nil, nil, errors.Trace(err)
}
return positiveSpaceIds, negativeSpaceIds, nil
}
// acquireNode2 allocates a machine from MAAS2.
func (env *maasEnviron) acquireNode2(
ctx context.ProviderCallContext,
nodeName, zoneName, systemId string,
cons constraints.Value,
interfaces []interfaceBinding,
volumes []volumeInfo,
) (maasInstance, error) {
acquireParams := convertConstraints2(cons)
positiveSpaceNames, negativeSpaceNames := convertSpacesFromConstraints(cons.Spaces)
positiveSpaces, negativeSpaces, err := env.spaceNamesToSpaceInfo(ctx, positiveSpaceNames, negativeSpaceNames)
// If spaces aren't supported the constraints should be empty anyway.
if err != nil && !errors.IsNotSupported(err) {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
err = addInterfaces2(&acquireParams, interfaces, positiveSpaces, negativeSpaces)
if err != nil {
return nil, errors.Trace(err)
}
addStorage2(&acquireParams, volumes)
acquireParams.AgentName = env.uuid
if zoneName != "" {
acquireParams.Zone = zoneName
}
if nodeName != "" {
acquireParams.Hostname = nodeName
}
if systemId != "" {
acquireParams.SystemId = systemId
}
machine, constraintMatches, err := env.maasController.AllocateMachine(acquireParams)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
return &maas2Instance{
machine: machine,
constraintMatches: constraintMatches,
environ: env,
}, nil
}
// acquireNode allocates a node from the MAAS.
func (env *maasEnviron) acquireNode(
ctx context.ProviderCallContext,
nodeName, zoneName, systemId string,
cons constraints.Value,
interfaces []interfaceBinding,
volumes []volumeInfo,
) (gomaasapi.MAASObject, error) {
// TODO(axw) 2014-08-18 #1358219
// We should be requesting preferred architectures if unspecified,
// like in the other providers.
//
// This is slightly complicated in MAAS as there are a finite
// number of each architecture; preference may also conflict with
// other constraints, such as tags. Thus, a preference becomes a
// demand (which may fail) if not handled properly.
acquireParams := convertConstraints(cons)
positiveSpaceNames, negativeSpaceNames := convertSpacesFromConstraints(cons.Spaces)
positiveSpaces, negativeSpaces, err := env.spaceNamesToSpaceInfo(ctx, positiveSpaceNames, negativeSpaceNames)
// If spaces aren't supported the constraints should be empty anyway.
if err != nil && !errors.IsNotSupported(err) {
return gomaasapi.MAASObject{}, errors.Trace(err)
}
err = addInterfaces(acquireParams, interfaces, positiveSpaces, negativeSpaces)
if err != nil {
return gomaasapi.MAASObject{}, errors.Trace(err)
}
addStorage(acquireParams, volumes)
acquireParams.Add("agent_name", env.uuid)
if zoneName != "" {
acquireParams.Add("zone", zoneName)
}
if nodeName != "" {
acquireParams.Add("name", nodeName)
}
if systemId != "" {
acquireParams.Add("system_id", systemId)
}
var result gomaasapi.JSONObject
for a := shortAttempt.Start(); a.Next(); {
client := env.getMAASClient().GetSubObject("nodes/")
logger.Tracef("calling acquire with params: %+v", acquireParams)
result, err = client.CallPost("acquire", acquireParams)
if err == nil {
break
}
}
if err != nil {
return gomaasapi.MAASObject{}, err
}
node, err := result.GetMAASObject()
if err != nil {
err := errors.Annotate(err, "unexpected result from 'acquire' on MAAS API")
return gomaasapi.MAASObject{}, err
}
return node, nil
}
// startNode installs and boots a node.
func (env *maasEnviron) startNode(node gomaasapi.MAASObject, series string, userdata []byte) (*gomaasapi.MAASObject, error) {
params := url.Values{
"distro_series": {series},
"user_data": {string(userdata)},
}
// Initialize err to a non-nil value as a sentinel for the following
// loop.
err := fmt.Errorf("(no error)")
var result gomaasapi.JSONObject
for a := shortAttempt.Start(); a.Next() && err != nil; {
result, err = node.CallPost("start", params)
if err == nil {
break
}
}
if err == nil {
var startedNode gomaasapi.MAASObject
startedNode, err = result.GetMAASObject()
if err != nil {
logger.Errorf("cannot process API response after successfully starting node: %v", err)
return nil, err
}
return &startedNode, nil
}
return nil, err
}
func (env *maasEnviron) startNode2(node maas2Instance, series string, userdata []byte) (*maas2Instance, error) {
err := node.machine.Start(gomaasapi.StartArgs{DistroSeries: series, UserData: string(userdata)})
if err != nil {
return nil, errors.Trace(err)
}
// Machine.Start updates the machine in-place when it succeeds.
return &maas2Instance{machine: node.machine}, nil
}
// DistributeInstances implements the state.InstanceDistributor policy.
func (env *maasEnviron) DistributeInstances(
ctx context.ProviderCallContext, candidates, distributionGroup []instance.Id, limitZones []string,
) ([]instance.Id, error) {
return common.DistributeInstances(env, ctx, candidates, distributionGroup, limitZones)
}
var availabilityZoneAllocations = common.AvailabilityZoneAllocations
// MaintainInstance is specified in the InstanceBroker interface.
func (*maasEnviron) MaintainInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) error {
return nil
}
// StartInstance is specified in the InstanceBroker interface.
func (env *maasEnviron) StartInstance(
ctx context.ProviderCallContext,
args environs.StartInstanceParams,
) (_ *environs.StartInstanceResult, err error) {
availabilityZone := args.AvailabilityZone
var nodeName, systemId string
if args.Placement != "" {
placement, err := env.parsePlacement(ctx, args.Placement)
if err != nil {
return nil, common.ZoneIndependentError(err)
}
// NOTE(axw) we wipe out args.AvailabilityZone if the
// user specified a specific node or system ID via
// placement, as placement must always take precedence.
switch {
case placement.systemId != "":
availabilityZone = ""
systemId = placement.systemId
case placement.nodeName != "":
availabilityZone = ""
nodeName = placement.nodeName
}
}
if availabilityZone != "" {
if err := common.ValidateAvailabilityZone(env, ctx, availabilityZone); err != nil {
return nil, errors.Trace(err)
}
logger.Debugf("attempting to acquire node in zone %q", availabilityZone)
}
// Storage.
volumes, err := buildMAASVolumeParameters(args.Volumes, args.Constraints)
if err != nil {
return nil, common.ZoneIndependentError(errors.Annotate(err, "invalid volume parameters"))
}
var interfaceBindings []interfaceBinding
if len(args.EndpointBindings) != 0 {
for endpoint, spaceProviderID := range args.EndpointBindings {
interfaceBindings = append(interfaceBindings, interfaceBinding{
Name: endpoint,
SpaceProviderId: string(spaceProviderID),
})
}
}
selectNode := env.selectNode2
if !env.usingMAAS2() {
selectNode = env.selectNode
}
inst, selectNodeErr := selectNode(ctx,
selectNodeArgs{
Constraints: args.Constraints,
AvailabilityZone: availabilityZone,
NodeName: nodeName,
SystemId: systemId,
Interfaces: interfaceBindings,
Volumes: volumes,
})
if selectNodeErr != nil {
err := errors.Annotate(selectNodeErr, "failed to acquire node")
if selectNodeErr.noMatch && availabilityZone != "" {
// The error was due to MAAS not being able to
// find provide a machine matching the specified