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