]> git.apps.os.sepia.ceph.com Git - ceph.git/blob
5d979137a3a0c94a190d578927c5ddbc34a9f485
[ceph.git] /
1 import { HttpParams } from '@angular/common/http';
2 import { Component, Input, OnInit, ViewChild } from '@angular/core';
3 import { AbstractControl, UntypedFormControl, Validators } from '@angular/forms';
4 import { ActivatedRoute, Router } from '@angular/router';
5
6 import { NgbActiveModal, NgbModalRef, NgbTypeahead } from '@ng-bootstrap/ng-bootstrap';
7 import { ListItem } from 'carbon-components-angular';
8 import _ from 'lodash';
9 import { forkJoin, merge, Observable, Subject, Subscription } from 'rxjs';
10 import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators';
11 import { Pool } from '~/app/ceph/pool/pool';
12 import { CreateRgwServiceEntitiesComponent } from '~/app/ceph/rgw/create-rgw-service-entities/create-rgw-service-entities.component';
13 import { RgwRealm, RgwZonegroup, RgwZone } from '~/app/ceph/rgw/models/rgw-multisite';
14
15 import { CephServiceService } from '~/app/shared/api/ceph-service.service';
16 import { HostService } from '~/app/shared/api/host.service';
17 import { PoolService } from '~/app/shared/api/pool.service';
18 import { RbdService } from '~/app/shared/api/rbd.service';
19 import { RgwMultisiteService } from '~/app/shared/api/rgw-multisite.service';
20 import { RgwRealmService } from '~/app/shared/api/rgw-realm.service';
21 import { RgwZoneService } from '~/app/shared/api/rgw-zone.service';
22 import { RgwZonegroupService } from '~/app/shared/api/rgw-zonegroup.service';
23 import { SelectMessages } from '~/app/shared/components/select/select-messages.model';
24 import { SelectOption } from '~/app/shared/components/select/select-option.model';
25 import {
26   ActionLabelsI18n,
27   TimerServiceInterval,
28   URLVerbs,
29   SSL_PROTOCOLS,
30   SSL_CIPHERS
31 } from '~/app/shared/constants/app.constants';
32 import { CdForm } from '~/app/shared/forms/cd-form';
33 import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
34 import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
35 import { CdValidators } from '~/app/shared/forms/cd-validators';
36 import { FinishedTask } from '~/app/shared/models/finished-task';
37 import { CephServiceSpec } from '~/app/shared/models/service.interface';
38 import { ModalService } from '~/app/shared/services/modal.service';
39 import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service';
40 import { TimerService } from '~/app/shared/services/timer.service';
41
42 @Component({
43   selector: 'cd-service-form',
44   templateUrl: './service-form.component.html',
45   styleUrls: ['./service-form.component.scss']
46 })
47 export class ServiceFormComponent extends CdForm implements OnInit {
48   public sub = new Subscription();
49
50   readonly MDS_SVC_ID_PATTERN = /^[a-zA-Z_.-][a-zA-Z0-9_.-]*$/;
51   readonly SNMP_DESTINATION_PATTERN = /^[^\:]+:[0-9]/;
52   readonly SNMP_ENGINE_ID_PATTERN = /^[0-9A-Fa-f]{10,64}/g;
53   readonly INGRESS_SUPPORTED_SERVICE_TYPES = ['rgw', 'nfs'];
54   readonly SMB_CONFIG_URI_PATTERN = /^(http:|https:|rados:|rados:mon-config-key:)/;
55   readonly OAUTH2_ISSUER_URL_PATTERN = /^(https?:\/\/)?([a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+)(:[0-9]{1,5})?(\/.*)?$/;
56   readonly SSL_CIPHERS_PATTERN = /^[a-zA-Z0-9\-:]+$/;
57   readonly DEFAULT_SSL_PROTOCOL_ITEM = [{ content: 'TLSv1.3', selected: true }];
58   @ViewChild(NgbTypeahead, { static: false })
59   typeahead: NgbTypeahead;
60
61   @Input() hiddenServices: string[] = [];
62
63   @Input() editing = false;
64
65   @Input() serviceName: string;
66
67   @Input() serviceType: string;
68
69   serviceForm: CdFormGroup;
70   action: string;
71   resource: string;
72   serviceTypes: string[] = [];
73   serviceIds: string[] = [];
74   hosts: any;
75   labels: string[];
76   labelClick = new Subject<string>();
77   labelFocus = new Subject<string>();
78   pools: Array<Pool>;
79   rbdPools: Array<Pool>;
80   services: Array<CephServiceSpec> = [];
81   pageURL: string;
82   serviceList: CephServiceSpec[];
83   multisiteInfo: object[] = [];
84   defaultRealmId = '';
85   defaultZonegroupId = '';
86   defaultZoneId = '';
87   realmList: RgwRealm[] = [];
88   zonegroupList: RgwZonegroup[] = [];
89   zoneList: RgwZone[] = [];
90   bsModalRef: NgbModalRef;
91   defaultZonegroup: RgwZonegroup;
92   showRealmCreationForm = false;
93   defaultsInfo: { defaultRealmName: string; defaultZonegroupName: string; defaultZoneName: string };
94   realmNames: string[];
95   zonegroupNames: string[];
96   zoneNames: string[];
97   smbFeaturesList = ['domain'];
98   currentURL: string;
99   port: number = 443;
100   sslProtocolsItems: Array<ListItem> = Object.values(SSL_PROTOCOLS).map((protocol) => ({
101     content: protocol,
102     selected: true
103   }));
104   sslCiphersItems: Array<ListItem> = Object.values(SSL_CIPHERS).map((cipher) => ({
105     content: cipher,
106     selected: false
107   }));
108   showMgmtGatewayMessage: boolean = false;
109
110   constructor(
111     public actionLabels: ActionLabelsI18n,
112     private cephServiceService: CephServiceService,
113     private formBuilder: CdFormBuilder,
114     private hostService: HostService,
115     private poolService: PoolService,
116     private rbdService: RbdService,
117     private router: Router,
118     private taskWrapperService: TaskWrapperService,
119     public timerService: TimerService,
120     public timerServiceVariable: TimerServiceInterval,
121     public rgwRealmService: RgwRealmService,
122     public rgwZonegroupService: RgwZonegroupService,
123     public rgwZoneService: RgwZoneService,
124     public rgwMultisiteService: RgwMultisiteService,
125     private route: ActivatedRoute,
126     public activeModal: NgbActiveModal,
127     public modalService: ModalService
128   ) {
129     super();
130     this.resource = $localize`service`;
131     this.hosts = {
132       options: [],
133       messages: new SelectMessages({
134         empty: $localize`There are no hosts.`,
135         filter: $localize`Filter hosts`
136       })
137     };
138     this.createForm();
139   }
140
141   createForm() {
142     this.serviceForm = this.formBuilder.group({
143       // Global
144       service_type: [null, [Validators.required]],
145       service_id: [
146         null,
147         [
148           CdValidators.composeIf(
149             {
150               service_type: 'mds'
151             },
152             [
153               Validators.required,
154               CdValidators.custom('mdsPattern', (value: string) => {
155                 if (_.isEmpty(value)) {
156                   return false;
157                 }
158                 return !this.MDS_SVC_ID_PATTERN.test(value);
159               })
160             ]
161           ),
162           CdValidators.requiredIf({
163             service_type: 'nfs'
164           }),
165           CdValidators.requiredIf({
166             service_type: 'iscsi'
167           }),
168           CdValidators.requiredIf({
169             service_type: 'nvmeof'
170           }),
171           CdValidators.requiredIf({
172             service_type: 'ingress'
173           }),
174           CdValidators.requiredIf({
175             service_type: 'smb'
176           }),
177           CdValidators.composeIf(
178             {
179               service_type: 'rgw'
180             },
181             [Validators.required]
182           ),
183           CdValidators.custom('uniqueName', (service_id: string) => {
184             return this.serviceIds && this.serviceIds.includes(service_id);
185           })
186         ]
187       ],
188       placement: ['hosts'],
189       label: [
190         null,
191         [
192           CdValidators.requiredIf({
193             placement: 'label',
194             unmanaged: false
195           })
196         ]
197       ],
198       hosts: [[]],
199       count: [null, [CdValidators.number(false)]],
200       unmanaged: [false],
201       // iSCSI
202       // NVMe/TCP
203       pool: [
204         null,
205         [
206           CdValidators.requiredIf({
207             service_type: 'iscsi'
208           }),
209           CdValidators.requiredIf({
210             service_type: 'nvmeof'
211           })
212         ]
213       ],
214       group: [
215         'default',
216         CdValidators.requiredIf({
217           service_type: 'nvmeof'
218         })
219       ],
220       enable_mtls: [false],
221       root_ca_cert: [
222         null,
223         [
224           CdValidators.composeIf(
225             {
226               service_type: 'nvmeof',
227               enable_mtls: true
228             },
229             [Validators.required]
230           )
231         ]
232       ],
233       client_cert: [
234         null,
235         [
236           CdValidators.composeIf(
237             {
238               service_type: 'nvmeof',
239               enable_mtls: true
240             },
241             [Validators.required]
242           )
243         ]
244       ],
245       client_key: [
246         null,
247         [
248           CdValidators.composeIf(
249             {
250               service_type: 'nvmeof',
251               enable_mtls: true
252             },
253             [Validators.required]
254           )
255         ]
256       ],
257       server_cert: [
258         null,
259         [
260           CdValidators.composeIf(
261             {
262               service_type: 'nvmeof',
263               enable_mtls: true
264             },
265             [Validators.required]
266           )
267         ]
268       ],
269       server_key: [
270         null,
271         [
272           CdValidators.composeIf(
273             {
274               service_type: 'nvmeof',
275               enable_mtls: true
276             },
277             [Validators.required]
278           )
279         ]
280       ],
281       // RGW
282       rgw_frontend_port: [null, [CdValidators.number(false)]],
283       realm_name: [null],
284       zonegroup_name: [null],
285       zone_name: [null],
286       // iSCSI
287       trusted_ip_list: [null],
288       api_port: [null, [CdValidators.number(false)]],
289       api_user: [
290         null,
291         [
292           CdValidators.requiredIf({
293             service_type: 'iscsi',
294             unmanaged: false
295           })
296         ]
297       ],
298       api_password: [
299         null,
300         [
301           CdValidators.requiredIf({
302             service_type: 'iscsi',
303             unmanaged: false
304           })
305         ]
306       ],
307       // smb
308       cluster_id: [
309         null,
310         [
311           CdValidators.requiredIf({
312             service_type: 'smb'
313           })
314         ]
315       ],
316       features: new CdFormGroup(
317         this.smbFeaturesList.reduce((acc: object, e) => {
318           acc[e] = new UntypedFormControl(false);
319           return acc;
320         }, {})
321       ),
322       config_uri: [
323         null,
324         [
325           CdValidators.composeIf(
326             {
327               service_type: 'smb'
328             },
329             [
330               Validators.required,
331               CdValidators.custom('configUriPattern', (value: string) => {
332                 if (_.isEmpty(value)) {
333                   return false;
334                 }
335                 return !this.SMB_CONFIG_URI_PATTERN.test(value);
336               })
337             ]
338           )
339         ]
340       ],
341       custom_dns: [null],
342       join_sources: [null],
343       user_sources: [null],
344       include_ceph_users: [null],
345       // Ingress
346       backend_service: [
347         null,
348         [
349           CdValidators.requiredIf({
350             service_type: 'ingress'
351           })
352         ]
353       ],
354       virtual_ip: [
355         null,
356         [
357           CdValidators.requiredIf({
358             service_type: 'ingress'
359           })
360         ]
361       ],
362       frontend_port: [
363         null,
364         [
365           CdValidators.number(false),
366           CdValidators.requiredIf({
367             service_type: 'ingress'
368           })
369         ]
370       ],
371       monitor_port: [
372         null,
373         [
374           CdValidators.number(false),
375           CdValidators.requiredIf({
376             service_type: 'ingress'
377           })
378         ]
379       ],
380       virtual_interface_networks: [null],
381       ssl_protocols: [this.DEFAULT_SSL_PROTOCOL_ITEM],
382       ssl_ciphers: [
383         null,
384         [
385           CdValidators.custom('invalidPattern', (ciphers: string) => {
386             if (_.isEmpty(ciphers)) {
387               return false;
388             }
389             return !this.SSL_CIPHERS_PATTERN.test(ciphers);
390           })
391         ]
392       ],
393       // RGW, Ingress & iSCSI
394       ssl: [false],
395       ssl_cert: [
396         '',
397         [
398           CdValidators.composeIf(
399             {
400               service_type: 'rgw',
401               unmanaged: false,
402               ssl: true
403             },
404             [Validators.required, CdValidators.pemCert()]
405           ),
406           CdValidators.composeIf(
407             {
408               service_type: 'iscsi',
409               unmanaged: false,
410               ssl: true
411             },
412             [Validators.required, CdValidators.sslCert()]
413           ),
414           CdValidators.composeIf(
415             {
416               service_type: 'ingress',
417               unmanaged: false,
418               ssl: true
419             },
420             [Validators.required, CdValidators.pemCert()]
421           ),
422           CdValidators.composeIf(
423             {
424               service_type: 'oauth2-proxy',
425               unmanaged: false,
426               ssl: true
427             },
428             [Validators.required, CdValidators.sslCert()]
429           ),
430           CdValidators.composeIf(
431             {
432               service_type: 'mgmt-gateway',
433               unmanaged: false,
434               ssl: false
435             },
436             [CdValidators.sslCert()]
437           )
438         ]
439       ],
440       ssl_key: [
441         '',
442         [
443           CdValidators.composeIf(
444             {
445               service_type: 'iscsi',
446               unmanaged: false,
447               ssl: true
448             },
449             [Validators.required, CdValidators.sslPrivKey()]
450           ),
451           CdValidators.composeIf(
452             {
453               service_type: 'oauth2-proxy',
454               unmanaged: false,
455               ssl: true
456             },
457             [Validators.required, CdValidators.sslPrivKey()]
458           ),
459           CdValidators.composeIf(
460             {
461               service_type: 'mgmt-gateway',
462               unmanaged: false,
463               ssl: false
464             },
465             [CdValidators.sslPrivKey()]
466           )
467         ]
468       ],
469       // mgmt-gateway
470       enable_auth: [null],
471       port: [443, [CdValidators.number(false)]],
472       // snmp-gateway
473       snmp_version: [
474         null,
475         [
476           CdValidators.requiredIf({
477             service_type: 'snmp-gateway'
478           })
479         ]
480       ],
481       snmp_destination: [
482         null,
483         {
484           validators: [
485             CdValidators.requiredIf({
486               service_type: 'snmp-gateway'
487             }),
488             CdValidators.custom('snmpDestinationPattern', (value: string) => {
489               if (_.isEmpty(value)) {
490                 return false;
491               }
492               return !this.SNMP_DESTINATION_PATTERN.test(value);
493             })
494           ]
495         }
496       ],
497       engine_id: [
498         null,
499         [
500           CdValidators.requiredIf({
501             service_type: 'snmp-gateway'
502           }),
503           CdValidators.custom('snmpEngineIdPattern', (value: string) => {
504             if (_.isEmpty(value)) {
505               return false;
506             }
507             return !this.SNMP_ENGINE_ID_PATTERN.test(value);
508           })
509         ]
510       ],
511       auth_protocol: [
512         'SHA',
513         [
514           CdValidators.requiredIf({
515             service_type: 'snmp-gateway'
516           })
517         ]
518       ],
519       privacy_protocol: [null],
520       snmp_community: [
521         null,
522         [
523           CdValidators.requiredIf({
524             snmp_version: 'V2c'
525           })
526         ]
527       ],
528       snmp_v3_auth_username: [
529         null,
530         [
531           CdValidators.requiredIf({
532             service_type: 'snmp-gateway'
533           })
534         ]
535       ],
536       snmp_v3_auth_password: [
537         null,
538         [
539           CdValidators.requiredIf({
540             service_type: 'snmp-gateway'
541           })
542         ]
543       ],
544       snmp_v3_priv_password: [
545         null,
546         [
547           CdValidators.requiredIf({
548             privacy_protocol: { op: '!empty' }
549           })
550         ]
551       ],
552       grafana_port: [null, [CdValidators.number(false)]],
553       grafana_admin_password: [null],
554       // oauth2-proxy
555       provider_display_name: [
556         'My OIDC provider',
557         [
558           CdValidators.requiredIf({
559             service_type: 'oauth2-proxy'
560           })
561         ]
562       ],
563       client_id: [
564         null,
565         [
566           CdValidators.requiredIf({
567             service_type: 'oauth2-proxy'
568           })
569         ]
570       ],
571       client_secret: [
572         null,
573         [
574           CdValidators.requiredIf({
575             service_type: 'oauth2-proxy'
576           })
577         ]
578       ],
579       oidc_issuer_url: [
580         null,
581         [
582           CdValidators.requiredIf({
583             service_type: 'oauth2-proxy'
584           }),
585           CdValidators.custom('validUrl', (url: string) => {
586             if (_.isEmpty(url)) {
587               return false;
588             }
589             return !this.OAUTH2_ISSUER_URL_PATTERN.test(url);
590           })
591         ]
592       ],
593       https_address: [null, [CdValidators.oauthAddressTest()]],
594       redirect_url: [null],
595       allowlist_domains: [null]
596     });
597   }
598
599   resolveRoute() {
600     if (this.router.url.includes('services/(modal:create')) {
601       this.pageURL = 'services';
602       this.route.params.subscribe((params: { type: string }) => {
603         if (params?.type) {
604           this.serviceType = params.type;
605           this.serviceForm.get('service_type').setValue(this.serviceType);
606         }
607       });
608     } else if (this.router.url.includes('services/(modal:edit')) {
609       this.editing = true;
610       this.pageURL = 'services';
611       this.route.params.subscribe((params: { type: string; name: string }) => {
612         this.serviceName = params.name;
613         this.serviceType = params.type;
614       });
615     }
616   }
617
618   ngOnInit(): void {
619     this.action = this.actionLabels.CREATE;
620     this.resolveRoute();
621
622     this.cephServiceService
623       .list(new HttpParams({ fromObject: { limit: -1, offset: 0 } }))
624       .observable.subscribe((services: CephServiceSpec[]) => {
625         this.serviceList = services;
626         this.services = services.filter((service: any) =>
627           this.INGRESS_SUPPORTED_SERVICE_TYPES.includes(service.service_type)
628         );
629       });
630
631     this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
632       // Remove service types:
633       // osd       - This is deployed a different way.
634       // container - This should only be used in the CLI.
635       this.hiddenServices.push('osd', 'container');
636
637       this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
638     });
639     this.hostService.getAllHosts().subscribe((resp: object[]) => {
640       const options: SelectOption[] = [];
641       _.forEach(resp, (host: object) => {
642         if (_.get(host, 'sources.orchestrator', false)) {
643           const option = new SelectOption(false, _.get(host, 'hostname'), '');
644           options.push(option);
645         }
646       });
647       this.hosts.options = [...options];
648     });
649     this.hostService.getLabels().subscribe((resp: string[]) => {
650       this.labels = resp;
651     });
652     this.poolService.getList().subscribe((resp: Pool[]) => {
653       this.pools = resp;
654       this.rbdPools = this.pools.filter(this.rbdService.isRBDPool);
655       if (!this.editing && this.serviceType) {
656         this.onServiceTypeChange(this.serviceType);
657       }
658     });
659
660     if (this.editing) {
661       this.action = this.actionLabels.EDIT;
662       this.disableForEditing(this.serviceType);
663       this.cephServiceService
664         .list(new HttpParams({ fromObject: { limit: -1, offset: 0 } }), this.serviceName)
665         .observable.subscribe((response: CephServiceSpec[]) => {
666           const formKeys = ['service_type', 'service_id', 'unmanaged'];
667           formKeys.forEach((keys) => {
668             this.serviceForm.get(keys).setValue(response[0][keys]);
669           });
670           if (!response[0]['unmanaged']) {
671             const placementKey = Object.keys(response[0]['placement'])[0];
672             let placementValue: string;
673             ['hosts', 'label'].indexOf(placementKey) >= 0
674               ? (placementValue = placementKey)
675               : (placementValue = 'hosts');
676             this.serviceForm.get('placement').setValue(placementValue);
677             this.serviceForm.get('count').setValue(response[0]['placement']['count']);
678             if (response[0]?.placement[placementValue]) {
679               this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
680             }
681           }
682           switch (this.serviceType) {
683             case 'iscsi':
684               const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
685               specKeys.forEach((key) => {
686                 this.serviceForm.get(key).setValue(response[0].spec[key]);
687               });
688               this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
689               if (response[0].spec?.api_secure) {
690                 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
691                 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
692               }
693               break;
694             case 'nvmeof':
695               this.serviceForm.get('pool').setValue(response[0].spec.pool);
696               this.serviceForm.get('group').setValue(response[0].spec.group);
697               this.serviceForm.get('enable_mtls').setValue(response[0].spec?.enable_auth);
698               this.serviceForm.get('root_ca_cert').setValue(response[0].spec?.root_ca_cert);
699               this.serviceForm.get('client_cert').setValue(response[0].spec?.client_cert);
700               this.serviceForm.get('client_key').setValue(response[0].spec?.client_key);
701               this.serviceForm.get('server_cert').setValue(response[0].spec?.server_cert);
702               this.serviceForm.get('server_key').setValue(response[0].spec?.server_key);
703               break;
704             case 'rgw':
705               this.serviceForm
706                 .get('rgw_frontend_port')
707                 .setValue(response[0].spec?.rgw_frontend_port);
708               this.setRgwFields(
709                 response[0].spec?.rgw_realm,
710                 response[0].spec?.rgw_zonegroup,
711                 response[0].spec?.rgw_zone
712               );
713               this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
714               if (response[0].spec?.ssl) {
715                 this.serviceForm
716                   .get('ssl_cert')
717                   .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
718               }
719               break;
720             case 'ingress':
721               const ingressSpecKeys = [
722                 'backend_service',
723                 'virtual_ip',
724                 'frontend_port',
725                 'monitor_port',
726                 'virtual_interface_networks',
727                 'ssl'
728               ];
729               ingressSpecKeys.forEach((key) => {
730                 this.serviceForm.get(key).setValue(response[0].spec[key]);
731               });
732               if (response[0].spec?.ssl) {
733                 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
734                 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
735               }
736               break;
737             case 'mgmt-gateway':
738               let hrefSplitted = window.location.href.split(':');
739               this.currentURL = hrefSplitted[0] + hrefSplitted[1];
740               this.port = response[0].spec?.port;
741
742               if (response[0].spec?.ssl_protocols) {
743                 let selectedValues: Array<ListItem> = [];
744                 for (const value of response[0].spec.ssl_protocols) {
745                   selectedValues.push({ content: value, selected: true });
746                 }
747                 this.serviceForm.get('ssl_protocols').setValue(selectedValues);
748               }
749               if (response[0].spec?.ssl_ciphers) {
750                 this.serviceForm
751                   .get('ssl_ciphers')
752                   .setValue(response[0].spec?.ssl_ciphers.join(':'));
753               }
754               if (response[0].spec?.ssl_cert) {
755                 this.serviceForm.get('ssl_cert').setValue(response[0].spec.ssl_cert);
756               }
757               if (response[0].spec?.ssl_key) {
758                 this.serviceForm.get('ssl_key').setValue(response[0].spec.ssl_key);
759               }
760               if (response[0].spec?.enable_auth) {
761                 this.serviceForm.get('enable_auth').setValue(response[0].spec.enable_auth);
762               }
763               if (response[0].spec?.port) {
764                 this.serviceForm.get('port').setValue(response[0].spec.port);
765               }
766               break;
767             case 'smb':
768               const smbSpecKeys = [
769                 'cluster_id',
770                 'config_uri',
771                 'features',
772                 'join_sources',
773                 'user_sources',
774                 'custom_dns',
775                 'include_ceph_users'
776               ];
777               smbSpecKeys.forEach((key) => {
778                 if (key === 'features') {
779                   if (response[0].spec?.features) {
780                     response[0].spec.features.forEach((feature) => {
781                       this.serviceForm.get(`features.${feature}`).setValue(true);
782                     });
783                   }
784                 } else {
785                   this.serviceForm.get(key).setValue(response[0].spec[key]);
786                 }
787               });
788               break;
789             case 'snmp-gateway':
790               const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
791               snmpCommonSpecKeys.forEach((key) => {
792                 this.serviceForm.get(key).setValue(response[0].spec[key]);
793               });
794               if (this.serviceForm.getValue('snmp_version') === 'V3') {
795                 const snmpV3SpecKeys = [
796                   'engine_id',
797                   'auth_protocol',
798                   'privacy_protocol',
799                   'snmp_v3_auth_username',
800                   'snmp_v3_auth_password',
801                   'snmp_v3_priv_password'
802                 ];
803                 snmpV3SpecKeys.forEach((key) => {
804                   if (key !== null) {
805                     if (
806                       key === 'snmp_v3_auth_username' ||
807                       key === 'snmp_v3_auth_password' ||
808                       key === 'snmp_v3_priv_password'
809                     ) {
810                       this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
811                     } else {
812                       this.serviceForm.get(key).setValue(response[0].spec[key]);
813                     }
814                   }
815                 });
816               } else {
817                 this.serviceForm
818                   .get('snmp_community')
819                   .setValue(response[0].spec['credentials']['snmp_community']);
820               }
821               break;
822             case 'grafana':
823               this.serviceForm.get('grafana_port').setValue(response[0].spec.port);
824               this.serviceForm
825                 .get('grafana_admin_password')
826                 .setValue(response[0].spec.initial_admin_password);
827               break;
828             case 'oauth2-proxy':
829               const oauth2SpecKeys = [
830                 'https_address',
831                 'provider_display_name',
832                 'client_id',
833                 'client_secret',
834                 'oidc_issuer_url',
835                 'redirect_url',
836                 'allowlist_domains'
837               ];
838               oauth2SpecKeys.forEach((key) => {
839                 this.serviceForm.get(key).setValue(response[0].spec[key]);
840               });
841               if (response[0].spec?.ssl) {
842                 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
843                 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
844               }
845           }
846         });
847     }
848     this.detectChanges();
849   }
850
851   detectChanges(): void {
852     const service_type = this.serviceForm.get('service_type');
853     if (service_type) {
854       service_type.valueChanges.subscribe((value) => {
855         if (value === 'mgmt-gateway') {
856           const port = this.serviceForm.get('port');
857           if (port) {
858             port.valueChanges.subscribe((_) => {
859               this.showMgmtGatewayMessage = true;
860             });
861           }
862           const ssl_protocols = this.serviceForm.get('ssl_protocols');
863           if (ssl_protocols) {
864             ssl_protocols.valueChanges.subscribe((_) => {
865               this.showMgmtGatewayMessage = true;
866             });
867           }
868           const ssl_ciphers = this.serviceForm.get('ssl_ciphers');
869           if (ssl_ciphers) {
870             ssl_ciphers.valueChanges.subscribe((_) => {
871               this.showMgmtGatewayMessage = true;
872             });
873           }
874         }
875       });
876     }
877   }
878
879   getDefaultsEntitiesForRgw(
880     defaultRealmId: string,
881     defaultZonegroupId: string,
882     defaultZoneId: string
883   ): { defaultRealmName: string; defaultZonegroupName: string; defaultZoneName: string } {
884     const defaultRealm = this.realmList.find((x: { id: string }) => x.id === defaultRealmId);
885     const defaultZonegroup = this.zonegroupList.find(
886       (x: { id: string }) => x.id === defaultZonegroupId
887     );
888     const defaultZone = this.zoneList.find((x: { id: string }) => x.id === defaultZoneId);
889     const defaultRealmName = defaultRealm !== undefined ? defaultRealm.name : null;
890     const defaultZonegroupName = defaultZonegroup !== undefined ? defaultZonegroup.name : 'default';
891     const defaultZoneName = defaultZone !== undefined ? defaultZone.name : 'default';
892     if (defaultZonegroupName === 'default' && !this.zonegroupNames.includes(defaultZonegroupName)) {
893       const defaultZonegroup = new RgwZonegroup();
894       defaultZonegroup.name = 'default';
895       this.zonegroupList.push(defaultZonegroup);
896     }
897     if (defaultZoneName === 'default' && !this.zoneNames.includes(defaultZoneName)) {
898       const defaultZone = new RgwZone();
899       defaultZone.name = 'default';
900       this.zoneList.push(defaultZone);
901     }
902     return {
903       defaultRealmName: defaultRealmName,
904       defaultZonegroupName: defaultZonegroupName,
905       defaultZoneName: defaultZoneName
906     };
907   }
908
909   getDefaultPlacementCount(serviceType: string) {
910     /**
911      * `defaults` from src/pybind/mgr/cephadm/module.py
912      */
913     switch (serviceType) {
914       case 'mon':
915         this.serviceForm.get('count').setValue(5);
916         break;
917       case 'mgr':
918       case 'mds':
919       case 'rgw':
920       case 'ingress':
921       case 'rbd-mirror':
922         this.serviceForm.get('count').setValue(2);
923         break;
924       case 'iscsi':
925       case 'cephfs-mirror':
926       case 'nfs':
927       case 'grafana':
928       case 'alertmanager':
929       case 'prometheus':
930       case 'loki':
931       case 'container':
932       case 'snmp-gateway':
933       case 'elastic-serach':
934       case 'jaeger-collector':
935       case 'jaeger-query':
936       case 'smb':
937       case 'oauth2-proxy':
938       case 'mgmt-gateway':
939         this.serviceForm.get('count').setValue(1);
940         break;
941       default:
942         this.serviceForm.get('count').setValue(null);
943     }
944   }
945
946   setRgwFields(realm_name?: string, zonegroup_name?: string, zone_name?: string) {
947     const observables = [
948       this.rgwRealmService.getAllRealmsInfo(),
949       this.rgwZonegroupService.getAllZonegroupsInfo(),
950       this.rgwZoneService.getAllZonesInfo()
951     ];
952     this.sub = forkJoin(observables).subscribe(
953       (multisiteInfo: [object, object, object]) => {
954         this.multisiteInfo = multisiteInfo;
955         this.realmList =
956           this.multisiteInfo[0] !== undefined && this.multisiteInfo[0].hasOwnProperty('realms')
957             ? this.multisiteInfo[0]['realms']
958             : [];
959         this.zonegroupList =
960           this.multisiteInfo[1] !== undefined && this.multisiteInfo[1].hasOwnProperty('zonegroups')
961             ? this.multisiteInfo[1]['zonegroups']
962             : [];
963         this.zoneList =
964           this.multisiteInfo[2] !== undefined && this.multisiteInfo[2].hasOwnProperty('zones')
965             ? this.multisiteInfo[2]['zones']
966             : [];
967         this.realmNames = this.realmList.map((realm) => {
968           return realm['name'];
969         });
970         this.zonegroupNames = this.zonegroupList.map((zonegroup) => {
971           return zonegroup['name'];
972         });
973         this.zoneNames = this.zoneList.map((zone) => {
974           return zone['name'];
975         });
976         this.defaultRealmId = multisiteInfo[0]['default_realm'];
977         this.defaultZonegroupId = multisiteInfo[1]['default_zonegroup'];
978         this.defaultZoneId = multisiteInfo[2]['default_zone'];
979         this.defaultsInfo = this.getDefaultsEntitiesForRgw(
980           this.defaultRealmId,
981           this.defaultZonegroupId,
982           this.defaultZoneId
983         );
984         if (!this.editing) {
985           this.serviceForm.get('realm_name').setValue(this.defaultsInfo['defaultRealmName']);
986           this.serviceForm
987             .get('zonegroup_name')
988             .setValue(this.defaultsInfo['defaultZonegroupName']);
989           this.serviceForm.get('zone_name').setValue(this.defaultsInfo['defaultZoneName']);
990         } else {
991           if (realm_name && !this.realmNames.includes(realm_name)) {
992             const realm = new RgwRealm();
993             realm.name = realm_name;
994             this.realmList.push(realm);
995           }
996           if (zonegroup_name && !this.zonegroupNames.includes(zonegroup_name)) {
997             const zonegroup = new RgwZonegroup();
998             zonegroup.name = zonegroup_name;
999             this.zonegroupList.push(zonegroup);
1000           }
1001           if (zone_name && !this.zoneNames.includes(zone_name)) {
1002             const zone = new RgwZone();
1003             zone.name = zone_name;
1004             this.zoneList.push(zone);
1005           }
1006           if (zonegroup_name === undefined && zone_name === undefined) {
1007             zonegroup_name = 'default';
1008             zone_name = 'default';
1009           }
1010           this.serviceForm.get('realm_name').setValue(realm_name);
1011           this.serviceForm.get('zonegroup_name').setValue(zonegroup_name);
1012           this.serviceForm.get('zone_name').setValue(zone_name);
1013         }
1014         if (this.realmList.length === 0) {
1015           this.showRealmCreationForm = true;
1016         } else {
1017           this.showRealmCreationForm = false;
1018         }
1019       },
1020       (_error) => {
1021         const defaultZone = new RgwZone();
1022         defaultZone.name = 'default';
1023         const defaultZonegroup = new RgwZonegroup();
1024         defaultZonegroup.name = 'default';
1025         this.zoneList.push(defaultZone);
1026         this.zonegroupList.push(defaultZonegroup);
1027       }
1028     );
1029   }
1030
1031   setNvmeServiceId() {
1032     const pool = this.serviceForm.get('pool').value;
1033     const group = this.serviceForm.get('group').value;
1034     if (pool && group) {
1035       this.serviceForm.get('service_id').setValue(`${pool}.${group}`);
1036     } else if (pool) {
1037       this.serviceForm.get('service_id').setValue(pool);
1038     } else if (group) {
1039       this.serviceForm.get('service_id').setValue(group);
1040     } else {
1041       this.serviceForm.get('service_id').setValue(null);
1042     }
1043   }
1044
1045   setNvmeDefaultPool() {
1046     const defaultPool =
1047       this.rbdPools?.find((p: Pool) => p.pool_name === 'rbd')?.pool_name ||
1048       this.rbdPools?.[0].pool_name;
1049     this.serviceForm.get('pool').setValue(defaultPool);
1050   }
1051
1052   requiresServiceId(serviceType: string) {
1053     return ['mds', 'rgw', 'nfs', 'iscsi', 'nvmeof', 'smb', 'ingress'].includes(serviceType);
1054   }
1055
1056   setServiceId(serviceId: string): void {
1057     const requiresServiceId: boolean = this.requiresServiceId(serviceId);
1058     if (requiresServiceId && serviceId === 'nvmeof') {
1059       this.setNvmeDefaultPool();
1060       this.setNvmeServiceId();
1061     } else if (requiresServiceId) {
1062       this.serviceForm.get('service_id').setValue(null);
1063     } else {
1064       this.serviceForm.get('service_id').setValue(serviceId);
1065     }
1066   }
1067
1068   onServiceTypeChange(selectedServiceType: string) {
1069     this.setServiceId(selectedServiceType);
1070
1071     this.serviceIds = this.serviceList
1072       ?.filter((service) => service['service_type'] === selectedServiceType)
1073       .map((service) => service['service_id']);
1074
1075     this.getDefaultPlacementCount(selectedServiceType);
1076
1077     if (selectedServiceType === 'rgw') {
1078       this.setRgwFields();
1079     }
1080     if (selectedServiceType === 'mgmt-gateway') {
1081       let hrefSplitted = window.location.href.split(':');
1082       this.currentURL = hrefSplitted[0] + hrefSplitted[1];
1083       // mgmt-gateway lacks HA for now
1084       this.serviceForm.get('count').disable();
1085     } else {
1086       this.serviceForm.get('count').enable();
1087     }
1088   }
1089
1090   onPlacementChange(selected: string) {
1091     if (selected === 'label') {
1092       this.serviceForm.get('count').setValue(null);
1093     }
1094   }
1095
1096   disableForEditing(serviceType: string) {
1097     const disableForEditKeys = ['service_type', 'service_id'];
1098     disableForEditKeys.forEach((key) => {
1099       this.serviceForm.get(key).disable();
1100     });
1101     switch (serviceType) {
1102       case 'ingress':
1103         this.serviceForm.get('backend_service').disable();
1104         break;
1105       case 'nvmeof':
1106         this.serviceForm.get('pool').disable();
1107         this.serviceForm.get('group').disable();
1108         break;
1109     }
1110   }
1111
1112   searchLabels = (text$: Observable<string>) => {
1113     return merge(
1114       text$.pipe(debounceTime(200), distinctUntilChanged()),
1115       this.labelFocus,
1116       this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
1117     ).pipe(
1118       map((value) =>
1119         this.labels
1120           .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
1121           .slice(0, 10)
1122       )
1123     );
1124   };
1125
1126   fileUpload(files: FileList, controlName: string) {
1127     const file: File = files[0];
1128     const reader = new FileReader();
1129     reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
1130       const control: AbstractControl = this.serviceForm.get(controlName);
1131       control.setValue(event.target.result);
1132       control.markAsDirty();
1133       control.markAsTouched();
1134       control.updateValueAndValidity();
1135     });
1136     reader.readAsText(file, 'utf8');
1137   }
1138
1139   prePopulateId() {
1140     const control: AbstractControl = this.serviceForm.get('service_id');
1141     const backendService = this.serviceForm.getValue('backend_service');
1142     // Set Id as read-only
1143     control.reset({ value: backendService, disabled: true });
1144   }
1145
1146   onSubmit() {
1147     const self = this;
1148     const values: object = this.serviceForm.getRawValue();
1149     const serviceType: string = values['service_type'];
1150     let taskUrl = `service/${URLVerbs.CREATE}`;
1151     if (this.editing) {
1152       taskUrl = `service/${URLVerbs.EDIT}`;
1153     }
1154     const serviceSpec: object = {
1155       service_type: serviceType,
1156       placement: {},
1157       unmanaged: values['unmanaged']
1158     };
1159     if (serviceType === 'rgw') {
1160       serviceSpec['rgw_realm'] = values['realm_name'] ? values['realm_name'] : null;
1161       serviceSpec['rgw_zonegroup'] =
1162         values['zonegroup_name'] !== 'default' ? values['zonegroup_name'] : null;
1163       serviceSpec['rgw_zone'] = values['zone_name'] !== 'default' ? values['zone_name'] : null;
1164     }
1165
1166     const serviceId: string = values['service_id'];
1167     let serviceName: string = serviceType;
1168     if (_.isString(serviceId) && !_.isEmpty(serviceId) && serviceId !== serviceType) {
1169       serviceName = `${serviceType}.${serviceId}`;
1170       serviceSpec['service_id'] = serviceId;
1171     }
1172
1173     // These services has some fields to be
1174     // filled out even if unmanaged is true
1175     switch (serviceType) {
1176       case 'ingress':
1177         serviceSpec['backend_service'] = values['backend_service'];
1178         serviceSpec['service_id'] = values['backend_service'];
1179         if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
1180           serviceSpec['frontend_port'] = values['frontend_port'];
1181         }
1182         if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
1183           serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
1184         }
1185         if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
1186           serviceSpec['monitor_port'] = values['monitor_port'];
1187         }
1188         break;
1189
1190       case 'nvmeof':
1191         serviceSpec['pool'] = values['pool'];
1192         serviceSpec['group'] = values['group'];
1193         serviceSpec['enable_auth'] = values['enable_mtls'];
1194         if (values['enable_mtls']) {
1195           serviceSpec['root_ca_cert'] = values['root_ca_cert'];
1196           serviceSpec['client_cert'] = values['client_cert'];
1197           serviceSpec['client_key'] = values['client_key'];
1198           serviceSpec['server_cert'] = values['server_cert'];
1199           serviceSpec['server_key'] = values['server_key'];
1200         }
1201         break;
1202       case 'iscsi':
1203         serviceSpec['pool'] = values['pool'];
1204         break;
1205
1206       case 'smb':
1207         serviceSpec['cluster_id'] = values['cluster_id']?.trim();
1208         serviceSpec['config_uri'] = values['config_uri']?.trim();
1209         for (const feature in values['features']) {
1210           if (values['features'][feature]) {
1211             (serviceSpec['features'] = serviceSpec['features'] || []).push(feature);
1212           }
1213         }
1214         serviceSpec['custom_dns'] = values['custom_dns']?.trim();
1215         serviceSpec['join_sources'] = values['join_sources']?.trim();
1216         serviceSpec['user_sources'] = values['user_sources']?.trim();
1217         serviceSpec['include_ceph_users'] = values['include_ceph_users']?.trim();
1218         break;
1219
1220       case 'snmp-gateway':
1221         serviceSpec['credentials'] = {};
1222         serviceSpec['snmp_version'] = values['snmp_version'];
1223         serviceSpec['snmp_destination'] = values['snmp_destination'];
1224         if (values['snmp_version'] === 'V3') {
1225           serviceSpec['engine_id'] = values['engine_id'];
1226           serviceSpec['auth_protocol'] = values['auth_protocol'];
1227           serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
1228           serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
1229           if (values['privacy_protocol'] !== null) {
1230             serviceSpec['privacy_protocol'] = values['privacy_protocol'];
1231             serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
1232           }
1233         } else {
1234           serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
1235         }
1236         break;
1237     }
1238
1239     if (!values['unmanaged']) {
1240       switch (values['placement']) {
1241         case 'hosts':
1242           if (values['hosts'].length > 0) {
1243             serviceSpec['placement']['hosts'] = values['hosts'];
1244           }
1245           break;
1246         case 'label':
1247           serviceSpec['placement']['label'] = values['label'];
1248           break;
1249       }
1250       if (_.isNumber(values['count']) && values['count'] > 0) {
1251         serviceSpec['placement']['count'] = values['count'];
1252       }
1253       switch (serviceType) {
1254         case 'rgw':
1255           if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
1256             serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
1257           }
1258           serviceSpec['ssl'] = values['ssl'];
1259           if (values['ssl']) {
1260             serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
1261           }
1262           break;
1263         case 'iscsi':
1264           if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
1265             serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
1266           }
1267           if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
1268             serviceSpec['api_port'] = values['api_port'];
1269           }
1270           serviceSpec['api_user'] = values['api_user'];
1271           serviceSpec['api_password'] = values['api_password'];
1272           serviceSpec['api_secure'] = values['ssl'];
1273           if (values['ssl']) {
1274             serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
1275             serviceSpec['ssl_key'] = values['ssl_key']?.trim();
1276           }
1277           break;
1278         case 'ingress':
1279           serviceSpec['ssl'] = values['ssl'];
1280           if (values['ssl']) {
1281             serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
1282             serviceSpec['ssl_key'] = values['ssl_key']?.trim();
1283           }
1284           serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
1285           break;
1286         case 'mgmt-gateway':
1287           serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
1288           serviceSpec['ssl_key'] = values['ssl_key']?.trim();
1289           serviceSpec['enable_auth'] = values['enable_auth'];
1290           serviceSpec['port'] = values['port'];
1291           if (serviceSpec['port'] === (443 || 80)) {
1292             // omit port default values due to issues with redirect_url on the backend
1293             delete serviceSpec['port'];
1294           }
1295           serviceSpec['ssl_protocols'] = [];
1296           if (values['ssl_protocols'] != this.DEFAULT_SSL_PROTOCOL_ITEM) {
1297             for (const key of Object.keys(values['ssl_protocols'])) {
1298               serviceSpec['ssl_protocols'].push(values['ssl_protocols'][key]['content']);
1299             }
1300           }
1301           serviceSpec['ssl_ciphers'] = values['ssl_ciphers']?.trim().split(':');
1302           break;
1303         case 'grafana':
1304           serviceSpec['port'] = values['grafana_port'];
1305           serviceSpec['initial_admin_password'] = values['grafana_admin_password'];
1306           break;
1307         case 'oauth2-proxy':
1308           serviceSpec['provider_display_name'] = values['provider_display_name']?.trim();
1309           serviceSpec['client_id'] = values['client_id']?.trim();
1310           serviceSpec['client_secret'] = values['client_secret']?.trim();
1311           serviceSpec['oidc_issuer_url'] = values['oidc_issuer_url']?.trim();
1312           serviceSpec['https_address'] = values['https_address']?.trim();
1313           serviceSpec['redirect_url'] = values['redirect_url']?.trim();
1314           serviceSpec['allowlist_domains'] = values['allowlist_domains']
1315             .split(',')
1316             .map((domain: string) => {
1317               return domain.trim();
1318             });
1319           if (values['ssl']) {
1320             serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
1321             serviceSpec['ssl_key'] = values['ssl_key']?.trim();
1322           }
1323           break;
1324       }
1325     }
1326     this.taskWrapperService
1327       .wrapTaskAroundCall({
1328         task: new FinishedTask(taskUrl, {
1329           service_name: serviceName
1330         }),
1331         call: this.editing
1332           ? this.cephServiceService.update(serviceSpec)
1333           : this.cephServiceService.create(serviceSpec)
1334       })
1335       .subscribe({
1336         error() {
1337           self.serviceForm.setErrors({ cdSubmitButton: true });
1338         },
1339         complete: () => {
1340           this.pageURL === 'services'
1341             ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
1342             : this.activeModal.close();
1343         }
1344       });
1345   }
1346
1347   clearValidations() {
1348     const snmpVersion = this.serviceForm.getValue('snmp_version');
1349     const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
1350     if (snmpVersion === 'V3') {
1351       this.serviceForm.get('snmp_community').clearValidators();
1352     } else {
1353       this.serviceForm.get('engine_id').clearValidators();
1354       this.serviceForm.get('auth_protocol').clearValidators();
1355       this.serviceForm.get('privacy_protocol').clearValidators();
1356       this.serviceForm.get('snmp_v3_auth_username').clearValidators();
1357       this.serviceForm.get('snmp_v3_auth_password').clearValidators();
1358     }
1359     if (privacyProtocol === null) {
1360       this.serviceForm.get('snmp_v3_priv_password').clearValidators();
1361     }
1362   }
1363
1364   createMultisiteSetup() {
1365     this.bsModalRef = this.modalService.show(CreateRgwServiceEntitiesComponent, {
1366       size: 'lg'
1367     });
1368     this.bsModalRef.componentInstance.submitAction.subscribe(() => {
1369       this.setRgwFields();
1370     });
1371   }
1372 }