github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/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 "gopkg.in/juju/charm.v5" 11 12 "github.com/juju/cmd" 13 "github.com/juju/errors" 14 "github.com/juju/utils/keyvalues" 15 ) 16 17 // Metric represents a single metric set by the charm. 18 type Metric struct { 19 Key string 20 Value string 21 Time time.Time 22 } 23 24 // AddMetricCommand implements the add-metric command. 25 type AddMetricCommand struct { 26 cmd.CommandBase 27 ctx Context 28 Metrics []Metric 29 } 30 31 // NewAddMetricCommand generates a new AddMetricCommand. 32 func NewAddMetricCommand(ctx Context) cmd.Command { 33 return &AddMetricCommand{ctx: ctx} 34 } 35 36 // Info returns the command infor structure for the add-metric command. 37 func (c *AddMetricCommand) Info() *cmd.Info { 38 return &cmd.Info{ 39 Name: "add-metric", 40 Args: "key1=value1 [key2=value2 ...]", 41 Purpose: "send metrics", 42 } 43 } 44 45 // Init parses the command's parameters. 46 func (c *AddMetricCommand) Init(args []string) error { 47 now := time.Now() 48 if len(args) == 0 { 49 return fmt.Errorf("no metrics specified") 50 } 51 options, err := keyvalues.Parse(args, false) 52 if err != nil { 53 return err 54 } 55 for key, value := range options { 56 c.Metrics = append(c.Metrics, Metric{key, value, now}) 57 } 58 return nil 59 } 60 61 // Run adds metrics to the hook context. 62 func (c *AddMetricCommand) Run(ctx *cmd.Context) (err error) { 63 for _, metric := range c.Metrics { 64 if charm.IsBuiltinMetric(metric.Key) { 65 return errors.Errorf("%v uses a reserved prefix", metric.Key) 66 } 67 err := c.ctx.AddMetric(metric.Key, metric.Value, metric.Time) 68 if err != nil { 69 return errors.Annotate(err, "cannot record metric") 70 } 71 } 72 return nil 73 }