1package newrelic_platform_go
2
3import (
4	"log"
5	"math"
6)
7
8type ComponentData interface{}
9type IComponent interface {
10	Harvest(plugin INewrelicPlugin) ComponentData
11	SetDuration(duration int)
12	AddMetrica(model IMetrica)
13	ClearSentData()
14}
15
16type PluginComponent struct {
17	Name          string                  `json:"name"`
18	GUID          string                  `json:"guid"`
19	Duration      int                     `json:"duration"`
20	Metrics       map[string]MetricaValue `json:"metrics"`
21	MetricaModels []IMetrica              `json:"-"`
22}
23
24func NewPluginComponent(name string, guid string) *PluginComponent {
25	c := &PluginComponent{
26		Name: name,
27		GUID: guid,
28	}
29	return c
30}
31
32func (component *PluginComponent) AddMetrica(model IMetrica) {
33	component.MetricaModels = append(component.MetricaModels, model)
34}
35
36func (component *PluginComponent) ClearSentData() {
37	component.Metrics = nil
38}
39
40func (component *PluginComponent) SetDuration(duration int) {
41	component.Duration = duration
42}
43
44func (component *PluginComponent) Harvest(plugin INewrelicPlugin) ComponentData {
45	component.Metrics = make(map[string]MetricaValue, len(component.MetricaModels))
46	for i := 0; i < len(component.MetricaModels); i++ {
47		model := component.MetricaModels[i]
48		metricaKey := plugin.GetMetricaKey(model)
49
50		if newValue, err := model.GetValue(); err == nil {
51		        if math.IsInf(newValue, 0) || math.IsNaN(newValue) {
52                                newValue = 0
53                        }
54
55			if existMetric, ok := component.Metrics[metricaKey]; ok {
56				if floatExistVal, ok := existMetric.(float64); ok {
57					component.Metrics[metricaKey] = NewAggregatedMetricaValue(floatExistVal, newValue)
58				} else if aggregatedValue, ok := existMetric.(*AggregatedMetricaValue); ok {
59					aggregatedValue.Aggregate(newValue)
60				} else {
61					panic("Invalid type in metrica value")
62				}
63			} else {
64				component.Metrics[metricaKey] = newValue
65			}
66		} else {
67			log.Printf("Can not get metrica: %v, got error:%#v", model.GetName(), err)
68		}
69	}
70	return component
71}
72