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