github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/worker/uniter/runner/jujuc/unit-get.go (about) 1 // Copyright 2012, 2013 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 jujucmd "github.com/juju/juju/cmd" 14 ) 15 16 // UnitGetCommand implements the unit-get command. 17 type UnitGetCommand struct { 18 cmd.CommandBase 19 ctx Context 20 Key string 21 out cmd.Output 22 } 23 24 func NewUnitGetCommand(ctx Context) (cmd.Command, error) { 25 return &UnitGetCommand{ctx: ctx}, nil 26 } 27 28 func (c *UnitGetCommand) Info() *cmd.Info { 29 return jujucmd.Info(&cmd.Info{ 30 Name: "unit-get", 31 Args: "<setting>", 32 Purpose: "print public-address or private-address", 33 }) 34 } 35 36 func (c *UnitGetCommand) SetFlags(f *gnuflag.FlagSet) { 37 c.out.AddFlags(f, "smart", cmd.DefaultFormatters) 38 } 39 40 func (c *UnitGetCommand) Init(args []string) error { 41 if args == nil { 42 return errors.New("no setting specified") 43 } 44 if args[0] != "private-address" && args[0] != "public-address" { 45 return fmt.Errorf("unknown setting %q", args[0]) 46 } 47 c.Key = args[0] 48 return cmd.CheckEmpty(args[1:]) 49 } 50 51 func (c *UnitGetCommand) Run(ctx *cmd.Context) error { 52 var value string 53 var err error 54 if c.Key == "private-address" { 55 networkInfos, err := c.ctx.NetworkInfo([]string{""}, -1) 56 if err == nil { 57 if networkInfos[""].Error != nil { 58 err = errors.Trace(networkInfos[""].Error) 59 } 60 } 61 // If we haven't found the address the NetworkInfo-way fall back to old, spaceless method 62 if err != nil || len(networkInfos[""].Info) == 0 || len(networkInfos[""].Info[0].Addresses) == 0 { 63 value, err = c.ctx.PrivateAddress() 64 } else { 65 value = networkInfos[""].Info[0].Addresses[0].Address 66 } 67 } else { 68 value, err = c.ctx.PublicAddress() 69 } 70 if err != nil { 71 return errors.Trace(err) 72 } 73 return c.out.Write(ctx, value) 74 }