-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (83 loc) · 2.33 KB
/
main.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
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"strings"
"time"
"github.com/prometheus/common/log"
"github.com/prometheus/prom2json"
dto "github.com/prometheus/client_model/go"
)
func main() {
cert := flag.String("cert", "", "certificate file")
key := flag.String("key", "", "key file")
labels := flag.String("labels", "", "custom label, eg:tagk1=tagv1,tagk2=tagv2")
prefixs := flag.String("prefixs", "", "metric prefixs")
skipServerCertCheck := flag.Bool("accept-invalid-cert", false, "Accept any certificate during TLS handshake. Insecure, use only for testing.")
flag.Parse()
if len(flag.Args()) != 1 {
log.Fatalf("Usage: %s METRICS_URL", os.Args[0])
}
if (*cert != "" && *key == "") || (*cert == "" && *key != "") {
log.Fatalf("Usage: %s METRICS_URL\n with TLS client authentication: %s -cert=/path/to/certificate -key=/path/to/key METRICS_URL", os.Args[0], os.Args[0])
}
mfChan := make(chan *dto.MetricFamily, 1024)
go prom2json.FetchMetricFamilies(flag.Args()[0], mfChan, *cert, *key, *skipServerCertCheck)
metrics := []TimeSeriesData{}
ts := time.Now().Unix()
customTags := ParseTags(*labels)
for mf := range mfChan {
switch mf.GetType() {
case dto.MetricType_SUMMARY, dto.MetricType_HISTOGRAM:
continue
default:
for _, m := range mf.Metric {
hasPrefix := false
for _, prefix := range strings.Split(*prefixs, ",") {
if strings.HasPrefix(mf.GetName(), prefix) {
hasPrefix = true
break
}
}
if !hasPrefix {
continue
}
metric := TimeSeriesData{
Metric: strings.Replace(mf.GetName(), "_", ".", -1),
DataType: mf.GetType().String(),
Timestamp: ts,
Tags: makeLabels(m),
Value: getValue(m),
}
metric.AddTags(customTags)
metrics = append(metrics, metric)
}
}
}
jsonBytes, _ := json.Marshal(metrics)
if _, err := os.Stdout.Write(jsonBytes); err != nil {
log.Fatalln("error writing to stdout:", err)
}
fmt.Println()
}
func getValue(m *dto.Metric) float64 {
if m.Gauge != nil {
return m.GetGauge().GetValue()
}
if m.Counter != nil {
return m.GetCounter().GetValue()
}
if m.Untyped != nil {
return m.GetUntyped().GetValue()
}
return 0.
}
func makeLabels(m *dto.Metric) map[string]string {
result := map[string]string{}
for _, lp := range m.Label {
result[lp.GetName()] = lp.GetValue()
}
return result
}