/
add-metric.go
105 lines (94 loc) · 2.57 KB
/
add-metric.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Copyright 2012-2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package jujuc
import (
"fmt"
"strings"
"time"
"github.com/juju/charm/v12"
"github.com/juju/cmd/v3"
"github.com/juju/errors"
"github.com/juju/gnuflag"
"github.com/juju/utils/v3/keyvalues"
jujucmd "github.com/juju/juju/cmd"
)
// Metric represents a single metric set by the charm.
type Metric struct {
Key string
Value string
Time time.Time
Labels map[string]string `json:",omitempty"`
}
// AddMetricCommand implements the add-metric command.
type AddMetricCommand struct {
cmd.CommandBase
ctx Context
Labels string
Metrics []Metric
}
// NewAddMetricCommand generates a new AddMetricCommand.
func NewAddMetricCommand(ctx Context) (cmd.Command, error) {
return &AddMetricCommand{ctx: ctx}, nil
}
// Info returns the command info structure for the add-metric command.
func (c *AddMetricCommand) Info() *cmd.Info {
return jujucmd.Info(&cmd.Info{
Name: "add-metric",
Args: "key1=value1 [key2=value2 ...]",
Purpose: "add metrics",
})
}
// SetFlags implements Command.
func (c *AddMetricCommand) SetFlags(f *gnuflag.FlagSet) {
f.StringVar(&c.Labels, "l", "", "labels to be associated with metric values")
f.StringVar(&c.Labels, "labels", "", "")
}
// Init parses the command's parameters.
func (c *AddMetricCommand) Init(args []string) error {
// TODO(fwereade): 2016-03-17 lp:1558657
now := time.Now()
if len(args) == 0 {
return fmt.Errorf("no metrics specified")
}
kvs, err := keyvalues.Parse(args, false)
if err != nil {
return errors.Annotate(err, "invalid metrics")
}
var labelArgs []string
if c.Labels != "" {
labelArgs = strings.Split(c.Labels, ",")
}
for key, value := range kvs {
labels, err := keyvalues.Parse(labelArgs, false)
if err != nil {
return errors.Annotate(err, "invalid labels")
}
c.Metrics = append(c.Metrics, Metric{
Key: key,
Value: value,
Time: now,
Labels: labels,
})
}
return nil
}
// Run adds metrics to the hook context.
func (c *AddMetricCommand) Run(ctx *cmd.Context) (err error) {
for _, metric := range c.Metrics {
if charm.IsBuiltinMetric(metric.Key) {
return errors.Errorf("%v uses a reserved prefix", metric.Key)
}
if len(metric.Labels) > 0 {
err := c.ctx.AddMetricLabels(metric.Key, metric.Value, metric.Time, metric.Labels)
if err != nil {
return errors.Annotate(err, "cannot record metric")
}
} else {
err := c.ctx.AddMetric(metric.Key, metric.Value, metric.Time)
if err != nil {
return errors.Annotate(err, "cannot record metric")
}
}
}
return nil
}