Merge "Merge 'origin/casablanca' into master"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCreateVfModule.groovy
index 58b90a1..53e3525 100644 (file)
 
 package org.onap.so.bpmn.infrastructure.scripts
 
+import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory
+import org.onap.so.client.HttpClientFactory
+
+import javax.ws.rs.core.MediaType
+import javax.ws.rs.core.Response
 import javax.xml.parsers.DocumentBuilder
 import javax.xml.parsers.DocumentBuilderFactory
 
@@ -28,6 +33,7 @@ import org.camunda.bpm.engine.delegate.DelegateExecution
 import org.json.JSONArray
 import org.json.JSONObject
 import org.onap.aai.domain.yang.GenericVnf
+import org.onap.aai.domain.yang.NetworkPolicy
 import org.onap.so.bpmn.common.scripts.AaiUtil
 import org.onap.so.bpmn.common.scripts.CatalogDbUtils
 import org.onap.so.bpmn.common.scripts.ExceptionUtil
@@ -35,14 +41,14 @@ import org.onap.so.bpmn.common.scripts.MsoUtils
 import org.onap.so.bpmn.common.scripts.NetworkUtils
 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
 import org.onap.so.bpmn.common.scripts.VfModuleBase
+import org.onap.so.bpmn.common.util.OofInfraUtils
 import org.onap.so.bpmn.core.RollbackData
 import org.onap.so.bpmn.core.UrnPropertiesReader
 import org.onap.so.bpmn.core.WorkflowException
-
 import org.onap.so.bpmn.core.domain.VnfResource
 import org.onap.so.bpmn.core.json.DecomposeJsonUtil
 import org.onap.so.bpmn.core.json.JsonUtils
-import org.onap.so.client.graphinventory.entities.uri.Depth
+import org.onap.so.client.HttpClient
 import org.onap.so.client.aai.AAIObjectPlurals
 import org.onap.so.client.aai.AAIObjectType;
 import org.onap.so.client.aai.AAIResourcesClient
@@ -50,13 +56,13 @@ import org.onap.so.client.aai.entities.AAIResultWrapper
 import org.onap.so.client.aai.entities.uri.AAIResourceUri
 import org.onap.so.client.aai.entities.uri.AAIUri
 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
+import org.onap.so.client.graphinventory.entities.uri.Depth
 import org.onap.so.constants.Defaults
+import org.onap.so.db.catalog.beans.HomingInstance
 import org.onap.so.logger.MessageEnum
 import org.onap.so.logger.MsoLogger
-import org.onap.so.rest.APIResponse
-import org.onap.so.rest.RESTClient
-import org.onap.so.rest.RESTConfig
-import org.springframework.web.util.UriUtils
+
+import org.onap.so.utils.TargetEntity
 import org.w3c.dom.Document
 import org.w3c.dom.Element
 import org.w3c.dom.NamedNodeMap
@@ -75,8 +81,10 @@ public class DoCreateVfModule extends VfModuleBase {
        ExceptionUtil exceptionUtil = new ExceptionUtil()
        JsonUtils jsonUtil = new JsonUtils()
        SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
-       CatalogDbUtils catalog = new CatalogDbUtils()
+       OofInfraUtils oofInfraUtils = new OofInfraUtils()
+       CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
        DecomposeJsonUtil decomposeJsonUtils = new DecomposeJsonUtil()
+       private final HttpClientFactory httpClientFactory = new HttpClientFactory()
 
        /**
         * Validates the request message and sets up the workflow.
@@ -232,12 +240,37 @@ public class DoCreateVfModule extends VfModuleBase {
                                String globalSubscriberId = execution.getVariable("globalSubscriberId")
                                execution.setVariable("DCVFM_globalSubscriberId", globalSubscriberId)
                                msoLogger.debug("globalSubsrciberId: " + globalSubscriberId)
-                               //OofDirectives
-                               String oofDirectives = execution.getVariable("oofDirectives")
+
+                               // Set Homing Info
+                               String oofDirectives = null
+                               try {
+                                       HomingInstance homingInstance = oofInfraUtils.getHomingInstance(serviceInstanceId, execution)
+                                       if (homingInstance != null) {
+                                               execution.setVariable("DCVFM_cloudSiteId", homingInstance.getCloudRegionId())
+                                               rollbackData.put("VFMODULE", "aiccloudregion", homingInstance.getCloudRegionId())
+                                               msoLogger.debug("Overwriting cloudSiteId with homing cloudSiteId: " +
+                                                               homingInstance.getCloudRegionId())
+                                               execution.setVariable("DCVFM_cloudOwner", homingInstance.getCloudOwner())
+                                               rollbackData.put("VFMODULE", "cloudOwner", homingInstance.getCloudOwner())
+                                               msoLogger.debug("Overwriting cloudOwner with homing cloudOwner: " +
+                                                               homingInstance.getCloudOwner())
+                                               oofDirectives = homingInstance.getOofDirectives()
+                                               execution.setVariable("DCVFM_oofDirectives", oofDirectives)
+                                       }
+                               } catch (Exception exception) {
+                                       msoLogger.debug("Could not find homing information for service instance: " + serviceInstanceId +
+                                                       "... continuing")
+                                       msoLogger.debug("Could not find homing information for service instance error: " + exception)
+                               }
+                               //OofDirectives to Input Params
                                Map<String,String> vfModuleInputParams = execution.getVariable("vfModuleInputParams")
-                               if (oofDirectives != null) {
-                                       vfModuleInputParams.put("oofDirectives", oofDirectives)
-                                       logDebug("OofDirectives are: " + oofDirectives, isDebugLogEnabled)
+                               if (oofDirectives != null && vfModuleInputParams != null) {
+                                       vfModuleInputParams.put("oof_directives", oofDirectives)
+                                       vfModuleInputParams.put("sdnc_directives", "{}")
+                                       msoLogger.debug("OofDirectives are: " + oofDirectives)
+                               } else if (vfModuleInputParams != null) {
+                                       vfModuleInputParams.put("oof_directives", "{}")
+                                       vfModuleInputParams.put("sdnc_directives", "{}")
                                }
                                if (vfModuleInputParams != null) {
                                        execution.setVariable("DCVFM_vnfParamsMap", vfModuleInputParams)
@@ -258,7 +291,7 @@ public class DoCreateVfModule extends VfModuleBase {
                                String serviceType =""
 
                                try{
-                                       String json = catalog.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid )
+                                       String json = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid )
                                        serviceType = jsonUtil.getJsonValue(json, "serviceResources.serviceType")
                                }catch(BpmnError e){
                                        throw e
@@ -464,11 +497,30 @@ public class DoCreateVfModule extends VfModuleBase {
                                                        }
 
                                //OofDirectives
-                               String oofDirectives = execution.getVariable("oofDirectives")
+                               String oofDirectives = null
+                               try {
+                                       HomingInstance homingInstance = oofInfraUtils.getHomingInstance(serviceInstanceId, execution)
+                                       if (homingInstance != null) {
+                                               execution.setVariable("DCVFM_cloudSiteId", homingInstance.getCloudRegionId())
+                                               rollbackData.put("VFMODULE", "aiccloudregion", homingInstance.getCloudRegionId())
+                                               msoLogger.debug("Overwriting cloudSiteId with homing cloudSiteId: " +
+                                                               homingInstance.getCloudRegionId())
+                                               execution.setVariable("DCVFM_cloudOwner", homingInstance.getCloudOwner())
+                                               rollbackData.put("VFMODULE", "cloudOwner", homingInstance.getCloudOwner())
+                                               msoLogger.debug("Overwriting cloudOwner with homing cloudOwner: " +
+                                                               homingInstance.getCloudOwner())
+                                               oofDirectives = homingInstance.getOofDirectives()
+                                               execution.setVariable("DCVFM_oofDirectives", oofDirectives)
+                                       }
+                               } catch (Exception exception) {
+                                       msoLogger.debug("Could not find homing information for service instance: " + serviceInstanceId +
+                                                       "... continuing")
+                                       msoLogger.debug("Could not find homing information for service instance error: " + exception)
+                               }
                                if (oofDirectives != null) {
                                        Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap")
                                        paramsMap.put("oofDirectives", oofDirectives)
-                                       logDebug("OofDirectives are: " + oofDirectives, isDebugLogEnabled)
+                                       msoLogger.debug("OofDirectives are: " + oofDirectives)
                                        execution.setVariable("DCVFM_vnfParamsMap", paramsMap)
                                }
                        }
@@ -639,28 +691,26 @@ public class DoCreateVfModule extends VfModuleBase {
                        String endPoint = aaiUriUtil.createAaiUri(uri)
 
                        try {
-                               RESTConfig config = new RESTConfig(endPoint);
-                               def responseData = ''
-                               def aaiRequestId = UUID.randomUUID().toString()
-                               RESTClient client = new RESTClient(config).
-                                       addHeader('X-TransactionId', aaiRequestId).
-                                       addHeader('X-FromAppId', 'MSO').
-                                       addHeader('Content-Type', 'application/xml').
-                                       addHeader('Accept','application/xml');
+                               HttpClient client = httpClientFactory.newXmlClient(new URL(endPoint), TargetEntity.AAI)
+                               client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString())
+                               client.addAdditionalHeader('X-FromAppId', 'MSO')
+                               client.addAdditionalHeader('Content-Type', MediaType.APPLICATION_XML)
+                               client.addAdditionalHeader('Accept', MediaType.APPLICATION_XML)
+
                                msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
-                               APIResponse response = client.httpGet()
+                               Response response = client.get()
 
-                               responseData = response.getResponseBodyAsString()
+                               String responseData = response.readEntity(String.class)
                                if (responseData != null) {
                                        msoLogger.debug("Received generic VNF data: " + responseData)
 
                                }
 
-                               execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode())
+                               execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatus())
                                execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData)
-                               msoLogger.debug('Response code:' + response.getStatusCode())
+                               msoLogger.debug('Response code:' + response.getStatus())
                                msoLogger.debug('Response:' + System.lineSeparator() + responseData)
-                               if (response.getStatusCode() == 200) {
+                               if (response.getStatus() == 200) {
                                        // Parse the VNF record from A&AI to find base module info
                                        msoLogger.debug('Parsing the VNF data to find base module info')
                                        if (responseData != null) {
@@ -723,31 +773,31 @@ public class DoCreateVfModule extends VfModuleBase {
                        AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, vnfId).queryParam("vf-module-name",vfModuleName)
                        String endPoint = aaiUriUtil.createAaiUri(uri)
 
+                       HttpClient client = httpClientFactory.newXmlClient(new URL(endPoint), TargetEntity.AAI)
+                       client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString())
+                       client.addAdditionalHeader('X-FromAppId', 'MSO')
+                       client.addAdditionalHeader('Content-Type', MediaType.APPLICATION_XML)
+                       client.addAdditionalHeader('Accept', MediaType.APPLICATION_XML)
+
                        try {
-                               RESTConfig config = new RESTConfig(endPoint);
                                def responseData = ''
-                               def aaiRequestId = UUID.randomUUID().toString()
-                               RESTClient client = new RESTClient(config).
-                                       addHeader('X-TransactionId', aaiRequestId).
-                                       addHeader('X-FromAppId', 'MSO').
-                                       addHeader('Content-Type', 'application/xml').
-                                       addHeader('Accept','application/xml');
+
                                msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
-                               APIResponse response = client.httpGet()
+                               Response response = client.get()
                                msoLogger.debug("createVfModule - invoking httpGet() to AAI")
 
-                               responseData = response.getResponseBodyAsString()
+                               responseData = response.readEntity(String.class)
                                if (responseData != null) {
                                        msoLogger.debug("Received generic VNF data: " + responseData)
 
                                }
 
-                               execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponseCode', response.getStatusCode())
+                               execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponseCode', response.getStatus())
                                execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponse', responseData)
-                               msoLogger.debug('Response code:' + response.getStatusCode())
+                               msoLogger.debug('Response code:' + response.getStatus())
                                msoLogger.debug('Response:' + System.lineSeparator() + responseData)
                                // Retrieve VF Module info and its orchestration status; if not found, do nothing
-                               if (response.getStatusCode() == 200) {
+                               if (response.getStatus() == 200) {
                                        // Parse the VNF record from A&AI to find base module info
                                        msoLogger.debug('Parsing the VNF data to find orchestration status')
                                        if (responseData != null) {
@@ -1002,7 +1052,7 @@ public class DoCreateVfModule extends VfModuleBase {
                        svcInstId = serviceInstanceId
                }
 
-               def createVnfARequest = """
+               String createVnfARequest = """
                <createVfModuleRequest>
                <cloudSiteId>${MsoUtils.xmlEscape(cloudSiteId)}</cloudSiteId>
                <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
@@ -1861,50 +1911,17 @@ public class DoCreateVfModule extends VfModuleBase {
                                                def networkPolicyId = UUID.randomUUID().toString()
                                                msoLogger.debug("Adding network-policy with network-policy-id " + networkPolicyId)
 
-                                               String aaiNamespace = aaiUriUtil.getNamespace()
-                                               msoLogger.debug('AAI namespace is: ' + aaiNamespace)
-                                               String payload = """<network-policy xmlns="${aaiNamespace}">
-                                                               <network-policy-id>${MsoUtils.xmlEscape(networkPolicyId)}</network-policy-id>
-                                                               <network-policy-fqdn>${MsoUtils.xmlEscape(fqdn)}</network-policy-fqdn>
-                                                               <heat-stack-id>${MsoUtils.xmlEscape(execution.getVariable("DCVFM_heatStackId"))}</heat-stack-id>
-                                                               </network-policy>""" as String
-
-                                               execution.setVariable("DCVFM_addNetworkPolicyAAIRequestBody", payload)
-
-                                               AAIResourceUri addUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId)
-                                               String addNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(addUri)
-
-                                               msoLogger.debug("AAI request endpoint: " + addNetworkPolicyAAIRequest)
-
-                                               def aaiRequestIdPut = UUID.randomUUID().toString()
-                                               RESTConfig configPut = new RESTConfig(addNetworkPolicyAAIRequest);
-                                               RESTClient clientPut = new RESTClient(configPut).addHeader("X-TransactionId", aaiRequestIdPut)
-                                                               .addHeader("X-FromAppId", "MSO")
-                                                               .addHeader("Content-Type", "application/xml")
-                                                               .addHeader("Accept","application/xml");
-                                               msoLogger.debug("invoking PUT call to AAI with payload:"+System.lineSeparator()+payload)
-                                               APIResponse responsePut = clientPut.httpPut(payload)
-                                               int returnCodePut = responsePut.getStatusCode()
-                                               execution.setVariable("DCVFM_aaiAddNetworkPolicyReturnCode", returnCodePut)
-                                               msoLogger.debug(" ***** AAI add network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodePut)
-
-                                               String aaiResponseAsStringPut = responsePut.getResponseBodyAsString()
-                                               if (isOneOf(returnCodePut, 200, 201)) {
-                                                       msoLogger.debug("The return code from adding network policy is: "  + returnCodePut)
-                                                       // This network policy was created in AAI successfully
-                                                       execution.setVariable("DCVFM_addNetworkPolicyAAIResponse", aaiResponseAsStringPut)
-                                                       msoLogger.debug(" AddAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsStringPut)
-                                                       rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true")
-                                                       rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn" + i, fqdn)
-                                                       execution.setVariable("rollbackData", rollbackData)
-
-                                               } else {
-                                                       // aai all errors
-                                                       String putErrorMessage = "Unable to add network-policy to AAI createNetworkPoliciesInAAI - " + returnCodePut
-                                                       msoLogger.debug(putErrorMessage)
-                                                       exceptionUtil.buildAndThrowWorkflowException(execution, 2500, putErrorMessage)
-                                               }
-
+                                               NetworkPolicy policy = new NetworkPolicy()
+                                               policy.setNetworkPolicyId(networkPolicyId)
+                                               policy.setNetworkPolicyFqdn(fqdn)
+                                               policy.setHeatStackId(execution.getVariable("DCVFM_heatStackId"))
+                                               
+                                               AAIResourceUri netUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId)
+                                               resourceClient.create(netUri, policy)
+
+                                               rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true")
+                                               rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn" + i, fqdn)
+                                               execution.setVariable("rollbackData", rollbackData)
                                        }
 
                                } // end loop
@@ -1917,7 +1934,6 @@ public class DoCreateVfModule extends VfModuleBase {
 
           } catch (BpmnError e) {
                   throw e;
-
           } catch (Exception ex) {
                   String exceptionMessage = "Bpmn error encountered in DoCreateVfModule flow. createNetworkPoliciesInAAI() - " + ex.getMessage()
                   msoLogger.debug(exceptionMessage)
@@ -2037,7 +2053,7 @@ public class DoCreateVfModule extends VfModuleBase {
 
                   msoLogger.debug("vnfModelCustomizationUuid: " + vnfModelCustomizationUuid)
 
-                  JSONArray vnfs = catalog.getAllVnfsByVnfModelCustomizationUuid(execution, vnfModelCustomizationUuid, "v2")
+                  JSONArray vnfs = catalogDbUtils.getAllVnfsByVnfModelCustomizationUuid(execution, vnfModelCustomizationUuid, "v2")
 
                   msoLogger.debug("Incoming Query Catalog DB for Vnf Response is: " + vnfModelCustomizationUuid)
                   // Only one match here