This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
metrics.go
217 lines (191 loc) · 5.57 KB
/
metrics.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
package ingest
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"sync"
"github.com/golang/snappy"
"github.com/grafana/metrictank/publish"
"github.com/grafana/metrictank/schema"
"github.com/grafana/metrictank/schema/msg"
"github.com/grafana/metrictank/stats"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
log "github.com/sirupsen/logrus"
)
var (
metricsValid = stats.NewCounterRate32("metrics.http.valid") // valid metrics received (not necessarily published)
metricsRejected = stats.NewCounterRate32("metrics.http.rejected") // invalid metrics received
metricsTSLock = &sync.Mutex{}
metricsTimestamp = make(map[int]*stats.Range32)
discardedSamples = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: "gateway",
Name: "invalid_samples_total",
Help: "The total number of samples that were discarded because they are invalid.",
},
[]string{"reason", "org"},
)
)
func getMetricsTimestampStat(org int) *stats.Range32 {
metricsTSLock.Lock()
metricTimestamp, ok := metricsTimestamp[org]
if !ok {
metricTimestamp = stats.NewRange32(fmt.Sprintf("metrics.timestamp.http.%d", org)) // min/max timestamps seen in each interval
metricsTimestamp[org] = metricTimestamp
}
metricsTSLock.Unlock()
return metricTimestamp
}
func Metrics(w http.ResponseWriter, r *http.Request) {
contentType := r.Header.Get("Content-Type")
switch contentType {
case "rt-metric-binary":
metricsBinary(w, r, false)
case "rt-metric-binary-snappy":
metricsBinary(w, r, true)
case "application/json":
metricsJson(w, r)
default:
writeErrorResponse(w, 400, "unknown content-type: %s", contentType)
}
}
type discardsByReason map[string]int
type discardsByOrg map[int]discardsByReason
func (dbo discardsByOrg) Add(org int, reason string) {
dbr, ok := dbo[org]
if !ok {
dbr = make(discardsByReason)
}
dbr[reason]++
dbo[org] = dbr
}
func prepareIngest(in []*schema.MetricData, toPublish []*schema.MetricData) ([]*schema.MetricData, MetricsResponse) {
resp := NewMetricsResponse()
promDiscards := make(discardsByOrg)
var metricTimestamp *stats.Range32
for i, m := range in {
if m.Mtype == "" {
m.Mtype = "gauge"
}
if err := m.Validate(); err != nil {
log.Debugf("received invalid metric: %v %v %v", m.Name, m.OrgId, m.Tags)
resp.AddInvalid(err, i)
promDiscards.Add(m.OrgId, err.Error())
continue
}
m.SetId()
metricTimestamp = getMetricsTimestampStat(m.OrgId)
metricTimestamp.ValueUint32(uint32(m.Time))
toPublish = append(toPublish, m)
}
// track invalid/discards in graphite and prometheus
metricsRejected.Add(resp.Invalid)
metricsValid.Add(len(toPublish))
for org, promDiscardsByOrg := range promDiscards {
for reason, cnt := range promDiscardsByOrg {
discardedSamples.WithLabelValues(reason, strconv.Itoa(org)).Add(float64(cnt))
}
}
return toPublish, resp
}
func metricsJson(w http.ResponseWriter, r *http.Request) {
if r.Body == nil {
writeErrorResponse(w, 400, "no data included in request.")
return
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
select {
case <-r.Context().Done():
writeErrorResponse(w, 499, "request canceled")
default:
writeErrorResponse(w, 500, "unable to read request body. %s", err)
}
return
}
metrics := make([]*schema.MetricData, 0)
err = json.Unmarshal(body, &metrics)
if err != nil {
writeErrorResponse(w, 400, "unable to parse request body. %s", err)
return
}
toPublish := make([]*schema.MetricData, 0, len(metrics))
toPublish, resp := prepareIngest(metrics, toPublish)
select {
case <-r.Context().Done():
writeErrorResponse(w, 499, "request canceled")
return
default:
}
err = publish.Publish(toPublish)
if err != nil {
writeErrorResponse(w, 500, "failed to publish metrics. %s", err)
return
}
// track published in the response (it already has discards)
resp.Published = len(toPublish)
w.WriteHeader(200)
json.NewEncoder(w).Encode(resp)
}
func metricsBinary(w http.ResponseWriter, r *http.Request, compressed bool) {
if r.Body == nil {
writeErrorResponse(w, 400, "no data included in request.")
return
}
var bodyReadCloser io.ReadCloser
if compressed {
bodyReadCloser = ioutil.NopCloser(snappy.NewReader(r.Body))
} else {
bodyReadCloser = r.Body
}
defer bodyReadCloser.Close()
body, err := ioutil.ReadAll(bodyReadCloser)
if err != nil {
select {
case <-r.Context().Done():
writeErrorResponse(w, 499, "request canceled")
default:
writeErrorResponse(w, 500, "unable to read request body. %s", err)
}
return
}
metricData := new(msg.MetricData)
err = metricData.InitFromMsg(body)
if err != nil {
writeErrorResponse(w, 400, "payload not metricData. %s", err)
return
}
err = metricData.DecodeMetricData()
if err != nil {
writeErrorResponse(w, 400, "failed to unmarshal metricData. %s", err)
return
}
toPublish := make([]*schema.MetricData, 0, len(metricData.Metrics))
toPublish, resp := prepareIngest(metricData.Metrics, toPublish)
select {
case <-r.Context().Done():
writeErrorResponse(w, 499, "request canceled")
return
default:
}
err = publish.Publish(toPublish)
if err != nil {
writeErrorResponse(w, 500, "failed to publish metrics. %s", err)
return
}
// track published in the response (it already has discards)
resp.Published = len(toPublish)
w.WriteHeader(200)
json.NewEncoder(w).Encode(resp)
}
func writeErrorResponse(w http.ResponseWriter, status int, msg string, fmtArgs ...interface{}) {
w.WriteHeader(status)
formatted := fmt.Sprintf(msg, fmtArgs...)
log.Error(formatted)
fmt.Fprint(w, formatted)
}