]> git.apps.os.sepia.ceph.com Git - ceph.git/blob
941eabfb67c623bba65ee0d47da97c90fc28b328
[ceph.git] /
1 import { Component, Input, OnInit, ViewChild } from '@angular/core';
2 import { AbstractControl, Validators } from '@angular/forms';
3 import { 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   @ViewChild(NgbTypeahead, { static: false })
32   typeahead: NgbTypeahead;
33
34   @Input() public hiddenServices: string[] = [];
35
36   serviceForm: CdFormGroup;
37   action: string;
38   resource: string;
39   serviceTypes: string[] = [];
40   hosts: any;
41   labels: string[];
42   labelClick = new Subject<string>();
43   labelFocus = new Subject<string>();
44   pools: Array<object>;
45   services: Array<CephServiceSpec> = [];
46   pageURL: string;
47
48   constructor(
49     public actionLabels: ActionLabelsI18n,
50     private cephServiceService: CephServiceService,
51     private formBuilder: CdFormBuilder,
52     private hostService: HostService,
53     private poolService: PoolService,
54     private router: Router,
55     private taskWrapperService: TaskWrapperService,
56     public activeModal: NgbActiveModal
57   ) {
58     super();
59     this.resource = $localize`service`;
60     this.hosts = {
61       options: [],
62       messages: new SelectMessages({
63         empty: $localize`There are no hosts.`,
64         filter: $localize`Filter hosts`
65       })
66     };
67     this.createForm();
68   }
69
70   createForm() {
71     this.serviceForm = this.formBuilder.group({
72       // Global
73       service_type: [null, [Validators.required]],
74       service_id: [
75         null,
76         [
77           CdValidators.requiredIf({
78             service_type: 'mds'
79           }),
80           CdValidators.requiredIf({
81             service_type: 'nfs'
82           }),
83           CdValidators.requiredIf({
84             service_type: 'iscsi'
85           }),
86           CdValidators.requiredIf({
87             service_type: 'ingress'
88           }),
89           CdValidators.composeIf(
90             {
91               service_type: 'rgw'
92             },
93             [
94               Validators.required,
95               CdValidators.custom('rgwPattern', (value: string) => {
96                 if (_.isEmpty(value)) {
97                   return false;
98                 }
99                 return !this.RGW_SVC_ID_PATTERN.test(value);
100               })
101             ]
102           )
103         ]
104       ],
105       placement: ['hosts'],
106       label: [
107         null,
108         [
109           CdValidators.requiredIf({
110             placement: 'label',
111             unmanaged: false
112           })
113         ]
114       ],
115       hosts: [[]],
116       count: [null, [CdValidators.number(false), Validators.min(1)]],
117       unmanaged: [false],
118       // NFS & iSCSI
119       pool: [
120         null,
121         [
122           CdValidators.requiredIf({
123             service_type: 'nfs',
124             unmanaged: false
125           }),
126           CdValidators.requiredIf({
127             service_type: 'iscsi',
128             unmanaged: false
129           })
130         ]
131       ],
132       // NFS
133       namespace: [null],
134       // RGW
135       rgw_frontend_port: [
136         null,
137         [CdValidators.number(false), Validators.min(1), Validators.max(65535)]
138       ],
139       // iSCSI
140       trusted_ip_list: [null],
141       api_port: [null, [CdValidators.number(false), Validators.min(1), Validators.max(65535)]],
142       api_user: [
143         null,
144         [
145           CdValidators.requiredIf({
146             service_type: 'iscsi',
147             unmanaged: false
148           })
149         ]
150       ],
151       api_password: [
152         null,
153         [
154           CdValidators.requiredIf({
155             service_type: 'iscsi',
156             unmanaged: false
157           })
158         ]
159       ],
160       // Ingress
161       backend_service: [
162         null,
163         [
164           CdValidators.requiredIf({
165             service_type: 'ingress',
166             unmanaged: false
167           })
168         ]
169       ],
170       virtual_ip: [
171         null,
172         [
173           CdValidators.requiredIf({
174             service_type: 'ingress',
175             unmanaged: false
176           })
177         ]
178       ],
179       frontend_port: [null, [CdValidators.number(false), Validators.min(1), Validators.max(65535)]],
180       monitor_port: [null, [CdValidators.number(false), Validators.min(1), Validators.max(65535)]],
181       virtual_interface_networks: [null],
182       // RGW, Ingress & iSCSI
183       ssl: [false],
184       ssl_cert: [
185         '',
186         [
187           CdValidators.composeIf(
188             {
189               service_type: 'rgw',
190               unmanaged: false,
191               ssl: true
192             },
193             [Validators.required, CdValidators.pemCert()]
194           ),
195           CdValidators.composeIf(
196             {
197               service_type: 'iscsi',
198               unmanaged: false,
199               ssl: true
200             },
201             [Validators.required, CdValidators.sslCert()]
202           )
203         ]
204       ],
205       ssl_key: [
206         '',
207         [
208           CdValidators.composeIf(
209             {
210               service_type: 'iscsi',
211               unmanaged: false,
212               ssl: true
213             },
214             [Validators.required, CdValidators.sslPrivKey()]
215           )
216         ]
217       ]
218     });
219   }
220
221   ngOnInit(): void {
222     if (this.router.url.includes('services')) {
223       this.pageURL = 'services';
224     }
225     this.action = this.actionLabels.CREATE;
226     this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
227       // Remove service types:
228       // osd       - This is deployed a different way.
229       // container - This should only be used in the CLI.
230       this.hiddenServices.push('osd', 'container');
231
232       this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
233     });
234     this.hostService.list().subscribe((resp: object[]) => {
235       const options: SelectOption[] = [];
236       _.forEach(resp, (host: object) => {
237         if (_.get(host, 'sources.orchestrator', false)) {
238           const option = new SelectOption(false, _.get(host, 'hostname'), '');
239           options.push(option);
240         }
241       });
242       this.hosts.options = [...options];
243     });
244     this.hostService.getLabels().subscribe((resp: string[]) => {
245       this.labels = resp;
246     });
247     this.poolService.getList().subscribe((resp: Array<object>) => {
248       this.pools = resp;
249     });
250     this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
251       this.services = services.filter((service: any) => service.service_type === 'rgw');
252     });
253   }
254
255   searchLabels = (text$: Observable<string>) => {
256     return merge(
257       text$.pipe(debounceTime(200), distinctUntilChanged()),
258       this.labelFocus,
259       this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
260     ).pipe(
261       map((value) =>
262         this.labels
263           .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
264           .slice(0, 10)
265       )
266     );
267   };
268
269   fileUpload(files: FileList, controlName: string) {
270     const file: File = files[0];
271     const reader = new FileReader();
272     reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
273       const control: AbstractControl = this.serviceForm.get(controlName);
274       control.setValue(event.target.result);
275       control.markAsDirty();
276       control.markAsTouched();
277       control.updateValueAndValidity();
278     });
279     reader.readAsText(file, 'utf8');
280   }
281
282   prePopulateId() {
283     const control: AbstractControl = this.serviceForm.get('service_id');
284     const backendService = this.serviceForm.getValue('backend_service');
285     // Set Id as read-only
286     control.reset({ value: backendService, disabled: true });
287   }
288
289   onSubmit() {
290     const self = this;
291     const values: object = this.serviceForm.value;
292     const serviceType: string = values['service_type'];
293     const serviceSpec: object = {
294       service_type: serviceType,
295       placement: {},
296       unmanaged: values['unmanaged']
297     };
298     let svcId: string;
299     if (serviceType === 'rgw') {
300       const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
301       svcId = svcIdMatch[1];
302       if (svcIdMatch[3]) {
303         serviceSpec['rgw_realm'] = svcIdMatch[3];
304         serviceSpec['rgw_zone'] = svcIdMatch[4];
305       }
306     } else {
307       svcId = values['service_id'];
308     }
309     const serviceId: string = svcId;
310     let serviceName: string = serviceType;
311     if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
312       serviceName = `${serviceType}.${serviceId}`;
313       serviceSpec['service_id'] = serviceId;
314     }
315     if (!values['unmanaged']) {
316       switch (values['placement']) {
317         case 'hosts':
318           if (values['hosts'].length > 0) {
319             serviceSpec['placement']['hosts'] = values['hosts'];
320           }
321           break;
322         case 'label':
323           serviceSpec['placement']['label'] = values['label'];
324           break;
325       }
326       if (_.isNumber(values['count']) && values['count'] > 0) {
327         serviceSpec['placement']['count'] = values['count'];
328       }
329       switch (serviceType) {
330         case 'nfs':
331           serviceSpec['pool'] = values['pool'];
332           if (_.isString(values['namespace']) && !_.isEmpty(values['namespace'])) {
333             serviceSpec['namespace'] = values['namespace'];
334           }
335           break;
336         case 'rgw':
337           if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
338             serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
339           }
340           serviceSpec['ssl'] = values['ssl'];
341           if (values['ssl']) {
342             serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert'].trim();
343           }
344           break;
345         case 'iscsi':
346           serviceSpec['pool'] = values['pool'];
347           if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
348             serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
349           }
350           if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
351             serviceSpec['api_port'] = values['api_port'];
352           }
353           serviceSpec['api_user'] = values['api_user'];
354           serviceSpec['api_password'] = values['api_password'];
355           serviceSpec['api_secure'] = values['ssl'];
356           if (values['ssl']) {
357             serviceSpec['ssl_cert'] = values['ssl_cert'].trim();
358             serviceSpec['ssl_key'] = values['ssl_key'].trim();
359           }
360           break;
361         case 'ingress':
362           serviceSpec['backend_service'] = values['backend_service'];
363           serviceSpec['service_id'] = values['backend_service'];
364           if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
365             serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
366           }
367           if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
368             serviceSpec['frontend_port'] = values['frontend_port'];
369           }
370           if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
371             serviceSpec['monitor_port'] = values['monitor_port'];
372           }
373           serviceSpec['ssl'] = values['ssl'];
374           if (values['ssl']) {
375             serviceSpec['ssl_cert'] = values['ssl_cert'].trim();
376             serviceSpec['ssl_key'] = values['ssl_key'].trim();
377           }
378           serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
379           break;
380       }
381     }
382     this.taskWrapperService
383       .wrapTaskAroundCall({
384         task: new FinishedTask(`service/${URLVerbs.CREATE}`, {
385           service_name: serviceName
386         }),
387         call: this.cephServiceService.create(serviceSpec)
388       })
389       .subscribe({
390         error() {
391           self.serviceForm.setErrors({ cdSubmitButton: true });
392         },
393         complete: () => {
394           this.pageURL === 'services'
395             ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
396             : this.activeModal.close();
397         }
398       });
399   }
400 }