]> git.apps.os.sepia.ceph.com Git - ceph.git/blob
da4daf9c1f5f4ad8bf1d99dfbb4b005c3eb2a8ec
[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       // iSCSI
119       pool: [
120         null,
121         [
122           CdValidators.requiredIf({
123             service_type: 'iscsi',
124             unmanaged: false
125           })
126         ]
127       ],
128       // RGW
129       rgw_frontend_port: [
130         null,
131         [CdValidators.number(false), Validators.min(1), Validators.max(65535)]
132       ],
133       // iSCSI
134       trusted_ip_list: [null],
135       api_port: [null, [CdValidators.number(false), Validators.min(1), Validators.max(65535)]],
136       api_user: [
137         null,
138         [
139           CdValidators.requiredIf({
140             service_type: 'iscsi',
141             unmanaged: false
142           })
143         ]
144       ],
145       api_password: [
146         null,
147         [
148           CdValidators.requiredIf({
149             service_type: 'iscsi',
150             unmanaged: false
151           })
152         ]
153       ],
154       // Ingress
155       backend_service: [
156         null,
157         [
158           CdValidators.requiredIf({
159             service_type: 'ingress',
160             unmanaged: false
161           })
162         ]
163       ],
164       virtual_ip: [
165         null,
166         [
167           CdValidators.requiredIf({
168             service_type: 'ingress',
169             unmanaged: false
170           })
171         ]
172       ],
173       frontend_port: [null, [CdValidators.number(false), Validators.min(1), Validators.max(65535)]],
174       monitor_port: [null, [CdValidators.number(false), Validators.min(1), Validators.max(65535)]],
175       virtual_interface_networks: [null],
176       // RGW, Ingress & iSCSI
177       ssl: [false],
178       ssl_cert: [
179         '',
180         [
181           CdValidators.composeIf(
182             {
183               service_type: 'rgw',
184               unmanaged: false,
185               ssl: true
186             },
187             [Validators.required, CdValidators.pemCert()]
188           ),
189           CdValidators.composeIf(
190             {
191               service_type: 'iscsi',
192               unmanaged: false,
193               ssl: true
194             },
195             [Validators.required, CdValidators.sslCert()]
196           )
197         ]
198       ],
199       ssl_key: [
200         '',
201         [
202           CdValidators.composeIf(
203             {
204               service_type: 'iscsi',
205               unmanaged: false,
206               ssl: true
207             },
208             [Validators.required, CdValidators.sslPrivKey()]
209           )
210         ]
211       ]
212     });
213   }
214
215   ngOnInit(): void {
216     if (this.router.url.includes('services')) {
217       this.pageURL = 'services';
218     }
219     this.action = this.actionLabels.CREATE;
220     this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
221       // Remove service types:
222       // osd       - This is deployed a different way.
223       // container - This should only be used in the CLI.
224       this.hiddenServices.push('osd', 'container');
225
226       this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
227     });
228     this.hostService.list('false').subscribe((resp: object[]) => {
229       const options: SelectOption[] = [];
230       _.forEach(resp, (host: object) => {
231         if (_.get(host, 'sources.orchestrator', false)) {
232           const option = new SelectOption(false, _.get(host, 'hostname'), '');
233           options.push(option);
234         }
235       });
236       this.hosts.options = [...options];
237     });
238     this.hostService.getLabels().subscribe((resp: string[]) => {
239       this.labels = resp;
240     });
241     this.poolService.getList().subscribe((resp: Array<object>) => {
242       this.pools = resp;
243     });
244     this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
245       this.services = services.filter((service: any) => service.service_type === 'rgw');
246     });
247   }
248
249   searchLabels = (text$: Observable<string>) => {
250     return merge(
251       text$.pipe(debounceTime(200), distinctUntilChanged()),
252       this.labelFocus,
253       this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
254     ).pipe(
255       map((value) =>
256         this.labels
257           .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
258           .slice(0, 10)
259       )
260     );
261   };
262
263   fileUpload(files: FileList, controlName: string) {
264     const file: File = files[0];
265     const reader = new FileReader();
266     reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
267       const control: AbstractControl = this.serviceForm.get(controlName);
268       control.setValue(event.target.result);
269       control.markAsDirty();
270       control.markAsTouched();
271       control.updateValueAndValidity();
272     });
273     reader.readAsText(file, 'utf8');
274   }
275
276   prePopulateId() {
277     const control: AbstractControl = this.serviceForm.get('service_id');
278     const backendService = this.serviceForm.getValue('backend_service');
279     // Set Id as read-only
280     control.reset({ value: backendService, disabled: true });
281   }
282
283   onSubmit() {
284     const self = this;
285     const values: object = this.serviceForm.value;
286     const serviceType: string = values['service_type'];
287     const serviceSpec: object = {
288       service_type: serviceType,
289       placement: {},
290       unmanaged: values['unmanaged']
291     };
292     let svcId: string;
293     if (serviceType === 'rgw') {
294       const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
295       svcId = svcIdMatch[1];
296       if (svcIdMatch[3]) {
297         serviceSpec['rgw_realm'] = svcIdMatch[3];
298         serviceSpec['rgw_zone'] = svcIdMatch[4];
299       }
300     } else {
301       svcId = values['service_id'];
302     }
303     const serviceId: string = svcId;
304     let serviceName: string = serviceType;
305     if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
306       serviceName = `${serviceType}.${serviceId}`;
307       serviceSpec['service_id'] = serviceId;
308     }
309     if (!values['unmanaged']) {
310       switch (values['placement']) {
311         case 'hosts':
312           if (values['hosts'].length > 0) {
313             serviceSpec['placement']['hosts'] = values['hosts'];
314           }
315           break;
316         case 'label':
317           serviceSpec['placement']['label'] = values['label'];
318           break;
319       }
320       if (_.isNumber(values['count']) && values['count'] > 0) {
321         serviceSpec['placement']['count'] = values['count'];
322       }
323       switch (serviceType) {
324         case 'rgw':
325           if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
326             serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
327           }
328           serviceSpec['ssl'] = values['ssl'];
329           if (values['ssl']) {
330             serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert'].trim();
331           }
332           break;
333         case 'iscsi':
334           serviceSpec['pool'] = values['pool'];
335           if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
336             serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
337           }
338           if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
339             serviceSpec['api_port'] = values['api_port'];
340           }
341           serviceSpec['api_user'] = values['api_user'];
342           serviceSpec['api_password'] = values['api_password'];
343           serviceSpec['api_secure'] = values['ssl'];
344           if (values['ssl']) {
345             serviceSpec['ssl_cert'] = values['ssl_cert'].trim();
346             serviceSpec['ssl_key'] = values['ssl_key'].trim();
347           }
348           break;
349         case 'ingress':
350           serviceSpec['backend_service'] = values['backend_service'];
351           serviceSpec['service_id'] = values['backend_service'];
352           if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
353             serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
354           }
355           if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
356             serviceSpec['frontend_port'] = values['frontend_port'];
357           }
358           if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
359             serviceSpec['monitor_port'] = values['monitor_port'];
360           }
361           serviceSpec['ssl'] = values['ssl'];
362           if (values['ssl']) {
363             serviceSpec['ssl_cert'] = values['ssl_cert'].trim();
364             serviceSpec['ssl_key'] = values['ssl_key'].trim();
365           }
366           serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
367           break;
368       }
369     }
370     this.taskWrapperService
371       .wrapTaskAroundCall({
372         task: new FinishedTask(`service/${URLVerbs.CREATE}`, {
373           service_name: serviceName
374         }),
375         call: this.cephServiceService.create(serviceSpec)
376       })
377       .subscribe({
378         error() {
379           self.serviceForm.setErrors({ cdSubmitButton: true });
380         },
381         complete: () => {
382           this.pageURL === 'services'
383             ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
384             : this.activeModal.close();
385         }
386       });
387   }
388 }