Angular upgrade
[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, isNullOrUndefined } from 'SharedService';
31 import { InstanceData, VDUR, VNFInstanceDetails } from 'VNFInstanceModel';
32
33 /**
34  * Creating component
35  * @Component takes VmMigrationComponent.html as template url
36  */
37 @Component({
38     selector: 'app-vm-migration',
39     templateUrl: './VmMigrationComponent.html',
40     styleUrls: ['./VmMigrationComponent.scss']
41 })
42 export class VmMigrationComponent implements OnInit {
43     /** To inject services @public */
44     public injector: Injector;
45     /** Instance for active modal service @public */
46     public activeModal: NgbActiveModal;
47     /** Check the loading results @public */
48     public isLoadingResults: Boolean = false;
49     /** Give the message for the loading @public */
50     public message: string = 'PLEASEWAIT';
51     /** FormGroup instance added to the form @ html @public */
52     public migrationForm: FormGroup;
53     /** Items for the vdu-Id and count-index @public */
54     public vdu: {}[];
55     /** Selected VNFInstanceId @public */
56     public selectedvnfId: string = '';
57     /** Array holds VNFR Data filtered with nsr ID @public */
58     public nsIdFilteredData: {}[] = [];
59     /** Items for the member types @public */
60     public memberTypes: {}[];
61     /** Contains MemberVNFIndex values @public */
62     public memberVnfIndex: {}[] = [];
63     /** Contains vnfInstanceId of the selected MemberVnfIndex  @public */
64     public instanceId: string;
65     /** Form valid on submit trigger @public */
66     public submitted: boolean = false;
67     /** Contains vduId @public */
68     public vduId: {};
69     /** Items for countIndex @public */
70     public countIndex: {}[];
71     /** Input contains component objects @private */
72     @Input() private params: URLPARAMS;
73     /** FormBuilder instance added to the formBuilder @private */
74     private formBuilder: FormBuilder;
75     /** Instance of the rest service @private */
76     private restService: RestService;
77     /** Controls the header form @private */
78     private headers: HttpHeaders;
79     /** Contains all methods related to shared @private */
80     private sharedService: SharedService;
81     /** Holds the instance of AuthService class of type AuthService @private */
82     private router: Router;
83     constructor(injector: Injector) {
84         this.injector = injector;
85         this.restService = this.injector.get(RestService);
86         this.activeModal = this.injector.get(NgbActiveModal);
87         this.formBuilder = this.injector.get(FormBuilder);
88         this.sharedService = this.injector.get(SharedService);
89         this.router = this.injector.get(Router);
90     }
91     /** convenience getter for easy access to form fields */
92     get f(): FormGroup['controls'] { return this.migrationForm.controls; }
93     /**
94      * Lifecyle Hooks the trigger before component is instantiate
95      */
96     public ngOnInit(): void {
97         this.initializeForm();
98         this.getMemberVnfIndex();
99         this.headers = new HttpHeaders({
100             'Content-Type': 'application/json',
101             Accept: 'application/json',
102             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
103         });
104     }
105     /** Initialize Migration Forms @public */
106     public initializeForm(): void {
107         this.migrationForm = this.formBuilder.group({
108             memberVnfIndex: [null, [Validators.required]],
109             vduId: [null],
110             countIndex: [null],
111             migrateToHost: [null]
112         });
113     }
114
115     /** Getting MemberVnfIndex using NSDescriptor API @public */
116     public getMemberVnfIndex(): void {
117         this.isLoadingResults = true;
118         const vnfInstanceData: {}[] = [];
119         this.restService.getResource(environment.VNFINSTANCES_URL).subscribe((vnfInstancesData: VNFInstanceDetails[]): void => {
120             vnfInstancesData.forEach((vnfData: VNFInstanceDetails): void => {
121                 const vnfdRef: string = 'vnfd-ref';
122                 const memberIndex: string = 'member-vnf-index-ref';
123                 const nsrId: string = 'nsr-id-ref';
124                 const vnfDataObj: {} =
125                 {
126                     // eslint-disable-next-line security/detect-object-injection
127                     VNFD: vnfData[vnfdRef],
128                     VNFInstanceId: vnfData._id,
129                     // eslint-disable-next-line security/detect-object-injection
130                     MemberIndex: vnfData[memberIndex],
131                     // eslint-disable-next-line security/detect-object-injection
132                     NS: vnfData[nsrId]
133                 };
134                 vnfInstanceData.push(vnfDataObj);
135             });
136             const nsId: string = 'NS';
137             // eslint-disable-next-line security/detect-object-injection
138             this.nsIdFilteredData = vnfInstanceData.filter((vnfdData: {}[]): boolean => vnfdData[nsId] === this.params.id);
139             this.nsIdFilteredData.forEach((resVNF: InstanceData): void => {
140                 const assignMemberIndex: {} = {
141                     id: resVNF.MemberIndex,
142                     vnfinstanceId: resVNF.VNFInstanceId
143                 };
144                 this.memberVnfIndex.push(assignMemberIndex);
145             });
146             this.memberTypes = this.memberVnfIndex;
147             this.isLoadingResults = false;
148         }, (error: ERRORDATA): void => {
149             this.restService.handleError(error, 'get');
150             this.isLoadingResults = false;
151         });
152     }
153
154     /** Getting vdu-id & count-index from VNFInstance API */
155     public getVdu(id: string): void {
156         this.vdu = [];
157         const vnfInstanceData: {}[] = [];
158         this.instanceId = id;
159         this.getFormControl('vduId').setValue(null);
160         this.getFormControl('countIndex').setValue(null);
161         if (!isNullOrUndefined(id)) {
162             this.restService.getResource(environment.VNFINSTANCES_URL + '/' + id).
163                 subscribe((vnfInstanceDetail: VNFInstanceDetails[]): void => {
164                     this.selectedvnfId = vnfInstanceDetail['vnfd-ref'];
165                     const VDU: string = 'vdur';
166                     // eslint-disable-next-line security/detect-object-injection
167                     if (vnfInstanceDetail[VDU] !== undefined) {
168                         // eslint-disable-next-line security/detect-object-injection
169                         vnfInstanceDetail[VDU].forEach((vdu: VDUR): void => {
170                             const vnfInstanceDataObj: {} =
171                             {
172                                 'count-index': vdu['count-index'],
173                                 VDU: vdu['vdu-id-ref']
174                             };
175                             vnfInstanceData.push(vnfInstanceDataObj);
176                         });
177                         this.vdu = vnfInstanceData;
178                         const vduName: string = 'VDU';
179                         this.vduId = this.vdu.filter((vdu: {}, index: number, self: {}[]): {} =>
180                             index === self.findIndex((t: {}): {} => (
181                                 // eslint-disable-next-line security/detect-object-injection
182                                 t[vduName] === vdu[vduName]
183                             ))
184                         );
185                     }
186                 }, (error: ERRORDATA): void => {
187                     this.restService.handleError(error, 'get');
188                     this.isLoadingResults = false;
189                 });
190         }
191     }
192
193     /** Getting count-index by filtering id  */
194     public getCountIndex(id: string): void {
195         const VDU: string = 'VDU';
196         // eslint-disable-next-line security/detect-object-injection
197         this.countIndex = this.vdu.filter((vnfdData: {}[]): boolean => vnfdData[VDU] === id);
198     }
199
200     /** Trigger VM Migration on submit */
201     public triggerMigration(): void {
202         this.submitted = true;
203         this.sharedService.cleanForm(this.migrationForm);
204         if (this.migrationForm.invalid) { return; } // Proceed, onces form is valid
205         const migrationPayload: VMMIGRATION = {
206             lcmOperationType: 'migrate',
207             vnfInstanceId: this.instanceId
208         };
209         if (!isNullOrUndefined(this.migrationForm.value.migrateToHost)) {
210             migrationPayload.migrateToHost = this.migrationForm.value.migrateToHost;
211         }
212         if (!isNullOrUndefined(this.migrationForm.value.vduId) && !isNullOrUndefined(this.migrationForm.value.countIndex)) {
213             migrationPayload.vdu = {
214                 vduId: this.migrationForm.value.vduId,
215                 vduCountIndex: this.migrationForm.value.countIndex
216             };
217         } else if (!isNullOrUndefined(this.migrationForm.value.vduId)) {
218             migrationPayload.vdu = {
219                 vduId: this.migrationForm.value.vduId
220             };
221         } else if (!isNullOrUndefined(this.migrationForm.value.countIndex)) {
222             migrationPayload.vdu = {
223                 vduCountIndex: this.migrationForm.value.countIndex
224             };
225         }
226         this.migrationInitialization(migrationPayload);
227     }
228
229     /** Initialize the Vm Migration operation @public */
230     public migrationInitialization(migrationPayload: object): void {
231         this.isLoadingResults = true;
232         const apiURLHeader: APIURLHEADER = {
233             url: environment.NSDINSTANCES_URL + '/' + this.params.id + '/migrate',
234             httpOptions: { headers: this.headers }
235         };
236         const modalData: MODALCLOSERESPONSEDATA = {
237             message: 'Done'
238         };
239         this.restService.postResource(apiURLHeader, migrationPayload).subscribe((result: {}): void => {
240             this.activeModal.close(modalData);
241             this.router.navigate(['/instances/ns/history-operations/' + this.params.id]).catch((): void => {
242                 // Catch Navigation Error
243             });
244         }, (error: ERRORDATA): void => {
245             this.restService.handleError(error, 'post');
246             this.isLoadingResults = false;
247         });
248     }
249
250     /** Used to get the AbstractControl of controlName passed @private */
251     private getFormControl(controlName: string): AbstractControl {
252         // eslint-disable-next-line security/detect-object-injection
253         return this.migrationForm.controls[controlName];
254     }
255 }