]> git.apps.os.sepia.ceph.com Git - ceph-ci.git/blob
d6eea1711ffc793dcef809036789a6262b0ce4e8
[ceph-ci.git] /
1 import { HttpParams } from '@angular/common/http';
2 import { Component, Input, OnInit, ViewChild } from '@angular/core';
3 import { AbstractControl, Validators } from '@angular/forms';
4 import { ActivatedRoute, Router } from '@angular/router';
5
6 import { NgbActiveModal, NgbModalRef, NgbTypeahead } from '@ng-bootstrap/ng-bootstrap';
7 import _ from 'lodash';
8 import { forkJoin, merge, Observable, Subject, Subscription } from 'rxjs';
9 import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators';
10 import { CreateRgwServiceEntitiesComponent } from '~/app/ceph/rgw/create-rgw-service-entities/create-rgw-service-entities.component';
11 import { RgwRealm, RgwZonegroup, RgwZone } from '~/app/ceph/rgw/models/rgw-multisite';
12
13 import { CephServiceService } from '~/app/shared/api/ceph-service.service';
14 import { HostService } from '~/app/shared/api/host.service';
15 import { PoolService } from '~/app/shared/api/pool.service';
16 import { RgwMultisiteService } from '~/app/shared/api/rgw-multisite.service';
17 import { RgwRealmService } from '~/app/shared/api/rgw-realm.service';
18 import { RgwZoneService } from '~/app/shared/api/rgw-zone.service';
19 import { RgwZonegroupService } from '~/app/shared/api/rgw-zonegroup.service';
20 import { SelectMessages } from '~/app/shared/components/select/select-messages.model';
21 import { SelectOption } from '~/app/shared/components/select/select-option.model';
22 import {
23   ActionLabelsI18n,
24   TimerServiceInterval,
25   URLVerbs
26 } from '~/app/shared/constants/app.constants';
27 import { CdForm } from '~/app/shared/forms/cd-form';
28 import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
29 import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
30 import { CdValidators } from '~/app/shared/forms/cd-validators';
31 import { FinishedTask } from '~/app/shared/models/finished-task';
32 import { CephServiceSpec } from '~/app/shared/models/service.interface';
33 import { ModalService } from '~/app/shared/services/modal.service';
34 import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service';
35 import { TimerService } from '~/app/shared/services/timer.service';
36
37 @Component({
38   selector: 'cd-service-form',
39   templateUrl: './service-form.component.html',
40   styleUrls: ['./service-form.component.scss']
41 })
42 export class ServiceFormComponent extends CdForm implements OnInit {
43   public sub = new Subscription();
44
45   readonly MDS_SVC_ID_PATTERN = /^[a-zA-Z_.-][a-zA-Z0-9_.-]*$/;
46   readonly SNMP_DESTINATION_PATTERN = /^[^\:]+:[0-9]/;
47   readonly SNMP_ENGINE_ID_PATTERN = /^[0-9A-Fa-f]{10,64}/g;
48   readonly INGRESS_SUPPORTED_SERVICE_TYPES = ['rgw', 'nfs'];
49   @ViewChild(NgbTypeahead, { static: false })
50   typeahead: NgbTypeahead;
51
52   @Input() hiddenServices: string[] = [];
53
54   @Input() editing = false;
55
56   @Input() serviceName: string;
57
58   @Input() serviceType: string;
59
60   serviceForm: CdFormGroup;
61   action: string;
62   resource: string;
63   serviceTypes: string[] = [];
64   serviceIds: string[] = [];
65   hosts: any;
66   labels: string[];
67   labelClick = new Subject<string>();
68   labelFocus = new Subject<string>();
69   pools: Array<object>;
70   services: Array<CephServiceSpec> = [];
71   pageURL: string;
72   serviceList: CephServiceSpec[];
73   multisiteInfo: object[] = [];
74   defaultRealmId = '';
75   defaultZonegroupId = '';
76   defaultZoneId = '';
77   realmList: RgwRealm[] = [];
78   zonegroupList: RgwZonegroup[] = [];
79   zoneList: RgwZone[] = [];
80   bsModalRef: NgbModalRef;
81   defaultZonegroup: RgwZonegroup;
82   showRealmCreationForm = false;
83   defaultsInfo: { defaultRealmName: string; defaultZonegroupName: string; defaultZoneName: string };
84   realmNames: string[];
85   zonegroupNames: string[];
86   zoneNames: string[];
87
88   constructor(
89     public actionLabels: ActionLabelsI18n,
90     private cephServiceService: CephServiceService,
91     private formBuilder: CdFormBuilder,
92     private hostService: HostService,
93     private poolService: PoolService,
94     private router: Router,
95     private taskWrapperService: TaskWrapperService,
96     public timerService: TimerService,
97     public timerServiceVariable: TimerServiceInterval,
98     public rgwRealmService: RgwRealmService,
99     public rgwZonegroupService: RgwZonegroupService,
100     public rgwZoneService: RgwZoneService,
101     public rgwMultisiteService: RgwMultisiteService,
102     private route: ActivatedRoute,
103     public activeModal: NgbActiveModal,
104     public modalService: ModalService
105   ) {
106     super();
107     this.resource = $localize`service`;
108     this.hosts = {
109       options: [],
110       messages: new SelectMessages({
111         empty: $localize`There are no hosts.`,
112         filter: $localize`Filter hosts`
113       })
114     };
115     this.createForm();
116   }
117
118   createForm() {
119     this.serviceForm = this.formBuilder.group({
120       // Global
121       service_type: [null, [Validators.required]],
122       service_id: [
123         null,
124         [
125           CdValidators.composeIf(
126             {
127               service_type: 'mds'
128             },
129             [
130               Validators.required,
131               CdValidators.custom('mdsPattern', (value: string) => {
132                 if (_.isEmpty(value)) {
133                   return false;
134                 }
135                 return !this.MDS_SVC_ID_PATTERN.test(value);
136               })
137             ]
138           ),
139           CdValidators.requiredIf({
140             service_type: 'nfs'
141           }),
142           CdValidators.requiredIf({
143             service_type: 'iscsi'
144           }),
145           CdValidators.requiredIf({
146             service_type: 'ingress'
147           }),
148           CdValidators.composeIf(
149             {
150               service_type: 'rgw'
151             },
152             [Validators.required]
153           ),
154           CdValidators.custom('uniqueName', (service_id: string) => {
155             return this.serviceIds && this.serviceIds.includes(service_id);
156           })
157         ]
158       ],
159       placement: ['hosts'],
160       label: [
161         null,
162         [
163           CdValidators.requiredIf({
164             placement: 'label',
165             unmanaged: false
166           })
167         ]
168       ],
169       hosts: [[]],
170       count: [null, [CdValidators.number(false)]],
171       unmanaged: [false],
172       // iSCSI
173       pool: [
174         null,
175         [
176           CdValidators.requiredIf({
177             service_type: 'iscsi'
178           })
179         ]
180       ],
181       // RGW
182       rgw_frontend_port: [null, [CdValidators.number(false)]],
183       realm_name: [null],
184       zonegroup_name: [null],
185       zone_name: [null],
186       // iSCSI
187       trusted_ip_list: [null],
188       api_port: [null, [CdValidators.number(false)]],
189       api_user: [
190         null,
191         [
192           CdValidators.requiredIf({
193             service_type: 'iscsi',
194             unmanaged: false
195           })
196         ]
197       ],
198       api_password: [
199         null,
200         [
201           CdValidators.requiredIf({
202             service_type: 'iscsi',
203             unmanaged: false
204           })
205         ]
206       ],
207       // Ingress
208       backend_service: [
209         null,
210         [
211           CdValidators.requiredIf({
212             service_type: 'ingress'
213           })
214         ]
215       ],
216       virtual_ip: [
217         null,
218         [
219           CdValidators.requiredIf({
220             service_type: 'ingress'
221           })
222         ]
223       ],
224       frontend_port: [
225         null,
226         [
227           CdValidators.number(false),
228           CdValidators.requiredIf({
229             service_type: 'ingress'
230           })
231         ]
232       ],
233       monitor_port: [
234         null,
235         [
236           CdValidators.number(false),
237           CdValidators.requiredIf({
238             service_type: 'ingress'
239           })
240         ]
241       ],
242       virtual_interface_networks: [null],
243       // RGW, Ingress & iSCSI
244       ssl: [false],
245       ssl_cert: [
246         '',
247         [
248           CdValidators.composeIf(
249             {
250               service_type: 'rgw',
251               unmanaged: false,
252               ssl: true
253             },
254             [Validators.required, CdValidators.pemCert()]
255           ),
256           CdValidators.composeIf(
257             {
258               service_type: 'iscsi',
259               unmanaged: false,
260               ssl: true
261             },
262             [Validators.required, CdValidators.sslCert()]
263           ),
264           CdValidators.composeIf(
265             {
266               service_type: 'ingress',
267               unmanaged: false,
268               ssl: true
269             },
270             [Validators.required, CdValidators.pemCert()]
271           )
272         ]
273       ],
274       ssl_key: [
275         '',
276         [
277           CdValidators.composeIf(
278             {
279               service_type: 'iscsi',
280               unmanaged: false,
281               ssl: true
282             },
283             [Validators.required, CdValidators.sslPrivKey()]
284           )
285         ]
286       ],
287       // snmp-gateway
288       snmp_version: [
289         null,
290         [
291           CdValidators.requiredIf({
292             service_type: 'snmp-gateway'
293           })
294         ]
295       ],
296       snmp_destination: [
297         null,
298         {
299           validators: [
300             CdValidators.requiredIf({
301               service_type: 'snmp-gateway'
302             }),
303             CdValidators.custom('snmpDestinationPattern', (value: string) => {
304               if (_.isEmpty(value)) {
305                 return false;
306               }
307               return !this.SNMP_DESTINATION_PATTERN.test(value);
308             })
309           ]
310         }
311       ],
312       engine_id: [
313         null,
314         [
315           CdValidators.requiredIf({
316             service_type: 'snmp-gateway'
317           }),
318           CdValidators.custom('snmpEngineIdPattern', (value: string) => {
319             if (_.isEmpty(value)) {
320               return false;
321             }
322             return !this.SNMP_ENGINE_ID_PATTERN.test(value);
323           })
324         ]
325       ],
326       auth_protocol: [
327         'SHA',
328         [
329           CdValidators.requiredIf({
330             service_type: 'snmp-gateway'
331           })
332         ]
333       ],
334       privacy_protocol: [null],
335       snmp_community: [
336         null,
337         [
338           CdValidators.requiredIf({
339             snmp_version: 'V2c'
340           })
341         ]
342       ],
343       snmp_v3_auth_username: [
344         null,
345         [
346           CdValidators.requiredIf({
347             service_type: 'snmp-gateway'
348           })
349         ]
350       ],
351       snmp_v3_auth_password: [
352         null,
353         [
354           CdValidators.requiredIf({
355             service_type: 'snmp-gateway'
356           })
357         ]
358       ],
359       snmp_v3_priv_password: [
360         null,
361         [
362           CdValidators.requiredIf({
363             privacy_protocol: { op: '!empty' }
364           })
365         ]
366       ],
367       grafana_port: [null, [CdValidators.number(false)]],
368       grafana_admin_password: [null]
369     });
370   }
371
372   ngOnInit(): void {
373     this.action = this.actionLabels.CREATE;
374     if (this.router.url.includes('services/(modal:create')) {
375       this.pageURL = 'services';
376     } else if (this.router.url.includes('services/(modal:edit')) {
377       this.editing = true;
378       this.pageURL = 'services';
379       this.route.params.subscribe((params: { type: string; name: string }) => {
380         this.serviceName = params.name;
381         this.serviceType = params.type;
382       });
383     }
384
385     this.cephServiceService
386       .list(new HttpParams({ fromObject: { limit: -1, offset: 0 } }))
387       .observable.subscribe((services: CephServiceSpec[]) => {
388         this.serviceList = services;
389         this.services = services.filter((service: any) =>
390           this.INGRESS_SUPPORTED_SERVICE_TYPES.includes(service.service_type)
391         );
392       });
393
394     this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
395       // Remove service types:
396       // osd       - This is deployed a different way.
397       // container - This should only be used in the CLI.
398       this.hiddenServices.push('osd', 'container');
399
400       this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
401     });
402     this.hostService.getAllHosts().subscribe((resp: object[]) => {
403       const options: SelectOption[] = [];
404       _.forEach(resp, (host: object) => {
405         if (_.get(host, 'sources.orchestrator', false)) {
406           const option = new SelectOption(false, _.get(host, 'hostname'), '');
407           options.push(option);
408         }
409       });
410       this.hosts.options = [...options];
411     });
412     this.hostService.getLabels().subscribe((resp: string[]) => {
413       this.labels = resp;
414     });
415     this.poolService.getList().subscribe((resp: Array<object>) => {
416       this.pools = resp;
417     });
418
419     if (this.editing) {
420       this.action = this.actionLabels.EDIT;
421       this.disableForEditing(this.serviceType);
422       this.cephServiceService
423         .list(new HttpParams({ fromObject: { limit: -1, offset: 0 } }), this.serviceName)
424         .observable.subscribe((response: CephServiceSpec[]) => {
425           const formKeys = ['service_type', 'service_id', 'unmanaged'];
426           formKeys.forEach((keys) => {
427             this.serviceForm.get(keys).setValue(response[0][keys]);
428           });
429           if (!response[0]['unmanaged']) {
430             const placementKey = Object.keys(response[0]['placement'])[0];
431             let placementValue: string;
432             ['hosts', 'label'].indexOf(placementKey) >= 0
433               ? (placementValue = placementKey)
434               : (placementValue = 'hosts');
435             this.serviceForm.get('placement').setValue(placementValue);
436             this.serviceForm.get('count').setValue(response[0]['placement']['count']);
437             if (response[0]?.placement[placementValue]) {
438               this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
439             }
440           }
441           switch (this.serviceType) {
442             case 'iscsi':
443               const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
444               specKeys.forEach((key) => {
445                 this.serviceForm.get(key).setValue(response[0].spec[key]);
446               });
447               this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
448               if (response[0].spec?.api_secure) {
449                 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
450                 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
451               }
452               break;
453             case 'rgw':
454               this.serviceForm
455                 .get('rgw_frontend_port')
456                 .setValue(response[0].spec?.rgw_frontend_port);
457               this.getServiceIds(
458                 'rgw',
459                 response[0].spec?.rgw_realm,
460                 response[0].spec?.rgw_zonegroup,
461                 response[0].spec?.rgw_zone
462               );
463               this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
464               if (response[0].spec?.ssl) {
465                 this.serviceForm
466                   .get('ssl_cert')
467                   .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
468               }
469               break;
470             case 'ingress':
471               const ingressSpecKeys = [
472                 'backend_service',
473                 'virtual_ip',
474                 'frontend_port',
475                 'monitor_port',
476                 'virtual_interface_networks',
477                 'ssl'
478               ];
479               ingressSpecKeys.forEach((key) => {
480                 this.serviceForm.get(key).setValue(response[0].spec[key]);
481               });
482               if (response[0].spec?.ssl) {
483                 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
484                 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
485               }
486               break;
487             case 'snmp-gateway':
488               const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
489               snmpCommonSpecKeys.forEach((key) => {
490                 this.serviceForm.get(key).setValue(response[0].spec[key]);
491               });
492               if (this.serviceForm.getValue('snmp_version') === 'V3') {
493                 const snmpV3SpecKeys = [
494                   'engine_id',
495                   'auth_protocol',
496                   'privacy_protocol',
497                   'snmp_v3_auth_username',
498                   'snmp_v3_auth_password',
499                   'snmp_v3_priv_password'
500                 ];
501                 snmpV3SpecKeys.forEach((key) => {
502                   if (key !== null) {
503                     if (
504                       key === 'snmp_v3_auth_username' ||
505                       key === 'snmp_v3_auth_password' ||
506                       key === 'snmp_v3_priv_password'
507                     ) {
508                       this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
509                     } else {
510                       this.serviceForm.get(key).setValue(response[0].spec[key]);
511                     }
512                   }
513                 });
514               } else {
515                 this.serviceForm
516                   .get('snmp_community')
517                   .setValue(response[0].spec['credentials']['snmp_community']);
518               }
519               break;
520             case 'grafana':
521               this.serviceForm.get('grafana_port').setValue(response[0].spec.port);
522               this.serviceForm
523                 .get('grafana_admin_password')
524                 .setValue(response[0].spec.initial_admin_password);
525               break;
526           }
527         });
528     }
529   }
530
531   getDefaultsEntities(
532     defaultRealmId: string,
533     defaultZonegroupId: string,
534     defaultZoneId: string
535   ): { defaultRealmName: string; defaultZonegroupName: string; defaultZoneName: string } {
536     const defaultRealm = this.realmList.find((x: { id: string }) => x.id === defaultRealmId);
537     const defaultZonegroup = this.zonegroupList.find(
538       (x: { id: string }) => x.id === defaultZonegroupId
539     );
540     const defaultZone = this.zoneList.find((x: { id: string }) => x.id === defaultZoneId);
541     const defaultRealmName = defaultRealm !== undefined ? defaultRealm.name : null;
542     const defaultZonegroupName = defaultZonegroup !== undefined ? defaultZonegroup.name : 'default';
543     const defaultZoneName = defaultZone !== undefined ? defaultZone.name : 'default';
544     if (defaultZonegroupName === 'default' && !this.zonegroupNames.includes(defaultZonegroupName)) {
545       const defaultZonegroup = new RgwZonegroup();
546       defaultZonegroup.name = 'default';
547       this.zonegroupList.push(defaultZonegroup);
548     }
549     if (defaultZoneName === 'default' && !this.zoneNames.includes(defaultZoneName)) {
550       const defaultZone = new RgwZone();
551       defaultZone.name = 'default';
552       this.zoneList.push(defaultZone);
553     }
554     return {
555       defaultRealmName: defaultRealmName,
556       defaultZonegroupName: defaultZonegroupName,
557       defaultZoneName: defaultZoneName
558     };
559   }
560
561   getServiceIds(
562     selectedServiceType: string,
563     realm_name?: string,
564     zonegroup_name?: string,
565     zone_name?: string
566   ) {
567     this.serviceIds = this.serviceList
568       ?.filter((service) => service['service_type'] === selectedServiceType)
569       .map((service) => service['service_id']);
570
571     if (selectedServiceType === 'rgw') {
572       const observables = [
573         this.rgwRealmService.getAllRealmsInfo(),
574         this.rgwZonegroupService.getAllZonegroupsInfo(),
575         this.rgwZoneService.getAllZonesInfo()
576       ];
577       this.sub = forkJoin(observables).subscribe(
578         (multisiteInfo: [object, object, object]) => {
579           this.multisiteInfo = multisiteInfo;
580           this.realmList =
581             this.multisiteInfo[0] !== undefined && this.multisiteInfo[0].hasOwnProperty('realms')
582               ? this.multisiteInfo[0]['realms']
583               : [];
584           this.zonegroupList =
585             this.multisiteInfo[1] !== undefined &&
586             this.multisiteInfo[1].hasOwnProperty('zonegroups')
587               ? this.multisiteInfo[1]['zonegroups']
588               : [];
589           this.zoneList =
590             this.multisiteInfo[2] !== undefined && this.multisiteInfo[2].hasOwnProperty('zones')
591               ? this.multisiteInfo[2]['zones']
592               : [];
593           this.realmNames = this.realmList.map((realm) => {
594             return realm['name'];
595           });
596           this.zonegroupNames = this.zonegroupList.map((zonegroup) => {
597             return zonegroup['name'];
598           });
599           this.zoneNames = this.zoneList.map((zone) => {
600             return zone['name'];
601           });
602           this.defaultRealmId = multisiteInfo[0]['default_realm'];
603           this.defaultZonegroupId = multisiteInfo[1]['default_zonegroup'];
604           this.defaultZoneId = multisiteInfo[2]['default_zone'];
605           this.defaultsInfo = this.getDefaultsEntities(
606             this.defaultRealmId,
607             this.defaultZonegroupId,
608             this.defaultZoneId
609           );
610           if (!this.editing) {
611             this.serviceForm.get('realm_name').setValue(this.defaultsInfo['defaultRealmName']);
612             this.serviceForm
613               .get('zonegroup_name')
614               .setValue(this.defaultsInfo['defaultZonegroupName']);
615             this.serviceForm.get('zone_name').setValue(this.defaultsInfo['defaultZoneName']);
616           } else {
617             if (realm_name && !this.realmNames.includes(realm_name)) {
618               const realm = new RgwRealm();
619               realm.name = realm_name;
620               this.realmList.push(realm);
621             }
622             if (zonegroup_name && !this.zonegroupNames.includes(zonegroup_name)) {
623               const zonegroup = new RgwZonegroup();
624               zonegroup.name = zonegroup_name;
625               this.zonegroupList.push(zonegroup);
626             }
627             if (zone_name && !this.zoneNames.includes(zone_name)) {
628               const zone = new RgwZone();
629               zone.name = zone_name;
630               this.zoneList.push(zone);
631             }
632             if (zonegroup_name === undefined && zone_name === undefined) {
633               zonegroup_name = 'default';
634               zone_name = 'default';
635             }
636             this.serviceForm.get('realm_name').setValue(realm_name);
637             this.serviceForm.get('zonegroup_name').setValue(zonegroup_name);
638             this.serviceForm.get('zone_name').setValue(zone_name);
639           }
640           if (this.realmList.length === 0) {
641             this.showRealmCreationForm = true;
642           } else {
643             this.showRealmCreationForm = false;
644           }
645         },
646         (_error) => {
647           const defaultZone = new RgwZone();
648           defaultZone.name = 'default';
649           const defaultZonegroup = new RgwZonegroup();
650           defaultZonegroup.name = 'default';
651           this.zoneList.push(defaultZone);
652           this.zonegroupList.push(defaultZonegroup);
653         }
654       );
655     }
656   }
657
658   disableForEditing(serviceType: string) {
659     const disableForEditKeys = ['service_type', 'service_id'];
660     disableForEditKeys.forEach((key) => {
661       this.serviceForm.get(key).disable();
662     });
663     switch (serviceType) {
664       case 'ingress':
665         this.serviceForm.get('backend_service').disable();
666     }
667   }
668
669   searchLabels = (text$: Observable<string>) => {
670     return merge(
671       text$.pipe(debounceTime(200), distinctUntilChanged()),
672       this.labelFocus,
673       this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
674     ).pipe(
675       map((value) =>
676         this.labels
677           .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
678           .slice(0, 10)
679       )
680     );
681   };
682
683   fileUpload(files: FileList, controlName: string) {
684     const file: File = files[0];
685     const reader = new FileReader();
686     reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
687       const control: AbstractControl = this.serviceForm.get(controlName);
688       control.setValue(event.target.result);
689       control.markAsDirty();
690       control.markAsTouched();
691       control.updateValueAndValidity();
692     });
693     reader.readAsText(file, 'utf8');
694   }
695
696   prePopulateId() {
697     const control: AbstractControl = this.serviceForm.get('service_id');
698     const backendService = this.serviceForm.getValue('backend_service');
699     // Set Id as read-only
700     control.reset({ value: backendService, disabled: true });
701   }
702
703   onSubmit() {
704     const self = this;
705     const values: object = this.serviceForm.getRawValue();
706     const serviceType: string = values['service_type'];
707     let taskUrl = `service/${URLVerbs.CREATE}`;
708     if (this.editing) {
709       taskUrl = `service/${URLVerbs.EDIT}`;
710     }
711     const serviceSpec: object = {
712       service_type: serviceType,
713       placement: {},
714       unmanaged: values['unmanaged']
715     };
716     let svcId: string;
717     if (serviceType === 'rgw') {
718       serviceSpec['rgw_realm'] = values['realm_name'] ? values['realm_name'] : null;
719       serviceSpec['rgw_zonegroup'] =
720         values['zonegroup_name'] !== 'default' ? values['zonegroup_name'] : null;
721       serviceSpec['rgw_zone'] = values['zone_name'] !== 'default' ? values['zone_name'] : null;
722       svcId = values['service_id'];
723     } else {
724       svcId = values['service_id'];
725     }
726     const serviceId: string = svcId;
727     let serviceName: string = serviceType;
728     if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
729       serviceName = `${serviceType}.${serviceId}`;
730       serviceSpec['service_id'] = serviceId;
731     }
732
733     // These services has some fields to be
734     // filled out even if unmanaged is true
735     switch (serviceType) {
736       case 'ingress':
737         serviceSpec['backend_service'] = values['backend_service'];
738         serviceSpec['service_id'] = values['backend_service'];
739         if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
740           serviceSpec['frontend_port'] = values['frontend_port'];
741         }
742         if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
743           serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
744         }
745         if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
746           serviceSpec['monitor_port'] = values['monitor_port'];
747         }
748         break;
749
750       case 'iscsi':
751         serviceSpec['pool'] = values['pool'];
752         break;
753
754       case 'snmp-gateway':
755         serviceSpec['credentials'] = {};
756         serviceSpec['snmp_version'] = values['snmp_version'];
757         serviceSpec['snmp_destination'] = values['snmp_destination'];
758         if (values['snmp_version'] === 'V3') {
759           serviceSpec['engine_id'] = values['engine_id'];
760           serviceSpec['auth_protocol'] = values['auth_protocol'];
761           serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
762           serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
763           if (values['privacy_protocol'] !== null) {
764             serviceSpec['privacy_protocol'] = values['privacy_protocol'];
765             serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
766           }
767         } else {
768           serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
769         }
770         break;
771     }
772
773     if (!values['unmanaged']) {
774       switch (values['placement']) {
775         case 'hosts':
776           if (values['hosts'].length > 0) {
777             serviceSpec['placement']['hosts'] = values['hosts'];
778           }
779           break;
780         case 'label':
781           serviceSpec['placement']['label'] = values['label'];
782           break;
783       }
784       if (_.isNumber(values['count']) && values['count'] > 0) {
785         serviceSpec['placement']['count'] = values['count'];
786       }
787       switch (serviceType) {
788         case 'rgw':
789           if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
790             serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
791           }
792           serviceSpec['ssl'] = values['ssl'];
793           if (values['ssl']) {
794             serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
795           }
796           break;
797         case 'iscsi':
798           if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
799             serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
800           }
801           if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
802             serviceSpec['api_port'] = values['api_port'];
803           }
804           serviceSpec['api_user'] = values['api_user'];
805           serviceSpec['api_password'] = values['api_password'];
806           serviceSpec['api_secure'] = values['ssl'];
807           if (values['ssl']) {
808             serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
809             serviceSpec['ssl_key'] = values['ssl_key']?.trim();
810           }
811           break;
812         case 'ingress':
813           serviceSpec['ssl'] = values['ssl'];
814           if (values['ssl']) {
815             serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
816             serviceSpec['ssl_key'] = values['ssl_key']?.trim();
817           }
818           serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
819           break;
820         case 'grafana':
821           serviceSpec['port'] = values['grafana_port'];
822           serviceSpec['initial_admin_password'] = values['grafana_admin_password'];
823       }
824     }
825
826     this.taskWrapperService
827       .wrapTaskAroundCall({
828         task: new FinishedTask(taskUrl, {
829           service_name: serviceName
830         }),
831         call: this.editing
832           ? this.cephServiceService.update(serviceSpec)
833           : this.cephServiceService.create(serviceSpec)
834       })
835       .subscribe({
836         error() {
837           self.serviceForm.setErrors({ cdSubmitButton: true });
838         },
839         complete: () => {
840           this.pageURL === 'services'
841             ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
842             : this.activeModal.close();
843         }
844       });
845   }
846
847   clearValidations() {
848     const snmpVersion = this.serviceForm.getValue('snmp_version');
849     const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
850     if (snmpVersion === 'V3') {
851       this.serviceForm.get('snmp_community').clearValidators();
852     } else {
853       this.serviceForm.get('engine_id').clearValidators();
854       this.serviceForm.get('auth_protocol').clearValidators();
855       this.serviceForm.get('privacy_protocol').clearValidators();
856       this.serviceForm.get('snmp_v3_auth_username').clearValidators();
857       this.serviceForm.get('snmp_v3_auth_password').clearValidators();
858     }
859     if (privacyProtocol === null) {
860       this.serviceForm.get('snmp_v3_priv_password').clearValidators();
861     }
862   }
863
864   createMultisiteSetup() {
865     this.bsModalRef = this.modalService.show(CreateRgwServiceEntitiesComponent, {
866       size: 'lg'
867     });
868     this.bsModalRef.componentInstance.submitAction.subscribe(() => {
869       this.getServiceIds('rgw');
870     });
871   }
872 }