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[] = [];
51 labelClick = new Subject<string>();
52 labelFocus = new Subject<string>();
54 services: Array<CephServiceSpec> = [];
58 public actionLabels: ActionLabelsI18n,
59 private cephServiceService: CephServiceService,
60 private formBuilder: CdFormBuilder,
61 private hostService: HostService,
62 private poolService: PoolService,
63 private router: Router,
64 private taskWrapperService: TaskWrapperService,
65 private route: ActivatedRoute,
66 public activeModal: NgbActiveModal
69 this.resource = $localize`service`;
72 messages: new SelectMessages({
73 empty: $localize`There are no hosts.`,
74 filter: $localize`Filter hosts`
81 this.serviceForm = this.formBuilder.group({
83 service_type: [null, [Validators.required]],
87 CdValidators.requiredIf({
90 CdValidators.requiredIf({
93 CdValidators.requiredIf({
96 CdValidators.requiredIf({
97 service_type: 'ingress'
99 CdValidators.composeIf(
105 CdValidators.custom('rgwPattern', (value: string) => {
106 if (_.isEmpty(value)) {
109 return !this.RGW_SVC_ID_PATTERN.test(value);
115 placement: ['hosts'],
119 CdValidators.requiredIf({
126 count: [null, [CdValidators.number(false)]],
132 CdValidators.requiredIf({
133 service_type: 'iscsi',
139 rgw_frontend_port: [null, [CdValidators.number(false)]],
141 trusted_ip_list: [null],
142 api_port: [null, [CdValidators.number(false)]],
146 CdValidators.requiredIf({
147 service_type: 'iscsi',
155 CdValidators.requiredIf({
156 service_type: 'iscsi',
165 CdValidators.requiredIf({
166 service_type: 'ingress',
174 CdValidators.requiredIf({
175 service_type: 'ingress',
183 CdValidators.number(false),
184 CdValidators.requiredIf({
185 service_type: 'ingress',
193 CdValidators.number(false),
194 CdValidators.requiredIf({
195 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;
340 this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
341 // Remove service types:
342 // osd - This is deployed a different way.
343 // container - This should only be used in the CLI.
344 this.hiddenServices.push('osd', 'container');
346 this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
348 this.hostService.list('false').subscribe((resp: object[]) => {
349 const options: SelectOption[] = [];
350 _.forEach(resp, (host: object) => {
351 if (_.get(host, 'sources.orchestrator', false)) {
352 const option = new SelectOption(false, _.get(host, 'hostname'), '');
353 options.push(option);
356 this.hosts.options = [...options];
358 this.hostService.getLabels().subscribe((resp: string[]) => {
361 this.poolService.getList().subscribe((resp: Array<object>) => {
364 this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
365 this.services = services.filter((service: any) =>
366 this.INGRESS_SUPPORTED_SERVICE_TYPES.includes(service.service_type)
371 this.action = this.actionLabels.EDIT;
372 this.disableForEditing(this.serviceType);
373 this.cephServiceService.list(this.serviceName).subscribe((response: CephServiceSpec[]) => {
374 const formKeys = ['service_type', 'service_id', 'unmanaged'];
375 formKeys.forEach((keys) => {
376 this.serviceForm.get(keys).setValue(response[0][keys]);
378 if (!response[0]['unmanaged']) {
379 const placementKey = Object.keys(response[0]['placement'])[0];
380 let placementValue: string;
381 ['hosts', 'label'].indexOf(placementKey) >= 0
382 ? (placementValue = placementKey)
383 : (placementValue = 'hosts');
384 this.serviceForm.get('placement').setValue(placementValue);
385 this.serviceForm.get('count').setValue(response[0]['placement']['count']);
386 if (response[0]?.placement[placementValue]) {
387 this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
390 switch (this.serviceType) {
392 const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
393 specKeys.forEach((key) => {
394 this.serviceForm.get(key).setValue(response[0].spec[key]);
396 this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
397 if (response[0].spec?.api_secure) {
398 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
399 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
403 this.serviceForm.get('rgw_frontend_port').setValue(response[0].spec?.rgw_frontend_port);
404 this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
405 if (response[0].spec?.ssl) {
408 .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
412 const ingressSpecKeys = [
417 'virtual_interface_networks',
420 ingressSpecKeys.forEach((key) => {
421 this.serviceForm.get(key).setValue(response[0].spec[key]);
423 if (response[0].spec?.ssl) {
424 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
425 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
429 const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
430 snmpCommonSpecKeys.forEach((key) => {
431 this.serviceForm.get(key).setValue(response[0].spec[key]);
433 if (this.serviceForm.getValue('snmp_version') === 'V3') {
434 const snmpV3SpecKeys = [
438 'snmp_v3_auth_username',
439 'snmp_v3_auth_password',
440 'snmp_v3_priv_password'
442 snmpV3SpecKeys.forEach((key) => {
445 key === 'snmp_v3_auth_username' ||
446 key === 'snmp_v3_auth_password' ||
447 key === 'snmp_v3_priv_password'
449 this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
451 this.serviceForm.get(key).setValue(response[0].spec[key]);
457 .get('snmp_community')
458 .setValue(response[0].spec['credentials']['snmp_community']);
466 disableForEditing(serviceType: string) {
467 const disableForEditKeys = ['service_type', 'service_id'];
468 disableForEditKeys.forEach((key) => {
469 this.serviceForm.get(key).disable();
471 switch (serviceType) {
473 this.serviceForm.get('backend_service').disable();
477 searchLabels = (text$: Observable<string>) => {
479 text$.pipe(debounceTime(200), distinctUntilChanged()),
481 this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
485 .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
491 fileUpload(files: FileList, controlName: string) {
492 const file: File = files[0];
493 const reader = new FileReader();
494 reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
495 const control: AbstractControl = this.serviceForm.get(controlName);
496 control.setValue(event.target.result);
497 control.markAsDirty();
498 control.markAsTouched();
499 control.updateValueAndValidity();
501 reader.readAsText(file, 'utf8');
505 const control: AbstractControl = this.serviceForm.get('service_id');
506 const backendService = this.serviceForm.getValue('backend_service');
507 // Set Id as read-only
508 control.reset({ value: backendService, disabled: true });
513 const values: object = this.serviceForm.getRawValue();
514 const serviceType: string = values['service_type'];
515 let taskUrl = `service/${URLVerbs.CREATE}`;
517 taskUrl = `service/${URLVerbs.EDIT}`;
519 const serviceSpec: object = {
520 service_type: serviceType,
522 unmanaged: values['unmanaged']
525 if (serviceType === 'rgw') {
526 const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
527 svcId = svcIdMatch[1];
529 serviceSpec['rgw_realm'] = svcIdMatch[3];
530 serviceSpec['rgw_zone'] = svcIdMatch[4];
533 svcId = values['service_id'];
535 const serviceId: string = svcId;
536 let serviceName: string = serviceType;
537 if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
538 serviceName = `${serviceType}.${serviceId}`;
539 serviceSpec['service_id'] = serviceId;
541 if (!values['unmanaged']) {
542 switch (values['placement']) {
544 if (values['hosts'].length > 0) {
545 serviceSpec['placement']['hosts'] = values['hosts'];
549 serviceSpec['placement']['label'] = values['label'];
552 if (_.isNumber(values['count']) && values['count'] > 0) {
553 serviceSpec['placement']['count'] = values['count'];
555 switch (serviceType) {
557 if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
558 serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
560 serviceSpec['ssl'] = values['ssl'];
562 serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
566 serviceSpec['pool'] = values['pool'];
567 if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
568 serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
570 if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
571 serviceSpec['api_port'] = values['api_port'];
573 serviceSpec['api_user'] = values['api_user'];
574 serviceSpec['api_password'] = values['api_password'];
575 serviceSpec['api_secure'] = values['ssl'];
577 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
578 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
582 serviceSpec['backend_service'] = values['backend_service'];
583 serviceSpec['service_id'] = values['backend_service'];
584 if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
585 serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
587 if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
588 serviceSpec['frontend_port'] = values['frontend_port'];
590 if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
591 serviceSpec['monitor_port'] = values['monitor_port'];
593 serviceSpec['ssl'] = values['ssl'];
595 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
596 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
598 serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
601 serviceSpec['credentials'] = {};
602 serviceSpec['snmp_version'] = values['snmp_version'];
603 serviceSpec['snmp_destination'] = values['snmp_destination'];
604 if (values['snmp_version'] === 'V3') {
605 serviceSpec['engine_id'] = values['engine_id'];
606 serviceSpec['auth_protocol'] = values['auth_protocol'];
607 serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
608 serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
609 if (values['privacy_protocol'] !== null) {
610 serviceSpec['privacy_protocol'] = values['privacy_protocol'];
611 serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
614 serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
620 this.taskWrapperService
621 .wrapTaskAroundCall({
622 task: new FinishedTask(taskUrl, {
623 service_name: serviceName
625 call: this.cephServiceService.create(serviceSpec)
629 self.serviceForm.setErrors({ cdSubmitButton: true });
632 this.pageURL === 'services'
633 ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
634 : this.activeModal.close();
640 const snmpVersion = this.serviceForm.getValue('snmp_version');
641 const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
642 if (snmpVersion === 'V3') {
643 this.serviceForm.get('snmp_community').clearValidators();
645 this.serviceForm.get('engine_id').clearValidators();
646 this.serviceForm.get('auth_protocol').clearValidators();
647 this.serviceForm.get('privacy_protocol').clearValidators();
648 this.serviceForm.get('snmp_v3_auth_username').clearValidators();
649 this.serviceForm.get('snmp_v3_auth_password').clearValidators();
651 if (privacyProtocol === null) {
652 this.serviceForm.get('snmp_v3_priv_password').clearValidators();