Search in sources :

Example 1 with MsoAdapterException

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

the class MsoKeystoneUtils method createTenant.

/**
 * Create a tenant with the specified name in the given cloud. If the tenant already exists, an Exception will be
 * thrown. The MSO User will also be added to the "member" list of the new tenant to perform subsequent Nova/Heat
 * commands in the tenant. If the MSO User association fails, the entire transaction will be rolled back.
 * <p>
 * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin requests go to the centralized
 * identity service in DCP. However, if some artifact must exist in each local LCP instance as well, then it will be
 * needed to access the correct region.
 * <p>
 *
 * @param tenantName The tenant name to create
 * @param cloudSiteId The cloud identifier (may be a region) in which to create the tenant.
 * @return the tenant ID of the newly created tenant
 * @throws MsoTenantAlreadyExists Thrown if the requested tenant already exists
 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
 */
public String createTenant(String tenantName, String cloudSiteId, Map<String, String> metadata, boolean backout) throws MsoException {
    // Obtain the cloud site information where we will create the tenant
    Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
    if (!cloudSiteOpt.isPresent()) {
        LOGGER.error("{} MSOCloudSite {} not found {} ", MessageEnum.RA_CREATE_TENANT_ERR, cloudSiteId, ErrorCode.DataError.getValue());
        throw new MsoCloudSiteNotFound(cloudSiteId);
    }
    Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSiteOpt.get());
    Tenant tenant = null;
    try {
        // Check if the tenant already exists
        tenant = findTenantByName(keystoneAdminClient, tenantName);
        if (tenant != null) {
            // Tenant already exists. Throw an exception
            LOGGER.error("{} Tenant name {} already exists on Cloud site id {}, {}", MessageEnum.RA_TENANT_ALREADY_EXIST, tenantName, cloudSiteId, ErrorCode.DataError.getValue());
            throw new MsoTenantAlreadyExists(tenantName, cloudSiteId);
        }
        // Does not exist, create a new one
        tenant = new Tenant();
        tenant.setName(tenantName);
        tenant.setDescription("SDN Tenant (via MSO)");
        tenant.setEnabled(true);
        OpenStackRequest<Tenant> request = keystoneAdminClient.tenants().create(tenant);
        tenant = executeAndRecordOpenstackRequest(request);
    } catch (OpenStackBaseException e) {
        // Convert Keystone OpenStackResponseException to MsoOpenstackException
        throw keystoneErrorToMsoException(e, "CreateTenant");
    } catch (RuntimeException e) {
        // Catch-all
        throw runtimeExceptionToMsoException(e, "CreateTenant");
    }
    // apply tenant metadata if supported by the cloud site
    try {
        CloudIdentity cloudIdentity = cloudSiteOpt.get().getIdentityService();
        User msoUser = findUserByNameOrId(keystoneAdminClient, cloudIdentity.getMsoId());
        Role memberRole = findRoleByNameOrId(keystoneAdminClient, cloudIdentity.getMemberRole());
        if (msoUser != null && memberRole != null) {
            OpenStackRequest<Void> request = keystoneAdminClient.tenants().addUser(tenant.getId(), msoUser.getId(), memberRole.getId());
            executeAndRecordOpenstackRequest(request);
        }
        if (cloudIdentity.getTenantMetadata() && metadata != null && !metadata.isEmpty()) {
            Metadata tenantMetadata = new Metadata();
            tenantMetadata.setMetadata(metadata);
            OpenStackRequest<Metadata> metaRequest = keystoneAdminClient.tenants().createOrUpdateMetadata(tenant.getId(), tenantMetadata);
            executeAndRecordOpenstackRequest(metaRequest);
        }
    } catch (Exception e) {
        // so roll back the tenant.
        if (!backout) {
            LOGGER.warn("{} Create Tenant errored, Tenant deletion suppressed {} ", MessageEnum.RA_CREATE_TENANT_ERR, ErrorCode.DataError.getValue());
        } else {
            try {
                OpenStackRequest<Void> request = keystoneAdminClient.tenants().delete(tenant.getId());
                executeAndRecordOpenstackRequest(request);
            } catch (Exception e2) {
                // Just log this one. We will report the original exception.
                LOGGER.error("{} Nested exception rolling back tenant {} ", MessageEnum.RA_CREATE_TENANT_ERR, ErrorCode.DataError.getValue(), e2);
            }
        }
        // Propagate the original exception on user/role/tenant mapping
        if (e instanceof OpenStackBaseException) {
            // Convert Keystone Exception to MsoOpenstackException
            throw keystoneErrorToMsoException((OpenStackBaseException) e, "CreateTenantUser");
        } else {
            MsoAdapterException me = new MsoAdapterException(e.getMessage(), e);
            me.addContext("CreateTenantUser");
            throw me;
        }
    }
    return tenant.getId();
}
Also used : MsoCloudSiteNotFound(org.onap.so.openstack.exceptions.MsoCloudSiteNotFound) MsoTenantAlreadyExists(org.onap.so.openstack.exceptions.MsoTenantAlreadyExists) User(com.woorea.openstack.keystone.model.User) OpenStackBaseException(com.woorea.openstack.base.client.OpenStackBaseException) CloudIdentity(org.onap.so.db.catalog.beans.CloudIdentity) Metadata(com.woorea.openstack.keystone.model.Metadata) OpenStackRequest(com.woorea.openstack.base.client.OpenStackRequest) MsoAdapterException(org.onap.so.openstack.exceptions.MsoAdapterException) OpenStackBaseException(com.woorea.openstack.base.client.OpenStackBaseException) MsoOpenstackException(org.onap.so.openstack.exceptions.MsoOpenstackException) OpenStackConnectException(com.woorea.openstack.base.client.OpenStackConnectException) OpenStackResponseException(com.woorea.openstack.base.client.OpenStackResponseException) MsoException(org.onap.so.openstack.exceptions.MsoException) Role(com.woorea.openstack.keystone.model.Role) MsoTenant(org.onap.so.openstack.beans.MsoTenant) Tenant(com.woorea.openstack.keystone.model.Tenant) MsoAdapterException(org.onap.so.openstack.exceptions.MsoAdapterException) Keystone(com.woorea.openstack.keystone.Keystone) CloudSite(org.onap.so.db.catalog.beans.CloudSite)

Example 2 with MsoAdapterException

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

the class MsoKeystoneUtils method getKeystoneAdminClient.

// -------------------------------------------------------------------
// PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
/*
     * Get a Keystone Admin client for the Openstack Identity service. This requires an 'admin'-level userId + password
     * along with an 'admin' tenant in the target cloud. These values will be retrieved from properties based on the
     * specified cloud ID. <p> On successful authentication, the Keystone object will be cached for the cloudId so that
     * it can be reused without going back to Openstack every time.
     *
     * @param cloudId
     *
     * @return an authenticated Keystone object
     */
public Keystone getKeystoneAdminClient(CloudSite cloudSite) throws MsoException {
    CloudIdentity cloudIdentity = cloudSite.getIdentityService();
    String adminTenantName = cloudIdentity.getAdminTenant();
    String region = cloudSite.getRegionId();
    MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
    final String keystoneUrl = tenantUtils.getKeystoneUrl(region, cloudIdentity);
    Keystone keystone = new Keystone(keystoneUrl);
    // Must authenticate against the 'admin' tenant to get the services endpoints
    Access access = null;
    String token = null;
    try {
        Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
        OpenStackRequest<Access> request = keystone.tokens().authenticate(credentials).withTenantName(adminTenantName);
        access = executeAndRecordOpenstackRequest(request);
        token = access.getToken().getId();
    } catch (OpenStackResponseException e) {
        if (e.getStatus() == 401) {
            // Authentication error. Can't access admin tenant - something is mis-configured
            String error = "MSO Authentication Failed for " + cloudIdentity.getId();
            throw new MsoAdapterException(error);
        } else {
            throw keystoneErrorToMsoException(e, "TokenAuth");
        }
    } catch (OpenStackConnectException e) {
        // Connection to Openstack failed
        throw keystoneErrorToMsoException(e, "TokenAuth");
    }
    // Get the Identity service URL. Throws runtime exception if not found per region.
    String adminUrl = null;
    try {
        adminUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "identity", region, "public");
        adminUrl = adminUrl.replaceFirst("5000", "35357");
    } catch (RuntimeException e) {
        String error = "Identity service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
        LOGGER.error("{} Region: {} Cloud identity {} {} Exception in findEndpointURL ", MessageEnum.IDENTITY_SERVICE_NOT_FOUND, region, cloudIdentity.getId(), ErrorCode.DataError.getValue(), e);
        throw new MsoAdapterException(error, e);
    }
    // A new Keystone object is required for the new URL. Use the auth token from above.
    // Note: this doesn't go back to Openstack, it's just a local object.
    keystone = new Keystone(adminUrl);
    keystone.token(token);
    return keystone;
}
Also used : MsoAdapterException(org.onap.so.openstack.exceptions.MsoAdapterException) Keystone(com.woorea.openstack.keystone.Keystone) OpenStackResponseException(com.woorea.openstack.base.client.OpenStackResponseException) Authentication(com.woorea.openstack.keystone.model.Authentication) CloudIdentity(org.onap.so.db.catalog.beans.CloudIdentity) Access(com.woorea.openstack.keystone.model.Access) OpenStackConnectException(com.woorea.openstack.base.client.OpenStackConnectException)

Example 3 with MsoAdapterException

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

the class MsoNeutronUtils method getNeutronClient.

// -------------------------------------------------------------------
// PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
/**
 * Get a Neutron (Quantum) client for the Openstack Network service. This requires a 'member'-level userId +
 * password, which will be retrieved from properties based on the specified cloud Id. The tenant in which to operate
 * must also be provided.
 * <p>
 * On successful authentication, the Quantum object will be cached for the tenantID + cloudId so that it can be
 * reused without reauthenticating with Openstack every time.
 *
 * @param cloudSite - a cloud site definition
 * @param tenantId - Openstack tenant ID
 * @return an authenticated Quantum object
 */
private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException {
    String cloudId = cloudSite.getId();
    String region = cloudSite.getRegionId();
    // Obtain an MSO token for the tenant from the identity service
    CloudIdentity cloudIdentity = cloudSite.getIdentityService();
    MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
    final String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
    String neutronUrl = null;
    String tokenId = null;
    try {
        if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
            Keystone keystoneTenantClient = new Keystone(keystoneUrl);
            Access access = null;
            Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
            OpenStackRequest<Access> request = keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
            access = executeAndRecordOpenstackRequest(request, true);
            try {
                neutronUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "network", region, "public");
                if (!neutronUrl.endsWith("/")) {
                    neutronUrl += "/v2.0/";
                }
            } catch (RuntimeException e) {
                // This comes back for not found (probably an incorrect region ID)
                String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
                throw new MsoAdapterException(error, e);
            }
            tokenId = access.getToken().getId();
        } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
            try {
                KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "network");
                tokenId = holder.getId();
                neutronUrl = holder.getServiceUrl();
                if (!neutronUrl.endsWith("/")) {
                    neutronUrl += "/v2.0/";
                }
            } catch (ServiceEndpointNotFoundException e) {
                // This comes back for not found (probably an incorrect region ID)
                String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
                throw new MsoAdapterException(error, e);
            }
        }
    } catch (OpenStackResponseException e) {
        if (e.getStatus() == 401) {
            // Authentication error.
            String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
            throw new MsoAdapterException(error);
        } else {
            MsoException me = keystoneErrorToMsoException(e, "TokenAuth");
            throw me;
        }
    } catch (OpenStackConnectException e) {
        // Connection to Openstack failed
        MsoIOException me = new MsoIOException(e.getMessage(), e);
        me.addContext("TokenAuth");
        throw me;
    } catch (RuntimeException e) {
        // Catch-all
        MsoException me = runtimeExceptionToMsoException(e, "TokenAuth");
        throw me;
    }
    Quantum neutronClient = new Quantum(neutronUrl);
    neutronClient.token(tokenId);
    return neutronClient;
}
Also used : MsoException(org.onap.so.openstack.exceptions.MsoException) CloudIdentity(org.onap.so.db.catalog.beans.CloudIdentity) Access(com.woorea.openstack.keystone.model.Access) KeystoneAuthHolder(org.onap.so.cloud.authentication.KeystoneAuthHolder) Quantum(com.woorea.openstack.quantum.Quantum) MsoAdapterException(org.onap.so.openstack.exceptions.MsoAdapterException) ServiceEndpointNotFoundException(org.onap.so.cloud.authentication.ServiceEndpointNotFoundException) Keystone(com.woorea.openstack.keystone.Keystone) OpenStackResponseException(com.woorea.openstack.base.client.OpenStackResponseException) KeystoneV3Authentication(org.onap.so.cloud.authentication.KeystoneV3Authentication) Authentication(com.woorea.openstack.keystone.model.Authentication) MsoIOException(org.onap.so.openstack.exceptions.MsoIOException) OpenStackConnectException(com.woorea.openstack.base.client.OpenStackConnectException)

Example 4 with MsoAdapterException

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

the class MsoCommonUtils method runtimeExceptionToMsoException.

/*
     * Convert a Java Runtime Exception to an MsoException. All Runtime exceptions will be translated into an
     * MsoAdapterException, which captures internal errors. Alarms will be generated on all such exceptions.
     */
protected MsoException runtimeExceptionToMsoException(RuntimeException e, String context) {
    MsoAdapterException me = new MsoAdapterException(e.getMessage(), e);
    me.addContext(context);
    me.setCategory(MsoExceptionCategory.INTERNAL);
    // Always generate an alarm for internal exceptions
    logger.error("{} {} An exception occured on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG, ErrorCode.DataError.getValue(), context, e);
    return me;
}
Also used : MsoAdapterException(org.onap.so.openstack.exceptions.MsoAdapterException)

Example 5 with MsoAdapterException

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

the class MsoCommonUtils method ioExceptionToMsoException.

protected MsoException ioExceptionToMsoException(IOException e, String context) {
    MsoAdapterException me = new MsoAdapterException(e.getMessage(), e);
    me.addContext(context);
    me.setCategory(MsoExceptionCategory.INTERNAL);
    // Always generate an alarm for internal exceptions
    logger.error("{} {} An exception occured on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG, ErrorCode.DataError.getValue(), context, e);
    return me;
}
Also used : MsoAdapterException(org.onap.so.openstack.exceptions.MsoAdapterException)

Aggregations

MsoAdapterException (org.onap.so.openstack.exceptions.MsoAdapterException)11 MsoException (org.onap.so.openstack.exceptions.MsoException)6 OpenStackConnectException (com.woorea.openstack.base.client.OpenStackConnectException)4 OpenStackResponseException (com.woorea.openstack.base.client.OpenStackResponseException)4 CloudIdentity (org.onap.so.db.catalog.beans.CloudIdentity)4 Keystone (com.woorea.openstack.keystone.Keystone)3 Access (com.woorea.openstack.keystone.model.Access)3 MsoIOException (org.onap.so.openstack.exceptions.MsoIOException)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Authentication (com.woorea.openstack.keystone.model.Authentication)2 ArrayList (java.util.ArrayList)2 Test (org.junit.Test)2 BaseTest (org.onap.so.BaseTest)2 ContrailSubnet (org.onap.so.adapters.network.beans.ContrailSubnet)2 NetworkException (org.onap.so.adapters.network.exceptions.NetworkException)2 KeystoneAuthHolder (org.onap.so.cloud.authentication.KeystoneAuthHolder)2 ServiceEndpointNotFoundException (org.onap.so.cloud.authentication.ServiceEndpointNotFoundException)2 CloudSite (org.onap.so.db.catalog.beans.CloudSite)2 Subnet (org.onap.so.openstack.beans.Subnet)2