Search in sources :

Example 41 with MsoException

use of org.onap.so.openstack.exceptions.MsoException in project so by onap.

the class MsoNetworkAdapterImpl method createNetwork.

/**
 * This is the "Create Network" web service implementation. It will create a new Network of the requested type in
 * the specified cloud and tenant. The tenant must exist at the time this service is called.
 *
 * If a network with the same name already exists, this can be considered a success or failure, depending on the
 * value of the 'failIfExists' parameter.
 *
 * There will be a pre-defined set of network types defined in the MSO Catalog. All such networks will have a
 * similar configuration, based on the allowable Openstack networking definitions. This includes basic networks,
 * provider networks (with a single VLAN), and multi-provider networks (one or more VLANs)
 *
 * Initially, all provider networks must be "vlan" type, and multiple segments in a multi-provider network must be
 * multiple VLANs on the same physical network.
 *
 * This service supports two modes of Network creation/update: - via Heat Templates - via Neutron API The network
 * orchestration mode for each network type is declared in its catalog definition. All Heat-based templates must
 * support some subset of the same input parameters: network_name, physical_network, vlan(s).
 *
 * The method returns the network ID and a NetworkRollback object. This latter object can be passed as-is to the
 * rollbackNetwork operation to undo everything that was created. This is useful if a network is successfully
 * created but the orchestration fails on a subsequent operation.
 */
public void createNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid, String networkName, String physicalNetworkName, List<Integer> vlans, List<RouteTarget> routeTargets, String shared, String external, Boolean failIfExists, Boolean backout, List<Subnet> subnets, List<String> policyFqdns, List<String> routeTableFqdns, MsoRequest msoRequest, Holder<String> stackId, MutableBoolean isOs3Nw) throws NetworkException {
    logger.debug("*** CREATE Network: {} of type {} in {}/{}", networkName, networkType, cloudSiteId, tenantId);
    // Will capture execution time for metrics
    long startTime = System.currentTimeMillis();
    Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
    if (!cloudSiteOpt.isPresent()) {
        String error = String.format("Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration", networkName, cloudSiteId, tenantId);
        logger.error(LoggingAnchor.THREE, MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error);
        // Set the detailed error as the Exception 'message'
        throw new NetworkException(error, MsoExceptionCategory.USERDATA);
    }
    NetworkResource networkResource = networkCheck(startTime, networkType, modelCustomizationUuid, networkName, physicalNetworkName, vlans, routeTargets, cloudSiteId, cloudSiteOpt.get());
    NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType());
    HeatTemplate heatTemplate = networkResource.getHeatTemplate();
    if (heatTemplate == null) {
        String error = String.format("Network error - undefined Heat Template. Network Type = %s", networkType);
        logger.error(LoggingAnchor.THREE, MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(), error);
        throw new NetworkException(error, MsoExceptionCategory.INTERNAL);
    }
    logger.debug("Got HEAT Template from DB: {}", heatTemplate);
    // "Fix" the template if it has CR/LF (getting this from Oracle)
    String template = heatTemplate.getHeatTemplate();
    template = template.replaceAll("\r\n", "\n");
    boolean os3template = false;
    String os3nw = environment.getProperty(OS3_NW_PROPERTY, OS3_NW);
    if (template.contains(os3nw))
        os3template = true;
    isOs3Nw.setValue(os3template);
    // First, look up to see if the Network already exists (by name).
    // For HEAT orchestration of networks, the stack name will always match the network name
    StackInfo heatStack = null;
    try {
        heatStack = heat.queryStack(cloudSiteId, CLOUD_OWNER, tenantId, networkName);
    } catch (MsoException me) {
        me.addContext(CREATE_NETWORK_CONTEXT);
        logger.error("{} {} Create Network (heat): query network {} in {}/{}: ", MessageEnum.RA_QUERY_NETWORK_EXC, ErrorCode.DataError.getValue(), networkName, cloudSiteId, tenantId, me);
        throw new NetworkException(me);
    }
    if (heatStack != null && (heatStack.getStatus() != HeatStatus.NOTFOUND)) {
        // Stack exists. Return success or error depending on input directive
        if (failIfExists != null && failIfExists) {
            String error = String.format("CreateNetwork: Stack %s already exists in %s/%s as %s", networkName, cloudSiteId, tenantId, heatStack.getCanonicalName());
            logger.error(LoggingAnchor.THREE, MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), error);
            throw new NetworkException(error, MsoExceptionCategory.USERDATA);
        } else {
            logger.warn("{} {} Found Existing network stack, status={} networkName={} for {}/{}", MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), heatStack.getStatus(), networkName, cloudSiteId, tenantId);
        }
        heat.updateResourceStatus(msoRequest.getRequestId(), NETWORK_EXIST_STATUS_MESSAGE);
        return;
    }
    // Ready to deploy the new Network
    // Build the common set of HEAT template parameters
    Map<String, Object> stackParams = populateNetworkParams(neutronNetworkType, networkName, physicalNetworkName, vlans, routeTargets, shared, external, os3template);
    // and inputs were already validated.
    try {
        stackParams = heat.validateStackParams(stackParams, heatTemplate);
    } catch (IllegalArgumentException e) {
        String error = "Create Network: Configuration Error: " + e.getMessage();
        logger.error(LoggingAnchor.THREE, MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error, e);
        // Input parameters were not valid
        throw new NetworkException(error, MsoExceptionCategory.INTERNAL);
    }
    if (subnets != null) {
        try {
            if (os3template) {
                template = mergeSubnetsAIC3(template, subnets, stackParams);
            } else {
                template = mergeSubnets(template, subnets);
            }
        } catch (MsoException me) {
            me.addContext(CREATE_NETWORK_CONTEXT);
            logger.error("{} {} Exception Create Network, merging subnets for network (heat) type {} in {}/{} ", MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(), neutronNetworkType.toString(), cloudSiteId, tenantId, me);
            throw new NetworkException(me);
        }
    }
    if (policyFqdns != null && !policyFqdns.isEmpty() && os3template) {
        try {
            mergePolicyRefs(policyFqdns, stackParams);
        } catch (MsoException me) {
            me.addContext(CREATE_NETWORK_CONTEXT);
            logger.error("{} {} Exception Create Network, merging policyRefs type {} in {}/{} ", MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(), neutronNetworkType.toString(), cloudSiteId, tenantId, me);
            throw new NetworkException(me);
        }
    }
    if (routeTableFqdns != null && !routeTableFqdns.isEmpty() && os3template) {
        try {
            mergeRouteTableRefs(routeTableFqdns, stackParams);
        } catch (MsoException me) {
            me.addContext(CREATE_NETWORK_CONTEXT);
            logger.error("{} {} Exception Create Network, merging routeTableRefs type {} in {}/{} ", MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(), neutronNetworkType.toString(), cloudSiteId, tenantId, me);
            throw new NetworkException(me);
        }
    }
    // Ignore MsoStackAlreadyExists exception because we already checked.
    try {
        if (backout == null)
            backout = true;
        heatStack = heat.createStack(cloudSiteId, CLOUD_OWNER, tenantId, networkName, null, template, stackParams, false, heatTemplate.getTimeoutMinutes(), null, null, null, backout.booleanValue(), failIfExists);
    } catch (MsoException me) {
        me.addContext(CREATE_NETWORK_CONTEXT);
        logger.error("{} {} Exception creating network type {} in {}/{} ", MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(), networkName, cloudSiteId, tenantId, me);
        throw new NetworkException(me);
    }
    // Reach this point if createStack is successful.
    stackId.value = heatStack.getCanonicalName();
    try {
        heat.updateResourceStatus(msoRequest.getRequestId(), NETWORK_CREATED_STATUS_MESSAGE);
    } catch (Exception e) {
        logger.warn("Exception while updating infra active request", e);
    }
    logger.debug("Network {} successfully created via HEAT", networkName);
    return;
}
Also used : MsoException(org.onap.so.openstack.exceptions.MsoException) NetworkException(org.onap.so.adapters.network.exceptions.NetworkException) MsoException(org.onap.so.openstack.exceptions.MsoException) MsoAdapterException(org.onap.so.openstack.exceptions.MsoAdapterException) NetworkResource(org.onap.so.db.catalog.beans.NetworkResource) NetworkType(org.onap.so.openstack.utils.MsoNeutronUtils.NetworkType) HeatTemplate(org.onap.so.db.catalog.beans.HeatTemplate) CloudSite(org.onap.so.db.catalog.beans.CloudSite) NetworkException(org.onap.so.adapters.network.exceptions.NetworkException) StackInfo(org.onap.so.openstack.beans.StackInfo)

Example 42 with MsoException

use of org.onap.so.openstack.exceptions.MsoException in project so by onap.

the class MsoNetworkAdapterImpl method deleteNetwork.

/**
 * This is the "Delete Network" web service implementation. It will delete a Network in the specified cloud and
 * tenant.
 *
 * If the network is not found, it is treated as a success.
 *
 * This service supports two modes of Network creation/update/delete: - via Heat Templates - via Neutron API The
 * network orchestration mode for each network type is declared in its catalog definition.
 *
 * For Heat-based orchestration, the networkId should be the stack ID. For Neutron-based orchestration, the
 * networkId should be the Neutron network UUID.
 *
 * The method returns nothing on success. Rollback is not possible for delete commands, so any failure on delete
 * will require manual fallout in the client.
 */
public void deleteNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid, String networkId, MsoRequest msoRequest) throws NetworkException {
    logger.debug("*** DELETE Network adapter with Network: {} in {}/{}", networkId, cloudSiteId, tenantId);
    if (commonUtils.isNullOrEmpty(cloudSiteId) || commonUtils.isNullOrEmpty(tenantId) || commonUtils.isNullOrEmpty(networkId)) {
        String error = "Missing mandatory parameter cloudSiteId, tenantId or networkId";
        logger.error(LoggingAnchor.THREE, MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error);
        throw new NetworkException(error, MsoExceptionCategory.USERDATA);
    }
    int timeoutMinutes = heat.getNetworkHeatTimeoutValue(modelCustomizationUuid, networkType);
    boolean networkDeleted = false;
    try {
        StackInfo stack = heat.deleteStack(tenantId, CLOUD_OWNER, cloudSiteId, networkId, false, timeoutMinutes);
        networkDeleted = stack.isOperationPerformed();
    } catch (MsoException me) {
        me.addContext("DeleteNetwork");
        logger.error("{} {} Delete Network (heat): {} in {}/{} ", MessageEnum.RA_DELETE_NETWORK_EXC, ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me);
        throw new NetworkException(me);
    }
    try {
        heat.updateResourceStatus(msoRequest.getRequestId(), networkDeleted ? NETWORK_DELETED_STATUS_MESSAGE : NETWORK_NOT_EXIST_STATUS_MESSAGE);
    } catch (Exception e) {
        logger.warn("Exception while updating infra active request", e);
    }
}
Also used : MsoException(org.onap.so.openstack.exceptions.MsoException) NetworkException(org.onap.so.adapters.network.exceptions.NetworkException) StackInfo(org.onap.so.openstack.beans.StackInfo) NetworkException(org.onap.so.adapters.network.exceptions.NetworkException) MsoException(org.onap.so.openstack.exceptions.MsoException) MsoAdapterException(org.onap.so.openstack.exceptions.MsoAdapterException)

Example 43 with MsoException

use of org.onap.so.openstack.exceptions.MsoException in project so by onap.

the class MsoNetworkAdapterImpl method mergePolicyRefs.

/**
 * policyRef_list structure in stackParams [ { "network_policy_refs_data_sequence": {
 * "network_policy_refs_data_sequence_major": "1", "network_policy_refs_data_sequence_minor": "0" } }, {
 * "network_policy_refs_data_sequence": { "network_policy_refs_data_sequence_major": "2",
 * "network_policy_refs_data_sequence_minor": "0" } } ]
 */
private void mergePolicyRefs(List<String> pFqdns, Map<String, Object> stackParams) throws MsoException {
    // Resource Property
    List<ContrailPolicyRef> prlist = new ArrayList<>();
    int index = 1;
    if (pFqdns != null) {
        for (String pf : pFqdns) {
            if (!commonUtils.isNullOrEmpty(pf)) {
                ContrailPolicyRef pr = new ContrailPolicyRef();
                ContrailPolicyRefSeq refSeq = new ContrailPolicyRefSeq(String.valueOf(index), "0");
                pr.setSeq(refSeq);
                index++;
                logger.debug("Contrail PolicyRefs Data:{}", pr);
                prlist.add(pr);
            }
        }
    } else {
        String error = "Null pFqdns at start of mergePolicyRefs";
        logger.error(LoggingAnchor.THREE, MessageEnum.RA_MARSHING_ERROR, ErrorCode.BusinessProcessError.getValue(), error);
        throw new MsoAdapterException(error);
    }
    JsonNode node = null;
    try {
        ObjectMapper mapper = new ObjectMapper();
        node = mapper.convertValue(prlist, JsonNode.class);
        String jsonString = mapper.writeValueAsString(prlist);
        logger.debug("Json PolicyRefs Data:{}", jsonString);
    } catch (Exception e) {
        String error = "Error creating JsonNode for policyRefs Data";
        logger.error(LoggingAnchor.THREE, MessageEnum.RA_MARSHING_ERROR, ErrorCode.BusinessProcessError.getValue(), error, e);
        throw new MsoAdapterException(error);
    }
    // update parameters
    if (pFqdns != null && node != null) {
        StringBuilder buf = new StringBuilder();
        String sep = "";
        for (String pf : pFqdns) {
            if (!commonUtils.isNullOrEmpty(pf)) {
                buf.append(sep).append(pf);
                sep = ",";
            }
        }
        String csl = buf.toString();
        stackParams.put("policy_refs", csl);
        stackParams.put("policy_refsdata", node);
    }
    logger.debug("StackParams updated with policy refs");
    return;
}
Also used : MsoAdapterException(org.onap.so.openstack.exceptions.MsoAdapterException) ContrailPolicyRefSeq(org.onap.so.adapters.network.beans.ContrailPolicyRefSeq) ContrailPolicyRef(org.onap.so.adapters.network.beans.ContrailPolicyRef) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NetworkException(org.onap.so.adapters.network.exceptions.NetworkException) MsoException(org.onap.so.openstack.exceptions.MsoException) MsoAdapterException(org.onap.so.openstack.exceptions.MsoAdapterException)

Example 44 with MsoException

use of org.onap.so.openstack.exceptions.MsoException in project so by onap.

the class MsoCommonUtilsTest method testKeystoneErrorToMsoException.

@Test
public final void testKeystoneErrorToMsoException() throws JsonParseException, JsonMappingException, IOException {
    OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
    OpenStackBaseException openStackResponseException = new OpenStackResponseException("response", 1);
    MsoException me = commonUtils.keystoneErrorToMsoException(openStackConnectException, "ContextError");
    assertTrue(me instanceof MsoIOException);
    assertTrue("connect".equals(me.getMessage()));
    MsoException me2 = commonUtils.keystoneErrorToMsoException(openStackResponseException, "ContextError");
    assertTrue(me2 instanceof MsoOpenstackException);
    assertTrue("ContextError".equals(me2.getContext()));
    assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
    OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
    Error error = mapper.readValue(new File(RESOURCE_PATH + "Error.json"), Error.class);
    doReturn(error).when(openStackResponse).getErrorEntity(eq(Error.class));
    openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
    MsoException me3 = commonUtils.keystoneErrorToMsoException(openStackResponseException, "ContextError");
    assertTrue(me3 instanceof MsoOpenstackException);
    assertEquals("1 title: message", me3.toString());
}
Also used : OpenStackResponse(com.woorea.openstack.base.client.OpenStackResponse) MsoException(org.onap.so.openstack.exceptions.MsoException) OpenStackResponseException(com.woorea.openstack.base.client.OpenStackResponseException) OpenStackBaseException(com.woorea.openstack.base.client.OpenStackBaseException) NeutronError(com.woorea.openstack.quantum.model.NeutronError) Error(com.woorea.openstack.keystone.model.Error) MsoIOException(org.onap.so.openstack.exceptions.MsoIOException) OpenStackConnectException(com.woorea.openstack.base.client.OpenStackConnectException) File(java.io.File) MsoOpenstackException(org.onap.so.openstack.exceptions.MsoOpenstackException) Test(org.junit.Test) BaseTest(org.onap.so.BaseTest)

Example 45 with MsoException

use of org.onap.so.openstack.exceptions.MsoException in project so by onap.

the class MsoCommonUtilsTest method testIoExceptionToMsoException.

@Test
public void testIoExceptionToMsoException() {
    IOException exception = new IOException("IOExceptionTestMessage");
    MsoException msoException = commonUtils.ioExceptionToMsoException(exception, "ContextError");
    assertTrue(msoException instanceof MsoAdapterException);
    assertEquals("ContextError", msoException.getContext());
    assertTrue(MsoExceptionCategory.INTERNAL.equals(msoException.getCategory()));
}
Also used : MsoException(org.onap.so.openstack.exceptions.MsoException) MsoAdapterException(org.onap.so.openstack.exceptions.MsoAdapterException) IOException(java.io.IOException) MsoIOException(org.onap.so.openstack.exceptions.MsoIOException) Test(org.junit.Test) BaseTest(org.onap.so.BaseTest)

Aggregations

MsoException (org.onap.so.openstack.exceptions.MsoException)53 OpenStackBaseException (com.woorea.openstack.base.client.OpenStackBaseException)12 CloudSite (org.onap.so.db.catalog.beans.CloudSite)12 MsoAdapterException (org.onap.so.openstack.exceptions.MsoAdapterException)12 Nova (com.woorea.openstack.nova.Nova)10 StackInfo (org.onap.so.openstack.beans.StackInfo)10 Quantum (com.woorea.openstack.quantum.Quantum)9 MsoOpenstackException (org.onap.so.openstack.exceptions.MsoOpenstackException)9 OpenStackConnectException (com.woorea.openstack.base.client.OpenStackConnectException)8 OpenStackResponseException (com.woorea.openstack.base.client.OpenStackResponseException)8 ArrayList (java.util.ArrayList)8 Test (org.junit.Test)8 BaseTest (org.onap.so.BaseTest)7 MsoIOException (org.onap.so.openstack.exceptions.MsoIOException)7 HashMap (java.util.HashMap)6 VnfException (org.onap.so.adapters.vnf.exceptions.VnfException)6 MsoCloudSiteNotFound (org.onap.so.openstack.exceptions.MsoCloudSiteNotFound)6 IOException (java.io.IOException)5 NetworkException (org.onap.so.adapters.network.exceptions.NetworkException)5 HeatTemplate (org.onap.so.db.catalog.beans.HeatTemplate)5