]>
Commit | Line | Data |
---|---|---|
494da23a TL |
1 | import { Injectable } from '@angular/core'; |
2 | ||
f67539c2 | 3 | import _ from 'lodash'; |
494da23a | 4 | |
494da23a TL |
5 | import { |
6 | AlertmanagerSilenceMatcher, | |
7 | AlertmanagerSilenceMatcherMatch | |
8 | } from '../models/alertmanager-silence'; | |
9 | import { PrometheusRule } from '../models/prometheus-alerts'; | |
10 | ||
11 | @Injectable({ | |
12 | providedIn: 'root' | |
13 | }) | |
14 | export class PrometheusSilenceMatcherService { | |
15 | private valueAttributePath = { | |
16 | alertname: 'name', | |
17 | instance: 'alerts.0.labels.instance', | |
18 | job: 'alerts.0.labels.job', | |
19 | severity: 'labels.severity' | |
20 | }; | |
21 | ||
494da23a TL |
22 | singleMatch( |
23 | matcher: AlertmanagerSilenceMatcher, | |
24 | rules: PrometheusRule[] | |
25 | ): AlertmanagerSilenceMatcherMatch { | |
26 | return this.multiMatch([matcher], rules); | |
27 | } | |
28 | ||
29 | multiMatch( | |
30 | matchers: AlertmanagerSilenceMatcher[], | |
31 | rules: PrometheusRule[] | |
32 | ): AlertmanagerSilenceMatcherMatch { | |
33 | if (matchers.some((matcher) => matcher.isRegex)) { | |
9f95a23c | 34 | return undefined; |
494da23a TL |
35 | } |
36 | matchers.forEach((matcher) => { | |
37 | rules = this.getMatchedRules(matcher, rules); | |
38 | }); | |
39 | return this.describeMatch(rules); | |
40 | } | |
41 | ||
39ae355f | 42 | getMatchedRules(matcher: AlertmanagerSilenceMatcher, rules: PrometheusRule[]): PrometheusRule[] { |
494da23a TL |
43 | const attributePath = this.getAttributePath(matcher.name); |
44 | return rules.filter((r) => _.get(r, attributePath) === matcher.value); | |
45 | } | |
46 | ||
47 | private describeMatch(rules: PrometheusRule[]): AlertmanagerSilenceMatcherMatch { | |
48 | let alerts = 0; | |
49 | rules.forEach((r) => (alerts += r.alerts.length)); | |
50 | return { | |
51 | status: this.getMatchText(rules.length, alerts), | |
52 | cssClass: alerts ? 'has-success' : 'has-warning' | |
53 | }; | |
54 | } | |
55 | ||
56 | getAttributePath(name: string): string { | |
57 | return this.valueAttributePath[name]; | |
58 | } | |
59 | ||
60 | private getMatchText(rules: number, alerts: number): string { | |
61 | const msg = { | |
f67539c2 TL |
62 | noRule: $localize`Your matcher seems to match no currently defined rule or active alert.`, |
63 | noAlerts: $localize`no active alerts`, | |
64 | alert: $localize`1 active alert`, | |
65 | alerts: $localize`${alerts} active alerts`, | |
66 | rule: $localize`Matches 1 rule`, | |
67 | rules: $localize`Matches ${rules} rules` | |
494da23a | 68 | }; |
f67539c2 TL |
69 | |
70 | const rule = rules > 1 ? msg.rules : msg.rule; | |
71 | const alert = alerts ? (alerts > 1 ? msg.alerts : msg.alert) : msg.noAlerts; | |
72 | ||
73 | return rules ? $localize`${rule} with ${alert}.` : msg.noRule; | |
494da23a TL |
74 | } |
75 | } |