forked from intelsdi-x/snap-plugin-publisher-influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
influx.go
375 lines (320 loc) · 9.73 KB
/
influx.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package influx
import (
"bytes"
"encoding/gob"
"fmt"
"net/url"
"strings"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/influxdata/influxdb/client/v2"
"github.com/intelsdi-x/snap/control/plugin"
"github.com/intelsdi-x/snap/control/plugin/cpolicy"
"github.com/intelsdi-x/snap/core"
"github.com/intelsdi-x/snap/core/ctypes"
)
const (
name = "influx"
version = 15
pluginType = plugin.PublisherPluginType
maxInt64 = ^uint64(0) / 2
defaultTimestampPrecision = "s"
)
var (
// The maximum time a connection can sit around unused.
maxConnectionIdle = time.Minute * 30
// How frequently idle connections are checked
watchConnctionWait = time.Minute * 15
// Our connection pool
connPool = make(map[string]*clientConnection)
// Mutex for synchronizing connection pool changes
m = &sync.Mutex{}
)
func init() {
go watchConnections()
}
// Meta returns a plugin meta data
func Meta() *plugin.PluginMeta {
return plugin.NewPluginMeta(name, version, pluginType, []string{plugin.SnapGOBContentType}, []string{plugin.SnapGOBContentType})
}
//NewInfluxPublisher returns an instance of the InfuxDB publisher
func NewInfluxPublisher() *influxPublisher {
return &influxPublisher{}
}
type influxPublisher struct {
}
func (f *influxPublisher) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) {
cp := cpolicy.New()
config := cpolicy.NewPolicyNode()
r1, err := cpolicy.NewStringRule("host", true)
handleErr(err)
r1.Description = "Influxdb host"
config.Add(r1)
r2, err := cpolicy.NewIntegerRule("port", true)
handleErr(err)
r2.Description = "Influxdb port"
config.Add(r2)
r3, err := cpolicy.NewStringRule("database", true)
handleErr(err)
r3.Description = "Influxdb db name"
config.Add(r3)
r4, err := cpolicy.NewStringRule("user", true)
handleErr(err)
r4.Description = "Influxdb user"
config.Add(r4)
r5, err := cpolicy.NewStringRule("password", true)
handleErr(err)
r5.Description = "Influxdb password"
config.Add(r4)
cp.Add([]string{""}, config)
return cp, nil
}
func watchConnections() {
for {
time.Sleep(watchConnctionWait)
for k, c := range connPool {
if time.Now().Sub(c.LastUsed) > maxConnectionIdle {
m.Lock()
// Close the connection
c.close()
// Remove from the pool
delete(connPool, k)
m.Unlock()
}
}
}
}
// Publish publishes metric data to influxdb
// currently only 0.9 version of influxdb are supported
func (f *influxPublisher) Publish(contentType string, content []byte, config map[string]ctypes.ConfigValue) error {
logger := getLogger(config)
var metrics []plugin.MetricType
switch contentType {
case plugin.SnapGOBContentType:
dec := gob.NewDecoder(bytes.NewBuffer(content))
if err := dec.Decode(&metrics); err != nil {
logger.WithFields(log.Fields{
"err": err,
}).Error("decoding error")
return err
}
default:
logger.Errorf("unknown content type '%v'", contentType)
return fmt.Errorf("Unknown content type '%s'", contentType)
}
con, err := selectClientConnection(config)
if err != nil {
logger.Error(err)
return err
}
//Set up batch points
bps, _ := client.NewBatchPoints(client.BatchPointsConfig{
Database: config["database"].(ctypes.ConfigValueStr).Value,
RetentionPolicy: "default",
Precision: defaultTimestampPrecision,
})
for _, m := range metrics {
tags := map[string]string{}
ns := m.Namespace().Strings()
isDynamic, indexes := m.Namespace().IsDynamic()
if isDynamic {
for i, j := range indexes {
// The second return value from IsDynamic(), in this case `indexes`, is the index of
// the dynamic element in the unmodified namespace. However, here we're deleting
// elements, which is problematic when the number of dynamic elements in a namespace is
// greater than 1. Therefore, we subtract i (the loop iteration) from j
// (the original index) to compensate.
//
// Remove "data" from the namespace and create a tag for it
ns = append(ns[:j-i], ns[j-i+1:]...)
tags[m.Namespace()[j].Name] = m.Namespace()[j].Value
}
}
// Add "unit"" if we do not already have a "unit" tag
if _, ok := m.Tags()["unit"]; !ok {
tags["unit"] = m.Unit()
}
// Process the tags for this metric
for k, v := range m.Tags() {
// Convert the standard tag describing where the plugin is running to "source"
if k == core.STD_TAG_PLUGIN_RUNNING_ON {
// Unless the "source" tag is already being used
if _, ok := m.Tags()["source"]; !ok {
k = "source"
}
}
tags[k] = v
}
data := m.Data()
//publishing of nil value causes errors
if data == nil {
log.Errorf("Received nil value of metric, this metric is not published, namespace: %s, timestamp: %s", m.Namespace().String(), m.Timestamp().String())
continue
}
// NOTE: uint64 is specifically not supported by influxdb client due to potential overflow
//without convertion of uint64 to int64, data with uint64 type will be saved as strings in influx database
v, ok := m.Data().(uint64)
if ok {
data = int64(v)
if v > maxInt64 {
log.Errorf("Overflow during conversion uint64 to int64, value after conversion to int64: %d, desired uint64 value: %d ", data, v)
}
}
pt, err := client.NewPoint(strings.Join(ns, "/"), tags, map[string]interface{}{
"value": data,
}, m.Timestamp())
if err != nil {
logger.WithFields(log.Fields{
"err": err,
"batch-points": bps.Points(),
"point": pt,
}).Error("Publishing failed. Problem creating data point")
return err
}
bps.AddPoint(pt)
}
err = con.write(bps)
if err != nil {
logger.WithFields(log.Fields{
"err": err,
"batch-points": bps,
}).Error("publishing failed")
// Remove connction from pool since something is wrong
m.Lock()
con.close()
delete(connPool, con.Key)
m.Unlock()
return err
}
logger.WithFields(log.Fields{
"batch-points": bps.Points(),
}).Debug("publishing metrics")
return nil
}
func handleErr(e error) {
if e != nil {
panic(e)
}
}
func getLogger(config map[string]ctypes.ConfigValue) *log.Entry {
logger := log.WithFields(log.Fields{
"plugin-name": name,
"plugin-version": version,
"plugin-type": pluginType.String(),
})
// default
log.SetLevel(log.WarnLevel)
if debug, ok := config["debug"]; ok {
switch v := debug.(type) {
case ctypes.ConfigValueBool:
if v.Value {
log.SetLevel(log.DebugLevel)
return logger
}
default:
logger.WithFields(log.Fields{
"field": "debug",
"type": v,
"expected type": "ctypes.ConfigValueBool",
}).Error("invalid config type")
}
}
if loglevel, ok := config["log-level"]; ok {
switch v := loglevel.(type) {
case ctypes.ConfigValueStr:
switch strings.ToLower(v.Value) {
case "warn":
log.SetLevel(log.WarnLevel)
case "error":
log.SetLevel(log.ErrorLevel)
case "debug":
log.SetLevel(log.DebugLevel)
case "info":
log.SetLevel(log.InfoLevel)
default:
log.WithFields(log.Fields{
"value": strings.ToLower(v.Value),
"acceptable values": "warn, error, debug, info",
}).Warn("invalid config value")
}
default:
logger.WithFields(log.Fields{
"field": "log-level",
"type": v,
"expected type": "ctypes.ConfigValueStr",
}).Error("invalid config type")
}
}
return logger
}
type clientConnection struct {
Key string
Conn *client.Client
LastUsed time.Time
}
// Map the batch points write into client.Client
func (c *clientConnection) write(bps client.BatchPoints) error {
return (*c.Conn).Write(bps)
}
// Map the close function into client.Client
func (c *clientConnection) close() error {
return (*c.Conn).Close()
}
func selectClientConnection(config map[string]ctypes.ConfigValue) (*clientConnection, error) {
// This is not an ideal way to get the logger but deferring solving this for a later date
logger := getLogger(config)
u, err := url.Parse(fmt.Sprintf("http://%s:%d", config["host"].(ctypes.ConfigValueStr).Value, config["port"].(ctypes.ConfigValueInt).Value))
if err != nil {
return nil, err
}
// Pool changes need to be safe (read & write) since the plugin can be called concurrently by snapd.
m.Lock()
defer m.Unlock()
user := config["user"].(ctypes.ConfigValueStr).Value
pass := config["password"].(ctypes.ConfigValueStr).Value
db := config["database"].(ctypes.ConfigValueStr).Value
key := connectionKey(u, user, db)
// Do we have a existing client?
if connPool[key] == nil {
// create one and add to the pool
con, err := client.NewHTTPClient(client.HTTPConfig{
Addr: u.String(),
Username: user,
Password: pass,
})
if err != nil {
return nil, err
}
cCon := &clientConnection{
Key: key,
Conn: &con,
LastUsed: time.Now(),
}
// Add to the pool
connPool[key] = cCon
logger.Debug("Opening new InfluxDB connection[", user, "@", db, " ", u.String(), "]")
return connPool[key], nil
}
// Update when it was accessed
connPool[key].LastUsed = time.Now()
// Return it
logger.Debug("Using open InfluxDB connection[", user, "@", db, " ", u.String(), "]")
return connPool[key], nil
}
func connectionKey(u *url.URL, user, db string) string {
return fmt.Sprintf("%s:%s:%s", u.String(), user, db)
}