-
Notifications
You must be signed in to change notification settings - Fork 491
/
bootstrap.go
1840 lines (1640 loc) · 60.5 KB
/
bootstrap.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.
package commands
import (
"bufio"
"context"
"fmt"
"os"
"path"
"sort"
"strings"
"github.com/juju/charm/v12"
jujuclock "github.com/juju/clock"
"github.com/juju/cmd/v3"
"github.com/juju/errors"
"github.com/juju/featureflag"
"github.com/juju/gnuflag"
"github.com/juju/names/v5"
"github.com/juju/naturalsort"
"github.com/juju/schema"
"github.com/juju/utils/v3"
"github.com/juju/utils/v3/keyvalues"
"github.com/juju/version/v2"
"github.com/juju/juju/caas"
k8s "github.com/juju/juju/caas/kubernetes"
k8sconstants "github.com/juju/juju/caas/kubernetes/provider/constants"
jujucloud "github.com/juju/juju/cloud"
jujucmd "github.com/juju/juju/cmd"
"github.com/juju/juju/cmd/constants"
"github.com/juju/juju/cmd/juju/application/refresher"
"github.com/juju/juju/cmd/juju/common"
cmdcontroller "github.com/juju/juju/cmd/juju/controller"
cmdmodel "github.com/juju/juju/cmd/juju/model"
"github.com/juju/juju/cmd/modelcmd"
"github.com/juju/juju/controller"
corebase "github.com/juju/juju/core/base"
"github.com/juju/juju/core/constraints"
"github.com/juju/juju/core/instance"
"github.com/juju/juju/core/model"
"github.com/juju/juju/core/network"
"github.com/juju/juju/docker"
"github.com/juju/juju/environs"
"github.com/juju/juju/environs/bootstrap"
environscloudspec "github.com/juju/juju/environs/cloudspec"
"github.com/juju/juju/environs/config"
envcontext "github.com/juju/juju/environs/context"
"github.com/juju/juju/environs/sync"
"github.com/juju/juju/feature"
"github.com/juju/juju/juju"
"github.com/juju/juju/juju/osenv"
"github.com/juju/juju/jujuclient"
"github.com/juju/juju/provider/lxd/lxdnames"
"github.com/juju/juju/proxy"
"github.com/juju/juju/state/stateenvirons"
"github.com/juju/juju/storage"
"github.com/juju/juju/storage/poolmanager"
jujuversion "github.com/juju/juju/version"
)
// provisionalProviders is the names of providers that are hidden behind
// feature flags.
var provisionalProviders = map[string]string{}
var usageBootstrapSummary = `
Initializes a cloud environment.`[1:]
var usageBootstrapDetailsPartOne = `
Used without arguments, bootstrap will step you through the process of
initializing a Juju cloud environment. Initialization consists of creating
a 'controller' model and provisioning a machine to act as controller.
We recommend you call your controller ‘username-region’ e.g. ‘fred-us-east-1’.
See --clouds for a list of clouds and credentials.
See --regions <cloud> for a list of available regions for a given cloud.
Credentials are set beforehand and are distinct from any other
configuration (see `[1:] + "`juju add-credential`" + `).
The 'controller' model typically does not run workloads. It should remain
pristine to run and manage Juju's own infrastructure for the corresponding
cloud. Additional models should be created with ` + "`juju add-model`" + ` for workload purposes.
Note that a 'default' model is also created and becomes the current model
of the environment once the command completes. It can be discarded if
other models are created.
If '--bootstrap-constraints' is used, its values will also apply to any
future controllers provisioned for high availability (HA).
If '--constraints' is used, its values will be set as the default
constraints for all future workload machines in the model, exactly as if
the constraints were set with ` + "`juju set-model-constraints`" + `.
It is possible to override constraints and the automatic machine selection
algorithm by assigning a "placement directive" via the '--to' option. This
dictates what machine to use for the controller. This would typically be
used with the MAAS provider ('--to <host>.maas').
You can change the default timeout and retry delays used during the
bootstrap by changing the following settings in your configuration
(all values represent number of seconds):
# How long to wait for a connection to the controller
bootstrap-timeout: 1200 # default: 20 minutes
# How long to wait between connection attempts to a controller address.
bootstrap-retry-delay: 5 # default: 5 seconds
# How often to refresh controller addresses from the API server.
bootstrap-addresses-delay: 10 # default: 10 seconds
It is possible to override the base e.g. ubuntu@22.04, Juju attempts
to bootstrap on to, by supplying a base argument to '--bootstrap-base'.
An error is emitted if the determined base is not supported. Using the
'--force' option to override this check:
juju bootstrap --bootstrap-base=ubuntu@22.04 --force
The '--bootstrap-series' flag can be still used, but is deprecated in favour
of '--bootstrap-base'.
Private clouds may need to specify their own custom image metadata and
tools/agent. Use '--metadata-source' whose value is a local directory.
By default, the Juju version of the agent binary that is downloaded and
installed on all models for the new controller will be the same as that
of the Juju client used to perform the bootstrap.
However, a user can specify a different agent version via '--agent-version'
option to bootstrap command. Juju will use this version for models' agents
as long as the client's version is from the same Juju release base.
In other words, a 2.2.1 client can bootstrap any 2.2.x agents but cannot
bootstrap any 2.0.x or 2.1.x agents.
The agent version can be specified a simple numeric version, e.g. 2.2.4.
For example, at the time when 2.3.0, 2.3.1 and 2.3.2 are released and your
agent stream is 'released' (default), then a 2.3.1 client can bootstrap:
* 2.3.0 controller by running '... bootstrap --agent-version=2.3.0 ...';
* 2.3.1 controller by running '... bootstrap ...';
* 2.3.2 controller by running 'bootstrap --auto-upgrade'.
However, if this client has a copy of codebase, then a local copy of Juju
will be built and bootstrapped - 2.3.1.1.
Bootstrapping to a k8s cluster requires that the service set up to handle
requests to the controller be accessible outside the cluster. Typically this
means a service type of LoadBalancer is needed, and Juju does create such a
service if it knows it is supported by the cluster. This is performed by
interrogating the cluster for a well known managed deployment such as microk8s,
GKE or EKS.
When bootstrapping to a k8s cluster Juju does not recognise, there's no
guarantee a load balancer is available, so Juju defaults to a controller
service type of ClusterIP. This may not be suitable, so there's 3 bootstrap
options available to tell Juju how to set up the controller service. Part of
the solution may require a load balancer for the cluster to be set up manually
first, or perhaps an external k8s service via a FQDN will be used
(this is a cluster specific implementation decision which Juju needs to be
informed about so it can set things up correctly). The 3 relevant bootstrap
options are (see list of bootstrap config items below for a full explanation):
- controller-service-type
- controller-external-name
- controller-external-ips
If a storage pool is specified using --storage-pool, this will be created
in the controller model.
`
var usageBootstrapConfigTxt = `
Available keys for use with --config are:
`
var usageBootstrapDetailsPartTwo = `
`
const usageBootstrapExamples = `
juju bootstrap
juju bootstrap --clouds
juju bootstrap --regions aws
juju bootstrap aws
juju bootstrap aws/us-east-1
juju bootstrap google joe-us-east1
juju bootstrap --config=~/config-rs.yaml google joe-syd
juju bootstrap --agent-version=2.2.4 aws joe-us-east-1
juju bootstrap --config bootstrap-timeout=1200 azure joe-eastus
juju bootstrap aws --storage-pool name=secret --storage-pool type=ebs --storage-pool encrypted=true
juju bootstrap lxd --bootstrap-base=ubuntu@22.04
# For a bootstrap on k8s, setting the service type of the Juju controller service to LoadBalancer
juju bootstrap --config controller-service-type=loadbalancer
# For a bootstrap on k8s, setting the service type of the Juju controller service to External
juju bootstrap --config controller-service-type=external --config controller-external-name=controller.juju.is
`
func newBootstrapCommand() cmd.Command {
command := &bootstrapCommand{}
command.clock = jujuclock.WallClock
command.CanClearCurrentModel = true
return modelcmd.Wrap(command,
modelcmd.WrapSkipModelFlags,
modelcmd.WrapSkipDefaultModel,
)
}
// bootstrapCommand is responsible for launching the first machine in a juju
// environment, and setting up everything necessary to continue working.
type bootstrapCommand struct {
modelcmd.ModelCommandBase
clock jujuclock.Clock
Constraints constraints.Value
ConstraintsStr string
BootstrapConstraints constraints.Value
BootstrapConstraintsStr string
BootstrapSeries string
BootstrapBase string
BootstrapImage string
BuildAgent bool
JujuDbSnapPath string
JujuDbSnapAssertionsPath string
MetadataSource string
Placement string
KeepBrokenEnvironment bool
AutoUpgrade bool
AgentVersionParam string
AgentVersion *version.Number
config common.ConfigFlag
modelDefaults common.ConfigFlag
storagePool common.ConfigFlag
showClouds bool
showRegionsForCloud string
controllerName string
CredentialName string
Cloud string
Region string
noSwitch bool
interactive bool
// initialModelName is the name of a new model to create
// in addition to the controller model.
initialModelName string
ControllerCharmPath string
ControllerCharmChannelStr string
ControllerCharmChannel charm.Channel
// Force is used to allow a bootstrap to be run on unsupported series.
Force bool
}
func (c *bootstrapCommand) Info() *cmd.Info {
info := &cmd.Info{
Name: "bootstrap",
Args: "[<cloud name>[/region] [<controller name>]]",
Examples: usageBootstrapExamples,
SeeAlso: []string{
"add-credential",
"autoload-credentials",
"add-model",
"controller-config",
"model-config",
"set-constraints",
"show-cloud",
},
Purpose: usageBootstrapSummary,
}
if details := c.configDetails(); len(details) > 0 {
if output, err := common.FormatConfigSchema(details); err == nil {
info.Doc = fmt.Sprintf("%s%s\n%s%s",
usageBootstrapDetailsPartOne,
usageBootstrapConfigTxt,
output,
usageBootstrapDetailsPartTwo)
return jujucmd.Info(info)
}
}
info.Doc = strings.TrimSpace(fmt.Sprintf("%s%s",
usageBootstrapDetailsPartOne,
usageBootstrapDetailsPartTwo))
return jujucmd.Info(info)
}
func (c *bootstrapCommand) configDetails() map[string]interface{} {
result := map[string]interface{}{}
addAll := func(m map[string]interface{}) {
for k, v := range m {
result[k] = v
}
}
if modelCgf, err := cmdmodel.ConfigDetails(); err == nil {
addAll(modelCgf)
}
if controllerCgf, err := cmdcontroller.ConfigDetailsAll(); err == nil {
addAll(controllerCgf)
}
for key, attr := range bootstrap.BootstrapConfigSchema {
result[key] = common.PrintConfigSchema{
Description: attr.Description,
Type: string(attr.Type),
}
}
return result
}
func (c *bootstrapCommand) setControllerName(controllerName string) {
c.controllerName = strings.ToLower(controllerName)
}
func (c *bootstrapCommand) SetFlags(f *gnuflag.FlagSet) {
c.ModelCommandBase.SetFlags(f)
f.StringVar(&c.ConstraintsStr, "constraints", "", "Set model constraints")
f.StringVar(&c.BootstrapConstraintsStr, "bootstrap-constraints", "", "Specify bootstrap machine constraints")
f.StringVar(&c.BootstrapSeries, "bootstrap-series", "", "Specify the series of the bootstrap machine (deprecated use bootstrap-base)")
f.StringVar(&c.BootstrapBase, "bootstrap-base", "", "Specify the base of the bootstrap machine")
f.StringVar(&c.BootstrapImage, "bootstrap-image", "", "Specify the image of the bootstrap machine (requires --bootstrap-constraints specifying architecture)")
f.BoolVar(&c.BuildAgent, "build-agent", false, "Build local version of agent binary before bootstrapping")
f.StringVar(&c.JujuDbSnapPath, "db-snap", "",
"Path to a locally built .snap to use as the internal juju-db service.")
f.StringVar(&c.JujuDbSnapAssertionsPath, "db-snap-asserts", "", "Path to a local .assert file. Requires --db-snap")
f.StringVar(&c.MetadataSource, "metadata-source", "", "Local path to use as agent and/or image metadata source")
f.StringVar(&c.Placement, "to", "", "Placement directive indicating an instance to bootstrap")
f.BoolVar(&c.KeepBrokenEnvironment, "keep-broken", false,
"Do not destroy the provisioned controller instance if bootstrap fails")
f.BoolVar(&c.AutoUpgrade, "auto-upgrade", false, "After bootstrap, upgrade to the latest patch release")
f.StringVar(&c.AgentVersionParam, "agent-version", "", "Version of agent binaries to use for Juju agents")
f.StringVar(&c.CredentialName, "credential", "", "Credentials to use when bootstrapping")
f.Var(&c.config, "config",
"Specify a controller configuration file, or one or more configuration\n options\n (--config config.yaml [--config key=value ...])")
f.Var(&c.modelDefaults, "model-default",
"Specify a configuration file, or one or more configuration\n options to be set for all models, unless otherwise specified\n (--model-default config.yaml [--model-default key=value ...])")
f.Var(&c.storagePool, "storage-pool",
"Specify options for an initial storage pool\n 'name' and 'type' are required, plus any additional attributes\n (--storage-pool pool-config.yaml [--storage-pool key=value ...])")
f.StringVar(&c.initialModelName, "add-model", "", "Name of an initial model to create on the new controller")
f.BoolVar(&c.showClouds, "clouds", false,
"Print the available clouds which can be used to bootstrap a Juju environment")
f.StringVar(&c.showRegionsForCloud, "regions", "", "Print the available regions for the specified cloud")
f.BoolVar(&c.noSwitch, "no-switch", false, "Do not switch to the newly created controller")
f.BoolVar(&c.Force, "force", false, "Allow the bypassing of checks such as supported series")
f.StringVar(&c.ControllerCharmPath, "controller-charm-path", "", "Path to a locally built controller charm")
f.StringVar(&c.ControllerCharmChannelStr, "controller-charm-channel",
fmt.Sprintf("%d.%d/stable", jujuversion.Current.Major, jujuversion.Current.Minor),
"The Charmhub channel to download the controller charm from (if not using a local charm)")
}
func (c *bootstrapCommand) Init(args []string) (err error) {
if c.JujuDbSnapPath != "" {
_, err := c.Filesystem().Stat(c.JujuDbSnapPath)
if err != nil {
return errors.Annotatef(err, "problem with --db-snap")
}
}
if c.BootstrapSeries != "" && c.BootstrapBase != "" {
return errors.New("cannot specify both --bootstrap-series and --bootstrap-base")
}
if c.BootstrapSeries != "" {
base, err := corebase.GetBaseFromSeries(c.BootstrapSeries)
if err != nil {
return errors.Errorf("cannot determine base for series %q", c.BootstrapSeries)
}
c.BootstrapBase = base.String()
c.BootstrapSeries = ""
}
// Validate the bootstrap base looks like a base.
if c.BootstrapBase != "" {
if _, err := corebase.ParseBaseFromString(c.BootstrapBase); err != nil {
return errors.NotValidf("base %q", c.BootstrapBase)
}
}
// fill in JujuDbSnapAssertionsPath from the same directory as JujuDbSnapPath
if c.JujuDbSnapAssertionsPath == "" && c.JujuDbSnapPath != "" {
assertionsPath := strings.Replace(c.JujuDbSnapPath, path.Ext(c.JujuDbSnapPath), ".assert", -1)
logger.Debugf("--db-snap-asserts unset, assuming %v", assertionsPath)
c.JujuDbSnapAssertionsPath = assertionsPath
}
if c.JujuDbSnapAssertionsPath != "" {
_, err := c.Filesystem().Stat(c.JujuDbSnapAssertionsPath)
if err != nil {
return errors.Annotatef(err, "problem with --db-snap-asserts")
}
}
if c.JujuDbSnapAssertionsPath != "" && c.JujuDbSnapPath == "" {
return errors.New("--db-snap-asserts requires --db-snap")
}
if c.ControllerCharmPath != "" {
if refresher.IsLocalURL(c.ControllerCharmPath) {
_, err := c.Filesystem().Stat(c.ControllerCharmPath)
if err != nil {
return errors.Annotatef(err, "problem with --controller-charm-path")
}
ch, err := charm.ReadCharm(c.ControllerCharmPath)
if err != nil {
return errors.Errorf("--controller-charm-path %q is not a valid charm", c.ControllerCharmPath)
}
if ch.Meta().Name != bootstrap.ControllerCharmName {
return errors.Errorf("--controller-charm-path %q is not a %q charm", c.ControllerCharmPath,
bootstrap.ControllerCharmName)
}
}
// Assume this is a Charmhub URL
// TODO(barrettj12): validate the charm exists on CharmHub
}
c.ControllerCharmChannel, err = parseControllerCharmChannel(c.ControllerCharmChannelStr)
if err != nil {
return errors.NotValidf("controller charm channel %q", c.ControllerCharmChannelStr)
}
if c.showClouds && c.showRegionsForCloud != "" {
return errors.New("--clouds and --regions can't be used together")
}
if c.showClouds {
return cmd.CheckEmpty(args)
}
if c.showRegionsForCloud != "" {
return cmd.CheckEmpty(args)
}
if c.AgentVersionParam != "" && c.BuildAgent {
return errors.New("--agent-version and --build-agent can't be used together")
}
if c.initialModelName == "" {
c.initialModelName = os.Getenv("JUJU_BOOTSTRAP_MODEL")
}
// Parse the placement directive. Bootstrap currently only
// supports provider-specific placement directives.
if c.Placement != "" {
_, err = instance.ParsePlacement(c.Placement)
if err != instance.ErrPlacementScopeMissing {
// We only support unscoped placement directives for bootstrap.
return errors.Errorf("unsupported bootstrap placement directive %q", c.Placement)
}
}
if !c.AutoUpgrade {
// With no auto upgrade chosen, we default to the version matching the bootstrap client.
vers := jujuversion.Current
c.AgentVersion = &vers
}
if c.AgentVersionParam != "" {
if vers, err := version.ParseBinary(c.AgentVersionParam); err == nil {
c.AgentVersion = &vers.Number
} else if vers, err := version.Parse(c.AgentVersionParam); err == nil {
c.AgentVersion = &vers
} else {
return err
}
}
if c.AgentVersion != nil && (c.AgentVersion.Major != jujuversion.Current.Major || c.AgentVersion.Minor != jujuversion.Current.Minor) {
return errors.Errorf("this client can only bootstrap %v.%v agents", jujuversion.Current.Major,
jujuversion.Current.Minor)
}
switch len(args) {
case 0:
// no args or flags, go interactive.
c.interactive = true
return nil
}
c.Cloud = args[0]
if i := strings.IndexRune(c.Cloud, '/'); i > 0 {
c.Cloud, c.Region = c.Cloud[:i], c.Cloud[i+1:]
}
if ok := names.IsValidCloud(c.Cloud); !ok {
return errors.NotValidf("cloud name %q", c.Cloud)
}
if len(args) > 1 {
c.setControllerName(args[1])
return cmd.CheckEmpty(args[2:])
}
return nil
}
func parseControllerCharmChannel(channelStr string) (charm.Channel, error) {
ch, err := charm.ParseChannel(channelStr)
if err != nil {
return charm.Channel{}, err
}
if ch.Track == "" {
ch.Track = fmt.Sprintf("%d.%d", jujuversion.Current.Major, jujuversion.Current.Minor)
}
if ch.Risk == "" {
ch.Risk = charm.Stable
}
return ch, nil
}
// BootstrapInterface provides bootstrap functionality that Run calls to support cleaner testing.
type BootstrapInterface interface {
// Bootstrap bootstraps a controller.
Bootstrap(ctx environs.BootstrapContext, environ environs.BootstrapEnviron, callCtx envcontext.ProviderCallContext,
args bootstrap.BootstrapParams) error
// CloudDetector returns a CloudDetector for the given provider,
// if the provider supports it.
CloudDetector(environs.EnvironProvider) (environs.CloudDetector, bool)
// CloudRegionDetector returns a CloudRegionDetector for the given provider,
// if the provider supports it.
CloudRegionDetector(environs.EnvironProvider) (environs.CloudRegionDetector, bool)
// CloudFinalizer returns a CloudFinalizer for the given provider,
// if the provider supports it.
CloudFinalizer(environs.EnvironProvider) (environs.CloudFinalizer, bool)
}
type bootstrapFuncs struct{}
func (b bootstrapFuncs) Bootstrap(ctx environs.BootstrapContext, env environs.BootstrapEnviron,
callCtx envcontext.ProviderCallContext, args bootstrap.BootstrapParams) error {
return bootstrap.Bootstrap(ctx, env, callCtx, args)
}
func (b bootstrapFuncs) CloudDetector(provider environs.EnvironProvider) (environs.CloudDetector, bool) {
detector, ok := provider.(environs.CloudDetector)
return detector, ok
}
func (b bootstrapFuncs) CloudRegionDetector(provider environs.EnvironProvider) (environs.CloudRegionDetector, bool) {
detector, ok := provider.(environs.CloudRegionDetector)
return detector, ok
}
func (b bootstrapFuncs) CloudFinalizer(provider environs.EnvironProvider) (environs.CloudFinalizer, bool) {
finalizer, ok := provider.(environs.CloudFinalizer)
return finalizer, ok
}
var getBootstrapFuncs = func() BootstrapInterface {
return &bootstrapFuncs{}
}
var supportedJujuBases = corebase.ControllerBases
var (
bootstrapPrepareController = bootstrap.PrepareController
environsDestroy = environs.Destroy
waitForAgentInitialisation = common.WaitForAgentInitialisation
)
var ambiguousDetectedCredentialError = errors.New(`
more than one credential detected
run juju autoload-credentials and specify a credential using the --credential argument`[1:],
)
var ambiguousCredentialError = errors.New(`
more than one credential is available
specify a credential using the --credential argument`[1:],
)
func (c *bootstrapCommand) parseConstraints(ctx *cmd.Context) (err error) {
allAliases := map[string]string{}
defer common.WarnConstraintAliases(ctx, allAliases)
if c.ConstraintsStr != "" {
cons, aliases, err := constraints.ParseWithAliases(c.ConstraintsStr)
for k, v := range aliases {
allAliases[k] = v
}
if err != nil {
return err
}
c.Constraints = cons
}
if c.BootstrapConstraintsStr != "" {
cons, aliases, err := constraints.ParseWithAliases(c.BootstrapConstraintsStr)
for k, v := range aliases {
allAliases[k] = v
}
if err != nil {
return err
}
c.BootstrapConstraints = cons
}
return nil
}
func (c *bootstrapCommand) initializeFirstModel(
isCAASController bool,
config bootstrapConfigs,
store jujuclient.ClientStore,
environ environs.BootstrapEnviron,
bootstrapParams *bootstrap.BootstrapParams,
) (*jujuclient.ModelDetails, error) {
if c.initialModelName == "" || c.initialModelName == "controller" {
// Nothing to do, but ensure the required model is selected by default.
return nil, store.SetCurrentModel(c.controllerName, c.initialModelName)
}
initialModelUUID, err := utils.NewUUID()
if err != nil {
return nil, errors.Trace(err)
}
initialModelType := model.IAAS
if isCAASController {
initialModelType = model.CAAS
}
modelDetails := &jujuclient.ModelDetails{
ModelUUID: initialModelUUID.String(),
ModelType: initialModelType,
}
if featureflag.Enabled(feature.Branches) || featureflag.Enabled(feature.Generations) {
modelDetails.ActiveBranch = model.GenerationMaster
}
if err := store.UpdateModel(
c.controllerName,
c.initialModelName,
*modelDetails,
); err != nil {
return nil, errors.Trace(err)
}
bootstrapParams.InitialModelConfig = c.InitialModelConfig(
initialModelUUID, config.inheritedControllerAttrs, config.userConfigAttrs, environ,
)
if !c.noSwitch {
// Set the current model to the initial hosted model.
if err := store.SetCurrentModel(c.controllerName, c.initialModelName); err != nil {
return nil, errors.Trace(err)
}
}
return modelDetails, nil
}
// Run connects to the environment specified on the command line and bootstraps
// a juju in that environment if none already exists. If there is as yet no environments.yaml file,
// the user is informed how to create one.
func (c *bootstrapCommand) Run(ctx *cmd.Context) (resultErr error) {
var (
initialModel *jujuclient.ModelDetails
isCAASController bool
// The stdCtx is used as a placeholder for the defer below. This will
// be replaced with a context that can be cancelled later on.
stdCtx = context.TODO()
)
defer func() {
// If the context is an error state, then don't continue on processing
// the bootstrap command.
if stdCtx.Err() != nil {
return
}
resultErr = handleChooseCloudRegionError(ctx, resultErr)
if !c.showClouds && resultErr == nil {
if initialModel != nil {
ctx.Infof("Initial model %q added", c.initialModelName)
return
}
workloadType := ""
if isCAASController {
workloadType = "k8s "
}
ctx.Infof(`
Now you can run
juju add-model <model-name>
to create a new model to deploy %sworkloads.
`, workloadType)
}
}()
// TODO(stickupkid): Once default-series has been deprecated, it's safe to
// remove this.
if err := c.warnDeprecatedModelConfig(ctx); err != nil {
return err
}
if err := c.parseConstraints(ctx); err != nil {
return err
}
// Start by checking for usage errors, requests for information
finished, err := c.handleCommandLineErrorsAndInfoRequests(ctx)
if err != nil {
return errors.Trace(err)
}
if finished {
return nil
}
// Run interactive bootstrap if needed/asked for
if c.interactive {
if err := c.runInteractive(ctx); err != nil {
return errors.Trace(err)
}
// now run normal bootstrap using info gained above.
}
cloud, provider, err := c.cloud(ctx)
if err != nil {
return errors.Trace(err)
}
// If region is specified by the user, validate it here.
// lp#1632735
if c.Region != "" {
_, err := jujucloud.RegionByName(cloud.Regions, c.Region)
if err != nil {
allRegions := make([]string, len(cloud.Regions))
for i, one := range cloud.Regions {
allRegions[i] = one.Name
}
if len(allRegions) > 0 {
naturalsort.Sort(allRegions)
plural := "s are"
if len(allRegions) == 1 {
plural = " is"
}
ctx.Infof("Available cloud region%v %v", plural, strings.Join(allRegions, ", "))
}
return errors.NotValidf("region %q for cloud %q", c.Region, c.Cloud)
}
}
// Custom clouds may not have explicitly declared support for any auth-
// types, in which case we'll assume that they support everything that
// the provider supports.
if len(cloud.AuthTypes) == 0 {
for authType := range provider.CredentialSchemas() {
cloud.AuthTypes = append(cloud.AuthTypes, authType)
}
}
credentials, regionName, err := c.credentialsAndRegionName(ctx, provider, cloud)
if err != nil {
if errors.IsNotFound(err) {
err = errors.NewNotFound(nil,
fmt.Sprintf("%v\nSee `juju add-credential %s --help` for instructions", err, cloud.Name))
}
if err == cmd.ErrSilent {
return err
}
return errors.Trace(err)
}
region, err := common.ChooseCloudRegion(cloud, regionName)
if err != nil {
return errors.Trace(err)
}
if c.controllerName == "" {
c.setControllerName(defaultControllerName(cloud.Name, region.Name))
}
// set a Region so it's config can be found below.
if c.Region == "" {
c.Region = region.Name
}
bootstrapCfg, err := c.bootstrapConfigs(ctx, cloud, provider)
if err != nil {
return errors.Trace(err)
}
isCAASController = jujucloud.CloudIsCAAS(cloud)
if isCAASController && refresher.IsLocalURL(c.ControllerCharmPath) {
return errors.NotSupportedf("deploying a local controller charm on a k8s controller")
}
if !isCAASController {
if bootstrapCfg.bootstrap.ControllerServiceType != "" ||
bootstrapCfg.bootstrap.ControllerExternalName != "" ||
len(bootstrapCfg.bootstrap.ControllerExternalIPs) > 0 {
return errors.Errorf("%q, %q and %q\nare only allowed for kubernetes controllers",
bootstrap.ControllerServiceType, bootstrap.ControllerExternalName, bootstrap.ControllerExternalIPs)
}
}
if bootstrapCfg.controller.ControllerName() != "" {
return errors.NewNotValid(nil, "controller name cannot be set via config, please use cmd args")
}
// Read existing current controller so we can clean up on error.
var oldCurrentController string
store := c.ClientStore()
oldCurrentController, err = modelcmd.DetermineCurrentController(store)
if errors.IsNotFound(err) {
oldCurrentController = ""
} else if err != nil {
return errors.Annotate(err, "error reading current controller")
}
defer func() {
if resultErr == nil || errors.IsAlreadyExists(resultErr) {
return
}
if oldCurrentController != "" {
if err := store.SetCurrentController(oldCurrentController); err != nil {
logger.Errorf(
"cannot reset current controller to %q: %v",
oldCurrentController, err,
)
}
}
if err := store.RemoveController(c.controllerName); err != nil {
logger.Errorf(
"cannot destroy newly created controller %q details: %v",
c.controllerName, err,
)
}
}()
var bootstrapBase corebase.Base
if c.BootstrapBase != "" {
var err error
bootstrapBase, err = corebase.ParseBaseFromString(c.BootstrapBase)
if err != nil {
return errors.NotValidf("bootstrap base %q", c.BootstrapBase)
}
}
// Get the supported bootstrap series.
var imageStream string
if cfg, ok := bootstrapCfg.bootstrapModel["image-stream"]; ok {
imageStream = cfg.(string)
}
now := c.clock.Now()
supportedBootstrapBases, err := supportedJujuBases(now, bootstrapBase, imageStream)
if err != nil {
return errors.Annotate(err, "error reading supported bootstrap series")
}
logger.Tracef("supported bootstrap bases %v", supportedBootstrapBases)
bootstrapCfg.controller[controller.ControllerName] = c.controllerName
// Handle Ctrl-C during bootstrap by asking the bootstrap process to stop
// early (and the above will then clean up resources).
interrupted := make(chan os.Signal, 1)
defer close(interrupted)
ctx.InterruptNotify(interrupted)
defer ctx.StopInterruptNotify(interrupted)
var cancel context.CancelFunc
stdCtx, cancel = context.WithTimeout(context.Background(), bootstrapCfg.bootstrap.BootstrapTimeout)
go func() {
for range interrupted {
select {
case <-stdCtx.Done():
// Ctrl-C already pressed
return
default:
// Newline prefix is intentional, so output appears as
// "^C\nCtrl-C pressed" instead of "^CCtrl-C pressed".
_, _ = fmt.Fprintln(ctx.GetStderr(), "\nCtrl-C pressed, attempting to stop bootstrap and clean up resources")
cancel()
}
}
}()
bootstrapCtx := modelcmd.BootstrapContext(stdCtx, ctx)
bootstrapPrepareParams := bootstrap.PrepareParams{
ModelConfig: bootstrapCfg.bootstrapModel,
ControllerConfig: bootstrapCfg.controller,
ControllerName: c.controllerName,
Cloud: environscloudspec.CloudSpec{
Type: cloud.Type,
Name: cloud.Name,
Region: region.Name,
Endpoint: region.Endpoint,
IdentityEndpoint: region.IdentityEndpoint,
StorageEndpoint: region.StorageEndpoint,
Credential: credentials.credential,
CACertificates: cloud.CACertificates,
SkipTLSVerify: cloud.SkipTLSVerify,
},
CredentialName: credentials.name,
AdminSecret: bootstrapCfg.bootstrap.AdminSecret,
}
environ, err := bootstrapPrepareController(
isCAASController, bootstrapCtx, store, bootstrapPrepareParams,
)
if err != nil {
return errors.Trace(err)
}
// Validate the storage provider config.
registry := stateenvirons.NewStorageProviderRegistry(environ)
m := poolmanager.MemSettings{
Settings: make(map[string]map[string]interface{}),
}
pm := poolmanager.New(m, registry)
for poolName, cfg := range bootstrapCfg.storagePools {
poolType, _ := cfg[poolmanager.Type].(string)
_, err = pm.Create(poolName, storage.ProviderType(poolType), cfg)
if err != nil {
return errors.NewNotValid(err, "invalid storage provider config")
}
}
bootstrapParams := bootstrap.BootstrapParams{
ControllerName: c.controllerName,
BootstrapBase: bootstrapBase,
SupportedBootstrapBases: supportedBootstrapBases,
BootstrapImage: c.BootstrapImage,
Placement: c.Placement,
BuildAgent: c.BuildAgent,
BuildAgentTarball: sync.BuildAgentTarball,
AgentVersion: c.AgentVersion,
Cloud: cloud,
CloudRegion: region.Name,
ControllerConfig: bootstrapCfg.controller,
ControllerInheritedConfig: bootstrapCfg.inheritedControllerAttrs,
RegionInheritedConfig: cloud.RegionConfig,
AdminSecret: bootstrapCfg.bootstrap.AdminSecret,
CAPrivateKey: bootstrapCfg.bootstrap.CAPrivateKey,
ControllerServiceType: bootstrapCfg.bootstrap.ControllerServiceType,
ControllerExternalName: bootstrapCfg.bootstrap.ControllerExternalName,
ControllerExternalIPs: append([]string(nil), bootstrapCfg.bootstrap.ControllerExternalIPs...),
JujuDbSnapPath: c.JujuDbSnapPath,
JujuDbSnapAssertionsPath: c.JujuDbSnapAssertionsPath,
StoragePools: bootstrapCfg.storagePools,
ControllerCharmPath: c.ControllerCharmPath,
ControllerCharmChannel: c.ControllerCharmChannel,
DialOpts: environs.BootstrapDialOpts{
Timeout: bootstrapCfg.bootstrap.BootstrapTimeout,
RetryDelay: bootstrapCfg.bootstrap.BootstrapRetryDelay,
AddressesDelay: bootstrapCfg.bootstrap.BootstrapAddressesDelay,
},
Force: c.Force,
}
initialModel, err = c.initializeFirstModel(
isCAASController, bootstrapCfg, store, environ, &bootstrapParams,
)
if err != nil {
return errors.Trace(err)
}
if !c.noSwitch {
// set the current controller.
if err := store.SetCurrentController(c.controllerName); err != nil {
return errors.Trace(err)
}
}
cloudRegion := c.Cloud
if region.Name != "" {
cloudRegion = fmt.Sprintf("%s/%s", cloudRegion, region.Name)
}
ctx.Infof(
"Creating Juju controller %q on %s",
c.controllerName, cloudRegion,
)
cloudCallCtx := envcontext.NewCloudCallContext(stdCtx)
// At this stage, the credential we intend to use is not yet stored
// server-side. So, if the credential is not accepted by the provider,
// we cannot mark it as invalid, just log it as an informative message.
cloudCallCtx.InvalidateCredentialFunc = func(reason string) error {
ctx.Infof("Cloud credential %q is not accepted by cloud provider: %v", credentials.name, reason)
return nil
}
// If we error out for any reason, clean up the environment.
defer func() {
if resultErr != nil {
if c.KeepBrokenEnvironment {
ctx.Infof(`
bootstrap failed but --keep-broken was specified.
This means that cloud resources are left behind, but not registered to
your local client, as the controller was not successfully created.
However, you should be able to ssh into the machine using the user "ubuntu" and
their IP address for diagnosis and investigation.
When you are ready to clean up the failed controller, use your cloud console or
equivalent CLI tools to terminate the instances and remove remaining resources.
See `[1:] + "`juju kill-controller`" + `.`)
} else {
logger.Errorf("%v", resultErr)
logger.Debugf("(error details: %v)", errors.Details(resultErr))
// Set resultErr to cmd.ErrSilent to prevent
// logging the error twice.
resultErr = cmd.ErrSilent
handleBootstrapError(ctx, func() error {
return environsDestroy(
c.controllerName, environ, cloudCallCtx, store,
)
})
}
}