-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprocess.go
334 lines (316 loc) · 11 KB
/
process.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
/*This file is part of sisyphus.
*
* Copyright Datto, Inc.
* Author: John Seekins <[email protected]>
*
* Licensed under the GNU General Public License Version 3
* Fedora-License-Identifier: GPLv3+
* SPDX-2.0-License-Identifier: GPL-3.0+
* SPDX-3.0-License-Identifier: GPL-3.0-or-later
*
* sisyphus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sisyphus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sisyphus. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"bytes"
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/influxdata/influxdb/models"
json "github.com/json-iterator/go"
log "github.com/sirupsen/logrus"
)
/*
Handle incoming data in Influx's Line protocol
e.g.
weather,location=us-midwest temperature=82 1465839830100400200
Becomes:
{
"name": "weather",
"tags": {"location": "us-midwest"},
"fields": {"temperature": 82},
"timestamp": 1465839830100400200
}
The other potential change is whether or not we're "flipping" single fields for a VictoriaMetrics output
*/
func deserializeInfluxLine(thread int, msg []byte, flipSingleField bool) []InfluxMetric {
var outputStats []InfluxMetric
ProcTimeStart := time.Now()
// logFields := {"threadNum": thread, "section": "processing"}
ReceivedMsgs.Inc()
if msg == nil {
log.Warning("Empty message received from Kafka")
} else {
points, err := models.ParsePoints(msg)
if err != nil {
log.WithFields(log.Fields{"threadnum": thread, "error": err, "incoming_msg": msg, "section": "influx Line processing"}).Error("Couldn't process message")
} else {
for _, point := range points {
jsonMsg := InfluxMetric{
Name: string(point.Name()), Tags: make(map[string]string),
Fields: make(map[string]interface{}), Timestamp: 0,
}
for _, tag := range point.Tags() {
jsonMsg.Tags[string(tag.Key)] = string(tag.Value)
}
fields, err := point.Fields()
if err != nil {
log.WithFields(log.Fields{"threadnum": thread, "error": err, "incoming_msg": msg, "section": "influx Line processing"}).Error("No fields in incoming message?")
}
if flipSingleField && len(fields) < 2 {
fieldName := ""
for field, value := range fields {
fieldName = field
jsonMsg.Fields["value"] = value
}
jsonMsg.Name += fmt.Sprintf("_%v", fieldName)
} else {
for field, value := range fields {
jsonMsg.Fields[field] = value
}
}
jsonMsg.Timestamp = point.UnixNano()
outputStats = append(outputStats, jsonMsg)
}
}
}
ProcessTime.Add(float64(time.Now().Sub(ProcTimeStart)) / TimeSegmentDivisor)
return outputStats
}
/*
Handle incoming data in Influx's default JSON output...
e.g.
{
"fields": {
"field_1": 30,
"field_2": 4,
"field_N": 59,
"n_images": 660
},
"name": "docker",
"tags": {
"host": "raynor"
},
"timestamp": 1458229140
}
The only potential change is whether or not we're "flipping" single fields for a VictoriaMetrics output
*/
func deserializeInfluxJSON(thread int, msg []byte, flipSingleField bool) []InfluxMetric {
var outputStats []InfluxMetric
ProcTimeStart := time.Now()
// logFields := {"threadNum": thread, "section": "processing"}
ReceivedMsgs.Inc()
if msg == nil {
log.Warning("Empty message received from Kafka")
} else {
var jsonMsg InfluxMetric
err := json.Unmarshal(msg, &jsonMsg)
if err != nil {
log.WithFields(log.Fields{"threadNum": thread, "error": err, "incoming_msg": msg, "section": "influx JSON processing"}).Error("Couldn't process message")
} else {
if flipSingleField && len(jsonMsg.Fields) < 2 {
// log.WithFields(log.Fields{"Message": jsonMsg, "threadNum": thread, "section": "processing"}).Info("Processing Message")
/*
Address single field messages
We'll add the field name to the metric name and make the field `value`.
This will make -influxSkipSingleField
*/
tmpMetric := InfluxMetric{
Name: "", Fields: make(map[string]interface{}),
Tags: make(map[string]string), Timestamp: jsonMsg.Timestamp,
}
fieldName := ""
for key, value := range jsonMsg.Fields {
fieldName = key
tmpMetric.Fields["value"] = value
}
tmpMetric.Name = fmt.Sprintf("%v_%v", jsonMsg.Name, fieldName)
for k, v := range jsonMsg.Tags {
tmpMetric.Tags[k] = v
}
// log.WithFields(log.Fields{"Message": tmpMetric, "threadNum": thread, "section": "influx JSON processing"}).Info("Finished Message")
outputStats = append(outputStats, tmpMetric)
} else {
outputStats = append(outputStats, jsonMsg)
}
}
}
ProcessTime.Add(float64(time.Now().Sub(ProcTimeStart)) / TimeSegmentDivisor)
return outputStats
}
/*
Handle data in Prometheus' JSON format
{
"timestamp": "1970-01-01T00:00:00Z",
"value": "9876543210",
"name": "up",
"labels": {
"__name__": "up",
"label1": "value1",
"label2": "value2"
}
}
Because Prometheus metrics should already meet the prometheus data model requirements, we don't send them
through filtering. This means we _do_ have to handle normalization here, as well as addressing the "single field"
issue for VictoriaMetrics outputs.
*/
func deserializePromJSON(thread int, msg []byte, normalize bool, flipSingleField bool) []InfluxMetric {
var outputStats []InfluxMetric
ProcTimeStart := time.Now()
ReceivedMsgs.Inc()
if msg == nil {
log.Warning("Empty message received from Kafka")
} else {
// nice that bytes has a ToLower functions like strings do, makes normalization easy
if normalize {
msg = bytes.ToLower(msg)
}
var jsonMsg PromMetric
err := json.Unmarshal(msg, &jsonMsg)
if err != nil {
log.WithFields(log.Fields{"threadNum": thread, "error": err, "incoming_msg": msg, "section": "prometheus processing"}).Error("Couldn't process message")
} else {
/*
normalizing the bytes before we serialize means the timestamp field gets slightly munged.
This is because the timestamp coming in may be in RFC3339
*/
if normalize {
jsonMsg.Timestamp = strings.ToUpper(jsonMsg.Timestamp)
}
/*
Timestamps produced by https://github.com/Telefonica/prometheus-kafka-adapter (which we're relying on)
come in as RFC3339. Need to convert that back to int64
*/
ts, err := time.Parse(time.RFC3339, jsonMsg.Timestamp)
if err != nil {
log.WithFields(log.Fields{"threadNum": thread, "error": err, "incoming_msg": msg, "section": "prometheus processing", "timestamp": jsonMsg.Timestamp}).Fatal("Invalid timestamp in message")
} else {
/*
For prometheus metrics, tags/labels don't
need special processing.
*/
finalMsg := InfluxMetric{
Name: "", Fields: make(map[string]interface{}),
Tags: make(map[string]string), Timestamp: ts.Unix(),
}
for key, value := range jsonMsg.Labels {
// don't add the __name__ tag, it's the name of the metric already
if key == "__name__" {
continue
}
finalMsg.Tags[key] = value
}
if flipSingleField {
/*
all prometheus metrics have a single "field" value
so handling single field issues is simpler:
We simply make the single field key `value`.
*/
finalMsg.Name = jsonMsg.Name
finalMsg.Fields["value"] = jsonMsg.Value
} else {
/*
The dance around turning a regular prometheus object
into an influx object is a bit weirder...
If we have multiple pieces to our name based on a consistent
splittable token (_ in our case), we can make the
field value be the final section of the metric "name".
If there's only one object after splitting on our token,
we simply add "value" as the field name.
*/
tmpSlice := strings.Split(jsonMsg.Name, "_")
tmpSliceLen := len(tmpSlice)
if tmpSliceLen > 1 {
finalMsg.Fields[tmpSlice[tmpSliceLen-1]] = jsonMsg.Value
finalMsg.Name = strings.Join(tmpSlice[0:tmpSliceLen-1], "_")
} else {
finalMsg.Fields["value"] = jsonMsg.Value
finalMsg.Name = jsonMsg.Name
}
}
outputStats = append(outputStats, finalMsg)
}
}
}
ProcessTime.Add(float64(time.Now().Sub(ProcTimeStart)) / TimeSegmentDivisor)
return outputStats
}
//ProcessInfluxLineMsg : parse and forward an influx line protocol message
func ProcessInfluxLineMsg(ctx context.Context, thread int, inChannel chan []byte, outChannel chan InfluxMetric, wg *sync.WaitGroup, flipSingleField bool) {
log.WithFields(log.Fields{"threadNum": thread, "section": "influx Line processing"}).Info("processing thread starting...")
defer wg.Done()
processloop:
for {
select {
case msg := <-inChannel:
for _, metric := range deserializeInfluxLine(thread, msg, flipSingleField) {
outChannel <- metric
}
case <-ctx.Done():
log.WithFields(log.Fields{"threadNum": thread, "section": "influx Line processing"}).Info("Closing processing thread...")
for msg := range inChannel {
for _, metric := range deserializeInfluxLine(thread, msg, flipSingleField) {
outChannel <- metric
}
}
break processloop
}
}
}
//ProcessInfluxJSONMsg : parse and forward an influx JSON protocol message
func ProcessInfluxJSONMsg(ctx context.Context, thread int, inChannel chan []byte, outChannel chan InfluxMetric, wg *sync.WaitGroup, flipSingleField bool) {
log.WithFields(log.Fields{"threadNum": thread, "section": "influx JSON processing"}).Info("processing thread starting...")
defer wg.Done()
processloop:
for {
select {
case msg := <-inChannel:
for _, metric := range deserializeInfluxJSON(thread, msg, flipSingleField) {
outChannel <- metric
}
case <-ctx.Done():
log.WithFields(log.Fields{"threadNum": thread, "section": "influx JSON processing"}).Info("Closing processing thread...")
for msg := range inChannel {
for _, metric := range deserializeInfluxJSON(thread, msg, flipSingleField) {
outChannel <- metric
}
}
break processloop
}
}
}
//ProcessPromMsg : parse and forward a Prometheus JSON protocol message
func ProcessPromMsg(ctx context.Context, thread int, inChannel chan []byte, outChannel chan InfluxMetric, normalize bool, flipSingleField bool, wg *sync.WaitGroup) {
log.WithFields(log.Fields{"threadNum": thread, "section": "prometheus processing"}).Info("processing thread starting...")
defer wg.Done()
processloop:
for {
select {
case msg := <-inChannel:
for _, metric := range deserializePromJSON(thread, msg, normalize, flipSingleField) {
outChannel <- metric
}
case <-ctx.Done():
log.WithFields(log.Fields{"threadNum": thread, "section": "prometheus processing"}).Info("Closing processing thread...")
for msg := range inChannel {
for _, metric := range deserializePromJSON(thread, msg, normalize, flipSingleField) {
outChannel <- metric
}
}
break processloop
}
}
}