forked from prometheus-community/prom-label-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrules.go
254 lines (217 loc) · 6.84 KB
/
rules.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
// 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 injectproxy
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/prometheus/prometheus/model/labels"
)
type apiResponse struct {
Status string `json:"status"`
Data json.RawMessage `json:"data,omitempty"`
ErrorType string `json:"errorType,omitempty"`
Error string `json:"error,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
func getAPIResponse(resp *http.Response) (*apiResponse, error) {
defer resp.Body.Close()
reader := resp.Body
if resp.Header.Get("Content-Encoding") == "gzip" && !resp.Uncompressed {
var err error
reader, err = gzip.NewReader(resp.Body)
if err != nil {
return nil, fmt.Errorf("gzip decoding error: %w", err)
}
defer reader.Close()
// TODO: recompress the modified response?
resp.Header.Del("Content-Encoding")
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
var apir apiResponse
if err := json.NewDecoder(reader).Decode(&apir); err != nil {
return nil, fmt.Errorf("JSON decoding error: %w", err)
}
if apir.Status != "success" {
return nil, fmt.Errorf("unexpected response status: %q", apir.Status)
}
return &apir, nil
}
type rulesData struct {
RuleGroups []*ruleGroup `json:"groups"`
}
type ruleGroup struct {
Name string `json:"name"`
File string `json:"file"`
Rules []rule `json:"rules"`
Interval float64 `json:"interval"`
}
type rule struct {
*alertingRule
*recordingRule
}
func (r *rule) Labels() labels.Labels {
if r.alertingRule != nil {
return r.alertingRule.Labels
}
return r.recordingRule.Labels
}
// MarshalJSON implements the json.Marshaler interface for rule.
func (r *rule) MarshalJSON() ([]byte, error) {
if r.alertingRule != nil {
return json.Marshal(r.alertingRule)
}
return json.Marshal(r.recordingRule)
}
// UnmarshalJSON implements the json.Unmarshaler interface for rule.
func (r *rule) UnmarshalJSON(b []byte) error {
var ruleType struct {
Type string `json:"type"`
}
if err := json.Unmarshal(b, &ruleType); err != nil {
return err
}
switch ruleType.Type {
case "alerting":
var alertingr alertingRule
if err := json.Unmarshal(b, &alertingr); err != nil {
return err
}
r.alertingRule = &alertingr
case "recording":
var recordingr recordingRule
if err := json.Unmarshal(b, &recordingr); err != nil {
return err
}
r.recordingRule = &recordingr
default:
return fmt.Errorf("failed to unmarshal rule: unknown type %q", ruleType.Type)
}
return nil
}
type alertingRule struct {
State string `json:"state"`
Name string `json:"name"`
Query string `json:"query"`
Duration float64 `json:"duration"`
KeepFiringFor float64 `json:"keepFiringFor"`
Labels labels.Labels `json:"labels"`
Annotations labels.Labels `json:"annotations"`
Alerts []*alert `json:"alerts"`
Health string `json:"health"`
LastError string `json:"lastError,omitempty"`
EvaluationTime float64 `json:"evaluationTime"`
LastEvaluation time.Time `json:"lastEvaluation"`
// Type of an alertingRule is always "alerting".
Type string `json:"type"`
}
type recordingRule struct {
Name string `json:"name"`
Query string `json:"query"`
Labels labels.Labels `json:"labels,omitempty"`
Health string `json:"health"`
LastError string `json:"lastError,omitempty"`
EvaluationTime float64 `json:"evaluationTime"`
LastEvaluation time.Time `json:"lastEvaluation"`
// Type of a recordingRule is always "recording".
Type string `json:"type"`
}
type alertsData 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"`
KeepFiringSince *time.Time `json:"keepFiringSince,omitempty"`
Value string `json:"value"`
}
// modifyAPIResponse unwraps the Prometheus API response, passes the enforced
// label value and the response to the given function and finally replaces the
// result in the response.
func modifyAPIResponse(f func([]string, *apiResponse) (interface{}, error)) func(*http.Response) error {
return func(resp *http.Response) error {
if resp.StatusCode != http.StatusOK {
// Pass non-200 responses as-is.
return nil
}
apir, err := getAPIResponse(resp)
if err != nil {
return fmt.Errorf("can't decode API response: %w", err)
}
v, err := f(MustLabelValues(resp.Request.Context()), apir)
if err != nil {
return err
}
b, err := json.Marshal(v)
if err != nil {
return fmt.Errorf("can't replace data: %w", err)
}
apir.Data = json.RawMessage(b)
var buf bytes.Buffer
if err = json.NewEncoder(&buf).Encode(apir); err != nil {
return fmt.Errorf("can't encode API response: %w", err)
}
resp.Body = io.NopCloser(&buf)
resp.Header["Content-Length"] = []string{fmt.Sprint(buf.Len())}
return nil
}
}
func (r *routes) filterRules(lvalues []string, resp *apiResponse) (interface{}, error) {
var rgs rulesData
if err := json.Unmarshal(resp.Data, &rgs); err != nil {
return nil, fmt.Errorf("can't decode rules data: %w", err)
}
m, err := r.newLabelMatcher(lvalues...)
if err != nil {
return nil, err
}
filtered := []*ruleGroup{}
for _, rg := range rgs.RuleGroups {
var rules []rule
for _, rule := range rg.Rules {
if lval := rule.Labels().Get(r.label); lval != "" && m.Matches(lval) {
rules = append(rules, rule)
}
}
if len(rules) > 0 {
rg.Rules = rules
filtered = append(filtered, rg)
}
}
return &rulesData{RuleGroups: filtered}, nil
}
func (r *routes) filterAlerts(lvalues []string, resp *apiResponse) (interface{}, error) {
var data alertsData
if err := json.Unmarshal(resp.Data, &data); err != nil {
return nil, fmt.Errorf("can't decode alerts data: %w", err)
}
m, err := r.newLabelMatcher(lvalues...)
if err != nil {
return nil, err
}
filtered := []*alert{}
for _, alert := range data.Alerts {
if lval := alert.Labels.Get(r.label); lval != "" && m.Matches(lval) {
filtered = append(filtered, alert)
}
}
return &alertsData{Alerts: filtered}, nil
}