]> git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/service-form/service-form.component.ts
import ceph 16.2.7
[ceph.git] / ceph / src / pybind / mgr / dashboard / frontend / src / app / ceph / cluster / services / service-form / service-form.component.ts
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 @ViewChild(NgbTypeahead, { static: false })
32 typeahead: NgbTypeahead;
33
34 @Input() hiddenServices: string[] = [];
35
36 @Input() editing = false;
37
38 @Input() serviceName: string;
39
40 @Input() serviceType: string;
41
42 serviceForm: CdFormGroup;
43 action: string;
44 resource: string;
45 serviceTypes: string[] = [];
46 hosts: any;
47 labels: string[];
48 labelClick = new Subject<string>();
49 labelFocus = new Subject<string>();
50 pools: Array<object>;
51 services: Array<CephServiceSpec> = [];
52 pageURL: string;
53
54 constructor(
55 public actionLabels: ActionLabelsI18n,
56 private cephServiceService: CephServiceService,
57 private formBuilder: CdFormBuilder,
58 private hostService: HostService,
59 private poolService: PoolService,
60 private router: Router,
61 private taskWrapperService: TaskWrapperService,
62 private route: ActivatedRoute,
63 public activeModal: NgbActiveModal
64 ) {
65 super();
66 this.resource = $localize`service`;
67 this.hosts = {
68 options: [],
69 messages: new SelectMessages({
70 empty: $localize`There are no hosts.`,
71 filter: $localize`Filter hosts`
72 })
73 };
74 this.createForm();
75 }
76
77 createForm() {
78 this.serviceForm = this.formBuilder.group({
79 // Global
80 service_type: [null, [Validators.required]],
81 service_id: [
82 null,
83 [
84 CdValidators.requiredIf({
85 service_type: 'mds'
86 }),
87 CdValidators.requiredIf({
88 service_type: 'nfs'
89 }),
90 CdValidators.requiredIf({
91 service_type: 'iscsi'
92 }),
93 CdValidators.requiredIf({
94 service_type: 'ingress'
95 }),
96 CdValidators.composeIf(
97 {
98 service_type: 'rgw'
99 },
100 [
101 Validators.required,
102 CdValidators.custom('rgwPattern', (value: string) => {
103 if (_.isEmpty(value)) {
104 return false;
105 }
106 return !this.RGW_SVC_ID_PATTERN.test(value);
107 })
108 ]
109 )
110 ]
111 ],
112 placement: ['hosts'],
113 label: [
114 null,
115 [
116 CdValidators.requiredIf({
117 placement: 'label',
118 unmanaged: false
119 })
120 ]
121 ],
122 hosts: [[]],
123 count: [null, [CdValidators.number(false), Validators.min(1)]],
124 unmanaged: [false],
125 // iSCSI
126 pool: [
127 null,
128 [
129 CdValidators.requiredIf({
130 service_type: 'iscsi',
131 unmanaged: false
132 })
133 ]
134 ],
135 // RGW
136 rgw_frontend_port: [
137 null,
138 [CdValidators.number(false), Validators.min(1), Validators.max(65535)]
139 ],
140 // iSCSI
141 trusted_ip_list: [null],
142 api_port: [null, [CdValidators.number(false), Validators.min(1), Validators.max(65535)]],
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: [null, [CdValidators.number(false), Validators.min(1), Validators.max(65535)]],
181 monitor_port: [null, [CdValidators.number(false), Validators.min(1), Validators.max(65535)]],
182 virtual_interface_networks: [null],
183 // RGW, Ingress & iSCSI
184 ssl: [false],
185 ssl_cert: [
186 '',
187 [
188 CdValidators.composeIf(
189 {
190 service_type: 'rgw',
191 unmanaged: false,
192 ssl: true
193 },
194 [Validators.required, CdValidators.pemCert()]
195 ),
196 CdValidators.composeIf(
197 {
198 service_type: 'iscsi',
199 unmanaged: false,
200 ssl: true
201 },
202 [Validators.required, CdValidators.sslCert()]
203 )
204 ]
205 ],
206 ssl_key: [
207 '',
208 [
209 CdValidators.composeIf(
210 {
211 service_type: 'iscsi',
212 unmanaged: false,
213 ssl: true
214 },
215 [Validators.required, CdValidators.sslPrivKey()]
216 )
217 ]
218 ]
219 });
220 }
221
222 ngOnInit(): void {
223 this.action = this.actionLabels.CREATE;
224 if (this.router.url.includes('services/(modal:create')) {
225 this.pageURL = 'services';
226 } else if (this.router.url.includes('services/(modal:edit')) {
227 this.editing = true;
228 this.pageURL = 'services';
229 this.route.params.subscribe((params: { type: string; name: string }) => {
230 this.serviceName = params.name;
231 this.serviceType = params.type;
232 });
233 }
234 this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
235 // Remove service types:
236 // osd - This is deployed a different way.
237 // container - This should only be used in the CLI.
238 this.hiddenServices.push('osd', 'container');
239
240 this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
241 });
242 this.hostService.list('false').subscribe((resp: object[]) => {
243 const options: SelectOption[] = [];
244 _.forEach(resp, (host: object) => {
245 if (_.get(host, 'sources.orchestrator', false)) {
246 const option = new SelectOption(false, _.get(host, 'hostname'), '');
247 options.push(option);
248 }
249 });
250 this.hosts.options = [...options];
251 });
252 this.hostService.getLabels().subscribe((resp: string[]) => {
253 this.labels = resp;
254 });
255 this.poolService.getList().subscribe((resp: Array<object>) => {
256 this.pools = resp;
257 });
258 this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
259 this.services = services.filter((service: any) => service.service_type === 'rgw');
260 });
261
262 if (this.editing) {
263 this.action = this.actionLabels.EDIT;
264 this.disableForEditing(this.serviceType);
265 this.cephServiceService.list(this.serviceName).subscribe((response: CephServiceSpec[]) => {
266 const formKeys = ['service_type', 'service_id', 'unmanaged'];
267 formKeys.forEach((keys) => {
268 this.serviceForm.get(keys).setValue(response[0][keys]);
269 });
270 if (!response[0]['unmanaged']) {
271 const placementKey = Object.keys(response[0]['placement'])[0];
272 let placementValue: string;
273 ['hosts', 'label'].indexOf(placementKey) >= 0
274 ? (placementValue = placementKey)
275 : (placementValue = 'hosts');
276 this.serviceForm.get('placement').setValue(placementValue);
277 this.serviceForm.get('count').setValue(response[0]['placement']['count']);
278 if (response[0]?.placement[placementValue]) {
279 this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
280 }
281 }
282 switch (this.serviceType) {
283 case 'iscsi':
284 const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
285 specKeys.forEach((key) => {
286 this.serviceForm.get(key).setValue(response[0].spec[key]);
287 });
288 this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
289 if (response[0].spec?.api_secure) {
290 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
291 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
292 }
293 break;
294 case 'rgw':
295 this.serviceForm.get('rgw_frontend_port').setValue(response[0].spec?.rgw_frontend_port);
296 this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
297 if (response[0].spec?.ssl) {
298 this.serviceForm
299 .get('ssl_cert')
300 .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
301 }
302 break;
303 case 'ingress':
304 const ingressSpecKeys = [
305 'backend_service',
306 'virtual_ip',
307 'frontend_port',
308 'monitor_port',
309 'virtual_interface_networks',
310 'ssl'
311 ];
312 ingressSpecKeys.forEach((key) => {
313 this.serviceForm.get(key).setValue(response[0].spec[key]);
314 });
315 if (response[0].spec?.ssl) {
316 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
317 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
318 }
319 break;
320 }
321 });
322 }
323 }
324
325 disableForEditing(serviceType: string) {
326 const disableForEditKeys = ['service_type', 'service_id'];
327 disableForEditKeys.forEach((key) => {
328 this.serviceForm.get(key).disable();
329 });
330 switch (serviceType) {
331 case 'ingress':
332 this.serviceForm.get('backend_service').disable();
333 }
334 }
335
336 searchLabels = (text$: Observable<string>) => {
337 return merge(
338 text$.pipe(debounceTime(200), distinctUntilChanged()),
339 this.labelFocus,
340 this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
341 ).pipe(
342 map((value) =>
343 this.labels
344 .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
345 .slice(0, 10)
346 )
347 );
348 };
349
350 fileUpload(files: FileList, controlName: string) {
351 const file: File = files[0];
352 const reader = new FileReader();
353 reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
354 const control: AbstractControl = this.serviceForm.get(controlName);
355 control.setValue(event.target.result);
356 control.markAsDirty();
357 control.markAsTouched();
358 control.updateValueAndValidity();
359 });
360 reader.readAsText(file, 'utf8');
361 }
362
363 prePopulateId() {
364 const control: AbstractControl = this.serviceForm.get('service_id');
365 const backendService = this.serviceForm.getValue('backend_service');
366 // Set Id as read-only
367 control.reset({ value: backendService, disabled: true });
368 }
369
370 onSubmit() {
371 const self = this;
372 const values: object = this.serviceForm.getRawValue();
373 const serviceType: string = values['service_type'];
374 let taskUrl = `service/${URLVerbs.CREATE}`;
375 if (this.editing) {
376 taskUrl = `service/${URLVerbs.EDIT}`;
377 }
378 const serviceSpec: object = {
379 service_type: serviceType,
380 placement: {},
381 unmanaged: values['unmanaged']
382 };
383 let svcId: string;
384 if (serviceType === 'rgw') {
385 const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
386 svcId = svcIdMatch[1];
387 if (svcIdMatch[3]) {
388 serviceSpec['rgw_realm'] = svcIdMatch[3];
389 serviceSpec['rgw_zone'] = svcIdMatch[4];
390 }
391 } else {
392 svcId = values['service_id'];
393 }
394 const serviceId: string = svcId;
395 let serviceName: string = serviceType;
396 if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
397 serviceName = `${serviceType}.${serviceId}`;
398 serviceSpec['service_id'] = serviceId;
399 }
400 if (!values['unmanaged']) {
401 switch (values['placement']) {
402 case 'hosts':
403 if (values['hosts'].length > 0) {
404 serviceSpec['placement']['hosts'] = values['hosts'];
405 }
406 break;
407 case 'label':
408 serviceSpec['placement']['label'] = values['label'];
409 break;
410 }
411 if (_.isNumber(values['count']) && values['count'] > 0) {
412 serviceSpec['placement']['count'] = values['count'];
413 }
414 switch (serviceType) {
415 case 'rgw':
416 if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
417 serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
418 }
419 serviceSpec['ssl'] = values['ssl'];
420 if (values['ssl']) {
421 serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
422 }
423 break;
424 case 'iscsi':
425 serviceSpec['pool'] = values['pool'];
426 if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
427 serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
428 }
429 if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
430 serviceSpec['api_port'] = values['api_port'];
431 }
432 serviceSpec['api_user'] = values['api_user'];
433 serviceSpec['api_password'] = values['api_password'];
434 serviceSpec['api_secure'] = values['ssl'];
435 if (values['ssl']) {
436 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
437 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
438 }
439 break;
440 case 'ingress':
441 serviceSpec['backend_service'] = values['backend_service'];
442 serviceSpec['service_id'] = values['backend_service'];
443 if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
444 serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
445 }
446 if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
447 serviceSpec['frontend_port'] = values['frontend_port'];
448 }
449 if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
450 serviceSpec['monitor_port'] = values['monitor_port'];
451 }
452 serviceSpec['ssl'] = values['ssl'];
453 if (values['ssl']) {
454 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
455 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
456 }
457 serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
458 break;
459 }
460 }
461
462 this.taskWrapperService
463 .wrapTaskAroundCall({
464 task: new FinishedTask(taskUrl, {
465 service_name: serviceName
466 }),
467 call: this.cephServiceService.create(serviceSpec)
468 })
469 .subscribe({
470 error() {
471 self.serviceForm.setErrors({ cdSubmitButton: true });
472 },
473 complete: () => {
474 this.pageURL === 'services'
475 ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
476 : this.activeModal.close();
477 }
478 });
479 }
480 }