Search in sources :

Example 1 with Throttle

use of org.apache.synapse.commons.throttle.core.Throttle in project carbon-apimgt by wso2.

the class ApplicationThrottleController method createThrottleContext.

private static ThrottleContext createThrottleContext(MessageContext synCtx, ThrottleDataHolder dataHolder, String applicationId, String policyKeyApplication) {
    // Object entryValue = synCtx.getEntry(APPLICATION_THROTTLE_POLICY_KEY);
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
    AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(synCtx);
    // extract the subscriber username from the auth Context
    String subscriber = authContext.getSubscriber();
    // get the tenant Domain from the subscriber
    String tenantDomain = MultitenantUtils.getTenantDomain(subscriber);
    int tenantId;
    // get the tenant domain id from the tenant domain name
    try {
        tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        handleException("Unable to Find the tenant ID using tenant: " + tenantDomain, e);
        return null;
    }
    Object entryValue = lookup(policyKeyApplication, tenantId);
    if (entryValue == null || !(entryValue instanceof OMElement)) {
        handleException("Unable to load throttling policy using key: " + policyKeyApplication);
    }
    try {
        Throttle throttle = ThrottleFactory.createMediatorThrottle(PolicyEngine.getPolicy((OMElement) entryValue));
        ThrottleContext context = throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY);
        dataHolder.addThrottleContext(applicationId, context);
        return context;
    } catch (ThrottleException e) {
        handleException("Error processing the throttling policy", e);
    }
    return null;
}
Also used : ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) RealmService(org.wso2.carbon.user.core.service.RealmService) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Throttle(org.apache.synapse.commons.throttle.core.Throttle)

Example 2 with Throttle

use of org.apache.synapse.commons.throttle.core.Throttle in project carbon-apimgt by wso2.

the class ThrottleHandler method initThrottleForSubscriptionLevelSpikeArrest.

/**
 * This method will intialize subscription level throttling context and throttle object.
 * This method need to be called for each and every request of spike arrest is enabled.
 * If throttle context for incoming message is already created method will do nothing. Else
 * it will create throttle object and context.
 *
 * @param synCtx synapse messaginitThrottleForSubscriptionLevelSpikeArreste context which contains message data
 */
private void initThrottleForSubscriptionLevelSpikeArrest(MessageContext synCtx, AuthenticationContext authenticationContext) {
    policyKey = authenticationContext.getTier();
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    String subscriptionLevelThrottleKey = getSubscriptionLevelThrottleKey(policyKey, authenticationContext, apiContext, apiVersion);
    int maxRequestCount = authenticationContext.getSpikeArrestLimit();
    if (maxRequestCount != 0) {
        String unitTime = authenticationContext.getSpikeArrestUnit();
        int spikeArrestWindowUnitTime;
        if (APIThrottleConstants.MIN.equalsIgnoreCase(unitTime)) {
            spikeArrestWindowUnitTime = 60000;
        } else {
            spikeArrestWindowUnitTime = 1000;
        }
        try {
            synchronized (this) {
                if (throttle == null) {
                    OMElement spikeArrestSubscriptionLevelPolicy = createSpikeArrestSubscriptionLevelPolicy(subscriptionLevelThrottleKey, maxRequestCount, spikeArrestWindowUnitTime);
                    if (spikeArrestSubscriptionLevelPolicy != null) {
                        throttle = ThrottleFactory.createMediatorThrottle(PolicyEngine.getPolicy(spikeArrestSubscriptionLevelPolicy));
                    }
                } else {
                    boolean createSpikeArrestSubscriptionLevelPolicy = false;
                    if (throttle.getThrottleContext(subscriptionLevelThrottleKey) == null) {
                        createSpikeArrestSubscriptionLevelPolicy = true;
                    } else {
                        CallerConfiguration existingCallerConfig = throttle.getThrottleContext(subscriptionLevelThrottleKey).getThrottleConfiguration().getCallerConfiguration(subscriptionLevelThrottleKey);
                        if (existingCallerConfig.getMaximumRequestPerUnitTime() != maxRequestCount || existingCallerConfig.getUnitTime() != spikeArrestWindowUnitTime) {
                            createSpikeArrestSubscriptionLevelPolicy = true;
                        }
                    }
                    if (createSpikeArrestSubscriptionLevelPolicy) {
                        OMElement spikeArrestSubscriptionLevelPolicy = createSpikeArrestSubscriptionLevelPolicy(subscriptionLevelThrottleKey, maxRequestCount, spikeArrestWindowUnitTime);
                        if (spikeArrestSubscriptionLevelPolicy != null) {
                            Throttle tempThrottle = ThrottleFactory.createMediatorThrottle(PolicyEngine.getPolicy(spikeArrestSubscriptionLevelPolicy));
                            ThrottleConfiguration newThrottleConfig = tempThrottle.getThrottleConfiguration(ThrottleConstants.ROLE_BASED_THROTTLE_KEY);
                            ThrottleContext subscriptionLevelSpikeThrottle = ThrottleContextFactory.createThrottleContext(ThrottleConstants.ROLE_BASE, newThrottleConfig);
                            throttle.addThrottleContext(subscriptionLevelThrottleKey, subscriptionLevelSpikeThrottle);
                        }
                    }
                }
            }
        } catch (ThrottleException e) {
            log.error("Error while initializing throttling object for subscription level spike arrest policy" + e.getMessage());
        }
    }
}
Also used : ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) CallerConfiguration(org.apache.synapse.commons.throttle.core.CallerConfiguration) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) ThrottleConfiguration(org.apache.synapse.commons.throttle.core.ThrottleConfiguration) OMElement(org.apache.axiom.om.OMElement) Throttle(org.apache.synapse.commons.throttle.core.Throttle)

Example 3 with Throttle

use of org.apache.synapse.commons.throttle.core.Throttle in project carbon-apimgt by wso2.

the class ThrottleHandler method initThrottleForHardLimitThrottling.

/**
 * This method will intialize subscription level throttling context and throttle object.
 * This method need to be called for each and every request of spike arrest is enabled.
 * If throttle context for incoming message is already created method will do nothing. Else
 * it will create throttle object and context.
 */
private void initThrottleForHardLimitThrottling() {
    OMElement hardThrottlingPolicy = createHardThrottlingPolicy();
    if (hardThrottlingPolicy != null) {
        Throttle tempThrottle;
        try {
            tempThrottle = ThrottleFactory.createMediatorThrottle(PolicyEngine.getPolicy(hardThrottlingPolicy));
            ThrottleConfiguration newThrottleConfig = tempThrottle.getThrottleConfiguration(ThrottleConstants.ROLE_BASED_THROTTLE_KEY);
            ThrottleContext hardThrottling = ThrottleContextFactory.createThrottleContext(ThrottleConstants.ROLE_BASE, newThrottleConfig);
            tempThrottle.addThrottleContext(APIThrottleConstants.HARD_THROTTLING_CONFIGURATION, hardThrottling);
            if (throttle != null) {
                throttle.addThrottleContext(APIThrottleConstants.HARD_THROTTLING_CONFIGURATION, hardThrottling);
            } else {
                throttle = tempThrottle;
            }
        } catch (ThrottleException e) {
            log.error("Error occurred while creating policy file for Hard Throttling.", e);
        }
    }
}
Also used : ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) ThrottleConfiguration(org.apache.synapse.commons.throttle.core.ThrottleConfiguration) OMElement(org.apache.axiom.om.OMElement) Throttle(org.apache.synapse.commons.throttle.core.Throttle)

Example 4 with Throttle

use of org.apache.synapse.commons.throttle.core.Throttle in project wso2-synapse by wso2.

the class ThrottleHandler method loadThrottle.

/**
 * Loads a throttle metadata for a particular throttle type
 *
 * @param messageContext - The messageContext
 * @param throttleType   - The type of throttle
 * @return IPBaseThrottleConfiguration     - The IPBaseThrottleConfiguration - load from AxisConfiguration
 * @throws ThrottleException Throws if the throttle type is unsupported
 */
public Throttle loadThrottle(MessageContext messageContext, int throttleType) throws ThrottleException {
    Throttle throttle = null;
    ConfigurationContext configContext = messageContext.getConfigurationContext();
    // the Parameter which hold throttle ipbase object
    // to get throttles map from the configuration context
    Map throttles = (Map) configContext.getPropertyNonReplicable(ThrottleConstants.THROTTLES_MAP);
    if (throttles == null) {
        if (debugOn) {
            log.debug("Couldn't find throttles object map .. thottlling will not be occurred ");
        }
        return null;
    }
    switch(throttleType) {
        case ThrottleConstants.GLOBAL_THROTTLE:
            {
                throttle = (Throttle) throttles.get(ThrottleConstants.GLOBAL_THROTTLE_KEY);
                break;
            }
        case ThrottleConstants.OPERATION_BASED_THROTTLE:
            {
                AxisOperation axisOperation = messageContext.getAxisOperation();
                if (axisOperation != null) {
                    QName opName = axisOperation.getName();
                    if (opName != null) {
                        AxisService service = (AxisService) axisOperation.getParent();
                        if (service != null) {
                            String currentServiceName = service.getName();
                            if (currentServiceName != null) {
                                throttle = (Throttle) throttles.get(currentServiceName + opName.getLocalPart());
                            }
                        }
                    }
                } else {
                    if (debugOn) {
                        log.debug("Couldn't find axis operation ");
                    }
                    return null;
                }
                break;
            }
        case ThrottleConstants.SERVICE_BASED_THROTTLE:
            {
                AxisService axisService = messageContext.getAxisService();
                if (axisService != null) {
                    throttle = (Throttle) throttles.get(axisService.getName());
                } else {
                    if (debugOn) {
                        log.debug("Couldn't find axis service ");
                    }
                    return null;
                }
                break;
            }
        default:
            {
                throw new ThrottleException("Unsupported Throttle type");
            }
    }
    return throttle;
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) AxisOperation(org.apache.axis2.description.AxisOperation) QName(javax.xml.namespace.QName) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) AxisService(org.apache.axis2.description.AxisService) Map(java.util.Map) Throttle(org.apache.synapse.commons.throttle.core.Throttle)

Example 5 with Throttle

use of org.apache.synapse.commons.throttle.core.Throttle in project wso2-synapse by wso2.

the class ThrottleEnguageUtils method enguage.

public static void enguage(AxisDescription axisDescription, ConfigurationContext configctx, Throttle defaultThrottle) throws AxisFault {
    String currentServiceName;
    if (axisDescription instanceof AxisService) {
        Throttle throttle = null;
        AxisService currentService = ((AxisService) axisDescription);
        PolicySubject policySubject = currentService.getPolicySubject();
        if (policySubject != null) {
            try {
                List policies = new ArrayList(policySubject.getAttachedPolicyComponents());
                Policy currentPolicy = PolicyUtil.getMergedPolicy(policies, currentService);
                if (currentPolicy != null) {
                    throttle = ThrottleFactory.createServiceThrottle(currentPolicy);
                    if (throttle == null) {
                        // this is for the scenario when throttle policy is empty rather than
                        // null (eg: removing the throttle policy via policy editor)
                        throttle = defaultThrottle;
                    }
                // todo - done by isuru, recheck
                } else {
                    AxisConfiguration axisConfig = configctx.getAxisConfiguration();
                    AxisModule throttleModule = axisConfig.getModule(ThrottleConstants.THROTTLE_MODULE_NAME);
                    policySubject = throttleModule.getPolicySubject();
                    if (policySubject != null) {
                        currentPolicy = ThrottleEnguageUtils.getThrottlePolicy(policySubject.getAttachedPolicyComponents());
                        if (currentPolicy != null) {
                            throttle = ThrottleFactory.createModuleThrottle(currentPolicy);
                        }
                    }
                // todo - done by isuru
                }
            } catch (ThrottleException e) {
                log.error("Error was occurred when engaging throttle module for" + " the service :" + currentService.getName() + e.getMessage());
                log.info("Throttling will occur using default module policy");
                throttle = defaultThrottle;
            }
            if (throttle != null) {
                Map throttles = (Map) configctx.getPropertyNonReplicable(ThrottleConstants.THROTTLES_MAP);
                if (throttles == null) {
                    throttles = new HashMap();
                    configctx.setNonReplicableProperty(ThrottleConstants.THROTTLES_MAP, throttles);
                }
                String serviceName = currentService.getName();
                throttle.setId(serviceName);
                throttles.put(serviceName, throttle);
                ConcurrentAccessController cac = throttle.getConcurrentAccessController();
                if (cac != null) {
                    String cacKey = ThrottleConstants.THROTTLE_PROPERTY_PREFIX + serviceName + ThrottleConstants.CAC_SUFFIX;
                    configctx.setProperty(cacKey, cac);
                }
            }
        }
    } else if (axisDescription instanceof AxisOperation) {
        Throttle throttle = null;
        AxisOperation currentOperation = ((AxisOperation) axisDescription);
        AxisService axisService = (AxisService) currentOperation.getParent();
        if (axisService != null) {
            currentServiceName = axisService.getName();
            PolicySubject policySubject = currentOperation.getPolicySubject();
            if (policySubject != null) {
                try {
                    List policies = new ArrayList(policySubject.getAttachedPolicyComponents());
                    Policy currentPolicy = PolicyUtil.getMergedPolicy(policies, currentOperation);
                    if (currentPolicy != null) {
                        throttle = ThrottleFactory.createOperationThrottle(currentPolicy);
                    }
                } catch (ThrottleException e) {
                    log.error("Error was occurred when engaging throttle module " + "for operation : " + currentOperation.getName() + " in the service :" + currentServiceName + e.getMessage());
                    log.info("Throttling will occur using default module policy");
                }
                // if current throttle is null, use the default throttle
                if (throttle == null) {
                    throttle = defaultThrottle;
                }
                Map throttles = (Map) configctx.getPropertyNonReplicable(ThrottleConstants.THROTTLES_MAP);
                if (throttles == null) {
                    throttles = new HashMap();
                    configctx.setNonReplicableProperty(ThrottleConstants.THROTTLES_MAP, throttles);
                }
                QName opQName = currentOperation.getName();
                if (opQName != null) {
                    String opName = opQName.getLocalPart();
                    String key = currentServiceName + opName;
                    throttle.setId(key);
                    throttles.put(key, throttle);
                    ConcurrentAccessController cac = throttle.getConcurrentAccessController();
                    if (cac != null) {
                        String cacKey = ThrottleConstants.THROTTLE_PROPERTY_PREFIX + key + ThrottleConstants.CAC_SUFFIX;
                        configctx.setProperty(cacKey, cac);
                    }
                }
            }
        }
    }
}
Also used : Policy(org.apache.neethi.Policy) AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) Throttle(org.apache.synapse.commons.throttle.core.Throttle) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) ArrayList(java.util.ArrayList) List(java.util.List) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Throttle (org.apache.synapse.commons.throttle.core.Throttle)9 ThrottleException (org.apache.synapse.commons.throttle.core.ThrottleException)6 OMElement (org.apache.axiom.om.OMElement)4 ThrottleContext (org.apache.synapse.commons.throttle.core.ThrottleContext)4 Map (java.util.Map)3 ThrottleConfiguration (org.apache.synapse.commons.throttle.core.ThrottleConfiguration)3 HashMap (java.util.HashMap)2 QName (javax.xml.namespace.QName)2 Policy (org.apache.neethi.Policy)2 ArrayList (java.util.ArrayList)1 Iterator (java.util.Iterator)1 List (java.util.List)1 TreeMap (java.util.TreeMap)1 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)1 AxisOperation (org.apache.axis2.description.AxisOperation)1 AxisService (org.apache.axis2.description.AxisService)1 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)1 SynapseException (org.apache.synapse.SynapseException)1 CallerConfiguration (org.apache.synapse.commons.throttle.core.CallerConfiguration)1 ConcurrentAccessController (org.apache.synapse.commons.throttle.core.ConcurrentAccessController)1