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