]> git.apps.os.sepia.ceph.com Git - ceph.git/blob
28bae956298b0dfa6a3a3fd6aedad3288abe45fc
[ceph.git] /
1 import { Component, Input, OnInit, ViewChild } from '@angular/core';
2 import { AbstractControl, Validators } from '@angular/forms';
3 import { ActivatedRoute, Router } from '@angular/router';
4
5 import { NgbActiveModal, NgbTypeahead } from '@ng-bootstrap/ng-bootstrap';
6 import _ from 'lodash';
7 import { merge, Observable, Subject } from 'rxjs';
8 import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators';
9
10 import { CephServiceService } from '~/app/shared/api/ceph-service.service';
11 import { HostService } from '~/app/shared/api/host.service';
12 import { PoolService } from '~/app/shared/api/pool.service';
13 import { SelectMessages } from '~/app/shared/components/select/select-messages.model';
14 import { SelectOption } from '~/app/shared/components/select/select-option.model';
15 import { ActionLabelsI18n, URLVerbs } from '~/app/shared/constants/app.constants';
16 import { CdForm } from '~/app/shared/forms/cd-form';
17 import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
18 import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
19 import { CdValidators } from '~/app/shared/forms/cd-validators';
20 import { FinishedTask } from '~/app/shared/models/finished-task';
21 import { CephServiceSpec } from '~/app/shared/models/service.interface';
22 import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service';
23
24 @Component({
25   selector: 'cd-service-form',
26   templateUrl: './service-form.component.html',
27   styleUrls: ['./service-form.component.scss']
28 })
29 export class ServiceFormComponent extends CdForm implements OnInit {
30   readonly RGW_SVC_ID_PATTERN = /^([^.]+)(\.([^.]+)\.([^.]+))?$/;
31   @ViewChild(NgbTypeahead, { static: false })
32   typeahead: NgbTypeahead;
33
34   @Input() hiddenServices: string[] = [];
35
36   @Input() editing = false;
37
38   @Input() serviceName: string;
39
40   @Input() serviceType: string;
41
42   serviceForm: CdFormGroup;
43   action: string;
44   resource: string;
45   serviceTypes: string[] = [];
46   hosts: any;
47   labels: string[];
48   labelClick = new Subject<string>();
49   labelFocus = new Subject<string>();
50   pools: Array<object>;
51   services: Array<CephServiceSpec> = [];
52   pageURL: string;
53
54   constructor(
55     public actionLabels: ActionLabelsI18n,
56     private cephServiceService: CephServiceService,
57     private formBuilder: CdFormBuilder,
58     private hostService: HostService,
59     private poolService: PoolService,
60     private router: Router,
61     private taskWrapperService: TaskWrapperService,
62     private route: ActivatedRoute,
63     public activeModal: NgbActiveModal
64   ) {
65     super();
66     this.resource = $localize`service`;
67     this.hosts = {
68       options: [],
69       messages: new SelectMessages({
70         empty: $localize`There are no hosts.`,
71         filter: $localize`Filter hosts`
72       })
73     };
74     this.createForm();
75   }
76
77   createForm() {
78     this.serviceForm = this.formBuilder.group({
79       // Global
80       service_type: [null, [Validators.required]],
81       service_id: [
82         null,
83         [
84           CdValidators.requiredIf({
85             service_type: 'mds'
86           }),
87           CdValidators.requiredIf({
88             service_type: 'nfs'
89           }),
90           CdValidators.requiredIf({
91             service_type: 'iscsi'
92           }),
93           CdValidators.requiredIf({
94             service_type: 'ingress'
95           }),
96           CdValidators.composeIf(
97             {
98               service_type: 'rgw'
99             },
100             [
101               Validators.required,
102               CdValidators.custom('rgwPattern', (value: string) => {
103                 if (_.isEmpty(value)) {
104                   return false;
105                 }
106                 return !this.RGW_SVC_ID_PATTERN.test(value);
107               })
108             ]
109           )
110         ]
111       ],
112       placement: ['hosts'],
113       label: [
114         null,
115         [
116           CdValidators.requiredIf({
117             placement: 'label',
118             unmanaged: false
119           })
120         ]
121       ],
122       hosts: [[]],
123       count: [null, [CdValidators.number(false)]],
124       unmanaged: [false],
125       // iSCSI
126       pool: [
127         null,
128         [
129           CdValidators.requiredIf({
130             service_type: 'iscsi',
131             unmanaged: false
132           })
133         ]
134       ],
135       // RGW
136       rgw_frontend_port: [null, [CdValidators.number(false)]],
137       // iSCSI
138       trusted_ip_list: [null],
139       api_port: [null, [CdValidators.number(false)]],
140       api_user: [
141         null,
142         [
143           CdValidators.requiredIf({
144             service_type: 'iscsi',
145             unmanaged: false
146           })
147         ]
148       ],
149       api_password: [
150         null,
151         [
152           CdValidators.requiredIf({
153             service_type: 'iscsi',
154             unmanaged: false
155           })
156         ]
157       ],
158       // Ingress
159       backend_service: [
160         null,
161         [
162           CdValidators.requiredIf({
163             service_type: 'ingress',
164             unmanaged: false
165           })
166         ]
167       ],
168       virtual_ip: [
169         null,
170         [
171           CdValidators.requiredIf({
172             service_type: 'ingress',
173             unmanaged: false
174           })
175         ]
176       ],
177       frontend_port: [null, [CdValidators.number(false)]],
178       monitor_port: [null, [CdValidators.number(false)]],
179       virtual_interface_networks: [null],
180       // RGW, Ingress & iSCSI
181       ssl: [false],
182       ssl_cert: [
183         '',
184         [
185           CdValidators.composeIf(
186             {
187               service_type: 'rgw',
188               unmanaged: false,
189               ssl: true
190             },
191             [Validators.required, CdValidators.pemCert()]
192           ),
193           CdValidators.composeIf(
194             {
195               service_type: 'iscsi',
196               unmanaged: false,
197               ssl: true
198             },
199             [Validators.required, CdValidators.sslCert()]
200           )
201         ]
202       ],
203       ssl_key: [
204         '',
205         [
206           CdValidators.composeIf(
207             {
208               service_type: 'iscsi',
209               unmanaged: false,
210               ssl: true
211             },
212             [Validators.required, CdValidators.sslPrivKey()]
213           )
214         ]
215       ],
216       // snmp-gateway
217       snmp_version: [null, [Validators.required]],
218       snmp_destination: [
219         null,
220         [
221           CdValidators.requiredIf({
222             service_type: 'snmp-gateway',
223             unmanaged: false
224           })
225         ]
226       ],
227       engine_id: [
228         null,
229         [
230           CdValidators.requiredIf({
231             service_type: 'snmp-gateway',
232             unmanaged: false
233           })
234         ]
235       ],
236       auth_protocol: [
237         'SHA',
238         [
239           CdValidators.requiredIf({
240             service_type: 'snmp-gateway',
241             unmanaged: false
242           })
243         ]
244       ],
245       privacy_protocol: [null],
246       snmp_community: [
247         null,
248         [
249           CdValidators.requiredIf({
250             service_type: 'snmp-gateway',
251             unmanaged: false
252           })
253         ]
254       ],
255       snmp_v3_auth_username: [
256         null,
257         [
258           CdValidators.requiredIf({
259             service_type: 'snmp-gateway',
260             unmanaged: false
261           })
262         ]
263       ],
264       snmp_v3_auth_password: [
265         null,
266         [
267           CdValidators.requiredIf({
268             service_type: 'snmp-gateway',
269             unmanaged: false
270           })
271         ]
272       ],
273       snmp_v3_priv_password: [
274         null,
275         [
276           CdValidators.requiredIf({
277             service_type: 'snmp-gateway',
278             unmanaged: false
279           })
280         ]
281       ]
282     });
283   }
284
285   ngOnInit(): void {
286     this.action = this.actionLabels.CREATE;
287     if (this.router.url.includes('services/(modal:create')) {
288       this.pageURL = 'services';
289     } else if (this.router.url.includes('services/(modal:edit')) {
290       this.editing = true;
291       this.pageURL = 'services';
292       this.route.params.subscribe((params: { type: string; name: string }) => {
293         this.serviceName = params.name;
294         this.serviceType = params.type;
295       });
296     }
297     this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
298       // Remove service types:
299       // osd       - This is deployed a different way.
300       // container - This should only be used in the CLI.
301       this.hiddenServices.push('osd', 'container');
302
303       this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
304     });
305     this.hostService.list('false').subscribe((resp: object[]) => {
306       const options: SelectOption[] = [];
307       _.forEach(resp, (host: object) => {
308         if (_.get(host, 'sources.orchestrator', false)) {
309           const option = new SelectOption(false, _.get(host, 'hostname'), '');
310           options.push(option);
311         }
312       });
313       this.hosts.options = [...options];
314     });
315     this.hostService.getLabels().subscribe((resp: string[]) => {
316       this.labels = resp;
317     });
318     this.poolService.getList().subscribe((resp: Array<object>) => {
319       this.pools = resp;
320     });
321     this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
322       this.services = services.filter((service: any) => service.service_type === 'rgw');
323     });
324
325     if (this.editing) {
326       this.action = this.actionLabels.EDIT;
327       this.disableForEditing(this.serviceType);
328       this.cephServiceService.list(this.serviceName).subscribe((response: CephServiceSpec[]) => {
329         const formKeys = ['service_type', 'service_id', 'unmanaged'];
330         formKeys.forEach((keys) => {
331           this.serviceForm.get(keys).setValue(response[0][keys]);
332         });
333         if (!response[0]['unmanaged']) {
334           const placementKey = Object.keys(response[0]['placement'])[0];
335           let placementValue: string;
336           ['hosts', 'label'].indexOf(placementKey) >= 0
337             ? (placementValue = placementKey)
338             : (placementValue = 'hosts');
339           this.serviceForm.get('placement').setValue(placementValue);
340           this.serviceForm.get('count').setValue(response[0]['placement']['count']);
341           if (response[0]?.placement[placementValue]) {
342             this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
343           }
344         }
345         switch (this.serviceType) {
346           case 'iscsi':
347             const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
348             specKeys.forEach((key) => {
349               this.serviceForm.get(key).setValue(response[0].spec[key]);
350             });
351             this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
352             if (response[0].spec?.api_secure) {
353               this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
354               this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
355             }
356             break;
357           case 'rgw':
358             this.serviceForm.get('rgw_frontend_port').setValue(response[0].spec?.rgw_frontend_port);
359             this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
360             if (response[0].spec?.ssl) {
361               this.serviceForm
362                 .get('ssl_cert')
363                 .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
364             }
365             break;
366           case 'ingress':
367             const ingressSpecKeys = [
368               'backend_service',
369               'virtual_ip',
370               'frontend_port',
371               'monitor_port',
372               'virtual_interface_networks',
373               'ssl'
374             ];
375             ingressSpecKeys.forEach((key) => {
376               this.serviceForm.get(key).setValue(response[0].spec[key]);
377             });
378             if (response[0].spec?.ssl) {
379               this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
380               this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
381             }
382             break;
383           case 'snmp-gateway':
384             const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
385             snmpCommonSpecKeys.forEach((key) => {
386               this.serviceForm.get(key).setValue(response[0].spec[key]);
387             });
388             if (this.serviceForm.getValue('snmp_version') === 'V3') {
389               const snmpV3SpecKeys = [
390                 'engine_id',
391                 'auth_protocol',
392                 'privacy_protocol',
393                 'snmp_v3_auth_username',
394                 'snmp_v3_auth_password',
395                 'snmp_v3_priv_password'
396               ];
397               snmpV3SpecKeys.forEach((key) => {
398                 if (key !== null) {
399                   if (
400                     key === 'snmp_v3_auth_username' ||
401                     key === 'snmp_v3_auth_password' ||
402                     key === 'snmp_v3_priv_password'
403                   ) {
404                     this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
405                   } else {
406                     this.serviceForm.get(key).setValue(response[0].spec[key]);
407                   }
408                 }
409               });
410             } else {
411               this.serviceForm
412                 .get('snmp_community')
413                 .setValue(response[0].spec['credentials']['snmp_community']);
414             }
415             break;
416         }
417       });
418     }
419   }
420
421   disableForEditing(serviceType: string) {
422     const disableForEditKeys = ['service_type', 'service_id'];
423     disableForEditKeys.forEach((key) => {
424       this.serviceForm.get(key).disable();
425     });
426     switch (serviceType) {
427       case 'ingress':
428         this.serviceForm.get('backend_service').disable();
429     }
430   }
431
432   searchLabels = (text$: Observable<string>) => {
433     return merge(
434       text$.pipe(debounceTime(200), distinctUntilChanged()),
435       this.labelFocus,
436       this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
437     ).pipe(
438       map((value) =>
439         this.labels
440           .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
441           .slice(0, 10)
442       )
443     );
444   };
445
446   fileUpload(files: FileList, controlName: string) {
447     const file: File = files[0];
448     const reader = new FileReader();
449     reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
450       const control: AbstractControl = this.serviceForm.get(controlName);
451       control.setValue(event.target.result);
452       control.markAsDirty();
453       control.markAsTouched();
454       control.updateValueAndValidity();
455     });
456     reader.readAsText(file, 'utf8');
457   }
458
459   prePopulateId() {
460     const control: AbstractControl = this.serviceForm.get('service_id');
461     const backendService = this.serviceForm.getValue('backend_service');
462     // Set Id as read-only
463     control.reset({ value: backendService, disabled: true });
464   }
465
466   onSubmit() {
467     const self = this;
468     const values: object = this.serviceForm.getRawValue();
469     const serviceType: string = values['service_type'];
470     let taskUrl = `service/${URLVerbs.CREATE}`;
471     if (this.editing) {
472       taskUrl = `service/${URLVerbs.EDIT}`;
473     }
474     const serviceSpec: object = {
475       service_type: serviceType,
476       placement: {},
477       unmanaged: values['unmanaged']
478     };
479     let svcId: string;
480     if (serviceType === 'rgw') {
481       const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
482       svcId = svcIdMatch[1];
483       if (svcIdMatch[3]) {
484         serviceSpec['rgw_realm'] = svcIdMatch[3];
485         serviceSpec['rgw_zone'] = svcIdMatch[4];
486       }
487     } else {
488       svcId = values['service_id'];
489     }
490     const serviceId: string = svcId;
491     let serviceName: string = serviceType;
492     if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
493       serviceName = `${serviceType}.${serviceId}`;
494       serviceSpec['service_id'] = serviceId;
495     }
496     if (!values['unmanaged']) {
497       switch (values['placement']) {
498         case 'hosts':
499           if (values['hosts'].length > 0) {
500             serviceSpec['placement']['hosts'] = values['hosts'];
501           }
502           break;
503         case 'label':
504           serviceSpec['placement']['label'] = values['label'];
505           break;
506       }
507       if (_.isNumber(values['count']) && values['count'] > 0) {
508         serviceSpec['placement']['count'] = values['count'];
509       }
510       switch (serviceType) {
511         case 'rgw':
512           if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
513             serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
514           }
515           serviceSpec['ssl'] = values['ssl'];
516           if (values['ssl']) {
517             serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
518           }
519           break;
520         case 'iscsi':
521           serviceSpec['pool'] = values['pool'];
522           if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
523             serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
524           }
525           if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
526             serviceSpec['api_port'] = values['api_port'];
527           }
528           serviceSpec['api_user'] = values['api_user'];
529           serviceSpec['api_password'] = values['api_password'];
530           serviceSpec['api_secure'] = values['ssl'];
531           if (values['ssl']) {
532             serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
533             serviceSpec['ssl_key'] = values['ssl_key']?.trim();
534           }
535           break;
536         case 'ingress':
537           serviceSpec['backend_service'] = values['backend_service'];
538           serviceSpec['service_id'] = values['backend_service'];
539           if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
540             serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
541           }
542           if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
543             serviceSpec['frontend_port'] = values['frontend_port'];
544           }
545           if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
546             serviceSpec['monitor_port'] = values['monitor_port'];
547           }
548           serviceSpec['ssl'] = values['ssl'];
549           if (values['ssl']) {
550             serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
551             serviceSpec['ssl_key'] = values['ssl_key']?.trim();
552           }
553           serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
554           break;
555         case 'snmp-gateway':
556           serviceSpec['credentials'] = {};
557           serviceSpec['snmp_version'] = values['snmp_version'];
558           serviceSpec['snmp_destination'] = values['snmp_destination'];
559           if (values['snmp_version'] === 'V3') {
560             serviceSpec['engine_id'] = values['engine_id'];
561             serviceSpec['auth_protocol'] = values['auth_protocol'];
562             serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
563             serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
564             if (values['privacy_protocol'] !== null) {
565               serviceSpec['privacy_protocol'] = values['privacy_protocol'];
566               serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
567             }
568           } else {
569             serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
570           }
571           break;
572       }
573     }
574
575     this.taskWrapperService
576       .wrapTaskAroundCall({
577         task: new FinishedTask(taskUrl, {
578           service_name: serviceName
579         }),
580         call: this.cephServiceService.create(serviceSpec)
581       })
582       .subscribe({
583         error() {
584           self.serviceForm.setErrors({ cdSubmitButton: true });
585         },
586         complete: () => {
587           this.pageURL === 'services'
588             ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
589             : this.activeModal.close();
590         }
591       });
592   }
593
594   clearValidations() {
595     const snmpVersion = this.serviceForm.getValue('snmp_version');
596     const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
597     if (snmpVersion === 'V3') {
598       this.serviceForm.get('snmp_community').clearValidators();
599     } else {
600       this.serviceForm.get('engine_id').clearValidators();
601       this.serviceForm.get('auth_protocol').clearValidators();
602       this.serviceForm.get('privacy_protocol').clearValidators();
603       this.serviceForm.get('snmp_v3_auth_username').clearValidators();
604       this.serviceForm.get('snmp_v3_auth_password').clearValidators();
605     }
606     if (privacyProtocol === null) {
607       this.serviceForm.get('snmp_v3_priv_password').clearValidators();
608     }
609   }
610 }