-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.go
752 lines (670 loc) · 23.8 KB
/
base.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package modelcmd
import (
"bufio"
"context"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/go-macaroon-bakery/macaroon-bakery/v3/httpbakery"
"github.com/juju/cmd"
"github.com/juju/errors"
"github.com/juju/gnuflag"
"github.com/juju/names/v4"
"golang.org/x/crypto/ssh/terminal"
"github.com/juju/juju/api"
"github.com/juju/juju/api/authentication"
"github.com/juju/juju/api/base"
"github.com/juju/juju/api/modelmanager"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/cloud"
"github.com/juju/juju/core/network"
"github.com/juju/juju/environs"
environscloudspec "github.com/juju/juju/environs/cloudspec"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/juju"
"github.com/juju/juju/jujuclient"
"github.com/juju/juju/pki"
)
var errNoNameSpecified = errors.New("no name specified")
type modelMigratedError string
func newModelMigratedError(store jujuclient.ClientStore, modelName string, redirErr *api.RedirectError) error {
// Check if this is a known controller
allEndpoints := network.CollapseToHostPorts(redirErr.Servers).Strings()
_, existingName, err := store.ControllerByAPIEndpoints(allEndpoints...)
if err != nil && !errors.IsNotFound(err) {
return err
}
if existingName != "" {
mErr := fmt.Sprintf(`Model %q has been migrated to controller %q.
To access it run 'juju switch %s:%s'.`, modelName, existingName, existingName, modelName)
return modelMigratedError(mErr)
}
// CACerts are always valid so no error checking is required here.
fingerprint, _, err := pki.Fingerprint([]byte(redirErr.CACert))
if err != nil {
return err
}
ctrlAlias := "new-controller"
if redirErr.ControllerAlias != "" {
ctrlAlias = redirErr.ControllerAlias
}
var loginCmds []string
for _, endpoint := range allEndpoints {
loginCmds = append(loginCmds, fmt.Sprintf(" 'juju login %s -c %s'", endpoint, ctrlAlias))
}
mErr := fmt.Sprintf(`Model %q has been migrated to another controller.
To access it run one of the following commands (you can replace the -c argument with your own preferred controller name):
%s
New controller fingerprint [%s]`, modelName, strings.Join(loginCmds, "\n"), fingerprint)
return modelMigratedError(mErr)
}
func (e modelMigratedError) Error() string {
return string(e)
}
// IsModelMigratedError returns true if err is of type modelMigratedError.
func IsModelMigratedError(err error) bool {
_, ok := errors.Cause(err).(modelMigratedError)
return ok
}
// Command extends cmd.Command with a closeContext method.
// It is implicitly implemented by any type that embeds CommandBase.
type Command interface {
cmd.Command
// SetAPIOpen sets the function used for opening an API connection.
SetAPIOpen(opener api.OpenFunc)
// SetModelAPI sets the api used to access model information.
SetModelAPI(api ModelAPI)
// SetEmbedded sets whether the command is being run inside a controller.
SetEmbedded(bool)
// closeAPIContexts closes any API contexts that have been opened.
closeAPIContexts()
initContexts(*cmd.Context)
setRunStarted()
}
// ModelAPI provides access to the model client facade methods.
type ModelAPI interface {
ListModels(user string) ([]base.UserModel, error)
Close() error
}
// CommandBase is a convenience type for embedding that need
// an API connection.
type CommandBase struct {
cmd.CommandBase
cmdContext *cmd.Context
apiContexts map[string]*apiContext
modelAPI_ ModelAPI
apiOpenFunc api.OpenFunc
authOpts AuthOpts
runStarted bool
refreshModels func(jujuclient.ClientStore, string) error
// StdContext is the Go context.
StdContext context.Context
// CanClearCurrentModel indicates that this command can reset current model in local cache, aka client store.
CanClearCurrentModel bool
// Embedded is true if this command is being run inside a controller.
Embedded bool
// filesystem provides access to os calls to access files.
// For embedded commands, methods will always return an error.
filesystem Filesystem
}
func (c *CommandBase) assertRunStarted() {
if !c.runStarted {
panic("inappropriate method called at init time")
}
}
func (c *CommandBase) setRunStarted() {
c.runStarted = true
}
// closeAPIContexts closes any API contexts that have
// been created.
func (c *CommandBase) closeAPIContexts() {
for name, ctx := range c.apiContexts {
if err := ctx.Close(); err != nil {
logger.Errorf("%v", err)
}
delete(c.apiContexts, name)
}
}
// SetEmbedded sets whether the command is embedded.
func (c *CommandBase) SetEmbedded(embedded bool) {
c.Embedded = embedded
if embedded {
c.filesystem = restrictedFilesystem{}
} else {
c.filesystem = osFilesystem{}
}
}
// SetFlags implements cmd.Command.SetFlags.
func (c *CommandBase) SetFlags(f *gnuflag.FlagSet) {
c.authOpts.SetFlags(f)
}
// SetModelAPI sets the api used to access model information.
func (c *CommandBase) SetModelAPI(api ModelAPI) {
c.modelAPI_ = api
}
// SetAPIOpen sets the function used for opening an API connection.
func (c *CommandBase) SetAPIOpen(apiOpen api.OpenFunc) {
c.apiOpenFunc = apiOpen
}
// SetModelRefresh sets the function used for refreshing models.
func (c *CommandBase) SetModelRefresh(refresh func(jujuclient.ClientStore, string) error) {
c.refreshModels = refresh
}
func (c *CommandBase) modelAPI(store jujuclient.ClientStore, controllerName string) (ModelAPI, error) {
c.assertRunStarted()
if c.modelAPI_ != nil {
return c.modelAPI_, nil
}
conn, err := c.NewAPIRoot(store, controllerName, "")
if err != nil {
return nil, errors.Trace(err)
}
c.modelAPI_ = modelmanager.NewClient(conn)
return c.modelAPI_, nil
}
// NewAPIRoot returns a new connection to the API server for the given
// model or controller.
func (c *CommandBase) NewAPIRoot(
store jujuclient.ClientStore,
controllerName, modelName string,
) (api.Connection, error) {
return c.NewAPIRootWithDialOpts(store, controllerName, modelName, nil)
}
// NewAPIRootWithDialOpts returns a new connection to the API server for the
// given model or controller (the default dial options will be overridden if
// dialOpts is not nil).
func (c *CommandBase) NewAPIRootWithDialOpts(
store jujuclient.ClientStore,
controllerName, modelName string,
dialOpts *api.DialOpts,
) (api.Connection, error) {
c.assertRunStarted()
accountDetails, err := store.AccountDetails(controllerName)
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
// If there are no account details or there's no logged-in
// user or the user is external, then trigger macaroon authentication
// by using an empty AccountDetails.
if accountDetails == nil || accountDetails.User == "" {
accountDetails = &jujuclient.AccountDetails{}
} else {
u := names.NewUserTag(accountDetails.User)
if !u.IsLocal() {
if len(accountDetails.Macaroons) == 0 {
accountDetails = &jujuclient.AccountDetails{}
} else {
// If the account has macaroon set, use those to login
// to avoid an unnecessary auth round trip.
// Used for embedded commands.
accountDetails = &jujuclient.AccountDetails{
User: u.Id(),
Macaroons: accountDetails.Macaroons,
}
}
}
}
param, err := c.NewAPIConnectionParams(
store, controllerName, modelName, accountDetails,
)
if err != nil {
return nil, errors.Trace(err)
}
if dialOpts != nil {
param.DialOpts = *dialOpts
}
conn, err := juju.NewAPIConnection(param)
if modelName != "" && params.ErrCode(err) == params.CodeModelNotFound {
return nil, c.missingModelError(store, controllerName, modelName)
}
if redirErr, ok := errors.Cause(err).(*api.RedirectError); ok {
return nil, newModelMigratedError(store, modelName, redirErr)
}
if juju.IsNoAddressesError(err) {
return nil, errors.New("no controller API addresses; is bootstrap still in progress?")
}
return conn, errors.Trace(err)
}
// RemoveModelFromClientStore removes given model from client cache, store,
// for a given controller.
// If this model has also been cached as current, it will be reset if
// the requesting command can modify current model.
// For example, commands such as add/destroy-model, login/register, etc.
// If the model was cached as current but the command is not expected to
// change current model, this call will still remove model details from the client cache
// but will keep current model name intact to allow subsequent calls to try to resolve
// model details on the controller.
func (c *CommandBase) RemoveModelFromClientStore(store jujuclient.ClientStore, controllerName, modelName string) {
err := store.RemoveModel(controllerName, modelName)
if err != nil && !errors.IsNotFound(err) {
logger.Warningf("cannot remove unknown model from cache: %v", err)
}
if c.CanClearCurrentModel {
currentModel, err := store.CurrentModel(controllerName)
if err != nil {
logger.Warningf("cannot read current model: %v", err)
} else if currentModel == modelName {
if err := store.SetCurrentModel(controllerName, ""); err != nil {
logger.Warningf("cannot reset current model: %v", err)
}
}
}
}
func (c *CommandBase) missingModelError(store jujuclient.ClientStore, controllerName, modelName string) error {
// First, we'll try and clean up the missing model from the local cache.
c.RemoveModelFromClientStore(store, controllerName, modelName)
return errors.Errorf("model %q has been removed from the controller, run 'juju models' and switch to one of them.", modelName)
}
// NewAPIConnectionParams returns a juju.NewAPIConnectionParams with the
// given arguments such that a call to juju.NewAPIConnection with the
// result behaves the same as a call to CommandBase.NewAPIRoot with
// the same arguments.
func (c *CommandBase) NewAPIConnectionParams(
store jujuclient.ClientStore,
controllerName, modelName string,
accountDetails *jujuclient.AccountDetails,
) (juju.NewAPIConnectionParams, error) {
c.assertRunStarted()
bakeryClient, err := c.BakeryClient(store, controllerName)
if err != nil {
return juju.NewAPIConnectionParams{}, errors.Trace(err)
}
var getPassword func(username string) (string, error)
if c.cmdContext != nil {
getPassword = func(username string) (string, error) {
fmt.Fprintf(c.cmdContext.Stderr, "please enter password for %s on %s: ", username, controllerName)
defer fmt.Fprintln(c.cmdContext.Stderr)
return readPassword(c.cmdContext.Stdin)
}
} else {
getPassword = func(username string) (string, error) {
return "", errors.New("no context to prompt for password")
}
}
return newAPIConnectionParams(
store, controllerName, modelName,
accountDetails,
c.Embedded,
bakeryClient,
c.apiOpen,
getPassword,
)
}
// HTTPClient returns an http.Client that contains the loaded
// persistent cookie jar. Note that this client is not good for
// connecting to the Juju API itself because it does not
// have the correct TLS setup - use api.Connection.HTTPClient
// for that.
func (c *CommandBase) HTTPClient(store jujuclient.ClientStore, controllerName string) (*http.Client, error) {
c.assertRunStarted()
bakeryClient, err := c.BakeryClient(store, controllerName)
if err != nil {
return nil, errors.Trace(err)
}
return bakeryClient.Client, nil
}
// BakeryClient returns a macaroon bakery client that
// uses the same HTTP client returned by HTTPClient.
func (c *CommandBase) BakeryClient(store jujuclient.CookieStore, controllerName string) (*httpbakery.Client, error) {
c.assertRunStarted()
ctx, err := c.getAPIContext(store, controllerName)
if err != nil {
return nil, errors.Trace(err)
}
return ctx.NewBakeryClient(), nil
}
// APIOpen establishes a connection to the API server using the
// the given api.Info and api.DialOpts, and associating any stored
// authorization tokens with the given controller name.
func (c *CommandBase) APIOpen(info *api.Info, opts api.DialOpts) (api.Connection, error) {
c.assertRunStarted()
return c.apiOpen(info, opts)
}
// apiOpen establishes a connection to the API server using the
// the give api.Info and api.DialOpts.
func (c *CommandBase) apiOpen(info *api.Info, opts api.DialOpts) (api.Connection, error) {
if c.apiOpenFunc != nil {
return c.apiOpenFunc(info, opts)
}
return api.Open(info, opts)
}
// RefreshModels refreshes the local models cache for the current user
// on the specified controller.
func (c *CommandBase) RefreshModels(store jujuclient.ClientStore, controllerName string) error {
if c.refreshModels == nil {
return c.doRefreshModels(store, controllerName)
}
return c.refreshModels(store, controllerName)
}
func (c *CommandBase) doRefreshModels(store jujuclient.ClientStore, controllerName string) error {
c.assertRunStarted()
modelManager, err := c.modelAPI(store, controllerName)
if err != nil {
return errors.Trace(err)
}
defer func() { _ = modelManager.Close() }()
accountDetails, err := store.AccountDetails(controllerName)
if err != nil {
return errors.Trace(err)
}
models, err := modelManager.ListModels(accountDetails.User)
if err != nil {
return errors.Trace(err)
}
if err := c.SetControllerModels(store, controllerName, models); err != nil {
return errors.Trace(err)
}
return nil
}
func (c *CommandBase) SetControllerModels(store jujuclient.ClientStore, controllerName string, models []base.UserModel) error {
modelsToStore := make(map[string]jujuclient.ModelDetails, len(models))
for _, model := range models {
modelDetails := jujuclient.ModelDetails{ModelUUID: model.UUID, ModelType: model.Type}
owner := names.NewUserTag(model.Owner)
modelName := jujuclient.JoinOwnerModelName(owner, model.Name)
modelsToStore[modelName] = modelDetails
}
if err := store.SetModels(controllerName, modelsToStore); err != nil {
return errors.Trace(err)
}
return nil
}
// ModelUUIDs returns the model UUIDs for the given model names.
func (c *CommandBase) ModelUUIDs(store jujuclient.ClientStore, controllerName string, modelNames []string) ([]string, error) {
var result []string
for _, modelName := range modelNames {
model, err := store.ModelByName(controllerName, modelName)
if errors.IsNotFound(err) {
// The model isn't known locally, so query the models available in the controller.
logger.Infof("model %q not cached locally, refreshing models from controller", modelName)
if err := c.RefreshModels(store, controllerName); err != nil {
return nil, errors.Annotatef(err, "refreshing model %q", modelName)
}
model, err = store.ModelByName(controllerName, modelName)
}
if err != nil {
return nil, errors.Trace(err)
}
result = append(result, model.ModelUUID)
}
return result, nil
}
// ControllerUUID returns the controller UUID for specified controller name.
func (c *CommandBase) ControllerUUID(store jujuclient.ClientStore, controllerName string) (string, error) {
ctrl, err := store.ControllerByName(controllerName)
if err != nil {
return "", errors.Annotate(err, "resolving controller name")
}
return ctrl.ControllerUUID, nil
}
// getAPIContext returns an apiContext for the given controller.
// It will return the same context if called twice for the same controller.
// The context will be closed when closeAPIContexts is called.
func (c *CommandBase) getAPIContext(store jujuclient.CookieStore, controllerName string) (*apiContext, error) {
c.assertRunStarted()
if ctx := c.apiContexts[controllerName]; ctx != nil {
return ctx, nil
}
if controllerName == "" {
return nil, errors.New("cannot get API context from empty controller name")
}
c.authOpts.Embedded = c.Embedded
ctx, err := newAPIContext(c.cmdContext, &c.authOpts, store, controllerName)
if err != nil {
return nil, errors.Trace(err)
}
c.apiContexts[controllerName] = ctx
return ctx, nil
}
// CookieJar returns the cookie jar that is used to store auth credentials
// when connecting to the API.
func (c *CommandBase) CookieJar(store jujuclient.CookieStore, controllerName string) (http.CookieJar, error) {
ctx, err := c.getAPIContext(store, controllerName)
if err != nil {
return nil, errors.Trace(err)
}
return ctx.CookieJar(), nil
}
// ClearControllerMacaroons will remove all macaroons stored
// for the given controller from the persistent cookie jar.
// This is called both from 'juju logout' and a failed 'juju register'.
func (c *CommandBase) ClearControllerMacaroons(store jujuclient.CookieStore, controllerName string) error {
ctx, err := c.getAPIContext(store, controllerName)
if err != nil {
return errors.Trace(err)
}
ctx.jar.RemoveAll()
return nil
}
func (c *CommandBase) initContexts(ctx *cmd.Context) {
c.StdContext = context.Background()
c.cmdContext = ctx
c.apiContexts = make(map[string]*apiContext)
}
// WrapBase wraps the specified Command. This should be
// used by any command that embeds CommandBase.
func WrapBase(c Command) Command {
return &baseCommandWrapper{
Command: c,
}
}
type baseCommandWrapper struct {
Command
}
// inner implements wrapper.inner.
func (w *baseCommandWrapper) inner() cmd.Command {
return w.Command
}
type hasClientStore interface {
SetClientStore(store jujuclient.ClientStore)
}
// SetClientStore sets the client store to use.
func (w *baseCommandWrapper) SetClientStore(store jujuclient.ClientStore) {
if csc, ok := w.Command.(hasClientStore); ok {
csc.SetClientStore(store)
}
}
// SetEmbedded implements the ModelCommand interface.
func (c *baseCommandWrapper) SetEmbedded(embedded bool) {
c.Command.SetEmbedded(embedded)
}
// Run implements Command.Run.
func (w *baseCommandWrapper) Run(ctx *cmd.Context) error {
defer w.closeAPIContexts()
w.initContexts(ctx)
w.setRunStarted()
return w.Command.Run(ctx)
}
func newAPIConnectionParams(
store jujuclient.ClientStore,
controllerName,
modelName string,
accountDetails *jujuclient.AccountDetails,
embedded bool,
bakery *httpbakery.Client,
apiOpen api.OpenFunc,
getPassword func(string) (string, error),
) (juju.NewAPIConnectionParams, error) {
if controllerName == "" {
return juju.NewAPIConnectionParams{}, errors.Trace(errNoNameSpecified)
}
var modelUUID string
if modelName != "" {
modelDetails, err := store.ModelByName(controllerName, modelName)
if err != nil {
return juju.NewAPIConnectionParams{}, errors.Trace(err)
}
modelUUID = modelDetails.ModelUUID
}
dialOpts := api.DefaultDialOpts()
dialOpts.BakeryClient = bakery
// Embedded clients with macaroons cannot discharge.
if accountDetails != nil && !embedded {
bakery.InteractionMethods = []httpbakery.Interactor{
authentication.NewInteractor(accountDetails.User, getPassword),
httpbakery.WebBrowserInteractor{},
}
}
return juju.NewAPIConnectionParams{
Store: store,
ControllerName: controllerName,
AccountDetails: accountDetails,
ModelUUID: modelUUID,
DialOpts: dialOpts,
OpenAPI: apiOpen,
}, nil
}
// NewGetBootstrapConfigParamsFunc returns a function that, given a controller name,
// returns the params needed to bootstrap a fresh copy of that controller in the given client store.
func NewGetBootstrapConfigParamsFunc(
ctx *cmd.Context,
store jujuclient.ClientStore,
providerRegistry environs.ProviderRegistry,
) func(string) (*jujuclient.BootstrapConfig, *environs.PrepareConfigParams, error) {
return bootstrapConfigGetter{ctx, store, providerRegistry}.getBootstrapConfigParams
}
type bootstrapConfigGetter struct {
ctx *cmd.Context
store jujuclient.ClientStore
registry environs.ProviderRegistry
}
func (g bootstrapConfigGetter) getBootstrapConfigParams(controllerName string) (*jujuclient.BootstrapConfig, *environs.PrepareConfigParams, error) {
controllerDetails, err := g.store.ControllerByName(controllerName)
if err != nil {
return nil, nil, errors.Annotate(err, "resolving controller name")
}
bootstrapConfig, err := g.store.BootstrapConfigForController(controllerName)
if err != nil {
return nil, nil, errors.Annotate(err, "getting bootstrap config")
}
var credential *cloud.Credential
bootstrapCloud := cloud.Cloud{
Name: bootstrapConfig.Cloud,
Type: bootstrapConfig.CloudType,
Endpoint: bootstrapConfig.CloudEndpoint,
IdentityEndpoint: bootstrapConfig.CloudIdentityEndpoint,
}
if bootstrapConfig.Credential != "" {
if bootstrapConfig.CloudRegion != "" {
bootstrapCloud.Regions = []cloud.Region{{
Name: bootstrapConfig.CloudRegion,
Endpoint: bootstrapConfig.CloudEndpoint,
IdentityEndpoint: bootstrapConfig.CloudIdentityEndpoint,
}}
}
credential, _, _, err = GetCredentials(
g.ctx, g.store,
GetCredentialsParams{
Cloud: bootstrapCloud,
CloudRegion: bootstrapConfig.CloudRegion,
CredentialName: bootstrapConfig.Credential,
},
)
if err != nil {
return nil, nil, errors.Trace(err)
}
} else {
// The credential was auto-detected; run auto-detection again.
provider, err := g.registry.Provider(bootstrapConfig.CloudType)
if err != nil {
return nil, nil, errors.Trace(err)
}
cloudCredential, err := DetectCredential(bootstrapConfig.Cloud, provider)
if err != nil {
return nil, nil, errors.Trace(err)
}
// DetectCredential ensures that there is only one credential
// to choose from. It's still in a map, though, hence for..range.
var credentialName string
for name, one := range cloudCredential.AuthCredentials {
credential = &one
credentialName = name
}
credential, err = FinalizeFileContent(credential, provider)
if err != nil {
return nil, nil, AnnotateWithFinalizationError(err, credentialName, bootstrapCloud.Name)
}
credential, err = provider.FinalizeCredential(
g.ctx, environs.FinalizeCredentialParams{
Credential: *credential,
CloudEndpoint: bootstrapConfig.CloudEndpoint,
CloudStorageEndpoint: bootstrapConfig.CloudStorageEndpoint,
CloudIdentityEndpoint: bootstrapConfig.CloudIdentityEndpoint,
},
)
if err != nil {
return nil, nil, errors.Trace(err)
}
}
// Add attributes from the controller details.
// TODO(wallyworld) - remove after beta18
controllerModelUUID := bootstrapConfig.ControllerModelUUID
if controllerModelUUID == "" {
controllerModelUUID = controllerDetails.ControllerUUID
}
bootstrapConfig.Config[config.UUIDKey] = controllerModelUUID
cfg, err := config.New(config.NoDefaults, bootstrapConfig.Config)
if err != nil {
return nil, nil, errors.Trace(err)
}
return bootstrapConfig, &environs.PrepareConfigParams{
Cloud: environscloudspec.CloudSpec{
Type: bootstrapConfig.CloudType,
Name: bootstrapConfig.Cloud,
Region: bootstrapConfig.CloudRegion,
Endpoint: bootstrapConfig.CloudEndpoint,
IdentityEndpoint: bootstrapConfig.CloudIdentityEndpoint,
StorageEndpoint: bootstrapConfig.CloudStorageEndpoint,
Credential: credential,
CACertificates: bootstrapConfig.CloudCACertificates,
SkipTLSVerify: bootstrapConfig.SkipTLSVerify,
IsControllerCloud: bootstrapConfig.Cloud == controllerDetails.Cloud,
},
Config: cfg,
}, nil
}
// TODO(axw) this is now in three places: change-password,
// register, and here. Refactor and move to a common location.
func readPassword(stdin io.Reader) (string, error) {
if f, ok := stdin.(*os.File); ok && terminal.IsTerminal(int(f.Fd())) {
password, err := terminal.ReadPassword(int(f.Fd()))
return string(password), err
}
return readLine(stdin)
}
func readLine(stdin io.Reader) (string, error) {
// Read one byte at a time to avoid reading beyond the delimiter.
line, err := bufio.NewReader(byteAtATimeReader{stdin}).ReadString('\n')
if err != nil {
return "", errors.Trace(err)
}
return line[:len(line)-1], nil
}
type byteAtATimeReader struct {
io.Reader
}
// Read is part of the io.Reader interface.
func (r byteAtATimeReader) Read(out []byte) (int, error) {
return r.Reader.Read(out[:1])
}
// wrapper is implemented by types that wrap a command.
type wrapper interface {
inner() cmd.Command
}
// InnerCommand returns the command that has been wrapped
// by one of the Wrap functions. This is useful for
// tests that wish to inspect internal details of a command
// instance. If c isn't wrapping anything, it returns c.
func InnerCommand(c cmd.Command) cmd.Command {
for {
c1, ok := c.(wrapper)
if !ok {
return c
}
c = c1.inner()
}
}