github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/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/v3" 10 "github.com/juju/errors" 11 "github.com/juju/gnuflag" 12 13 jujucmd "github.com/juju/juju/cmd" 14 "github.com/juju/juju/rpc/params" 15 ) 16 17 // UnitGetCommand implements the unit-get command. 18 type UnitGetCommand struct { 19 cmd.CommandBase 20 ctx Context 21 Key string 22 out cmd.Output 23 } 24 25 func NewUnitGetCommand(ctx Context) (cmd.Command, error) { 26 return &UnitGetCommand{ctx: ctx}, nil 27 } 28 29 func (c *UnitGetCommand) Info() *cmd.Info { 30 return jujucmd.Info(&cmd.Info{ 31 Name: "unit-get", 32 Args: "<setting>", 33 Purpose: "print public-address or private-address", 34 }) 35 } 36 37 func (c *UnitGetCommand) SetFlags(f *gnuflag.FlagSet) { 38 c.out.AddFlags(f, "smart", cmd.DefaultFormatters.Formatters()) 39 } 40 41 func (c *UnitGetCommand) Init(args []string) error { 42 if args == nil { 43 return errors.New("no setting specified") 44 } 45 if args[0] != "private-address" && args[0] != "public-address" { 46 return fmt.Errorf("unknown setting %q", args[0]) 47 } 48 c.Key = args[0] 49 return cmd.CheckEmpty(args[1:]) 50 } 51 52 func (c *UnitGetCommand) Run(ctx *cmd.Context) error { 53 var value string 54 var err error 55 if c.Key == "private-address" { 56 var networkInfos map[string]params.NetworkInfoResult 57 networkInfos, err = c.ctx.NetworkInfo([]string{""}, -1) 58 if err == nil { 59 if networkInfos[""].Error != nil { 60 err = errors.Trace(networkInfos[""].Error) 61 } 62 } 63 // If we haven't found the address the NetworkInfo-way fall back to old, spaceless method 64 if err != nil || len(networkInfos[""].Info) == 0 || len(networkInfos[""].Info[0].Addresses) == 0 { 65 value, err = c.ctx.PrivateAddress() 66 } else { 67 // Here, we preserve behaviour that changed inadvertently in 2.8.7 68 // when we pushed host name resolution from the network-get tool 69 // into the NetworkInfo method on the uniter API. 70 // If addresses were resolved from host names, return the host name 71 // instead of the IP we resolved. 72 addr := networkInfos[""].Info[0].Addresses[0] 73 if addr.Hostname != "" { 74 value = addr.Hostname 75 } else { 76 value = addr.Address 77 } 78 } 79 } else { 80 value, err = c.ctx.PublicAddress() 81 } 82 if err != nil { 83 return errors.Trace(err) 84 } 85 return c.out.Write(ctx, value) 86 }