-
Notifications
You must be signed in to change notification settings - Fork 450
/
report.go
187 lines (159 loc) · 5.52 KB
/
report.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 json
import (
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"github.com/m3db/m3/src/collector/reporter"
"github.com/m3db/m3/src/metrics/metric/id"
"github.com/m3db/m3/src/query/api/v1/handler"
"github.com/m3db/m3/src/query/models"
"github.com/m3db/m3/src/query/storage"
"github.com/m3db/m3/src/x/net/http"
"github.com/m3db/m3/src/x/serialize"
"github.com/m3db/m3x/instrument"
)
const (
// ReportURL is the url for the report json handler
ReportURL = handler.RoutePrefixV1 + "/json/report"
// ReportHTTPMethod is the HTTP method used with this resource.
ReportHTTPMethod = http.MethodPost
counterType = "counter"
gaugeType = "gauge"
timerType = "timer"
)
var (
errEncoderNoBytes = errors.New("tags encoder has no access to bytes")
)
type reportHandler struct {
reporter reporter.Reporter
encoderPool serialize.TagEncoderPool
decoderPool serialize.TagDecoderPool
instrumentOpts instrument.Options
}
// NewReportHandler returns a new instance of the report handler.
func NewReportHandler(
reporter reporter.Reporter,
encoderPool serialize.TagEncoderPool,
decoderPool serialize.TagDecoderPool,
instrumentOpts instrument.Options,
) http.Handler {
return &reportHandler{
reporter: reporter,
encoderPool: encoderPool,
decoderPool: decoderPool,
instrumentOpts: instrumentOpts,
}
}
// reportRequest represents the report request from the caller.
type reportRequest struct {
Metrics []metricValue `json:"metrics"`
}
// metricValue is a reportable metric value.
type metricValue struct {
Type string `json:"type" validate:"nonzero"`
Tags map[string]string `json:"tags" validate:"nonzero"`
Value float64 `json:"value" validate:"nonzero"`
}
// reportResponse represents the report response.
type reportResponse struct {
Reported int `json:"reported"`
}
func (h *reportHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
req, err := h.parseRequest(r)
if err != nil {
xhttp.Error(w, err.Inner(), err.Code())
return
}
for _, metric := range req.Metrics {
id, err := h.newMetricID(metric)
if err != nil {
xhttp.Error(w, err.Inner(), err.Code())
return
}
if err := h.reportMetric(id, metric); err != nil {
xhttp.Error(w, err.Inner(), err.Code())
return
}
}
resp := &reportResponse{Reported: len(req.Metrics)}
xhttp.WriteJSONResponse(w, resp, h.instrumentOpts.ZapLogger())
}
func (h *reportHandler) parseRequest(r *http.Request) (*reportRequest, *xhttp.ParseError) {
if r.Body == nil {
err := fmt.Errorf("empty request body")
return nil, xhttp.NewParseError(err, http.StatusBadRequest)
}
defer r.Body.Close()
req := new(reportRequest)
if err := json.NewDecoder(r.Body).Decode(req); err != nil {
return nil, xhttp.NewParseError(err, http.StatusBadRequest)
}
return req, nil
}
func (h *reportHandler) newMetricID(metric metricValue) (id.ID, *xhttp.ParseError) {
tags := models.NewTags(len(metric.Tags), models.NewTagOptions())
for n, v := range metric.Tags {
tags = tags.AddTag(models.Tag{Name: []byte(n), Value: []byte(v)})
}
tagsIter := storage.TagsToIdentTagIterator(tags)
encoder := h.encoderPool.Get()
encoder.Reset()
defer encoder.Finalize()
if err := encoder.Encode(tagsIter); err != nil {
return nil, xhttp.NewParseError(err, http.StatusInternalServerError)
}
data, ok := encoder.Data()
if !ok {
return nil, xhttp.NewParseError(errEncoderNoBytes, http.StatusInternalServerError)
}
// Take a copy of the pooled encoder's bytes
bytes := append([]byte(nil), data.Bytes()...)
metricTagsIter := serialize.NewMetricTagsIterator(h.decoderPool.Get(), nil)
metricTagsIter.Reset(bytes)
return metricTagsIter, nil
}
func (h *reportHandler) reportMetric(id id.ID, metric metricValue) *xhttp.ParseError {
var err error
switch metric.Type {
case counterType:
roundedValue := math.Ceil(metric.Value)
if roundedValue != metric.Value {
// Not an int
badReqErr := fmt.Errorf("counter value not a float: %v", metric.Value)
return xhttp.NewParseError(badReqErr, http.StatusBadRequest)
}
err = h.reporter.ReportCounter(id, int64(roundedValue))
case gaugeType:
err = h.reporter.ReportGauge(id, metric.Value)
case timerType:
err = h.reporter.ReportBatchTimer(id, []float64{metric.Value})
default:
badReqErr := fmt.Errorf("invalid metric type: %s", metric.Type)
return xhttp.NewParseError(badReqErr, http.StatusBadRequest)
}
if err != nil {
return xhttp.NewParseError(err, http.StatusInternalServerError)
}
return nil
}