1 import { Component } from '@angular/core';
2 import { Validators } from '@angular/forms';
3 import { ActivatedRoute, Router } from '@angular/router';
5 import { I18n } from '@ngx-translate/i18n-polyfill';
6 import * as _ from 'lodash';
7 import * as moment from 'moment';
9 import { PrometheusService } from '../../../../shared/api/prometheus.service';
12 SucceededActionLabelsI18n
13 } from '../../../../shared/constants/app.constants';
14 import { Icons } from '../../../../shared/enum/icons.enum';
15 import { NotificationType } from '../../../../shared/enum/notification-type.enum';
16 import { CdFormBuilder } from '../../../../shared/forms/cd-form-builder';
17 import { CdFormGroup } from '../../../../shared/forms/cd-form-group';
18 import { CdValidators } from '../../../../shared/forms/cd-validators';
21 AlertmanagerSilenceMatcher,
22 AlertmanagerSilenceMatcherMatch
23 } from '../../../../shared/models/alertmanager-silence';
24 import { Permission } from '../../../../shared/models/permissions';
25 import { AlertmanagerAlert, PrometheusRule } from '../../../../shared/models/prometheus-alerts';
26 import { AuthStorageService } from '../../../../shared/services/auth-storage.service';
27 import { ModalService } from '../../../../shared/services/modal.service';
28 import { NotificationService } from '../../../../shared/services/notification.service';
29 import { PrometheusSilenceMatcherService } from '../../../../shared/services/prometheus-silence-matcher.service';
30 import { TimeDiffService } from '../../../../shared/services/time-diff.service';
31 import { SilenceMatcherModalComponent } from '../silence-matcher-modal/silence-matcher-modal.component';
34 selector: 'cd-prometheus-form',
35 templateUrl: './silence-form.component.html',
36 styleUrls: ['./silence-form.component.scss']
38 export class SilenceFormComponent {
40 permission: Permission;
42 rules: PrometheusRule[];
49 resource = this.i18n('silence');
51 matchers: AlertmanagerSilenceMatcher[] = [];
52 matcherMatch: AlertmanagerSilenceMatcherMatch = undefined;
55 tooltip: this.i18n('Attribute name'),
56 icon: this.icons.paragraph,
60 tooltip: this.i18n('Value'),
61 icon: this.icons.terminal,
65 tooltip: this.i18n('Regular expression'),
66 icon: this.icons.magic,
71 datetimeFormat = 'YYYY-MM-DD HH:mm';
75 private router: Router,
76 private authStorageService: AuthStorageService,
77 private formBuilder: CdFormBuilder,
78 private prometheusService: PrometheusService,
79 private notificationService: NotificationService,
80 private route: ActivatedRoute,
81 private timeDiff: TimeDiffService,
82 private modalService: ModalService,
83 private silenceMatcher: PrometheusSilenceMatcherService,
84 private actionLabels: ActionLabelsI18n,
85 private succeededLabels: SucceededActionLabelsI18n
98 private chooseMode() {
99 this.edit = this.router.url.startsWith('/monitoring/silences/edit');
100 this.recreate = this.router.url.startsWith('/monitoring/silences/recreate');
102 this.action = this.actionLabels.EDIT;
103 } else if (this.recreate) {
104 this.action = this.actionLabels.RECREATE;
106 this.action = this.actionLabels.CREATE;
110 private authenticate() {
111 this.permission = this.authStorageService.getPermissions().prometheus;
113 this.permission.read && (this.edit ? this.permission.update : this.permission.create);
115 this.router.navigate(['/404']);
119 private createForm() {
120 const formatValidator = CdValidators.custom('format', (expiresAt: string) => {
121 const result = expiresAt === '' || moment(expiresAt, this.datetimeFormat).isValid();
124 this.form = this.formBuilder.group(
126 startsAt: ['', [Validators.required, formatValidator]],
127 duration: ['2h', [Validators.min(1)]],
128 endsAt: ['', [Validators.required, formatValidator]],
129 createdBy: [this.authStorageService.getUsername(), [Validators.required]],
130 comment: [null, [Validators.required]]
133 validators: CdValidators.custom('matcherRequired', () => this.matchers.length === 0)
138 private setupDates() {
139 const now = moment().format(this.datetimeFormat);
140 this.form.silentSet('startsAt', now);
142 this.subscribeDateChanges();
145 private updateDate(updateStartDate?: boolean) {
146 const date = moment(this.form.getValue(updateStartDate ? 'endsAt' : 'startsAt')).toDate();
147 const next = this.timeDiff.calculateDate(date, this.form.getValue('duration'), updateStartDate);
149 const nextDate = moment(next).format(this.datetimeFormat);
150 this.form.silentSet(updateStartDate ? 'startsAt' : 'endsAt', nextDate);
154 private subscribeDateChanges() {
155 this.form.get('startsAt').valueChanges.subscribe(() => {
158 this.form.get('duration').valueChanges.subscribe(() => {
161 this.form.get('endsAt').valueChanges.subscribe(() => {
162 this.onDateChange(true);
166 private onDateChange(updateStartDate?: boolean) {
167 const startsAt = moment(this.form.getValue('startsAt'));
168 const endsAt = moment(this.form.getValue('endsAt'));
169 if (startsAt.isBefore(endsAt)) {
170 this.updateDuration();
172 this.updateDate(updateStartDate);
176 private updateDuration() {
177 const startsAt = moment(this.form.getValue('startsAt')).toDate();
178 const endsAt = moment(this.form.getValue('endsAt')).toDate();
179 this.form.silentSet('duration', this.timeDiff.calculateDuration(startsAt, endsAt));
184 this.getModeSpecificData();
188 this.prometheusService.ifPrometheusConfigured(
190 this.prometheusService.getRules().subscribe(
192 this.rules = groups['groups'].reduce(
193 (acc, group) => _.concat<PrometheusRule>(acc, group.rules),
198 this.prometheusService.disablePrometheusConfig();
204 this.notificationService.show(
205 NotificationType.info,
207 'Please add your Prometheus host to the dashboard configuration and refresh the page'
217 private getModeSpecificData() {
218 this.route.params.subscribe((params: { id: string }) => {
222 if (this.edit || this.recreate) {
223 this.prometheusService.getSilences(params).subscribe((silences) => {
224 this.fillFormWithSilence(silences[0]);
227 this.prometheusService.getAlerts(params).subscribe((alerts) => {
228 this.fillFormByAlert(alerts[0]);
234 private fillFormWithSilence(silence: AlertmanagerSilence) {
235 this.id = silence.id;
237 ['startsAt', 'endsAt'].forEach((attr) =>
238 this.form.silentSet(attr, moment(silence[attr]).format(this.datetimeFormat))
240 this.updateDuration();
242 ['createdBy', 'comment'].forEach((attr) => this.form.silentSet(attr, silence[attr]));
243 this.matchers = silence.matchers;
244 this.validateMatchers();
247 private validateMatchers() {
249 window.setTimeout(() => this.validateMatchers(), 100);
252 this.matcherMatch = this.silenceMatcher.multiMatch(this.matchers, this.rules);
253 this.form.markAsDirty();
254 this.form.updateValueAndValidity();
257 private fillFormByAlert(alert: AlertmanagerAlert) {
258 const labels = alert.labels;
259 Object.keys(labels).forEach((key) =>
268 private setMatcher(matcher: AlertmanagerSilenceMatcher, index?: number) {
269 if (_.isNumber(index)) {
270 this.matchers[index] = matcher;
272 this.matchers.push(matcher);
274 this.validateMatchers();
277 showMatcherModal(index?: number) {
278 const modalRef = this.modalService.show(SilenceMatcherModalComponent);
279 const modalComponent = modalRef.componentInstance as SilenceMatcherModalComponent;
280 modalComponent.rules = this.rules;
281 if (_.isNumber(index)) {
282 modalComponent.editMode = true;
283 modalComponent.preFillControls(this.matchers[index]);
285 modalComponent.submitAction.subscribe((matcher: AlertmanagerSilenceMatcher) => {
286 this.setMatcher(matcher, index);
290 deleteMatcher(index: number) {
291 this.matchers.splice(index, 1);
292 this.validateMatchers();
296 if (this.form.invalid) {
299 this.prometheusService.setSilence(this.getSubmitData()).subscribe(
301 this.router.navigate(['/monitoring/silences']);
302 this.notificationService.show(
303 NotificationType.success,
304 this.getNotificationTile(resp.body['silenceId']),
310 () => this.form.setErrors({ cdSubmitButton: true })
314 private getSubmitData(): AlertmanagerSilence {
315 const payload = this.form.value;
316 delete payload.duration;
317 payload.startsAt = moment(payload.startsAt, this.datetimeFormat).toISOString();
318 payload.endsAt = moment(payload.endsAt, this.datetimeFormat).toISOString();
319 payload.matchers = this.matchers;
321 payload.id = this.id;
326 private getNotificationTile(id: string) {
329 action = this.succeededLabels.EDITED;
330 } else if (this.recreate) {
331 action = this.succeededLabels.RECREATED;
333 action = this.succeededLabels.CREATED;
335 return `${action} ${this.resource} ${id}`;