com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule Java Examples

The following examples show how to use com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RuleTypeTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetByClass() {
	assertThat(RuleType.getByClass(Object.class).isPresent())
			.isEqualTo(Boolean.FALSE);
	assertThat(RuleType.getByClass(AbstractRule.class).isPresent())
			.isEqualTo(Boolean.FALSE);
	assertThat(RuleType.getByClass(FlowRule.class).isPresent())
			.isEqualTo(Boolean.TRUE);
	assertThat(RuleType.getByClass(DegradeRule.class).isPresent())
			.isEqualTo(Boolean.TRUE);
	assertThat(RuleType.getByClass(ParamFlowRule.class).isPresent())
			.isEqualTo(Boolean.TRUE);
	assertThat(RuleType.getByClass(SystemRule.class).isPresent())
			.isEqualTo(Boolean.TRUE);
	assertThat(RuleType.getByClass(AuthorityRule.class).isPresent())
			.isEqualTo(Boolean.TRUE);
}
 
Example #2
Source File: ClusterParamFlowRuleManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
/**
 * Get all cluster parameter flow rules within a specific namespace.
 *
 * @param namespace a valid namespace
 * @return cluster parameter flow rules within the provided namespace
 */
public static List<ParamFlowRule> getParamRules(String namespace) {
    if (StringUtil.isEmpty(namespace)) {
        return new ArrayList<>();
    }
    List<ParamFlowRule> rules = new ArrayList<>();
    Set<Long> flowIdSet = NAMESPACE_FLOW_ID_MAP.get(namespace);
    if (flowIdSet == null || flowIdSet.isEmpty()) {
        return rules;
    }
    for (Long flowId : flowIdSet) {
        ParamFlowRule rule = PARAM_RULES.get(flowId);
        if (rule != null) {
            rules.add(rule);
        }
    }
    return rules;
}
 
Example #3
Source File: ClusterParamFlowRuleManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
/**
 * Listen to the {@link SentinelProperty} for cluster {@link ParamFlowRule}s.
 * The property is the source of cluster {@link ParamFlowRule}s for a specific namespace.
 *
 * @param namespace namespace to register
 */
public static void register2Property(String namespace) {
    AssertUtil.notEmpty(namespace, "namespace cannot be empty");
    if (propertySupplier == null) {
        RecordLog.warn(
            "[ClusterParamFlowRuleManager] Cluster param rule property supplier is absent, cannot register "
                + "property");
        return;
    }
    SentinelProperty<List<ParamFlowRule>> property = propertySupplier.apply(namespace);
    if (property == null) {
        RecordLog.warn(
            "[ClusterParamFlowRuleManager] Wrong created property from cluster param rule property supplier, "
                + "ignoring");
        return;
    }
    synchronized (UPDATE_LOCK) {
        RecordLog.info("[ClusterParamFlowRuleManager] Registering new property to cluster param rule manager"
            + " for namespace <{0}>", namespace);
        registerPropertyInternal(namespace, property);
    }
}
 
Example #4
Source File: ClusterMetricNodeGenerator.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
public static ClusterMetricNode paramToMetricNode(long flowId) {
    ParamFlowRule rule = ClusterParamFlowRuleManager.getParamRuleById(flowId);
    if (rule == null) {
        return null;
    }
    ClusterParamMetric metric = ClusterParamMetricStatistics.getMetric(flowId);
    if (metric == null) {
        return new ClusterMetricNode().setFlowId(flowId)
            .setResourceName(rule.getResource())
            .setTimestamp(TimeUtil.currentTimeMillis())
            .setTopParams(new HashMap<Object, Double>(0));
    }
    return new ClusterMetricNode()
        .setFlowId(flowId)
        .setResourceName(rule.getResource())
        .setTimestamp(TimeUtil.currentTimeMillis())
        .setTopParams(metric.getTopValues(5));
}
 
Example #5
Source File: ModifyClusterParamFlowRulesCommandHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String namespace = request.getParam("namespace");
    if (StringUtil.isEmpty(namespace)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty namespace"));
    }
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
    }
    try {
        data = URLDecoder.decode(data, "UTF-8");
        RecordLog.info("[ModifyClusterParamFlowRulesCommandHandler] Receiving cluster param rules for namespace <{0}>: {1}", namespace, data);

        List<ParamFlowRule> flowRules = JSONArray.parseArray(data, ParamFlowRule.class);
        ClusterParamFlowRuleManager.loadRules(namespace, flowRules);

        return CommandResponse.ofSuccess(SUCCESS);
    } catch (Exception e) {
        RecordLog.warn("[ModifyClusterParamFlowRulesCommandHandler] Decode cluster param rules error", e);
        return CommandResponse.ofFailure(e, "decode cluster param rules error");
    }
}
 
Example #6
Source File: GatewayFlowSlot.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private void checkGatewayParamFlow(ResourceWrapper resourceWrapper, int count, Object... args)
    throws BlockException {
    if (args == null) {
        return;
    }

    List<ParamFlowRule> rules = GatewayRuleManager.getConvertedParamRules(resourceWrapper.getName());
    if (rules == null || rules.isEmpty()) {
        return;
    }

    for (ParamFlowRule rule : rules) {
        // Initialize the parameter metrics.
        ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);

        if (!ParamFlowChecker.passCheck(resourceWrapper, rule, count, args)) {
            String triggeredParam = "";
            if (args.length > rule.getParamIdx()) {
                Object value = args[rule.getParamIdx()];
                triggeredParam = String.valueOf(value);
            }
            throw new ParamFlowException(resourceWrapper.getName(), triggeredParam, rule);
        }
    }
}
 
Example #7
Source File: GatewayRuleConverter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a gateway rule to parameter flow rule, then apply the generated
 * parameter index to {@link GatewayParamFlowItem} of the rule.
 *
 * @param gatewayRule a valid gateway rule that should contain valid parameter items
 * @param idx generated parameter index (callers should guarantee it's unique and incremental)
 * @return converted parameter flow rule
 */
static ParamFlowRule applyToParamRule(/*@Valid*/ GatewayFlowRule gatewayRule, int idx) {
    ParamFlowRule paramRule = new ParamFlowRule(gatewayRule.getResource())
        .setCount(gatewayRule.getCount())
        .setGrade(gatewayRule.getGrade())
        .setDurationInSec(gatewayRule.getIntervalSec())
        .setBurstCount(gatewayRule.getBurst())
        .setControlBehavior(gatewayRule.getControlBehavior())
        .setMaxQueueingTimeMs(gatewayRule.getMaxQueueingTimeoutMs())
        .setParamIdx(idx);
    GatewayParamFlowItem gatewayItem = gatewayRule.getParamItem();
    // Apply the current idx to gateway rule item.
    gatewayItem.setIndex(idx);
    // Apply for pattern-based parameters.
    String valuePattern = gatewayItem.getPattern();
    if (valuePattern != null) {
        paramRule.getParamFlowItemList().add(generateNonMatchPassParamItem());
    }
    return paramRule;
}
 
Example #8
Source File: GatewayRuleConverterTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertAndApplyToParamRule() {
    GatewayFlowRule routeRule1 = new GatewayFlowRule("routeId1")
        .setCount(2)
        .setIntervalSec(2)
        .setBurst(2)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
        );
    int idx = 1;
    ParamFlowRule paramRule = GatewayRuleConverter.applyToParamRule(routeRule1, idx);
    assertEquals(routeRule1.getResource(), paramRule.getResource());
    assertEquals(routeRule1.getCount(), paramRule.getCount(), 0.01);
    assertEquals(routeRule1.getControlBehavior(), paramRule.getControlBehavior());
    assertEquals(routeRule1.getIntervalSec(), paramRule.getDurationInSec());
    assertEquals(routeRule1.getBurst(), paramRule.getBurstCount());
    assertEquals(idx, (int)paramRule.getParamIdx());
    assertEquals(idx, (int)routeRule1.getParamItem().getIndex());
}
 
Example #9
Source File: ModifyParamFlowRulesCommandHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("Bad data"));
    }
    try {
        data = URLDecoder.decode(data, "utf-8");
    } catch (Exception e) {
        RecordLog.info("Decode rule data error", e);
        return CommandResponse.ofFailure(e, "decode rule data error");
    }

    RecordLog.info(String.format("[API Server] Receiving rule change (type:parameter flow rule): %s", data));

    String result = SUCCESS_MSG;
    List<ParamFlowRule> flowRules = JSONArray.parseArray(data, ParamFlowRule.class);
    ParamFlowRuleManager.loadRules(flowRules);
    if (!writeToDataSource(paramFlowWds, flowRules)) {
        result = WRITE_DS_FAILURE_MSG;
    }
    return CommandResponse.ofSuccess(result);
}
 
Example #10
Source File: ParamFlowQpsDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private static void initParamFlowRules() {
    // QPS mode, threshold is 5 for every frequent "hot spot" parameter in index 0 (the first arg).
    ParamFlowRule rule = new ParamFlowRule(RESOURCE_KEY)
        .setParamIdx(0)
        .setGrade(RuleConstant.FLOW_GRADE_QPS)
        //.setDurationInSec(3)
        //.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
        //.setMaxQueueingTimeMs(600)
        .setCount(5);

    // We can set threshold count for specific parameter value individually.
    // Here we add an exception item. That means: QPS threshold of entries with parameter `PARAM_B` (type: int)
    // in index 0 will be 10, rather than the global threshold (5).
    ParamFlowItem item = new ParamFlowItem().setObject(String.valueOf(PARAM_B))
        .setClassType(int.class.getName())
        .setCount(10);
    rule.setParamFlowItemList(Collections.singletonList(item));
    ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example #11
Source File: ClusterParamFlowRuleManager.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Get all cluster parameter flow rules within a specific namespace.
 *
 * @param namespace a valid namespace
 * @return cluster parameter flow rules within the provided namespace
 */
public static List<ParamFlowRule> getParamRules(String namespace) {
    if (StringUtil.isEmpty(namespace)) {
        return new ArrayList<>();
    }
    List<ParamFlowRule> rules = new ArrayList<>();
    Set<Long> flowIdSet = NAMESPACE_FLOW_ID_MAP.get(namespace);
    if (flowIdSet == null || flowIdSet.isEmpty()) {
        return rules;
    }
    for (Long flowId : flowIdSet) {
        ParamFlowRule rule = PARAM_RULES.get(flowId);
        if (rule != null) {
            rules.add(rule);
        }
    }
    return rules;
}
 
Example #12
Source File: ClusterMetricNodeGenerator.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public static ClusterMetricNode paramToMetricNode(long flowId) {
    ParamFlowRule rule = ClusterParamFlowRuleManager.getParamRuleById(flowId);
    if (rule == null) {
        return null;
    }
    ClusterParamMetric metric = ClusterParamMetricStatistics.getMetric(flowId);
    if (metric == null) {
        return new ClusterMetricNode().setFlowId(flowId)
            .setResourceName(rule.getResource())
            .setTimestamp(TimeUtil.currentTimeMillis())
            .setTopParams(new HashMap<Object, Double>(0));
    }
    return new ClusterMetricNode()
        .setFlowId(flowId)
        .setResourceName(rule.getResource())
        .setTimestamp(TimeUtil.currentTimeMillis())
        .setTopParams(metric.getTopValues(5));
}
 
Example #13
Source File: ModifyClusterParamFlowRulesCommandHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String namespace = request.getParam("namespace");
    if (StringUtil.isEmpty(namespace)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty namespace"));
    }
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
    }
    try {
        data = URLDecoder.decode(data, "UTF-8");
        RecordLog.info("Receiving cluster param rules for namespace <{}> from command handler: {}", namespace, data);

        List<ParamFlowRule> flowRules = JSONArray.parseArray(data, ParamFlowRule.class);
        ClusterParamFlowRuleManager.loadRules(namespace, flowRules);

        return CommandResponse.ofSuccess(SUCCESS);
    } catch (Exception e) {
        RecordLog.warn("[ModifyClusterParamFlowRulesCommandHandler] Decode cluster param rules error", e);
        return CommandResponse.ofFailure(e, "decode cluster param rules error");
    }
}
 
Example #14
Source File: SentinelRecorder.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * register fastjson serializer deserializer class info
 */
public void init() {
    SerializeConfig.getGlobalInstance().getObjectWriter(NodeVo.class);
    SerializeConfig.getGlobalInstance().getObjectWriter(FlowRule.class);
    SerializeConfig.getGlobalInstance().getObjectWriter(SystemRule.class);
    SerializeConfig.getGlobalInstance().getObjectWriter(DegradeRule.class);
    SerializeConfig.getGlobalInstance().getObjectWriter(AuthorityRule.class);
    SerializeConfig.getGlobalInstance().getObjectWriter(ParamFlowRule.class);

    ParserConfig.getGlobalInstance().getDeserializer(NodeVo.class);
    ParserConfig.getGlobalInstance().getDeserializer(FlowRule.class);
    ParserConfig.getGlobalInstance().getDeserializer(SystemRule.class);
    ParserConfig.getGlobalInstance().getDeserializer(DegradeRule.class);
    ParserConfig.getGlobalInstance().getDeserializer(AuthorityRule.class);
    ParserConfig.getGlobalInstance().getDeserializer(ParamFlowRule.class);
}
 
Example #15
Source File: GatewayFlowSlot.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void checkGatewayParamFlow(ResourceWrapper resourceWrapper, int count, Object... args)
    throws BlockException {
    if (args == null) {
        return;
    }

    List<ParamFlowRule> rules = GatewayRuleManager.getConvertedParamRules(resourceWrapper.getName());
    if (rules == null || rules.isEmpty()) {
        return;
    }

    for (ParamFlowRule rule : rules) {
        // Initialize the parameter metrics.
        ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);

        if (!ParamFlowChecker.passCheck(resourceWrapper, rule, count, args)) {
            String triggeredParam = "";
            if (args.length > rule.getParamIdx()) {
                Object value = args[rule.getParamIdx()];
                triggeredParam = String.valueOf(value);
            }
            throw new ParamFlowException(resourceWrapper.getName(), triggeredParam, rule);
        }
    }
}
 
Example #16
Source File: GatewayRuleConverter.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a gateway rule to parameter flow rule, then apply the generated
 * parameter index to {@link GatewayParamFlowItem} of the rule.
 *
 * @param gatewayRule a valid gateway rule that should contain valid parameter items
 * @param idx generated parameter index (callers should guarantee it's unique and incremental)
 * @return converted parameter flow rule
 */
static ParamFlowRule applyToParamRule(/*@Valid*/ GatewayFlowRule gatewayRule, int idx) {
    ParamFlowRule paramRule = new ParamFlowRule(gatewayRule.getResource())
        .setCount(gatewayRule.getCount())
        .setGrade(gatewayRule.getGrade())
        .setDurationInSec(gatewayRule.getIntervalSec())
        .setBurstCount(gatewayRule.getBurst())
        .setControlBehavior(gatewayRule.getControlBehavior())
        .setMaxQueueingTimeMs(gatewayRule.getMaxQueueingTimeoutMs())
        .setParamIdx(idx);
    GatewayParamFlowItem gatewayItem = gatewayRule.getParamItem();
    // Apply the current idx to gateway rule item.
    gatewayItem.setIndex(idx);
    // Apply for pattern-based parameters.
    String valuePattern = gatewayItem.getPattern();
    if (valuePattern != null) {
        paramRule.getParamFlowItemList().add(generateNonMatchPassParamItem());
    }
    return paramRule;
}
 
Example #17
Source File: GatewayRuleConverterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertAndApplyToParamRule() {
    GatewayFlowRule routeRule1 = new GatewayFlowRule("routeId1")
        .setCount(2)
        .setIntervalSec(2)
        .setBurst(2)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
        );
    int idx = 1;
    ParamFlowRule paramRule = GatewayRuleConverter.applyToParamRule(routeRule1, idx);
    assertEquals(routeRule1.getResource(), paramRule.getResource());
    assertEquals(routeRule1.getCount(), paramRule.getCount(), 0.01);
    assertEquals(routeRule1.getControlBehavior(), paramRule.getControlBehavior());
    assertEquals(routeRule1.getIntervalSec(), paramRule.getDurationInSec());
    assertEquals(routeRule1.getBurst(), paramRule.getBurstCount());
    assertEquals(idx, (int)paramRule.getParamIdx());
    assertEquals(idx, (int)routeRule1.getParamItem().getIndex());
}
 
Example #18
Source File: ClusterParamFlowRuleManager.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Listen to the {@link SentinelProperty} for cluster {@link ParamFlowRule}s.
 * The property is the source of cluster {@link ParamFlowRule}s for a specific namespace.
 *
 * @param namespace namespace to register
 */
public static void register2Property(String namespace) {
    AssertUtil.notEmpty(namespace, "namespace cannot be empty");
    if (propertySupplier == null) {
        RecordLog.warn(
            "[ClusterParamFlowRuleManager] Cluster param rule property supplier is absent, cannot register "
                + "property");
        return;
    }
    SentinelProperty<List<ParamFlowRule>> property = propertySupplier.apply(namespace);
    if (property == null) {
        RecordLog.warn(
            "[ClusterParamFlowRuleManager] Wrong created property from cluster param rule property supplier, "
                + "ignoring");
        return;
    }
    synchronized (UPDATE_LOCK) {
        RecordLog.info("[ClusterParamFlowRuleManager] Registering new property to cluster param rule manager"
            + " for namespace <{}>", namespace);
        registerPropertyInternal(namespace, property);
    }
}
 
Example #19
Source File: ModifyParamFlowRulesCommandHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("Bad data"));
    }
    try {
        data = URLDecoder.decode(data, "utf-8");
    } catch (Exception e) {
        RecordLog.info("Decode rule data error", e);
        return CommandResponse.ofFailure(e, "decode rule data error");
    }

    RecordLog.info(String.format("[API Server] Receiving rule change (type:parameter flow rule): %s", data));

    String result = SUCCESS_MSG;
    List<ParamFlowRule> flowRules = JSONArray.parseArray(data, ParamFlowRule.class);
    ParamFlowRuleManager.loadRules(flowRules);
    if (!writeToDataSource(paramFlowWds, flowRules)) {
        result = WRITE_DS_FAILURE_MSG;
    }
    return CommandResponse.ofSuccess(result);
}
 
Example #20
Source File: ParamFlowQpsDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void initParamFlowRules() {
    // QPS mode, threshold is 5 for every frequent "hot spot" parameter in index 0 (the first arg).
    ParamFlowRule rule = new ParamFlowRule(RESOURCE_KEY)
        .setParamIdx(0)
        .setGrade(RuleConstant.FLOW_GRADE_QPS)
        //.setDurationInSec(3)
        //.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
        //.setMaxQueueingTimeMs(600)
        .setCount(5);

    // We can set threshold count for specific parameter value individually.
    // Here we add an exception item. That means: QPS threshold of entries with parameter `PARAM_B` (type: int)
    // in index 0 will be 10, rather than the global threshold (5).
    ParamFlowItem item = new ParamFlowItem().setObject(String.valueOf(PARAM_B))
        .setClassType(int.class.getName())
        .setCount(10);
    rule.setParamFlowItemList(Collections.singletonList(item));
    ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example #21
Source File: ClusterParamFlowRuleManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public static void removeProperty(String namespace) {
    AssertUtil.notEmpty(namespace, "namespace cannot be empty");
    synchronized (UPDATE_LOCK) {
        NamespaceFlowProperty<ParamFlowRule> property = PROPERTY_MAP.get(namespace);
        if (property != null) {
            property.getProperty().removeListener(property.getListener());
            PROPERTY_MAP.remove(namespace);
        }
        RecordLog.info("[ClusterParamFlowRuleManager] Removing property from cluster flow rule manager"
            + " for namespace <{0}>", namespace);
    }
}
 
Example #22
Source File: ClusterParamFlowRuleManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Load parameter flow rules for a specific namespace. The former rules of the namespace will be replaced.
 *
 * @param namespace a valid namespace
 * @param rules rule list
 */
public static void loadRules(String namespace, List<ParamFlowRule> rules) {
    AssertUtil.notEmpty(namespace, "namespace cannot be empty");
    NamespaceFlowProperty<ParamFlowRule> property = PROPERTY_MAP.get(namespace);
    if (property != null) {
        property.getProperty().updateValue(rules);
    }
}
 
Example #23
Source File: ClusterParamFlowRuleManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private static void registerPropertyInternal(/*@NonNull*/ String namespace, /*@Valid*/
                                                          SentinelProperty<List<ParamFlowRule>> property) {
    NamespaceFlowProperty<ParamFlowRule> oldProperty = PROPERTY_MAP.get(namespace);
    if (oldProperty != null) {
        oldProperty.getProperty().removeListener(oldProperty.getListener());
    }
    PropertyListener<List<ParamFlowRule>> listener = new ParamRulePropertyListener(namespace);
    property.addListener(listener);
    PROPERTY_MAP.put(namespace, new NamespaceFlowProperty<>(namespace, property, listener));
    Set<Long> flowIdSet = NAMESPACE_FLOW_ID_MAP.get(namespace);
    if (flowIdSet == null) {
        resetNamespaceFlowIdMapFor(namespace);
    }
}
 
Example #24
Source File: ClusterParamFlowRuleManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static void removeProperty(String namespace) {
    AssertUtil.notEmpty(namespace, "namespace cannot be empty");
    synchronized (UPDATE_LOCK) {
        NamespaceFlowProperty<ParamFlowRule> property = PROPERTY_MAP.get(namespace);
        if (property != null) {
            property.getProperty().removeListener(property.getListener());
            PROPERTY_MAP.remove(namespace);
        }
        RecordLog.info("[ClusterParamFlowRuleManager] Removing property from cluster flow rule manager"
            + " for namespace <{}>", namespace);
    }
}
 
Example #25
Source File: ClusterParamFlowRuleManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static void registerPropertyInternal(/*@NonNull*/ String namespace, /*@Valid*/
                                                          SentinelProperty<List<ParamFlowRule>> property) {
    NamespaceFlowProperty<ParamFlowRule> oldProperty = PROPERTY_MAP.get(namespace);
    if (oldProperty != null) {
        oldProperty.getProperty().removeListener(oldProperty.getListener());
    }
    PropertyListener<List<ParamFlowRule>> listener = new ParamRulePropertyListener(namespace);
    property.addListener(listener);
    PROPERTY_MAP.put(namespace, new NamespaceFlowProperty<>(namespace, property, listener));
    Set<Long> flowIdSet = NAMESPACE_FLOW_ID_MAP.get(namespace);
    if (flowIdSet == null) {
        resetNamespaceFlowIdMapFor(namespace);
    }
}
 
Example #26
Source File: GatewayRuleConverter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
static ParamFlowRule applyNonParamToParamRule(/*@Valid*/ GatewayFlowRule gatewayRule, int idx) {
    return new ParamFlowRule(gatewayRule.getResource())
        .setCount(gatewayRule.getCount())
        .setGrade(gatewayRule.getGrade())
        .setDurationInSec(gatewayRule.getIntervalSec())
        .setBurstCount(gatewayRule.getBurst())
        .setControlBehavior(gatewayRule.getControlBehavior())
        .setMaxQueueingTimeMs(gatewayRule.getMaxQueueingTimeoutMs())
        .setParamIdx(idx);
}
 
Example #27
Source File: ClusterParamFlowChecker.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static double getRawThreshold(ParamFlowRule rule, Object value) {
    Integer itemCount = rule.retrieveExclusiveItemCount(value);
    if (itemCount == null) {
        return rule.getCount();
    } else {
        return itemCount;
    }
}
 
Example #28
Source File: ClusterParamFlowChecker.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static double calcGlobalThreshold(ParamFlowRule rule, Object value) {
    double count = getRawThreshold(rule, value);
    switch (rule.getClusterConfig().getThresholdType()) {
        case ClusterRuleConstant.FLOW_THRESHOLD_GLOBAL:
            return count;
        case ClusterRuleConstant.FLOW_THRESHOLD_AVG_LOCAL:
        default:
            int connectedCount = ClusterParamFlowRuleManager.getConnectedCount(rule.getClusterConfig().getFlowId());
            return count * connectedCount;
    }
}
 
Example #29
Source File: ClusterParamFlowChecker.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private static double getRawThreshold(ParamFlowRule rule, Object value) {
    Integer itemCount = rule.retrieveExclusiveItemCount(value);
    if (itemCount == null) {
        return rule.getCount();
    } else {
        return itemCount;
    }
}
 
Example #30
Source File: DemoClusterInitFunc.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void initDynamicRuleProperty() {
    ReadableDataSource<String, List<FlowRule>> ruleSource = new NacosDataSource<>(remoteAddress, groupId,
        flowDataId, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
    FlowRuleManager.register2Property(ruleSource.getProperty());

    ReadableDataSource<String, List<ParamFlowRule>> paramRuleSource = new NacosDataSource<>(remoteAddress, groupId,
        paramDataId, source -> JSON.parseObject(source, new TypeReference<List<ParamFlowRule>>() {}));
    ParamFlowRuleManager.register2Property(paramRuleSource.getProperty());
}