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 @ViewChild(NgbTypeahead, { static: false })
33 typeahead: NgbTypeahead;
35 @Input() hiddenServices: string[] = [];
37 @Input() editing = false;
39 @Input() serviceName: string;
41 @Input() serviceType: string;
43 serviceForm: CdFormGroup;
46 serviceTypes: string[] = [];
49 labelClick = new Subject<string>();
50 labelFocus = new Subject<string>();
52 services: Array<CephServiceSpec> = [];
56 public actionLabels: ActionLabelsI18n,
57 private cephServiceService: CephServiceService,
58 private formBuilder: CdFormBuilder,
59 private hostService: HostService,
60 private poolService: PoolService,
61 private router: Router,
62 private taskWrapperService: TaskWrapperService,
63 private route: ActivatedRoute,
64 public activeModal: NgbActiveModal
67 this.resource = $localize`service`;
70 messages: new SelectMessages({
71 empty: $localize`There are no hosts.`,
72 filter: $localize`Filter hosts`
79 this.serviceForm = this.formBuilder.group({
81 service_type: [null, [Validators.required]],
85 CdValidators.requiredIf({
88 CdValidators.requiredIf({
91 CdValidators.requiredIf({
94 CdValidators.requiredIf({
95 service_type: 'ingress'
97 CdValidators.composeIf(
103 CdValidators.custom('rgwPattern', (value: string) => {
104 if (_.isEmpty(value)) {
107 return !this.RGW_SVC_ID_PATTERN.test(value);
113 placement: ['hosts'],
117 CdValidators.requiredIf({
124 count: [null, [CdValidators.number(false)]],
130 CdValidators.requiredIf({
131 service_type: 'iscsi',
137 rgw_frontend_port: [null, [CdValidators.number(false)]],
139 trusted_ip_list: [null],
140 api_port: [null, [CdValidators.number(false)]],
144 CdValidators.requiredIf({
145 service_type: 'iscsi',
153 CdValidators.requiredIf({
154 service_type: 'iscsi',
163 CdValidators.requiredIf({
164 service_type: 'ingress',
172 CdValidators.requiredIf({
173 service_type: 'ingress',
178 frontend_port: [null, [CdValidators.number(false)]],
179 monitor_port: [null, [CdValidators.number(false)]],
180 virtual_interface_networks: [null],
181 // RGW, Ingress & iSCSI
186 CdValidators.composeIf(
192 [Validators.required, CdValidators.pemCert()]
194 CdValidators.composeIf(
196 service_type: 'iscsi',
200 [Validators.required, CdValidators.sslCert()]
207 CdValidators.composeIf(
209 service_type: 'iscsi',
213 [Validators.required, CdValidators.sslPrivKey()]
218 snmp_version: [null, [Validators.required]],
223 CdValidators.requiredIf({
224 service_type: 'snmp-gateway',
227 CdValidators.custom('snmpDestinationPattern', (value: string) => {
228 if (_.isEmpty(value)) {
231 return !this.SNMP_DESTINATION_PATTERN.test(value);
239 CdValidators.requiredIf({
240 service_type: 'snmp-gateway',
248 CdValidators.requiredIf({
249 service_type: 'snmp-gateway',
254 privacy_protocol: [null],
258 CdValidators.requiredIf({
259 service_type: 'snmp-gateway',
264 snmp_v3_auth_username: [
267 CdValidators.requiredIf({
268 service_type: 'snmp-gateway',
273 snmp_v3_auth_password: [
276 CdValidators.requiredIf({
277 service_type: 'snmp-gateway',
282 snmp_v3_priv_password: [
285 CdValidators.requiredIf({
286 service_type: 'snmp-gateway',
295 this.action = this.actionLabels.CREATE;
296 if (this.router.url.includes('services/(modal:create')) {
297 this.pageURL = 'services';
298 } else if (this.router.url.includes('services/(modal:edit')) {
300 this.pageURL = 'services';
301 this.route.params.subscribe((params: { type: string; name: string }) => {
302 this.serviceName = params.name;
303 this.serviceType = params.type;
306 this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
307 // Remove service types:
308 // osd - This is deployed a different way.
309 // container - This should only be used in the CLI.
310 this.hiddenServices.push('osd', 'container');
312 this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
314 this.hostService.list('false').subscribe((resp: object[]) => {
315 const options: SelectOption[] = [];
316 _.forEach(resp, (host: object) => {
317 if (_.get(host, 'sources.orchestrator', false)) {
318 const option = new SelectOption(false, _.get(host, 'hostname'), '');
319 options.push(option);
322 this.hosts.options = [...options];
324 this.hostService.getLabels().subscribe((resp: string[]) => {
327 this.poolService.getList().subscribe((resp: Array<object>) => {
330 this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
331 this.services = services.filter((service: any) => service.service_type === 'rgw');
335 this.action = this.actionLabels.EDIT;
336 this.disableForEditing(this.serviceType);
337 this.cephServiceService.list(this.serviceName).subscribe((response: CephServiceSpec[]) => {
338 const formKeys = ['service_type', 'service_id', 'unmanaged'];
339 formKeys.forEach((keys) => {
340 this.serviceForm.get(keys).setValue(response[0][keys]);
342 if (!response[0]['unmanaged']) {
343 const placementKey = Object.keys(response[0]['placement'])[0];
344 let placementValue: string;
345 ['hosts', 'label'].indexOf(placementKey) >= 0
346 ? (placementValue = placementKey)
347 : (placementValue = 'hosts');
348 this.serviceForm.get('placement').setValue(placementValue);
349 this.serviceForm.get('count').setValue(response[0]['placement']['count']);
350 if (response[0]?.placement[placementValue]) {
351 this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
354 switch (this.serviceType) {
356 const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
357 specKeys.forEach((key) => {
358 this.serviceForm.get(key).setValue(response[0].spec[key]);
360 this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
361 if (response[0].spec?.api_secure) {
362 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
363 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
367 this.serviceForm.get('rgw_frontend_port').setValue(response[0].spec?.rgw_frontend_port);
368 this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
369 if (response[0].spec?.ssl) {
372 .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
376 const ingressSpecKeys = [
381 'virtual_interface_networks',
384 ingressSpecKeys.forEach((key) => {
385 this.serviceForm.get(key).setValue(response[0].spec[key]);
387 if (response[0].spec?.ssl) {
388 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
389 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
393 const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
394 snmpCommonSpecKeys.forEach((key) => {
395 this.serviceForm.get(key).setValue(response[0].spec[key]);
397 if (this.serviceForm.getValue('snmp_version') === 'V3') {
398 const snmpV3SpecKeys = [
402 'snmp_v3_auth_username',
403 'snmp_v3_auth_password',
404 'snmp_v3_priv_password'
406 snmpV3SpecKeys.forEach((key) => {
409 key === 'snmp_v3_auth_username' ||
410 key === 'snmp_v3_auth_password' ||
411 key === 'snmp_v3_priv_password'
413 this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
415 this.serviceForm.get(key).setValue(response[0].spec[key]);
421 .get('snmp_community')
422 .setValue(response[0].spec['credentials']['snmp_community']);
430 disableForEditing(serviceType: string) {
431 const disableForEditKeys = ['service_type', 'service_id'];
432 disableForEditKeys.forEach((key) => {
433 this.serviceForm.get(key).disable();
435 switch (serviceType) {
437 this.serviceForm.get('backend_service').disable();
441 searchLabels = (text$: Observable<string>) => {
443 text$.pipe(debounceTime(200), distinctUntilChanged()),
445 this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
449 .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
455 fileUpload(files: FileList, controlName: string) {
456 const file: File = files[0];
457 const reader = new FileReader();
458 reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
459 const control: AbstractControl = this.serviceForm.get(controlName);
460 control.setValue(event.target.result);
461 control.markAsDirty();
462 control.markAsTouched();
463 control.updateValueAndValidity();
465 reader.readAsText(file, 'utf8');
469 const control: AbstractControl = this.serviceForm.get('service_id');
470 const backendService = this.serviceForm.getValue('backend_service');
471 // Set Id as read-only
472 control.reset({ value: backendService, disabled: true });
477 const values: object = this.serviceForm.getRawValue();
478 const serviceType: string = values['service_type'];
479 let taskUrl = `service/${URLVerbs.CREATE}`;
481 taskUrl = `service/${URLVerbs.EDIT}`;
483 const serviceSpec: object = {
484 service_type: serviceType,
486 unmanaged: values['unmanaged']
489 if (serviceType === 'rgw') {
490 const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
491 svcId = svcIdMatch[1];
493 serviceSpec['rgw_realm'] = svcIdMatch[3];
494 serviceSpec['rgw_zone'] = svcIdMatch[4];
497 svcId = values['service_id'];
499 const serviceId: string = svcId;
500 let serviceName: string = serviceType;
501 if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
502 serviceName = `${serviceType}.${serviceId}`;
503 serviceSpec['service_id'] = serviceId;
505 if (!values['unmanaged']) {
506 switch (values['placement']) {
508 if (values['hosts'].length > 0) {
509 serviceSpec['placement']['hosts'] = values['hosts'];
513 serviceSpec['placement']['label'] = values['label'];
516 if (_.isNumber(values['count']) && values['count'] > 0) {
517 serviceSpec['placement']['count'] = values['count'];
519 switch (serviceType) {
521 if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
522 serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
524 serviceSpec['ssl'] = values['ssl'];
526 serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
530 serviceSpec['pool'] = values['pool'];
531 if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
532 serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
534 if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
535 serviceSpec['api_port'] = values['api_port'];
537 serviceSpec['api_user'] = values['api_user'];
538 serviceSpec['api_password'] = values['api_password'];
539 serviceSpec['api_secure'] = values['ssl'];
541 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
542 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
546 serviceSpec['backend_service'] = values['backend_service'];
547 serviceSpec['service_id'] = values['backend_service'];
548 if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
549 serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
551 if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
552 serviceSpec['frontend_port'] = values['frontend_port'];
554 if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
555 serviceSpec['monitor_port'] = values['monitor_port'];
557 serviceSpec['ssl'] = values['ssl'];
559 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
560 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
562 serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
565 serviceSpec['credentials'] = {};
566 serviceSpec['snmp_version'] = values['snmp_version'];
567 serviceSpec['snmp_destination'] = values['snmp_destination'];
568 if (values['snmp_version'] === 'V3') {
569 serviceSpec['engine_id'] = values['engine_id'];
570 serviceSpec['auth_protocol'] = values['auth_protocol'];
571 serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
572 serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
573 if (values['privacy_protocol'] !== null) {
574 serviceSpec['privacy_protocol'] = values['privacy_protocol'];
575 serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
578 serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
584 this.taskWrapperService
585 .wrapTaskAroundCall({
586 task: new FinishedTask(taskUrl, {
587 service_name: serviceName
589 call: this.cephServiceService.create(serviceSpec)
593 self.serviceForm.setErrors({ cdSubmitButton: true });
596 this.pageURL === 'services'
597 ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
598 : this.activeModal.close();
604 const snmpVersion = this.serviceForm.getValue('snmp_version');
605 const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
606 if (snmpVersion === 'V3') {
607 this.serviceForm.get('snmp_community').clearValidators();
609 this.serviceForm.get('engine_id').clearValidators();
610 this.serviceForm.get('auth_protocol').clearValidators();
611 this.serviceForm.get('privacy_protocol').clearValidators();
612 this.serviceForm.get('snmp_v3_auth_username').clearValidators();
613 this.serviceForm.get('snmp_v3_auth_password').clearValidators();
615 if (privacyProtocol === null) {
616 this.serviceForm.get('snmp_v3_priv_password').clearValidators();