1 import { Injectable } from '@angular/core';
3 import * as _ from 'lodash';
5 import { PrometheusService } from '../api/prometheus.service';
10 } from '../models/prometheus-alerts';
11 import { PrometheusAlertFormatter } from './prometheus-alert-formatter';
16 export class PrometheusAlertService {
17 private canAlertsBeNotified = false;
18 alerts: AlertmanagerAlert[] = [];
19 rules: PrometheusRule[] = [];
22 private alertFormatter: PrometheusAlertFormatter,
23 private prometheusService: PrometheusService
27 this.prometheusService.ifAlertmanagerConfigured(() => {
28 this.prometheusService.getAlerts().subscribe(
29 (alerts) => this.handleAlerts(alerts),
31 if ([404, 504].includes(resp.status)) {
32 this.prometheusService.disableAlertmanagerConfig();
40 this.prometheusService.ifPrometheusConfigured(() => {
41 this.prometheusService.getRules('alerting').subscribe((groups) => {
42 this.rules = groups['groups'].reduce((acc, group) => {
44 group.rules.map((rule) => {
45 rule.group = group.name;
59 private handleAlerts(alerts: AlertmanagerAlert[]) {
60 if (this.canAlertsBeNotified) {
61 this.notifyOnAlertChanges(alerts, this.alerts);
64 this.canAlertsBeNotified = true;
67 private notifyOnAlertChanges(alerts: AlertmanagerAlert[], oldAlerts: AlertmanagerAlert[]) {
68 const changedAlerts = this.getChangedAlerts(
69 this.alertFormatter.convertToCustomAlerts(alerts),
70 this.alertFormatter.convertToCustomAlerts(oldAlerts)
72 const notifications = changedAlerts.map((alert) =>
73 this.alertFormatter.convertAlertToNotification(alert)
75 this.alertFormatter.sendNotifications(notifications);
78 private getChangedAlerts(alerts: PrometheusCustomAlert[], oldAlerts: PrometheusCustomAlert[]) {
79 const updatedAndNew = _.differenceWith(alerts, oldAlerts, _.isEqual);
80 return updatedAndNew.concat(this.getVanishedAlerts(alerts, oldAlerts));
83 private getVanishedAlerts(alerts: PrometheusCustomAlert[], oldAlerts: PrometheusCustomAlert[]) {
84 return _.differenceWith(oldAlerts, alerts, (a, b) => a.fingerprint === b.fingerprint).map(
86 alert.status = 'resolved';