/
add.go
809 lines (721 loc) · 24.8 KB
/
add.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
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package cloud
import (
"fmt"
"io/ioutil"
"sort"
"strings"
"github.com/juju/cmd"
"github.com/juju/errors"
"github.com/juju/gnuflag"
"github.com/juju/utils"
"github.com/juju/utils/cert"
"gopkg.in/juju/names.v3"
"gopkg.in/yaml.v2"
cloudapi "github.com/juju/juju/api/cloud"
"github.com/juju/juju/apiserver/params"
jujucloud "github.com/juju/juju/cloud"
jujucmd "github.com/juju/juju/cmd"
"github.com/juju/juju/cmd/juju/common"
"github.com/juju/juju/cmd/juju/interact"
"github.com/juju/juju/cmd/modelcmd"
"github.com/juju/juju/environs"
"github.com/juju/juju/environs/context"
"github.com/juju/juju/jujuclient"
)
type PersonalCloudMetadataStore interface {
PersonalCloudMetadata() (map[string]jujucloud.Cloud, error)
WritePersonalCloudMetadata(cloudsMap map[string]jujucloud.Cloud) error
}
type CloudMetadataStore interface {
ParseCloudMetadataFile(path string) (map[string]jujucloud.Cloud, error)
ParseOneCloud(data []byte) (jujucloud.Cloud, error)
PublicCloudMetadata(searchPaths ...string) (result map[string]jujucloud.Cloud, fallbackUsed bool, _ error)
PersonalCloudMetadataStore
}
var usageAddCloudSummary = `
Adds a cloud definition to Juju.`[1:]
var usageAddCloudDetails = `
Juju needs to know how to connect to clouds. A cloud definition
describes a cloud's endpoints and authentication requirements. Each
definition is stored and accessed later as <cloud name>.
If you are accessing a public cloud, running add-cloud is unlikely to be
necessary. Juju already contains definitions for the public cloud
providers it supports.
add-cloud operates in two modes:
juju add-cloud
juju add-cloud <cloud name> <cloud definition file>
When invoked without arguments, add-cloud begins an interactive session
designed for working with private clouds. The session will enable you
to instruct Juju how to connect to your private cloud.
A cloud definition can be provided in a file either as an option --f or as a
positional argument:
juju add-cloud mycloud ~/mycloud.yaml
juju add-cloud mycloud -f ~/mycloud.yaml
When <cloud definition file> is provided with <cloud name>,
Juju will validate the content of the file and add this cloud
to this client as well as upload it to a controller.
Use --controller option to upload a cloud to a controller.
Use --client option to add cloud to the current client.
DEPRECATED (use 'update-credential' instead)
If <cloud name> already exists on this client, then the `[1:] + "`--replace`" + `
option is required.
A cloud definition file has the following YAML format:
clouds: # mandatory
mycloud: # <cloud name> argument
type: openstack # <cloud type>, see below
auth-types: [ userpass ]
regions:
london:
endpoint: https://london.mycloud.com:35574/v3.0/
<cloud types> for private clouds:
- lxd
- maas
- manual
- openstack
- vsphere
<cloud types> for public clouds:
- azure
- cloudsigma
- ec2
- gce
- joyent
- oci
When a running controller is updated, the credential for the cloud
is also uploaded. As with the cloud, the credential needs
to have been added to the current client, use add-credential to
do that. If there's only one credential for the cloud it will be
uploaded to the controller automatically by add-cloud command.
However, if the cloud has multiple credentials on this client
you can specify which to upload with the --credential option.
When adding clouds to a controller, some clouds are whitelisted and can be easily added:
%v
Other cloud combinations can only be force added as the user must consider
network routability, etc - concerns that are outside of scope of Juju.
When forced addition is desired, use --force.
Examples:
juju add-cloud
juju add-cloud --force
juju add-cloud mycloud ~/mycloud.yaml
juju add-cloud --controller mycontroller mycloud
juju add-cloud --controller mycontroller mycloud --credential mycred
juju add-cloud --client mycloud ~/mycloud.yaml
See also:
clouds
update-cloud
remove-cloud
update-credential`
// AddCloudAPI - Implemented by cloudapi.Client.
type AddCloudAPI interface {
AddCloud(jujucloud.Cloud, bool) error
AddCredential(tag string, credential jujucloud.Credential) error
Close() error
}
// AddCloudCommand is the command that allows you to add a cloud configuration
// for use with juju bootstrap.
type AddCloudCommand struct {
modelcmd.OptionalControllerCommand
// Replace, if true, existing cloud information is overwritten.
// TODO (anastasiamac 2019-6-4) Remove as redundant and unsupported for Juju 3.
Replace bool
// Cloud is the name of the cloud to add.
Cloud string
// CloudFile is the name of the cloud YAML file.
CloudFile string
// Ping contains the logic for pinging a cloud endpoint to know whether or
// not it really has a valid cloud of the same type as the provider. By
// default it just calls the correct provider's Ping method.
Ping func(p environs.EnvironProvider, endpoint string) error
// CloudCallCtx contains context to be used for any cloud calls.
CloudCallCtx *context.CloudCallContext
cloudMetadataStore CloudMetadataStore
// These attributes are used when adding a cloud to a controller.
credentialName string
addCloudAPIFunc func() (AddCloudAPI, error)
// Force holds whether user wants to force addition of the cloud.
Force bool
// existsLocally whether this cloud already exists locally.
existsLocally bool
}
// NewAddCloudCommand returns a command to add cloud information.
func NewAddCloudCommand(cloudMetadataStore CloudMetadataStore) cmd.Command {
cloudCallCtx := context.NewCloudCallContext()
store := jujuclient.NewFileClientStore()
c := &AddCloudCommand{
OptionalControllerCommand: modelcmd.OptionalControllerCommand{
Store: store,
},
cloudMetadataStore: cloudMetadataStore,
CloudCallCtx: cloudCallCtx,
// Ping is provider.Ping except in tests where we don't actually want to
// require a valid cloud.
Ping: func(p environs.EnvironProvider, endpoint string) error {
return p.Ping(cloudCallCtx, endpoint)
},
}
c.addCloudAPIFunc = c.cloudAPI
return modelcmd.WrapBase(c)
}
func (c *AddCloudCommand) cloudAPI() (AddCloudAPI, error) {
root, err := c.NewAPIRoot(c.Store, c.ControllerName, "")
if err != nil {
return nil, errors.Trace(err)
}
return cloudapi.NewClient(root), nil
}
// Info returns help information about the command.
func (c *AddCloudCommand) Info() *cmd.Info {
return jujucmd.Info(&cmd.Info{
Name: "add-cloud",
Args: "<cloud name> [<cloud definition file>]",
Purpose: usageAddCloudSummary,
Doc: fmt.Sprintf(usageAddCloudDetails, jujucloud.CurrentWhiteList()),
})
}
// SetFlags initializes the flags supported by the command.
func (c *AddCloudCommand) SetFlags(f *gnuflag.FlagSet) {
c.OptionalControllerCommand.SetFlags(f)
f.BoolVar(&c.Replace, "replace", false, "DEPRECATED: Overwrite any existing cloud information for <cloud name>")
f.BoolVar(&c.Force, "force", false, "Force add cloud to the controller")
f.StringVar(&c.CloudFile, "f", "", "The path to a cloud definition file")
f.StringVar(&c.CloudFile, "file", "", "The path to a cloud definition file")
f.StringVar(&c.credentialName, "credential", "", "Credential to use for new cloud")
}
// Init populates the command with the args from the command line.
func (c *AddCloudCommand) Init(args []string) (err error) {
if err := c.OptionalControllerCommand.Init(args); err != nil {
return err
}
if len(args) > 0 {
c.Cloud = args[0]
if ok := names.IsValidCloud(c.Cloud); !ok {
return errors.NotValidf("cloud name %q", c.Cloud)
}
}
if len(args) > 1 {
if c.CloudFile != args[1] && c.CloudFile != "" {
return errors.BadRequestf("cannot specify cloud file with option and argument")
}
c.CloudFile = args[1]
}
if len(args) > 2 {
return cmd.CheckEmpty(args[2:])
}
return nil
}
var ambiguousCredentialError = errors.New(`
more than one credential is available
specify a credential using the --credential argument`[1:],
)
func (c *AddCloudCommand) findLocalCredential(ctx *cmd.Context, cloud jujucloud.Cloud, credentialName string) (*jujucloud.Credential, string, error) {
credential, chosenCredentialName, _, err := modelcmd.GetCredentials(ctx, c.Store, modelcmd.GetCredentialsParams{
Cloud: cloud,
CredentialName: credentialName,
})
if err == nil {
return credential, chosenCredentialName, nil
}
switch errors.Cause(err) {
case modelcmd.ErrMultipleCredentials:
return nil, "", ambiguousCredentialError
}
return nil, "", errors.Trace(err)
}
func (c *AddCloudCommand) addCredentialToController(ctx *cmd.Context, cloud jujucloud.Cloud, apiClient AddCloudAPI) error {
_, err := c.Store.ControllerByName(c.ControllerName)
if err != nil {
return errors.Trace(err)
}
currentAccountDetails, err := c.Store.AccountDetails(c.ControllerName)
if err != nil {
return errors.Trace(err)
}
cred, credentialName, err := c.findLocalCredential(ctx, cloud, c.credentialName)
if err != nil {
return errors.Trace(err)
}
id := fmt.Sprintf("%s/%s/%s", c.Cloud, currentAccountDetails.User, credentialName)
if !names.IsValidCloudCredential(id) {
return errors.NotValidf("cloud credential ID %q", id)
}
cloudCredTag := names.NewCloudCredentialTag(id)
if err := apiClient.AddCredential(cloudCredTag.String(), *cred); err != nil {
return errors.Trace(err)
}
return nil
}
// Run executes the add cloud command, adding a cloud based on a passed-in yaml
// file or interactive queries.
func (c *AddCloudCommand) Run(ctxt *cmd.Context) error {
if c.Replace {
ctxt.Warningf("'add-cloud --replace' is deprecated. Use 'update-cloud' instead.")
}
var newCloud *jujucloud.Cloud
var err error
if c.CloudFile != "" {
newCloud, err = c.readCloudFromFile(ctxt)
} else {
if c.Cloud != "" {
// It's possible that the user wants to add an existing local cloud to a current controller,
// i.e. 'juju add-cloud aws'. So let's see if we can find the cloud.
newCloud, err = common.CloudByName(c.Cloud)
c.existsLocally = err == nil
}
if !c.existsLocally {
newCloud, err = c.runInteractive(ctxt)
}
}
if err != nil {
return errors.Trace(err)
}
if err := c.MaybePrompt(ctxt, fmt.Sprintf("add cloud %q to", newCloud.Name)); err != nil {
return errors.Trace(err)
}
// All clouds must have at least one default region - lp#1819409.
if len(newCloud.Regions) == 0 {
newCloud.Regions = []jujucloud.Region{{Name: jujucloud.DefaultCloudRegion}}
}
var returnErr error
if c.Replace || (c.Client && !c.existsLocally) {
returnErr = c.addLocalCloud(ctxt, newCloud)
}
if !c.Replace && (c.Client && c.existsLocally) {
returnErr = errors.AlreadyExistsf("use `update-cloud %s --client` to override known definition: local cloud %q", newCloud.Name, newCloud.Name)
}
if c.Client && c.ControllerName != "" {
ctxt.Infof("")
}
if c.ControllerName != "" {
if err = c.addRemoteCloud(ctxt, newCloud); err != nil {
ctxt.Infof("Could not upload cloud to a controller: %v", err)
returnErr = cmd.ErrSilent
}
}
return returnErr
}
func (c *AddCloudCommand) addRemoteCloud(ctxt *cmd.Context, newCloud *jujucloud.Cloud) error {
// A controller has been specified so upload the cloud details
// plus a corresponding credential to the controller.
api, err := c.addCloudAPIFunc()
if err != nil {
return err
}
defer api.Close()
err = api.AddCloud(*newCloud, c.Force)
if err != nil {
if params.ErrCode(err) == params.CodeAlreadyExists {
ctxt.Infof("Cloud %q already exists on the controller %q.", c.Cloud, c.ControllerName)
ctxt.Infof("To upload a credential to the controller for cloud %q, use \n"+
"* 'add-model' with --credential option or\n"+
"* 'add-credential -c %v'.", newCloud.Name, newCloud.Name)
return nil
}
if params.ErrCode(err) == params.CodeIncompatibleClouds {
logger.Infof("%v", err)
ctxt.Infof("Adding a cloud of type %q might not function correctly on this controller.\n"+
"If you really want to do this, use --force.", newCloud.Type)
return nil
}
return err
}
ctxt.Infof("Cloud %q added to controller %q.", c.Cloud, c.ControllerName)
// Add a credential for the newly added cloud.
err = c.addCredentialToController(ctxt, *newCloud, api)
if err != nil {
logger.Warningf("%v", err)
ctxt.Infof("To upload a credential to the controller for cloud %q, use \n"+
"* 'add-model' with --credential option or\n"+
"* 'add-credential -c %v'.", newCloud.Name, newCloud.Name)
return nil
}
ctxt.Infof("Credential for cloud %q added to controller %q.", c.Cloud, c.ControllerName)
return nil
}
func (c *AddCloudCommand) addLocalCloud(ctxt *cmd.Context, newCloud *jujucloud.Cloud) error {
operation := "added"
if c.Replace {
operation = "updated"
}
if err := addLocalCloud(c.cloudMetadataStore, *newCloud); err != nil {
ctxt.Infof("Cloud %q was not %v locally: %v", newCloud.Name, operation, err)
return cmd.ErrSilent
}
ctxt.Infof("Cloud %q successfully %v to your local client.", newCloud.Name, operation)
if len(newCloud.AuthTypes) != 0 {
ctxt.Infof("You will need to add a credential for this cloud (`juju add-credential %s`)", newCloud.Name)
ctxt.Infof("before you can use it to bootstrap a controller (`juju bootstrap %s`) or", newCloud.Name)
ctxt.Infof("to create a model (`juju add-model <your model name> %s`).", newCloud.Name)
}
return nil
}
func cloudFromLocal(store jujuclient.CredentialGetter, cloudName string) (*jujucloud.Cloud, error) {
details, err := listLocalCloudDetails(store)
if err != nil {
return nil, err
}
cloudDetails, ok := details.all()[cloudName]
if !ok {
return nil, errors.NotFoundf("cloud %q", cloudName)
}
newCloud := &jujucloud.Cloud{
Name: cloudName,
Type: cloudDetails.CloudType,
Description: cloudDetails.CloudDescription,
Endpoint: cloudDetails.Endpoint,
IdentityEndpoint: cloudDetails.IdentityEndpoint,
StorageEndpoint: cloudDetails.StorageEndpoint,
CACertificates: cloudDetails.CACredentials,
Config: cloudDetails.Config,
RegionConfig: cloudDetails.RegionConfig,
}
for _, at := range cloudDetails.AuthTypes {
newCloud.AuthTypes = append(newCloud.AuthTypes, jujucloud.AuthType(at))
}
for name, r := range cloudDetails.RegionsMap {
newCloud.Regions = append(newCloud.Regions, jujucloud.Region{
Name: name,
Endpoint: r.Endpoint,
StorageEndpoint: r.StorageEndpoint,
IdentityEndpoint: r.IdentityEndpoint,
})
}
return newCloud, nil
}
func (c *AddCloudCommand) readCloudFromFile(ctxt *cmd.Context) (*jujucloud.Cloud, error) {
r := &cloudFileReader{
cloudMetadataStore: c.cloudMetadataStore,
cloudName: c.Cloud,
}
newCloud, err := r.readCloudFromFile(c.CloudFile, ctxt)
if err != nil {
return nil, errors.Trace(err)
}
c.Cloud = r.cloudName
c.existsLocally = r.alreadyExists
return newCloud, nil
}
func (c *AddCloudCommand) runInteractive(ctxt *cmd.Context) (*jujucloud.Cloud, error) {
errout := interact.NewErrWriter(ctxt.Stdout)
pollster := interact.New(ctxt.Stdin, ctxt.Stdout, errout)
cloudType, err := queryCloudType(pollster)
if err != nil {
return nil, errors.Trace(err)
}
name, err := queryName(c.cloudMetadataStore, c.Cloud, cloudType, pollster)
if err != nil {
return nil, errors.Trace(err)
}
provider, err := environs.Provider(cloudType)
if err != nil {
return nil, errors.Trace(err)
}
// At this stage, since we do not have a reference to any model, nor can we get it,
// nor do we need to have a model for anything that this command does,
// no cloud credential stored server-side can be invalidated.
// So, just log an informative message.
c.CloudCallCtx.InvalidateCredentialFunc = func(reason string) error {
ctxt.Infof("Cloud credential is not accepted by cloud provider: %v", reason)
return nil
}
// VerifyURLs will return true if a schema format type jsonschema.FormatURI is used
// and the value will Ping().
pollster.VerifyURLs = func(s string) (bool, string, error) {
err := c.Ping(provider, s)
if err != nil {
return false, "Can't validate endpoint: " + err.Error(), nil
}
return true, "", nil
}
// VerifyCertFile will return true if the schema format type "cert-filename" is used
// and the value is readable and a valid cert file.
pollster.VerifyCertFile = func(s string) (bool, string, error) {
out, err := ioutil.ReadFile(s)
if err != nil {
return false, "Can't validate CA Certificate file: " + err.Error(), nil
}
if _, err := cert.ParseCert(string(out)); err != nil {
return false, fmt.Sprintf("Can't validate CA Certificate %s: %s", s, err.Error()), nil
}
return true, "", nil
}
v, err := pollster.QuerySchema(provider.CloudSchema())
if err != nil {
return nil, errors.Trace(err)
}
b, err := yaml.Marshal(v)
if err != nil {
return nil, errors.Trace(err)
}
filename, alt, err := addCertificate(b)
switch {
case errors.IsNotFound(err):
case err != nil:
return nil, errors.Annotate(err, "CA Certificate")
default:
ctxt.Infof("Successfully read CA Certificate from %s", filename)
b = alt
}
newCloud, err := c.cloudMetadataStore.ParseOneCloud(b)
if err != nil {
return nil, errors.Trace(err)
}
newCloud.Name = name
newCloud.Type = cloudType
return &newCloud, nil
}
// addCertificate reads the cloud certificate file if available and adds the contents
// to the byte slice with the appropriate key. A NotFound error is returned if
// a cloud.CertFilenameKey is not contained in the data, or the value is empty, this is
// not a fatal error.
func addCertificate(data []byte) (string, []byte, error) {
vals, err := ensureStringMaps(string(data))
if err != nil {
return "", nil, err
}
name, ok := vals[jujucloud.CertFilenameKey]
if !ok {
return "", nil, errors.NotFoundf("yaml has no certificate file")
}
filename := name.(string)
if ok && filename != "" {
out, err := ioutil.ReadFile(filename)
if err != nil {
return filename, nil, err
}
certificate := string(out)
if _, err := cert.ParseCert(certificate); err != nil {
return filename, nil, errors.Annotate(err, "bad cloud CA certificate")
}
vals["ca-certificates"] = []string{certificate}
} else {
return filename, nil, errors.NotFoundf("yaml has no certificate file")
}
alt, err := yaml.Marshal(vals)
return filename, alt, err
}
func ensureStringMaps(in string) (map[string]interface{}, error) {
userDataMap := make(map[string]interface{})
if err := yaml.Unmarshal([]byte(in), &userDataMap); err != nil {
return nil, errors.Annotate(err, "must be valid YAML")
}
out, err := utils.ConformYAML(userDataMap)
if err != nil {
return nil, err
}
return out.(map[string]interface{}), nil
}
func queryName(
cloudMetadataStore CloudMetadataStore,
cloudName string,
cloudType string,
pollster *interact.Pollster,
) (string, error) {
public, _, err := cloudMetadataStore.PublicCloudMetadata()
if err != nil {
return "", err
}
personal, err := cloudMetadataStore.PersonalCloudMetadata()
if err != nil {
return "", err
}
verifyCloudName := func(name string) (bool, string, error) {
if names.IsValidCloud(name) {
return true, "", nil
}
return false, "Invalid name. Valid names start with a letter, and use only letters, numbers, hyphens, and underscores: ", nil
}
for {
if cloudName == "" {
name, err := pollster.EnterVerify(fmt.Sprintf("a name for your %s cloud", cloudType), verifyCloudName)
if err != nil {
return "", errors.Trace(err)
}
cloudName = name
}
if _, ok := personal[cloudName]; ok {
override, err := pollster.YN(fmt.Sprintf("A cloud named %q already exists. Do you want to replace that definition", cloudName), false)
if err != nil {
return "", errors.Trace(err)
}
if override {
return cloudName, nil
}
// else, ask again
cloudName = ""
continue
}
msg, err := nameExists(cloudName, public)
if err != nil {
return "", errors.Trace(err)
}
if msg == "" {
return cloudName, nil
}
override, err := pollster.YN(msg+", do you want to override that definition", false)
if err != nil {
return "", errors.Trace(err)
}
if override {
return cloudName, nil
}
// else, ask again
}
}
// addableCloudProviders returns the names of providers supported by add-cloud,
// and also the names of those which are not supported.
func addableCloudProviders() (providers []string, unsupported []string, _ error) {
allproviders := environs.RegisteredProviders()
for _, name := range allproviders {
provider, err := environs.Provider(name)
if err != nil {
// should be impossible
return nil, nil, errors.Trace(err)
}
if provider.CloudSchema() != nil {
providers = append(providers, name)
} else {
unsupported = append(unsupported, name)
}
}
sort.Strings(providers)
return providers, unsupported, nil
}
func queryCloudType(pollster *interact.Pollster) (string, error) {
providers, unsupported, err := addableCloudProviders()
if err != nil {
// should be impossible
return "", errors.Trace(err)
}
supportedCloud := interact.VerifyOptions("cloud type", providers, false)
cloudVerify := func(s string) (ok bool, errmsg string, err error) {
ok, errmsg, err = supportedCloud(s)
if err != nil {
return false, "", errors.Trace(err)
}
if ok {
return true, "", nil
}
// Print out a different message if they entered a valid provider that
// just isn't something we want people to add (like ec2).
for _, name := range unsupported {
if strings.ToLower(name) == strings.ToLower(s) {
return false, fmt.Sprintf("Cloud type %q not supported for interactive add-cloud.", s), nil
}
}
return false, errmsg, nil
}
return pollster.SelectVerify(interact.List{
Singular: "cloud type",
Plural: "cloud types",
Options: providers,
}, cloudVerify)
}
func addLocalCloud(cloudMetadataStore PersonalCloudMetadataStore, newCloud jujucloud.Cloud) error {
personalClouds, err := cloudMetadataStore.PersonalCloudMetadata()
if err != nil {
return err
}
if personalClouds == nil {
personalClouds = make(map[string]jujucloud.Cloud)
}
personalClouds[newCloud.Name] = newCloud
return cloudMetadataStore.WritePersonalCloudMetadata(personalClouds)
}
type cloudFileReader struct {
cloudMetadataStore CloudMetadataStore
cloudName string
alreadyExists bool
}
func (p *cloudFileReader) readCloudFromFile(cloudFile string, ctxt *cmd.Context) (*jujucloud.Cloud, error) {
specifiedClouds, err := p.cloudMetadataStore.ParseCloudMetadataFile(cloudFile)
if err != nil {
return nil, errors.Trace(err)
}
if len(specifiedClouds) == 0 {
return nil, errors.New("no personal clouds are defined")
}
var newCloud jujucloud.Cloud
if p.cloudName == "" {
if len(specifiedClouds) == 1 {
for k, v := range specifiedClouds {
newCloud = v
// User did not specify cloud name aka as a command argument,
// use what is in th file.
p.cloudName = k
}
} else {
if p.cloudName == "" {
return nil, errors.Errorf("there is more than one cloud defined in file %q, specify a cloud name to select one", cloudFile)
}
}
} else {
var ok bool
newCloud, ok = specifiedClouds[p.cloudName]
if !ok {
return nil, errors.Errorf("cloud %q not found in file %q", p.cloudName, cloudFile)
}
}
// first validate cloud input
data, err := ioutil.ReadFile(cloudFile)
if err != nil {
return nil, errors.Trace(err)
}
if err = jujucloud.ValidateCloudSet(data); err != nil {
ctxt.Warningf(err.Error())
}
// validate cloud data
provider, err := environs.Provider(newCloud.Type)
if err != nil {
return nil, errors.Trace(err)
}
schemas := provider.CredentialSchemas()
for _, authType := range newCloud.AuthTypes {
if _, defined := schemas[authType]; !defined {
return nil, errors.NotSupportedf("auth type %q", authType)
}
}
if err := p.verifyName(p.cloudName); err != nil {
if !errors.IsAlreadyExists(err) {
return nil, errors.Trace(err)
}
p.alreadyExists = true
}
return &newCloud, nil
}
func (p *cloudFileReader) verifyName(name string) error {
public, _, err := p.cloudMetadataStore.PublicCloudMetadata()
if err != nil {
return err
}
personal, err := p.cloudMetadataStore.PersonalCloudMetadata()
if err != nil {
return err
}
if _, ok := personal[name]; ok {
return errors.AlreadyExistsf("use `update-cloud %s --client` to replace this cloud locally: %q", name, name)
}
msg, err := nameExists(name, public)
if err != nil {
return errors.Trace(err)
}
if msg != "" {
return errors.AlreadyExistsf(msg + "; use `update-cloud --client` to override this definition locally")
}
return nil
}
// nameExists returns either an empty string if the name does not exist, or a
// non-empty string with an error message if it does exist.
func nameExists(name string, public map[string]jujucloud.Cloud) (string, error) {
if _, ok := public[name]; ok {
return fmt.Sprintf("%q is the name of a public cloud", name), nil
}
builtin, err := common.BuiltInClouds()
if err != nil {
return "", errors.Trace(err)
}
if _, ok := builtin[name]; ok {
return fmt.Sprintf("%q is the name of a built-in cloud", name), nil
}
return "", nil
}