Fix Bug 2336: Manual Healing option in Ui
[osm/NG-UI.git] / src / app / instances / ns-primitive / NSPrimitiveComponent.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: KUMARAN M (kumaran.m@tataelxsi.co.in), RAJESH S (rajesh.s@tataelxsi.co.in), BARATH KUMAR R (barath.r@tataelxsi.co.in)
17  */
18 /**
19  * @file NS Instance Primitive Component
20  */
21 import { isNullOrUndefined } from 'util';
22 import { Component, Injector, Input, OnInit } from '@angular/core';
23 import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
24 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
25 import { TranslateService } from '@ngx-translate/core';
26 import { NotifierService } from 'angular-notifier';
27 import { APIURLHEADER, ERRORDATA, PRIMITIVEDATA, PRIMITIVETYPES, URLPARAMS } from 'CommonModel';
28 import { DataService } from 'DataService';
29 import { environment } from 'environment';
30 import { KDUPRIMITIVELEVEL, NSData, VDUPRIMITIVELEVEL, VNFPROFILE } from 'NSDModel';
31 import { NSPrimitiveParams } from 'NSInstanceModel';
32 import { RestService } from 'RestService';
33 import { SharedService } from 'SharedService';
34 import { CONFIGPRIMITIVE, DF, VDUCONFIG, VDUPROFILE, VNFCONFIG, VNFD } from 'VNFDModel';
35 import { VNFInstanceDetails } from 'VNFInstanceModel';
36
37 /**
38  * Creating component
39  * @Component takes NSPrimitiveComponent.html as template url
40  */
41 @Component({
42     templateUrl: './NSPrimitiveComponent.html',
43     styleUrls: ['./NSPrimitiveComponent.scss']
44 })
45 /** Exporting a class @exports NSPrimitiveComponent */
46 export class NSPrimitiveComponent implements OnInit {
47     /** Form valid on submit trigger @public */
48     public submitted: boolean = false;
49
50     /** To inject services @public */
51     public injector: Injector;
52
53     /** Instance for active modal service @public */
54     public activeModal: NgbActiveModal;
55
56     /** FormGroup instance added to the form @ html @public */
57     public primitiveForm: FormGroup;
58
59     /** Primitive params array @public */
60     public primitiveParams: FormArray;
61
62     /** Variable set for twoway binding @public */
63     public nsdId: string;
64
65     /** Check the loading results @public */
66     public isLoadingResults: boolean = false;
67
68     /** Give the message for the loading @public */
69     public message: string = 'PLEASEWAIT';
70
71     /** Contains list of primitive parameter @public */
72     public primitiveParameter: {}[] = [];
73
74     /** Input contains component objects @public */
75     @Input() public params: URLPARAMS;
76
77     /** Contains list of primitive actions @public */
78     public primitiveList: {}[];
79
80     /** Contains objects that is used to hold types of primitive @public */
81     public primitiveTypeList: PRIMITIVETYPES[] = [];
82
83     /** Model value used to hold selected primitive type @public */
84     public primitiveType: string;
85
86     /** Contains list of VDU primitive lists @public */
87     public vduList: VDUPROFILE[];
88
89     /** Contains list of KDU primitive lists @public */
90     public kduList: {}[];
91
92     /** Array holds MemberVNFIndex values @public */
93     public memberVnfIndex: {}[] = [];
94
95     /** Array holds VNFR Data filtered with nsr ID @public */
96     public nsIdFilteredData: {}[] = [];
97
98     /** Items for the memberVNFIndex data @public */
99     public memberTypes: {}[];
100
101     /** FormBuilder instance added to the formBuilder @private */
102     private formBuilder: FormBuilder;
103
104     /** Utilizes rest service for any CRUD operations @private */
105     private restService: RestService;
106
107     /** packages data service collections @private */
108     private dataService: DataService;
109
110     /** Contains tranlsate instance @private */
111     private translateService: TranslateService;
112
113     /** Notifier service to popup notification @private */
114     private notifierService: NotifierService;
115
116     /** Contains all methods related to shared @private */
117     private sharedService: SharedService;
118
119     /** Contains objects that is used to convert key/value pair @private */
120     private objectPrimitiveParams: {} = {};
121
122     constructor(injector: Injector) {
123         this.injector = injector;
124         this.restService = this.injector.get(RestService);
125         this.dataService = this.injector.get(DataService);
126         this.translateService = this.injector.get(TranslateService);
127         this.notifierService = this.injector.get(NotifierService);
128         this.sharedService = this.injector.get(SharedService);
129         this.activeModal = this.injector.get(NgbActiveModal);
130         this.formBuilder = this.injector.get(FormBuilder);
131         this.primitiveTypeList = [
132             {
133                 title: this.translateService.instant('NSPRIMITIVE'),
134                 value: 'NS_Primitive'
135             },
136             {
137                 title: this.translateService.instant('VNFPRIMITIVE'),
138                 value: 'VNF_Primitive'
139             },
140             {
141                 title: this.translateService.instant('VDUPRIMITIVE'),
142                 value: 'VDU_Primitive'
143             },
144             {
145                 title: this.translateService.instant('KDUPRIMITIVE'),
146                 value: 'KDU_Primitive'
147             }
148         ];
149     }
150
151     /** convenience getter for easy access to form fields */
152     get f(): FormGroup['controls'] { return this.primitiveForm.controls; }
153
154     /**
155      * Lifecyle Hooks the trigger before component is instantiate
156      */
157     public ngOnInit(): void {
158         /** Setting up initial value for NSD */
159         this.dataService.currentMessage.subscribe((event: NSData): void => {
160             if (event.identifier !== undefined || event.identifier !== '' || event.identifier !== null) {
161                 this.nsdId = event.identifier;
162             }
163         });
164         this.getMemberVnfIndex();
165         this.initializeForm();
166     }
167
168     /** initialize Forms @public */
169     public initializeForm(): void {
170         this.primitiveForm = this.formBuilder.group({
171             primitive: [null, [Validators.required]],
172             member_vnf_index: [null, [Validators.required]],
173             vdu_id: [null, [Validators.required]],
174             kdu_name: [null, [Validators.required]],
175             primitive_params: this.formBuilder.array([this.primitiveParamsBuilder()])
176         });
177     }
178
179     /** Generate primitive params @public */
180     public primitiveParamsBuilder(): FormGroup {
181         return this.formBuilder.group({
182             primitive_params_name: [null, [Validators.required]],
183             primitive_params_value: ['', [Validators.required]]
184         });
185     }
186
187     /** Handle FormArray Controls @public */
188     public getControls(): AbstractControl[] {
189         return (this.getFormControl('primitive_params') as FormArray).controls;
190     }
191
192     /** Push all primitive params on user's action @public */
193     public createPrimitiveParams(): void {
194         this.primitiveParams = this.getFormControl('primitive_params') as FormArray;
195         this.primitiveParams.push(this.primitiveParamsBuilder());
196     }
197
198     /** Remove primitive params on user's action @public */
199     public removePrimitiveParams(index: number): void {
200         this.primitiveParams.removeAt(index);
201     }
202
203     /** Execute Primitive @public */
204     public execPrimitive(): void {
205         this.submitted = true;
206         this.objectPrimitiveParams = {};
207         this.sharedService.cleanForm(this.primitiveForm);
208         if (this.primitiveForm.invalid) { return; } // Proceed, onces form is valid
209         this.primitiveForm.value.primitive_params.forEach((params: NSPrimitiveParams): void => {
210             if (params.primitive_params_name !== null && params.primitive_params_value !== '') {
211                 this.objectPrimitiveParams[params.primitive_params_name] = params.primitive_params_value;
212             }
213         });
214         //Prepare primitive params
215         const primitiveParamsPayLoads: {} = {
216             primitive: this.primitiveForm.value.primitive,
217             primitive_params: this.objectPrimitiveParams
218         };
219         if (this.primitiveType === 'VNF_Primitive') {
220             // eslint-disable-next-line @typescript-eslint/dot-notation
221             primitiveParamsPayLoads['member_vnf_index'] = this.primitiveForm.value.member_vnf_index;
222         }
223         if (this.primitiveType === 'VDU_Primitive') {
224             // eslint-disable-next-line @typescript-eslint/dot-notation
225             primitiveParamsPayLoads['member_vnf_index'] = this.primitiveForm.value.member_vnf_index;
226             // eslint-disable-next-line @typescript-eslint/dot-notation
227             primitiveParamsPayLoads['vdu_id'] = this.primitiveForm.value.vdu_id;
228         }
229         if (this.primitiveType === 'KDU_Primitive') {
230             // eslint-disable-next-line @typescript-eslint/dot-notation
231             primitiveParamsPayLoads['member_vnf_index'] = this.primitiveForm.value.member_vnf_index;
232             // eslint-disable-next-line @typescript-eslint/dot-notation
233             primitiveParamsPayLoads['kdu_name'] = this.primitiveForm.value.kdu_name;
234         }
235         const apiURLHeader: APIURLHEADER = {
236             url: environment.NSDINSTANCES_URL + '/' + this.nsdId + '/action'
237         };
238         this.isLoadingResults = true;
239         this.restService.postResource(apiURLHeader, primitiveParamsPayLoads).subscribe((result: {}): void => {
240             this.activeModal.dismiss();
241             this.notifierService.notify('success', this.translateService.instant('PAGE.NSPRIMITIVE.EXECUTEDSUCCESSFULLY'));
242             this.isLoadingResults = false;
243         }, (error: ERRORDATA): void => {
244             this.isLoadingResults = false;
245             this.restService.handleError(error, 'post');
246         });
247     }
248     /** Getting MemberVnfIndex using VNFDescriptor API @public */
249     public getMemberVnfIndex(): void {
250         const vnfInstanceData: {}[] = [];
251         this.restService.getResource(environment.VNFINSTANCES_URL).subscribe((vnfInstancesData: VNFInstanceDetails[]): void => {
252             vnfInstancesData.forEach((vnfData: VNFInstanceDetails): void => {
253                 const vnfDataObj: {} =
254                 {
255                     'vnf-ref': vnfData['vnfd-ref'],
256                     'vnf-id': vnfData._id,
257                     'member-index': vnfData['member-vnf-index-ref']
258                 };
259                 vnfInstanceData.push(vnfDataObj);
260             });
261             for (const id of this.params.id) {
262                 this.nsIdFilteredData = vnfInstanceData.filter((vnfdData: {}[]): boolean => vnfdData['vnf-id'] === id);
263                 this.nsIdFilteredData.forEach((resVNF: {}[]): void => {
264                     const assignMemberIndex: {} = {
265                         id: resVNF['member-index'],
266                         'vnf-ref': resVNF['vnf-ref']
267                     };
268                     this.memberVnfIndex.push(assignMemberIndex);
269                 });
270             }
271             this.memberTypes = this.memberVnfIndex;
272             this.isLoadingResults = false;
273         }, (error: ERRORDATA): void => {
274             this.restService.handleError(error, 'get');
275             this.isLoadingResults = false;
276         });
277     }
278     /** Primitive type change event @public */
279     public primitiveTypeChange(data: PRIMITIVETYPES): void {
280         this.primitiveList = [];
281         this.primitiveParameter = [];
282         this.initializeForm();
283         if (data.value === 'NS_Primitive') {
284             this.getNSInfo(this.params.name);
285             this.setUpdateValueandValidation('member_vnf_index');
286         }
287         if (data.value === 'VNF_Primitive' || data.value === 'KDU_Primitive' || data.value === 'NS_Primitive') {
288             this.setUpdateValueandValidation('vdu_id');
289         }
290         if (data.value === 'VDU_Primitive' || data.value === 'VNF_Primitive' || data.value === 'NS_Primitive') {
291             this.setUpdateValueandValidation('kdu_name');
292         }
293     }
294     /** Member index change event */
295     public indexChange(data: VNFPROFILE, getType?: string): void {
296         this.getFormControl('vdu_id').setValue(null);
297         this.getFormControl('kdu_name').setValue(null);
298         if (data['vnf-ref'] !== null) {
299             this.getVnfdInfo(data['vnf-ref'], getType);
300         } else {
301             this.primitiveList = [];
302             this.getFormControl('primitive').setValue(null);
303             this.primitiveParameter = [];
304         }
305     }
306     /** Get VDU/KDU primitive List for the selected event @public */
307     public getPrimitiveList(data: {}, selectedType: string): void {
308         this.primitiveList = data[selectedType + '-configuration']['config-primitive'];
309     }
310     /** Primivtive change event */
311     public primitiveChange(data: PRIMITIVEDATA): void {
312         this.primitiveParameter = [];
313         const formArr: FormArray = this.getFormControl('primitive_params') as FormArray;
314         formArr.controls = [];
315         this.createPrimitiveParams();
316         if (data) {
317             this.updatePrimitive(data);
318         }
319     }
320     /** Generate vdu section @public */
321     public generateVDUData(vduConfig: VDUCONFIG): VDUPROFILE {
322         return {
323             id: vduConfig.id,
324             name: vduConfig.id,
325             'vdu-configuration': vduConfig
326         };
327     }
328     /** Generate kdu section @public */
329     public generateKDUData(kduData: KDUPRIMITIVELEVEL, kduConfig: VDUCONFIG): KDUPRIMITIVELEVEL {
330         return {
331             name: kduData.name,
332             'juju-bundle': kduData['juju-bundle'],
333             'kdu-configuration': kduConfig
334         };
335     }
336     /** Used to set the validation and value and update the validation and value @public */
337     public setUpdateValueandValidation(formName: string): void {
338         this.getFormControl(formName).setValidators([]);
339         this.getFormControl(formName).updateValueAndValidity();
340     }
341     /** Update primitive value based on parameter */
342     private updatePrimitive(primitive: PRIMITIVEDATA): void {
343         if (primitive.parameter) {
344             this.primitiveParameter = primitive.parameter;
345         } else {
346             this.primitiveParameter = [];
347             const formArr: AbstractControl[] = this.getControls();
348             formArr.forEach((formGp: FormGroup): void => {
349                 formGp.controls.primitive_params_name.setValidators([]);
350                 formGp.controls.primitive_params_name.updateValueAndValidity();
351                 formGp.controls.primitive_params_value.setValidators([]);
352                 formGp.controls.primitive_params_value.updateValueAndValidity();
353             });
354         }
355     }
356     /** Get primivitive actions from vnfd data */
357     private getVnfdInfo(vnfdRef: string, getType?: string): void {
358         this.primitiveList = [];
359         this.primitiveParameter = [];
360         this.getFormControl('primitive').setValue(null);
361         const apiUrl: string = environment.VNFPACKAGES_URL + '?id=' + vnfdRef;
362         this.isLoadingResults = true;
363         this.restService.getResource(apiUrl).subscribe((vnfdInfo: VNFD[]): void => {
364             const vnfInstances: VNFD = vnfdInfo[0];
365             if (!isNullOrUndefined(vnfInstances.df)) {
366                 this.getFormControl('vdu_id').setValidators([]);
367                 this.getFormControl('kdu_name').setValidators([]);
368                 vnfInstances.df.forEach((df: DF): void => {
369                     if (df['lcm-operations-configuration'] !== undefined) {
370                         if (df['lcm-operations-configuration']['operate-vnf-op-config'] !== undefined) {
371                             const day12Operation: VDUCONFIG[] = df['lcm-operations-configuration']['operate-vnf-op-config']['day1-2'];
372                             if (day12Operation !== undefined) {
373                                 const vnfprimitiveList: VNFCONFIG = day12Operation
374                                     .filter((itemData: VNFCONFIG): boolean => itemData.id === vnfInstances.id)[0];
375                                 if (vnfprimitiveList !== undefined) {
376                                     this.primitiveList = vnfprimitiveList['config-primitive'];
377                                 }
378                                 /** VDU Primitive */
379                                 if (getType === 'VDU_Primitive') {
380                                     this.kduList = [];
381                                     this.vduList = [];
382                                     this.primitiveList = [];
383                                     df['vdu-profile'].forEach((vduProfile: VDUPROFILE): void => {
384                                         day12Operation.forEach((element: VDUCONFIG): void => {
385                                             if (element.id === vduProfile.id) {
386                                                 const vduDataObj: VDUPROFILE = this.generateVDUData(element);
387                                                 this.vduList.push(vduDataObj);
388                                             }
389                                         });
390                                     });
391                                 }
392                                 /** KDU Primitive */
393                                 if (getType === 'KDU_Primitive') {
394                                     this.kduList = [];
395                                     this.vduList = [];
396                                     this.primitiveList = [];
397                                     if (!isNullOrUndefined(vnfInstances.kdu)) {
398                                         vnfInstances.kdu.forEach((kduData: KDUPRIMITIVELEVEL): void => {
399                                             day12Operation.forEach((element: VDUCONFIG): void => {
400                                                 if (element.id === kduData.name) {
401                                                     const kduDataObj: KDUPRIMITIVELEVEL = this.generateKDUData(kduData, element);
402                                                     this.kduList.push(kduDataObj);
403                                                 }
404                                             });
405                                         });
406                                     }
407                                 }
408                             }
409                         }
410                     }
411                 });
412             }
413             this.isLoadingResults = false;
414         }, (error: ERRORDATA): void => {
415             this.isLoadingResults = false;
416             this.restService.handleError(error, 'get');
417         });
418     }
419     /** Get primivitive actions from NSD data */
420     private getNSInfo(nsdRef: string): void {
421         this.primitiveList = [];
422         this.primitiveParameter = [];
423         this.getFormControl('primitive').setValue(null);
424         const apiUrl: string = environment.NSDESCRIPTORS_URL + '?id=' + nsdRef;
425         this.isLoadingResults = true;
426         this.restService.getResource(apiUrl)
427             .subscribe((nsdInfo: {}): void => {
428                 if (!isNullOrUndefined(nsdInfo[0]['ns-configuration'])) {
429                     this.primitiveList = !isNullOrUndefined(nsdInfo[0]['ns-configuration']['config-primitive']) ?
430                         nsdInfo[0]['ns-configuration']['config-primitive'] : [];
431                 } else {
432                     this.primitiveList = [];
433                 }
434                 this.isLoadingResults = false;
435             }, (error: ERRORDATA): void => {
436                 this.isLoadingResults = false;
437                 this.restService.handleError(error, 'get');
438             });
439     }
440     /** Used to get the AbstractControl of controlName passed @private */
441     private getFormControl(controlName: string): AbstractControl {
442         // eslint-disable-next-line security/detect-object-injection
443         return this.primitiveForm.controls[controlName];
444     }
445 }