]> git.apps.os.sepia.ceph.com Git - ceph-ci.git/blob
bcbb8517016148d29f34dc2a9748b63ee2e0be95
[ceph-ci.git] /
1 import { Component } from '@angular/core';
2 import { Validators } from '@angular/forms';
3 import { ActivatedRoute, Router } from '@angular/router';
4
5 import { I18n } from '@ngx-translate/i18n-polyfill';
6 import * as _ from 'lodash';
7 import * as moment from 'moment';
8
9 import { PrometheusService } from '../../../../shared/api/prometheus.service';
10 import {
11   ActionLabelsI18n,
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';
19 import {
20   AlertmanagerSilence,
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';
32
33 @Component({
34   selector: 'cd-prometheus-form',
35   templateUrl: './silence-form.component.html',
36   styleUrls: ['./silence-form.component.scss']
37 })
38 export class SilenceFormComponent {
39   icons = Icons;
40   permission: Permission;
41   form: CdFormGroup;
42   rules: PrometheusRule[];
43
44   recreate = false;
45   edit = false;
46   id: string;
47
48   action: string;
49   resource = this.i18n('silence');
50
51   matchers: AlertmanagerSilenceMatcher[] = [];
52   matcherMatch: AlertmanagerSilenceMatcherMatch = undefined;
53   matcherConfig = [
54     {
55       tooltip: this.i18n('Attribute name'),
56       icon: this.icons.paragraph,
57       attribute: 'name'
58     },
59     {
60       tooltip: this.i18n('Value'),
61       icon: this.icons.terminal,
62       attribute: 'value'
63     },
64     {
65       tooltip: this.i18n('Regular expression'),
66       icon: this.icons.magic,
67       attribute: 'isRegex'
68     }
69   ];
70
71   datetimeFormat = 'YYYY-MM-DD HH:mm';
72
73   constructor(
74     private i18n: I18n,
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
86   ) {
87     this.init();
88   }
89
90   private init() {
91     this.chooseMode();
92     this.authenticate();
93     this.createForm();
94     this.setupDates();
95     this.getData();
96   }
97
98   private chooseMode() {
99     this.edit = this.router.url.startsWith('/monitoring/silences/edit');
100     this.recreate = this.router.url.startsWith('/monitoring/silences/recreate');
101     if (this.edit) {
102       this.action = this.actionLabels.EDIT;
103     } else if (this.recreate) {
104       this.action = this.actionLabels.RECREATE;
105     } else {
106       this.action = this.actionLabels.CREATE;
107     }
108   }
109
110   private authenticate() {
111     this.permission = this.authStorageService.getPermissions().prometheus;
112     const allowed =
113       this.permission.read && (this.edit ? this.permission.update : this.permission.create);
114     if (!allowed) {
115       this.router.navigate(['/404']);
116     }
117   }
118
119   private createForm() {
120     const formatValidator = CdValidators.custom('format', (expiresAt: string) => {
121       const result = expiresAt === '' || moment(expiresAt, this.datetimeFormat).isValid();
122       return !result;
123     });
124     this.form = this.formBuilder.group(
125       {
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]]
131       },
132       {
133         validators: CdValidators.custom('matcherRequired', () => this.matchers.length === 0)
134       }
135     );
136   }
137
138   private setupDates() {
139     const now = moment().format(this.datetimeFormat);
140     this.form.silentSet('startsAt', now);
141     this.updateDate();
142     this.subscribeDateChanges();
143   }
144
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);
148     if (next) {
149       const nextDate = moment(next).format(this.datetimeFormat);
150       this.form.silentSet(updateStartDate ? 'startsAt' : 'endsAt', nextDate);
151     }
152   }
153
154   private subscribeDateChanges() {
155     this.form.get('startsAt').valueChanges.subscribe(() => {
156       this.onDateChange();
157     });
158     this.form.get('duration').valueChanges.subscribe(() => {
159       this.updateDate();
160     });
161     this.form.get('endsAt').valueChanges.subscribe(() => {
162       this.onDateChange(true);
163     });
164   }
165
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();
171     } else {
172       this.updateDate(updateStartDate);
173     }
174   }
175
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));
180   }
181
182   private getData() {
183     this.getRules();
184     this.getModeSpecificData();
185   }
186
187   private getRules() {
188     this.prometheusService.ifPrometheusConfigured(
189       () =>
190         this.prometheusService.getRules().subscribe(
191           (groups) => {
192             this.rules = groups['groups'].reduce(
193               (acc, group) => _.concat<PrometheusRule>(acc, group.rules),
194               []
195             );
196           },
197           () => {
198             this.prometheusService.disablePrometheusConfig();
199             this.rules = [];
200           }
201         ),
202       () => {
203         this.rules = [];
204         this.notificationService.show(
205           NotificationType.info,
206           this.i18n(
207             'Please add your Prometheus host to the dashboard configuration and refresh the page'
208           ),
209           undefined,
210           undefined,
211           'Prometheus'
212         );
213       }
214     );
215   }
216
217   private getModeSpecificData() {
218     this.route.params.subscribe((params: { id: string }) => {
219       if (!params.id) {
220         return;
221       }
222       if (this.edit || this.recreate) {
223         this.prometheusService.getSilences(params).subscribe((silences) => {
224           this.fillFormWithSilence(silences[0]);
225         });
226       } else {
227         this.prometheusService.getAlerts(params).subscribe((alerts) => {
228           this.fillFormByAlert(alerts[0]);
229         });
230       }
231     });
232   }
233
234   private fillFormWithSilence(silence: AlertmanagerSilence) {
235     this.id = silence.id;
236     if (this.edit) {
237       ['startsAt', 'endsAt'].forEach((attr) =>
238         this.form.silentSet(attr, moment(silence[attr]).format(this.datetimeFormat))
239       );
240       this.updateDuration();
241     }
242     ['createdBy', 'comment'].forEach((attr) => this.form.silentSet(attr, silence[attr]));
243     this.matchers = silence.matchers;
244     this.validateMatchers();
245   }
246
247   private validateMatchers() {
248     if (!this.rules) {
249       window.setTimeout(() => this.validateMatchers(), 100);
250       return;
251     }
252     this.matcherMatch = this.silenceMatcher.multiMatch(this.matchers, this.rules);
253     this.form.markAsDirty();
254     this.form.updateValueAndValidity();
255   }
256
257   private fillFormByAlert(alert: AlertmanagerAlert) {
258     const labels = alert.labels;
259     Object.keys(labels).forEach((key) =>
260       this.setMatcher({
261         name: key,
262         value: labels[key],
263         isRegex: false
264       })
265     );
266   }
267
268   private setMatcher(matcher: AlertmanagerSilenceMatcher, index?: number) {
269     if (_.isNumber(index)) {
270       this.matchers[index] = matcher;
271     } else {
272       this.matchers.push(matcher);
273     }
274     this.validateMatchers();
275   }
276
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]);
284     }
285     modalComponent.submitAction.subscribe((matcher: AlertmanagerSilenceMatcher) => {
286       this.setMatcher(matcher, index);
287     });
288   }
289
290   deleteMatcher(index: number) {
291     this.matchers.splice(index, 1);
292     this.validateMatchers();
293   }
294
295   submit() {
296     if (this.form.invalid) {
297       return;
298     }
299     this.prometheusService.setSilence(this.getSubmitData()).subscribe(
300       (resp) => {
301         this.router.navigate(['/monitoring/silences']);
302         this.notificationService.show(
303           NotificationType.success,
304           this.getNotificationTile(resp.body['silenceId']),
305           undefined,
306           undefined,
307           'Prometheus'
308         );
309       },
310       () => this.form.setErrors({ cdSubmitButton: true })
311     );
312   }
313
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;
320     if (this.edit) {
321       payload.id = this.id;
322     }
323     return payload;
324   }
325
326   private getNotificationTile(id: string) {
327     let action;
328     if (this.edit) {
329       action = this.succeededLabels.EDITED;
330     } else if (this.recreate) {
331       action = this.succeededLabels.RECREATED;
332     } else {
333       action = this.succeededLabels.CREATED;
334     }
335     return `${action} ${this.resource} ${id}`;
336   }
337 }