1 import { Component } from '@angular/core';
2 import { Validators } from '@angular/forms';
3 import { ActivatedRoute, Router } from '@angular/router';
5 import _ from 'lodash';
6 import moment from 'moment';
8 import { DashboardNotFoundError } from '~/app/core/error/error';
9 import { PrometheusService } from '~/app/shared/api/prometheus.service';
10 import { ActionLabelsI18n, SucceededActionLabelsI18n } from '~/app/shared/constants/app.constants';
11 import { Icons } from '~/app/shared/enum/icons.enum';
12 import { NotificationType } from '~/app/shared/enum/notification-type.enum';
13 import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
14 import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
15 import { CdValidators } from '~/app/shared/forms/cd-validators';
18 AlertmanagerSilenceMatcher,
19 AlertmanagerSilenceMatcherMatch
20 } from '~/app/shared/models/alertmanager-silence';
21 import { Permission } from '~/app/shared/models/permissions';
22 import { AlertmanagerAlert, PrometheusRule } from '~/app/shared/models/prometheus-alerts';
23 import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
24 import { ModalService } from '~/app/shared/services/modal.service';
25 import { NotificationService } from '~/app/shared/services/notification.service';
26 import { PrometheusSilenceMatcherService } from '~/app/shared/services/prometheus-silence-matcher.service';
27 import { TimeDiffService } from '~/app/shared/services/time-diff.service';
28 import { SilenceMatcherModalComponent } from '../silence-matcher-modal/silence-matcher-modal.component';
31 selector: 'cd-prometheus-form',
32 templateUrl: './silence-form.component.html',
33 styleUrls: ['./silence-form.component.scss']
35 export class SilenceFormComponent {
37 permission: Permission;
39 rules: PrometheusRule[];
48 resource = $localize`silence`;
50 matchers: AlertmanagerSilenceMatcher[] = [];
51 matcherMatch: AlertmanagerSilenceMatcherMatch = undefined;
54 tooltip: $localize`Attribute name`,
58 tooltip: $localize`Regular expression`,
62 tooltip: $localize`Value`,
67 datetimeFormat = 'YYYY-MM-DD HH:mm';
71 private router: Router,
72 private authStorageService: AuthStorageService,
73 private formBuilder: CdFormBuilder,
74 private prometheusService: PrometheusService,
75 private notificationService: NotificationService,
76 private route: ActivatedRoute,
77 private timeDiff: TimeDiffService,
78 private modalService: ModalService,
79 private silenceMatcher: PrometheusSilenceMatcherService,
80 private actionLabels: ActionLabelsI18n,
81 private succeededLabels: SucceededActionLabelsI18n
94 private chooseMode() {
95 this.edit = this.router.url.startsWith('/monitoring/silences/edit');
96 this.recreate = this.router.url.startsWith('/monitoring/silences/recreate');
98 this.action = this.actionLabels.EDIT;
99 } else if (this.recreate) {
100 this.action = this.actionLabels.RECREATE;
102 this.action = this.actionLabels.CREATE;
106 private authenticate() {
107 this.permission = this.authStorageService.getPermissions().prometheus;
109 this.permission.read && (this.edit ? this.permission.update : this.permission.create);
111 throw new DashboardNotFoundError();
115 private createForm() {
116 const formatValidator = CdValidators.custom('format', (expiresAt: string) => {
117 const result = expiresAt === '' || moment(expiresAt, this.datetimeFormat).isValid();
120 this.form = this.formBuilder.group(
122 startsAt: ['', [Validators.required, formatValidator]],
123 duration: ['2h', [Validators.min(1)]],
124 endsAt: ['', [Validators.required, formatValidator]],
125 createdBy: [this.authStorageService.getUsername(), [Validators.required]],
126 comment: [null, [Validators.required]]
129 validators: CdValidators.custom('matcherRequired', () => this.matchers.length === 0)
134 private setupDates() {
135 const now = moment().format(this.datetimeFormat);
136 this.form.silentSet('startsAt', now);
138 this.subscribeDateChanges();
141 private updateDate(updateStartDate?: boolean) {
143 this.form.getValue(updateStartDate ? 'endsAt' : 'startsAt'),
146 const next = this.timeDiff.calculateDate(date, this.form.getValue('duration'), updateStartDate);
148 const nextDate = moment(next).format(this.datetimeFormat);
149 this.form.silentSet(updateStartDate ? 'startsAt' : 'endsAt', nextDate);
153 private subscribeDateChanges() {
154 this.form.get('startsAt').valueChanges.subscribe(() => {
157 this.form.get('duration').valueChanges.subscribe(() => {
160 this.form.get('endsAt').valueChanges.subscribe(() => {
161 this.onDateChange(true);
165 private onDateChange(updateStartDate?: boolean) {
166 const startsAt = moment(this.form.getValue('startsAt'), this.datetimeFormat);
167 const endsAt = moment(this.form.getValue('endsAt'), this.datetimeFormat);
168 if (startsAt.isBefore(endsAt)) {
169 this.updateDuration();
171 this.updateDate(updateStartDate);
175 private updateDuration() {
176 const startsAt = moment(this.form.getValue('startsAt'), this.datetimeFormat).toDate();
177 const endsAt = moment(this.form.getValue('endsAt'), this.datetimeFormat).toDate();
178 this.form.silentSet('duration', this.timeDiff.calculateDuration(startsAt, endsAt));
183 this.getModeSpecificData();
187 this.prometheusService.ifPrometheusConfigured(
189 this.prometheusService.getRules().subscribe(
191 this.rules = groups['groups'].reduce(
192 (acc, group) => _.concat<PrometheusRule>(acc, group.rules),
197 this.prometheusService.disablePrometheusConfig();
203 this.notificationService.show(
204 NotificationType.info,
205 $localize`Please add your Prometheus host to the dashboard configuration and refresh the page`,
215 private getModeSpecificData() {
216 this.route.params.subscribe((params: { id: string }) => {
220 if (this.edit || this.recreate) {
221 this.prometheusService.getSilences().subscribe((silences) => {
222 const silence = _.find(silences, ['id', params.id]);
223 if (!_.isUndefined(silence)) {
224 this.fillFormWithSilence(silence);
228 this.prometheusService.getAlerts().subscribe((alerts) => {
229 const alert = _.find(alerts, ['fingerprint', params.id]);
230 if (!_.isUndefined(alert)) {
231 this.fillFormByAlert(alert);
238 private fillFormWithSilence(silence: AlertmanagerSilence) {
239 this.id = silence.id;
241 ['startsAt', 'endsAt'].forEach((attr) =>
242 this.form.silentSet(attr, moment(silence[attr]).format(this.datetimeFormat))
244 this.updateDuration();
246 ['createdBy', 'comment'].forEach((attr) => this.form.silentSet(attr, silence[attr]));
247 this.matchers = silence.matchers;
248 this.validateMatchers();
251 private validateMatchers() {
253 window.setTimeout(() => this.validateMatchers(), 100);
256 this.matcherMatch = this.silenceMatcher.multiMatch(this.matchers, this.rules);
257 this.form.markAsDirty();
258 this.form.updateValueAndValidity();
261 private fillFormByAlert(alert: AlertmanagerAlert) {
262 const labels = alert.labels;
265 value: labels.alertname,
270 private setMatcher(matcher: AlertmanagerSilenceMatcher, index?: number) {
271 if (_.isNumber(index)) {
272 this.matchers[index] = matcher;
274 this.matchers.push(matcher);
276 this.validateMatchers();
279 showMatcherModal(index?: number) {
280 const modalRef = this.modalService.show(SilenceMatcherModalComponent);
281 const modalComponent = modalRef.componentInstance as SilenceMatcherModalComponent;
282 modalComponent.rules = this.rules;
283 if (_.isNumber(index)) {
284 modalComponent.editMode = true;
285 modalComponent.preFillControls(this.matchers[index]);
287 modalComponent.submitAction.subscribe((matcher: AlertmanagerSilenceMatcher) => {
288 this.setMatcher(matcher, index);
292 deleteMatcher(index: number) {
293 this.matchers.splice(index, 1);
294 this.validateMatchers();
298 if (this.form.invalid) {
301 this.prometheusService.setSilence(this.getSubmitData()).subscribe(
304 data.silenceId = resp.body['silenceId'];
306 if (this.isNavigate) {
307 this.router.navigate(['/monitoring/silences']);
309 this.notificationService.show(
310 NotificationType.success,
311 this.getNotificationTile(this.matchers),
318 () => this.form.setErrors({ cdSubmitButton: true })
322 private getSubmitData(): AlertmanagerSilence {
323 const payload = this.form.value;
324 delete payload.duration;
325 payload.startsAt = moment(payload.startsAt, this.datetimeFormat).toISOString();
326 payload.endsAt = moment(payload.endsAt, this.datetimeFormat).toISOString();
327 payload.matchers = this.matchers;
329 payload.id = this.id;
334 private getNotificationTile(matchers: AlertmanagerSilenceMatcher[]) {
337 action = this.succeededLabels.EDITED;
338 } else if (this.recreate) {
339 action = this.succeededLabels.RECREATED;
341 action = this.succeededLabels.CREATED;
344 for (const matcher of matchers) {
345 msg = msg.concat(` ${matcher.name} - ${matcher.value},`);
347 return `${action} ${this.resource} for ${msg.slice(0, -1)}`;