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