Search in sources :

Example 6 with Resource

use of org.wso2.carbon.registry.api.Resource in project carbon-apimgt by wso2.

the class KubernetesGatewayImpl method createContainerGateway.

/**
 * @see ContainerBasedGatewayGenerator#createContainerGateway(String, API)
 */
@Override
public void createContainerGateway(String label, API api) throws ContainerBasedGatewayException {
    Map<String, String> templateValues = new HashMap<>();
    String serviceName = label + ContainerBasedGatewayConstants.CMS_SERVICE_SUFFIX;
    String deploymentName = label + ContainerBasedGatewayConstants.CMS_DEPLOYMENT_SUFFIX;
    String ingressName = label + ContainerBasedGatewayConstants.CMS_INGRESS_SUFFIX;
    templateValues.put(ContainerBasedGatewayConstants.NAMESPACE, namespace);
    templateValues.put(ContainerBasedGatewayConstants.GATEWAY_LABEL, label);
    templateValues.put(ContainerBasedGatewayConstants.SERVICE_NAME, serviceName);
    templateValues.put(ContainerBasedGatewayConstants.DEPLOYMENT_NAME, deploymentName);
    templateValues.put(ContainerBasedGatewayConstants.INGRESS_NAME, ingressName);
    templateValues.put(ContainerBasedGatewayConstants.CONTAINER_NAME, label + ContainerBasedGatewayConstants.CMS_CONTAINER_SUFFIX);
    templateValues.put(ContainerBasedGatewayConstants.API_CORE_URL, apiCoreUrl);
    templateValues.put(ContainerBasedGatewayConstants.BROKER_HOST, brokerHost);
    templateValues.put(ContainerBasedGatewayConstants.GATEWAY_HOSTNAME, generateSubDomain(api) + "." + gatewayHostname);
    ContainerBasedGatewayTemplateBuilder builder = new ContainerBasedGatewayTemplateBuilder();
    // Create gateway service resource
    createServiceResource(builder.generateTemplate(templateValues, ContainerBasedGatewayConstants.GATEWAY_SERVICE_TEMPLATE), serviceName);
    // Create gateway deployment resource
    createDeploymentResource(builder.generateTemplate(templateValues, ContainerBasedGatewayConstants.GATEWAY_DEPLOYMENT_TEMPLATE), deploymentName);
    // Create gateway ingress resource
    createIngressResource(builder.generateTemplate(templateValues, ContainerBasedGatewayConstants.GATEWAY_INGRESS_TEMPLATE), ingressName);
}
Also used : HashMap(java.util.HashMap) ContainerBasedGatewayTemplateBuilder(org.wso2.carbon.apimgt.core.template.ContainerBasedGatewayTemplateBuilder)

Example 7 with Resource

use of org.wso2.carbon.registry.api.Resource in project carbon-apimgt by wso2.

the class KubernetesGatewayImpl method createDeploymentResource.

/**
 * Create a deployment in cms
 *
 * @param deploymentTemplate Deployment template as a String
 * @param deploymentName     Name of the deployment
 * @throws ContainerBasedGatewayException if failed to create a deployment
 */
private void createDeploymentResource(String deploymentTemplate, String deploymentName) throws ContainerBasedGatewayException {
    HasMetadata resource = getResourcesFromTemplate(deploymentTemplate);
    try {
        if (resource instanceof Deployment) {
            // check whether there are existing service already
            if (client.extensions().deployments().inNamespace(namespace).withName(deploymentName).get() == null) {
                log.debug("Deploying in CMS type: {} and the Deployment resource definition: {} ", cmsType, deploymentTemplate);
                Deployment deployment = (Deployment) resource;
                Deployment result = client.extensions().deployments().inNamespace(namespace).create(deployment);
                log.info("Created Deployment : " + result.getMetadata().getName() + " in Namespace : " + result.getMetadata().getNamespace() + " in " + cmsType);
            } else {
                log.info("There exist a deployment with the same name in " + cmsType + ". Deployment name : " + deploymentName);
            }
        } else {
            throw new ContainerBasedGatewayException("Loaded Resource is not a Deployment in " + cmsType + "! " + resource, ExceptionCodes.LOADED_RESOURCE_DEFINITION_IS_NOT_VALID);
        }
    } catch (KubernetesClientException e) {
        throw new ContainerBasedGatewayException("Error while creating container based gateway deployment in " + cmsType + "!", e, ExceptionCodes.DEDICATED_CONTAINER_GATEWAY_CREATION_FAILED);
    }
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) ContainerBasedGatewayException(org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 8 with Resource

use of org.wso2.carbon.registry.api.Resource in project carbon-apimgt by wso2.

the class KubernetesGatewayImpl method createIngressResource.

/**
 * Create an Ingress resource in cms
 *
 * @param ingressTemplate Ingress template as a String
 * @param ingressName     Name of the ingress
 * @throws ContainerBasedGatewayException if failed to create a service
 */
private void createIngressResource(String ingressTemplate, String ingressName) throws ContainerBasedGatewayException {
    HasMetadata resource = getResourcesFromTemplate(ingressTemplate);
    try {
        if (resource instanceof Ingress) {
            // check whether there are existing service already
            if (client.extensions().ingresses().inNamespace(namespace).withName(ingressName).get() == null) {
                log.debug("Deploying in CMS type: {} and the Ingress resource definition: {} ", cmsType, ingressTemplate);
                Ingress ingress = (Ingress) resource;
                Ingress result = client.extensions().ingresses().inNamespace(namespace).create(ingress);
                log.info("Created Ingress : " + result.getMetadata().getName() + " in Namespace : " + result.getMetadata().getNamespace() + " in " + cmsType);
            } else {
                log.info("There exist an ingress with the same name in " + cmsType + ". Ingress name : " + ingressName);
            }
        } else {
            throw new ContainerBasedGatewayException("Loaded Resource is not a Service in " + cmsType + "! " + resource, ExceptionCodes.LOADED_RESOURCE_DEFINITION_IS_NOT_VALID);
        }
    } catch (KubernetesClientException e) {
        throw new ContainerBasedGatewayException("Error while creating container based gateway ingress in " + cmsType + "!", e, ExceptionCodes.DEDICATED_CONTAINER_GATEWAY_CREATION_FAILED);
    }
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Ingress(io.fabric8.kubernetes.api.model.extensions.Ingress) ContainerBasedGatewayException(org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 9 with Resource

use of org.wso2.carbon.registry.api.Resource in project carbon-apimgt by wso2.

the class ETagUtils method getHash.

/**
 * If some other hashing algorithm is needed use this method.
 *
 * @param updatedTime, the updated/created time of the resource in UNIX time
 * @param algorithm            the algorithm used for hashing
 * @return String
 * @throws NoSuchAlgorithmException if the given algorithm is invalid or not found in {@link MessageDigest}
 * @throws ETagGenerationException if hash generation failed.
 */
private static String getHash(String updatedTime, String algorithm) throws ETagGenerationException, NoSuchAlgorithmException {
    MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
    try {
        messageDigest.update(updatedTime.getBytes("UTF-8"));
        byte[] digest = messageDigest.digest();
        // conversion to hexadecimal
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b & 0xff));
        }
        String generatedHash = sb.toString();
        if (log.isDebugEnabled()) {
            log.debug("ETag generated in HEX '" + generatedHash + "' for '" + updatedTime + "'");
        }
        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        String errorMessage = "Error while converting timestamp to String :" + updatedTime;
        log.error(errorMessage, e);
        throw new ETagGenerationException(errorMessage, e);
    }
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) MessageDigest(java.security.MessageDigest) ETagGenerationException(org.wso2.carbon.apimgt.core.exception.ETagGenerationException)

Example 10 with Resource

use of org.wso2.carbon.registry.api.Resource in project carbon-apimgt by wso2.

the class ThrottlerUtil method addDefaultAdvancedThrottlePolicies.

/**
 * Deploy default throttle polices at startup
 *
 * @throws APIManagementException throws if any exception occured
 */
public static void addDefaultAdvancedThrottlePolicies() throws APIManagementException {
    int[] requestCount = new int[] { 50, 20, 10, Integer.MAX_VALUE };
    // Adding application level throttle policies
    String[] appPolicies = new String[] { ThrottleConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN, ThrottleConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN, ThrottleConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN, ThrottleConstants.DEFAULT_APP_POLICY_UNLIMITED };
    String[] appPolicyDecs = new String[] { ThrottleConstants.DEFAULT_APP_POLICY_LARGE_DESC, ThrottleConstants.DEFAULT_APP_POLICY_MEDIUM_DESC, ThrottleConstants.DEFAULT_APP_POLICY_SMALL_DESC, ThrottleConstants.DEFAULT_APP_POLICY_UNLIMITED_DESC };
    PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
    String policyName;
    // Add application level throttle policies
    for (int i = 0; i < appPolicies.length; i++) {
        policyName = appPolicies[i];
        if (!isPolicyExist(APIMgtAdminService.PolicyLevel.application, policyName)) {
            ApplicationPolicy applicationPolicy = new ApplicationPolicy(policyName);
            applicationPolicy.setUuid(UUID.randomUUID().toString());
            applicationPolicy.setDisplayName(policyName);
            applicationPolicy.setDescription(appPolicyDecs[i]);
            applicationPolicy.setDeployed(true);
            QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
            RequestCountLimit requestCountLimit = new RequestCountLimit(ThrottleConstants.TIME_UNIT_MINUTE, 1, requestCount[i]);
            defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
            defaultQuotaPolicy.setLimit(requestCountLimit);
            applicationPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
            policyDAO.addApplicationPolicy(applicationPolicy);
        }
    }
    // Adding Subscription level policies
    int[] requestCountSubPolicies = new int[] { 5000, 2000, 1000, 500, Integer.MAX_VALUE };
    String[] subPolicies = new String[] { ThrottleConstants.DEFAULT_SUB_POLICY_GOLD, ThrottleConstants.DEFAULT_SUB_POLICY_SILVER, ThrottleConstants.DEFAULT_SUB_POLICY_BRONZE, ThrottleConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED, ThrottleConstants.DEFAULT_SUB_POLICY_UNLIMITED };
    String[] subPolicyDecs = new String[] { ThrottleConstants.DEFAULT_SUB_POLICY_GOLD_DESC, ThrottleConstants.DEFAULT_SUB_POLICY_SILVER_DESC, ThrottleConstants.DEFAULT_SUB_POLICY_BRONZE_DESC, ThrottleConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED_DESC, ThrottleConstants.DEFAULT_SUB_POLICY_UNLIMITED_DESC };
    for (int i = 0; i < subPolicies.length; i++) {
        policyName = subPolicies[i];
        if (!isPolicyExist(APIMgtAdminService.PolicyLevel.subscription, policyName)) {
            SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(policyName);
            subscriptionPolicy.setUuid(UUID.randomUUID().toString());
            subscriptionPolicy.setDisplayName(policyName);
            subscriptionPolicy.setDescription(subPolicyDecs[i]);
            subscriptionPolicy.setDeployed(true);
            QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
            RequestCountLimit requestCountLimit = new RequestCountLimit(ThrottleConstants.TIME_UNIT_MINUTE, 1, requestCountSubPolicies[i]);
            defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
            defaultQuotaPolicy.setLimit(requestCountLimit);
            subscriptionPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
            subscriptionPolicy.setStopOnQuotaReach(true);
            subscriptionPolicy.setBillingPlan(ThrottleConstants.BILLING_PLAN_FREE);
            policyDAO.addSubscriptionPolicy(subscriptionPolicy);
        }
    }
    // Adding Resource level policies
    String[] apiPolicies = new String[] { ThrottleConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN, ThrottleConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN, ThrottleConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN, ThrottleConstants.DEFAULT_API_POLICY_UNLIMITED };
    String[] apiPolicyDecs = new String[] { ThrottleConstants.DEFAULT_API_POLICY_ULTIMATE_DESC, ThrottleConstants.DEFAULT_API_POLICY_PLUS_DESC, ThrottleConstants.DEFAULT_API_POLICY_BASIC_DESC, ThrottleConstants.DEFAULT_API_POLICY_UNLIMITED_DESC };
    int[] requestCountApiPolicies = new int[] { 50000, 20000, 10000, Integer.MAX_VALUE };
    for (int i = 0; i < apiPolicies.length; i++) {
        policyName = apiPolicies[i];
        if (!isPolicyExist(APIMgtAdminService.PolicyLevel.api, policyName)) {
            APIPolicy apiPolicy = new APIPolicy(policyName);
            apiPolicy.setUuid(UUID.randomUUID().toString());
            apiPolicy.setDisplayName(policyName);
            apiPolicy.setDescription(apiPolicyDecs[i]);
            apiPolicy.setUserLevel(ThrottleConstants.API_POLICY_API_LEVEL);
            apiPolicy.setDeployed(true);
            QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
            RequestCountLimit requestCountLimit = new RequestCountLimit(ThrottleConstants.TIME_UNIT_MINUTE, 1, requestCountApiPolicies[i]);
            defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
            defaultQuotaPolicy.setLimit(requestCountLimit);
            apiPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
            policyDAO.addApiPolicy(apiPolicy);
        }
    }
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)111 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)102 HashMap (java.util.HashMap)91 Test (org.testng.annotations.Test)64 HTTPCarbonMessage (org.wso2.transport.http.netty.message.HTTPCarbonMessage)59 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)56 HttpMessageDataStreamer (org.wso2.transport.http.netty.message.HttpMessageDataStreamer)53 BJSON (org.ballerinalang.model.values.BJSON)46 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)38 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)29 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)27 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)24 CharonException (org.wso2.charon3.core.exceptions.CharonException)24 IOException (java.io.IOException)23 Map (java.util.Map)20 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)20 NotFoundException (org.wso2.charon3.core.exceptions.NotFoundException)17 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)17 ArrayList (java.util.ArrayList)15 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)15