/
environ.go
2232 lines (2071 loc) · 70 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 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package azure
import (
stdcontext "context"
"fmt"
"net/url"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v2"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/names/v5"
"github.com/juju/retry"
"github.com/juju/version/v2"
"github.com/juju/juju/agent"
"github.com/juju/juju/cloudconfig/instancecfg"
"github.com/juju/juju/cloudconfig/providerinit"
"github.com/juju/juju/core/arch"
"github.com/juju/juju/core/constraints"
"github.com/juju/juju/core/instance"
"github.com/juju/juju/core/os/ostype"
"github.com/juju/juju/environs"
environscloudspec "github.com/juju/juju/environs/cloudspec"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/environs/context"
"github.com/juju/juju/environs/instances"
"github.com/juju/juju/environs/simplestreams"
"github.com/juju/juju/environs/tags"
"github.com/juju/juju/provider/azure/internal/armtemplates"
"github.com/juju/juju/provider/azure/internal/azureauth"
"github.com/juju/juju/provider/azure/internal/errorutils"
"github.com/juju/juju/provider/azure/internal/tracing"
"github.com/juju/juju/provider/common"
"github.com/juju/juju/tools"
jujuversion "github.com/juju/juju/version"
)
const (
jujuMachineNameTag = tags.JujuTagPrefix + "machine-name"
// minRootDiskSize is the minimum root disk size Azure
// accepts for a VM's OS disk.
// It will be used if none is specified by the user.
minRootDiskSize = 30 * 1024 // 30 GiB
// serviceErrorCodeDeploymentCannotBeCancelled is the error code for
// service errors in response to an attempt to cancel a deployment
// that cannot be cancelled.
serviceErrorCodeDeploymentCannotBeCancelled = "DeploymentCannotBeCancelled"
// serviceErrorCodeResourceGroupBeingDeleted is the error code for
// service errors in response to an attempt to cancel a deployment
// that has already started to be deleted.
serviceErrorCodeResourceGroupBeingDeleted = "ResourceGroupBeingDeleted"
// controllerAvailabilitySet is the name of the availability set
// used for controller machines.
controllerAvailabilitySet = "juju-controller"
// commonDeployment is used to create resources common to all models.
commonDeployment = "common"
computeAPIVersion = "2021-11-01"
networkAPIVersion = "2018-08-01"
)
type azureEnviron struct {
environs.NoSpaceDiscoveryEnviron
// provider is the azureEnvironProvider used to open this environment.
provider *azureEnvironProvider
// cloud defines the cloud configuration for this environment.
cloud environscloudspec.CloudSpec
// location is the canonical location name. Use this instead
// of cloud.Region in API calls.
location string
// subscriptionId is the Azure account subscription ID.
subscriptionId string
// tenantId is the Azure account tenant ID.
tenantId string
// storageEndpoint is the Azure storage endpoint. This is the host
// portion of the storage endpoint URL only; use this instead of
// cloud.StorageEndpoint in API calls.
storageEndpoint string
// resourceGroup is the name of the Resource Group in the Azure
// subscription that corresponds to the environment.
resourceGroup string
// modelName is the name of the model.
modelName string
// namespace is used to create the machine and device hostnames.
namespace instance.Namespace
clientOptions policy.ClientOptions
credential azcore.TokenCredential
mu sync.Mutex
config *azureModelConfig
instanceTypes map[string]instances.InstanceType
commonResourcesCreated bool
}
var _ environs.Environ = (*azureEnviron)(nil)
// SetCloudSpec is specified in the environs.Environ interface.
func (env *azureEnviron) SetCloudSpec(ctx stdcontext.Context, cloud environscloudspec.CloudSpec) error {
if err := validateCloudSpec(cloud); err != nil {
return errors.Annotate(err, "validating cloud spec")
}
env.mu.Lock()
defer env.mu.Unlock()
// The Azure storage code wants the endpoint host only, not the URL.
storageEndpointURL, err := url.Parse(cloud.StorageEndpoint)
if err != nil {
return errors.Annotate(err, "parsing storage endpoint URL")
}
env.cloud = cloud
env.location = canonicalLocation(cloud.Region)
env.storageEndpoint = storageEndpointURL.Host
if err := env.initEnviron(ctx); err != nil {
return errors.Trace(err)
}
cfg := env.config
if env.resourceGroup == "" {
env.resourceGroup = cfg.resourceGroupName
}
// If no user specified resource group, make one from the model UUID.
if env.resourceGroup == "" {
modelTag := names.NewModelTag(cfg.UUID())
if env.resourceGroup, err = env.resourceGroupName(ctx, modelTag, cfg.Name()); err != nil {
return errors.Trace(err)
}
}
env.modelName = cfg.Name()
return nil
}
func (env *azureEnviron) initEnviron(ctx stdcontext.Context) error {
credAttrs := env.cloud.Credential.Attributes()
env.subscriptionId = credAttrs[credAttrManagedSubscriptionId]
if env.subscriptionId == "" {
env.subscriptionId = credAttrs[credAttrSubscriptionId]
}
env.clientOptions = azcore.ClientOptions{
Cloud: azureCloud(env.cloud.Name, env.cloud.Endpoint, env.cloud.IdentityEndpoint),
PerCallPolicies: []policy.Policy{
&tracing.LoggingPolicy{
Logger: logger.Child("azureapi"),
},
},
Telemetry: policy.TelemetryOptions{
ApplicationID: "Juju/" + jujuversion.Current.String(),
},
Transport: env.provider.config.Sender,
Retry: env.provider.config.Retry,
}
if env.provider.config.RequestInspector != nil {
env.clientOptions.PerCallPolicies = append(env.clientOptions.PerCallPolicies, env.provider.config.RequestInspector)
}
tenantID, err := azureauth.DiscoverTenantID(ctx, env.subscriptionId, arm.ClientOptions{
ClientOptions: env.clientOptions,
})
if err != nil {
return errors.Annotate(err, "getting tenant ID")
}
logger.Debugf("discovered tenant id: %s", tenantID)
env.tenantId = tenantID
appId := credAttrs[credAttrAppId]
appPassword := credAttrs[credAttrAppPassword]
env.credential, err = env.provider.config.CreateTokenCredential(appId, appPassword, tenantID, env.clientOptions)
if err != nil {
return errors.Annotate(err, "set up credential")
}
return nil
}
// PrepareForBootstrap is part of the Environ interface.
func (env *azureEnviron) PrepareForBootstrap(ctx environs.BootstrapContext, _ string) error {
if ctx.ShouldVerifyCredentials() {
cloudCtx := &context.CloudCallContext{
Context: ctx.Context(),
InvalidateCredentialFunc: func(string) error { return nil },
}
if err := verifyCredentials(env, cloudCtx); err != nil {
return errors.Trace(err)
}
}
return nil
}
// Create is part of the Environ interface.
func (env *azureEnviron) Create(ctx context.ProviderCallContext, args environs.CreateParams) error {
if err := verifyCredentials(env, ctx); err != nil {
return errors.Trace(err)
}
return errors.Trace(env.initResourceGroup(ctx, args.ControllerUUID, env.config.resourceGroupName != "", false))
}
// Bootstrap is part of the Environ interface.
func (env *azureEnviron) Bootstrap(
ctx environs.BootstrapContext,
callCtx context.ProviderCallContext,
args environs.BootstrapParams,
) (*environs.BootstrapResult, error) {
if err := env.initResourceGroup(callCtx, args.ControllerConfig.ControllerUUID(), env.config.resourceGroupName != "", true); err != nil {
return nil, errors.Annotate(err, "creating controller resource group")
}
result, err := common.Bootstrap(ctx, env, callCtx, args)
if err != nil {
logger.Errorf("bootstrap failed, destroying model: %v", err)
// First cancel the in-progress deployment.
var wg sync.WaitGroup
var cancelResult error
logger.Debugf("canceling deployment for bootstrap instance")
wg.Add(1)
go func(id string) {
defer wg.Done()
cancelResult = errors.Annotatef(
env.cancelDeployment(callCtx, id),
"canceling deployment %q", id,
)
}(names.NewMachineTag(agent.BootstrapControllerId).String())
wg.Wait()
if cancelResult != nil && !errors.IsNotFound(cancelResult) {
return nil, errors.Annotate(cancelResult, "aborting failed bootstrap")
}
// Then cleanup the resource group.
if err := env.Destroy(callCtx); err != nil {
logger.Errorf("failed to destroy model: %v", err)
}
return nil, errors.Trace(err)
}
return result, nil
}
// initResourceGroup creates a resource group for this environment.
func (env *azureEnviron) initResourceGroup(ctx context.ProviderCallContext, controllerUUID string, existingResourceGroup, controller bool) error {
env.mu.Lock()
resourceTags := tags.ResourceTags(
names.NewModelTag(env.config.Config.UUID()),
names.NewControllerTag(controllerUUID),
env.config,
)
env.mu.Unlock()
resourceGroups, err := env.resourceGroupsClient()
if err != nil {
return errors.Trace(err)
}
if existingResourceGroup {
logger.Debugf("using existing resource group %q for model %q", env.resourceGroup, env.modelName)
g, err := resourceGroups.Get(ctx, env.resourceGroup, nil)
if err != nil {
return errorutils.HandleCredentialError(errors.Annotatef(err, "checking resource group %q", env.resourceGroup), ctx)
}
if region := toValue(g.Location); region != env.location {
return errors.Errorf("cannot use resource group in region %q when operating in region %q", region, env.location)
}
} else {
logger.Debugf("creating resource group %q for model %q", env.resourceGroup, env.modelName)
if _, err := resourceGroups.CreateOrUpdate(ctx, env.resourceGroup, armresources.ResourceGroup{
Location: to.Ptr(env.location),
Tags: toMapPtr(resourceTags),
}, nil); err != nil {
return errorutils.HandleCredentialError(errors.Annotate(err, "creating resource group"), ctx)
}
}
if !controller {
// When we create a resource group for a non-controller model,
// we must create the common resources up-front. This is so
// that parallel deployments do not affect dynamic changes,
// e.g. those made by the firewaller. For the controller model,
// we fold the creation of these resources into the bootstrap
// machine's deployment.
if err := env.createCommonResourceDeployment(ctx, resourceTags, nil); err != nil {
return errors.Trace(err)
}
}
return nil
}
func (env *azureEnviron) createCommonResourceDeployment(
ctx context.ProviderCallContext,
tags map[string]string,
rules []*armnetwork.SecurityRule,
commonResources ...armtemplates.Resource,
) error {
// Only create network resources if the user has not
// specified their own to use.
if env.config.virtualNetworkName == "" {
networkResources, _ := networkTemplateResources(env.location, tags, nil, rules)
commonResources = append(commonResources, networkResources...)
}
if len(commonResources) == 0 {
return nil
}
template := armtemplates.Template{Resources: commonResources}
if err := env.createDeployment(
ctx,
env.resourceGroup,
commonDeployment,
template,
); err != nil {
return errors.Trace(err)
}
return nil
}
// ControllerInstances is specified in the Environ interface.
func (env *azureEnviron) ControllerInstances(ctx context.ProviderCallContext, controllerUUID string) ([]instance.Id, error) {
inst, err := env.allInstances(ctx, env.resourceGroup, false, controllerUUID)
if err != nil {
return nil, err
}
if len(inst) == 0 {
return nil, environs.ErrNoInstances
}
ids := make([]instance.Id, len(inst))
for i, inst := range inst {
ids[i] = inst.Id()
}
return ids, nil
}
// Config is specified in the Environ interface.
func (env *azureEnviron) Config() *config.Config {
env.mu.Lock()
defer env.mu.Unlock()
return env.config.Config
}
// SetConfig is specified in the Environ interface.
func (env *azureEnviron) SetConfig(cfg *config.Config) error {
env.mu.Lock()
defer env.mu.Unlock()
var old *config.Config
if env.config != nil {
old = env.config.Config
}
ecfg, err := validateConfig(cfg, old)
if err != nil {
return err
}
env.config = ecfg
return nil
}
var unsupportedConstraints = []string{
constraints.CpuPower,
constraints.Tags,
constraints.VirtType,
constraints.ImageID,
}
// ConstraintsValidator is defined on the Environs interface.
func (env *azureEnviron) ConstraintsValidator(ctx context.ProviderCallContext) (constraints.Validator, error) {
instanceTypes, err := env.getInstanceTypes(ctx)
if err != nil {
return nil, err
}
instTypeNames := make([]string, 0, len(instanceTypes))
for instTypeName := range instanceTypes {
instTypeNames = append(instTypeNames, instTypeName)
}
sort.Strings(instTypeNames)
validator := constraints.NewValidator()
validator.RegisterUnsupported(unsupportedConstraints)
validator.RegisterVocabulary(
constraints.Arch,
[]string{arch.AMD64},
)
validator.RegisterVocabulary(
constraints.InstanceType,
instTypeNames,
)
validator.RegisterConflicts(
[]string{constraints.InstanceType},
[]string{
constraints.Mem,
constraints.Cores,
// TODO: move to a dynamic conflict for arch when azure supports more than amd64
//constraints.Arch,
},
)
return validator, nil
}
// PrecheckInstance is defined on the environs.InstancePrechecker interface.
func (env *azureEnviron) PrecheckInstance(ctx context.ProviderCallContext, args environs.PrecheckInstanceParams) error {
if _, err := env.findPlacementSubnet(ctx, args.Placement); err != nil {
return errors.Trace(err)
}
if !args.Constraints.HasInstanceType() {
return nil
}
// Constraint has an instance-type constraint so let's see if it is valid.
instanceTypes, err := env.getInstanceTypes(ctx)
if err != nil {
return err
}
for _, instanceType := range instanceTypes {
if instanceType.Name == *args.Constraints.InstanceType {
return nil
}
}
return fmt.Errorf("invalid instance type %q", *args.Constraints.InstanceType)
}
// StartInstance is specified in the InstanceBroker interface.
func (env *azureEnviron) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (*environs.StartInstanceResult, error) {
if args.ControllerUUID == "" {
return nil, errors.New("missing controller UUID")
}
// Get the required configuration and config-dependent information
// required to create the instance. We take the lock just once, to
// ensure we obtain all information based on the same configuration.
env.mu.Lock()
envTags := tags.ResourceTags(
names.NewModelTag(env.config.Config.UUID()),
names.NewControllerTag(args.ControllerUUID),
env.config,
)
imageStream := env.config.ImageStream()
envInstanceTypes, err := env.getInstanceTypesLocked(ctx)
if err != nil {
env.mu.Unlock()
return nil, errors.Trace(err)
}
instanceTypes := make(map[string]instances.InstanceType)
for k, v := range envInstanceTypes {
instanceTypes[k] = v
}
env.mu.Unlock()
// If the user has not specified a root-disk size, then
// set a sensible default.
var rootDisk uint64
// Azure complains if we try and specify a root disk size less than the minimum.
// See http://pad.lv/1645408
if args.Constraints.RootDisk != nil && *args.Constraints.RootDisk > minRootDiskSize {
rootDisk = *args.Constraints.RootDisk
} else {
rootDisk = minRootDiskSize
args.Constraints.RootDisk = &rootDisk
}
// Start the instance - if we get a quota error, that instance type is ignored
// and we'll try the next most expensive one, up to a reasonable number of attempts.
arch, err := args.Tools.OneArch()
if err != nil {
return nil, errors.Trace(err)
}
for i := 0; i < 15; i++ {
// Identify the instance type and image to provision.
instanceSpec, err := env.findInstanceSpec(
ctx,
instanceTypes,
&instances.InstanceConstraint{
Region: env.location,
Base: args.InstanceConfig.Base,
Arch: arch,
Constraints: args.Constraints,
},
imageStream,
)
if err != nil {
return nil, err
}
if rootDisk < instanceSpec.InstanceType.RootDisk {
// The InstanceType's RootDisk is set to the maximum
// OS disk size; override it with the user-specified
// or default root disk size.
instanceSpec.InstanceType.RootDisk = rootDisk
}
result, err := env.startInstance(ctx, args, instanceSpec, envTags)
quotaErr, ok := errorutils.MaybeQuotaExceededError(err)
if ok {
logger.Warningf("%v quota exceeded error: %q", instanceSpec.InstanceType.Name, quotaErr.Error())
deleteInstanceFamily(instanceTypes, instanceSpec.InstanceType.Name)
continue
}
return result, errorutils.SimpleError(err)
}
return nil, errors.New("no suitable instance type found for this subscription")
}
func (env *azureEnviron) startInstance(
ctx context.ProviderCallContext, args environs.StartInstanceParams,
instanceSpec *instances.InstanceSpec, envTags map[string]string,
) (*environs.StartInstanceResult, error) {
// Pick tools by filtering the available tools down to the architecture of
// the image that will be provisioned.
selectedTools, err := args.Tools.Match(tools.Filter{
Arch: instanceSpec.Image.Arch,
})
if err != nil {
return nil, errors.Trace(err)
}
logger.Infof("picked agent binaries %q", selectedTools[0].Version)
// Finalize the instance config, which we'll render to CustomData below.
if err := args.InstanceConfig.SetTools(selectedTools); err != nil {
return nil, errors.Trace(err)
}
if err := instancecfg.FinishInstanceConfig(
args.InstanceConfig, env.Config(),
); err != nil {
return nil, err
}
vmName, err := env.namespace.Hostname(args.InstanceConfig.MachineId)
if err != nil {
return nil, errors.Trace(err)
}
vmTags := make(map[string]string)
for k, v := range args.InstanceConfig.Tags {
vmTags[k] = v
}
// jujuMachineNameTag identifies the VM name, in which is encoded
// the Juju machine name. We tag all resources related to the
// machine with this.
vmTags[jujuMachineNameTag] = vmName
// Use a public IP by default unless a constraint
// explicitly forbids it.
usePublicIP := true
if args.Constraints.HasAllocatePublicIP() {
usePublicIP = *args.Constraints.AllocatePublicIP
}
err = env.createVirtualMachine(
ctx, vmName, vmTags, envTags,
instanceSpec, args, usePublicIP, true,
)
// If there's a conflict, it's because another machine is
// being provisioned with the same availability set so
// retry and do not create the availability set.
if errorutils.IsConflictError(err) {
logger.Debugf("conflict creating %s, retrying...", vmName)
err = env.createVirtualMachine(
ctx, vmName, vmTags, envTags,
instanceSpec, args, usePublicIP, false,
)
}
if err != nil {
logger.Debugf("creating instance failed, destroying: %v", err)
if err := env.StopInstances(ctx, instance.Id(vmName)); err != nil {
logger.Errorf("could not destroy failed virtual machine: %v", err)
}
return nil, errors.Annotatef(err, "creating virtual machine %q", vmName)
}
// Note: the instance is initialised without addresses to keep the
// API chatter down. We will refresh the instance if we need to know
// the addresses.
inst := &azureInstance{
vmName: vmName,
provisioningState: armresources.ProvisioningStateCreating,
env: env,
}
amd64 := arch.AMD64
hc := &instance.HardwareCharacteristics{
Arch: &amd64,
Mem: &instanceSpec.InstanceType.Mem,
RootDisk: &instanceSpec.InstanceType.RootDisk,
CpuCores: &instanceSpec.InstanceType.CpuCores,
}
return &environs.StartInstanceResult{
Instance: inst,
Hardware: hc,
}, nil
}
// referenceInfo splits a reference to an Azure entity into an
// optional resource group and name, or just name if no
// resource group is specified.
func referenceInfo(entityRef string) (entityRG, entityName string) {
parts := strings.Split(entityRef, "/")
if len(parts) == 1 {
return "", entityRef
}
return parts[0], parts[1]
}
// createVirtualMachine creates a virtual machine and related resources.
//
// All resources created are tagged with the specified "vmTags", so if
// this function fails then all resources can be deleted by tag.
func (env *azureEnviron) createVirtualMachine(
ctx context.ProviderCallContext,
vmName string,
vmTags, envTags map[string]string,
instanceSpec *instances.InstanceSpec,
args environs.StartInstanceParams,
usePublicIP bool,
createAvailabilitySet bool,
) error {
instanceConfig := args.InstanceConfig
apiPorts := make([]int, 0, 2)
if instanceConfig.IsController() {
apiPorts = append(apiPorts, instanceConfig.ControllerConfig.APIPort())
if instanceConfig.ControllerConfig.AutocertDNSName() != "" {
// Open port 80 as well as it handles Let's Encrypt HTTP challenge.
apiPorts = append(apiPorts, 80)
}
} else {
ports := instanceConfig.APIInfo.Ports()
if len(ports) != 1 {
return errors.Errorf("expected one API port, found %v", ports)
}
apiPorts = append(apiPorts, ports[0])
}
var nicDependsOn, vmDependsOn []string
var res []armtemplates.Resource
bootstrapping := instanceConfig.Bootstrap != nil
// We only need to deal with creating network resources
// if the user has not specified their own to use.
if bootstrapping && env.config.virtualNetworkName == "" && args.Placement == "" {
// We're starting the bootstrap machine, so we will create the
// networking resources in the same deployment.
networkResources, dependsOn := networkTemplateResources(env.location, envTags, apiPorts, nil)
res = append(res, networkResources...)
nicDependsOn = append(nicDependsOn, dependsOn...)
}
if !bootstrapping {
// Wait for the common resource deployment to complete.
if err := env.waitCommonResourcesCreated(ctx); err != nil {
return errors.Annotate(
err, "waiting for common resources to be created",
)
}
}
osProfile, seriesOS, err := newOSProfile(
vmName, instanceConfig,
env.provider.config.GenerateSSHKey,
)
if err != nil {
return errors.Annotate(err, "creating OS profile")
}
storageProfile, err := newStorageProfile(
vmName,
instanceSpec,
)
if err != nil {
return errors.Annotate(err, "creating storage profile")
}
diskEncryptionID, err := env.diskEncryptionInfo(ctx, args.RootDisk, envTags)
if err != nil {
return environs.ZoneIndependentError(fmt.Errorf("creating disk encryption info: %w", err))
}
if diskEncryptionID != "" && storageProfile.OSDisk.ManagedDisk != nil {
storageProfile.OSDisk.ManagedDisk.DiskEncryptionSet = &armcompute.DiskEncryptionSetParameters{
ID: to.Ptr(diskEncryptionID),
}
}
var availabilitySetSubResource *armcompute.SubResource
availabilitySetName, err := availabilitySetName(
vmName, vmTags, instanceConfig.IsController(),
)
if err != nil {
return errors.Annotate(err, "getting availability set name")
}
availabilitySetId := fmt.Sprintf(
`[resourceId('Microsoft.Compute/availabilitySets','%s')]`,
availabilitySetName,
)
if availabilitySetName != "" {
availabilitySetSubResource = &armcompute.SubResource{
ID: to.Ptr(availabilitySetId),
}
}
if !createAvailabilitySet && availabilitySetName != "" {
availabilitySet, err := env.availabilitySetsClient()
if err != nil {
return errors.Trace(err)
}
if _, err = availabilitySet.Get(ctx, env.resourceGroup, availabilitySetName, nil); err != nil {
return errors.Annotatef(err, "expecting availability set %q to be available", availabilitySetName)
}
}
if createAvailabilitySet && availabilitySetName != "" {
availabilitySetProperties := &armcompute.AvailabilitySetProperties{
// Azure complains when the fault domain count
// is not specified, even though it is meant
// to be optional and default to the maximum.
// The maximum depends on the location, and
// there is no API to query it.
PlatformFaultDomainCount: to.Ptr(maxFaultDomains(env.location)),
}
res = append(res, armtemplates.Resource{
APIVersion: computeAPIVersion,
Type: "Microsoft.Compute/availabilitySets",
Name: availabilitySetName,
Location: env.location,
Tags: envTags,
Properties: availabilitySetProperties,
Sku: &armtemplates.Sku{Name: "Aligned"},
})
vmDependsOn = append(vmDependsOn, availabilitySetId)
}
placementSubnetID, err := env.findPlacementSubnet(ctx, args.Placement)
if err != nil {
return environs.ZoneIndependentError(err)
}
vnetId, subnetIds, err := env.networkInfoForInstance(ctx, args, bootstrapping, instanceConfig.IsController(), placementSubnetID)
if err != nil {
return environs.ZoneIndependentError(err)
}
logger.Debugf("creating instance using vnet %v, subnets %q", vnetId, subnetIds)
if env.config.virtualNetworkName == "" && bootstrapping {
nicDependsOn = append(nicDependsOn, vnetId)
}
var publicIPAddressId string
if usePublicIP {
publicIPAddressName := vmName + "-public-ip"
publicIPAddressId = fmt.Sprintf(`[resourceId('Microsoft.Network/publicIPAddresses', '%s')]`, publicIPAddressName)
// Default to static public IP so address is preserved across reboots.
publicIPAddressAllocationMethod := armnetwork.IPAllocationMethodStatic
if env.config.loadBalancerSkuName == string(armnetwork.LoadBalancerSKUNameBasic) {
publicIPAddressAllocationMethod = armnetwork.IPAllocationMethodDynamic // preserve the settings that were used in Juju 2.4 and earlier
}
res = append(res, armtemplates.Resource{
APIVersion: networkAPIVersion,
Type: "Microsoft.Network/publicIPAddresses",
Name: publicIPAddressName,
Location: env.location,
Tags: vmTags,
Sku: &armtemplates.Sku{Name: env.config.loadBalancerSkuName},
Properties: &armnetwork.PublicIPAddressPropertiesFormat{
PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4),
PublicIPAllocationMethod: to.Ptr(publicIPAddressAllocationMethod),
},
})
}
// Create one NIC per subnet. The first one is the primary and has
// the public IP address if so configured.
var nics []*armcompute.NetworkInterfaceReference
for i, subnetID := range subnetIds {
primary := i == 0
ipConfig := &armnetwork.InterfaceIPConfigurationPropertiesFormat{
Primary: to.Ptr(primary),
PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic),
Subnet: &armnetwork.Subnet{ID: to.Ptr(string(subnetID))},
}
if primary && usePublicIP {
ipConfig.PublicIPAddress = &armnetwork.PublicIPAddress{
ID: to.Ptr(publicIPAddressId),
}
nicDependsOn = append(nicDependsOn, publicIPAddressId)
}
ipConfigName := "primary"
if i > 0 {
ipConfigName = fmt.Sprintf("interface-%d", i)
}
nicName := vmName + "-" + ipConfigName
nicId := fmt.Sprintf(`[resourceId('Microsoft.Network/networkInterfaces', '%s')]`, nicName)
ipConfigurations := []*armnetwork.InterfaceIPConfiguration{{
Name: to.Ptr(ipConfigName),
Properties: ipConfig,
}}
res = append(res, armtemplates.Resource{
APIVersion: networkAPIVersion,
Type: "Microsoft.Network/networkInterfaces",
Name: nicName,
Location: env.location,
Tags: vmTags,
Properties: &armnetwork.InterfacePropertiesFormat{
IPConfigurations: ipConfigurations,
},
DependsOn: nicDependsOn,
})
vmDependsOn = append(vmDependsOn, nicId)
nics = append(nics, &armcompute.NetworkInterfaceReference{
ID: to.Ptr(nicId),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(primary),
},
})
}
res = append(res, armtemplates.Resource{
APIVersion: computeAPIVersion,
Type: "Microsoft.Compute/virtualMachines",
Name: vmName,
Location: env.location,
Tags: vmTags,
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypes(
instanceSpec.InstanceType.Name,
)),
},
StorageProfile: storageProfile,
OSProfile: osProfile,
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: nics,
},
AvailabilitySet: availabilitySetSubResource,
},
DependsOn: vmDependsOn,
})
// On CentOS, we must add the CustomScript VM extension to run the
// CustomData script.
if seriesOS == ostype.CentOS {
properties, err := vmExtensionProperties(seriesOS)
if err != nil {
return errors.Annotate(
err, "creating virtual machine extension",
)
}
res = append(res, armtemplates.Resource{
APIVersion: computeAPIVersion,
Type: "Microsoft.Compute/virtualMachines/extensions",
Name: vmName + "/" + extensionName,
Location: env.location,
Tags: vmTags,
Properties: properties,
DependsOn: []string{"Microsoft.Compute/virtualMachines/" + vmName},
})
}
logger.Debugf("- creating virtual machine deployment in %q", env.resourceGroup)
template := armtemplates.Template{Resources: res}
if err := env.createDeployment(
ctx,
env.resourceGroup,
vmName, // deployment name
template,
); err != nil {
return errors.Trace(err)
}
return nil
}
// maxFaultDomains returns the maximum number of fault domains for the
// given location/region. The numbers were taken from
// https://docs.microsoft.com/en-au/azure/virtual-machines/windows/manage-availability,
// as at 31 August 2017.
func maxFaultDomains(location string) int32 {
// From the page linked in the doc comment:
// "The number of fault domains for managed availability sets varies
// by region - either two or three per region."
//
// We record those that at the time of writing have 3. Anything
// else has at least 2, so we just assume 2.
switch location {
case
"eastus",
"eastus2",
"westus",
"centralus",
"northcentralus",
"southcentralus",
"northeurope",
"westeurope":
return 3
}
return 2
}
// waitCommonResourcesCreated waits for the "common" deployment to complete.
func (env *azureEnviron) waitCommonResourcesCreated(ctx context.ProviderCallContext) error {
env.mu.Lock()
defer env.mu.Unlock()
if env.commonResourcesCreated {
return nil
}
if _, err := env.waitCommonResourcesCreatedLocked(ctx); err != nil {
return errors.Trace(err)
}
env.commonResourcesCreated = true
return nil
}
type deploymentIncompleteError struct {
error
}
func (env *azureEnviron) waitCommonResourcesCreatedLocked(ctx context.ProviderCallContext) (*armresources.DeploymentExtended, error) {
// Release the lock while we're waiting, to avoid blocking others.
env.mu.Unlock()
defer env.mu.Lock()
deploy, err := env.deployClient()
if err != nil {
return nil, errors.Trace(err)
}
// Wait for up to 5 minutes, with a 5 second polling interval,
// for the "common" deployment to be in one of the terminal
// states. The deployment typically takes only around 30 seconds,
// but we allow for a longer duration to be defensive.
var deployment *armresources.DeploymentExtended
waitDeployment := func() error {
result, err := deploy.Get(ctx, env.resourceGroup, commonDeployment, nil)
if err != nil {
if errorutils.IsNotFoundError(err) {
// The controller model, and also models with bespoke
// networks, do not have a "common" deployment
// For controller models, common resources are created
// in the machine-0 deployment to keep bootstrap times optimal.
return nil
}
return errors.Annotate(err, "querying common deployment")
}
if result.Properties == nil {
return deploymentIncompleteError{errors.New("deployment incomplete")}
}
state := toValue(result.Properties.ProvisioningState)
if state == armresources.ProvisioningStateSucceeded {
// The deployment has succeeded, so the resources are
// ready for use.
deployment = to.Ptr(result.DeploymentExtended)
return nil
}
err = errors.Errorf("%q resource deployment status is %q", commonDeployment, state)
switch state {
case armresources.ProvisioningStateCanceled,
armresources.ProvisioningStateFailed,
armresources.ProvisioningStateDeleted:
default:
err = deploymentIncompleteError{err}
}
return err
}
if err := retry.Call(retry.CallArgs{
Func: waitDeployment,
IsFatalError: func(err error) bool {
_, ok := err.(deploymentIncompleteError)
return !ok
},
Attempts: -1,
Delay: 5 * time.Second,
MaxDuration: 5 * time.Minute,
Clock: env.provider.config.RetryClock,
}); err != nil {
return nil, errors.Trace(err)
}
return deployment, nil
}
// createAvailabilitySet creates the availability set for a machine to use
// if it doesn't already exist, and returns the availability set's ID. The
// algorithm used for choosing the availability set is:
// - if the machine is a controller, use the availability set name
// "juju-controller";
// - if the machine has units assigned, create an availability
// name with a name based on the value of the tags.JujuUnitsDeployed tag
// in vmTags, if it exists;
// - otherwise, do not assign the machine to an availability set
func availabilitySetName(
vmName string,
vmTags map[string]string,
controller bool,
) (string, error) {