forked from prometheus/pushgateway
/
api.go
280 lines (240 loc) · 7.35 KB
/
api.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright 2020 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package v1
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/common/route"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/pushgateway/handler"
"github.com/prometheus/pushgateway/storage"
)
type status string
const (
statusSuccess status = "success"
statusError status = "error"
)
type errorType string
const (
errorNone errorType = ""
errorTimeout errorType = "timeout"
errorCanceled errorType = "canceled"
errorExec errorType = "execution"
errorBadData errorType = "bad_data"
errorInternal errorType = "internal"
errorUnavailable errorType = "unavailable"
errorNotFound errorType = "not_found"
)
type apiError struct {
typ errorType
err error
}
func (e *apiError) Error() string {
return fmt.Sprintf("%s: %s", e.typ, e.err)
}
var corsHeaders = map[string]string{
"Access-Control-Allow-Headers": "Accept, Authorization, Content-Type, Origin",
"Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
"Access-Control-Allow-Origin": "*",
"Access-Control-Expose-Headers": "Date",
"Cache-Control": "no-cache, no-store, must-revalidate",
}
// Enables cross-site script calls.
func setCORS(w http.ResponseWriter) {
for h, v := range corsHeaders {
w.Header().Set(h, v)
}
}
// API provides registration of handlers for API routes.
type API struct {
logger log.Logger
MetricStore storage.MetricStore
Flags map[string]string
StartTime time.Time
BuildInfo map[string]string
}
// New returns a new API. The log.Logger can be nil, in which case no logging is performed.
func New(
l log.Logger,
ms storage.MetricStore,
flags map[string]string,
buildInfo map[string]string,
) *API {
if l == nil {
l = log.NewNopLogger()
}
return &API{
StartTime: time.Now(),
logger: l,
MetricStore: ms,
Flags: flags,
BuildInfo: buildInfo,
}
}
// Register registers the API handlers under their correct routes
// in the given router.
func (api *API) Register(r *route.Router) {
wrap := func(handlerName string, f http.HandlerFunc) http.HandlerFunc {
return handler.InstrumentWithCounter(
handlerName,
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
setCORS(w)
f(w, r)
}),
)
}
r.Options("/*path", wrap("api/v1/options", func(w http.ResponseWriter, r *http.Request) {}))
r.Get("/status", wrap("api/v1/status", api.status))
r.Get("/metrics", wrap("api/v1/metrics", api.metrics))
}
type metrics struct {
Timestamp time.Time `json:"time_stamp"`
Type string `json:"type"`
Help string `json:"help,omitempty"`
Metrics []encodableMetric `json:"metrics"`
}
func (api *API) metrics(w http.ResponseWriter, r *http.Request) {
familyMaps := api.MetricStore.GetMetricFamiliesMap()
res := []interface{}{}
for _, v := range familyMaps {
metricResponse := map[string]interface{}{}
metricResponse["labels"] = v.Labels
metricResponse["last_push_successful"] = v.LastPushSuccess()
for name, metricValues := range v.Metrics {
metricFamily := metricValues.GetMetricFamily()
uniqueMetrics := metrics{
Type: metricFamily.GetType().String(),
Help: metricFamily.GetHelp(),
Timestamp: metricValues.Timestamp,
Metrics: makeEncodableMetrics(metricFamily.GetMetric(), metricFamily.GetType()),
}
metricResponse[name] = uniqueMetrics
}
res = append(res, metricResponse)
}
api.respond(w, res)
}
func (api *API) status(w http.ResponseWriter, r *http.Request) {
res := map[string]interface{}{}
res["flags"] = api.Flags
res["start_time"] = api.StartTime
res["build_information"] = api.BuildInfo
api.respond(w, res)
}
type response struct {
Status status `json:"status"`
Data interface{} `json:"data,omitempty"`
ErrorType errorType `json:"errorType,omitempty"`
Error string `json:"error,omitempty"`
}
func (api *API) respond(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
b, err := json.Marshal(&response{
Status: statusSuccess,
Data: data,
})
if err != nil {
level.Error(api.logger).Log("msg", "error marshaling JSON", "err", err)
api.respondError(w, apiError{
typ: errorBadData,
err: err,
}, "")
}
if _, err := w.Write(b); err != nil {
level.Error(api.logger).Log("msg", "failed to write data to connection", "err", err)
}
}
func (api *API) respondError(w http.ResponseWriter, apiErr apiError, data interface{}) {
w.Header().Set("Content-Type", "application/json")
switch apiErr.typ {
case errorBadData:
w.WriteHeader(http.StatusBadRequest)
case errorInternal:
w.WriteHeader(http.StatusInternalServerError)
default:
panic(fmt.Sprintf("unknown error type %q", apiErr.Error()))
}
b, err := json.Marshal(&response{
Status: statusError,
ErrorType: apiErr.typ,
Error: apiErr.err.Error(),
Data: data,
})
if err != nil {
return
}
level.Error(api.logger).Log("msg", "API error", "err", apiErr.Error())
if _, err := w.Write(b); err != nil {
level.Error(api.logger).Log("msg", "failed to write data to connection", "err", err)
}
}
type encodableMetric map[string]interface{}
func makeEncodableMetrics(metrics []*dto.Metric, metricsType dto.MetricType) []encodableMetric {
jsonMetrics := make([]encodableMetric, len(metrics))
for i, m := range metrics {
metric := encodableMetric{}
metric["labels"] = makeLabels(m)
switch metricsType {
case dto.MetricType_SUMMARY:
metric["quantiles"] = makeQuantiles(m)
metric["count"] = fmt.Sprint(m.GetSummary().GetSampleCount())
metric["sum"] = fmt.Sprint(m.GetSummary().GetSampleSum())
case dto.MetricType_HISTOGRAM:
metric["buckets"] = makeBuckets(m)
metric["count"] = fmt.Sprint(m.GetHistogram().GetSampleCount())
metric["sum"] = fmt.Sprint(m.GetHistogram().GetSampleSum())
default:
metric["value"] = fmt.Sprint(getValue(m))
}
jsonMetrics[i] = metric
}
return jsonMetrics
}
func makeLabels(m *dto.Metric) map[string]string {
result := map[string]string{}
for _, lp := range m.Label {
result[lp.GetName()] = lp.GetValue()
}
return result
}
func makeQuantiles(m *dto.Metric) map[string]string {
result := map[string]string{}
for _, q := range m.GetSummary().Quantile {
result[fmt.Sprint(q.GetQuantile())] = fmt.Sprint(q.GetValue())
}
return result
}
func makeBuckets(m *dto.Metric) map[string]string {
result := map[string]string{}
for _, b := range m.GetHistogram().Bucket {
result[fmt.Sprint(b.GetUpperBound())] = fmt.Sprint(b.GetCumulativeCount())
}
return result
}
func getValue(m *dto.Metric) float64 {
switch {
case m.Gauge != nil:
return m.GetGauge().GetValue()
case m.Counter != nil:
return m.GetCounter().GetValue()
case m.Untyped != nil:
return m.GetUntyped().GetValue()
default:
return 0
}
}