-
Notifications
You must be signed in to change notification settings - Fork 494
/
provider.go
1800 lines (1630 loc) · 55.3 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"
"net/url"
"strings"
"sync"
"time"
"github.com/juju/errors"
"github.com/juju/jsonschema"
"github.com/juju/loggo"
"github.com/juju/retry"
"github.com/juju/utils"
"github.com/juju/utils/clock"
"github.com/juju/version"
"gopkg.in/goose.v2/cinder"
"gopkg.in/goose.v2/client"
gooseerrors "gopkg.in/goose.v2/errors"
"gopkg.in/goose.v2/identity"
gooselogging "gopkg.in/goose.v2/logging"
"gopkg.in/goose.v2/neutron"
"gopkg.in/goose.v2/nova"
"gopkg.in/juju/names.v2"
"github.com/juju/juju/cloud"
"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/instances"
"github.com/juju/juju/environs/simplestreams"
"github.com/juju/juju/environs/tags"
"github.com/juju/juju/instance"
"github.com/juju/juju/network"
"github.com/juju/juju/provider/common"
"github.com/juju/juju/status"
"github.com/juju/juju/storage"
"github.com/juju/juju/tools"
)
var logger = loggo.GetLogger("juju.provider.openstack")
type EnvironProvider struct {
environs.ProviderCredentials
Configurator ProviderConfigurator
FirewallerFactory FirewallerFactory
FlavorFilter FlavorFilter
// NetworkingDecorator, if non-nil, will be used to
// decorate the default networking implementation.
// This can be used to override behaviour.
NetworkingDecorator NetworkingDecorator
// ClientFromEndpoint returns an Openstack client for the given endpoint.
ClientFromEndpoint func(endpoint string) client.AuthenticatingClient
}
var (
_ environs.EnvironProvider = (*EnvironProvider)(nil)
_ environs.ProviderSchema = (*EnvironProvider)(nil)
)
var providerInstance *EnvironProvider = &EnvironProvider{
ProviderCredentials: OpenstackCredentials{},
Configurator: &defaultConfigurator{},
FirewallerFactory: &firewallerFactory{},
FlavorFilter: FlavorFilterFunc(AcceptAllFlavors),
NetworkingDecorator: nil,
ClientFromEndpoint: newGooseClient,
}
var cloudSchema = &jsonschema.Schema{
Type: []jsonschema.Type{jsonschema.ObjectType},
Required: []string{cloud.EndpointKey, cloud.AuthTypesKey, cloud.RegionsKey},
Order: []string{cloud.EndpointKey, cloud.AuthTypesKey, cloud.RegionsKey},
Properties: map[string]*jsonschema.Schema{
cloud.EndpointKey: {
Singular: "the API endpoint url for the cloud",
Type: []jsonschema.Type{jsonschema.StringType},
Format: jsonschema.FormatURI,
},
cloud.AuthTypesKey: {
Singular: "auth type",
Plural: "auth types",
Type: []jsonschema.Type{jsonschema.ArrayType},
UniqueItems: jsonschema.Bool(true),
Items: &jsonschema.ItemSpec{
Schemas: []*jsonschema.Schema{{
Type: []jsonschema.Type{jsonschema.StringType},
Enum: []interface{}{
string(cloud.AccessKeyAuthType),
string(cloud.UserPassAuthType),
},
}},
},
},
cloud.RegionsKey: {
Type: []jsonschema.Type{jsonschema.ObjectType},
Singular: "region",
Plural: "regions",
AdditionalProperties: &jsonschema.Schema{
Type: []jsonschema.Type{jsonschema.ObjectType},
Required: []string{cloud.EndpointKey},
MaxProperties: jsonschema.Int(1),
Properties: map[string]*jsonschema.Schema{
cloud.EndpointKey: &jsonschema.Schema{
Singular: "the API endpoint url for the region",
Type: []jsonschema.Type{jsonschema.StringType},
Format: jsonschema.FormatURI,
Default: "",
PromptDefault: "use cloud api url",
},
},
},
},
},
}
var makeServiceURL = client.AuthenticatingClient.MakeServiceURL
// TODO: shortAttempt was kept to a long timeout because Nova needs
// more time than EC2. Storage delays are handled separately now, and
// perhaps other polling attempts can time out faster.
// shortAttempt is used when polling for short-term events in tests.
var shortAttempt = utils.AttemptStrategy{
Total: 15 * time.Second,
Delay: 200 * time.Millisecond,
}
// Version is part of the EnvironProvider interface.
func (EnvironProvider) Version() int {
return 0
}
func (p EnvironProvider) Open(args environs.OpenParams) (environs.Environ, error) {
logger.Infof("opening model %q", args.Config.Name())
if err := validateCloudSpec(args.Cloud); err != nil {
return nil, errors.Annotate(err, "validating cloud spec")
}
uuid := args.Config.UUID()
namespace, err := instance.NewNamespace(uuid)
if err != nil {
return nil, errors.Annotate(err, "creating instance namespace")
}
e := &Environ{
name: args.Config.Name(),
uuid: uuid,
cloud: args.Cloud,
namespace: namespace,
clock: clock.WallClock,
configurator: p.Configurator,
flavorFilter: p.FlavorFilter,
}
e.firewaller = p.FirewallerFactory.GetFirewaller(e)
var networking Networking = &switchingNetworking{env: e}
if p.NetworkingDecorator != nil {
var err error
networking, err = p.NetworkingDecorator.DecorateNetworking(networking)
if err != nil {
return nil, errors.Trace(err)
}
}
e.networking = networking
if err := e.SetConfig(args.Config); err != nil {
return nil, err
}
e.ecfgMutex.Lock()
defer e.ecfgMutex.Unlock()
client, err := authClient(e.cloud, e.ecfgUnlocked)
if err != nil {
return nil, errors.Annotate(err, "cannot set config")
}
e.clientUnlocked = client
e.novaUnlocked = nova.New(e.clientUnlocked)
e.neutronUnlocked = neutron.New(e.clientUnlocked)
return e, nil
}
// DetectRegions implements environs.CloudRegionDetector.
func (EnvironProvider) DetectRegions() ([]cloud.Region, error) {
// If OS_REGION_NAME and OS_AUTH_URL are both set,
// return return a region using them.
creds := identity.CredentialsFromEnv()
if creds.Region == "" {
return nil, errors.NewNotFound(nil, "OS_REGION_NAME environment variable not set")
}
if creds.URL == "" {
return nil, errors.NewNotFound(nil, "OS_AUTH_URL environment variable not set")
}
return []cloud.Region{{
Name: creds.Region,
Endpoint: creds.URL,
}}, nil
}
// CloudSchema returns the schema for adding new clouds of this type.
func (p EnvironProvider) CloudSchema() *jsonschema.Schema {
return cloudSchema
}
// Ping tests the connection to the cloud, to verify the endpoint is valid.
func (p EnvironProvider) Ping(endpoint string) error {
c := p.ClientFromEndpoint(endpoint)
if _, err := c.IdentityAuthOptions(); err != nil {
return errors.Wrap(err, errors.Errorf("No Openstack server running at %s", endpoint))
}
return nil
}
// newGooseClient is the default function in EnvironProvider.ClientFromEndpoint.
func newGooseClient(endpoint string) client.AuthenticatingClient {
return client.NewClient(&identity.Credentials{URL: endpoint}, 0, nil)
}
// PrepareConfig is specified in the EnvironProvider interface.
func (p EnvironProvider) PrepareConfig(args environs.PrepareConfigParams) (*config.Config, error) {
if err := validateCloudSpec(args.Cloud); err != nil {
return nil, errors.Annotate(err, "validating cloud spec")
}
// Set the default block-storage source.
attrs := make(map[string]interface{})
if _, ok := args.Config.StorageDefaultBlockSource(); !ok {
attrs[config.StorageDefaultBlockSourceKey] = CinderProviderType
}
cfg, err := args.Config.Apply(attrs)
if err != nil {
return nil, errors.Trace(err)
}
return cfg, 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, errors.Errorf("region must be specified")
}
return &simplestreams.MetadataLookupParams{
Region: region,
}, nil
}
func (p EnvironProvider) newConfig(cfg *config.Config) (*environConfig, error) {
valid, err := p.Validate(cfg, nil)
if err != nil {
return nil, err
}
return &environConfig{valid, valid.UnknownAttrs()}, nil
}
type Environ struct {
name string
uuid string
cloud environs.CloudSpec
namespace instance.Namespace
ecfgMutex sync.Mutex
ecfgUnlocked *environConfig
clientUnlocked client.AuthenticatingClient
novaUnlocked *nova.Client
neutronUnlocked *neutron.Client
volumeURL *url.URL
// 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
firewaller Firewaller
networking Networking
configurator ProviderConfigurator
flavorFilter FlavorFilter
// Clock is defined so it can be replaced for testing
clock clock.Clock
}
var _ environs.Environ = (*Environ)(nil)
var _ simplestreams.HasRegion = (*Environ)(nil)
var _ instance.Distributor = (*Environ)(nil)
var _ environs.InstanceTagger = (*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 *string
}
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() instance.InstanceStatus {
instStatus := inst.getServerDetail().Status
jujuStatus := status.Pending
switch instStatus {
case nova.StatusActive:
jujuStatus = status.Running
case nova.StatusError:
jujuStatus = status.ProvisioningError
case nova.StatusBuild, nova.StatusBuildSpawning,
nova.StatusDeleted, nova.StatusHardReboot,
nova.StatusPassword, nova.StatusReboot,
nova.StatusRebuild, nova.StatusRescue,
nova.StatusResize, nova.StatusShutoff,
nova.StatusSuspended, nova.StatusVerifyResize:
jujuStatus = status.Empty
case nova.StatusUnknown:
jujuStatus = status.Unknown
default:
jujuStatus = status.Empty
}
return instance.InstanceStatus{
Status: jujuStatus,
Message: instStatus,
}
}
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 {
floatingIP = *inst.floatingIP
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)
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)
if machineAddr.Type != addrtype {
logger.Warningf("derived address type %v, nova reports %v", machineAddr.Type, addrtype)
}
machineAddresses = append(machineAddresses, machineAddr)
}
}
return machineAddresses
}
func (inst *openstackInstance) OpenPorts(machineId string, rules []network.IngressRule) error {
return inst.e.firewaller.OpenInstancePorts(inst, machineId, rules)
}
func (inst *openstackInstance) ClosePorts(machineId string, rules []network.IngressRule) error {
return inst.e.firewaller.CloseInstancePorts(inst, machineId, rules)
}
func (inst *openstackInstance) IngressRules(machineId string) ([]network.IngressRule, error) {
return inst.e.firewaller.InstanceIngressRules(inst, machineId)
}
func (e *Environ) ecfg() *environConfig {
e.ecfgMutex.Lock()
ecfg := e.ecfgUnlocked
e.ecfgMutex.Unlock()
return ecfg
}
func (e *Environ) client() client.AuthenticatingClient {
e.ecfgMutex.Lock()
client := e.clientUnlocked
e.ecfgMutex.Unlock()
return client
}
func (e *Environ) nova() *nova.Client {
e.ecfgMutex.Lock()
nova := e.novaUnlocked
e.ecfgMutex.Unlock()
return nova
}
func (e *Environ) neutron() *neutron.Client {
e.ecfgMutex.Lock()
neutron := e.neutronUnlocked
e.ecfgMutex.Unlock()
return neutron
}
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.RootDisk, constraints.Cores})
validator.RegisterUnsupported(unsupportedConstraints)
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)
validator.RegisterVocabulary(constraints.VirtType, []string{"kvm", "lxd"})
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, errors.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, errors.Errorf("invalid availability zone %q", availabilityZone)
}
return nil, errors.Errorf("unknown placement directive: %v", placement)
}
// PrecheckInstance is defined on the environs.InstancePrechecker interface.
func (e *Environ) PrecheckInstance(args environs.PrecheckInstanceParams) error {
volumeAttachmentsZone, err := e.volumeAttachmentsZone(args.VolumeAttachments)
if err != nil {
return errors.Trace(err)
}
if _, err := e.instancePlacementZone(args.Placement, volumeAttachmentsZone); 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.
novaClient := e.nova()
flavors, err := novaClient.ListFlavorsDetail()
if err != nil {
return err
}
for _, flavor := range flavors {
if flavor.Name == *args.Constraints.InstanceType {
return nil
}
}
return errors.Errorf("invalid Openstack flavour %q specified", *args.Constraints.InstanceType)
}
// PrepareForBootstrap is part of the Environ interface.
func (e *Environ) PrepareForBootstrap(ctx environs.BootstrapContext) error {
// Verify credentials.
if err := authenticateClient(e.client()); err != nil {
return err
}
if !e.supportsNeutron() {
logger.Warningf(`Using deprecated OpenStack APIs.
Neutron networking is not supported by this OpenStack cloud.
Falling back to deprecated Nova networking.
Support for deprecated Nova networking APIs will be removed
in a future Juju release. Please upgrade to OpenStack Icehouse
or newer to maintain compatibility.
`,
)
}
return nil
}
// Create is part of the Environ interface.
func (e *Environ) Create(environs.CreateParams) error {
// Verify credentials.
if err := authenticateClient(e.client()); err != nil {
return err
}
// TODO(axw) 2016-08-04 #1609643
// Create global security group(s) here.
return nil
}
func (e *Environ) Bootstrap(ctx environs.BootstrapContext, args environs.BootstrapParams) (*environs.BootstrapResult, 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.client()); err != nil {
return nil, err
}
return common.Bootstrap(ctx, e, args)
}
func (e *Environ) supportsNeutron() bool {
client := e.client()
endpointMap := client.EndpointsForRegion(e.cloud.Region)
_, ok := endpointMap["network"]
return ok
}
func (e *Environ) ControllerInstances(controllerUUID string) ([]instance.Id, error) {
// Find all instances tagged with tags.JujuIsController.
instances, err := e.allControllerManagedInstances(controllerUUID, e.ecfg().useFloatingIP())
if err != nil {
return nil, errors.Trace(err)
}
ids := make([]instance.Id, 0, 1)
for _, instance := range instances {
detail := instance.(*openstackInstance).getServerDetail()
if detail.Metadata[tags.JujuIsController] == "true" {
ids = append(ids, instance.Id())
}
}
if len(ids) == 0 {
return nil, environs.ErrNoInstances
}
return ids, nil
}
func (e *Environ) Config() *config.Config {
return e.ecfg().Config
}
func newCredentials(spec environs.CloudSpec) (identity.Credentials, identity.AuthMode) {
credAttrs := spec.Credential.Attributes()
cred := identity.Credentials{
Region: spec.Region,
URL: spec.Endpoint,
TenantName: credAttrs[CredAttrTenantName],
}
// AuthType is validated when the environment is opened, so it's known
// to be one of these values.
var authMode identity.AuthMode
switch spec.Credential.AuthType() {
case cloud.UserPassAuthType:
// TODO(axw) we need a way of saying to use legacy auth.
cred.User = credAttrs[CredAttrUserName]
cred.Secrets = credAttrs[CredAttrPassword]
cred.ProjectDomain = credAttrs[CredAttrProjectDomainName]
cred.UserDomain = credAttrs[CredAttrUserDomainName]
cred.Domain = credAttrs[CredAttrDomainName]
authMode = identity.AuthUserPass
if cred.Domain != "" || cred.UserDomain != "" || cred.ProjectDomain != "" {
authMode = identity.AuthUserPassV3
}
case cloud.AccessKeyAuthType:
cred.User = credAttrs[CredAttrAccessKey]
cred.Secrets = credAttrs[CredAttrSecretKey]
authMode = identity.AuthKeyPair
}
return cred, authMode
}
func determineBestClient(
options identity.AuthOptions,
client client.AuthenticatingClient,
cred identity.Credentials,
newClient func(*identity.Credentials, identity.AuthMode, gooselogging.CompatLogger) client.AuthenticatingClient,
logger gooselogging.CompatLogger,
) client.AuthenticatingClient {
for _, option := range options {
if option.Mode != identity.AuthUserPassV3 {
continue
}
cred.URL = option.Endpoint
v3client := newClient(&cred, identity.AuthUserPassV3, logger)
// V3 being advertised is not necessaritly a guarantee that it will
// work.
err := v3client.Authenticate()
if err == nil {
return v3client
}
}
return client
}
func authClient(spec environs.CloudSpec, ecfg *environConfig) (client.AuthenticatingClient, error) {
identityClientVersion, err := identityClientVersion(spec.Endpoint)
if err != nil {
return nil, errors.Annotate(err, "cannot create a client")
}
cred, authMode := newCredentials(spec)
gooseLogger := gooselogging.LoggoLogger{loggo.GetLogger("goose")}
newClient := client.NewClient
if ecfg.SSLHostnameVerification() == false {
newClient = client.NewNonValidatingClient
}
client := newClient(&cred, authMode, gooseLogger)
// before returning, lets make sure that we want to have AuthMode
// AuthUserPass instead of its V3 counterpart.
if authMode == identity.AuthUserPass && (identityClientVersion == -1 || identityClientVersion == 3) {
options, err := client.IdentityAuthOptions()
if err != nil {
logger.Errorf("cannot determine available auth versions %v", err)
} else {
client = determineBestClient(
options,
client,
cred,
newClient,
gooseLogger,
)
}
}
// Juju requires "compute" at a minimum. We'll use "network" if it's
// available in preference to the Nova network APIs; and "volume" or
// "volume2" for storage if either one is available.
client.SetRequiredServiceTypes([]string{"compute"})
return client, nil
}
type authenticator interface {
Authenticate() error
}
var authenticateClient = func(auth authenticator) error {
err := auth.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 model 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
return nil
}
func identityClientVersion(authURL string) (int, error) {
url, err := url.Parse(authURL)
if err != nil {
// Return 0 as this is the lowest invalid number according to openstack codebase:
// -1 is reserved and has special handling; 1, 2, 3, etc are valid identity client versions.
return 0, err
}
if url.Path == authURL {
// This means we could not parse URL into url structure
// with protocols, domain, port, etc.
// For example, specifying "keystone.foo" instead of "https://keystone.foo:443/v3/"
// falls into this category.
return 0, errors.Errorf("url %s is malformed", authURL)
}
if url.Path == "" || url.Path == "/" {
// User explicitely did not provide any version, it is empty.
return -1, nil
}
// The last part of the path should be the version #.
// Example: https://keystone.foo:443/v3/
versionNumStr := strings.TrimPrefix(strings.ToLower(url.Path), "/v")
versionNumStr = strings.TrimSuffix(versionNumStr, "/")
if versionNumStr == url.Path || versionNumStr == "" {
// If nothing was trimmed, version specification was malformed.
// If nothing was left after trim, version number is not provided and,
// hence, version specification was malformed.
// At this stage only '/Vxxx' and '/vxxx' are valid where xxx is major.minor version.
// Return 0 as this is the lowest invalid number according to openstack codebase:
// -1 is reserved and has special handling; 1, 2, 3, etc are valid identity client versions.
return 0, errors.NotValidf("version part of identity url %s", authURL)
}
logger.Tracef("authURL: %s", authURL)
major, _, err := version.ParseMajorMinor(versionNumStr)
return major, err
}
// 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 model")
}
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 model")
}
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
}
client := e.client()
if !client.IsAuthenticated() {
if err := authenticateClient(client); err != nil {
return nil, err
}
}
url, err := makeServiceURL(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, simplestreams.SPECIFIC_CLOUD_DATA, false)
return *datasource, nil
}
// assignPublicIP tries to assign the given floating IP address to the
// specified server, or returns an error.
func (e *Environ) assignPublicIP(fip *string, serverId string) (err error) {
if *fip == "" {
return errors.Errorf("cannot assign a nil public IP to %q", serverId)
}
// 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)
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) {
if args.ControllerUUID == "" {
return nil, errors.New("missing controller UUID")
}
availabilityZones, err := e.startInstanceAvailabilityZones(args)
if err != nil {
return nil, errors.Trace(err)
}
series := args.Tools.OneSeries()
arches := args.Tools.Arches()
spec, err := findInstanceSpec(e, &instances.InstanceConstraint{
Region: e.cloud.Region,
Series: series,
Arches: arches,
Constraints: args.Constraints,
}, args.ImageMetadata)
if err != nil {
return nil, err
}
tools, err := args.Tools.Match(tools.Filter{Arch: spec.Image.Arch})
if err != nil {
return nil, errors.Errorf("chosen architecture %v not present in %v", spec.Image.Arch, arches)
}
if err := args.InstanceConfig.SetTools(tools); err != nil {
return nil, errors.Trace(err)
}
if err := instancecfg.FinishInstanceConfig(args.InstanceConfig, e.Config()); err != nil {
return nil, err
}
cloudcfg, err := e.configurator.GetCloudConfig(args)
if err != nil {
return nil, errors.Trace(err)
}
userData, err := providerinit.ComposeUserData(args.InstanceConfig, cloudcfg, OpenstackRenderer{})
if err != nil {
return nil, errors.Annotate(err, "cannot make user data")
}
logger.Debugf("openstack user data; %d bytes", len(userData))
networks, err := e.networking.DefaultNetworks()
if err != nil {
return nil, errors.Annotate(err, "getting initial networks")
}
usingNetwork := e.ecfg().network()
if usingNetwork != "" {
networkId, err := e.networking.ResolveNetwork(usingNetwork, false)
if err != nil {
return nil, err
}
logger.Debugf("using network id %q", networkId)
networks = append(networks, nova.ServerNetworks{NetworkId: networkId})
}
// For BUG 1680787: openstack: add support for neutron networks where port
// security is disabled.
// If any network specified for instance boot has PortSecurityEnabled equals
// false, don't create security groups, instance boot will fail.
createSecurityGroups := true
if len(networks) > 0 && e.supportsNeutron() {
client := e.neutron()
for _, n := range networks {
net, err := client.GetNetworkV2(n.NetworkId)