/
v1.go
206 lines (180 loc) · 6.42 KB
/
v1.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
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package v1
import (
"fmt"
"net/http"
"strconv"
"time"
"github.com/NYTimes/gziphandler"
"github.com/prometheus/client_golang/prometheus"
"github.com/go-kit/kit/log"
opentracing "github.com/opentracing/opentracing-go"
"github.com/prometheus/common/route"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/rules"
extpromhttp "github.com/thanos-io/thanos/pkg/extprom/http"
qapi "github.com/thanos-io/thanos/pkg/query/api"
thanosrule "github.com/thanos-io/thanos/pkg/rule"
"github.com/thanos-io/thanos/pkg/store/storepb"
"github.com/thanos-io/thanos/pkg/tracing"
)
type API struct {
logger log.Logger
now func() time.Time
ruleRetriever RulesRetriever
reg prometheus.Registerer
}
func NewAPI(
logger log.Logger,
reg prometheus.Registerer,
ruleRetriever RulesRetriever,
) *API {
return &API{
logger: logger,
now: time.Now,
ruleRetriever: ruleRetriever,
reg: reg,
}
}
func (api *API) Register(r *route.Router, tracer opentracing.Tracer, logger log.Logger, ins extpromhttp.InstrumentationMiddleware) {
instr := func(name string, f qapi.ApiFunc) http.HandlerFunc {
hf := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
qapi.SetCORS(w)
if data, warnings, err := f(r); err != nil {
qapi.RespondError(w, err, data)
} else if data != nil {
qapi.Respond(w, data, warnings)
} else {
w.WriteHeader(http.StatusNoContent)
}
})
return ins.NewHandler(name, tracing.HTTPMiddleware(tracer, name, logger, gziphandler.GzipHandler(hf)))
}
r.Get("/alerts", instr("alerts", api.alerts))
r.Get("/rules", instr("rules", api.rules))
}
type RulesRetriever interface {
RuleGroups() []thanosrule.Group
AlertingRules() []thanosrule.AlertingRule
}
func (api *API) rules(r *http.Request) (interface{}, []error, *qapi.ApiError) {
res := &RuleDiscovery{}
for _, grp := range api.ruleRetriever.RuleGroups() {
apiRuleGroup := &RuleGroup{
Name: grp.Name(),
File: grp.OriginalFile(),
Interval: grp.Interval().Seconds(),
Rules: []rule{},
PartialResponseStrategy: grp.PartialResponseStrategy.String(),
}
for _, r := range grp.Rules() {
var enrichedRule rule
lastError := ""
if r.LastError() != nil {
lastError = r.LastError().Error()
}
switch rule := r.(type) {
case *rules.AlertingRule:
enrichedRule = alertingRule{
Name: rule.Name(),
Query: rule.Query().String(),
Duration: rule.Duration().Seconds(),
Labels: rule.Labels(),
Annotations: rule.Annotations(),
Alerts: rulesAlertsToAPIAlerts(grp.PartialResponseStrategy, rule.ActiveAlerts()),
Health: rule.Health(),
LastError: lastError,
Type: "alerting",
PartialResponseStrategy: grp.PartialResponseStrategy.String(),
}
case *rules.RecordingRule:
enrichedRule = recordingRule{
Name: rule.Name(),
Query: rule.Query().String(),
Labels: rule.Labels(),
Health: rule.Health(),
LastError: lastError,
Type: "recording",
}
default:
err := fmt.Errorf("rule %q: unsupported type %T", r.Name(), rule)
return nil, nil, &qapi.ApiError{Typ: qapi.ErrorInternal, Err: err}
}
apiRuleGroup.Rules = append(apiRuleGroup.Rules, enrichedRule)
}
res.RuleGroups = append(res.RuleGroups, apiRuleGroup)
}
return res, nil, nil
}
func (api *API) alerts(r *http.Request) (interface{}, []error, *qapi.ApiError) {
var alerts []*Alert
for _, alertingRule := range api.ruleRetriever.AlertingRules() {
alerts = append(
alerts,
rulesAlertsToAPIAlerts(alertingRule.PartialResponseStrategy, alertingRule.ActiveAlerts())...,
)
}
res := &AlertDiscovery{Alerts: alerts}
return res, nil, nil
}
type AlertDiscovery struct {
Alerts []*Alert `json:"alerts"`
}
type Alert struct {
Labels labels.Labels `json:"labels"`
Annotations labels.Labels `json:"annotations"`
State string `json:"state"`
ActiveAt *time.Time `json:"activeAt,omitempty"`
Value string `json:"value"`
PartialResponseStrategy string `json:"partial_response_strategy"`
}
func rulesAlertsToAPIAlerts(s storepb.PartialResponseStrategy, rulesAlerts []*rules.Alert) []*Alert {
apiAlerts := make([]*Alert, len(rulesAlerts))
for i, ruleAlert := range rulesAlerts {
apiAlerts[i] = &Alert{
PartialResponseStrategy: s.String(),
Labels: ruleAlert.Labels,
Annotations: ruleAlert.Annotations,
State: ruleAlert.State.String(),
ActiveAt: &ruleAlert.ActiveAt,
Value: strconv.FormatFloat(ruleAlert.Value, 'e', -1, 64),
}
}
return apiAlerts
}
type RuleDiscovery struct {
RuleGroups []*RuleGroup `json:"groups"`
}
type RuleGroup struct {
Name string `json:"name"`
File string `json:"file"`
// In order to preserve rule ordering, while exposing type (alerting or recording)
// specific properties, both alerting and recording rules are exposed in the
// same array.
Rules []rule `json:"rules"`
Interval float64 `json:"interval"`
PartialResponseStrategy string `json:"partial_response_strategy"`
}
type rule interface{}
type alertingRule struct {
Name string `json:"name"`
Query string `json:"query"`
Duration float64 `json:"duration"`
Labels labels.Labels `json:"labels"`
Annotations labels.Labels `json:"annotations"`
Alerts []*Alert `json:"alerts"`
Health rules.RuleHealth `json:"health"`
LastError string `json:"lastError,omitempty"`
Type string `json:"type"`
PartialResponseStrategy string `json:"partial_response_strategy"`
}
type recordingRule struct {
Name string `json:"name"`
Query string `json:"query"`
Labels labels.Labels `json:"labels,omitempty"`
Health rules.RuleHealth `json:"health"`
LastError string `json:"lastError,omitempty"`
// Type of a recordingRule is always "recording".
Type string `json:"type"`
}