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'
155 rgw_frontend_port: [null, [CdValidators.number(false)]],
157 trusted_ip_list: [null],
158 api_port: [null, [CdValidators.number(false)]],
162 CdValidators.requiredIf({
163 service_type: 'iscsi',
171 CdValidators.requiredIf({
172 service_type: 'iscsi',
181 CdValidators.requiredIf({
182 service_type: 'ingress'
189 CdValidators.requiredIf({
190 service_type: 'ingress'
197 CdValidators.number(false),
198 CdValidators.requiredIf({
199 service_type: 'ingress'
206 CdValidators.number(false),
207 CdValidators.requiredIf({
208 service_type: 'ingress'
212 virtual_interface_networks: [null],
213 // RGW, Ingress & iSCSI
218 CdValidators.composeIf(
224 [Validators.required, CdValidators.pemCert()]
226 CdValidators.composeIf(
228 service_type: 'iscsi',
232 [Validators.required, CdValidators.sslCert()]
234 CdValidators.composeIf(
236 service_type: 'ingress',
240 [Validators.required, CdValidators.pemCert()]
247 CdValidators.composeIf(
249 service_type: 'iscsi',
253 [Validators.required, CdValidators.sslPrivKey()]
261 CdValidators.requiredIf({
262 service_type: 'snmp-gateway'
270 CdValidators.requiredIf({
271 service_type: 'snmp-gateway'
273 CdValidators.custom('snmpDestinationPattern', (value: string) => {
274 if (_.isEmpty(value)) {
277 return !this.SNMP_DESTINATION_PATTERN.test(value);
285 CdValidators.requiredIf({
286 service_type: 'snmp-gateway'
288 CdValidators.custom('snmpEngineIdPattern', (value: string) => {
289 if (_.isEmpty(value)) {
292 return !this.SNMP_ENGINE_ID_PATTERN.test(value);
299 CdValidators.requiredIf({
300 service_type: 'snmp-gateway'
304 privacy_protocol: [null],
308 CdValidators.requiredIf({
313 snmp_v3_auth_username: [
316 CdValidators.requiredIf({
317 service_type: 'snmp-gateway'
321 snmp_v3_auth_password: [
324 CdValidators.requiredIf({
325 service_type: 'snmp-gateway'
329 snmp_v3_priv_password: [
332 CdValidators.requiredIf({
333 privacy_protocol: { op: '!empty' }
341 this.action = this.actionLabels.CREATE;
342 if (this.router.url.includes('services/(modal:create')) {
343 this.pageURL = 'services';
344 } else if (this.router.url.includes('services/(modal:edit')) {
346 this.pageURL = 'services';
347 this.route.params.subscribe((params: { type: string; name: string }) => {
348 this.serviceName = params.name;
349 this.serviceType = params.type;
353 this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
354 this.serviceList = services;
355 this.services = services.filter((service: any) =>
356 this.INGRESS_SUPPORTED_SERVICE_TYPES.includes(service.service_type)
360 this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
361 // Remove service types:
362 // osd - This is deployed a different way.
363 // container - This should only be used in the CLI.
364 this.hiddenServices.push('osd', 'container');
366 this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
368 this.hostService.list('false').subscribe((resp: object[]) => {
369 const options: SelectOption[] = [];
370 _.forEach(resp, (host: object) => {
371 if (_.get(host, 'sources.orchestrator', false)) {
372 const option = new SelectOption(false, _.get(host, 'hostname'), '');
373 options.push(option);
376 this.hosts.options = [...options];
378 this.hostService.getLabels().subscribe((resp: string[]) => {
381 this.poolService.getList().subscribe((resp: Array<object>) => {
386 this.action = this.actionLabels.EDIT;
387 this.disableForEditing(this.serviceType);
388 this.cephServiceService.list(this.serviceName).subscribe((response: CephServiceSpec[]) => {
389 const formKeys = ['service_type', 'service_id', 'unmanaged'];
390 formKeys.forEach((keys) => {
391 this.serviceForm.get(keys).setValue(response[0][keys]);
393 if (!response[0]['unmanaged']) {
394 const placementKey = Object.keys(response[0]['placement'])[0];
395 let placementValue: string;
396 ['hosts', 'label'].indexOf(placementKey) >= 0
397 ? (placementValue = placementKey)
398 : (placementValue = 'hosts');
399 this.serviceForm.get('placement').setValue(placementValue);
400 this.serviceForm.get('count').setValue(response[0]['placement']['count']);
401 if (response[0]?.placement[placementValue]) {
402 this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
405 switch (this.serviceType) {
407 const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
408 specKeys.forEach((key) => {
409 this.serviceForm.get(key).setValue(response[0].spec[key]);
411 this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
412 if (response[0].spec?.api_secure) {
413 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
414 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
418 this.serviceForm.get('rgw_frontend_port').setValue(response[0].spec?.rgw_frontend_port);
419 this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
420 if (response[0].spec?.ssl) {
423 .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
427 const ingressSpecKeys = [
432 'virtual_interface_networks',
435 ingressSpecKeys.forEach((key) => {
436 this.serviceForm.get(key).setValue(response[0].spec[key]);
438 if (response[0].spec?.ssl) {
439 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
440 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
444 const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
445 snmpCommonSpecKeys.forEach((key) => {
446 this.serviceForm.get(key).setValue(response[0].spec[key]);
448 if (this.serviceForm.getValue('snmp_version') === 'V3') {
449 const snmpV3SpecKeys = [
453 'snmp_v3_auth_username',
454 'snmp_v3_auth_password',
455 'snmp_v3_priv_password'
457 snmpV3SpecKeys.forEach((key) => {
460 key === 'snmp_v3_auth_username' ||
461 key === 'snmp_v3_auth_password' ||
462 key === 'snmp_v3_priv_password'
464 this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
466 this.serviceForm.get(key).setValue(response[0].spec[key]);
472 .get('snmp_community')
473 .setValue(response[0].spec['credentials']['snmp_community']);
481 getServiceIds(selectedServiceType: string) {
482 this.serviceIds = this.serviceList
483 ?.filter((service) => service['service_type'] === selectedServiceType)
484 .map((service) => service['service_id']);
487 disableForEditing(serviceType: string) {
488 const disableForEditKeys = ['service_type', 'service_id'];
489 disableForEditKeys.forEach((key) => {
490 this.serviceForm.get(key).disable();
492 switch (serviceType) {
494 this.serviceForm.get('backend_service').disable();
498 searchLabels = (text$: Observable<string>) => {
500 text$.pipe(debounceTime(200), distinctUntilChanged()),
502 this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
506 .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
512 fileUpload(files: FileList, controlName: string) {
513 const file: File = files[0];
514 const reader = new FileReader();
515 reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
516 const control: AbstractControl = this.serviceForm.get(controlName);
517 control.setValue(event.target.result);
518 control.markAsDirty();
519 control.markAsTouched();
520 control.updateValueAndValidity();
522 reader.readAsText(file, 'utf8');
526 const control: AbstractControl = this.serviceForm.get('service_id');
527 const backendService = this.serviceForm.getValue('backend_service');
528 // Set Id as read-only
529 control.reset({ value: backendService, disabled: true });
534 const values: object = this.serviceForm.getRawValue();
535 const serviceType: string = values['service_type'];
536 let taskUrl = `service/${URLVerbs.CREATE}`;
538 taskUrl = `service/${URLVerbs.EDIT}`;
540 const serviceSpec: object = {
541 service_type: serviceType,
543 unmanaged: values['unmanaged']
546 if (serviceType === 'rgw') {
547 const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
548 svcId = svcIdMatch[1];
550 serviceSpec['rgw_realm'] = svcIdMatch[3];
551 serviceSpec['rgw_zone'] = svcIdMatch[4];
554 svcId = values['service_id'];
556 const serviceId: string = svcId;
557 let serviceName: string = serviceType;
558 if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
559 serviceName = `${serviceType}.${serviceId}`;
560 serviceSpec['service_id'] = serviceId;
563 // These services has some fields to be
564 // filled out even if unmanaged is true
565 switch (serviceType) {
567 serviceSpec['backend_service'] = values['backend_service'];
568 serviceSpec['service_id'] = values['backend_service'];
569 if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
570 serviceSpec['frontend_port'] = values['frontend_port'];
572 if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
573 serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
575 if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
576 serviceSpec['monitor_port'] = values['monitor_port'];
581 serviceSpec['pool'] = values['pool'];
585 serviceSpec['credentials'] = {};
586 serviceSpec['snmp_version'] = values['snmp_version'];
587 serviceSpec['snmp_destination'] = values['snmp_destination'];
588 if (values['snmp_version'] === 'V3') {
589 serviceSpec['engine_id'] = values['engine_id'];
590 serviceSpec['auth_protocol'] = values['auth_protocol'];
591 serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
592 serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
593 if (values['privacy_protocol'] !== null) {
594 serviceSpec['privacy_protocol'] = values['privacy_protocol'];
595 serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
598 serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
603 if (!values['unmanaged']) {
604 switch (values['placement']) {
606 if (values['hosts'].length > 0) {
607 serviceSpec['placement']['hosts'] = values['hosts'];
611 serviceSpec['placement']['label'] = values['label'];
614 if (_.isNumber(values['count']) && values['count'] > 0) {
615 serviceSpec['placement']['count'] = values['count'];
617 switch (serviceType) {
619 if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
620 serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
622 serviceSpec['ssl'] = values['ssl'];
624 serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
628 if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
629 serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
631 if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
632 serviceSpec['api_port'] = values['api_port'];
634 serviceSpec['api_user'] = values['api_user'];
635 serviceSpec['api_password'] = values['api_password'];
636 serviceSpec['api_secure'] = values['ssl'];
638 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
639 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
643 serviceSpec['ssl'] = values['ssl'];
645 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
646 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
648 serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
653 this.taskWrapperService
654 .wrapTaskAroundCall({
655 task: new FinishedTask(taskUrl, {
656 service_name: serviceName
659 ? this.cephServiceService.update(serviceSpec)
660 : this.cephServiceService.create(serviceSpec)
664 self.serviceForm.setErrors({ cdSubmitButton: true });
667 this.pageURL === 'services'
668 ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
669 : this.activeModal.close();
675 const snmpVersion = this.serviceForm.getValue('snmp_version');
676 const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
677 if (snmpVersion === 'V3') {
678 this.serviceForm.get('snmp_community').clearValidators();
680 this.serviceForm.get('engine_id').clearValidators();
681 this.serviceForm.get('auth_protocol').clearValidators();
682 this.serviceForm.get('privacy_protocol').clearValidators();
683 this.serviceForm.get('snmp_v3_auth_username').clearValidators();
684 this.serviceForm.get('snmp_v3_auth_password').clearValidators();
686 if (privacyProtocol === null) {
687 this.serviceForm.get('snmp_v3_priv_password').clearValidators();