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[];
46 resource = $localize`silence`;
48 matchers: AlertmanagerSilenceMatcher[] = [];
49 matcherMatch: AlertmanagerSilenceMatcherMatch = undefined;
52 tooltip: $localize`Attribute name`,
53 icon: this.icons.paragraph,
57 tooltip: $localize`Value`,
58 icon: this.icons.terminal,
62 tooltip: $localize`Regular expression`,
63 icon: this.icons.magic,
68 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`,
214 private getModeSpecificData() {
215 this.route.params.subscribe((params: { id: string }) => {
219 if (this.edit || this.recreate) {
220 this.prometheusService.getSilences().subscribe((silences) => {
221 const silence = _.find(silences, ['id', params.id]);
222 if (!_.isUndefined(silence)) {
223 this.fillFormWithSilence(silence);
227 this.prometheusService.getAlerts().subscribe((alerts) => {
228 const alert = _.find(alerts, ['fingerprint', params.id]);
229 if (!_.isUndefined(alert)) {
230 this.fillFormByAlert(alert);
237 private fillFormWithSilence(silence: AlertmanagerSilence) {
238 this.id = silence.id;
240 ['startsAt', 'endsAt'].forEach((attr) =>
241 this.form.silentSet(attr, moment(silence[attr]).format(this.datetimeFormat))
243 this.updateDuration();
245 ['createdBy', 'comment'].forEach((attr) => this.form.silentSet(attr, silence[attr]));
246 this.matchers = silence.matchers;
247 this.validateMatchers();
250 private validateMatchers() {
252 window.setTimeout(() => this.validateMatchers(), 100);
255 this.matcherMatch = this.silenceMatcher.multiMatch(this.matchers, this.rules);
256 this.form.markAsDirty();
257 this.form.updateValueAndValidity();
260 private fillFormByAlert(alert: AlertmanagerAlert) {
261 const labels = alert.labels;
262 Object.keys(labels).forEach((key) =>
271 private setMatcher(matcher: AlertmanagerSilenceMatcher, index?: number) {
272 if (_.isNumber(index)) {
273 this.matchers[index] = matcher;
275 this.matchers.push(matcher);
277 this.validateMatchers();
280 showMatcherModal(index?: number) {
281 const modalRef = this.modalService.show(SilenceMatcherModalComponent);
282 const modalComponent = modalRef.componentInstance as SilenceMatcherModalComponent;
283 modalComponent.rules = this.rules;
284 if (_.isNumber(index)) {
285 modalComponent.editMode = true;
286 modalComponent.preFillControls(this.matchers[index]);
288 modalComponent.submitAction.subscribe((matcher: AlertmanagerSilenceMatcher) => {
289 this.setMatcher(matcher, index);
293 deleteMatcher(index: number) {
294 this.matchers.splice(index, 1);
295 this.validateMatchers();
299 if (this.form.invalid) {
302 this.prometheusService.setSilence(this.getSubmitData()).subscribe(
304 this.router.navigate(['/monitoring/silences']);
305 this.notificationService.show(
306 NotificationType.success,
307 this.getNotificationTile(resp.body['silenceId']),
313 () => this.form.setErrors({ cdSubmitButton: true })
317 private getSubmitData(): AlertmanagerSilence {
318 const payload = this.form.value;
319 delete payload.duration;
320 payload.startsAt = moment(payload.startsAt, this.datetimeFormat).toISOString();
321 payload.endsAt = moment(payload.endsAt, this.datetimeFormat).toISOString();
322 payload.matchers = this.matchers;
324 payload.id = this.id;
329 private getNotificationTile(id: string) {
332 action = this.succeededLabels.EDITED;
333 } else if (this.recreate) {
334 action = this.succeededLabels.RECREATED;
336 action = this.succeededLabels.CREATED;
338 return `${action} ${this.resource} ${id}`;