Split interceptor

This commit is contained in:
lytscu 2017-11-15 11:49:12 +08:00
parent 778d3c6751
commit ab36a1bb83
5 changed files with 242 additions and 31 deletions

View File

@ -0,0 +1,101 @@
/*
* Copyright 2017, OpenSkywalking Organization All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Project repository: https://github.com/OpenSkywalking/skywalking
*/
package org.skywalking.apm.plugin.mongodb.v2;
import com.mongodb.AggregationOutput;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;
import java.lang.reflect.Method;
import java.util.List;
import org.skywalking.apm.agent.core.context.ContextCarrier;
import org.skywalking.apm.agent.core.context.ContextManager;
import org.skywalking.apm.agent.core.context.tag.Tags;
import org.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor;
import org.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.skywalking.apm.network.trace.component.ComponentsDefine;
/**
* {@link MongoDBCollectionMethodInterceptor} intercept method of {@link com.mongodb.DBCollection#find()}
* or{@link com.mongodb.DBCollectionImpl#insert}.... record the mongoDB host, operation name ...
*/
public class MongoDBCollectionMethodInterceptor implements InstanceMethodsAroundInterceptor, InstanceConstructorInterceptor {
private static final String DB_TYPE = "MongoDB";
private static final String MONGO_DB_OP_PREFIX = "MongoDB/";
@Override public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
String remotePeer = (String)objInst.getSkyWalkingDynamicField();
String carrier = null;
carrier = method.getName();
AbstractSpan span = ContextManager.createExitSpan(MONGO_DB_OP_PREFIX + carrier, new ContextCarrier(), remotePeer);
span.setComponent(ComponentsDefine.MONGODB);
Tags.DB_TYPE.set(span, DB_TYPE);
SpanLayer.asDB(span);
}
@Override public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Object ret) throws Throwable {
AbstractSpan activeSpan = ContextManager.activeSpan();
CommandResult cresult = null;
if (ret instanceof WriteResult) {
WriteResult wresult = (WriteResult)ret;
cresult = wresult.getCachedLastError();
} else if (ret instanceof AggregationOutput) {
AggregationOutput aresult = (AggregationOutput)ret;
cresult = aresult.getCommandResult();
}
if (null != cresult && !cresult.ok()) {
activeSpan.tag("CommandError", cresult.getErrorMessage());
}
ContextManager.stopSpan();
return ret;
}
@Override public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Throwable t) {
AbstractSpan activeSpan = ContextManager.activeSpan();
activeSpan.errorOccurred();
activeSpan.log(t);
}
@Override
public void onConstruct(EnhancedInstance objInst, Object[] allArguments) {
List<ServerAddress> servers = null;
DB db = (DB)allArguments[0];
servers = db.getMongo().getAllAddress();
StringBuilder peers = new StringBuilder();
for (ServerAddress address : servers) {
peers.append(address.getHost() + ":" + address.getPort() + ";");
}
objInst.setSkyWalkingDynamicField(peers.subSequence(0, peers.length() - 1).toString());
}
}

View File

@ -19,12 +19,10 @@
package org.skywalking.apm.plugin.mongodb.v2;
import com.mongodb.CommandResult;
import com.mongodb.DBEncoder;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.ServerAddress;
import com.mongodb.DB;
import com.mongodb.WriteResult;
import com.mongodb.AggregationOutput;
import java.lang.reflect.Method;
import java.util.List;
import org.skywalking.apm.agent.core.context.ContextCarrier;
@ -39,8 +37,8 @@ import org.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptR
import org.skywalking.apm.network.trace.component.ComponentsDefine;
/**
* {@link MongoDBV2MethodInterceptor} intercept method of {@link com.mongodb.DBCollection#find()}
* or{@link com.mongodb.DBCollectionImpl#insertImpl}.... record the mongoDB host, operation name ...
* {@link MongoDBV2MethodInterceptor} intercept method of {@link com.mongodb.DB#command(DBObject, DBEncoder)} ()}
* record the mongoDB host, operation name ...
*/
public class MongoDBV2MethodInterceptor implements InstanceMethodsAroundInterceptor, InstanceConstructorInterceptor {
@ -53,15 +51,13 @@ public class MongoDBV2MethodInterceptor implements InstanceMethodsAroundIntercep
Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
String remotePeer = (String)objInst.getSkyWalkingDynamicField();
String carrier = null;
String carrier = "command";
if (method.getName().equals("command")) {
DBObject obj = (DBObject)allArguments[0];
for (String key : obj.keySet()) {
carrier = key;
break;
}
} else {
carrier = method.getName();
}
AbstractSpan span = ContextManager.createExitSpan(MONGO_DB_OP_PREFIX + carrier, new ContextCarrier(), remotePeer);
span.setComponent(ComponentsDefine.MONGODB);
@ -74,15 +70,7 @@ public class MongoDBV2MethodInterceptor implements InstanceMethodsAroundIntercep
Class<?>[] argumentsTypes, Object ret) throws Throwable {
AbstractSpan activeSpan = ContextManager.activeSpan();
CommandResult cresult = null;
if (ret instanceof WriteResult) {
WriteResult wresult = (WriteResult)ret;
cresult = wresult.getCachedLastError();
} else if (ret instanceof CommandResult) {
cresult = (CommandResult)ret;
} else if (ret instanceof AggregationOutput) {
AggregationOutput aresult = (AggregationOutput)ret;
cresult = aresult.getCommandResult();
}
cresult = (CommandResult)ret;
if (null != cresult && !cresult.ok()) {
activeSpan.tag("CommandError", cresult.getErrorMessage());
}
@ -100,14 +88,8 @@ public class MongoDBV2MethodInterceptor implements InstanceMethodsAroundIntercep
@Override
public void onConstruct(EnhancedInstance objInst, Object[] allArguments) {
List<ServerAddress> servers = null;
if (allArguments[0] instanceof DB) {
DB db = (DB)allArguments[0];
servers = db.getMongo().getAllAddress();
} else if (allArguments[0] instanceof Mongo) {
Mongo mongo = (Mongo)allArguments[0];
servers = mongo.getAllAddress();
}
Mongo mongo = (Mongo)allArguments[0];
servers = mongo.getAllAddress();
StringBuilder peers = new StringBuilder();
for (ServerAddress address : servers) {
peers.append(address.getHost() + ":" + address.getPort() + ";");

View File

@ -38,7 +38,7 @@ public class MongoDBCollectionInstrumentation extends ClassInstanceMethodsEnhanc
private static final String ENHANCE_CLASS = "com.mongodb.DBCollection";
private static final String MONGDB_METHOD_INTERCET_CLASS = "org.skywalking.apm.plugin.mongodb.v2.MongoDBV2MethodInterceptor";
private static final String MONGDB_METHOD_INTERCET_CLASS = "org.skywalking.apm.plugin.mongodb.v2.MongoDBCollectionMethodInterceptor";
@Override
protected ConstructorInterceptPoint[] getConstructorsInterceptPoints() {

View File

@ -0,0 +1,125 @@
/*
* Copyright 2017, OpenSkywalking Organization All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Project repository: https://github.com/OpenSkywalking/skywalking
*/
package org.skywalking.apm.plugin.mongodb.v2;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import java.lang.reflect.Method;
import java.util.List;
import org.hamcrest.MatcherAssert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.skywalking.apm.agent.core.conf.Config;
import org.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.skywalking.apm.agent.core.context.trace.LogDataEntity;
import org.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.skywalking.apm.agent.core.context.util.KeyValuePair;
import org.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.skywalking.apm.agent.test.helper.SegmentHelper;
import org.skywalking.apm.agent.test.helper.SpanHelper;
import org.skywalking.apm.agent.test.tools.AgentServiceRule;
import org.skywalking.apm.agent.test.tools.SegmentStorage;
import org.skywalking.apm.agent.test.tools.SegmentStoragePoint;
import org.skywalking.apm.agent.test.tools.TracingSegmentRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import static org.skywalking.apm.agent.test.tools.SpanAssert.assertException;
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(TracingSegmentRunner.class)
public class MongoDBCollectionMethodInterceptorTest {
@SegmentStoragePoint
private SegmentStorage segmentStorage;
@Rule
public AgentServiceRule serviceRule = new AgentServiceRule();
private MongoDBCollectionMethodInterceptor interceptor;
@Mock
private EnhancedInstance enhancedInstance;
private Object[] arguments = new Object[3];
private Class[] argumentTypes;
@SuppressWarnings({"rawtypes", "unchecked"})
@Before
public void setUp() throws Exception {
interceptor = new MongoDBCollectionMethodInterceptor();
Config.Plugin.MongoDB.TRACE_PARAM = true;
when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn("127.0.0.1:27017");
}
@Test
public void testIntercept() throws Throwable {
interceptor.beforeMethod(enhancedInstance, getExecuteMethod(), null, null, null);
interceptor.afterMethod(enhancedInstance, getExecuteMethod(), null, null, null);
MatcherAssert.assertThat(segmentStorage.getTraceSegments().size(), is(1));
TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0);
List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment);
assertMongoSpan(spans.get(0));
}
@Test
public void testInterceptWithException() throws Throwable {
interceptor.beforeMethod(enhancedInstance, getExecuteMethod(), null, null, null);
interceptor.handleMethodException(enhancedInstance, getExecuteMethod(), null, null, new RuntimeException());
interceptor.afterMethod(enhancedInstance, getExecuteMethod(), null, null, null);
MatcherAssert.assertThat(segmentStorage.getTraceSegments().size(), is(1));
TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0);
List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment);
assertMongoSpan(spans.get(0));
List<LogDataEntity> logDataEntities = SpanHelper.getLogs(spans.get(0));
assertThat(logDataEntities.size(), is(1));
assertException(logDataEntities.get(0), RuntimeException.class);
}
private void assertMongoSpan(AbstractTracingSpan span) {
assertThat(span.getOperationName(), is("MongoDB/insert"));
assertThat(SpanHelper.getComponentId(span), is(9));
List<KeyValuePair> tags = SpanHelper.getTags(span);
assertThat(tags.get(0).getValue(), is("MongoDB"));
assertThat(span.isExit(), is(true));
assertThat(SpanHelper.getLayer(span), is(SpanLayer.DB));
}
private Method getExecuteMethod() {
try {
return DBCollection.class.getMethod("insert", DBObject[].class);
} catch (NoSuchMethodException e) {
return null;
}
}
}

View File

@ -18,7 +18,8 @@
package org.skywalking.apm.plugin.mongodb.v2;
import com.mongodb.Mongo;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBCollection;
import java.lang.reflect.Method;
import java.util.List;
import org.hamcrest.MatcherAssert;
@ -63,7 +64,7 @@ public class MongoDBV2MethodInterceptorTest {
@Mock
private EnhancedInstance enhancedInstance;
private Object[] arguments;
private Object[] arguments = new Object[3];
private Class[] argumentTypes;
@SuppressWarnings({"rawtypes", "unchecked"})
@ -76,11 +77,13 @@ public class MongoDBV2MethodInterceptorTest {
when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn("127.0.0.1:27017");
arguments[0] = BasicDBObjectBuilder.start().add("getCount", "name").get();
}
@Test
public void testIntercept() throws Throwable {
interceptor.beforeMethod(enhancedInstance, getExecuteMethod(), null, null, null);
interceptor.beforeMethod(enhancedInstance, getExecuteMethod(), arguments, null, null);
interceptor.afterMethod(enhancedInstance, getExecuteMethod(), null, null, null);
MatcherAssert.assertThat(segmentStorage.getTraceSegments().size(), is(1));
@ -105,7 +108,7 @@ public class MongoDBV2MethodInterceptorTest {
}
private void assertMongoSpan(AbstractTracingSpan span) {
assertThat(span.getOperationName(), is("MongoDB/getWriteConcern"));
assertThat(span.getOperationName(), is("MongoDB/command"));
assertThat(SpanHelper.getComponentId(span), is(9));
List<KeyValuePair> tags = SpanHelper.getTags(span);
assertThat(tags.get(0).getValue(), is("MongoDB"));
@ -115,7 +118,7 @@ public class MongoDBV2MethodInterceptorTest {
private Method getExecuteMethod() {
try {
return Mongo.class.getMethod("getWriteConcern");
return DBCollection.class.getMethod("getCount");
} catch (NoSuchMethodException e) {
return null;
}