]> git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-form/nfs-form.component.ts
a56c1105e08e49c2b89b9ac41fb5c7b9faec0d61
[ceph.git] / ceph / src / pybind / mgr / dashboard / frontend / src / app / ceph / nfs / nfs-form / nfs-form.component.ts
1 import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
2 import {
3 AbstractControl,
4 AsyncValidatorFn,
5 FormControl,
6 ValidationErrors,
7 Validators
8 } from '@angular/forms';
9 import { ActivatedRoute, Router } from '@angular/router';
10
11 import _ from 'lodash';
12 import { forkJoin, Observable, of } from 'rxjs';
13 import { catchError, debounceTime, distinctUntilChanged, map, mergeMap } from 'rxjs/operators';
14
15 import { NfsFSAbstractionLayer } from '~/app/ceph/nfs/models/nfs.fsal';
16 import { Directory, NfsService } from '~/app/shared/api/nfs.service';
17 import { RgwBucketService } from '~/app/shared/api/rgw-bucket.service';
18 import { RgwSiteService } from '~/app/shared/api/rgw-site.service';
19 import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
20 import { Icons } from '~/app/shared/enum/icons.enum';
21 import { CdForm } from '~/app/shared/forms/cd-form';
22 import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
23 import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
24 import { CdValidators } from '~/app/shared/forms/cd-validators';
25 import { FinishedTask } from '~/app/shared/models/finished-task';
26 import { Permission } from '~/app/shared/models/permissions';
27 import { CdHttpErrorResponse } from '~/app/shared/services/api-interceptor.service';
28 import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
29 import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service';
30 import { NfsFormClientComponent } from '../nfs-form-client/nfs-form-client.component';
31
32 @Component({
33 selector: 'cd-nfs-form',
34 templateUrl: './nfs-form.component.html',
35 styleUrls: ['./nfs-form.component.scss']
36 })
37 export class NfsFormComponent extends CdForm implements OnInit {
38 @ViewChild('nfsClients', { static: true })
39 nfsClients: NfsFormClientComponent;
40
41 clients: any[] = [];
42
43 permission: Permission;
44 nfsForm: CdFormGroup;
45 isEdit = false;
46
47 cluster_id: string = null;
48 export_id: string = null;
49
50 allClusters: { cluster_id: string }[] = null;
51 icons = Icons;
52
53 allFsals: any[] = [];
54 allFsNames: any[] = null;
55 fsalAvailabilityError: string = null;
56
57 defaultAccessType = { RGW: 'RO' };
58 nfsAccessType: any[] = this.nfsService.nfsAccessType;
59 nfsSquash: any[] = this.nfsService.nfsSquash;
60
61 action: string;
62 resource: string;
63
64 pathDataSource = (text$: Observable<string>) => {
65 return text$.pipe(
66 debounceTime(200),
67 distinctUntilChanged(),
68 mergeMap((token: string) => this.getPathTypeahead(token)),
69 map((val: string[]) => val)
70 );
71 };
72
73 bucketDataSource = (text$: Observable<string>) => {
74 return text$.pipe(
75 debounceTime(200),
76 distinctUntilChanged(),
77 mergeMap((token: string) => this.getBucketTypeahead(token))
78 );
79 };
80
81 constructor(
82 private authStorageService: AuthStorageService,
83 private nfsService: NfsService,
84 private route: ActivatedRoute,
85 private router: Router,
86 private rgwBucketService: RgwBucketService,
87 private rgwSiteService: RgwSiteService,
88 private formBuilder: CdFormBuilder,
89 private taskWrapper: TaskWrapperService,
90 private cdRef: ChangeDetectorRef,
91 public actionLabels: ActionLabelsI18n
92 ) {
93 super();
94 this.permission = this.authStorageService.getPermissions().pool;
95 this.resource = $localize`NFS export`;
96 this.createForm();
97 }
98
99 ngOnInit() {
100 const promises: Observable<any>[] = [
101 this.nfsService.listClusters(),
102 this.nfsService.fsals(),
103 this.nfsService.filesystems()
104 ];
105
106 if (this.router.url.startsWith('/nfs/edit')) {
107 this.isEdit = true;
108 }
109
110 if (this.isEdit) {
111 this.action = this.actionLabels.EDIT;
112 this.route.params.subscribe((params: { cluster_id: string; export_id: string }) => {
113 this.cluster_id = decodeURIComponent(params.cluster_id);
114 this.export_id = decodeURIComponent(params.export_id);
115 promises.push(this.nfsService.get(this.cluster_id, this.export_id));
116
117 this.getData(promises);
118 });
119 this.nfsForm.get('cluster_id').disable();
120 } else {
121 this.action = this.actionLabels.CREATE;
122 this.getData(promises);
123 }
124 }
125
126 getData(promises: Observable<any>[]) {
127 forkJoin(promises).subscribe((data: any[]) => {
128 this.resolveClusters(data[0]);
129 this.resolveFsals(data[1]);
130 this.resolveFilesystems(data[2]);
131 if (data[3]) {
132 this.resolveModel(data[3]);
133 }
134
135 this.loadingReady();
136 });
137 }
138
139 createForm() {
140 this.nfsForm = new CdFormGroup({
141 cluster_id: new FormControl('', {
142 validators: [Validators.required]
143 }),
144 fsal: new CdFormGroup({
145 name: new FormControl('', {
146 validators: [Validators.required]
147 }),
148 fs_name: new FormControl('', {
149 validators: [
150 CdValidators.requiredIf({
151 name: 'CEPH'
152 })
153 ]
154 })
155 }),
156 path: new FormControl('/'),
157 protocolNfsv4: new FormControl(true),
158 pseudo: new FormControl('', {
159 validators: [
160 CdValidators.requiredIf({ protocolNfsv4: true }),
161 Validators.pattern('^/[^><|&()]*$')
162 ]
163 }),
164 access_type: new FormControl('RW', {
165 validators: [Validators.required]
166 }),
167 squash: new FormControl(this.nfsSquash[0], {
168 validators: [Validators.required]
169 }),
170 transportUDP: new FormControl(true, {
171 validators: [
172 CdValidators.requiredIf({ transportTCP: false }, (value: boolean) => {
173 return !value;
174 })
175 ]
176 }),
177 transportTCP: new FormControl(true, {
178 validators: [
179 CdValidators.requiredIf({ transportUDP: false }, (value: boolean) => {
180 return !value;
181 })
182 ]
183 }),
184 clients: this.formBuilder.array([]),
185 security_label: new FormControl(false),
186 sec_label_xattr: new FormControl(
187 'security.selinux',
188 CdValidators.requiredIf({ security_label: true, 'fsal.name': 'CEPH' })
189 )
190 });
191 }
192
193 resolveModel(res: any) {
194 if (res.fsal.name === 'CEPH') {
195 res.sec_label_xattr = res.fsal.sec_label_xattr;
196 }
197
198 res.protocolNfsv4 = res.protocols.indexOf(4) !== -1;
199 delete res.protocols;
200
201 res.transportTCP = res.transports.indexOf('TCP') !== -1;
202 res.transportUDP = res.transports.indexOf('UDP') !== -1;
203 delete res.transports;
204
205 res.clients.forEach((client: any) => {
206 let addressStr = '';
207 client.addresses.forEach((address: string) => {
208 addressStr += address + ', ';
209 });
210 if (addressStr.length >= 2) {
211 addressStr = addressStr.substring(0, addressStr.length - 2);
212 }
213 client.addresses = addressStr;
214 });
215
216 this.nfsForm.patchValue(res);
217 this.setPathValidation();
218 this.clients = res.clients;
219 }
220
221 resolveClusters(clusters: string[]) {
222 this.allClusters = [];
223 for (const cluster of clusters) {
224 this.allClusters.push({ cluster_id: cluster });
225 }
226 if (!this.isEdit && this.allClusters.length > 0) {
227 this.nfsForm.get('cluster_id').setValue(this.allClusters[0].cluster_id);
228 }
229 }
230
231 resolveFsals(res: string[]) {
232 res.forEach((fsal) => {
233 const fsalItem = this.nfsService.nfsFsal.find((currentFsalItem) => {
234 return fsal === currentFsalItem.value;
235 });
236
237 if (_.isObjectLike(fsalItem)) {
238 this.allFsals.push(fsalItem);
239 }
240 });
241 if (!this.isEdit && this.allFsals.length > 0) {
242 this.nfsForm.patchValue({
243 fsal: {
244 name: this.allFsals[0].value
245 }
246 });
247 }
248 }
249
250 resolveFilesystems(filesystems: any[]) {
251 this.allFsNames = filesystems;
252 if (!this.isEdit && filesystems.length > 0) {
253 this.nfsForm.patchValue({
254 fsal: {
255 fs_name: filesystems[0].name
256 }
257 });
258 }
259 }
260
261 fsalChangeHandler() {
262 this.setPathValidation();
263 const fsalValue = this.nfsForm.getValue('name');
264 const checkAvailability =
265 fsalValue === 'RGW'
266 ? this.rgwSiteService.get('realms').pipe(
267 mergeMap((realms: string[]) =>
268 realms.length === 0
269 ? of(true)
270 : this.rgwSiteService.isDefaultRealm().pipe(
271 mergeMap((isDefaultRealm) => {
272 if (!isDefaultRealm) {
273 throw new Error('Selected realm is not the default.');
274 }
275 return of(true);
276 })
277 )
278 )
279 )
280 : this.nfsService.filesystems();
281
282 checkAvailability.subscribe({
283 next: () => {
284 this.setFsalAvailability(fsalValue, true);
285 if (!this.isEdit) {
286 this.nfsForm.patchValue({
287 path: fsalValue === 'RGW' ? '' : '/',
288 pseudo: this.generatePseudo(),
289 access_type: this.updateAccessType()
290 });
291 }
292
293 this.cdRef.detectChanges();
294 },
295 error: (error) => {
296 this.setFsalAvailability(fsalValue, false, error);
297 this.nfsForm.get('name').setValue('');
298 }
299 });
300 }
301
302 private setFsalAvailability(fsalValue: string, available: boolean, errorMessage: string = '') {
303 this.allFsals = this.allFsals.map((fsalItem: NfsFSAbstractionLayer) => {
304 if (fsalItem.value === fsalValue) {
305 fsalItem.disabled = !available;
306
307 this.fsalAvailabilityError = fsalItem.disabled
308 ? $localize`${fsalItem.descr} backend is not available. ${errorMessage}`
309 : null;
310 }
311 return fsalItem;
312 });
313 }
314
315 accessTypeChangeHandler() {
316 const name = this.nfsForm.getValue('name');
317 const accessType = this.nfsForm.getValue('access_type');
318 this.defaultAccessType[name] = accessType;
319 }
320
321 setPathValidation() {
322 const path = this.nfsForm.get('path');
323 path.setValidators([Validators.required]);
324 if (this.nfsForm.getValue('name') === 'RGW') {
325 path.setAsyncValidators([CdValidators.bucketExistence(true, this.rgwBucketService)]);
326 } else {
327 path.setAsyncValidators([this.pathExistence(true)]);
328 }
329
330 if (this.isEdit) {
331 path.markAsDirty();
332 }
333 }
334
335 getAccessTypeHelp(accessType: string) {
336 const accessTypeItem = this.nfsAccessType.find((currentAccessTypeItem) => {
337 if (accessType === currentAccessTypeItem.value) {
338 return currentAccessTypeItem;
339 }
340 });
341 return _.isObjectLike(accessTypeItem) ? accessTypeItem.help : '';
342 }
343
344 getId() {
345 if (
346 _.isString(this.nfsForm.getValue('cluster_id')) &&
347 _.isString(this.nfsForm.getValue('path'))
348 ) {
349 return this.nfsForm.getValue('cluster_id') + ':' + this.nfsForm.getValue('path');
350 }
351 return '';
352 }
353
354 private getPathTypeahead(path: any) {
355 if (!_.isString(path) || path === '/') {
356 return of([]);
357 }
358
359 const fsName = this.nfsForm.getValue('fsal').fs_name;
360 return this.nfsService.lsDir(fsName, path).pipe(
361 map((result: Directory) =>
362 result.paths.filter((dirName: string) => dirName.toLowerCase().includes(path)).slice(0, 15)
363 ),
364 catchError(() => of([$localize`Error while retrieving paths.`]))
365 );
366 }
367
368 pathChangeHandler() {
369 if (!this.isEdit) {
370 this.nfsForm.patchValue({
371 pseudo: this.generatePseudo()
372 });
373 }
374 }
375
376 private getBucketTypeahead(path: string): Observable<any> {
377 if (_.isString(path) && path !== '/' && path !== '') {
378 return this.rgwBucketService.list().pipe(
379 map((bucketList) =>
380 bucketList
381 .filter((bucketName: string) => bucketName.toLowerCase().includes(path))
382 .slice(0, 15)
383 ),
384 catchError(() => of([$localize`Error while retrieving bucket names.`]))
385 );
386 } else {
387 return of([]);
388 }
389 }
390
391 private generatePseudo() {
392 let newPseudo = this.nfsForm.getValue('pseudo');
393 if (this.nfsForm.get('pseudo') && !this.nfsForm.get('pseudo').dirty) {
394 newPseudo = undefined;
395 if (this.nfsForm.getValue('fsal') === 'CEPH') {
396 newPseudo = '/cephfs';
397 if (_.isString(this.nfsForm.getValue('path'))) {
398 newPseudo += this.nfsForm.getValue('path');
399 }
400 }
401 }
402 return newPseudo;
403 }
404
405 private updateAccessType() {
406 const name = this.nfsForm.getValue('name');
407 let accessType = this.defaultAccessType[name];
408
409 if (!accessType) {
410 accessType = 'RW';
411 }
412
413 return accessType;
414 }
415
416 submitAction() {
417 let action: Observable<any>;
418 const requestModel = this.buildRequest();
419
420 if (this.isEdit) {
421 action = this.taskWrapper.wrapTaskAroundCall({
422 task: new FinishedTask('nfs/edit', {
423 cluster_id: this.cluster_id,
424 export_id: _.parseInt(this.export_id)
425 }),
426 call: this.nfsService.update(this.cluster_id, _.parseInt(this.export_id), requestModel)
427 });
428 } else {
429 // Create
430 action = this.taskWrapper.wrapTaskAroundCall({
431 task: new FinishedTask('nfs/create', {
432 path: requestModel.path,
433 fsal: requestModel.fsal,
434 cluster_id: requestModel.cluster_id
435 }),
436 call: this.nfsService.create(requestModel)
437 });
438 }
439
440 action.subscribe({
441 error: (errorResponse: CdHttpErrorResponse) => this.setFormErrors(errorResponse),
442 complete: () => this.router.navigate(['/nfs'])
443 });
444 }
445
446 private setFormErrors(errorResponse: CdHttpErrorResponse) {
447 if (
448 errorResponse.error.detail &&
449 errorResponse.error.detail
450 .toString()
451 .includes(`Pseudo ${this.nfsForm.getValue('pseudo')} is already in use`)
452 ) {
453 this.nfsForm.get('pseudo').setErrors({ pseudoAlreadyExists: true });
454 }
455 this.nfsForm.setErrors({ cdSubmitButton: true });
456 }
457
458 private buildRequest() {
459 const requestModel: any = _.cloneDeep(this.nfsForm.value);
460
461 if (this.isEdit) {
462 requestModel.export_id = _.parseInt(this.export_id);
463 }
464
465 if (requestModel.fsal.name === 'RGW') {
466 delete requestModel.fsal.fs_name;
467 }
468
469 requestModel.protocols = [];
470 if (requestModel.protocolNfsv4) {
471 requestModel.protocols.push(4);
472 } else {
473 requestModel.pseudo = null;
474 }
475 delete requestModel.protocolNfsv4;
476
477 requestModel.transports = [];
478 if (requestModel.transportTCP) {
479 requestModel.transports.push('TCP');
480 }
481 delete requestModel.transportTCP;
482 if (requestModel.transportUDP) {
483 requestModel.transports.push('UDP');
484 }
485 delete requestModel.transportUDP;
486
487 requestModel.clients.forEach((client: any) => {
488 if (_.isString(client.addresses)) {
489 client.addresses = _(client.addresses)
490 .split(/[ ,]+/)
491 .uniq()
492 .filter((address) => address !== '')
493 .value();
494 } else {
495 client.addresses = [];
496 }
497
498 if (!client.squash) {
499 client.squash = requestModel.squash;
500 }
501
502 if (!client.access_type) {
503 client.access_type = requestModel.access_type;
504 }
505 });
506
507 if (requestModel.security_label === false || requestModel.fsal.name === 'RGW') {
508 requestModel.fsal.sec_label_xattr = null;
509 } else {
510 requestModel.fsal.sec_label_xattr = requestModel.sec_label_xattr;
511 }
512 delete requestModel.sec_label_xattr;
513
514 return requestModel;
515 }
516
517 private pathExistence(requiredExistenceResult: boolean): AsyncValidatorFn {
518 return (control: AbstractControl): Observable<ValidationErrors | null> => {
519 if (control.pristine || !control.value) {
520 return of({ required: true });
521 }
522 const fsName = this.nfsForm.getValue('fsal').fs_name;
523 return this.nfsService.lsDir(fsName, control.value).pipe(
524 map((directory: Directory) =>
525 directory.paths.includes(control.value) === requiredExistenceResult
526 ? null
527 : { pathNameNotAllowed: true }
528 ),
529 catchError(() => of({ pathNameNotAllowed: true }))
530 );
531 };
532 }
533 }