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