This repository has been archived by the owner on Oct 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
89 lines (73 loc) · 2.01 KB
/
main.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
package main
import (
"io/ioutil"
"net/http"
"os"
"prom-dynamodb-storage/pkg/dynamodb"
"prom-dynamodb-storage/pkg/settings"
"strconv"
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/prompb"
"github.com/urfave/cli"
)
var version = "0.3"
func main() {
app := cli.NewApp()
app.Name = "prom-dynamodb-storage"
app.Flags = settings.NewContext()
app.Action = runWeb
app.Version = version
app.Run(os.Args)
}
func protoToSamples(req *prompb.WriteRequest) model.Samples {
var samples model.Samples
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 {
samples = append(samples, &model.Sample{
Metric: metric,
Value: model.SampleValue(s.Value),
Timestamp: model.Time(s.Timestamp),
})
}
}
return samples
}
func runWeb(ctx *cli.Context) {
// init logging
settings.LoggerContext(ctx)
// init dynanodb session
client := dynamodb.NewClient(settings.DynamoTable, settings.DynamoRegion)
http.HandleFunc("/write", func(w http.ResponseWriter, r *http.Request) {
compressed, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
reqBuf, err := snappy.Decode(nil, compressed)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var req prompb.WriteRequest
if err := proto.Unmarshal(reqBuf, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
samples := protoToSamples(&req)
err = client.Write(samples)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
return
})
settings.Logger.Info().Str("event", "boot").Msg("Starting server on " + strconv.Itoa(settings.ListenPort))
http.ListenAndServe(":"+strconv.Itoa(settings.ListenPort), nil)
}