1 import { HttpParams } from '@angular/common/http';
2 import { Component, Input, OnInit, ViewChild } from '@angular/core';
3 import { AbstractControl, Validators } from '@angular/forms';
4 import { ActivatedRoute, Router } from '@angular/router';
6 import { NgbActiveModal, NgbTypeahead } from '@ng-bootstrap/ng-bootstrap';
7 import _ from 'lodash';
8 import { merge, Observable, Subject } from 'rxjs';
9 import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators';
11 import { CephServiceService } from '~/app/shared/api/ceph-service.service';
12 import { HostService } from '~/app/shared/api/host.service';
13 import { PoolService } from '~/app/shared/api/pool.service';
14 import { SelectMessages } from '~/app/shared/components/select/select-messages.model';
15 import { SelectOption } from '~/app/shared/components/select/select-option.model';
16 import { ActionLabelsI18n, URLVerbs } from '~/app/shared/constants/app.constants';
17 import { CdForm } from '~/app/shared/forms/cd-form';
18 import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
19 import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
20 import { CdValidators } from '~/app/shared/forms/cd-validators';
21 import { FinishedTask } from '~/app/shared/models/finished-task';
22 import { CephServiceSpec } from '~/app/shared/models/service.interface';
23 import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service';
26 selector: 'cd-service-form',
27 templateUrl: './service-form.component.html',
28 styleUrls: ['./service-form.component.scss']
30 export class ServiceFormComponent extends CdForm implements OnInit {
31 readonly RGW_SVC_ID_PATTERN = /^([^.]+)(\.([^.]+)\.([^.]+))?$/;
32 readonly MDS_SVC_ID_PATTERN = /^[a-zA-Z_.-][a-zA-Z0-9_.-]*$/;
33 readonly SNMP_DESTINATION_PATTERN = /^[^\:]+:[0-9]/;
34 readonly SNMP_ENGINE_ID_PATTERN = /^[0-9A-Fa-f]{10,64}/g;
35 readonly INGRESS_SUPPORTED_SERVICE_TYPES = ['rgw', 'nfs'];
36 @ViewChild(NgbTypeahead, { static: false })
37 typeahead: NgbTypeahead;
39 @Input() hiddenServices: string[] = [];
41 @Input() editing = false;
43 @Input() serviceName: string;
45 @Input() serviceType: string;
47 serviceForm: CdFormGroup;
50 serviceTypes: string[] = [];
51 serviceIds: string[] = [];
54 labelClick = new Subject<string>();
55 labelFocus = new Subject<string>();
57 services: Array<CephServiceSpec> = [];
59 serviceList: CephServiceSpec[];
62 public actionLabels: ActionLabelsI18n,
63 private cephServiceService: CephServiceService,
64 private formBuilder: CdFormBuilder,
65 private hostService: HostService,
66 private poolService: PoolService,
67 private router: Router,
68 private taskWrapperService: TaskWrapperService,
69 private route: ActivatedRoute,
70 public activeModal: NgbActiveModal
73 this.resource = $localize`service`;
76 messages: new SelectMessages({
77 empty: $localize`There are no hosts.`,
78 filter: $localize`Filter hosts`
85 this.serviceForm = this.formBuilder.group({
87 service_type: [null, [Validators.required]],
91 CdValidators.composeIf(
97 CdValidators.custom('mdsPattern', (value: string) => {
98 if (_.isEmpty(value)) {
101 return !this.MDS_SVC_ID_PATTERN.test(value);
105 CdValidators.requiredIf({
108 CdValidators.requiredIf({
109 service_type: 'iscsi'
111 CdValidators.requiredIf({
112 service_type: 'ingress'
114 CdValidators.composeIf(
120 CdValidators.custom('rgwPattern', (value: string) => {
121 if (_.isEmpty(value)) {
124 return !this.RGW_SVC_ID_PATTERN.test(value);
128 CdValidators.custom('uniqueName', (service_id: string) => {
129 return this.serviceIds && this.serviceIds.includes(service_id);
133 placement: ['hosts'],
137 CdValidators.requiredIf({
144 count: [null, [CdValidators.number(false)]],
150 CdValidators.requiredIf({
151 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
355 .list(new HttpParams({ fromObject: { limit: -1, offset: 0 } }))
356 .observable.subscribe((services: CephServiceSpec[]) => {
357 this.serviceList = services;
358 this.services = services.filter((service: any) =>
359 this.INGRESS_SUPPORTED_SERVICE_TYPES.includes(service.service_type)
363 this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
364 // Remove service types:
365 // osd - This is deployed a different way.
366 // container - This should only be used in the CLI.
367 this.hiddenServices.push('osd', 'container');
369 this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
371 this.hostService.list('false').subscribe((resp: object[]) => {
372 const options: SelectOption[] = [];
373 _.forEach(resp, (host: object) => {
374 if (_.get(host, 'sources.orchestrator', false)) {
375 const option = new SelectOption(false, _.get(host, 'hostname'), '');
376 options.push(option);
379 this.hosts.options = [...options];
381 this.hostService.getLabels().subscribe((resp: string[]) => {
384 this.poolService.getList().subscribe((resp: Array<object>) => {
389 this.action = this.actionLabels.EDIT;
390 this.disableForEditing(this.serviceType);
391 this.cephServiceService
392 .list(new HttpParams({ fromObject: { limit: -1, offset: 0 } }), this.serviceName)
393 .observable.subscribe((response: CephServiceSpec[]) => {
394 const formKeys = ['service_type', 'service_id', 'unmanaged'];
395 formKeys.forEach((keys) => {
396 this.serviceForm.get(keys).setValue(response[0][keys]);
398 if (!response[0]['unmanaged']) {
399 const placementKey = Object.keys(response[0]['placement'])[0];
400 let placementValue: string;
401 ['hosts', 'label'].indexOf(placementKey) >= 0
402 ? (placementValue = placementKey)
403 : (placementValue = 'hosts');
404 this.serviceForm.get('placement').setValue(placementValue);
405 this.serviceForm.get('count').setValue(response[0]['placement']['count']);
406 if (response[0]?.placement[placementValue]) {
407 this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
410 switch (this.serviceType) {
412 const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
413 specKeys.forEach((key) => {
414 this.serviceForm.get(key).setValue(response[0].spec[key]);
416 this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
417 if (response[0].spec?.api_secure) {
418 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
419 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
424 .get('rgw_frontend_port')
425 .setValue(response[0].spec?.rgw_frontend_port);
426 this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
427 if (response[0].spec?.ssl) {
430 .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
434 const ingressSpecKeys = [
439 'virtual_interface_networks',
442 ingressSpecKeys.forEach((key) => {
443 this.serviceForm.get(key).setValue(response[0].spec[key]);
445 if (response[0].spec?.ssl) {
446 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
447 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
451 const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
452 snmpCommonSpecKeys.forEach((key) => {
453 this.serviceForm.get(key).setValue(response[0].spec[key]);
455 if (this.serviceForm.getValue('snmp_version') === 'V3') {
456 const snmpV3SpecKeys = [
460 'snmp_v3_auth_username',
461 'snmp_v3_auth_password',
462 'snmp_v3_priv_password'
464 snmpV3SpecKeys.forEach((key) => {
467 key === 'snmp_v3_auth_username' ||
468 key === 'snmp_v3_auth_password' ||
469 key === 'snmp_v3_priv_password'
471 this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
473 this.serviceForm.get(key).setValue(response[0].spec[key]);
479 .get('snmp_community')
480 .setValue(response[0].spec['credentials']['snmp_community']);
488 getServiceIds(selectedServiceType: string) {
489 this.serviceIds = this.serviceList
490 ?.filter((service) => service['service_type'] === selectedServiceType)
491 .map((service) => service['service_id']);
494 disableForEditing(serviceType: string) {
495 const disableForEditKeys = ['service_type', 'service_id'];
496 disableForEditKeys.forEach((key) => {
497 this.serviceForm.get(key).disable();
499 switch (serviceType) {
501 this.serviceForm.get('backend_service').disable();
505 searchLabels = (text$: Observable<string>) => {
507 text$.pipe(debounceTime(200), distinctUntilChanged()),
509 this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
513 .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
519 fileUpload(files: FileList, controlName: string) {
520 const file: File = files[0];
521 const reader = new FileReader();
522 reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
523 const control: AbstractControl = this.serviceForm.get(controlName);
524 control.setValue(event.target.result);
525 control.markAsDirty();
526 control.markAsTouched();
527 control.updateValueAndValidity();
529 reader.readAsText(file, 'utf8');
533 const control: AbstractControl = this.serviceForm.get('service_id');
534 const backendService = this.serviceForm.getValue('backend_service');
535 // Set Id as read-only
536 control.reset({ value: backendService, disabled: true });
541 const values: object = this.serviceForm.getRawValue();
542 const serviceType: string = values['service_type'];
543 let taskUrl = `service/${URLVerbs.CREATE}`;
545 taskUrl = `service/${URLVerbs.EDIT}`;
547 const serviceSpec: object = {
548 service_type: serviceType,
550 unmanaged: values['unmanaged']
553 if (serviceType === 'rgw') {
554 const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
555 svcId = svcIdMatch[1];
557 serviceSpec['rgw_realm'] = svcIdMatch[3];
558 serviceSpec['rgw_zone'] = svcIdMatch[4];
561 svcId = values['service_id'];
563 const serviceId: string = svcId;
564 let serviceName: string = serviceType;
565 if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
566 serviceName = `${serviceType}.${serviceId}`;
567 serviceSpec['service_id'] = serviceId;
570 // These services has some fields to be
571 // filled out even if unmanaged is true
572 switch (serviceType) {
574 serviceSpec['backend_service'] = values['backend_service'];
575 serviceSpec['service_id'] = values['backend_service'];
576 if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
577 serviceSpec['frontend_port'] = values['frontend_port'];
579 if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
580 serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
582 if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
583 serviceSpec['monitor_port'] = values['monitor_port'];
588 serviceSpec['pool'] = values['pool'];
592 serviceSpec['credentials'] = {};
593 serviceSpec['snmp_version'] = values['snmp_version'];
594 serviceSpec['snmp_destination'] = values['snmp_destination'];
595 if (values['snmp_version'] === 'V3') {
596 serviceSpec['engine_id'] = values['engine_id'];
597 serviceSpec['auth_protocol'] = values['auth_protocol'];
598 serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
599 serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
600 if (values['privacy_protocol'] !== null) {
601 serviceSpec['privacy_protocol'] = values['privacy_protocol'];
602 serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
605 serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
610 if (!values['unmanaged']) {
611 switch (values['placement']) {
613 if (values['hosts'].length > 0) {
614 serviceSpec['placement']['hosts'] = values['hosts'];
618 serviceSpec['placement']['label'] = values['label'];
621 if (_.isNumber(values['count']) && values['count'] > 0) {
622 serviceSpec['placement']['count'] = values['count'];
624 switch (serviceType) {
626 if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
627 serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
629 serviceSpec['ssl'] = values['ssl'];
631 serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
635 if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
636 serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
638 if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
639 serviceSpec['api_port'] = values['api_port'];
641 serviceSpec['api_user'] = values['api_user'];
642 serviceSpec['api_password'] = values['api_password'];
643 serviceSpec['api_secure'] = values['ssl'];
645 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
646 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
650 serviceSpec['ssl'] = values['ssl'];
652 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
653 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
655 serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
660 this.taskWrapperService
661 .wrapTaskAroundCall({
662 task: new FinishedTask(taskUrl, {
663 service_name: serviceName
666 ? this.cephServiceService.update(serviceSpec)
667 : this.cephServiceService.create(serviceSpec)
671 self.serviceForm.setErrors({ cdSubmitButton: true });
674 this.pageURL === 'services'
675 ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
676 : this.activeModal.close();
682 const snmpVersion = this.serviceForm.getValue('snmp_version');
683 const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
684 if (snmpVersion === 'V3') {
685 this.serviceForm.get('snmp_community').clearValidators();
687 this.serviceForm.get('engine_id').clearValidators();
688 this.serviceForm.get('auth_protocol').clearValidators();
689 this.serviceForm.get('privacy_protocol').clearValidators();
690 this.serviceForm.get('snmp_v3_auth_username').clearValidators();
691 this.serviceForm.get('snmp_v3_auth_password').clearValidators();
693 if (privacyProtocol === null) {
694 this.serviceForm.get('snmp_v3_priv_password').clearValidators();