1 import { Component, Input, OnInit, ViewChild } from '@angular/core';
2 import { AbstractControl, Validators } from '@angular/forms';
3 import { ActivatedRoute, Router } from '@angular/router';
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';
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';
25 selector: 'cd-service-form',
26 templateUrl: './service-form.component.html',
27 styleUrls: ['./service-form.component.scss']
29 export class ServiceFormComponent extends CdForm implements OnInit {
30 readonly RGW_SVC_ID_PATTERN = /^([^.]+)(\.([^.]+)\.([^.]+))?$/;
31 readonly MDS_SVC_ID_PATTERN = /^[a-zA-Z_.-][a-zA-Z0-9_.-]*$/;
32 readonly SNMP_DESTINATION_PATTERN = /^[^\:]+:[0-9]/;
33 readonly SNMP_ENGINE_ID_PATTERN = /^[0-9A-Fa-f]{10,64}/g;
34 readonly INGRESS_SUPPORTED_SERVICE_TYPES = ['rgw', 'nfs'];
35 @ViewChild(NgbTypeahead, { static: false })
36 typeahead: NgbTypeahead;
38 @Input() hiddenServices: string[] = [];
40 @Input() editing = false;
42 @Input() serviceName: string;
44 @Input() serviceType: string;
46 serviceForm: CdFormGroup;
49 serviceTypes: string[] = [];
50 serviceIds: string[] = [];
53 labelClick = new Subject<string>();
54 labelFocus = new Subject<string>();
56 services: Array<CephServiceSpec> = [];
58 serviceList: CephServiceSpec[];
61 public actionLabels: ActionLabelsI18n,
62 private cephServiceService: CephServiceService,
63 private formBuilder: CdFormBuilder,
64 private hostService: HostService,
65 private poolService: PoolService,
66 private router: Router,
67 private taskWrapperService: TaskWrapperService,
68 private route: ActivatedRoute,
69 public activeModal: NgbActiveModal
72 this.resource = $localize`service`;
75 messages: new SelectMessages({
76 empty: $localize`There are no hosts.`,
77 filter: $localize`Filter hosts`
84 this.serviceForm = this.formBuilder.group({
86 service_type: [null, [Validators.required]],
90 CdValidators.composeIf(
96 CdValidators.custom('mdsPattern', (value: string) => {
97 if (_.isEmpty(value)) {
100 return !this.MDS_SVC_ID_PATTERN.test(value);
104 CdValidators.requiredIf({
107 CdValidators.requiredIf({
108 service_type: 'iscsi'
110 CdValidators.requiredIf({
111 service_type: 'ingress'
113 CdValidators.composeIf(
119 CdValidators.custom('rgwPattern', (value: string) => {
120 if (_.isEmpty(value)) {
123 return !this.RGW_SVC_ID_PATTERN.test(value);
127 CdValidators.custom('uniqueName', (service_id: string) => {
128 return this.serviceIds && this.serviceIds.includes(service_id);
132 placement: ['hosts'],
136 CdValidators.requiredIf({
143 count: [null, [CdValidators.number(false)]],
149 CdValidators.requiredIf({
150 service_type: 'iscsi',
156 rgw_frontend_port: [null, [CdValidators.number(false)]],
158 trusted_ip_list: [null],
159 api_port: [null, [CdValidators.number(false)]],
163 CdValidators.requiredIf({
164 service_type: 'iscsi',
172 CdValidators.requiredIf({
173 service_type: 'iscsi',
182 CdValidators.requiredIf({
183 service_type: 'ingress'
190 CdValidators.requiredIf({
191 service_type: 'ingress'
198 CdValidators.number(false),
199 CdValidators.requiredIf({
200 service_type: 'ingress'
207 CdValidators.number(false),
208 CdValidators.requiredIf({
209 service_type: 'ingress'
213 virtual_interface_networks: [null],
214 // RGW, Ingress & iSCSI
219 CdValidators.composeIf(
225 [Validators.required, CdValidators.pemCert()]
227 CdValidators.composeIf(
229 service_type: 'iscsi',
233 [Validators.required, CdValidators.sslCert()]
235 CdValidators.composeIf(
237 service_type: 'ingress',
241 [Validators.required, CdValidators.pemCert()]
248 CdValidators.composeIf(
250 service_type: 'iscsi',
254 [Validators.required, CdValidators.sslPrivKey()]
262 CdValidators.requiredIf({
263 service_type: 'snmp-gateway'
271 CdValidators.requiredIf({
272 service_type: 'snmp-gateway'
274 CdValidators.custom('snmpDestinationPattern', (value: string) => {
275 if (_.isEmpty(value)) {
278 return !this.SNMP_DESTINATION_PATTERN.test(value);
286 CdValidators.requiredIf({
287 service_type: 'snmp-gateway'
289 CdValidators.custom('snmpEngineIdPattern', (value: string) => {
290 if (_.isEmpty(value)) {
293 return !this.SNMP_ENGINE_ID_PATTERN.test(value);
300 CdValidators.requiredIf({
301 service_type: 'snmp-gateway'
305 privacy_protocol: [null],
309 CdValidators.requiredIf({
314 snmp_v3_auth_username: [
317 CdValidators.requiredIf({
318 service_type: 'snmp-gateway'
322 snmp_v3_auth_password: [
325 CdValidators.requiredIf({
326 service_type: 'snmp-gateway'
330 snmp_v3_priv_password: [
333 CdValidators.requiredIf({
334 privacy_protocol: { op: '!empty' }
342 this.action = this.actionLabels.CREATE;
343 if (this.router.url.includes('services/(modal:create')) {
344 this.pageURL = 'services';
345 } else if (this.router.url.includes('services/(modal:edit')) {
347 this.pageURL = 'services';
348 this.route.params.subscribe((params: { type: string; name: string }) => {
349 this.serviceName = params.name;
350 this.serviceType = params.type;
354 this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
355 this.serviceList = services;
356 this.services = services.filter((service: any) =>
357 this.INGRESS_SUPPORTED_SERVICE_TYPES.includes(service.service_type)
361 this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
362 // Remove service types:
363 // osd - This is deployed a different way.
364 // container - This should only be used in the CLI.
365 this.hiddenServices.push('osd', 'container');
367 this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
369 this.hostService.list('false').subscribe((resp: object[]) => {
370 const options: SelectOption[] = [];
371 _.forEach(resp, (host: object) => {
372 if (_.get(host, 'sources.orchestrator', false)) {
373 const option = new SelectOption(false, _.get(host, 'hostname'), '');
374 options.push(option);
377 this.hosts.options = [...options];
379 this.hostService.getLabels().subscribe((resp: string[]) => {
382 this.poolService.getList().subscribe((resp: Array<object>) => {
387 this.action = this.actionLabels.EDIT;
388 this.disableForEditing(this.serviceType);
389 this.cephServiceService.list(this.serviceName).subscribe((response: CephServiceSpec[]) => {
390 const formKeys = ['service_type', 'service_id', 'unmanaged'];
391 formKeys.forEach((keys) => {
392 this.serviceForm.get(keys).setValue(response[0][keys]);
394 if (!response[0]['unmanaged']) {
395 const placementKey = Object.keys(response[0]['placement'])[0];
396 let placementValue: string;
397 ['hosts', 'label'].indexOf(placementKey) >= 0
398 ? (placementValue = placementKey)
399 : (placementValue = 'hosts');
400 this.serviceForm.get('placement').setValue(placementValue);
401 this.serviceForm.get('count').setValue(response[0]['placement']['count']);
402 if (response[0]?.placement[placementValue]) {
403 this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
406 switch (this.serviceType) {
408 const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
409 specKeys.forEach((key) => {
410 this.serviceForm.get(key).setValue(response[0].spec[key]);
412 this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
413 if (response[0].spec?.api_secure) {
414 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
415 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
419 this.serviceForm.get('rgw_frontend_port').setValue(response[0].spec?.rgw_frontend_port);
420 this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
421 if (response[0].spec?.ssl) {
424 .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
428 const ingressSpecKeys = [
433 'virtual_interface_networks',
436 ingressSpecKeys.forEach((key) => {
437 this.serviceForm.get(key).setValue(response[0].spec[key]);
439 if (response[0].spec?.ssl) {
440 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
441 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
445 const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
446 snmpCommonSpecKeys.forEach((key) => {
447 this.serviceForm.get(key).setValue(response[0].spec[key]);
449 if (this.serviceForm.getValue('snmp_version') === 'V3') {
450 const snmpV3SpecKeys = [
454 'snmp_v3_auth_username',
455 'snmp_v3_auth_password',
456 'snmp_v3_priv_password'
458 snmpV3SpecKeys.forEach((key) => {
461 key === 'snmp_v3_auth_username' ||
462 key === 'snmp_v3_auth_password' ||
463 key === 'snmp_v3_priv_password'
465 this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
467 this.serviceForm.get(key).setValue(response[0].spec[key]);
473 .get('snmp_community')
474 .setValue(response[0].spec['credentials']['snmp_community']);
482 getServiceIds(selectedServiceType: string) {
483 this.serviceIds = this.serviceList
484 .filter((service) => service['service_type'] === selectedServiceType)
485 .map((service) => service['service_id']);
488 disableForEditing(serviceType: string) {
489 const disableForEditKeys = ['service_type', 'service_id'];
490 disableForEditKeys.forEach((key) => {
491 this.serviceForm.get(key).disable();
493 switch (serviceType) {
495 this.serviceForm.get('backend_service').disable();
499 searchLabels = (text$: Observable<string>) => {
501 text$.pipe(debounceTime(200), distinctUntilChanged()),
503 this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
507 .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
513 fileUpload(files: FileList, controlName: string) {
514 const file: File = files[0];
515 const reader = new FileReader();
516 reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
517 const control: AbstractControl = this.serviceForm.get(controlName);
518 control.setValue(event.target.result);
519 control.markAsDirty();
520 control.markAsTouched();
521 control.updateValueAndValidity();
523 reader.readAsText(file, 'utf8');
527 const control: AbstractControl = this.serviceForm.get('service_id');
528 const backendService = this.serviceForm.getValue('backend_service');
529 // Set Id as read-only
530 control.reset({ value: backendService, disabled: true });
535 const values: object = this.serviceForm.getRawValue();
536 const serviceType: string = values['service_type'];
537 let taskUrl = `service/${URLVerbs.CREATE}`;
539 taskUrl = `service/${URLVerbs.EDIT}`;
541 const serviceSpec: object = {
542 service_type: serviceType,
544 unmanaged: values['unmanaged']
547 if (serviceType === 'rgw') {
548 const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
549 svcId = svcIdMatch[1];
551 serviceSpec['rgw_realm'] = svcIdMatch[3];
552 serviceSpec['rgw_zone'] = svcIdMatch[4];
555 svcId = values['service_id'];
557 const serviceId: string = svcId;
558 let serviceName: string = serviceType;
559 if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
560 serviceName = `${serviceType}.${serviceId}`;
561 serviceSpec['service_id'] = serviceId;
564 switch (serviceType) {
566 serviceSpec['backend_service'] = values['backend_service'];
567 serviceSpec['service_id'] = values['backend_service'];
568 if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
569 serviceSpec['frontend_port'] = values['frontend_port'];
571 if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
572 serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
574 if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
575 serviceSpec['monitor_port'] = values['monitor_port'];
580 if (!values['unmanaged']) {
581 switch (values['placement']) {
583 if (values['hosts'].length > 0) {
584 serviceSpec['placement']['hosts'] = values['hosts'];
588 serviceSpec['placement']['label'] = values['label'];
591 if (_.isNumber(values['count']) && values['count'] > 0) {
592 serviceSpec['placement']['count'] = values['count'];
594 switch (serviceType) {
596 if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
597 serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
599 serviceSpec['ssl'] = values['ssl'];
601 serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
605 serviceSpec['pool'] = values['pool'];
606 if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
607 serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
609 if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
610 serviceSpec['api_port'] = values['api_port'];
612 serviceSpec['api_user'] = values['api_user'];
613 serviceSpec['api_password'] = values['api_password'];
614 serviceSpec['api_secure'] = values['ssl'];
616 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
617 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
621 serviceSpec['ssl'] = values['ssl'];
623 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
624 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
626 serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
629 serviceSpec['credentials'] = {};
630 serviceSpec['snmp_version'] = values['snmp_version'];
631 serviceSpec['snmp_destination'] = values['snmp_destination'];
632 if (values['snmp_version'] === 'V3') {
633 serviceSpec['engine_id'] = values['engine_id'];
634 serviceSpec['auth_protocol'] = values['auth_protocol'];
635 serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
636 serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
637 if (values['privacy_protocol'] !== null) {
638 serviceSpec['privacy_protocol'] = values['privacy_protocol'];
639 serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
642 serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
648 this.taskWrapperService
649 .wrapTaskAroundCall({
650 task: new FinishedTask(taskUrl, {
651 service_name: serviceName
654 ? this.cephServiceService.update(serviceSpec)
655 : this.cephServiceService.create(serviceSpec)
659 self.serviceForm.setErrors({ cdSubmitButton: true });
662 this.pageURL === 'services'
663 ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
664 : this.activeModal.close();
670 const snmpVersion = this.serviceForm.getValue('snmp_version');
671 const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
672 if (snmpVersion === 'V3') {
673 this.serviceForm.get('snmp_community').clearValidators();
675 this.serviceForm.get('engine_id').clearValidators();
676 this.serviceForm.get('auth_protocol').clearValidators();
677 this.serviceForm.get('privacy_protocol').clearValidators();
678 this.serviceForm.get('snmp_v3_auth_username').clearValidators();
679 this.serviceForm.get('snmp_v3_auth_password').clearValidators();
681 if (privacyProtocol === null) {
682 this.serviceForm.get('snmp_v3_priv_password').clearValidators();