-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
382 lines (342 loc) · 11.7 KB
/
client.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
382
/*
Copyright 2020 Kohl's Department Stores, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bigquerydb
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"os"
"sort"
"strings"
"time"
"cloud.google.com/go/bigquery"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/prompb"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
// BigqueryClient allows sending batches of Prometheus samples to Bigquery.
type BigqueryClient struct {
logger log.Logger
client bigquery.Client
datasetID string
tableID string
timeout time.Duration
ignoredSamples prometheus.Counter
recordsFetched prometheus.Counter
batchWriteDuration prometheus.Histogram
sqlQueryCount prometheus.Counter
sqlQueryDuration prometheus.Histogram
}
// NewClient creates a new Client.
func NewClient(logger log.Logger, googleAPIjsonkeypath, googleProjectID, googleAPIdatasetID, googleAPItableID string, remoteTimeout time.Duration) *BigqueryClient {
ctx := context.Background()
bigQueryClientOptions := []option.ClientOption{}
if googleAPIjsonkeypath != "" {
jsonFile, err := os.Open(googleAPIjsonkeypath)
if err != nil {
level.Error(logger).Log("err", err) //nolint:errcheck
os.Exit(1)
}
byteValue, _ := ioutil.ReadAll(jsonFile)
var result map[string]interface{}
err = json.Unmarshal([]byte(byteValue), &result)
if err != nil {
level.Error(logger).Log("err", err) //nolint:errcheck
os.Exit(1)
}
jsonFile.Close()
googleProjectID = fmt.Sprintf("%v", result["project_id"])
bigQueryClientOptions = append(bigQueryClientOptions, option.WithCredentialsFile(googleAPIjsonkeypath))
}
c, err := bigquery.NewClient(ctx, googleProjectID, bigQueryClientOptions...)
if err != nil {
level.Error(logger).Log("err", err) //nolint:errcheck
os.Exit(1)
}
if logger == nil {
logger = log.NewNopLogger()
}
return &BigqueryClient{
logger: logger,
client: *c,
datasetID: googleAPIdatasetID,
tableID: googleAPItableID,
timeout: remoteTimeout,
ignoredSamples: prometheus.NewCounter(
prometheus.CounterOpts{
Name: "storage_bigquery_ignored_samples_total",
Help: "The total number of samples not sent to BigQuery due to unsupported float values (Inf, -Inf, NaN).",
},
),
recordsFetched: prometheus.NewCounter(
prometheus.CounterOpts{
Name: "storage_bigquery_records_fetched",
Help: "Total number of records fetched",
},
),
batchWriteDuration: prometheus.NewHistogram(
prometheus.HistogramOpts{
Name: "storage_bigquery_batch_write_duration_seconds",
Help: "The duration it takes to write a batch of samples to BigQuery.",
Buckets: prometheus.DefBuckets,
},
),
sqlQueryCount: prometheus.NewCounter(
prometheus.CounterOpts{
Name: "storage_bigquery_sql_query_count_total",
Help: "Total number of sql_queries executed.",
},
),
sqlQueryDuration: prometheus.NewHistogram(
prometheus.HistogramOpts{
Name: "storage_bigquery_sql_query_duration_seconds",
Help: "Duration of the sql reads from BigQuery.",
},
),
}
}
// Item represents a row item.
type Item struct {
value float64 `bigquery:"value"`
metricname string `bigquery:"metricname"`
timestamp int64 `bigquery:"timestamp"`
tags string `bigquery:"tags"`
}
// Save implements the ValueSaver interface.
func (i *Item) Save() (map[string]bigquery.Value, string, error) {
return map[string]bigquery.Value{
"value": i.value,
"metricname": i.metricname,
"timestamp": i.timestamp,
"tags": i.tags,
}, "", nil
}
// tagsFromMetric extracts tags from a Prometheus MetricNameLabel.
func tagsFromMetric(m model.Metric) string {
tags := make(map[string]interface{}, len(m)-1)
for l, v := range m {
if l != model.MetricNameLabel {
tags[string(l)] = string(v)
}
}
tagsmarshaled, _ := json.Marshal(tags)
return string(tagsmarshaled)
}
// Write sends a batch of samples to BigQuery via the client.
func (c *BigqueryClient) Write(timeseries []*prompb.TimeSeries) error {
inserter := c.client.Dataset(c.datasetID).Table(c.tableID).Inserter()
inserter.SkipInvalidRows = true
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
for i := range timeseries {
ts := timeseries[i]
samples := ts.Samples
batch := make([]*Item, 0, len(samples))
c.recordsFetched.Add(float64(len(samples)))
metric := make(model.Metric, len(ts.Labels))
for _, l := range ts.Labels {
metric[model.LabelName(l.Name)] = model.LabelValue(l.Value)
}
for _, s := range samples {
v := float64(s.Value)
if math.IsNaN(v) || math.IsInf(v, 0) {
//level.Debug(c.logger).Log("msg", "cannot send to BigQuery, skipping sample", "value", v, "sample", s)
c.ignoredSamples.Inc()
continue
}
batch = append(batch, &Item{
value: v,
metricname: string(metric[model.MetricNameLabel]),
timestamp: model.Time(s.Timestamp).Unix(),
tags: tagsFromMetric(metric),
})
}
begin := time.Now()
if err := inserter.Put(ctx, batch); err != nil {
if multiError, ok := err.(bigquery.PutMultiError); ok {
for _, err1 := range multiError {
for _, err2 := range err1.Errors {
fmt.Println(err2)
}
}
}
defer cancel()
return err
}
duration := time.Since(begin).Seconds()
c.batchWriteDuration.Observe(duration)
}
defer cancel()
return nil
}
// Name identifies the client as a BigQuery client.
func (c BigqueryClient) Name() string {
return "bigquerydb"
}
// Describe implements prometheus.Collector.
func (c *BigqueryClient) Describe(ch chan<- *prometheus.Desc) {
ch <- c.ignoredSamples.Desc()
ch <- c.recordsFetched.Desc()
ch <- c.sqlQueryCount.Desc()
ch <- c.sqlQueryDuration.Desc()
ch <- c.batchWriteDuration.Desc()
}
// Collect implements prometheus.Collector.
func (c *BigqueryClient) Collect(ch chan<- prometheus.Metric) {
ch <- c.ignoredSamples
ch <- c.recordsFetched
ch <- c.sqlQueryCount
ch <- c.sqlQueryDuration
ch <- c.batchWriteDuration
}
// Read queries the database and returns the results to Prometheus
func (c *BigqueryClient) Read(req *prompb.ReadRequest) (*prompb.ReadResponse, error) {
tsMap := map[model.Fingerprint]*prompb.TimeSeries{}
for _, q := range req.Queries {
command, err := c.buildCommand(q)
if err != nil {
return nil, err
}
query := c.client.Query(command)
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
c.sqlQueryCount.Inc()
begin := time.Now()
iter, err := query.Read(ctx)
defer cancel()
if err != nil {
return nil, err
}
if err = mergeResult(tsMap, iter); err != nil {
return nil, err
}
duration := time.Since(begin).Seconds()
c.sqlQueryDuration.Observe(duration)
level.Debug(c.logger).Log("msg", "BigQuery SQL query", "rows", iter.TotalRows, "duration", duration) //nolint:errcheck
}
resp := prompb.ReadResponse{
Results: []*prompb.QueryResult{
{Timeseries: make([]*prompb.TimeSeries, 0, len(tsMap))},
},
}
for _, ts := range tsMap {
resp.Results[0].Timeseries = append(resp.Results[0].Timeseries, ts)
}
return &resp, nil
}
// BuildCommand generates the proper SQL for the query
func (c *BigqueryClient) buildCommand(q *prompb.Query) (string, error) {
matchers := make([]string, 0, len(q.Matchers))
for _, m := range q.Matchers {
// Metric Names
if m.Name == model.MetricNameLabel {
switch m.Type {
case prompb.LabelMatcher_EQ:
matchers = append(matchers, fmt.Sprintf("metricname = '%s'", escapeSingleQuotes(m.Value)))
case prompb.LabelMatcher_NEQ:
matchers = append(matchers, fmt.Sprintf("metricname != '%s'", escapeSingleQuotes(m.Value)))
case prompb.LabelMatcher_RE:
matchers = append(matchers, fmt.Sprintf("REGEXP_CONTAINS(metricname, r'%s')", escapeSlashes(m.Value)))
case prompb.LabelMatcher_NRE:
matchers = append(matchers, fmt.Sprintf("not REGEXP_CONTAINS(metricname, r'%s')", escapeSlashes(m.Value)))
default:
return "", errors.Errorf("unknown match type %v", m.Type)
}
continue
}
// Labels
switch m.Type {
case prompb.LabelMatcher_EQ:
matchers = append(matchers, fmt.Sprintf(`IFNULL(JSON_EXTRACT(tags, '$.%s'), '""') = '"%s"'`, m.Name, m.Value))
case prompb.LabelMatcher_NEQ:
matchers = append(matchers, fmt.Sprintf(`IFNULL(JSON_EXTRACT(tags, '$.%s'), '""') = '"%s"'`, m.Name, m.Value))
case prompb.LabelMatcher_RE:
matchers = append(matchers, fmt.Sprintf(`REGEXP_CONTAINS(IFNULL(JSON_EXTRACT(tags, '$.%s'), '""'), r'"%s"')`, m.Name, m.Value))
case prompb.LabelMatcher_NRE:
matchers = append(matchers, fmt.Sprintf(`not REGEXP_CONTAINS(IFNULL(JSON_EXTRACT(tags, '$.%s'), '""'), r'"%s"')`, m.Name, m.Value))
default:
return "", errors.Errorf("unknown match type %v", m.Type)
}
}
matchers = append(matchers, fmt.Sprintf("timestamp >= TIMESTAMP_MILLIS(%v)", q.StartTimestampMs))
matchers = append(matchers, fmt.Sprintf("timestamp <= TIMESTAMP_MILLIS(%v)", q.EndTimestampMs))
query := fmt.Sprintf("SELECT metricname, tags, UNIX_MILLIS(timestamp) as timestamp, value FROM %s.%s WHERE %v ORDER BY timestamp", c.datasetID, c.tableID, strings.Join(matchers, " AND "))
level.Debug(c.logger).Log("msg", "BigQuery read", "sql query", query) //nolint:errcheck
return query, nil
}
// rowsToTimeseries iterates over the BigQuery data and creates time series for Prometheus
func mergeResult(tsMap map[model.Fingerprint]*prompb.TimeSeries, iter *bigquery.RowIterator) error {
if iter == nil {
return nil
}
for {
row := make(map[string]bigquery.Value)
err := iter.Next(&row)
if err == iterator.Done {
break
}
if err != nil {
return err
}
sample, metric, labels, err := rowToSample(row)
if err != nil {
return err
}
fp := metric.Fingerprint()
ts, ok := tsMap[fp]
if !ok {
ts = &prompb.TimeSeries{Labels: labels}
tsMap[fp] = ts
}
ts.Samples = append(ts.Samples, sample)
}
return nil
}
// rowToSample converts a BigQuery row to a sample and also processes the labels for later consumption
func rowToSample(row map[string]bigquery.Value) (prompb.Sample, model.Metric, []*prompb.Label, error) {
var v interface{}
labelsJSON := row["tags"].(string)
err := json.Unmarshal([]byte(labelsJSON), &v)
if err != nil {
return prompb.Sample{}, nil, nil, err
}
labels := v.(map[string]interface{})
labelPairs := make([]*prompb.Label, 0, len(labels))
metric := model.Metric{}
for name, value := range labels {
labelPairs = append(labelPairs, &prompb.Label{
Name: name,
Value: value.(string),
})
metric[model.LabelName(name)] = model.LabelValue(value.(string))
}
labelPairs = append(labelPairs, &prompb.Label{
Name: model.MetricNameLabel,
Value: row["metricname"].(string),
})
// Make sure we sort the labels, so the test cases won't blow up
sort.Slice(labelPairs, func(i, j int) bool { return labelPairs[i].Name < labelPairs[j].Name })
metric[model.LabelName(model.MetricNameLabel)] = model.LabelValue(row["metricname"].(string))
return prompb.Sample{Timestamp: row["timestamp"].(int64), Value: row["value"].(float64)}, metric, labelPairs, nil
}
func escapeSingleQuotes(str string) string {
return strings.Replace(str, `'`, `\'`, -1)
}
func escapeSlashes(str string) string {
return strings.Replace(str, `/`, `\/`, -1)
}