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 @ViewChild(NgbTypeahead, { static: false })
34 typeahead: NgbTypeahead;
36 @Input() hiddenServices: string[] = [];
38 @Input() editing = false;
40 @Input() serviceName: string;
42 @Input() serviceType: string;
44 serviceForm: CdFormGroup;
47 serviceTypes: string[] = [];
50 labelClick = new Subject<string>();
51 labelFocus = new Subject<string>();
53 services: Array<CephServiceSpec> = [];
57 public actionLabels: ActionLabelsI18n,
58 private cephServiceService: CephServiceService,
59 private formBuilder: CdFormBuilder,
60 private hostService: HostService,
61 private poolService: PoolService,
62 private router: Router,
63 private taskWrapperService: TaskWrapperService,
64 private route: ActivatedRoute,
65 public activeModal: NgbActiveModal
68 this.resource = $localize`service`;
71 messages: new SelectMessages({
72 empty: $localize`There are no hosts.`,
73 filter: $localize`Filter hosts`
80 this.serviceForm = this.formBuilder.group({
82 service_type: [null, [Validators.required]],
86 CdValidators.requiredIf({
89 CdValidators.requiredIf({
92 CdValidators.requiredIf({
95 CdValidators.requiredIf({
96 service_type: 'ingress'
98 CdValidators.composeIf(
104 CdValidators.custom('rgwPattern', (value: string) => {
105 if (_.isEmpty(value)) {
108 return !this.RGW_SVC_ID_PATTERN.test(value);
114 placement: ['hosts'],
118 CdValidators.requiredIf({
125 count: [null, [CdValidators.number(false)]],
131 CdValidators.requiredIf({
132 service_type: 'iscsi',
138 rgw_frontend_port: [null, [CdValidators.number(false)]],
140 trusted_ip_list: [null],
141 api_port: [null, [CdValidators.number(false)]],
145 CdValidators.requiredIf({
146 service_type: 'iscsi',
154 CdValidators.requiredIf({
155 service_type: 'iscsi',
164 CdValidators.requiredIf({
165 service_type: 'ingress',
173 CdValidators.requiredIf({
174 service_type: 'ingress',
179 frontend_port: [null, [CdValidators.number(false)]],
180 monitor_port: [null, [CdValidators.number(false)]],
181 virtual_interface_networks: [null],
182 // RGW, Ingress & iSCSI
187 CdValidators.composeIf(
193 [Validators.required, CdValidators.pemCert()]
195 CdValidators.composeIf(
197 service_type: 'iscsi',
201 [Validators.required, CdValidators.sslCert()]
208 CdValidators.composeIf(
210 service_type: 'iscsi',
214 [Validators.required, CdValidators.sslPrivKey()]
222 CdValidators.requiredIf({
223 service_type: 'snmp-gateway'
231 CdValidators.requiredIf({
232 service_type: 'snmp-gateway'
234 CdValidators.custom('snmpDestinationPattern', (value: string) => {
235 if (_.isEmpty(value)) {
238 return !this.SNMP_DESTINATION_PATTERN.test(value);
246 CdValidators.requiredIf({
247 service_type: 'snmp-gateway'
249 CdValidators.custom('snmpEngineIdPattern', (value: string) => {
250 if (_.isEmpty(value)) {
253 return !this.SNMP_ENGINE_ID_PATTERN.test(value);
260 CdValidators.requiredIf({
261 service_type: 'snmp-gateway'
265 privacy_protocol: [null],
269 CdValidators.requiredIf({
274 snmp_v3_auth_username: [
277 CdValidators.requiredIf({
278 service_type: 'snmp-gateway'
282 snmp_v3_auth_password: [
285 CdValidators.requiredIf({
286 service_type: 'snmp-gateway'
290 snmp_v3_priv_password: [
293 CdValidators.requiredIf({
294 privacy_protocol: { op: '!empty' }
302 this.action = this.actionLabels.CREATE;
303 if (this.router.url.includes('services/(modal:create')) {
304 this.pageURL = 'services';
305 } else if (this.router.url.includes('services/(modal:edit')) {
307 this.pageURL = 'services';
308 this.route.params.subscribe((params: { type: string; name: string }) => {
309 this.serviceName = params.name;
310 this.serviceType = params.type;
313 this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
314 // Remove service types:
315 // osd - This is deployed a different way.
316 // container - This should only be used in the CLI.
317 this.hiddenServices.push('osd', 'container');
319 this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
321 this.hostService.list('false').subscribe((resp: object[]) => {
322 const options: SelectOption[] = [];
323 _.forEach(resp, (host: object) => {
324 if (_.get(host, 'sources.orchestrator', false)) {
325 const option = new SelectOption(false, _.get(host, 'hostname'), '');
326 options.push(option);
329 this.hosts.options = [...options];
331 this.hostService.getLabels().subscribe((resp: string[]) => {
334 this.poolService.getList().subscribe((resp: Array<object>) => {
337 this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
338 this.services = services.filter((service: any) => service.service_type === 'rgw');
342 this.action = this.actionLabels.EDIT;
343 this.disableForEditing(this.serviceType);
344 this.cephServiceService.list(this.serviceName).subscribe((response: CephServiceSpec[]) => {
345 const formKeys = ['service_type', 'service_id', 'unmanaged'];
346 formKeys.forEach((keys) => {
347 this.serviceForm.get(keys).setValue(response[0][keys]);
349 if (!response[0]['unmanaged']) {
350 const placementKey = Object.keys(response[0]['placement'])[0];
351 let placementValue: string;
352 ['hosts', 'label'].indexOf(placementKey) >= 0
353 ? (placementValue = placementKey)
354 : (placementValue = 'hosts');
355 this.serviceForm.get('placement').setValue(placementValue);
356 this.serviceForm.get('count').setValue(response[0]['placement']['count']);
357 if (response[0]?.placement[placementValue]) {
358 this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
361 switch (this.serviceType) {
363 const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
364 specKeys.forEach((key) => {
365 this.serviceForm.get(key).setValue(response[0].spec[key]);
367 this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
368 if (response[0].spec?.api_secure) {
369 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
370 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
374 this.serviceForm.get('rgw_frontend_port').setValue(response[0].spec?.rgw_frontend_port);
375 this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
376 if (response[0].spec?.ssl) {
379 .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
383 const ingressSpecKeys = [
388 'virtual_interface_networks',
391 ingressSpecKeys.forEach((key) => {
392 this.serviceForm.get(key).setValue(response[0].spec[key]);
394 if (response[0].spec?.ssl) {
395 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
396 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
400 const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
401 snmpCommonSpecKeys.forEach((key) => {
402 this.serviceForm.get(key).setValue(response[0].spec[key]);
404 if (this.serviceForm.getValue('snmp_version') === 'V3') {
405 const snmpV3SpecKeys = [
409 'snmp_v3_auth_username',
410 'snmp_v3_auth_password',
411 'snmp_v3_priv_password'
413 snmpV3SpecKeys.forEach((key) => {
416 key === 'snmp_v3_auth_username' ||
417 key === 'snmp_v3_auth_password' ||
418 key === 'snmp_v3_priv_password'
420 this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
422 this.serviceForm.get(key).setValue(response[0].spec[key]);
428 .get('snmp_community')
429 .setValue(response[0].spec['credentials']['snmp_community']);
437 disableForEditing(serviceType: string) {
438 const disableForEditKeys = ['service_type', 'service_id'];
439 disableForEditKeys.forEach((key) => {
440 this.serviceForm.get(key).disable();
442 switch (serviceType) {
444 this.serviceForm.get('backend_service').disable();
448 searchLabels = (text$: Observable<string>) => {
450 text$.pipe(debounceTime(200), distinctUntilChanged()),
452 this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
456 .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
462 fileUpload(files: FileList, controlName: string) {
463 const file: File = files[0];
464 const reader = new FileReader();
465 reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
466 const control: AbstractControl = this.serviceForm.get(controlName);
467 control.setValue(event.target.result);
468 control.markAsDirty();
469 control.markAsTouched();
470 control.updateValueAndValidity();
472 reader.readAsText(file, 'utf8');
476 const control: AbstractControl = this.serviceForm.get('service_id');
477 const backendService = this.serviceForm.getValue('backend_service');
478 // Set Id as read-only
479 control.reset({ value: backendService, disabled: true });
484 const values: object = this.serviceForm.getRawValue();
485 const serviceType: string = values['service_type'];
486 let taskUrl = `service/${URLVerbs.CREATE}`;
488 taskUrl = `service/${URLVerbs.EDIT}`;
490 const serviceSpec: object = {
491 service_type: serviceType,
493 unmanaged: values['unmanaged']
496 if (serviceType === 'rgw') {
497 const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
498 svcId = svcIdMatch[1];
500 serviceSpec['rgw_realm'] = svcIdMatch[3];
501 serviceSpec['rgw_zone'] = svcIdMatch[4];
504 svcId = values['service_id'];
506 const serviceId: string = svcId;
507 let serviceName: string = serviceType;
508 if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
509 serviceName = `${serviceType}.${serviceId}`;
510 serviceSpec['service_id'] = serviceId;
512 if (!values['unmanaged']) {
513 switch (values['placement']) {
515 if (values['hosts'].length > 0) {
516 serviceSpec['placement']['hosts'] = values['hosts'];
520 serviceSpec['placement']['label'] = values['label'];
523 if (_.isNumber(values['count']) && values['count'] > 0) {
524 serviceSpec['placement']['count'] = values['count'];
526 switch (serviceType) {
528 if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
529 serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
531 serviceSpec['ssl'] = values['ssl'];
533 serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
537 serviceSpec['pool'] = values['pool'];
538 if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
539 serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
541 if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
542 serviceSpec['api_port'] = values['api_port'];
544 serviceSpec['api_user'] = values['api_user'];
545 serviceSpec['api_password'] = values['api_password'];
546 serviceSpec['api_secure'] = values['ssl'];
548 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
549 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
553 serviceSpec['backend_service'] = values['backend_service'];
554 serviceSpec['service_id'] = values['backend_service'];
555 if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
556 serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
558 if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
559 serviceSpec['frontend_port'] = values['frontend_port'];
561 if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
562 serviceSpec['monitor_port'] = values['monitor_port'];
564 serviceSpec['ssl'] = values['ssl'];
566 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
567 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
569 serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
572 serviceSpec['credentials'] = {};
573 serviceSpec['snmp_version'] = values['snmp_version'];
574 serviceSpec['snmp_destination'] = values['snmp_destination'];
575 if (values['snmp_version'] === 'V3') {
576 serviceSpec['engine_id'] = values['engine_id'];
577 serviceSpec['auth_protocol'] = values['auth_protocol'];
578 serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
579 serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
580 if (values['privacy_protocol'] !== null) {
581 serviceSpec['privacy_protocol'] = values['privacy_protocol'];
582 serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
585 serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
591 this.taskWrapperService
592 .wrapTaskAroundCall({
593 task: new FinishedTask(taskUrl, {
594 service_name: serviceName
596 call: this.cephServiceService.create(serviceSpec)
600 self.serviceForm.setErrors({ cdSubmitButton: true });
603 this.pageURL === 'services'
604 ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
605 : this.activeModal.close();
611 const snmpVersion = this.serviceForm.getValue('snmp_version');
612 const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
613 if (snmpVersion === 'V3') {
614 this.serviceForm.get('snmp_community').clearValidators();
616 this.serviceForm.get('engine_id').clearValidators();
617 this.serviceForm.get('auth_protocol').clearValidators();
618 this.serviceForm.get('privacy_protocol').clearValidators();
619 this.serviceForm.get('snmp_v3_auth_username').clearValidators();
620 this.serviceForm.get('snmp_v3_auth_password').clearValidators();
622 if (privacyProtocol === null) {
623 this.serviceForm.get('snmp_v3_priv_password').clearValidators();