github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/cmd/juju/action/fetch.go (about) 1 // Copyright 2014-2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package action 5 6 import ( 7 "fmt" 8 9 "github.com/juju/cmd" 10 errors "github.com/juju/errors" 11 "launchpad.net/gnuflag" 12 13 "github.com/juju/juju/apiserver/params" 14 ) 15 16 // FetchCommand fetches the results of an action by UUID. 17 type FetchCommand struct { 18 ActionCommandBase 19 out cmd.Output 20 requestedId string 21 fullSchema bool 22 } 23 24 const fetchDoc = ` 25 Show the results returned by an action. 26 ` 27 28 // Set up the YAML output. 29 func (c *FetchCommand) SetFlags(f *gnuflag.FlagSet) { 30 // TODO(binary132) add json output? 31 c.out.AddFlags(f, "yaml", map[string]cmd.Formatter{ 32 "yaml": cmd.FormatYaml, 33 }) 34 } 35 36 func (c *FetchCommand) Info() *cmd.Info { 37 return &cmd.Info{ 38 Name: "fetch", 39 Args: "<action UUID>", 40 Purpose: "WIP: show results of an action by UUID", 41 Doc: fetchDoc, 42 } 43 } 44 45 // Init validates the action ID and any other options. 46 func (c *FetchCommand) Init(args []string) error { 47 switch len(args) { 48 case 0: 49 return errors.New("no action UUID specified") 50 case 1: 51 c.requestedId = args[0] 52 return nil 53 default: 54 return cmd.CheckEmpty(args[1:]) 55 } 56 } 57 58 // Run issues the API call to get Actions by UUID. 59 func (c *FetchCommand) Run(ctx *cmd.Context) error { 60 api, err := c.NewActionAPIClient() 61 if err != nil { 62 return err 63 } 64 defer api.Close() 65 66 actionTag, err := getActionTagFromPrefix(api, c.requestedId) 67 if err != nil { 68 return err 69 } 70 71 actions, err := api.Actions(params.Entities{ 72 Entities: []params.Entity{{actionTag.String()}}, 73 }) 74 if err != nil { 75 return err 76 } 77 actionResults := actions.Results 78 numActionResults := len(actionResults) 79 if numActionResults == 0 { 80 return c.out.Write(ctx, fmt.Sprintf("no results for action %s", c.requestedId)) 81 } 82 if numActionResults != 1 { 83 return errors.Errorf("too many results for action %s", c.requestedId) 84 } 85 86 result := actionResults[0] 87 if result.Error != nil { 88 return result.Error 89 } 90 return c.out.Write(ctx, formatActionResult(result)) 91 } 92 93 func formatActionResult(result params.ActionResult) map[string]interface{} { 94 return map[string]interface{}{ 95 "status": result.Status, 96 "message": result.Message, 97 "results": result.Output, 98 "timing": map[string]string{ 99 "enqueued": result.Enqueued.String(), 100 "started": result.Started.String(), 101 "completed": result.Completed.String(), 102 }, 103 } 104 }