88e7b34dcd934e0c22d9af136f3a44a66709d567
[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                    Map<String,String> vfModuleNames = execution.getVariable("vfModuleNames")
123                    msoLogger.debug("Incoming vfModuleNames: " + vfModuleNames)
124
125                    // Set aLaCarte to false
126                    execution.setVariable("aLaCarte", false)
127
128                    def rollbackData = execution.getVariable("rollbackData")
129                    if (rollbackData == null) {
130                            rollbackData = new RollbackData()
131                    }
132                    
133                    def isTest = execution.getVariable("isTest")
134                    
135                         if (isTest == null || isTest == false) {
136                                 execution.setVariable("isBaseVfModule", "true")
137                         }
138                    execution.setVariable("numOfCreatedAddOnModules", 0)
139
140                    rollbackData.put("VNFANDMODULES", "numOfCreatedAddOnModules", "0")
141                    execution.setVariable("rollbackData", rollbackData)
142
143                    String delayMS = execution.getVariable("delayMS")
144                    long longDelayMS = 20000;
145
146                    if (delayMS != null && !delayMS.isEmpty()) {
147                            longDelayMS = Long.parseLong(delayMS);
148                    }
149
150                    if (longDelayMS > 0) {
151                            msoLogger.debug("Delaying workflow " + longDelayMS + "ms");
152                            sleep(longDelayMS)
153                    }
154            }catch(BpmnError b){
155                    msoLogger.debug("Rethrowing MSOWorkflowException")
156                    throw b
157            }catch(Exception e){
158                    msoLogger.debug(" Error Occured in DoCreateVnfAndModules PreProcessRequest method!" + e.getMessage())
159                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PreProcessRequest")
160
161            }
162            msoLogger.trace("COMPLETED DoCreateVnfAndModules PreProcessRequest Process")
163    }
164
165    public void queryCatalogDB (DelegateExecution execution) {
166          
167            execution.setVariable("prefix",Prefix)
168
169            msoLogger.trace("STARTED DoCreateVnfAndModules QueryCatalogDB Process")
170            try {
171                    VnfResource vnf = null
172                    // if serviceDecomposition is specified, get info from serviceDecomposition
173                    ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
174                    if (serviceDecomposition != null) {
175                            msoLogger.debug("Getting Catalog DB data from ServiceDecomposition object: " + serviceDecomposition.toJsonString())
176                            List<VnfResource> vnfs = serviceDecomposition.getVnfResources()
177                            msoLogger.debug("Read vnfs")
178                            if (vnfs == null) {
179                                    msoLogger.debug("Error - vnfs are empty in serviceDecomposition object")
180                                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf queryCatalogDB, vnfs are empty")
181                            }
182                            vnf = vnfs[0]
183                            String serviceModelName = serviceDecomposition.getModelInfo().getModelName()
184                            vnf.constructVnfType(serviceModelName)
185                            String vnfType = vnf.getVnfType()
186                            msoLogger.debug("Incoming Vnf Type is: " + vnfType)
187                            execution.setVariable("vnfType", vnfType)
188                    }
189                    else {
190                            //Get Vnf Info
191                            String vnfModelInfo = execution.getVariable("vnfModelInfo")
192                            msoLogger.debug("vnfModelInfo: " + vnfModelInfo)
193                            String vnfModelCustomizationUuid = jsonUtil.getJsonValueForKey(vnfModelInfo, "modelCustomizationUuid")
194                            if (vnfModelCustomizationUuid == null) {
195                                            vnfModelCustomizationUuid = ""
196                            }
197                            msoLogger.debug("querying Catalog DB by vnfModelCustomizationUuid: " + vnfModelCustomizationUuid)
198                           
199                            JSONArray vnfs = catalogDbUtils.getAllVnfsByVnfModelCustomizationUuid(execution,
200                                                            vnfModelCustomizationUuid, "v1")
201                            msoLogger.debug("obtained VNF list")
202                            // Only one match here
203                            JSONObject vnfObject = vnfs[0]
204                            vnf = DecomposeJsonUtil.jsonToVnfResource(vnfObject.toString())
205                    }
206                    msoLogger.debug("Read vnfResource")
207                    if (vnf == null) {
208                            msoLogger.debug("Error - vnf is empty in serviceDecomposition object")
209                            exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf queryCatalogDB, vnf is null")
210                    }
211                    execution.setVariable("vnfResourceDecomposition", vnf)
212
213                    List<ModuleResource> vfModules = vnf.getAllVfModuleObjects()
214                    msoLogger.debug("Read vfModules")
215                    if (vfModules == null) {
216                            msoLogger.debug("Error - vfModules are empty in serviceDecomposition object")
217                            exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf queryCatalogDB, vf modules are empty")
218                    }
219                                                   
220                    ModuleResource baseVfModule = null
221                    Map<String,String> vfModuleNames = execution.getVariable("vfModuleNames")
222
223                    for (int i = 0; i < vfModules.size; i++) {
224                            msoLogger.debug("handling VF Module ")
225                            ModuleResource vfModule = vfModules[i]
226                            boolean isBase = vfModule.getIsBase()
227                            if (isBase) {
228                                            ModelInfo baseVfModuleModelInfoObject = vfModule.getModelInfo()
229                                            String baseVfModuleModelInfoWithRoot = baseVfModuleModelInfoObject.toString()
230                                            String baseVfModuleModelInfo = jsonUtil.getJsonValue(baseVfModuleModelInfoWithRoot, "modelInfo")
231                                            execution.setVariable("baseVfModuleModelInfo", baseVfModuleModelInfo)
232                                            String baseVfModuleLabel = vfModule.getVfModuleLabel()
233                                            execution.setVariable("baseVfModuleLabel", baseVfModuleLabel)
234                                            String basePersonaModelId = baseVfModuleModelInfoObject.getModelInvariantUuid()
235                                            execution.setVariable("basePersonaModelId", basePersonaModelId)
236                                            String baseVfModuleName = getPredefinedVfModuleName(execution, basePersonaModelId)
237                                            execution.setVariable("baseVfModuleName", baseVfModuleName)
238                                            baseVfModule = vfModule
239                                            break
240                            }               
241                                 
242                         }
243                            
244                         List<ModuleResource>addOnModules = vfModules - baseVfModule
245                            
246                         int addOnModulesToDeploy = 0
247                         if (addOnModules != null) {                             
248                                    addOnModulesToDeploy = addOnModules.size
249                         }
250                            
251
252                         execution.setVariable("addOnModules", addOnModules)
253                         execution.setVariable("addOnModulesToDeploy", addOnModulesToDeploy)
254                         execution.setVariable("addOnModulesDeployed", 0)          
255
256            }catch(Exception ex) {
257                    msoLogger.debug("Error Occured in DoCreateVnfAndModules QueryCatalogDB Process " + ex.getMessage())
258                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnfAndModules QueryCatalogDB Process")
259            }
260
261            // Generate vfModuleId for base VF Module
262            def baseVfModuleId = UUID.randomUUID().toString()
263            execution.setVariable("baseVfModuleId", baseVfModuleId)
264            // For JUnits
265            String requestId = execution.getVariable("requestId")
266            if (requestId.equals("testRequestId123")) {
267                    execution.setVariable("vnfId", "skask")
268            }
269
270            msoLogger.trace("COMPLETED DoCreateVnfAndModules QueryCatalogDB Process")
271    }
272
273    public void preProcessAddOnModule(DelegateExecution execution){
274            
275            execution.setVariable("prefix", Prefix)
276            msoLogger.debug("STARTED preProcessAddOnModule")
277
278            try {
279                    List<ModuleResource>addOnModules = execution.getVariable("addOnModules")
280                    int addOnIndex = (int) execution.getVariable("addOnModulesDeployed")
281
282                    ModuleResource addOnModule = addOnModules[addOnIndex]
283                    
284                    msoLogger.debug("Got addon module")
285
286                    def newVfModuleId = UUID.randomUUID().toString()
287                    execution.setVariable("addOnVfModuleId", newVfModuleId)
288                    execution.setVariable("isBaseVfModule", "false")
289                    
290                    execution.setVariable("instancesOfThisModuleDeployed", 0)
291
292                    ModelInfo addOnVfModuleModelInfoObject = addOnModule.getModelInfo()            
293                    String addOnVfModuleModelInfoWithRoot = addOnVfModuleModelInfoObject.toString()
294                    String addOnVfModuleModelInfo = jsonUtil.getJsonValue(addOnVfModuleModelInfoWithRoot, "modelInfo")
295                    execution.setVariable("addOnVfModuleModelInfo", addOnVfModuleModelInfo)
296                    String addOnVfModuleLabel = addOnModule.getVfModuleLabel()
297                    execution.setVariable("addOnVfModuleLabel", addOnVfModuleLabel)
298                    String addOnPersonaModelId = addOnVfModuleModelInfoObject.getModelInvariantUuid()
299                    execution.setVariable("addOnPersonaModelId", addOnPersonaModelId)
300                    String addOnVfModuleName = getPredefinedVfModuleName(execution, addOnPersonaModelId)
301                    execution.setVariable("addOnVfModuleName", addOnVfModuleName)
302                    int addOnInitialCount = addOnModule.getInitialCount()
303                    execution.setVariable("initialCount", addOnInitialCount)
304
305
306            }catch(Exception e){
307                    msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessAddOnModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
308                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage())
309            }
310            msoLogger.trace("COMPLETED preProcessAddOnModule")
311    }
312
313    public void postProcessAddOnModule(DelegateExecution execution){
314            
315            execution.setVariable("prefix", Prefix)
316            msoLogger.trace("STARTED postProcessAddOnModule")
317
318            try {
319                    int addOnModulesDeployed = execution.getVariable("addOnModulesDeployed")
320                    execution.setVariable("addOnModulesDeployed", addOnModulesDeployed + 1)
321
322            }catch(Exception e){
323                    msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing postProcessAddOnModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
324                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during postProcessAddOnModule Method:\n" + e.getMessage())
325            }
326            msoLogger.trace("COMPLETED postProcessAddOnModule")
327    }
328    
329    public void validateBaseModule(DelegateExecution execution){
330            
331            execution.setVariable("prefix", Prefix)
332            msoLogger.trace("STARTED validateBaseModule")
333
334            try {
335                    def baseRollbackData = execution.getVariable("DCVAM_baseRollbackData")
336                    def rollbackData = execution.getVariable("rollbackData")
337
338                    def baseModuleMap = baseRollbackData.get("VFMODULE")
339                    baseModuleMap.each{ k, v -> rollbackData.put("VFMODULE_BASE", "${k}","${v}") }
340                    execution.setVariable("rollbackData", rollbackData)
341                    msoLogger.debug("addOnModulesDeployed: " + execution.getVariable("addOnModulesDeployed"))
342                    msoLogger.debug("addOnModulesToDeploy: " + execution.getVariable("addOnModulesToDeploy"))
343                    if (execution.getVariable("addOnModulesDeployed") <  execution.getVariable("addOnModulesToDeploy")) {
344                            msoLogger.debug("More add on modules to deploy")
345                    }
346                    else {
347                            msoLogger.debug("No more add on modules to deploy")
348                    }
349
350            }catch(Exception e){
351                    msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing validateBaseModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
352                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during validateBaseModule Method:\n" + e.getMessage())
353            }
354            msoLogger.trace("COMPLETED validateBaseModule")
355    }
356
357    public void validateAddOnModule(DelegateExecution execution){
358            
359            execution.setVariable("prefix", Prefix)
360            msoLogger.trace("STARTED validateAddOnModule")
361
362            try {
363                    int instancesOfThisModuleDeployed = execution.getVariable("instancesOfThisModuleDeployed")
364                    int numOfCreatedAddOnModules = execution.getVariable("numOfCreatedAddOnModules")
365                    def addOnRollbackData = execution.getVariable("DCVAM_addOnRollbackData")
366                    def rollbackData = execution.getVariable("rollbackData")
367
368                    def addOnModuleMap = addOnRollbackData.get("VFMODULE")
369                    numOfCreatedAddOnModules = numOfCreatedAddOnModules + 1
370                    addOnModuleMap.each{ k, v -> rollbackData.put("VFMODULE_ADDON_" + numOfCreatedAddOnModules, "${k}","${v}") }
371
372                    execution.setVariable("DCVAM_addOnRollbackData", null)
373
374                    execution.setVariable("instancesOfThisModuleDeployed", instancesOfThisModuleDeployed + 1)
375
376                    execution.setVariable("numOfCreatedAddOnModules", numOfCreatedAddOnModules)
377                    rollbackData.put("VNFANDMODULES", "numOfCreatedAddOnModules", "${numOfCreatedAddOnModules}")
378                    execution.setVariable("rollbackData", rollbackData)
379            }catch(Exception e){
380                    msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessAddOnModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
381                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage())
382            }
383            msoLogger.trace("COMPLETED validateAddOnModule")
384    }   
385    
386    public void preProcessRollback (DelegateExecution execution) {
387          
388            msoLogger.trace("preProcessRollback")
389            try {
390                    
391                    Object workflowException = execution.getVariable("WorkflowException");
392
393                    if (workflowException instanceof WorkflowException) {
394                            msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage())
395                            execution.setVariable("prevWorkflowException", workflowException);
396                            //execution.setVariable("WorkflowException", null);
397                    }
398            } catch (BpmnError e) {
399                    msoLogger.debug("BPMN Error during preProcessRollback")
400            } catch(Exception ex) {
401                    String msg = "Exception in preProcessRollback. " + ex.getMessage()
402                    msoLogger.debug(msg)
403            }
404            msoLogger.trace("Exit preProcessRollback")
405    }
406
407    public void postProcessRollback (DelegateExecution execution) {
408          
409            msoLogger.trace("postProcessRollback")
410            String msg = ""
411            try {
412                    Object workflowException = execution.getVariable("prevWorkflowException");
413                    if (workflowException instanceof WorkflowException) {
414                            msoLogger.debug("Setting prevException to WorkflowException: ")
415                            execution.setVariable("WorkflowException", workflowException);
416                    }
417                    execution.setVariable("rollbackData", null)
418            } catch (BpmnError b) {
419                    msoLogger.debug("BPMN Error during postProcessRollback")
420                    throw b;
421            } catch(Exception ex) {
422                    msg = "Exception in postProcessRollback. " + ex.getMessage()
423                    msoLogger.debug(msg)
424            }
425            msoLogger.trace("Exit postProcessRollback")
426    }
427    
428    public void createPlatform (DelegateExecution execution) {
429          
430            msoLogger.trace("START createPlatform")
431            
432            String platformName = execution.getVariable("platformName")
433            String vnfId = execution.getVariable("vnfId")
434    
435            msoLogger.debug("Platform NAME: " + platformName)
436            msoLogger.debug("VnfID: " + vnfId)
437            
438            if(isBlank(platformName)){
439                    msoLogger.debug("platformName was not found. Continuing on with flow...")
440            }else{
441                    msoLogger.debug("platformName was found.")
442                    try{
443                            AAICreateResources aaiCR = new AAICreateResources()
444                            aaiCR.createAAIPlatform(platformName, vnfId)
445                    }catch(Exception ex){
446                            String msg = "Exception in createPlatform. " + ex.getMessage();
447                            msoLogger.debug(msg)
448                    }
449            }
450            msoLogger.trace("Exit createPlatform")
451    }
452    
453    public void createLineOfBusiness (DelegateExecution execution) {
454          
455            msoLogger.trace("START createLineOfBusiness")
456            
457            String lineOfBusiness = execution.getVariable("lineOfBusiness")
458            String vnfId = execution.getVariable("vnfId")
459    
460            msoLogger.debug("LineOfBusiness NAME: " + lineOfBusiness)
461            msoLogger.debug("VnfID: " + vnfId)
462            
463            if(isBlank(lineOfBusiness)){
464                    msoLogger.debug("LineOfBusiness was not found. Continuing on with flow...")
465            }else{
466                    msoLogger.debug("LineOfBusiness was found.")
467                    try{
468                            AAICreateResources aaiCR = new AAICreateResources()
469                            aaiCR.createAAILineOfBusiness(lineOfBusiness, vnfId)
470                    }catch(Exception ex){
471                            String msg = "Exception in LineOfBusiness. " + ex.getMessage();
472                             msoLogger.debug(msg)
473                    }
474            }
475            msoLogger.trace("Exit createLineOfBusiness")
476    }
477
478    public String getPredefinedVfModuleName(DelegateExecution execution, String vfModuleModelInvariantUuid) {
479            Map<String,String> vfModuleNames = execution.getVariable("vfModuleNames")
480                    
481            if (vfModuleNames == null) {
482                    return null
483            }
484
485            String vfModuleName = vfModuleNames.get(vfModuleModelInvariantUuid)
486
487            if (vfModuleName != null) {
488                    msoLogger.debug("Using vfModuleName='" + vfModuleName + "' for vfModuleModelInvariantUuid=" + vfModuleModelInvariantUuid)
489            }
490
491            return vfModuleName
492    }
493 }