/
kill.go
247 lines (219 loc) · 7.96 KB
/
kill.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package controller
import (
"fmt"
"time"
"github.com/juju/cmd"
"github.com/juju/errors"
"github.com/juju/gnuflag"
"github.com/juju/utils/clock"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/cmd/modelcmd"
"github.com/juju/juju/environs"
"github.com/juju/juju/environs/config"
)
const killDoc = `
Forcibly destroy the specified controller. If the API server is accessible,
this command will attempt to destroy the controller model and all hosted models
and their resources.
If the API server is unreachable, the machines of the controller model will be
destroyed through the cloud provisioner. If there are additional machines,
including machines within hosted models, these machines will not be destroyed
and will never be reconnected to the Juju controller being destroyed.
The normal process of killing the controller will involve watching the hosted
models as they are brought down in a controlled manner. If for some reason the
models do not stop cleanly, there is a default five minute timeout. If no change
in the model state occurs for the duration of this timeout, the command will
stop watching and destroy the models directly through the cloud provider.
See also:
destroy-controller
unregister
`
// NewKillCommand returns a command to kill a controller. Killing is a forceful
// destroy.
func NewKillCommand() cmd.Command {
// Even though this command is all about killing 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 wrapKillCommand(&killCommand{
clock: clock.WallClock,
}, nil, clock.WallClock)
}
// wrapKillCommand provides the common wrapping used by tests and
// the default NewKillCommand above.
func wrapKillCommand(kill *killCommand, apiOpen modelcmd.APIOpener, clock clock.Clock) cmd.Command {
if apiOpen == nil {
apiOpen = modelcmd.OpenFunc(kill.JujuCommandBase.NewAPIRoot)
}
openStrategy := modelcmd.NewTimeoutOpener(apiOpen, clock, 10*time.Second)
return modelcmd.WrapController(
kill,
modelcmd.WrapControllerSkipControllerFlags,
modelcmd.WrapControllerSkipDefaultController,
modelcmd.WrapControllerAPIOpener(openStrategy),
)
}
// killCommand kills the specified controller.
type killCommand struct {
destroyCommandBase
clock clock.Clock
timeout time.Duration
}
// SetFlags implements Command.SetFlags.
func (c *killCommand) SetFlags(f *gnuflag.FlagSet) {
c.destroyCommandBase.SetFlags(f)
f.Var(newDurationValue(time.Minute*5, &c.timeout), "t", "Timeout before direct destruction")
f.Var(newDurationValue(time.Minute*5, &c.timeout), "timeout", "")
}
// Info implements Command.Info.
func (c *killCommand) Info() *cmd.Info {
return &cmd.Info{
Name: "kill-controller",
Args: "<controller name>",
Purpose: "Forcibly terminate all machines and other associated resources for a Juju controller.",
Doc: killDoc,
}
}
// Init implements Command.Init.
func (c *killCommand) Init(args []string) error {
return c.destroyCommandBase.Init(args)
}
// Run implements Command.Run
func (c *killCommand) Run(ctx *cmd.Context) error {
controllerName := c.ControllerName()
store := c.ClientStore()
if !c.assumeYes {
if err := confirmDestruction(ctx, controllerName); err != nil {
return err
}
}
// Attempt to connect to the API.
api, err := c.getControllerAPI()
switch {
case err == nil:
defer api.Close()
case errors.Cause(err) == common.ErrPerm:
return errors.Annotate(err, "cannot destroy controller")
default:
if errors.Cause(err) != modelcmd.ErrConnTimedOut {
logger.Debugf("unable to open api: %s", err)
}
ctx.Infof("Unable to open API: %s\n", err)
api = nil
}
// 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")
}
// If we were unable to connect to the API, just destroy the controller through
// the environs interface.
if api == nil {
ctx.Infof("Unable to connect to the API server, destroying through provider")
return environs.Destroy(controllerName, controllerEnviron, store)
}
// Attempt to destroy the controller and all environments.
err = api.DestroyController(true)
if err != nil {
ctx.Infof("Unable to destroy controller through the API: %s\nDestroying through provider", err)
return environs.Destroy(controllerName, controllerEnviron, store)
}
ctx.Infof("Destroying controller %q\nWaiting for resources to be reclaimed", controllerName)
uuid := controllerEnviron.Config().UUID()
if err := c.WaitForModels(ctx, api, uuid); err != nil {
c.DirectDestroyRemaining(ctx, api)
}
return environs.Destroy(controllerName, controllerEnviron, store)
}
// DirectDestroyRemaining will attempt to directly destroy any remaining
// models that have machines left.
func (c *killCommand) DirectDestroyRemaining(ctx *cmd.Context, api destroyControllerAPI) {
hasErrors := false
hostedConfig, err := api.HostedModelConfigs()
if err != nil {
hasErrors = true
logger.Errorf("unable to retrieve hosted model config: %v", err)
}
for _, model := range hostedConfig {
ctx.Infof("Killing %s/%s directly", model.Owner.Canonical(), model.Name)
cfg, err := config.New(config.NoDefaults, model.Config)
if err != nil {
logger.Errorf(err.Error())
hasErrors = true
continue
}
env, err := environs.New(environs.OpenParams{
Cloud: model.CloudSpec,
Config: cfg,
})
if err != nil {
logger.Errorf(err.Error())
hasErrors = true
continue
}
if err := env.Destroy(); err != nil {
logger.Errorf(err.Error())
hasErrors = true
} else {
ctx.Infof(" done")
}
}
if hasErrors {
logger.Errorf("there were problems destroying some models, manual intervention may be necessary to ensure resources are released")
} else {
ctx.Infof("All hosted models destroyed, cleaning up controller machines")
}
}
// WaitForModels will wait for the models to bring themselves down nicely.
// It will return the UUIDs of any models that need to be removed forceably.
func (c *killCommand) WaitForModels(ctx *cmd.Context, api destroyControllerAPI, uuid string) error {
thirtySeconds := (time.Second * 30)
updateStatus := newTimedStatusUpdater(ctx, api, uuid, c.clock)
ctrStatus, modelsStatus := updateStatus(0)
lastStatus := ctrStatus
lastChange := c.clock.Now().Truncate(time.Second)
deadline := lastChange.Add(c.timeout)
for ; hasUnDeadModels(modelsStatus) && (deadline.After(c.clock.Now())); ctrStatus, modelsStatus = updateStatus(5 * time.Second) {
now := c.clock.Now().Truncate(time.Second)
if ctrStatus != lastStatus {
lastStatus = ctrStatus
lastChange = now
deadline = lastChange.Add(c.timeout)
}
timeSinceLastChange := now.Sub(lastChange)
timeUntilDestruction := deadline.Sub(now)
warning := ""
// We want to show the warning if it has been more than 30 seconds since
// the last change, or we are within 30 seconds of our timeout.
if timeSinceLastChange > thirtySeconds || timeUntilDestruction < thirtySeconds {
warning = fmt.Sprintf(", will kill machines directly in %s", timeUntilDestruction)
}
ctx.Infof("%s%s", fmtCtrStatus(ctrStatus), warning)
for _, modelStatus := range modelsStatus {
ctx.Verbosef(fmtModelStatus(modelStatus))
}
}
if hasUnDeadModels(modelsStatus) {
return errors.New("timed out")
} else {
ctx.Infof("All hosted models reclaimed, cleaning up controller machines")
}
return nil
}
type durationValue time.Duration
func newDurationValue(value time.Duration, p *time.Duration) *durationValue {
*p = value
return (*durationValue)(p)
}
func (d *durationValue) Set(s string) error {
v, err := time.ParseDuration(s)
if err != nil {
return err
}
*d = durationValue(v)
return err
}
func (d *durationValue) String() string { return (*time.Duration)(d).String() }