forked from juju/juju
/
environ.go
1732 lines (1559 loc) · 52.5 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 (
stdcontext "context"
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/gomaasapi/v2"
"github.com/juju/names/v4"
"github.com/juju/utils/v2"
"github.com/juju/version/v2"
"github.com/DavinZhang/juju/cloudconfig/cloudinit"
"github.com/DavinZhang/juju/cloudconfig/instancecfg"
"github.com/DavinZhang/juju/cloudconfig/providerinit"
"github.com/DavinZhang/juju/core/constraints"
"github.com/DavinZhang/juju/core/instance"
corenetwork "github.com/DavinZhang/juju/core/network"
"github.com/DavinZhang/juju/core/os"
"github.com/DavinZhang/juju/core/series"
"github.com/DavinZhang/juju/core/status"
"github.com/DavinZhang/juju/environs"
environscloudspec "github.com/DavinZhang/juju/environs/cloudspec"
"github.com/DavinZhang/juju/environs/config"
"github.com/DavinZhang/juju/environs/context"
"github.com/DavinZhang/juju/environs/instances"
"github.com/DavinZhang/juju/environs/storage"
"github.com/DavinZhang/juju/environs/tags"
"github.com/DavinZhang/juju/network"
"github.com/DavinZhang/juju/provider/common"
"github.com/DavinZhang/juju/tools"
)
const (
// The version strings indicating the MAAS API version.
apiVersion2 = "2.0"
)
// A request may fail due to "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,
}
var (
DeploymentStatusCall = deploymentStatusCall
GetMAAS2Controller = getMAAS2Controller
)
func getMAAS2Controller(maasServer, apiKey string) (gomaasapi.Controller, error) {
return gomaasapi.NewController(gomaasapi.ControllerArgs{
BaseURL: maasServer,
APIKey: apiKey,
})
}
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 corenetwork.AvailabilityZones
// 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 Capabilities
}
var _ environs.Environ = (*maasEnviron)(nil)
var _ environs.Networking = (*maasEnviron)(nil)
// Capabilities is an alias for a function that gets
// the capabilities of a MAAS installation.
type Capabilities = func(client *gomaasapi.MAASObject, serverURL string) (set.Strings, error)
func NewEnviron(cloud environscloudspec.CloudSpec, cfg *config.Config, getCaps Capabilities) (*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(stdcontext.TODO(), 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
}
// PrepareForBootstrap is part of the Environ interface.
func (env *maasEnviron) PrepareForBootstrap(_ environs.BootstrapContext, _ string) error {
return nil
}
// Create is part of the Environ interface.
func (env *maasEnviron) Create(_ context.ProviderCallContext, _ environs.CreateParams) error {
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) {
instances, err := env.instances(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(_ stdcontext.Context, spec environscloudspec.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)
}
apiVersion := apiVersion2
controller, err := GetMAAS2Controller(maasServer, maasOAuth)
if err != nil {
return errors.Trace(err)
}
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()
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
}
// 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
}
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) (corenetwork.AvailabilityZones, error) {
env.availabilityZonesMutex.Lock()
defer env.availabilityZonesMutex.Unlock()
if env.availabilityZones == nil {
availabilityZones, err := env.availabilityZones2(ctx)
if err != nil {
return nil, errors.Trace(err)
}
env.availabilityZones = availabilityZones
}
return env.availabilityZones, nil
}
func (env *maasEnviron) availabilityZones2(ctx context.ProviderCallContext) (corenetwork.AvailabilityZones, error) {
zones, err := env.maasController.Zones()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
availabilityZones := make(corenetwork.AvailabilityZones, 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) (map[instance.Id]string, error) {
instances, err := env.Instances(ctx, ids)
if err != nil && err != environs.ErrPartialInstances {
return nil, err
}
zones := make(map[instance.Id]string, 0)
for _, inst := range instances {
if inst == nil {
continue
}
mInst, ok := inst.(maasInstance)
if !ok {
continue
}
z, err := mInst.zone()
if err != nil {
logger.Errorf("could not get availability zone %v", err)
continue
}
zones[inst.Id()] = 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":
zones, err := env.AvailabilityZones(ctx)
if err != nil {
return nil, errors.Trace(err)
}
if err := zones.Validate(value); err != nil {
return nil, errors.Trace(err)
}
return &maasPlacement{zoneName: value}, 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
}
// 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(); {
ver := client.GetSubObject("version/")
result, err = ver.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 := corenetwork.ConvertSpaceName(string(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
}
// networkSpaceRequirements combines the space requirements for the application
// bindings and the specified constraints and returns a set of provider
// space IDs for which a NIC needs to be provisioned in the instance we are
// about to launch and a second (negative) set of space IDs that must not be
// present in the launched instance NICs.
func (env *maasEnviron) networkSpaceRequirements(ctx context.ProviderCallContext, endpointToProviderSpaceID map[string]corenetwork.Id, cons constraints.Value) (set.Strings, set.Strings, error) {
positiveSpaceIds := set.NewStrings()
negativeSpaceIds := set.NewStrings()
// Iterate the application bindings and add each bound space ID to the
// positive space set.
for _, providerSpaceID := range endpointToProviderSpaceID {
// The alpha space is not part of the MAAS space list. When the
// code that maps between space IDs and provider space IDs
// encounters a space that it cannot map, it passes the space
// name through.
if providerSpaceID == corenetwork.AlphaSpaceName {
continue
}
positiveSpaceIds.Add(string(providerSpaceID))
}
// Convert space constraints into a list of space IDs to include and
// a list of space IDs to omit.
positiveSpaceNames, negativeSpaceNames := convertSpacesFromConstraints(cons.Spaces)
positiveSpaceInfo, negativeSpaceInfo, err := env.spaceNamesToSpaceInfo(ctx, positiveSpaceNames, negativeSpaceNames)
if err != nil {
// Spaces are not supported by this MAAS instance.
if errors.IsNotSupported(err) {
return nil, nil, nil
}
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, nil, errors.Trace(err)
}
// Append required space IDs from constraints.
for _, si := range positiveSpaceInfo {
if si.ProviderId == "" {
continue
}
positiveSpaceIds.Add(string(si.ProviderId))
}
// Calculate negative space ID set and check for clashes with the positive set.
for _, si := range negativeSpaceInfo {
if si.ProviderId == "" {
continue
}
if positiveSpaceIds.Contains(string(si.ProviderId)) {
return nil, nil, errors.NewNotValid(nil, fmt.Sprintf("negative space %q from constraints clashes with required spaces for instance NICs", si.Name))
}
negativeSpaceIds.Add(string(si.ProviderId))
}
return positiveSpaceIds, negativeSpaceIds, nil
}
// acquireNode2 allocates a machine from MAAS2.
func (env *maasEnviron) acquireNode2(
ctx context.ProviderCallContext,
nodeName, zoneName, systemId string,
cons constraints.Value,
positiveSpaceIDs set.Strings,
negativeSpaceIDs set.Strings,
volumes []volumeInfo,
) (maasInstance, error) {
acquireParams := convertConstraints2(cons)
addInterfaces2(&acquireParams, positiveSpaceIDs, negativeSpaceIDs)
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,
positiveSpaceIDs set.Strings,
negativeSpaceIDs set.Strings,
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)
addInterfaces(acquireParams, positiveSpaceIDs, negativeSpaceIDs)
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
err error
)
for a := shortAttempt.Start(); a.Next(); {
client := env.getMAASClient().GetSubObject("nodes/")
logger.Tracef("calling acquire with params: %+v", acquireParams)
if result, err = client.CallPost("acquire", acquireParams); err == nil {
break // Got a result back.
}
}
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
}
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)
}
// 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 != "" {
zones, err := env.AvailabilityZones(ctx)
if err != nil {
return nil, errors.Trace(err)
}
if err := errors.Trace(zones.Validate(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"))
}
// Calculate network space requirements.
positiveSpaceIDs, negativeSpaceIDs, err := env.networkSpaceRequirements(ctx, args.EndpointBindings, args.Constraints)
if err != nil {
return nil, errors.Trace(err)
}
inst, selectNodeErr := env.selectNode(ctx,
selectNodeArgs{
Constraints: args.Constraints,
AvailabilityZone: availabilityZone,
NodeName: nodeName,
SystemId: systemId,
PositiveSpaceIDs: positiveSpaceIDs,
NegativeSpaceIDs: negativeSpaceIDs,
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
// constraints in the zone; try again in another.
return nil, errors.Trace(err)
}
return nil, common.ZoneIndependentError(err)
}
defer func() {
if err != nil {
if err := env.StopInstances(ctx, inst.Id()); err != nil {
logger.Errorf("error releasing failed instance: %v", err)
}
}
}()
hc, err := inst.hardwareCharacteristics()
if err != nil {
return nil, common.ZoneIndependentError(err)
}
selectedTools, err := args.Tools.Match(tools.Filter{
Arch: *hc.Arch,
})
if err != nil {
return nil, common.ZoneIndependentError(err)
}
if err := args.InstanceConfig.SetTools(selectedTools); err != nil {
return nil, common.ZoneIndependentError(err)
}
hostname, err := inst.hostname()
if err != nil {
return nil, common.ZoneIndependentError(err)
}
if err := instancecfg.FinishInstanceConfig(args.InstanceConfig, env.Config()); err != nil {
return nil, common.ZoneIndependentError(err)
}
subnetsMap, err := env.subnetToSpaceIds(ctx)
if err != nil {
return nil, common.ZoneIndependentError(err)
}
series := args.InstanceConfig.Series
cloudcfg, err := env.newCloudinitConfig(hostname, series)
if err != nil {
return nil, common.ZoneIndependentError(err)
}
userdata, err := providerinit.ComposeUserData(args.InstanceConfig, cloudcfg, MAASRenderer{})
if err != nil {
return nil, common.ZoneIndependentError(errors.Annotate(
err, "could not compose userdata for bootstrap node",
))
}
logger.Debugf("maas user data; %d bytes", len(userdata))
var displayName string
var interfaces corenetwork.InterfaceInfos
inst2 := inst.(*maas2Instance)
startedInst, err := env.startNode2(*inst2, series, userdata)
if err != nil {
return nil, common.ZoneIndependentError(err)
}
domains, err := env.Domains(ctx)
if err != nil {
return nil, errors.Trace(err)
}
interfaces, err = maasNetworkInterfaces(ctx, startedInst, subnetsMap, domains...)
if err != nil {
return nil, common.ZoneIndependentError(err)
}
env.tagInstance2(inst2, args.InstanceConfig)
displayName, err = inst2.displayName()
if err != nil {
return nil, common.ZoneIndependentError(err)
}
logger.Debugf("started instance %q", inst.Id())
requestedVolumes := make([]names.VolumeTag, len(args.Volumes))
for i, v := range args.Volumes {
requestedVolumes[i] = v.Tag
}
resultVolumes, resultAttachments, err := inst.volumes(
names.NewMachineTag(args.InstanceConfig.MachineId),
requestedVolumes,
)
if err != nil {
return nil, common.ZoneIndependentError(err)
}
if len(resultVolumes) != len(requestedVolumes) {
return nil, common.ZoneIndependentError(errors.Errorf(
"requested %v storage volumes. %v returned",
len(requestedVolumes), len(resultVolumes),
))
}
return &environs.StartInstanceResult{
DisplayName: displayName,
Instance: inst,
Hardware: hc,
NetworkInfo: interfaces,
Volumes: resultVolumes,
VolumeAttachments: resultAttachments,
}, nil
}
func (env *maasEnviron) tagInstance2(inst *maas2Instance, instanceConfig *instancecfg.InstanceConfig) {
err := inst.machine.SetOwnerData(instanceConfig.Tags)
if err != nil {
logger.Errorf("could not set owner data for instance: %v", err)
}
}
func (env *maasEnviron) waitForNodeDeployment(ctx context.ProviderCallContext, id instance.Id, timeout time.Duration) error {
// TODO(katco): 2016-08-09: lp:1611427
longAttempt := utils.AttemptStrategy{
Delay: 10 * time.Second,
Total: timeout,
}
retryCount := 1
for a := longAttempt.Start(); a.Next(); {
machine, err := env.getInstance(ctx, id)
if err != nil {
logger.Warningf("failed to get instance from provider attempt %d", retryCount)
if denied := common.MaybeHandleCredentialError(IsAuthorisationFailure, err, ctx); denied {
break
}
retryCount++
continue
}
stat := machine.Status(ctx)
if stat.Status == status.Running {
return nil
}
if stat.Status == status.ProvisioningError {
return errors.Errorf("instance %q failed to deploy", id)
}
}
return errors.Errorf("instance %q is started but not deployed", id)
}
func (env *maasEnviron) deploymentStatusOne(ctx context.ProviderCallContext, id instance.Id) (string, string) {
results, err := env.deploymentStatus(ctx, id)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return "", ""
}
systemId := extractSystemId(id)
substatus := env.getDeploymentSubstatus(ctx, systemId)
return results[systemId], substatus
}
func (env *maasEnviron) getDeploymentSubstatus(ctx context.ProviderCallContext, systemId string) string {
nodesAPI := env.getMAASClient().GetSubObject("nodes")
result, err := nodesAPI.CallGet("list", nil)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return ""
}
slices, err := result.GetArray()
if err != nil {
return ""
}
for _, slice := range slices {
resultMap, err := slice.GetMap()
if err != nil {
continue
}
sysId, err := resultMap["system_id"].GetString()
if err != nil {
continue
}
if sysId == systemId {
message, err := resultMap["substatus_message"].GetString()
if err != nil {
logger.Warningf("could not get string for substatus_message: %v", resultMap["substatus_message"])
return ""
}
return message
}
}
return ""
}
// deploymentStatus returns the deployment state of MAAS instances with
// the specified Juju instance ids.
// Note: the result is a map of MAAS systemId to state.
func (env *maasEnviron) deploymentStatus(ctx context.ProviderCallContext, ids ...instance.Id) (map[string]string, error) {
nodesAPI := env.getMAASClient().GetSubObject("nodes")
result, err := DeploymentStatusCall(nodesAPI, ids...)
if err != nil {
if err, ok := errors.Cause(err).(gomaasapi.ServerError); ok && err.StatusCode == http.StatusBadRequest {
return nil, errors.NewNotImplemented(err, "deployment status")
}
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
resultMap, err := result.GetMap()
if err != nil {
return nil, errors.Trace(err)
}
statusValues := make(map[string]string)
for systemId, jsonValue := range resultMap {
sts, err := jsonValue.GetString()
if err != nil {
return nil, errors.Trace(err)
}
statusValues[systemId] = sts
}
return statusValues, nil
}
func deploymentStatusCall(nodes gomaasapi.MAASObject, ids ...instance.Id) (gomaasapi.JSONObject, error) {
filter := getSystemIdValues("nodes", ids)
return nodes.CallGet("deployment_status", filter)
}
type selectNodeArgs struct {
AvailabilityZone string
NodeName string
SystemId string
Constraints constraints.Value
PositiveSpaceIDs set.Strings