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 @ViewChild(NgbTypeahead, { static: false })
32 typeahead: NgbTypeahead;
34 @Input() hiddenServices: string[] = [];
36 @Input() editing = false;
38 @Input() serviceName: string;
40 @Input() serviceType: string;
42 serviceForm: CdFormGroup;
45 serviceTypes: string[] = [];
48 labelClick = new Subject<string>();
49 labelFocus = new Subject<string>();
51 services: Array<CephServiceSpec> = [];
55 public actionLabels: ActionLabelsI18n,
56 private cephServiceService: CephServiceService,
57 private formBuilder: CdFormBuilder,
58 private hostService: HostService,
59 private poolService: PoolService,
60 private router: Router,
61 private taskWrapperService: TaskWrapperService,
62 private route: ActivatedRoute,
63 public activeModal: NgbActiveModal
66 this.resource = $localize`service`;
69 messages: new SelectMessages({
70 empty: $localize`There are no hosts.`,
71 filter: $localize`Filter hosts`
78 this.serviceForm = this.formBuilder.group({
80 service_type: [null, [Validators.required]],
84 CdValidators.requiredIf({
87 CdValidators.requiredIf({
90 CdValidators.requiredIf({
93 CdValidators.requiredIf({
94 service_type: 'ingress'
96 CdValidators.composeIf(
102 CdValidators.custom('rgwPattern', (value: string) => {
103 if (_.isEmpty(value)) {
106 return !this.RGW_SVC_ID_PATTERN.test(value);
112 placement: ['hosts'],
116 CdValidators.requiredIf({
123 count: [null, [CdValidators.number(false)]],
129 CdValidators.requiredIf({
130 service_type: 'iscsi',
136 rgw_frontend_port: [null, [CdValidators.number(false)]],
138 trusted_ip_list: [null],
139 api_port: [null, [CdValidators.number(false)]],
143 CdValidators.requiredIf({
144 service_type: 'iscsi',
152 CdValidators.requiredIf({
153 service_type: 'iscsi',
162 CdValidators.requiredIf({
163 service_type: 'ingress',
171 CdValidators.requiredIf({
172 service_type: 'ingress',
177 frontend_port: [null, [CdValidators.number(false)]],
178 monitor_port: [null, [CdValidators.number(false)]],
179 virtual_interface_networks: [null],
180 // RGW, Ingress & iSCSI
185 CdValidators.composeIf(
191 [Validators.required, CdValidators.pemCert()]
193 CdValidators.composeIf(
195 service_type: 'iscsi',
199 [Validators.required, CdValidators.sslCert()]
206 CdValidators.composeIf(
208 service_type: 'iscsi',
212 [Validators.required, CdValidators.sslPrivKey()]
217 snmp_version: [null, [Validators.required]],
221 CdValidators.requiredIf({
222 service_type: 'snmp-gateway',
230 CdValidators.requiredIf({
231 service_type: 'snmp-gateway',
239 CdValidators.requiredIf({
240 service_type: 'snmp-gateway',
245 privacy_protocol: [null],
249 CdValidators.requiredIf({
250 service_type: 'snmp-gateway',
255 snmp_v3_auth_username: [
258 CdValidators.requiredIf({
259 service_type: 'snmp-gateway',
264 snmp_v3_auth_password: [
267 CdValidators.requiredIf({
268 service_type: 'snmp-gateway',
273 snmp_v3_priv_password: [
276 CdValidators.requiredIf({
277 service_type: 'snmp-gateway',
286 this.action = this.actionLabels.CREATE;
287 if (this.router.url.includes('services/(modal:create')) {
288 this.pageURL = 'services';
289 } else if (this.router.url.includes('services/(modal:edit')) {
291 this.pageURL = 'services';
292 this.route.params.subscribe((params: { type: string; name: string }) => {
293 this.serviceName = params.name;
294 this.serviceType = params.type;
297 this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => {
298 // Remove service types:
299 // osd - This is deployed a different way.
300 // container - This should only be used in the CLI.
301 this.hiddenServices.push('osd', 'container');
303 this.serviceTypes = _.difference(resp, this.hiddenServices).sort();
305 this.hostService.list('false').subscribe((resp: object[]) => {
306 const options: SelectOption[] = [];
307 _.forEach(resp, (host: object) => {
308 if (_.get(host, 'sources.orchestrator', false)) {
309 const option = new SelectOption(false, _.get(host, 'hostname'), '');
310 options.push(option);
313 this.hosts.options = [...options];
315 this.hostService.getLabels().subscribe((resp: string[]) => {
318 this.poolService.getList().subscribe((resp: Array<object>) => {
321 this.cephServiceService.list().subscribe((services: CephServiceSpec[]) => {
322 this.services = services.filter((service: any) => service.service_type === 'rgw');
326 this.action = this.actionLabels.EDIT;
327 this.disableForEditing(this.serviceType);
328 this.cephServiceService.list(this.serviceName).subscribe((response: CephServiceSpec[]) => {
329 const formKeys = ['service_type', 'service_id', 'unmanaged'];
330 formKeys.forEach((keys) => {
331 this.serviceForm.get(keys).setValue(response[0][keys]);
333 if (!response[0]['unmanaged']) {
334 const placementKey = Object.keys(response[0]['placement'])[0];
335 let placementValue: string;
336 ['hosts', 'label'].indexOf(placementKey) >= 0
337 ? (placementValue = placementKey)
338 : (placementValue = 'hosts');
339 this.serviceForm.get('placement').setValue(placementValue);
340 this.serviceForm.get('count').setValue(response[0]['placement']['count']);
341 if (response[0]?.placement[placementValue]) {
342 this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]);
345 switch (this.serviceType) {
347 const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port'];
348 specKeys.forEach((key) => {
349 this.serviceForm.get(key).setValue(response[0].spec[key]);
351 this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure);
352 if (response[0].spec?.api_secure) {
353 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
354 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
358 this.serviceForm.get('rgw_frontend_port').setValue(response[0].spec?.rgw_frontend_port);
359 this.serviceForm.get('ssl').setValue(response[0].spec?.ssl);
360 if (response[0].spec?.ssl) {
363 .setValue(response[0].spec?.rgw_frontend_ssl_certificate);
367 const ingressSpecKeys = [
372 'virtual_interface_networks',
375 ingressSpecKeys.forEach((key) => {
376 this.serviceForm.get(key).setValue(response[0].spec[key]);
378 if (response[0].spec?.ssl) {
379 this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert);
380 this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key);
384 const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination'];
385 snmpCommonSpecKeys.forEach((key) => {
386 this.serviceForm.get(key).setValue(response[0].spec[key]);
388 if (this.serviceForm.getValue('snmp_version') === 'V3') {
389 const snmpV3SpecKeys = [
393 'snmp_v3_auth_username',
394 'snmp_v3_auth_password',
395 'snmp_v3_priv_password'
397 snmpV3SpecKeys.forEach((key) => {
400 key === 'snmp_v3_auth_username' ||
401 key === 'snmp_v3_auth_password' ||
402 key === 'snmp_v3_priv_password'
404 this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]);
406 this.serviceForm.get(key).setValue(response[0].spec[key]);
412 .get('snmp_community')
413 .setValue(response[0].spec['credentials']['snmp_community']);
421 disableForEditing(serviceType: string) {
422 const disableForEditKeys = ['service_type', 'service_id'];
423 disableForEditKeys.forEach((key) => {
424 this.serviceForm.get(key).disable();
426 switch (serviceType) {
428 this.serviceForm.get('backend_service').disable();
432 searchLabels = (text$: Observable<string>) => {
434 text$.pipe(debounceTime(200), distinctUntilChanged()),
436 this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen()))
440 .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1)
446 fileUpload(files: FileList, controlName: string) {
447 const file: File = files[0];
448 const reader = new FileReader();
449 reader.addEventListener('load', (event: ProgressEvent<FileReader>) => {
450 const control: AbstractControl = this.serviceForm.get(controlName);
451 control.setValue(event.target.result);
452 control.markAsDirty();
453 control.markAsTouched();
454 control.updateValueAndValidity();
456 reader.readAsText(file, 'utf8');
460 const control: AbstractControl = this.serviceForm.get('service_id');
461 const backendService = this.serviceForm.getValue('backend_service');
462 // Set Id as read-only
463 control.reset({ value: backendService, disabled: true });
468 const values: object = this.serviceForm.getRawValue();
469 const serviceType: string = values['service_type'];
470 let taskUrl = `service/${URLVerbs.CREATE}`;
472 taskUrl = `service/${URLVerbs.EDIT}`;
474 const serviceSpec: object = {
475 service_type: serviceType,
477 unmanaged: values['unmanaged']
480 if (serviceType === 'rgw') {
481 const svcIdMatch = values['service_id'].match(this.RGW_SVC_ID_PATTERN);
482 svcId = svcIdMatch[1];
484 serviceSpec['rgw_realm'] = svcIdMatch[3];
485 serviceSpec['rgw_zone'] = svcIdMatch[4];
488 svcId = values['service_id'];
490 const serviceId: string = svcId;
491 let serviceName: string = serviceType;
492 if (_.isString(serviceId) && !_.isEmpty(serviceId)) {
493 serviceName = `${serviceType}.${serviceId}`;
494 serviceSpec['service_id'] = serviceId;
496 if (!values['unmanaged']) {
497 switch (values['placement']) {
499 if (values['hosts'].length > 0) {
500 serviceSpec['placement']['hosts'] = values['hosts'];
504 serviceSpec['placement']['label'] = values['label'];
507 if (_.isNumber(values['count']) && values['count'] > 0) {
508 serviceSpec['placement']['count'] = values['count'];
510 switch (serviceType) {
512 if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) {
513 serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port'];
515 serviceSpec['ssl'] = values['ssl'];
517 serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim();
521 serviceSpec['pool'] = values['pool'];
522 if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) {
523 serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim();
525 if (_.isNumber(values['api_port']) && values['api_port'] > 0) {
526 serviceSpec['api_port'] = values['api_port'];
528 serviceSpec['api_user'] = values['api_user'];
529 serviceSpec['api_password'] = values['api_password'];
530 serviceSpec['api_secure'] = values['ssl'];
532 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
533 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
537 serviceSpec['backend_service'] = values['backend_service'];
538 serviceSpec['service_id'] = values['backend_service'];
539 if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) {
540 serviceSpec['virtual_ip'] = values['virtual_ip'].trim();
542 if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) {
543 serviceSpec['frontend_port'] = values['frontend_port'];
545 if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) {
546 serviceSpec['monitor_port'] = values['monitor_port'];
548 serviceSpec['ssl'] = values['ssl'];
550 serviceSpec['ssl_cert'] = values['ssl_cert']?.trim();
551 serviceSpec['ssl_key'] = values['ssl_key']?.trim();
553 serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks'];
556 serviceSpec['credentials'] = {};
557 serviceSpec['snmp_version'] = values['snmp_version'];
558 serviceSpec['snmp_destination'] = values['snmp_destination'];
559 if (values['snmp_version'] === 'V3') {
560 serviceSpec['engine_id'] = values['engine_id'];
561 serviceSpec['auth_protocol'] = values['auth_protocol'];
562 serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username'];
563 serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password'];
564 if (values['privacy_protocol'] !== null) {
565 serviceSpec['privacy_protocol'] = values['privacy_protocol'];
566 serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password'];
569 serviceSpec['credentials']['snmp_community'] = values['snmp_community'];
575 this.taskWrapperService
576 .wrapTaskAroundCall({
577 task: new FinishedTask(taskUrl, {
578 service_name: serviceName
580 call: this.cephServiceService.create(serviceSpec)
584 self.serviceForm.setErrors({ cdSubmitButton: true });
587 this.pageURL === 'services'
588 ? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
589 : this.activeModal.close();
595 const snmpVersion = this.serviceForm.getValue('snmp_version');
596 const privacyProtocol = this.serviceForm.getValue('privacy_protocol');
597 if (snmpVersion === 'V3') {
598 this.serviceForm.get('snmp_community').clearValidators();
600 this.serviceForm.get('engine_id').clearValidators();
601 this.serviceForm.get('auth_protocol').clearValidators();
602 this.serviceForm.get('privacy_protocol').clearValidators();
603 this.serviceForm.get('snmp_v3_auth_username').clearValidators();
604 this.serviceForm.get('snmp_v3_auth_password').clearValidators();
606 if (privacyProtocol === null) {
607 this.serviceForm.get('snmp_v3_priv_password').clearValidators();