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