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 SNMP_DESTINATION_PATTERN = /^[^\:]+:[0-9]/;
32 readonly SNMP_ENGINE_ID_PATTERN = /^[0-9A-Fa-f]{10,64}/g;
33 readonly INGRESS_SUPPORTED_SERVICE_TYPES = ['rgw', 'nfs'];
34 @ViewChild(NgbTypeahead, { static: false })
35 typeahead: NgbTypeahead;
37 @Input() hiddenServices: string[] = [];
39 @Input() editing = false;
41 @Input() serviceName: string;
43 @Input() serviceType: string;
45 serviceForm: CdFormGroup;
48 serviceTypes: string[] = [];
49 serviceIds: string[] = [];
52 labelClick = new Subject<string>();
53 labelFocus = new Subject<string>();
55 services: Array<CephServiceSpec> = [];
57 serviceList: CephServiceSpec[];
60 public actionLabels: ActionLabelsI18n,
61 private cephServiceService: CephServiceService,
62 private formBuilder: CdFormBuilder,
63 private hostService: HostService,
64 private poolService: PoolService,
65 private router: Router,
66 private taskWrapperService: TaskWrapperService,
67 private route: ActivatedRoute,
68 public activeModal: NgbActiveModal
71 this.resource = $localize`service`;
74 messages: new SelectMessages({
75 empty: $localize`There are no hosts.`,
76 filter: $localize`Filter hosts`
83 this.serviceForm = this.formBuilder.group({
85 service_type: [null, [Validators.required]],
89 CdValidators.requiredIf({
92 CdValidators.requiredIf({
95 CdValidators.requiredIf({
98 CdValidators.requiredIf({
99 service_type: 'ingress'
101 CdValidators.composeIf(
107 CdValidators.custom('rgwPattern', (value: string) => {
108 if (_.isEmpty(value)) {
111 return !this.RGW_SVC_ID_PATTERN.test(value);
115 CdValidators.custom('uniqueName', (service_id: string) => {
116 return this.serviceIds && this.serviceIds.includes(service_id);
120 placement: ['hosts'],
124 CdValidators.requiredIf({
131 count: [null, [CdValidators.number(false)]],
137 CdValidators.requiredIf({
138 service_type: 'iscsi'
143 rgw_frontend_port: [null, [CdValidators.number(false)]],
145 trusted_ip_list: [null],
146 api_port: [null, [CdValidators.number(false)]],
150 CdValidators.requiredIf({
151 service_type: 'iscsi',
159 CdValidators.requiredIf({
160 service_type: 'iscsi',
169 CdValidators.requiredIf({
170 service_type: 'ingress'
177 CdValidators.requiredIf({
178 service_type: 'ingress'
185 CdValidators.number(false),
186 CdValidators.requiredIf({
187 service_type: 'ingress'
194 CdValidators.number(false),
195 CdValidators.requiredIf({
196 service_type: 'ingress'
200 virtual_interface_networks: [null],
201 // RGW, Ingress & iSCSI
206 CdValidators.composeIf(
212 [Validators.required, CdValidators.pemCert()]
214 CdValidators.composeIf(
216 service_type: 'iscsi',
220 [Validators.required, CdValidators.sslCert()]
222 CdValidators.composeIf(
224 service_type: 'ingress',
228 [Validators.required, CdValidators.pemCert()]
235 CdValidators.composeIf(
237 service_type: 'iscsi',
241 [Validators.required, CdValidators.sslPrivKey()]
249 CdValidators.requiredIf({
250 service_type: 'snmp-gateway'
258 CdValidators.requiredIf({
259 service_type: 'snmp-gateway'
261 CdValidators.custom('snmpDestinationPattern', (value: string) => {
262 if (_.isEmpty(value)) {
265 return !this.SNMP_DESTINATION_PATTERN.test(value);
273 CdValidators.requiredIf({
274 service_type: 'snmp-gateway'
276 CdValidators.custom('snmpEngineIdPattern', (value: string) => {
277 if (_.isEmpty(value)) {
280 return !this.SNMP_ENGINE_ID_PATTERN.test(value);
287 CdValidators.requiredIf({
288 service_type: 'snmp-gateway'
292 privacy_protocol: [null],
296 CdValidators.requiredIf({
301 snmp_v3_auth_username: [
304 CdValidators.requiredIf({
305 service_type: 'snmp-gateway'
309 snmp_v3_auth_password: [
312 CdValidators.requiredIf({
313 service_type: 'snmp-gateway'
317 snmp_v3_priv_password: [
320 CdValidators.requiredIf({
321 privacy_protocol: { op: '!empty' }
329 this.action = this.actionLabels.CREATE;
330 if (this.router.url.includes('services/(modal:create')) {
331 this.pageURL = 'services';
332 } else if (this.router.url.includes('services/(modal:edit')) {
334 this.pageURL = 'services';
335 this.route.params.subscribe((params: { type: string; name: string }) => {
336 this.serviceName = params.name;
337 this.serviceType = params.type;
341 this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
342 this.serviceList = services;
343 this.services = services.filter((service: any) =>
344 this.INGRESS_SUPPORTED_SERVICE_TYPES.includes(service.service_type)
348 this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
349 // Remove service types:
350 // osd - This is deployed a different way.
351 // container - This should only be used in the CLI.
352 this.hiddenServices.push('osd', 'container');
354 this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
356 this.hostService.list('false').subscribe((resp: object[]) => {
357 const options: SelectOption[] = [];
358 _.forEach(resp, (host: object) => {
359 if (_.get(host, 'sources.orchestrator', false)) {
360 const option = new SelectOption(false, _.get(host, 'hostname'), '');
361 options.push(option);
364 this.hosts.options = [...options];
366 this.hostService.getLabels().subscribe((resp: string[]) => {
369 this.poolService.getList().subscribe((resp: Array<object>) => {
374 this.action = this.actionLabels.EDIT;
375 this.disableForEditing(this.serviceType);
376 this.cephServiceService.list(this.serviceName).subscribe((response: CephServiceSpec[]) => {
377 const formKeys = ['service_type', 'service_id', 'unmanaged'];
378 formKeys.forEach((keys) => {
379 this.serviceForm.get(keys).setValue(response[0][keys]);
381 if (!response[0]['unmanaged']) {
382 const placementKey = Object.keys(response[0]['placement'])[0];
383 let placementValue: string;
384 ['hosts', 'label'].indexOf(placementKey) >= 0
385 ? (placementValue = placementKey)
386 : (placementValue = 'hosts');
387 this.serviceForm.get('placement').setValue(placementValue);
388 this.serviceForm.get('count').setValue(response[0]['placement']['count']);
389 if (response[0]?.placement[placementValue]) {
390 this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
393 switch (this.serviceType) {
395 const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
396 specKeys.forEach((key) => {
397 this.serviceForm.get(key).setValue(response[0].spec[key]);
399 this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
400 if (response[0].spec?.api_secure) {
401 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
402 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
406 this.serviceForm.get('rgw_frontend_port').setValue(response[0].spec?.rgw_frontend_port);
407 this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
408 if (response[0].spec?.ssl) {
411 .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
415 const ingressSpecKeys = [
420 'virtual_interface_networks',
423 ingressSpecKeys.forEach((key) => {
424 this.serviceForm.get(key).setValue(response[0].spec[key]);
426 if (response[0].spec?.ssl) {
427 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
428 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
432 const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
433 snmpCommonSpecKeys.forEach((key) => {
434 this.serviceForm.get(key).setValue(response[0].spec[key]);
436 if (this.serviceForm.getValue('snmp_version') === 'V3') {
437 const snmpV3SpecKeys = [
441 'snmp_v3_auth_username',
442 'snmp_v3_auth_password',
443 'snmp_v3_priv_password'
445 snmpV3SpecKeys.forEach((key) => {
448 key === 'snmp_v3_auth_username' ||
449 key === 'snmp_v3_auth_password' ||
450 key === 'snmp_v3_priv_password'
452 this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
454 this.serviceForm.get(key).setValue(response[0].spec[key]);
460 .get('snmp_community')
461 .setValue(response[0].spec['credentials']['snmp_community']);
469 getServiceIds(selectedServiceType: string) {
470 this.serviceIds = this.serviceList
471 .filter((service) => service['service_type'] === selectedServiceType)
472 .map((service) => service['service_id']);
475 disableForEditing(serviceType: string) {
476 const disableForEditKeys = ['service_type', 'service_id'];
477 disableForEditKeys.forEach((key) => {
478 this.serviceForm.get(key).disable();
480 switch (serviceType) {
482 this.serviceForm.get('backend_service').disable();
486 searchLabels = (text$: Observable<string>) => {
488 text$.pipe(debounceTime(200), distinctUntilChanged()),
490 this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
494 .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
500 fileUpload(files: FileList, controlName: string) {
501 const file: File = files[0];
502 const reader = new FileReader();
503 reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
504 const control: AbstractControl = this.serviceForm.get(controlName);
505 control.setValue(event.target.result);
506 control.markAsDirty();
507 control.markAsTouched();
508 control.updateValueAndValidity();
510 reader.readAsText(file, 'utf8');
514 const control: AbstractControl = this.serviceForm.get('service_id');
515 const backendService = this.serviceForm.getValue('backend_service');
516 // Set Id as read-only
517 control.reset({ value: backendService, disabled: true });
522 const values: object = this.serviceForm.getRawValue();
523 const serviceType: string = values['service_type'];
524 let taskUrl = `service/${URLVerbs.CREATE}`;
526 taskUrl = `service/${URLVerbs.EDIT}`;
528 const serviceSpec: object = {
529 service_type: serviceType,
531 unmanaged: values['unmanaged']
534 if (serviceType === 'rgw') {
535 const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
536 svcId = svcIdMatch[1];
538 serviceSpec['rgw_realm'] = svcIdMatch[3];
539 serviceSpec['rgw_zone'] = svcIdMatch[4];
542 svcId = values['service_id'];
544 const serviceId: string = svcId;
545 let serviceName: string = serviceType;
546 if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
547 serviceName = `${serviceType}.${serviceId}`;
548 serviceSpec['service_id'] = serviceId;
551 // These services has some fields to be
552 // filled out even if unmanaged is true
553 switch (serviceType) {
555 serviceSpec['backend_service'] = values['backend_service'];
556 serviceSpec['service_id'] = values['backend_service'];
557 if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
558 serviceSpec['frontend_port'] = values['frontend_port'];
560 if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
561 serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
563 if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
564 serviceSpec['monitor_port'] = values['monitor_port'];
569 serviceSpec['pool'] = values['pool'];
573 serviceSpec['credentials'] = {};
574 serviceSpec['snmp_version'] = values['snmp_version'];
575 serviceSpec['snmp_destination'] = values['snmp_destination'];
576 if (values['snmp_version'] === 'V3') {
577 serviceSpec['engine_id'] = values['engine_id'];
578 serviceSpec['auth_protocol'] = values['auth_protocol'];
579 serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
580 serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
581 if (values['privacy_protocol'] !== null) {
582 serviceSpec['privacy_protocol'] = values['privacy_protocol'];
583 serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
586 serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
591 if (!values['unmanaged']) {
592 switch (values['placement']) {
594 if (values['hosts'].length > 0) {
595 serviceSpec['placement']['hosts'] = values['hosts'];
599 serviceSpec['placement']['label'] = values['label'];
602 if (_.isNumber(values['count']) && values['count'] > 0) {
603 serviceSpec['placement']['count'] = values['count'];
605 switch (serviceType) {
607 if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
608 serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
610 serviceSpec['ssl'] = values['ssl'];
612 serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
616 if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
617 serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
619 if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
620 serviceSpec['api_port'] = values['api_port'];
622 serviceSpec['api_user'] = values['api_user'];
623 serviceSpec['api_password'] = values['api_password'];
624 serviceSpec['api_secure'] = values['ssl'];
626 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
627 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
631 serviceSpec['ssl'] = values['ssl'];
633 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
634 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
636 serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
641 this.taskWrapperService
642 .wrapTaskAroundCall({
643 task: new FinishedTask(taskUrl, {
644 service_name: serviceName
647 ? this.cephServiceService.update(serviceSpec)
648 : this.cephServiceService.create(serviceSpec)
652 self.serviceForm.setErrors({ cdSubmitButton: true });
655 this.pageURL === 'services'
656 ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
657 : this.activeModal.close();
663 const snmpVersion = this.serviceForm.getValue('snmp_version');
664 const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
665 if (snmpVersion === 'V3') {
666 this.serviceForm.get('snmp_community').clearValidators();
668 this.serviceForm.get('engine_id').clearValidators();
669 this.serviceForm.get('auth_protocol').clearValidators();
670 this.serviceForm.get('privacy_protocol').clearValidators();
671 this.serviceForm.get('snmp_v3_auth_username').clearValidators();
672 this.serviceForm.get('snmp_v3_auth_password').clearValidators();
674 if (privacyProtocol === null) {
675 this.serviceForm.get('snmp_v3_priv_password').clearValidators();