-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmain.go
279 lines (208 loc) · 6.19 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
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
package main
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/kelseyhightower/envconfig"
"github.com/prometheus/client_golang/api/prometheus"
"github.com/prometheus/common/expfmt"
"github.com/prometheus/common/model"
)
const (
exporterAuthID = "exporter"
)
type ExporterAuth struct {
User string `envconfig:"user" default:""`
Password string `envconfig:"password" default:""`
Header string `envconfig:"header" default:""`
}
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__" {
tags := fmt.Sprintf(",%s=%s", name, value)
if !strings.Contains(tags, "\n") && strings.Count(tags, "=") == 1 {
metric += tags
}
}
}
metric = strings.Replace(metric, "\n", "", -1)
value := strconv.FormatFloat(float64(sample.Value), 'f', -1, 64)
now := time.Now()
timestamp := now.Unix()
metric += fmt.Sprintf(" value=%s %d\n", value, timestamp)
segments := strings.Split(metric, " ")
if len(segments) == 3 {
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.Print(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, auth ExporterAuth, insecureSkipVerify bool) (model.Vector, error) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: insecureSkipVerify},
}
client := &http.Client{Transport: tr}
req, err := http.NewRequest("GET", exporterURL, nil)
if err != nil {
return nil, err
}
if auth.User != "" && auth.Password != "" {
req.SetBasicAuth(auth.User, auth.Password)
}
if auth.Header != "" {
req.Header.Set("Authorization", auth.Header)
}
expResponse, err := client.Do(req)
if err != nil {
return nil, err
}
defer expResponse.Body.Close()
if expResponse.StatusCode != http.StatusOK {
return nil, errors.New("exporter returned non OK HTTP response status: " + expResponse.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 setExporterAuth(user string, password string, header string) (auth ExporterAuth, error error) {
err := envconfig.Process(exporterAuthID, &auth)
if err != nil {
return auth, err
}
if user != "" && password != "" {
auth.User = user
auth.Password = password
}
if header != "" {
auth.Header = header
}
return auth, nil
}
func main() {
exporterURL := flag.String("exporter-url", "", "Prometheus exporter URL to pull metrics from.")
exporterUser := flag.String("exporter-user", "", "Prometheus exporter basic auth user.")
exporterPassword := flag.String("exporter-password", "", "Prometheus exporter basic auth password.")
exporterAuthorizationHeader := flag.String("exporter-authorization", "", "Prometheus exporter Authorization header.")
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.")
insecureSkipVerify := flag.Bool("insecure-skip-verify", false, "Skip TLS peer verification.")
flag.Parse()
var samples model.Vector
var err error
if *exporterURL != "" {
auth, err := setExporterAuth(*exporterUser, *exporterPassword, *exporterAuthorizationHeader)
if err != nil {
log.Fatal(err)
os.Exit(2)
}
samples, err = QueryExporter(*exporterURL, auth, *insecureSkipVerify)
if err != nil {
log.Fatal(err)
os.Exit(2)
}
} else {
samples, err = QueryPrometheus(*promURL, *queryString)
if err != nil {
log.Fatal(err)
os.Exit(2)
}
}
err = OutputMetrics(samples, *outputFormat, *metricPrefix)
if err != nil {
_ = fmt.Errorf("error %v", err)
os.Exit(2)
}
}