github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/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: "add metrics", 41 } 42 } 43 44 // Init parses the command's parameters. 45 func (c *AddMetricCommand) Init(args []string) error { 46 // TODO(fwereade): 2016-03-17 lp:1558657 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 }