Fix Bug 2336: Manual Healing option in Ui
[osm/NG-UI.git] / src / app / utilities / scaling / ScalingComponent.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: BARATH KUMAR R (barath.r@tataelxsi.co.in)
17 */
18 /**
19  * @file Scaling 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 } from '@ng-bootstrap/ng-bootstrap';
27 import { TranslateService } from '@ngx-translate/core';
28 import { APIURLHEADER, ERRORDATA, MODALCLOSERESPONSEDATA, URLPARAMS } from 'CommonModel';
29 import { environment } from 'environment';
30 import { RestService } from 'RestService';
31 import { SharedService } from 'SharedService';
32 import { DF, SCALING, VNFD } from 'VNFDModel';
33 import { InstanceData, VNFInstanceDetails } from 'VNFInstanceModel';
34 /**
35  * Creating component
36  * @Component takes ScalingComponent.html as template url
37  */
38 @Component({
39     selector: 'app-scaling',
40     templateUrl: './ScalingComponent.html',
41     styleUrls: ['./ScalingComponent.scss']
42 })
43 export class ScalingComponent 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     /** Contains the scaling group descriptor names @public */
53     public scalingGroup: {}[];
54     /** Member index of the NS @public */
55     public memberVNFIndex: {}[] = [];
56     /** Items for the memberVNFIndex @public */
57     public memberTypes: {}[];
58     /** handles the selected VNFID @public */
59     public selectedVNFID: string = '';
60     /** Items for the Scale Types @public */
61     public scaleTypes: {}[];
62     /** FormGroup instance added to the form @ html @public */
63     public scalingForm: FormGroup;
64     /** Form valid on submit trigger @public */
65     public submitted: boolean = false;
66     /** Array holds VNFR Data filtered with nsr ID @private */
67     private nsIdFilteredData: {}[] = [];
68     /** FormBuilder instance added to the formBuilder @private */
69     private formBuilder: FormBuilder;
70     /** Instance of the rest service @private */
71     private restService: RestService;
72     /** Controls the header form @private */
73     private headers: HttpHeaders;
74     /** Contains tranlsate instance @private */
75     private translateService: TranslateService;
76     /** Input contains component objects @private */
77     @Input() private params: URLPARAMS;
78     /** Contains all methods related to shared @private */
79     private sharedService: SharedService;
80     /** Holds teh instance of AuthService class of type AuthService @private */
81     private router: Router;
82
83     constructor(injector: Injector) {
84         this.injector = injector;
85         this.restService = this.injector.get(RestService);
86         this.activeModal = this.injector.get(NgbActiveModal);
87         this.translateService = this.injector.get(TranslateService);
88         this.formBuilder = this.injector.get(FormBuilder);
89         this.sharedService = this.injector.get(SharedService);
90         this.router = this.injector.get(Router);
91     }
92
93     /** convenience getter for easy access to form fields */
94     get f(): FormGroup['controls'] { return this.scalingForm.controls; }
95
96     /**
97      * Lifecyle Hooks the trigger before component is instantiate
98      */
99     public ngOnInit(): void {
100         this.initializeForm();
101         this.getmemberIndex();
102         this.scaleTypes = [
103             { id: 'SCALE_OUT', name: this.translateService.instant('SCALEOUT') },
104             { id: 'SCALE_IN', name: this.translateService.instant('SCALEIN') }
105         ];
106         this.headers = new HttpHeaders({
107             'Content-Type': 'application/json',
108             Accept: 'application/json',
109             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
110         });
111     }
112
113     /** Initialize Scaling Forms @public */
114     public initializeForm(): void {
115         this.scalingForm = this.formBuilder.group({
116             memberIndex: [null, [Validators.required]],
117             scalingname: [null, [Validators.required]],
118             scaleType: [null, [Validators.required]]
119         });
120     }
121
122     /** Get the member-vnf-index from NS Package -> vnf-profile @public */
123     public getmemberIndex(): void {
124         this.isLoadingResults = true;
125         const vnfInstanceData: {}[] = [];
126         this.restService.getResource(environment.VNFINSTANCES_URL).subscribe((vnfInstancesData: VNFInstanceDetails[]): void => {
127             vnfInstancesData.forEach((vnfData: VNFInstanceDetails): void => {
128                 const vnfdRef: string = 'vnfd-ref';
129                 const memberIndex: string = 'member-vnf-index-ref';
130                 const nsrId: string = 'nsr-id-ref';
131                 const vnfId: string = 'vnfd-id';
132                 const vnfDataObj: {} =
133                 {
134                     // eslint-disable-next-line security/detect-object-injection
135                     VNFD: vnfData[vnfdRef],
136                     VNFInstanceId: vnfData._id,
137                     // eslint-disable-next-line security/detect-object-injection
138                     MemberIndex: vnfData[memberIndex],
139                     // eslint-disable-next-line security/detect-object-injection
140                     NS: vnfData[nsrId],
141                     // eslint-disable-next-line security/detect-object-injection
142                     VNFID: vnfData[vnfId]
143                 };
144                 vnfInstanceData.push(vnfDataObj);
145             });
146             const nsId: string = 'NS';
147             // eslint-disable-next-line security/detect-object-injection
148             this.nsIdFilteredData = vnfInstanceData.filter((vnfdData: {}[]): boolean => vnfdData[nsId] === this.params.id);
149             this.nsIdFilteredData.forEach((resVNF: InstanceData): void => {
150                 const assignMemberIndex: {} = {
151                     id: resVNF.MemberIndex,
152                     vnfinstanceId: resVNF.VNFInstanceId,
153                     vnfdRef: resVNF.VNFD
154                 };
155                 this.memberVNFIndex.push(assignMemberIndex);
156             });
157             this.memberTypes = this.memberVNFIndex;
158             this.isLoadingResults = false;
159         }, (error: ERRORDATA): void => {
160             this.restService.handleError(error, 'get');
161             this.isLoadingResults = false;
162         });
163     }
164
165     /** Get the scaling-group-descriptor name @public */
166     public getScalingGroupDescriptorName(vnfID: string): void {
167         this.selectedVNFID = vnfID;
168         this.scalingGroup = [];
169         this.getFormControl('scalingname').setValue(null);
170         const scalingGroupDescriptorName: SCALING[] = [];
171         if (!isNullOrUndefined(this.params.data)) {
172             const vnfdPackageDetails: VNFD = this.params.data.filter((vnfdData: VNFD): boolean => vnfdData.id === vnfID)[0];
173             if (vnfdPackageDetails.df.length > 0) {
174                 vnfdPackageDetails.df.forEach((df: DF): void => {
175                     if (!isNullOrUndefined(df['scaling-aspect']) && df['scaling-aspect'].length > 0) {
176                         df['scaling-aspect'].forEach((scalingAspect: SCALING): void => {
177                             scalingGroupDescriptorName.push(scalingAspect);
178                         });
179                     }
180                 });
181                 this.scalingGroup = scalingGroupDescriptorName;
182             }
183         }
184     }
185
186     /** If form is valid and call scaleInstances method to initialize scaling @public */
187     public manualScalingTrigger(): void {
188         this.submitted = true;
189         this.sharedService.cleanForm(this.scalingForm);
190         if (this.scalingForm.invalid) { return; } // Proceed, onces form is valid
191         const scalingPayload: object = {
192             scaleType: 'SCALE_VNF',
193             scaleVnfData:
194             {
195                 scaleVnfType: this.scalingForm.value.scaleType,
196                 scaleByStepData: {
197                     'scaling-group-descriptor': this.scalingForm.value.scalingname,
198                     'member-vnf-index': this.scalingForm.value.memberIndex
199                 }
200             }
201         };
202         this.scaleInstances(scalingPayload);
203     }
204
205     /** Initialize the scaling @public */
206     public scaleInstances(scalingPayload: object): void {
207         this.isLoadingResults = true;
208         const apiURLHeader: APIURLHEADER = {
209             url: environment.NSDINSTANCES_URL + '/' + this.params.id + '/scale',
210             httpOptions: { headers: this.headers }
211         };
212         const modalData: MODALCLOSERESPONSEDATA = {
213             message: 'Done'
214         };
215         this.restService.postResource(apiURLHeader, scalingPayload).subscribe((result: {}): void => {
216             this.activeModal.close(modalData);
217             this.router.navigate(['/instances/ns/history-operations/' + this.params.id]).catch((): void => {
218                 // Catch Navigation Error
219             });
220         }, (error: ERRORDATA): void => {
221             this.restService.handleError(error, 'post');
222             this.isLoadingResults = false;
223         });
224     }
225
226     /** Used to get the AbstractControl of controlName passed @private */
227     private getFormControl(controlName: string): AbstractControl {
228         // eslint-disable-next-line security/detect-object-injection
229         return this.scalingForm.controls[controlName];
230     }
231 }