b33bfc445edf0b01515f4ae9ed60757a0aa85a86
[osm/NG-UI.git] / src / app / utilities / ns-update / NsUpdateComponent.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 Ns Update Component
20  */
21 import { isNullOrUndefined } from 'util';
22 import { HttpHeaders } from '@angular/common/http';
23 import { Component, Injector, Input, OnInit } from '@angular/core';
24 import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
25 import { Router } from '@angular/router';
26 import { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
27 import { TranslateService } from '@ngx-translate/core';
28 import { APIURLHEADER, CONFIGCONSTANT, ERRORDATA, MODALCLOSERESPONSEDATA, URLPARAMS } from 'CommonModel';
29 import { environment } from 'environment';
30 import { NSUPDATE, TERMINATEVNF } from 'NSInstanceModel';
31 import { RestService } from 'RestService';
32 import { SharedService } from 'SharedService';
33 import { VNFD } from 'VNFDModel';
34 import { VNFInstanceDetails } from 'VNFInstanceModel';
35 import { WarningComponent } from 'WarningComponent';
36
37 /**
38  * Creating component
39  * @Component takes NsUpdateComponent.html as template url
40  */
41 @Component({
42     selector: 'app-ns-update',
43     templateUrl: './NsUpdateComponent.html',
44     styleUrls: ['./NsUpdateComponent.scss']
45 })
46 export class NsUpdateComponent implements OnInit {
47     /** To inject services @public */
48     public injector: Injector;
49     /** Instance for active modal service @public */
50     public activeModal: NgbActiveModal;
51     /** Check the loading results @public */
52     public isLoadingResults: Boolean = false;
53     /** Give the message for the loading @public */
54     public message: string = 'PLEASEWAIT';
55     /** FormGroup instance added to the form @ html @public */
56     public nsUpdateForm: FormGroup;
57     /** Items for the member types @public */
58     public memberTypes: {}[];
59     /** Contains objects that is used to hold types of primitive @public */
60     public updateTypeList: {}[] = [];
61     /** Form valid on submit trigger @public */
62     public submitted: boolean = false;
63     /** Give the update type @public */
64     public terminateVnf: string;
65     /** Model value used to hold selected MemberVNFIndex @public */
66     public memberIndexValue: string;
67     /** Form Check vnfdId Section @public */
68     public vnfdIdShow: boolean = false;
69     /** Contains MemberVNFIndex values @public */
70     public memberVnfIndex: {}[] = [];
71     /** Contains MemberVNFIndex content @public */
72     public selectedVnf: {}[];
73     /** Array holds VNFR Data filtered with nsr ID @public */
74     public nsIdFilteredData: {}[] = [];
75     /** Contains vnfdId value @public */
76     public vnfdId: string;
77     /** Contains vnfId value of the selected MemberVnfIndex @public */
78     public vnfID: string;
79     /** Contains version of the selected MemberVnfIndex @public */
80     public version: string;
81     /** Contains version of the vnfId @public */
82     public vnfversion: string;
83     /** Contains vnfInstanceId of the selected MemberVnfIndex  @public */
84     public instanceId: string;
85     /** Selected VNFInstanceId @public */
86     public selectedvnfId: string = '';
87     /** Input contains component objects @private */
88     @Input() private params: URLPARAMS;
89     /** FormBuilder instance added to the formBuilder @private */
90     private formBuilder: FormBuilder;
91     /** Contains tranlsate instance @private */
92     private translateService: TranslateService;
93     /** Instance of the rest service @private */
94     private restService: RestService;
95     /** Controls the header form @private */
96     private headers: HttpHeaders;
97     /** Contains all methods related to shared @private */
98     private sharedService: SharedService;
99     /** Holds the instance of AuthService class of type AuthService @private */
100     private router: Router;
101     /** Instance of the modal service @private */
102     private modalService: NgbModal;
103     constructor(injector: Injector) {
104         this.injector = injector;
105         this.restService = this.injector.get(RestService);
106         this.activeModal = this.injector.get(NgbActiveModal);
107         this.formBuilder = this.injector.get(FormBuilder);
108         this.sharedService = this.injector.get(SharedService);
109         this.translateService = this.injector.get(TranslateService);
110         this.router = this.injector.get(Router);
111         this.modalService = this.injector.get(NgbModal);
112         this.updateTypeList = [
113             {
114                 title: this.translateService.instant('VNFPKGCHANGE'),
115                 value: 'CHANGE_VNFPKG'
116             },
117             {
118                 title: this.translateService.instant('REMOVEVNF'),
119                 value: 'REMOVE_VNF'
120             }
121         ];
122     }
123     /** convenience getter for easy access to form fields */
124     get f(): FormGroup['controls'] { return this.nsUpdateForm.controls; }
125     /**
126      * Lifecyle Hooks the trigger before component is instantiate
127      */
128     public ngOnInit(): void {
129         this.initializeForm();
130         this.getMemberVnfIndex();
131         this.headers = new HttpHeaders({
132             'Content-Type': 'application/json',
133             Accept: 'application/json',
134             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
135         });
136     }
137
138     /** Initialize Ns Update Forms @public */
139     public initializeForm(): void {
140         this.nsUpdateForm = this.formBuilder.group({
141             updateType: [null, [Validators.required]],
142             memberVnfIndex: [null, [Validators.required]],
143             vnfdId: [null, [Validators.required]]
144         });
145     }
146
147     /** Getting MemberVnfIndex using NSDescriptor API @public */
148     public getMemberVnfIndex(): void {
149         const vnfInstanceData: {}[] = [];
150         this.restService.getResource(environment.VNFINSTANCES_URL).subscribe((vnfInstancesData: VNFInstanceDetails[]): void => {
151             vnfInstancesData.forEach((vnfData: VNFInstanceDetails): void => {
152                 const vnfDataObj: {} =
153                 {
154                     VNFD: vnfData['vnfd-ref'],
155                     VNFInstanceId: vnfData._id,
156                     MemberIndex: vnfData['member-vnf-index-ref'],
157                     NS: vnfData['nsr-id-ref'],
158                     VNFID: vnfData['vnfd-id']
159                 };
160                 vnfInstanceData.push(vnfDataObj);
161             });
162             const nsId: string = 'NS';
163             // eslint-disable-next-line security/detect-object-injection
164             this.nsIdFilteredData = vnfInstanceData.filter((vnfdData: {}[]): boolean => vnfdData[nsId] === this.params.id);
165             this.nsIdFilteredData.forEach((resVNF: {}[]): void => {
166                 const memberIndex: string = 'MemberIndex';
167                 const vnfinstanceID: string = 'VNFInstanceId';
168                 const assignMemberIndex: {} = {
169                     // eslint-disable-next-line security/detect-object-injection
170                     id: resVNF[memberIndex],
171                     // eslint-disable-next-line security/detect-object-injection
172                     vnfinstanceId: resVNF[vnfinstanceID]
173                 };
174                 this.memberVnfIndex.push(assignMemberIndex);
175             });
176             this.memberTypes = this.memberVnfIndex;
177             this.isLoadingResults = false;
178         }, (error: ERRORDATA): void => {
179             this.restService.handleError(error, 'get');
180             this.isLoadingResults = false;
181         });
182     }
183
184     /**
185      *  Fetching the VNFR Information filtered with MemberVnfIndex
186      *  Get the selected VNF Instance ID
187      */
188     public getSelectedVNF(id: string): void {
189         this.instanceId = id;
190         let memberIndexFilteredData: {}[] = [];
191         const memberIndex: string = 'MemberIndex';
192         memberIndexFilteredData = this.nsIdFilteredData.filter((vnfdData: {}[]): boolean =>
193         // eslint-disable-next-line security/detect-object-injection
194             vnfdData[memberIndex] === this.memberIndexValue);
195         const vnfId: string = 'VNFID';
196         const selectedvnfId: string = 'VNFD';
197         this.selectedVnf = memberIndexFilteredData;
198         for (const data of memberIndexFilteredData) {
199             // eslint-disable-next-line security/detect-object-injection
200             this.vnfID = data[vnfId];
201             // eslint-disable-next-line security/detect-object-injection
202             this.selectedvnfId = data[selectedvnfId];
203         }
204     }
205
206     /** Trigger NsUpdate on submit */
207     public triggerNsUpdate(): void {
208         this.submitted = true;
209         this.sharedService.cleanForm(this.nsUpdateForm);
210         if (this.nsUpdateForm.invalid) { return; } // Proceed, onces form is valid
211         this.vnfdId = this.nsUpdateForm.value.vnfdId;
212         this.checkUpdateType();
213     }
214
215     /** Ns Update on submit */
216     public onSubmit(): void {
217         if (this.terminateVnf === 'REMOVE_VNF') {
218             const nsUpdateTerminatePayload: TERMINATEVNF = {
219                 lcmOperationType: 'update',
220                 updateType: this.nsUpdateForm.value.updateType,
221                 nsInstanceId: this.params.id,
222                 removeVnfInstanceId: this.instanceId
223             };
224             this.nsUpdateInitialization(nsUpdateTerminatePayload);
225         } else {
226             const nsUpdatePayload: NSUPDATE = {
227                 lcmOperationType: 'update',
228                 updateType: this.nsUpdateForm.value.updateType,
229                 nsInstanceId: this.params.id,
230                 changeVnfPackageData: {
231                     vnfInstanceId: this.instanceId,
232                     vnfdId: this.nsUpdateForm.value.vnfdId
233                 }
234             };
235             this.nsUpdateInitialization(nsUpdatePayload);
236         }
237     }
238
239     /**
240      *  Open Modal based on selected NS-UPDATE Type
241      */
242     public checkUpdateType(): void {
243         this.isLoadingResults = true;
244         if (this.nsUpdateForm.value.updateType === 'CHANGE_VNFPKG') {
245             this.checkVersion();
246         } else {
247             // eslint-disable-next-line security/detect-non-literal-fs-filename
248             const modalRef: NgbModalRef = this.modalService.open(WarningComponent, { backdrop: 'static' });
249             modalRef.componentInstance.heading = this.translateService.instant('TERMINATEVNF');
250             modalRef.componentInstance.confirmationMessage = this.translateService.instant('TERMINATEVNFCONTENT');
251             modalRef.componentInstance.submitMessage = this.translateService.instant('TERMINATEVNF');
252             modalRef.result.then((result: MODALCLOSERESPONSEDATA): void => {
253                 if (result.message === CONFIGCONSTANT.done) {
254                     this.onSubmit();
255                 }
256             }).catch((): void => {
257                 // Catch Navigation Error
258             });
259         }
260         this.isLoadingResults = false;
261     }
262
263     /** To check the versions are matching or not for 'CHANGE_VNFPKG' type */
264     public checkVersion(): void {
265         this.isLoadingResults = true;
266         const vnfDetails: {}[] = [];
267         this.restService.getResource(environment.VNFPACKAGESCONTENT_URL + '/' + this.vnfdId).subscribe((vnfData: VNFD[]): void => {
268             if (!isNullOrUndefined(vnfData['software-version'])) {
269                 this.version = vnfData['software-version'];
270             }
271             this.restService.getResource(environment.VNFPACKAGESCONTENT_URL).subscribe((vnfDetail: VNFD[]): void => {
272                 vnfDetail.forEach((vnfDatas: VNFD): void => {
273                     const vnfDataObj: {} =
274                     {
275                         VNFID: vnfDatas._id,
276                         version: vnfDatas['software-version']
277                     };
278                     vnfDetails.push(vnfDataObj);
279                 });
280                 let vnfIdFilteredData: {}[] = [];
281                 const vnfID: string = 'VNFID';
282                 const version: string = 'version';
283                 // eslint-disable-next-line security/detect-object-injection
284                 vnfIdFilteredData = vnfDetails.filter((vnfdData: {}[]): boolean => vnfdData[vnfID] === this.vnfID);
285                 for (const data of vnfIdFilteredData) {
286                     // eslint-disable-next-line security/detect-object-injection
287                     this.vnfversion = data[version];
288                 }
289                 if (this.version === this.vnfversion) {
290                     // eslint-disable-next-line security/detect-non-literal-fs-filename
291                     const modalRef: NgbModalRef = this.modalService.open(WarningComponent, { backdrop: 'static' });
292                     modalRef.componentInstance.heading = this.translateService.instant('UPDATENS');
293                     modalRef.componentInstance.confirmationMessage = this.translateService.instant('GENERICCONTENT');
294                     modalRef.componentInstance.submitMessage = this.translateService.instant('UPDATENS');
295                     modalRef.result.then((result: MODALCLOSERESPONSEDATA): void => {
296                         if (result.message === CONFIGCONSTANT.done) {
297                             this.onSubmit();
298                         }
299                     }).catch((): void => { //empty
300                      }
301                     );
302                 } else {
303                     // eslint-disable-next-line security/detect-non-literal-fs-filename
304                     const modalRef: NgbModalRef = this.modalService.open(WarningComponent, { backdrop: 'static' });
305                     modalRef.componentInstance.heading = this.translateService.instant('REDEPLOY');
306                     modalRef.componentInstance.confirmationMessage = this.translateService.instant('REDEPLOYCONTENT');
307                     modalRef.componentInstance.submitMessage = this.translateService.instant('REDEPLOY');
308                     modalRef.result.then((result: MODALCLOSERESPONSEDATA): void => {
309                         if (result.message === CONFIGCONSTANT.done) {
310                             this.onSubmit();
311                         }
312                     }).catch((): void => { //empty
313                      });
314                 }
315             }, (error: ERRORDATA): void => {
316                 this.restService.handleError(error, 'get');
317                 this.isLoadingResults = false;
318             });
319             this.isLoadingResults = false;
320         }, (error: ERRORDATA): void => {
321             this.restService.handleError(error, 'get');
322             this.isLoadingResults = false;
323         });
324     }
325
326     /** Initialize the Ns Update @public */
327     public nsUpdateInitialization(nsUpdatePayload: object): void {
328         this.isLoadingResults = true;
329         const apiURLHeader: APIURLHEADER = {
330             url: environment.NSDINSTANCES_URL + '/' + this.params.id + '/update',
331             httpOptions: { headers: this.headers }
332         };
333         const modalData: MODALCLOSERESPONSEDATA = {
334             message: 'Done'
335         };
336         this.restService.postResource(apiURLHeader, nsUpdatePayload).subscribe((result: {}): void => {
337             this.activeModal.close(modalData);
338             this.router.navigate(['/instances/ns/history-operations/' + this.params.id]).catch((): void => {
339                 // Catch Navigation Error
340             });
341         }, (error: ERRORDATA): void => {
342             this.restService.handleError(error, 'post');
343             this.isLoadingResults = false;
344         });
345     }
346
347     /** To enable or disable vnfdId field @public */
348     public terminateVNF(value: string): void {
349         this.terminateVnf = value;
350         if (this.terminateVnf === 'REMOVE_VNF') {
351             this.vnfdIdShow = true;
352             this.getFormControl('vnfdId').disable();
353         } else {
354             this.vnfdIdShow = false;
355             this.getFormControl('vnfdId').enable();
356         }
357     }
358
359     /** Used to get the AbstractControl of controlName passed @private */
360     private getFormControl(controlName: string): AbstractControl {
361         // eslint-disable-next-line security/detect-object-injection
362         return this.nsUpdateForm.controls[controlName];
363     }
364 }