-
Notifications
You must be signed in to change notification settings - Fork 455
/
handlers.go
265 lines (228 loc) · 8.99 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// SPDX-License-Identifier: AGPL-3.0-only
// Provenance-includes-location: https://github.com/cortexproject/cortex/blob/master/pkg/api/handlers.go
// Provenance-includes-license: Apache-2.0
// Provenance-includes-copyright: The Cortex Authors.
package api
import (
"context"
"embed"
"html/template"
"net/http"
"path"
"sort"
"sync"
"github.com/go-kit/log"
"github.com/gorilla/mux"
"github.com/grafana/regexp"
"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"
"github.com/grafana/mimir/pkg/querier"
"github.com/grafana/mimir/pkg/querier/stats"
"github.com/grafana/mimir/pkg/util"
"github.com/grafana/mimir/pkg/util/validation"
)
func newIndexPageContent() *IndexPageContent {
return &IndexPageContent{}
}
// IndexPageContent is a map of sections to path -> description.
type IndexPageContent struct {
mu sync.Mutex
elements []IndexPageLinkGroup
}
type IndexPageLinkGroup struct {
weight int
Desc string
Links []IndexPageLink
}
type IndexPageLink struct {
Desc string
Path string
Dangerous bool
}
// List of weights to order link groups in the same order as weights are ordered here.
const (
serviceStatusWeight = iota
configWeight
runtimeConfigWeight
defaultWeight
memberlistWeight
dangerousWeight
)
func (pc *IndexPageContent) AddLinks(weight int, groupDesc string, links []IndexPageLink) {
pc.mu.Lock()
defer pc.mu.Unlock()
pc.elements = append(pc.elements, IndexPageLinkGroup{weight: weight, Desc: groupDesc, Links: links})
}
func (pc *IndexPageContent) GetContent() []IndexPageLinkGroup {
pc.mu.Lock()
els := append([]IndexPageLinkGroup(nil), pc.elements...)
pc.mu.Unlock()
sort.Slice(els, func(i, j int) bool {
if els[i].weight != els[j].weight {
return els[i].weight < els[j].weight
}
return els[i].Desc < els[j].Desc
})
return els
}
//go:embed index.gohtml
var indexPageHTML string
type indexPageContents struct {
LinkGroups []IndexPageLinkGroup
}
//go:embed static
var staticFiles embed.FS
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(indexPageHTML))
return func(w http.ResponseWriter, r *http.Request) {
err := templ.Execute(w, indexPageContents{LinkGroups: content.GetContent()})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
func (cfg *Config) configHandler(actualCfg interface{}, defaultCfg interface{}) http.HandlerFunc {
if cfg.CustomConfigHandler != nil {
return cfg.CustomConfigHandler(actualCfg, defaultCfg)
}
return DefaultConfigHandler(actualCfg, defaultCfg)
}
func DefaultConfigHandler(actualCfg interface{}, defaultCfg interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var output interface{}
switch r.URL.Query().Get("mode") {
case "diff":
defaultCfgObj, err := util.YAMLMarshalUnmarshal(defaultCfg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
actualCfgObj, err := util.YAMLMarshalUnmarshal(actualCfg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
diff, err := util.DiffConfig(defaultCfgObj, actualCfgObj)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
output = diff
case "defaults":
output = defaultCfg
default:
output = actualCfg
}
util.WriteYAMLResponse(w, output)
}
}
// 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,
exemplarQueryable storage.ExemplarQueryable,
engine *promql.Engine,
distributor Distributor,
reg prometheus.Registerer,
logger log.Logger,
limits *validation.Overrides,
) 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(
errorTranslateQueryEngine{engine},
querier.NewErrorTranslateSampleAndChunkQueryable(queryable), // Translate errors to errors expected by API.
nil, // No remote write support.
exemplarQueryable,
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.
false, // Not an agent.
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 }),
reg,
nil,
)
router := mux.NewRouter()
// Use a separate metric for the querier in order to differentiate requests from the query-frontend when
// running Mimir as a single binary.
instrumentMiddleware := middleware.Instrument{
RouteMatcher: router,
Duration: querierRequestDuration,
RequestBodySize: receivedMessageSize,
ResponseBodySize: sentMessageSize,
InflightRequests: inflightRequests,
}
router.Use(instrumentMiddleware.Wrap)
// Define the prefixes for all routes
prefix := path.Join(cfg.ServerPrefix, cfg.PrometheusHTTPPrefix)
promRouter := route.New().WithPrefix(path.Join(prefix, "/api/v1"))
api.Register(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(path.Join(prefix, "/api/v1/metadata")).Handler(querier.MetadataHandler(distributor))
router.Path(path.Join(prefix, "/api/v1/read")).Handler(querier.RemoteReadHandler(queryable, logger))
router.Path(path.Join(prefix, "/api/v1/read")).Methods("POST").Handler(promRouter)
router.Path(path.Join(prefix, "/api/v1/query")).Methods("GET", "POST").Handler(promRouter)
router.Path(path.Join(prefix, "/api/v1/query_range")).Methods("GET", "POST").Handler(promRouter)
router.Path(path.Join(prefix, "/api/v1/query_exemplars")).Methods("GET", "POST").Handler(promRouter)
router.Path(path.Join(prefix, "/api/v1/labels")).Methods("GET", "POST").Handler(promRouter)
router.Path(path.Join(prefix, "/api/v1/label/{name}/values")).Methods("GET").Handler(promRouter)
router.Path(path.Join(prefix, "/api/v1/series")).Methods("GET", "POST", "DELETE").Handler(promRouter)
router.Path(path.Join(prefix, "/api/v1/metadata")).Methods("GET").Handler(promRouter)
router.Path(path.Join(prefix, "/api/v1/cardinality/label_names")).Methods("GET", "POST").Handler(querier.LabelNamesCardinalityHandler(distributor, limits))
router.Path(path.Join(prefix, "/api/v1/cardinality/label_values")).Methods("GET", "POST").Handler(querier.LabelValuesCardinalityHandler(distributor, limits))
// Track execution time.
return stats.NewWallTimeMiddleware().Wrap(router)
}