-
Notifications
You must be signed in to change notification settings - Fork 13
/
reader.go
258 lines (214 loc) · 6.7 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
256
257
258
// Copyright 2021 The TiPrometheus Authors
// 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 adapter
import (
"bytes"
"encoding/gob"
"log"
"math"
"strconv"
"github.com/bragfoo/TiPrometheus/pkg/conf"
"github.com/bragfoo/TiPrometheus/pkg/lib"
"github.com/bragfoo/TiPrometheus/pkg/tikv"
"github.com/prometheus/prometheus/prompb"
"go.uber.org/zap/buffer"
)
var (
pool = buffer.NewPool()
)
func RemoteReader(querys prompb.ReadRequest) *prompb.ReadResponse {
//query
query := querys.Queries[0]
startTime := query.StartTimestampMs
endTime := query.EndTimestampMs
matchers := query.Matchers
log.Println("Query:", startTime, endTime, matchers)
//compute time endpoint
timeEndpoinFromGet := getTimeEndpoint(startTime, endTime)
//get data by matchers
docTimeseries := getSameMatcher(matchers, timeEndpoinFromGet)
//response
var queryResult prompb.QueryResult
queryResult.Timeseries = docTimeseries
var queryResults []*prompb.QueryResult
queryResults = append(queryResults, &queryResult)
var resp prompb.ReadResponse
resp.Results = queryResults
return &resp
}
func getTimeEndpoint(startTime, endTime int64) []int64 {
interval := float64(conf.RunTimeInfo.TimeInterval * 1000 * 60)
startTimeCompute := (math.Floor(float64(startTime) / interval)) * interval
endTimeCompute := (math.Floor(float64(endTime) / interval)) * interval
//log.Println("Time compute:", int64(startTimeCompute), int64(endTimeCompute))
//get timeEndpointList
timeEndpointList := getTimeEndpointList(int64(startTimeCompute), int64(endTimeCompute), int64(interval))
return timeEndpointList
}
func getTimeEndpointList(startTimeCompute, endTimeCompute, interval int64) []int64 {
var timeEndpointList []int64
//in one time interval
if startTimeCompute == endTimeCompute {
endTimeCompute = startTimeCompute + interval
}
//in time intervals
timeEndpointList = append(timeEndpointList, int64(startTimeCompute))
timeEndpoint := startTimeCompute
for {
// TODO: use-interval-instead-of-hardcoded-value -- Incoming Change
timeEndpoint = timeEndpoint + interval
timeEndpointList = append(timeEndpointList, int64(timeEndpoint))
if timeEndpoint == endTimeCompute {
break
}
}
//log.Println("Time endpoint list:", timeEndpointList)
return timeEndpointList
}
func getSameMatcher(matchers []*prompb.LabelMatcher, timeEndpointList []int64) []*prompb.TimeSeries {
buf := pool.Get()
defer buf.Free()
//get count map
countMap := getCountMap(matchers)
var docTimeseries []*prompb.TimeSeries
//get intersection
for md, count := range countMap {
if count == len(matchers) {
//log.Println("Find intersection key md:", md)
//get labels info
buf.AppendString("doc:")
buf.AppendString(md)
labelInfoKey := buf.Bytes()
labelInfoKV, _ := tikv.Get([]byte(labelInfoKey))
buf.Reset()
//get labels
labels, _ := makeLabels([]byte(labelInfoKV.Value))
//get timeseries list
timeListString := getTimeList(md, timeEndpointList)
timeList := lib.ReadStringByStepwidth(13, timeListString)
//get values
values := getValues(timeList, md)
// one timeseries
oneDocTimeseries := prompb.TimeSeries{
Labels: labels,
Samples: values,
}
docTimeseries = append(docTimeseries, &oneDocTimeseries)
}
}
log.Println("Response:", docTimeseries)
return docTimeseries
}
func getCountMap(matchers []*prompb.LabelMatcher) map[string]int {
buf := pool.Get()
defer buf.Free()
countMap := make(map[string]int)
for _, queryLabel := range matchers {
//newLabel
buf.AppendString("index:label:")
buf.AppendString(queryLabel.Name)
buf.AppendString("#")
buf.AppendString(queryLabel.Value)
newLabel := buf.String()
buf.Reset()
//get label index list
//key type index:label:newLabel
newLabelValue, _ := tikv.Get([]byte(newLabel))
mdList := lib.ReadStringByStepwidth(32, newLabelValue.Value)
//mark count
for _, oneMD := range mdList {
oldCount := countMap[oneMD]
newCount := oldCount + 1
countMap[oneMD] = newCount
}
}
//log.Println("Count Map:", countMap)
return countMap
}
func makeLabels(labelInfoByte []byte) ([]*prompb.Label, error) {
var labels []*prompb.Label
var buf bytes.Buffer
// wtire to buffer
buf.Write(labelInfoByte)
dec := gob.NewDecoder(&buf)
// read from buffer
err := dec.Decode(&labels)
if err != nil {
return nil, err
}
//log.Println("Labels:", labels)
return labels, nil
}
func getTimeList(md string, timeEndpointList []int64) string {
buf := pool.Get()
defer buf.Free()
var timeList string
//key type index:timeseries:5d4decf2a1d0dd0151cd893cfc752af4:1543639500000
for _, oneTimeEndpoint := range timeEndpointList {
buf.AppendString("index:timeseries:")
buf.AppendString(md)
buf.AppendString(":")
buf.AppendString(strconv.FormatInt(oneTimeEndpoint, 10))
timeIndexBytes := buf.Bytes()
buf.Reset()
newLabelValue, _ := tikv.Get(timeIndexBytes)
//log.Println("One time endpoint list:", newLabelValue.Value)
if newLabelValue.Value != "" {
//split with ,
//timeList = append(timeList, strings.Split(newLabelValue.Value, ",")...)
timeList = timeList + newLabelValue.Value
}
}
//log.Println("Time list:", timeList)
return timeList
}
func getValues(timeList []string, md string) []prompb.Sample {
var values []prompb.Sample
bvChan := make(chan prompb.Sample, 1000)
for _, oneTimePoint := range timeList {
//get time point and value
go getTimePointValue(oneTimePoint, md, bvChan)
}
// init count
var bvNum int
// read from channel
for {
baseValue := <-bvChan
bvNum = bvNum + 1
values = append(values, baseValue)
if bvNum == len(timeList) {
close(bvChan)
break
}
}
return values
}
func getTimePointValue(oneTimePoint, md string, bvChan chan prompb.Sample) {
buf := pool.Get()
//key type timeseries:doc:5d4decf2a1d0dd0151cd893cfc752af4:1543639730686
buf.AppendString("timeseries:doc:")
buf.AppendString(md)
buf.AppendString(":")
buf.AppendString(oneTimePoint)
key := buf.Bytes()
oneTimePointValue, _ := tikv.Get([]byte(key))
buf.Free()
//log.Println("One doc:", oneTimeseriesValue)
oneTimePointValueFloat, _ := strconv.ParseFloat(oneTimePointValue.Value, 64)
oneTimePointInt, _ := strconv.ParseInt(oneTimePoint, 10, 64)
baseValue := prompb.Sample{
Value: oneTimePointValueFloat,
Timestamp: oneTimePointInt,
}
bvChan <- baseValue
}