rebuild GUI structure(only changed modules' name)
[vnfsdk/refrepo.git] / lifecyclemgr / src / main / webapp / lifecyclemgr / js / gsolcm.js
1 /*
2  * Copyright 2016-2017 ZTE Corporation.
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 var templateParameters = {
17     changed : true,
18     // the create params used for ui
19     paramJsonObj : {}
20 };
21
22 var lcmHandler = function() {
23     this._addOwnEvents();
24     jQuery.i18n.properties({
25         language : 'en-US',
26         name : 'lcm-template-parameters-i18n',
27         path : 'i18n/',
28         mode : 'map'
29     });
30 };
31
32 lcmHandler.prototype = {
33     _addOwnEvents : function() {
34         $('#createNS').click(this.okAction);
35     },
36     okAction : function() {
37         if (!checkInputs('create', templateParameters.paramJsonObj)) {
38             return;
39         }
40         var sengMsgObj = collectCreateParamfromUI('', 'create', templateParameters.paramJsonObj);
41         var gatewayService = '/openoapi/servicegateway/v1/services';
42         $.when(createServiceInstance(sengMsgObj))
43         .then(function(response) {
44             if (response.status === 'finished') {
45                 $.when(queryService()).then(function(serviceInstance){                    
46                     $('#sai').bootstrapTable("append", serviceInstance);
47                 });
48                 $('#vmAppDialog').removeClass('in').css('display','none');
49             } else {
50                 showErrorMessage('Create service failed',response);
51             }
52         });
53     }
54 };
55
56 /**
57  * init parameter tab
58  * @returns
59  */
60 function initParameterTab() {
61     // Service template was not changed. Do not re-initiate the parameter tab.
62     if (!templateParameters.changed) {
63         return;
64     }
65     var templateId = $("#svcTempl").val();
66     if ('select' === templateId) {
67         document.getElementById("templateParameterTab").innerHTML = '';
68         return;
69     }
70     $.when(fetchCreateParameters(templateId))
71     .then(function(createParam) {
72         // set the create param object
73         templateParameters.paramJsonObj = createParam.parameters;
74         // convert the create param to UI.
75         var components = convertCreateParamsToUI('create', createParam.parameters);
76         document.getElementById("templateParameterTab").innerHTML = components;
77         templateParameters.changed = false;
78     });
79 }
80
81 /**
82  * generate the template to create parameters object
83  * 
84  * @param templateId
85  *            the template id
86  * @returns
87  */
88 function fetchCreateParameters(templateId) {
89     //return $.getJSON("./conf/queryCreateParams.json");
90     var uri = '/openoapi/servicegateway/v1/createparameters/' + templateId;
91     return $.ajax({
92         type : "GET",
93         url : uri
94     });
95 }
96
97 /**
98  * convert the template params obj to html UI string
99  * 
100  * @param identify the object identify, it should be '' when called
101  * @return the html component string
102  */
103 function convertCreateParamsToUI(identify, createParam) {
104     var components = '';
105     // convert host to UI
106     if (undefined !=  createParam.domainHost && 'enum' === createParam.domainHost.type) {
107         components = components
108                 + generateParamComponent(createParam.nodeType, identify,
109                         createParam.domainHost, false);
110     }
111     // convert own param to UI
112     createParam.additionalParamForNs
113             .forEach(function(param) {
114                 components = components
115                         + generateParamComponent(createParam.nodeType,
116                                 identify, param, false);
117             });
118     // convert segments to UI
119     createParam.segments.forEach(function(segment) {
120         // each segment in a field set.
121         components = components + '<fieldset style="margin-left:25px;"><legend>'
122                 + segment.nodeTemplateName + '</legend>';
123         // the identify for segment
124         var segmentIdentify = '' == identify ? segment.nodeTemplateName
125                 : identify + '_' + segment.nodeTemplateName;
126         // convert segment to UI
127         components = components
128                 + convertCreateParamsToUI(segmentIdentify, segment);
129         components = components + '</fieldset>';
130     });
131     return components;
132 }
133
134
135 /**
136  * for each required parameter it could not be empty
137  * @param identify the identify of a segment
138  * @param createParam the create param object 
139  * @returns the check result
140  */
141 function checkInputs(identify, createParam) {
142     //check domain host
143     if (undefined !=  createParam.domainHost && 'enum' === createParam.domainHost.type) {
144         var value = collectParamValue(identify, createParam.domainHost);
145         if ('select' == value) {
146             var name = getParamLabel(createParam.nodeType, createParam.domainHost);
147             alert( name + ' is required.')
148             return false;
149         }
150     }
151     // check parameters
152     for(var i= 0; i < createParam.additionalParamForNs.length; i++){    
153         var param = createParam.additionalParamForNs[i];
154         var value = collectParamValue(identify, param);
155         if(param.required && ('' === value || ('enum' == param.type && 'select' == value))){
156             // the param resource key is nodeType.paramName
157             var name = getParamLabel(createParam.nodeType, param);
158             alert(name + ' is required.')
159             return false;
160         }
161     }
162     // get segments param value from UI
163     var segmentcheckResult = true;
164     for(var i= 0; i < createParam.segments.length; i++){
165         var segment = createParam.segments[i];
166         // the identify for segment
167         var segmentIdentify = '' == identify ? segment.nodeTemplateName
168                 : identify + '_' + segment.nodeTemplateName;
169         segmentcheckResult = checkInputs(segmentIdentify, segment);
170         if (!segmentcheckResult) {
171             break;
172         }
173     }
174     return segmentcheckResult;
175 }
176
177
178 /**
179  * convert the template params obj to html UI string
180  * 
181  * @param identify the object identify, it should be different every time
182  * @return the html component string
183  */
184 function collectCreateParamfromUI(parentHost,identify, createParam) {
185     // the create params used for create msg
186     var paramSentObj = {
187             domainHost:'',
188             nodeTemplateName:'',
189             nodeType:'',
190             segments:[],
191             additionalParamForNs:{}
192     };  
193     // get the domain value
194     if (undefined !=  createParam.domainHost && 'enum' === createParam.domainHost.type) {
195         var domain = collectParamValue(identify, createParam.domainHost);
196         paramSentObj.domainHost = collectParamValue(identify, createParam.domainHost)
197     }
198     //if parent domainHost is not '' and local domain host is'', it should be setted as parent
199     if('' != parentHost && '' == paramSentObj.domainHost){
200         paramSentObj.domainHost = parentHost;
201     }
202     paramSentObj.nodeTemplateName = createParam.nodeTemplateName;
203     paramSentObj.nodeType = createParam.nodeType;
204
205     // get own param value from UI
206     createParam.additionalParamForNs.forEach(function(param) {
207         paramSentObj.additionalParamForNs[param.name] = collectParamValue(identify, param);
208     });
209     // get segments param value from UI
210     createParam.segments.forEach(function(segment) {
211         // the identify for segment
212         var segmentIdentify = '' == identify ? segment.nodeTemplateName
213                 : identify + '_' + segment.nodeTemplateName;
214         var segmentObj = collectCreateParamfromUI(paramSentObj.domainHost, segmentIdentify, segment);
215         paramSentObj.segments.push(segmentObj);
216     });
217     return paramSentObj;
218 }
219
220 /**
221  * get a param value
222  * @param identify the identify of a segment
223  * @param param the param object 
224  * @returns the value of the param
225  */
226 function collectParamValue(identify, param) {
227     var value = $('#' + getParamId(identify, param)).val();
228     return value;
229 }
230
231 /**
232  * get the param id in ui
233  * @param identify
234  * @param param
235  * @returns
236  */
237 function getParamId(identify, param) {
238     return '' ===identify ? param.name : identify + '_' + param.name;
239 }
240
241 /**
242  * get the resource string of a param.
243  * @param nodeType node type
244  * @param param param object
245  * @returns resource string
246  */
247 function getParamLabel(nodeType, param) {
248     var name = $.i18n.prop(nodeType + '.' + param.name);
249     if (name.length === 0 || name.slice(0, 1) === '[') {
250         name = param.name;
251     }
252     return name;
253 }
254 /**
255  * convert combox component
256  * 
257  * @param inputPara
258  * @param items
259  * @param stringReadOnly
260  * @returns
261  */
262 function generateParamComponent(nodeType, identify, param, strReadOnly) {
263     // the param resource key is nodeType.paramName
264     var name = getParamLabel(nodeType, param);
265     var id = getParamId(identify,param);
266     var component = '';
267     if (param.type === 'string') {
268         component = '<div class="mT15 form-group" style="margin-left:0px;">'
269                 + '<label class="col-sm-5 control-label">'
270                 + '<span>' + name + '</span>' + generateRequiredLabel(param)
271                 + '</label>' 
272                 + '<div class="col-sm-5"><input type="text" id="' + id 
273                 + '" name="parameter description" class="form-control" placeholder="'
274                 + name + '" value="' + param.defaultValue;
275         if(strReadOnly){
276             component = component + '" readonly="' + strReadOnly + '"/>'+ '</div></div>';
277         }else{
278             component = component + '"/>'+ '</div></div>';
279         }
280                 
281     } else if (param.type === 'enum') {
282         component = '<div class="form-group" style="margin-left:0px;margin-bottom:5px;">'
283                 + '<label class="col-sm-5 control-label">'
284                 + '<span>' + name + '</span>'
285                 + '<span class="required">*</span>'
286                 + '</label>'
287                 + '<div class="col-sm-5">'
288                 + '<select class="form-control" style ="padding-top: 0px;padding-bottom: 0px;"'
289                 + ' id="' + id + '" name="' + param.name + '" value="' + param.defaultValue 
290                 + '">'
291                 + this.transformToOptions(param.range)
292                 + '</select></div></div>';
293     }
294     return component;
295 }
296
297 /**
298  * transfer the enum range to html body
299  * @param items the map of the range
300  * @returns the html string
301  */
302 function transformToOptions(items) {
303     var options = '<option value="select">--select--</option>';
304     var i;
305     for ( var key in items) {
306         var option = '<option value="' + key + '">' + items[key] + '</option>';
307         options = options + option;
308     }
309     return options;
310 }
311
312 /**
313  * generate required identify to html string
314  * @param parameter the parameter object
315  * @returns the html string 
316  */
317 function generateRequiredLabel(parameter) {
318     var requiredLabel = '';
319     if (parameter.required === 'true') {
320         requiredLabel = '<span class="required">*</span>';
321     }
322     return requiredLabel;
323 }
324
325 /**
326  * create service
327  * @param sengMsgObj the parameters
328  * @returns 
329  */
330 function createServiceInstance(sengMsgObj) {
331     var defer = $.Deferred();
332     var parameter = {
333         'service' : {
334             'name' :  $('#svcName').val(),
335             'description' : $('#svcDesc').val(),
336             'serviceDefId' : '', //no need now, reserved
337             'templateId' :  $("#svcTempl").val(),
338             'parameters' : sengMsgObj
339         }
340     };
341     var serviceGatewayUri = '/openoapi/servicegateway/v1/services';
342     $.when($.ajax({
343         type : "POST",
344         url : serviceGatewayUri,
345         contentType : "application/json",
346         dataType : "json",
347         data : JSON.stringify(parameter)
348     }))
349     .then(function(response) {
350         return queryProgress('create service', response.service.serviceId,response.service.operationId);
351     }).then(function(result){
352         defer.resolve(result);
353     });
354     return defer;
355 }
356
357 /**
358  * 
359  * @param rowId
360  * @param row
361  * @returns
362  */
363 function deleteService(rowId, row) {
364     var deleteHandle = function(result) {
365         if (result) {
366             var serviceId = row.serviceId;
367             var remove = function() {
368                 $('#sai').bootstrapTable('remove', {
369                     field : 'serviceId',
370                     values : [ serviceId ]
371                 });
372             };
373             var failFun = function(responseDesc) {
374                 $.isLoading("hide");
375                 showErrorMessage("Delete service failed", responseDesc);
376             }
377             $.when(deleteServiceInstance(serviceId))
378             .then(function(response) {
379                 if (response.status === 'finished') {
380                     remove();
381                 } else {
382                     showErrorMessage('Create service failed',response);
383                 }
384             });
385             ;
386         }
387     };
388     bootbox.confirm("Do you confirm to delete service?", deleteHandle);
389 }
390
391 /**
392  * sent delete instance msg
393  * @param serviceId the service id
394  * @returns
395  */
396 function deleteServiceInstance(serviceId) {
397     var defer = $.Deferred();
398     var deleteUrl = '/openoapi/servicegateway/v1/services/' + serviceId;
399     $.when($.ajax({
400         type : "DELETE",
401         url : deleteUrl,
402         contentType : "application/json",
403         dataType : "json",
404         data : JSON.stringify(parameter)
405     }))
406     .then(function(response) {
407         return queryProgress('delete service', serviceId,response.operationId);
408     }).then(function(result){
409         defer.resolve(result);
410     });
411     return defer;
412 }
413
414 /**
415  * query progress of the operation 
416  * @param operation the operation string
417  * @param serviceId the service id
418  * @param operationId the operation id
419  * @returns
420  */
421 function queryProgress(operation, serviceId, operationId) {
422     //show the progress dialog
423     $( "#idProgressTitle" ).text(operation);
424     $( "#progressContent" ).text('status:');            
425     $( "#progressbar" ).attr("style","width: 0%");
426     $( "#progressDialog" ).modal({backdrop:'static', keyboard:false});    
427     //set a timer for query operation
428     var defer = $.Deferred();
429     var queryProgressUril = '/openoapi/servicegateway/v1/services/' + serviceId + '/operations/' + operationId;
430     var timerDefer = $.Deferred();
431     var timeout = 3600000;
432     var fun = function() {
433         if (timeout === 0) {
434             timerDefer.resolve({
435                 status : 'error',
436                 reason : operation + ' timeout!',
437             });
438             return;
439         }
440         timeout = timeout - 1000;
441         $.when($.ajax({
442             type : "GET",
443             url : gsoServiceUri
444         }))
445         .then(function(response) {
446             //update progress
447             $( "#progressbar" ).attr("style","width: " + response.operation.progress.toString() + "%");
448             $( "#progressValue" ).text(response.operation.progress.toString() + '%');
449             $( "#progressContent" ).text('status: ' + response.operation.operationContent);            
450             if (response.operation.result == 'finished' || response.operation.result == 'error') {
451                 timerDefer.resolve({
452                     status : response.operation.result ,
453                     reason : response.operation.reason
454                 });
455             }
456         });
457     };
458     var timerId = setInterval(fun, 1000);
459     $.when(timerDefer)
460     .then(function(responseDesc) {
461         clearInterval(timerId);
462         $('#progressDialog').modal('hide');
463         defer.resolve({
464             status : responseDesc.status,
465             reason : responseDesc.reason,
466             serviceId:serviceId
467         });
468
469     });
470     return defer; 
471 }
472
473
474 /**
475  * convert the input parameters to ui
476  * @param identify the identify of a segment
477  * @param createParam the create param object 
478  * @returns the check result
479  */
480 function convertInputsToUI(parentHost, identify, serviceParam) {
481     var components = '';
482     // convert host to UI
483     if (undefined !=  serviceParam.domainHost && '' != serviceParam.domainHost && parentHost != serviceParam.domainHost) {
484         var param ={
485             name:'domainHost',
486             type:'string',
487             defaultValue:getShowVal('domainHost', serviceParam.domainHost),
488             required:false            
489         }
490         components = components + generateParamComponent(serviceParam.nodeType, identify,
491                 param, true);
492     }
493     // convert own param to UI
494     for(var key in serviceParam.additionalParamForNs ){
495         var param ={
496                 name: key,
497                 type:'string',
498                 defaultValue:getShowVal(key, serviceParam.additionalParamForNs[key]),
499                 required:false            
500             }
501         components = components + generateParamComponent(serviceParam.nodeType,
502                         identify, param, true);
503     }
504     // convert segments to UI
505     serviceParam.segments.forEach(function(segment) {
506         // each segment in a field set.
507         components = components + '<div class="mT15 form-group"><fieldset style="margin-left:25px;"><legend>'
508                 + segment.nodeTemplateName + '</legend>';
509         // the identify for segment
510         var segmentIdentify = '' == identify ? segment.nodeTemplateName
511                 : identify + '_' + segment.nodeTemplateName;
512         // convert segment to UI
513         components = components
514                 + convertInputsToUI(serviceParam.domainHost, segmentIdentify, segment);
515         components = components + '</fieldset></div>';
516     });
517     return components;
518 }
519
520 function getShowVal(paramName, paramValue){
521     if(paramName == 'domainHost'){
522         return getHostNameByVal(paramValue);
523     }
524     else if(paramName == 'location'){
525         return getVimNameById(paramValue);
526     }
527     else if(paramName == 'sdncontroller'){
528         return getSdnControllerNameById(paramValue);
529     }
530     else{
531         return paramValue;
532     }
533 }
534
535 function getHostNameByVal(hostDomain){
536      var requestUrl ="/openoapi/servicegateway/v1/domains";
537       var returnObj = '';
538       $.ajax({
539               type : "GET",
540               async: false,
541               url : requestUrl,
542               contentType : "application/json",
543               success : function(jsonobj) {
544                 jsonobj.forEach(function(host){
545                     if(host.host == hostDomain){
546                           returnObj = host.name;
547                     }
548                 });
549               },
550               error : function(xhr, ajaxOptions, thrownError) {
551                   alert("Error on getting link data : " + xhr.responseText);
552               }
553           });
554       return returnObj;
555 }
556
557 //get the vim name by id.
558 function getVimNameById(vimId){
559   var requestUrl ="/openoapi/extsys/v1/vims/" + vimId;
560   var returnObj;
561   $
562       .ajax({
563           type : "GET",
564           async: false,
565           url : requestUrl,
566           contentType : "application/json",
567           success : function(jsonobj) {
568               // TODO return according to the json data received.
569               returnObj = jsonobj;
570           },
571           error : function(xhr, ajaxOptions, thrownError) {
572               alert("Error on getting link data : " + xhr.responseText);
573           }
574       });
575   return returnObj;
576 }
577
578 //get the sdn controller name by id.
579 function getSdnControllerNameById(sdnControllerId){
580   var requestUrl ="/openoapi/extsys/v1/sdncontrollers/" + sdnControllerId;
581   var returnObj;
582   $
583       .ajax({
584           type : "GET",
585           async: false,
586           url : requestUrl,
587           contentType : "application/json",
588           success : function(jsonobj) {
589               // TODO return according to the json data received.
590               returnObj = jsonobj;
591           },
592           error : function(xhr, ajaxOptions, thrownError) {
593               alert("Error on getting link data : " + xhr.responseText);
594           }
595       });
596   return returnObj;
597 }
598
599
600
601 /**
602  * show error dialog
603  * @param title the title 
604  * @param result the result
605  * @returns
606  */
607 function showErrorMessage(title, result) {
608     //show the error dialog
609     $( "#errorDialogTitle" ).text(title);
610     $( "#errorDialogReason" ).text(result.reason);            
611     $( "#errorDialog" ).modal({backdrop:'static', keyboard:false});    
612 }
613
614 /**
615  * generate the template to create parameters object
616  * 
617  * @param templateId the template id
618  * @returns
619  */
620 function queryService(serviceId) {
621     var uri = '/openoapi/servicegateway/v1/services/' + serviceId;
622     return $.ajax({
623         type : "GET",
624         url : uri
625     });
626 }