-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.go
149 lines (137 loc) · 4.19 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
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
package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"time"
"github.com/prometheus/client_golang/api"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/model"
"k8s.io/klog/v2"
)
var (
insecureListenAddress string
upstream string
tlsSkipVerify bool
bearerFile string
forceGet bool
)
func parseFlag() {
flag.StringVar(&insecureListenAddress, "insecure-listen-address", "127.0.0.1:9099", "The address which proxy listens on")
flag.StringVar(&upstream, "upstream", "http://127.0.0.1:9090", "The upstream thanos URL")
flag.BoolVar(&tlsSkipVerify, "tlsSkipVerify", false, "Skip TLS Verification")
flag.StringVar(&bearerFile, "bearer-file", "", "File containing bearer token for API requests")
flag.BoolVar(&forceGet, "force-get", false, "Force api.Client to use GET by rejecting POST requests")
flag.Parse()
}
func main() {
parseFlag()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// DefaultRoundTripper is used if no RoundTripper is set in Config.
var roundTripper http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: tlsSkipVerify,
},
}
// Create a new client.
c, err := api.NewClient(api.Config{
Address: upstream,
RoundTripper: roundTripper,
})
if err != nil {
klog.Fatalf("error creating API client: %s", err)
}
// Collect client options
options := []clientOption{}
if bearerFile != "" {
fullPath, err := filepath.Abs(bearerFile)
if err != nil {
klog.Fatalf("error locating bearer file: %s", err)
}
dirName, fileName := filepath.Split(fullPath)
bearer, err := readBearerToken(os.DirFS(dirName), fileName)
if err != nil {
klog.Fatalf("error reading bearer file: %s", err)
}
options = append(options, withToken(bearer))
}
if forceGet {
klog.Infof("Forcing api,Client to use GET requests")
options = append(options, withGet)
}
if c, err = newClient(c, options...); err != nil {
klog.Fatalf("error building custom API client: %s", err)
}
apiClient := v1.NewAPI(c)
// server mux
mux := http.NewServeMux()
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
mux.Handle("/metrics", promhttp.Handler())
mux.HandleFunc("/federate", func(w http.ResponseWriter, r *http.Request) {
federate(ctx, w, r, apiClient)
})
startServer(insecureListenAddress, mux, cancel)
}
func federate(_ context.Context, w http.ResponseWriter, r *http.Request, apiClient v1.API) {
params := r.URL.Query()
matchQueries := params["match[]"]
nctx, ncancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer ncancel()
if params.Del("match[]"); len(params) > 0 {
nctx = addValues(nctx, params)
}
for _, matchQuery := range matchQueries {
start := time.Now()
// Ignoring warnings for now.
val, _, err := apiClient.Query(nctx, matchQuery, start)
responseTime := time.Since(start).Seconds()
if err != nil {
klog.Errorf("query failed: %s", err)
scrapeDurations.With(prometheus.Labels{
"match_query": matchQuery,
"status_code": "500",
}).Observe(responseTime)
w.WriteHeader(http.StatusInternalServerError)
ncancel()
return
}
if val.Type() != model.ValVector {
klog.Errorf("query result is not a vector: %v", val.Type())
scrapeDurations.With(prometheus.Labels{
"match_query": matchQuery,
"status_code": "502",
}).Observe(responseTime)
// TODO: should we continue to the next query?
w.WriteHeader(http.StatusInternalServerError)
ncancel()
return
}
scrapeDurations.With(prometheus.Labels{
"match_query": matchQuery,
"status_code": "200",
}).Observe(responseTime)
printVector(w, val)
}
}
func printVector(w http.ResponseWriter, v model.Value) {
vec := v.(model.Vector)
for _, sample := range vec {
fmt.Fprintf(w, "%v %v %v\n", sample.Metric, sample.Value, int(sample.Timestamp))
}
}