]> git.apps.os.sepia.ceph.com Git - ceph.git/blob
076c99014a6b7a65608fafa1f81c50d9dd8bd000
[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 { padStart, 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}-${padStart(date.month.toString(), 2, '0')}-${padStart(
228       date.day.toString(),
229       2,
230       '0'
231     )}T${time.hour || '00'}:${time.minute || '00'}:${time.second || '00'}`;
232   }
233   parseSchedule(interval: number, frequency: string): string {
234     return `${interval}${frequency}`;
235   }
236
237   parseRetentionPolicies(retentionPolicies: RetentionPolicy[]) {
238     return retentionPolicies
239       ?.filter((r) => r?.retentionInterval !== null && r?.retentionFrequency !== null)
240       ?.map?.((r) => `${r.retentionInterval}-${r.retentionFrequency}`)
241       .join('|');
242   }
243
244   submit() {
245     if (this.snapScheduleForm.invalid) {
246       this.snapScheduleForm.setErrors({ cdSubmitButton: true });
247       return;
248     }
249
250     const values = this.snapScheduleForm.value as SnapshotScheduleFormValue;
251
252     if (this.isEdit) {
253       const retentionPoliciesToAdd = (this.snapScheduleForm.get(
254         'retentionPolicies'
255       ) as FormArray).controls
256         ?.filter(
257           (ctrl) =>
258             !ctrl.get('retentionInterval').disabled && !ctrl.get('retentionFrequency').disabled
259         )
260         .map((ctrl) => ({
261           retentionInterval: ctrl.get('retentionInterval').value,
262           retentionFrequency: ctrl.get('retentionFrequency').value
263         }));
264
265       const updateObj = {
266         fs: this.fsName,
267         path: this.path,
268         subvol: this.subvol,
269         group: this.group,
270         retention_to_add: this.parseRetentionPolicies(retentionPoliciesToAdd) || null,
271         retention_to_remove: this.parseRetentionPolicies(this.retentionPoliciesToRemove) || null
272       };
273
274       this.taskWrapper
275         .wrapTaskAroundCall({
276           task: new FinishedTask('cephfs/snapshot/schedule/' + URLVerbs.EDIT, {
277             path: this.path
278           }),
279           call: this.snapScheduleService.update(updateObj)
280         })
281         .subscribe({
282           error: () => {
283             this.snapScheduleForm.setErrors({ cdSubmitButton: true });
284           },
285           complete: () => {
286             this.activeModal.close();
287           }
288         });
289     } else {
290       const snapScheduleObj = {
291         fs: this.fsName,
292         path: values.directory,
293         snap_schedule: this.parseSchedule(values?.repeatInterval, values?.repeatFrequency),
294         start: this.parseDatetime(values?.startDate, values?.startTime)
295       };
296
297       const retentionPoliciesValues = this.parseRetentionPolicies(values?.retentionPolicies);
298
299       if (retentionPoliciesValues) snapScheduleObj['retention_policy'] = retentionPoliciesValues;
300
301       if (this.isSubvolume) snapScheduleObj['subvol'] = this.subvolume;
302
303       if (this.isSubvolume && !this.isDefaultSubvolumeGroup) {
304         snapScheduleObj['group'] = this.subvolumeGroup;
305       }
306
307       this.taskWrapper
308         .wrapTaskAroundCall({
309           task: new FinishedTask('cephfs/snapshot/schedule/' + URLVerbs.CREATE, {
310             path: snapScheduleObj.path
311           }),
312           call: this.snapScheduleService.create(snapScheduleObj)
313         })
314         .subscribe({
315           error: () => {
316             this.snapScheduleForm.setErrors({ cdSubmitButton: true });
317           },
318           complete: () => {
319             this.activeModal.close();
320           }
321         });
322     }
323   }
324
325   validateSchedule() {
326     return (frm: AbstractControl) => {
327       const directory = frm.get('directory');
328       const repeatFrequency = frm.get('repeatFrequency');
329       const repeatInterval = frm.get('repeatInterval');
330
331       if (this.isEdit) {
332         return of(null);
333       }
334
335       return timer(VALIDATON_TIMER).pipe(
336         switchMap(() =>
337           this.snapScheduleService
338             .checkScheduleExists(
339               directory?.value,
340               this.fsName,
341               repeatInterval?.value,
342               repeatFrequency?.value
343             )
344             .pipe(
345               map((exists: boolean) => {
346                 if (exists) {
347                   repeatFrequency?.setErrors({ notUnique: true }, { emitEvent: true });
348                 } else {
349                   repeatFrequency?.setErrors(null);
350                 }
351                 return null;
352               })
353             )
354         )
355       );
356     };
357   }
358
359   getFormArrayItem(frm: FormGroup, frmArrayName: string, ctrl: string, idx: number) {
360     return (frm.get(frmArrayName) as FormArray)?.controls?.[idx]?.get?.(ctrl);
361   }
362
363   validateRetention() {
364     return (frm: FormGroup) => {
365       return timer(VALIDATON_TIMER).pipe(
366         switchMap(() => {
367           const retentionList = (frm.get('retentionPolicies') as FormArray).controls?.map(
368             (ctrl) => {
369               return ctrl.get('retentionFrequency').value;
370             }
371           );
372           if (uniq(retentionList)?.length !== retentionList?.length) {
373             this.getFormArrayItem(
374               frm,
375               'retentionPolicies',
376               'retentionFrequency',
377               retentionList.length - 1
378             )?.setErrors?.({
379               notUnique: true
380             });
381             return null;
382           }
383           return this.snapScheduleService
384             .checkRetentionPolicyExists(
385               frm.get('directory').value,
386               this.fsName,
387               retentionList,
388               this.retentionPoliciesToRemove?.map?.((rp) => rp.retentionFrequency) || []
389             )
390             .pipe(
391               map(({ exists, errorIndex }) => {
392                 if (exists) {
393                   this.getFormArrayItem(
394                     frm,
395                     'retentionPolicies',
396                     'retentionFrequency',
397                     errorIndex
398                   )?.setErrors?.({ notUnique: true });
399                 } else {
400                   (frm.get('retentionPolicies') as FormArray).controls?.forEach?.((_, i) => {
401                     this.getFormArrayItem(
402                       frm,
403                       'retentionPolicies',
404                       'retentionFrequency',
405                       i
406                     )?.setErrors?.(null);
407                   });
408                 }
409                 return null;
410               })
411             );
412         })
413       );
414     };
415   }
416 }