From 70b457bdc8530d5b3f94affa5ebe415b233704d7 Mon Sep 17 00:00:00 2001 From: brothelul <1285823170@qq.com> Date: Fri, 18 Dec 2020 11:20:38 +0800 Subject: [PATCH] Fix potential NPE bug when updating ParamFlowRule before the resource has been requested once (#1901) --- .../block/flow/param/ParamFlowRuleManager.java | 5 ++++- .../block/flow/param/ParamFlowRuleManagerTest.java | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/sentinel-extension/sentinel-parameter-flow-control/src/main/java/com/alibaba/csp/sentinel/slots/block/flow/param/ParamFlowRuleManager.java b/sentinel-extension/sentinel-parameter-flow-control/src/main/java/com/alibaba/csp/sentinel/slots/block/flow/param/ParamFlowRuleManager.java index 1f1ebf81..0802226a 100644 --- a/sentinel-extension/sentinel-parameter-flow-control/src/main/java/com/alibaba/csp/sentinel/slots/block/flow/param/ParamFlowRuleManager.java +++ b/sentinel-extension/sentinel-parameter-flow-control/src/main/java/com/alibaba/csp/sentinel/slots/block/flow/param/ParamFlowRuleManager.java @@ -138,7 +138,10 @@ public final class ParamFlowRuleManager { List oldRuleList = new ArrayList<>(entry.getValue()); oldRuleList.removeAll(newRuleList); for (ParamFlowRule rule : oldRuleList) { - ParameterMetricStorage.getParamMetricForResource(resource).clearForRule(rule); + ParameterMetric parameterMetric = ParameterMetricStorage.getParamMetricForResource(resource); + if (parameterMetric != null) { + parameterMetric.clearForRule(rule); + } } } diff --git a/sentinel-extension/sentinel-parameter-flow-control/src/test/java/com/alibaba/csp/sentinel/slots/block/flow/param/ParamFlowRuleManagerTest.java b/sentinel-extension/sentinel-parameter-flow-control/src/test/java/com/alibaba/csp/sentinel/slots/block/flow/param/ParamFlowRuleManagerTest.java index 974372b3..fe21297d 100644 --- a/sentinel-extension/sentinel-parameter-flow-control/src/test/java/com/alibaba/csp/sentinel/slots/block/flow/param/ParamFlowRuleManagerTest.java +++ b/sentinel-extension/sentinel-parameter-flow-control/src/test/java/com/alibaba/csp/sentinel/slots/block/flow/param/ParamFlowRuleManagerTest.java @@ -138,4 +138,18 @@ public class ParamFlowRuleManagerTest { assertTrue(allRules.contains(ruleC)); assertTrue(allRules.contains(ruleD)); } + + @Test + public void testLoadParamRulesWithNoMetric() { + String resource = "test"; + ParamFlowRule paramFlowRule = new ParamFlowRule(resource) + .setDurationInSec(1).setParamIdx(1); + ParamFlowRuleManager.loadRules(Collections.singletonList(paramFlowRule)); + ParamFlowRule newParamFlowRule = new ParamFlowRule(resource) + .setDurationInSec(2).setParamIdx(1); + ParamFlowRuleManager.loadRules(Collections.singletonList(newParamFlowRule)); + List result = ParamFlowRuleManager.getRulesOfResource(resource); + assertEquals(1, result.size()); + assertEquals(2, result.get(0).getDurationInSec()); + } }