Fix NPE in Tracer when context size exceeds the limit (#1293)

This commit is contained in:
cdfive 2020-02-21 09:21:30 +08:00 committed by GitHub
parent f3b1b126c8
commit c1ff9135ee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 39 additions and 13 deletions

View File

@ -17,6 +17,7 @@ package com.alibaba.csp.sentinel;
import com.alibaba.csp.sentinel.context.Context;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.context.NullContext;
import com.alibaba.csp.sentinel.metric.extension.MetricExtensionProvider;
import com.alibaba.csp.sentinel.node.ClusterNode;
import com.alibaba.csp.sentinel.node.DefaultNode;
@ -53,17 +54,7 @@ public class Tracer {
* @param count exception count to add
*/
public static void trace(Throwable e, int count) {
if (!shouldTrace(e)) {
return;
}
Context context = ContextUtil.getContext();
if (context == null) {
return;
}
DefaultNode curNode = (DefaultNode)context.getCurNode();
traceExceptionToNode(e, count, context.getCurEntry(), curNode);
traceContext(e, count, ContextUtil.getContext());
}
/**
@ -77,7 +68,8 @@ public class Tracer {
if (!shouldTrace(e)) {
return;
}
if (context == null) {
if (context == null || context instanceof NullContext) {
return;
}

View File

@ -109,7 +109,7 @@ public class Context {
}
public Node getCurNode() {
return curEntry.getCurNode();
return curEntry == null ? null : curEntry.getCurNode();
}
public Context setCurNode(Node node) {

View File

@ -1,6 +1,10 @@
package com.alibaba.csp.sentinel;
import com.alibaba.csp.sentinel.context.ContextTestUtil;
import com.alibaba.csp.sentinel.context.ContextUtil;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
@ -8,6 +12,36 @@ import org.junit.Test;
*/
public class TracerTest extends Tracer {
@Before
public void setUp() {
ContextTestUtil.cleanUpContext();
ContextTestUtil.resetContextMap();
}
@After
public void tearDown() {
ContextTestUtil.cleanUpContext();
ContextTestUtil.resetContextMap();
}
@Test
public void testTraceWhenContextSizeExceedsThreshold() {
int i = 0;
for (; i < Constants.MAX_CONTEXT_NAME_SIZE; i++) {
ContextUtil.enter("test-context-" + i);
ContextUtil.exit();
}
try {
ContextUtil.enter("test-context-" + i);
throw new RuntimeException("test");
} catch (Exception e) {
Tracer.trace(e);
} finally {
ContextUtil.exit();
}
}
@Test
public void setExceptionsToTrace() {
Tracer.ignoreClasses = null;