-
Notifications
You must be signed in to change notification settings - Fork 178
/
putmetrics.go
207 lines (185 loc) · 6.61 KB
/
putmetrics.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
// Copyright (c) 2021-2024 SigScalr, Inc.
//
// This file is part of SigLens Observability Solution
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package writer
import (
"encoding/json"
"fmt"
"strconv"
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/prompb"
"github.com/siglens/siglens/pkg/grpc"
"github.com/siglens/siglens/pkg/hooks"
. "github.com/siglens/siglens/pkg/segment/utils"
"github.com/siglens/siglens/pkg/segment/writer"
"github.com/siglens/siglens/pkg/usageStats"
"github.com/siglens/siglens/pkg/utils"
log "github.com/sirupsen/logrus"
"github.com/valyala/fasthttp"
)
type PrometheusPutResp struct {
Failed uint64 `json:"failed"`
Success uint64 `json:"success"`
Errors []string `json:"errors,omitempty"`
}
func decodeWriteRequest(compressed []byte) (*prompb.WriteRequest, error) {
reqBuf, err := snappy.Decode(nil, compressed)
if err != nil {
log.Errorf("decodeWriteRequest: Error decompressing request body. Compressed length: %v, data: %v, err=%v", len(compressed), compressed, err)
return nil, err
}
var req prompb.WriteRequest
if err := proto.Unmarshal(reqBuf, &req); err != nil {
log.Errorf("decodeWriteRequest: Error unmarshalling request body %v, err=%v", reqBuf, err)
return nil, err
}
return &req, nil
}
func PutMetrics(ctx *fasthttp.RequestCtx) {
if hook := hooks.GlobalHooks.OverrideIngestRequestHook; hook != nil {
alreadyHandled := hook(ctx, 0 /* TODO */, grpc.INGEST_FUNC_PROMETHEUS_METRICS, false)
if alreadyHandled {
return
}
}
var processedCount uint64
var failedCount uint64
var err error
version := string(ctx.Request.Header.Peek("X-Prometheus-Remote-Write-Version"))
if version != "0.1.0" {
log.Errorf("PutMetrics: Unsupported remote write protocol version %v, expected 0.1.0", version)
writePrometheusResponse(ctx, processedCount, failedCount, "unsupported remote write protocol", fasthttp.StatusBadRequest)
return
}
cType := string(ctx.Request.Header.ContentType())
if cType != "application/x-protobuf" {
log.Errorf("PutMetrics: unknown content type: %s, expected application/x-protobuf", cType)
writePrometheusResponse(ctx, processedCount, failedCount, "unknown content type", fasthttp.StatusBadRequest)
return
}
encoding := string(ctx.Request.Header.ContentEncoding())
if encoding != "snappy" {
log.Errorf("PutMetrics: unknown content encoding %s, expected snappy", encoding)
writePrometheusResponse(ctx, processedCount, failedCount, "unknown content encoding", fasthttp.StatusBadRequest)
return
}
compressed := ctx.PostBody()
processedCount, failedCount, err = HandlePutMetrics(compressed)
if err != nil {
log.Errorf("PutMetrics: failed to handle put metrics for compressed data: %v. err=%+v", compressed, err)
writePrometheusResponse(ctx, processedCount, failedCount, err.Error(), fasthttp.StatusBadRequest)
return
}
writePrometheusResponse(ctx, processedCount, failedCount, "", fasthttp.StatusOK)
}
func HandlePutMetrics(compressed []byte) (uint64, uint64, error) {
var successCount uint64 = 0
var failedCount uint64 = 0
req, err := decodeWriteRequest(compressed)
if err != nil {
err = fmt.Errorf("HandlePutMetrics: failed to decode request %v, err=%v", compressed, err)
log.Errorf(err.Error())
return successCount, failedCount, err
}
for _, ts := range req.Timeseries {
metric := make(model.Metric, len(ts.Labels))
for _, l := range ts.Labels {
metric[model.LabelName(l.Name)] = model.LabelValue(l.Value)
}
for _, s := range ts.Samples {
var sample model.Sample = model.Sample{
Metric: metric,
Value: model.SampleValue(s.Value),
Timestamp: model.Time(s.Timestamp),
}
data, err := sample.MarshalJSON()
if err != nil {
failedCount++
log.Errorf("HandlePutMetrics: failed to marshal sample=%+v to json, err=%v", sample, err)
continue
}
var dataJson map[string]interface{}
err = json.Unmarshal(data, &dataJson)
if err != nil {
failedCount++
log.Errorf("HandlePutMetrics: failed to Unmarshal data=%+v, err=%v", data, err)
continue
}
var metricName string
tags := "{"
for key, val := range dataJson {
if key == "metric" {
valMap, ok := val.(map[string]interface{})
if ok {
for k, v := range valMap {
if k == "__name__" {
valString, ok := v.(string)
if ok {
metricName = valString
}
continue // skip metric __name__ as tag
}
valString, ok := v.(string)
if ok {
tags += `"` + k + `":"` + valString + `",`
}
}
}
}
}
if tags[len(tags)-1] == ',' {
tags = tags[:len(tags)-1]
}
tags += "}"
if metricName == "" {
failedCount++
log.Errorf("HandlePutMetrics: the Metric name is empty. json data payload: %+v", dataJson)
continue
}
modifiedData := `{"metric":"` + metricName + `","tags":` + tags + `,"timestamp":` + strconv.FormatInt(s.Timestamp, 10) + `,"value":` + strconv.FormatFloat(s.Value, 'f', -1, 64) + `}`
err = writer.AddTimeSeriesEntryToInMemBuf([]byte(modifiedData), SIGNAL_METRICS_OTSDB, uint64(0))
if err != nil {
log.Errorf("HandlePutMetrics: failed to add time series entry for data=%+v, err=%v", modifiedData, err)
failedCount++
} else {
successCount++
}
}
}
bytesReceived := uint64(len(compressed))
usageStats.UpdateMetricsStats(bytesReceived, successCount, 0)
return successCount, failedCount, nil
}
func writePrometheusResponse(ctx *fasthttp.RequestCtx, processedCount uint64, failedCount uint64, err string, code int) {
resp := PrometheusPutResp{Success: processedCount, Failed: failedCount}
if err != "" {
resp.Errors = []string{err}
}
ctx.SetStatusCode(code)
ctx.SetContentType(utils.ContentJson)
jval, mErr := json.Marshal(resp)
if mErr != nil {
log.Errorf("writePrometheusResponse: failed to marshal %v to json, err=%v", resp, mErr)
return
}
_, mErr = ctx.Write(jval)
if mErr != nil {
log.Errorf("writePrometheusResponse: failed to write jval=%v to http context, err=%v", jval, mErr)
return
}
}