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