/
provider.go
1659 lines (1505 loc) · 50.6 KB
/
provider.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 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
// Stub provider for OpenStack, using goose will be implemented here
package openstack
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
"sync"
"time"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names"
"github.com/juju/utils"
"gopkg.in/goose.v1/client"
gooseerrors "gopkg.in/goose.v1/errors"
"gopkg.in/goose.v1/identity"
"gopkg.in/goose.v1/nova"
"gopkg.in/goose.v1/swift"
"github.com/juju/juju/cloudconfig/instancecfg"
"github.com/juju/juju/cloudconfig/providerinit"
"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/juju/arch"
"github.com/juju/juju/network"
"github.com/juju/juju/provider/common"
"github.com/juju/juju/state"
"github.com/juju/juju/state/multiwatcher"
"github.com/juju/juju/tools"
)
var logger = loggo.GetLogger("juju.provider.openstack")
type environProvider struct{}
var _ environs.EnvironProvider = (*environProvider)(nil)
var providerInstance environProvider
var makeServiceURL = client.AuthenticatingClient.MakeServiceURL
// Use shortAttempt to poll for short-term events.
// TODO: This was kept to a long timeout because Nova needs more time than EC2.
// For example, HP Cloud takes around 9.1 seconds (10 samples) to return a
// BUILD(spawning) status. But storage delays are handled separately now, and
// perhaps other polling attempts can time out faster.
var shortAttempt = utils.AttemptStrategy{
Total: 15 * time.Second,
Delay: 200 * time.Millisecond,
}
func (p environProvider) BoilerplateConfig() string {
return `
# https://juju.ubuntu.com/docs/config-openstack.html
openstack:
type: openstack
# use-floating-ip specifies whether a floating IP address is
# required to give the nodes a public IP address. Some
# installations assign public IP addresses by default without
# requiring a floating IP address.
#
# use-floating-ip: false
# use-default-secgroup specifies whether new machine instances
# should have the "default" Openstack security group assigned.
#
# use-default-secgroup: false
# network specifies the network label or uuid to bring machines up
# on, in the case where multiple networks exist. It may be omitted
# otherwise.
#
# network: <your network label or uuid>
# agent-metadata-url specifies the location of the Juju tools and
# metadata. It defaults to the global public tools metadata
# location https://streams.canonical.com/tools.
#
# agent-metadata-url: https://your-agent-metadata-url
# image-metadata-url specifies the location of Ubuntu cloud image
# metadata. It defaults to the global public image metadata
# location https://cloud-images.ubuntu.com/releases.
#
# image-metadata-url: https://your-image-metadata-url
# image-stream chooses a simplestreams stream from which to select
# OS images, for example daily or released images (or any other stream
# available on simplestreams).
#
# image-stream: "released"
# agent-stream chooses a simplestreams stream from which to select tools,
# for example released or proposed tools (or any other stream available
# on simplestreams).
#
# agent-stream: "released"
# auth-url defaults to the value of the environment variable
# OS_AUTH_URL, but can be specified here.
#
# auth-url: https://yourkeystoneurl:443/v2.0/
# tenant-name holds the openstack tenant name. It defaults to the
# environment variable OS_TENANT_NAME.
#
# tenant-name: <your tenant name>
# region holds the openstack region. It defaults to the
# environment variable OS_REGION_NAME.
#
# region: <your region>
# The auth-mode, username and password attributes are used for
# userpass authentication (the default).
#
# auth-mode holds the authentication mode. For user-password
# authentication, auth-mode should be "userpass" and username and
# password should be set appropriately; they default to the
# environment variables OS_USERNAME and OS_PASSWORD respectively.
#
# auth-mode: userpass
# username: <your username>
# password: <secret>
# For key-pair authentication, auth-mode should be "keypair" and
# access-key and secret-key should be set appropriately; they
# default to the environment variables OS_ACCESS_KEY and
# OS_SECRET_KEY respectively.
#
# auth-mode: keypair
# access-key: <secret>
# secret-key: <secret>
# Whether or not to refresh the list of available updates for an
# OS. The default option of true is recommended for use in
# production systems, but disabling this can speed up local
# deployments for development or testing.
#
# enable-os-refresh-update: true
# Whether or not to perform OS upgrades when machines are
# provisioned. The default option of true is recommended for use
# in production systems, but disabling this can speed up local
# deployments for development or testing.
#
# enable-os-upgrade: true
# https://juju.ubuntu.com/docs/config-hpcloud.html
hpcloud:
type: openstack
# use-floating-ip specifies whether a floating IP address is
# required to give the nodes a public IP address. Some
# installations assign public IP addresses by default without
# requiring a floating IP address.
#
# use-floating-ip: true
# use-default-secgroup specifies whether new machine instances
# should have the "default" Openstack security group assigned.
#
# use-default-secgroup: false
# tenant-name holds the openstack tenant name. In HPCloud, this is
# synonymous with the project-name It defaults to the environment
# variable OS_TENANT_NAME.
#
# tenant-name: <your tenant name>
# image-stream chooses a simplestreams stream from which to select
# OS images, for example daily or released images (or any other stream
# available on simplestreams).
#
# image-stream: "released"
# agent-stream chooses a simplestreams stream from which to select tools,
# for example released or proposed tools (or any other stream available
# on simplestreams).
#
# agent-stream: "released"
# auth-url holds the keystone url for authentication. It defaults
# to the value of the environment variable OS_AUTH_URL.
#
# auth-url: https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/
# region holds the HP Cloud region (e.g. region-a.geo-1). It
# defaults to the environment variable OS_REGION_NAME.
#
# region: <your region>
# auth-mode holds the authentication mode. For user-password
# authentication, auth-mode should be "userpass" and username and
# password should be set appropriately; they default to the
# environment variables OS_USERNAME and OS_PASSWORD respectively.
#
# auth-mode: userpass
# username: <your_username>
# password: <your_password>
# For key-pair authentication, auth-mode should be "keypair" and
# access-key and secret-key should be set appropriately; they
# default to the environment variables OS_ACCESS_KEY and
# OS_SECRET_KEY respectively.
#
# auth-mode: keypair
# access-key: <secret>
# secret-key: <secret>
# Whether or not to refresh the list of available updates for an
# OS. The default option of true is recommended for use in
# production systems, but disabling this can speed up local
# deployments for development or testing.
#
# enable-os-refresh-update: true
# Whether or not to perform OS upgrades when machines are
# provisioned. The default option of true is recommended for use
# in production systems, but disabling this can speed up local
# deployments for development or testing.
#
# enable-os-upgrade: true
`[1:]
}
func (p environProvider) Open(cfg *config.Config) (environs.Environ, error) {
logger.Infof("opening environment %q", cfg.Name())
e := new(environ)
err := e.SetConfig(cfg)
if err != nil {
return nil, err
}
e.name = cfg.Name()
return e, nil
}
// RestrictedConfigAttributes is specified in the EnvironProvider interface.
func (p environProvider) RestrictedConfigAttributes() []string {
return []string{"region", "auth-url", "auth-mode"}
}
// PrepareForCreateEnvironment is specified in the EnvironProvider interface.
func (p environProvider) PrepareForCreateEnvironment(cfg *config.Config) (*config.Config, error) {
attrs := cfg.UnknownAttrs()
if _, ok := attrs["control-bucket"]; !ok {
uuid, err := utils.NewUUID()
if err != nil {
return nil, errors.Trace(err)
}
attrs["control-bucket"] = fmt.Sprintf("%x", uuid.Raw())
}
return cfg.Apply(attrs)
}
func (p environProvider) PrepareForBootstrap(ctx environs.BootstrapContext, cfg *config.Config) (environs.Environ, error) {
cfg, err := p.PrepareForCreateEnvironment(cfg)
if err != nil {
return nil, err
}
e, err := p.Open(cfg)
if err != nil {
return nil, err
}
// Verify credentials.
if err := authenticateClient(e.(*environ)); err != nil {
return nil, err
}
return e, nil
}
// MetadataLookupParams returns parameters which are used to query image metadata to
// find matching image information.
func (p environProvider) MetadataLookupParams(region string) (*simplestreams.MetadataLookupParams, error) {
if region == "" {
return nil, fmt.Errorf("region must be specified")
}
return &simplestreams.MetadataLookupParams{
Region: region,
Architectures: arch.AllSupportedArches,
}, nil
}
func (p environProvider) SecretAttrs(cfg *config.Config) (map[string]string, error) {
m := make(map[string]string)
ecfg, err := providerInstance.newConfig(cfg)
if err != nil {
return nil, err
}
m["username"] = ecfg.username()
m["password"] = ecfg.password()
m["tenant-name"] = ecfg.tenantName()
return m, nil
}
func retryGet(uri string) (data []byte, err error) {
for a := shortAttempt.Start(); a.Next(); {
var resp *http.Response
resp, err = http.Get(uri)
if err != nil {
continue
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("bad http response %v", resp.Status)
continue
}
var data []byte
data, err = ioutil.ReadAll(resp.Body)
if err != nil {
continue
}
return data, nil
}
if err != nil {
return nil, fmt.Errorf("cannot get %q: %v", uri, err)
}
return
}
type environ struct {
common.SupportsUnitPlacementPolicy
name string
// archMutex gates access to supportedArchitectures
archMutex sync.Mutex
// supportedArchitectures caches the architectures
// for which images can be instantiated.
supportedArchitectures []string
ecfgMutex sync.Mutex
ecfgUnlocked *environConfig
client client.AuthenticatingClient
novaUnlocked *nova.Client
storageUnlocked storage.Storage
// keystoneImageDataSource caches the result of getKeystoneImageSource.
keystoneImageDataSourceMutex sync.Mutex
keystoneImageDataSource simplestreams.DataSource
// keystoneToolsDataSource caches the result of getKeystoneToolsSource.
keystoneToolsDataSourceMutex sync.Mutex
keystoneToolsDataSource simplestreams.DataSource
availabilityZonesMutex sync.Mutex
availabilityZones []common.AvailabilityZone
}
var _ environs.Environ = (*environ)(nil)
var _ simplestreams.HasRegion = (*environ)(nil)
var _ state.Prechecker = (*environ)(nil)
var _ state.InstanceDistributor = (*environ)(nil)
type openstackInstance struct {
e *environ
instType *instances.InstanceType
arch *string
mu sync.Mutex
serverDetail *nova.ServerDetail
// floatingIP is non-nil iff use-floating-ip is true.
floatingIP *nova.FloatingIP
}
func (inst *openstackInstance) String() string {
return string(inst.Id())
}
var _ instance.Instance = (*openstackInstance)(nil)
func (inst *openstackInstance) Refresh() error {
inst.mu.Lock()
defer inst.mu.Unlock()
server, err := inst.e.nova().GetServer(inst.serverDetail.Id)
if err != nil {
return err
}
inst.serverDetail = server
return nil
}
func (inst *openstackInstance) getServerDetail() *nova.ServerDetail {
inst.mu.Lock()
defer inst.mu.Unlock()
return inst.serverDetail
}
func (inst *openstackInstance) Id() instance.Id {
return instance.Id(inst.getServerDetail().Id)
}
func (inst *openstackInstance) Status() string {
return inst.getServerDetail().Status
}
func (inst *openstackInstance) hardwareCharacteristics() *instance.HardwareCharacteristics {
hc := &instance.HardwareCharacteristics{Arch: inst.arch}
if inst.instType != nil {
hc.Mem = &inst.instType.Mem
// openstack is special in that a 0-size root disk means that
// the root disk will result in an instance with a root disk
// the same size as the image that created it, so we just set
// the HardwareCharacteristics to nil to signal that we don't
// know what the correct size is.
if inst.instType.RootDisk == 0 {
hc.RootDisk = nil
} else {
hc.RootDisk = &inst.instType.RootDisk
}
hc.CpuCores = &inst.instType.CpuCores
hc.CpuPower = inst.instType.CpuPower
// tags not currently supported on openstack
}
hc.AvailabilityZone = &inst.serverDetail.AvailabilityZone
return hc
}
// getAddresses returns the existing server information on addresses,
// but fetches the details over the api again if no addresses exist.
func (inst *openstackInstance) getAddresses() (map[string][]nova.IPAddress, error) {
addrs := inst.getServerDetail().Addresses
if len(addrs) == 0 {
server, err := inst.e.nova().GetServer(string(inst.Id()))
if err != nil {
return nil, err
}
addrs = server.Addresses
}
return addrs, nil
}
// Addresses implements network.Addresses() returning generic address
// details for the instances, and calling the openstack api if needed.
func (inst *openstackInstance) Addresses() ([]network.Address, error) {
addresses, err := inst.getAddresses()
if err != nil {
return nil, err
}
var floatingIP string
if inst.floatingIP != nil && inst.floatingIP.IP != "" {
floatingIP = inst.floatingIP.IP
logger.Debugf("instance %v has floating IP address: %v", inst.Id(), floatingIP)
}
return convertNovaAddresses(floatingIP, addresses), nil
}
// convertNovaAddresses returns nova addresses in generic format
func convertNovaAddresses(publicIP string, addresses map[string][]nova.IPAddress) []network.Address {
var machineAddresses []network.Address
if publicIP != "" {
publicAddr := network.NewScopedAddress(publicIP, network.ScopePublic)
publicAddr.NetworkName = "public"
machineAddresses = append(machineAddresses, publicAddr)
}
// TODO(gz) Network ordering may be significant but is not preserved by
// the map, see lp:1188126 for example. That could potentially be fixed
// in goose, or left to be derived by other means.
for netName, ips := range addresses {
networkScope := network.ScopeUnknown
if netName == "public" {
networkScope = network.ScopePublic
}
for _, address := range ips {
// If this address has already been added as a floating IP, skip it.
if publicIP == address.Address {
continue
}
// Assume IPv4 unless specified otherwise
addrtype := network.IPv4Address
if address.Version == 6 {
addrtype = network.IPv6Address
}
machineAddr := network.NewScopedAddress(address.Address, networkScope)
machineAddr.NetworkName = netName
if machineAddr.Type != addrtype {
logger.Warningf("derived address type %v, nova reports %v", machineAddr.Type, addrtype)
}
machineAddresses = append(machineAddresses, machineAddr)
}
}
return machineAddresses
}
// TODO: following 30 lines nearly verbatim from environs/ec2
func (inst *openstackInstance) OpenPorts(machineId string, ports []network.PortRange) error {
if inst.e.Config().FirewallMode() != config.FwInstance {
return fmt.Errorf("invalid firewall mode %q for opening ports on instance",
inst.e.Config().FirewallMode())
}
name := inst.e.machineGroupName(machineId)
if err := inst.e.openPortsInGroup(name, ports); err != nil {
return err
}
logger.Infof("opened ports in security group %s: %v", name, ports)
return nil
}
func (inst *openstackInstance) ClosePorts(machineId string, ports []network.PortRange) error {
if inst.e.Config().FirewallMode() != config.FwInstance {
return fmt.Errorf("invalid firewall mode %q for closing ports on instance",
inst.e.Config().FirewallMode())
}
name := inst.e.machineGroupName(machineId)
if err := inst.e.closePortsInGroup(name, ports); err != nil {
return err
}
logger.Infof("closed ports in security group %s: %v", name, ports)
return nil
}
func (inst *openstackInstance) Ports(machineId string) ([]network.PortRange, error) {
if inst.e.Config().FirewallMode() != config.FwInstance {
return nil, fmt.Errorf("invalid firewall mode %q for retrieving ports from instance",
inst.e.Config().FirewallMode())
}
name := inst.e.machineGroupName(machineId)
portRanges, err := inst.e.portsInGroup(name)
if err != nil {
return nil, err
}
return portRanges, nil
}
func (e *environ) ecfg() *environConfig {
e.ecfgMutex.Lock()
ecfg := e.ecfgUnlocked
e.ecfgMutex.Unlock()
return ecfg
}
func (e *environ) nova() *nova.Client {
e.ecfgMutex.Lock()
nova := e.novaUnlocked
e.ecfgMutex.Unlock()
return nova
}
// SupportedArchitectures is specified on the EnvironCapability interface.
func (e *environ) SupportedArchitectures() ([]string, error) {
e.archMutex.Lock()
defer e.archMutex.Unlock()
if e.supportedArchitectures != nil {
return e.supportedArchitectures, nil
}
// Create a filter to get all images from our region and for the correct stream.
cloudSpec, err := e.Region()
if err != nil {
return nil, err
}
imageConstraint := imagemetadata.NewImageConstraint(simplestreams.LookupParams{
CloudSpec: cloudSpec,
Stream: e.Config().ImageStream(),
})
e.supportedArchitectures, err = common.SupportedArchitectures(e, imageConstraint)
return e.supportedArchitectures, err
}
var unsupportedConstraints = []string{
constraints.Tags,
constraints.CpuPower,
}
// ConstraintsValidator is defined on the Environs interface.
func (e *environ) ConstraintsValidator() (constraints.Validator, error) {
validator := constraints.NewValidator()
validator.RegisterConflicts(
[]string{constraints.InstanceType},
[]string{constraints.Mem, constraints.Arch, constraints.RootDisk, constraints.CpuCores})
validator.RegisterUnsupported(unsupportedConstraints)
supportedArches, err := e.SupportedArchitectures()
if err != nil {
return nil, err
}
validator.RegisterVocabulary(constraints.Arch, supportedArches)
novaClient := e.nova()
flavors, err := novaClient.ListFlavorsDetail()
if err != nil {
return nil, err
}
instTypeNames := make([]string, len(flavors))
for i, flavor := range flavors {
instTypeNames[i] = flavor.Name
}
validator.RegisterVocabulary(constraints.InstanceType, instTypeNames)
return validator, nil
}
var novaListAvailabilityZones = (*nova.Client).ListAvailabilityZones
type openstackAvailabilityZone struct {
nova.AvailabilityZone
}
func (z *openstackAvailabilityZone) Name() string {
return z.AvailabilityZone.Name
}
func (z *openstackAvailabilityZone) Available() bool {
return z.AvailabilityZone.State.Available
}
// AvailabilityZones returns a slice of availability zones.
func (e *environ) AvailabilityZones() ([]common.AvailabilityZone, error) {
e.availabilityZonesMutex.Lock()
defer e.availabilityZonesMutex.Unlock()
if e.availabilityZones == nil {
zones, err := novaListAvailabilityZones(e.nova())
if gooseerrors.IsNotImplemented(err) {
return nil, errors.NotImplementedf("availability zones")
}
if err != nil {
return nil, err
}
e.availabilityZones = make([]common.AvailabilityZone, len(zones))
for i, z := range zones {
e.availabilityZones[i] = &openstackAvailabilityZone{z}
}
}
return e.availabilityZones, nil
}
// InstanceAvailabilityZoneNames returns the availability zone names for each
// of the specified instances.
func (e *environ) InstanceAvailabilityZoneNames(ids []instance.Id) ([]string, error) {
instances, err := e.Instances(ids)
if err != nil && err != environs.ErrPartialInstances {
return nil, err
}
zones := make([]string, len(instances))
for i, inst := range instances {
if inst == nil {
continue
}
zones[i] = inst.(*openstackInstance).serverDetail.AvailabilityZone
}
return zones, err
}
type openstackPlacement struct {
availabilityZone nova.AvailabilityZone
}
func (e *environ) parsePlacement(placement string) (*openstackPlacement, error) {
pos := strings.IndexRune(placement, '=')
if pos == -1 {
return nil, fmt.Errorf("unknown placement directive: %v", placement)
}
switch key, value := placement[:pos], placement[pos+1:]; key {
case "zone":
availabilityZone := value
zones, err := e.AvailabilityZones()
if err != nil {
return nil, err
}
for _, z := range zones {
if z.Name() == availabilityZone {
return &openstackPlacement{
z.(*openstackAvailabilityZone).AvailabilityZone,
}, nil
}
}
return nil, fmt.Errorf("invalid availability zone %q", availabilityZone)
}
return nil, fmt.Errorf("unknown placement directive: %v", placement)
}
// PrecheckInstance is defined on the state.Prechecker interface.
func (e *environ) PrecheckInstance(series string, cons constraints.Value, placement string) error {
if placement != "" {
if _, err := e.parsePlacement(placement); err != nil {
return err
}
}
if !cons.HasInstanceType() {
return nil
}
// Constraint has an instance-type constraint so let's see if it is valid.
novaClient := e.nova()
flavors, err := novaClient.ListFlavorsDetail()
if err != nil {
return err
}
for _, flavor := range flavors {
if flavor.Name == *cons.InstanceType {
return nil
}
}
return fmt.Errorf("invalid Openstack flavour %q specified", *cons.InstanceType)
}
func (e *environ) Storage() storage.Storage {
e.ecfgMutex.Lock()
stor := e.storageUnlocked
e.ecfgMutex.Unlock()
return stor
}
func (e *environ) Bootstrap(ctx environs.BootstrapContext, args environs.BootstrapParams) (arch, series string, _ environs.BootstrapFinalizer, _ error) {
// The client's authentication may have been reset when finding tools if the agent-version
// attribute was updated so we need to re-authenticate. This will be a no-op if already authenticated.
// An authenticated client is needed for the URL() call below.
if err := authenticateClient(e); err != nil {
return "", "", nil, err
}
return common.Bootstrap(ctx, e, args)
}
func (e *environ) StateServerInstances() ([]instance.Id, error) {
return common.ProviderStateInstances(e, e.Storage())
}
func (e *environ) Config() *config.Config {
return e.ecfg().Config
}
func authClient(ecfg *environConfig) client.AuthenticatingClient {
cred := &identity.Credentials{
User: ecfg.username(),
Secrets: ecfg.password(),
Region: ecfg.region(),
TenantName: ecfg.tenantName(),
URL: ecfg.authURL(),
}
// authModeCfg has already been validated so we know it's one of the values below.
var authMode identity.AuthMode
switch AuthMode(ecfg.authMode()) {
case AuthLegacy:
authMode = identity.AuthLegacy
case AuthUserPass:
authMode = identity.AuthUserPass
case AuthKeyPair:
authMode = identity.AuthKeyPair
cred.User = ecfg.accessKey()
cred.Secrets = ecfg.secretKey()
}
newClient := client.NewClient
if !ecfg.SSLHostnameVerification() {
newClient = client.NewNonValidatingClient
}
return newClient(cred, authMode, nil)
}
var authenticateClient = func(e *environ) error {
err := e.client.Authenticate()
if err != nil {
// Log the error in case there are any useful hints,
// but provide a readable and helpful error message
// to the user.
logger.Debugf("authentication failed: %v", err)
return errors.New(`authentication failed.
Please ensure the credentials are correct. A common mistake is
to specify the wrong tenant. Use the OpenStack "project" name
for tenant-name in your environment configuration.`)
}
return nil
}
func (e *environ) SetConfig(cfg *config.Config) error {
ecfg, err := providerInstance.newConfig(cfg)
if err != nil {
return err
}
// At this point, the authentication method config value has been validated so we extract it's value here
// to avoid having to validate again each time when creating the OpenStack client.
e.ecfgMutex.Lock()
defer e.ecfgMutex.Unlock()
e.ecfgUnlocked = ecfg
e.client = authClient(ecfg)
e.novaUnlocked = nova.New(e.client)
// create new control storage instance, existing instances continue
// to reference their existing configuration.
// public storage instance creation is deferred until needed since authenticated
// access to the identity service is required so that any juju-tools endpoint can be used.
e.storageUnlocked = &openstackstorage{
containerName: ecfg.controlBucket(),
// this is possibly just a hack - if the ACL is swift.Private,
// the machine won't be able to get the tools (401 error)
containerACL: swift.PublicRead,
swift: swift.New(e.client)}
return nil
}
// getKeystoneImageSource is an imagemetadata.ImageDataSourceFunc that
// returns a DataSource using the "product-streams" keystone URL.
func getKeystoneImageSource(env environs.Environ) (simplestreams.DataSource, error) {
e, ok := env.(*environ)
if !ok {
return nil, errors.NotSupportedf("non-openstack environment")
}
return e.getKeystoneDataSource(&e.keystoneImageDataSourceMutex, &e.keystoneImageDataSource, "product-streams")
}
// getKeystoneToolsSource is a tools.ToolsDataSourceFunc that
// returns a DataSource using the "juju-tools" keystone URL.
func getKeystoneToolsSource(env environs.Environ) (simplestreams.DataSource, error) {
e, ok := env.(*environ)
if !ok {
return nil, errors.NotSupportedf("non-openstack environment")
}
return e.getKeystoneDataSource(&e.keystoneToolsDataSourceMutex, &e.keystoneToolsDataSource, "juju-tools")
}
func (e *environ) getKeystoneDataSource(mu *sync.Mutex, datasource *simplestreams.DataSource, keystoneName string) (simplestreams.DataSource, error) {
mu.Lock()
defer mu.Unlock()
if *datasource != nil {
return *datasource, nil
}
if !e.client.IsAuthenticated() {
if err := authenticateClient(e); err != nil {
return nil, err
}
}
url, err := makeServiceURL(e.client, keystoneName, nil)
if err != nil {
return nil, errors.NewNotSupported(err, fmt.Sprintf("cannot make service URL: %v", err))
}
verify := utils.VerifySSLHostnames
if !e.Config().SSLHostnameVerification() {
verify = utils.NoVerifySSLHostnames
}
*datasource = simplestreams.NewURLDataSource("keystone catalog", url, verify)
return *datasource, nil
}
// TODO(gz): Move this somewhere more reusable
const uuidPattern = "^([a-fA-F0-9]{8})-([a-fA-f0-9]{4})-([1-5][a-fA-f0-9]{3})-([a-fA-f0-9]{4})-([a-fA-f0-9]{12})$"
var uuidRegexp = regexp.MustCompile(uuidPattern)
// resolveNetwork takes either a network id or label and returns a network id
func (e *environ) resolveNetwork(networkName string) (string, error) {
if uuidRegexp.MatchString(networkName) {
// Network id supplied, assume valid as boot will fail if not
return networkName, nil
}
// Network label supplied, resolve to a network id
networks, err := e.nova().ListNetworks()
if err != nil {
return "", err
}
var networkIds = []string{}
for _, network := range networks {
if network.Label == networkName {
networkIds = append(networkIds, network.Id)
}
}
switch len(networkIds) {
case 1:
return networkIds[0], nil
case 0:
return "", fmt.Errorf("No networks exist with label %q", networkName)
}
return "", fmt.Errorf("Multiple networks with label %q: %v", networkName, networkIds)
}
// allocatePublicIP tries to find an available floating IP address, or
// allocates a new one, returning it, or an error
func (e *environ) allocatePublicIP() (*nova.FloatingIP, error) {
fips, err := e.nova().ListFloatingIPs()
if err != nil {
return nil, err
}
var newfip *nova.FloatingIP
for _, fip := range fips {
newfip = &fip
if fip.InstanceId != nil && *fip.InstanceId != "" {
// unavailable, skip
newfip = nil
continue
} else {
logger.Debugf("found unassigned public ip: %v", newfip.IP)
// unassigned, we can use it
return newfip, nil
}
}
if newfip == nil {
// allocate a new IP and use it
newfip, err = e.nova().AllocateFloatingIP()
if err != nil {
return nil, err
}
logger.Debugf("allocated new public IP: %v", newfip.IP)
}
return newfip, nil
}
// assignPublicIP tries to assign the given floating IP address to the
// specified server, or returns an error.
func (e *environ) assignPublicIP(fip *nova.FloatingIP, serverId string) (err error) {
if fip == nil {
return fmt.Errorf("cannot assign a nil public IP to %q", serverId)
}
if fip.InstanceId != nil && *fip.InstanceId == serverId {
// IP already assigned, nothing to do
return nil
}
// At startup nw_info is not yet cached so this may fail
// temporarily while the server is being built
for a := common.LongAttempt.Start(); a.Next(); {
err = e.nova().AddServerFloatingIP(serverId, fip.IP)
if err == nil {
return nil
}
}
return err
}
// DistributeInstances implements the state.InstanceDistributor policy.
func (e *environ) DistributeInstances(candidates, distributionGroup []instance.Id) ([]instance.Id, error) {
return common.DistributeInstances(e, candidates, distributionGroup)
}
var availabilityZoneAllocations = common.AvailabilityZoneAllocations
// MaintainInstance is specified in the InstanceBroker interface.
func (*environ) MaintainInstance(args environs.StartInstanceParams) error {
return nil
}
// StartInstance is specified in the InstanceBroker interface.
func (e *environ) StartInstance(args environs.StartInstanceParams) (*environs.StartInstanceResult, error) {
var availabilityZones []string
if args.Placement != "" {
placement, err := e.parsePlacement(args.Placement)
if err != nil {
return nil, err
}
if !placement.availabilityZone.State.Available {
return nil, fmt.Errorf("availability zone %q is unavailable", placement.availabilityZone.Name)
}
availabilityZones = append(availabilityZones, placement.availabilityZone.Name)
}
// If no availability zone is specified, then automatically spread across
// the known zones for optimal spread across the instance distribution
// group.
if len(availabilityZones) == 0 {
var group []instance.Id
var err error
if args.DistributionGroup != nil {
group, err = args.DistributionGroup()
if err != nil {
return nil, err
}
}
zoneInstances, err := availabilityZoneAllocations(e, group)
if errors.IsNotImplemented(err) {
// Availability zones are an extension, so we may get a
// not implemented error; ignore these.
} else if err != nil {
return nil, err
} else {
for _, zone := range zoneInstances {
availabilityZones = append(availabilityZones, zone.ZoneName)
}
}
if len(availabilityZones) == 0 {
// No explicitly selectable zones available, so use an unspecified zone.
availabilityZones = []string{""}
}
}
if args.InstanceConfig.HasNetworks() {
return nil, fmt.Errorf("starting instances with networks is not supported yet.")
}
series := args.Tools.OneSeries()
arches := args.Tools.Arches()
spec, err := findInstanceSpec(e, &instances.InstanceConstraint{
Region: e.ecfg().region(),
Series: series,
Arches: arches,
Constraints: args.Constraints,
})
if err != nil {
return nil, err
}