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