-
Notifications
You must be signed in to change notification settings - Fork 458
/
Copy pathhandler.go
304 lines (251 loc) · 8.35 KB
/
handler.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
// Copyright (c) 2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package validator
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"net/http"
"time"
"github.com/m3db/m3/src/query/api/v1/handler"
"github.com/m3db/m3/src/query/api/v1/handler/prometheus"
"github.com/m3db/m3/src/query/api/v1/handler/prometheus/native"
"github.com/m3db/m3/src/query/executor"
"github.com/m3db/m3/src/query/models"
"github.com/m3db/m3/src/query/storage/validator"
"github.com/m3db/m3/src/query/ts"
qjson "github.com/m3db/m3/src/query/util/json"
"github.com/m3db/m3/src/query/util/logging"
xhttp "github.com/m3db/m3/src/x/net/http"
"github.com/uber-go/tally"
"go.uber.org/zap"
)
const (
// PromDebugURL is the url for the Prom and m3query debugging tool
PromDebugURL = handler.RoutePrefixV1 + "/debug/validate_query"
// PromDebugHTTPMethod is the HTTP method used with this resource.
PromDebugHTTPMethod = http.MethodPost
mismatchCapacity = 10
)
// PromDebugHandler represents a handler for prometheus debug endpoint, which allows users
// to compare Prometheus results vs m3 query results.
type PromDebugHandler struct {
scope tally.Scope
readHandler *native.PromReadHandler
lookbackDuration time.Duration
}
// NewPromDebugHandler returns a new instance of handler.
func NewPromDebugHandler(
h *native.PromReadHandler,
scope tally.Scope,
lookbackDuration time.Duration,
) *PromDebugHandler {
return &PromDebugHandler{
scope: scope,
readHandler: h,
lookbackDuration: lookbackDuration,
}
}
type mismatchResp struct {
mismatches [][]mismatch
corrrect bool
err error
}
func (h *PromDebugHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), handler.HeaderKey, r.Header)
logger := logging.WithContext(ctx)
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
if err != nil {
logger.Error("unable to read data", zap.Error(err))
xhttp.Error(w, err, http.StatusBadRequest)
return
}
var promDebug prometheus.PromDebug
if err := json.Unmarshal(data, &promDebug); err != nil {
logger.Error("unable to unmarshal data", zap.Error(err))
xhttp.Error(w, err, http.StatusBadRequest)
return
}
s, err := validator.NewStorage(promDebug.Input, h.lookbackDuration)
if err != nil {
logger.Error("unable to create storage", zap.Error(err))
xhttp.Error(w, err, http.StatusBadRequest)
return
}
engine := executor.NewEngine(s, h.scope.SubScope("debug_engine"), h.lookbackDuration)
results, _, respErr := h.readHandler.ServeHTTPWithEngine(w, r, engine)
if respErr != nil {
logger.Error("unable to read data", zap.Error(respErr.Err))
xhttp.Error(w, respErr.Err, respErr.Code)
return
}
promResults, err := validator.PromResultToSeriesList(promDebug.Results, models.NewTagOptions())
if err != nil {
logger.Error("unable to convert prom results data", zap.Error(err))
xhttp.Error(w, err, http.StatusBadRequest)
return
}
mismatches, err := validate(tsListToMap(promResults), tsListToMap(results))
if err != nil && len(mismatches) == 0 {
logger.Error("error validating results", zap.Error(err))
xhttp.Error(w, err, http.StatusBadRequest)
return
}
var correct bool
if len(mismatches) == 0 {
correct = true
}
mismatchResp := mismatchResp{
corrrect: correct,
mismatches: mismatches,
err: err,
}
w.Header().Set("Content-Type", "application/json")
if err := renderDebugMismatchResultsJSON(w, mismatchResp); err != nil {
logger.Error("unable to write back mismatch data", zap.Error(err))
xhttp.Error(w, err, http.StatusInternalServerError)
return
}
}
func tsListToMap(tsList []*ts.Series) map[string]*ts.Series {
tsMap := make(map[string]*ts.Series, len(tsList))
for _, series := range tsList {
series.Tags = series.Tags.Normalize()
id := series.Tags.ID()
tsMap[string(id)] = series
}
return tsMap
}
type mismatch struct {
seriesName string
promVal, m3Val float64
promTime, m3Time time.Time
err error
}
// validate compares prom results to m3 results less NaNs
func validate(prom, m3 map[string]*ts.Series) ([][]mismatch, error) {
if len(prom) != len(m3) {
return nil, errors.New("number of Prom series not equal to number of M3 series")
}
mismatches := make([][]mismatch, 0, mismatchCapacity)
for id, promSeries := range prom {
m3Series, exists := m3[id]
if !exists {
return nil, fmt.Errorf("series with id %s does not exist in M3 results", id)
}
promdps := promSeries.Values().Datapoints()
m3dps := m3Series.Values().Datapoints()
mismatchList := make([]mismatch, 0, mismatchCapacity)
m3idx := 0
m3dp := m3dps[m3idx]
for _, promdp := range promdps {
if math.IsNaN(promdp.Value) && !math.IsNaN(m3dp.Value) {
mismatchList = append(mismatchList, newMismatch(id, promdp.Value, m3dp.Value, promdp.Timestamp, m3dp.Timestamp, nil))
continue
}
// skip over any NaN datapoints in the m3 results
for ; m3idx < len(m3dps) && math.IsNaN(m3dps[m3idx].Value); m3idx++ {
}
if m3idx > len(m3dps)-1 {
err := errors.New("series has extra prom datapoints")
mismatchList = append(mismatchList, newMismatch(id, promdp.Value, math.NaN(), promdp.Timestamp, time.Time{}, err))
continue
}
m3dp = m3dps[m3idx]
if (promdp.Value != m3dp.Value && !math.IsNaN(promdp.Value)) || !promdp.Timestamp.Equal(m3dp.Timestamp) {
mismatchList = append(mismatchList, newMismatch(id, promdp.Value, m3dp.Value, promdp.Timestamp, m3dp.Timestamp, nil))
}
m3idx++
}
// check remaining m3dps to make sure there are no more non-NaN Values
for _, dp := range m3dps[m3idx:] {
if !math.IsNaN(dp.Value) {
err := errors.New("series has extra m3 datapoints")
mismatchList = append(mismatchList, newMismatch(id, math.NaN(), dp.Value, time.Time{}, dp.Timestamp, err))
}
}
if len(mismatchList) > 0 {
mismatches = append(mismatches, mismatchList)
}
}
return mismatches, nil
}
func newMismatch(name string, promVal, m3Val float64, promTime, m3Time time.Time, err error) mismatch {
return mismatch{
seriesName: name,
promVal: promVal,
promTime: promTime,
m3Val: m3Val,
m3Time: m3Time,
err: err,
}
}
func renderDebugMismatchResultsJSON(
w io.Writer,
mismatchResp mismatchResp,
) error {
jw := qjson.NewWriter(w)
jw.BeginObject()
jw.BeginObjectField("correct")
jw.WriteBool(mismatchResp.corrrect)
if mismatchResp.err != nil {
jw.BeginObjectField("error")
jw.WriteString(mismatchResp.err.Error())
}
jw.BeginObjectField("mismatches_list")
jw.BeginArray()
for _, mismatchList := range mismatchResp.mismatches {
jw.BeginObject()
jw.BeginObjectField("mismatches")
jw.BeginArray()
for _, mismatch := range mismatchList {
jw.BeginObject()
if mismatch.err != nil {
jw.BeginObjectField("error")
jw.WriteString(mismatch.err.Error())
}
jw.BeginObjectField("name")
jw.WriteString(mismatch.seriesName)
if !mismatch.promTime.IsZero() {
jw.BeginObjectField("promVal")
jw.WriteFloat64(mismatch.promVal)
jw.BeginObjectField("promTime")
jw.WriteString(mismatch.promTime.String())
}
if !mismatch.m3Time.IsZero() {
jw.BeginObjectField("m3Val")
jw.WriteFloat64(mismatch.m3Val)
jw.BeginObjectField("m3Time")
jw.WriteString(mismatch.m3Time.String())
}
jw.EndObject()
}
jw.EndArray()
jw.EndObject()
}
jw.EndArray()
jw.EndObject()
return jw.Close()
}