forked from sensu/sensu-prometheus-collector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsensu-prometheus-collector.go
203 lines (148 loc) · 4.29 KB
/
sensu-prometheus-collector.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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"net/http"
"os"
"strconv"
"time"
"github.com/prometheus/client_golang/api/prometheus"
"github.com/prometheus/common/expfmt"
"github.com/prometheus/common/model"
)
type Tag struct {
Name model.LabelName
Value model.LabelValue
}
type Metric struct {
Tags []Tag
Value float64
}
func CreateJSONMetrics(samples model.Vector) string {
metrics := []Metric{}
for _, sample := range samples {
metric := Metric{}
for name, value := range sample.Metric {
tag := Tag{
Name: name,
Value: value,
}
metric.Tags = append(metric.Tags, tag)
}
metric.Value = float64(sample.Value)
metrics = append(metrics, metric)
}
jsonMetrics, _ := json.Marshal(metrics)
return string(jsonMetrics)
}
func CreateGraphiteMetrics(samples model.Vector, metricPrefix string) string {
metrics := ""
for _, sample := range samples {
name := fmt.Sprintf("%s%s", metricPrefix, sample.Metric["__name__"])
value := strconv.FormatFloat(float64(sample.Value), 'f', -1, 64)
now := time.Now()
timestamp := now.Unix()
metric := fmt.Sprintf("%s %s %d\n", name, value, timestamp)
metrics += metric
}
return metrics
}
func CreateInfluxMetrics(samples model.Vector, metricPrefix string) string {
metrics := ""
for _, sample := range samples {
metric := fmt.Sprintf("%s%s", metricPrefix, sample.Metric["__name__"])
for name, value := range sample.Metric {
if name != "__name__" {
metric += fmt.Sprintf(",%s=%s", name, value)
}
}
value := strconv.FormatFloat(float64(sample.Value), 'f', -1, 64)
now := time.Now()
timestamp := now.Unix()
metric += fmt.Sprintf(" value=%s %d\n", value, timestamp)
metrics += metric
}
return metrics
}
func OutputMetrics(samples model.Vector, outputFormat string, metricPrefix string) error {
output := ""
switch outputFormat {
case "influx":
output = CreateInfluxMetrics(samples, metricPrefix)
case "graphite":
output = CreateGraphiteMetrics(samples, metricPrefix)
case "json":
output = CreateJSONMetrics(samples)
}
fmt.Println(output)
return nil
}
func QueryPrometheus(promURL string, queryString string) (model.Vector, error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
promConfig := prometheus.Config{Address: promURL}
promClient, err := prometheus.New(promConfig)
if err != nil {
return nil, err
}
promQueryClient := prometheus.NewQueryAPI(promClient)
promResponse, err := promQueryClient.Query(ctx, queryString, time.Now())
if err != nil {
return nil, err
}
if promResponse.Type() == model.ValVector {
return promResponse.(model.Vector), nil
}
return nil, errors.New("unexpected response type")
}
func QueryExporter(exporterURL string) (model.Vector, error) {
expResponse, err := http.Get(exporterURL)
defer expResponse.Body.Close()
if err != nil {
return nil, err
}
if expResponse.StatusCode != http.StatusOK {
return nil, errors.New("exporter returned non OK HTTP response status")
}
var parser expfmt.TextParser
metricFamilies, err := parser.TextToMetricFamilies(expResponse.Body)
if err != nil {
return nil, err
}
samples := model.Vector{}
decodeOptions := &expfmt.DecodeOptions{
Timestamp: model.Time(time.Now().Unix()),
}
for _, family := range metricFamilies {
familySamples, _ := expfmt.ExtractSamples(decodeOptions, family)
samples = append(samples, familySamples...)
}
return samples, nil
}
func main() {
exporterURL := flag.String("exporter-url", "", "Prometheus exporter URL to pull metrics from.")
promURL := flag.String("prom-url", "http://localhost:9090", "Prometheus API URL.")
queryString := flag.String("prom-query", "up", "Prometheus API query string.")
outputFormat := flag.String("output-format", "influx", "The check output format to use for metrics {influx|graphite|json}.")
metricPrefix := flag.String("metric-prefix", "", "Metric name prefix, only supported by line protocol output formats.")
flag.Parse()
samples := model.Vector{}
var err error
if *exporterURL != "" {
samples, err = QueryExporter(*exporterURL)
} else {
samples, err = QueryPrometheus(*promURL, *queryString)
}
if err != nil {
fmt.Errorf("%v", err)
os.Exit(2)
}
err = OutputMetrics(samples, *outputFormat, *metricPrefix)
if err != nil {
fmt.Errorf("%v", err)
os.Exit(2)
}
}