-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
opentsdb.go
259 lines (221 loc) · 5.81 KB
/
opentsdb.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
//go:generate ../../../tools/readme_config_includer/generator
package opentsdb
import (
_ "embed"
"errors"
"fmt"
"math"
"net"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/outputs"
)
//go:embed sample.conf
var sampleConfig string
var (
allowedChars = regexp.MustCompile(`[^a-zA-Z0-9-_./\p{L}]`)
hyphenChars = strings.NewReplacer(
"@", "-",
"*", "-",
`%`, "-",
"#", "-",
"$", "-")
defaultHTTPPath = "/api/put"
defaultSeparator = "_"
)
type OpenTSDB struct {
Prefix string `toml:"prefix"`
Host string `toml:"host"`
Port int `toml:"port"`
HTTPBatchSize int `toml:"http_batch_size"`
HTTPPath string `toml:"http_path"`
Debug bool `toml:"debug"`
Separator string `toml:"separator"`
Log telegraf.Logger `toml:"-"`
}
func ToLineFormat(tags map[string]string) string {
tagsArray := make([]string, 0, len(tags))
for k, v := range tags {
tagsArray = append(tagsArray, fmt.Sprintf("%s=%s", k, v))
}
sort.Strings(tagsArray)
return strings.Join(tagsArray, " ")
}
func (*OpenTSDB) SampleConfig() string {
return sampleConfig
}
func (o *OpenTSDB) Connect() error {
if !strings.HasPrefix(o.Host, "http") && !strings.HasPrefix(o.Host, "tcp") {
o.Host = "tcp://" + o.Host
}
// Test Connection to OpenTSDB Server
u, err := url.Parse(o.Host)
if err != nil {
return fmt.Errorf("error in parsing host url: %w", err)
}
uri := fmt.Sprintf("%s:%d", u.Host, o.Port)
tcpAddr, err := net.ResolveTCPAddr("tcp", uri)
if err != nil {
return fmt.Errorf("failed to resolve TCP address: %w", err)
}
connection, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
return fmt.Errorf("failed to connect to OpenTSDB: %w", err)
}
defer connection.Close()
return nil
}
func (o *OpenTSDB) Write(metrics []telegraf.Metric) error {
if len(metrics) == 0 {
return nil
}
u, err := url.Parse(o.Host)
if err != nil {
return fmt.Errorf("error in parsing host url: %w", err)
}
if u.Scheme == "" || u.Scheme == "tcp" {
return o.WriteTelnet(metrics, u)
} else if u.Scheme == "http" || u.Scheme == "https" {
return o.WriteHTTP(metrics, u)
}
return errors.New("unknown scheme in host parameter")
}
func (o *OpenTSDB) WriteHTTP(metrics []telegraf.Metric, u *url.URL) error {
http := openTSDBHttp{
Host: u.Host,
Port: o.Port,
Scheme: u.Scheme,
User: u.User,
BatchSize: o.HTTPBatchSize,
Path: o.HTTPPath,
Debug: o.Debug,
log: o.Log,
}
for _, m := range metrics {
now := m.Time().UnixNano() / 1000000000
tags := cleanTags(m.Tags())
for fieldName, value := range m.Fields() {
switch fv := value.(type) {
case int64:
case uint64:
case float64:
// JSON does not support these special values
if math.IsNaN(fv) || math.IsInf(fv, 0) {
continue
}
default:
o.Log.Debugf("OpenTSDB does not support metric value: [%s] of type [%T].", value, value)
continue
}
metric := &HTTPMetric{
Metric: sanitize(fmt.Sprintf("%s%s%s%s",
o.Prefix, m.Name(), o.Separator, fieldName)),
Tags: tags,
Timestamp: now,
Value: value,
}
if err := http.sendDataPoint(metric); err != nil {
return err
}
}
}
return http.flush()
}
func (o *OpenTSDB) WriteTelnet(metrics []telegraf.Metric, u *url.URL) error {
// Send Data with telnet / socket communication
uri := fmt.Sprintf("%s:%d", u.Host, o.Port)
tcpAddr, err := net.ResolveTCPAddr("tcp", uri)
if err != nil {
return fmt.Errorf("failed to resolve TCP address: %w", err)
}
connection, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
return fmt.Errorf("failed to connect to OpenTSDB: %w", err)
}
defer connection.Close()
for _, m := range metrics {
now := m.Time().UnixNano() / 1000000000
tags := ToLineFormat(cleanTags(m.Tags()))
for fieldName, value := range m.Fields() {
switch fv := value.(type) {
case int64:
case uint64:
case float64:
// JSON does not support these special values
if math.IsNaN(fv) || math.IsInf(fv, 0) {
continue
}
default:
o.Log.Debugf("OpenTSDB does not support metric value: [%s] of type [%T].", value, value)
continue
}
metricValue, buildError := buildValue(value)
if buildError != nil {
o.Log.Errorf("OpenTSDB: %s", buildError.Error())
continue
}
messageLine := fmt.Sprintf("put %s %v %s %s\n",
sanitize(fmt.Sprintf("%s%s%s%s", o.Prefix, m.Name(), o.Separator, fieldName)),
now, metricValue, tags)
_, err = connection.Write([]byte(messageLine))
if err != nil {
return fmt.Errorf("telnet writing error: %w", err)
}
}
}
return nil
}
func cleanTags(tags map[string]string) map[string]string {
tagSet := make(map[string]string, len(tags))
for k, v := range tags {
val := sanitize(v)
if val != "" {
tagSet[sanitize(k)] = val
}
}
return tagSet
}
func buildValue(v interface{}) (string, error) {
var retv string
switch p := v.(type) {
case int64:
retv = IntToString(p)
case uint64:
retv = UIntToString(p)
case float64:
retv = FloatToString(p)
default:
return retv, fmt.Errorf("unexpected type %T with value %v for OpenTSDB", v, v)
}
return retv, nil
}
func IntToString(inputNum int64) string {
return strconv.FormatInt(inputNum, 10)
}
func UIntToString(inputNum uint64) string {
return strconv.FormatUint(inputNum, 10)
}
func FloatToString(inputNum float64) string {
return strconv.FormatFloat(inputNum, 'f', 6, 64)
}
func (o *OpenTSDB) Close() error {
return nil
}
func sanitize(value string) string {
// Apply special hyphenation rules to preserve backwards compatibility
value = hyphenChars.Replace(value)
// Replace any remaining illegal chars
return allowedChars.ReplaceAllLiteralString(value, "_")
}
func init() {
outputs.Add("opentsdb", func() telegraf.Output {
return &OpenTSDB{
HTTPPath: defaultHTTPPath,
Separator: defaultSeparator,
}
})
}