-
Notifications
You must be signed in to change notification settings - Fork 2
/
prometheus-downsampler.go
341 lines (290 loc) · 9.27 KB
/
prometheus-downsampler.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
package main
import (
"bufio"
"context"
"errors"
"fmt"
lalalog "github.com/lalamove-go/logs"
prometheusApi "github.com/prometheus/client_golang/api"
"github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
"go.uber.org/zap"
"gopkg.in/urfave/cli.v1"
"math/rand"
"os"
"runtime"
"strings"
"time"
)
type SelectRange struct {
Start, End time.Time
Step time.Duration
}
func (r SelectRange) String() string {
return fmt.Sprintf("%v to %v with %v step.", r.Start, r.End, r.Step)
}
type metric struct {
name string
values []model.SamplePair
value float64
time model.Time
}
const (
METRIC_LABEL = "__name__"
)
var lastExecuteTime time.Time
var running bool = false
var concurrency int
var sourcePrometheusUrl string
var outputPath string
var collectInterval time.Duration
func queryRangeData(concurrency chan int, api v1.API, query string, timeRange SelectRange, result chan []*metric) (model.Value, error) {
concurrency <- 0
rawData, queryErr := api.QueryRange(context.Background(), query, v1.Range{Start: timeRange.Start, End: timeRange.End, Step: timeRange.Step})
if queryErr != nil {
errMsg := fmt.Sprintf("Query range data error: %v", queryErr.Error())
<-concurrency
result <- []*metric{}
return nil, errors.New(errMsg)
}
<-concurrency
return rawData, nil
}
func downsampleMetrics(matrix *model.Matrix) []*metric {
type tempCounter struct {
sum model.SampleValue
count int
}
metrics := []*metric{}
for _, sample := range *matrix {
// Don't know is it have chance have metric but no value
if len(sample.Values) < 1 {
continue
}
counterByTime := make(map[model.Time]*tempCounter)
for _, v := range sample.Values {
recordTime := v.Timestamp - (v.Timestamp % model.Time(collectInterval/time.Millisecond))
counter, ok := counterByTime[recordTime]
if !ok {
counter = &tempCounter{}
counterByTime[recordTime] = counter
}
(*counterByTime[recordTime]).sum += v.Value
(*counterByTime[recordTime]).count++
}
for recordTime, counter := range counterByTime {
met := metric{name: sample.Metric.String(), value: float64(counter.sum) / float64(counter.count), time: recordTime}
metrics = append(metrics, &met)
}
}
return metrics
}
func getMetric(api v1.API, query string, timeRange SelectRange, result chan []*metric, concurrency chan int) {
defer lalalog.Logger().Sync()
// download metric data from prometheus
rawData, err := queryRangeData(concurrency, api, query, timeRange, result)
if err != nil {
// if download from prometheus got error, ignore it.
lalalog.Logger().Error("Get metric error", zap.String("error", err.Error()), zap.String("target_label", query))
result <- []*metric{}
return
}
matrix, ok := rawData.(model.Matrix)
if !ok {
// if the download data not matrix type, ignore it.
lalalog.Logger().Warn("Query result not type of metrix", zap.String("target_label", query))
result <- []*metric{}
return
}
metrics := downsampleMetrics(&matrix)
result <- metrics
}
func getMetricLabels(api v1.API) model.LabelValues {
defer lalalog.Logger().Sync()
labels, getLabelErr := api.LabelValues(context.Background(), METRIC_LABEL)
if getLabelErr != nil {
lalalog.Logger().Panic("Can't get labels", zap.String("error", getLabelErr.Error()))
}
return labels
}
func processOutput(metrics *map[string][]*metric) {
defer lalalog.Logger().Sync()
// Create temp file
tempFilePath := fmt.Sprintf("%s_%s.tmp", outputPath, randomString(6))
outputFile, err := os.Create(tempFilePath)
if err != nil {
lalalog.Logger().Fatal("Can't create output file", zap.String("filepath", tempFilePath), zap.String("error", err.Error()))
}
fileOpened := true
defer func() {
if fileOpened {
lalalog.Logger().Warn("Output file not normally closed", zap.String("filepath", tempFilePath))
outputFile.Close()
}
}()
// use buffer io for write file
writer := bufio.NewWriter(outputFile)
var counter uint64
for k, v := range *metrics {
fmt.Fprintf(writer, "# TYPE %v gauge\n", k)
for _, met := range v {
fmt.Fprintf(writer, "%v %f %d\n", met.name, met.value, met.time)
counter++
}
}
// close file before move
writer.Flush()
outputFile.Close()
fileOpened = false
// Copy file instead direct write to output file. avoid read garbage data when output file still writing
renameErr := os.Rename(tempFilePath, outputPath)
if renameErr != nil {
lalalog.Logger().Fatal("Can't rename output file", zap.String("from_filepath", tempFilePath), zap.String("to_filepath", outputPath))
}
lalalog.Logger().Info("Finish write to output file", zap.Uint64("number_metrics", counter))
PrintMemUsage()
}
func generateTimeRange() SelectRange {
startTime := time.Now().Add(-collectInterval).Truncate(collectInterval)
timeRange := SelectRange{
// Set time range for last 5 minutes. If not -1 second. It will take 6 samples.
Start: startTime,
End: startTime.Add(collectInterval - (1 * time.Second)),
Step: time.Minute,
}
return timeRange
}
func startNewProcess(api v1.API) {
defer lalalog.Logger().Sync()
// Set flag for running
running = true
defer func() {
running = false
}()
lastExecuteTime = time.Now()
lalalog.Logger().Info("Start process", zap.Time("start_time", lastExecuteTime))
PrintMemUsage()
// Get all metric name from prometheus
labels := getMetricLabels(api)
lalalog.Logger().Debug("Downloaded labels", zap.Int("number_labels", labels.Len()))
// gerate time range for range query
timeRange := generateTimeRange()
lalalog.Logger().Debug("Collect data for time", zap.String("timerange", timeRange.String()))
downloaded := make(chan []*metric)
concurrency := make(chan int, concurrency)
metrics := make(map[string][]*metric)
// Download those metric and make downsample
for _, v := range labels {
go getMetric(api, string(v), timeRange, downloaded, concurrency)
}
// Extract the metric name and save it to a map for processOutput() write metric type on output file
for i := 0; i < len(labels); i++ {
receivedMetrics := <-downloaded
if len(receivedMetrics) > 0 {
metricName := strings.Split(receivedMetrics[0].name, "{")[0]
metrics[metricName] = receivedMetrics
}
}
close(downloaded)
close(concurrency)
lalalog.Logger().Info("Metrics downloaded", zap.Time("end_time", time.Now()), zap.Duration("time_elapsed", time.Since(lastExecuteTime)))
PrintMemUsage()
processOutput(&metrics)
lalalog.Logger().Info("Finish process", zap.Time("end_time", time.Now()), zap.Duration("time_elapsed", time.Since(lastExecuteTime)))
}
func argsParserSetup() *cli.App {
app := cli.NewApp()
// Detail can refer: https://github.com/urfave/cli
app.Name = "prometheus-downsampler"
app.Usage = "Read metrics from Prometheus and downsample it to file"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "source,s",
EnvVar: "PDS_SOURCE",
Usage: "Source Prometheus endpoint.",
Value: "http://127.0.0.1:9090",
Destination: &sourcePrometheusUrl,
},
cli.StringFlag{
Name: "output,o",
EnvVar: "PDS_OUTPUT",
Usage: "Output file path.",
Value: "/tmp/prometheus_downsample_output.txt",
Destination: &outputPath,
},
cli.IntFlag{
Name: "concurrency,c",
EnvVar: "PDS_CONCURRENT",
Usage: "Max concurrent connection to source Prometheus.",
Value: 50,
Destination: &concurrency,
},
cli.DurationFlag{
Name: "interval,i",
EnvVar: "PDS_INTERVAL",
Usage: "Interval in minute for collect data from source Prometheus.",
Value: 5 * time.Minute,
Destination: &collectInterval,
},
}
app.HideVersion = true
app.HideHelp = true
return app
}
func argsHandler(c *cli.Context) error {
needHelp := c.Bool("help")
if needHelp {
cli.ShowAppHelpAndExit(c, 1)
}
return nil
}
func main() {
app := argsParserSetup()
app.Action = argsHandler
err := app.Run(os.Args)
if err != nil {
lalalog.Logger().Fatal("Parse args error", zap.String("error", err.Error()))
}
client, clientErr := prometheusApi.NewClient(prometheusApi.Config{Address: sourcePrometheusUrl})
if clientErr != nil {
lalalog.Logger().Fatal("Can't create prometheus client", zap.String("error", clientErr.Error()))
}
api := v1.NewAPI(client)
go startNewProcess(api)
for {
// Start process every hour.
<-time.After(collectInterval)
if running == true {
lalalog.Logger().Warn("Job still running. Will skip this time.", zap.Time("last_execution", lastExecuteTime))
lalalog.Logger().Sync()
} else {
go startNewProcess(api)
}
}
}
// Below function copy from Internet
// Copy from https://golangcode.com/print-the-current-memory-usage/
func PrintMemUsage() {
defer lalalog.Logger().Sync()
var m runtime.MemStats
runtime.ReadMemStats(&m)
// For info on each, see: https://golang.org/pkg/runtime/#MemStats
lalalog.Logger().Debug("Runtime memory status",
zap.Uint64("Alloc_MiB", bToMb(m.Alloc)),
zap.Uint64("TotalAlloc_MiB", bToMb(m.TotalAlloc)),
zap.Uint64("Sys_MiB", bToMb(m.Sys)),
zap.Uint32("NumGC", m.NumGC),
)
}
func bToMb(b uint64) uint64 {
return b / 1024 / 1024
}
// Copy from https://www.admfactory.com/how-to-generate-a-fixed-length-random-string-using-golang/
func randomString(n int) string {
var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, n)
for i := range b {
b[i] = letter[rand.Intn(len(letter))]
}
return string(b)
}