Bugfixes for December 2018
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCreateVnfAndModules.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import org.json.JSONObject;
24 import org.json.JSONArray;
25 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
26 import org.onap.so.bpmn.common.scripts.CatalogDbUtils
27 import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory
28 import org.onap.so.bpmn.common.scripts.ExceptionUtil
29 import org.onap.so.bpmn.common.scripts.VidUtils
30 import org.onap.so.bpmn.core.RollbackData
31 import org.onap.so.bpmn.core.WorkflowException
32 import org.onap.so.bpmn.core.domain.ModelInfo
33 import org.onap.so.bpmn.core.domain.ModuleResource
34 import org.onap.so.bpmn.core.domain.ServiceDecomposition
35 import org.onap.so.bpmn.core.domain.VnfResource
36 import org.onap.so.bpmn.core.json.DecomposeJsonUtil
37 import org.onap.so.bpmn.core.json.JsonUtils
38 import org.camunda.bpm.engine.delegate.BpmnError
39 import org.camunda.bpm.engine.delegate.DelegateExecution;
40 import org.onap.so.bpmn.infrastructure.aai.groovyflows.AAICreateResources;
41 import org.onap.so.logger.MsoLogger
42 import org.onap.so.logger.MessageEnum
43
44 import static org.apache.commons.lang3.StringUtils.*;
45
46
47
48 /**
49 * This class supports the macro VID Flow
50 * with the creation of a generic vnf and related VF modules.
51 */
52 class DoCreateVnfAndModules extends AbstractServiceTaskProcessor {
53
54         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVnfAndModules.class);
55    String Prefix="DCVAM_"
56    ExceptionUtil exceptionUtil = new ExceptionUtil()
57    JsonUtils jsonUtil = new JsonUtils()
58    VidUtils vidUtils = new VidUtils(this)
59    CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
60
61    /**
62         * This method gets and validates the incoming
63         * request.
64         *
65         * @param - execution
66         */
67    public void preProcessRequest(DelegateExecution execution) {
68            
69            execution.setVariable("prefix",Prefix)
70            msoLogger.trace("STARTED DoCreateVnfAndModules PreProcessRequest Process")
71            def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
72            
73            setBasicDBAuthHeader(execution, isDebugLogEnabled)
74            try{
75                    // Get Variables
76
77                    ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
78
79                    String vnfModelInfo = execution.getVariable("vnfModelInfo")
80
81                    String requestId = execution.getVariable("msoRequestId")
82                    execution.setVariable("requestId", requestId)
83                    execution.setVariable("mso-request-id", requestId)
84                    msoLogger.debug("Incoming Request Id is: " + requestId)
85
86                    String serviceInstanceId = execution.getVariable("serviceInstanceId")
87                    msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
88
89                    String vnfName = execution.getVariable("vnfName")
90                    execution.setVariable("CREVI_vnfName", vnfName)
91                    msoLogger.debug("Incoming Vnf Name is: " + vnfName)
92
93                    String productFamilyId = execution.getVariable("productFamilyId")
94                    msoLogger.debug("Incoming Product Family Id is: " + productFamilyId)
95
96                    String source = "VID"
97                    execution.setVariable("source", source)
98                    msoLogger.debug("Incoming Source is: " + source)
99
100                    String lcpCloudRegionId = execution.getVariable("lcpCloudRegionId")
101                   msoLogger.debug("Incoming LCP Cloud Region Id is: " + lcpCloudRegionId)
102
103                    String tenantId = execution.getVariable("tenantId")
104                    msoLogger.debug("Incoming Tenant Id is: " + tenantId)
105
106                    String disableRollback = execution.getVariable("disableRollback")
107                    msoLogger.debug("Incoming Disable Rollback is: " + disableRollback)
108
109                    String asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion")
110                    msoLogger.debug("Incoming asdcServiceModelVersion: " + asdcServiceModelVersion)
111
112                    String vnfId = execution.getVariable("testVnfId") // for junits
113                    if(isBlank(vnfId)){
114                            vnfId = execution.getVariable("vnfId")
115                            if (isBlank(vnfId)) {
116                                    vnfId = UUID.randomUUID().toString()
117                                    msoLogger.debug("Generated Vnf Id is: " + vnfId)
118                            }
119                    }
120                    execution.setVariable("vnfId", vnfId)
121                    
122                    // Set aLaCarte to false
123                    execution.setVariable("aLaCarte", false)
124
125                    def rollbackData = execution.getVariable("rollbackData")
126                    if (rollbackData == null) {
127                            rollbackData = new RollbackData()
128                    }
129                    
130                    def isTest = execution.getVariable("isTest")
131                    
132                         if (isTest == null || isTest == false) {
133                                 execution.setVariable("isBaseVfModule", "true")
134                         }
135                    execution.setVariable("numOfCreatedAddOnModules", 0)
136
137                    rollbackData.put("VNFANDMODULES", "numOfCreatedAddOnModules", "0")
138                    execution.setVariable("rollbackData", rollbackData)
139
140                    sleep (20000)
141
142
143            }catch(BpmnError b){
144                    msoLogger.debug("Rethrowing MSOWorkflowException")
145                    throw b
146            }catch(Exception e){
147                    msoLogger.debug(" Error Occured in DoCreateVnfAndModules PreProcessRequest method!" + e.getMessage())
148                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PreProcessRequest")
149
150            }
151            msoLogger.trace("COMPLETED DoCreateVnfAndModules PreProcessRequest Process")
152    }
153
154
155    public void queryCatalogDB (DelegateExecution execution) {
156          
157            execution.setVariable("prefix",Prefix)
158
159            msoLogger.trace("STARTED DoCreateVnfAndModules QueryCatalogDB Process")
160            try {
161                    VnfResource vnf = null
162                    ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
163                    // if serviceDecomposition is specified, get info from serviceDecomposition
164                    if (serviceDecomposition != null) {
165                            msoLogger.debug("Getting Catalog DB data from ServiceDecomposition object: " + serviceDecomposition.toJsonString())
166                            List<VnfResource> vnfs = serviceDecomposition.getVnfResources()
167                            msoLogger.debug("Read vnfs")
168                            if (vnfs == null) {
169                                    msoLogger.debug("Error - vnfs are empty in serviceDecomposition object")
170                                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf queryCatalogDB, vnfs are empty")
171                            }
172                            vnf = vnfs[0]
173                            String serviceModelName = serviceDecomposition.getModelInfo().getModelName()
174                            vnf.constructVnfType(serviceModelName)
175                            String vnfType = vnf.getVnfType()
176                            msoLogger.debug("Incoming Vnf Type is: " + vnfType)
177                            execution.setVariable("vnfType", vnfType)
178                    }
179                    else {
180                            //Get Vnf Info
181                            String vnfModelInfo = execution.getVariable("vnfModelInfo")
182                            msoLogger.debug("vnfModelInfo: " + vnfModelInfo)
183                            String vnfModelCustomizationUuid = jsonUtil.getJsonValueForKey(vnfModelInfo, "modelCustomizationUuid")
184                            if (vnfModelCustomizationUuid == null) {
185                                            vnfModelCustomizationUuid = ""
186                            }
187                            msoLogger.debug("querying Catalog DB by vnfModelCustomizationUuid: " + vnfModelCustomizationUuid)
188                           
189                            JSONArray vnfs = catalogDbUtils.getAllVnfsByVnfModelCustomizationUuid(execution,
190                                                            vnfModelCustomizationUuid, "v1")
191                            msoLogger.debug("obtained VNF list")
192                            // Only one match here
193                            JSONObject vnfObject = vnfs[0]
194                            vnf = DecomposeJsonUtil.jsonToVnfResource(vnfObject.toString())
195                    }
196                    msoLogger.debug("Read vnfResource")
197                    if (vnf == null) {
198                            msoLogger.debug("Error - vnf is empty in serviceDecomposition object")
199                            exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf queryCatalogDB, vnf is null")
200                    }
201                    execution.setVariable("vnfResourceDecomposition", vnf)
202
203                    List<ModuleResource> vfModules = vnf.getAllVfModuleObjects()
204                    msoLogger.debug("Read vfModules")
205                    if (vfModules == null) {
206                            msoLogger.debug("Error - vfModules are empty in serviceDecomposition object")
207                            exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf queryCatalogDB, vf modules are empty")
208                    }
209                                                   
210                    ModuleResource baseVfModule = null
211
212                    for (int i = 0; i < vfModules.size; i++) {
213                            msoLogger.debug("handling VF Module ")
214                            ModuleResource vfModule = vfModules[i]
215                            boolean isBase = vfModule.getIsBase()
216                            if (isBase) {
217                                            ModelInfo baseVfModuleModelInfoObject = vfModule.getModelInfo()
218                                            String baseVfModuleModelInfoWithRoot = baseVfModuleModelInfoObject.toString()
219                                            String baseVfModuleModelInfo = jsonUtil.getJsonValue(baseVfModuleModelInfoWithRoot, "modelInfo")
220                                            execution.setVariable("baseVfModuleModelInfo", baseVfModuleModelInfo)
221                                            String baseVfModuleLabel = vfModule.getVfModuleLabel()
222                                            execution.setVariable("baseVfModuleLabel", baseVfModuleLabel)
223                                            String basePersonaModelId = baseVfModuleModelInfoObject.getModelInvariantUuid()
224                                            execution.setVariable("basePersonaModelId", basePersonaModelId)
225                                            baseVfModule = vfModule
226                                            break
227                            }               
228                                 
229                         }
230                            
231                         List<ModuleResource>addOnModules = vfModules - baseVfModule
232                            
233                         int addOnModulesToDeploy = 0
234                         if (addOnModules != null) {                             
235                                    addOnModulesToDeploy = addOnModules.size
236                         }
237                            
238
239                         execution.setVariable("addOnModules", addOnModules)
240                         execution.setVariable("addOnModulesToDeploy", addOnModulesToDeploy)
241                         execution.setVariable("addOnModulesDeployed", 0)          
242
243            }catch(Exception ex) {
244                    msoLogger.debug("Error Occured in DoCreateVnfAndModules QueryCatalogDB Process " + ex.getMessage())
245                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnfAndModules QueryCatalogDB Process")
246            }
247
248            // Generate vfModuleId for base VF Module
249            def baseVfModuleId = UUID.randomUUID().toString()
250            execution.setVariable("baseVfModuleId", baseVfModuleId)
251            // For JUnits
252            String requestId = execution.getVariable("requestId")
253            if (requestId.equals("testRequestId123")) {
254                    execution.setVariable("vnfId", "skask")
255            }
256
257            msoLogger.trace("COMPLETED DoCreateVnfAndModules QueryCatalogDB Process")
258    }
259
260    public void preProcessAddOnModule(DelegateExecution execution){
261            
262            execution.setVariable("prefix", Prefix)
263            msoLogger.debug("STARTED preProcessAddOnModule")
264
265            try {
266                    List<ModuleResource>addOnModules = execution.getVariable("addOnModules")
267                    int addOnIndex = (int) execution.getVariable("addOnModulesDeployed")
268
269                    ModuleResource addOnModule = addOnModules[addOnIndex]
270                    
271                    msoLogger.debug("Got addon module")
272
273                    def newVfModuleId = UUID.randomUUID().toString()
274                    execution.setVariable("addOnVfModuleId", newVfModuleId)
275                    execution.setVariable("isBaseVfModule", "false")
276                    
277                    execution.setVariable("instancesOfThisModuleDeployed", 0)
278
279                    ModelInfo addOnVfModuleModelInfoObject = addOnModule.getModelInfo()            
280                    String addOnVfModuleModelInfoWithRoot = addOnVfModuleModelInfoObject.toString()
281                    String addOnVfModuleModelInfo = jsonUtil.getJsonValue(addOnVfModuleModelInfoWithRoot, "modelInfo")
282                    execution.setVariable("addOnVfModuleModelInfo", addOnVfModuleModelInfo)
283                    String addOnVfModuleLabel = addOnModule.getVfModuleLabel()
284                    execution.setVariable("addOnVfModuleLabel", addOnVfModuleLabel)
285                    String addOnPersonaModelId = addOnVfModuleModelInfoObject.getModelInvariantUuid()
286                    execution.setVariable("addOnPersonaModelId", addOnPersonaModelId)
287                    int addOnInitialCount = addOnModule.getInitialCount()
288                    execution.setVariable("initialCount", addOnInitialCount)
289
290
291            }catch(Exception e){
292                    msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessAddOnModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
293                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage())
294            }
295            msoLogger.trace("COMPLETED preProcessAddOnModule")
296    }
297
298    public void postProcessAddOnModule(DelegateExecution execution){
299            
300            execution.setVariable("prefix", Prefix)
301            msoLogger.trace("STARTED postProcessAddOnModule")
302
303            try {
304                    int addOnModulesDeployed = execution.getVariable("addOnModulesDeployed")
305                    execution.setVariable("addOnModulesDeployed", addOnModulesDeployed + 1)
306
307            }catch(Exception e){
308                    msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing postProcessAddOnModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
309                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during postProcessAddOnModule Method:\n" + e.getMessage())
310            }
311            msoLogger.trace("COMPLETED postProcessAddOnModule")
312    }
313    
314    public void validateBaseModule(DelegateExecution execution){
315            
316            execution.setVariable("prefix", Prefix)
317            msoLogger.trace("STARTED validateBaseModule")
318
319            try {
320                    def baseRollbackData = execution.getVariable("DCVAM_baseRollbackData")
321                    def rollbackData = execution.getVariable("rollbackData")
322
323                    def baseModuleMap = baseRollbackData.get("VFMODULE")
324                    baseModuleMap.each{ k, v -> rollbackData.put("VFMODULE_BASE", "${k}","${v}") }
325                    execution.setVariable("rollbackData", rollbackData)
326                    msoLogger.debug("addOnModulesDeployed: " + execution.getVariable("addOnModulesDeployed"))
327                    msoLogger.debug("addOnModulesToDeploy: " + execution.getVariable("addOnModulesToDeploy"))
328                    if (execution.getVariable("addOnModulesDeployed") <  execution.getVariable("addOnModulesToDeploy")) {
329                            msoLogger.debug("More add on modules to deploy")
330                    }
331                    else {
332                            msoLogger.debug("No more add on modules to deploy")
333                    }
334
335            }catch(Exception e){
336                    msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing validateBaseModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
337                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during validateBaseModule Method:\n" + e.getMessage())
338            }
339            msoLogger.trace("COMPLETED validateBaseModule")
340    }
341
342    public void validateAddOnModule(DelegateExecution execution){
343            
344            execution.setVariable("prefix", Prefix)
345            msoLogger.trace("STARTED validateAddOnModule")
346
347            try {
348                    int instancesOfThisModuleDeployed = execution.getVariable("instancesOfThisModuleDeployed")
349                    int numOfCreatedAddOnModules = execution.getVariable("numOfCreatedAddOnModules")
350                    def addOnRollbackData = execution.getVariable("DCVAM_addOnRollbackData")
351                    def rollbackData = execution.getVariable("rollbackData")
352
353                    def addOnModuleMap = addOnRollbackData.get("VFMODULE")
354                    numOfCreatedAddOnModules = numOfCreatedAddOnModules + 1
355                    addOnModuleMap.each{ k, v -> rollbackData.put("VFMODULE_ADDON_" + numOfCreatedAddOnModules, "${k}","${v}") }
356
357                    execution.setVariable("DCVAM_addOnRollbackData", null)
358
359                    execution.setVariable("instancesOfThisModuleDeployed", instancesOfThisModuleDeployed + 1)
360
361                    execution.setVariable("numOfCreatedAddOnModules", numOfCreatedAddOnModules)
362                    rollbackData.put("VNFANDMODULES", "numOfCreatedAddOnModules", "${numOfCreatedAddOnModules}")
363                    execution.setVariable("rollbackData", rollbackData)
364            }catch(Exception e){
365                    msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessAddOnModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
366                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage())
367            }
368            msoLogger.trace("COMPLETED validateAddOnModule")
369    }   
370    
371    public void preProcessRollback (DelegateExecution execution) {
372          
373            msoLogger.trace("preProcessRollback")
374            try {
375                    
376                    Object workflowException = execution.getVariable("WorkflowException");
377
378                    if (workflowException instanceof WorkflowException) {
379                            msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage())
380                            execution.setVariable("prevWorkflowException", workflowException);
381                            //execution.setVariable("WorkflowException", null);
382                    }
383            } catch (BpmnError e) {
384                    msoLogger.debug("BPMN Error during preProcessRollback")
385            } catch(Exception ex) {
386                    String msg = "Exception in preProcessRollback. " + ex.getMessage()
387                    msoLogger.debug(msg)
388            }
389            msoLogger.trace("Exit preProcessRollback")
390    }
391
392    public void postProcessRollback (DelegateExecution execution) {
393          
394            msoLogger.trace("postProcessRollback")
395            String msg = ""
396            try {
397                    Object workflowException = execution.getVariable("prevWorkflowException");
398                    if (workflowException instanceof WorkflowException) {
399                            msoLogger.debug("Setting prevException to WorkflowException: ")
400                            execution.setVariable("WorkflowException", workflowException);
401                    }
402                    execution.setVariable("rollbackData", null)
403            } catch (BpmnError b) {
404                    msoLogger.debug("BPMN Error during postProcessRollback")
405                    throw b;
406            } catch(Exception ex) {
407                    msg = "Exception in postProcessRollback. " + ex.getMessage()
408                    msoLogger.debug(msg)
409            }
410            msoLogger.trace("Exit postProcessRollback")
411    }
412    
413    public void createPlatform (DelegateExecution execution) {
414          
415            msoLogger.trace("START createPlatform")
416            
417            String platformName = execution.getVariable("platformName")
418            String vnfId = execution.getVariable("vnfId")
419    
420            msoLogger.debug("Platform NAME: " + platformName)
421            msoLogger.debug("VnfID: " + vnfId)
422            
423            if(isBlank(platformName)){
424                    msoLogger.debug("platformName was not found. Continuing on with flow...")
425            }else{
426                    msoLogger.debug("platformName was found.")
427                    try{
428                            AAICreateResources aaiCR = new AAICreateResources()
429                            aaiCR.createAAIPlatform(platformName, vnfId)
430                    }catch(Exception ex){
431                            String msg = "Exception in createPlatform. " + ex.getMessage();
432                            msoLogger.debug(msg)
433                    }
434            }
435            msoLogger.trace("Exit createPlatform")
436    }
437    
438    public void createLineOfBusiness (DelegateExecution execution) {
439          
440            msoLogger.trace("START createLineOfBusiness")
441            
442            String lineOfBusiness = execution.getVariable("lineOfBusiness")
443            String vnfId = execution.getVariable("vnfId")
444    
445            msoLogger.debug("LineOfBusiness NAME: " + lineOfBusiness)
446            msoLogger.debug("VnfID: " + vnfId)
447            
448            if(isBlank(lineOfBusiness)){
449                    msoLogger.debug("LineOfBusiness was not found. Continuing on with flow...")
450            }else{
451                    msoLogger.debug("LineOfBusiness was found.")
452                    try{
453                            AAICreateResources aaiCR = new AAICreateResources()
454                            aaiCR.createAAILineOfBusiness(lineOfBusiness, vnfId)
455                    }catch(Exception ex){
456                            String msg = "Exception in LineOfBusiness. " + ex.getMessage();
457                             msoLogger.debug(msg)
458                    }
459            }
460            msoLogger.trace("Exit createLineOfBusiness")
461    }
462
463
464 }