-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.go
213 lines (199 loc) · 5.61 KB
/
server.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
208
209
210
211
212
213
package main
import (
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
_ "net/http/pprof"
"net/url"
"regexp"
"slices"
"strconv"
"strings"
)
// Server provides the promethus endpoint for ForecastMetrics.
type Server struct {
LocationService LocationService
Dispatcher *Dispatcher
PromConverter PromConverter
AuthToken string
AllowedMetricNames []string
}
// Start starts the prometheus endpoint.
func (s *Server) Start(config ServerConfig) {
server := &http.Server{
Addr: fmt.Sprintf(":%d", config.Port),
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS13,
CurvePreferences: []tls.CurveID{
tls.CurveP256,
tls.X25519,
},
},
}
// don't 404 on other prometheus endpoints
http.HandleFunc("/api/v1/", func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(204)
})
http.Handle("/api/v1/query_range", s)
if len(config.CertFile) > 0 && len(config.KeyFile) > 0 {
err := server.ListenAndServeTLS(config.CertFile, config.KeyFile)
if err != nil {
panic(err)
}
} else {
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}
}
// ServeHTTP implements http.Handler by serving prometheus metrics for specially formed
// prometheus http requests. If a parsed location is already written to the database,
// we proxy the prometheus request to the database.
func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
// handle auth
if !Auth(req.Header.Get("Authorization"), s.AuthToken) {
resp.Header().Set("WWW-Authenticate", `Basic realm="ForecastMetrics", charset="UTF-8"`)
resp.WriteHeader(http.StatusUnauthorized)
return
}
// get params
err := req.ParseForm()
if err != nil {
fmt.Printf("Failed to parse form: %s", err)
resp.WriteHeader(http.StatusBadRequest)
errorJson(err, resp)
return
}
params, err := s.ParseParams(req.Form)
if err != nil {
fmt.Printf("Failed to parse params: %s: %+v\n", err, req.Form)
resp.WriteHeader(http.StatusBadRequest)
errorJson(err, resp)
return
}
forecast, err := s.Dispatcher.GetForecast(params.Location, params.Source, params.AdHoc)
if err != nil {
fmt.Printf("Error getting forecast: %+v\n", err)
resp.WriteHeader(http.StatusInternalServerError)
errorJson(err, resp)
return
}
// convert to prometheus response.
promResponse := s.PromConverter.ConvertToTimeSeries(*forecast, *params)
// send prom response as json to client
resp.Header().Add("content-type", "application/json")
respJson, err := json.Marshal(promResponse)
if err != nil {
resp.WriteHeader(http.StatusInternalServerError)
errorJson(err, resp)
return
}
_, err = resp.Write(respJson)
if err != nil {
fmt.Printf("Error writing response to client: %+v\n", err)
}
}
func errorJson(err error, resp http.ResponseWriter) {
respJson, err := json.Marshal(PromResponse{
Status: "error",
Error: err.Error(),
})
if err != nil {
fmt.Printf("Error marshalling json: %s\n", err)
return
}
_, err = resp.Write(respJson)
if err != nil {
fmt.Printf("Error writing response to client: %+v\n", err)
}
}
// Auth checks if the authHeader passes Basic authentication with the configured credentials.
func Auth(authHeader, authToken string) bool {
if token, ok := strings.CutPrefix(authHeader, "Basic "); ok {
b, err := base64.StdEncoding.DecodeString(token)
if err != nil {
return false
}
return string(b) == authToken
}
return false
}
// ParsedQuery is the information parsed and looked up from the prometheus query string
type ParsedQuery struct {
Metric string
Location Location
Source string
AdHoc bool
}
// Params are the timestamps of the query range along with the query string information.
type Params struct {
Start int64
End int64
Step int64
ParsedQuery
}
// String implements Stringer by printing the parsed prometheus query string.
func (p Params) String() string {
return fmt.Sprintf("Metric:%s Location:%s Source:%s Adhoc:%t\n", p.Metric, p.Location.Name, p.Source, p.AdHoc)
}
var queryRE = regexp.MustCompile(`^(\w+)\{(.+)}$`)
var tagRE = regexp.MustCompile(`(\w+)="([^"]+)",?`)
// ParseQuery parses the information in the prometheus query string.
func (s *Server) ParseQuery(query string) (*ParsedQuery, error) {
matches := queryRE.FindStringSubmatch(query)
if len(matches) == 0 {
return nil, errors.New("no matches found")
}
pq := &ParsedQuery{
Metric: matches[1],
}
validMetric := slices.ContainsFunc(s.AllowedMetricNames, func(str string) bool {
return strings.HasPrefix(pq.Metric, str)
})
if !validMetric {
return nil, fmt.Errorf("invalid metric name: %s", pq.Metric)
}
tagMatches := tagRE.FindAllStringSubmatch(matches[2], -1)
tags := make(map[string]string)
for _, tagMatch := range tagMatches {
tags[tagMatch[1]] = tagMatch[2]
}
adhoc := true
if save := tags["save"]; save == "true" {
adhoc = false
}
loc, ok := tags["location"]
if !ok {
return nil, errors.New("no location tag found")
}
location, err := s.LocationService.ParseLocation(loc)
if err != nil {
return nil, err
}
pq.Location = *location
pq.AdHoc = adhoc
if pq.Source, ok = tags["source"]; !ok {
return nil, errors.New("no source tag found")
}
return pq, nil
}
// ParseParams parses all the information needed from the prometheus request.
func (s *Server) ParseParams(Form url.Values) (*Params, error) {
pq, err := s.ParseQuery(Form.Get("query"))
if err != nil {
return nil, err
}
start, _ := strconv.ParseInt(Form.Get("start"), 10, 64)
end, _ := strconv.ParseInt(Form.Get("end"), 10, 64)
step, _ := strconv.ParseInt(Form.Get("step"), 10, 64)
return &Params{
Start: start,
End: end,
Step: step,
ParsedQuery: *pq,
}, nil
}