github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/cmd/juju/machine/base.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package machine 5 6 import ( 7 "fmt" 8 "io" 9 10 "github.com/juju/cmd" 11 "github.com/juju/errors" 12 "github.com/juju/gnuflag" 13 14 "github.com/juju/juju/apiserver/params" 15 "github.com/juju/juju/cmd/juju/status" 16 "github.com/juju/juju/cmd/modelcmd" 17 ) 18 19 // statusAPI defines the API methods for the machines and show-machine commands. 20 type statusAPI interface { 21 Status(pattern []string) (*params.FullStatus, error) 22 Close() error 23 } 24 25 // baseMachineCommand provides access to information about machines in a model. 26 type baselistMachinesCommand struct { 27 modelcmd.ModelCommandBase 28 out cmd.Output 29 isoTime bool 30 api statusAPI 31 machineIds []string 32 defaultFormat string 33 color bool 34 } 35 36 // SetFlags sets utc and format flags based on user specified options. 37 func (c *baselistMachinesCommand) SetFlags(f *gnuflag.FlagSet) { 38 c.ModelCommandBase.SetFlags(f) 39 f.BoolVar(&c.isoTime, "utc", false, "Display time as UTC in RFC3339 format") 40 f.BoolVar(&c.color, "color", false, "Force use of ANSI color codes") 41 c.out.AddFlags(f, c.defaultFormat, map[string]cmd.Formatter{ 42 "yaml": cmd.FormatYaml, 43 "json": cmd.FormatJson, 44 "tabular": c.tabular, 45 }) 46 } 47 48 var newAPIClientForMachines = func(c *baselistMachinesCommand) (statusAPI, error) { 49 if c.api != nil { 50 return c.api, nil 51 } 52 return c.NewAPIClient() 53 } 54 55 // Run implements Command.Run for baseMachinesCommand. 56 func (c *baselistMachinesCommand) Run(ctx *cmd.Context) error { 57 apiclient, err := newAPIClientForMachines(c) 58 if err != nil { 59 return errors.Trace(err) 60 } 61 defer apiclient.Close() 62 63 fullStatus, err := apiclient.Status(nil) 64 if err != nil { 65 if fullStatus == nil { 66 // Status call completely failed, there is nothing to report 67 return err 68 } 69 // Display any error, but continue to print status if some was returned 70 fmt.Fprintf(ctx.Stderr, "%v\n", err) 71 } else if fullStatus == nil { 72 return errors.Errorf("unable to obtain the current status") 73 } 74 75 formatter := status.NewStatusFormatter(fullStatus, c.isoTime) 76 formatted := formatter.MachineFormat(c.machineIds) 77 return c.out.Write(ctx, formatted) 78 } 79 80 func (c *baselistMachinesCommand) tabular(writer io.Writer, value interface{}) error { 81 return status.FormatMachineTabular(writer, c.color, value) 82 }