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