github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/worker/uniter/runner/jujuc/network-get.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package jujuc
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/juju/cmd"
    10  	"github.com/juju/errors"
    11  	"github.com/juju/gnuflag"
    12  )
    13  
    14  // NetworkGetCommand implements the network-get command.
    15  type NetworkGetCommand struct {
    16  	cmd.CommandBase
    17  	ctx Context
    18  
    19  	bindingName    string
    20  	primaryAddress bool
    21  
    22  	out cmd.Output
    23  }
    24  
    25  func NewNetworkGetCommand(ctx Context) (cmd.Command, error) {
    26  	cmd := &NetworkGetCommand{ctx: ctx}
    27  	return cmd, nil
    28  }
    29  
    30  // Info is part of the cmd.Command interface.
    31  func (c *NetworkGetCommand) Info() *cmd.Info {
    32  	args := "<binding-name> --primary-address"
    33  	doc := `
    34  network-get returns the network config for a given binding name. The only
    35  supported flag for now is --primary-address, which is required and returns
    36  the IP address the local unit should advertise as its endpoint to its peers.
    37  `
    38  	return &cmd.Info{
    39  		Name:    "network-get",
    40  		Args:    args,
    41  		Purpose: "get network config",
    42  		Doc:     doc,
    43  	}
    44  }
    45  
    46  // SetFlags is part of the cmd.Command interface.
    47  func (c *NetworkGetCommand) SetFlags(f *gnuflag.FlagSet) {
    48  	c.out.AddFlags(f, "smart", cmd.DefaultFormatters)
    49  	f.BoolVar(&c.primaryAddress, "primary-address", false, "get the primary address for the binding")
    50  }
    51  
    52  // Init is part of the cmd.Command interface.
    53  func (c *NetworkGetCommand) Init(args []string) error {
    54  
    55  	if len(args) < 1 {
    56  		return errors.New("no arguments specified")
    57  	}
    58  	c.bindingName = args[0]
    59  	if c.bindingName == "" {
    60  		return fmt.Errorf("no binding name specified")
    61  	}
    62  
    63  	if !c.primaryAddress {
    64  		return fmt.Errorf("--primary-address is currently required")
    65  	}
    66  
    67  	return cmd.CheckEmpty(args[1:])
    68  }
    69  
    70  func (c *NetworkGetCommand) Run(ctx *cmd.Context) error {
    71  	netConfig, err := c.ctx.NetworkConfig(c.bindingName)
    72  	if err != nil {
    73  		return errors.Trace(err)
    74  	}
    75  	if len(netConfig) < 1 {
    76  		return fmt.Errorf("no network config found for binding %q", c.bindingName)
    77  	}
    78  
    79  	if c.primaryAddress {
    80  		return c.out.Write(ctx, netConfig[0].Address)
    81  	}
    82  
    83  	return nil // never reached as --primary-address is required.
    84  }