1 import { Injectable } from '@angular/core';
3 import _ from 'lodash';
6 AlertmanagerSilenceMatcher,
7 AlertmanagerSilenceMatcherMatch
8 } from '../models/alertmanager-silence';
9 import { PrometheusRule } from '../models/prometheus-alerts';
14 export class PrometheusSilenceMatcherService {
15 private valueAttributePath = {
17 instance: 'alerts.0.labels.instance',
18 job: 'alerts.0.labels.job',
19 severity: 'labels.severity'
23 matcher: AlertmanagerSilenceMatcher,
24 rules: PrometheusRule[]
25 ): AlertmanagerSilenceMatcherMatch {
26 return this.multiMatch([matcher], rules);
30 matchers: AlertmanagerSilenceMatcher[],
31 rules: PrometheusRule[]
32 ): AlertmanagerSilenceMatcherMatch {
33 if (matchers.some((matcher) => matcher.isRegex)) {
36 matchers.forEach((matcher) => {
37 rules = this.getMatchedRules(matcher, rules);
39 return this.describeMatch(rules);
42 private getMatchedRules(
43 matcher: AlertmanagerSilenceMatcher,
44 rules: PrometheusRule[]
46 const attributePath = this.getAttributePath(matcher.name);
47 return rules.filter((r) => _.get(r, attributePath) === matcher.value);
50 private describeMatch(rules: PrometheusRule[]): AlertmanagerSilenceMatcherMatch {
52 rules.forEach((r) => (alerts += r.alerts.length));
54 status: this.getMatchText(rules.length, alerts),
55 cssClass: alerts ? 'has-success' : 'has-warning'
59 getAttributePath(name: string): string {
60 return this.valueAttributePath[name];
63 private getMatchText(rules: number, alerts: number): string {
65 noRule: $localize`Your matcher seems to match no currently defined rule or active alert.`,
66 noAlerts: $localize`no active alerts`,
67 alert: $localize`1 active alert`,
68 alerts: $localize`${alerts} active alerts`,
69 rule: $localize`Matches 1 rule`,
70 rules: $localize`Matches ${rules} rules`
73 const rule = rules > 1 ? msg.rules : msg.rule;
74 const alert = alerts ? (alerts > 1 ? msg.alerts : msg.alert) : msg.noAlerts;
76 return rules ? $localize`${rule} with ${alert}.` : msg.noRule;