forked from ClickHouse/clickhouse_exporter
/
exporter.go
321 lines (272 loc) · 8.4 KB
/
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
package exporter
import (
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unicode"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/log"
)
const (
namespace = "clickhouse" // For Prometheus metrics.
)
// 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
client *http.Client
scrapeFailures prometheus.Counter
user string
password string
}
// NewExporter returns an initialized Exporter.
func NewExporter(uri url.URL, insecure bool, user, password string) *Exporter {
q := uri.Query()
metricsURI := uri
q.Set("query", "select metric, value from system.metrics")
metricsURI.RawQuery = q.Encode()
asyncMetricsURI := uri
q.Set("query", "select metric, value from system.asynchronous_metrics")
asyncMetricsURI.RawQuery = q.Encode()
eventsURI := uri
q.Set("query", "select event, value 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.",
}),
client: &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure},
},
Timeout: 30 * time.Second,
},
user: user,
password: password,
}
}
// 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 (e *Exporter) handleResponse(uri string) ([]byte, error) {
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return nil, err
}
if e.user != "" && e.password != "" {
req.Header.Set("X-ClickHouse-User", e.user)
req.Header.Set("X-ClickHouse-Key", e.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) {
if err := e.collect(ch); err != nil {
log.Printf("Error scraping clickhouse: %s", err)
e.scrapeFailures.Inc()
e.scrapeFailures.Collect(ch)
}
}
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)
}
// check interface
var _ prometheus.Collector = (*Exporter)(nil)