/
write.go
223 lines (192 loc) · 6.14 KB
/
write.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
// 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"
"errors"
"net/http"
"sync"
"github.com/m3db/m3/src/cmd/services/m3coordinator/downsample"
"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/generated/proto/prompb"
"github.com/m3db/m3/src/query/storage"
"github.com/m3db/m3/src/query/util/logging"
xerrors "github.com/m3db/m3x/errors"
"github.com/golang/protobuf/proto"
"github.com/uber-go/tally"
"go.uber.org/zap"
)
const (
// PromWriteURL is the url for the prom write handler
PromWriteURL = handler.RoutePrefixV1 + "/prom/remote/write"
// PromWriteHTTPMethod is the HTTP method used with this resource.
PromWriteHTTPMethod = http.MethodPost
)
var (
errNoStorageOrDownsampler = errors.New("no storage or downsampler set, requires at least one or both")
)
// PromWriteHandler represents a handler for prometheus write endpoint.
type PromWriteHandler struct {
store storage.Storage
downsampler downsample.Downsampler
promWriteMetrics promWriteMetrics
}
// NewPromWriteHandler returns a new instance of handler.
func NewPromWriteHandler(
store storage.Storage,
downsampler downsample.Downsampler,
scope tally.Scope,
) (http.Handler, error) {
if store == nil && downsampler == nil {
return nil, errNoStorageOrDownsampler
}
return &PromWriteHandler{
store: store,
downsampler: downsampler,
promWriteMetrics: newPromWriteMetrics(scope),
}, nil
}
type promWriteMetrics struct {
writeSuccess tally.Counter
writeErrorsServer tally.Counter
writeErrorsClient tally.Counter
}
func newPromWriteMetrics(scope tally.Scope) promWriteMetrics {
return promWriteMetrics{
writeSuccess: scope.Counter("write.success"),
writeErrorsServer: scope.Tagged(map[string]string{"code": "5XX"}).Counter("write.errors"),
writeErrorsClient: scope.Tagged(map[string]string{"code": "4XX"}).Counter("write.errors"),
}
}
func (h *PromWriteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
req, rErr := h.parseRequest(r)
if rErr != nil {
h.promWriteMetrics.writeErrorsClient.Inc(1)
handler.Error(w, rErr.Inner(), rErr.Code())
return
}
if err := h.write(r.Context(), req); err != nil {
h.promWriteMetrics.writeErrorsServer.Inc(1)
logging.WithContext(r.Context()).Error("Write error", zap.Any("err", err))
handler.Error(w, err, http.StatusInternalServerError)
return
}
h.promWriteMetrics.writeSuccess.Inc(1)
}
func (h *PromWriteHandler) parseRequest(r *http.Request) (*prompb.WriteRequest, *handler.ParseError) {
reqBuf, err := prometheus.ParsePromCompressedRequest(r)
if err != nil {
return nil, err
}
var req prompb.WriteRequest
if err := proto.Unmarshal(reqBuf, &req); err != nil {
return nil, handler.NewParseError(err, http.StatusBadRequest)
}
return &req, nil
}
func (h *PromWriteHandler) write(ctx context.Context, r *prompb.WriteRequest) error {
var (
wg sync.WaitGroup
writeUnaggErr error
writeAggErr error
)
if h.downsampler != nil {
// If writing downsampled aggregations, write them async
wg.Add(1)
go func() {
writeAggErr = h.writeAggregated(ctx, r)
wg.Done()
}()
}
if h.store != nil {
// Write the unaggregated points out, don't spawn goroutine
// so we reduce number of goroutines just a fraction
writeUnaggErr = h.writeUnaggregated(ctx, r)
}
if h.downsampler != nil {
// Wait for downsampling to finish if we wrote datapoints
// for aggregations
wg.Wait()
}
var multiErr xerrors.MultiError
multiErr = multiErr.Add(writeUnaggErr)
multiErr = multiErr.Add(writeAggErr)
return multiErr.FinalError()
}
func (h *PromWriteHandler) writeUnaggregated(
ctx context.Context,
r *prompb.WriteRequest,
) error {
var (
wg sync.WaitGroup
errLock sync.Mutex
multiErr xerrors.MultiError
)
for _, t := range r.Timeseries {
t := t // Capture for goroutine
// TODO(r): Consider adding a worker pool to limit write
// request concurrency, instead of using the batch size
// of incoming request to determine concurrency (some level of control).
wg.Add(1)
go func() {
write := storage.PromWriteTSToM3(t)
write.Attributes = storage.Attributes{
MetricsType: storage.UnaggregatedMetricsType,
}
if err := h.store.Write(ctx, write); err != nil {
errLock.Lock()
multiErr = multiErr.Add(err)
errLock.Unlock()
}
wg.Done()
}()
}
wg.Wait()
return multiErr.FinalError()
}
func (h *PromWriteHandler) writeAggregated(
_ context.Context,
r *prompb.WriteRequest,
) error {
var (
metricsAppender = h.downsampler.NewMetricsAppender()
multiErr xerrors.MultiError
)
for _, ts := range r.Timeseries {
metricsAppender.Reset()
for _, label := range ts.Labels {
metricsAppender.AddTag(label.Name, label.Value)
}
samplesAppender, err := metricsAppender.SamplesAppender()
if err != nil {
multiErr = multiErr.Add(err)
continue
}
for _, elem := range ts.Samples {
err := samplesAppender.AppendGaugeSample(elem.Value)
if err != nil {
multiErr = multiErr.Add(err)
}
}
}
metricsAppender.Finalize()
return multiErr.FinalError()
}