]> git.apps.os.sepia.ceph.com Git - ceph.git/blob
d14d7debcce94db1ee1325fff75b1b56b0b16749
[ceph.git] /
1 import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
2 import { AbstractControl, FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
3 import { NgbActiveModal, NgbDateStruct, NgbTimeStruct } from '@ng-bootstrap/ng-bootstrap';
4 import { uniq } from 'lodash';
5 import { Observable, OperatorFunction, of, timer } from 'rxjs';
6 import { catchError, debounceTime, distinctUntilChanged, map, switchMap } from 'rxjs/operators';
7 import { CephfsSnapshotScheduleService } from '~/app/shared/api/cephfs-snapshot-schedule.service';
8 import { CephfsSubvolumeService } from '~/app/shared/api/cephfs-subvolume.service';
9 import { DirectoryStoreService } from '~/app/shared/api/directory-store.service';
10 import { ActionLabelsI18n, URLVerbs } from '~/app/shared/constants/app.constants';
11 import { Icons } from '~/app/shared/enum/icons.enum';
12 import { RepeatFrequency } from '~/app/shared/enum/repeat-frequency.enum';
13 import { RetentionFrequency } from '~/app/shared/enum/retention-frequency.enum';
14 import { CdForm } from '~/app/shared/forms/cd-form';
15 import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
16 import { CdTableColumn } from '~/app/shared/models/cd-table-column';
17 import { FinishedTask } from '~/app/shared/models/finished-task';
18 import {
19   RetentionPolicy,
20   SnapshotSchedule,
21   SnapshotScheduleFormValue
22 } from '~/app/shared/models/snapshot-schedule';
23 import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service';
24
25 const VALIDATON_TIMER = 300;
26 const DEBOUNCE_TIMER = 300;
27 const DEFAULT_SUBVOLUME_GROUP = '_nogroup';
28
29 @Component({
30   selector: 'cd-cephfs-snapshotschedule-form',
31   templateUrl: './cephfs-snapshotschedule-form.component.html',
32   styleUrls: ['./cephfs-snapshotschedule-form.component.scss']
33 })
34 export class CephfsSnapshotscheduleFormComponent extends CdForm implements OnInit {
35   fsName!: string;
36   path!: string;
37   schedule!: string;
38   retention!: string;
39   start!: string;
40   status!: string;
41   subvol!: string;
42   group!: string;
43   id!: number;
44   isEdit = false;
45   icons = Icons;
46   repeatFrequencies = Object.entries(RepeatFrequency);
47   retentionFrequencies = Object.entries(RetentionFrequency);
48   retentionPoliciesToRemove: RetentionPolicy[] = [];
49   isDefaultSubvolumeGroup = false;
50   subvolumeGroup!: string;
51   subvolume!: string;
52   isSubvolume = false;
53
54   currentTime!: NgbTimeStruct;
55   minDate!: NgbDateStruct;
56
57   snapScheduleForm!: CdFormGroup;
58
59   action!: string;
60   resource!: string;
61
62   columns!: CdTableColumn[];
63
64   constructor(
65     public activeModal: NgbActiveModal,
66     private actionLabels: ActionLabelsI18n,
67     private snapScheduleService: CephfsSnapshotScheduleService,
68     private taskWrapper: TaskWrapperService,
69     private cd: ChangeDetectorRef,
70     public directoryStore: DirectoryStoreService,
71     private subvolumeService: CephfsSubvolumeService
72   ) {
73     super();
74     this.resource = $localize`Snapshot schedule`;
75
76     const currentDatetime = new Date();
77     this.minDate = {
78       year: currentDatetime.getUTCFullYear(),
79       month: currentDatetime.getUTCMonth() + 1,
80       day: currentDatetime.getUTCDate()
81     };
82     this.currentTime = {
83       hour: currentDatetime.getUTCHours(),
84       minute: currentDatetime.getUTCMinutes(),
85       second: currentDatetime.getUTCSeconds()
86     };
87   }
88
89   ngOnInit(): void {
90     this.action = this.actionLabels.CREATE;
91     this.directoryStore.loadDirectories(this.id, '/', 3);
92     this.createForm();
93     this.isEdit ? this.populateForm() : this.loadingReady();
94     this.snapScheduleForm.get('directory').valueChanges.subscribe({
95       next: (value: string) => {
96         this.subvolumeGroup = value?.split?.('/')?.[2];
97         this.subvolume = value?.split?.('/')?.[3];
98         this.subvolumeService
99           .exists(
100             this.subvolume,
101             this.fsName,
102             this.subvolumeGroup === DEFAULT_SUBVOLUME_GROUP ? '' : this.subvolumeGroup
103           )
104           .subscribe({
105             next: (exists: boolean) => {
106               this.isSubvolume = exists;
107               this.isDefaultSubvolumeGroup =
108                 exists && this.subvolumeGroup === DEFAULT_SUBVOLUME_GROUP;
109             }
110           });
111       }
112     });
113   }
114
115   get retentionPolicies() {
116     return this.snapScheduleForm.get('retentionPolicies') as FormArray;
117   }
118
119   search: OperatorFunction<string, readonly string[]> = (input: Observable<string>) =>
120     input.pipe(
121       debounceTime(DEBOUNCE_TIMER),
122       distinctUntilChanged(),
123       switchMap((term) =>
124         this.directoryStore.search(term, this.id).pipe(
125           catchError(() => {
126             return of([]);
127           })
128         )
129       )
130     );
131
132   populateForm() {
133     this.action = this.actionLabels.EDIT;
134     this.snapScheduleService.getSnapshotSchedule(this.path, this.fsName, false).subscribe({
135       next: (response: SnapshotSchedule[]) => {
136         const first = response.find((x) => x.path === this.path);
137         this.snapScheduleForm.get('directory').disable();
138         this.snapScheduleForm.get('directory').setValue(first.path);
139         this.snapScheduleForm.get('startDate').disable();
140         this.snapScheduleForm.get('startDate').setValue({
141           year: new Date(first.start).getUTCFullYear(),
142           month: new Date(first.start).getUTCMonth() + 1,
143           day: new Date(first.start).getUTCDate()
144         });
145         this.snapScheduleForm.get('startTime').disable();
146         this.snapScheduleForm.get('startTime').setValue({
147           hour: new Date(first.start).getUTCHours(),
148           minute: new Date(first.start).getUTCMinutes(),
149           second: new Date(first.start).getUTCSeconds()
150         });
151         this.snapScheduleForm.get('repeatInterval').disable();
152         this.snapScheduleForm.get('repeatInterval').setValue(first.schedule.split('')?.[0]);
153         this.snapScheduleForm.get('repeatFrequency').disable();
154         this.snapScheduleForm.get('repeatFrequency').setValue(first.schedule.split('')?.[1]);
155
156         // retention policies
157         first.retention &&
158           Object.entries(first.retention).forEach(([frequency, interval], idx) => {
159             const freqKey = Object.keys(RetentionFrequency)[
160               Object.values(RetentionFrequency).indexOf(frequency as any)
161             ];
162             this.retentionPolicies.push(
163               new FormGroup({
164                 retentionInterval: new FormControl(interval),
165                 retentionFrequency: new FormControl(RetentionFrequency[freqKey])
166               })
167             );
168             this.retentionPolicies.controls[idx].get('retentionInterval').disable();
169             this.retentionPolicies.controls[idx].get('retentionFrequency').disable();
170           });
171         this.loadingReady();
172       }
173     });
174   }
175
176   createForm() {
177     this.snapScheduleForm = new CdFormGroup(
178       {
179         directory: new FormControl(undefined, {
180           updateOn: 'blur',
181           validators: [Validators.required]
182         }),
183         startDate: new FormControl(this.minDate, {
184           validators: [Validators.required]
185         }),
186         startTime: new FormControl(this.currentTime, {
187           validators: [Validators.required]
188         }),
189         repeatInterval: new FormControl(1, {
190           validators: [Validators.required, Validators.min(1)]
191         }),
192         repeatFrequency: new FormControl(RepeatFrequency.Daily, {
193           validators: [Validators.required]
194         }),
195         retentionPolicies: new FormArray([])
196       },
197       {
198         asyncValidators: [this.validateSchedule(), this.validateRetention()]
199       }
200     );
201   }
202
203   addRetentionPolicy() {
204     this.retentionPolicies.push(
205       new FormGroup({
206         retentionInterval: new FormControl(1),
207         retentionFrequency: new FormControl(RetentionFrequency.Daily)
208       })
209     );
210     this.cd.detectChanges();
211   }
212
213   removeRetentionPolicy(idx: number) {
214     if (this.isEdit && this.retentionPolicies.at(idx).disabled) {
215       const values = this.retentionPolicies.at(idx).value as RetentionPolicy;
216       this.retentionPoliciesToRemove.push(values);
217     }
218     this.retentionPolicies.removeAt(idx);
219     this.retentionPolicies.controls.forEach((x) =>
220       x.get('retentionFrequency').updateValueAndValidity()
221     );
222     this.cd.detectChanges();
223   }
224
225   parseDatetime(date: NgbDateStruct, time?: NgbTimeStruct): string {
226     if (!date || !time) return null;
227     return `${date.year}-${date.month}-${date.day}T${time.hour || '00'}:${time.minute || '00'}:${
228       time.second || '00'
229     }`;
230   }
231   parseSchedule(interval: number, frequency: string): string {
232     return `${interval}${frequency}`;
233   }
234
235   parseRetentionPolicies(retentionPolicies: RetentionPolicy[]) {
236     return retentionPolicies
237       ?.filter((r) => r?.retentionInterval !== null && r?.retentionFrequency !== null)
238       ?.map?.((r) => `${r.retentionInterval}-${r.retentionFrequency}`)
239       .join('|');
240   }
241
242   submit() {
243     if (this.snapScheduleForm.invalid) {
244       this.snapScheduleForm.setErrors({ cdSubmitButton: true });
245       return;
246     }
247
248     const values = this.snapScheduleForm.value as SnapshotScheduleFormValue;
249
250     if (this.isEdit) {
251       const retentionPoliciesToAdd = (this.snapScheduleForm.get(
252         'retentionPolicies'
253       ) as FormArray).controls
254         ?.filter(
255           (ctrl) =>
256             !ctrl.get('retentionInterval').disabled && !ctrl.get('retentionFrequency').disabled
257         )
258         .map((ctrl) => ({
259           retentionInterval: ctrl.get('retentionInterval').value,
260           retentionFrequency: ctrl.get('retentionFrequency').value
261         }));
262
263       const updateObj = {
264         fs: this.fsName,
265         path: this.path,
266         subvol: this.subvol,
267         group: this.group,
268         retention_to_add: this.parseRetentionPolicies(retentionPoliciesToAdd) || null,
269         retention_to_remove: this.parseRetentionPolicies(this.retentionPoliciesToRemove) || null
270       };
271
272       this.taskWrapper
273         .wrapTaskAroundCall({
274           task: new FinishedTask('cephfs/snapshot/schedule/' + URLVerbs.EDIT, {
275             path: this.path
276           }),
277           call: this.snapScheduleService.update(updateObj)
278         })
279         .subscribe({
280           error: () => {
281             this.snapScheduleForm.setErrors({ cdSubmitButton: true });
282           },
283           complete: () => {
284             this.activeModal.close();
285           }
286         });
287     } else {
288       const snapScheduleObj = {
289         fs: this.fsName,
290         path: values.directory,
291         snap_schedule: this.parseSchedule(values?.repeatInterval, values?.repeatFrequency),
292         start: this.parseDatetime(values?.startDate, values?.startTime)
293       };
294
295       const retentionPoliciesValues = this.parseRetentionPolicies(values?.retentionPolicies);
296
297       if (retentionPoliciesValues) snapScheduleObj['retention_policy'] = retentionPoliciesValues;
298
299       if (this.isSubvolume) snapScheduleObj['subvol'] = this.subvolume;
300
301       if (this.isSubvolume && !this.isDefaultSubvolumeGroup) {
302         snapScheduleObj['group'] = this.subvolumeGroup;
303       }
304
305       this.taskWrapper
306         .wrapTaskAroundCall({
307           task: new FinishedTask('cephfs/snapshot/schedule/' + URLVerbs.CREATE, {
308             path: snapScheduleObj.path
309           }),
310           call: this.snapScheduleService.create(snapScheduleObj)
311         })
312         .subscribe({
313           error: () => {
314             this.snapScheduleForm.setErrors({ cdSubmitButton: true });
315           },
316           complete: () => {
317             this.activeModal.close();
318           }
319         });
320     }
321   }
322
323   validateSchedule() {
324     return (frm: AbstractControl) => {
325       const directory = frm.get('directory');
326       const repeatFrequency = frm.get('repeatFrequency');
327       const repeatInterval = frm.get('repeatInterval');
328
329       if (this.isEdit) {
330         return of(null);
331       }
332
333       return timer(VALIDATON_TIMER).pipe(
334         switchMap(() =>
335           this.snapScheduleService
336             .checkScheduleExists(
337               directory?.value,
338               this.fsName,
339               repeatInterval?.value,
340               repeatFrequency?.value
341             )
342             .pipe(
343               map((exists: boolean) => {
344                 if (exists) {
345                   repeatFrequency?.setErrors({ notUnique: true }, { emitEvent: true });
346                 } else {
347                   repeatFrequency?.setErrors(null);
348                 }
349                 return null;
350               })
351             )
352         )
353       );
354     };
355   }
356
357   getFormArrayItem(frm: FormGroup, frmArrayName: string, ctrl: string, idx: number) {
358     return (frm.get(frmArrayName) as FormArray)?.controls?.[idx]?.get?.(ctrl);
359   }
360
361   validateRetention() {
362     return (frm: FormGroup) => {
363       return timer(VALIDATON_TIMER).pipe(
364         switchMap(() => {
365           const retentionList = (frm.get('retentionPolicies') as FormArray).controls?.map(
366             (ctrl) => {
367               return ctrl.get('retentionFrequency').value;
368             }
369           );
370           if (uniq(retentionList)?.length !== retentionList?.length) {
371             this.getFormArrayItem(
372               frm,
373               'retentionPolicies',
374               'retentionFrequency',
375               retentionList.length - 1
376             )?.setErrors?.({
377               notUnique: true
378             });
379             return null;
380           }
381           return this.snapScheduleService
382             .checkRetentionPolicyExists(
383               frm.get('directory').value,
384               this.fsName,
385               retentionList,
386               this.retentionPoliciesToRemove?.map?.((rp) => rp.retentionFrequency) || []
387             )
388             .pipe(
389               map(({ exists, errorIndex }) => {
390                 if (exists) {
391                   this.getFormArrayItem(
392                     frm,
393                     'retentionPolicies',
394                     'retentionFrequency',
395                     errorIndex
396                   )?.setErrors?.({ notUnique: true });
397                 } else {
398                   (frm.get('retentionPolicies') as FormArray).controls?.forEach?.((_, i) => {
399                     this.getFormArrayItem(
400                       frm,
401                       'retentionPolicies',
402                       'retentionFrequency',
403                       i
404                     )?.setErrors?.(null);
405                   });
406                 }
407                 return null;
408               })
409             );
410         })
411       );
412     };
413   }
414 }