-
Notifications
You must be signed in to change notification settings - Fork 0
/
remoteread.go
100 lines (81 loc) · 2.9 KB
/
remoteread.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
package remoteread
import (
"net/http"
"flag"
"fmt"
"time"
"os"
"strconv"
"github.com/go-kit/kit/log"
"github.com/prometheus/prometheus/storage/remote"
"github.com/prometheus/prometheus/prompb"
"github.com/prometheus/tsdb"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/prometheus/pkg/labels"
)
type myHandler struct{
db *tsdb.DB
}
func (this myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
req, err := remote.DecodeReadRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp := prompb.ReadResponse{
Results: make([]*prompb.QueryResult, len(req.Queries)),
}
for i, query := range req.Queries {
from, through, matchers, selectParams, err := remote.FromQuery(query)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
querier, err := this.db.Querier(from, through)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
filteredMatchers := make([]*labels.Matcher, 0, len(matchers))
for _, m := range matchers {
filteredMatchers = append(filteredMatchers, m)
}
set, err := querier.Select(filteredMatchers...)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
resp.Results[i], err = remote.ToQueryResult(set, 5e7)
if err != nil {
if httpErr, ok := err.(remote.HTTPError); ok {
http.Error(w, httpErr.Error(), httpErr.Status())
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
if err := remote.EncodeReadResponse(&resp, w); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func main() {
var logger log.Logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
dbpath := flag.String("dbpath", "/root/lm/bkup/data", "a string")
port := flag.Int("port", 8080, "a int")
flag.Parse()
var reg = prometheus.NewRegistry()
db, err := tsdb.Open(*dbpath, log.With(logger, "db", "tsdb"), reg, tsdb.DefaultOptions)
if err != nil {
fmt.Println("Open tsdb error")
fmt.Println(err.Error())
return
}
addr := ":" + strconv.Itoa(*port)
server := http.Server{
Addr: addr,
Handler: &myHandler{db: db},
ReadTimeout: 300*time.Second,
}
}