-
Notifications
You must be signed in to change notification settings - Fork 937
/
Copy pathaction.go
422 lines (341 loc) · 10.9 KB
/
action.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
package main
import (
"errors"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/canonical/lxd/lxc/config"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
cli "github.com/canonical/lxd/shared/cmd"
"github.com/canonical/lxd/shared/i18n"
)
// Start.
type cmdStart struct {
global *cmdGlobal
action *cmdAction
}
// The function command() returns a cobra.Command object representing the "start" command.
// It is used to start one or more instances specified by the user.
func (c *cmdStart) command() *cobra.Command {
cmdAction := cmdAction{global: c.global}
c.action = &cmdAction
cmd := c.action.Command("start")
cmd.Use = usage("start", i18n.G("[<remote>:]<instance> [[<remote>:]<instance>...]"))
cmd.Short = i18n.G("Start instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Start instances`))
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return c.global.cmpInstancesAction(toComplete, "start", c.action.flagForce)
}
return cmd
}
// Pause.
type cmdPause struct {
global *cmdGlobal
action *cmdAction
}
// The function command() returns a cobra.Command object representing the "pause" command.
// It is used to pause (or freeze) one or more instances specified by the user. This command is hidden and has an alias "freeze".
func (c *cmdPause) command() *cobra.Command {
cmdAction := cmdAction{global: c.global}
c.action = &cmdAction
cmd := c.action.Command("pause")
cmd.Use = usage("pause", i18n.G("[<remote>:]<instance> [[<remote>:]<instance>...]"))
cmd.Short = i18n.G("Pause instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Pause instances`))
cmd.Aliases = []string{"freeze"}
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return c.global.cmpInstancesAction(toComplete, "pause", c.action.flagForce)
}
return cmd
}
// Restart.
type cmdRestart struct {
global *cmdGlobal
action *cmdAction
}
// The function command() returns a cobra.Command object representing the "restart" command.
// It is used to restart one or more instances specified by the user. This command restarts the instances, which is the opposite of the "pause" command.
func (c *cmdRestart) command() *cobra.Command {
cmdAction := cmdAction{global: c.global}
c.action = &cmdAction
cmd := c.action.Command("restart")
cmd.Use = usage("restart", i18n.G("[<remote>:]<instance> [[<remote>:]<instance>...]"))
cmd.Short = i18n.G("Restart instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Restart instances
The opposite of "lxc pause" is "lxc start".`))
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return c.global.cmpInstancesAction(toComplete, "restart", c.action.flagForce)
}
return cmd
}
// Stop.
type cmdStop struct {
global *cmdGlobal
action *cmdAction
}
// The function command() returns a cobra.Command object representing the "stop" command.
// It is used to stop one or more instances specified by the user. This command stops the instances, effectively shutting them down.
func (c *cmdStop) command() *cobra.Command {
cmdAction := cmdAction{global: c.global}
c.action = &cmdAction
cmd := c.action.Command("stop")
cmd.Use = usage("stop", i18n.G("[<remote>:]<instance> [[<remote>:]<instance>...]"))
cmd.Short = i18n.G("Stop instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Stop instances`))
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return c.global.cmpInstancesAction(toComplete, "stop", c.action.flagForce)
}
return cmd
}
type cmdAction struct {
global *cmdGlobal
flagAll bool
flagConsole string
flagForce bool
flagStateful bool
flagStateless bool
flagTimeout int
}
// Command is a method of the cmdAction structure which constructs and configures a cobra Command object.
// It creates a command with a specific action, defines flags based on that action, and assigns appropriate help text.
func (c *cmdAction) Command(action string) *cobra.Command {
cmd := &cobra.Command{}
cmd.RunE = c.run
cmd.Flags().BoolVar(&c.flagAll, "all", false, i18n.G("Run against all instances"))
if action == "stop" {
cmd.Flags().BoolVar(&c.flagStateful, "stateful", false, i18n.G("Store the instance state"))
} else if action == "start" {
cmd.Flags().BoolVar(&c.flagStateless, "stateless", false, i18n.G("Ignore the instance state"))
}
if shared.ValueInSlice(action, []string{"start", "restart", "stop"}) {
cmd.Flags().StringVar(&c.flagConsole, "console", "", i18n.G("Immediately attach to the console")+"``")
cmd.Flags().Lookup("console").NoOptDefVal = "console"
}
if shared.ValueInSlice(action, []string{"restart", "stop"}) {
cmd.Flags().BoolVarP(&c.flagForce, "force", "f", false, i18n.G("Force the instance to stop"))
cmd.Flags().IntVar(&c.flagTimeout, "timeout", -1, i18n.G("Time to wait for the instance to shutdown cleanly")+"``")
}
return cmd
}
// doActionAll is a method of the cmdAction structure. It performs a specified action on all instances of a remote resource.
// It ensures that flags and parameters are appropriately set, and handles any errors that may occur during the process.
func (c *cmdAction) doActionAll(action string, resource remoteResource) error {
if resource.name != "" {
// both --all and instance name given.
return errors.New(i18n.G("Both --all and instance name given"))
}
remote := resource.remote
d, err := c.global.conf.GetInstanceServer(remote)
if err != nil {
return err
}
// Pause is called freeze.
if action == "pause" {
action = "freeze"
}
// Only store state if asked to.
state := false
if action == "stop" && c.flagStateful {
state = true
}
req := api.InstancesPut{
State: &api.InstanceStatePut{
Action: action,
Timeout: c.flagTimeout,
Force: c.flagForce,
Stateful: state,
},
}
// Update all instances.
op, err := d.UpdateInstances(req, "")
if err != nil {
return err
}
progress := cli.ProgressRenderer{
Quiet: c.global.flagQuiet,
}
_, err = op.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
return err
}
err = cli.CancelableWait(op, &progress)
if err != nil {
progress.Done("")
return err
}
progress.Done("")
return nil
}
// doAction is a method of the cmdAction structure. It carries out a specified action on an instance,
// using a given config and instance name. It manages state changes, flag checks, error handling and console attachment.
func (c *cmdAction) doAction(action string, conf *config.Config, nameArg string) error {
state := false
// Pause is called freeze
if action == "pause" {
action = "freeze"
}
// Only store state if asked to
if action == "stop" && c.flagStateful {
state = true
}
if action == "stop" && c.flagForce && c.flagConsole != "" {
return errors.New(i18n.G("--console can't be used while forcing instance shutdown"))
}
remote, name, err := conf.ParseRemote(nameArg)
if err != nil {
return err
}
d, err := conf.GetInstanceServer(remote)
if err != nil {
return err
}
if name == "" {
return fmt.Errorf(i18n.G("Must supply instance name for: ")+"\"%s\"", nameArg)
}
if action == "start" {
current, _, err := d.GetInstance(name)
if err != nil {
return err
}
// "start" for a frozen instance means "unfreeze"
if current.StatusCode == api.Frozen {
action = "unfreeze"
}
// Always restore state (if present) unless asked not to
if action == "start" && current.Stateful && !c.flagStateless {
state = true
}
}
req := api.InstanceStatePut{
Action: action,
Timeout: c.flagTimeout,
Force: c.flagForce,
Stateful: state,
}
op, err := d.UpdateInstanceState(name, req, "")
if err != nil {
return err
}
if action == "stop" && c.flagConsole != "" {
// Handle console attach
console := cmdConsole{}
console.global = c.global
console.flagType = c.flagConsole
return console.runConsole(d, name)
}
progress := cli.ProgressRenderer{
Quiet: c.global.flagQuiet,
}
_, err = op.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
return err
}
// Wait for operation to finish
err = cli.CancelableWait(op, &progress)
if err != nil {
progress.Done("")
return fmt.Errorf("%s\n"+i18n.G("Try `lxc info --show-log %s` for more info"), err, nameArg)
}
progress.Done("")
// Handle console attach
if c.flagConsole != "" {
console := cmdConsole{}
console.global = c.global
console.flagType = c.flagConsole
return console.runConsole(d, name)
}
return nil
}
// Run is a method of the cmdAction structure that implements the execution logic for the given Cobra command.
// It handles actions on instances (single or all) and manages error handling, console flag restrictions, and batch operations.
func (c *cmdAction) run(cmd *cobra.Command, args []string) error {
conf := c.global.conf
var names []string
if c.flagAll {
// If no server passed, use current default.
if len(args) == 0 {
args = []string{conf.DefaultRemote + ":"}
}
// Get all the servers.
resources, err := c.global.ParseServers(args...)
if err != nil {
return err
}
for _, resource := range resources {
// We don't allow instance names with --all.
if resource.name != "" {
return errors.New(i18n.G("Both --all and instance name given"))
}
// See if we can use the bulk API.
if resource.server.HasExtension("instance_bulk_state_change") {
err = c.doActionAll(cmd.Name(), resource)
if err != nil {
return fmt.Errorf("%s: %w", resource.remote, err)
}
continue
}
ctslist, err := resource.server.GetInstances(api.InstanceTypeAny)
if err != nil {
return err
}
for _, ct := range ctslist {
switch cmd.Name() {
case "start":
if ct.StatusCode == api.Running {
continue
}
case "stop":
if ct.StatusCode == api.Stopped {
continue
}
}
names = append(names, resource.remote+":"+ct.Name)
}
}
} else {
names = args
if len(args) == 0 {
_ = cmd.Usage()
return nil
}
}
if c.flagConsole != "" {
if c.flagAll {
return errors.New(i18n.G("--console can't be used with --all"))
}
if len(names) != 1 {
return errors.New(i18n.G("--console only works with a single instance"))
}
}
// Run the action for every listed instance
results := runBatch(names, func(name string) error { return c.doAction(cmd.Name(), conf, name) })
// Single instance is easy
if len(results) == 1 {
return results[0].err
}
// Do fancier rendering for batches
success := true
for _, result := range results {
if result.err == nil {
continue
}
success = false
msg := fmt.Sprintf(i18n.G("error: %v"), result.err)
for _, line := range strings.Split(msg, "\n") {
fmt.Fprintf(os.Stderr, "%s: %s\n", result.name, line)
}
}
if !success {
fmt.Fprintln(os.Stderr, "")
return fmt.Errorf(i18n.G("Some instances failed to %s"), cmd.Name())
}
return nil
}