-
Notifications
You must be signed in to change notification settings - Fork 100
/
metric.go
126 lines (108 loc) · 2.24 KB
/
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package metric
import (
"fmt"
"math"
"sort"
"strings"
)
// Context XXX
type Context [4]string
// Formatter XXX
type Formatter func(metric Metric) interface{}
// Metric XXX
type Metric struct {
Name string
Value interface{}
Tags []string
Hostname string
DeviceName string
Timestamp int64
LastSampleTime int64
Type string
Samplerate float64
Formatter Formatter
}
// Field XXX
type Field struct {
Name string
Type string
}
// NewMetric creates a new instance of Metric.
func NewMetric(name string, value interface{}, tags ...[]string) Metric {
if value == nil {
panic("Value can't be nil")
}
m := Metric{
Name: name,
Value: value,
}
if len(tags) > 0 {
m.Tags = tags[0]
}
return m
}
func (m *Metric) getCorrectedValue() (float64, error) {
var value float64
switch d := m.Value.(type) {
case int:
value = float64(int(d))
case int32:
value = float64(int32(d))
case uint32:
value = float64(uint32(d))
case int64:
value = float64(int64(d))
case uint64:
value = float64(uint64(d))
case float32:
value = float64(d)
case float64:
value = float64(d)
default:
return 0, fmt.Errorf("undeterminable type: %s", d)
}
if math.IsNaN(value) || math.IsInf(value, 0) {
return 0, fmt.Errorf("NaN and Inf is unsupported value for %s", m.Name)
}
return value, nil
}
func (m *Metric) removeDuplicates(s []string) []string {
result := []string{}
found := map[string]bool{}
for _, val := range s {
if _, ok := found[val]; !ok {
result = append(result, val)
found[val] = true
}
}
return result
}
func (m *Metric) context() Context {
tags := m.removeDuplicates(m.Tags)
sort.Strings(tags)
return Context{m.Name, strings.Join(tags, ","), m.Hostname, m.DeviceName}
}
// IsExpired XXX
func (m *Metric) IsExpired(timestamp, expirySeconds int64) bool {
if timestamp-m.LastSampleTime > expirySeconds {
return true
}
return false
}
// String XXX
func (m *Metric) String() string {
return fmt.Sprintf("%s %f %v", m.Name, m.Value, m.Tags)
}
// Format XXX
func (m Metric) Format() interface{} {
if m.Formatter != nil {
return m.Formatter(m)
}
return m
}
// UpdateMap XXX
func UpdateMap(dst, src map[string]Field) {
for k, v := range src {
dst[k] = v
}
}