All files / src/app/ceph/cluster/prometheus/silence-form silence-form.component.ts

97.75% Statements 174/178
84.09% Branches 74/88
95.12% Functions 39/41
98.17% Lines 161/164

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 3296x 6x 6x 6x   6x 6x   6x 6x       6x 6x 6x   6x               6x 6x 6x 6x 6x             6x 38x           38x   38x 38x       38x   38x 38x 38x                                     38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x   38x     6x 54x 54x 54x 54x 54x     6x 54x 54x 54x 4x 50x 3x   47x       6x 54x   54x 54x 50x       54x 54x                 516x         6x 54x 54x 54x 54x 54x     6x 61x         61x 59x       54x 54x 4x   54x 2x   54x 3x       6x 7x 2x   5x       6x 3x           6x 54x 54x     54x 54x   53x 52x   1x 1x       1x 1x                         54x 54x 54x 51x   3x 2x 2x     1x 1x           6x 2x 2x 2x 1x   4x 2x 2x     36x 36x       36x 36x 36x     6x 1x 1x 4x               6x 32x 1x   31x   32x     6x 1x 1x 1x 1x 1x 1x   1x 1x       6x 2x 2x     6x 5x 1x   4x   4x 4x                       6x 4x 4x 4x 4x 4x 4x 1x   4x     6x   4x 1x 3x 1x   2x   4x   6x  
import { Component } from '@angular/core';
import { Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { I18n } from '@ngx-translate/i18n-polyfill';
 
import * as _ from 'lodash';
import { BsModalService } from 'ngx-bootstrap/modal';
 
import { PrometheusService } from '../../../../shared/api/prometheus.service';
import {
  ActionLabelsI18n,
  SucceededActionLabelsI18n
} from '../../../../shared/constants/app.constants';
import { Icons } from '../../../../shared/enum/icons.enum';
import { NotificationType } from '../../../../shared/enum/notification-type.enum';
import { CdFormBuilder } from '../../../../shared/forms/cd-form-builder';
import { CdFormGroup } from '../../../../shared/forms/cd-form-group';
import { CdValidators } from '../../../../shared/forms/cd-validators';
import {
  AlertmanagerSilence,
  AlertmanagerSilenceMatcher,
  AlertmanagerSilenceMatcherMatch
} from '../../../../shared/models/alertmanager-silence';
import { Permission } from '../../../../shared/models/permissions';
import { AlertmanagerAlert, PrometheusRule } from '../../../../shared/models/prometheus-alerts';
import { AuthStorageService } from '../../../../shared/services/auth-storage.service';
import { NotificationService } from '../../../../shared/services/notification.service';
import { PrometheusSilenceMatcherService } from '../../../../shared/services/prometheus-silence-matcher.service';
import { TimeDiffService } from '../../../../shared/services/time-diff.service';
import { SilenceMatcherModalComponent } from '../silence-matcher-modal/silence-matcher-modal.component';
 
@Component({
  selector: 'cd-prometheus-form',
  template: require('./silence-form.component.html'),
  styles: []
})
export class SilenceFormComponent {
  icons = Icons;
  permission: Permission;
  form: CdFormGroup;
  rules: PrometheusRule[];
 
  // Date formatting rules can be found here: https://momentjs.com/docs/#/displaying/format/
  bsConfig = { dateInputFormat: 'YYYY-MM-DDT HH:mm' };
 
  recreate = false;
  edit = false;
  id: string;
 
  action: string;
  resource = this.i18n('silence');
 
  matchers: AlertmanagerSilenceMatcher[] = [];
  matcherMatch: AlertmanagerSilenceMatcherMatch = undefined;
  matcherConfig = [
    {
      tooltip: this.i18n('Attribute name'),
      icon: this.icons.paragraph,
      attribute: 'name'
    },
    {
      tooltip: this.i18n('Value'),
      icon: this.icons.terminal,
      attribute: 'value'
    },
    {
      tooltip: this.i18n('Regular expression'),
      icon: this.icons.magic,
      attribute: 'isRegex'
    }
  ];
 
  constructor(
    private i18n: I18n,
    private router: Router,
    private authStorageService: AuthStorageService,
    private formBuilder: CdFormBuilder,
    private prometheusService: PrometheusService,
    private notificationService: NotificationService,
    private route: ActivatedRoute,
    private timeDiff: TimeDiffService,
    private bsModalService: BsModalService,
    private silenceMatcher: PrometheusSilenceMatcherService,
    private actionLabels: ActionLabelsI18n,
    private succeededLabels: SucceededActionLabelsI18n
  ) {
    this.init();
  }
 
  private init() {
    this.chooseMode();
    this.authenticate();
    this.createForm();
    this.setupDates();
    this.getData();
  }
 
  private chooseMode() {
    this.edit = this.router.url.startsWith('/silence/edit');
    this.recreate = this.router.url.startsWith('/silence/recreate');
    if (this.edit) {
      this.action = this.actionLabels.EDIT;
    } else if (this.recreate) {
      this.action = this.actionLabels.RECREATE;
    } else {
      this.action = this.actionLabels.CREATE;
    }
  }
 
  private authenticate() {
    this.permission = this.authStorageService.getPermissions().prometheus;
    const allowed =
      this.permission.read && (this.edit ? this.permission.update : this.permission.create);
    if (!allowed) {
      this.router.navigate(['/404']);
    }
  }
 
  private createForm() {
    this.form = this.formBuilder.group(
      {
        startsAt: [null, [Validators.required]],
        duration: ['2h', [Validators.min(1)]],
        endsAt: [null, [Validators.required]],
        createdBy: [this.authStorageService.getUsername(), [Validators.required]],
        comment: [null, [Validators.required]]
      },
      {
        validators: CdValidators.custom('matcherRequired', () => this.matchers.length === 0)
      }
    );
  }
 
  private setupDates() {
    const now = new Date();
    now.setSeconds(0, 0); // Normalizes start date
    this.form.silentSet('startsAt', now);
    this.updateDate();
    this.subscribeDateChanges();
  }
 
  private updateDate(updateStartDate?: boolean) {
    const next = this.timeDiff.calculateDate(
      this.form.getValue(updateStartDate ? 'endsAt' : 'startsAt'),
      this.form.getValue('duration'),
      updateStartDate
    );
    if (next) {
      this.form.silentSet(updateStartDate ? 'startsAt' : 'endsAt', next);
    }
  }
 
  private subscribeDateChanges() {
    this.form.get('startsAt').valueChanges.subscribe(() => {
      this.onDateChange();
    });
    this.form.get('duration').valueChanges.subscribe(() => {
      this.updateDate();
    });
    this.form.get('endsAt').valueChanges.subscribe(() => {
      this.onDateChange(true);
    });
  }
 
  private onDateChange(updateStartDate?: boolean) {
    if (this.form.getValue('startsAt') < this.form.getValue('endsAt')) {
      this.updateDuration();
    } else {
      this.updateDate(updateStartDate);
    }
  }
 
  private updateDuration() {
    this.form.silentSet(
      'duration',
      this.timeDiff.calculateDuration(this.form.getValue('startsAt'), this.form.getValue('endsAt'))
    );
  }
 
  private getData() {
    this.getRules();
    this.getModeSpecificData();
  }
 
  private getRules() {
    this.prometheusService.ifPrometheusConfigured(
      () =>
        this.prometheusService.getRules().subscribe(
          (rules) => (this.rules = rules),
          () => {
            this.prometheusService.disablePrometheusConfig();
            this.rules = [];
          }
        ),
      () => {
        this.rules = [];
        this.notificationService.show(
          NotificationType.info,
          this.i18n(
            'Please add your Prometheus host to the dashboard configuration and refresh the page'
          ),
          undefined,
          undefined,
          'Prometheus'
        );
      }
    );
  }
 
  private getModeSpecificData() {
    this.route.params.subscribe((params: { id: string }) => {
      if (!params.id) {
        return;
      }
      if (this.edit || this.recreate) {
        this.prometheusService.getSilences(params).subscribe((silences) => {
          this.fillFormWithSilence(silences[0]);
        });
      } else {
        this.prometheusService.getAlerts(params).subscribe((alerts) => {
          this.fillFormByAlert(alerts[0]);
        });
      }
    });
  }
 
  private fillFormWithSilence(silence: AlertmanagerSilence) {
    this.id = silence.id;
    if (this.edit) {
      ['startsAt', 'endsAt'].forEach((attr) => this.form.silentSet(attr, new Date(silence[attr])));
      this.updateDuration();
    }
    ['createdBy', 'comment'].forEach((attr) => this.form.silentSet(attr, silence[attr]));
    this.matchers = silence.matchers;
    this.validateMatchers();
  }
 
  private validateMatchers() {
    Iif (!this.rules) {
      window.setTimeout(() => this.validateMatchers(), 100);
      return;
    }
    this.matcherMatch = this.silenceMatcher.multiMatch(this.matchers, this.rules);
    this.form.markAsDirty();
    this.form.updateValueAndValidity();
  }
 
  private fillFormByAlert(alert: AlertmanagerAlert) {
    const labels = alert.labels;
    Object.keys(labels).forEach((key) =>
      this.setMatcher({
        name: key,
        value: labels[key],
        isRegex: false
      })
    );
  }
 
  private setMatcher(matcher: AlertmanagerSilenceMatcher, index?: number) {
    if (_.isNumber(index)) {
      this.matchers[index] = matcher;
    } else {
      this.matchers.push(matcher);
    }
    this.validateMatchers();
  }
 
  showMatcherModal(index?: number) {
    const modalRef = this.bsModalService.show(SilenceMatcherModalComponent);
    const modal = modalRef.content as SilenceMatcherModalComponent;
    modal.rules = this.rules;
    Eif (_.isNumber(index)) {
      modal.editMode = true;
      modal.preFillControls(this.matchers[index]);
    }
    modalRef.content.submitAction.subscribe((matcher: AlertmanagerSilenceMatcher) => {
      this.setMatcher(matcher, index);
    });
  }
 
  deleteMatcher(index: number) {
    this.matchers.splice(index, 1);
    this.validateMatchers();
  }
 
  submit() {
    if (this.form.invalid) {
      return;
    }
    this.prometheusService.setSilence(this.getSubmitData()).subscribe(
      (resp) => {
        this.router.navigate(['/silence']);
        this.notificationService.show(
          NotificationType.success,
          this.getNotificationTile(resp.body['silenceId']),
          undefined,
          undefined,
          'Prometheus'
        );
      },
      () => this.form.setErrors({ cdSubmitButton: true })
    );
  }
 
  private getSubmitData(): AlertmanagerSilence {
    const payload = this.form.value;
    delete payload.duration;
    payload.startsAt = payload.startsAt.toISOString();
    payload.endsAt = payload.endsAt.toISOString();
    payload.matchers = this.matchers;
    if (this.edit) {
      payload.id = this.id;
    }
    return payload;
  }
 
  private getNotificationTile(id: string) {
    let action;
    if (this.edit) {
      action = this.succeededLabels.EDITED;
    } else if (this.recreate) {
      action = this.succeededLabels.RECREATED;
    } else {
      action = this.succeededLabels.CREATED;
    }
    return `${action} ${this.resource} ${id}`;
  }
}