1 import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
8 } from '@angular/forms';
9 import { ActivatedRoute, Router } from '@angular/router';
11 import _ from 'lodash';
12 import { forkJoin, Observable, of } from 'rxjs';
13 import { catchError, debounceTime, distinctUntilChanged, map, mergeMap } from 'rxjs/operators';
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';
33 selector: 'cd-nfs-form',
34 templateUrl: './nfs-form.component.html',
35 styleUrls: ['./nfs-form.component.scss']
37 export class NfsFormComponent extends CdForm implements OnInit {
38 @ViewChild('nfsClients', { static: true })
39 nfsClients: NfsFormClientComponent;
43 permission: Permission;
47 cluster_id: string = null;
48 export_id: string = null;
50 allClusters: { cluster_id: string }[] = null;
54 allFsNames: any[] = null;
55 fsalAvailabilityError: string = null;
57 defaultAccessType = { RGW: 'RO' };
58 nfsAccessType: any[] = this.nfsService.nfsAccessType;
59 nfsSquash: any[] = this.nfsService.nfsSquash;
64 pathDataSource = (text$: Observable<string>) => {
67 distinctUntilChanged(),
68 mergeMap((token: string) => this.getPathTypeahead(token)),
69 map((val: string[]) => val)
73 bucketDataSource = (text$: Observable<string>) => {
76 distinctUntilChanged(),
77 mergeMap((token: string) => this.getBucketTypeahead(token))
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
94 this.permission = this.authStorageService.getPermissions().pool;
95 this.resource = $localize`NFS export`;
100 const promises: Observable<any>[] = [
101 this.nfsService.listClusters(),
102 this.nfsService.fsals(),
103 this.nfsService.filesystems()
106 if (this.router.url.startsWith('/nfs/edit')) {
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));
117 this.getData(promises);
119 this.nfsForm.get('cluster_id').disable();
121 this.action = this.actionLabels.CREATE;
122 this.getData(promises);
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]);
132 this.resolveModel(data[3]);
140 this.nfsForm = new CdFormGroup({
141 cluster_id: new FormControl('', {
142 validators: [Validators.required]
144 fsal: new CdFormGroup({
145 name: new FormControl('', {
146 validators: [Validators.required]
148 fs_name: new FormControl('', {
150 CdValidators.requiredIf({
156 path: new FormControl('/'),
157 protocolNfsv4: new FormControl(true),
158 pseudo: new FormControl('', {
160 CdValidators.requiredIf({ protocolNfsv4: true }),
161 Validators.pattern('^/[^><|&()]*$')
164 access_type: new FormControl('RW', {
165 validators: [Validators.required]
167 squash: new FormControl(this.nfsSquash[0], {
168 validators: [Validators.required]
170 transportUDP: new FormControl(true, {
172 CdValidators.requiredIf({ transportTCP: false }, (value: boolean) => {
177 transportTCP: new FormControl(true, {
179 CdValidators.requiredIf({ transportUDP: false }, (value: boolean) => {
184 clients: this.formBuilder.array([]),
185 security_label: new FormControl(false),
186 sec_label_xattr: new FormControl(
188 CdValidators.requiredIf({ security_label: true, 'fsal.name': 'CEPH' })
193 resolveModel(res: any) {
194 if (res.fsal.name === 'CEPH') {
195 res.sec_label_xattr = res.fsal.sec_label_xattr;
198 res.protocolNfsv4 = res.protocols.indexOf(4) !== -1;
199 delete res.protocols;
201 res.transportTCP = res.transports.indexOf('TCP') !== -1;
202 res.transportUDP = res.transports.indexOf('UDP') !== -1;
203 delete res.transports;
205 res.clients.forEach((client: any) => {
207 client.addresses.forEach((address: string) => {
208 addressStr += address + ', ';
210 if (addressStr.length >= 2) {
211 addressStr = addressStr.substring(0, addressStr.length - 2);
213 client.addresses = addressStr;
216 this.nfsForm.patchValue(res);
217 this.setPathValidation();
218 this.clients = res.clients;
221 resolveClusters(clusters: string[]) {
222 this.allClusters = [];
223 for (const cluster of clusters) {
224 this.allClusters.push({ cluster_id: cluster });
226 if (!this.isEdit && this.allClusters.length > 0) {
227 this.nfsForm.get('cluster_id').setValue(this.allClusters[0].cluster_id);
231 resolveFsals(res: string[]) {
232 res.forEach((fsal) => {
233 const fsalItem = this.nfsService.nfsFsal.find((currentFsalItem) => {
234 return fsal === currentFsalItem.value;
237 if (_.isObjectLike(fsalItem)) {
238 this.allFsals.push(fsalItem);
241 if (!this.isEdit && this.allFsals.length > 0) {
242 this.nfsForm.patchValue({
244 name: this.allFsals[0].value
250 resolveFilesystems(filesystems: any[]) {
251 this.allFsNames = filesystems;
252 if (!this.isEdit && filesystems.length > 0) {
253 this.nfsForm.patchValue({
255 fs_name: filesystems[0].name
261 fsalChangeHandler() {
262 this.setPathValidation();
263 const fsalValue = this.nfsForm.getValue('name');
264 const checkAvailability =
266 ? this.rgwSiteService.get('realms').pipe(
267 mergeMap((realms: string[]) =>
270 : this.rgwSiteService.isDefaultRealm().pipe(
271 mergeMap((isDefaultRealm) => {
272 if (!isDefaultRealm) {
273 throw new Error('Selected realm is not the default.');
280 : this.nfsService.filesystems();
282 checkAvailability.subscribe({
284 this.setFsalAvailability(fsalValue, true);
286 this.nfsForm.patchValue({
287 path: fsalValue === 'RGW' ? '' : '/',
288 pseudo: this.generatePseudo(),
289 access_type: this.updateAccessType()
293 this.cdRef.detectChanges();
296 this.setFsalAvailability(fsalValue, false, error);
297 this.nfsForm.get('name').setValue('');
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;
307 this.fsalAvailabilityError = fsalItem.disabled
308 ? $localize`${fsalItem.descr} backend is not available. ${errorMessage}`
315 accessTypeChangeHandler() {
316 const name = this.nfsForm.getValue('name');
317 const accessType = this.nfsForm.getValue('access_type');
318 this.defaultAccessType[name] = accessType;
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)]);
327 path.setAsyncValidators([this.pathExistence(true)]);
335 getAccessTypeHelp(accessType: string) {
336 const accessTypeItem = this.nfsAccessType.find((currentAccessTypeItem) => {
337 if (accessType === currentAccessTypeItem.value) {
338 return currentAccessTypeItem;
341 return _.isObjectLike(accessTypeItem) ? accessTypeItem.help : '';
346 _.isString(this.nfsForm.getValue('cluster_id')) &&
347 _.isString(this.nfsForm.getValue('path'))
349 return this.nfsForm.getValue('cluster_id') + ':' + this.nfsForm.getValue('path');
354 private getPathTypeahead(path: any) {
355 if (!_.isString(path) || path === '/') {
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)
364 catchError(() => of([$localize`Error while retrieving paths.`]))
368 pathChangeHandler() {
370 this.nfsForm.patchValue({
371 pseudo: this.generatePseudo()
376 private getBucketTypeahead(path: string): Observable<any> {
377 if (_.isString(path) && path !== '/' && path !== '') {
378 return this.rgwBucketService.list().pipe(
381 .filter((bucketName: string) => bucketName.toLowerCase().includes(path))
384 catchError(() => of([$localize`Error while retrieving bucket names.`]))
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');
405 private updateAccessType() {
406 const name = this.nfsForm.getValue('name');
407 let accessType = this.defaultAccessType[name];
417 let action: Observable<any>;
418 const requestModel = this.buildRequest();
421 action = this.taskWrapper.wrapTaskAroundCall({
422 task: new FinishedTask('nfs/edit', {
423 cluster_id: this.cluster_id,
424 export_id: _.parseInt(this.export_id)
426 call: this.nfsService.update(this.cluster_id, _.parseInt(this.export_id), requestModel)
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
436 call: this.nfsService.create(requestModel)
441 error: (errorResponse: CdHttpErrorResponse) => this.setFormErrors(errorResponse),
442 complete: () => this.router.navigate(['/nfs'])
446 private setFormErrors(errorResponse: CdHttpErrorResponse) {
448 errorResponse.error.detail &&
449 errorResponse.error.detail
451 .includes(`Pseudo ${this.nfsForm.getValue('pseudo')} is already in use`)
453 this.nfsForm.get('pseudo').setErrors({ pseudoAlreadyExists: true });
455 this.nfsForm.setErrors({ cdSubmitButton: true });
458 private buildRequest() {
459 const requestModel: any = _.cloneDeep(this.nfsForm.value);
462 requestModel.export_id = _.parseInt(this.export_id);
465 if (requestModel.fsal.name === 'RGW') {
466 delete requestModel.fsal.fs_name;
469 requestModel.protocols = [];
470 if (requestModel.protocolNfsv4) {
471 requestModel.protocols.push(4);
473 requestModel.pseudo = null;
475 delete requestModel.protocolNfsv4;
477 requestModel.transports = [];
478 if (requestModel.transportTCP) {
479 requestModel.transports.push('TCP');
481 delete requestModel.transportTCP;
482 if (requestModel.transportUDP) {
483 requestModel.transports.push('UDP');
485 delete requestModel.transportUDP;
487 requestModel.clients.forEach((client: any) => {
488 if (_.isString(client.addresses)) {
489 client.addresses = _(client.addresses)
492 .filter((address) => address !== '')
495 client.addresses = [];
498 if (!client.squash) {
499 client.squash = requestModel.squash;
502 if (!client.access_type) {
503 client.access_type = requestModel.access_type;
507 if (requestModel.security_label === false || requestModel.fsal.name === 'RGW') {
508 requestModel.fsal.sec_label_xattr = null;
510 requestModel.fsal.sec_label_xattr = requestModel.sec_label_xattr;
512 delete requestModel.sec_label_xattr;
517 private pathExistence(requiredExistenceResult: boolean): AsyncValidatorFn {
518 return (control: AbstractControl): Observable<ValidationErrors | null> => {
519 if (control.pristine || !control.value) {
520 return of({ required: true });
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
527 : { pathNameNotAllowed: true }
529 catchError(() => of({ pathNameNotAllowed: true }))