]> git.apps.os.sepia.ceph.com Git - ceph.git/blob
27477a845f79204857841edfd68fc6fa5378efe9
[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       // RGW
221       rgw_frontend_port: [null, [CdValidators.number(false)]],
222       realm_name: [null],
223       zonegroup_name: [null],
224       zone_name: [null],
225       // iSCSI
226       trusted_ip_list: [null],
227       api_port: [null, [CdValidators.number(false)]],
228       api_user: [
229         null,
230         [
231           CdValidators.requiredIf({
232             service_type: 'iscsi',
233             unmanaged: false
234           })
235         ]
236       ],
237       api_password: [
238         null,
239         [
240           CdValidators.requiredIf({
241             service_type: 'iscsi',
242             unmanaged: false
243           })
244         ]
245       ],
246       // smb
247       cluster_id: [
248         null,
249         [
250           CdValidators.requiredIf({
251             service_type: 'smb'
252           })
253         ]
254       ],
255       features: new CdFormGroup(
256         this.smbFeaturesList.reduce((acc: object, e) => {
257           acc[e] = new UntypedFormControl(false);
258           return acc;
259         }, {})
260       ),
261       config_uri: [
262         null,
263         [
264           CdValidators.composeIf(
265             {
266               service_type: 'smb'
267             },
268             [
269               Validators.required,
270               CdValidators.custom('configUriPattern', (value: string) => {
271                 if (_.isEmpty(value)) {
272                   return false;
273                 }
274                 return !this.SMB_CONFIG_URI_PATTERN.test(value);
275               })
276             ]
277           )
278         ]
279       ],
280       custom_dns: [null],
281       join_sources: [null],
282       user_sources: [null],
283       include_ceph_users: [null],
284       // Ingress
285       backend_service: [
286         null,
287         [
288           CdValidators.requiredIf({
289             service_type: 'ingress'
290           })
291         ]
292       ],
293       virtual_ip: [
294         null,
295         [
296           CdValidators.requiredIf({
297             service_type: 'ingress'
298           })
299         ]
300       ],
301       frontend_port: [
302         null,
303         [
304           CdValidators.number(false),
305           CdValidators.requiredIf({
306             service_type: 'ingress'
307           })
308         ]
309       ],
310       monitor_port: [
311         null,
312         [
313           CdValidators.number(false),
314           CdValidators.requiredIf({
315             service_type: 'ingress'
316           })
317         ]
318       ],
319       virtual_interface_networks: [null],
320       ssl_protocols: [this.DEFAULT_SSL_PROTOCOL_ITEM],
321       ssl_ciphers: [
322         null,
323         [
324           CdValidators.custom('invalidPattern', (ciphers: string) => {
325             if (_.isEmpty(ciphers)) {
326               return false;
327             }
328             return !this.SSL_CIPHERS_PATTERN.test(ciphers);
329           })
330         ]
331       ],
332       // RGW, Ingress & iSCSI
333       ssl: [false],
334       ssl_cert: [
335         '',
336         [
337           CdValidators.composeIf(
338             {
339               service_type: 'rgw',
340               unmanaged: false,
341               ssl: true
342             },
343             [Validators.required, CdValidators.pemCert()]
344           ),
345           CdValidators.composeIf(
346             {
347               service_type: 'iscsi',
348               unmanaged: false,
349               ssl: true
350             },
351             [Validators.required, CdValidators.sslCert()]
352           ),
353           CdValidators.composeIf(
354             {
355               service_type: 'ingress',
356               unmanaged: false,
357               ssl: true
358             },
359             [Validators.required, CdValidators.pemCert()]
360           ),
361           CdValidators.composeIf(
362             {
363               service_type: 'oauth2-proxy',
364               unmanaged: false,
365               ssl: true
366             },
367             [Validators.required, CdValidators.sslCert()]
368           ),
369           CdValidators.composeIf(
370             {
371               service_type: 'mgmt-gateway',
372               unmanaged: false,
373               ssl: false
374             },
375             [CdValidators.sslCert()]
376           )
377         ]
378       ],
379       ssl_key: [
380         '',
381         [
382           CdValidators.composeIf(
383             {
384               service_type: 'iscsi',
385               unmanaged: false,
386               ssl: true
387             },
388             [Validators.required, CdValidators.sslPrivKey()]
389           ),
390           CdValidators.composeIf(
391             {
392               service_type: 'oauth2-proxy',
393               unmanaged: false,
394               ssl: true
395             },
396             [Validators.required, CdValidators.sslPrivKey()]
397           ),
398           CdValidators.composeIf(
399             {
400               service_type: 'mgmt-gateway',
401               unmanaged: false,
402               ssl: false
403             },
404             [CdValidators.sslPrivKey()]
405           )
406         ]
407       ],
408       // mgmt-gateway
409       enable_auth: [null],
410       port: [443, [CdValidators.number(false)]],
411       // snmp-gateway
412       snmp_version: [
413         null,
414         [
415           CdValidators.requiredIf({
416             service_type: 'snmp-gateway'
417           })
418         ]
419       ],
420       snmp_destination: [
421         null,
422         {
423           validators: [
424             CdValidators.requiredIf({
425               service_type: 'snmp-gateway'
426             }),
427             CdValidators.custom('snmpDestinationPattern', (value: string) => {
428               if (_.isEmpty(value)) {
429                 return false;
430               }
431               return !this.SNMP_DESTINATION_PATTERN.test(value);
432             })
433           ]
434         }
435       ],
436       engine_id: [
437         null,
438         [
439           CdValidators.requiredIf({
440             service_type: 'snmp-gateway'
441           }),
442           CdValidators.custom('snmpEngineIdPattern', (value: string) => {
443             if (_.isEmpty(value)) {
444               return false;
445             }
446             return !this.SNMP_ENGINE_ID_PATTERN.test(value);
447           })
448         ]
449       ],
450       auth_protocol: [
451         'SHA',
452         [
453           CdValidators.requiredIf({
454             service_type: 'snmp-gateway'
455           })
456         ]
457       ],
458       privacy_protocol: [null],
459       snmp_community: [
460         null,
461         [
462           CdValidators.requiredIf({
463             snmp_version: 'V2c'
464           })
465         ]
466       ],
467       snmp_v3_auth_username: [
468         null,
469         [
470           CdValidators.requiredIf({
471             service_type: 'snmp-gateway'
472           })
473         ]
474       ],
475       snmp_v3_auth_password: [
476         null,
477         [
478           CdValidators.requiredIf({
479             service_type: 'snmp-gateway'
480           })
481         ]
482       ],
483       snmp_v3_priv_password: [
484         null,
485         [
486           CdValidators.requiredIf({
487             privacy_protocol: { op: '!empty' }
488           })
489         ]
490       ],
491       grafana_port: [null, [CdValidators.number(false)]],
492       grafana_admin_password: [null],
493       // oauth2-proxy
494       provider_display_name: [
495         'My OIDC provider',
496         [
497           CdValidators.requiredIf({
498             service_type: 'oauth2-proxy'
499           })
500         ]
501       ],
502       client_id: [
503         null,
504         [
505           CdValidators.requiredIf({
506             service_type: 'oauth2-proxy'
507           })
508         ]
509       ],
510       client_secret: [
511         null,
512         [
513           CdValidators.requiredIf({
514             service_type: 'oauth2-proxy'
515           })
516         ]
517       ],
518       oidc_issuer_url: [
519         null,
520         [
521           CdValidators.requiredIf({
522             service_type: 'oauth2-proxy'
523           }),
524           CdValidators.custom('validUrl', (url: string) => {
525             if (_.isEmpty(url)) {
526               return false;
527             }
528             return !this.OAUTH2_ISSUER_URL_PATTERN.test(url);
529           })
530         ]
531       ],
532       https_address: [null, [CdValidators.oauthAddressTest()]],
533       redirect_url: [null],
534       allowlist_domains: [null]
535     });
536   }
537
538   resolveRoute() {
539     if (this.router.url.includes('services/(modal:create')) {
540       this.pageURL = 'services';
541       this.route.params.subscribe((params: { type: string }) => {
542         if (params?.type) {
543           this.serviceType = params.type;
544           this.serviceForm.get('service_type').setValue(this.serviceType);
545         }
546       });
547     } else if (this.router.url.includes('services/(modal:edit')) {
548       this.editing = true;
549       this.pageURL = 'services';
550       this.route.params.subscribe((params: { type: string; name: string }) => {
551         this.serviceName = params.name;
552         this.serviceType = params.type;
553       });
554     }
555   }
556
557   ngOnInit(): void {
558     this.action = this.actionLabels.CREATE;
559     this.resolveRoute();
560
561     this.cephServiceService
562       .list(new HttpParams({ fromObject: { limit: -1, offset: 0 } }))
563       .observable.subscribe((services: CephServiceSpec[]) => {
564         this.serviceList = services;
565         this.services = services.filter((service: any) =>
566           this.INGRESS_SUPPORTED_SERVICE_TYPES.includes(service.service_type)
567         );
568       });
569
570     this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
571       // Remove service types:
572       // osd       - This is deployed a different way.
573       // container - This should only be used in the CLI.
574       this.hiddenServices.push('osd', 'container');
575
576       this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
577     });
578     this.hostService.getAllHosts().subscribe((resp: object[]) => {
579       const options: SelectOption[] = [];
580       _.forEach(resp, (host: object) => {
581         if (_.get(host, 'sources.orchestrator', false)) {
582           const option = new SelectOption(false, _.get(host, 'hostname'), '');
583           options.push(option);
584         }
585       });
586       this.hosts.options = [...options];
587     });
588     this.hostService.getLabels().subscribe((resp: string[]) => {
589       this.labels = resp;
590     });
591     this.poolService.getList().subscribe((resp: Pool[]) => {
592       this.pools = resp;
593       this.rbdPools = this.pools.filter(this.rbdService.isRBDPool);
594       if (!this.editing && this.serviceType) {
595         this.onServiceTypeChange(this.serviceType);
596       }
597     });
598
599     if (this.editing) {
600       this.action = this.actionLabels.EDIT;
601       this.disableForEditing(this.serviceType);
602       this.cephServiceService
603         .list(new HttpParams({ fromObject: { limit: -1, offset: 0 } }), this.serviceName)
604         .observable.subscribe((response: CephServiceSpec[]) => {
605           const formKeys = ['service_type', 'service_id', 'unmanaged'];
606           formKeys.forEach((keys) => {
607             this.serviceForm.get(keys).setValue(response[0][keys]);
608           });
609           if (!response[0]['unmanaged']) {
610             const placementKey = Object.keys(response[0]['placement'])[0];
611             let placementValue: string;
612             ['hosts', 'label'].indexOf(placementKey) >= 0
613               ? (placementValue = placementKey)
614               : (placementValue = 'hosts');
615             this.serviceForm.get('placement').setValue(placementValue);
616             this.serviceForm.get('count').setValue(response[0]['placement']['count']);
617             if (response[0]?.placement[placementValue]) {
618               this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
619             }
620           }
621           switch (this.serviceType) {
622             case 'iscsi':
623               const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
624               specKeys.forEach((key) => {
625                 this.serviceForm.get(key).setValue(response[0].spec[key]);
626               });
627               this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
628               if (response[0].spec?.api_secure) {
629                 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
630                 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
631               }
632               break;
633             case 'nvmeof':
634               this.serviceForm.get('pool').setValue(response[0].spec.pool);
635               this.serviceForm.get('group').setValue(response[0].spec.group);
636               break;
637             case 'rgw':
638               this.serviceForm
639                 .get('rgw_frontend_port')
640                 .setValue(response[0].spec?.rgw_frontend_port);
641               this.setRgwFields(
642                 response[0].spec?.rgw_realm,
643                 response[0].spec?.rgw_zonegroup,
644                 response[0].spec?.rgw_zone
645               );
646               this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
647               if (response[0].spec?.ssl) {
648                 this.serviceForm
649                   .get('ssl_cert')
650                   .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
651               }
652               break;
653             case 'ingress':
654               const ingressSpecKeys = [
655                 'backend_service',
656                 'virtual_ip',
657                 'frontend_port',
658                 'monitor_port',
659                 'virtual_interface_networks',
660                 'ssl'
661               ];
662               ingressSpecKeys.forEach((key) => {
663                 this.serviceForm.get(key).setValue(response[0].spec[key]);
664               });
665               if (response[0].spec?.ssl) {
666                 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
667                 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
668               }
669               break;
670             case 'mgmt-gateway':
671               let hrefSplitted = window.location.href.split(':');
672               this.currentURL = hrefSplitted[0] + hrefSplitted[1];
673               this.port = response[0].spec?.port;
674
675               if (response[0].spec?.ssl_protocols) {
676                 let selectedValues: Array<ListItem> = [];
677                 for (const value of response[0].spec.ssl_protocols) {
678                   selectedValues.push({ content: value, selected: true });
679                 }
680                 this.serviceForm.get('ssl_protocols').setValue(selectedValues);
681               }
682               if (response[0].spec?.ssl_ciphers) {
683                 this.serviceForm
684                   .get('ssl_ciphers')
685                   .setValue(response[0].spec?.ssl_ciphers.join(':'));
686               }
687               if (response[0].spec?.ssl_cert) {
688                 this.serviceForm.get('ssl_cert').setValue(response[0].spec.ssl_certificate);
689               }
690               if (response[0].spec?.ssl_key) {
691                 this.serviceForm.get('ssl_key').setValue(response[0].spec.ssl_certificate_key);
692               }
693               if (response[0].spec?.enable_auth) {
694                 this.serviceForm.get('enable_auth').setValue(response[0].spec.enable_auth);
695               }
696               if (response[0].spec?.port) {
697                 this.serviceForm.get('port').setValue(response[0].spec.port);
698               }
699               break;
700             case 'smb':
701               const smbSpecKeys = [
702                 'cluster_id',
703                 'config_uri',
704                 'features',
705                 'join_sources',
706                 'user_sources',
707                 'custom_dns',
708                 'include_ceph_users'
709               ];
710               smbSpecKeys.forEach((key) => {
711                 if (key === 'features') {
712                   if (response[0].spec?.features) {
713                     response[0].spec.features.forEach((feature) => {
714                       this.serviceForm.get(`features.${feature}`).setValue(true);
715                     });
716                   }
717                 } else {
718                   this.serviceForm.get(key).setValue(response[0].spec[key]);
719                 }
720               });
721               break;
722             case 'snmp-gateway':
723               const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
724               snmpCommonSpecKeys.forEach((key) => {
725                 this.serviceForm.get(key).setValue(response[0].spec[key]);
726               });
727               if (this.serviceForm.getValue('snmp_version') === 'V3') {
728                 const snmpV3SpecKeys = [
729                   'engine_id',
730                   'auth_protocol',
731                   'privacy_protocol',
732                   'snmp_v3_auth_username',
733                   'snmp_v3_auth_password',
734                   'snmp_v3_priv_password'
735                 ];
736                 snmpV3SpecKeys.forEach((key) => {
737                   if (key !== null) {
738                     if (
739                       key === 'snmp_v3_auth_username' ||
740                       key === 'snmp_v3_auth_password' ||
741                       key === 'snmp_v3_priv_password'
742                     ) {
743                       this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
744                     } else {
745                       this.serviceForm.get(key).setValue(response[0].spec[key]);
746                     }
747                   }
748                 });
749               } else {
750                 this.serviceForm
751                   .get('snmp_community')
752                   .setValue(response[0].spec['credentials']['snmp_community']);
753               }
754               break;
755             case 'grafana':
756               this.serviceForm.get('grafana_port').setValue(response[0].spec.port);
757               this.serviceForm
758                 .get('grafana_admin_password')
759                 .setValue(response[0].spec.initial_admin_password);
760               break;
761             case 'oauth2-proxy':
762               const oauth2SpecKeys = [
763                 'https_address',
764                 'provider_display_name',
765                 'client_id',
766                 'client_secret',
767                 'oidc_issuer_url',
768                 'redirect_url',
769                 'allowlist_domains'
770               ];
771               oauth2SpecKeys.forEach((key) => {
772                 this.serviceForm.get(key).setValue(response[0].spec[key]);
773               });
774               if (response[0].spec?.ssl) {
775                 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
776                 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
777               }
778           }
779         });
780     }
781     this.detectChanges();
782   }
783
784   detectChanges(): void {
785     const service_type = this.serviceForm.get('service_type');
786     if (service_type) {
787       service_type.valueChanges.subscribe((value) => {
788         if (value === 'mgmt-gateway') {
789           const port = this.serviceForm.get('port');
790           if (port) {
791             port.valueChanges.subscribe((_) => {
792               this.showMgmtGatewayMessage = true;
793             });
794           }
795           const ssl_protocols = this.serviceForm.get('ssl_protocols');
796           if (ssl_protocols) {
797             ssl_protocols.valueChanges.subscribe((_) => {
798               this.showMgmtGatewayMessage = true;
799             });
800           }
801           const ssl_ciphers = this.serviceForm.get('ssl_ciphers');
802           if (ssl_ciphers) {
803             ssl_ciphers.valueChanges.subscribe((_) => {
804               this.showMgmtGatewayMessage = true;
805             });
806           }
807         }
808       });
809     }
810   }
811
812   getDefaultsEntitiesForRgw(
813     defaultRealmId: string,
814     defaultZonegroupId: string,
815     defaultZoneId: string
816   ): { defaultRealmName: string; defaultZonegroupName: string; defaultZoneName: string } {
817     const defaultRealm = this.realmList.find((x: { id: string }) => x.id === defaultRealmId);
818     const defaultZonegroup = this.zonegroupList.find(
819       (x: { id: string }) => x.id === defaultZonegroupId
820     );
821     const defaultZone = this.zoneList.find((x: { id: string }) => x.id === defaultZoneId);
822     const defaultRealmName = defaultRealm !== undefined ? defaultRealm.name : null;
823     const defaultZonegroupName = defaultZonegroup !== undefined ? defaultZonegroup.name : 'default';
824     const defaultZoneName = defaultZone !== undefined ? defaultZone.name : 'default';
825     if (defaultZonegroupName === 'default' && !this.zonegroupNames.includes(defaultZonegroupName)) {
826       const defaultZonegroup = new RgwZonegroup();
827       defaultZonegroup.name = 'default';
828       this.zonegroupList.push(defaultZonegroup);
829     }
830     if (defaultZoneName === 'default' && !this.zoneNames.includes(defaultZoneName)) {
831       const defaultZone = new RgwZone();
832       defaultZone.name = 'default';
833       this.zoneList.push(defaultZone);
834     }
835     return {
836       defaultRealmName: defaultRealmName,
837       defaultZonegroupName: defaultZonegroupName,
838       defaultZoneName: defaultZoneName
839     };
840   }
841
842   getDefaultPlacementCount(serviceType: string) {
843     /**
844      * `defaults` from src/pybind/mgr/cephadm/module.py
845      */
846     switch (serviceType) {
847       case 'mon':
848         this.serviceForm.get('count').setValue(5);
849         break;
850       case 'mgr':
851       case 'mds':
852       case 'rgw':
853       case 'ingress':
854       case 'rbd-mirror':
855         this.serviceForm.get('count').setValue(2);
856         break;
857       case 'iscsi':
858       case 'cephfs-mirror':
859       case 'nfs':
860       case 'grafana':
861       case 'alertmanager':
862       case 'prometheus':
863       case 'loki':
864       case 'container':
865       case 'snmp-gateway':
866       case 'elastic-serach':
867       case 'jaeger-collector':
868       case 'jaeger-query':
869       case 'smb':
870       case 'oauth2-proxy':
871       case 'mgmt-gateway':
872         this.serviceForm.get('count').setValue(1);
873         break;
874       default:
875         this.serviceForm.get('count').setValue(null);
876     }
877   }
878
879   setRgwFields(realm_name?: string, zonegroup_name?: string, zone_name?: string) {
880     const observables = [
881       this.rgwRealmService.getAllRealmsInfo(),
882       this.rgwZonegroupService.getAllZonegroupsInfo(),
883       this.rgwZoneService.getAllZonesInfo()
884     ];
885     this.sub = forkJoin(observables).subscribe(
886       (multisiteInfo: [object, object, object]) => {
887         this.multisiteInfo = multisiteInfo;
888         this.realmList =
889           this.multisiteInfo[0] !== undefined && this.multisiteInfo[0].hasOwnProperty('realms')
890             ? this.multisiteInfo[0]['realms']
891             : [];
892         this.zonegroupList =
893           this.multisiteInfo[1] !== undefined && this.multisiteInfo[1].hasOwnProperty('zonegroups')
894             ? this.multisiteInfo[1]['zonegroups']
895             : [];
896         this.zoneList =
897           this.multisiteInfo[2] !== undefined && this.multisiteInfo[2].hasOwnProperty('zones')
898             ? this.multisiteInfo[2]['zones']
899             : [];
900         this.realmNames = this.realmList.map((realm) => {
901           return realm['name'];
902         });
903         this.zonegroupNames = this.zonegroupList.map((zonegroup) => {
904           return zonegroup['name'];
905         });
906         this.zoneNames = this.zoneList.map((zone) => {
907           return zone['name'];
908         });
909         this.defaultRealmId = multisiteInfo[0]['default_realm'];
910         this.defaultZonegroupId = multisiteInfo[1]['default_zonegroup'];
911         this.defaultZoneId = multisiteInfo[2]['default_zone'];
912         this.defaultsInfo = this.getDefaultsEntitiesForRgw(
913           this.defaultRealmId,
914           this.defaultZonegroupId,
915           this.defaultZoneId
916         );
917         if (!this.editing) {
918           this.serviceForm.get('realm_name').setValue(this.defaultsInfo['defaultRealmName']);
919           this.serviceForm
920             .get('zonegroup_name')
921             .setValue(this.defaultsInfo['defaultZonegroupName']);
922           this.serviceForm.get('zone_name').setValue(this.defaultsInfo['defaultZoneName']);
923         } else {
924           if (realm_name && !this.realmNames.includes(realm_name)) {
925             const realm = new RgwRealm();
926             realm.name = realm_name;
927             this.realmList.push(realm);
928           }
929           if (zonegroup_name && !this.zonegroupNames.includes(zonegroup_name)) {
930             const zonegroup = new RgwZonegroup();
931             zonegroup.name = zonegroup_name;
932             this.zonegroupList.push(zonegroup);
933           }
934           if (zone_name && !this.zoneNames.includes(zone_name)) {
935             const zone = new RgwZone();
936             zone.name = zone_name;
937             this.zoneList.push(zone);
938           }
939           if (zonegroup_name === undefined && zone_name === undefined) {
940             zonegroup_name = 'default';
941             zone_name = 'default';
942           }
943           this.serviceForm.get('realm_name').setValue(realm_name);
944           this.serviceForm.get('zonegroup_name').setValue(zonegroup_name);
945           this.serviceForm.get('zone_name').setValue(zone_name);
946         }
947         if (this.realmList.length === 0) {
948           this.showRealmCreationForm = true;
949         } else {
950           this.showRealmCreationForm = false;
951         }
952       },
953       (_error) => {
954         const defaultZone = new RgwZone();
955         defaultZone.name = 'default';
956         const defaultZonegroup = new RgwZonegroup();
957         defaultZonegroup.name = 'default';
958         this.zoneList.push(defaultZone);
959         this.zonegroupList.push(defaultZonegroup);
960       }
961     );
962   }
963
964   onNvmeofGroupChange(groupName: string) {
965     const pool = this.serviceForm.get('pool').value;
966     if (pool) this.serviceForm.get('service_id').setValue(`${pool}.${groupName}`);
967     else this.serviceForm.get('service_id').setValue(groupName);
968   }
969
970   getDefaultBlockPool(): string {
971     // returns 'rbd' pool otherwise the first block pool
972     return (
973       this.rbdPools?.find((p: Pool) => p.pool_name === 'rbd')?.pool_name ||
974       this.rbdPools?.[0].pool_name
975     );
976   }
977
978   setNvmeofServiceIdAndPool(): void {
979     const defaultBlockPool: string = this.getDefaultBlockPool();
980     const group: string = this.serviceForm.get('group').value;
981     if (defaultBlockPool && group) {
982       this.serviceForm.get('pool').setValue(defaultBlockPool);
983       this.serviceForm.get('service_id').setValue(`${defaultBlockPool}.${group}`);
984     } else {
985       this.serviceForm.get('service_id').setValue(null);
986     }
987   }
988
989   requiresServiceId(serviceType: string) {
990     return ['mds', 'rgw', 'nfs', 'iscsi', 'nvmeof', 'smb', 'ingress'].includes(serviceType);
991   }
992
993   setServiceId(serviceId: string): void {
994     const requiresServiceId: boolean = this.requiresServiceId(serviceId);
995     if (requiresServiceId && serviceId === 'nvmeof') {
996       this.setNvmeofServiceIdAndPool();
997     } else if (requiresServiceId) {
998       this.serviceForm.get('service_id').setValue(null);
999     } else {
1000       this.serviceForm.get('service_id').setValue(serviceId);
1001     }
1002   }
1003
1004   onServiceTypeChange(selectedServiceType: string) {
1005     this.setServiceId(selectedServiceType);
1006
1007     this.serviceIds = this.serviceList
1008       ?.filter((service) => service['service_type'] === selectedServiceType)
1009       .map((service) => service['service_id']);
1010
1011     this.getDefaultPlacementCount(selectedServiceType);
1012
1013     if (selectedServiceType === 'rgw') {
1014       this.setRgwFields();
1015     }
1016     if (selectedServiceType === 'mgmt-gateway') {
1017       let hrefSplitted = window.location.href.split(':');
1018       this.currentURL = hrefSplitted[0] + hrefSplitted[1];
1019       // mgmt-gateway lacks HA for now
1020       this.serviceForm.get('count').disable();
1021     } else {
1022       this.serviceForm.get('count').enable();
1023     }
1024   }
1025
1026   onPlacementChange(selected: string) {
1027     if (selected === 'label') {
1028       this.serviceForm.get('count').setValue(null);
1029     }
1030   }
1031
1032   onBlockPoolChange() {
1033     const selectedBlockPool = this.serviceForm.get('pool').value;
1034     const group = this.serviceForm.get('group').value;
1035     if (selectedBlockPool && group) {
1036       this.serviceForm.get('service_id').setValue(`${selectedBlockPool}.${group}`);
1037     } else if (selectedBlockPool) {
1038       this.serviceForm.get('service_id').setValue(selectedBlockPool);
1039     } else {
1040       this.serviceForm.get('service_id').setValue(null);
1041     }
1042   }
1043
1044   disableForEditing(serviceType: string) {
1045     const disableForEditKeys = ['service_type', 'service_id'];
1046     disableForEditKeys.forEach((key) => {
1047       this.serviceForm.get(key).disable();
1048     });
1049     switch (serviceType) {
1050       case 'ingress':
1051         this.serviceForm.get('backend_service').disable();
1052         break;
1053       case 'nvmeof':
1054         this.serviceForm.get('pool').disable();
1055         this.serviceForm.get('group').disable();
1056         break;
1057     }
1058   }
1059
1060   searchLabels = (text$: Observable<string>) => {
1061     return merge(
1062       text$.pipe(debounceTime(200), distinctUntilChanged()),
1063       this.labelFocus,
1064       this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
1065     ).pipe(
1066       map((value) =>
1067         this.labels
1068           .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
1069           .slice(0, 10)
1070       )
1071     );
1072   };
1073
1074   fileUpload(files: FileList, controlName: string) {
1075     const file: File = files[0];
1076     const reader = new FileReader();
1077     reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
1078       const control: AbstractControl = this.serviceForm.get(controlName);
1079       control.setValue(event.target.result);
1080       control.markAsDirty();
1081       control.markAsTouched();
1082       control.updateValueAndValidity();
1083     });
1084     reader.readAsText(file, 'utf8');
1085   }
1086
1087   prePopulateId() {
1088     const control: AbstractControl = this.serviceForm.get('service_id');
1089     const backendService = this.serviceForm.getValue('backend_service');
1090     // Set Id as read-only
1091     control.reset({ value: backendService, disabled: true });
1092   }
1093
1094   onSubmit() {
1095     const self = this;
1096     const values: object = this.serviceForm.getRawValue();
1097     const serviceType: string = values['service_type'];
1098     let taskUrl = `service/${URLVerbs.CREATE}`;
1099     if (this.editing) {
1100       taskUrl = `service/${URLVerbs.EDIT}`;
1101     }
1102     const serviceSpec: object = {
1103       service_type: serviceType,
1104       placement: {},
1105       unmanaged: values['unmanaged']
1106     };
1107     if (serviceType === 'rgw') {
1108       serviceSpec['rgw_realm'] = values['realm_name'] ? values['realm_name'] : null;
1109       serviceSpec['rgw_zonegroup'] =
1110         values['zonegroup_name'] !== 'default' ? values['zonegroup_name'] : null;
1111       serviceSpec['rgw_zone'] = values['zone_name'] !== 'default' ? values['zone_name'] : null;
1112     }
1113
1114     const serviceId: string = values['service_id'];
1115     let serviceName: string = serviceType;
1116     if (_.isString(serviceId) && !_.isEmpty(serviceId) && serviceId !== serviceType) {
1117       serviceName = `${serviceType}.${serviceId}`;
1118       serviceSpec['service_id'] = serviceId;
1119     }
1120
1121     // These services has some fields to be
1122     // filled out even if unmanaged is true
1123     switch (serviceType) {
1124       case 'ingress':
1125         serviceSpec['backend_service'] = values['backend_service'];
1126         serviceSpec['service_id'] = values['backend_service'];
1127         if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
1128           serviceSpec['frontend_port'] = values['frontend_port'];
1129         }
1130         if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
1131           serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
1132         }
1133         if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
1134           serviceSpec['monitor_port'] = values['monitor_port'];
1135         }
1136         break;
1137
1138       case 'nvmeof':
1139         serviceSpec['pool'] = values['pool'];
1140         serviceSpec['group'] = values['group'];
1141         break;
1142       case 'iscsi':
1143         serviceSpec['pool'] = values['pool'];
1144         break;
1145
1146       case 'smb':
1147         serviceSpec['cluster_id'] = values['cluster_id']?.trim();
1148         serviceSpec['config_uri'] = values['config_uri']?.trim();
1149         for (const feature in values['features']) {
1150           if (values['features'][feature]) {
1151             (serviceSpec['features'] = serviceSpec['features'] || []).push(feature);
1152           }
1153         }
1154         serviceSpec['custom_dns'] = values['custom_dns']?.trim();
1155         serviceSpec['join_sources'] = values['join_sources']?.trim();
1156         serviceSpec['user_sources'] = values['user_sources']?.trim();
1157         serviceSpec['include_ceph_users'] = values['include_ceph_users']?.trim();
1158         break;
1159
1160       case 'snmp-gateway':
1161         serviceSpec['credentials'] = {};
1162         serviceSpec['snmp_version'] = values['snmp_version'];
1163         serviceSpec['snmp_destination'] = values['snmp_destination'];
1164         if (values['snmp_version'] === 'V3') {
1165           serviceSpec['engine_id'] = values['engine_id'];
1166           serviceSpec['auth_protocol'] = values['auth_protocol'];
1167           serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
1168           serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
1169           if (values['privacy_protocol'] !== null) {
1170             serviceSpec['privacy_protocol'] = values['privacy_protocol'];
1171             serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
1172           }
1173         } else {
1174           serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
1175         }
1176         break;
1177     }
1178
1179     if (!values['unmanaged']) {
1180       switch (values['placement']) {
1181         case 'hosts':
1182           if (values['hosts'].length > 0) {
1183             serviceSpec['placement']['hosts'] = values['hosts'];
1184           }
1185           break;
1186         case 'label':
1187           serviceSpec['placement']['label'] = values['label'];
1188           break;
1189       }
1190       if (_.isNumber(values['count']) && values['count'] > 0) {
1191         serviceSpec['placement']['count'] = values['count'];
1192       }
1193       switch (serviceType) {
1194         case 'rgw':
1195           if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
1196             serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
1197           }
1198           serviceSpec['ssl'] = values['ssl'];
1199           if (values['ssl']) {
1200             serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
1201           }
1202           break;
1203         case 'iscsi':
1204           if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
1205             serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
1206           }
1207           if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
1208             serviceSpec['api_port'] = values['api_port'];
1209           }
1210           serviceSpec['api_user'] = values['api_user'];
1211           serviceSpec['api_password'] = values['api_password'];
1212           serviceSpec['api_secure'] = values['ssl'];
1213           if (values['ssl']) {
1214             serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
1215             serviceSpec['ssl_key'] = values['ssl_key']?.trim();
1216           }
1217           break;
1218         case 'ingress':
1219           serviceSpec['ssl'] = values['ssl'];
1220           if (values['ssl']) {
1221             serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
1222             serviceSpec['ssl_key'] = values['ssl_key']?.trim();
1223           }
1224           serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
1225           break;
1226         case 'mgmt-gateway':
1227           serviceSpec['ssl_certificate'] = values['ssl_cert']?.trim();
1228           serviceSpec['ssl_certificate_key'] = values['ssl_key']?.trim();
1229           serviceSpec['enable_auth'] = values['enable_auth'];
1230           serviceSpec['port'] = values['port'];
1231           if (serviceSpec['port'] === (443 || 80)) {
1232             // omit port default values due to issues with redirect_url on the backend
1233             delete serviceSpec['port'];
1234           }
1235           serviceSpec['ssl_protocols'] = [];
1236           if (values['ssl_protocols'] != this.DEFAULT_SSL_PROTOCOL_ITEM) {
1237             for (const key of Object.keys(values['ssl_protocols'])) {
1238               serviceSpec['ssl_protocols'].push(values['ssl_protocols'][key]['content']);
1239             }
1240           }
1241           serviceSpec['ssl_ciphers'] = values['ssl_ciphers']?.trim().split(':');
1242           break;
1243         case 'grafana':
1244           serviceSpec['port'] = values['grafana_port'];
1245           serviceSpec['initial_admin_password'] = values['grafana_admin_password'];
1246           break;
1247         case 'oauth2-proxy':
1248           serviceSpec['provider_display_name'] = values['provider_display_name']?.trim();
1249           serviceSpec['client_id'] = values['client_id']?.trim();
1250           serviceSpec['client_secret'] = values['client_secret']?.trim();
1251           serviceSpec['oidc_issuer_url'] = values['oidc_issuer_url']?.trim();
1252           serviceSpec['https_address'] = values['https_address']?.trim();
1253           serviceSpec['redirect_url'] = values['redirect_url']?.trim();
1254           serviceSpec['allowlist_domains'] = values['allowlist_domains']
1255             .split(',')
1256             .map((domain: string) => {
1257               return domain.trim();
1258             });
1259           if (values['ssl']) {
1260             serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
1261             serviceSpec['ssl_key'] = values['ssl_key']?.trim();
1262           }
1263           break;
1264       }
1265     }
1266     this.taskWrapperService
1267       .wrapTaskAroundCall({
1268         task: new FinishedTask(taskUrl, {
1269           service_name: serviceName
1270         }),
1271         call: this.editing
1272           ? this.cephServiceService.update(serviceSpec)
1273           : this.cephServiceService.create(serviceSpec)
1274       })
1275       .subscribe({
1276         error() {
1277           self.serviceForm.setErrors({ cdSubmitButton: true });
1278         },
1279         complete: () => {
1280           this.pageURL === 'services'
1281             ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
1282             : this.activeModal.close();
1283         }
1284       });
1285   }
1286
1287   clearValidations() {
1288     const snmpVersion = this.serviceForm.getValue('snmp_version');
1289     const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
1290     if (snmpVersion === 'V3') {
1291       this.serviceForm.get('snmp_community').clearValidators();
1292     } else {
1293       this.serviceForm.get('engine_id').clearValidators();
1294       this.serviceForm.get('auth_protocol').clearValidators();
1295       this.serviceForm.get('privacy_protocol').clearValidators();
1296       this.serviceForm.get('snmp_v3_auth_username').clearValidators();
1297       this.serviceForm.get('snmp_v3_auth_password').clearValidators();
1298     }
1299     if (privacyProtocol === null) {
1300       this.serviceForm.get('snmp_v3_priv_password').clearValidators();
1301     }
1302   }
1303
1304   createMultisiteSetup() {
1305     this.bsModalRef = this.modalService.show(CreateRgwServiceEntitiesComponent, {
1306       size: 'lg'
1307     });
1308     this.bsModalRef.componentInstance.submitAction.subscribe(() => {
1309       this.setRgwFields();
1310     });
1311   }
1312 }