This repository has been archived by the owner on May 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
67 lines (59 loc) · 1.82 KB
/
handler.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/prometheus/common/log"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/storage/remote"
)
// ingestHandler returns an http.Handler that accepts proto encoded samples.
func ingestHandler(appender storage.SampleAppender) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if v := r.Header.Get("X-Prometheus-Remote-Write-Version"); v != "0.1.0" {
msg := fmt.Sprintf("Unsupported remote write protocol version %q", v)
log.Errorln(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
compressed, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Errorf("Error reading request body: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
reqBuf, err := snappy.Decode(nil, compressed)
if err != nil {
log.Errorf("Error decompressing request body: %v", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var req remote.WriteRequest
if err := proto.Unmarshal(reqBuf, &req); err != nil {
log.Errorf("Error unmarshalling request body: %v", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
for _, ts := range req.Timeseries {
metric := model.Metric{}
for _, l := range ts.Labels {
metric[model.LabelName(l.Name)] = model.LabelValue(l.Value)
}
for _, s := range ts.Samples {
err := appender.Append(&model.Sample{
Metric: metric,
Value: model.SampleValue(s.Value),
Timestamp: model.Time(s.TimestampMs),
})
if err != nil {
log.Errorf("Error appending sample: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
})
}