summaryrefslogtreecommitdiffstats
path: root/src/pybind/mgr/dashboard/frontend/src/app/shared/services/prometheus-alert-formatter.ts
blob: 96ad5f96f71bfa9479167f5effd5d2652d88a6af (plain)
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
import { Injectable } from '@angular/core';

import _ from 'lodash';

import { Icons } from '../enum/icons.enum';
import { NotificationType } from '../enum/notification-type.enum';
import { CdNotificationConfig } from '../models/cd-notification';
import {
  AlertmanagerAlert,
  AlertmanagerNotificationAlert,
  PrometheusCustomAlert
} from '../models/prometheus-alerts';
import { NotificationService } from './notification.service';

@Injectable({
  providedIn: 'root'
})
export class PrometheusAlertFormatter {
  constructor(private notificationService: NotificationService) {}

  sendNotifications(notifications: CdNotificationConfig[]) {
    notifications.forEach((n) => this.notificationService.show(n));
  }

  convertToCustomAlerts(
    alerts: (AlertmanagerNotificationAlert | AlertmanagerAlert)[]
  ): PrometheusCustomAlert[] {
    return _.uniqWith(
      alerts.map((alert) => {
        return {
          status: _.isObject(alert.status)
            ? (alert as AlertmanagerAlert).status.state
            : this.getPrometheusNotificationStatus(alert as AlertmanagerNotificationAlert),
          name: alert.labels.alertname,
          url: alert.generatorURL,
          description: alert.annotations.description,
          fingerprint: _.isObject(alert.status) && (alert as AlertmanagerAlert).fingerprint
        };
      }),
      _.isEqual
    ) as PrometheusCustomAlert[];
  }

  /*
   * This is needed because NotificationAlerts don't use 'active'
   */
  private getPrometheusNotificationStatus(alert: AlertmanagerNotificationAlert): string {
    const state = alert.status;
    return state === 'firing' ? 'active' : state;
  }

  convertAlertToNotification(alert: PrometheusCustomAlert): CdNotificationConfig {
    return new CdNotificationConfig(
      this.formatType(alert.status),
      `${alert.name} (${alert.status})`,
      this.appendSourceLink(alert, alert.description),
      undefined,
      'Prometheus'
    );
  }

  private formatType(status: string): NotificationType {
    const types = {
      error: ['firing', 'active'],
      info: ['suppressed', 'unprocessed'],
      success: ['resolved']
    };
    return NotificationType[_.findKey(types, (type) => type.includes(status))];
  }

  private appendSourceLink(alert: PrometheusCustomAlert, message: string): string {
    return `${message} <a href="${alert.url}" target="_blank"><i class="${Icons.lineChart}"></i></a>`;
  }
}