-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
255 lines (219 loc) · 7.48 KB
/
reader.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
package main
import (
_"bytes"
"database/sql"
"errors"
"fmt"
"strings"
"encoding/json"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/storage/remote"
)
type p2cReader struct {
conf *config
db *sql.DB
}
// getTimePeriod return select and where SQL chunks relating to the time period -or- error
func (r *p2cReader) getTimePeriod(query *remote.Query) (string, string, error) {
var tselSQL = "SELECT COUNT() AS CNT, (intDiv(toUInt32(ts), %d) * %d) * 1000 as t"
var twhereSQL = "WHERE date >= toDate(%d) AND ts >= toDateTime(%d) AND ts <= toDateTime(%d)"
var err error
tstart := query.StartTimestampMs / 1000
tend := query.EndTimestampMs / 1000
// valid time period
if tend < tstart {
err = errors.New("Start time is after end time")
return "", "", err
}
// need time period in seconds
tperiod := tend - tstart
// need to split time period into <nsamples> - also, don't divide by zero
if r.conf.CHMaxSamples < 1 {
err = fmt.Errorf(fmt.Sprintf("Invalid CHMaxSamples: %d", r.conf.CHMaxSamples))
return "", "", err
}
taggr := tperiod / int64(r.conf.CHMaxSamples)
if taggr < int64(r.conf.CHMinPeriod) {
taggr = int64(r.conf.CHMinPeriod)
}
selectSQL := fmt.Sprintf(tselSQL, taggr, taggr)
whereSQL := fmt.Sprintf(twhereSQL, tstart, tstart, tend)
return selectSQL, whereSQL, nil
}
func (r *p2cReader) getSQL(query *remote.Query) (string, error) {
// time related select sql, where sql chunks
tselectSQL, twhereSQL, err := r.getTimePeriod(query)
if err != nil {
return "", err
}
// match sql chunk
var mwhereSQL []string
// build an sql statement chunk for each matcher in the query
// yeah, this is a bit ugly..
for _, m := range query.Matchers {
// __name__ is handled specially - match it directly
// as it is stored in the name column (it's also in tags as __name__)
// note to self: add name to index.. otherwise this will be slow..
if m.Name == model.MetricNameLabel {
var whereAdd string
switch m.Type {
case remote.MatchType_EQUAL:
whereAdd = fmt.Sprintf(` name='%s' `, strings.Replace(m.Value, `'`, `\'`, -1))
case remote.MatchType_NOT_EQUAL:
whereAdd = fmt.Sprintf(` name!='%s' `, strings.Replace(m.Value, `'`, `\'`, -1))
case remote.MatchType_REGEX_MATCH:
whereAdd = fmt.Sprintf(` match(name, %s) = 1 `, strings.Replace(m.Value, `/`, `\/`, -1))
case remote.MatchType_REGEX_NO_MATCH:
whereAdd = fmt.Sprintf(` match(name, %s) = 0 `, strings.Replace(m.Value, `/`, `\/`, -1))
}
mwhereSQL = append(mwhereSQL, whereAdd)
continue
}
switch m.Type {
case remote.MatchType_EQUAL:
asql := "JSONExtractString(tags,'%s') = '%s'"
wstr := fmt.Sprintf(asql, m.Name,m.Value)
mwhereSQL = append(mwhereSQL, wstr)
case remote.MatchType_NOT_EQUAL:
asql := "JSONExtractString(tags,'%s') != '%s'"
wstr := fmt.Sprintf(asql, m.Name,m.Value)
mwhereSQL = append(mwhereSQL, wstr)
case remote.MatchType_REGEX_MATCH:
asql := "match(JSONExtractString(tags,'%s'),'%s') = 1"
var val string
if strings.HasPrefix(m.Value, "^") {
val = strings.Replace(m.Value, "^", "", 1)
val = strings.Replace(val, `/`, `\/`, -1)
} else {
val = strings.Replace(m.Value, `/`, `\/`, -1)
}
wstr := fmt.Sprintf(asql, m.Name,val)
mwhereSQL = append(mwhereSQL, wstr)
case remote.MatchType_REGEX_NO_MATCH:
asql := "match(JSONExtractString(tags,'%s'),'%s') = 0"
var val string
if strings.HasPrefix(m.Value, "^") {
val = strings.Replace(m.Value, "^", "", 1)
val = strings.Replace(val, `/`, `\/`, -1)
} else {
val = strings.Replace(m.Value, `/`, `\/`, -1)
}
wstr := fmt.Sprintf(asql, m.Name,val)
mwhereSQL = append(mwhereSQL, wstr)
}
}
// put select and where together with group by etc
tempSQL := "%s, name, tags, quantile(%f)(val) as value FROM %s.%s %s AND %s GROUP BY t, name, tags ORDER BY t"
sql := fmt.Sprintf(tempSQL, tselectSQL, r.conf.CHQuantile, r.conf.ChDB, r.conf.ChTable, twhereSQL,
strings.Join(mwhereSQL, " AND "))
return sql, nil
}
func NewP2CReader(conf *config) (*p2cReader, error) {
var err error
r := new(p2cReader)
r.conf = conf
r.db, err = sql.Open("clickhouse", r.conf.ChDSN)
if err != nil {
fmt.Printf("Error connecting to clickhouse: %s\n", err.Error())
return r, err
}
return r, nil
}
func (r *p2cReader) Read(req *remote.ReadRequest) (*remote.ReadResponse, error) {
var err error
var sqlStr string
var rows *sql.Rows
resp := remote.ReadResponse{
Results: []*remote.QueryResult{
{Timeseries: make([]*remote.TimeSeries, 0, 0)},
},
}
// need to map tags to timeseries to record samples
var tsres = make(map[string]*remote.TimeSeries)
// for debugging/figuring out query format/etc
rcount := 0
for _, q := range req.Queries {
// remove me..
fmt.Printf("\nquery: start: %d, end: %d\n\n", q.StartTimestampMs, q.EndTimestampMs)
// get the select sql
sqlStr, err = r.getSQL(q)
fmt.Printf("query: running sql: %s\n\n", sqlStr)
if err != nil {
fmt.Printf("Error: reader: getSQL: %s\n", err.Error())
return &resp, err
}
// get the select sql
if err != nil {
fmt.Printf("Error: reader: getSQL: %s\n", err.Error())
return &resp, err
}
// todo: metrics on number of errors, rows, selects, timings, etc
rows, err = r.db.Query(sqlStr)
if err != nil {
fmt.Printf("Error: query failed: %s", sqlStr)
fmt.Printf("Error: query error: %s\n", err)
return &resp, err
}
// build map of timeseries from sql result
for rows.Next() {
rcount++
var (
cnt int
t int64
name string
tags string
value float64
)
if err = rows.Scan(&cnt, &t, &name, &tags, &value); err != nil {
fmt.Printf("Error: scan: %s\n", err.Error())
}
// remove this..
//fmt.Printf(fmt.Sprintf("%d,%d,%s,%s,%f\n", cnt, t, name, strings.Join(tags, ":"), value))
// borrowed from influx remote storage adapter - array sep
//key := strings.Join(tags, "\xff")
ts, ok := tsres[tags]
if !ok {
ts = &remote.TimeSeries{
Labels: makeLabels(tags),
}
tsres[tags] = ts
}
ts.Samples = append(ts.Samples, &remote.Sample{
Value: float64(value),
TimestampMs: t,
})
}
}
// now add results to response
for _, ts := range tsres {
resp.Results[0].Timeseries = append(resp.Results[0].Timeseries, ts)
}
fmt.Printf("query: returning %d rows for %d queries\n", rcount, len(req.Queries))
return &resp, nil
}
func makeLabels(tags string) []*remote.LabelPair {
datab := []byte(tags)
m := make(map[string]string)
err:=json.Unmarshal(datab,&m)
if err != nil {
fmt.Println("Error parse string to json")
}
lpairs := make([]*remote.LabelPair, 0, len(m))
// (currently) writer includes __name__ in tags so no need to add it here
// may change this to save space later..
for key := range m {
//vals := strings.SplitN(tag, "=", 2)
//if len(vals) != 2 {
// fmt.Printf("Error unpacking tag key/val: %s\n", tag)
// continue
//}
//if vals[1] == "" {
// continue
//}
lpairs = append(lpairs, &remote.LabelPair{
Name: key,
Value: m[key],
})
}
return lpairs
}