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