/
environ.go
1304 lines (1183 loc) · 41.7 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 azure
import (
"encoding/base64"
"fmt"
"net/http"
"regexp"
"strings"
"sync"
"time"
"github.com/juju/errors"
"github.com/juju/utils"
"github.com/juju/utils/set"
"launchpad.net/gwacl"
"github.com/juju/juju/cloudconfig/instancecfg"
"github.com/juju/juju/constraints"
"github.com/juju/juju/environs"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/environs/imagemetadata"
"github.com/juju/juju/environs/instances"
"github.com/juju/juju/environs/simplestreams"
"github.com/juju/juju/environs/storage"
"github.com/juju/juju/instance"
"github.com/juju/juju/network"
"github.com/juju/juju/provider/common"
"github.com/juju/juju/state"
"github.com/juju/juju/state/multiwatcher"
)
const (
// deploymentSlot says in which slot to deploy instances. Azure
// supports 'Production' or 'Staging'.
// This provider always deploys to Production. Think twice about
// changing that: DNS names in the staging slot work differently from
// those in the production slot. In Staging, Azure assigns an
// arbitrary hostname that we can then extract from the deployment's
// URL. In Production, the hostname in the deployment URL does not
// actually seem to resolve; instead, the service name is used as the
// DNS name, with ".cloudapp.net" appended.
deploymentSlot = "Production"
// Address space of the virtual network used by the nodes in this
// environement, in CIDR notation. This is the network used for
// machine-to-machine communication.
networkDefinition = "10.0.0.0/8"
// stateServerLabel is the label applied to the cloud service created
// for state servers.
stateServerLabel = "juju-state-server"
)
// vars for testing purposes.
var (
createInstance = (*azureEnviron).createInstance
)
type azureEnviron struct {
// Except where indicated otherwise, all fields in this object should
// only be accessed using a lock or a snapshot.
sync.Mutex
// archMutex gates access to supportedArchitectures
archMutex sync.Mutex
// supportedArchitectures caches the architectures
// for which images can be instantiated.
supportedArchitectures []string
// ecfg is the environment's Azure-specific configuration.
ecfg *azureEnvironConfig
// storage is this environ's own private storage.
storage storage.Storage
// storageAccountKey holds an access key to this environment's
// private storage. This is automatically queried from Azure on
// startup.
storageAccountKey string
// api is a management API for Microsoft Azure.
api *gwacl.ManagementAPI
// vnet describes the configured virtual network.
vnet *gwacl.VirtualNetworkSite
// availableRoleSizes is the role sizes available in the configured
// location. This will be reset whenever the location configuration changes.
availableRoleSizes set.Strings
}
// azureEnviron implements Environ and HasRegion.
var _ environs.Environ = (*azureEnviron)(nil)
var _ simplestreams.HasRegion = (*azureEnviron)(nil)
var _ state.Prechecker = (*azureEnviron)(nil)
// NewEnviron creates a new azureEnviron.
func NewEnviron(cfg *config.Config) (*azureEnviron, error) {
var env azureEnviron
err := env.SetConfig(cfg)
if err != nil {
return nil, err
}
// Set up storage.
env.storage = &azureStorage{
storageContext: &environStorageContext{environ: &env},
}
return &env, nil
}
// extractStorageKey returns the primary account key from a gwacl
// StorageAccountKeys struct, or if there is none, the secondary one.
func extractStorageKey(keys *gwacl.StorageAccountKeys) string {
if keys.Primary != "" {
return keys.Primary
}
return keys.Secondary
}
// queryStorageAccountKey retrieves the storage account's key from Azure.
func (env *azureEnviron) queryStorageAccountKey() (string, error) {
snap := env.getSnapshot()
accountName := snap.ecfg.storageAccountName()
keys, err := snap.api.GetStorageAccountKeys(accountName)
if err != nil {
return "", errors.Annotate(err, "cannot obtain storage account keys")
}
key := extractStorageKey(keys)
if key == "" {
return "", errors.New("no keys available for storage account")
}
return key, nil
}
// getSnapshot produces an atomic shallow copy of the environment object.
// Whenever you need to access the environment object's fields without
// modifying them, get a snapshot and read its fields instead. You will
// get a consistent view of the fields without any further locking.
// If you do need to modify the environment's fields, do not get a snapshot
// but lock the object throughout the critical section.
func (env *azureEnviron) getSnapshot() *azureEnviron {
env.Lock()
defer env.Unlock()
// Copy the environment. (Not the pointer, the environment itself.)
// This is a shallow copy.
snap := *env
// Reset the snapshot's mutex, because we just copied it while we
// were holding it. The snapshot will have a "clean," unlocked mutex.
snap.Mutex = sync.Mutex{}
return &snap
}
// getAffinityGroupName returns the name of the affinity group used by all
// the Services in this environment. The affinity group name is immutable,
// so there is no need to use a configuration snapshot.
func (env *azureEnviron) getAffinityGroupName() string {
return env.getEnvPrefix() + "ag"
}
// getLocation gets the configured Location for the environment.
func (env *azureEnviron) getLocation() string {
snap := env.getSnapshot()
return snap.ecfg.location()
}
func (env *azureEnviron) createAffinityGroup() error {
snap := env.getSnapshot()
affinityGroupName := env.getAffinityGroupName()
location := snap.ecfg.location()
cag := gwacl.NewCreateAffinityGroup(affinityGroupName, affinityGroupName, affinityGroupName, location)
return snap.api.CreateAffinityGroup(&gwacl.CreateAffinityGroupRequest{
CreateAffinityGroup: cag,
})
}
func (env *azureEnviron) deleteAffinityGroup() error {
snap := env.getSnapshot()
affinityGroupName := env.getAffinityGroupName()
return snap.api.DeleteAffinityGroup(&gwacl.DeleteAffinityGroupRequest{
Name: affinityGroupName,
})
}
// getAvailableRoleSizes returns the role sizes available for the configured
// location.
func (env *azureEnviron) getAvailableRoleSizes() (_ set.Strings, err error) {
defer errors.DeferredAnnotatef(&err, "cannot get available role sizes")
snap := env.getSnapshot()
if snap.availableRoleSizes != nil {
return snap.availableRoleSizes, nil
}
locations, err := snap.api.ListLocations()
if err != nil {
return nil, errors.Annotate(err, "cannot list locations")
}
var available set.Strings
for _, location := range locations {
if location.Name != snap.ecfg.location() {
continue
}
if location.ComputeCapabilities == nil {
return nil, errors.Annotate(err, "cannot determine compute capabilities")
}
available = set.NewStrings(location.ComputeCapabilities.VirtualMachineRoleSizes...)
break
}
if available == nil {
return nil, errors.NotFoundf("location %q", snap.ecfg.location())
}
env.Lock()
env.availableRoleSizes = available
env.Unlock()
return available, nil
}
// getVirtualNetworkName returns the name of the virtual network used by all
// the VMs in this environment. The virtual network name is immutable,
// so there is no need to use a configuration snapshot.
func (env *azureEnviron) getVirtualNetworkName() string {
return env.getEnvPrefix() + "vnet"
}
// getVirtualNetwork returns the virtual network used by all the VMs in this
// environment.
func (env *azureEnviron) getVirtualNetwork() (*gwacl.VirtualNetworkSite, error) {
snap := env.getSnapshot()
if snap.vnet != nil {
return snap.vnet, nil
}
cfg, err := env.api.GetNetworkConfiguration()
if err != nil {
return nil, errors.Annotate(err, "error getting network configuration")
}
var vnet *gwacl.VirtualNetworkSite
vnetName := env.getVirtualNetworkName()
if cfg != nil && cfg.VirtualNetworkSites != nil {
for _, site := range *cfg.VirtualNetworkSites {
if site.Name == vnetName {
vnet = &site
break
}
}
}
if vnet == nil {
return nil, errors.NotFoundf("virtual network %q", vnetName)
}
env.Lock()
env.vnet = vnet
env.Unlock()
return vnet, nil
}
// createVirtualNetwork creates a virtual network for the environment.
func (env *azureEnviron) createVirtualNetwork() error {
snap := env.getSnapshot()
vnetName := env.getVirtualNetworkName()
virtualNetwork := gwacl.VirtualNetworkSite{
Name: vnetName,
Location: snap.ecfg.location(),
AddressSpacePrefixes: []string{
networkDefinition,
},
}
if err := snap.api.AddVirtualNetworkSite(&virtualNetwork); err != nil {
return errors.Trace(err)
}
env.Lock()
env.vnet = &virtualNetwork
env.Unlock()
return nil
}
// deleteVnetAttempt is an AttemptyStrategy for use
// when attempting delete a virtual network. This is
// necessary as Azure apparently does not release all
// references to the vnet even when all cloud services
// are deleted.
var deleteVnetAttempt = utils.AttemptStrategy{
Total: 30 * time.Second,
Delay: 1 * time.Second,
}
var networkInUse = regexp.MustCompile(".*The virtual network .* is currently in use.*")
func (env *azureEnviron) deleteVirtualNetwork() error {
snap := env.getSnapshot()
vnetName := env.getVirtualNetworkName()
var err error
for a := deleteVnetAttempt.Start(); a.Next(); {
err = snap.api.RemoveVirtualNetworkSite(vnetName)
if err == nil {
return nil
}
if err, ok := err.(*gwacl.AzureError); ok {
if err.StatusCode() == 400 && networkInUse.MatchString(err.Message) {
// Retry on "virtual network XYZ is currently in use".
continue
}
}
// Any other error should be returned.
break
}
return err
}
// getContainerName returns the name of the private storage account container
// that this environment is using. The container name is immutable,
// so there is no need to use a configuration snapshot.
func (env *azureEnviron) getContainerName() string {
return env.getEnvPrefix() + "private"
}
func isHTTPConflict(err error) bool {
if err, ok := err.(gwacl.HTTPError); ok {
return err.StatusCode() == http.StatusConflict
}
return false
}
func isVirtualNetworkExist(err error) bool {
// TODO(axw) 2014-06-16 #1330473
// Add an error type to gwacl for this.
s := err.Error()
const prefix = "could not add virtual network"
const suffix = "already exists"
return strings.HasPrefix(s, prefix) && strings.HasSuffix(s, suffix)
}
// Bootstrap is specified in the Environ interface.
func (env *azureEnviron) Bootstrap(ctx environs.BootstrapContext, args environs.BootstrapParams) (arch, series string, _ environs.BootstrapFinalizer, err error) {
// The creation of the affinity group and the virtual network is specific to the Azure provider.
err = env.createAffinityGroup()
if err != nil && !isHTTPConflict(err) {
return "", "", nil, err
}
// If we fail after this point, clean up the affinity group.
defer func() {
if err != nil {
env.deleteAffinityGroup()
}
}()
err = env.createVirtualNetwork()
if err != nil && !isVirtualNetworkExist(err) {
return "", "", nil, err
}
// If we fail after this point, clean up the virtual network.
defer func() {
if err != nil {
env.deleteVirtualNetwork()
}
}()
return common.Bootstrap(ctx, env, args)
}
// isLegacyInstance reports whether the instance is a
// legacy instance (i.e. one-to-one cloud service to instance).
func isLegacyInstance(inst *azureInstance) (bool, error) {
snap := inst.environ.getSnapshot()
serviceName := inst.hostedService.ServiceName
service, err := snap.api.GetHostedServiceProperties(serviceName, true)
if err != nil {
return false, err
} else if len(service.Deployments) != 1 {
return false, nil
}
deploymentName := service.Deployments[0].Name
return deploymentName == deploymentNameV1(serviceName), nil
}
// StateServerInstances is specified in the Environ interface.
func (env *azureEnviron) StateServerInstances() ([]instance.Id, error) {
// Locate the state-server cloud service, and get its addresses.
instances, err := env.AllInstances()
if err != nil {
return nil, err
}
var stateServerInstanceIds []instance.Id
var loadStateFile bool
for _, inst := range instances {
azureInstance := inst.(*azureInstance)
label := azureInstance.hostedService.Label
if decoded, err := base64.StdEncoding.DecodeString(label); err == nil {
if string(decoded) == stateServerLabel {
stateServerInstanceIds = append(stateServerInstanceIds, inst.Id())
continue
}
}
if !loadStateFile {
_, roleName := env.splitInstanceId(azureInstance.Id())
if roleName == "" {
loadStateFile = true
}
}
}
if loadStateFile {
// Some legacy instances were found, so we must load provider-state
// to find which instance was the original state server. If we find
// a legacy environment, then stateServerInstanceIds will not contain
// the original bootstrap instance, which is the only one that will
// be in provider-state.
instanceIds, err := common.ProviderStateInstances(env, env.Storage())
if err != nil {
return nil, err
}
stateServerInstanceIds = append(stateServerInstanceIds, instanceIds...)
}
if len(stateServerInstanceIds) == 0 {
return nil, environs.ErrNoInstances
}
return stateServerInstanceIds, nil
}
// Config is specified in the Environ interface.
func (env *azureEnviron) Config() *config.Config {
snap := env.getSnapshot()
return snap.ecfg.Config
}
// SetConfig is specified in the Environ interface.
func (env *azureEnviron) SetConfig(cfg *config.Config) error {
var oldLocation string
if snap := env.getSnapshot(); snap.ecfg != nil {
oldLocation = snap.ecfg.location()
}
ecfg, err := azureEnvironProvider{}.newConfig(cfg)
if err != nil {
return err
}
env.Lock()
defer env.Unlock()
if env.ecfg != nil {
_, err = azureEnvironProvider{}.Validate(cfg, env.ecfg.Config)
if err != nil {
return err
}
}
env.ecfg = ecfg
// Reset storage account key. Even if we had one before, it may not
// be appropriate for the new config.
env.storageAccountKey = ""
subscription := ecfg.managementSubscriptionId()
certKeyPEM := []byte(ecfg.managementCertificate())
location := ecfg.location()
mgtAPI, err := gwacl.NewManagementAPICertDataWithRetryPolicy(subscription, certKeyPEM, certKeyPEM, location, retryPolicy)
if err != nil {
return errors.Annotate(err, "cannot acquire management API")
}
env.api = mgtAPI
// If the location changed, reset the available role sizes.
if location != oldLocation {
env.availableRoleSizes = nil
}
return nil
}
// attemptCreateService tries to create a new hosted service on Azure, with a
// name it chooses (based on the given prefix), but recognizes that the name
// may not be available. If the name is not available, it does not treat that
// as an error but just returns nil.
func attemptCreateService(azure *gwacl.ManagementAPI, prefix, affinityGroupName, label string) (*gwacl.CreateHostedService, error) {
var err error
name := gwacl.MakeRandomHostedServiceName(prefix)
err = azure.CheckHostedServiceNameAvailability(name)
if err != nil {
// The calling function should retry.
return nil, nil
}
if label == "" {
label = name
}
req := gwacl.NewCreateHostedServiceWithLocation(name, label, "")
req.AffinityGroup = affinityGroupName
err = azure.AddHostedService(req)
if err != nil {
return nil, err
}
return req, nil
}
// newHostedService creates a hosted service. It will make up a unique name,
// starting with the given prefix.
func newHostedService(azure *gwacl.ManagementAPI, prefix, affinityGroupName, label string) (*gwacl.HostedService, error) {
var err error
var createdService *gwacl.CreateHostedService
for tries := 10; tries > 0 && err == nil && createdService == nil; tries-- {
createdService, err = attemptCreateService(azure, prefix, affinityGroupName, label)
}
if err != nil {
return nil, errors.Annotate(err, "could not create hosted service")
}
if createdService == nil {
return nil, fmt.Errorf("could not come up with a unique hosted service name - is your randomizer initialized?")
}
return azure.GetHostedServiceProperties(createdService.ServiceName, true)
}
// SupportedArchitectures is specified on the EnvironCapability interface.
func (env *azureEnviron) SupportedArchitectures() ([]string, error) {
env.archMutex.Lock()
defer env.archMutex.Unlock()
if env.supportedArchitectures != nil {
return env.supportedArchitectures, nil
}
// Create a filter to get all images from our region and for the correct stream.
ecfg := env.getSnapshot().ecfg
region := ecfg.location()
cloudSpec := simplestreams.CloudSpec{
Region: region,
Endpoint: getEndpoint(region),
}
imageConstraint := imagemetadata.NewImageConstraint(simplestreams.LookupParams{
CloudSpec: cloudSpec,
Stream: ecfg.ImageStream(),
})
var err error
env.supportedArchitectures, err = common.SupportedArchitectures(env, imageConstraint)
return env.supportedArchitectures, err
}
// selectInstanceTypeAndImage returns the appropriate instances.InstanceType and
// the OS image name for launching a virtual machine with the given parameters.
func (env *azureEnviron) selectInstanceTypeAndImage(constraint *instances.InstanceConstraint) (*instances.InstanceType, string, error) {
ecfg := env.getSnapshot().ecfg
sourceImageName := ecfg.forceImageName()
if sourceImageName != "" {
// Configuration forces us to use a specific image. There may
// not be a suitable image in the simplestreams database.
// This means we can't use Juju's normal selection mechanism,
// because it combines instance-type and image selection: if
// there are no images we can use, it won't offer us an
// instance type either.
//
// Select the instance type using simple, Azure-specific code.
instanceType, err := selectMachineType(env, defaultToBaselineSpec(constraint.Constraints))
if err != nil {
return nil, "", err
}
return instanceType, sourceImageName, nil
}
// Choose the most suitable instance type and OS image, based on simplestreams information.
spec, err := findInstanceSpec(env, constraint)
if err != nil {
return nil, "", err
}
return &spec.InstanceType, spec.Image.Id, nil
}
var unsupportedConstraints = []string{
constraints.CpuPower,
constraints.Tags,
}
// ConstraintsValidator is defined on the Environs interface.
func (env *azureEnviron) ConstraintsValidator() (constraints.Validator, error) {
validator := constraints.NewValidator()
validator.RegisterUnsupported(unsupportedConstraints)
supportedArches, err := env.SupportedArchitectures()
if err != nil {
return nil, err
}
validator.RegisterVocabulary(constraints.Arch, supportedArches)
instanceTypes, err := listInstanceTypes(env)
if err != nil {
return nil, err
}
instTypeNames := make([]string, len(instanceTypes))
for i, instanceType := range instanceTypes {
instTypeNames[i] = instanceType.Name
}
validator.RegisterVocabulary(constraints.InstanceType, instTypeNames)
validator.RegisterConflicts(
[]string{constraints.InstanceType},
[]string{constraints.Mem, constraints.CpuCores, constraints.Arch, constraints.RootDisk})
return validator, nil
}
// PrecheckInstance is defined on the state.Prechecker interface.
func (env *azureEnviron) PrecheckInstance(series string, cons constraints.Value, placement string) error {
if placement != "" {
return fmt.Errorf("unknown placement directive: %s", placement)
}
if !cons.HasInstanceType() {
return nil
}
// Constraint has an instance-type constraint so let's see if it is valid.
instanceTypes, err := listInstanceTypes(env)
if err != nil {
return err
}
for _, instanceType := range instanceTypes {
if instanceType.Name == *cons.InstanceType {
return nil
}
}
return fmt.Errorf("invalid instance type %q", *cons.InstanceType)
}
// createInstance creates all of the Azure entities necessary for a
// new instance. This includes Cloud Service, Deployment and Role.
//
// If serviceName is non-empty, then createInstance will assign to
// the Cloud Service with that name. Otherwise, a new Cloud Service
// will be created.
func (env *azureEnviron) createInstance(azure *gwacl.ManagementAPI, role *gwacl.Role, serviceName string, stateServer bool) (resultInst instance.Instance, resultErr error) {
var inst instance.Instance
defer func() {
if inst != nil && resultErr != nil {
if err := env.StopInstances(inst.Id()); err != nil {
// Failure upon failure. Log it, but return the original error.
logger.Errorf("error releasing failed instance: %v", err)
}
}
}()
var err error
var service *gwacl.HostedService
if serviceName != "" {
logger.Debugf("creating instance in existing cloud service %q", serviceName)
service, err = azure.GetHostedServiceProperties(serviceName, true)
} else {
logger.Debugf("creating instance in new cloud service")
// If we're creating a cloud service for state servers,
// we will want to open additional ports. We need to
// record this against the cloud service, so we use a
// special label for the purpose.
var label string
if stateServer {
label = stateServerLabel
}
service, err = newHostedService(azure, env.getEnvPrefix(), env.getAffinityGroupName(), label)
}
if err != nil {
return nil, err
}
if len(service.Deployments) == 0 {
// This is a newly created cloud service, so we
// should destroy it if anything below fails.
defer func() {
if resultErr != nil {
azure.DeleteHostedService(service.ServiceName)
// Destroying the hosted service destroys the instance,
// so ensure StopInstances isn't called.
inst = nil
}
}()
// Create an initial deployment.
deployment := gwacl.NewDeploymentForCreateVMDeployment(
deploymentNameV2(service.ServiceName),
deploymentSlot,
deploymentNameV2(service.ServiceName),
[]gwacl.Role{*role},
env.getVirtualNetworkName(),
)
if err := azure.AddDeployment(deployment, service.ServiceName); err != nil {
return nil, errors.Annotate(err, "error creating VM deployment")
}
service.Deployments = append(service.Deployments, *deployment)
} else {
// Update the deployment.
deployment := &service.Deployments[0]
if err := azure.AddRole(&gwacl.AddRoleRequest{
ServiceName: service.ServiceName,
DeploymentName: deployment.Name,
PersistentVMRole: (*gwacl.PersistentVMRole)(role),
}); err != nil {
return nil, err
}
deployment.RoleList = append(deployment.RoleList, *role)
}
return env.getInstance(service, role.RoleName)
}
// deploymentNameV1 returns the deployment name used
// in the original implementation of the Azure provider.
func deploymentNameV1(serviceName string) string {
return serviceName
}
// deploymentNameV2 returns the deployment name used
// in the current implementation of the Azure provider.
func deploymentNameV2(serviceName string) string {
return serviceName + "-v2"
}
// MaintainInstance is specified in the InstanceBroker interface.
func (*azureEnviron) MaintainInstance(args environs.StartInstanceParams) error {
return nil
}
// StartInstance is specified in the InstanceBroker interface.
func (env *azureEnviron) StartInstance(args environs.StartInstanceParams) (*environs.StartInstanceResult, error) {
if args.InstanceConfig.HasNetworks() {
return nil, errors.New("starting instances with networks is not supported yet")
}
err := instancecfg.FinishInstanceConfig(args.InstanceConfig, env.Config())
if err != nil {
return nil, err
}
// Pick envtools. Needed for the custom data (which is what we normally
// call userdata).
args.InstanceConfig.Tools = args.Tools[0]
logger.Infof("picked tools %q", args.InstanceConfig.Tools)
// Compose userdata.
userData, err := makeCustomData(args.InstanceConfig)
if err != nil {
return nil, errors.Annotate(err, "cannot compose user data")
}
snapshot := env.getSnapshot()
location := snapshot.ecfg.location()
instanceType, sourceImageName, err := env.selectInstanceTypeAndImage(&instances.InstanceConstraint{
Region: location,
Series: args.Tools.OneSeries(),
Arches: args.Tools.Arches(),
Constraints: args.Constraints,
})
if err != nil {
return nil, err
}
// We use the cloud service label as a way to group instances with
// the same affinity, so that machines can be be allocated to the
// same availability set.
var cloudServiceName string
if args.DistributionGroup != nil && snapshot.ecfg.availabilitySetsEnabled() {
instanceIds, err := args.DistributionGroup()
if err != nil {
return nil, err
}
for _, id := range instanceIds {
cloudServiceName, _ = env.splitInstanceId(id)
if cloudServiceName != "" {
break
}
}
}
vhd := env.newOSDisk(sourceImageName)
// If we're creating machine-0, we'll want to expose port 22.
// All other machines get an auto-generated public port for SSH.
stateServer := multiwatcher.AnyJobNeedsState(args.InstanceConfig.Jobs...)
role := env.newRole(instanceType.Id, vhd, userData, stateServer)
inst, err := createInstance(env, snapshot.api, role, cloudServiceName, stateServer)
if err != nil {
return nil, err
}
hc := &instance.HardwareCharacteristics{
Mem: &instanceType.Mem,
RootDisk: &instanceType.RootDisk,
CpuCores: &instanceType.CpuCores,
}
if len(instanceType.Arches) == 1 {
hc.Arch = &instanceType.Arches[0]
}
return &environs.StartInstanceResult{
Instance: inst,
Hardware: hc,
}, nil
}
// getInstance returns an up-to-date version of the instance with the given
// name.
func (env *azureEnviron) getInstance(hostedService *gwacl.HostedService, roleName string) (instance.Instance, error) {
if n := len(hostedService.Deployments); n != 1 {
return nil, fmt.Errorf("expected one deployment for %q, got %d", hostedService.ServiceName, n)
}
deployment := &hostedService.Deployments[0]
var maskStateServerPorts bool
var instanceId instance.Id
switch deployment.Name {
case deploymentNameV1(hostedService.ServiceName):
// Old style instance.
instanceId = instance.Id(hostedService.ServiceName)
if n := len(deployment.RoleList); n != 1 {
return nil, fmt.Errorf("expected one role for %q, got %d", deployment.Name, n)
}
roleName = deployment.RoleList[0].RoleName
// In the old implementation of the Azure provider,
// all machines opened the state and API server ports.
maskStateServerPorts = true
case deploymentNameV2(hostedService.ServiceName):
instanceId = instance.Id(fmt.Sprintf("%s-%s", hostedService.ServiceName, roleName))
// Newly created state server machines are put into
// the cloud service with the stateServerLabel label.
if decoded, err := base64.StdEncoding.DecodeString(hostedService.Label); err == nil {
maskStateServerPorts = string(decoded) == stateServerLabel
}
}
var roleInstance *gwacl.RoleInstance
for _, role := range deployment.RoleInstanceList {
if role.RoleName == roleName {
roleInstance = &role
break
}
}
instance := &azureInstance{
environ: env,
hostedService: &hostedService.HostedServiceDescriptor,
instanceId: instanceId,
deploymentName: deployment.Name,
roleName: roleName,
roleInstance: roleInstance,
maskStateServerPorts: maskStateServerPorts,
}
return instance, nil
}
// newOSDisk creates a gwacl.OSVirtualHardDisk object suitable for an
// Azure Virtual Machine.
func (env *azureEnviron) newOSDisk(sourceImageName string) *gwacl.OSVirtualHardDisk {
vhdName := gwacl.MakeRandomDiskName("juju")
vhdPath := fmt.Sprintf("vhds/%s", vhdName)
snap := env.getSnapshot()
storageAccount := snap.ecfg.storageAccountName()
mediaLink := gwacl.CreateVirtualHardDiskMediaLink(storageAccount, vhdPath)
// The disk label is optional and the disk name can be omitted if
// mediaLink is provided.
return gwacl.NewOSVirtualHardDisk("", "", "", mediaLink, sourceImageName, "Linux")
}
// getInitialEndpoints returns a slice of the endpoints every instance should have open
// (ssh port, etc).
func (env *azureEnviron) getInitialEndpoints(stateServer bool) []gwacl.InputEndpoint {
cfg := env.Config()
endpoints := []gwacl.InputEndpoint{{
LocalPort: 22,
Name: "sshport",
Port: 22,
Protocol: "tcp",
}}
if stateServer {
endpoints = append(endpoints, []gwacl.InputEndpoint{{
LocalPort: cfg.APIPort(),
Port: cfg.APIPort(),
Protocol: "tcp",
Name: "apiport",
}}...)
}
for i, endpoint := range endpoints {
endpoint.LoadBalancedEndpointSetName = endpoint.Name
endpoint.LoadBalancerProbe = &gwacl.LoadBalancerProbe{
Port: endpoint.Port,
Protocol: "TCP",
}
endpoints[i] = endpoint
}
return endpoints
}
// newRole creates a gwacl.Role object (an Azure Virtual Machine) which uses
// the given Virtual Hard Drive.
//
// The VM will have:
// - an 'ubuntu' user defined with an unguessable (randomly generated) password
// - its ssh port (TCP 22) open
// (if a state server)
// - its state port (TCP mongoDB) port open
// - its API port (TCP) open
//
// roleSize is the name of one of Azure's machine types, e.g. ExtraSmall,
// Large, A6 etc.
func (env *azureEnviron) newRole(roleSize string, vhd *gwacl.OSVirtualHardDisk, userData string, stateServer bool) *gwacl.Role {
roleName := gwacl.MakeRandomRoleName("juju")
// Create a Linux Configuration with the username and the password
// empty and disable SSH with password authentication.
hostname := roleName
username := "ubuntu"
password := gwacl.MakeRandomPassword()
linuxConfigurationSet := gwacl.NewLinuxProvisioningConfigurationSet(hostname, username, password, userData, "true")
// Generate a Network Configuration with the initially required ports open.
networkConfigurationSet := gwacl.NewNetworkConfigurationSet(env.getInitialEndpoints(stateServer), nil)
role := gwacl.NewRole(
roleSize, roleName, vhd,
[]gwacl.ConfigurationSet{*linuxConfigurationSet, *networkConfigurationSet},
)
role.AvailabilitySetName = "juju"
return role
}
// StopInstances is specified in the InstanceBroker interface.
func (env *azureEnviron) StopInstances(ids ...instance.Id) error {
snap := env.getSnapshot()
// Map services to role names we want to delete.
serviceInstances := make(map[string]map[string]bool)
var serviceNames []string
for _, id := range ids {
serviceName, roleName := env.splitInstanceId(id)
if roleName == "" {
serviceInstances[serviceName] = nil
serviceNames = append(serviceNames, serviceName)
} else {
deleteRoleNames, ok := serviceInstances[serviceName]
if !ok {
deleteRoleNames = make(map[string]bool)
serviceInstances[serviceName] = deleteRoleNames
serviceNames = append(serviceNames, serviceName)
}
deleteRoleNames[roleName] = true
}
}
// Load the properties of each service, so we know whether to
// delete the entire service.
//
// Note: concurrent operations on Affinity Groups have been
// found to cause conflict responses, so we do everything serially.
for _, serviceName := range serviceNames {
deleteRoleNames := serviceInstances[serviceName]
service, err := snap.api.GetHostedServiceProperties(serviceName, true)
if err != nil {
return err
} else if len(service.Deployments) != 1 {
continue
}
// Filter the instances that have no corresponding role.
roleNames := make(set.Strings)
for _, role := range service.Deployments[0].RoleList {
roleNames.Add(role.RoleName)
}
for roleName := range deleteRoleNames {
if !roleNames.Contains(roleName) {
delete(deleteRoleNames, roleName)
}
}
// If we're deleting all the roles, we need to delete the
// entire cloud service or we'll get an error. deleteRoleNames
// is nil if we're dealing with a legacy deployment.
if deleteRoleNames == nil || len(deleteRoleNames) == roleNames.Size() {
if err := snap.api.DeleteHostedService(serviceName); err != nil {
return err
}
} else {
for roleName := range deleteRoleNames {
if err := snap.api.DeleteRole(&gwacl.DeleteRoleRequest{
ServiceName: serviceName,
DeploymentName: service.Deployments[0].Name,
RoleName: roleName,
DeleteMedia: true,
}); err != nil {
return err
}
}
}
}
return nil
}
// hostedServices returns all services for this environment.
func (env *azureEnviron) hostedServices() ([]gwacl.HostedServiceDescriptor, error) {
snap := env.getSnapshot()
services, err := snap.api.ListHostedServices()
if err != nil {
return nil, err
}
var filteredServices []gwacl.HostedServiceDescriptor
// Service names are prefixed with the environment name, followed by "-".
// We must be careful not to include services where the environment name
// is a substring of another name. ie we mustn't allow "azure" to match "azure-1".
envPrefix := env.getEnvPrefix()
// Just in case.
filterPrefix := regexp.QuoteMeta(envPrefix)
// Now filter the services.
prefixMatch := regexp.MustCompile("^" + filterPrefix + "[^-]*$")
for _, service := range services {
if prefixMatch.Match([]byte(service.ServiceName)) {
filteredServices = append(filteredServices, service)
}
}
return filteredServices, nil
}