-
Notifications
You must be signed in to change notification settings - Fork 455
/
read.go
187 lines (157 loc) · 5.57 KB
/
read.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
// 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 remote
import (
"context"
"fmt"
"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/executor"
"github.com/m3db/m3/src/query/generated/proto/prompb"
"github.com/m3db/m3/src/query/storage"
"github.com/m3db/m3/src/query/util/logging"
xhttp "github.com/m3db/m3/src/x/net/http"
"github.com/golang/protobuf/proto"
"github.com/golang/snappy"
"github.com/uber-go/tally"
"go.uber.org/zap"
)
const (
// PromReadURL is the url for remote prom read handler
PromReadURL = handler.RoutePrefixV1 + "/prom/remote/read"
// PromReadHTTPMethod is the HTTP method used with this resource.
PromReadHTTPMethod = http.MethodPost
)
// PromReadHandler represents a handler for prometheus read endpoint.
type PromReadHandler struct {
engine *executor.Engine
promReadMetrics promReadMetrics
timeoutOpts *prometheus.TimeoutOpts
}
// NewPromReadHandler returns a new instance of handler.
func NewPromReadHandler(engine *executor.Engine, scope tally.Scope, timeoutOpts *prometheus.TimeoutOpts) http.Handler {
return &PromReadHandler{
engine: engine,
promReadMetrics: newPromReadMetrics(scope),
timeoutOpts: timeoutOpts,
}
}
type promReadMetrics struct {
fetchSuccess tally.Counter
fetchErrorsServer tally.Counter
fetchErrorsClient tally.Counter
}
func newPromReadMetrics(scope tally.Scope) promReadMetrics {
return promReadMetrics{
fetchSuccess: scope.Counter("fetch.success"),
fetchErrorsServer: scope.Tagged(map[string]string{"code": "5XX"}).Counter("fetch.errors"),
fetchErrorsClient: scope.Tagged(map[string]string{"code": "4XX"}).Counter("fetch.errors"),
}
}
func (h *PromReadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), handler.HeaderKey, r.Header)
logger := logging.WithContext(ctx)
req, rErr := h.parseRequest(r)
if rErr != nil {
xhttp.Error(w, rErr.Inner(), rErr.Code())
return
}
timeout, err := prometheus.ParseRequestTimeout(r, h.timeoutOpts.FetchTimeout)
if err != nil {
h.promReadMetrics.fetchErrorsClient.Inc(1)
xhttp.Error(w, err, http.StatusBadRequest)
return
}
result, err := h.read(ctx, w, req, timeout)
if err != nil {
h.promReadMetrics.fetchErrorsServer.Inc(1)
logger.Error("unable to fetch data", zap.Any("error", err))
xhttp.Error(w, err, http.StatusInternalServerError)
return
}
resp := &prompb.ReadResponse{
Results: result,
}
data, err := proto.Marshal(resp)
if err != nil {
h.promReadMetrics.fetchErrorsServer.Inc(1)
logger.Error("unable to marshal read results to protobuf", zap.Any("error", err))
xhttp.Error(w, err, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/x-protobuf")
w.Header().Set("Content-Encoding", "snappy")
compressed := snappy.Encode(nil, data)
if _, err := w.Write(compressed); err != nil {
h.promReadMetrics.fetchErrorsServer.Inc(1)
logger.Error("unable to encode read results to snappy", zap.Any("err", err))
xhttp.Error(w, err, http.StatusInternalServerError)
return
}
h.promReadMetrics.fetchSuccess.Inc(1)
}
func (h *PromReadHandler) parseRequest(
r *http.Request,
) (*prompb.ReadRequest, *xhttp.ParseError) {
reqBuf, err := prometheus.ParsePromCompressedRequest(r)
if err != nil {
return nil, err
}
var req prompb.ReadRequest
if err := proto.Unmarshal(reqBuf, &req); err != nil {
return nil, xhttp.NewParseError(err, http.StatusBadRequest)
}
return &req, nil
}
func (h *PromReadHandler) read(
reqCtx context.Context,
w http.ResponseWriter,
r *prompb.ReadRequest,
timeout time.Duration,
) ([]*prompb.QueryResult, error) {
// TODO: Handle multi query use case
if len(r.Queries) != 1 {
return nil, fmt.Errorf("prometheus read endpoint currently only supports one query at a time")
}
ctx, cancel := context.WithTimeout(reqCtx, timeout)
defer cancel()
promQuery := r.Queries[0]
query, err := storage.PromReadQueryToM3(promQuery)
if err != nil {
return nil, err
}
// Results is closed by execute
results := make(chan *storage.QueryResult)
opts := &executor.EngineOptions{}
// Detect clients closing connections
handler.CloseWatcher(ctx, cancel, w)
go h.engine.Execute(ctx, query, opts, results)
promResults := make([]*prompb.QueryResult, 0, 1)
for result := range results {
if result.Err != nil {
return nil, result.Err
}
promRes := storage.FetchResultToPromResult(result.FetchResult)
promResults = append(promResults, promRes)
}
return promResults, nil
}