Fix Bug 2048:The VCA Status for an NS with both a KNF and a VNF does not provide...
[osm/NG-UI.git] / src / app / utilities / healing / HealingComponent.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 Healing Component
20  */
21 import { HttpHeaders } from '@angular/common/http';
22 import { Component, Injector, Input, OnInit } from '@angular/core';
23 import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
24 import { Router } from '@angular/router';
25 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
26 import { TranslateService } from '@ngx-translate/core';
27 import { APIURLHEADER, ERRORDATA, MODALCLOSERESPONSEDATA, URLPARAMS } from 'CommonModel';
28 import { environment } from 'environment';
29 import { VDUMAP, VDUMAPPINGS } from 'NSInstanceModel';
30 import { RestService } from 'RestService';
31 import { SharedService, isNullOrUndefined } from 'SharedService';
32 import { InstanceData, VDUR, VNFInstanceDetails } from 'VNFInstanceModel';
33 /**
34  * Creating component
35  * @Component takes HealingComponent.html as template url
36  */
37 @Component({
38     selector: 'app-healing',
39     templateUrl: './HealingComponent.html',
40     styleUrls: ['./HealingComponent.scss']
41 })
42 export class HealingComponent 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     /** Member index of the NS @public */
52     public memberVNFIndex: {}[] = [];
53     /** Items for the memberVNFIndex @public */
54     public memberTypes: {}[];
55     /** Items for the Day1 operation  @public */
56     public day1Operation: {}[];
57     /** Items for the vdu-Id and count-index @public */
58     public vdu: {}[];
59     /** Selected VNFInstanceId @public */
60     public selectedvnfId: string = '';
61     /** Contains vduId @public */
62     public vduId: {};
63     /** VDU Mapping @public */
64     public vduMap: VDUMAP = {};
65     /** Items for countIndex @public */
66     public countIndex: {}[];
67     /** Contains vnfInstanceId of the selected MemberVnfIndex  @public */
68     public instanceId: string;
69     /** FormGroup instance added to the form @ html @public */
70     public healingForm: FormGroup;
71     /** Form valid on submit trigger @public */
72     public submitted: boolean = false;
73     /** VDU Form array @private */
74     private vduFormArray: FormArray;
75     /** Array holds VNFR Data filtered with nsr ID @private */
76     private nsIdFilteredData: {}[] = [];
77     /** FormBuilder instance added to the formBuilder @private */
78     private formBuilder: FormBuilder;
79     /** Instance of the rest service @private */
80     private restService: RestService;
81     /** Controls the header form @private */
82     private headers: HttpHeaders;
83     /** Contains tranlsate instance @private */
84     private translateService: TranslateService;
85     /** Input contains component objects @private */
86     @Input() private params: URLPARAMS;
87     /** Contains all methods related to shared @private */
88     private sharedService: SharedService;
89     /** Holds teh instance of AuthService class of type AuthService @private */
90     private router: Router;
91
92     constructor(injector: Injector) {
93         this.injector = injector;
94         this.restService = this.injector.get(RestService);
95         this.activeModal = this.injector.get(NgbActiveModal);
96         this.translateService = this.injector.get(TranslateService);
97         this.formBuilder = this.injector.get(FormBuilder);
98         this.sharedService = this.injector.get(SharedService);
99         this.router = this.injector.get(Router);
100     }
101
102     /** convenience getter for easy access to form fields */
103     get f(): FormGroup['controls'] { return this.healingForm.controls; }
104
105     /**
106      * Lifecyle Hooks the trigger before component is instantiate
107      */
108     public ngOnInit(): void {
109         this.initializeForm();
110         this.getmemberIndex();
111         this.day1Operation = [
112             { id: 'true', name: this.translateService.instant('True') },
113             { id: '', name: this.translateService.instant('False') }
114         ];
115         this.headers = new HttpHeaders({
116             'Content-Type': 'application/json',
117             Accept: 'application/json',
118             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
119         });
120     }
121
122     /** Generate primitive params @public */
123     get vduParamsBuilder(): FormGroup {
124         return this.formBuilder.group({
125             vduId: [null],
126             countIndex: [null],
127             runDay1: [null]
128         });
129     }
130
131     /** Initialize Healing Forms @public */
132     public initializeForm(): void {
133         this.healingForm = this.formBuilder.group({
134             memberIndex: [null, [Validators.required]],
135             run_day1: [null],
136             vdu: this.formBuilder.array([])
137         });
138     }
139
140     /** Handle FormArray Controls @public */
141     public getControls(): AbstractControl[] {
142         return (this.healingForm.get('vdu') as FormArray).controls;
143     }
144
145     /** Get the member-vnf-index from NS Package -> vnf-profile @private */
146     private getmemberIndex(): void {
147         this.isLoadingResults = true;
148         const vnfInstanceData: {}[] = [];
149         this.restService.getResource(environment.VNFINSTANCES_URL).subscribe((vnfInstancesData: VNFInstanceDetails[]): void => {
150             vnfInstancesData.forEach((vnfData: VNFInstanceDetails): void => {
151                 const nsrId: string = 'nsr-id-ref';
152                 const memberIndex: string = 'member-vnf-index-ref';
153                 const vnfDataObj: {} =
154                 {
155                     VNFInstanceId: vnfData._id,
156                     // eslint-disable-next-line security/detect-object-injection
157                     MemberIndex: vnfData[memberIndex],
158                     // eslint-disable-next-line security/detect-object-injection
159                     NS: vnfData[nsrId]
160                 };
161                 vnfInstanceData.push(vnfDataObj);
162             });
163             const nsId: string = 'NS';
164             // eslint-disable-next-line security/detect-object-injection
165             this.nsIdFilteredData = vnfInstanceData.filter((vnfdData: {}[]): boolean => vnfdData[nsId] === this.params.id);
166             this.nsIdFilteredData.forEach((resVNF: InstanceData): void => {
167                 const assignMemberIndex: {} = {
168                     id: resVNF.MemberIndex,
169                     vnfinstanceId: resVNF.VNFInstanceId
170                 };
171                 this.memberVNFIndex.push(assignMemberIndex);
172             });
173             this.memberTypes = this.memberVNFIndex;
174             this.isLoadingResults = false;
175         }, (error: ERRORDATA): void => {
176             this.restService.handleError(error, 'get');
177             this.isLoadingResults = false;
178         });
179     }
180
181     /** Getting vdu-id & count-index from VNFInstance API */
182     public getVdu(id: string): void {
183         this.isLoadingResults = true;
184         this.vdu = [];
185         const vnfInstanceData: {}[] = [];
186         this.instanceId = id;
187         if (!isNullOrUndefined(id)) {
188             this.restService.getResource(environment.VNFINSTANCES_URL + '/' + id).
189                 subscribe((vnfInstanceDetail: VNFInstanceDetails): void => {
190                     this.selectedvnfId = vnfInstanceDetail['vnfd-ref'];
191                     if (!isNullOrUndefined(vnfInstanceDetail.vdur)) {
192                         vnfInstanceDetail.vdur.forEach((vdu: VDUR): void => {
193                             const vnfInstanceDataObj: {} =
194                             {
195                                 'count-index': vdu['count-index'],
196                                 VDU: vdu['vdu-id-ref']
197                             };
198                             vnfInstanceData.push(vnfInstanceDataObj);
199                         });
200                         this.vdu = vnfInstanceData;
201                         this.vduId = this.vdu.filter((vdu: { VDU?: string }, index: number, self: {}[]): {} =>
202                             index === self.findIndex((t: { VDU?: string }): {} => (
203                                 // eslint-disable-next-line security/detect-object-injection
204                                 t.VDU === vdu.VDU
205                             ))
206                         );
207                         this.isLoadingResults = false;
208                     }
209                 }
210                     , (error: ERRORDATA): void => {
211                         this.restService.handleError(error, 'get');
212                         this.isLoadingResults = false;
213                     });
214         }
215     }
216
217     /** Getting count-index by filtering id  */
218     public getCountIndex(id: string): void {
219         const VDU: string = 'VDU';
220         // eslint-disable-next-line security/detect-object-injection
221         this.countIndex = this.vdu.filter((vnfdData: {}[]): boolean => vnfdData[VDU] === id);
222     }
223
224
225     /** Add vdu @public */
226     public addVdu(): void {
227         this.vduFormArray = this.healingForm.get('vdu') as FormArray;
228         this.vduFormArray.push(this.vduParamsBuilder);
229     }
230
231     /** Remove vdu @public */
232     public removeMapping(index: number): void {
233         this.vduFormArray.removeAt(index);
234     }
235
236     /** If form is valid and call healInstances method to initialize healing @public */
237     public manualHealingTrigger(): void {
238         this.submitted = true;
239         let healingPayload: object = {};
240         this.sharedService.cleanForm(this.healingForm);
241         if (this.healingForm.invalid) { return; } // Proceed, onces form is valid
242         this.vduMap.vdu_mappings = [];
243         this.healingForm.value.vdu.forEach((res: VDUMAPPINGS): void => {
244             this.vduMap.vdu_mappings.push({ 'vdu-id': res.vduId, 'count-index': res.countIndex, 'run-day1': Boolean(res.runDay1) });
245         });
246         if (this.vduMap.vdu_mappings.length !== 0) {
247             healingPayload = {
248                 healVnfData:
249                     [{
250                         vnfInstanceId: this.instanceId,
251                         cause: 'manual',
252                         additionalParams: {
253                             'run-day1': false,
254                             vdu: this.vduMap.vdu_mappings
255                         }
256                     }]
257             };
258         } else {
259             healingPayload = {
260                 healVnfData:
261                     [{
262                         vnfInstanceId: this.instanceId,
263                         cause: 'manual',
264                         additionalParams: {
265                             'run-day1': Boolean(this.getFormControl('run_day1').value)
266                         }
267                     }]
268             };
269         }
270         this.healInstances(healingPayload);
271     }
272
273     /** Initialize the healing @public */
274     public healInstances(healingPayload: object): void {
275         this.isLoadingResults = true;
276         const apiURLHeader: APIURLHEADER = {
277             url: environment.NSDINSTANCES_URL + '/' + this.params.id + '/heal',
278             httpOptions: { headers: this.headers }
279         };
280         const modalData: MODALCLOSERESPONSEDATA = {
281             message: 'Done'
282         };
283         this.restService.postResource(apiURLHeader, healingPayload).subscribe((result: {}): void => {
284             this.activeModal.close(modalData);
285             this.router.navigate(['/instances/ns/history-operations/' + this.params.id]).catch((): void => {
286                 // Catch Navigation Error
287             });
288         }, (error: ERRORDATA): void => {
289             this.restService.handleError(error, 'post');
290             this.isLoadingResults = false;
291         });
292     }
293
294     /** Used to get the AbstractControl of controlName passed @private */
295     private getFormControl(controlName: string): AbstractControl {
296         // eslint-disable-next-line security/detect-object-injection
297         return this.healingForm.controls[controlName];
298     }
299 }