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()]
203 CdValidators.composeIf(
205 service_type: 'ingress',
209 [Validators.required, CdValidators.pemCert()]
216 CdValidators.composeIf(
218 service_type: 'iscsi',
222 [Validators.required, CdValidators.sslPrivKey()]
230 CdValidators.requiredIf({
231 service_type: 'snmp-gateway'
239 CdValidators.requiredIf({
240 service_type: 'snmp-gateway'
242 CdValidators.custom('snmpDestinationPattern', (value: string) => {
243 if (_.isEmpty(value)) {
246 return !this.SNMP_DESTINATION_PATTERN.test(value);
254 CdValidators.requiredIf({
255 service_type: 'snmp-gateway'
257 CdValidators.custom('snmpEngineIdPattern', (value: string) => {
258 if (_.isEmpty(value)) {
261 return !this.SNMP_ENGINE_ID_PATTERN.test(value);
268 CdValidators.requiredIf({
269 service_type: 'snmp-gateway'
273 privacy_protocol: [null],
277 CdValidators.requiredIf({
282 snmp_v3_auth_username: [
285 CdValidators.requiredIf({
286 service_type: 'snmp-gateway'
290 snmp_v3_auth_password: [
293 CdValidators.requiredIf({
294 service_type: 'snmp-gateway'
298 snmp_v3_priv_password: [
301 CdValidators.requiredIf({
302 privacy_protocol: { op: '!empty' }
310 this.action = this.actionLabels.CREATE;
311 if (this.router.url.includes('services/(modal:create')) {
312 this.pageURL = 'services';
313 } else if (this.router.url.includes('services/(modal:edit')) {
315 this.pageURL = 'services';
316 this.route.params.subscribe((params: { type: string; name: string }) => {
317 this.serviceName = params.name;
318 this.serviceType = params.type;
321 this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
322 // Remove service types:
323 // osd - This is deployed a different way.
324 // container - This should only be used in the CLI.
325 this.hiddenServices.push('osd', 'container');
327 this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
329 this.hostService.list('false').subscribe((resp: object[]) => {
330 const options: SelectOption[] = [];
331 _.forEach(resp, (host: object) => {
332 if (_.get(host, 'sources.orchestrator', false)) {
333 const option = new SelectOption(false, _.get(host, 'hostname'), '');
334 options.push(option);
337 this.hosts.options = [...options];
339 this.hostService.getLabels().subscribe((resp: string[]) => {
342 this.poolService.getList().subscribe((resp: Array<object>) => {
345 this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
346 this.services = services.filter((service: any) => service.service_type === 'rgw');
350 this.action = this.actionLabels.EDIT;
351 this.disableForEditing(this.serviceType);
352 this.cephServiceService.list(this.serviceName).subscribe((response: CephServiceSpec[]) => {
353 const formKeys = ['service_type', 'service_id', 'unmanaged'];
354 formKeys.forEach((keys) => {
355 this.serviceForm.get(keys).setValue(response[0][keys]);
357 if (!response[0]['unmanaged']) {
358 const placementKey = Object.keys(response[0]['placement'])[0];
359 let placementValue: string;
360 ['hosts', 'label'].indexOf(placementKey) >= 0
361 ? (placementValue = placementKey)
362 : (placementValue = 'hosts');
363 this.serviceForm.get('placement').setValue(placementValue);
364 this.serviceForm.get('count').setValue(response[0]['placement']['count']);
365 if (response[0]?.placement[placementValue]) {
366 this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
369 switch (this.serviceType) {
371 const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
372 specKeys.forEach((key) => {
373 this.serviceForm.get(key).setValue(response[0].spec[key]);
375 this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
376 if (response[0].spec?.api_secure) {
377 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
378 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
382 this.serviceForm.get('rgw_frontend_port').setValue(response[0].spec?.rgw_frontend_port);
383 this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
384 if (response[0].spec?.ssl) {
387 .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
391 const ingressSpecKeys = [
396 'virtual_interface_networks',
399 ingressSpecKeys.forEach((key) => {
400 this.serviceForm.get(key).setValue(response[0].spec[key]);
402 if (response[0].spec?.ssl) {
403 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
404 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
408 const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
409 snmpCommonSpecKeys.forEach((key) => {
410 this.serviceForm.get(key).setValue(response[0].spec[key]);
412 if (this.serviceForm.getValue('snmp_version') === 'V3') {
413 const snmpV3SpecKeys = [
417 'snmp_v3_auth_username',
418 'snmp_v3_auth_password',
419 'snmp_v3_priv_password'
421 snmpV3SpecKeys.forEach((key) => {
424 key === 'snmp_v3_auth_username' ||
425 key === 'snmp_v3_auth_password' ||
426 key === 'snmp_v3_priv_password'
428 this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
430 this.serviceForm.get(key).setValue(response[0].spec[key]);
436 .get('snmp_community')
437 .setValue(response[0].spec['credentials']['snmp_community']);
445 disableForEditing(serviceType: string) {
446 const disableForEditKeys = ['service_type', 'service_id'];
447 disableForEditKeys.forEach((key) => {
448 this.serviceForm.get(key).disable();
450 switch (serviceType) {
452 this.serviceForm.get('backend_service').disable();
456 searchLabels = (text$: Observable<string>) => {
458 text$.pipe(debounceTime(200), distinctUntilChanged()),
460 this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
464 .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
470 fileUpload(files: FileList, controlName: string) {
471 const file: File = files[0];
472 const reader = new FileReader();
473 reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
474 const control: AbstractControl = this.serviceForm.get(controlName);
475 control.setValue(event.target.result);
476 control.markAsDirty();
477 control.markAsTouched();
478 control.updateValueAndValidity();
480 reader.readAsText(file, 'utf8');
484 const control: AbstractControl = this.serviceForm.get('service_id');
485 const backendService = this.serviceForm.getValue('backend_service');
486 // Set Id as read-only
487 control.reset({ value: backendService, disabled: true });
492 const values: object = this.serviceForm.getRawValue();
493 const serviceType: string = values['service_type'];
494 let taskUrl = `service/${URLVerbs.CREATE}`;
496 taskUrl = `service/${URLVerbs.EDIT}`;
498 const serviceSpec: object = {
499 service_type: serviceType,
501 unmanaged: values['unmanaged']
504 if (serviceType === 'rgw') {
505 const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
506 svcId = svcIdMatch[1];
508 serviceSpec['rgw_realm'] = svcIdMatch[3];
509 serviceSpec['rgw_zone'] = svcIdMatch[4];
512 svcId = values['service_id'];
514 const serviceId: string = svcId;
515 let serviceName: string = serviceType;
516 if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
517 serviceName = `${serviceType}.${serviceId}`;
518 serviceSpec['service_id'] = serviceId;
520 if (!values['unmanaged']) {
521 switch (values['placement']) {
523 if (values['hosts'].length > 0) {
524 serviceSpec['placement']['hosts'] = values['hosts'];
528 serviceSpec['placement']['label'] = values['label'];
531 if (_.isNumber(values['count']) && values['count'] > 0) {
532 serviceSpec['placement']['count'] = values['count'];
534 switch (serviceType) {
536 if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
537 serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
539 serviceSpec['ssl'] = values['ssl'];
541 serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
545 serviceSpec['pool'] = values['pool'];
546 if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
547 serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
549 if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
550 serviceSpec['api_port'] = values['api_port'];
552 serviceSpec['api_user'] = values['api_user'];
553 serviceSpec['api_password'] = values['api_password'];
554 serviceSpec['api_secure'] = values['ssl'];
556 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
557 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
561 serviceSpec['backend_service'] = values['backend_service'];
562 serviceSpec['service_id'] = values['backend_service'];
563 if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
564 serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
566 if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
567 serviceSpec['frontend_port'] = values['frontend_port'];
569 if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
570 serviceSpec['monitor_port'] = values['monitor_port'];
572 serviceSpec['ssl'] = values['ssl'];
574 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
575 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
577 serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
580 serviceSpec['credentials'] = {};
581 serviceSpec['snmp_version'] = values['snmp_version'];
582 serviceSpec['snmp_destination'] = values['snmp_destination'];
583 if (values['snmp_version'] === 'V3') {
584 serviceSpec['engine_id'] = values['engine_id'];
585 serviceSpec['auth_protocol'] = values['auth_protocol'];
586 serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
587 serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
588 if (values['privacy_protocol'] !== null) {
589 serviceSpec['privacy_protocol'] = values['privacy_protocol'];
590 serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
593 serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
599 this.taskWrapperService
600 .wrapTaskAroundCall({
601 task: new FinishedTask(taskUrl, {
602 service_name: serviceName
604 call: this.cephServiceService.create(serviceSpec)
608 self.serviceForm.setErrors({ cdSubmitButton: true });
611 this.pageURL === 'services'
612 ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
613 : this.activeModal.close();
619 const snmpVersion = this.serviceForm.getValue('snmp_version');
620 const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
621 if (snmpVersion === 'V3') {
622 this.serviceForm.get('snmp_community').clearValidators();
624 this.serviceForm.get('engine_id').clearValidators();
625 this.serviceForm.get('auth_protocol').clearValidators();
626 this.serviceForm.get('privacy_protocol').clearValidators();
627 this.serviceForm.get('snmp_v3_auth_username').clearValidators();
628 this.serviceForm.get('snmp_v3_auth_password').clearValidators();
630 if (privacyProtocol === null) {
631 this.serviceForm.get('snmp_v3_priv_password').clearValidators();