1 import { Component, OnInit } from '@angular/core';
2 import { FormArray, FormControl, Validators } from '@angular/forms';
3 import { ActivatedRoute, Router } from '@angular/router';
5 import { I18n } from '@ngx-translate/i18n-polyfill';
6 import * as _ from 'lodash';
7 import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
8 import { forkJoin } from 'rxjs';
10 import { IscsiService } from '../../../shared/api/iscsi.service';
11 import { RbdService } from '../../../shared/api/rbd.service';
12 import { SelectMessages } from '../../../shared/components/select/select-messages.model';
13 import { SelectOption } from '../../../shared/components/select/select-option.model';
14 import { ActionLabelsI18n } from '../../../shared/constants/app.constants';
15 import { CdFormGroup } from '../../../shared/forms/cd-form-group';
16 import { CdValidators } from '../../../shared/forms/cd-validators';
17 import { FinishedTask } from '../../../shared/models/finished-task';
18 import { TaskWrapperService } from '../../../shared/services/task-wrapper.service';
19 import { IscsiTargetImageSettingsModalComponent } from '../iscsi-target-image-settings-modal/iscsi-target-image-settings-modal.component';
20 import { IscsiTargetIqnSettingsModalComponent } from '../iscsi-target-iqn-settings-modal/iscsi-target-iqn-settings-modal.component';
23 selector: 'cd-iscsi-target-form',
24 templateUrl: './iscsi-target-form.component.html',
25 styleUrls: ['./iscsi-target-form.component.scss']
27 export class IscsiTargetFormComponent implements OnInit {
28 targetForm: CdFormGroup;
31 target_default_controls: any;
32 disk_default_controls: any;
34 default_backstore: string;
35 supported_rbd_features: any;
36 required_rbd_features: any;
42 imagesSelections: SelectOption[];
43 portalsSelections: SelectOption[] = [];
45 imagesInitiatorSelections: SelectOption[][] = [];
46 groupDiskSelections: SelectOption[][] = [];
47 groupMembersSelections: SelectOption[][] = [];
49 imagesSettings: any = {};
51 portals: new SelectMessages(
52 { noOptions: this.i18n('There are no portals available.') },
55 images: new SelectMessages(
56 { noOptions: this.i18n('There are no images available.') },
59 initiatorImage: new SelectMessages(
62 'There are no images available. Please make sure you add an image to the target.'
67 groupInitiator: new SelectMessages(
70 'There are no initiators available. Please make sure you add an initiator to the target.'
77 IQN_REGEX = /^iqn\.(19|20)\d\d-(0[1-9]|1[0-2])\.\D{2,3}(\.[A-Za-z0-9-]+)+(:[A-Za-z0-9-\.]+)*$/;
78 USER_REGEX = /[\w\.:@_-]{8,64}/;
79 PASSWORD_REGEX = /[\w@\-_\/]{12,16}/;
84 private iscsiService: IscsiService,
85 private modalService: BsModalService,
86 private rbdService: RbdService,
87 private router: Router,
88 private route: ActivatedRoute,
90 private taskWrapper: TaskWrapperService,
91 public actionLabels: ActionLabelsI18n
93 this.resource = this.i18n('target');
97 const promises: any[] = [
98 this.iscsiService.listTargets(),
99 this.rbdService.list(),
100 this.iscsiService.portals(),
101 this.iscsiService.settings()
104 if (this.router.url.startsWith('/block/iscsi/targets/edit')) {
106 this.route.params.subscribe((params: { target_iqn: string }) => {
107 this.target_iqn = decodeURIComponent(params.target_iqn);
108 promises.push(this.iscsiService.getTarget(this.target_iqn));
111 this.action = this.isEdit ? this.actionLabels.EDIT : this.actionLabels.CREATE;
113 forkJoin(promises).subscribe((data: any[]) => {
114 // iscsiService.listTargets
115 const usedImages = _(data[0])
116 .filter((target) => target.target_iqn !== this.target_iqn)
117 .flatMap((target) => target.disks)
118 .map((image) => `${image.pool}/${image.image}`)
121 // iscsiService.settings()
122 this.minimum_gateways = data[3].config.minimum_gateways;
123 this.target_default_controls = data[3].target_default_controls;
124 this.disk_default_controls = data[3].disk_default_controls;
125 this.backstores = data[3].backstores;
126 this.default_backstore = data[3].default_backstore;
127 this.supported_rbd_features = data[3].supported_rbd_features;
128 this.required_rbd_features = data[3].required_rbd_features;
131 this.imagesAll = _(data[1])
132 .flatMap((pool) => pool.value)
134 const imageId = `${image.pool_name}/${image.name}`;
135 if (usedImages.indexOf(imageId) !== -1) {
138 const validBackstores = this.getValidBackstores(image);
139 if (validBackstores.length === 0) {
146 this.imagesSelections = this.imagesAll.map(
147 (image) => new SelectOption(false, `${image.pool_name}/${image.name}`, '')
150 // iscsiService.portals()
151 const portals: SelectOption[] = [];
152 data[2].forEach((portal) => {
153 portal.ip_addresses.forEach((ip) => {
154 portals.push(new SelectOption(false, portal.name + ':' + ip, ''));
157 this.portalsSelections = [...portals];
161 // iscsiService.getTarget()
163 this.resolveModel(data[4]);
169 this.targetForm = new CdFormGroup({
170 target_iqn: new FormControl('iqn.2001-07.com.ceph:' + Date.now(), {
171 validators: [Validators.required, Validators.pattern(this.IQN_REGEX)]
173 target_controls: new FormControl({}),
174 portals: new FormControl([], {
176 CdValidators.custom('minGateways', (value) => {
177 const gateways = _.uniq(value.map((elem) => elem.split(':')[0]));
178 return gateways.length < Math.max(1, this.minimum_gateways);
182 disks: new FormControl([]),
183 initiators: new FormArray([]),
184 groups: new FormArray([]),
185 acl_enabled: new FormControl(false)
190 this.targetForm.patchValue({
191 target_iqn: res.target_iqn,
192 target_controls: res.target_controls,
193 acl_enabled: res.acl_enabled
197 _.forEach(res.portals, (portal) => {
198 const id = `${portal.host}:${portal.ip}`;
201 this.targetForm.patchValue({
206 _.forEach(res.disks, (disk) => {
207 const id = `${disk.pool}/${disk.image}`;
209 this.imagesSettings[id] = {
210 backstore: disk.backstore
212 this.imagesSettings[id][disk.backstore] = disk.controls;
214 this.onImageSelection({ option: { name: id, selected: true } });
216 this.targetForm.patchValue({
220 _.forEach(res.clients, (client) => {
221 const initiator = this.addInitiator();
222 client.luns = _.map(client.luns, (lun) => `${lun.pool}/${lun.image}`);
223 initiator.patchValue(client);
224 // updatedInitiatorSelector()
227 _.forEach(res.groups, (group) => {
228 const fg = this.addGroup();
230 group.disks = _.map(group.disks, (disk) => `${disk.pool}/${disk.image}`);
231 fg.patchValue(group);
232 _.forEach(group.members, (member) => {
233 this.onGroupMemberSelection({ option: new SelectOption(true, member, '') });
238 hasAdvancedSettings(settings: any) {
239 return Object.values(settings).length > 0;
244 return this.targetForm.get('portals') as FormControl;
247 onPortalSelection() {
248 this.portals.setValue(this.portals.value);
251 removePortal(index: number, portal: string) {
252 this.portalsSelections.forEach((value) => {
253 if (value.name === portal) {
254 value.selected = false;
258 this.portals.value.splice(index, 1);
259 this.portals.setValue(this.portals.value);
265 return this.targetForm.get('disks') as FormControl;
268 removeImage(index: number, image: string) {
269 this.imagesSelections.forEach((value) => {
270 if (value.name === image) {
271 value.selected = false;
274 this.disks.value.splice(index, 1);
275 this.removeImageRefs(image);
279 removeImageRefs(name) {
280 this.initiators.controls.forEach((element) => {
281 const newImages = element.value.luns.filter((item) => item !== name);
282 element.get('luns').setValue(newImages);
285 this.groups.controls.forEach((element) => {
286 const newDisks = element.value.disks.filter((item) => item !== name);
287 element.get('disks').setValue(newDisks);
290 _.forEach(this.imagesInitiatorSelections, (selections, i) => {
291 this.imagesInitiatorSelections[i] = selections.filter((item: any) => item.name !== name);
293 _.forEach(this.groupDiskSelections, (selections, i) => {
294 this.groupDiskSelections[i] = selections.filter((item: any) => item.name !== name);
298 getDefaultBackstore(imageId) {
299 let result = this.default_backstore;
300 const image = this.getImageById(imageId);
301 if (!this.validFeatures(image, this.default_backstore)) {
302 this.backstores.forEach((backstore) => {
303 if (backstore !== this.default_backstore) {
304 if (this.validFeatures(image, backstore)) {
313 onImageSelection($event) {
314 const option = $event.option;
316 if (option.selected) {
317 if (!this.imagesSettings[option.name]) {
318 const defaultBackstore = this.getDefaultBackstore(option.name);
319 this.imagesSettings[option.name] = {
320 backstore: defaultBackstore
322 this.imagesSettings[option.name][defaultBackstore] = {};
325 _.forEach(this.imagesInitiatorSelections, (selections, i) => {
326 selections.push(new SelectOption(false, option.name, ''));
327 this.imagesInitiatorSelections[i] = [...selections];
330 _.forEach(this.groupDiskSelections, (selections, i) => {
331 selections.push(new SelectOption(false, option.name, ''));
332 this.groupDiskSelections[i] = [...selections];
335 this.removeImageRefs(option.name);
341 return this.targetForm.get('initiators') as FormArray;
345 const fg = new CdFormGroup({
346 client_iqn: new FormControl('', {
349 CdValidators.custom('notUnique', (client_iqn) => {
350 const flattened = this.initiators.controls.reduce(function(accumulator, currentValue) {
351 return accumulator.concat(currentValue.value.client_iqn);
354 return flattened.indexOf(client_iqn) !== flattened.lastIndexOf(client_iqn);
356 Validators.pattern(this.IQN_REGEX)
359 auth: new CdFormGroup({
360 user: new FormControl(''),
361 password: new FormControl(''),
362 mutual_user: new FormControl(''),
363 mutual_password: new FormControl('')
365 luns: new FormControl([]),
366 cdIsInGroup: new FormControl(false)
369 CdValidators.validateIf(
371 () => fg.getValue('password') || fg.getValue('mutual_user') || fg.getValue('mutual_password'),
372 [Validators.required],
373 [Validators.pattern(this.USER_REGEX)],
374 [fg.get('password'), fg.get('mutual_user'), fg.get('mutual_password')]
377 CdValidators.validateIf(
379 () => fg.getValue('user') || fg.getValue('mutual_user') || fg.getValue('mutual_password'),
380 [Validators.required],
381 [Validators.pattern(this.PASSWORD_REGEX)],
382 [fg.get('user'), fg.get('mutual_user'), fg.get('mutual_password')]
385 CdValidators.validateIf(
386 fg.get('mutual_user'),
387 () => fg.getValue('mutual_password'),
388 [Validators.required],
389 [Validators.pattern(this.USER_REGEX)],
390 [fg.get('user'), fg.get('password'), fg.get('mutual_password')]
393 CdValidators.validateIf(
394 fg.get('mutual_password'),
395 () => fg.getValue('mutual_user'),
396 [Validators.required],
397 [Validators.pattern(this.PASSWORD_REGEX)],
398 [fg.get('user'), fg.get('password'), fg.get('mutual_user')]
401 this.initiators.push(fg);
403 _.forEach(this.groupMembersSelections, (selections, i) => {
404 selections.push(new SelectOption(false, '', ''));
405 this.groupMembersSelections[i] = [...selections];
409 this.targetForm.getValue('disks'),
410 (disk) => new SelectOption(false, disk, '')
412 this.imagesInitiatorSelections.push(disks);
417 removeInitiator(index) {
418 const removed = this.initiators.value[index];
420 this.initiators.removeAt(index);
422 _.forEach(this.groupMembersSelections, (selections, i) => {
423 selections.splice(index, 1);
424 this.groupMembersSelections[i] = [...selections];
427 this.groups.controls.forEach((element) => {
428 const newMembers = element.value.members.filter((item) => item !== removed.client_iqn);
429 element.get('members').setValue(newMembers);
432 this.imagesInitiatorSelections.splice(index, 1);
435 updatedInitiatorSelector() {
436 // Validate all client_iqn
437 this.initiators.controls.forEach((control) => {
438 control.get('client_iqn').updateValueAndValidity({ emitEvent: false });
441 // Update Group Initiator Selector
442 _.forEach(this.groupMembersSelections, (group, group_index) => {
443 _.forEach(group, (elem, index) => {
444 const oldName = elem.name;
445 elem.name = this.initiators.controls[index].value.client_iqn;
447 this.groups.controls.forEach((element) => {
448 const members = element.value.members;
449 const i = members.indexOf(oldName);
452 members[i] = elem.name;
454 element.get('members').setValue(members);
457 this.groupMembersSelections[group_index] = [...this.groupMembersSelections[group_index]];
461 removeInitiatorImage(initiator: any, lun_index: number, initiator_index: string, image: string) {
462 const luns = initiator.getValue('luns');
463 luns.splice(lun_index, 1);
464 initiator.patchValue({ luns: luns });
466 this.imagesInitiatorSelections[initiator_index].forEach((value) => {
467 if (value.name === image) {
468 value.selected = false;
477 return this.targetForm.get('groups') as FormArray;
481 const fg = new CdFormGroup({
482 group_id: new FormControl('', { validators: [Validators.required] }),
483 members: new FormControl([]),
484 disks: new FormControl([])
487 this.groups.push(fg);
490 this.targetForm.getValue('disks'),
491 (disk) => new SelectOption(false, disk, '')
493 this.groupDiskSelections.push(disks);
495 const initiators = _.map(
496 this.initiators.value,
497 (initiator) => new SelectOption(false, initiator.client_iqn, '')
499 this.groupMembersSelections.push(initiators);
505 this.groups.removeAt(index);
506 this.groupDiskSelections.splice(index, 1);
509 onGroupMemberSelection($event) {
510 const option = $event.option;
512 this.initiators.controls.forEach((element) => {
513 if (element.value.client_iqn === option.name) {
514 element.patchValue({ luns: [] });
515 element.get('cdIsInGroup').setValue(option.selected);
520 removeGroupInitiator(group, member_index, group_index) {
521 const name = group.getValue('members')[member_index];
522 group.getValue('members').splice(member_index, 1);
524 this.groupMembersSelections[group_index].forEach((value) => {
525 if (value.name === name) {
526 value.selected = false;
529 this.groupMembersSelections[group_index] = [...this.groupMembersSelections[group_index]];
531 this.onGroupMemberSelection({ option: new SelectOption(false, name, '') });
534 removeGroupDisk(group, disk_index, group_index) {
535 const name = group.getValue('disks')[disk_index];
536 group.getValue('disks').splice(disk_index, 1);
538 this.groupDiskSelections[group_index].forEach((value) => {
539 if (value.name === name) {
540 value.selected = false;
543 this.groupDiskSelections[group_index] = [...this.groupDiskSelections[group_index]];
547 const formValue = _.cloneDeep(this.targetForm.value);
550 target_iqn: this.targetForm.getValue('target_iqn'),
551 target_controls: this.targetForm.getValue('target_controls'),
552 acl_enabled: this.targetForm.getValue('acl_enabled'),
560 formValue.disks.forEach((disk) => {
561 const imageSplit = disk.split('/');
562 const backstore = this.imagesSettings[disk].backstore;
565 image: imageSplit[1],
566 backstore: backstore,
567 controls: this.imagesSettings[disk][backstore]
572 formValue.portals.forEach((portal) => {
573 const portalSplit = portal.split(':');
574 request.portals.push({
575 host: portalSplit[0],
581 if (request.acl_enabled) {
582 formValue.initiators.forEach((initiator) => {
583 if (!initiator.auth.user) {
584 initiator.auth.user = '';
586 if (!initiator.auth.password) {
587 initiator.auth.password = '';
589 if (!initiator.auth.mutual_user) {
590 initiator.auth.mutual_user = '';
592 if (!initiator.auth.mutual_password) {
593 initiator.auth.mutual_password = '';
595 delete initiator.cdIsInGroup;
598 initiator.luns.forEach((lun) => {
599 const imageSplit = lun.split('/');
606 initiator.luns = newLuns;
608 request.clients = formValue.initiators;
612 if (request.acl_enabled) {
613 formValue.groups.forEach((group) => {
615 group.disks.forEach((disk) => {
616 const imageSplit = disk.split('/');
623 group.disks = newDisks;
625 request.groups = formValue.groups;
630 request['new_target_iqn'] = request.target_iqn;
631 request.target_iqn = this.target_iqn;
632 wrapTask = this.taskWrapper.wrapTaskAroundCall({
633 task: new FinishedTask('iscsi/target/edit', {
634 target_iqn: request.target_iqn
636 call: this.iscsiService.updateTarget(this.target_iqn, request)
639 wrapTask = this.taskWrapper.wrapTaskAroundCall({
640 task: new FinishedTask('iscsi/target/create', {
641 target_iqn: request.target_iqn
643 call: this.iscsiService.createTarget(request)
650 this.targetForm.setErrors({ cdSubmitButton: true });
652 () => this.router.navigate(['/block/iscsi/targets'])
656 targetSettingsModal() {
657 const initialState = {
658 target_controls: this.targetForm.get('target_controls'),
659 target_default_controls: this.target_default_controls
662 this.modalRef = this.modalService.show(IscsiTargetIqnSettingsModalComponent, { initialState });
665 imageSettingsModal(image) {
666 const initialState = {
667 imagesSettings: this.imagesSettings,
669 disk_default_controls: this.disk_default_controls,
670 backstores: this.getValidBackstores(this.getImageById(image))
673 this.modalRef = this.modalService.show(IscsiTargetImageSettingsModalComponent, {
678 validFeatures(image, backstore) {
679 const imageFeatures = image.features;
680 const requiredFeatures = this.required_rbd_features[backstore];
681 const supportedFeatures = this.supported_rbd_features[backstore];
682 // tslint:disable-next-line:no-bitwise
683 const validRequiredFeatures = (imageFeatures & requiredFeatures) === requiredFeatures;
684 // tslint:disable-next-line:no-bitwise
685 const validSupportedFeatures = (imageFeatures & supportedFeatures) === imageFeatures;
686 return validRequiredFeatures && validSupportedFeatures;
689 getImageById(imageId) {
690 return this.imagesAll.find((image) => imageId === `${image.pool_name}/${image.name}`);
693 getValidBackstores(image) {
694 return this.backstores.filter((backstore) => this.validFeatures(image, backstore));