github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/cmd/juju/destroymachine.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package main 5 6 import ( 7 "fmt" 8 9 "launchpad.net/gnuflag" 10 11 "launchpad.net/juju-core/cmd" 12 "launchpad.net/juju-core/juju" 13 "launchpad.net/juju-core/names" 14 "launchpad.net/juju-core/state/api/params" 15 "launchpad.net/juju-core/state/statecmd" 16 ) 17 18 // DestroyMachineCommand causes an existing machine to be destroyed. 19 type DestroyMachineCommand struct { 20 cmd.EnvCommandBase 21 MachineIds []string 22 Force bool 23 } 24 25 const destroyMachineDoc = ` 26 Machines that are responsible for the environment cannot be destroyed. Machines 27 running units or containers can only be destroyed with the --force flag; doing 28 so will also destroy all those units and containers without giving them any 29 opportunity to shut down cleanly. 30 ` 31 32 func (c *DestroyMachineCommand) Info() *cmd.Info { 33 return &cmd.Info{ 34 Name: "destroy-machine", 35 Args: "<machine> ...", 36 Purpose: "destroy machines", 37 Doc: destroyMachineDoc, 38 Aliases: []string{"remove-machine", "terminate-machine"}, 39 } 40 } 41 42 func (c *DestroyMachineCommand) SetFlags(f *gnuflag.FlagSet) { 43 c.EnvCommandBase.SetFlags(f) 44 f.BoolVar(&c.Force, "force", false, "completely remove machine and all dependencies") 45 } 46 47 func (c *DestroyMachineCommand) Init(args []string) error { 48 if len(args) == 0 { 49 return fmt.Errorf("no machines specified") 50 } 51 for _, id := range args { 52 if !names.IsMachine(id) { 53 return fmt.Errorf("invalid machine id %q", id) 54 } 55 } 56 c.MachineIds = args 57 return nil 58 } 59 60 func (c *DestroyMachineCommand) run1dot16() error { 61 if c.Force { 62 return fmt.Errorf("destroy-machine --force is not supported in Juju servers older than 1.16.4") 63 } 64 conn, err := juju.NewConnFromName(c.EnvName) 65 if err != nil { 66 return err 67 } 68 defer conn.Close() 69 // TODO: When this run1dot16 code is removed, we should remove the 70 // method in state as well (as long as add-machine also no longer 71 // needs it.) 72 return statecmd.DestroyMachines1dot16(conn.State, c.MachineIds...) 73 } 74 75 func (c *DestroyMachineCommand) Run(_ *cmd.Context) error { 76 apiclient, err := juju.NewAPIClientFromName(c.EnvName) 77 if err != nil { 78 return err 79 } 80 defer apiclient.Close() 81 if c.Force { 82 err = apiclient.ForceDestroyMachines(c.MachineIds...) 83 } else { 84 err = apiclient.DestroyMachines(c.MachineIds...) 85 } 86 // Juju 1.16.3 and older did not have DestroyMachines as an API command. 87 if params.IsCodeNotImplemented(err) { 88 logger.Infof("DestroyMachines not supported by the API server, " + 89 "falling back to <=1.16.3 compatibility") 90 return c.run1dot16() 91 } 92 return err 93 }