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
|
import { Injectable } from '@angular/core';
import _ from 'lodash';
import {
AlertmanagerSilenceMatcher,
AlertmanagerSilenceMatcherMatch
} from '../models/alertmanager-silence';
import { PrometheusRule } from '../models/prometheus-alerts';
@Injectable({
providedIn: 'root'
})
export class PrometheusSilenceMatcherService {
private valueAttributePath = {
alertname: 'name',
instance: 'alerts.0.labels.instance',
job: 'alerts.0.labels.job',
severity: 'labels.severity'
};
singleMatch(
matcher: AlertmanagerSilenceMatcher,
rules: PrometheusRule[]
): AlertmanagerSilenceMatcherMatch {
return this.multiMatch([matcher], rules);
}
multiMatch(
matchers: AlertmanagerSilenceMatcher[],
rules: PrometheusRule[]
): AlertmanagerSilenceMatcherMatch {
if (matchers.some((matcher) => matcher.isRegex)) {
return undefined;
}
matchers.forEach((matcher) => {
rules = this.getMatchedRules(matcher, rules);
});
return this.describeMatch(rules);
}
private getMatchedRules(
matcher: AlertmanagerSilenceMatcher,
rules: PrometheusRule[]
): PrometheusRule[] {
const attributePath = this.getAttributePath(matcher.name);
return rules.filter((r) => _.get(r, attributePath) === matcher.value);
}
private describeMatch(rules: PrometheusRule[]): AlertmanagerSilenceMatcherMatch {
let alerts = 0;
rules.forEach((r) => (alerts += r.alerts.length));
return {
status: this.getMatchText(rules.length, alerts),
cssClass: alerts ? 'has-success' : 'has-warning'
};
}
getAttributePath(name: string): string {
return this.valueAttributePath[name];
}
private getMatchText(rules: number, alerts: number): string {
const msg = {
noRule: $localize`Your matcher seems to match no currently defined rule or active alert.`,
noAlerts: $localize`no active alerts`,
alert: $localize`1 active alert`,
alerts: $localize`${alerts} active alerts`,
rule: $localize`Matches 1 rule`,
rules: $localize`Matches ${rules} rules`
};
const rule = rules > 1 ? msg.rules : msg.rule;
const alert = alerts ? (alerts > 1 ? msg.alerts : msg.alert) : msg.noAlerts;
return rules ? $localize`${rule} with ${alert}.` : msg.noRule;
}
}
|