github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/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  
     9  	"github.com/juju/cmd"
    10  	"github.com/juju/errors"
    11  	"launchpad.net/gnuflag"
    12  
    13  	"github.com/juju/juju/apiserver/params"
    14  	"github.com/juju/juju/cmd/juju/status"
    15  	"github.com/juju/juju/cmd/modelcmd"
    16  )
    17  
    18  // statusAPI defines the API methods for the list-mahines and show-machine commands.
    19  type statusAPI interface {
    20  	Status(pattern []string) (*params.FullStatus, error)
    21  	Close() error
    22  }
    23  
    24  // baseMachineCommand provides access to information about machines in a model.
    25  type baselistMachinesCommand struct {
    26  	modelcmd.ModelCommandBase
    27  	out           cmd.Output
    28  	isoTime       bool
    29  	api           statusAPI
    30  	machineIds    []string
    31  	defaultFormat string
    32  }
    33  
    34  // SetFlags sets utc and format flags based on user specified options.
    35  func (c *baselistMachinesCommand) SetFlags(f *gnuflag.FlagSet) {
    36  	f.BoolVar(&c.isoTime, "utc", false, "Display time as UTC in RFC3339 format")
    37  	c.out.AddFlags(f, c.defaultFormat, map[string]cmd.Formatter{
    38  		"yaml":    cmd.FormatYaml,
    39  		"json":    cmd.FormatJson,
    40  		"tabular": status.FormatMachineTabular,
    41  	})
    42  }
    43  
    44  var newAPIClientForMachines = func(c *baselistMachinesCommand) (statusAPI, error) {
    45  	if c.api != nil {
    46  		return c.api, nil
    47  	}
    48  	return c.NewAPIClient()
    49  }
    50  
    51  // Run implements Command.Run for baseMachinesCommand.
    52  func (c *baselistMachinesCommand) Run(ctx *cmd.Context) error {
    53  	apiclient, err := newAPIClientForMachines(c)
    54  	if err != nil {
    55  		return errors.Trace(err)
    56  	}
    57  	defer apiclient.Close()
    58  
    59  	fullStatus, err := apiclient.Status(nil)
    60  	if err != nil {
    61  		if fullStatus == nil {
    62  			// Status call completely failed, there is nothing to report
    63  			return err
    64  		}
    65  		// Display any error, but continue to print status if some was returned
    66  		fmt.Fprintf(ctx.Stderr, "%v\n", err)
    67  	} else if fullStatus == nil {
    68  		return errors.Errorf("unable to obtain the current status")
    69  	}
    70  
    71  	formatter := status.NewStatusFormatter(fullStatus, c.isoTime)
    72  	formatted := formatter.MachineFormat(c.machineIds)
    73  	return c.out.Write(ctx, formatted)
    74  }