-
Notifications
You must be signed in to change notification settings - Fork 70
logs: re-introduce rules filtering for Prometheus API as this is still not supported by Loki #805
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,280 @@ | ||
package http | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"errors" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"strconv" | ||
"time" | ||
|
||
"github.com/go-kit/log" | ||
"github.com/go-kit/log/level" | ||
"github.com/observatorium/api/authentication" | ||
"github.com/observatorium/api/authorization" | ||
"github.com/prometheus/prometheus/model/labels" | ||
) | ||
|
||
const contentTypeApplicationJSON = "application/json" | ||
|
||
var ( | ||
errUnknownTenantKey = errors.New("unknown tenant key") | ||
errUnknownRulesContentType = errors.New("unknown rules response content type") | ||
) | ||
|
||
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"` | ||
} | ||
|
||
func (a *alert) GetLabels() labels.Labels { return a.Labels } | ||
|
||
type alertingRule struct { | ||
State string `json:"state"` | ||
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 string `json:"health"` | ||
LastError string `json:"lastError"` | ||
LastEvaluation string `json:"lastEvaluation"` | ||
EvaluationTime float64 `json:"evaluationTime"` | ||
// 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"` | ||
Health string `json:"health"` | ||
LastError string `json:"lastError"` | ||
LastEvaluation string `json:"lastEvaluation"` | ||
EvaluationTime float64 `json:"evaluationTime"` | ||
// Type of a recordingRule is always "recording". | ||
Type string `json:"type"` | ||
} | ||
|
||
type ruleGroup struct { | ||
Name string `json:"name"` | ||
File string `json:"file"` | ||
Rules []rule `json:"rules"` | ||
Interval float64 `json:"interval"` | ||
LastEvaluation string `json:"lastEvaluation"` | ||
EvaluationTime float64 `json:"evaluationTime"` | ||
} | ||
|
||
type rule struct { | ||
*alertingRule | ||
*recordingRule | ||
} | ||
|
||
func (r *rule) GetLabels() 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 rulesData struct { | ||
RuleGroups []*ruleGroup `json:"groups,omitempty"` | ||
Alerts []*alert `json:"alerts,omitempty"` | ||
} | ||
|
||
type prometheusRulesResponse struct { | ||
Status string `json:"status"` | ||
Data rulesData `json:"data"` | ||
Error string `json:"error"` | ||
ErrorType string `json:"errorType"` | ||
} | ||
|
||
func newModifyResponseProm(logger log.Logger, labelKeys map[string][]string) func(*http.Response) error { | ||
return func(res *http.Response) error { | ||
tenant, ok := authentication.GetTenant(res.Request.Context()) | ||
if !ok { | ||
return errUnknownTenantKey | ||
} | ||
|
||
keys, ok := labelKeys[tenant] | ||
if !ok { | ||
level.Debug(logger).Log("msg", "Skip applying rule label filters", "tenant", tenant) | ||
return nil | ||
} | ||
|
||
var ( | ||
matchers = extractMatchers(res.Request, keys) | ||
contentType = res.Header.Get("Content-Type") | ||
) | ||
|
||
data, ok := authorization.GetData(res.Request.Context()) | ||
|
||
var matchersInfo AuthzResponseData | ||
if ok && data != "" { | ||
if err := json.Unmarshal([]byte(data), &matchersInfo); err != nil { | ||
return nil | ||
} | ||
} | ||
|
||
strictMode := len(matchersInfo.Matchers) != 0 | ||
|
||
matcherStr := fmt.Sprintf("%s", matchers) | ||
level.Debug(logger).Log("msg", "filtering using matchers", "tenant", tenant, "matchers", matcherStr) | ||
|
||
body, err := io.ReadAll(res.Body) | ||
if err != nil { | ||
level.Error(logger).Log("msg", err) | ||
return err | ||
} | ||
res.Body.Close() | ||
|
||
b, err := filterRules(body, contentType, matchers, strictMode) | ||
if err != nil { | ||
level.Error(logger).Log("msg", err) | ||
return err | ||
} | ||
|
||
res.Body = io.NopCloser(bytes.NewReader(b)) | ||
res.ContentLength = int64(len(b)) | ||
res.Header.Set("Content-Length", strconv.FormatInt(res.ContentLength, 10)) | ||
|
||
return nil | ||
} | ||
} | ||
|
||
func extractMatchers(r *http.Request, l []string) map[string]string { | ||
queryParams := r.URL.Query() | ||
matchers := map[string]string{} | ||
for _, name := range l { | ||
value := queryParams.Get(name) | ||
if value != "" { | ||
matchers[name] = value | ||
} | ||
} | ||
|
||
return matchers | ||
} | ||
|
||
func filterRules(body []byte, contentType string, matchers map[string]string, strictMode bool) ([]byte, error) { | ||
switch contentType { | ||
case contentTypeApplicationJSON: | ||
var res prometheusRulesResponse | ||
err := json.Unmarshal(body, &res) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return json.Marshal(filterPrometheusResponse(res, matchers, strictMode)) | ||
default: | ||
return nil, errUnknownRulesContentType | ||
} | ||
} | ||
|
||
func filterPrometheusResponse(res prometheusRulesResponse, matchers map[string]string, strictEnforce bool) prometheusRulesResponse { | ||
if len(matchers) == 0 { | ||
if strictEnforce { | ||
res.Data = rulesData{} | ||
} | ||
|
||
return res | ||
} | ||
|
||
if len(res.Data.RuleGroups) > 0 { | ||
filtered := filterPrometheusRuleGroups(res.Data.RuleGroups, matchers) | ||
res.Data = rulesData{RuleGroups: filtered} | ||
} | ||
|
||
if len(res.Data.Alerts) > 0 { | ||
filtered := filterPrometheusAlerts(res.Data.Alerts, matchers) | ||
res.Data = rulesData{Alerts: filtered} | ||
} | ||
|
||
return res | ||
} | ||
|
||
type labeledRule interface { | ||
GetLabels() labels.Labels | ||
} | ||
|
||
func hasMatchingLabels(rule labeledRule, matchers map[string]string) bool { | ||
for key, value := range matchers { | ||
labels := rule.GetLabels().Map() | ||
val, ok := labels[key] | ||
if !ok || val != value { | ||
return false | ||
} | ||
} | ||
return true | ||
} | ||
|
||
func filterPrometheusRuleGroups(groups []*ruleGroup, matchers map[string]string) []*ruleGroup { | ||
var filtered []*ruleGroup | ||
|
||
for _, group := range groups { | ||
var filteredRules []rule | ||
for _, r := range group.Rules { | ||
if hasMatchingLabels(&r, matchers) { | ||
filteredRules = append(filteredRules, r) | ||
} | ||
} | ||
|
||
if len(filteredRules) > 0 { | ||
group.Rules = filteredRules | ||
filtered = append(filtered, group) | ||
} | ||
} | ||
|
||
return filtered | ||
} | ||
|
||
func filterPrometheusAlerts(alerts []*alert, matchers map[string]string) []*alert { | ||
var filtered []*alert | ||
for _, a := range alerts { | ||
if hasMatchingLabels(a, matchers) { | ||
filtered = append(filtered, a) | ||
} | ||
} | ||
|
||
return filtered | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Some of the error code-paths are not covered by the current set of tests. Should we add one or more tests to cover some of them? Most of them seem to be simple cases, so it's more a question of "completeness" and if it's worth the effort (not talking about all the paths where it's an IO operation or marshalling).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added tests for alerts let me know if you were also referring to anything else