github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/cmd/juju/machine/remove.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package machine 5 6 import ( 7 "fmt" 8 9 "github.com/juju/cmd" 10 "github.com/juju/names" 11 "launchpad.net/gnuflag" 12 13 "github.com/juju/juju/cmd/juju/block" 14 "github.com/juju/juju/cmd/modelcmd" 15 ) 16 17 // NewRemoveCommand returns a command used to remove a specified machine. 18 func NewRemoveCommand() cmd.Command { 19 return modelcmd.Wrap(&removeCommand{}) 20 } 21 22 // removeCommand causes an existing machine to be destroyed. 23 type removeCommand struct { 24 modelcmd.ModelCommandBase 25 api RemoveMachineAPI 26 MachineIds []string 27 Force bool 28 } 29 30 const destroyMachineDoc = ` 31 Machines that are responsible for the model cannot be removed. Machines 32 running units or containers can only be removed with the --force flag; doing 33 so will also remove all those units and containers without giving them any 34 opportunity to shut down cleanly. 35 36 Examples: 37 # Remove machine number 5 which has no running units or containers 38 $ juju remove-machine 5 39 40 # Remove machine 6 and any running units or containers 41 $ juju remove-machine 6 --force 42 ` 43 44 // Info implements Command.Info. 45 func (c *removeCommand) Info() *cmd.Info { 46 return &cmd.Info{ 47 Name: "remove-machine", 48 Args: "<machineID[s]> ...", 49 Purpose: "remove machines from the model", 50 Doc: destroyMachineDoc, 51 Aliases: []string{"remove-machines"}, 52 } 53 } 54 55 // SetFlags implements Command.SetFlags. 56 func (c *removeCommand) SetFlags(f *gnuflag.FlagSet) { 57 f.BoolVar(&c.Force, "force", false, "completely remove machine and all dependencies") 58 } 59 60 func (c *removeCommand) Init(args []string) error { 61 if len(args) == 0 { 62 return fmt.Errorf("no machines specified") 63 } 64 for _, id := range args { 65 if !names.IsValidMachine(id) { 66 return fmt.Errorf("invalid machine id %q", id) 67 } 68 } 69 c.MachineIds = args 70 return nil 71 } 72 73 type RemoveMachineAPI interface { 74 DestroyMachines(machines ...string) error 75 ForceDestroyMachines(machines ...string) error 76 Close() error 77 } 78 79 func (c *removeCommand) getRemoveMachineAPI() (RemoveMachineAPI, error) { 80 if c.api != nil { 81 return c.api, nil 82 } 83 return c.NewAPIClient() 84 } 85 86 // Run implements Command.Run. 87 func (c *removeCommand) Run(_ *cmd.Context) error { 88 client, err := c.getRemoveMachineAPI() 89 if err != nil { 90 return err 91 } 92 defer client.Close() 93 if c.Force { 94 err = client.ForceDestroyMachines(c.MachineIds...) 95 } else { 96 err = client.DestroyMachines(c.MachineIds...) 97 } 98 return block.ProcessBlockedError(err, block.BlockRemove) 99 }