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