forked from ClickHouse/clickhouse_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clickhouse_exporter.go
381 lines (322 loc) · 10.1 KB
/
clickhouse_exporter.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package main
import (
"crypto/tls"
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"unicode"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/log"
"os"
)
const (
namespace = "clickhouse" // For Prometheus metrics.
)
var (
listeningAddress = flag.String("telemetry.address", ":9116", "Address on which to expose metrics.")
metricsEndpoint = flag.String("telemetry.endpoint", "/metrics", "Path under which to expose metrics.")
clickhouseScrapeURI = flag.String("scrape_uri", "http://localhost:8123/", "URI to clickhouse http endpoint")
insecure = flag.Bool("insecure", true, "Ignore server certificate if using https")
credentialsPresent, user, password = getCredentials()
)
// Exporter collects clickhouse stats from the given URI and exports them using
// the prometheus metrics package.
type Exporter struct {
metricsURI string
asyncMetricsURI string
eventsURI string
partsURI string
mutex sync.RWMutex
client *http.Client
scrapeFailures prometheus.Counter
gauges []*prometheus.GaugeVec
counters []*prometheus.CounterVec
}
// NewExporter returns an initialized Exporter.
func NewExporter(uri url.URL) *Exporter {
q := uri.Query()
metricsURI := uri
q.Set("query", "select * from system.metrics")
metricsURI.RawQuery = q.Encode()
asyncMetricsURI := uri
q.Set("query", "select * from system.asynchronous_metrics")
asyncMetricsURI.RawQuery = q.Encode()
eventsURI := uri
q.Set("query", "select * from system.events")
eventsURI.RawQuery = q.Encode()
partsURI := uri
q.Set("query", "select database, table, sum(bytes) as bytes, count() as parts, sum(rows) as rows from system.parts where active = 1 group by database, table")
partsURI.RawQuery = q.Encode()
return &Exporter{
metricsURI: metricsURI.String(),
asyncMetricsURI: asyncMetricsURI.String(),
eventsURI: eventsURI.String(),
partsURI: partsURI.String(),
scrapeFailures: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_scrape_failures_total",
Help: "Number of errors while scraping clickhouse.",
}),
gauges: make([]*prometheus.GaugeVec, 0, 20),
counters: make([]*prometheus.CounterVec, 0, 20),
client: &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: *insecure},
},
},
}
}
// Describe describes all the metrics ever exported by the clickhouse exporter. It
// implements prometheus.Collector.
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
// We cannot know in advance what metrics the exporter will generate
// from clickhouse. So we use the poor man's describe method: Run a collect
// and send the descriptors of all the collected metrics.
metricCh := make(chan prometheus.Metric)
doneCh := make(chan struct{})
go func() {
for m := range metricCh {
ch <- m.Desc()
}
close(doneCh)
}()
e.Collect(metricCh)
close(metricCh)
<-doneCh
}
func (e *Exporter) collect(ch chan<- prometheus.Metric) error {
metrics, err := e.parseKeyValueResponse(e.metricsURI)
if err != nil {
return fmt.Errorf("Error scraping clickhouse url %v: %v", e.metricsURI, err)
}
for _, m := range metrics {
newMetric := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: metricName(m.key),
Help: "Number of " + m.key + " currently processed",
}, []string{}).WithLabelValues()
newMetric.Set(float64(m.value))
newMetric.Collect(ch)
}
asyncMetrics, err := e.parseKeyValueResponse(e.asyncMetricsURI)
if err != nil {
return fmt.Errorf("Error scraping clickhouse url %v: %v", e.asyncMetricsURI, err)
}
for _, am := range asyncMetrics {
newMetric := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: metricName(am.key),
Help: "Number of " + am.key + " async processed",
}, []string{}).WithLabelValues()
newMetric.Set(float64(am.value))
newMetric.Collect(ch)
}
events, err := e.parseKeyValueResponse(e.eventsURI)
if err != nil {
return fmt.Errorf("Error scraping clickhouse url %v: %v", e.eventsURI, err)
}
for _, ev := range events {
newMetric, _ := prometheus.NewConstMetric(
prometheus.NewDesc(
namespace+"_"+metricName(ev.key)+"_total",
"Number of "+ev.key+" total processed", []string{}, nil),
prometheus.CounterValue, float64(ev.value))
ch <- newMetric
}
parts, err := e.parsePartsResponse(e.partsURI)
if err != nil {
return fmt.Errorf("Error scraping clickhouse url %v: %v", e.partsURI, err)
}
for _, part := range parts {
newBytesMetric := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: "table_parts_bytes",
Help: "Table size in bytes",
}, []string{"database", "table"}).WithLabelValues(part.database, part.table)
newBytesMetric.Set(float64(part.bytes))
newBytesMetric.Collect(ch)
newCountMetric := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: "table_parts_count",
Help: "Number of parts of the table",
}, []string{"database", "table"}).WithLabelValues(part.database, part.table)
newCountMetric.Set(float64(part.parts))
newCountMetric.Collect(ch)
newRowsMetric := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: "table_parts_rows",
Help: "Number of rows in the table",
}, []string{"database", "table"}).WithLabelValues(part.database, part.table)
newRowsMetric.Set(float64(part.rows))
newRowsMetric.Collect(ch)
}
return nil
}
func getCredentials() (bool, string, string) {
user, userPresent := os.LookupEnv("CLICKHOUSE_USER")
password, passwordPresent := os.LookupEnv("CLICKHOUSE_PASSWORD")
return userPresent && passwordPresent, user, password
}
func (e *Exporter) handleResponse(uri string) ([]byte, error) {
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return nil, err
}
if credentialsPresent {
req.Header.Set("X-ClickHouse-User", user)
req.Header.Set("X-ClickHouse-Key", password)
}
resp, err := e.client.Do(req)
if err != nil {
return nil, fmt.Errorf("Error scraping clickhouse: %v", err)
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
if err != nil {
data = []byte(err.Error())
}
return nil, fmt.Errorf("Status %s (%d): %s", resp.Status, resp.StatusCode, data)
}
return data, nil
}
type lineResult struct {
key string
value int
}
func (e *Exporter) parseKeyValueResponse(uri string) ([]lineResult, error) {
data, err := e.handleResponse(uri)
if err != nil {
return nil, err
}
// Parsing results
lines := strings.Split(string(data), "\n")
var results []lineResult = make([]lineResult, 0)
for i, line := range lines {
parts := strings.Fields(line)
if len(parts) == 0 {
continue
}
if len(parts) != 2 {
return nil, fmt.Errorf("parseKeyValueResponse: unexpected %d line: %s", i, line)
}
k := strings.TrimSpace(parts[0])
v, err := strconv.Atoi(strings.TrimSpace(parts[1]))
if err != nil {
return nil, err
}
results = append(results, lineResult{k, v})
}
return results, nil
}
type partsResult struct {
database string
table string
bytes int
parts int
rows int
}
func (e *Exporter) parsePartsResponse(uri string) ([]partsResult, error) {
data, err := e.handleResponse(uri)
if err != nil {
return nil, err
}
// Parsing results
lines := strings.Split(string(data), "\n")
var results []partsResult = make([]partsResult, 0)
for i, line := range lines {
parts := strings.Fields(line)
if len(parts) == 0 {
continue
}
if len(parts) != 5 {
return nil, fmt.Errorf("parsePartsResponse: unexpected %d line: %s", i, line)
}
database := strings.TrimSpace(parts[0])
table := strings.TrimSpace(parts[1])
bytes, err := strconv.Atoi(strings.TrimSpace(parts[2]))
if err != nil {
return nil, err
}
count, err := strconv.Atoi(strings.TrimSpace(parts[3]))
if err != nil {
return nil, err
}
rows, err := strconv.Atoi(strings.TrimSpace(parts[4]))
if err != nil {
return nil, err
}
results = append(results, partsResult{database, table, bytes, count, rows})
}
return results, nil
}
// Collect fetches the stats from configured clickhouse location and delivers them
// as Prometheus metrics. It implements prometheus.Collector.
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
e.mutex.Lock() // To protect metrics from concurrent collects.
defer e.mutex.Unlock()
if err := e.collect(ch); err != nil {
log.Printf("Error scraping clickhouse: %s", err)
e.scrapeFailures.Inc()
e.scrapeFailures.Collect(ch)
}
// Reset metrics.
for _, vec := range e.gauges {
vec.Reset()
}
for _, vec := range e.counters {
vec.Reset()
}
for _, vec := range e.gauges {
vec.Collect(ch)
}
for _, vec := range e.counters {
vec.Collect(ch)
}
return
}
func metricName(in string) string {
out := toSnake(in)
return strings.Replace(out, ".", "_", -1)
}
// toSnake convert the given string to snake case following the Golang format:
// acronyms are converted to lower-case and preceded by an underscore.
func toSnake(in string) string {
runes := []rune(in)
length := len(runes)
var out []rune
for i := 0; i < length; i++ {
if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
out = append(out, '_')
}
out = append(out, unicode.ToLower(runes[i]))
}
return string(out)
}
//var _ Exporter = (*prometheus.Collector)(nil)
func main() {
flag.Parse()
uri, err := url.Parse(*clickhouseScrapeURI)
if err != nil {
log.Fatal(err)
}
exporter := NewExporter(*uri)
prometheus.MustRegister(exporter)
log.Printf("Starting Server: %s", *listeningAddress)
http.Handle(*metricsEndpoint, prometheus.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Clickhouse Exporter</title></head>
<body>
<h1>Clickhouse Exporter</h1>
<p><a href="` + *metricsEndpoint + `">Metrics</a></p>
</body>
</html>`))
})
log.Fatal(http.ListenAndServe(*listeningAddress, nil))
}