Fix Bug 2148: VDU Id issue & Multivdu Count Index Error in VM Action
[osm/NG-UI.git] / src / app / utilities / vm-migration / VmMigrationComponent.ts
1 /*
2  Copyright 2020 TATA ELXSI
3
4  Licensed under the Apache License, Version 2.0 (the 'License');
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15
16  Author: SANDHYA JS (sandhya.j@tataelxsi.co.in)
17 */
18 /**
19  * @file Vm Migration Component
20  */
21 import { HttpHeaders } from '@angular/common/http';
22 import { Component, Injector, Input, OnInit } from '@angular/core';
23 import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
24 import { Router } from '@angular/router';
25 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
26 import { APIURLHEADER, ERRORDATA, MODALCLOSERESPONSEDATA, URLPARAMS } from 'CommonModel';
27 import { environment } from 'environment';
28 import { VMMIGRATION } from 'NSInstanceModel';
29 import { RestService } from 'RestService';
30 import { SharedService } from 'SharedService';
31 import { isNullOrUndefined } from 'util';
32 import { VDUR, VNFInstanceDetails } from 'VNFInstanceModel';
33
34 /**
35  * Creating component
36  * @Component takes VmMigrationComponent.html as template url
37  */
38 @Component({
39     selector: 'app-vm-migration',
40     templateUrl: './VmMigrationComponent.html',
41     styleUrls: ['./VmMigrationComponent.scss']
42 })
43 export class VmMigrationComponent implements OnInit {
44     /** To inject services @public */
45     public injector: Injector;
46     /** Instance for active modal service @public */
47     public activeModal: NgbActiveModal;
48     /** Check the loading results @public */
49     public isLoadingResults: Boolean = false;
50     /** Give the message for the loading @public */
51     public message: string = 'PLEASEWAIT';
52     /** FormGroup instance added to the form @ html @public */
53     public migrationForm: FormGroup;
54     /** Items for the vdu-Id and count-index @public */
55     public vdu: {}[];
56     /** Selected VNFInstanceId @public */
57     public selectedvnfId: string = '';
58     /** Array holds VNFR Data filtered with nsr ID @public */
59     public nsIdFilteredData: {}[] = [];
60     /** Items for the member types @public */
61     public memberTypes: {}[];
62     /** Contains MemberVNFIndex values @public */
63     public memberVnfIndex: {}[] = [];
64     /** Contains vnfInstanceId of the selected MemberVnfIndex  @public */
65     public instanceId: string;
66     /** Form valid on submit trigger @public */
67     public submitted: boolean = false;
68      /** Contains vduId @public */
69     public vduId: {};
70     /** Items for countIndex @public */
71     public countIndex: {}[];
72     /** Input contains component objects @private */
73     @Input() private params: URLPARAMS;
74     /** FormBuilder instance added to the formBuilder @private */
75     private formBuilder: FormBuilder;
76     /** Instance of the rest service @private */
77     private restService: RestService;
78     /** Controls the header form @private */
79     private headers: HttpHeaders;
80     /** Contains all methods related to shared @private */
81     private sharedService: SharedService;
82     /** Holds the instance of AuthService class of type AuthService @private */
83     private router: Router;
84     constructor(injector: Injector) {
85         this.injector = injector;
86         this.restService = this.injector.get(RestService);
87         this.activeModal = this.injector.get(NgbActiveModal);
88         this.formBuilder = this.injector.get(FormBuilder);
89         this.sharedService = this.injector.get(SharedService);
90         this.router = this.injector.get(Router);
91     }
92     /** convenience getter for easy access to form fields */
93     get f(): FormGroup['controls'] { return this.migrationForm.controls; }
94     /**
95      * Lifecyle Hooks the trigger before component is instantiate
96      */
97     public ngOnInit(): void {
98         this.initializeForm();
99         this.getMemberVnfIndex();
100         this.headers = new HttpHeaders({
101             'Content-Type': 'application/json',
102             Accept: 'application/json',
103             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
104         });
105     }
106     /** Initialize Migration Forms @public */
107     public initializeForm(): void {
108         this.migrationForm = this.formBuilder.group({
109             memberVnfIndex: [null, [Validators.required]],
110             vduId: [null],
111             countIndex: [null],
112             migrateToHost: [null]
113         });
114     }
115
116     /** Getting MemberVnfIndex using NSDescriptor API @public */
117     public getMemberVnfIndex(): void {
118         const vnfInstanceData: {}[] = [];
119         this.isLoadingResults = true;
120         this.restService.getResource(environment.VNFINSTANCES_URL).subscribe((vnfInstancesData: VNFInstanceDetails[]): void => {
121             vnfInstancesData.forEach((vnfData: VNFInstanceDetails): void => {
122                 const vnfDataObj: {} =
123                 {
124                     VNFD: vnfData['vnfd-ref'],
125                     VNFInstanceId: vnfData._id,
126                     MemberIndex: vnfData['member-vnf-index-ref'],
127                     NS: vnfData['nsr-id-ref']
128                 };
129                 vnfInstanceData.push(vnfDataObj);
130             });
131             const nsId: string = 'NS';
132             this.nsIdFilteredData = vnfInstanceData.filter((vnfdData: {}[]): boolean => vnfdData[nsId] === this.params.id);
133             this.nsIdFilteredData.forEach((resVNF: {}[]): void => {
134                 const memberIndex: string = 'MemberIndex';
135                 const vnfinstanceID: string = 'VNFInstanceId';
136                 const assignMemberIndex: {} = {
137                     id: resVNF[memberIndex],
138                     vnfinstanceId: resVNF[vnfinstanceID]
139                 };
140                 this.memberVnfIndex.push(assignMemberIndex);
141             });
142             this.memberTypes = this.memberVnfIndex;
143             this.isLoadingResults = false;
144         }, (error: ERRORDATA): void => {
145             this.restService.handleError(error, 'get');
146             this.isLoadingResults = false;
147         });
148     }
149
150     /** Getting vdu-id & count-index from VNFInstance API */
151     public getVdu(id: string): void {
152         this.vdu = [];
153         const vnfInstanceData: {}[] = [];
154         this.instanceId = id;
155         this.getFormControl('vduId').setValue(null);
156         this.getFormControl('countIndex').setValue(null);
157         if (!isNullOrUndefined(id)) {
158             this.restService.getResource(environment.VNFINSTANCES_URL + '/' + id).
159                 subscribe((vnfInstanceDetail: VNFInstanceDetails[]): void => {
160                     this.selectedvnfId = vnfInstanceDetail['vnfd-ref'];
161                     const VDU: string = 'vdur';
162                     if (vnfInstanceDetail[VDU] !== undefined) {
163                         vnfInstanceDetail[VDU].forEach((vdu: VDUR): void => {
164                             const vnfInstanceDataObj: {} =
165                             {
166                                 'count-index': vdu['count-index'],
167                                 VDU: vdu['vdu-id-ref']
168
169                             };
170                             vnfInstanceData.push(vnfInstanceDataObj);
171                         });
172                         this.vdu = vnfInstanceData;
173                         const vduName: string = 'VDU';
174                         this.vduId = this.vdu.filter((vdu: {}, index: number, self: {}[]): {} =>
175                             index === self.findIndex((t: {}): {} => (
176                                 t[vduName] === vdu[vduName]
177                             ))
178                         );
179                     }
180                 }, (error: ERRORDATA): void => {
181                     this.restService.handleError(error, 'get');
182                     this.isLoadingResults = false;
183                 });
184         }
185     }
186
187     /** Getting count-index by filtering id  */
188     public getCountIndex(id: string): void {
189         const VDU: string = 'VDU';
190         this.countIndex = this.vdu.filter((vnfdData: {}[]): boolean => vnfdData[VDU] === id);
191     }
192
193     /** Trigger VM Migration on submit */
194     public triggerMigration(): void {
195         this.submitted = true;
196         this.sharedService.cleanForm(this.migrationForm);
197         if (this.migrationForm.invalid) { return; } // Proceed, onces form is valid
198         const migrationPayload: VMMIGRATION = {
199             lcmOperationType: 'migrate',
200             vnfInstanceId: this.instanceId
201         };
202         if (!isNullOrUndefined(this.migrationForm.value.migrateToHost)) {
203             migrationPayload.migrateToHost = this.migrationForm.value.migrateToHost;
204         }
205         if (!isNullOrUndefined(this.migrationForm.value.vduId) && !isNullOrUndefined(this.migrationForm.value.countIndex)) {
206             migrationPayload.vdu = {
207                 vduId: this.migrationForm.value.vduId,
208                 vduCountIndex: this.migrationForm.value.countIndex
209             };
210         } else if (!isNullOrUndefined(this.migrationForm.value.vduId)) {
211             migrationPayload.vdu = {
212                 vduId: this.migrationForm.value.vduId
213             };
214         } else if (!isNullOrUndefined(this.migrationForm.value.countIndex)) {
215             migrationPayload.vdu = {
216                 vduCountIndex: this.migrationForm.value.countIndex
217             };
218         }
219         this.migrationInitialization(migrationPayload);
220
221     }
222
223     /** Initialize the Vm Migration operation @public */
224     public migrationInitialization(migrationPayload: object): void {
225         this.isLoadingResults = true;
226         const apiURLHeader: APIURLHEADER = {
227             url: environment.NSDINSTANCES_URL + '/' + this.params.id + '/migrate',
228             httpOptions: { headers: this.headers }
229         };
230         const modalData: MODALCLOSERESPONSEDATA = {
231             message: 'Done'
232         };
233         this.restService.postResource(apiURLHeader, migrationPayload).subscribe((result: {}): void => {
234             this.activeModal.close(modalData);
235             this.router.navigate(['/instances/ns/history-operations/' + this.params.id]).catch();
236         }, (error: ERRORDATA): void => {
237             this.restService.handleError(error, 'post');
238             this.isLoadingResults = false;
239         });
240     }
241
242     /** Used to get the AbstractControl of controlName passed @private */
243     private getFormControl(controlName: string): AbstractControl {
244         return this.migrationForm.controls[controlName];
245     }
246 }