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