forked from cortexproject/cortex
/
handlers.go
248 lines (219 loc) · 8.92 KB
/
handlers.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package api
import (
"context"
"html/template"
"net/http"
"path"
"regexp"
"sync"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/gorilla/mux"
"github.com/opentracing-contrib/go-stdlib/nethttp"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/route"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/promql"
"github.com/prometheus/prometheus/storage"
v1 "github.com/prometheus/prometheus/web/api/v1"
"github.com/weaveworks/common/instrument"
"github.com/weaveworks/common/middleware"
"gopkg.in/yaml.v2"
"github.com/cortexproject/cortex/pkg/chunk/purger"
"github.com/cortexproject/cortex/pkg/distributor"
"github.com/cortexproject/cortex/pkg/querier"
"github.com/cortexproject/cortex/pkg/util"
)
const (
SectionAdminEndpoints = "Admin Endpoints:"
SectionDangerous = "Dangerous:"
)
func newIndexPageContent() *IndexPageContent {
return &IndexPageContent{
content: map[string]map[string]string{},
}
}
// IndexPageContent is a map of sections to path -> description.
type IndexPageContent struct {
mu sync.Mutex
content map[string]map[string]string
}
func (pc *IndexPageContent) AddLink(section, path, description string) {
pc.mu.Lock()
defer pc.mu.Unlock()
sectionMap := pc.content[section]
if sectionMap == nil {
sectionMap = make(map[string]string)
pc.content[section] = sectionMap
}
sectionMap[path] = description
}
func (pc *IndexPageContent) GetContent() map[string]map[string]string {
pc.mu.Lock()
defer pc.mu.Unlock()
result := map[string]map[string]string{}
for k, v := range pc.content {
sm := map[string]string{}
for smK, smV := range v {
sm[smK] = smV
}
result[k] = sm
}
return result
}
var indexPageTemplate = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cortex</title>
</head>
<body>
<h1>Cortex</h1>
{{ range $s, $links := . }}
<p>{{ $s }}</p>
<ul>
{{ range $path, $desc := $links }}
<li><a href="{{ AddPathPrefix $path }}">{{ $desc }}</a></li>
{{ end }}
</ul>
{{ end }}
</body>
</html>`
func indexHandler(httpPathPrefix string, content *IndexPageContent) http.HandlerFunc {
templ := template.New("main")
templ.Funcs(map[string]interface{}{
"AddPathPrefix": func(link string) string {
return path.Join(httpPathPrefix, link)
},
})
template.Must(templ.Parse(indexPageTemplate))
return func(w http.ResponseWriter, r *http.Request) {
err := templ.Execute(w, content.GetContent())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
func configHandler(cfg interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
out, err := yaml.Marshal(cfg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/yaml")
w.WriteHeader(http.StatusOK)
if _, err := w.Write(out); err != nil {
level.Error(util.Logger).Log("msg", "error writing response", "err", err)
}
}
}
// NewQuerierHandler returns a HTTP handler that can be used by the querier service to
// either register with the frontend worker query processor or with the external HTTP
// server to fulfill the Prometheus query API.
func NewQuerierHandler(
cfg Config,
queryable storage.SampleAndChunkQueryable,
engine *promql.Engine,
distributor *distributor.Distributor,
tombstonesLoader *purger.TombstonesLoader,
reg prometheus.Registerer,
logger log.Logger,
) http.Handler {
// Prometheus histograms for requests to the querier.
querierRequestDuration := promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Namespace: "cortex",
Name: "querier_request_duration_seconds",
Help: "Time (in seconds) spent serving HTTP requests to the querier.",
Buckets: instrument.DefBuckets,
}, []string{"method", "route", "status_code", "ws"})
receivedMessageSize := promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Namespace: "cortex",
Name: "querier_request_message_bytes",
Help: "Size (in bytes) of messages received in the request to the querier.",
Buckets: middleware.BodySizeBuckets,
}, []string{"method", "route"})
sentMessageSize := promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Namespace: "cortex",
Name: "querier_response_message_bytes",
Help: "Size (in bytes) of messages sent in response by the querier.",
Buckets: middleware.BodySizeBuckets,
}, []string{"method", "route"})
inflightRequests := promauto.With(reg).NewGaugeVec(prometheus.GaugeOpts{
Namespace: "cortex",
Name: "querier_inflight_requests",
Help: "Current number of inflight requests to the querier.",
}, []string{"method", "route"})
api := v1.NewAPI(
engine,
errorTranslateQueryable{queryable}, // Translate errors to errors expected by API.
func(context.Context) v1.TargetRetriever { return &querier.DummyTargetRetriever{} },
func(context.Context) v1.AlertmanagerRetriever { return &querier.DummyAlertmanagerRetriever{} },
func() config.Config { return config.Config{} },
map[string]string{}, // TODO: include configuration flags
v1.GlobalURLOptions{},
func(f http.HandlerFunc) http.HandlerFunc { return f },
nil, // Only needed for admin APIs.
"", // This is for snapshots, which is disabled when admin APIs are disabled. Hence empty.
false, // Disable admin APIs.
logger,
func(context.Context) v1.RulesRetriever { return &querier.DummyRulesRetriever{} },
0, 0, 0, // Remote read samples and concurrency limit.
regexp.MustCompile(".*"),
func() (v1.RuntimeInfo, error) { return v1.RuntimeInfo{}, errors.New("not implemented") },
&v1.PrometheusVersion{},
// This is used for the stats API which we should not support. Or find other ways to.
prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) { return nil, nil }),
)
router := mux.NewRouter()
// Use a separate metric for the querier in order to differentiate requests from the query-frontend when
// running Cortex as a single binary.
inst := middleware.Instrument{
RouteMatcher: router,
Duration: querierRequestDuration,
RequestBodySize: receivedMessageSize,
ResponseBodySize: sentMessageSize,
InflightRequests: inflightRequests,
}
cacheGenHeaderMiddleware := getHTTPCacheGenNumberHeaderSetterMiddleware(tombstonesLoader)
middlewares := middleware.Merge(inst, cacheGenHeaderMiddleware)
router.Use(middlewares.Wrap)
// Define the prefixes for all routes
prefix := cfg.ServerPrefix + cfg.PrometheusHTTPPrefix
legacyPrefix := cfg.ServerPrefix + cfg.LegacyHTTPPrefix
promRouter := route.New().WithPrefix(prefix + "/api/v1")
api.Register(promRouter)
legacyPromRouter := route.New().WithPrefix(legacyPrefix + "/api/v1")
api.Register(legacyPromRouter)
// TODO(gotjosh): This custom handler is temporary until we're able to vendor the changes in:
// https://github.com/prometheus/prometheus/pull/7125/files
router.Path(prefix + "/api/v1/metadata").Handler(querier.MetadataHandler(distributor))
router.Path(prefix + "/api/v1/read").Handler(querier.RemoteReadHandler(queryable))
router.Path(prefix + "/api/v1/read").Methods("POST").Handler(promRouter)
router.Path(prefix+"/api/v1/query").Methods("GET", "POST").Handler(promRouter)
router.Path(prefix+"/api/v1/query_range").Methods("GET", "POST").Handler(promRouter)
router.Path(prefix+"/api/v1/labels").Methods("GET", "POST").Handler(promRouter)
router.Path(prefix + "/api/v1/label/{name}/values").Methods("GET").Handler(promRouter)
router.Path(prefix+"/api/v1/series").Methods("GET", "POST", "DELETE").Handler(promRouter)
router.Path(prefix + "/api/v1/metadata").Methods("GET").Handler(promRouter)
// TODO(gotjosh): This custom handler is temporary until we're able to vendor the changes in:
// https://github.com/prometheus/prometheus/pull/7125/files
router.Path(legacyPrefix + "/api/v1/metadata").Handler(querier.MetadataHandler(distributor))
router.Path(legacyPrefix + "/api/v1/read").Handler(querier.RemoteReadHandler(queryable))
router.Path(legacyPrefix + "/api/v1/read").Methods("POST").Handler(legacyPromRouter)
router.Path(legacyPrefix+"/api/v1/query").Methods("GET", "POST").Handler(legacyPromRouter)
router.Path(legacyPrefix+"/api/v1/query_range").Methods("GET", "POST").Handler(legacyPromRouter)
router.Path(legacyPrefix+"/api/v1/labels").Methods("GET", "POST").Handler(legacyPromRouter)
router.Path(legacyPrefix + "/api/v1/label/{name}/values").Methods("GET").Handler(legacyPromRouter)
router.Path(legacyPrefix+"/api/v1/series").Methods("GET", "POST", "DELETE").Handler(legacyPromRouter)
router.Path(legacyPrefix + "/api/v1/metadata").Methods("GET").Handler(legacyPromRouter)
// Add a middleware to extract the trace context and add a header.
return nethttp.MiddlewareFunc(opentracing.GlobalTracer(), router.ServeHTTP, nethttp.OperationNameFunc(func(r *http.Request) string {
return "internalQuerier"
}))
}