/
destroy.go
393 lines (347 loc) · 11.4 KB
/
destroy.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package controller
import (
"bufio"
"bytes"
"fmt"
"io"
"strings"
"time"
"github.com/juju/cmd"
"github.com/juju/errors"
"github.com/juju/gnuflag"
"github.com/juju/utils/clock"
"gopkg.in/juju/names.v2"
"github.com/juju/juju/api/base"
"github.com/juju/juju/api/controller"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/cmd/juju/block"
"github.com/juju/juju/cmd/modelcmd"
"github.com/juju/juju/environs"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/jujuclient"
)
// NewDestroyCommand returns a command to destroy a controller.
func NewDestroyCommand() cmd.Command {
// Even though this command is all about destroying a controller we end up
// needing environment endpoints so we can fall back to the client destroy
// environment method. This shouldn't really matter in practice as the
// user trying to take down the controller will need to have access to the
// controller environment anyway.
return modelcmd.WrapController(
&destroyCommand{},
modelcmd.WrapControllerSkipControllerFlags,
modelcmd.WrapControllerSkipDefaultController,
)
}
// destroyCommand destroys the specified controller.
type destroyCommand struct {
destroyCommandBase
destroyModels bool
}
// usageDetails has backticks which we want to keep for markdown processing.
// TODO(cheryl): Do we want the usage, options, examples, and see also text in
// backticks for markdown?
var usageDetails = `
All models (initial model plus all workload/hosted) associated with the
controller will first need to be destroyed, either in advance, or by
specifying `[1:] + "`--destroy-all-models`." + `
Examples:
juju destroy-controller --destroy-all-models mycontroller
See also:
kill-controller
unregister`
var usageSummary = `
Destroys a controller.`[1:]
var destroySysMsg = `
WARNING! This command will destroy the %q controller.
This includes all machines, applications, data and other resources.
Continue? (y/N):`[1:]
// destroyControllerAPI defines the methods on the controller API endpoint
// that the destroy command calls.
type destroyControllerAPI interface {
Close() error
ModelConfig() (map[string]interface{}, error)
HostedModelConfigs() ([]controller.HostedConfig, error)
CloudSpec(names.ModelTag) (environs.CloudSpec, error)
DestroyController(destroyModels bool) error
ListBlockedModels() ([]params.ModelBlockInfo, error)
ModelStatus(models ...names.ModelTag) ([]base.ModelStatus, error)
AllModels() ([]base.UserModel, error)
}
// destroyClientAPI defines the methods on the client API endpoint that the
// destroy command might call.
type destroyClientAPI interface {
Close() error
ModelGet() (map[string]interface{}, error)
DestroyModel() error
}
// Info implements Command.Info.
func (c *destroyCommand) Info() *cmd.Info {
return &cmd.Info{
Name: "destroy-controller",
Args: "<controller name>",
Purpose: usageSummary,
Doc: usageDetails,
}
}
// SetFlags implements Command.SetFlags.
func (c *destroyCommand) SetFlags(f *gnuflag.FlagSet) {
c.destroyCommandBase.SetFlags(f)
f.BoolVar(&c.destroyModels, "destroy-all-models", false, "Destroy all hosted models in the controller")
}
// Run implements Command.Run
func (c *destroyCommand) Run(ctx *cmd.Context) error {
controllerName := c.ControllerName()
store := c.ClientStore()
if !c.assumeYes {
if err := confirmDestruction(ctx, c.ControllerName()); err != nil {
return err
}
}
// Attempt to connect to the API. If we can't, fail the destroy. Users will
// need to use the controller kill command if we can't connect.
api, err := c.getControllerAPI()
if err != nil {
return c.ensureUserFriendlyErrorLog(errors.Annotate(err, "cannot connect to API"), ctx, nil)
}
defer api.Close()
// Obtain controller environ so we can clean up afterwards.
controllerEnviron, err := c.getControllerEnviron(ctx, store, controllerName, api)
if err != nil {
return errors.Annotate(err, "getting controller environ")
}
for {
// Attempt to destroy the controller.
ctx.Infof("Destroying controller")
var hasHostedModels bool
err = api.DestroyController(c.destroyModels)
if err != nil {
if params.IsCodeHasHostedModels(err) {
hasHostedModels = true
} else {
return c.ensureUserFriendlyErrorLog(
errors.Annotate(err, "cannot destroy controller"),
ctx, api,
)
}
}
updateStatus := newTimedStatusUpdater(ctx, api, controllerEnviron.Config().UUID(), clock.WallClock)
ctrStatus, modelsStatus := updateStatus(0)
if !c.destroyModels {
if err := c.checkNoAliveHostedModels(ctx, modelsStatus); err != nil {
return errors.Trace(err)
}
if hasHostedModels && !hasUnDeadModels(modelsStatus) {
// When we called DestroyController before, we were
// informed that there were hosted models remaining.
// When we checked just now, there were none. We should
// try destroying again.
continue
}
}
// Even if we've not just requested for hosted models to be destroyed,
// there may be some being destroyed already. We need to wait for them.
ctx.Infof("Waiting for hosted model resources to be reclaimed")
for ; hasUnDeadModels(modelsStatus); ctrStatus, modelsStatus = updateStatus(2 * time.Second) {
ctx.Infof(fmtCtrStatus(ctrStatus))
for _, model := range modelsStatus {
ctx.Verbosef(fmtModelStatus(model))
}
}
ctx.Infof("All hosted models reclaimed, cleaning up controller machines")
return environs.Destroy(c.ControllerName(), controllerEnviron, store)
}
}
// checkNoAliveHostedModels ensures that the given set of hosted models
// contains none that are Alive. If there are, an message is printed
// out to
func (c *destroyCommand) checkNoAliveHostedModels(ctx *cmd.Context, models []modelData) error {
if !hasAliveModels(models) {
return nil
}
// The user did not specify --destroy-all-models,
// and there are models still alive.
var buf bytes.Buffer
for _, model := range models {
if model.Life != string(params.Alive) {
continue
}
buf.WriteString(fmtModelStatus(model))
buf.WriteRune('\n')
}
return errors.Errorf(`cannot destroy controller %q
The controller has live hosted models. If you want
to destroy all hosted models in the controller,
run this command again with the --destroy-all-models
flag.
Models:
%s`, c.ControllerName(), buf.String())
}
// ensureUserFriendlyErrorLog ensures that error will be logged and displayed
// in a user-friendly manner with readable and digestable error message.
func (c *destroyCommand) ensureUserFriendlyErrorLog(destroyErr error, ctx *cmd.Context, api destroyControllerAPI) error {
if destroyErr == nil {
return nil
}
if params.IsCodeOperationBlocked(destroyErr) {
logger.Errorf(destroyControllerBlockedMsg)
if api != nil {
models, err := api.ListBlockedModels()
out := &bytes.Buffer{}
if err == nil {
var info interface{}
info, err = block.FormatModelBlockInfo(models)
if err != nil {
return errors.Trace(err)
}
err = block.FormatTabularBlockedModels(out, info)
}
if err != nil {
logger.Errorf("Unable to list models: %s", err)
return cmd.ErrSilent
}
ctx.Infof(out.String())
}
return cmd.ErrSilent
}
if params.IsCodeHasHostedModels(destroyErr) {
return destroyErr
}
logger.Errorf(stdFailureMsg, c.ControllerName())
return destroyErr
}
const destroyControllerBlockedMsg = `there are models with disabled commands preventing controller destruction
To enable controller destruction, please run:
juju enable-destroy-controller
`
// TODO(axw) this should only be printed out if we couldn't
// connect to the controller.
const stdFailureMsg = `failed to destroy controller %q
If the controller is unusable, then you may run
juju kill-controller
to forcibly destroy the controller. Upon doing so, review
your cloud provider console for any resources that need
to be cleaned up.
`
// destroyCommandBase provides common attributes and methods that both the controller
// destroy and controller kill commands require.
type destroyCommandBase struct {
modelcmd.ControllerCommandBase
assumeYes bool
// The following fields are for mocking out
// api behavior for testing.
api destroyControllerAPI
apierr error
clientapi destroyClientAPI
}
func (c *destroyCommandBase) getControllerAPI() (destroyControllerAPI, error) {
if c.api != nil {
return c.api, c.apierr
}
root, err := c.NewAPIRoot()
if err != nil {
return nil, errors.Trace(err)
}
return controller.NewClient(root), nil
}
// SetFlags implements Command.SetFlags.
func (c *destroyCommandBase) SetFlags(f *gnuflag.FlagSet) {
c.ControllerCommandBase.SetFlags(f)
f.BoolVar(&c.assumeYes, "y", false, "Do not ask for confirmation")
f.BoolVar(&c.assumeYes, "yes", false, "")
}
// Init implements Command.Init.
func (c *destroyCommandBase) Init(args []string) error {
switch len(args) {
case 0:
return errors.New("no controller specified")
case 1:
return c.SetControllerName(args[0])
default:
return cmd.CheckEmpty(args[1:])
}
}
// getControllerEnviron returns the Environ for the controller model.
//
// getControllerEnviron gets the information required to get the
// Environ by first checking the config store, then querying the
// API if the information is not in the store.
func (c *destroyCommandBase) getControllerEnviron(
ctx *cmd.Context,
store jujuclient.ClientStore,
controllerName string,
sysAPI destroyControllerAPI,
) (environs.Environ, error) {
env, err := c.getControllerEnvironFromStore(ctx, store, controllerName)
if errors.IsNotFound(err) {
return c.getControllerEnvironFromAPI(sysAPI, controllerName)
} else if err != nil {
return nil, errors.Annotate(err, "getting environ using bootstrap config from client store")
}
return env, nil
}
func (c *destroyCommandBase) getControllerEnvironFromStore(
ctx *cmd.Context,
store jujuclient.ClientStore,
controllerName string,
) (environs.Environ, error) {
bootstrapConfig, params, err := modelcmd.NewGetBootstrapConfigParamsFunc(ctx, store)(controllerName)
if err != nil {
return nil, errors.Trace(err)
}
provider, err := environs.Provider(bootstrapConfig.CloudType)
if err != nil {
return nil, errors.Trace(err)
}
cfg, err := provider.PrepareConfig(*params)
if err != nil {
return nil, errors.Trace(err)
}
return environs.New(environs.OpenParams{
Cloud: params.Cloud,
Config: cfg,
})
}
func (c *destroyCommandBase) getControllerEnvironFromAPI(
api destroyControllerAPI,
controllerName string,
) (environs.Environ, error) {
if api == nil {
return nil, errors.New(
"unable to get bootstrap information from client store or API",
)
}
attrs, err := api.ModelConfig()
if err != nil {
return nil, errors.Annotate(err, "getting model config from API")
}
cfg, err := config.New(config.NoDefaults, attrs)
if err != nil {
return nil, errors.Trace(err)
}
cloudSpec, err := api.CloudSpec(names.NewModelTag(cfg.UUID()))
if err != nil {
return nil, errors.Annotate(err, "getting cloud spec from API")
}
return environs.New(environs.OpenParams{
Cloud: cloudSpec,
Config: cfg,
})
}
func confirmDestruction(ctx *cmd.Context, controllerName string) error {
// Get confirmation from the user that they want to continue
fmt.Fprintf(ctx.Stdout, destroySysMsg, controllerName)
scanner := bufio.NewScanner(ctx.Stdin)
scanner.Scan()
err := scanner.Err()
if err != nil && err != io.EOF {
return errors.Annotate(err, "controller destruction aborted")
}
answer := strings.ToLower(scanner.Text())
if answer != "y" && answer != "yes" {
return errors.New("controller destruction aborted")
}
return nil
}