Search in sources :

Example 1 with ThrottleDataPublisher

use of org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher in project carbon-apimgt by wso2.

the class ThrottleHandlerTest method testMsgDoContinueWhenAllThrottlingLevelsAreNotThrolled.

@Test
public void testMsgDoContinueWhenAllThrottlingLevelsAreNotThrolled() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    ServiceReferenceHolder.getInstance().setThrottleDataPublisher(new ThrottleDataPublisher());
    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty(API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
    // Should continue the message flow if API level, application level, resource level, subscription level,
    // subscription spike level and hard throttling limit levels are not throttled
    Assert.assertTrue(throttleHandler.handleRequest(messageContext));
}
Also used : ThrottleDataHolder(org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) ThrottleDataPublisher(org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 2 with ThrottleDataPublisher

use of org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher in project carbon-apimgt by wso2.

the class ThrottleHandlerTest method testCheckForStaledThrottleData.

@Test
public void testCheckForStaledThrottleData() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    ServiceReferenceHolder.getInstance().setThrottleDataPublisher(new ThrottleDataPublisher());
    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator, accessInformation);
    throttleHandler.setProductionMaxCount("100");
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    throttleHandler.init(synapseEnvironment);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty(API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    authenticationContext.setSpikeArrestLimit(0);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
    verbInfo.setConditionGroups(conditionGroupDTOs);
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
    Mockito.when(accessInformation.isAccessAllowed()).thenReturn(false);
    matchingConditions.add(conditionGroupDTO);
    throttleDataHolder.addKeyTemplate("testKeyTemplate", "testKeyTemplateValue");
    throttleDataHolder.addThrottleData("testKeyTemplate", System.currentTimeMillis() - 10000);
    Assert.assertTrue(throttleHandler.handleRequest(messageContext));
}
Also used : ThrottleDataHolder(org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) ThrottleDataPublisher(org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) ArrayList(java.util.ArrayList) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) ConditionGroupDTO(org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 3 with ThrottleDataPublisher

use of org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher in project carbon-apimgt by wso2.

the class SseUtils method publishNonThrottledEvent.

public static void publishNonThrottledEvent(int eventCount, String messageId, ThrottleInfo throttleInfo, JSONObject properties) {
    Object[] objects = new Object[] { messageId, throttleInfo.getApplicationLevelThrottleKey(), throttleInfo.getApplicationTier(), throttleInfo.getApiLevelThrottleKey(), throttleInfo.getApiTier(), throttleInfo.getSubscriptionLevelThrottleKey(), throttleInfo.getTier(), throttleInfo.getResourceLevelThrottleKey(), throttleInfo.getResourceTier(), throttleInfo.getAuthorizedUser(), throttleInfo.getApiContext(), throttleInfo.getApiVersion(), throttleInfo.getSubscriberTenantDomain(), throttleInfo.getSubscriberTenantDomain(), throttleInfo.getApplicationId(), throttleInfo.getApiName(), properties.toString() };
    org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons.Event(THROTTLE_STREAM_ID, System.currentTimeMillis(), null, null, objects);
    ThrottleDataPublisher throttleDataPublisher = ServiceReferenceHolder.getInstance().getThrottleDataPublisher();
    if (throttleDataPublisher != null) {
        int count = 1;
        DataPublisher publisher = ThrottleDataPublisher.getDataPublisher();
        while (count <= eventCount) {
            publisher.tryPublish(event);
            count++;
        }
    } else {
        log.error("Cannot publish events to traffic manager because ThrottleDataPublisher " + "has not been initialised");
    }
}
Also used : ThrottleDataPublisher(org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher) ThrottleDataPublisher(org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher) DataPublisher(org.wso2.carbon.databridge.agent.DataPublisher) JSONObject(org.json.JSONObject)

Example 4 with ThrottleDataPublisher

use of org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher in project carbon-apimgt by wso2.

the class InboundWebsocketProcessorUtilTest method init.

@Before
public void init() {
    System.setProperty("carbon.home", "jhkjn");
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.mockStatic(ThrottleDataPublisher.class);
    dataPublisher = Mockito.mock(DataPublisher.class);
    ThrottleDataPublisher throttleDataPublisher = Mockito.mock(ThrottleDataPublisher.class);
    Mockito.when(serviceReferenceHolder.getThrottleDataPublisher()).thenReturn(throttleDataPublisher);
    PowerMockito.when(ThrottleDataPublisher.getDataPublisher()).thenReturn(dataPublisher);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    PowerMockito.when(serviceReferenceHolder.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    PowerMockito.mockStatic(WebsocketUtil.class);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) ThrottleDataPublisher(org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher) ThrottleDataPublisher(org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher) DataPublisher(org.wso2.carbon.databridge.agent.DataPublisher) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Before(org.junit.Before)

Example 5 with ThrottleDataPublisher

use of org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher in project carbon-apimgt by wso2.

the class InboundWebsocketProcessorUtil method doThrottle.

/**
 * Checks if the request is throttled.
 *
 * @param msgSize               Websocket msg size
 * @param verbInfoDTO           VerbInfoDTO for invoking operation. Pass null for websocket API throttling.
 * @param inboundMessageContext InboundMessageContext
 * @return false if throttled
 */
public static InboundProcessorResponseDTO doThrottle(int msgSize, VerbInfoDTO verbInfoDTO, InboundMessageContext inboundMessageContext, InboundProcessorResponseDTO responseDTO) {
    APIKeyValidationInfoDTO infoDTO = inboundMessageContext.getInfoDTO();
    String applicationLevelTier = infoDTO.getApplicationTier();
    String apiLevelTier = infoDTO.getApiTier() == null && verbInfoDTO == null ? APIConstants.UNLIMITED_TIER : infoDTO.getApiTier();
    String subscriptionLevelTier = infoDTO.getTier();
    String resourceLevelTier;
    String authorizedUser;
    if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(infoDTO.getSubscriberTenantDomain())) {
        authorizedUser = infoDTO.getSubscriber() + "@" + infoDTO.getSubscriberTenantDomain();
    } else {
        authorizedUser = infoDTO.getSubscriber();
    }
    String apiName = infoDTO.getApiName();
    String apiVersion = inboundMessageContext.getVersion();
    String appTenant = infoDTO.getSubscriberTenantDomain();
    String apiTenant = inboundMessageContext.getTenantDomain();
    String appId = infoDTO.getApplicationId();
    String applicationLevelThrottleKey = appId + ":" + authorizedUser;
    String apiLevelThrottleKey = inboundMessageContext.getApiContext() + ":" + apiVersion;
    String resourceLevelThrottleKey;
    // If API level throttle policy is present then it will apply and no resource level policy will apply for it
    if (StringUtils.isNotEmpty(apiLevelTier) && verbInfoDTO == null) {
        resourceLevelThrottleKey = apiLevelThrottleKey;
        resourceLevelTier = apiLevelTier;
    } else {
        resourceLevelThrottleKey = verbInfoDTO.getRequestKey();
        resourceLevelTier = verbInfoDTO.getThrottling();
    }
    String subscriptionLevelThrottleKey = appId + ":" + inboundMessageContext.getApiContext() + ":" + apiVersion;
    String messageId = UIDGenerator.generateURNString();
    String remoteIP = inboundMessageContext.getUserIP();
    if (log.isDebugEnabled()) {
        log.debug("Remote IP address : " + remoteIP);
    }
    if (remoteIP.indexOf(":") > 0) {
        remoteIP = remoteIP.substring(1, remoteIP.indexOf(":"));
    }
    JSONObject jsonObMap = new JSONObject();
    Utils.setRemoteIp(jsonObMap, remoteIP);
    jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, msgSize);
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(inboundMessageContext.getTenantDomain(), true);
        boolean isThrottled = WebsocketUtil.isThrottled(resourceLevelThrottleKey, subscriptionLevelThrottleKey, applicationLevelThrottleKey);
        if (isThrottled) {
            responseDTO.setError(true);
            responseDTO.setErrorCode(WebSocketApiConstants.FrameErrorConstants.THROTTLED_OUT_ERROR);
            responseDTO.setErrorMessage(WebSocketApiConstants.FrameErrorConstants.THROTTLED_OUT_ERROR_MESSAGE);
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    Object[] objects = new Object[] { messageId, applicationLevelThrottleKey, applicationLevelTier, apiLevelThrottleKey, apiLevelTier, subscriptionLevelThrottleKey, subscriptionLevelTier, resourceLevelThrottleKey, resourceLevelTier, authorizedUser, inboundMessageContext.getApiContext(), apiVersion, appTenant, apiTenant, appId, apiName, jsonObMap.toString() };
    org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons.Event("org.wso2.throttle.request.stream:1.0.0", System.currentTimeMillis(), null, null, objects);
    if (ServiceReferenceHolder.getInstance().getThrottleDataPublisher() == null) {
        log.error("Cannot publish events to traffic manager because ThrottleDataPublisher " + "has not been initialised");
    }
    ServiceReferenceHolder.getInstance().getThrottleDataPublisher().getDataPublisher().tryPublish(event);
    return responseDTO;
}
Also used : JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Aggregations

ThrottleDataPublisher (org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher)5 ThrottleDataHolder (org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder)3 MessageContext (org.apache.synapse.MessageContext)2 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)2 JSONObject (org.json.JSONObject)2 Test (org.junit.Test)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)2 DataPublisher (org.wso2.carbon.databridge.agent.DataPublisher)2 ArrayList (java.util.ArrayList)1 XMLStreamException (javax.xml.stream.XMLStreamException)1 ThrottleException (org.apache.synapse.commons.throttle.core.ThrottleException)1 SynapseEnvironment (org.apache.synapse.core.SynapseEnvironment)1 Before (org.junit.Before)1 ConditionGroupDTO (org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO)1 ServiceReferenceHolder (org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder)1 APIThrottleDataServiceImpl (org.wso2.carbon.apimgt.gateway.service.APIThrottleDataServiceImpl)1 RevokedTokenDataImpl (org.wso2.carbon.apimgt.gateway.service.RevokedTokenDataImpl)1 SubscriptionsDataServiceImpl (org.wso2.carbon.apimgt.gateway.webhooks.SubscriptionsDataServiceImpl)1 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)1