github.com/cloud-green/juju@v0.0.0-20151002100041-a00291338d3d/worker/uniter/runner/jujuc/add-metric.go (about) 1 // Copyright 2012-2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package jujuc 5 6 import ( 7 "fmt" 8 "time" 9 10 "github.com/juju/cmd" 11 "github.com/juju/errors" 12 "github.com/juju/utils/keyvalues" 13 "gopkg.in/juju/charm.v6-unstable" 14 ) 15 16 // Metric represents a single metric set by the charm. 17 type Metric struct { 18 Key string 19 Value string 20 Time time.Time 21 } 22 23 // AddMetricCommand implements the add-metric command. 24 type AddMetricCommand struct { 25 cmd.CommandBase 26 ctx Context 27 Metrics []Metric 28 } 29 30 // NewAddMetricCommand generates a new AddMetricCommand. 31 func NewAddMetricCommand(ctx Context) (cmd.Command, error) { 32 return &AddMetricCommand{ctx: ctx}, nil 33 } 34 35 // Info returns the command infor structure for the add-metric command. 36 func (c *AddMetricCommand) Info() *cmd.Info { 37 return &cmd.Info{ 38 Name: "add-metric", 39 Args: "key1=value1 [key2=value2 ...]", 40 Purpose: "send metrics", 41 } 42 } 43 44 // Init parses the command's parameters. 45 func (c *AddMetricCommand) Init(args []string) error { 46 now := time.Now() 47 if len(args) == 0 { 48 return fmt.Errorf("no metrics specified") 49 } 50 options, err := keyvalues.Parse(args, false) 51 if err != nil { 52 return err 53 } 54 for key, value := range options { 55 c.Metrics = append(c.Metrics, Metric{key, value, now}) 56 } 57 return nil 58 } 59 60 // Run adds metrics to the hook context. 61 func (c *AddMetricCommand) Run(ctx *cmd.Context) (err error) { 62 for _, metric := range c.Metrics { 63 if charm.IsBuiltinMetric(metric.Key) { 64 return errors.Errorf("%v uses a reserved prefix", metric.Key) 65 } 66 err := c.ctx.AddMetric(metric.Key, metric.Value, metric.Time) 67 if err != nil { 68 return errors.Annotate(err, "cannot record metric") 69 } 70 } 71 return nil 72 }