From 7da8cc05c51844017978b3c0b1f441008265dda1 Mon Sep 17 00:00:00 2001 From: Hyun Jeong Date: Fri, 29 Aug 2014 12:56:52 +0900 Subject: [PATCH 01/18] [#4] Add support for RootSpan tracing to test modifier/interceptors. --- .../bootstrap/context/ReadableStorage.java | 12 ---- .../context/storage/ReadableSpanStorage.java | 48 ------------- .../storage/ReadableSpanStorageFactory.java | 13 ---- .../context/storage/HoldingSpanStorage.java | 36 ++++++++++ .../storage/HoldingSpanStorageFactory.java | 29 ++++++++ .../profiler/junit4/BasePinpointTest.java | 34 +++++++-- .../pinpoint/profiler/junit4/IsRootSpan.java | 15 ++++ .../junit4/PinpointJUnit4ClassRunner.java | 70 +++++++++++++------ .../pinpoint/profiler/util/MockAgent.java | 38 ++++++---- .../profiler/util/TestClassLoader.java | 5 ++ 10 files changed, 186 insertions(+), 114 deletions(-) delete mode 100644 bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/ReadableStorage.java delete mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/ReadableSpanStorage.java delete mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/ReadableSpanStorageFactory.java create mode 100644 profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/HoldingSpanStorage.java create mode 100644 profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/HoldingSpanStorageFactory.java create mode 100644 profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/IsRootSpan.java diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/ReadableStorage.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/ReadableStorage.java deleted file mode 100644 index b7126a384b3c..000000000000 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/ReadableStorage.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.nhn.pinpoint.bootstrap.context; - -import java.util.List; - -import com.nhn.pinpoint.common.bo.SpanEventBo; - -/** - * @author Hyun Jeong - */ -public interface ReadableStorage { - public List getSpanEventList(); -} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/ReadableSpanStorage.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/ReadableSpanStorage.java deleted file mode 100644 index c0560ed43e6c..000000000000 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/ReadableSpanStorage.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.nhn.pinpoint.profiler.context.storage; - -import java.util.ArrayList; -import java.util.List; - -import com.nhn.pinpoint.bootstrap.context.ReadableStorage; -import com.nhn.pinpoint.common.bo.SpanEventBo; -import com.nhn.pinpoint.profiler.context.Span; -import com.nhn.pinpoint.profiler.context.SpanEvent; - -/** - * @author Hyun Jeong - */ -public final class ReadableSpanStorage implements Storage, ReadableStorage { - - private List spanEventList = new ArrayList(10); - - @Override - public void store(SpanEvent spanEvent) { - if (spanEvent == null) { - throw new NullPointerException("spanEvent must not be null"); - } - final List spanEventList = this.spanEventList; - if (spanEventList != null) { - final SpanEventBo spanEventBo = new SpanEventBo(spanEvent.getSpan(), spanEvent); - spanEventList.add(spanEventBo); - } else { - throw new IllegalStateException("spanEventList is null"); - } - } - - @Override - public void store(Span span) { - if (span == null) { - throw new NullPointerException("span must not be null"); - } - this.spanEventList = null; - } - - @Override - public List getSpanEventList() { - if (this.spanEventList == null) { - throw new IllegalStateException("Trace not initialized or already completed."); - } - return this.spanEventList; - } - -} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/ReadableSpanStorageFactory.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/ReadableSpanStorageFactory.java deleted file mode 100644 index 3133286c155d..000000000000 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/ReadableSpanStorageFactory.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.nhn.pinpoint.profiler.context.storage; - -/** - * @author Hyun Jeong - */ -public class ReadableSpanStorageFactory implements StorageFactory { - - @Override - public Storage createStorage() { - return new ReadableSpanStorage(); - } - -} diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/HoldingSpanStorage.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/HoldingSpanStorage.java new file mode 100644 index 000000000000..1a22e9c7a32c --- /dev/null +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/HoldingSpanStorage.java @@ -0,0 +1,36 @@ +package com.nhn.pinpoint.profiler.context.storage; + +import org.apache.thrift.TBase; + +import com.nhn.pinpoint.profiler.context.Span; +import com.nhn.pinpoint.profiler.context.SpanEvent; +import com.nhn.pinpoint.profiler.sender.PeekableDataSender; + +/** + * @author hyungil.jeong + */ +public final class HoldingSpanStorage implements Storage { + + private final PeekableDataSender> dataSender; + + public HoldingSpanStorage(PeekableDataSender> dataSender) { + this.dataSender = dataSender; + } + + @Override + public void store(SpanEvent spanEvent) { + if (spanEvent == null) { + throw new NullPointerException("spanEvent must not be null"); + } + this.dataSender.send(spanEvent); + } + + @Override + public void store(Span span) { + if (span == null) { + throw new NullPointerException("span must not be null"); + } + this.dataSender.send(span); + } + +} diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/HoldingSpanStorageFactory.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/HoldingSpanStorageFactory.java new file mode 100644 index 000000000000..53fb69ab0252 --- /dev/null +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/HoldingSpanStorageFactory.java @@ -0,0 +1,29 @@ +package com.nhn.pinpoint.profiler.context.storage; + +import com.nhn.pinpoint.profiler.sender.DataSender; +import com.nhn.pinpoint.profiler.sender.PeekableDataSender; + +/** + * @author hyungil.jeong + */ +public class HoldingSpanStorageFactory implements StorageFactory { + + private final PeekableDataSender dataSender; + + public HoldingSpanStorageFactory(DataSender dataSender) { + if (dataSender == null) { + throw new NullPointerException("dataSender must not be null"); + } + if (dataSender instanceof PeekableDataSender) { + this.dataSender = (PeekableDataSender)dataSender; + } else { + throw new IllegalArgumentException("dataSender must be an instance of PeekableDataSender."); + } + } + + @Override + public Storage createStorage() { + return new HoldingSpanStorage(this.dataSender); + } + +} diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/BasePinpointTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/BasePinpointTest.java index 64f8d1969799..16fac5f58387 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/BasePinpointTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/BasePinpointTest.java @@ -1,26 +1,48 @@ package com.nhn.pinpoint.profiler.junit4; +import java.util.ArrayList; import java.util.List; +import org.apache.thrift.TBase; import org.junit.runner.RunWith; -import com.nhn.pinpoint.bootstrap.context.ReadableStorage; +import com.nhn.pinpoint.common.bo.SpanBo; import com.nhn.pinpoint.common.bo.SpanEventBo; +import com.nhn.pinpoint.profiler.context.Span; +import com.nhn.pinpoint.profiler.context.SpanEvent; +import com.nhn.pinpoint.profiler.sender.PeekableDataSender; import com.nhn.pinpoint.profiler.util.TestClassLoader; /** * @author hyungil.jeong */ -@RunWith(value=PinpointJUnit4ClassRunner.class) +@RunWith(value = PinpointJUnit4ClassRunner.class) @PinpointTestClassLoader(TestClassLoader.class) public abstract class BasePinpointTest { - private ThreadLocal traceHolder = new ThreadLocal(); + private ThreadLocal>> traceHolder = new ThreadLocal>>(); protected final List getCurrentSpanEvents() { - return this.traceHolder.get().getSpanEventList(); + List spanEvents = new ArrayList(); + for (TBase span : this.traceHolder.get()) { + if (span instanceof SpanEvent) { + SpanEvent spanEvent = (SpanEvent)span; + spanEvents.add(new SpanEventBo(spanEvent.getSpan(), spanEvent)); + } + } + return spanEvents; } - final void setCurrentStorage(ReadableStorage spanStorage) { - traceHolder.set(spanStorage); + protected final List getCurrentRootSpans() { + List rootSpans = new ArrayList(); + for (TBase span : this.traceHolder.get()) { + if (span instanceof Span) { + rootSpans.add(new SpanBo((Span)span)); + } + } + return rootSpans; + } + + final void setCurrentHolder(PeekableDataSender> dataSender) { + traceHolder.set(dataSender); } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/IsRootSpan.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/IsRootSpan.java new file mode 100644 index 000000000000..def727813861 --- /dev/null +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/IsRootSpan.java @@ -0,0 +1,15 @@ +package com.nhn.pinpoint.profiler.junit4; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author hyungil.jeong + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface IsRootSpan { + boolean value() default true; +} diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java index aff1cc685a9b..0fb3a3c740a1 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java @@ -6,6 +6,8 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import org.apache.thrift.TBase; +import org.junit.internal.runners.model.EachTestNotifier; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; @@ -21,8 +23,8 @@ import com.nhn.pinpoint.common.ServiceType; import com.nhn.pinpoint.profiler.DefaultAgent; import com.nhn.pinpoint.profiler.DummyInstrumentation; -import com.nhn.pinpoint.profiler.context.DefaultTrace; import com.nhn.pinpoint.profiler.logging.Slf4jLoggerBinder; +import com.nhn.pinpoint.profiler.sender.PeekableDataSender; import com.nhn.pinpoint.profiler.util.MockAgent; import com.nhn.pinpoint.profiler.util.TestClassLoader; @@ -37,13 +39,16 @@ public final class PinpointJUnit4ClassRunner extends BlockJUnit4ClassRunner { private final TestClassLoader testClassLoader; private final TestContext testContext; private final DefaultAgent testAgent; + private final PeekableDataSender> testDataSender; public PinpointJUnit4ClassRunner(Class clazz) throws InitializationError { super(clazz); if (logger.isDebugEnabled()) { logger.debug("PinpointJUnit4ClassRunner constructor called with [" + clazz + "]."); } - this.testAgent = createTestAgent(); + MockAgent testAgent = createTestAgent(); + this.testAgent = testAgent; + this.testDataSender = testAgent.getPeekableSpanDataSender(); this.testClassLoader = getTestClassLoader(clazz); this.testClassLoader.initialize(); try { @@ -64,7 +69,7 @@ public PinpointJUnit4ClassRunner(Class clazz) throws InitializationError { } } - private DefaultAgent createTestAgent() throws InitializationError { + private MockAgent createTestAgent() throws InitializationError { PLoggerFactory.initialize(new Slf4jLoggerBinder()); ProfilerConfig profilerConfig = new ProfilerConfig(); @@ -91,7 +96,7 @@ private Class findPinpointTestClassLoaderAnnotationForClass(Class testClas } private TestClassLoader getTestClassLoader(Class testClass) throws InitializationError { - Class classWithPinpointTestClassLoaderAnnotationSpecified = findPinpointTestClassLoaderAnnotationForClass(testClass); + Class classWithPinpointTestClassLoaderAnnotationSpecified = findPinpointTestClassLoaderAnnotationForClass(testClass); if (classWithPinpointTestClassLoaderAnnotationSpecified == null) { if (logger.isInfoEnabled()) { logger.info(String.format("@PinpointTestClassLoader not found for class [%s]", testClass)); @@ -119,51 +124,72 @@ private TestClassLoader createTestClassLoader(Class< @Override protected void runChild(FrameworkMethod method, RunNotifier notifier) { - TraceContext traceContext = this.testAgent.getTraceContext(); - beginTracing(traceContext); + beginTracing(method); ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.testClassLoader); super.runChild(method, notifier); } finally { Thread.currentThread().setContextClassLoader(originalClassLoader); - endTracing(traceContext); + endTracing(method, notifier); } } - // TODO refine root trace parameters for test - private void beginTracing(TraceContext traceContext) { - Trace trace = traceContext.newTraceObject(); - trace.markBeforeTime(); - trace.recordServiceType(ServiceType.TEST); + private void beginTracing(FrameworkMethod method) { + if (shouldCreateNewTraceObject(method)) { + TraceContext traceContext = this.testAgent.getTraceContext(); + Trace trace = traceContext.newTraceObject(); + trace.markBeforeTime(); + trace.recordServiceType(ServiceType.TEST); + } } - private void endTracing(TraceContext traceContext) { - try { - Trace trace = traceContext.currentRawTraceObject(); + private void endTracing(FrameworkMethod method, RunNotifier notifier) { + if (shouldCreateNewTraceObject(method)) { + TraceContext traceContext = this.testAgent.getTraceContext(); try { - trace.markAfterTime(); + Trace trace = traceContext.currentRawTraceObject(); + if (trace == null) { + // Trace is already detached from the ThreadLocal storage. + // Happens when root trace method is tested without @IsRootSpan. + EachTestNotifier testMethodNotifier = new EachTestNotifier(notifier, super.describeChild(method)); + String traceObjectAlreadyDetachedMessage = "Trace object already detached. If you're testing a trace root, please add @IsRootSpan to the test method"; + testMethodNotifier.addFailure(new IllegalStateException(traceObjectAlreadyDetachedMessage)); + } else { + try { + trace.markAfterTime(); + } finally { + trace.traceRootBlockEnd(); + } + } } finally { - trace.traceRootBlockEnd(); + traceContext.detachTraceObject(); } - } finally { - traceContext.detachTraceObject(); } } + private boolean shouldCreateNewTraceObject(FrameworkMethod method) { + IsRootSpan isRootSpan = method.getAnnotation(IsRootSpan.class); + if (isRootSpan == null || !isRootSpan.value()) { + return true; + } + return false; + } + @Override protected Statement methodInvoker(FrameworkMethod method, Object test) { // TestContext의 baseTestClass는 BasePinpointTest이므로, 캐스팅해도 된다. @SuppressWarnings("unchecked") Class baseTestClass = (Class)this.testContext.getBaseTestClass(); if (baseTestClass.isInstance(test)) { - DefaultTrace currentTrace = (DefaultTrace)this.testAgent.getTraceContext().currentRawTraceObject(); Method[] methods = baseTestClass.getDeclaredMethods(); for (Method m : methods) { - if (m.getName().equals("setCurrentStorage")) { + if (m.getName().equals("setCurrentHolder")) { try { + // 각 테스트 메소드 마다 PeekableDataSender를 reset 함. + this.testDataSender.clear(); m.setAccessible(true); - m.invoke(test, currentTrace.getStorage()); + m.invoke(test, this.testDataSender); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/MockAgent.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/MockAgent.java index 9ee15b8239d7..e3cf55e01bfa 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/MockAgent.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/MockAgent.java @@ -2,20 +2,24 @@ import java.lang.instrument.Instrumentation; +import org.apache.thrift.TBase; + import com.nhn.pinpoint.bootstrap.config.ProfilerConfig; import com.nhn.pinpoint.profiler.DefaultAgent; import com.nhn.pinpoint.profiler.DummyInstrumentation; -import com.nhn.pinpoint.profiler.context.storage.ReadableSpanStorageFactory; +import com.nhn.pinpoint.profiler.context.storage.HoldingSpanStorageFactory; import com.nhn.pinpoint.profiler.context.storage.StorageFactory; import com.nhn.pinpoint.profiler.sender.DataSender; import com.nhn.pinpoint.profiler.sender.EnhancedDataSender; import com.nhn.pinpoint.profiler.sender.LoggingDataSender; +import com.nhn.pinpoint.profiler.sender.PeekableDataSender; import com.nhn.pinpoint.rpc.client.PinpointSocket; import com.nhn.pinpoint.rpc.client.PinpointSocketFactory; /** * @author emeroad * @author koo.taejin + * @author hyungil.jeong */ public class MockAgent extends DefaultAgent { @@ -29,33 +33,41 @@ public MockAgent(String agentArgs, Instrumentation instrumentation, ProfilerConf @Override protected DataSender createUdpDataSender(int port, String threadName, int writeQueueSize, int timeout, int sendBufferSize) { - return new LoggingDataSender(); + return new PeekableDataSender>(); } - @Override + public PeekableDataSender getPeekableSpanDataSender() { + DataSender spanDataSender = getSpanDataSender(); + if (spanDataSender instanceof PeekableDataSender) { + return (PeekableDataSender)getSpanDataSender(); + } else { + throw new IllegalStateException("UdpDataSender must be an instance of a PeekableDataSender. Found : " + spanDataSender.getClass().getName()); + } + } + + @Override protected StorageFactory createStorageFactory() { - return new ReadableSpanStorageFactory(); + return new HoldingSpanStorageFactory(getSpanDataSender()); } - - + @Override protected PinpointSocketFactory createPinpointSocketFactory() { - return null; + return null; } - + @Override protected PinpointSocket createPinpointSocket(String host, int port, PinpointSocketFactory factory) { - return null; + return null; } - + @Override protected PinpointSocket createPinpointSocket(String host, int port, PinpointSocketFactory factory, boolean useMessageListener) { - return null; + return null; } - + @Override protected EnhancedDataSender createTcpDataSender(PinpointSocket socket) { return new LoggingDataSender(); } - + } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/TestClassLoader.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/TestClassLoader.java index d6719bceff94..764937dcc2ee 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/TestClassLoader.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/TestClassLoader.java @@ -112,6 +112,11 @@ public Modifier addModifier(Modifier modifier) { private void addDefaultDelegateLoadingOf() { this.delegateLoadingOf("com.nhn.pinpoint.bootstrap."); this.delegateLoadingOf("com.nhn.pinpoint.common."); + this.delegateLoadingOf("com.nhn.pinpoint.thrift."); + this.delegateLoadingOf("com.nhn.pinpoint.profiler.context."); + this.delegateLoadingOf("com.nhn.pinpoint.profiler.sender.PeekableDataSender"); + this.delegateLoadingOf("com.nhn.pinpoint.profiler.junit4.IsRootSpan"); + this.delegateLoadingOf("org.apache.thrift.TBase"); this.delegateLoadingOf("junit."); this.delegateLoadingOf("org.hamcrest."); this.delegateLoadingOf("org.junit."); From 387df4198f5024afb49fc438ea37c7f0bcf8edac Mon Sep 17 00:00:00 2001 From: Hyun Jeong Date: Fri, 29 Aug 2014 13:22:59 +0900 Subject: [PATCH 02/18] [#4] Added StandardHostValveInvokeModifier root span trace test. --- pom.xml | 5 + profiler/pom.xml | 5 + .../StandardHostValveInvokeModifierTest.java | 137 ++++++++++++++++++ 3 files changed, 147 insertions(+) create mode 100644 profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardHostValveInvokeModifierTest.java diff --git a/pom.xml b/pom.xml index 688b99d4458e..3677c05b256a 100644 --- a/pom.xml +++ b/pom.xml @@ -409,6 +409,11 @@ catalina 6.0.35 + + org.apache.tomcat + coyote + 6.0.35 + arcus diff --git a/profiler/pom.xml b/profiler/pom.xml index 92142aed8a04..5ee9af8615fe 100644 --- a/profiler/pom.xml +++ b/profiler/pom.xml @@ -258,6 +258,11 @@ catalina provided + + org.apache.tomcat + coyote + test + arcus diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardHostValveInvokeModifierTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardHostValveInvokeModifierTest.java new file mode 100644 index 000000000000..03e3339173e7 --- /dev/null +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardHostValveInvokeModifierTest.java @@ -0,0 +1,137 @@ +package com.nhn.pinpoint.profiler.modifier.tomcat; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import java.util.Enumeration; +import java.util.List; + +import org.apache.catalina.connector.Request; +import org.apache.catalina.connector.Response; +import org.apache.catalina.core.StandardHost; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import com.nhn.pinpoint.bootstrap.context.Header; +import com.nhn.pinpoint.common.ServiceType; +import com.nhn.pinpoint.common.bo.SpanBo; +import com.nhn.pinpoint.common.util.TransactionIdUtils; +import com.nhn.pinpoint.profiler.junit4.BasePinpointTest; +import com.nhn.pinpoint.profiler.junit4.IsRootSpan; + +/** + * @author hyungil.jeong + */ +public class StandardHostValveInvokeModifierTest extends BasePinpointTest { + + private static final ServiceType SERVICE_TYPE = ServiceType.TOMCAT; + private static final String REQUEST_URI = "testRequestUri"; + private static final String SERVER_NAME = "serverForTest"; + private static final int SERVER_PORT = 19999; + private static final String REMOTE_ADDRESS = "1.1.1.1"; + private static final Enumeration EMPTY_PARAM_KEYS = new Enumeration() { + @Override + public boolean hasMoreElements() { + return false; + } + + @Override + public String nextElement() { + return null; + } + }; + + private StandardHost host; + + @Mock + private Request mockRequest; + @Mock + private Response mockResponse; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + initMockRequest(); + // StandardHost's default constructor sets StandardHostValve as the first item in the pipeline. + host = new StandardHost(); + } + + private void initMockRequest() { + when(mockRequest.getRequestURI()).thenReturn(REQUEST_URI); + when(mockRequest.getServerName()).thenReturn(SERVER_NAME); + when(mockRequest.getServerPort()).thenReturn(SERVER_PORT); + when(mockRequest.getRemoteAddr()).thenReturn(REMOTE_ADDRESS); + when(mockRequest.getParameterNames()).thenReturn(EMPTY_PARAM_KEYS); + } + + @Test + @IsRootSpan + public void invokeShouldBeTraced() throws Exception { + // Given + // When + host.invoke(mockRequest, mockResponse); + // Then + final List rootSpans = getCurrentRootSpans(); + assertEquals(rootSpans.size(), 1); + + final SpanBo rootSpan = rootSpans.get(0); + assertEquals(rootSpan.getParentSpanId(), -1); + assertEquals(rootSpan.getServiceType(), SERVICE_TYPE); + assertEquals(rootSpan.getRpc(), REQUEST_URI); + assertEquals(rootSpan.getEndPoint(), SERVER_NAME + ":" + SERVER_PORT); + assertEquals(rootSpan.getRemoteAddr(), REMOTE_ADDRESS); + } + + @Test + @IsRootSpan + public void invokeShouldTraceExceptions() throws Exception { + // Given + when(mockRequest.getContext()).thenThrow(new RuntimeException("expected exception.")); + // When + try { + host.invoke(mockRequest, mockResponse); + assertTrue(false); + } catch (RuntimeException e) { + // Then + final List rootSpans = getCurrentRootSpans(); + assertEquals(rootSpans.size(), 1); + + final SpanBo rootSpan = rootSpans.get(0); + assertEquals(rootSpan.getParentSpanId(), -1); + assertEquals(rootSpan.getServiceType(), SERVICE_TYPE); + assertTrue(rootSpan.hasException()); + } + } + + @Test + @IsRootSpan + public void invokeShouldContinueTracingFromRequest() throws Exception { + // Given + // Set Transaction ID from remote source. + final String sourceAgentId = "agentId"; + final long sourceAgentStartTime = 1234567890123L; + final long sourceTransactionSequence = 12345678L; + final String sourceTransactionId = TransactionIdUtils.formatString(sourceAgentId, sourceAgentStartTime, sourceTransactionSequence); + when(mockRequest.getHeader(Header.HTTP_TRACE_ID.toString())).thenReturn(sourceTransactionId); + // Set parent Span ID from remote source. + final long sourceParentId = 99999; + when(mockRequest.getHeader(Header.HTTP_PARENT_SPAN_ID.toString())).thenReturn(String.valueOf(sourceParentId)); + // When + host.invoke(mockRequest, mockResponse); + // Then + final List rootSpans = getCurrentRootSpans(); + assertEquals(rootSpans.size(), 1); + + final SpanBo rootSpan = rootSpans.get(0); + // Check Transaction ID from remote source. + assertEquals(rootSpan.getTransactionId(), sourceTransactionId); + assertEquals(rootSpan.getTraceAgentId(), sourceAgentId); + assertEquals(rootSpan.getTraceAgentStartTime(), sourceAgentStartTime); + assertEquals(rootSpan.getTraceTransactionSequence(), sourceTransactionSequence); + // Check parent Span ID from remote source. + assertEquals(rootSpan.getParentSpanId(), sourceParentId); + } + +} From 5bd0562ecef74af0acd672bd067d1c7f8b248f1e Mon Sep 17 00:00:00 2001 From: koo-taejin Date: Thu, 4 Sep 2014 18:55:30 +0900 Subject: [PATCH 03/18] =?UTF-8?q?#5=20Pinpoint=20=ED=81=B4=EB=9F=AC?= =?UTF-8?q?=EC=8A=A4=ED=84=B0=20=EA=B0=9C=EB=B0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Pinpoint web에서 클러스터 등록시 해당 acceptor로 연결할수 있는 기능 지원 - cluster 지원 설정 추가 - 상태값 보강 - 로그 강화 --- .../collector/cluster/ClusterPoint.java | 5 + .../collector/cluster/ClusterService.java | 13 + .../cluster/PinpointClusterManager.java | 14 - .../collector/cluster/WebClusterPoint.java | 130 +++ .../collector/cluster/WorkerState.java | 13 + .../collector/cluster/WorkerStateContext.java | 45 + .../cluster/zookeeper/ZookeeperClient.java | 464 ++++++----- .../zookeeper/ZookeeperClusterManager.java | 179 ---- .../zookeeper/ZookeeperClusterService.java | 209 +++++ .../zookeeper/ZookeeperLatestJobWorker.java | 776 +++++++++--------- .../ZookeeperProfilerClusterManager.java | 194 +++++ .../cluster/zookeeper/ZookeeperUtils.java | 47 ++ .../zookeeper/ZookeeperWebClusterManager.java | 229 ++++++ .../config/CollectorConfiguration.java | 50 ++ .../pinpoint-collector.properties | 92 ++- .../pinpoint-collector.properties | 92 ++- .../pinpoint-collector.properties | 92 ++- .../pinpoint-collector.properties | 92 ++- .../src/main/resources/applicationContext.xml | 238 +++--- ...erEnsembleProfilerClusterServiceTest.java} | 479 ++++++----- .../ZookeeperProfilerClusterServiceTest.java} | 524 ++++++------ .../ZookeeperWebClusterServiceTest.java | 136 +++ .../controller/ScatterChartController.java | 621 +++++++------- .../web/server/PinpointSocketManager.java | 1 + 24 files changed, 2868 insertions(+), 1867 deletions(-) create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPoint.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterService.java delete mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/PinpointClusterManager.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebClusterPoint.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerState.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerStateContext.java delete mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterManager.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperUtils.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java rename collector/src/test/java/com/navercorp/pinpoint/collector/cluster/{ZookeeperClusterManagerTest2.java => zookeeper/ZookeeperEnsembleProfilerClusterServiceTest.java} (71%) rename collector/src/test/java/com/navercorp/pinpoint/collector/cluster/{ZookeeperClusterManagerTest.java => zookeeper/ZookeeperProfilerClusterServiceTest.java} (66%) create mode 100644 collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterServiceTest.java diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPoint.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPoint.java new file mode 100644 index 000000000000..93555d5326c4 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPoint.java @@ -0,0 +1,5 @@ +package com.nhn.pinpoint.collector.cluster; + +public interface ClusterPoint { + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterService.java new file mode 100644 index 000000000000..e37e93ccbf4b --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterService.java @@ -0,0 +1,13 @@ +package com.nhn.pinpoint.collector.cluster; + + +/** + * @author koo.taejin + */ +public interface ClusterService { + + void setUp() throws Exception; + + void tearDown() throws Exception; + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/PinpointClusterManager.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/PinpointClusterManager.java deleted file mode 100644 index 9003b279e1d6..000000000000 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/PinpointClusterManager.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.nhn.pinpoint.collector.cluster; - -import com.nhn.pinpoint.rpc.server.ChannelContext; - -/** - * @author koo.taejin - */ -public interface PinpointClusterManager { - - void register(ChannelContext channelContext); - - void unregister(ChannelContext channelContext); - -} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebClusterPoint.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebClusterPoint.java new file mode 100644 index 000000000000..fb77a58dda56 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebClusterPoint.java @@ -0,0 +1,130 @@ +package com.nhn.pinpoint.collector.cluster; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jboss.netty.channel.Channel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nhn.pinpoint.rpc.PinpointSocketException; +import com.nhn.pinpoint.rpc.client.MessageListener; +import com.nhn.pinpoint.rpc.client.PinpointSocket; +import com.nhn.pinpoint.rpc.client.PinpointSocketFactory; +import com.nhn.pinpoint.rpc.packet.RequestPacket; +import com.nhn.pinpoint.rpc.packet.SendPacket; + +/** + * @author koo.taejin + */ +public class WebClusterPoint implements ClusterPoint { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final PinpointSocketFactory factory; + + // InetSocketAddress List로 전달 하는게 좋을거 같은데 이걸 Key로만들기가 쉽지 않네; + + private final Map clusterRepository = new HashMap(); + + public WebClusterPoint(String id) { + factory = new PinpointSocketFactory(); + factory.setTimeoutMillis(1000 * 5); + + Map properties = new HashMap(); + properties.put("id", id); + + factory.setProperties(properties); + } + + // Not safe for use by multiple threads. + public void connectPointIfAbsent(InetSocketAddress address) { + logger.info("localhost -> {} connect started.", address); + + if (clusterRepository.containsKey(address)) { + logger.info("localhost -> {} already connected.", address); + return; + } + + PinpointSocket socket = createPinpointSocket(address); + clusterRepository.put(address, socket); + + logger.info("localhost -> {} connect completed.", address); + } + + // Not safe for use by multiple threads. + public void disconnectPoint(InetSocketAddress address) { + logger.info("localhost -> {} disconnect started.", address); + + PinpointSocket socket = clusterRepository.remove(address); + if (socket != null) { + socket.close(); + logger.info("localhost -> {} disconnect completed.", address); + } else { + logger.info("localhost -> {} already disconnected.", address); + } + } + + private PinpointSocket createPinpointSocket(InetSocketAddress address) { + MessageListener messageListener = new SimpleMessageListener(address); + + String host = address.getHostName(); + int port = address.getPort(); + + PinpointSocket socket = null; + for (int i = 0; i < 3; i++) { + try { + socket = factory.connect(host, port, messageListener); + logger.info("tcp connect success:{}/{}", host, port); + return socket; + } catch (PinpointSocketException e) { + logger.warn("tcp connect fail:{}/{} try reconnect, retryCount:{}", host, port, i); + } + } + logger.warn("change background tcp connect mode {}/{} ", host, port); + socket = factory.scheduledConnect(host, port, messageListener); + + return socket; + } + + public List getWebClusterList() { + return new ArrayList(clusterRepository.keySet()); + } + + public void close() { + for (PinpointSocket socket : clusterRepository.values()) { + if (socket != null) { + socket.close(); + } + } + + if (factory != null) { + factory.release(); + } + } + + class SimpleMessageListener implements MessageListener { + + private final InetSocketAddress address; + + public SimpleMessageListener(InetSocketAddress address) { + this.address = address; + } + + @Override + public void handleSend(SendPacket sendPacket, Channel channel) { + logger.info("{} receive send Message {}", address, sendPacket); + // TODO Auto-generated method stub + + } + + @Override + public void handleRequest(RequestPacket requestPacket, Channel channel) { + logger.info("{} receive Request Message {}", address, requestPacket); + } + + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerState.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerState.java new file mode 100644 index 000000000000..c26f2412ebcc --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerState.java @@ -0,0 +1,13 @@ +package com.nhn.pinpoint.collector.cluster; + + +public enum WorkerState { + + NEW, + INITIALIZING, + STARTED, + DESTROYING, + STOPPED, + ILLEGAL_STATE + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerStateContext.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerStateContext.java new file mode 100644 index 000000000000..6371c7ecd189 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerStateContext.java @@ -0,0 +1,45 @@ +package com.nhn.pinpoint.collector.cluster; + +import java.util.concurrent.atomic.AtomicReference; + +public class WorkerStateContext { + + private final AtomicReference currentState = new AtomicReference(); + + public WorkerStateContext() { + currentState.set(WorkerState.NEW); + } + + public WorkerState getCurrentState() { + return currentState.get(); + } + + public boolean changeStateInitializing() { + return currentState.compareAndSet(WorkerState.NEW, WorkerState.INITIALIZING); + } + + public boolean changeStateStarted() { + return currentState.compareAndSet(WorkerState.INITIALIZING, WorkerState.STARTED); + } + + public boolean changeStateDestroying() { + return currentState.compareAndSet(WorkerState.STARTED, WorkerState.DESTROYING); + } + + public boolean changeStateStoped() { + return currentState.compareAndSet(WorkerState.DESTROYING, WorkerState.STOPPED); + } + + public boolean changeStateIllegal() { + currentState.set(WorkerState.ILLEGAL_STATE); + return true; + } + + public boolean isStarted() { + if (currentState.get() == WorkerState.STARTED) { + return true; + } else { + return false; + } + } +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java index 30efcbe25083..3090f1678b5c 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java @@ -1,214 +1,250 @@ -package com.nhn.pinpoint.collector.cluster.zookeeper; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.KeeperException.Code; -import org.apache.zookeeper.ZooDefs.Ids; -import org.apache.zookeeper.ZooKeeper; -import org.apache.zookeeper.data.Stat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.nhn.pinpoint.collector.cluster.zookeeper.ZookeeperEventWatcher; -import com.nhn.pinpoint.collector.cluster.zookeeper.exception.AuthException; -import com.nhn.pinpoint.collector.cluster.zookeeper.exception.BadOperationException; -import com.nhn.pinpoint.collector.cluster.zookeeper.exception.ConnectionException; -import com.nhn.pinpoint.collector.cluster.zookeeper.exception.PinpointZookeeperException; -import com.nhn.pinpoint.collector.cluster.zookeeper.exception.TimeoutException; -import com.nhn.pinpoint.collector.cluster.zookeeper.exception.UnknownException; - -/** - * @author koo.taejin - */ -public class ZookeeperClient { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - // 쥬키퍼 클라이언트는 스레드 세이프함 - private final ZooKeeper zookeeper; - private final AtomicBoolean clientState = new AtomicBoolean(true); - - private final ZookeeperEventWatcher watcher; - - // 데이터를 이친구가 다가지고 있어야 할 거 같은데; - public ZookeeperClient(String hostPort, int sessionTimeout, ZookeeperEventWatcher watcher) throws KeeperException, IOException, InterruptedException { - this.watcher = watcher; - zookeeper = new ZooKeeper(hostPort, sessionTimeout, this.watcher); // server - } - - /** - * path의 가장마지막에 있는 node는 생성하지 않는다. - * - * @throws PinpointZookeeperException - * @throws InterruptedException - */ - public void createPath(String path) throws PinpointZookeeperException, InterruptedException { - checkState(); - - int pos = 1; - do { - pos = path.indexOf('/', pos + 1); - - if (pos == -1) { - pos = path.length(); - return; - } - - try { - String subPath = path.substring(0, pos); - if (zookeeper.exists(subPath, false) != null) { - continue; - } - - zookeeper.create(subPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); - } catch (KeeperException exception) { - if (exception.code() != Code.NODEEXISTS) { - handleException(exception); - } - } - - } while (pos < path.length()); - } - -// 이미있는 노드가 괜찮은건지 검사 필요없을거 같긴한데, 혹시나 이건 일단 주석으로 -// Stat stat = zookeeper.exists(node, false); -// if (stat != null) { -// byte[] result = zookeeper.getData(node, false, stat); -// if (byte[] array같은지 검사) { -// return node; -// } -// } - - - // 데이터를 어떤식으로 넣지? - public String createNode(String znodePath, byte[] data) throws PinpointZookeeperException, InterruptedException { - checkState(); - - try { - if (zookeeper.exists(znodePath, false) != null) { - return znodePath; - } - - String pathName = zookeeper.create(znodePath, data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); - return pathName; - } catch (KeeperException exception) { - if (exception.code() != Code.NODEEXISTS) { - handleException(exception); - } - } - return znodePath; - } - - public byte[] getData(String path) throws PinpointZookeeperException, InterruptedException { - checkState(); - - try { - return zookeeper.getData(path, false, null); - } catch (KeeperException exception) { - handleException(exception); - } - - throw new UnknownException("UnknownException."); - } - - public void setData(String path, byte[] data) throws PinpointZookeeperException, InterruptedException { - checkState(); - - try { - if (zookeeper.exists(path, false) == null) { - return; - } - - zookeeper.setData(path, data, -1); - } catch (KeeperException exception) { - handleException(exception); - } - } - - public void delete(String path) throws PinpointZookeeperException, InterruptedException { - checkState(); - - try { - zookeeper.delete(path, -1); - } catch (KeeperException exception) { - if (exception.code() != Code.NONODE) { - handleException(exception); - } - } - } - - public boolean exists(String path) throws PinpointZookeeperException, InterruptedException { - checkState(); - - try { - Stat stat = zookeeper.exists(path, false); - if (stat == null) { - return false; - } - } catch (KeeperException exception) { - if (exception.code() != Code.NODEEXISTS) { - handleException(exception); - } - } - return true; - } - - private void checkState() throws PinpointZookeeperException { - if (!watcher.isConnected() || !clientState.get()) { - throw new ConnectionException("instance must be connected."); - } - } - -// public byte[] getData(String path) throws KeeperException, InterruptedException { -// checkState(); -// -// return zookeeper.getData(path, false, null); -// } -// -// public List getChildrenNode(String path) throws KeeperException, InterruptedException { -// checkState(); -// -// List childNodeList = zookeeper.getChildren(path, false); -// logger.info("ChildNode List = {}", childNodeList); -// return childNodeList; -// } - - private void handleException(KeeperException keeperException) throws PinpointZookeeperException { - switch (keeperException.code()) { - case CONNECTIONLOSS: - case SESSIONEXPIRED: - throw new ConnectionException(keeperException.getMessage(), keeperException); - case AUTHFAILED: - case INVALIDACL: - case NOAUTH: - throw new AuthException(keeperException.getMessage(), keeperException); - case BADARGUMENTS: - case BADVERSION: - case NOCHILDRENFOREPHEMERALS: - case NOTEMPTY: - case NODEEXISTS: - case NONODE: - throw new BadOperationException(keeperException.getMessage(), keeperException); - case OPERATIONTIMEOUT: - throw new TimeoutException(keeperException.getMessage(), keeperException); - default: - throw new UnknownException(keeperException.getMessage(), keeperException); - } - } - - public void close() { - if (clientState.compareAndSet(true, false)) { - if (zookeeper != null) { - try { - zookeeper.close(); - } catch (InterruptedException ignore) { - logger.debug(ignore.getMessage(), ignore); - } - } - } - } - -} +package com.nhn.pinpoint.collector.cluster.zookeeper; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.KeeperException.Code; +import org.apache.zookeeper.ZooDefs.Ids; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.data.Stat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nhn.pinpoint.collector.cluster.zookeeper.exception.AuthException; +import com.nhn.pinpoint.collector.cluster.zookeeper.exception.BadOperationException; +import com.nhn.pinpoint.collector.cluster.zookeeper.exception.ConnectionException; +import com.nhn.pinpoint.collector.cluster.zookeeper.exception.PinpointZookeeperException; +import com.nhn.pinpoint.collector.cluster.zookeeper.exception.TimeoutException; +import com.nhn.pinpoint.collector.cluster.zookeeper.exception.UnknownException; + +/** + * @author koo.taejin + */ +public class ZookeeperClient { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + // 쥬키퍼 클라이언트는 스레드 세이프함 + private final ZooKeeper zookeeper; + private final AtomicBoolean clientState = new AtomicBoolean(true); + + private final ZookeeperEventWatcher watcher; + + // 데이터를 이친구가 다가지고 있어야 할 거 같은데; + public ZookeeperClient(String hostPort, int sessionTimeout, ZookeeperEventWatcher watcher) throws KeeperException, IOException, InterruptedException { + this.watcher = watcher; + zookeeper = new ZooKeeper(hostPort, sessionTimeout, this.watcher); // server + } + + /** + * path의 가장마지막에 있는 node는 생성하지 않는다. + * + * @throws PinpointZookeeperException + * @throws InterruptedException + */ + public void createPath(String path) throws PinpointZookeeperException, InterruptedException { + createPath(path, false); + } + + public void createPath(String path, boolean createEndNode) throws PinpointZookeeperException, InterruptedException { + checkState(); + + int pos = 1; + do { + pos = path.indexOf('/', pos + 1); + + if (pos == -1) { + pos = path.length(); + } + + try { + if (pos == path.length()) { + if (!createEndNode) { + return; + } + } + + String subPath = path.substring(0, pos); + if (zookeeper.exists(subPath, false) != null) { + continue; + } + + zookeeper.create(subPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + } catch (KeeperException exception) { + if (exception.code() != Code.NODEEXISTS) { + handleException(exception); + } + } + + } while (pos < path.length()); + } + + +// 이미있는 노드가 괜찮은건지 검사 필요없을거 같긴한데, 혹시나 이건 일단 주석으로 +// Stat stat = zookeeper.exists(node, false); +// if (stat != null) { +// byte[] result = zookeeper.getData(node, false, stat); +// if (byte[] array같은지 검사) { +// return node; +// } +// } + + + // 데이터를 어떤식으로 넣지? + public String createNode(String znodePath, byte[] data) throws PinpointZookeeperException, InterruptedException { + checkState(); + + try { + if (zookeeper.exists(znodePath, false) != null) { + return znodePath; + } + + String pathName = zookeeper.create(znodePath, data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); + return pathName; + } catch (KeeperException exception) { + if (exception.code() != Code.NODEEXISTS) { + handleException(exception); + } + } + return znodePath; + } + + public byte[] getData(String path) throws PinpointZookeeperException, InterruptedException { + checkState(); + + try { + return zookeeper.getData(path, false, null); + } catch (KeeperException exception) { + handleException(exception); + } + + throw new UnknownException("UnknownException."); + } + + public void setData(String path, byte[] data) throws PinpointZookeeperException, InterruptedException { + checkState(); + + try { + if (zookeeper.exists(path, false) == null) { + return; + } + + zookeeper.setData(path, data, -1); + } catch (KeeperException exception) { + handleException(exception); + } + } + + public void delete(String path) throws PinpointZookeeperException, InterruptedException { + checkState(); + + try { + zookeeper.delete(path, -1); + } catch (KeeperException exception) { + if (exception.code() != Code.NONODE) { + handleException(exception); + } + } + } + + public boolean exists(String path) throws PinpointZookeeperException, InterruptedException { + checkState(); + + try { + Stat stat = zookeeper.exists(path, false); + if (stat == null) { + return false; + } + } catch (KeeperException exception) { + if (exception.code() != Code.NODEEXISTS) { + handleException(exception); + } + } + return true; + } + + private void checkState() throws PinpointZookeeperException { + if (!isConnected()) { + throw new ConnectionException("instance must be connected."); + } + } + + public boolean isConnected() { + if (!watcher.isConnected() || !clientState.get()) { + return false; + } + + return true; + } + + public List getChildrenNode(String path, boolean watch) throws PinpointZookeeperException, InterruptedException { + checkState(); + + try { + List childNodeList = zookeeper.getChildren(path, watch, null); + + logger.info("ChildNode List = {}", childNodeList); + return childNodeList; + } catch (KeeperException exception) { + if (exception.code() != Code.NONODE) { + handleException(exception); + } + } + + return Collections.EMPTY_LIST; + } + +// public byte[] getData(String path) throws KeeperException, InterruptedException { +// checkState(); +// +// return zookeeper.getData(path, false, null); +// } +// +// public List getChildrenNode(String path) throws KeeperException, InterruptedException { +// checkState(); +// +// List childNodeList = zookeeper.getChildren(path, false); +// logger.info("ChildNode List = {}", childNodeList); +// return childNodeList; +// } + + private void handleException(KeeperException keeperException) throws PinpointZookeeperException { + switch (keeperException.code()) { + case CONNECTIONLOSS: + case SESSIONEXPIRED: + throw new ConnectionException(keeperException.getMessage(), keeperException); + case AUTHFAILED: + case INVALIDACL: + case NOAUTH: + throw new AuthException(keeperException.getMessage(), keeperException); + case BADARGUMENTS: + case BADVERSION: + case NOCHILDRENFOREPHEMERALS: + case NOTEMPTY: + case NODEEXISTS: + case NONODE: + throw new BadOperationException(keeperException.getMessage(), keeperException); + case OPERATIONTIMEOUT: + throw new TimeoutException(keeperException.getMessage(), keeperException); + default: + throw new UnknownException(keeperException.getMessage(), keeperException); + } + } + + public void close() { + if (clientState.compareAndSet(true, false)) { + if (zookeeper != null) { + try { + zookeeper.close(); + } catch (InterruptedException ignore) { + logger.debug(ignore.getMessage(), ignore); + } + } + } + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterManager.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterManager.java deleted file mode 100644 index 879376870bf4..000000000000 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterManager.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.nhn.pinpoint.collector.cluster.zookeeper; - -import java.io.IOException; -import java.net.InetAddress; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.commons.lang.StringUtils; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher.Event.KeeperState; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.nhn.pinpoint.collector.cluster.zookeeper.job.DeleteJob; -import com.nhn.pinpoint.collector.cluster.zookeeper.job.UpdateJob; -import com.nhn.pinpoint.collector.receiver.tcp.AgentPropertiesType; -import com.nhn.pinpoint.rpc.server.ChannelContext; -import com.nhn.pinpoint.rpc.server.PinpointServerSocketStateCode; -import com.nhn.pinpoint.rpc.server.SocketChannelStateChangeEventListener; -import com.nhn.pinpoint.rpc.util.MapUtils; - -/** - * @author koo.taejin - */ -public class ZookeeperClusterManager implements SocketChannelStateChangeEventListener { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - private final InetAddress localHost; - - private final ZookeeperClient client; - private final ZookeeperLatestJobWorker worker; - - private final ObjectMapper objectmapper = new ObjectMapper(); - - - // 단순하게 하자 그냥 RUN이면 등록 FINISHED면 경우 삭제 그외 skip - // 만약 상태가 안맞으면(?) 보정 들어가야 하는데 leack detector 같은걸 worker내부에 둘 까도 고민중 - // - // RUN에서만 생성할수 있게 해야한다. - // 지금은 RUN_WITHOUT_REGISTER면 상대방의 상태를 알수 없는 상태이기 때문에 이상황에서 등록 - - public ZookeeperClusterManager(String hostPort, int sessionTimeout) throws KeeperException, IOException, InterruptedException { - // 디폴트값으로 사용할 ip같은거 지정해 주는게 좋을듯 - this.localHost = InetAddress.getLocalHost(); - - this.client = new ZookeeperClient(hostPort, sessionTimeout, new ClusterManagerWatcher()); - this.worker = new ZookeeperLatestJobWorker(client); - worker.start(); - } - - @Override - public void eventPerformed(ChannelContext channelContext, PinpointServerSocketStateCode stateCode) { - logger.info("eventPerformed ChannelContext={}, State={}", channelContext, stateCode); - - Map agentProperties = channelContext.getChannelProperties(); - - // 현재는 AgentProperties에 값을 모를 경우 skip - if (skipAgent(agentProperties)) { - return; - } - - if (PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION == stateCode) { - byte[] contents = serializeContents(agentProperties, stateCode); - if (contents == null) { - return; - } - - UpdateJob job = new UpdateJob(channelContext, contents); - worker.putJob(job); - } else if (PinpointServerSocketStateCode.isFinished(stateCode)) { - DeleteJob job = new DeleteJob(channelContext); - worker.putJob(job); - } - } - - public Map getData(ChannelContext channelContext) { - byte[] contents = worker.getData(channelContext); - - if (contents == null) { - return Collections.EMPTY_MAP; - } - - return deserializeContents(contents); - } - - private boolean skipAgent(Map agentProperties) { - String applicationName = MapUtils.getString(agentProperties, AgentPropertiesType.APPLICATION_NAME.getName()); - String agentId = MapUtils.getString(agentProperties, AgentPropertiesType.AGENT_ID.getName()); - - if (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(agentId)) { - return true; - } - - return false; - } - - private byte[] serializeContents(Map agentProperties, PinpointServerSocketStateCode state) { - Map contents = new HashMap(); - contents.put(localHost.getHostAddress(), agentProperties); - contents.put("state", state.name()); - - try { - return objectmapper.writeValueAsBytes(contents); - } catch (JsonProcessingException e) { - logger.warn(e.getMessage(), e); - } - - return null; - } - - private Map deserializeContents(byte[] contents) { - try { - return objectmapper.readValue(contents, Map.class); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - - return Collections.EMPTY_MAP; - } - - public void close() { - client.close(); - worker.stop(); - } - - // 쥬키퍼의 모든 노드를 EPHEMERAL 형태로 만들기 때문에 연결이 새로 연결되면 원래 가지고 있던 것들 재등록 함 - // 연결이 종료 될때는 별다른 액션을 취하지 않는다. - class ClusterManagerWatcher implements ZookeeperEventWatcher { - - private final AtomicBoolean connected = new AtomicBoolean(false); - - // 여기서 고민을 좀 해봐야 할듯 - // 이전에 있던 job을 다 지운다. 어떻게 지울까? - // 새로 생긴 job을 모두 새로 만든다 어떻게 만들지? 추가적으로 이걸 지워질수는 없나? - // 타이밍이 안좋아서 문제가 생길수 있나? - // - - @Override - public void process(WatchedEvent event) { - KeeperState state = event.getState(); - - // 상태가 되면 ephemeral 노드가 사라짐 - // 문서에 따라 자동으로 연결이 되고, 연결되는 이벤트는 process에서 감지가 됨 - if (state == KeeperState.Disconnected || state == KeeperState.Expired) { - connected.compareAndSet(true, false); - return; - } - - if (state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) { - // 이전상태가 RUN일수 있기 때문에 유지해도 됨 - boolean changed = connected.compareAndSet(false, true); - if (changed) { - // 여기서 데이터가 있으면 다 넣어줘야함 - List currentChannelContextList = worker.getRegisteredChannelContextList(); - - for (ChannelContext channelContext : currentChannelContextList) { - eventPerformed(channelContext, channelContext.getCurrentStateCode()); - } - } - - return; - } - } - - @Override - public boolean isConnected() { - return connected.get(); - } - - } - -} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java new file mode 100644 index 000000000000..1c6a4804b8ec --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java @@ -0,0 +1,209 @@ +package com.nhn.pinpoint.collector.cluster.zookeeper; + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher.Event.EventType; +import org.apache.zookeeper.Watcher.Event.KeeperState; +import org.apache.zookeeper.proto.WatcherEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nhn.pinpoint.collector.cluster.ClusterService; +import com.nhn.pinpoint.collector.cluster.WorkerState; +import com.nhn.pinpoint.collector.cluster.WorkerStateContext; +import com.nhn.pinpoint.collector.config.CollectorConfiguration; +import com.nhn.pinpoint.rpc.server.ChannelContext; +import com.nhn.pinpoint.rpc.server.SocketChannelStateChangeEventListener; + +public class ZookeeperClusterService implements ClusterService { + + private static final String PINPOINT_CLUSTER_PATH = "/pinpoint-cluster"; + private static final String PINPOINT_WEB_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/web"; + private static final String PINPOINT_PROFILER_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/profiler"; + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + // 해당 값이 유일한 값이 아닌 경우 MAC주소나 IP주소 등으로 변경할 예정 + // 요렇게 하면 pid@hostname 으로 나옴 (localhost 요런놈은 겹칠 가능성이 존재함) + private final String serverIdentifier = ManagementFactory.getRuntimeMXBean().getName(); + + private final CollectorConfiguration config; + + private final WorkerStateContext serviceState; + + private ZookeeperClient client; + + // ProfilerClusterManager는 프로파일러 -> 콜렉터 연결을 감지 및 관리하고, 쥬키퍼에 등록한다. + // private ZookeeperProfilerClusterManager profilerClusterManager; + // WebClusterManager는 웹 정보가 쥬키퍼에 등록되어 있는지 체크하고, 콜렉터 -> 웹 연결을 관리한다. + private ZookeeperWebClusterManager webClusterManager; + private ZookeeperProfilerClusterManager profilerClusterManager; + + public ZookeeperClusterService(CollectorConfiguration config) { + this.config = config; + this.serviceState = new WorkerStateContext(); + } + + @PostConstruct + @Override + public void setUp() throws KeeperException, IOException, InterruptedException { + if (!config.isClusterEnable()) { + logger.info("pinpoint-collector cluster disable."); + return; + } + + switch (this.serviceState.getCurrentState()) { + case NEW: + if (this.serviceState.changeStateInitializing()) { + logger.info("{} initialization started.", this.getClass().getSimpleName()); + + // 이 상태값은 반드시 필요한것들인데. + ClusterManagerWatcher watcher = new ClusterManagerWatcher(); + this.client = new ZookeeperClient(config.getClusterAddress(), config.getClusterSessionTimeout(), watcher); + + this.profilerClusterManager = new ZookeeperProfilerClusterManager(client, serverIdentifier); + this.profilerClusterManager.start(); + + this.webClusterManager = new ZookeeperWebClusterManager(client, PINPOINT_WEB_CLUSTER_PATH, serverIdentifier); + this.webClusterManager.start(); + + this.serviceState.changeStateStarted(); + logger.info("{} initialization completed.", this.getClass().getSimpleName()); + + if (client.isConnected()) { + WatcherEvent watcherEvent = new WatcherEvent(EventType.None.getIntValue(), KeeperState.SyncConnected.getIntValue(), ""); + WatchedEvent event = new WatchedEvent(watcherEvent); + + watcher.process(event); + } + } + break; + case INITIALIZING: + logger.info("{} already initializing.", this.getClass().getSimpleName()); + break; + case STARTED: + logger.info("{} already started.", this.getClass().getSimpleName()); + break; + case DESTROYING: + throw new IllegalStateException("Already destroying."); + case STOPPED: + throw new IllegalStateException("Already stopped."); + case ILLEGAL_STATE: + throw new IllegalStateException("Invalid State."); + } + } + + @PreDestroy + @Override + public void tearDown() { + if (!config.isClusterEnable()) { + logger.info("pinpoint-collector cluster disable."); + return; + } + + if (!(this.serviceState.changeStateDestroying())) { + WorkerState state = this.serviceState.getCurrentState(); + + logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); + return; + } + + logger.info("{} destroying started.", this.getClass().getSimpleName()); + + if (this.profilerClusterManager != null) { + profilerClusterManager.stop(); + } + + if (this.webClusterManager != null) { + webClusterManager.stop(); + } + + if (client != null) { + client.close(); + } + + this.serviceState.changeStateStoped(); + logger.info("{} destroying completed.", this.getClass().getSimpleName()); + + return; + } + + public SocketChannelStateChangeEventListener getChannelStateChangeEventListener() { + return profilerClusterManager; + } + + public ZookeeperProfilerClusterManager getProfilerClusterManager() { + return profilerClusterManager; + } + + public ZookeeperWebClusterManager getWebClusterManager() { + return webClusterManager; + } + + class ClusterManagerWatcher implements ZookeeperEventWatcher { + + private final AtomicBoolean connected = new AtomicBoolean(false); + + @Override + public void process(WatchedEvent event) { + logger.debug("Process Zookeeper Event({})", event); + + KeeperState state = event.getState(); + EventType eventType = event.getType(); + + // 상태가 되면 ephemeral 노드가 사라짐 + // 문서에 따라 자동으로 연결이 되고, 연결되는 이벤트는 process에서 감지가 됨 + if (ZookeeperUtils.isDisconnectedEvent(state, eventType)) { + connected.compareAndSet(true, false); + return; + } + + if (ZookeeperUtils.isConnectedEvent(state, eventType)) { + // 이전상태가 RUN일수 있기 때문에 유지해도 됨 + boolean changed = connected.compareAndSet(false, true); + } + + if (serviceState.isStarted() && connected.get()) { + + // 중복 요청이 있을수 있음 일단은 중복 로직 감안함 + if (ZookeeperUtils.isConnectedEvent(state, eventType)) { + // 이전상태가 RUN일수 있기 때문에 유지해도 됨 + // 여기서 데이터가 있으면 다 넣어줘야함 + List currentChannelContextList = profilerClusterManager.getRegisteredChannelContextList(); + for (ChannelContext channelContext : currentChannelContextList) { + profilerClusterManager.eventPerformed(channelContext, channelContext.getCurrentStateCode()); + } + + webClusterManager.handleAndRegisterWatcher(PINPOINT_WEB_CLUSTER_PATH); + return; + } + + if (eventType == EventType.NodeChildrenChanged) { + String path = event.getPath(); + + if (PINPOINT_WEB_CLUSTER_PATH.equals(path)) { + webClusterManager.handleAndRegisterWatcher(path); + } else { + logger.warn("Unknown Path ChildrenChanged {}.", path); + } + + } + } + } + + @Override + public boolean isConnected() { + return connected.get(); + } + + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java index ad4b02a3c8c2..6283eb697bc3 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java @@ -1,380 +1,396 @@ -package com.nhn.pinpoint.collector.cluster.zookeeper; - -import java.lang.management.ManagementFactory; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.nhn.pinpoint.collector.cluster.zookeeper.exception.TimeoutException; -import com.nhn.pinpoint.collector.cluster.zookeeper.job.DeleteJob; -import com.nhn.pinpoint.collector.cluster.zookeeper.job.Job; -import com.nhn.pinpoint.collector.cluster.zookeeper.job.UpdateJob; -import com.nhn.pinpoint.common.util.PinpointThreadFactory; -import com.nhn.pinpoint.collector.receiver.tcp.AgentPropertiesType; -import com.nhn.pinpoint.rpc.server.ChannelContext; -import com.nhn.pinpoint.rpc.server.PinpointServerSocketStateCode; -import com.nhn.pinpoint.rpc.util.MapUtils; - -/** - * @author koo.taejin - */ -public class ZookeeperLatestJobWorker implements Runnable { - - private static final String PREFIX_ROOT_ZNODE = "/pinpoint-cluster"; - private static final String PATH_SEPRATOR = "/"; - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - private final Object lock = new Object(); - - private final AtomicInteger workerState; - private final Thread workerThread; - - private final String identifier = ManagementFactory.getRuntimeMXBean().getName(); - private final AtomicInteger sequntialId = new AtomicInteger(0); - - private final ZookeeperClient zookeeperClient; - - // 메시지가 사라지면 ChannelContext 역시 사라짐 - private final Map latestJobRepository = new HashMap(); - - // 들어온 ChannelContext는 계속 유지됨 - private final Map znodeMappingRepository = new HashMap(); - - private final BlockingQueue leakJobQueue = new LinkedBlockingQueue(); - - // 등록순서 - // 순서대로 작업은 반드시 Worker에서만 돌아가기 때문에 동시성은 보장됨 - - public ZookeeperLatestJobWorker(ZookeeperClient zookeeperClient) { - // TODO Auto-generated constructor stub - this.zookeeperClient = zookeeperClient; - - this.workerState = new AtomicInteger(0); - - final ThreadFactory threadFactory = new PinpointThreadFactory(this.getClass().getSimpleName(), true); - this.workerThread = threadFactory.newThread(this); - } - - public void start() { - switch (this.workerState.get()) { - case 0: - if (this.workerState.compareAndSet(0, 1)) - logger.info("{} will be started", this.getClass().getSimpleName()); - this.workerThread.start(); - break; - case 1: - logger.info("{} already started.", this.getClass().getSimpleName()); - break; - case 2: - throw new IllegalStateException("Already stopped"); - default: - throw new Error("Invalid WorkerState"); - } - } - - public void stop() { - if (!(this.workerState.compareAndSet(1, 2))) { - logger.info("{} already stopped.", this.getClass().getSimpleName()); - this.workerState.set(2); - return; - } - - logger.info("{} will be stopped", this.getClass().getSimpleName()); - - boolean interrupted = false; - while (this.workerThread.isAlive()) { - this.workerThread.interrupt(); - try { - this.workerThread.join(100L); - } catch (InterruptedException e) { - interrupted = true; - } - } - - return; - } - - @Override - public void run() { - - // 고민할 것 - // 이벤트 삭제가 안될떄 spinlock 고민해야함 - // 이벤트 발생시 처리가 안될 경우 실제 등록이 안되어이는 ChannelContext가 남아있을 수 있음 이 경우 - // Manager에서 - // 종료가 될 경우 처리해주긴 하지만 LeakDetector같은게 있으면 더 좋을듯 안되면 (1분마다 확인등도 괜찮을듯) - while (workerState.get() == 1) { - boolean eventCreated = await(60000, 200); - if (workerState.get() != 1) { - break; - } - - // 이벤트 발생시 이벤트 처리 - // 이벤트 발생하지 않을 경우 leack ChannelContext 확인 및 처리 - if (eventCreated) { - // ConcurrentModificationException 발생 피하기 위해서 - Iterator keyIterator = getLatestJobRepositoryKeyIterator(); - - while (keyIterator.hasNext()) { - ChannelContext channelContext = keyIterator.next(); - Job job = getJob(channelContext); - - if (job == null) { - continue; - } - - if (job instanceof UpdateJob) { - handleUpdate((UpdateJob) job); - } else if (job instanceof DeleteJob) { - handleDelete((DeleteJob) job); - } - } - } else { - logger.debug("LeackDetector Start."); - - // while 걸자 - while (true) { - Job job = leakJobQueue.poll(); - if (job == null) { - break; - } - - if (job instanceof UpdateJob) { - putJob(new UpdateJob(job.getChannelContext(), 0, ((UpdateJob) job).getContents())); - } - } - - List currentChannelContextList = getRegisteredChannelContextList(); - for (ChannelContext channelContext : currentChannelContextList) { - if (PinpointServerSocketStateCode.isFinished(channelContext.getCurrentStateCode())) { - logger.info("LeackDetector Find Leak ChannelContext={}.", channelContext); - putJob(new DeleteJob(channelContext)); - } - } - - } - } - - logger.info("{} stopped", this.getClass().getSimpleName()); - } - - public boolean handleUpdate(UpdateJob job) { - ChannelContext channelContext = job.getChannelContext(); - - PinpointServerSocketStateCode code = channelContext.getCurrentStateCode(); - if (PinpointServerSocketStateCode.isFinished(code)) { - putJob(new DeleteJob(channelContext)); - return false; - } - - // 동시성에 문제 없게 하자 - String uniquePath = getUniquePath(channelContext, true); - - try { - if (zookeeperClient.exists(uniquePath)) { - zookeeperClient.setData(uniquePath, job.getContents()); - } else { - zookeeperClient.createPath(uniquePath); - zookeeperClient.createNode(uniquePath, job.getContents()); - logger.info("Registed Zookeeper UniqPath = {}", uniquePath); - } - return true; - } catch (Exception e) { - logger.warn(e.getMessage(), e); - if (e instanceof TimeoutException) { - job.incrementCurrentRetryCount(); - putJob(job); - } - } - - return false; - } - - public boolean handleDelete(Job job) { - ChannelContext channelContext = job.getChannelContext(); - - String uniquePath = getUniquePath(channelContext, false); - - if (uniquePath == null) { - logger.info("Already Delete Zookeeper UniqPath ChannelContext = {}.", channelContext); - return true; - } - - try { - if (zookeeperClient.exists(uniquePath)) { - zookeeperClient.delete(uniquePath); - logger.info("Unregisted Zookeeper UniqPath = {}", uniquePath); - } - removeUniquePath(channelContext); - return true; - } catch (Exception e) { - logger.warn(e.getMessage(), e); - if (e instanceof TimeoutException) { - job.incrementCurrentRetryCount(); - putJob(job); - } - } - - return false; - } - - public byte[] getData(ChannelContext channelContext) { - String uniquePath = getUniquePath(channelContext, false); - - if (uniquePath == null) { - logger.info("Can't find suitable UniqPath ChannelContext = {}.", channelContext); - return null; - } - - try { - return zookeeperClient.getData(uniquePath); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - - return null; - } - - public List getRegisteredChannelContextList() { - synchronized (znodeMappingRepository) { - return new ArrayList(znodeMappingRepository.keySet()); - } - } - - /** - * 파라미터의 대기시간동안 이벤트가 일어날 경우 true 일어나지 않을 경우 false - * - * @param waitTimeMillis - * @return - */ - private boolean await(long waitTimeMillis, long waitUnitTimeMillis) { - synchronized (lock) { - long waitTime = waitTimeMillis; - long waitUnitTime = waitUnitTimeMillis; - if (waitTimeMillis < 1000) { - waitTime = 1000; - } - if (waitUnitTimeMillis < 100) { - waitUnitTime = 100; - } - - long startTimeMillis = System.currentTimeMillis(); - - while (latestJobRepository.size() == 0 && !isOverWaitTime(waitTime, startTimeMillis) && workerState.get() == 1) { - try { - lock.wait(waitUnitTime); - } catch (InterruptedException e) { - - } - } - - if (isOverWaitTime(waitTime, startTimeMillis)) { - return false; - } - - return true; - } - } - - private boolean isOverWaitTime(long waitTimeMillis, long startTimeMillis) { - return waitTimeMillis < (System.currentTimeMillis() - startTimeMillis); - } - - private Iterator getLatestJobRepositoryKeyIterator() { - synchronized (lock) { - return latestJobRepository.keySet().iterator(); - } - } - - // 상당히 민감한 api임 Runnable에서만 사용해야함 - private Job getJob(ChannelContext channelContext) { - synchronized (lock) { - Job job = latestJobRepository.remove(channelContext); - return job; - } - - } - - public void putJob(Job job) { - if (job.getMaxRetryCount() < job.getCurrentRetryCount()) { - if (logger.isInfoEnabled()) { - logger.warn("Leack Job Queue Register Job={}.", job); - } - leakJobQueue.add(job); - return; - } - - synchronized (lock) { - ChannelContext channelContext = job.getChannelContext(); - - latestJobRepository.put(channelContext, job); - lock.notifyAll(); - } - } - - private String getUniquePath(ChannelContext channelContext, boolean create) { - synchronized (znodeMappingRepository) { - String zNodePath = znodeMappingRepository.get(channelContext); - - if (!create) { - return zNodePath; - } - - if (zNodePath == null) { - Map agentProperties = channelContext.getChannelProperties(); - final String applicationName = MapUtils.getString(agentProperties, AgentPropertiesType.APPLICATION_NAME.getName()); - final String agentId = MapUtils.getString(agentProperties, AgentPropertiesType.AGENT_ID.getName()); - - if (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(agentId)) { - return null; - } - - String path = PREFIX_ROOT_ZNODE + "/" + applicationName + "/" + agentId; - String zNodeName = createUniqueZnodeName(); - - zNodePath = bindingPathAndZnode(path, zNodeName); - znodeMappingRepository.put(channelContext, zNodePath); - - logger.info("Created Zookeeper UniqPath = {}", zNodePath); - } - - return zNodePath; - } - } - - private void removeUniquePath(ChannelContext channelContext) { - synchronized (znodeMappingRepository) { - String zNodePath = znodeMappingRepository.remove(channelContext); - if (zNodePath != null) { - logger.info("Deleted Zookeeper UniqPath = {}", zNodePath); - } - } - } - - private String createUniqueZnodeName() { - return identifier + "_" + sequntialId.getAndIncrement(); - } - - private String bindingPathAndZnode(String path, String znodeName) { - StringBuilder fullPath = new StringBuilder(); - - fullPath.append(path); - if (!path.endsWith(PATH_SEPRATOR)) { - fullPath.append(PATH_SEPRATOR); - } - fullPath.append(znodeName); - - return fullPath.toString(); - } - -} +package com.nhn.pinpoint.collector.cluster.zookeeper; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nhn.pinpoint.collector.cluster.WorkerState; +import com.nhn.pinpoint.collector.cluster.WorkerStateContext; +import com.nhn.pinpoint.collector.cluster.zookeeper.exception.TimeoutException; +import com.nhn.pinpoint.collector.cluster.zookeeper.job.DeleteJob; +import com.nhn.pinpoint.collector.cluster.zookeeper.job.Job; +import com.nhn.pinpoint.collector.cluster.zookeeper.job.UpdateJob; +import com.nhn.pinpoint.collector.receiver.tcp.AgentPropertiesType; +import com.nhn.pinpoint.common.util.PinpointThreadFactory; +import com.nhn.pinpoint.rpc.server.ChannelContext; +import com.nhn.pinpoint.rpc.server.PinpointServerSocketStateCode; +import com.nhn.pinpoint.rpc.util.MapUtils; + +/** + * @author koo.taejin + */ +public class ZookeeperLatestJobWorker implements Runnable { + + private static final String PINPOINT_CLUSTER_PATH = "/pinpoint-cluster"; + private static final String PINPOINT_PROFILER_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/profiler"; + + private static final String PATH_SEPRATOR = "/"; + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final Object lock = new Object(); + + private final WorkerStateContext workerState; + private final Thread workerThread; + + private final String identifier; + private final AtomicInteger sequntialId = new AtomicInteger(0); + + private final ZookeeperClient zookeeperClient; + + // 메시지가 사라지면 ChannelContext 역시 사라짐 + private final Map latestJobRepository = new HashMap(); + + // 들어온 ChannelContext는 계속 유지됨 + private final Map znodeMappingRepository = new HashMap(); + + private final BlockingQueue leakJobQueue = new LinkedBlockingQueue(); + + // 등록순서 + // 순서대로 작업은 반드시 Worker에서만 돌아가기 때문에 동시성은 보장됨 + + public ZookeeperLatestJobWorker(ZookeeperClient zookeeperClient, String serverIdentifier) { + // TODO Auto-generated constructor stub + this.zookeeperClient = zookeeperClient; + + this.workerState = new WorkerStateContext(); + + this.identifier = serverIdentifier; + + final ThreadFactory threadFactory = new PinpointThreadFactory(this.getClass().getSimpleName(), true); + this.workerThread = threadFactory.newThread(this); + } + + public void start() { + switch (this.workerState.getCurrentState()) { + case NEW: + if (this.workerState.changeStateInitializing()) { + logger.info("{} initialization started.", this.getClass().getSimpleName()); + this.workerThread.start(); + + workerState.changeStateStarted(); + logger.info("{} initialization completed.", this.getClass().getSimpleName()); + + break; + } + case INITIALIZING: + logger.info("{} already initializing.", this.getClass().getSimpleName()); + break; + case STARTED: + logger.info("{} already started.", this.getClass().getSimpleName()); + break; + case DESTROYING: + throw new IllegalStateException("Already destroying."); + case STOPPED: + throw new IllegalStateException("Already stopped."); + case ILLEGAL_STATE: + throw new IllegalStateException("Invalid State."); + } + } + + public void stop() { + if (!(this.workerState.changeStateDestroying())) { + WorkerState state = this.workerState.getCurrentState(); + + logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); + return; + } + + logger.info("{} destorying started.", this.getClass().getSimpleName()); + boolean interrupted = false; + while (this.workerThread.isAlive()) { + this.workerThread.interrupt(); + try { + this.workerThread.join(100L); + } catch (InterruptedException e) { + interrupted = true; + } + } + + this.workerState.changeStateStoped(); + logger.info("{} destorying completed.", this.getClass().getSimpleName()); + + return; + } + + @Override + public void run() { + + // 고민할 것 + // 이벤트 삭제가 안될떄 spinlock 고민해야함 + // 이벤트 발생시 처리가 안될 경우 실제 등록이 안되어이는 ChannelContext가 남아있을 수 있음 이 경우 + while (workerState.isStarted()) { + boolean eventCreated = await(60000, 200); + if (!workerState.isStarted()) { + break; + } + + // 이벤트 발생시 이벤트 처리 + // 이벤트 발생하지 않을 경우 leak ChannelContext 확인 및 처리 + if (eventCreated) { + // ConcurrentModificationException 발생 피하기 위해서 + Iterator keyIterator = getLatestJobRepositoryKeyIterator(); + + while (keyIterator.hasNext()) { + ChannelContext channelContext = keyIterator.next(); + Job job = getJob(channelContext); + + if (job == null) { + continue; + } + + if (job instanceof UpdateJob) { + handleUpdate((UpdateJob) job); + } else if (job instanceof DeleteJob) { + handleDelete((DeleteJob) job); + } + } + } else { + // 삭제 타이밍이 잘 안맞을 경우 메시지 유실이 발생할 가능성이 있어서 유실 Job 처리 + logger.debug("LeakDetector Start."); + + while (true) { + Job job = leakJobQueue.poll(); + if (job == null) { + break; + } + + if (job instanceof UpdateJob) { + putJob(new UpdateJob(job.getChannelContext(), 0, ((UpdateJob) job).getContents())); + } + } + + List currentChannelContextList = getRegisteredChannelContextList(); + for (ChannelContext channelContext : currentChannelContextList) { + if (PinpointServerSocketStateCode.isFinished(channelContext.getCurrentStateCode())) { + logger.info("LeakDetector Find Leak ChannelContext={}.", channelContext); + putJob(new DeleteJob(channelContext)); + } + } + + } + } + + logger.info("{} stopped", this.getClass().getSimpleName()); + } + + public boolean handleUpdate(UpdateJob job) { + ChannelContext channelContext = job.getChannelContext(); + + PinpointServerSocketStateCode code = channelContext.getCurrentStateCode(); + if (PinpointServerSocketStateCode.isFinished(code)) { + putJob(new DeleteJob(channelContext)); + return false; + } + + // 동시성에 문제 없게 하자 + String uniquePath = getUniquePath(channelContext, true); + + try { + if (zookeeperClient.exists(uniquePath)) { + zookeeperClient.setData(uniquePath, job.getContents()); + } else { + zookeeperClient.createPath(uniquePath); + zookeeperClient.createNode(uniquePath, job.getContents()); + logger.info("Registed Zookeeper UniqPath = {}", uniquePath); + } + return true; + } catch (Exception e) { + logger.warn(e.getMessage(), e); + if (e instanceof TimeoutException) { + job.incrementCurrentRetryCount(); + putJob(job); + } + } + + return false; + } + + public boolean handleDelete(Job job) { + ChannelContext channelContext = job.getChannelContext(); + + String uniquePath = getUniquePath(channelContext, false); + + if (uniquePath == null) { + logger.info("Already Delete Zookeeper UniqPath ChannelContext = {}.", channelContext); + return true; + } + + try { + if (zookeeperClient.exists(uniquePath)) { + zookeeperClient.delete(uniquePath); + logger.info("Unregisted Zookeeper UniqPath = {}", uniquePath); + } + removeUniquePath(channelContext); + return true; + } catch (Exception e) { + logger.warn(e.getMessage(), e); + if (e instanceof TimeoutException) { + job.incrementCurrentRetryCount(); + putJob(job); + } + } + + return false; + } + + public byte[] getData(ChannelContext channelContext) { + String uniquePath = getUniquePath(channelContext, false); + + if (uniquePath == null) { + logger.info("Can't find suitable UniqPath ChannelContext = {}.", channelContext); + return null; + } + + try { + return zookeeperClient.getData(uniquePath); + } catch (Exception e) { + logger.warn(e.getMessage(), e); + } + + return null; + } + + public List getRegisteredChannelContextList() { + synchronized (znodeMappingRepository) { + return new ArrayList(znodeMappingRepository.keySet()); + } + } + + /** + * 파라미터의 대기시간동안 이벤트가 일어날 경우 true 일어나지 않을 경우 false + * + * @param waitTimeMillis + * @return + */ + private boolean await(long waitTimeMillis, long waitUnitTimeMillis) { + synchronized (lock) { + long waitTime = waitTimeMillis; + long waitUnitTime = waitUnitTimeMillis; + if (waitTimeMillis < 1000) { + waitTime = 1000; + } + if (waitUnitTimeMillis < 100) { + waitUnitTime = 100; + } + + long startTimeMillis = System.currentTimeMillis(); + + while (latestJobRepository.size() == 0 && !isOverWaitTime(waitTime, startTimeMillis) && workerState.isStarted()) { + try { + lock.wait(waitUnitTime); + } catch (InterruptedException e) { + + } + } + + if (isOverWaitTime(waitTime, startTimeMillis)) { + return false; + } + + return true; + } + } + + private boolean isOverWaitTime(long waitTimeMillis, long startTimeMillis) { + return waitTimeMillis < (System.currentTimeMillis() - startTimeMillis); + } + + private Iterator getLatestJobRepositoryKeyIterator() { + synchronized (lock) { + return latestJobRepository.keySet().iterator(); + } + } + + // 상당히 민감한 api임 Runnable에서만 사용해야함 + private Job getJob(ChannelContext channelContext) { + synchronized (lock) { + Job job = latestJobRepository.remove(channelContext); + return job; + } + + } + + public void putJob(Job job) { + if (job.getMaxRetryCount() < job.getCurrentRetryCount()) { + if (logger.isInfoEnabled()) { + logger.warn("Leack Job Queue Register Job={}.", job); + } + leakJobQueue.add(job); + return; + } + + synchronized (lock) { + ChannelContext channelContext = job.getChannelContext(); + + latestJobRepository.put(channelContext, job); + lock.notifyAll(); + } + } + + private String getUniquePath(ChannelContext channelContext, boolean create) { + synchronized (znodeMappingRepository) { + String zNodePath = znodeMappingRepository.get(channelContext); + + if (!create) { + return zNodePath; + } + + if (zNodePath == null) { + Map agentProperties = channelContext.getChannelProperties(); + final String applicationName = MapUtils.getString(agentProperties, AgentPropertiesType.APPLICATION_NAME.getName()); + final String agentId = MapUtils.getString(agentProperties, AgentPropertiesType.AGENT_ID.getName()); + + if (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(agentId)) { + return null; + } + + String path = PINPOINT_PROFILER_CLUSTER_PATH + "/" + applicationName + "/" + agentId; + String zNodeName = createUniqueZnodeName(); + + zNodePath = bindingPathAndZnode(path, zNodeName); + znodeMappingRepository.put(channelContext, zNodePath); + + logger.info("Created Zookeeper UniqPath = {}", zNodePath); + } + + return zNodePath; + } + } + + private void removeUniquePath(ChannelContext channelContext) { + synchronized (znodeMappingRepository) { + String zNodePath = znodeMappingRepository.remove(channelContext); + if (zNodePath != null) { + logger.info("Deleted Zookeeper UniqPath = {}", zNodePath); + } + } + } + + private String createUniqueZnodeName() { + return identifier + "_" + sequntialId.getAndIncrement(); + } + + private String bindingPathAndZnode(String path, String znodeName) { + StringBuilder fullPath = new StringBuilder(); + + fullPath.append(path); + if (!path.endsWith(PATH_SEPRATOR)) { + fullPath.append(PATH_SEPRATOR); + } + fullPath.append(znodeName); + + return fullPath.toString(); + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java new file mode 100644 index 000000000000..4de01ff24fd5 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java @@ -0,0 +1,194 @@ +package com.nhn.pinpoint.collector.cluster.zookeeper; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.apache.zookeeper.KeeperException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.nhn.pinpoint.collector.cluster.WorkerState; +import com.nhn.pinpoint.collector.cluster.WorkerStateContext; +import com.nhn.pinpoint.collector.cluster.zookeeper.exception.PinpointZookeeperException; +import com.nhn.pinpoint.collector.cluster.zookeeper.job.DeleteJob; +import com.nhn.pinpoint.collector.cluster.zookeeper.job.UpdateJob; +import com.nhn.pinpoint.collector.receiver.tcp.AgentPropertiesType; +import com.nhn.pinpoint.rpc.server.ChannelContext; +import com.nhn.pinpoint.rpc.server.PinpointServerSocketStateCode; +import com.nhn.pinpoint.rpc.server.SocketChannelStateChangeEventListener; +import com.nhn.pinpoint.rpc.util.MapUtils; + +/** + * @author koo.taejin + */ +public class ZookeeperProfilerClusterManager implements SocketChannelStateChangeEventListener { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final ZookeeperClient client; + private final ZookeeperLatestJobWorker worker; + + private final WorkerStateContext workerState; + + private final ObjectMapper objectmapper = new ObjectMapper(); + + // 단순하게 하자 그냥 RUN이면 등록 FINISHED면 경우 삭제 그외 skip + // 만약 상태가 안맞으면(?) 보정 들어가야 하는데 leak detector 같은걸 worker내부에 둘 까도 고민중 + // + // RUN_DUPLEX에서만 생성할수 있게 해야한다. + // 지금은 RUN 상대방의 상태를 알수 없는 상태이기 때문에 이상황에서 등록 + public ZookeeperProfilerClusterManager(ZookeeperClient client, String serverIdentifier) throws KeeperException, IOException, InterruptedException { + this.workerState = new WorkerStateContext(); + + this.client = client; + this.worker = new ZookeeperLatestJobWorker(client, serverIdentifier); + } + + public void start() { + switch (this.workerState.getCurrentState()) { + case NEW: + if (this.workerState.changeStateInitializing()) { + logger.info("{} initialization started.", this.getClass().getSimpleName()); + + if (worker != null) { + worker.start(); + } + + workerState.changeStateStarted(); + logger.info("{} initialization completed.", this.getClass().getSimpleName()); + + break; + } + case INITIALIZING: + logger.info("{} already initializing.", this.getClass().getSimpleName()); + break; + case STARTED: + logger.info("{} already started.", this.getClass().getSimpleName()); + break; + case DESTROYING: + throw new IllegalStateException("Already destroying."); + case STOPPED: + throw new IllegalStateException("Already stopped."); + case ILLEGAL_STATE: + throw new IllegalStateException("Invalid State."); + } + } + + public void stop() { + if (!(this.workerState.changeStateDestroying())) { + WorkerState state = this.workerState.getCurrentState(); + + logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); + return; + } + + logger.info("{} destorying started.", this.getClass().getSimpleName()); + + if (worker != null) { + worker.stop(); + } + + this.workerState.changeStateStoped(); + logger.info("{} destorying completed.", this.getClass().getSimpleName()); + + return; + + } + + @Override + public void eventPerformed(ChannelContext channelContext, PinpointServerSocketStateCode stateCode) { + if (workerState.isStarted()) { + logger.info("eventPerformed ChannelContext={}, State={}", channelContext, stateCode); + + Map agentProperties = channelContext.getChannelProperties(); + + // 현재는 AgentProperties에 값을 모를 경우 skip + if (skipAgent(agentProperties)) { + return; + } + + if (PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION == stateCode) { + byte[] contents = serializeContents(agentProperties, stateCode); + if (contents == null) { + return; + } + + UpdateJob job = new UpdateJob(channelContext, contents); + worker.putJob(job); + } else if (PinpointServerSocketStateCode.isFinished(stateCode)) { + DeleteJob job = new DeleteJob(channelContext); + worker.putJob(job); + } + } else { + WorkerState state = this.workerState.getCurrentState(); + logger.info("{} invalid state {}.", this.getClass().getSimpleName(), state.toString()); + return; + } + + } + + public Map getData(ChannelContext channelContext) { + byte[] contents = worker.getData(channelContext); + + if (contents == null) { + return Collections.EMPTY_MAP; + } + + return deserializeContents(contents); + } + + public List getChildrenNode(String path, boolean watch) throws PinpointZookeeperException, InterruptedException { + if (client.exists(path)) { + return client.getChildrenNode(path, watch); + } else { + client.createPath(path); + return client.getChildrenNode(path, watch); + } + } + + public List getRegisteredChannelContextList() { + return worker.getRegisteredChannelContextList(); + } + + private boolean skipAgent(Map agentProperties) { + String applicationName = MapUtils.getString(agentProperties, AgentPropertiesType.APPLICATION_NAME.getName()); + String agentId = MapUtils.getString(agentProperties, AgentPropertiesType.AGENT_ID.getName()); + + if (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(agentId)) { + return true; + } + + return false; + } + + private byte[] serializeContents(Map agentProperties, PinpointServerSocketStateCode state) { + Map contents = new HashMap(); + contents.put("agent", agentProperties); + contents.put("state", state.name()); + + try { + return objectmapper.writeValueAsBytes(contents); + } catch (JsonProcessingException e) { + logger.warn(e.getMessage(), e); + } + + return null; + } + + private Map deserializeContents(byte[] contents) { + try { + return objectmapper.readValue(contents, Map.class); + } catch (Exception e) { + logger.warn(e.getMessage(), e); + } + + return Collections.EMPTY_MAP; + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperUtils.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperUtils.java new file mode 100644 index 000000000000..e3dafaa411f6 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperUtils.java @@ -0,0 +1,47 @@ +package com.nhn.pinpoint.collector.cluster.zookeeper; + +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher.Event.EventType; +import org.apache.zookeeper.Watcher.Event.KeeperState; + +/** + * @author koo.taejin + */ +public final class ZookeeperUtils { + + // 나중에 commons-hbase 같은것이 생기면 그쪽에 포함하는 것도 방법일듯 + private ZookeeperUtils() { + } + + public static boolean isConnectedEvent(WatchedEvent event) { + KeeperState state = event.getState(); + EventType eventType = event.getType(); + + return isConnectedEvent(state, eventType); + } + + public static boolean isConnectedEvent(KeeperState state, EventType eventType) { + if ((state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) && eventType == EventType.None) { + return true; + } else { + return false; + } + } + + + public static boolean isDisconnectedEvent(WatchedEvent event) { + KeeperState state = event.getState(); + EventType eventType = event.getType(); + + return isDisconnectedEvent(state, eventType); + } + + public static boolean isDisconnectedEvent(KeeperState state, EventType eventType) { + if ((state == KeeperState.Disconnected || state == KeeperState.Expired) && eventType == eventType.None) { + return true; + } else { + return false; + } + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java new file mode 100644 index 000000000000..5ade2e8de737 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java @@ -0,0 +1,229 @@ +package com.nhn.pinpoint.collector.cluster.zookeeper; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.zookeeper.KeeperException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nhn.pinpoint.collector.cluster.WebClusterPoint; +import com.nhn.pinpoint.collector.cluster.WorkerState; +import com.nhn.pinpoint.collector.cluster.WorkerStateContext; +import com.nhn.pinpoint.collector.cluster.zookeeper.exception.ConnectionException; +import com.nhn.pinpoint.common.util.NetUtils; +import com.nhn.pinpoint.common.util.PinpointThreadFactory; + +/** + * @author koo.taejin + */ +public class ZookeeperWebClusterManager implements Runnable { + + // 콜렉터 에서는 무한 retry를 해도됨 + // RETRY_INTERVAL을 받게만 하면 될듯 + private static final int DEFAULT_RETRY_INTERVAL = 10000; + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final GetAndRegisterTask getAndRegisterTask = new GetAndRegisterTask(); + private final StopTask stopTask = new StopTask(); + + private final ZookeeperClient client; + private final WebClusterPoint webClusterPoint; + private final String zNodePath; + + private final AtomicBoolean retryMode = new AtomicBoolean(false); + + private final BlockingQueue queue = new LinkedBlockingQueue(1); + + private final WorkerStateContext workerState; + private final Thread workerThread; + + // private final Timer timer; + + // Worker + Job 등록 + // Job이 포함되면 실행. Job성공시 이후 Job 모두 삭제 + // 먼가 이상한 형태의 자료구조가 필요한거 같은데.... + + public ZookeeperWebClusterManager(ZookeeperClient client, String zookeeperClusterPath, String serverIdentifier) throws KeeperException, IOException, + InterruptedException { + this.client = client; + + this.webClusterPoint = new WebClusterPoint(serverIdentifier); + this.zNodePath = zookeeperClusterPath; + + this.workerState = new WorkerStateContext(); + + final ThreadFactory threadFactory = new PinpointThreadFactory(this.getClass().getSimpleName(), true); + this.workerThread = threadFactory.newThread(this); + } + + public void start() { + switch (this.workerState.getCurrentState()) { + case NEW: + if (this.workerState.changeStateInitializing()) { + logger.info("{} initialization started.", this.getClass().getSimpleName()); + this.workerThread.start(); + + workerState.changeStateStarted(); + logger.info("{} initialization completed.", this.getClass().getSimpleName()); + break; + } + case INITIALIZING: + logger.info("{} already initializing.", this.getClass().getSimpleName()); + break; + case STARTED: + logger.info("{} already started.", this.getClass().getSimpleName()); + break; + case DESTROYING: + throw new IllegalStateException("Already destroying."); + case STOPPED: + throw new IllegalStateException("Already stopped."); + case ILLEGAL_STATE: + throw new IllegalStateException("Invalid State."); + } + } + + public void stop() { + if (!(this.workerState.changeStateDestroying())) { + WorkerState state = this.workerState.getCurrentState(); + + logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); + return; + } + + logger.info("{} destorying started.", this.getClass().getSimpleName()); + + queue.offer(stopTask); + if (webClusterPoint != null) { + webClusterPoint.close(); + } + + boolean interrupted = false; + while (this.workerThread.isAlive()) { + this.workerThread.interrupt(); + try { + this.workerThread.join(100L); + } catch (InterruptedException e) { + interrupted = true; + } + } + + this.workerState.changeStateStoped(); + logger.info("{} destorying completed.", this.getClass().getSimpleName()); + + return; + } + + // NoNode인 경우 Node생성후 재 호출 + // Timeout인 경우 스케쥴 걸어서 재요청 + // 그외는 그대로 둠 + public void handleAndRegisterWatcher(String path) { + if (workerState.isStarted()) { + if (zNodePath.equals(path)) { + boolean offerSuccess = queue.offer(getAndRegisterTask); + + if (!offerSuccess) { + logger.info("Message Queue is Full."); + } + } else { + logger.info("Invald Path {}.", path); + } + } else { + WorkerState state = this.workerState.getCurrentState(); + logger.info("{} invalid state {}.", this.getClass().getSimpleName(), state.toString()); + return; + } + } + + @Override + public void run() { + while (workerState.isStarted()) { + Task task = null; + + try { + task = queue.poll(DEFAULT_RETRY_INTERVAL, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + logger.debug(e.getMessage(), e); + } + + if (!workerState.isStarted()) { + break; + } + + if (task == null) { + if (retryMode.get()) { + boolean success = getAndRegisterTask.handleAndRegisterWatcher0(); + if (success) { + retryMode.compareAndSet(true, false); + } + } + } else if (task instanceof GetAndRegisterTask) { + boolean success = ((GetAndRegisterTask) task).handleAndRegisterWatcher0(); + if (!success) { + retryMode.compareAndSet(false, true); + } + } else if (task instanceof StopTask) { + break; + } + } + + logger.info("{} stopped", this.getClass().getSimpleName()); + } + + interface Task { + + } + + class GetAndRegisterTask implements Task { + + private boolean handleAndRegisterWatcher0() { + boolean needNotRetry = false; + try { + + if (!client.exists(zNodePath)) { + client.createPath(zNodePath, true); + } + + List childNodeList = client.getChildrenNode(zNodePath, true); + List clusterAddressList = NetUtils.toInetSocketAddressLIst(childNodeList); + + List addressList = webClusterPoint.getWebClusterList(); + + logger.info("Handle register and remove Task. Current Address List = {}, Cluster Address List = {}", addressList, clusterAddressList); + + for (InetSocketAddress clusterAddress : clusterAddressList) { + if (!addressList.contains(clusterAddress)) { + webClusterPoint.connectPointIfAbsent(clusterAddress); + } + } + + for (InetSocketAddress address : addressList) { + if (!clusterAddressList.contains(address)) { + webClusterPoint.disconnectPoint(address); + } + } + + needNotRetry = true; + return needNotRetry; + } catch (Exception e) { + if (!(e instanceof ConnectionException)) { + needNotRetry = true; + } + } + + return needNotRetry; + } + } + + class StopTask implements Task { + + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java b/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java index 59ca5c0abb01..027f066e7e5a 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java @@ -17,6 +17,9 @@ public class CollectorConfiguration implements InitializingBean { private final Logger logger = LoggerFactory.getLogger(this.getClass()); +// cluster.zookeeper.address=dev.zk.pinpoint.navercorp.com +// cluster.zookeeper.sessiontimeout=3000 + private static final String CONFIG_FILE_NAME = "pinpoint-collector.properties"; private static final String DEFAULT_LISTEN_IP = "0.0.0.0"; @@ -44,6 +47,9 @@ public void setProperties(Properties properties) { private int udpSpanWorkerQueueSize; private int udpSpanSocketReceiveBufferSize; + private boolean clusterEnable; + private String clusterAddress; + private int clusterSessionTimeout; public String getTcpListenIp() { return tcpListenIp; @@ -108,6 +114,29 @@ public void setUdpSpanSocketReceiveBufferSize(int udpSpanSocketReceiveBufferSize this.udpSpanSocketReceiveBufferSize = udpSpanSocketReceiveBufferSize; } + public boolean isClusterEnable() { + return clusterEnable; + } + + public void setClusterEnable(boolean clusterEnable) { + this.clusterEnable = clusterEnable; + } + + public String getClusterAddress() { + return clusterAddress; + } + + public void setClusterAddress(String clusterAddress) { + this.clusterAddress = clusterAddress; + } + + public int getClusterSessionTimeout() { + return clusterSessionTimeout; + } + + public void setClusterSessionTimeout(int clusterSessionTimeout) { + this.clusterSessionTimeout = clusterSessionTimeout; + } public void readConfigFile() { // testcase와 같이 단독으로 사용할 경우 해당 api를 사용하면 좋을듯. testcase에서 쓸려면 classpath를 읽도록 고쳐야 될거임. @@ -154,6 +183,10 @@ private void readPropertyValues(Properties properties) { this.udpSpanWorkerThread = readInt(properties, "collector.udpSpanWorkerThread", 256); this.udpSpanWorkerQueueSize = readInt(properties, "collector.udpSpanWorkerQueueSize", 1024 * 5); this.udpSpanSocketReceiveBufferSize = readInt(properties, "collector.udpSpanSocketReceiveBufferSize", 1024 * 4096); + + this.clusterEnable = readBoolen(properties, "cluster.enable"); + this.clusterAddress = readString(properties, "cluster.zookeeper.address", ""); + this.clusterSessionTimeout = readInt(properties, "cluster.zookeeper.sessiontimeout", -1); } private String readString(Properties properties, String propertyName, String defaultValue) { @@ -173,6 +206,18 @@ private int readInt(Properties properties, String propertyName, int defaultValue } return result; } + + private boolean readBoolen(Properties properties, String propertyName) { + final String value = properties.getProperty(propertyName); + + // true 문자열인 경우만 true 그외는 모두 false + // 이후 default value가 필요할 경우, Utils 대신 문자열 매칭으로 해야할듯 현재는 필요없기 떄문에 그냥 둠 + boolean result = Boolean.valueOf(value); + if (logger.isInfoEnabled()) { + logger.info("{}={}", propertyName, result); + } + return result; + } @Override public String toString() { @@ -189,7 +234,12 @@ public String toString() { sb.append(", udpSpanWorkerThread=").append(udpSpanWorkerThread); sb.append(", udpSpanWorkerQueueSize=").append(udpSpanWorkerQueueSize); sb.append(", udpSpanSocketReceiveBufferSize=").append(udpSpanSocketReceiveBufferSize); + sb.append(", clusterEnable=").append(clusterEnable); + sb.append(", clusterAddress=").append(clusterAddress); + sb.append(", clusterSessionTimeout=").append(clusterSessionTimeout); + sb.append('}'); return sb.toString(); } + } diff --git a/collector/src/main/resources-dev/pinpoint-collector.properties b/collector/src/main/resources-dev/pinpoint-collector.properties index c1ba611e63aa..4d3356515848 100644 --- a/collector/src/main/resources-dev/pinpoint-collector.properties +++ b/collector/src/main/resources-dev/pinpoint-collector.properties @@ -1,44 +1,48 @@ -#HBaseTemplate에서 사용하는 HtablePool사이즈 -hbase.hTablePoolSize=1024 - -# tcp listen ip -collector.tcpListenIp=0.0.0.0 -collector.tcpListenPort=9994 - -# udp listen ip -collector.udpStatListenIp=0.0.0.0 -collector.udpStatListenPort=9995 - -# L4 tcp 채널 close 무시를 위한 설정. -collector.l4.ip= - -# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. -collector.udpStatWorkerThread=256 -# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? -collector.udpStatWorkerQueueSize=5120 - -#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. -collector.udpStatSocketReceiveBufferSize=4194304 - - -# span listen port --------------------------------------------------------------------- -collector.udpSpanListenIp=0.0.0.0 -collector.udpSpanListenPort=9996 - -# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. -collector.udpSpanWorkerThread=256 -# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? -collector.udpSpanWorkerQueueSize=5120 - -#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. -collector.udpSpanSocketReceiveBufferSize=4194304 -#$ /sbin/sysctl -a | grep -e rmem -e wmem -#net.core.wmem_max = 524288 -#net.core.rmem_max = 524288 -#net.core.wmem_default = 229376 -#net.core.rmem_default = 229376 -#위 설정을 다음과 같이 수정합니다. -#irteamsu$ sudo sysctl -w net.core.rmem_max=4194304 - -# 통계값 flush 주기 -statistics.flushPeriod=1000 \ No newline at end of file +#HBaseTemplate에서 사용하는 HtablePool사이즈 +hbase.hTablePoolSize=1024 + +# tcp listen ip +collector.tcpListenIp=0.0.0.0 +collector.tcpListenPort=9994 + +# udp listen ip +collector.udpStatListenIp=0.0.0.0 +collector.udpStatListenPort=9995 + +# L4 tcp 채널 close 무시를 위한 설정. +collector.l4.ip= + +# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. +collector.udpStatWorkerThread=256 +# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? +collector.udpStatWorkerQueueSize=5120 + +#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. +collector.udpStatSocketReceiveBufferSize=4194304 + + +# span listen port --------------------------------------------------------------------- +collector.udpSpanListenIp=0.0.0.0 +collector.udpSpanListenPort=9996 + +# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. +collector.udpSpanWorkerThread=256 +# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? +collector.udpSpanWorkerQueueSize=5120 + +#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. +collector.udpSpanSocketReceiveBufferSize=4194304 +#$ /sbin/sysctl -a | grep -e rmem -e wmem +#net.core.wmem_max = 524288 +#net.core.rmem_max = 524288 +#net.core.wmem_default = 229376 +#net.core.rmem_default = 229376 +#위 설정을 다음과 같이 수정합니다. +#irteamsu$ sudo sysctl -w net.core.rmem_max=4194304 + +# 통계값 flush 주기 +statistics.flushPeriod=1000 + +cluster.enable=false +cluster.zookeeper.address= +cluster.zookeeper.sessiontimeout= \ No newline at end of file diff --git a/collector/src/main/resources-local/pinpoint-collector.properties b/collector/src/main/resources-local/pinpoint-collector.properties index b3c04663e992..1f0f9d9860c7 100644 --- a/collector/src/main/resources-local/pinpoint-collector.properties +++ b/collector/src/main/resources-local/pinpoint-collector.properties @@ -1,44 +1,48 @@ -#HBaseTemplate에서 사용하는 HtablePool사이즈 -hbase.hTablePoolSize=1024 - -# tcp listen ip -collector.tcpListenIp=0.0.0.0 -collector.tcpListenPort=9994 - -# udp listen ip -collector.udpStatListenIp=0.0.0.0 -collector.udpStatListenPort=9995 - -# L4 tcp 채널 close 무시를 위한 설정. -collector.l4.ip= - -# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. -collector.udpStatWorkerThread=16 -# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? -collector.udpStatWorkerQueueSize=512 - -#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. -collector.udpStatSocketReceiveBufferSize=4194304 - - -# span listen port --------------------------------------------------------------------- -collector.udpSpanListenIp=0.0.0.0 -collector.udpSpanListenPort=9996 - -# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. -collector.udpSpanWorkerThread=32 -# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? -collector.udpSpanWorkerQueueSize=1024 - -#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. -collector.udpSpanSocketReceiveBufferSize=4194304 -#$ /sbin/sysctl -a | grep -e rmem -e wmem -#net.core.wmem_max = 524288 -#net.core.rmem_max = 524288 -#net.core.wmem_default = 229376 -#net.core.rmem_default = 229376 -#위 설정을 다음과 같이 수정합니다. -#irteamsu$ sudo sysctl -w net.core.rmem_max=4194304 - -# 통계값 flush 주기 -statistics.flushPeriod=1000 \ No newline at end of file +#HBaseTemplate에서 사용하는 HtablePool사이즈 +hbase.hTablePoolSize=1024 + +# tcp listen ip +collector.tcpListenIp=0.0.0.0 +collector.tcpListenPort=9994 + +# udp listen ip +collector.udpStatListenIp=0.0.0.0 +collector.udpStatListenPort=9995 + +# L4 tcp 채널 close 무시를 위한 설정. +collector.l4.ip= + +# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. +collector.udpStatWorkerThread=16 +# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? +collector.udpStatWorkerQueueSize=512 + +#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. +collector.udpStatSocketReceiveBufferSize=4194304 + + +# span listen port --------------------------------------------------------------------- +collector.udpSpanListenIp=0.0.0.0 +collector.udpSpanListenPort=9996 + +# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. +collector.udpSpanWorkerThread=32 +# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? +collector.udpSpanWorkerQueueSize=1024 + +#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. +collector.udpSpanSocketReceiveBufferSize=4194304 +#$ /sbin/sysctl -a | grep -e rmem -e wmem +#net.core.wmem_max = 524288 +#net.core.rmem_max = 524288 +#net.core.wmem_default = 229376 +#net.core.rmem_default = 229376 +#위 설정을 다음과 같이 수정합니다. +#irteamsu$ sudo sysctl -w net.core.rmem_max=4194304 + +# 통계값 flush 주기 +statistics.flushPeriod=1000 + +cluster.enable=false +cluster.zookeeper.address= +cluster.zookeeper.sessiontimeout= \ No newline at end of file diff --git a/collector/src/main/resources-release/pinpoint-collector.properties b/collector/src/main/resources-release/pinpoint-collector.properties index 5dc4c0e49d9a..6107066817ef 100644 --- a/collector/src/main/resources-release/pinpoint-collector.properties +++ b/collector/src/main/resources-release/pinpoint-collector.properties @@ -1,44 +1,48 @@ -#HBaseTemplate에서 사용하는 HtablePool사이즈 -hbase.hTablePoolSize=1024 - -# tcp listen ip -collector.tcpListenIp=0.0.0.0 -collector.tcpListenPort=9994 - -# udp listen ip -collector.udpStatListenIp=0.0.0.0 -collector.udpStatListenPort=9995 - -# L4 tcp 채널 close 무시를 위한 설정. -collector.l4.ip=10.118.36.61,10.118.36.62 - -# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. -collector.udpStatWorkerThread=64 -# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? -collector.udpStatWorkerQueueSize=5120 - -#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. -collector.udpStatSocketReceiveBufferSize=4194304 - - -# span listen port --------------------------------------------------------------------- -collector.udpSpanListenIp=0.0.0.0 -collector.udpSpanListenPort=9996 - -# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. -collector.udpSpanWorkerThread=512 -# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? -collector.udpSpanWorkerQueueSize=20000 - -#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. -collector.udpSpanSocketReceiveBufferSize=4194304 -#$ /sbin/sysctl -a | grep -e rmem -e wmem -#net.core.wmem_max = 524288 -#net.core.rmem_max = 524288 -#net.core.wmem_default = 229376 -#net.core.rmem_default = 229376 -#위 설정을 다음과 같이 수정합니다. -#irteamsu$ sudo sysctl -w net.core.rmem_max=4194304 - -# 통계값 flush 주기 -statistics.flushPeriod=1000 \ No newline at end of file +#HBaseTemplate에서 사용하는 HtablePool사이즈 +hbase.hTablePoolSize=1024 + +# tcp listen ip +collector.tcpListenIp=0.0.0.0 +collector.tcpListenPort=9994 + +# udp listen ip +collector.udpStatListenIp=0.0.0.0 +collector.udpStatListenPort=9995 + +# L4 tcp 채널 close 무시를 위한 설정. +collector.l4.ip=10.118.36.61,10.118.36.62 + +# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. +collector.udpStatWorkerThread=64 +# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? +collector.udpStatWorkerQueueSize=5120 + +#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. +collector.udpStatSocketReceiveBufferSize=4194304 + + +# span listen port --------------------------------------------------------------------- +collector.udpSpanListenIp=0.0.0.0 +collector.udpSpanListenPort=9996 + +# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. +collector.udpSpanWorkerThread=512 +# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? +collector.udpSpanWorkerQueueSize=20000 + +#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. +collector.udpSpanSocketReceiveBufferSize=4194304 +#$ /sbin/sysctl -a | grep -e rmem -e wmem +#net.core.wmem_max = 524288 +#net.core.rmem_max = 524288 +#net.core.wmem_default = 229376 +#net.core.rmem_default = 229376 +#위 설정을 다음과 같이 수정합니다. +#irteamsu$ sudo sysctl -w net.core.rmem_max=4194304 + +# 통계값 flush 주기 +statistics.flushPeriod=1000 + +cluster.enable=false +cluster.zookeeper.address= +cluster.zookeeper.sessiontimeout= \ No newline at end of file diff --git a/collector/src/main/resources-test/pinpoint-collector.properties b/collector/src/main/resources-test/pinpoint-collector.properties index b3c04663e992..1f0f9d9860c7 100644 --- a/collector/src/main/resources-test/pinpoint-collector.properties +++ b/collector/src/main/resources-test/pinpoint-collector.properties @@ -1,44 +1,48 @@ -#HBaseTemplate에서 사용하는 HtablePool사이즈 -hbase.hTablePoolSize=1024 - -# tcp listen ip -collector.tcpListenIp=0.0.0.0 -collector.tcpListenPort=9994 - -# udp listen ip -collector.udpStatListenIp=0.0.0.0 -collector.udpStatListenPort=9995 - -# L4 tcp 채널 close 무시를 위한 설정. -collector.l4.ip= - -# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. -collector.udpStatWorkerThread=16 -# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? -collector.udpStatWorkerQueueSize=512 - -#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. -collector.udpStatSocketReceiveBufferSize=4194304 - - -# span listen port --------------------------------------------------------------------- -collector.udpSpanListenIp=0.0.0.0 -collector.udpSpanListenPort=9996 - -# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. -collector.udpSpanWorkerThread=32 -# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? -collector.udpSpanWorkerQueueSize=1024 - -#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. -collector.udpSpanSocketReceiveBufferSize=4194304 -#$ /sbin/sysctl -a | grep -e rmem -e wmem -#net.core.wmem_max = 524288 -#net.core.rmem_max = 524288 -#net.core.wmem_default = 229376 -#net.core.rmem_default = 229376 -#위 설정을 다음과 같이 수정합니다. -#irteamsu$ sudo sysctl -w net.core.rmem_max=4194304 - -# 통계값 flush 주기 -statistics.flushPeriod=1000 \ No newline at end of file +#HBaseTemplate에서 사용하는 HtablePool사이즈 +hbase.hTablePoolSize=1024 + +# tcp listen ip +collector.tcpListenIp=0.0.0.0 +collector.tcpListenPort=9994 + +# udp listen ip +collector.udpStatListenIp=0.0.0.0 +collector.udpStatListenPort=9995 + +# L4 tcp 채널 close 무시를 위한 설정. +collector.l4.ip= + +# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. +collector.udpStatWorkerThread=16 +# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? +collector.udpStatWorkerQueueSize=512 + +#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. +collector.udpStatSocketReceiveBufferSize=4194304 + + +# span listen port --------------------------------------------------------------------- +collector.udpSpanListenIp=0.0.0.0 +collector.udpSpanListenPort=9996 + +# udp메시지를 처리할 thread 수, hbase.hTablePoolSize사이즈와 같이 조절해야 한다. +collector.udpSpanWorkerThread=32 +# udp메시지를 처리할 thread가 모두 동작중일때 요청을 몇개까지 큐잉할지? +collector.udpSpanWorkerQueueSize=1024 + +#udp socket의 receiveBufferSize설정. 만약 udp 손실율이 심할 경우 아래 사항을 체크해볼것. +collector.udpSpanSocketReceiveBufferSize=4194304 +#$ /sbin/sysctl -a | grep -e rmem -e wmem +#net.core.wmem_max = 524288 +#net.core.rmem_max = 524288 +#net.core.wmem_default = 229376 +#net.core.rmem_default = 229376 +#위 설정을 다음과 같이 수정합니다. +#irteamsu$ sudo sysctl -w net.core.rmem_max=4194304 + +# 통계값 flush 주기 +statistics.flushPeriod=1000 + +cluster.enable=false +cluster.zookeeper.address= +cluster.zookeeper.sessiontimeout= \ No newline at end of file diff --git a/collector/src/main/resources/applicationContext.xml b/collector/src/main/resources/applicationContext.xml index 5166d6db2269..8eca27b555ea 100644 --- a/collector/src/main/resources/applicationContext.xml +++ b/collector/src/main/resources/applicationContext.xml @@ -1,118 +1,122 @@ - - - - - - - - - - - classpath:hbase.properties - classpath:pinpoint-collector.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + classpath:hbase.properties + classpath:pinpoint-collector.properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/ZookeeperClusterManagerTest2.java b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperEnsembleProfilerClusterServiceTest.java similarity index 71% rename from collector/src/test/java/com/navercorp/pinpoint/collector/cluster/ZookeeperClusterManagerTest2.java rename to collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperEnsembleProfilerClusterServiceTest.java index f001c890a6bc..3bc27090e192 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/ZookeeperClusterManagerTest2.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperEnsembleProfilerClusterServiceTest.java @@ -1,227 +1,252 @@ -package com.nhn.pinpoint.collector.cluster; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.apache.curator.test.InstanceSpec; -import org.apache.curator.test.TestingCluster; -import org.apache.curator.test.TestingZooKeeperServer; -import org.junit.Assert; -import org.junit.Test; - -import com.nhn.pinpoint.collector.cluster.zookeeper.ZookeeperClusterManager; -import com.nhn.pinpoint.collector.receiver.tcp.AgentProperties; -import com.nhn.pinpoint.rpc.server.ChannelContext; -import com.nhn.pinpoint.rpc.server.PinpointServerSocketStateCode; - -public class ZookeeperClusterManagerTest2 { - - @Test - public void simpleTest1() throws Exception { - TestingCluster tcluster = null; - try { - tcluster = createZookeeperCluster(3); - - String connectString = getConnectString(tcluster); - - ZookeeperClusterManager clusterManager = new ZookeeperClusterManager(connectString, 3000); - - ChannelContext channelContext = new ChannelContext(null, null, clusterManager); - channelContext.setChannelProperties(getParams()); - - channelContext.changeStateRun(); - Thread.sleep(1000); - Map result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - channelContext.changeStateRunDuplexCommunication(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); - - channelContext.changeStateShutdown(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - clusterManager.close(); - } finally { - closeZookeeperCluster(tcluster); - } - } - - // 연결되어 있는 쥬키퍼 클러스터가 끊어졌을때 해당 이벤트가 유지되는지 - // 테스트 코드만으로는 정확한 확인은 힘들다. 로그를 봐야함 - @Test - public void simpleTest2() throws Exception { - TestingCluster tcluster = null; - try { - tcluster = createZookeeperCluster(3); - - String connectString = getConnectString(tcluster); - - ZookeeperClusterManager clusterManager = new ZookeeperClusterManager(connectString, 3000); - - ChannelContext channelContext = new ChannelContext(null, null, clusterManager); - channelContext.setChannelProperties(getParams()); - - channelContext.changeStateRun(); - Thread.sleep(1000); - Map result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - channelContext.changeStateRunDuplexCommunication(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); - - restart(tcluster); - - result = clusterManager.getData(channelContext); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); - - channelContext.changeStateShutdown(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - clusterManager.close(); - } finally { - closeZookeeperCluster(tcluster); - } - } - - // 연결되어 있는 쥬키퍼 클러스터가 모두 죽었을 경우 - // 그 이후 해당 이벤트가 유지되는지 - // 테스트 코드만으로는 정확한 확인은 힘들다. 로그를 봐야함 - @Test - public void simpleTest3() throws Exception { - TestingCluster tcluster = null; - try { - tcluster = createZookeeperCluster(3); - - String connectString = getConnectString(tcluster); - - ZookeeperClusterManager clusterManager = new ZookeeperClusterManager(connectString, 3000); - - ChannelContext channelContext = new ChannelContext(null, null, clusterManager); - channelContext.setChannelProperties(getParams()); - - channelContext.changeStateRun(); - Thread.sleep(1000); - Map result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - channelContext.changeStateRunDuplexCommunication(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); - - stop(tcluster); - - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - restart(tcluster); - - result = clusterManager.getData(channelContext); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); - - channelContext.changeStateShutdown(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - clusterManager.close(); - } finally { - closeZookeeperCluster(tcluster); - } - } - - - private TestingCluster createZookeeperCluster(int size) throws Exception { - return createZookeeperCluster(size, true); - } - - private TestingCluster createZookeeperCluster(int size, boolean start) throws Exception { - TestingCluster zookeeperCluster = new TestingCluster(size); - - // 주의 cluster 초기화에 시간이 좀 걸림 그래서 테스트에 sleep을 좀 길게 둠 - // 다 된걸 받는 이벤트도 없음 - if (start) { - zookeeperCluster.start(); - Thread.sleep(5000); - } - - return zookeeperCluster; - } - - private void startZookeeperCluster(TestingCluster zookeeperCluster) throws Exception { - zookeeperCluster.start(); - Thread.sleep(5000); - } - - private void restart(TestingCluster zookeeperCluster) throws Exception { - for (TestingZooKeeperServer zookeeperServer : zookeeperCluster.getServers()) { - zookeeperServer.restart(); - } - Thread.sleep(5000); - } - - private void stop(TestingCluster zookeeperCluster) throws Exception { - zookeeperCluster.stop(); - Thread.sleep(5000); - } - - - private void closeZookeeperCluster(TestingCluster zookeeperCluster) throws Exception { - try { - if (zookeeperCluster != null) { - zookeeperCluster.close(); - } - } catch (Exception e) { - } - } - - private String getConnectString(TestingZooKeeperServer testingZooKeeperServer) { - return testingZooKeeperServer.getInstanceSpec().getConnectString(); - } - - private String getConnectString(TestingCluster zookeeperCluster) { - StringBuilder connectString = new StringBuilder(); - - Iterator instanceSpecIterator = zookeeperCluster.getInstances().iterator(); - while (instanceSpecIterator.hasNext()) { - InstanceSpec instanceSpec = instanceSpecIterator.next(); - connectString.append(instanceSpec.getConnectString()); - - if (instanceSpecIterator.hasNext()) { - connectString.append(","); - } - } - - return connectString.toString(); - } - - private PinpointServerSocketStateCode getCode(Map channelContextData) { - String state = (String) channelContextData.get("state"); - return PinpointServerSocketStateCode.getStateCode(state); - } - - private Map getParams() { - Map properties = new HashMap(); - - properties.put(AgentProperties.KEY_AGENTID, "agent"); - properties.put(AgentProperties.KEY_APPLICATION_NAME, "application"); - properties.put(AgentProperties.KEY_HOSTNAME, "hostname"); - properties.put(AgentProperties.KEY_IP, "ip"); - properties.put(AgentProperties.KEY_PID, 1111); - properties.put(AgentProperties.KEY_SERVICE_TYPE, 10); - properties.put(AgentProperties.KEY_START_TIME_MILLIS, System.currentTimeMillis()); - properties.put(AgentProperties.KEY_VERSION, "1.0"); - - return properties; - } - -} +package com.nhn.pinpoint.collector.cluster.zookeeper; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import junit.framework.Assert; + +import org.apache.curator.test.InstanceSpec; +import org.apache.curator.test.TestingCluster; +import org.apache.curator.test.TestingZooKeeperServer; +import org.junit.Test; + +import com.nhn.pinpoint.collector.config.CollectorConfiguration; +import com.nhn.pinpoint.collector.receiver.tcp.AgentProperties; +import com.nhn.pinpoint.rpc.server.ChannelContext; +import com.nhn.pinpoint.rpc.server.PinpointServerSocketStateCode; + +public class ZookeeperEnsembleProfilerClusterServiceTest { + + @Test + public void simpleTest1() throws Exception { + TestingCluster tcluster = null; + try { + tcluster = createZookeeperCluster(3); + + String connectString = getConnectString(tcluster); + + CollectorConfiguration collectorConfig = createConfig(connectString); + + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + service.setUp(); + + ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); + channelContext.setChannelProperties(getParams()); + + ZookeeperProfilerClusterManager profilerClusterManager = service.getProfilerClusterManager(); + + channelContext.changeStateRun(); + Thread.sleep(1000); + Map result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + channelContext.changeStateRunDuplexCommunication(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); + + channelContext.changeStateShutdown(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + service.tearDown(); + } finally { + closeZookeeperCluster(tcluster); + } + } + + // 연결되어 있는 쥬키퍼 클러스터가 끊어졌을때 해당 이벤트가 유지되는지 + // 테스트 코드만으로는 정확한 확인은 힘들다. 로그를 봐야함 + @Test + public void simpleTest2() throws Exception { + TestingCluster tcluster = null; + try { + tcluster = createZookeeperCluster(3); + + String connectString = getConnectString(tcluster); + + CollectorConfiguration collectorConfig = createConfig(connectString); + + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + service.setUp(); + + ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); + channelContext.setChannelProperties(getParams()); + + ZookeeperProfilerClusterManager profilerClusterManager = service.getProfilerClusterManager(); + + channelContext.changeStateRun(); + Thread.sleep(1000); + Map result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + channelContext.changeStateRunDuplexCommunication(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); + + restart(tcluster); + + result = profilerClusterManager.getData(channelContext); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); + + channelContext.changeStateShutdown(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + service.tearDown(); + } finally { + closeZookeeperCluster(tcluster); + } + } + + // + // 연결되어 있는 쥬키퍼 클러스터가 모두 죽었을 경우 + // 그 이후 해당 이벤트가 유지되는지 + // 테스트 코드만으로는 정확한 확인은 힘들다. 로그를 봐야함 + @Test + public void simpleTest3() throws Exception { + TestingCluster tcluster = null; + try { + tcluster = createZookeeperCluster(3); + + String connectString = getConnectString(tcluster); + + CollectorConfiguration collectorConfig = createConfig(connectString); + + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + service.setUp(); + + ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); + channelContext.setChannelProperties(getParams()); + + ZookeeperProfilerClusterManager profilerClusterManager = service.getProfilerClusterManager(); + + channelContext.changeStateRun(); + Thread.sleep(1000); + Map result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + channelContext.changeStateRunDuplexCommunication(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); + + stop(tcluster); + + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + restart(tcluster); + + result = profilerClusterManager.getData(channelContext); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); + + channelContext.changeStateShutdown(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + service.tearDown(); + } finally { + closeZookeeperCluster(tcluster); + } + } + + private TestingCluster createZookeeperCluster(int size) throws Exception { + return createZookeeperCluster(size, true); + } + + private TestingCluster createZookeeperCluster(int size, boolean start) throws Exception { + TestingCluster zookeeperCluster = new TestingCluster(size); + + // 주의 cluster 초기화에 시간이 좀 걸림 그래서 테스트에 sleep을 좀 길게 둠 + // 다 된걸 받는 이벤트도 없음 + if (start) { + zookeeperCluster.start(); + Thread.sleep(5000); + } + + return zookeeperCluster; + } + + private void startZookeeperCluster(TestingCluster zookeeperCluster) throws Exception { + zookeeperCluster.start(); + Thread.sleep(5000); + } + + private void restart(TestingCluster zookeeperCluster) throws Exception { + for (TestingZooKeeperServer zookeeperServer : zookeeperCluster.getServers()) { + zookeeperServer.restart(); + } + Thread.sleep(5000); + } + + private void stop(TestingCluster zookeeperCluster) throws Exception { + zookeeperCluster.stop(); + Thread.sleep(5000); + } + + private void closeZookeeperCluster(TestingCluster zookeeperCluster) throws Exception { + try { + if (zookeeperCluster != null) { + zookeeperCluster.close(); + } + } catch (Exception e) { + } + } + + private String getConnectString(TestingZooKeeperServer testingZooKeeperServer) { + return testingZooKeeperServer.getInstanceSpec().getConnectString(); + } + + private String getConnectString(TestingCluster zookeeperCluster) { + StringBuilder connectString = new StringBuilder(); + + Iterator instanceSpecIterator = zookeeperCluster.getInstances().iterator(); + while (instanceSpecIterator.hasNext()) { + InstanceSpec instanceSpec = instanceSpecIterator.next(); + connectString.append(instanceSpec.getConnectString()); + + if (instanceSpecIterator.hasNext()) { + connectString.append(","); + } + } + + return connectString.toString(); + } + + private PinpointServerSocketStateCode getCode(Map channelContextData) { + String state = (String) channelContextData.get("state"); + return PinpointServerSocketStateCode.getStateCode(state); + } + + private Map getParams() { + Map properties = new HashMap(); + + properties.put(AgentProperties.KEY_AGENTID, "agent"); + properties.put(AgentProperties.KEY_APPLICATION_NAME, "application"); + properties.put(AgentProperties.KEY_HOSTNAME, "hostname"); + properties.put(AgentProperties.KEY_IP, "ip"); + properties.put(AgentProperties.KEY_PID, 1111); + properties.put(AgentProperties.KEY_SERVICE_TYPE, 10); + properties.put(AgentProperties.KEY_START_TIME_MILLIS, System.currentTimeMillis()); + properties.put(AgentProperties.KEY_VERSION, "1.0"); + + return properties; + } + + private CollectorConfiguration createConfig(String connectString) { + CollectorConfiguration collectorConfig = new CollectorConfiguration(); + + collectorConfig.setClusterEnable(true); + collectorConfig.setClusterAddress(connectString); + collectorConfig.setClusterSessionTimeout(3000); + + return collectorConfig; + } + +} diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/ZookeeperClusterManagerTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterServiceTest.java similarity index 66% rename from collector/src/test/java/com/navercorp/pinpoint/collector/cluster/ZookeeperClusterManagerTest.java rename to collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterServiceTest.java index 50ff2a39315f..e080a9272824 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/ZookeeperClusterManagerTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterServiceTest.java @@ -1,249 +1,275 @@ -package com.nhn.pinpoint.collector.cluster; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.curator.test.TestingServer; -import org.junit.Assert; -import org.junit.Test; - -import com.nhn.pinpoint.collector.cluster.zookeeper.ZookeeperClusterManager; -import com.nhn.pinpoint.collector.receiver.tcp.AgentProperties; -import com.nhn.pinpoint.rpc.server.ChannelContext; -import com.nhn.pinpoint.rpc.server.PinpointServerSocketStateCode; - -public class ZookeeperClusterManagerTest { - - private static final int DEFAULT_ACCEPTOR_PORT = 22213; - - // 심플 쥬키퍼 테스트 - // 상태에 변경에 따라 상태 변경이 제대로 되어있는지 확인 - @Test - public void simpleTest1() throws Exception { - TestingServer ts = null; - try { - ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); - - ZookeeperClusterManager clusterManager = new ZookeeperClusterManager("127.0.0.1:" + DEFAULT_ACCEPTOR_PORT, 3000); - - ChannelContext channelContext = new ChannelContext(null, null, clusterManager); - channelContext.setChannelProperties(getParams()); - - channelContext.changeStateRun(); - Thread.sleep(1000); - Map result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - channelContext.changeStateRunDuplexCommunication(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); - - channelContext.changeStateShutdown(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - clusterManager.close(); - } finally { - closeZookeeperServer(ts); - } - } - - // 심플 쥬키퍼 테스트 - // 쥬키퍼와 연결이 끊어져 있는경우 이벤트가 발생했을때 쥬키퍼와 연결이 될 경우 해당 이벤트가 처리되어 있는지 - @Test - public void simpleTest2() throws Exception { - TestingServer ts = null; - try { - - ZookeeperClusterManager clusterManager = new ZookeeperClusterManager("127.0.0.1:" + DEFAULT_ACCEPTOR_PORT, 3000); - - ChannelContext channelContext = new ChannelContext(null, null, clusterManager); - channelContext.setChannelProperties(getParams()); - - channelContext.changeStateRun(); - Thread.sleep(1000); - Map result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - channelContext.changeStateRunDuplexCommunication(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); - - channelContext.changeStateShutdown(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - clusterManager.close(); - } finally { - closeZookeeperServer(ts); - } - } - - // 심플 쥬키퍼 테스트 - // 쥬키퍼와 연결되었을때 이벤트가 등록되었는데 - // 쥬키퍼가 종료 되고 다시 연결될때 해당 이벤트가 상태를 유지 되는지 - @Test - public void simpleTest3() throws Exception { - TestingServer ts = null; - try { - ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); - - ZookeeperClusterManager clusterManager = new ZookeeperClusterManager("127.0.0.1:" + DEFAULT_ACCEPTOR_PORT, 3000); - - ChannelContext channelContext = new ChannelContext(null, null, clusterManager); - channelContext.setChannelProperties(getParams()); - - channelContext.changeStateRun(); - Thread.sleep(1000); - Map result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - channelContext.changeStateRunDuplexCommunication(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); - - ts.stop(); - Thread.sleep(1000); - ts.restart(); - Thread.sleep(1000); - - result = clusterManager.getData(channelContext); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); - - channelContext.changeStateShutdown(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - clusterManager.close(); - } finally { - closeZookeeperServer(ts); - } - } - - // 심플 쥬키퍼 테스트 - // 쥬키퍼와 연결이 끊어져 있는경우 이벤트가 발생했을때 쥬키퍼와 연결이 될 경우 해당 이벤트가 처리되어 있는지 - @Test - public void simpleTest4() throws Exception { - TestingServer ts = null; - try { - ZookeeperClusterManager clusterManager = new ZookeeperClusterManager("127.0.0.1:" + DEFAULT_ACCEPTOR_PORT, 3000); - - ChannelContext channelContext = new ChannelContext(null, null, clusterManager); - channelContext.setChannelProperties(getParams()); - - channelContext.changeStateRun(); - Thread.sleep(1000); - Map result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - channelContext.changeStateRunDuplexCommunication(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - channelContext.changeStateShutdown(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - clusterManager.close(); - } finally { - closeZookeeperServer(ts); - } - } - - // 심플 쥬키퍼 테스트 - // 쥬키퍼와 연결되었을때 이벤트가 등록되었는데 - // 쥬키퍼가 종료 되고 다시 연결될때 해당 이벤트가 상태를 유지 되는지 - @Test - public void simpleTest5() throws Exception { - TestingServer ts = null; - try { - ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); - - ZookeeperClusterManager clusterManager = new ZookeeperClusterManager("127.0.0.1:" + DEFAULT_ACCEPTOR_PORT, 3000); - - ChannelContext channelContext = new ChannelContext(null, null, clusterManager); - channelContext.setChannelProperties(getParams()); - - channelContext.changeStateRun(); - Thread.sleep(1000); - Map result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - channelContext.changeStateRunDuplexCommunication(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); - - channelContext.changeStateShutdown(); - Thread.sleep(1000); - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - ts.stop(); - Thread.sleep(1000); - ts.restart(); - Thread.sleep(1000); - - result = clusterManager.getData(channelContext); - Assert.assertNull(getCode(result)); - - clusterManager.close(); - } finally { - closeZookeeperServer(ts); - } - } - - private TestingServer createZookeeperServer(int port) throws Exception { - TestingServer mockZookeeperServer = new TestingServer(port); - mockZookeeperServer.start(); - - return mockZookeeperServer; - } - - private void closeZookeeperServer(TestingServer mockZookeeperServer) throws Exception { - try { - mockZookeeperServer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private PinpointServerSocketStateCode getCode(Map channelContextData) { - String state = (String) channelContextData.get("state"); - return PinpointServerSocketStateCode.getStateCode(state); - } - - private Map getParams() { - Map properties = new HashMap(); - - properties.put(AgentProperties.KEY_AGENTID, "agent"); - properties.put(AgentProperties.KEY_APPLICATION_NAME, "application"); - properties.put(AgentProperties.KEY_HOSTNAME, "hostname"); - properties.put(AgentProperties.KEY_IP, "ip"); - properties.put(AgentProperties.KEY_PID, 1111); - properties.put(AgentProperties.KEY_SERVICE_TYPE, 10); - properties.put(AgentProperties.KEY_START_TIME_MILLIS, System.currentTimeMillis()); - properties.put(AgentProperties.KEY_VERSION, "1.0"); - - return properties; - } - -} +package com.nhn.pinpoint.collector.cluster.zookeeper; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.curator.test.TestingServer; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.nhn.pinpoint.collector.config.CollectorConfiguration; +import com.nhn.pinpoint.collector.receiver.tcp.AgentProperties; +import com.nhn.pinpoint.rpc.server.ChannelContext; +import com.nhn.pinpoint.rpc.server.PinpointServerSocketStateCode; + +public class ZookeeperProfilerClusterServiceTest { + + private static final int DEFAULT_ACCEPTOR_PORT = 22213; + + private static CollectorConfiguration collectorConfig = null; + + @BeforeClass + public static void setUp() { + collectorConfig = new CollectorConfiguration(); + + collectorConfig.setClusterEnable(true); + collectorConfig.setClusterAddress("127.0.0.1:" + DEFAULT_ACCEPTOR_PORT); + collectorConfig.setClusterSessionTimeout(3000); + } + + @Test + public void simpleTest1() throws Exception { + TestingServer ts = null; + try { + ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); + + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + service.setUp(); + + ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); + channelContext.setChannelProperties(getParams()); + + ZookeeperProfilerClusterManager profilerClusterManager = service.getProfilerClusterManager(); + + channelContext.changeStateRun(); + Thread.sleep(1000); + + Map result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + channelContext.changeStateRunDuplexCommunication(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); + + channelContext.changeStateShutdown(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + service.tearDown(); + } finally { + closeZookeeperServer(ts); + } + } + + // 심플 쥬키퍼 테스트 + // 쥬키퍼와 연결이 끊어져 있는경우 이벤트가 발생했을때 쥬키퍼와 연결이 될 경우 해당 이벤트가 처리되어 있는지 + @Test + public void simpleTest2() throws Exception { + TestingServer ts = null; + try { + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + service.setUp(); + + ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); + channelContext.setChannelProperties(getParams()); + + ZookeeperProfilerClusterManager profilerClusterManager = service.getProfilerClusterManager(); + + channelContext.changeStateRun(); + Thread.sleep(1000); + Map result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + channelContext.changeStateRunDuplexCommunication(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); + + channelContext.changeStateShutdown(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + service.tearDown(); + } finally { + closeZookeeperServer(ts); + } + } + + // 심플 쥬키퍼 테스트 + // 쥬키퍼와 연결되었을때 이벤트가 등록되었는데 + // 쥬키퍼가 종료 되고 다시 연결될때 해당 이벤트가 상태를 유지 되는지 + @Test + public void simpleTest3() throws Exception { + TestingServer ts = null; + try { + ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); + + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + service.setUp(); + + ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); + channelContext.setChannelProperties(getParams()); + + ZookeeperProfilerClusterManager profilerClusterManager = service.getProfilerClusterManager(); + + channelContext.changeStateRun(); + Thread.sleep(1000); + Map result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + channelContext.changeStateRunDuplexCommunication(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); + + ts.stop(); + Thread.sleep(1000); + ts.restart(); + Thread.sleep(1000); + + result = profilerClusterManager.getData(channelContext); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); + + channelContext.changeStateShutdown(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + service.tearDown(); + } finally { + closeZookeeperServer(ts); + } + } + + // 심플 쥬키퍼 테스트 + // 쥬키퍼와 연결이 끊어져 있는경우 이벤트가 발생했을때 쥬키퍼와 연결이 될 경우 해당 이벤트가 처리되어 있는지 + @Test + public void simpleTest4() throws Exception { + TestingServer ts = null; + try { + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + service.setUp(); + + ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); + channelContext.setChannelProperties(getParams()); + + ZookeeperProfilerClusterManager profilerClusterManager = service.getProfilerClusterManager(); + + channelContext.changeStateRun(); + Thread.sleep(1000); + Map result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + channelContext.changeStateRunDuplexCommunication(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + channelContext.changeStateShutdown(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + service.tearDown(); + } finally { + closeZookeeperServer(ts); + } + } + + // + // 심플 쥬키퍼 테스트 + // 쥬키퍼와 연결되었을때 이벤트가 등록되었는데 + // 쥬키퍼가 종료 되고 다시 연결될때 해당 이벤트가 상태를 유지 되는지 + @Test + public void simpleTest5() throws Exception { + TestingServer ts = null; + try { + ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); + + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + service.setUp(); + + ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); + channelContext.setChannelProperties(getParams()); + + ZookeeperProfilerClusterManager profilerClusterManager = service.getProfilerClusterManager(); + + channelContext.changeStateRun(); + Thread.sleep(1000); + Map result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + channelContext.changeStateRunDuplexCommunication(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, getCode(result)); + + channelContext.changeStateShutdown(); + Thread.sleep(1000); + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + ts.stop(); + Thread.sleep(1000); + ts.restart(); + Thread.sleep(1000); + + result = profilerClusterManager.getData(channelContext); + Assert.assertNull(getCode(result)); + + service.tearDown(); + } finally { + closeZookeeperServer(ts); + } + } + + private TestingServer createZookeeperServer(int port) throws Exception { + TestingServer mockZookeeperServer = new TestingServer(port); + mockZookeeperServer.start(); + + return mockZookeeperServer; + } + + private void closeZookeeperServer(TestingServer mockZookeeperServer) throws Exception { + try { + mockZookeeperServer.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private PinpointServerSocketStateCode getCode(Map channelContextData) { + String state = (String) channelContextData.get("state"); + return PinpointServerSocketStateCode.getStateCode(state); + } + + private Map getParams() { + Map properties = new HashMap(); + + properties.put(AgentProperties.KEY_AGENTID, "agent"); + properties.put(AgentProperties.KEY_APPLICATION_NAME, "application"); + properties.put(AgentProperties.KEY_HOSTNAME, "hostname"); + properties.put(AgentProperties.KEY_IP, "ip"); + properties.put(AgentProperties.KEY_PID, 1111); + properties.put(AgentProperties.KEY_SERVICE_TYPE, 10); + properties.put(AgentProperties.KEY_START_TIME_MILLIS, System.currentTimeMillis()); + properties.put(AgentProperties.KEY_VERSION, "1.0"); + + return properties; + } + +} diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterServiceTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterServiceTest.java new file mode 100644 index 000000000000..a2fa57d163c0 --- /dev/null +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterServiceTest.java @@ -0,0 +1,136 @@ +package com.nhn.pinpoint.collector.cluster.zookeeper; + +import java.util.List; +import java.util.Map; + +import junit.framework.Assert; + +import org.apache.curator.test.TestingServer; +import org.apache.zookeeper.WatchedEvent; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nhn.pinpoint.collector.config.CollectorConfiguration; +import com.nhn.pinpoint.rpc.packet.ControlEnableWorkerConfirmPacket; +import com.nhn.pinpoint.rpc.packet.RequestPacket; +import com.nhn.pinpoint.rpc.packet.SendPacket; +import com.nhn.pinpoint.rpc.packet.StreamPacket; +import com.nhn.pinpoint.rpc.server.ChannelContext; +import com.nhn.pinpoint.rpc.server.PinpointServerSocket; +import com.nhn.pinpoint.rpc.server.PinpointServerSocketStateCode; +import com.nhn.pinpoint.rpc.server.ServerMessageListener; +import com.nhn.pinpoint.rpc.server.ServerStreamChannel; +import com.nhn.pinpoint.rpc.server.SocketChannel; + +public class ZookeeperWebClusterServiceTest { + + private static final String PINPOINT_CLUSTER_PATH = "/pinpoint-cluster"; + private static final String PINPOINT_WEB_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/web"; + private static final String PINPOINT_PROFILER_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/profiler"; + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private static final int DEFAULT_ZOOKEEPER_PORT = 22213; + private static final int DEFAULT_ACCEPTOR_SOCKET_PORT = 22214; + + private static CollectorConfiguration collectorConfig = null; + + @BeforeClass + public static void setUp() { + collectorConfig = new CollectorConfiguration(); + + collectorConfig.setClusterEnable(true); + collectorConfig.setClusterAddress("127.0.0.1:" + DEFAULT_ZOOKEEPER_PORT); + collectorConfig.setClusterSessionTimeout(3000); + } + + @Test + public void simpleTest1() throws Exception { + TestingServer ts = null; + try { + ts = createZookeeperServer(DEFAULT_ZOOKEEPER_PORT); + + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + service.setUp(); + + PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(); + pinpointServerSocket.setMessageListener(new PinpointSocketManagerHandler()); + pinpointServerSocket.bind("127.0.0.1", DEFAULT_ACCEPTOR_SOCKET_PORT); + + ZookeeperClient client = new ZookeeperClient("127.0.0.1:" + DEFAULT_ZOOKEEPER_PORT, 3000, new ZookeeperEventWatcher() { + + @Override + public void process(WatchedEvent event) { + + } + + @Override + public boolean isConnected() { + return true; + } + }); + client.createPath(PINPOINT_WEB_CLUSTER_PATH, true); + client.createNode(PINPOINT_WEB_CLUSTER_PATH + "/" + "127.0.0.1:" + DEFAULT_ACCEPTOR_SOCKET_PORT, "127.0.0.1".getBytes()); + + Thread.sleep(5000); + + List channelContextList = pinpointServerSocket.getDuplexCommunicationChannelContext(); + Assert.assertEquals(1, channelContextList.size()); + + client.close(); + + Thread.sleep(5000); + channelContextList = pinpointServerSocket.getDuplexCommunicationChannelContext(); + Assert.assertEquals(0, channelContextList.size()); + + service.tearDown(); + } finally { + closeZookeeperServer(ts); + } + } + + private TestingServer createZookeeperServer(int port) throws Exception { + TestingServer mockZookeeperServer = new TestingServer(port); + mockZookeeperServer.start(); + + return mockZookeeperServer; + } + + private void closeZookeeperServer(TestingServer mockZookeeperServer) throws Exception { + try { + mockZookeeperServer.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private PinpointServerSocketStateCode getCode(Map channelContextData) { + String state = (String) channelContextData.get("state"); + return PinpointServerSocketStateCode.getStateCode(state); + } + + private class PinpointSocketManagerHandler implements ServerMessageListener { + @Override + public void handleSend(SendPacket sendPacket, SocketChannel channel) { + logger.warn("Unsupport send received {} {}", sendPacket, channel); + } + + @Override + public void handleRequest(RequestPacket requestPacket, SocketChannel channel) { + logger.warn("Unsupport request received {} {}", requestPacket, channel); + } + + @Override + public void handleStream(StreamPacket streamPacket, ServerStreamChannel streamChannel) { + logger.warn("unsupported streamPacket received {}", streamPacket); + } + + @Override + public int handleEnableWorker(Map properties) { + logger.warn("do handleEnableWorker {}", properties); + return ControlEnableWorkerConfirmPacket.SUCCESS; + } + } + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/ScatterChartController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/ScatterChartController.java index 538e87b585ec..1d6671047560 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/controller/ScatterChartController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/ScatterChartController.java @@ -1,312 +1,311 @@ -package com.nhn.pinpoint.web.controller; - -import java.util.List; -import java.util.SortedSet; -import java.util.TreeSet; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.nhn.pinpoint.common.util.DateUtils; -import com.nhn.pinpoint.web.service.FilteredMapService; -import com.nhn.pinpoint.web.util.LimitUtils; -import com.nhn.pinpoint.web.filter.Filter; -import com.nhn.pinpoint.web.filter.FilterBuilder; -import com.nhn.pinpoint.web.vo.*; -import com.nhn.pinpoint.web.vo.scatter.Dot; -import com.nhn.pinpoint.web.vo.scatter.ScatterIndex; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.util.StopWatch; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; - -import com.nhn.pinpoint.common.bo.SpanBo; -import com.nhn.pinpoint.web.service.ScatterChartService; -import com.nhn.pinpoint.web.util.TimeUtils; -import org.springframework.web.servlet.ModelAndView; - -/** - * - * @author netspider - * @author emeroad - */ -@Controller -public class ScatterChartController { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - private ScatterChartService scatter; - - @Autowired - private FilteredMapService flow; - - @Autowired - private FilterBuilder filterBuilder; - - private static final String PREFIX_TRANSACTION_ID = "I"; - private static final String PREFIX_TIME = "T"; - private static final String PREFIX_RESPONSE_TIME = "R"; - - @RequestMapping(value = "/scatterpopup", method = RequestMethod.GET) - public String scatterPopup(Model model, - @RequestParam("application") String applicationName, - @RequestParam("from") long from, - @RequestParam("to") long to, - @RequestParam("period") long period, - @RequestParam("usePeriod") boolean usePeriod, - @RequestParam(value = "filter", required = false) String filterText) { - model.addAttribute("applicationName", applicationName); - model.addAttribute("from", from); - model.addAttribute("to", to); - model.addAttribute("period", period); - model.addAttribute("usePeriod", usePeriod); - model.addAttribute("filter", filterText); - return "scatterPopup"; - } - - /** - * - * @param applicationName - * @param from - * @param to - * @param limit - * 한번에 조회 할 데이터의 크기, 조회 결과가 이 크기를 넘어가면 limit개만 반환한다. 나머지는 다시 요청해서 - * 조회해야 한다. - * @return - */ - @RequestMapping(value = "/getScatterData", method = RequestMethod.GET) - public ModelAndView getScatterData( - @RequestParam("application") String applicationName, - @RequestParam("from") long from, - @RequestParam("to") long to, - @RequestParam("limit") int limit, - @RequestParam(value = "filter", required = false) String filterText, - @RequestParam(value = "_callback", required = false) String jsonpCallback, - @RequestParam(value = "v", required = false, defaultValue = "2") int version) { - limit = LimitUtils.checkRange(limit); - - StopWatch watch = new StopWatch(); - watch.start("selectScatterData"); - - // TODO 레인지 체크 확인 exception 발생, from값이 to 보다 더 큼. - final Range range = Range.createUncheckedRange(from, to); - logger.debug("fetch scatter data. {}, LIMIT={}, FILTER={}", range, limit, filterText); - - ModelAndView mv; - if (filterText == null) { - mv = selectScatterData(applicationName, range, limit, jsonpCallback); - } else { - mv = selectFilterScatterDataData(applicationName, range, filterText, limit, jsonpCallback); - } - - watch.stop(); - - logger.info("Fetch scatterData time : {}ms", watch.getLastTaskTimeMillis()); - - return mv; - } - - private ModelAndView selectFilterScatterDataData(String applicationName, Range range, String filterText, int limit, String jsonpCallback) { - - final LimitedScanResult> limitedScanResult = flow.selectTraceIdsFromApplicationTraceIndex(applicationName, range, limit); - - final List traceIdList = limitedScanResult.getScanData(); - logger.trace("submitted transactionId count={}", traceIdList.size()); - // TODO sorted만 하는가? tree기반으로 레인지 체크하도록 하고 삭제하도록 하자. - SortedSet traceIdSet = new TreeSet(traceIdList); - logger.debug("unified traceIdSet size={}", traceIdSet.size()); - - Filter filter = filterBuilder.build(filterText); - List scatterData = scatter.selectScatterData(traceIdSet, applicationName, filter); - if (logger.isDebugEnabled()) { - logger.debug("getScatterData range scan(limited:{}) from ~ to:{} ~ {}, limited:{}, filterDataSize:{}", - limit, DateUtils.longToDateStr(range.getFrom()), DateUtils.longToDateStr(range.getTo()), DateUtils.longToDateStr(limitedScanResult.getLimitedTime()), traceIdList.size()); - } - - Range resultRange; - if (traceIdList.isEmpty()) { - resultRange = new Range(-1, -1); - } else { - resultRange = new Range(limitedScanResult.getLimitedTime(), range.getTo()); - } - return createModelAndView(resultRange, jsonpCallback, scatterData); - } - - private ModelAndView selectScatterData(String applicationName, Range range, int limit, String jsonpCallback) { - - final List scatterData = scatter.selectScatterData(applicationName, range, limit); - Range resultRange; - if (scatterData.isEmpty()) { - resultRange = new Range(-1, -1); - } else { - resultRange = new Range(scatterData.get(scatterData.size() - 1).getAcceptedTime(), range.getTo()); - } - return createModelAndView(resultRange, jsonpCallback, scatterData); - } - - private ModelAndView createModelAndView(Range range, String jsonpCallback, List scatterData) { - ModelAndView mv = new ModelAndView(); - mv.addObject("resultFrom", range.getFrom()); - mv.addObject("resultTo", range.getTo()); - mv.addObject("scatterIndex", ScatterIndex.MATA_DATA); - mv.addObject("scatter", scatterData); - if (jsonpCallback == null) { - mv.setViewName("jsonView"); - } else { - mv.setViewName("jsonpView"); - } - return mv; - } - - /** - * NOW 버튼을 눌렀을 때 scatter 데이터 조회. - * - * @param applicationName - * @param limit - * @return - */ - @RequestMapping(value = "/getLastScatterData", method = RequestMethod.GET) - public ModelAndView getLastScatterData( - @RequestParam("application") String applicationName, - @RequestParam("period") long period, - @RequestParam("limit") int limit, - @RequestParam(value = "filter", required = false) String filterText, - @RequestParam(value = "_callback", required = false) String jsonpCallback, - @RequestParam(value = "v", required = false, defaultValue = "1") int version) { - limit = LimitUtils.checkRange(limit); - - long to = TimeUtils.getDelayLastTime(); - long from = to - period; - // TODO version은 임시로 사용됨. template변경과 서버개발을 동시에 하려고.. - return getScatterData(applicationName, from, to, limit, filterText, jsonpCallback, version); - } - - /** - * scatter에서 점 여러개를 선택했을 때 점에 대한 정보를 조회한다. - * - * @param model - * @param request - * @param response - * @return - */ - @RequestMapping(value = "/transactionmetadata", method = RequestMethod.POST) - public String transactionmetadata(Model model, HttpServletRequest request, HttpServletResponse response) { - - TransactionMetadataQuery query = parseSelectTransaction(request); - if (query.size() > 0) { - List metadata = scatter.selectTransactionMetadata(query); - model.addAttribute("metadata", metadata); - } - - return "transactionmetadata"; - } - - private TransactionMetadataQuery parseSelectTransaction(HttpServletRequest request) { - final TransactionMetadataQuery query = new TransactionMetadataQuery(); - int index = 0; - while (true) { - final String traceId = request.getParameter(PREFIX_TRANSACTION_ID + index); - final String time = request.getParameter(PREFIX_TIME + index); - final String responseTime = request.getParameter(PREFIX_RESPONSE_TIME + index); - - if (traceId == null || time == null || responseTime == null) { - break; - } - - query.addQueryCondition(traceId, Long.parseLong(time), Integer.parseInt(responseTime)); - index++; - } - logger.debug("query:{}", query); - return query; - } - - /** - * scatter chart에서 선택한 범위에 속하는 트랜잭션 목록을 조회 - * - *
-     * TEST URL = http://localhost:7080/transactionmetadata2.pinpoint?application=FRONT-WEB&from=1394432299032&to=1394433498269&responseFrom=100&responseTo=200&responseOffset=100&limit=10
-     * 
- * - * @param model - * @param request - * @param response - * @return - */ - @RequestMapping(value = "/transactionmetadata2", method = RequestMethod.GET) - public String getTransaction(Model model, - @RequestParam("application") String applicationName, - @RequestParam("from") long from, - @RequestParam("to") long to, - @RequestParam("responseFrom") int responseFrom, - @RequestParam("responseTo") int responseTo, - @RequestParam("limit") int limit, - @RequestParam(value = "offsetTime", required = false, defaultValue = "-1") long offsetTime, - @RequestParam(value = "offsetTransactionId", required = false) String offsetTransactionId, - @RequestParam(value = "offsetTransactionElapsed", required = false, defaultValue = "-1") int offsetTransactionElapsed, - @RequestParam(value = "filter", required = false) String filterText) { - - limit = LimitUtils.checkRange(limit); - - StopWatch watch = new StopWatch(); - watch.start("selectScatterData"); - - final SelectedScatterArea area = SelectedScatterArea.createUncheckedArea(from, to, responseFrom, responseTo); - logger.debug("fetch scatter data. {}, LIMIT={}, FILTER={}", area, limit, filterText); - - if (filterText == null) { - // limit에 걸려서 조회되지 않은 부분 우선 조회 - TransactionId offsetId = null; - List extraMetadata = null; - if (offsetTransactionId != null) { - offsetId = new TransactionId(offsetTransactionId); - - SelectedScatterArea extraArea = SelectedScatterArea.createUncheckedArea(offsetTime, offsetTime, responseFrom, responseTo); - List extraAreaDotList = scatter.selectScatterData(applicationName, extraArea, offsetId, offsetTransactionElapsed, limit); - extraMetadata = scatter.selectTransactionMetadata(parseSelectTransaction(extraAreaDotList)); - model.addAttribute("extraMetadata", extraMetadata); - } - - // limit에 걸려서 조회되지 않은 부분 조회 결과가 limit에 미치지 못하면 나머지 영역 추가 조회 - if (extraMetadata == null || extraMetadata.size() < limit) { - int newlimit = limit - ((extraMetadata == null) ? 0 : extraMetadata.size()); - List selectedDotList = scatter.selectScatterData(applicationName, area, null, -1, newlimit); - List metadata = scatter.selectTransactionMetadata(parseSelectTransaction(selectedDotList)); - model.addAttribute("metadata", metadata); - } - } else { - final LimitedScanResult> limitedScanResult = flow.selectTraceIdsFromApplicationTraceIndex(applicationName, area, limit); - final List traceIdList = limitedScanResult.getScanData(); - logger.trace("submitted transactionId count={}", traceIdList.size()); - - // TODO sorted만 하는가? tree기반으로 레인지 체크하도록 하고 삭제하도록 하자. - SortedSet traceIdSet = new TreeSet(traceIdList); - logger.debug("unified traceIdSet size={}", traceIdSet.size()); - - List dots = scatter.selectScatterData(traceIdSet, applicationName, filterBuilder.build(filterText)); - System.out.println(dots); - } - - watch.stop(); - logger.info("Fetch scatterData time : {}ms", watch.getLastTaskTimeMillis()); - - return "transactionmetadata2"; - } - - private TransactionMetadataQuery parseSelectTransaction(List dotList) { - TransactionMetadataQuery query = new TransactionMetadataQuery(); - if (dotList == null) { - return query; - } - for (Dot dot : dotList) { - query.addQueryCondition(dot.getTransactionId(), dot.getAcceptedTime(), dot.getElapsedTime()); - } - logger.debug("query:{}", query); - return query; - } +package com.nhn.pinpoint.web.controller; + +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.nhn.pinpoint.common.util.DateUtils; +import com.nhn.pinpoint.web.service.FilteredMapService; +import com.nhn.pinpoint.web.util.LimitUtils; +import com.nhn.pinpoint.web.filter.Filter; +import com.nhn.pinpoint.web.filter.FilterBuilder; +import com.nhn.pinpoint.web.vo.*; +import com.nhn.pinpoint.web.vo.scatter.Dot; +import com.nhn.pinpoint.web.vo.scatter.ScatterIndex; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.util.StopWatch; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +import com.nhn.pinpoint.common.bo.SpanBo; +import com.nhn.pinpoint.web.service.ScatterChartService; +import com.nhn.pinpoint.web.util.TimeUtils; +import org.springframework.web.servlet.ModelAndView; + +/** + * + * @author netspider + * @author emeroad + */ +@Controller +public class ScatterChartController { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + private ScatterChartService scatter; + + @Autowired + private FilteredMapService flow; + + @Autowired + private FilterBuilder filterBuilder; + + private static final String PREFIX_TRANSACTION_ID = "I"; + private static final String PREFIX_TIME = "T"; + private static final String PREFIX_RESPONSE_TIME = "R"; + + @RequestMapping(value = "/scatterpopup", method = RequestMethod.GET) + public String scatterPopup(Model model, + @RequestParam("application") String applicationName, + @RequestParam("from") long from, + @RequestParam("to") long to, + @RequestParam("period") long period, + @RequestParam("usePeriod") boolean usePeriod, + @RequestParam(value = "filter", required = false) String filterText) { + model.addAttribute("applicationName", applicationName); + model.addAttribute("from", from); + model.addAttribute("to", to); + model.addAttribute("period", period); + model.addAttribute("usePeriod", usePeriod); + model.addAttribute("filter", filterText); + return "scatterPopup"; + } + + /** + * + * @param applicationName + * @param from + * @param to + * @param limit + * 한번에 조회 할 데이터의 크기, 조회 결과가 이 크기를 넘어가면 limit개만 반환한다. 나머지는 다시 요청해서 + * 조회해야 한다. + * @return + */ + @RequestMapping(value = "/getScatterData", method = RequestMethod.GET) + public ModelAndView getScatterData( + @RequestParam("application") String applicationName, + @RequestParam("from") long from, + @RequestParam("to") long to, + @RequestParam("limit") int limit, + @RequestParam(value = "filter", required = false) String filterText, + @RequestParam(value = "_callback", required = false) String jsonpCallback, + @RequestParam(value = "v", required = false, defaultValue = "2") int version) { + limit = LimitUtils.checkRange(limit); + + StopWatch watch = new StopWatch(); + watch.start("selectScatterData"); + + // TODO 레인지 체크 확인 exception 발생, from값이 to 보다 더 큼. + final Range range = Range.createUncheckedRange(from, to); + logger.debug("fetch scatter data. {}, LIMIT={}, FILTER={}", range, limit, filterText); + + ModelAndView mv; + if (filterText == null) { + mv = selectScatterData(applicationName, range, limit, jsonpCallback); + } else { + mv = selectFilterScatterDataData(applicationName, range, filterText, limit, jsonpCallback); + } + + watch.stop(); + + logger.info("Fetch scatterData time : {}ms", watch.getLastTaskTimeMillis()); + + return mv; + } + + private ModelAndView selectFilterScatterDataData(String applicationName, Range range, String filterText, int limit, String jsonpCallback) { + + final LimitedScanResult> limitedScanResult = flow.selectTraceIdsFromApplicationTraceIndex(applicationName, range, limit); + + final List traceIdList = limitedScanResult.getScanData(); + logger.trace("submitted transactionId count={}", traceIdList.size()); + // TODO sorted만 하는가? tree기반으로 레인지 체크하도록 하고 삭제하도록 하자. + SortedSet traceIdSet = new TreeSet(traceIdList); + logger.debug("unified traceIdSet size={}", traceIdSet.size()); + + Filter filter = filterBuilder.build(filterText); + List scatterData = scatter.selectScatterData(traceIdSet, applicationName, filter); + if (logger.isDebugEnabled()) { + logger.debug("getScatterData range scan(limited:{}) from ~ to:{} ~ {}, limited:{}, filterDataSize:{}", + limit, DateUtils.longToDateStr(range.getFrom()), DateUtils.longToDateStr(range.getTo()), DateUtils.longToDateStr(limitedScanResult.getLimitedTime()), traceIdList.size()); + } + + Range resultRange; + if (traceIdList.isEmpty()) { + resultRange = new Range(-1, -1); + } else { + resultRange = new Range(limitedScanResult.getLimitedTime(), range.getTo()); + } + return createModelAndView(resultRange, jsonpCallback, scatterData); + } + + private ModelAndView selectScatterData(String applicationName, Range range, int limit, String jsonpCallback) { + + final List scatterData = scatter.selectScatterData(applicationName, range, limit); + Range resultRange; + if (scatterData.isEmpty()) { + resultRange = new Range(-1, -1); + } else { + resultRange = new Range(scatterData.get(scatterData.size() - 1).getAcceptedTime(), range.getTo()); + } + return createModelAndView(resultRange, jsonpCallback, scatterData); + } + + private ModelAndView createModelAndView(Range range, String jsonpCallback, List scatterData) { + ModelAndView mv = new ModelAndView(); + mv.addObject("resultFrom", range.getFrom()); + mv.addObject("resultTo", range.getTo()); + mv.addObject("scatterIndex", ScatterIndex.MATA_DATA); + mv.addObject("scatter", scatterData); + if (jsonpCallback == null) { + mv.setViewName("jsonView"); + } else { + mv.setViewName("jsonpView"); + } + return mv; + } + + /** + * NOW 버튼을 눌렀을 때 scatter 데이터 조회. + * + * @param applicationName + * @param limit + * @return + */ + @RequestMapping(value = "/getLastScatterData", method = RequestMethod.GET) + public ModelAndView getLastScatterData( + @RequestParam("application") String applicationName, + @RequestParam("period") long period, + @RequestParam("limit") int limit, + @RequestParam(value = "filter", required = false) String filterText, + @RequestParam(value = "_callback", required = false) String jsonpCallback, + @RequestParam(value = "v", required = false, defaultValue = "1") int version) { + limit = LimitUtils.checkRange(limit); + + long to = TimeUtils.getDelayLastTime(); + long from = to - period; + // TODO version은 임시로 사용됨. template변경과 서버개발을 동시에 하려고.. + return getScatterData(applicationName, from, to, limit, filterText, jsonpCallback, version); + } + + /** + * scatter에서 점 여러개를 선택했을 때 점에 대한 정보를 조회한다. + * + * @param model + * @param request + * @param response + * @return + */ + @RequestMapping(value = "/transactionmetadata", method = RequestMethod.POST) + public String transactionmetadata(Model model, HttpServletRequest request, HttpServletResponse response) { + + TransactionMetadataQuery query = parseSelectTransaction(request); + if (query.size() > 0) { + List metadata = scatter.selectTransactionMetadata(query); + model.addAttribute("metadata", metadata); + } + + return "transactionmetadata"; + } + + private TransactionMetadataQuery parseSelectTransaction(HttpServletRequest request) { + final TransactionMetadataQuery query = new TransactionMetadataQuery(); + int index = 0; + while (true) { + final String traceId = request.getParameter(PREFIX_TRANSACTION_ID + index); + final String time = request.getParameter(PREFIX_TIME + index); + final String responseTime = request.getParameter(PREFIX_RESPONSE_TIME + index); + + if (traceId == null || time == null || responseTime == null) { + break; + } + + query.addQueryCondition(traceId, Long.parseLong(time), Integer.parseInt(responseTime)); + index++; + } + logger.debug("query:{}", query); + return query; + } + + /** + * scatter chart에서 선택한 범위에 속하는 트랜잭션 목록을 조회 + * + *
+     * TEST URL = http://localhost:7080/transactionmetadata2.pinpoint?application=FRONT-WEB&from=1394432299032&to=1394433498269&responseFrom=100&responseTo=200&responseOffset=100&limit=10
+     * 
+ * + * @param model + * @param request + * @param response + * @return + */ + @RequestMapping(value = "/transactionmetadata2", method = RequestMethod.GET) + public String getTransaction(Model model, + @RequestParam("application") String applicationName, + @RequestParam("from") long from, + @RequestParam("to") long to, + @RequestParam("responseFrom") int responseFrom, + @RequestParam("responseTo") int responseTo, + @RequestParam("limit") int limit, + @RequestParam(value = "offsetTime", required = false, defaultValue = "-1") long offsetTime, + @RequestParam(value = "offsetTransactionId", required = false) String offsetTransactionId, + @RequestParam(value = "offsetTransactionElapsed", required = false, defaultValue = "-1") int offsetTransactionElapsed, + @RequestParam(value = "filter", required = false) String filterText) { + + limit = LimitUtils.checkRange(limit); + + StopWatch watch = new StopWatch(); + watch.start("selectScatterData"); + + final SelectedScatterArea area = SelectedScatterArea.createUncheckedArea(from, to, responseFrom, responseTo); + logger.debug("fetch scatter data. {}, LIMIT={}, FILTER={}", area, limit, filterText); + + if (filterText == null) { + // limit에 걸려서 조회되지 않은 부분 우선 조회 + TransactionId offsetId = null; + List extraMetadata = null; + if (offsetTransactionId != null) { + offsetId = new TransactionId(offsetTransactionId); + + SelectedScatterArea extraArea = SelectedScatterArea.createUncheckedArea(offsetTime, offsetTime, responseFrom, responseTo); + List extraAreaDotList = scatter.selectScatterData(applicationName, extraArea, offsetId, offsetTransactionElapsed, limit); + extraMetadata = scatter.selectTransactionMetadata(parseSelectTransaction(extraAreaDotList)); + model.addAttribute("extraMetadata", extraMetadata); + } + + // limit에 걸려서 조회되지 않은 부분 조회 결과가 limit에 미치지 못하면 나머지 영역 추가 조회 + if (extraMetadata == null || extraMetadata.size() < limit) { + int newlimit = limit - ((extraMetadata == null) ? 0 : extraMetadata.size()); + List selectedDotList = scatter.selectScatterData(applicationName, area, null, -1, newlimit); + List metadata = scatter.selectTransactionMetadata(parseSelectTransaction(selectedDotList)); + model.addAttribute("metadata", metadata); + } + } else { + final LimitedScanResult> limitedScanResult = flow.selectTraceIdsFromApplicationTraceIndex(applicationName, area, limit); + final List traceIdList = limitedScanResult.getScanData(); + logger.trace("submitted transactionId count={}", traceIdList.size()); + + // TODO sorted만 하는가? tree기반으로 레인지 체크하도록 하고 삭제하도록 하자. + SortedSet traceIdSet = new TreeSet(traceIdList); + logger.debug("unified traceIdSet size={}", traceIdSet.size()); + + List dots = scatter.selectScatterData(traceIdSet, applicationName, filterBuilder.build(filterText)); + } + + watch.stop(); + logger.info("Fetch scatterData time : {}ms", watch.getLastTaskTimeMillis()); + + return "transactionmetadata2"; + } + + private TransactionMetadataQuery parseSelectTransaction(List dotList) { + TransactionMetadataQuery query = new TransactionMetadataQuery(); + if (dotList == null) { + return query; + } + for (Dot dot : dotList) { + query.addQueryCondition(dot.getTransactionId(), dot.getAcceptedTime(), dot.getElapsedTime()); + } + logger.debug("query:{}", query); + return query; + } } \ No newline at end of file diff --git a/web/src/main/java/com/navercorp/pinpoint/web/server/PinpointSocketManager.java b/web/src/main/java/com/navercorp/pinpoint/web/server/PinpointSocketManager.java index f820d41e78ce..0fab39390412 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/server/PinpointSocketManager.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/server/PinpointSocketManager.java @@ -76,6 +76,7 @@ public void start() throws KeeperException, IOException, InterruptedException { this.clusterManager = new ZookeeperClusterManager(config.getClusterZookeeperAddress(), config.getClusterZookeeperSessionTimeout(), config.getClusterZookeeperRetryInterval()); + // TODO 여기서 수정이 필요함 // json list는 표준규칙이 아니기 때문에 ip\r\n으로 저장 this.clusterManager.registerWebCluster(nodeName, convertIpListToBytes(localIpList, "\r\n")); } From f3a92ee327fdc9db34eecfd6fd98edafe102a963 Mon Sep 17 00:00:00 2001 From: koo-taejin Date: Tue, 16 Sep 2014 14:06:02 +0900 Subject: [PATCH 04/18] =?UTF-8?q?#12=20thrift=20command=20=EA=B0=9D?= =?UTF-8?q?=EC=B2=B4=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. version 등록 (1.0.3-SNAPSHOT) 2. command 기능 등록 echo (echo) commandTransfer (단순 req/res 방식 형태의 command message를 전달하는 기능) (stream은 이후 추가 예정) --- .../profiler/receiver/CommandDispatcher.java | 251 ++++++------ .../pinpoint/profiler/receiver/bo/EchoBO.java | 24 ++ .../thrift/dto/command/TCommandEcho.java | 385 ++++++++++++++++++ .../pinpoint/thrift/io/TCommandType.java | 14 + .../thrift/io/TCommandTypeVersion.java | 19 + thrift/src/main/thrift/Command.thrift | 31 +- 6 files changed, 589 insertions(+), 135 deletions(-) create mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/bo/EchoBO.java create mode 100644 thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/command/TCommandEcho.java diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/CommandDispatcher.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/CommandDispatcher.java index d6dece3e7e7b..32f7d4804447 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/CommandDispatcher.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/CommandDispatcher.java @@ -1,124 +1,127 @@ -package com.nhn.pinpoint.profiler.receiver; - -import org.apache.thrift.TBase; -import org.apache.thrift.TException; -import org.apache.thrift.protocol.TCompactProtocol; -import org.apache.thrift.protocol.TProtocolFactory; -import org.jboss.netty.channel.Channel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.nhn.pinpoint.common.Version; -import com.nhn.pinpoint.profiler.receiver.bo.ThreadDumpBO; -import com.nhn.pinpoint.rpc.client.MessageListener; -import com.nhn.pinpoint.rpc.packet.RequestPacket; -import com.nhn.pinpoint.rpc.packet.ResponsePacket; -import com.nhn.pinpoint.rpc.packet.SendPacket; -import com.nhn.pinpoint.thrift.dto.TResult; -import com.nhn.pinpoint.thrift.dto.command.TCommandThreadDump; -import com.nhn.pinpoint.thrift.io.HeaderTBaseDeserializer; -import com.nhn.pinpoint.thrift.io.HeaderTBaseDeserializerFactory; -import com.nhn.pinpoint.thrift.io.HeaderTBaseSerializer; -import com.nhn.pinpoint.thrift.io.HeaderTBaseSerializerFactory; -import com.nhn.pinpoint.thrift.io.SerializerFactory; -import com.nhn.pinpoint.thrift.io.TBaseLocator; -import com.nhn.pinpoint.thrift.io.TCommandRegistry; -import com.nhn.pinpoint.thrift.io.TCommandTypeVersion; - -/** - * @author koo.taejin - */ -public class CommandDispatcher implements MessageListener { - - // 일단은 현재 스레드가 워커스레드로 되는 것을 등록 (이후에 변경하자.) - - private static final TProtocolFactory DEFAULT_PROTOCOL_FACTORY = new TCompactProtocol.Factory(); - private static final TBaseLocator commandTbaseLocator = new TCommandRegistry(TCommandTypeVersion.getVersion(Version.VERSION)); - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - // 여기만 따로 TBaseLocator를 상속받아 만들어주는 것이 좋을듯 - - private final TBaseBOLocator locator; - - private final SerializerFactory serializerFactory = new HeaderTBaseSerializerFactory(true, HeaderTBaseSerializerFactory.DEFAULT_UDP_STREAM_MAX_SIZE, DEFAULT_PROTOCOL_FACTORY, commandTbaseLocator); - private final HeaderTBaseDeserializerFactory deserializerFactory = new HeaderTBaseDeserializerFactory(DEFAULT_PROTOCOL_FACTORY, commandTbaseLocator); - - public CommandDispatcher() { - TBaseBORegistry registry = new TBaseBORegistry(); - registry.addBO(TCommandThreadDump.class, new ThreadDumpBO()); - - this.locator = registry; - } - - @Override - public void handleRequest(RequestPacket packet, Channel channel) { - logger.info("MessageReceive {} {}", packet, channel); - - TBase request = deserialize(packet.getPayload()); - - TBase response = null; - if (request == null) { - TResult tResult = new TResult(false); - tResult.setMessage("Unsupported Type."); - - response = tResult; - } else { - TBaseRequestBO bo = locator.getRequestBO(request); - - if (bo == null) { - TResult tResult = new TResult(false); - tResult.setMessage("Unsupported Listener."); - - response = tResult; - } else { - response = bo.handleRequest(request); - } - } - - byte[] payload = serialize(response); - if (payload != null) { - channel.write(new ResponsePacket(packet.getRequestId(), payload)); - } - } - - @Override - public void handleSend(SendPacket packet, Channel channel) { - logger.info("MessageReceive {} {}", packet, channel); - } - - private TBase deserialize(byte[] payload) { - if (payload == null) { - logger.warn("Payload may not be null."); - return null; - } - - try { - final HeaderTBaseDeserializer deserializer = deserializerFactory.createDeserializer(); - TBase tBase = deserializer.deserialize(payload); - return tBase; - } catch (TException e) { - logger.warn(e.getMessage(), e); - } - - return null; - } - - private byte[] serialize(TBase result) { - if (result == null) { - logger.warn("tBase may not be null."); - return null; - } - - try { - HeaderTBaseSerializer serializer = serializerFactory.createSerializer(); - byte[] payload = serializer.serialize(result); - return payload; - } catch (TException e) { - logger.warn(e.getMessage(), e); - } - - return null; - } - -} +package com.nhn.pinpoint.profiler.receiver; + +import org.apache.thrift.TBase; +import org.apache.thrift.TException; +import org.apache.thrift.protocol.TCompactProtocol; +import org.apache.thrift.protocol.TProtocolFactory; +import org.jboss.netty.channel.Channel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nhn.pinpoint.common.Version; +import com.nhn.pinpoint.profiler.receiver.bo.EchoBO; +import com.nhn.pinpoint.profiler.receiver.bo.ThreadDumpBO; +import com.nhn.pinpoint.rpc.client.MessageListener; +import com.nhn.pinpoint.rpc.packet.RequestPacket; +import com.nhn.pinpoint.rpc.packet.ResponsePacket; +import com.nhn.pinpoint.rpc.packet.SendPacket; +import com.nhn.pinpoint.thrift.dto.TResult; +import com.nhn.pinpoint.thrift.dto.command.TCommandEcho; +import com.nhn.pinpoint.thrift.dto.command.TCommandThreadDump; +import com.nhn.pinpoint.thrift.io.HeaderTBaseDeserializer; +import com.nhn.pinpoint.thrift.io.HeaderTBaseDeserializerFactory; +import com.nhn.pinpoint.thrift.io.HeaderTBaseSerializer; +import com.nhn.pinpoint.thrift.io.HeaderTBaseSerializerFactory; +import com.nhn.pinpoint.thrift.io.SerializerFactory; +import com.nhn.pinpoint.thrift.io.TBaseLocator; +import com.nhn.pinpoint.thrift.io.TCommandRegistry; +import com.nhn.pinpoint.thrift.io.TCommandTypeVersion; + +/** + * @author koo.taejin + */ +public class CommandDispatcher implements MessageListener { + + // 일단은 현재 스레드가 워커스레드로 되는 것을 등록 (이후에 변경하자.) + + private static final TProtocolFactory DEFAULT_PROTOCOL_FACTORY = new TCompactProtocol.Factory(); + private static final TBaseLocator commandTbaseLocator = new TCommandRegistry(TCommandTypeVersion.getVersion(Version.VERSION)); + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + // 여기만 따로 TBaseLocator를 상속받아 만들어주는 것이 좋을듯 + + private final TBaseBOLocator locator; + + private final SerializerFactory serializerFactory = new HeaderTBaseSerializerFactory(true, HeaderTBaseSerializerFactory.DEFAULT_UDP_STREAM_MAX_SIZE, DEFAULT_PROTOCOL_FACTORY, commandTbaseLocator); + private final HeaderTBaseDeserializerFactory deserializerFactory = new HeaderTBaseDeserializerFactory(DEFAULT_PROTOCOL_FACTORY, commandTbaseLocator); + + public CommandDispatcher() { + TBaseBORegistry registry = new TBaseBORegistry(); + registry.addBO(TCommandThreadDump.class, new ThreadDumpBO()); + registry.addBO(TCommandEcho.class, new EchoBO()); + + this.locator = registry; + } + + @Override + public void handleRequest(RequestPacket packet, Channel channel) { + logger.info("MessageReceive {} {}", packet, channel); + + TBase request = deserialize(packet.getPayload()); + + TBase response = null; + if (request == null) { + TResult tResult = new TResult(false); + tResult.setMessage("Unsupported Type."); + + response = tResult; + } else { + TBaseRequestBO bo = locator.getRequestBO(request); + + if (bo == null) { + TResult tResult = new TResult(false); + tResult.setMessage("Unsupported Listener."); + + response = tResult; + } else { + response = bo.handleRequest(request); + } + } + + byte[] payload = serialize(response); + if (payload != null) { + channel.write(new ResponsePacket(packet.getRequestId(), payload)); + } + } + + @Override + public void handleSend(SendPacket packet, Channel channel) { + logger.info("MessageReceive {} {}", packet, channel); + } + + private TBase deserialize(byte[] payload) { + if (payload == null) { + logger.warn("Payload may not be null."); + return null; + } + + try { + final HeaderTBaseDeserializer deserializer = deserializerFactory.createDeserializer(); + TBase tBase = deserializer.deserialize(payload); + return tBase; + } catch (TException e) { + logger.warn(e.getMessage(), e); + } + + return null; + } + + private byte[] serialize(TBase result) { + if (result == null) { + logger.warn("tBase may not be null."); + return null; + } + + try { + HeaderTBaseSerializer serializer = serializerFactory.createSerializer(); + byte[] payload = serializer.serialize(result); + return payload; + } catch (TException e) { + logger.warn(e.getMessage(), e); + } + + return null; + } + +} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/bo/EchoBO.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/bo/EchoBO.java new file mode 100644 index 000000000000..ce2e95948cc8 --- /dev/null +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/bo/EchoBO.java @@ -0,0 +1,24 @@ +package com.nhn.pinpoint.profiler.receiver.bo; + +import org.apache.thrift.TBase; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nhn.pinpoint.profiler.receiver.TBaseRequestBO; +import com.nhn.pinpoint.thrift.dto.command.TCommandEcho; + +/** + * @author koo.taejin + */ +public class EchoBO implements TBaseRequestBO { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Override + public TBase handleRequest(TBase tbase) { + logger.info("{} execute {}.", this, tbase); + + TCommandEcho param = (TCommandEcho) tbase; + return param; + } + +} diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/command/TCommandEcho.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/command/TCommandEcho.java new file mode 100644 index 000000000000..406c516ce9c1 --- /dev/null +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/command/TCommandEcho.java @@ -0,0 +1,385 @@ +/** + * Autogenerated by Thrift Compiler (0.9.1) + * + * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING + * @generated + */ +package com.nhn.pinpoint.thrift.dto.command; + +import org.apache.thrift.scheme.IScheme; +import org.apache.thrift.scheme.SchemeFactory; +import org.apache.thrift.scheme.StandardScheme; + +import org.apache.thrift.scheme.TupleScheme; +import org.apache.thrift.protocol.TTupleProtocol; +import org.apache.thrift.protocol.TProtocolException; +import org.apache.thrift.EncodingUtils; +import org.apache.thrift.TException; +import org.apache.thrift.async.AsyncMethodCallback; +import org.apache.thrift.server.AbstractNonblockingServer.*; +import java.util.List; +import java.util.ArrayList; +import java.util.Map; +import java.util.HashMap; +import java.util.EnumMap; +import java.util.Set; +import java.util.HashSet; +import java.util.EnumSet; +import java.util.Collections; +import java.util.BitSet; +import java.nio.ByteBuffer; +import java.util.Arrays; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TCommandEcho implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TCommandEcho"); + + private static final org.apache.thrift.protocol.TField MESSAGE_FIELD_DESC = new org.apache.thrift.protocol.TField("message", org.apache.thrift.protocol.TType.STRING, (short)1); + + private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); + static { + schemes.put(StandardScheme.class, new TCommandEchoStandardSchemeFactory()); + schemes.put(TupleScheme.class, new TCommandEchoTupleSchemeFactory()); + } + + private String message; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + MESSAGE((short)1, "message"); + + private static final Map byName = new HashMap(); + + static { + for (_Fields field : EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // MESSAGE + return MESSAGE; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.MESSAGE, new org.apache.thrift.meta_data.FieldMetaData("message", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + metaDataMap = Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TCommandEcho.class, metaDataMap); + } + + public TCommandEcho() { + } + + public TCommandEcho( + String message) + { + this(); + this.message = message; + } + + /** + * Performs a deep copy on other. + */ + public TCommandEcho(TCommandEcho other) { + if (other.isSetMessage()) { + this.message = other.message; + } + } + + public TCommandEcho deepCopy() { + return new TCommandEcho(this); + } + + @Override + public void clear() { + this.message = null; + } + + public String getMessage() { + return this.message; + } + + public void setMessage(String message) { + this.message = message; + } + + public void unsetMessage() { + this.message = null; + } + + /** Returns true if field message is set (has been assigned a value) and false otherwise */ + public boolean isSetMessage() { + return this.message != null; + } + + public void setMessageIsSet(boolean value) { + if (!value) { + this.message = null; + } + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case MESSAGE: + if (value == null) { + unsetMessage(); + } else { + setMessage((String)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case MESSAGE: + return getMessage(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case MESSAGE: + return isSetMessage(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof TCommandEcho) + return this.equals((TCommandEcho)that); + return false; + } + + public boolean equals(TCommandEcho that) { + if (that == null) + return false; + + boolean this_present_message = true && this.isSetMessage(); + boolean that_present_message = true && that.isSetMessage(); + if (this_present_message || that_present_message) { + if (!(this_present_message && that_present_message)) + return false; + if (!this.message.equals(that.message)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + return 0; + } + + @Override + public int compareTo(TCommandEcho other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetMessage()).compareTo(other.isSetMessage()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetMessage()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.message, other.message); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + schemes.get(iprot.getScheme()).getScheme().read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + schemes.get(oprot.getScheme()).getScheme().write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("TCommandEcho("); + boolean first = true; + + sb.append("message:"); + if (this.message == null) { + sb.append("null"); + } else { + sb.append(this.message); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class TCommandEchoStandardSchemeFactory implements SchemeFactory { + public TCommandEchoStandardScheme getScheme() { + return new TCommandEchoStandardScheme(); + } + } + + private static class TCommandEchoStandardScheme extends StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, TCommandEcho struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // MESSAGE + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.message = iprot.readString(); + struct.setMessageIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, TCommandEcho struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.message != null) { + oprot.writeFieldBegin(MESSAGE_FIELD_DESC); + oprot.writeString(struct.message); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class TCommandEchoTupleSchemeFactory implements SchemeFactory { + public TCommandEchoTupleScheme getScheme() { + return new TCommandEchoTupleScheme(); + } + } + + private static class TCommandEchoTupleScheme extends TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, TCommandEcho struct) throws org.apache.thrift.TException { + TTupleProtocol oprot = (TTupleProtocol) prot; + BitSet optionals = new BitSet(); + if (struct.isSetMessage()) { + optionals.set(0); + } + oprot.writeBitSet(optionals, 1); + if (struct.isSetMessage()) { + oprot.writeString(struct.message); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, TCommandEcho struct) throws org.apache.thrift.TException { + TTupleProtocol iprot = (TTupleProtocol) prot; + BitSet incoming = iprot.readBitSet(1); + if (incoming.get(0)) { + struct.message = iprot.readString(); + struct.setMessageIsSet(true); + } + } + } + +} + diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandType.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandType.java index f55dc651319d..cc8fb950bae0 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandType.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandType.java @@ -3,7 +3,9 @@ import org.apache.thrift.TBase; import com.nhn.pinpoint.thrift.dto.TResult; +import com.nhn.pinpoint.thrift.dto.command.TCommandEcho; import com.nhn.pinpoint.thrift.dto.command.TCommandThreadDump; +import com.nhn.pinpoint.thrift.dto.command.TCommandTransfer; /** * @author koo.taejin @@ -19,6 +21,18 @@ public TBase newObject() { return new TResult(); } }, + TRANSFER((short) 700, TCommandTransfer.class) { + @Override + public TBase newObject() { + return new TCommandTransfer(); + } + }, + ECHO((short) 710, TCommandEcho.class) { + @Override + public TBase newObject() { + return new TCommandEcho(); + } + }, THREAD_DUMP((short) 720, TCommandThreadDump.class) { @Override public TBase newObject() { diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java index 3ab1f481ee94..00b1f0f358e2 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java @@ -3,6 +3,8 @@ import java.util.ArrayList; import java.util.List; +import org.apache.thrift.TBase; + /** * @author koo.taejin */ @@ -10,6 +12,9 @@ public enum TCommandTypeVersion { // Agent 버젼과 맞추면 좋을듯 일단은 Agent 버전과 맞춰놓음 V_1_0_2_SNAPSHOT("1.0.2-SNAPSHOT", TCommandType.RESULT, TCommandType.THREAD_DUMP), + V_1_0_2("1.0.2", V_1_0_2_SNAPSHOT), + V_1_0_3_SNAPSHOT("1.0.3-SNAPSHOT", V_1_0_2, TCommandType.ECHO, TCommandType.TRANSFER), + UNKNOWN("UNKNOWN"); private final String versionName; @@ -38,6 +43,20 @@ private TCommandTypeVersion(String versionName, TCommandType... supportCommandAr public List getSupportCommandList() { return supportCommandList; } + + public boolean isSupportCommand(TBase command) { + if (command == null) { + return false; + } + + for (TCommandType eachCommand : supportCommandList) { + if (command.getClass().isInstance(eachCommand)) { + return true; + } + } + + return false; + } public String getVersionName() { return versionName; diff --git a/thrift/src/main/thrift/Command.thrift b/thrift/src/main/thrift/Command.thrift index 86c4f2b243a6..f1ecd4ba4d6f 100644 --- a/thrift/src/main/thrift/Command.thrift +++ b/thrift/src/main/thrift/Command.thrift @@ -1,11 +1,20 @@ -namespace java com.nhn.pinpoint.thrift.dto.command - -enum TThreadDumpType { - TARGET, - PENDING -} -struct TCommandThreadDump { - 1: TThreadDumpType type = TThreadDumpType.TARGET - 2: optional string name - 3: optional i64 pendingTimeMillis -} +namespace java com.nhn.pinpoint.thrift.dto.command + +enum TThreadDumpType { + TARGET, + PENDING +} +struct TCommandThreadDump { + 1: TThreadDumpType type = TThreadDumpType.TARGET + 2: optional string name + 3: optional i64 pendingTimeMillis +} +struct TCommandEcho { + 1: string message +} +struct TCommandTransfer { + 1: string applicationName + 2: string agentId + 3: optional i64 startTime + 4: binary payload +} From d8f48c988046ecf2f075d82f3045397adab68224 Mon Sep 17 00:00:00 2001 From: koo-taejin Date: Tue, 16 Sep 2014 18:17:39 +0900 Subject: [PATCH 05/18] =?UTF-8?q?#12=20thrift=20command=20=EA=B0=9D?= =?UTF-8?q?=EC=B2=B4=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. version 등록 (1.0.3-SNAPSHOT) 2. command 기능 등록 echo (echo) commandTransfer (단순 req/res 방식 형태의 command message를 전달하는 기능) (stream은 이후 추가 예정) --- .../thrift/dto/command/TCommandTransfer.java | 692 ++++++++++++++++++ 1 file changed, 692 insertions(+) create mode 100644 thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/command/TCommandTransfer.java diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/command/TCommandTransfer.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/command/TCommandTransfer.java new file mode 100644 index 000000000000..6221e9c06630 --- /dev/null +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/command/TCommandTransfer.java @@ -0,0 +1,692 @@ +/** + * Autogenerated by Thrift Compiler (0.9.1) + * + * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING + * @generated + */ +package com.nhn.pinpoint.thrift.dto.command; + +import org.apache.thrift.scheme.IScheme; +import org.apache.thrift.scheme.SchemeFactory; +import org.apache.thrift.scheme.StandardScheme; + +import org.apache.thrift.scheme.TupleScheme; +import org.apache.thrift.protocol.TTupleProtocol; +import org.apache.thrift.protocol.TProtocolException; +import org.apache.thrift.EncodingUtils; +import org.apache.thrift.TException; +import org.apache.thrift.async.AsyncMethodCallback; +import org.apache.thrift.server.AbstractNonblockingServer.*; +import java.util.List; +import java.util.ArrayList; +import java.util.Map; +import java.util.HashMap; +import java.util.EnumMap; +import java.util.Set; +import java.util.HashSet; +import java.util.EnumSet; +import java.util.Collections; +import java.util.BitSet; +import java.nio.ByteBuffer; +import java.util.Arrays; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TCommandTransfer implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TCommandTransfer"); + + private static final org.apache.thrift.protocol.TField APPLICATION_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("applicationName", org.apache.thrift.protocol.TType.STRING, (short)1); + private static final org.apache.thrift.protocol.TField AGENT_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("agentId", org.apache.thrift.protocol.TType.STRING, (short)2); + private static final org.apache.thrift.protocol.TField START_TIME_FIELD_DESC = new org.apache.thrift.protocol.TField("startTime", org.apache.thrift.protocol.TType.I64, (short)3); + private static final org.apache.thrift.protocol.TField PAYLOAD_FIELD_DESC = new org.apache.thrift.protocol.TField("payload", org.apache.thrift.protocol.TType.STRING, (short)4); + + private static final Map, SchemeFactory> schemes = new HashMap, SchemeFactory>(); + static { + schemes.put(StandardScheme.class, new TCommandTransferStandardSchemeFactory()); + schemes.put(TupleScheme.class, new TCommandTransferTupleSchemeFactory()); + } + + private String applicationName; // required + private String agentId; // required + private long startTime; // optional + private ByteBuffer payload; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + APPLICATION_NAME((short)1, "applicationName"), + AGENT_ID((short)2, "agentId"), + START_TIME((short)3, "startTime"), + PAYLOAD((short)4, "payload"); + + private static final Map byName = new HashMap(); + + static { + for (_Fields field : EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // APPLICATION_NAME + return APPLICATION_NAME; + case 2: // AGENT_ID + return AGENT_ID; + case 3: // START_TIME + return START_TIME; + case 4: // PAYLOAD + return PAYLOAD; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + private static final int __STARTTIME_ISSET_ID = 0; + private byte __isset_bitfield = 0; + private _Fields optionals[] = {_Fields.START_TIME}; + public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.APPLICATION_NAME, new org.apache.thrift.meta_data.FieldMetaData("applicationName", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + tmpMap.put(_Fields.AGENT_ID, new org.apache.thrift.meta_data.FieldMetaData("agentId", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + tmpMap.put(_Fields.START_TIME, new org.apache.thrift.meta_data.FieldMetaData("startTime", org.apache.thrift.TFieldRequirementType.OPTIONAL, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); + tmpMap.put(_Fields.PAYLOAD, new org.apache.thrift.meta_data.FieldMetaData("payload", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); + metaDataMap = Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TCommandTransfer.class, metaDataMap); + } + + public TCommandTransfer() { + } + + public TCommandTransfer( + String applicationName, + String agentId, + ByteBuffer payload) + { + this(); + this.applicationName = applicationName; + this.agentId = agentId; + this.payload = payload; + } + + /** + * Performs a deep copy on other. + */ + public TCommandTransfer(TCommandTransfer other) { + __isset_bitfield = other.__isset_bitfield; + if (other.isSetApplicationName()) { + this.applicationName = other.applicationName; + } + if (other.isSetAgentId()) { + this.agentId = other.agentId; + } + this.startTime = other.startTime; + if (other.isSetPayload()) { + this.payload = org.apache.thrift.TBaseHelper.copyBinary(other.payload); +; + } + } + + public TCommandTransfer deepCopy() { + return new TCommandTransfer(this); + } + + @Override + public void clear() { + this.applicationName = null; + this.agentId = null; + setStartTimeIsSet(false); + this.startTime = 0; + this.payload = null; + } + + public String getApplicationName() { + return this.applicationName; + } + + public void setApplicationName(String applicationName) { + this.applicationName = applicationName; + } + + public void unsetApplicationName() { + this.applicationName = null; + } + + /** Returns true if field applicationName is set (has been assigned a value) and false otherwise */ + public boolean isSetApplicationName() { + return this.applicationName != null; + } + + public void setApplicationNameIsSet(boolean value) { + if (!value) { + this.applicationName = null; + } + } + + public String getAgentId() { + return this.agentId; + } + + public void setAgentId(String agentId) { + this.agentId = agentId; + } + + public void unsetAgentId() { + this.agentId = null; + } + + /** Returns true if field agentId is set (has been assigned a value) and false otherwise */ + public boolean isSetAgentId() { + return this.agentId != null; + } + + public void setAgentIdIsSet(boolean value) { + if (!value) { + this.agentId = null; + } + } + + public long getStartTime() { + return this.startTime; + } + + public void setStartTime(long startTime) { + this.startTime = startTime; + setStartTimeIsSet(true); + } + + public void unsetStartTime() { + __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __STARTTIME_ISSET_ID); + } + + /** Returns true if field startTime is set (has been assigned a value) and false otherwise */ + public boolean isSetStartTime() { + return EncodingUtils.testBit(__isset_bitfield, __STARTTIME_ISSET_ID); + } + + public void setStartTimeIsSet(boolean value) { + __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __STARTTIME_ISSET_ID, value); + } + + public byte[] getPayload() { + setPayload(org.apache.thrift.TBaseHelper.rightSize(payload)); + return payload == null ? null : payload.array(); + } + + public ByteBuffer bufferForPayload() { + return payload; + } + + public void setPayload(byte[] payload) { + setPayload(payload == null ? (ByteBuffer)null : ByteBuffer.wrap(payload)); + } + + public void setPayload(ByteBuffer payload) { + this.payload = payload; + } + + public void unsetPayload() { + this.payload = null; + } + + /** Returns true if field payload is set (has been assigned a value) and false otherwise */ + public boolean isSetPayload() { + return this.payload != null; + } + + public void setPayloadIsSet(boolean value) { + if (!value) { + this.payload = null; + } + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case APPLICATION_NAME: + if (value == null) { + unsetApplicationName(); + } else { + setApplicationName((String)value); + } + break; + + case AGENT_ID: + if (value == null) { + unsetAgentId(); + } else { + setAgentId((String)value); + } + break; + + case START_TIME: + if (value == null) { + unsetStartTime(); + } else { + setStartTime((Long)value); + } + break; + + case PAYLOAD: + if (value == null) { + unsetPayload(); + } else { + setPayload((ByteBuffer)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case APPLICATION_NAME: + return getApplicationName(); + + case AGENT_ID: + return getAgentId(); + + case START_TIME: + return Long.valueOf(getStartTime()); + + case PAYLOAD: + return getPayload(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case APPLICATION_NAME: + return isSetApplicationName(); + case AGENT_ID: + return isSetAgentId(); + case START_TIME: + return isSetStartTime(); + case PAYLOAD: + return isSetPayload(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof TCommandTransfer) + return this.equals((TCommandTransfer)that); + return false; + } + + public boolean equals(TCommandTransfer that) { + if (that == null) + return false; + + boolean this_present_applicationName = true && this.isSetApplicationName(); + boolean that_present_applicationName = true && that.isSetApplicationName(); + if (this_present_applicationName || that_present_applicationName) { + if (!(this_present_applicationName && that_present_applicationName)) + return false; + if (!this.applicationName.equals(that.applicationName)) + return false; + } + + boolean this_present_agentId = true && this.isSetAgentId(); + boolean that_present_agentId = true && that.isSetAgentId(); + if (this_present_agentId || that_present_agentId) { + if (!(this_present_agentId && that_present_agentId)) + return false; + if (!this.agentId.equals(that.agentId)) + return false; + } + + boolean this_present_startTime = true && this.isSetStartTime(); + boolean that_present_startTime = true && that.isSetStartTime(); + if (this_present_startTime || that_present_startTime) { + if (!(this_present_startTime && that_present_startTime)) + return false; + if (this.startTime != that.startTime) + return false; + } + + boolean this_present_payload = true && this.isSetPayload(); + boolean that_present_payload = true && that.isSetPayload(); + if (this_present_payload || that_present_payload) { + if (!(this_present_payload && that_present_payload)) + return false; + if (!this.payload.equals(that.payload)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + return 0; + } + + @Override + public int compareTo(TCommandTransfer other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetApplicationName()).compareTo(other.isSetApplicationName()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetApplicationName()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.applicationName, other.applicationName); + if (lastComparison != 0) { + return lastComparison; + } + } + lastComparison = Boolean.valueOf(isSetAgentId()).compareTo(other.isSetAgentId()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetAgentId()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.agentId, other.agentId); + if (lastComparison != 0) { + return lastComparison; + } + } + lastComparison = Boolean.valueOf(isSetStartTime()).compareTo(other.isSetStartTime()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetStartTime()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.startTime, other.startTime); + if (lastComparison != 0) { + return lastComparison; + } + } + lastComparison = Boolean.valueOf(isSetPayload()).compareTo(other.isSetPayload()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetPayload()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.payload, other.payload); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + schemes.get(iprot.getScheme()).getScheme().read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + schemes.get(oprot.getScheme()).getScheme().write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("TCommandTransfer("); + boolean first = true; + + sb.append("applicationName:"); + if (this.applicationName == null) { + sb.append("null"); + } else { + sb.append(this.applicationName); + } + first = false; + if (!first) sb.append(", "); + sb.append("agentId:"); + if (this.agentId == null) { + sb.append("null"); + } else { + sb.append(this.agentId); + } + first = false; + if (isSetStartTime()) { + if (!first) sb.append(", "); + sb.append("startTime:"); + sb.append(this.startTime); + first = false; + } + if (!first) sb.append(", "); + sb.append("payload:"); + if (this.payload == null) { + sb.append("null"); + } else { + org.apache.thrift.TBaseHelper.toString(this.payload, sb); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. + __isset_bitfield = 0; + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class TCommandTransferStandardSchemeFactory implements SchemeFactory { + public TCommandTransferStandardScheme getScheme() { + return new TCommandTransferStandardScheme(); + } + } + + private static class TCommandTransferStandardScheme extends StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, TCommandTransfer struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // APPLICATION_NAME + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.applicationName = iprot.readString(); + struct.setApplicationNameIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + case 2: // AGENT_ID + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.agentId = iprot.readString(); + struct.setAgentIdIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + case 3: // START_TIME + if (schemeField.type == org.apache.thrift.protocol.TType.I64) { + struct.startTime = iprot.readI64(); + struct.setStartTimeIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + case 4: // PAYLOAD + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.payload = iprot.readBinary(); + struct.setPayloadIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, TCommandTransfer struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.applicationName != null) { + oprot.writeFieldBegin(APPLICATION_NAME_FIELD_DESC); + oprot.writeString(struct.applicationName); + oprot.writeFieldEnd(); + } + if (struct.agentId != null) { + oprot.writeFieldBegin(AGENT_ID_FIELD_DESC); + oprot.writeString(struct.agentId); + oprot.writeFieldEnd(); + } + if (struct.isSetStartTime()) { + oprot.writeFieldBegin(START_TIME_FIELD_DESC); + oprot.writeI64(struct.startTime); + oprot.writeFieldEnd(); + } + if (struct.payload != null) { + oprot.writeFieldBegin(PAYLOAD_FIELD_DESC); + oprot.writeBinary(struct.payload); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class TCommandTransferTupleSchemeFactory implements SchemeFactory { + public TCommandTransferTupleScheme getScheme() { + return new TCommandTransferTupleScheme(); + } + } + + private static class TCommandTransferTupleScheme extends TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, TCommandTransfer struct) throws org.apache.thrift.TException { + TTupleProtocol oprot = (TTupleProtocol) prot; + BitSet optionals = new BitSet(); + if (struct.isSetApplicationName()) { + optionals.set(0); + } + if (struct.isSetAgentId()) { + optionals.set(1); + } + if (struct.isSetStartTime()) { + optionals.set(2); + } + if (struct.isSetPayload()) { + optionals.set(3); + } + oprot.writeBitSet(optionals, 4); + if (struct.isSetApplicationName()) { + oprot.writeString(struct.applicationName); + } + if (struct.isSetAgentId()) { + oprot.writeString(struct.agentId); + } + if (struct.isSetStartTime()) { + oprot.writeI64(struct.startTime); + } + if (struct.isSetPayload()) { + oprot.writeBinary(struct.payload); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, TCommandTransfer struct) throws org.apache.thrift.TException { + TTupleProtocol iprot = (TTupleProtocol) prot; + BitSet incoming = iprot.readBitSet(4); + if (incoming.get(0)) { + struct.applicationName = iprot.readString(); + struct.setApplicationNameIsSet(true); + } + if (incoming.get(1)) { + struct.agentId = iprot.readString(); + struct.setAgentIdIsSet(true); + } + if (incoming.get(2)) { + struct.startTime = iprot.readI64(); + struct.setStartTimeIsSet(true); + } + if (incoming.get(3)) { + struct.payload = iprot.readBinary(); + struct.setPayloadIsSet(true); + } + } + } + +} + From bcd849d36aafad1cfb22e35332155c143c394f61 Mon Sep 17 00:00:00 2001 From: koo-taejin Date: Tue, 16 Sep 2014 19:41:11 +0900 Subject: [PATCH 06/18] =?UTF-8?q?#5=20Pinpoint=20=ED=81=B4=EB=9F=AC?= =?UTF-8?q?=EC=8A=A4=ED=84=B0=20=EA=B0=9C=EB=B0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. clusterPoint간의 데이터를 전달하는 clusterRouter 추가 2. clusterPoint 기능 강화 3. 클래스 구조 및 ci서버 지적사항 수정 --- .../cluster/AbstractClusterService.java | 18 ++ .../collector/cluster/ClusterPointRouter.java | 158 ++++++++++++++++++ .../cluster/ProfilerClusterPoint.java | 84 ++++++++++ .../collector/cluster/WebClusterPoint.java | 36 +--- .../cluster/zookeeper/ZookeeperClient.java | 2 +- .../zookeeper/ZookeeperClusterService.java | 32 ++-- .../zookeeper/ZookeeperLatestJobWorker.java | 5 + .../ZookeeperProfilerClusterManager.java | 16 +- .../zookeeper/ZookeeperWebClusterManager.java | 10 +- .../config/CollectorBeanConfiguration.java | 52 ++++++ .../collector/receiver/tcp/TCPReceiver.java | 13 +- .../collector/util/CollectorUtils.java | 20 +++ .../src/main/resources/applicationContext.xml | 15 +- ...perEnsembleProfilerClusterServiceTest.java | 18 +- .../ZookeeperProfilerClusterServiceTest.java | 20 ++- .../ZookeeperWebClusterServiceTest.java | 12 +- .../resources/applicationContext-test.xml | 146 ++++++++-------- 17 files changed, 510 insertions(+), 147 deletions(-) create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/AbstractClusterService.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouter.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ProfilerClusterPoint.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorBeanConfiguration.java create mode 100644 collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/AbstractClusterService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/AbstractClusterService.java new file mode 100644 index 000000000000..2ea65752a9e4 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/AbstractClusterService.java @@ -0,0 +1,18 @@ +package com.nhn.pinpoint.collector.cluster; + +import com.nhn.pinpoint.collector.config.CollectorConfiguration; + +/** + * @author koo.taejin + */ +public abstract class AbstractClusterService implements ClusterService { + + protected final CollectorConfiguration config; + protected final ClusterPointRouter clusterPointRouter; + + public AbstractClusterService(CollectorConfiguration config, ClusterPointRouter clusterPointRouter) { + this.config = config; + this.clusterPointRouter = clusterPointRouter; + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouter.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouter.java new file mode 100644 index 000000000000..f4f491824d7f --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouter.java @@ -0,0 +1,158 @@ +package com.nhn.pinpoint.collector.cluster; + +import java.util.Map; + +import javax.annotation.PreDestroy; + +import org.apache.thrift.TBase; +import org.apache.thrift.TException; +import org.jboss.netty.channel.Channel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nhn.pinpoint.collector.receiver.tcp.AgentPropertiesType; +import com.nhn.pinpoint.collector.util.CollectorUtils; +import com.nhn.pinpoint.rpc.Future; +import com.nhn.pinpoint.rpc.ResponseMessage; +import com.nhn.pinpoint.rpc.client.MessageListener; +import com.nhn.pinpoint.rpc.packet.RequestPacket; +import com.nhn.pinpoint.rpc.packet.ResponsePacket; +import com.nhn.pinpoint.rpc.packet.SendPacket; +import com.nhn.pinpoint.rpc.server.ChannelContext; +import com.nhn.pinpoint.rpc.util.MapUtils; +import com.nhn.pinpoint.thrift.dto.TResult; +import com.nhn.pinpoint.thrift.dto.command.TCommandTransfer; +import com.nhn.pinpoint.thrift.io.DeserializerFactory; +import com.nhn.pinpoint.thrift.io.HeaderTBaseDeserializer; +import com.nhn.pinpoint.thrift.io.HeaderTBaseSerializer; +import com.nhn.pinpoint.thrift.io.SerializerFactory; +import com.nhn.pinpoint.thrift.io.TCommandTypeVersion; + +/** + * @author koo.taejin + */ +public class ClusterPointRouter { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final String serverIdentifier = CollectorUtils.getServerIdentifier(); + + private final ProfilerClusterPoint profilerClusterPoint; + private final WebClusterPoint webClusterPoint; + + @Autowired + private SerializerFactory commandSerializerFactory; + + @Autowired + private DeserializerFactory commandDeserializerFactory; + + public ClusterPointRouter() { + this.profilerClusterPoint = new ProfilerClusterPoint(); + this.webClusterPoint = new WebClusterPoint(serverIdentifier, new WebPointMessageListener()); + } + + @PreDestroy + public void stop() { + if (webClusterPoint != null) { + webClusterPoint.close(); + } + } + + public ProfilerClusterPoint getProfilerClusterPoint() { + return profilerClusterPoint; + } + + public WebClusterPoint getWebClusterPoint() { + return webClusterPoint; + } + + private byte[] serialize(TBase result) { + if (result == null) { + logger.warn("tBase may not be null."); + return null; + } + + try { + HeaderTBaseSerializer serializer = commandSerializerFactory.createSerializer(); + byte[] payload = serializer.serialize(result); + return payload; + } catch (TException e) { + logger.warn(e.getMessage(), e); + } + + return null; + } + + private TBase deserialize(byte[] payload) { + if (payload == null) { + logger.warn("Payload may not be null."); + return null; + } + + try { + final HeaderTBaseDeserializer deserializer = commandDeserializerFactory.createDeserializer(); + TBase tBase = deserializer.deserialize(payload); + return tBase; + } catch (TException e) { + logger.warn(e.getMessage(), e); + } + + return null; + } + + class WebPointMessageListener implements MessageListener { + + @Override + public void handleSend(SendPacket sendPacket, Channel channel) { + logger.info("Received SendPacket {} {}.", sendPacket, channel); + } + + @Override + public void handleRequest(RequestPacket requestPacket, Channel channel) { + logger.info("Received RequestPacket {} {}.", requestPacket, channel); + + TBase request = deserialize(requestPacket.getPayload()); + + if (request == null) { + TResult tResult = new TResult(false); + tResult.setMessage("Unexpected decode result."); + + channel.write(new ResponsePacket(requestPacket.getRequestId(), serialize(tResult))); + } else if (request instanceof TCommandTransfer) { + + String applicationName = ((TCommandTransfer) request).getApplicationName(); + String agentId = ((TCommandTransfer) request).getAgentId(); + byte[] payload = ((TCommandTransfer) request).getPayload(); + + TBase command = deserialize(payload); + + ChannelContext channelContext = profilerClusterPoint.getChannelContext(applicationName, agentId, -1); + + Map proeprties = channelContext.getChannelProperties(); + String version = MapUtils.getString(proeprties, AgentPropertiesType.VERSION.getName()); + + TCommandTypeVersion commandVersion = TCommandTypeVersion.getVersion(version); + if (commandVersion.isSupportCommand(command)) { + Future future = channelContext.getSocketChannel().sendRequestMessage(payload); + future.await(); + ResponseMessage responseMessage = future.getResult(); + + channel.write(new ResponsePacket(requestPacket.getRequestId(), responseMessage.getMessage())); + } else { + TResult result = new TResult(false); + result.setMessage(applicationName + "/" + agentId + " unsupported command(" + command + ") type."); + + channel.write(new ResponsePacket(requestPacket.getRequestId(), serialize(result))); + } + } else { + TResult tResult = new TResult(false); + tResult.setMessage("Unsupported command(" + request + ") type."); + + channel.write(new ResponsePacket(requestPacket.getRequestId(), serialize(tResult))); + } + + } + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ProfilerClusterPoint.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ProfilerClusterPoint.java new file mode 100644 index 000000000000..b8bd0d901438 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ProfilerClusterPoint.java @@ -0,0 +1,84 @@ +package com.nhn.pinpoint.collector.cluster; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nhn.pinpoint.collector.receiver.tcp.AgentPropertiesType; +import com.nhn.pinpoint.rpc.server.ChannelContext; +import com.nhn.pinpoint.rpc.util.MapUtils; + +/** + * @author koo.taejin + */ +public class ProfilerClusterPoint implements ClusterPoint { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final CopyOnWriteArrayList clusterRepository = new CopyOnWriteArrayList(); + + + public boolean registerChannelContext(ChannelContext channelContext) { + boolean isAdd = clusterRepository.addIfAbsent(channelContext); + + if (!isAdd) { + logger.warn("Already registered ChannelContext({}).", channelContext); + } + + return isAdd; + } + + public boolean unregisterChannelContext(ChannelContext channelContext) { + boolean isRemove = clusterRepository.remove(channelContext); + + if (!isRemove) { + logger.warn("Already unregistered or not registered ChannelContext({}).", channelContext); + } + + return isRemove; + } + + public List getChannelContext() { + return new ArrayList(clusterRepository); + } + + public ChannelContext getChannelContext(String applicationName, String agentId) { + return getChannelContext(applicationName, agentId, -1); + } + + public ChannelContext getChannelContext(String applicationName, String agentId, long startTimestamp) { + + for (ChannelContext channelContext : clusterRepository) { + if (checkSuitableChannelContext(channelContext, applicationName, agentId, startTimestamp)) { + return channelContext; + } + } + + return null; + } + + private boolean checkSuitableChannelContext(ChannelContext channelContext, String applicationName, String agentId, long startTimestamp) { + Map properties = channelContext.getChannelProperties(); + + if (!applicationName.equals(MapUtils.getString(properties, AgentPropertiesType.APPLICATION_NAME.getName()))) { + return false; + } + + if (!agentId.equals(MapUtils.getString(properties, AgentPropertiesType.AGENT_ID.getName()))) { + return false; + } + + if (startTimestamp <= 0) { + // Fix Me + // startTimestamp도 체크하게 변경해야함 + return false; + } + + return true; + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebClusterPoint.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebClusterPoint.java index fb77a58dda56..840b0ca7d2eb 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebClusterPoint.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebClusterPoint.java @@ -6,7 +6,6 @@ import java.util.List; import java.util.Map; -import org.jboss.netty.channel.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,8 +13,6 @@ import com.nhn.pinpoint.rpc.client.MessageListener; import com.nhn.pinpoint.rpc.client.PinpointSocket; import com.nhn.pinpoint.rpc.client.PinpointSocketFactory; -import com.nhn.pinpoint.rpc.packet.RequestPacket; -import com.nhn.pinpoint.rpc.packet.SendPacket; /** * @author koo.taejin @@ -25,13 +22,16 @@ public class WebClusterPoint implements ClusterPoint { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final PinpointSocketFactory factory; + private final MessageListener messageListener; // InetSocketAddress List로 전달 하는게 좋을거 같은데 이걸 Key로만들기가 쉽지 않네; private final Map clusterRepository = new HashMap(); - public WebClusterPoint(String id) { - factory = new PinpointSocketFactory(); - factory.setTimeoutMillis(1000 * 5); + public WebClusterPoint(String id, MessageListener messageListener) { + this.messageListener = messageListener; + + this.factory = new PinpointSocketFactory(); + this.factory.setTimeoutMillis(1000 * 5); Map properties = new HashMap(); properties.put("id", id); @@ -68,8 +68,6 @@ public void disconnectPoint(InetSocketAddress address) { } private PinpointSocket createPinpointSocket(InetSocketAddress address) { - MessageListener messageListener = new SimpleMessageListener(address); - String host = address.getHostName(); int port = address.getPort(); @@ -105,26 +103,4 @@ public void close() { } } - class SimpleMessageListener implements MessageListener { - - private final InetSocketAddress address; - - public SimpleMessageListener(InetSocketAddress address) { - this.address = address; - } - - @Override - public void handleSend(SendPacket sendPacket, Channel channel) { - logger.info("{} receive send Message {}", address, sendPacket); - // TODO Auto-generated method stub - - } - - @Override - public void handleRequest(RequestPacket requestPacket, Channel channel) { - logger.info("{} receive Request Message {}", address, requestPacket); - } - - } - } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java index 3090f1678b5c..eb881b1af98f 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java @@ -195,7 +195,7 @@ public List getChildrenNode(String path, boolean watch) throws PinpointZ } } - return Collections.EMPTY_LIST; + return Collections.emptyList(); } // public byte[] getData(String path) throws KeeperException, InterruptedException { diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java index 1c6a4804b8ec..b46098b9b968 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java @@ -1,7 +1,6 @@ package com.nhn.pinpoint.collector.cluster.zookeeper; import java.io.IOException; -import java.lang.management.ManagementFactory; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @@ -16,14 +15,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.nhn.pinpoint.collector.cluster.ClusterService; +import com.nhn.pinpoint.collector.cluster.AbstractClusterService; +import com.nhn.pinpoint.collector.cluster.ClusterPointRouter; import com.nhn.pinpoint.collector.cluster.WorkerState; import com.nhn.pinpoint.collector.cluster.WorkerStateContext; import com.nhn.pinpoint.collector.config.CollectorConfiguration; +import com.nhn.pinpoint.collector.util.CollectorUtils; import com.nhn.pinpoint.rpc.server.ChannelContext; import com.nhn.pinpoint.rpc.server.SocketChannelStateChangeEventListener; -public class ZookeeperClusterService implements ClusterService { +public class ZookeeperClusterService extends AbstractClusterService { private static final String PINPOINT_CLUSTER_PATH = "/pinpoint-cluster"; private static final String PINPOINT_WEB_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/web"; @@ -33,22 +34,22 @@ public class ZookeeperClusterService implements ClusterService { // 해당 값이 유일한 값이 아닌 경우 MAC주소나 IP주소 등으로 변경할 예정 // 요렇게 하면 pid@hostname 으로 나옴 (localhost 요런놈은 겹칠 가능성이 존재함) - private final String serverIdentifier = ManagementFactory.getRuntimeMXBean().getName(); - - private final CollectorConfiguration config; + private final String serverIdentifier = CollectorUtils.getServerIdentifier(); private final WorkerStateContext serviceState; private ZookeeperClient client; + // ProfilerClusterManager는 프로파일러 -> 콜렉터 연결을 감지 및 관리하고, 쥬키퍼에 등록한다. // private ZookeeperProfilerClusterManager profilerClusterManager; // WebClusterManager는 웹 정보가 쥬키퍼에 등록되어 있는지 체크하고, 콜렉터 -> 웹 연결을 관리한다. + private ZookeeperWebClusterManager webClusterManager; private ZookeeperProfilerClusterManager profilerClusterManager; - public ZookeeperClusterService(CollectorConfiguration config) { - this.config = config; + public ZookeeperClusterService(CollectorConfiguration config, ClusterPointRouter clusterPointRouter) { + super(config, clusterPointRouter); this.serviceState = new WorkerStateContext(); } @@ -68,11 +69,11 @@ public void setUp() throws KeeperException, IOException, InterruptedException { // 이 상태값은 반드시 필요한것들인데. ClusterManagerWatcher watcher = new ClusterManagerWatcher(); this.client = new ZookeeperClient(config.getClusterAddress(), config.getClusterSessionTimeout(), watcher); - - this.profilerClusterManager = new ZookeeperProfilerClusterManager(client, serverIdentifier); + + this.profilerClusterManager = new ZookeeperProfilerClusterManager(client, serverIdentifier, clusterPointRouter.getProfilerClusterPoint()); this.profilerClusterManager.start(); - this.webClusterManager = new ZookeeperWebClusterManager(client, PINPOINT_WEB_CLUSTER_PATH, serverIdentifier); + this.webClusterManager = new ZookeeperWebClusterManager(client, PINPOINT_WEB_CLUSTER_PATH, serverIdentifier, clusterPointRouter.getWebClusterPoint()); this.webClusterManager.start(); this.serviceState.changeStateStarted(); @@ -98,7 +99,7 @@ public void setUp() throws KeeperException, IOException, InterruptedException { throw new IllegalStateException("Already stopped."); case ILLEGAL_STATE: throw new IllegalStateException("Invalid State."); - } + } } @PreDestroy @@ -125,7 +126,7 @@ public void tearDown() { if (this.webClusterManager != null) { webClusterManager.stop(); } - + if (client != null) { client.close(); } @@ -183,10 +184,7 @@ public void process(WatchedEvent event) { } webClusterManager.handleAndRegisterWatcher(PINPOINT_WEB_CLUSTER_PATH); - return; - } - - if (eventType == EventType.NodeChildrenChanged) { + } else if (eventType == EventType.NodeChildrenChanged) { String path = event.getPath(); if (PINPOINT_WEB_CLUSTER_PATH.equals(path)) { diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java index 6283eb697bc3..57edf6a6dd31 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java @@ -195,6 +195,10 @@ public boolean handleUpdate(UpdateJob job) { // 동시성에 문제 없게 하자 String uniquePath = getUniquePath(channelContext, true); + if (uniquePath == null) { + logger.warn("Zookeeper UniqPath({}) may not be null.", uniquePath); + return false; + } try { if (zookeeperClient.exists(uniquePath)) { @@ -352,6 +356,7 @@ private String getUniquePath(ChannelContext channelContext, boolean create) { final String agentId = MapUtils.getString(agentProperties, AgentPropertiesType.AGENT_ID.getName()); if (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(agentId)) { + logger.warn("ApplicationName({}) and AgnetId({}) may not be null.", applicationName, agentId); return null; } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java index 4de01ff24fd5..35b60d68443f 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java @@ -1,18 +1,17 @@ package com.nhn.pinpoint.collector.cluster.zookeeper; -import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; -import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.nhn.pinpoint.collector.cluster.ProfilerClusterPoint; import com.nhn.pinpoint.collector.cluster.WorkerState; import com.nhn.pinpoint.collector.cluster.WorkerStateContext; import com.nhn.pinpoint.collector.cluster.zookeeper.exception.PinpointZookeeperException; @@ -36,6 +35,8 @@ public class ZookeeperProfilerClusterManager implements SocketChannelStateChange private final WorkerStateContext workerState; + private final ProfilerClusterPoint clusterPoint; + private final ObjectMapper objectmapper = new ObjectMapper(); // 단순하게 하자 그냥 RUN이면 등록 FINISHED면 경우 삭제 그외 skip @@ -43,8 +44,9 @@ public class ZookeeperProfilerClusterManager implements SocketChannelStateChange // // RUN_DUPLEX에서만 생성할수 있게 해야한다. // 지금은 RUN 상대방의 상태를 알수 없는 상태이기 때문에 이상황에서 등록 - public ZookeeperProfilerClusterManager(ZookeeperClient client, String serverIdentifier) throws KeeperException, IOException, InterruptedException { + public ZookeeperProfilerClusterManager(ZookeeperClient client, String serverIdentifier, ProfilerClusterPoint clusterPoint) { this.workerState = new WorkerStateContext(); + this.clusterPoint = clusterPoint; this.client = client; this.worker = new ZookeeperLatestJobWorker(client, serverIdentifier); @@ -121,9 +123,13 @@ public void eventPerformed(ChannelContext channelContext, PinpointServerSocketSt UpdateJob job = new UpdateJob(channelContext, contents); worker.putJob(job); + + clusterPoint.registerChannelContext(channelContext); } else if (PinpointServerSocketStateCode.isFinished(stateCode)) { DeleteJob job = new DeleteJob(channelContext); worker.putJob(job); + + clusterPoint.unregisterChannelContext(channelContext); } } else { WorkerState state = this.workerState.getCurrentState(); @@ -137,7 +143,7 @@ public Map getData(ChannelContext channelContext) { byte[] contents = worker.getData(channelContext); if (contents == null) { - return Collections.EMPTY_MAP; + return Collections.emptyMap(); } return deserializeContents(contents); @@ -188,7 +194,7 @@ private Map deserializeContents(byte[] contents) { logger.warn(e.getMessage(), e); } - return Collections.EMPTY_MAP; + return Collections.emptyMap(); } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java index 5ade2e8de737..927c669993fe 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java @@ -1,6 +1,5 @@ package com.nhn.pinpoint.collector.cluster.zookeeper; -import java.io.IOException; import java.net.InetSocketAddress; import java.util.List; import java.util.concurrent.BlockingQueue; @@ -9,7 +8,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -51,11 +49,10 @@ public class ZookeeperWebClusterManager implements Runnable { // Job이 포함되면 실행. Job성공시 이후 Job 모두 삭제 // 먼가 이상한 형태의 자료구조가 필요한거 같은데.... - public ZookeeperWebClusterManager(ZookeeperClient client, String zookeeperClusterPath, String serverIdentifier) throws KeeperException, IOException, - InterruptedException { + public ZookeeperWebClusterManager(ZookeeperClient client, String zookeeperClusterPath, String serverIdentifier, WebClusterPoint clusterPoint) { this.client = client; - this.webClusterPoint = new WebClusterPoint(serverIdentifier); + this.webClusterPoint = clusterPoint; this.zNodePath = zookeeperClusterPath; this.workerState = new WorkerStateContext(); @@ -101,9 +98,6 @@ public void stop() { logger.info("{} destorying started.", this.getClass().getSimpleName()); queue.offer(stopTask); - if (webClusterPoint != null) { - webClusterPoint.close(); - } boolean interrupted = false; while (this.workerThread.isAlive()) { diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorBeanConfiguration.java b/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorBeanConfiguration.java new file mode 100644 index 000000000000..d2783e77d219 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorBeanConfiguration.java @@ -0,0 +1,52 @@ +package com.nhn.pinpoint.collector.config; + +import org.apache.thrift.protocol.TCompactProtocol; +import org.apache.thrift.protocol.TProtocolFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; + +import com.nhn.pinpoint.common.Version; +import com.nhn.pinpoint.thrift.io.DeserializerFactory; +import com.nhn.pinpoint.thrift.io.HeaderTBaseDeserializerFactory; +import com.nhn.pinpoint.thrift.io.HeaderTBaseSerializerFactory; +import com.nhn.pinpoint.thrift.io.SerializerFactory; +import com.nhn.pinpoint.thrift.io.TBaseLocator; +import com.nhn.pinpoint.thrift.io.TCommandRegistry; +import com.nhn.pinpoint.thrift.io.TCommandTypeVersion; +import com.nhn.pinpoint.thrift.io.ThreadLocalHeaderTBaseDeserializerFactory; +import com.nhn.pinpoint.thrift.io.ThreadLocalHeaderTBaseSerializerFactory; + +/** + * @author koo.taejin + */ +@Configuration +public class CollectorBeanConfiguration { + + public static final int DEFAULT_SERIALIZER_MAX_SIZE = 1024 * 64; + + @Bean + @Scope(value = "singleton") + public SerializerFactory commandSerializerFactory() { + TBaseLocator commandTbaseLocator = new TCommandRegistry(TCommandTypeVersion.getVersion(Version.VERSION)); + + TProtocolFactory protocolFactory = new TCompactProtocol.Factory(); + HeaderTBaseSerializerFactory serializerFactory = new HeaderTBaseSerializerFactory(true, DEFAULT_SERIALIZER_MAX_SIZE, protocolFactory, commandTbaseLocator); + + ThreadLocalHeaderTBaseSerializerFactory threadLocalSerializerFactory = new ThreadLocalHeaderTBaseSerializerFactory(serializerFactory); + return threadLocalSerializerFactory; + } + + @Bean + @Scope(value = "singleton") + public DeserializerFactory commandDeserializerFactory() { + TBaseLocator commandTbaseLocator = new TCommandRegistry(TCommandTypeVersion.getVersion(Version.VERSION)); + + TProtocolFactory protocolFactory = new TCompactProtocol.Factory(); + HeaderTBaseDeserializerFactory deserializerFactory = new HeaderTBaseDeserializerFactory(protocolFactory, commandTbaseLocator); + + ThreadLocalHeaderTBaseDeserializerFactory threadLocalDeserializerFactory = new ThreadLocalHeaderTBaseDeserializerFactory(deserializerFactory); + return threadLocalDeserializerFactory; + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiver.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiver.java index e54611bf7165..d76015ad267d 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiver.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiver.java @@ -19,6 +19,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; +import com.nhn.pinpoint.collector.cluster.zookeeper.ZookeeperClusterService; import com.nhn.pinpoint.collector.receiver.DispatchHandler; import com.nhn.pinpoint.collector.util.PacketUtils; import com.nhn.pinpoint.common.util.ExecutorFactory; @@ -70,13 +71,23 @@ public class TCPReceiver { public TCPReceiver(DispatchHandler dispatchHandler, String bindAddress, int port) { + this(dispatchHandler, bindAddress, port, null); + } + + public TCPReceiver(DispatchHandler dispatchHandler, String bindAddress, int port, ZookeeperClusterService service) { if (dispatchHandler == null) { throw new NullPointerException("dispatchHandler must not be null"); } if (bindAddress == null) { throw new NullPointerException("bindAddress must not be null"); } - this.pinpointServerSocket = new PinpointServerSocket(); + + if (service == null) { + this.pinpointServerSocket = new PinpointServerSocket(); + } else { + this.pinpointServerSocket = new PinpointServerSocket(service.getChannelStateChangeEventListener()); + } + this.dispatchHandler = dispatchHandler; this.bindAddress = bindAddress; this.port = port; diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java b/collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java new file mode 100644 index 000000000000..ae846878c108 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java @@ -0,0 +1,20 @@ +package com.nhn.pinpoint.collector.util; + +import java.lang.management.ManagementFactory; + +/** + * @author koo.taejin + */ +public final class CollectorUtils { + + private CollectorUtils() { + } + + public static String getServerIdentifier() { + + // 해당 값이 유일한 값이 아닌 경우 MAC주소나 IP주소 등으로 변경할 예정 + // 요렇게 하면 pid@hostname 으로 나옴 (localhost 요런놈은 겹칠 가능성이 존재함) + return ManagementFactory.getRuntimeMXBean().getName(); + } + +} diff --git a/collector/src/main/resources/applicationContext.xml b/collector/src/main/resources/applicationContext.xml index 8eca27b555ea..ab5971395209 100644 --- a/collector/src/main/resources/applicationContext.xml +++ b/collector/src/main/resources/applicationContext.xml @@ -20,7 +20,8 @@ base-package="com.nhn.pinpoint.collector.dao.hbase, com.nhn.pinpoint.collector.handler, com.nhn.pinpoint.collector.mapper - com.nhn.pinpoint.collector.util" /> + com.nhn.pinpoint.collector.util + com.nhn.pinpoint.collector.config" /> @@ -63,11 +64,19 @@ + + + + + + + + @@ -111,12 +120,8 @@ - - - -
\ No newline at end of file diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperEnsembleProfilerClusterServiceTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperEnsembleProfilerClusterServiceTest.java index 3bc27090e192..372f9b6e3b5a 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperEnsembleProfilerClusterServiceTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperEnsembleProfilerClusterServiceTest.java @@ -10,14 +10,24 @@ import org.apache.curator.test.TestingCluster; import org.apache.curator.test.TestingZooKeeperServer; import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import com.nhn.pinpoint.collector.cluster.ClusterPointRouter; import com.nhn.pinpoint.collector.config.CollectorConfiguration; import com.nhn.pinpoint.collector.receiver.tcp.AgentProperties; import com.nhn.pinpoint.rpc.server.ChannelContext; import com.nhn.pinpoint.rpc.server.PinpointServerSocketStateCode; +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:applicationContext-test.xml") public class ZookeeperEnsembleProfilerClusterServiceTest { + @Autowired + ClusterPointRouter clusterPointRouter; + @Test public void simpleTest1() throws Exception { TestingCluster tcluster = null; @@ -28,7 +38,9 @@ public void simpleTest1() throws Exception { CollectorConfiguration collectorConfig = createConfig(connectString); - ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + + + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig, clusterPointRouter); service.setUp(); ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); @@ -69,7 +81,7 @@ public void simpleTest2() throws Exception { CollectorConfiguration collectorConfig = createConfig(connectString); - ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig, clusterPointRouter); service.setUp(); ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); @@ -117,7 +129,7 @@ public void simpleTest3() throws Exception { CollectorConfiguration collectorConfig = createConfig(connectString); - ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig, clusterPointRouter); service.setUp(); ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterServiceTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterServiceTest.java index e080a9272824..111dc08e0ccb 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterServiceTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterServiceTest.java @@ -7,18 +7,28 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import com.nhn.pinpoint.collector.cluster.ClusterPointRouter; import com.nhn.pinpoint.collector.config.CollectorConfiguration; import com.nhn.pinpoint.collector.receiver.tcp.AgentProperties; import com.nhn.pinpoint.rpc.server.ChannelContext; import com.nhn.pinpoint.rpc.server.PinpointServerSocketStateCode; +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:applicationContext-test.xml") public class ZookeeperProfilerClusterServiceTest { private static final int DEFAULT_ACCEPTOR_PORT = 22213; private static CollectorConfiguration collectorConfig = null; + @Autowired + ClusterPointRouter clusterPointRouter; + @BeforeClass public static void setUp() { collectorConfig = new CollectorConfiguration(); @@ -34,7 +44,7 @@ public void simpleTest1() throws Exception { try { ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); - ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig, clusterPointRouter); service.setUp(); ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); @@ -70,7 +80,7 @@ public void simpleTest1() throws Exception { public void simpleTest2() throws Exception { TestingServer ts = null; try { - ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig, clusterPointRouter); service.setUp(); ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); @@ -113,7 +123,7 @@ public void simpleTest3() throws Exception { try { ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); - ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig, clusterPointRouter); service.setUp(); ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); @@ -156,7 +166,7 @@ public void simpleTest3() throws Exception { public void simpleTest4() throws Exception { TestingServer ts = null; try { - ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig, clusterPointRouter); service.setUp(); ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); @@ -200,7 +210,7 @@ public void simpleTest5() throws Exception { try { ts = createZookeeperServer(DEFAULT_ACCEPTOR_PORT); - ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig, clusterPointRouter); service.setUp(); ChannelContext channelContext = new ChannelContext(null, null, service.getChannelStateChangeEventListener()); diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterServiceTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterServiceTest.java index a2fa57d163c0..4fb2b3905136 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterServiceTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterServiceTest.java @@ -9,9 +9,14 @@ import org.apache.zookeeper.WatchedEvent; import org.junit.BeforeClass; import org.junit.Test; +import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import com.nhn.pinpoint.collector.cluster.ClusterPointRouter; import com.nhn.pinpoint.collector.config.CollectorConfiguration; import com.nhn.pinpoint.rpc.packet.ControlEnableWorkerConfirmPacket; import com.nhn.pinpoint.rpc.packet.RequestPacket; @@ -24,6 +29,8 @@ import com.nhn.pinpoint.rpc.server.ServerStreamChannel; import com.nhn.pinpoint.rpc.server.SocketChannel; +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:applicationContext-test.xml") public class ZookeeperWebClusterServiceTest { private static final String PINPOINT_CLUSTER_PATH = "/pinpoint-cluster"; @@ -36,6 +43,9 @@ public class ZookeeperWebClusterServiceTest { private static CollectorConfiguration collectorConfig = null; + @Autowired + ClusterPointRouter clusterPointRouter; + @BeforeClass public static void setUp() { collectorConfig = new CollectorConfiguration(); @@ -51,7 +61,7 @@ public void simpleTest1() throws Exception { try { ts = createZookeeperServer(DEFAULT_ZOOKEEPER_PORT); - ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig); + ZookeeperClusterService service = new ZookeeperClusterService(collectorConfig, clusterPointRouter); service.setUp(); PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(); diff --git a/collector/src/test/resources/applicationContext-test.xml b/collector/src/test/resources/applicationContext-test.xml index a8e6b2bdadea..676233c4d88d 100644 --- a/collector/src/test/resources/applicationContext-test.xml +++ b/collector/src/test/resources/applicationContext-test.xml @@ -1,72 +1,76 @@ - - - - - - - - - - - hbase.properties - pinpoint-collector.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + hbase.properties + pinpoint-collector.properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From c3f668bfdf04aa44909ce78da0dd709be65e9e8b Mon Sep 17 00:00:00 2001 From: koo-taejin Date: Tue, 16 Sep 2014 20:11:54 +0900 Subject: [PATCH 07/18] =?UTF-8?q?#5=20Pinpoint=20=ED=81=B4=EB=9F=AC?= =?UTF-8?q?=EC=8A=A4=ED=84=B0=20=EA=B0=9C=EB=B0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pinpoint/collector/cluster/ClusterPointRouter.java | 6 ++++++ .../pinpoint/collector/cluster/ProfilerClusterPoint.java | 2 +- .../navercorp/pinpoint/thrift/io/TCommandTypeVersion.java | 6 +++++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouter.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouter.java index f4f491824d7f..1dfb7b05ad2f 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouter.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouter.java @@ -128,6 +128,12 @@ public void handleRequest(RequestPacket requestPacket, Channel channel) { TBase command = deserialize(payload); ChannelContext channelContext = profilerClusterPoint.getChannelContext(applicationName, agentId, -1); + if (channelContext == null) { + TResult result = new TResult(false); + result.setMessage(applicationName + "/" + agentId + " can't find suitable ChannelContext."); + channel.write(new ResponsePacket(requestPacket.getRequestId(), serialize(result))); + return; + } Map proeprties = channelContext.getChannelProperties(); String version = MapUtils.getString(proeprties, AgentPropertiesType.VERSION.getName()); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ProfilerClusterPoint.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ProfilerClusterPoint.java index b8bd0d901438..82921c075df1 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ProfilerClusterPoint.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ProfilerClusterPoint.java @@ -75,7 +75,7 @@ private boolean checkSuitableChannelContext(ChannelContext channelContext, Strin if (startTimestamp <= 0) { // Fix Me // startTimestamp도 체크하게 변경해야함 - return false; + return true; } return true; diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java index 00b1f0f358e2..628986ed48c6 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java @@ -50,7 +50,11 @@ public boolean isSupportCommand(TBase command) { } for (TCommandType eachCommand : supportCommandList) { - if (command.getClass().isInstance(eachCommand)) { + if (eachCommand == null) { + continue; + } + + if (eachCommand.getClazz() == command.getClass()) { return true; } } From bc5fdd3f205fddfb4f4742acbe00e9379fed76eb Mon Sep 17 00:00:00 2001 From: koo-taejin Date: Tue, 16 Sep 2014 21:36:22 +0900 Subject: [PATCH 08/18] =?UTF-8?q?#5=20Pinpoint=20=ED=81=B4=EB=9F=AC?= =?UTF-8?q?=EC=8A=A4=ED=84=B0=20=EA=B0=9C=EB=B0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 테스트코드 작성 --- .../cluster/ClusterPointRouterTest.java | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 collector/src/test/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouterTest.java diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouterTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouterTest.java new file mode 100644 index 000000000000..2bfd2d6295a6 --- /dev/null +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRouterTest.java @@ -0,0 +1,118 @@ +package com.nhn.pinpoint.collector.cluster; + +import java.net.InetSocketAddress; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.Assert; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.nhn.pinpoint.collector.receiver.tcp.AgentProperties; +import com.nhn.pinpoint.rpc.packet.ControlEnableWorkerConfirmPacket; +import com.nhn.pinpoint.rpc.packet.RequestPacket; +import com.nhn.pinpoint.rpc.packet.SendPacket; +import com.nhn.pinpoint.rpc.packet.StreamPacket; +import com.nhn.pinpoint.rpc.server.ChannelContext; +import com.nhn.pinpoint.rpc.server.PinpointServerSocket; +import com.nhn.pinpoint.rpc.server.ServerMessageListener; +import com.nhn.pinpoint.rpc.server.ServerStreamChannel; +import com.nhn.pinpoint.rpc.server.SocketChannel; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:applicationContext-test.xml") +public class ClusterPointRouterTest { + + private static final int DEFAULT_ACCEPTOR_SOCKET_PORT = 22214; + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + ClusterPointRouter clusterPointRouter; + + @Test + public void webClusterPointtest() { + WebClusterPoint webClusterPoint = clusterPointRouter.getWebClusterPoint(); + + PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(); + pinpointServerSocket.setMessageListener(new PinpointSocketManagerHandler()); + pinpointServerSocket.bind("127.0.0.1", DEFAULT_ACCEPTOR_SOCKET_PORT); + + InetSocketAddress address = new InetSocketAddress("127.0.0.1", DEFAULT_ACCEPTOR_SOCKET_PORT); + + Assert.assertEquals(0, webClusterPoint.getWebClusterList().size()); + webClusterPoint.connectPointIfAbsent(address); + Assert.assertEquals(1, webClusterPoint.getWebClusterList().size()); + webClusterPoint.connectPointIfAbsent(address); + Assert.assertEquals(1, webClusterPoint.getWebClusterList().size()); + + webClusterPoint.disconnectPoint(address); + Assert.assertEquals(0, webClusterPoint.getWebClusterList().size()); + webClusterPoint.disconnectPoint(address); + Assert.assertEquals(0, webClusterPoint.getWebClusterList().size()); + } + + @Test + public void profilerClusterPointtest() { + ProfilerClusterPoint profilerClusterPoint = clusterPointRouter.getProfilerClusterPoint(); + + ChannelContext channelContext = new ChannelContext(null, null); + channelContext.setChannelProperties(getParams()); + + profilerClusterPoint.registerChannelContext(channelContext); + Assert.assertEquals(1, profilerClusterPoint.getChannelContext().size()); + + Assert.assertNull(profilerClusterPoint.getChannelContext("a", "a")); + Assert.assertNull(profilerClusterPoint.getChannelContext("application", "a")); + Assert.assertEquals(channelContext, profilerClusterPoint.getChannelContext("application", "agent")); + + profilerClusterPoint.unregisterChannelContext(channelContext); + Assert.assertEquals(0, profilerClusterPoint.getChannelContext().size()); + Assert.assertNull(profilerClusterPoint.getChannelContext("application", "agent")); + } + + private class PinpointSocketManagerHandler implements ServerMessageListener { + @Override + public void handleSend(SendPacket sendPacket, SocketChannel channel) { + logger.warn("Unsupport send received {} {}", sendPacket, channel); + } + + @Override + public void handleRequest(RequestPacket requestPacket, SocketChannel channel) { + logger.warn("Unsupport request received {} {}", requestPacket, channel); + } + + @Override + public void handleStream(StreamPacket streamPacket, ServerStreamChannel streamChannel) { + logger.warn("unsupported streamPacket received {}", streamPacket); + } + + @Override + public int handleEnableWorker(Map properties) { + logger.warn("do handleEnableWorker {}", properties); + return ControlEnableWorkerConfirmPacket.SUCCESS; + } + } + + private Map getParams() { + Map properties = new HashMap(); + + properties.put(AgentProperties.KEY_AGENTID, "agent"); + properties.put(AgentProperties.KEY_APPLICATION_NAME, "application"); + properties.put(AgentProperties.KEY_HOSTNAME, "hostname"); + properties.put(AgentProperties.KEY_IP, "ip"); + properties.put(AgentProperties.KEY_PID, 1111); + properties.put(AgentProperties.KEY_SERVICE_TYPE, 10); + properties.put(AgentProperties.KEY_START_TIME_MILLIS, System.currentTimeMillis()); + properties.put(AgentProperties.KEY_VERSION, "1.0.3-SNAPSHOT"); + + return properties; + } + +} From 127165ff794ea9c4dd3ef9b8fc275cd5aeb67393 Mon Sep 17 00:00:00 2001 From: Hyun Jeong Date: Thu, 18 Sep 2014 13:07:06 +0900 Subject: [PATCH 09/18] [#14] Changed Tomcat start event hook to when StandardService starts. --- .../modifier/tomcat/CatalinaModifier.java | 67 ----------------- .../tomcat/StandardServiceModifier.java | 72 +++++++++++++++++++ .../tomcat/TomcatStandardServiceModifier.java | 64 ----------------- .../interceptor/CatalinaAwaitInterceptor.java | 39 ---------- .../interceptor/CatalinaStartInterceptor.java | 37 ---------- .../interceptor/CatalinaStopInterceptor.java | 41 ----------- 6 files changed, 72 insertions(+), 248 deletions(-) delete mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/CatalinaModifier.java create mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardServiceModifier.java delete mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/TomcatStandardServiceModifier.java delete mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaAwaitInterceptor.java delete mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaStartInterceptor.java delete mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaStopInterceptor.java diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/CatalinaModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/CatalinaModifier.java deleted file mode 100644 index 5490bb671424..000000000000 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/CatalinaModifier.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.nhn.pinpoint.profiler.modifier.tomcat; - -import java.security.ProtectionDomain; - -import com.nhn.pinpoint.bootstrap.Agent; -import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; -import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentClass; -import com.nhn.pinpoint.profiler.modifier.AbstractModifier; -import com.nhn.pinpoint.profiler.modifier.tomcat.interceptor.CatalinaAwaitInterceptor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Tomcat startup정보를 Pinpoint서버로 전송하는 코드를 호출하기위한 modifier - * - * @author netspider - */ -public class CatalinaModifier extends AbstractModifier { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public CatalinaModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } - - public String getTargetClass() { - return "org/apache/catalina/startup/Catalina"; - } - - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } - return changeMethod(javassistClassName, classFileBuffer); - } - - public byte[] changeMethod(String javassistClassName, byte[] classfileBuffer) { - try { - /** - * Tomcat startup완료되면 Catalina.await()을 호출하고 stop되기를 기다린다. 이 때 - * await하기 전에 서버가 시작되면서 수집된 WAS정보를 Pinpoint 서버로 전송한다. - */ - InstrumentClass aClass = this.byteCodeInstrumentor.getClass(javassistClassName); - - CatalinaAwaitInterceptor catalinaAwaitInterceptor = new CatalinaAwaitInterceptor(agent); - aClass.addInterceptor("await", null, catalinaAwaitInterceptor); - -// // Tomcat 7 -// if (aClass.hasDeclaredMethod("start", null) && aClass.hasDeclaredMethod("stop", null)) { -// LifeCycleEventListener lifeCycleEventListener = new LifeCycleEventListener(agent); -// aClass.addInterceptor("start", null, new CatalinaStartInterceptor(lifeCycleEventListener)); -// aClass.addInterceptor("stop", null, new CatalinaStopInterceptor(lifeCycleEventListener)); -// } - - if (this.logger.isInfoEnabled()) { - this.logger.info("{} class is converted.", javassistClassName); - } - - return aClass.toBytecode(); - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn(e.getMessage(), e); - } - } - return null; - } -} \ No newline at end of file diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardServiceModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardServiceModifier.java new file mode 100644 index 000000000000..ac82a7865688 --- /dev/null +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardServiceModifier.java @@ -0,0 +1,72 @@ +package com.nhn.pinpoint.profiler.modifier.tomcat; + +import java.security.ProtectionDomain; + +import com.nhn.pinpoint.bootstrap.Agent; +import com.nhn.pinpoint.bootstrap.interceptor.Interceptor; +import com.nhn.pinpoint.profiler.LifeCycleEventListener; +import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; +import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentClass; +import com.nhn.pinpoint.profiler.modifier.AbstractModifier; +import com.nhn.pinpoint.profiler.modifier.tomcat.interceptor.StandardServiceStartInterceptor; +import com.nhn.pinpoint.profiler.modifier.tomcat.interceptor.StandardServiceStopInterceptor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author cowboy93, netspider + * @author hyungil.jeong + */ +public class StandardServiceModifier extends AbstractModifier { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public StandardServiceModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } + + public String getTargetClass() { + return "org/apache/catalina/core/StandardService"; + } + + @Override + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifying. {}", javassistClassName); + } +// byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); + + try { + InstrumentClass standardService = byteCodeInstrumentor.getClass(javassistClassName); + + LifeCycleEventListener lifeCycleEventListener = new LifeCycleEventListener(agent); + Interceptor standardServiceStartInterceptor = new StandardServiceStartInterceptor(lifeCycleEventListener); + Interceptor standardServiceStopInterceptor = new StandardServiceStopInterceptor(lifeCycleEventListener); + + boolean isHooked = false; + // Tomcat 6 - org.apache.catalina.core.StandardService.start(), stop() + if (isHooked = (standardService.hasDeclaredMethod("start", null) && standardService.hasDeclaredMethod("stop", null))) { + standardService.addInterceptor("start", null, standardServiceStartInterceptor); + standardService.addInterceptor("stop", null, standardServiceStopInterceptor); + } + // Tomcat 7, 8 - org.apache.catalina.core.StandardService.startInternal(), stopInternal() + else if (isHooked = (standardService.hasDeclaredMethod("startInternal", null) && standardService.hasDeclaredMethod("stopInternal", null))) { + standardService.addInterceptor("startInternal", null, standardServiceStartInterceptor); + standardService.addInterceptor("stopInternal", null, standardServiceStopInterceptor); + } + + if (isHooked) { + logger.info("{} class is converted.", javassistClassName); + } else { + logger.warn("{} class not converted - start() or startInternal() method not found.", javassistClassName); + } + return standardService.toBytecode(); + } catch (Exception e) { + if (logger.isWarnEnabled()) { + logger.warn("modify fail. Cause:" + e.getMessage(), e); + } + } + return null; + } +} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/TomcatStandardServiceModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/TomcatStandardServiceModifier.java deleted file mode 100644 index 800f398bf954..000000000000 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/TomcatStandardServiceModifier.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.nhn.pinpoint.profiler.modifier.tomcat; - -import java.security.ProtectionDomain; - -import com.nhn.pinpoint.bootstrap.Agent; -import com.nhn.pinpoint.profiler.LifeCycleEventListener; -import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; -import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentClass; -import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentException; -import com.nhn.pinpoint.profiler.modifier.tomcat.interceptor.StandardServiceStartInterceptor; -import com.nhn.pinpoint.profiler.modifier.tomcat.interceptor.StandardServiceStopInterceptor; - -import com.nhn.pinpoint.profiler.modifier.AbstractModifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * When org.apache.catalina.core.StandardService class is loaded in ClassLoader, - * this class modifies methods. - * - * @author cowboy93, netspider - */ -public class TomcatStandardServiceModifier extends AbstractModifier { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - - public TomcatStandardServiceModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } - - public String getTargetClass() { - return "org/apache/catalina/core/StandardService"; - } - - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } - byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); - - try { - InstrumentClass standardService = byteCodeInstrumentor.getClass(javassistClassName); - - LifeCycleEventListener lifeCycleEventListener = new LifeCycleEventListener(agent); - - // Tomcat 6 - if (standardService.hasDeclaredMethod("start", null) && standardService.hasDeclaredMethod("stop", null)) { - standardService.addInterceptor("start", null, new StandardServiceStartInterceptor(lifeCycleEventListener)); - standardService.addInterceptor("stop", null, new StandardServiceStopInterceptor(lifeCycleEventListener)); - } - // Tomcat 7 - else if (standardService.hasDeclaredMethod("startInternal", null) && standardService.hasDeclaredMethod("stopInternal", null)) { - standardService.addInterceptor("startInternal", null, new StandardServiceStartInterceptor(lifeCycleEventListener)); - standardService.addInterceptor("stopInternal", null, new StandardServiceStopInterceptor(lifeCycleEventListener)); - } - - return standardService.toBytecode(); - } catch (InstrumentException e) { - logger.warn("modify fail. Cause:" + e.getMessage(), e); - return null; - } - } -} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaAwaitInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaAwaitInterceptor.java deleted file mode 100644 index 0f1a01a18fc1..000000000000 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaAwaitInterceptor.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.nhn.pinpoint.profiler.modifier.tomcat.interceptor; - -import com.nhn.pinpoint.bootstrap.interceptor.SimpleAroundInterceptor; -import com.nhn.pinpoint.bootstrap.logging.PLogger; -import com.nhn.pinpoint.bootstrap.logging.PLoggerFactory; - -import com.nhn.pinpoint.bootstrap.Agent; - -/** - * @author emeroad - */ -public class CatalinaAwaitInterceptor implements SimpleAroundInterceptor { - - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); - private final boolean isDebug = logger.isDebugEnabled(); - - private Agent agent; - - public CatalinaAwaitInterceptor(Agent agent) { - if (agent == null) { - throw new IllegalArgumentException("agent must not be null"); - } - this.agent = agent; - } - - @Override - public void before(Object target, Object[] args) { - if (isDebug) { - logger.beforeInterceptor(target, args); - } - agent.started(); - // agent.sendStartupInfo(); - } - - @Override - public void after(Object target, Object[] args, Object result, Throwable throwable) { - - } -} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaStartInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaStartInterceptor.java deleted file mode 100644 index 0bb410daf060..000000000000 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaStartInterceptor.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.nhn.pinpoint.profiler.modifier.tomcat.interceptor; - -import com.nhn.pinpoint.bootstrap.interceptor.SimpleAroundInterceptor; -import com.nhn.pinpoint.bootstrap.logging.PLogger; -import com.nhn.pinpoint.bootstrap.logging.PLoggerFactory; - -import com.nhn.pinpoint.profiler.LifeCycleEventListener; - -/** - * @author emeroad - */ -public class CatalinaStartInterceptor implements SimpleAroundInterceptor { - - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); - private final boolean isDebug = logger.isDebugEnabled(); - - private LifeCycleEventListener lifeCycleEventListener; - - public CatalinaStartInterceptor(LifeCycleEventListener lifeCycleEventListener) { - this.lifeCycleEventListener = lifeCycleEventListener; - } - - @Override - public void before(Object target, Object[] args) { - } - - @Override - public void after(Object target, Object[] args, Object result, Throwable throwable) { - if (isDebug) { - logger.afterInterceptor(target, args, result, throwable); - } - // if (!InterceptorUtils.isSuccess(result)) { - // return; - // } - lifeCycleEventListener.start(); - } -} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaStopInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaStopInterceptor.java deleted file mode 100644 index 18ca29499a5c..000000000000 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/CatalinaStopInterceptor.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.nhn.pinpoint.profiler.modifier.tomcat.interceptor; - -import com.nhn.pinpoint.bootstrap.interceptor.SimpleAroundInterceptor; -import com.nhn.pinpoint.bootstrap.logging.PLogger; -import com.nhn.pinpoint.bootstrap.logging.PLoggerFactory; -import com.nhn.pinpoint.profiler.util.StackTraceUtil; - -import com.nhn.pinpoint.profiler.LifeCycleEventListener; - -/** - * @author emeroad - */ -public class CatalinaStopInterceptor implements SimpleAroundInterceptor { - - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); - private final boolean isDebug = logger.isDebugEnabled(); - - private LifeCycleEventListener lifeCycleEventListener; - - public CatalinaStopInterceptor(LifeCycleEventListener lifeCycleEventListener) { - this.lifeCycleEventListener = lifeCycleEventListener; - } - - @Override - public void before(Object target, Object[] args) { - System.out.println("TOMCAT-STOP"); - StackTraceUtil.printCurrentStackTrace(); - } - - @Override - public void after(Object target, Object[] args, Object result, Throwable throwable) { - if (isDebug) { - logger.afterInterceptor(target, args, result, throwable); - } - // TODO 시작이 실패했을때 stop이 불러 지는가? - // if (!InterceptorUtils.isSuccess(result)) { - // return; - // } - lifeCycleEventListener.stop(); - } -} From 9f6939c285a890df3f8ca63a9823d2686abc1811 Mon Sep 17 00:00:00 2001 From: Woonduk Kang Date: Thu, 18 Sep 2014 18:38:40 +0900 Subject: [PATCH 10/18] [#10] support jtds driver(ms sqlserver) --- .../bootstrap/config/ProfilerConfig.java | 170 ++++++++++-------- pom.xml | 10 +- profiler/pom.xml | 5 + .../modifier/DefaultModifierRegistry.java | 27 +-- .../profiler/modifier/db/JDBCUrlParser.java | 137 ++------------ .../profiler/modifier/db/StringMaker.java | 15 +- .../db/cubrid/CubridResultSetModifier.java | 16 +- .../modifier/db/interceptor/JDBCScope.java | 11 -- .../db/jtds/Jdbc2ConnectionModifier.java | 19 ++ .../db/jtds/Jdbc4_1ConnectionModifier.java | 19 ++ .../db/jtds/JtdsConnectionModifier.java | 102 +++++++++++ .../db/jtds/JtdsConnectionStringParser.java | 62 +++++++ .../modifier/db/jtds/JtdsDriverModifier.java | 58 ++++++ .../jtds/JtdsPreparedStatementModifier.java | 100 +++++++++++ .../JtdsResultSetModifier.java} | 25 +-- .../profiler/modifier/db/jtds/JtdsScope.java | 8 + .../db/jtds/JtdsStatementModifier.java | 65 +++++++ .../db/mssql/MSSQLConnectionModifier.java | 52 ------ .../mssql/MSSQLPreparedStatementModifier.java | 54 ------ .../db/mssql/MSSQLStatementModifier.java | 49 ----- .../db/mysql/MySQLResultSetModifier.java | 19 +- .../oracle/OracleConnectionStringParser.java | 105 +++++++++++ .../db/oracle/OracleResultSetModifier.java | 19 +- .../src/main/resources-dev/pinpoint.config | 7 +- .../src/main/resources-local/pinpoint.config | 13 +- .../main/resources-release/pinpoint.config | 7 +- .../src/main/resources-test/pinpoint.config | 9 +- .../jtds/JtdsConnectionStringParserTest.java | 117 ++++++++++++ 28 files changed, 837 insertions(+), 463 deletions(-) delete mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/JDBCScope.java create mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/Jdbc2ConnectionModifier.java create mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/Jdbc4_1ConnectionModifier.java create mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionModifier.java create mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionStringParser.java create mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsDriverModifier.java create mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsPreparedStatementModifier.java rename profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/{mssql/MSSQLResultSetModifier.java => jtds/JtdsResultSetModifier.java} (50%) create mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsScope.java create mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsStatementModifier.java delete mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLConnectionModifier.java delete mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLPreparedStatementModifier.java delete mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLStatementModifier.java create mode 100644 profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/oracle/OracleConnectionStringParser.java create mode 100644 profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionStringParserTest.java diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java index ec079d4fb410..436ff05bd46d 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java @@ -44,7 +44,10 @@ public class ProfilerConfig { private boolean jdbcProfileMySqlCommit = false; private boolean jdbcProfileMySqlRollback = false; - private boolean jdbcProfileMsSql = true; + private boolean jdbcProfileJtds = true; + private boolean jdbcProfileJtdsSetAutoCommit = false; + private boolean jdbcProfileJtdsCommit = false; + private boolean jdbcProfileJtdsRollback = false; private boolean jdbcProfileOracle = true; private boolean jdbcProfileOracleSetAutoCommit = false; @@ -250,10 +253,22 @@ public boolean isJdbcProfileMySqlRollback() { } // mysql end----------------------------------------------------- - public boolean isJdbcProfileMsSql() { - return jdbcProfileMsSql; + public boolean isJdbcProfileJtds() { + return jdbcProfileJtds; } + public boolean isJdbcProfileJtdsSetAutoCommit() { + return jdbcProfileJtdsSetAutoCommit; + } + + public boolean isJdbcProfileJtdsCommit() { + return jdbcProfileJtdsCommit; + } + + public boolean isJdbcProfileJtdsRollback() { + return jdbcProfileJtdsRollback; + } + // oracle start ----------------------------------------------------- public boolean isJdbcProfileOracle() { return jdbcProfileOracle; @@ -506,7 +521,10 @@ private void readPropertyValues(Properties prop) { this.jdbcProfileMySqlRollback = readBoolean(prop, "profiler.jdbc.mysql.rollback", false); - this.jdbcProfileMsSql = readBoolean(prop, "profiler.jdbc.mssql", true); + this.jdbcProfileJtds = readBoolean(prop, "profiler.jdbc.jtds", true); + this.jdbcProfileJtdsSetAutoCommit = readBoolean(prop, "profiler.jdbc.jtds.setautocommit", false); + this.jdbcProfileJtdsCommit = readBoolean(prop, "profiler.jdbc.jtds.commit", false); + this.jdbcProfileJtdsRollback = readBoolean(prop, "profiler.jdbc.jtds.rollback", false); this.jdbcProfileOracle = readBoolean(prop, "profiler.jdbc.oracle", true); @@ -692,81 +710,85 @@ private boolean readBoolean(Properties prop, String propertyName, boolean defaul } + + @Override public String toString() { - final StringBuilder sb = new StringBuilder(512); - sb.append("ProfilerConfig{"); + final StringBuilder sb = new StringBuilder("ProfilerConfig{"); sb.append("profileEnable=").append(profileEnable); - sb.append("\n collectorServerIp='").append(collectorServerIp).append('\''); - sb.append("\n collectorUdpSpanServerPort=").append(collectorUdpSpanServerPort); - sb.append("\n collectorUdpServerPort=").append(collectorUdpServerPort); - sb.append("\n collectorTcpServerPort=").append(collectorTcpServerPort); - sb.append("\n spanDataSenderWriteQueueSize=").append(spanDataSenderWriteQueueSize); - sb.append("\n spanDataSenderSocketSendBufferSize=").append(spanDataSenderSocketSendBufferSize); - sb.append("\n spanDataSenderSocketTimeout=").append(spanDataSenderSocketTimeout); - sb.append("\n statDataSenderWriteQueueSize=").append(statDataSenderWriteQueueSize); - sb.append("\n statDataSenderSocketSendBufferSize=").append(statDataSenderSocketSendBufferSize); - sb.append("\n statDataSenderSocketTimeout=").append(statDataSenderSocketTimeout); - sb.append("\n tcpCommandAcceptEnable=").append(tcpDataSenderCommandAcceptEnable); - sb.append("\n jdbcSqlCacheSize=").append(jdbcSqlCacheSize); - sb.append("\n jdbcProfile=").append(jdbcProfile); - sb.append("\n jdbcProfileMySql=").append(jdbcProfileMySql); - sb.append("\n jdbcProfileMySqlSetAutoCommit=").append(jdbcProfileMySqlSetAutoCommit); - sb.append("\n jdbcProfileMySqlCommit=").append(jdbcProfileMySqlCommit); - sb.append("\n jdbcProfileMySqlRollback=").append(jdbcProfileMySqlRollback); - sb.append("\n jdbcProfileMsSql=").append(jdbcProfileMsSql); - sb.append("\n jdbcProfileOracle=").append(jdbcProfileOracle); - sb.append("\n jdbcProfileOracleSetAutoCommit=").append(jdbcProfileOracleSetAutoCommit); - sb.append("\n jdbcProfileOracleCommit=").append(jdbcProfileOracleCommit); - sb.append("\n jdbcProfileOracleRollback=").append(jdbcProfileOracleRollback); - sb.append("\n jdbcProfileCubrid=").append(jdbcProfileCubrid); - sb.append("\n jdbcProfileCubridSetAutoCommit=").append(jdbcProfileCubridSetAutoCommit); - sb.append("\n jdbcProfileCubridCommit=").append(jdbcProfileCubridCommit); - sb.append("\n jdbcProfileCubridRollback=").append(jdbcProfileCubridRollback); - sb.append("\n jdbcProfileDbcp=").append(jdbcProfileDbcp); - sb.append("\n jdbcProfileDbcpConnectionClose=").append(jdbcProfileDbcpConnectionClose); - sb.append("\n arucs=").append(arucs); - sb.append("\n arucsKeyTrace=").append(arucsKeyTrace); - sb.append("\n memcached=").append(memcached); - sb.append("\n memcachedKeyTrace=").append(memcachedKeyTrace); - sb.append("\n ibatis=").append(ibatis); - sb.append("\n mybatis=").append(mybatis); - sb.append("\n apacheHttpClient4Profile=").append(apacheHttpClient4Profile); - sb.append("\n apacheHttpClient4ProfileCookie=").append(apacheHttpClient4ProfileCookie); - sb.append("\n apacheHttpClient4ProfileCookieDumpType=").append(apacheHttpClient4ProfileCookieDumpType); - sb.append("\n apacheHttpClient4ProfileCookieSamplingRate=").append(apacheHttpClient4ProfileCookieSamplingRate); - sb.append("\n apacheHttpClient4ProfileEntity=").append(apacheHttpClient4ProfileEntity); - sb.append("\n apacheHttpClient4ProfileEntityDumpType=").append(apacheHttpClient4ProfileEntityDumpType); - sb.append("\n apacheHttpClient4ProfileEntitySamplingRate=").append(apacheHttpClient4ProfileEntitySamplingRate); - sb.append("\n apacheNIOHttpClient4Profile=").append(apacheNIOHttpClient4Profile); - sb.append("\n ningAsyncHttpClientProfile=").append(ningAsyncHttpClientProfile); - sb.append("\n ningAsyncHttpClientProfileCookie=").append(ningAsyncHttpClientProfileCookie); - sb.append("\n ningAsyncHttpClientProfileCookieDumpType=").append(ningAsyncHttpClientProfileCookieDumpType); - sb.append("\n ningAsyncHttpClientProfileCookieDumpSize=").append(ningAsyncHttpClientProfileCookieDumpSize); - sb.append("\n ningAsyncHttpClientProfileCookieSamplingRate=").append(ningAsyncHttpClientProfileCookieSamplingRate); - sb.append("\n ningAsyncHttpClientProfileEntity=").append(ningAsyncHttpClientProfileEntity); - sb.append("\n ningAsyncHttpClientProfileEntityDumpType=").append(ningAsyncHttpClientProfileEntityDumpType); - sb.append("\n ningAsyncHttpClientProfileEntityDumpSize=").append(ningAsyncHttpClientProfileEntityDumpSize); - sb.append("\n ningAsyncHttpClientProfileEntitySamplingRate=").append(ningAsyncHttpClientProfileEntitySamplingRate); - sb.append("\n ningAsyncHttpClientProfileParam=").append(ningAsyncHttpClientProfileParam); - sb.append("\n ningAsyncHttpClientProfileParamDumpType=").append(ningAsyncHttpClientProfileParamDumpType); - sb.append("\n ningAsyncHttpClientProfileParamDumpSize=").append(ningAsyncHttpClientProfileParamDumpSize); - sb.append("\n ningAsyncHttpClientProfileParamSamplingRate=").append(ningAsyncHttpClientProfileParamSamplingRate); - sb.append("\n lineGameNettyParamDumpSize=").append(lineGameNettyParamDumpSize); - sb.append("\n lineGameNettyEntityDumpSize=").append(lineGameNettyEntityDumpSize); - sb.append("\n samplingEnable=").append(samplingEnable); - sb.append("\n samplingRate=").append(samplingRate); - sb.append("\n ioBufferingEnable=").append(ioBufferingEnable); - sb.append("\n ioBufferingBufferSize=").append(ioBufferingBufferSize); - sb.append("\n profileJvmCollectInterval=").append(profileJvmCollectInterval); - sb.append("\n profileInclude=").append(profileInclude); - sb.append("\n profileIncludeSub=").append(profileIncludeSub); - sb.append("\n heartbeatInterval=").append(heartbeatInterval); - sb.append("\n applicationServerType=").append(applicationServerType); + sb.append(", collectorServerIp='").append(collectorServerIp).append('\''); + sb.append(", collectorUdpSpanServerPort=").append(collectorUdpSpanServerPort); + sb.append(", collectorUdpServerPort=").append(collectorUdpServerPort); + sb.append(", collectorTcpServerPort=").append(collectorTcpServerPort); + sb.append(", spanDataSenderWriteQueueSize=").append(spanDataSenderWriteQueueSize); + sb.append(", spanDataSenderSocketSendBufferSize=").append(spanDataSenderSocketSendBufferSize); + sb.append(", spanDataSenderSocketTimeout=").append(spanDataSenderSocketTimeout); + sb.append(", statDataSenderWriteQueueSize=").append(statDataSenderWriteQueueSize); + sb.append(", statDataSenderSocketSendBufferSize=").append(statDataSenderSocketSendBufferSize); + sb.append(", statDataSenderSocketTimeout=").append(statDataSenderSocketTimeout); + sb.append(", tcpDataSenderCommandAcceptEnable=").append(tcpDataSenderCommandAcceptEnable); + sb.append(", jdbcSqlCacheSize=").append(jdbcSqlCacheSize); + sb.append(", jdbcMaxSqlBindValueSize=").append(jdbcMaxSqlBindValueSize); + sb.append(", jdbcProfile=").append(jdbcProfile); + sb.append(", jdbcProfileMySql=").append(jdbcProfileMySql); + sb.append(", jdbcProfileMySqlSetAutoCommit=").append(jdbcProfileMySqlSetAutoCommit); + sb.append(", jdbcProfileMySqlCommit=").append(jdbcProfileMySqlCommit); + sb.append(", jdbcProfileMySqlRollback=").append(jdbcProfileMySqlRollback); + sb.append(", jdbcProfileJtds=").append(jdbcProfileJtds); + sb.append(", jdbcProfileJtdsSetAutoCommit=").append(jdbcProfileJtdsSetAutoCommit); + sb.append(", jdbcProfileJtdsCommit=").append(jdbcProfileJtdsCommit); + sb.append(", jdbcProfileJtdsRollback=").append(jdbcProfileJtdsRollback); + sb.append(", jdbcProfileOracle=").append(jdbcProfileOracle); + sb.append(", jdbcProfileOracleSetAutoCommit=").append(jdbcProfileOracleSetAutoCommit); + sb.append(", jdbcProfileOracleCommit=").append(jdbcProfileOracleCommit); + sb.append(", jdbcProfileOracleRollback=").append(jdbcProfileOracleRollback); + sb.append(", jdbcProfileCubrid=").append(jdbcProfileCubrid); + sb.append(", jdbcProfileCubridSetAutoCommit=").append(jdbcProfileCubridSetAutoCommit); + sb.append(", jdbcProfileCubridCommit=").append(jdbcProfileCubridCommit); + sb.append(", jdbcProfileCubridRollback=").append(jdbcProfileCubridRollback); + sb.append(", jdbcProfileDbcp=").append(jdbcProfileDbcp); + sb.append(", jdbcProfileDbcpConnectionClose=").append(jdbcProfileDbcpConnectionClose); + sb.append(", arucs=").append(arucs); + sb.append(", arucsKeyTrace=").append(arucsKeyTrace); + sb.append(", memcached=").append(memcached); + sb.append(", memcachedKeyTrace=").append(memcachedKeyTrace); + sb.append(", ibatis=").append(ibatis); + sb.append(", mybatis=").append(mybatis); + sb.append(", apacheHttpClient4Profile=").append(apacheHttpClient4Profile); + sb.append(", apacheHttpClient4ProfileCookie=").append(apacheHttpClient4ProfileCookie); + sb.append(", apacheHttpClient4ProfileCookieDumpType=").append(apacheHttpClient4ProfileCookieDumpType); + sb.append(", apacheHttpClient4ProfileCookieSamplingRate=").append(apacheHttpClient4ProfileCookieSamplingRate); + sb.append(", apacheHttpClient4ProfileEntity=").append(apacheHttpClient4ProfileEntity); + sb.append(", apacheHttpClient4ProfileEntityDumpType=").append(apacheHttpClient4ProfileEntityDumpType); + sb.append(", apacheHttpClient4ProfileEntitySamplingRate=").append(apacheHttpClient4ProfileEntitySamplingRate); + sb.append(", apacheNIOHttpClient4Profile=").append(apacheNIOHttpClient4Profile); + sb.append(", ningAsyncHttpClientProfile=").append(ningAsyncHttpClientProfile); + sb.append(", ningAsyncHttpClientProfileCookie=").append(ningAsyncHttpClientProfileCookie); + sb.append(", ningAsyncHttpClientProfileCookieDumpType=").append(ningAsyncHttpClientProfileCookieDumpType); + sb.append(", ningAsyncHttpClientProfileCookieDumpSize=").append(ningAsyncHttpClientProfileCookieDumpSize); + sb.append(", ningAsyncHttpClientProfileCookieSamplingRate=").append(ningAsyncHttpClientProfileCookieSamplingRate); + sb.append(", ningAsyncHttpClientProfileEntity=").append(ningAsyncHttpClientProfileEntity); + sb.append(", ningAsyncHttpClientProfileEntityDumpType=").append(ningAsyncHttpClientProfileEntityDumpType); + sb.append(", ningAsyncHttpClientProfileEntityDumpSize=").append(ningAsyncHttpClientProfileEntityDumpSize); + sb.append(", ningAsyncHttpClientProfileEntitySamplingRate=").append(ningAsyncHttpClientProfileEntitySamplingRate); + sb.append(", ningAsyncHttpClientProfileParam=").append(ningAsyncHttpClientProfileParam); + sb.append(", ningAsyncHttpClientProfileParamDumpType=").append(ningAsyncHttpClientProfileParamDumpType); + sb.append(", ningAsyncHttpClientProfileParamDumpSize=").append(ningAsyncHttpClientProfileParamDumpSize); + sb.append(", ningAsyncHttpClientProfileParamSamplingRate=").append(ningAsyncHttpClientProfileParamSamplingRate); + sb.append(", lineGameNettyParamDumpSize=").append(lineGameNettyParamDumpSize); + sb.append(", lineGameNettyEntityDumpSize=").append(lineGameNettyEntityDumpSize); + sb.append(", samplingEnable=").append(samplingEnable); + sb.append(", samplingRate=").append(samplingRate); + sb.append(", ioBufferingEnable=").append(ioBufferingEnable); + sb.append(", ioBufferingBufferSize=").append(ioBufferingBufferSize); + sb.append(", profileJvmCollectInterval=").append(profileJvmCollectInterval); + sb.append(", profileInclude=").append(profileInclude); + sb.append(", profileIncludeSub=").append(profileIncludeSub); + sb.append(", DEFAULT_HEART_BEAT_INTERVAL=").append(DEFAULT_HEART_BEAT_INTERVAL); + sb.append(", heartbeatInterval=").append(heartbeatInterval); + sb.append(", applicationServerType=").append(applicationServerType); sb.append('}'); return sb.toString(); } - - } diff --git a/pom.xml b/pom.xml index a7780bec0ff1..16a19d823bb3 100644 --- a/pom.xml +++ b/pom.xml @@ -389,6 +389,11 @@ ojdbc6 11.1.0.7.0
+ + net.sourceforge.jtds + jtds + 1.2.5 + com.ning @@ -470,11 +475,6 @@ commons-lang3 3.3.2 - - net.sourceforge.jtds - jtds - 1.2.4 - commons-fileupload commons-fileupload diff --git a/profiler/pom.xml b/profiler/pom.xml index 28458ecb1703..e18678bb1c37 100644 --- a/profiler/pom.xml +++ b/profiler/pom.xml @@ -162,6 +162,11 @@ ojdbc6 provided + + net.sourceforge.jtds + jtds + provided + com.nhncorp.lucy diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java index 96ef673d031b..49c312d100c8 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java @@ -38,10 +38,7 @@ import com.nhn.pinpoint.profiler.modifier.db.cubrid.CubridStatementModifier; import com.nhn.pinpoint.profiler.modifier.db.dbcp.DBCPBasicDataSourceModifier; import com.nhn.pinpoint.profiler.modifier.db.dbcp.DBCPPoolGuardConnectionWrapperModifier; -import com.nhn.pinpoint.profiler.modifier.db.mssql.MSSQLConnectionModifier; -import com.nhn.pinpoint.profiler.modifier.db.mssql.MSSQLPreparedStatementModifier; -import com.nhn.pinpoint.profiler.modifier.db.mssql.MSSQLResultSetModifier; -import com.nhn.pinpoint.profiler.modifier.db.mssql.MSSQLStatementModifier; +import com.nhn.pinpoint.profiler.modifier.db.jtds.*; import com.nhn.pinpoint.profiler.modifier.db.mysql.MySQLConnectionImplModifier; import com.nhn.pinpoint.profiler.modifier.db.mysql.MySQLConnectionModifier; import com.nhn.pinpoint.profiler.modifier.db.mysql.MySQLNonRegisteringDriverModifier; @@ -223,9 +220,8 @@ public void addJdbcModifier() { addMySqlDriver(); } - if (profilerConfig.isJdbcProfileMsSql()) { -// 아직 개발이 안됨 -// addMsSqlDriver(); + if (profilerConfig.isJdbcProfileJtds()) { + addJtdsDriver(); } if (profilerConfig.isJdbcProfileOracle()) { @@ -269,18 +265,23 @@ private void addMySqlDriver() { // addModifier(mysqlResultSetModifier); } - private void addMsSqlDriver() { + private void addJtdsDriver() { + JtdsDriverModifier jtdsDriverModifier = new JtdsDriverModifier(byteCodeInstrumentor, agent); + addModifier(jtdsDriverModifier); - Modifier mssqlConnectionModifier = new MSSQLConnectionModifier(byteCodeInstrumentor, agent); - addModifier(mssqlConnectionModifier); + Modifier jdbc2ConnectionModifier = new Jdbc2ConnectionModifier(byteCodeInstrumentor, agent); + addModifier(jdbc2ConnectionModifier); - Modifier mssqlStatementModifier = new MSSQLStatementModifier(byteCodeInstrumentor, agent); + Modifier jdbc4_1ConnectionModifier = new Jdbc4_1ConnectionModifier(byteCodeInstrumentor, agent); + addModifier(jdbc4_1ConnectionModifier); + + Modifier mssqlStatementModifier = new JtdsStatementModifier(byteCodeInstrumentor, agent); addModifier(mssqlStatementModifier); - Modifier mssqlPreparedStatementModifier = new MSSQLPreparedStatementModifier(byteCodeInstrumentor, agent); + Modifier mssqlPreparedStatementModifier = new JtdsPreparedStatementModifier(byteCodeInstrumentor, agent); addModifier(mssqlPreparedStatementModifier); - Modifier mssqlResultSetModifier = new MSSQLResultSetModifier(byteCodeInstrumentor, agent); + Modifier mssqlResultSetModifier = new JtdsResultSetModifier(byteCodeInstrumentor, agent); addModifier(mssqlResultSetModifier); } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/JDBCUrlParser.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/JDBCUrlParser.java index 87b26e1dc0f9..84d1422bc098 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/JDBCUrlParser.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/JDBCUrlParser.java @@ -3,7 +3,9 @@ import com.nhn.pinpoint.common.ServiceType; import com.nhn.pinpoint.bootstrap.context.DatabaseInfo; import com.nhn.pinpoint.profiler.modifier.db.cubrid.CubridConnectionStringParser; +import com.nhn.pinpoint.profiler.modifier.db.jtds.JtdsConnectionStringParser; import com.nhn.pinpoint.profiler.modifier.db.mysql.MySqlConnectionStringParser; +import com.nhn.pinpoint.profiler.modifier.db.oracle.OracleConnectionStringParser; import com.nhn.pinpoint.profiler.modifier.db.oracle.parser.Description; import com.nhn.pinpoint.profiler.modifier.db.oracle.parser.KeyValue; import com.nhn.pinpoint.profiler.modifier.db.oracle.parser.OracleConnectionStringException; @@ -23,7 +25,7 @@ public class JDBCUrlParser { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final ConcurrentMap cache = new ConcurrentHashMap(); - + //http://www.petefreitag.com/articles/jdbc_urls/ public DatabaseInfo parse(String url) { final DatabaseInfo hit = cache.get(url); if (hit != null) { @@ -37,52 +39,6 @@ public DatabaseInfo parse(String url) { return old; } return databaseInfo; - -// else if (url.indexOf("jdbc:oracle") >= 0) { -// maker.lower().after("jdbc:oracle:").after(':'); -// info.type = TYPE.ORACLE; -// String description = maker.after('@').value().trim(); -// -// if (description.startsWith("(")) { -// Matcher matcher = oracleRAC.matcher(description); -// -// if (matcher.matches()) { -// info.host = matcher.group(1); -// info.port = matcher.group(2); -// info.databaseId = matcher.group(3); -// } else { -// info.databaseId = "ParsingFailed[" + System.currentTimeMillis() + ']'; -// } -// } else { -// info.host = maker.before(':').value(); -// info.port = maker.next().after(':').before(':').value(); -// info.databaseId = maker.next().afterLast(':').value(); -// } -// } else if (url.indexOf("jdbc:sqlserver") >= 0) { -// maker.lower().after("jdbc:sqlserver:"); -// info.type = TYPE.MSSQL; -// info.host = maker.after("//").before(';').value(); -// info.port = maker.currentTraceClear().after("port=").before(';').value(); -// info.databaseId = maker.currentTraceClear().after("databasename=").before(';').value(); -// } else if (url.indexOf("jdbc:jtds:sqlserver") >= 0) { -// maker.lower().after("jdbc:jtds:sqlserver:"); -// info.type = TYPE.MSSQL; -// info.host = maker.after("//").beforeLast('/').beforeLast(':').value(); -// info.port = maker.next().after(':').beforeLast('/').value(); -// info.databaseId = maker.next().afterLast('/').before(';').value(); -// } else if (url.indexOf("jdbc:cubrid") >= 0) { -// maker.lower().after("jdbc:cubrid"); -// info.type = TYPE.CUBRID; -// info.host = maker.after(':').before(':').value(); -// info.port = maker.next().after(':').before(':').value(); -// info.databaseId = maker.next().after(':').before(':').value(); -// } -// if ("".equals(info.databaseId)) { -// info.databaseId = info.host; -// } - -// return info; -// return null; } private DatabaseInfo doParse(String url) { @@ -98,6 +54,10 @@ private DatabaseInfo doParse(String url) { if (driverTypeCheck(lowCaseURL, "oracle")) { return parseOracle(url); } + + if (driverTypeCheck(lowCaseURL, "jtds:sqlserver")) { + return parseJtds(url); + } if (driverTypeCheck(lowCaseURL, "cubrid")) { return parseCubrid(url); } @@ -109,87 +69,14 @@ private boolean driverTypeCheck(String lowCaseURL, String type) { return lowCaseURL.startsWith(type, jdbcNextIndex); } - // rac url. -// jdbc:oracle:thin:@(Description=(LOAD_BALANCE=on)" + -// "(ADDRESS=(PROTOCOL=TCP)(HOST=1.2.3.4) (PORT=1521))" + -// "(ADDRESS=(PROTOCOL=TCP)(HOST=1.2.3.5) (PORT=1521))" + -// "(CONNECT_DATA=(SERVICE_NAME=service)))" -// -// thin driver url -// jdbc:oracle:thin:@hostname:port:SID -// "jdbc:oracle:thin:MYWORKSPACE/qwerty@localhost:1521:XE"; -// 들여 쓰기를 통해 token을 보기 좋게 나눈경우. -// jdbc:oracle:thin: -// @( -// Description=(LOAD_BALANCE=on) -// ( -// ADDRESS=(PROTOCOL=TCP)(HOST=1.2.3.4) (PORT=1521) -// ) -// ( -// ADDRESS=(PROTOCOL=TCP)(HOST=1.2.3.5) (PORT=1521) -// ) -// ( -// CONNECT_DATA=(SERVICE_NAME=service) -// ) -// ) private DatabaseInfo parseOracle(String url) { - StringMaker maker = new StringMaker(url); - maker.after("jdbc:oracle:").after(":"); - String description = maker.after('@').value().trim(); - if (description.startsWith("(")) { - return parseNetConnectionUrl(url); - } else { - return parseSimpleUrl(url, maker); - } - } - - private DatabaseInfo parseNetConnectionUrl(String url) { - try { - // oracle new URL : rac용 - OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(url); - KeyValue keyValue = parser.parse(); - // TODO oci 드라이버 일경우의 추가 처리가 필요함. nhn말고 왠간한데는 oci를 더 많이 씀. -// parser.getDriverType(); - return createOracleDatabaseInfo(keyValue, url); - } catch (OracleConnectionStringException ex) { - logger.warn("OracleConnectionString parse error. url:{} Caused:", url, ex.getMessage(), ex); - - // 에러찍고 그냥 unknownDataBase 생성 - return createUnknownDataBase(ServiceType.ORACLE, ServiceType.ORACLE_EXECUTE_QUERY, url); - } catch (Throwable ex) { - // 나중에 좀더 정교하게 exception을 던지게 되면 OracleConnectionStringException 만 잡는것으로 바꿔야 될듯하다. - logger.warn("OracleConnectionString parse error. url:{} Caused:", url, ex.getMessage(), ex); - // 에러찍고 그냥 unknownDataBase 생성 - return createUnknownDataBase(ServiceType.ORACLE, ServiceType.ORACLE_EXECUTE_QUERY, url); - } - } - - private DefaultDatabaseInfo parseSimpleUrl(String url, StringMaker maker) { - // thin driver - // jdbc:oracle:thin:@hostname:port:SID - // "jdbc:oracle:thin:MYWORKSPACE/qwerty@localhost:1521:XE"; -// jdbc:oracle:thin:@//hostname:port/serviceName - String host = maker.before(':').value(); - String port = maker.next().after(':').before(':', '/').value(); - String databaseId = maker.next().afterLast(':', '/').value(); - - List hostList = new ArrayList(1); - hostList.add(host + ":" + port); - return new DefaultDatabaseInfo(ServiceType.ORACLE, ServiceType.ORACLE_EXECUTE_QUERY, url, url, hostList, databaseId); - } - - private DatabaseInfo createOracleDatabaseInfo(KeyValue keyValue, String url) { - - Description description = new Description(keyValue); - List jdbcHost = description.getJdbcHost(); - - return new DefaultDatabaseInfo(ServiceType.ORACLE, ServiceType.ORACLE_EXECUTE_QUERY, url, url, jdbcHost, description.getDatabaseId()); + OracleConnectionStringParser parser = new OracleConnectionStringParser(); + return parser.parse(url); } - public static DatabaseInfo createUnknownDataBase(String url) { return createUnknownDataBase(ServiceType.UNKNOWN_DB, ServiceType.UNKNOWN_DB_EXECUTE_QUERY, url); } @@ -205,6 +92,12 @@ private DatabaseInfo parseMysql(String url) { final ConnectionStringParser parser = new MySqlConnectionStringParser(); return parser.parse(url); } + + private DatabaseInfo parseJtds(String url) { + final JtdsConnectionStringParser parser = new JtdsConnectionStringParser(); + return parser.parse(url); + + } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/StringMaker.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/StringMaker.java index da02ffb6298a..9154fabb93a9 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/StringMaker.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/StringMaker.java @@ -1,7 +1,7 @@ package com.nhn.pinpoint.profiler.modifier.db; /** - * @author emeroad + * copy lucy 1.5 */ public class StringMaker { @@ -263,6 +263,19 @@ public StringMaker beforeLast(char ch) { return this; } + public StringMaker beforeLast(char ch1, char ch2) { + int index = lastIndexOf(indexing, end, ch1, ch2); + if (index < begin) { + return this; + } + + //end = index < begin ? begin : index; + //for Klocwork + + end = index; + return this; + } + /** * Before last. * diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridResultSetModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridResultSetModifier.java index 3c0e9978aab4..addb7c1df013 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridResultSetModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridResultSetModifier.java @@ -4,8 +4,6 @@ import com.nhn.pinpoint.bootstrap.Agent; import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; -import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentClass; -import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentException; import com.nhn.pinpoint.profiler.modifier.AbstractModifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,18 +27,6 @@ public byte[] modify(ClassLoader classLoader, String javassistClassName, Protect if (logger.isInfoEnabled()) { logger.info("Modifing. {}", javassistClassName); } - this.byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); - try { - InstrumentClass resultSetClass = byteCodeInstrumentor.getClass(javassistClassName); - - // DO NOTHING - - return resultSetClass.toBytecode(); - } catch (InstrumentException e) { - if (logger.isWarnEnabled()) { - logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); - } - return null; - } + return null; } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/JDBCScope.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/JDBCScope.java deleted file mode 100644 index ed91c213540c..000000000000 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/JDBCScope.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.nhn.pinpoint.profiler.modifier.db.interceptor; - -import com.nhn.pinpoint.profiler.util.DepthScope; - -/** - * @author emeroad - */ -@Deprecated -public class JDBCScope { - public static final DepthScope SCOPE = new DepthScope("JDBCScope"); -} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/Jdbc2ConnectionModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/Jdbc2ConnectionModifier.java new file mode 100644 index 000000000000..213516cda0d0 --- /dev/null +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/Jdbc2ConnectionModifier.java @@ -0,0 +1,19 @@ +package com.nhn.pinpoint.profiler.modifier.db.jtds; + +import com.nhn.pinpoint.bootstrap.Agent; +import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; + +/** + * 1.2.x -> jdk 1.5 + * @author emeroad + */ +public class Jdbc2ConnectionModifier extends JtdsConnectionModifier { + + public Jdbc2ConnectionModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } + + public String getTargetClass() { + return "net/sourceforge/jtds/jdbc/ConnectionJDBC2"; + } +} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/Jdbc4_1ConnectionModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/Jdbc4_1ConnectionModifier.java new file mode 100644 index 000000000000..d2e195e6b842 --- /dev/null +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/Jdbc4_1ConnectionModifier.java @@ -0,0 +1,19 @@ +package com.nhn.pinpoint.profiler.modifier.db.jtds; + +import com.nhn.pinpoint.bootstrap.Agent; +import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; + +/** + * 1.3.x -> jdk 1.7 + * @author emeroad + */ +public class Jdbc4_1ConnectionModifier extends JtdsConnectionModifier { + + public Jdbc4_1ConnectionModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } + + public String getTargetClass() { + return "net/sourceforge/jtds/jdbc/JtdsConnection"; + } +} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionModifier.java new file mode 100644 index 000000000000..4dc7c7fdf4ba --- /dev/null +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionModifier.java @@ -0,0 +1,102 @@ +package com.nhn.pinpoint.profiler.modifier.db.jtds; + +import com.nhn.pinpoint.bootstrap.Agent; + +import com.nhn.pinpoint.bootstrap.config.ProfilerConfig; +import com.nhn.pinpoint.bootstrap.interceptor.Interceptor; +import com.nhn.pinpoint.bootstrap.interceptor.tracevalue.DatabaseInfoTraceValue; +import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; +import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentClass; +import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentException; +import com.nhn.pinpoint.profiler.modifier.AbstractModifier; +import com.nhn.pinpoint.profiler.modifier.db.interceptor.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.security.ProtectionDomain; + +public abstract class JtdsConnectionModifier extends AbstractModifier { + + private static final String SCOPE_NAME = JtdsScope.SCOPE_NAME; + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public JtdsConnectionModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } + + + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } + this.byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); + try { + InstrumentClass jtdsConnection = byteCodeInstrumentor.getClass(javassistClassName); + + + jtdsConnection.addTraceValue(DatabaseInfoTraceValue.class); + + + Interceptor closeConnection = new ConnectionCloseInterceptor(); + jtdsConnection.addScopeInterceptor("close", null, closeConnection, SCOPE_NAME); + + + Interceptor statementCreateInterceptor1 = new StatementCreateInterceptor(); + jtdsConnection.addScopeInterceptor("createStatement", null, statementCreateInterceptor1, SCOPE_NAME); + + Interceptor statementCreateInterceptor2 = new StatementCreateInterceptor(); + jtdsConnection.addScopeInterceptor("createStatement", new String[]{"int", "int"}, statementCreateInterceptor2, SCOPE_NAME); + + Interceptor statementCreateInterceptor3 = new StatementCreateInterceptor(); + jtdsConnection.addScopeInterceptor("createStatement", new String[]{"int", "int", "int"}, statementCreateInterceptor3, SCOPE_NAME); + + + Interceptor preparedStatementCreateInterceptor1 = new PreparedStatementCreateInterceptor(); + jtdsConnection.addScopeInterceptor("prepareStatement", new String[]{"java.lang.String"}, preparedStatementCreateInterceptor1, SCOPE_NAME); + + Interceptor preparedStatementCreateInterceptor2 = new PreparedStatementCreateInterceptor(); + jtdsConnection.addScopeInterceptor("prepareStatement", new String[]{"java.lang.String", "int"}, preparedStatementCreateInterceptor2, SCOPE_NAME); + + Interceptor preparedStatementCreateInterceptor3 = new PreparedStatementCreateInterceptor(); + jtdsConnection.addScopeInterceptor("prepareStatement", new String[]{"java.lang.String", "int[]"}, preparedStatementCreateInterceptor3, SCOPE_NAME); + + Interceptor preparedStatementCreateInterceptor4 = new PreparedStatementCreateInterceptor(); + jtdsConnection.addScopeInterceptor("prepareStatement", new String[]{"java.lang.String", "java.lang.String[]"}, preparedStatementCreateInterceptor4, SCOPE_NAME); + + Interceptor preparedStatementCreateInterceptor5 = new PreparedStatementCreateInterceptor(); + jtdsConnection.addScopeInterceptor("prepareStatement", new String[]{"java.lang.String", "int", "int"}, preparedStatementCreateInterceptor5, SCOPE_NAME); + + Interceptor preparedStatementCreateInterceptor6 = new PreparedStatementCreateInterceptor(); + jtdsConnection.addScopeInterceptor("prepareStatement", new String[]{"java.lang.String", "int", "int", "int"}, preparedStatementCreateInterceptor6, SCOPE_NAME); + + final ProfilerConfig profilerConfig = agent.getProfilerConfig(); + if (profilerConfig.isJdbcProfileJtdsSetAutoCommit()) { + Interceptor setAutocommit = new TransactionSetAutoCommitInterceptor(); + jtdsConnection.addScopeInterceptor("setAutoCommit", new String[]{"boolean"}, setAutocommit, SCOPE_NAME); + } + if (profilerConfig.isJdbcProfileJtdsCommit()) { + Interceptor commit = new TransactionCommitInterceptor(); + jtdsConnection.addScopeInterceptor("commit", null, commit, SCOPE_NAME); + } + if (profilerConfig.isJdbcProfileJtdsRollback()) { + Interceptor rollback = new TransactionRollbackInterceptor(); + jtdsConnection.addScopeInterceptor("rollback", null, rollback, SCOPE_NAME); + } + + if (this.logger.isInfoEnabled()) { + this.logger.info("{} class is converted.", javassistClassName); + } + + return jtdsConnection.toBytecode(); + } catch (InstrumentException e) { + if (logger.isWarnEnabled()) { + logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); + } + return null; + } + } + + + +} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionStringParser.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionStringParser.java new file mode 100644 index 000000000000..423d8c7c091f --- /dev/null +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionStringParser.java @@ -0,0 +1,62 @@ +package com.nhn.pinpoint.profiler.modifier.db.jtds; + +import com.nhn.pinpoint.bootstrap.context.DatabaseInfo; +import com.nhn.pinpoint.common.ServiceType; +import com.nhn.pinpoint.profiler.modifier.db.ConnectionStringParser; +import com.nhn.pinpoint.profiler.modifier.db.DefaultDatabaseInfo; +import com.nhn.pinpoint.profiler.modifier.db.JDBCUrlParser; +import com.nhn.pinpoint.profiler.modifier.db.StringMaker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author emeroad + */ +public class JtdsConnectionStringParser implements ConnectionStringParser { + + public static final int DEFAULT_PORT = 1433; + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Override + public DatabaseInfo parse(String url) { + if (url == null) { + return JDBCUrlParser.createUnknownDataBase(ServiceType.MSSQL, ServiceType.MSSQL_EXECUTE_QUERY, url); + } + +// jdbc:jtds:sqlserver://10.xx.xx.xx:1433;DatabaseName=CAFECHAT;sendStringParametersAsUnicode=false;useLOBs=false;loginTimeout=3 +// jdbc:jtds:sqlserver://server[:port][/database][;property=value[;...]] +// jdbc:jtds:sqlserver://server/db;user=userName;password=password + StringMaker maker = new StringMaker(url); + + maker.lower().after("jdbc:jtds:sqlserver:"); + + StringMaker before = maker.after("//").before(';'); + final String hostAndPortAndDataBaseString = before.value(); + String databaseId = ""; + String hostAndPortString = ""; + final int databaseIdIndex = hostAndPortAndDataBaseString.indexOf('/'); + if (databaseIdIndex != -1) { + hostAndPortString = hostAndPortAndDataBaseString.substring(0, databaseIdIndex); + databaseId = hostAndPortAndDataBaseString.substring(databaseIdIndex+1, hostAndPortAndDataBaseString.length()); + } else { + hostAndPortString = hostAndPortAndDataBaseString; + } + + List hostList = new ArrayList(1); + hostList.add(hostAndPortString); + // option properties search + if (databaseId.isEmpty()) { + databaseId = maker.next().after("databasename=").before(';').value(); + } + + String normalizedUrl = maker.clear().before(";").value(); + + return new DefaultDatabaseInfo(ServiceType.MSSQL, ServiceType.MSSQL_EXECUTE_QUERY, url, normalizedUrl, hostList, databaseId); + } + + +} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsDriverModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsDriverModifier.java new file mode 100644 index 000000000000..898237306044 --- /dev/null +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsDriverModifier.java @@ -0,0 +1,58 @@ +package com.nhn.pinpoint.profiler.modifier.db.jtds; + +import com.nhn.pinpoint.bootstrap.Agent; +import com.nhn.pinpoint.bootstrap.interceptor.Interceptor; +import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; +import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentClass; +import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentException; +import com.nhn.pinpoint.profiler.modifier.AbstractModifier; +import com.nhn.pinpoint.profiler.modifier.db.interceptor.DriverConnectInterceptor; +import com.nhn.pinpoint.profiler.util.Scope; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.security.ProtectionDomain; + +/** + * @author emeroad + */ +public class JtdsDriverModifier extends AbstractModifier { + +// oracle.jdbc.driver + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public JtdsDriverModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } + + public String getTargetClass() { + return "net/sourceforge/jtds/jdbc/Driver"; + } + + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } + this.byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); + try { + InstrumentClass jtdsDriver = byteCodeInstrumentor.getClass(javassistClassName); + + final Scope scope = byteCodeInstrumentor.getScope(JtdsScope.SCOPE_NAME); + Interceptor createConnection = new DriverConnectInterceptor(scope); + String[] params = new String[]{ "java.lang.String", "java.util.Properties" }; + jtdsDriver.addInterceptor("connect", params, createConnection); + + if (logger.isInfoEnabled()) { + logger.info("{} class is converted.", javassistClassName); + } + + return jtdsDriver.toBytecode(); + } catch (InstrumentException e) { + if (logger.isWarnEnabled()) { + logger.warn(this.getClass().getSimpleName() + " modify fail. Cause:" + e.getMessage(), e); + } + return null; + } + } +} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsPreparedStatementModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsPreparedStatementModifier.java new file mode 100644 index 000000000000..66917ca0ae3e --- /dev/null +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsPreparedStatementModifier.java @@ -0,0 +1,100 @@ +package com.nhn.pinpoint.profiler.modifier.db.jtds; + +import com.nhn.pinpoint.bootstrap.Agent; +import com.nhn.pinpoint.bootstrap.interceptor.Interceptor; +import com.nhn.pinpoint.bootstrap.interceptor.tracevalue.BindValueTraceValue; +import com.nhn.pinpoint.bootstrap.interceptor.tracevalue.DatabaseInfoTraceValue; +import com.nhn.pinpoint.bootstrap.interceptor.tracevalue.ParsingResultTraceValue; +import com.nhn.pinpoint.profiler.interceptor.ScopeDelegateStaticInterceptor; +import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; +import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentClass; +import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentException; +import com.nhn.pinpoint.profiler.interceptor.bci.NotFoundInstrumentException; +import com.nhn.pinpoint.profiler.modifier.AbstractModifier; +import com.nhn.pinpoint.profiler.modifier.db.interceptor.PreparedStatementBindVariableInterceptor; +import com.nhn.pinpoint.profiler.modifier.db.interceptor.PreparedStatementExecuteQueryInterceptor; +import com.nhn.pinpoint.profiler.util.JavaAssistUtils; +import com.nhn.pinpoint.profiler.util.PreparedStatementUtils; +import com.nhn.pinpoint.profiler.util.Scope; + + +import java.lang.reflect.Method; +import java.security.ProtectionDomain; +import java.util.Arrays; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JtdsPreparedStatementModifier extends AbstractModifier { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public JtdsPreparedStatementModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } + + public String getTargetClass() { + return "net/sourceforge/jtds/jdbc/JtdsPreparedStatement"; + } + + + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } + this.byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); + try { + InstrumentClass preparedStatementClass = byteCodeInstrumentor.getClass(javassistClassName); + + Interceptor executeInterceptor = new PreparedStatementExecuteQueryInterceptor(); + preparedStatementClass.addScopeInterceptor("execute", null, executeInterceptor, JtdsScope.SCOPE_NAME); + + Interceptor executeQueryInterceptor = new PreparedStatementExecuteQueryInterceptor(); + preparedStatementClass.addScopeInterceptor("executeQuery", null, executeQueryInterceptor, JtdsScope.SCOPE_NAME); + + Interceptor executeUpdateInterceptor = new PreparedStatementExecuteQueryInterceptor(); + preparedStatementClass.addScopeInterceptor("executeUpdate", null, executeUpdateInterceptor, JtdsScope.SCOPE_NAME); + + preparedStatementClass.addTraceValue(DatabaseInfoTraceValue.class); + preparedStatementClass.addTraceValue(ParsingResultTraceValue.class); + preparedStatementClass.addTraceValue(BindValueTraceValue.class, "new java.util.HashMap();"); + + bindVariableIntercept(preparedStatementClass, classLoader, protectedDomain); + + return preparedStatementClass.toBytecode(); + } catch (InstrumentException e) { + if (logger.isWarnEnabled()) { + logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); + } + return null; + } + } + + private void bindVariableIntercept(InstrumentClass preparedStatement, ClassLoader classLoader, ProtectionDomain protectedDomain) throws InstrumentException { + List bindMethod = PreparedStatementUtils.findBindVariableSetMethod(); + final Scope scope = byteCodeInstrumentor.getScope(JtdsScope.SCOPE_NAME); + Interceptor interceptor = new ScopeDelegateStaticInterceptor(new PreparedStatementBindVariableInterceptor(), scope); + int interceptorId = -1; + for (Method method : bindMethod) { + String methodName = method.getName(); + String[] parameterType = JavaAssistUtils.getParameterType(method.getParameterTypes()); + try { + if (interceptorId == -1) { + interceptorId = preparedStatement.addInterceptor(methodName, parameterType, interceptor); + } else { + preparedStatement.reuseInterceptor(methodName, parameterType, interceptorId); + } + } catch (NotFoundInstrumentException e) { + // bind variable setter메소드를 못찾을 경우는 그냥 경고만 표시, 에러 아님. + if (logger.isDebugEnabled()) { + logger.debug("bindVariable api not found. method:{} param:{} Cause:{}", methodName, Arrays.toString(parameterType), e.getMessage()); + } + } + } + } + + + + +} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLResultSetModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsResultSetModifier.java similarity index 50% rename from profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLResultSetModifier.java rename to profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsResultSetModifier.java index 00451a75e5ef..355e27d72584 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLResultSetModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsResultSetModifier.java @@ -1,4 +1,4 @@ -package com.nhn.pinpoint.profiler.modifier.db.mssql; +package com.nhn.pinpoint.profiler.modifier.db.jtds; import com.nhn.pinpoint.bootstrap.Agent; import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; @@ -10,11 +10,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class MSSQLResultSetModifier extends AbstractModifier { +public class JtdsResultSetModifier extends AbstractModifier { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public MSSQLResultSetModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + public JtdsResultSetModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { super(byteCodeInstrumentor, agent); } @@ -26,26 +26,11 @@ public byte[] modify(ClassLoader classLoader, String javassistClassName, Protect if (logger.isInfoEnabled()) { logger.info("Modifing. {}", javassistClassName); } - this.byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); - return changeMethod(javassistClassName, classFileBuffer); - } - - private byte[] changeMethod(String javassistClassName, byte[] classfileBuffer) { - try { - CtClass cc = null; - - if (this.logger.isInfoEnabled()) { - this.logger.info("{} class is converted.", javassistClassName); - } - return null; - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn(e.getMessage(), e); - } - } return null; } + + } \ No newline at end of file diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsScope.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsScope.java new file mode 100644 index 000000000000..43a96ac96169 --- /dev/null +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsScope.java @@ -0,0 +1,8 @@ +package com.nhn.pinpoint.profiler.modifier.db.jtds; + +/** + * @author emeroad + */ +public final class JtdsScope { + public static final String SCOPE_NAME = "Jtds"; +} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsStatementModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsStatementModifier.java new file mode 100644 index 000000000000..45a466c384fb --- /dev/null +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsStatementModifier.java @@ -0,0 +1,65 @@ +package com.nhn.pinpoint.profiler.modifier.db.jtds; + +import com.nhn.pinpoint.bootstrap.Agent; +import com.nhn.pinpoint.bootstrap.interceptor.Interceptor; +import com.nhn.pinpoint.bootstrap.interceptor.tracevalue.DatabaseInfoTraceValue; +import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; +import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentClass; +import com.nhn.pinpoint.profiler.interceptor.bci.InstrumentException; +import com.nhn.pinpoint.profiler.modifier.AbstractModifier; +import com.nhn.pinpoint.profiler.modifier.db.interceptor.StatementExecuteQueryInterceptor; +import com.nhn.pinpoint.profiler.modifier.db.interceptor.StatementExecuteUpdateInterceptor; + +import java.security.ProtectionDomain; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JtdsStatementModifier extends AbstractModifier { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public JtdsStatementModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } + + public String getTargetClass() { + return "net/sourceforge/jtds/jdbc/JtdsStatement"; + } + + + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } + + byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); + + try { + InstrumentClass statementClass = byteCodeInstrumentor.getClass(javassistClassName); + Interceptor executeQuery = new StatementExecuteQueryInterceptor(); + statementClass.addScopeInterceptor("executeQuery", new String[]{"java.lang.String"}, executeQuery, JtdsScope.SCOPE_NAME); + + Interceptor executeUpdateInterceptor1 = new StatementExecuteUpdateInterceptor(); + statementClass.addScopeInterceptor("executeUpdate", new String[]{"java.lang.String"}, executeUpdateInterceptor1, JtdsScope.SCOPE_NAME); + + + Interceptor executeUpdateInterceptor2 = new StatementExecuteUpdateInterceptor(); + statementClass.addScopeInterceptor("executeUpdate", new String[]{"java.lang.String", "int"}, executeUpdateInterceptor2, JtdsScope.SCOPE_NAME); + + Interceptor executeInterceptor1 = new StatementExecuteUpdateInterceptor(); + statementClass.addScopeInterceptor("execute", new String[]{"java.lang.String"}, executeInterceptor1, JtdsScope.SCOPE_NAME); + + Interceptor executeInterceptor2 = new StatementExecuteUpdateInterceptor(); + statementClass.addScopeInterceptor("execute", new String[]{"java.lang.String", "int"}, executeInterceptor2, JtdsScope.SCOPE_NAME); + + statementClass.addTraceValue(DatabaseInfoTraceValue.class); + return statementClass.toBytecode(); + } catch (InstrumentException e) { + if (logger.isWarnEnabled()) { + logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); + } + return null; + } + } + +} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLConnectionModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLConnectionModifier.java deleted file mode 100644 index 3f38db093454..000000000000 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLConnectionModifier.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.nhn.pinpoint.profiler.modifier.db.mssql; - -import com.nhn.pinpoint.bootstrap.Agent; - -import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; -import com.nhn.pinpoint.profiler.modifier.AbstractModifier; -import javassist.CtClass; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.security.ProtectionDomain; - -public class MSSQLConnectionModifier extends AbstractModifier { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public MSSQLConnectionModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } - - public String getTargetClass() { - return "net/sourceforge/jtds/jdbc/ConnectionJDBC2"; - } - - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } - this.byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); - return changeMethods(javassistClassName, classFileBuffer); - } - - private byte[] changeMethods(String javassistClassName, byte[] classfileBuffer) { - try { - CtClass cc = null; - - - if (this.logger.isInfoEnabled()) { - this.logger.info("{} class is converted.", javassistClassName); - } - - return null; - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn(e.getMessage(), e); - } - } - return null; - } - - -} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLPreparedStatementModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLPreparedStatementModifier.java deleted file mode 100644 index d2f4db1dfd7e..000000000000 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLPreparedStatementModifier.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.nhn.pinpoint.profiler.modifier.db.mssql; - -import com.nhn.pinpoint.bootstrap.Agent; -import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; -import com.nhn.pinpoint.profiler.modifier.AbstractModifier; -import javassist.CtClass; - - -import java.security.ProtectionDomain; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MSSQLPreparedStatementModifier extends AbstractModifier { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public MSSQLPreparedStatementModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } - - public String getTargetClass() { - return "net/sourceforge/jtds/jdbc/JtdsPreparedStatement"; - } - - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } - this.byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); - return changeMethod(javassistClassName, classFileBuffer); - } - - private byte[] changeMethod(String javassistClassName, byte[] classfileBuffer) { - try { - CtClass cc = null; - - if (this.logger.isInfoEnabled()) { - this.logger.info("{} class is converted.", javassistClassName); - } - - return null; - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn(e.getMessage(), e); - } - } - return null; - } - - - - -} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLStatementModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLStatementModifier.java deleted file mode 100644 index 538bbc9ff97a..000000000000 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mssql/MSSQLStatementModifier.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.nhn.pinpoint.profiler.modifier.db.mssql; - -import com.nhn.pinpoint.bootstrap.Agent; -import com.nhn.pinpoint.profiler.interceptor.bci.ByteCodeInstrumentor; -import com.nhn.pinpoint.profiler.modifier.AbstractModifier; -import javassist.CtClass; - -import java.security.ProtectionDomain; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MSSQLStatementModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public MSSQLStatementModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } - - public String getTargetClass() { - return "net/sourceforge/jtds/jdbc/JtdsStatement"; - } - - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } - this.byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); - return changeMethod(javassistClassName, classFileBuffer); - } - - private byte[] changeMethod(String javassistClassName, byte[] classfileBuffer) { - try { - CtClass cc = null; - - if (this.logger.isInfoEnabled()) { - this.logger.info("{} class is converted.", javassistClassName); - } - - return null; - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn(e.getMessage(), e); - } - } - return null; - } - -} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLResultSetModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLResultSetModifier.java index 1ad01a822114..5a0e71687d3e 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLResultSetModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLResultSetModifier.java @@ -28,25 +28,8 @@ public byte[] modify(ClassLoader classLoader, String javassistClassName, Protect if (logger.isInfoEnabled()) { logger.info("Modifing. {}", javassistClassName); } - this.byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); - return changeMethod(javassistClassName, classFileBuffer); - } - - private byte[] changeMethod(String javassistClassName, byte[] classfileBuffer) { - try { - - - if (this.logger.isInfoEnabled()) { - this.logger.info("{} class is converted.", javassistClassName); - } - - return null; - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn(e.getMessage(), e); - } - } return null; } + } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/oracle/OracleConnectionStringParser.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/oracle/OracleConnectionStringParser.java new file mode 100644 index 000000000000..2c934f12dc73 --- /dev/null +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/oracle/OracleConnectionStringParser.java @@ -0,0 +1,105 @@ +package com.nhn.pinpoint.profiler.modifier.db.oracle; + +import com.nhn.pinpoint.bootstrap.context.DatabaseInfo; +import com.nhn.pinpoint.common.ServiceType; +import com.nhn.pinpoint.profiler.modifier.db.ConnectionStringParser; +import com.nhn.pinpoint.profiler.modifier.db.DefaultDatabaseInfo; +import com.nhn.pinpoint.profiler.modifier.db.JDBCUrlParser; +import com.nhn.pinpoint.profiler.modifier.db.StringMaker; +import com.nhn.pinpoint.profiler.modifier.db.oracle.parser.Description; +import com.nhn.pinpoint.profiler.modifier.db.oracle.parser.KeyValue; +import com.nhn.pinpoint.profiler.modifier.db.oracle.parser.OracleConnectionStringException; +import com.nhn.pinpoint.profiler.modifier.db.oracle.parser.OracleNetConnectionDescriptorParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author emeroad + */ +public class OracleConnectionStringParser implements ConnectionStringParser { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Override + public DatabaseInfo parse(String url) { + StringMaker maker = new StringMaker(url); + maker.after("jdbc:oracle:").after(":"); + String description = maker.after('@').value().trim(); + if (description.startsWith("(")) { + return parseNetConnectionUrl(url); + } else { + return parseSimpleUrl(url, maker); + } + } + + + // rac url. +// jdbc:oracle:thin:@(Description=(LOAD_BALANCE=on)" + +// "(ADDRESS=(PROTOCOL=TCP)(HOST=1.2.3.4) (PORT=1521))" + +// "(ADDRESS=(PROTOCOL=TCP)(HOST=1.2.3.5) (PORT=1521))" + +// "(CONNECT_DATA=(SERVICE_NAME=service)))" +// +// thin driver url +// jdbc:oracle:thin:@hostname:port:SID +// "jdbc:oracle:thin:MYWORKSPACE/qwerty@localhost:1521:XE"; +// 들여 쓰기를 통해 token을 보기 좋게 나눈경우. +// jdbc:oracle:thin: +// @( +// Description=(LOAD_BALANCE=on) +// ( +// ADDRESS=(PROTOCOL=TCP)(HOST=1.2.3.4) (PORT=1521) +// ) +// ( +// ADDRESS=(PROTOCOL=TCP)(HOST=1.2.3.5) (PORT=1521) +// ) +// ( +// CONNECT_DATA=(SERVICE_NAME=service) +// ) +// ) + private DatabaseInfo parseNetConnectionUrl(String url) { + try { + // oracle new URL : rac용 + OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(url); + KeyValue keyValue = parser.parse(); + // TODO oci 드라이버 일경우의 추가 처리가 필요함. nhn말고 왠간한데는 oci를 더 많이 씀. +// parser.getDriverType(); + return createOracleDatabaseInfo(keyValue, url); + } catch (OracleConnectionStringException ex) { + logger.warn("OracleConnectionString parse error. url:{} Caused:", url, ex.getMessage(), ex); + + // 에러찍고 그냥 unknownDataBase 생성 + return JDBCUrlParser.createUnknownDataBase(ServiceType.ORACLE, ServiceType.ORACLE_EXECUTE_QUERY, url); + } catch (Throwable ex) { + // 나중에 좀더 정교하게 exception을 던지게 되면 OracleConnectionStringException 만 잡는것으로 바꿔야 될듯하다. + logger.warn("OracleConnectionString parse error. url:{} Caused:", url, ex.getMessage(), ex); + // 에러찍고 그냥 unknownDataBase 생성 + return JDBCUrlParser.createUnknownDataBase(ServiceType.ORACLE, ServiceType.ORACLE_EXECUTE_QUERY, url); + } + } + + private DefaultDatabaseInfo parseSimpleUrl(String url, StringMaker maker) { + // thin driver + // jdbc:oracle:thin:@hostname:port:SID + // "jdbc:oracle:thin:MYWORKSPACE/qwerty@localhost:1521:XE"; +// jdbc:oracle:thin:@//hostname:port/serviceName + String host = maker.before(':').value(); + String port = maker.next().after(':').before(':', '/').value(); + String databaseId = maker.next().afterLast(':', '/').value(); + + List hostList = new ArrayList(1); + hostList.add(host + ":" + port); + return new DefaultDatabaseInfo(ServiceType.ORACLE, ServiceType.ORACLE_EXECUTE_QUERY, url, url, hostList, databaseId); + } + + private DatabaseInfo createOracleDatabaseInfo(KeyValue keyValue, String url) { + + Description description = new Description(keyValue); + List jdbcHost = description.getJdbcHost(); + + return new DefaultDatabaseInfo(ServiceType.ORACLE, ServiceType.ORACLE_EXECUTE_QUERY, url, url, jdbcHost, description.getDatabaseId()); + + } +} diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/oracle/OracleResultSetModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/oracle/OracleResultSetModifier.java index a801eb25db44..a0bb37110d72 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/oracle/OracleResultSetModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/oracle/OracleResultSetModifier.java @@ -30,27 +30,10 @@ public byte[] modify(ClassLoader classLoader, String javassistClassName, Protect if (logger.isInfoEnabled()) { logger.info("Modifing. {}", javassistClassName); } - this.byteCodeInstrumentor.checkLibrary(classLoader, javassistClassName); - return changeMethod(javassistClassName, classFileBuffer); + return null; } - private byte[] changeMethod(String javassistClassName, byte[] classfileBuffer) { - try { - CtClass cc = null; - - - if (this.logger.isInfoEnabled()) { - this.logger.info("{} class is converted.", javassistClassName); - } - return null; - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn(e.getMessage(), e); - } - } - return null; - } } diff --git a/profiler/src/main/resources-dev/pinpoint.config b/profiler/src/main/resources-dev/pinpoint.config index fbd26a58172d..8721b3d14458 100644 --- a/profiler/src/main/resources-dev/pinpoint.config +++ b/profiler/src/main/resources-dev/pinpoint.config @@ -72,9 +72,12 @@ profiler.jdbc.mysql.commit=true profiler.jdbc.mysql.rollback=true # -# MSSQL +# MSSQL Jtds # -profiler.jdbc.mssql=false +profiler.jdbc.jtds=true +profiler.jdbc.jtds.setautocommit=true +profiler.jdbc.jtds.commit=true +profiler.jdbc.jtds.rollback=true # # Oracle diff --git a/profiler/src/main/resources-local/pinpoint.config b/profiler/src/main/resources-local/pinpoint.config index 1ad8c0bb4cc2..d448d37de598 100644 --- a/profiler/src/main/resources-local/pinpoint.config +++ b/profiler/src/main/resources-local/pinpoint.config @@ -6,11 +6,11 @@ ########################################################### # Collector server # ########################################################### -# 로컬 +# local profiler.collector.ip=127.0.0.1 -# 개발 +# dev #profiler.collector.ip=10.64.84.188 -# 운영 +# real #profiler.collector.ip=10.25.149.249 profiler.collector.udpspan.port=9996 @@ -80,9 +80,12 @@ profiler.jdbc.mysql.commit=true profiler.jdbc.mysql.rollback=true # -# MSSQL +# MSSQL Jtds # -profiler.jdbc.mssql=false +profiler.jdbc.jtds=true +profiler.jdbc.jtds.setautocommit=true +profiler.jdbc.jtds.commit=true +profiler.jdbc.jtds.rollback=true # # Oracle diff --git a/profiler/src/main/resources-release/pinpoint.config b/profiler/src/main/resources-release/pinpoint.config index 6928d6c94b91..14936e3e58c9 100644 --- a/profiler/src/main/resources-release/pinpoint.config +++ b/profiler/src/main/resources-release/pinpoint.config @@ -75,9 +75,12 @@ profiler.jdbc.mysql.commit=false profiler.jdbc.mysql.rollback=false # -# MSSQL +# MSSQL Jtds # -profiler.jdbc.mssql=false +profiler.jdbc.jtds=true +profiler.jdbc.jtds.setautocommit=false +profiler.jdbc.jtds.commit=false +profiler.jdbc.jtds.rollback=false # # Oracle diff --git a/profiler/src/main/resources-test/pinpoint.config b/profiler/src/main/resources-test/pinpoint.config index c24a0a53d1b6..396b7643104f 100644 --- a/profiler/src/main/resources-test/pinpoint.config +++ b/profiler/src/main/resources-test/pinpoint.config @@ -20,8 +20,13 @@ profiler.jdbc.mysql.setautocommit=true profiler.jdbc.mysql.commit=true profiler.jdbc.mysql.rollback=true -# mssql 아직 미개발 -profiler.jdbc.mssql=false +# +# MSSQL Jtds +# +profiler.jdbc.jtds=true +profiler.jdbc.jtds.setautocommit=true +profiler.jdbc.jtds.commit=true +profiler.jdbc.jtds.rollback=true # oracle profiler.jdbc.oracle=true diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionStringParserTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionStringParserTest.java new file mode 100644 index 000000000000..3c494a901f73 --- /dev/null +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionStringParserTest.java @@ -0,0 +1,117 @@ +package com.nhn.pinpoint.profiler.modifier.db.jtds; + +import com.nhn.pinpoint.bootstrap.context.DatabaseInfo; +import com.nhn.pinpoint.common.ServiceType; +import com.nhn.pinpoint.profiler.modifier.db.ConnectionStringParser; +import junit.framework.Assert; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JtdsConnectionStringParserTest { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Test + public void testParse1() throws Exception { +// jdbc:jtds:sqlserver://server[:port][/database][;property=value[;...]] +// jdbc:jtds:sqlserver://server/db;user=userName;password=password + String url = "jdbc:jtds:sqlserver://10.xx.xx.xx:1433;DatabaseName=CAFECHAT;sendStringParametersAsUnicode=false;useLOBs=false;loginTimeout=3"; + ConnectionStringParser parser = new JtdsConnectionStringParser(); + DatabaseInfo info = parser.parse(url); + logger.debug("{}", info); + + Assert.assertEquals(info.getType(), ServiceType.MSSQL); + Assert.assertEquals(info.getMultipleHost(), "10.xx.xx.xx:1433"); + Assert.assertEquals(info.getDatabaseId(), "CAFECHAT"); + Assert.assertEquals(info.getUrl(), "jdbc:jtds:sqlserver://10.xx.xx.xx:1433"); + + } + + @Test + public void testParse2() throws Exception { + String url = "jdbc:jtds:sqlserver://10.xx.xx.xx:1433/CAFECHAT;sendStringParametersAsUnicode=false;useLOBs=false;loginTimeout=3"; + ConnectionStringParser parser = new JtdsConnectionStringParser(); + DatabaseInfo info = parser.parse(url); + logger.debug("{}", info); + + Assert.assertEquals(info.getType(), ServiceType.MSSQL); + Assert.assertEquals(info.getMultipleHost(), "10.xx.xx.xx:1433"); + Assert.assertEquals(info.getDatabaseId(), "CAFECHAT"); + Assert.assertEquals(info.getUrl(), "jdbc:jtds:sqlserver://10.xx.xx.xx:1433/CAFECHAT"); + + } + + @Test + public void testParse3() throws Exception { + String url = "jdbc:jtds:sqlserver://10.xx.xx.xx:1433/CAFECHAT"; + ConnectionStringParser parser = new JtdsConnectionStringParser(); + DatabaseInfo info = parser.parse(url); + logger.debug("{}", info); + + Assert.assertEquals(info.getType(), ServiceType.MSSQL); + Assert.assertEquals(info.getMultipleHost(), "10.xx.xx.xx:1433"); + Assert.assertEquals(info.getDatabaseId(), "CAFECHAT"); + Assert.assertEquals(info.getUrl(), "jdbc:jtds:sqlserver://10.xx.xx.xx:1433/CAFECHAT"); + } + + @Test + public void testParse4() throws Exception { + String url = "jdbc:jtds:sqlserver://10.xx.xx.xx:1433"; + ConnectionStringParser parser = new JtdsConnectionStringParser(); + DatabaseInfo info = parser.parse(url); + logger.debug("{}", info); + + Assert.assertEquals(info.getType(), ServiceType.MSSQL); + Assert.assertEquals(info.getMultipleHost(), "10.xx.xx.xx:1433"); + Assert.assertEquals(info.getDatabaseId(), ""); + Assert.assertEquals(info.getUrl(), "jdbc:jtds:sqlserver://10.xx.xx.xx:1433"); + } + + + @Test + public void testParse5() throws Exception { +// jdbc:jtds:sqlserver://server[:port][/database][;property=value[;...]] +// jdbc:jtds:sqlserver://server/db;user=userName;password=password + String url = "jdbc:jtds:sqlserver://10.xx.xx.xx;DatabaseName=CAFECHAT"; + ConnectionStringParser parser = new JtdsConnectionStringParser(); + DatabaseInfo info = parser.parse(url); + logger.debug("{}", info); + + Assert.assertEquals(info.getType(), ServiceType.MSSQL); + Assert.assertEquals(info.getMultipleHost(), "10.xx.xx.xx"); + Assert.assertEquals(info.getDatabaseId(), "CAFECHAT"); + Assert.assertEquals(info.getUrl(), "jdbc:jtds:sqlserver://10.xx.xx.xx"); + + } + + @Test + public void testParse6() throws Exception { +// jdbc:jtds:sqlserver://server[:port][/database][;property=value[;...]] +// jdbc:jtds:sqlserver://server/db;user=userName;password=password + String url = "jdbc:jtds:sqlserver://10.xx.xx.xx"; + ConnectionStringParser parser = new JtdsConnectionStringParser(); + DatabaseInfo info = parser.parse(url); + logger.debug("{}", info); + + Assert.assertEquals(info.getType(), ServiceType.MSSQL); + Assert.assertEquals(info.getMultipleHost(), "10.xx.xx.xx"); + Assert.assertEquals(info.getDatabaseId(), ""); + Assert.assertEquals(info.getUrl(), "jdbc:jtds:sqlserver://10.xx.xx.xx"); + + } + + + @Test + public void testParse7() throws Exception { + String url = "jdbc:jtds:sqlserver://10.xx.xx.xx:1433/CAFECHAT;abc=1;bcd=2"; + ConnectionStringParser parser = new JtdsConnectionStringParser(); + DatabaseInfo info = parser.parse(url); + logger.debug("{}", info); + + Assert.assertEquals(info.getType(), ServiceType.MSSQL); + Assert.assertEquals(info.getMultipleHost(), "10.xx.xx.xx:1433"); + Assert.assertEquals(info.getDatabaseId(), "CAFECHAT"); + Assert.assertEquals(info.getUrl(), "jdbc:jtds:sqlserver://10.xx.xx.xx:1433/CAFECHAT"); + } +} \ No newline at end of file From 138951c8e45e3b5497572247c55ae717cf8a234d Mon Sep 17 00:00:00 2001 From: Hyun Jeong Date: Thu, 18 Sep 2014 13:09:35 +0900 Subject: [PATCH 11/18] [#14] Modified LifeCycleEventListener to directly check Agent's status. --- .../navercorp/pinpoint/bootstrap/Agent.java | 7 +- .../pinpoint/bootstrap/DummyAgent.java | 33 ++-- .../pinpoint/profiler/AgentStatus.java | 1 - .../pinpoint/profiler/DefaultAgent.java | 144 ++++++++---------- .../profiler/LifeCycleEventListener.java | 21 +-- .../modifier/DefaultModifierRegistry.java | 8 +- 6 files changed, 91 insertions(+), 123 deletions(-) diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/Agent.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/Agent.java index b0a323bd3566..065949fa6106 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/Agent.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/Agent.java @@ -5,15 +5,14 @@ /** * @author emeroad + * @author hyungil.jeong */ public interface Agent { - // TODO 필요없을것 같음 started를 start로 바꿔도 될 듯... - void start(); - void started(); + void start(); void stop(); - + void addConnector(String protocol, int port); TraceContext getTraceContext(); diff --git a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/DummyAgent.java b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/DummyAgent.java index 534c34700056..95e6b7a9968a 100644 --- a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/DummyAgent.java +++ b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/DummyAgent.java @@ -7,6 +7,7 @@ /** * @author emeroad + * @author hyungil.jeong */ public class DummyAgent implements Agent { @@ -18,10 +19,6 @@ public DummyAgent(String agentArgs, Instrumentation instrumentation, ProfilerCon public void start() { } - @Override - public void started() { - } - @Override public void stop() { } @@ -40,18 +37,18 @@ public ProfilerConfig getProfilerConfig() { return null; } -// @Override -// public PLoggerBinder initializeLogger() { -// return new PLoggerBinder() { -// @Override -// public PLogger getLogger(String name) { -// return new DummyPLogger(); -// } -// -// @Override -// public void shutdown() { -// -// } -// }; -// } + // @Override + // public PLoggerBinder initializeLogger() { + // return new PLoggerBinder() { + // @Override + // public PLogger getLogger(String name) { + // return new DummyPLogger(); + // } + // + // @Override + // public void shutdown() { + // + // } + // }; + // } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentStatus.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentStatus.java index 094315d8ec62..44e5152137bd 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentStatus.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentStatus.java @@ -3,6 +3,5 @@ public enum AgentStatus { INITIALIZING, RUNNING, - STOPPING, STOPPED } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java index 79e488a9acc5..b08303c761e0 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java @@ -47,6 +47,7 @@ /** * @author emeroad * @author koo.taejin + * @author hyungil.jeong */ public class DefaultAgent implements Agent { @@ -66,7 +67,7 @@ public class DefaultAgent implements Agent { private final PinpointSocketFactory factory; private final PinpointSocket socket; - + private final EnhancedDataSender tcpDataSender; private final DataSender statDataSender; private final DataSender spanDataSender; @@ -87,7 +88,6 @@ public class DefaultAgent implements Agent { ClassPreLoader.preload(); } - public DefaultAgent(String agentArgs, Instrumentation instrumentation, ProfilerConfig profilerConfig) { if (instrumentation == null) { throw new NullPointerException("instrumentation must not be null"); @@ -123,17 +123,19 @@ public DefaultAgent(String agentArgs, Instrumentation instrumentation, ProfilerC logger.info("agentInformation:{}", agentInformation); this.tAgentInfo = createTAgentInfo(); - + this.factory = createPinpointSocketFactory(); - this.socket = createPinpointSocket(this.profilerConfig.getCollectorServerIp(), this.profilerConfig.getCollectorTcpServerPort(), factory, this.profilerConfig.isTcpDataSenderCommandAcceptEnable()); - + this.socket = createPinpointSocket(this.profilerConfig.getCollectorServerIp(), this.profilerConfig.getCollectorTcpServerPort(), factory, + this.profilerConfig.isTcpDataSenderCommandAcceptEnable()); + this.tcpDataSender = createTcpDataSender(socket); - + this.spanDataSender = createUdpDataSender(this.profilerConfig.getCollectorUdpSpanServerPort(), "Pinpoint-UdpSpanDataExecutor", - this.profilerConfig.getSpanDataSenderWriteQueueSize(), this.profilerConfig.getSpanDataSenderSocketTimeout(), this.profilerConfig.getSpanDataSenderSocketSendBufferSize()); + this.profilerConfig.getSpanDataSenderWriteQueueSize(), this.profilerConfig.getSpanDataSenderSocketTimeout(), + this.profilerConfig.getSpanDataSenderSocketSendBufferSize()); this.statDataSender = createUdpDataSender(this.profilerConfig.getCollectorUdpServerPort(), "Pinpoint-UdpStatDataExecutor", - this.profilerConfig.getStatDataSenderWriteQueueSize(), this.profilerConfig.getStatDataSenderSocketTimeout(), this.profilerConfig.getStatDataSenderSocketSendBufferSize()); - + this.profilerConfig.getStatDataSenderWriteQueueSize(), this.profilerConfig.getStatDataSenderSocketTimeout(), + this.profilerConfig.getStatDataSenderSocketSendBufferSize()); this.traceContext = createTraceContext(agentInformation.getServerType()); @@ -143,15 +145,13 @@ public DefaultAgent(String agentArgs, Instrumentation instrumentation, ProfilerC this.agentStatMonitor = new AgentStatMonitor(this.statDataSender, this.agentInformation.getAgentId(), this.agentInformation.getStartTime()); preLoadClass(); - + /** - * FIXME - * tomcat의 경우에는 com.nhn.pinpoint.profiler.modifier.tomcat.interceptor.CatalinaAwaitInterceptor가 - * org/apache/catalina/startup/Catalina/await함수가 실행되기 전에 실행해주나. - * stand alone application은 그렇지 않으므로.. + * FIXME tomcat의 경우에는 com.nhn.pinpoint.profiler.modifier.tomcat.interceptor.CatalinaAwaitInterceptor가 org/apache/catalina/startup/Catalina/await함수가 실행되기 + * 전에 실행해주나. stand alone application은 그렇지 않으므로.. */ if (typeResolver.isManuallyStartupRequired()) { - started(); + start(); } } @@ -168,8 +168,6 @@ public ClassFileTransformer getClassFileTransformer() { return classFileTransformer; } - - private void dumpSystemProperties() { if (logger.isInfoEnabled()) { Properties properties = System.getProperties(); @@ -191,7 +189,6 @@ public ProfilerConfig getProfilerConfig() { return profilerConfig; } - private TAgentInfo createTAgentInfo() { final ServerInfo serverInfo = this.serverInfo; String ip = serverInfo.getHostip(); @@ -209,16 +206,14 @@ private TAgentInfo createTAgentInfo() { agentInfo.setApplicationName(agentInformation.getApplicationName()); agentInfo.setPid(agentInformation.getPid()); agentInfo.setStartTimestamp(agentInformation.getStartTime()); - agentInfo.setServiceType(agentInformation.getServerType()); + agentInfo.setServiceType(agentInformation.getServerType()); agentInfo.setVersion(Version.VERSION); -// agentInfo.setIsAlive(true); + // agentInfo.setIsAlive(true); return agentInfo; } - - private void changeStatus(AgentStatus status) { this.agentStatus = status; if (logger.isDebugEnabled()) { @@ -235,7 +230,6 @@ private void bindPLoggerFactory(PLoggerBinder binder) { // shutdown hook이나 stop에 LoggerBinder의 연결을 풀어야 되는가? } - private TraceContext createTraceContext(short serverType) { final StorageFactory storageFactory = createStorageFactory(); logger.info("StorageFactoryType:{}", storageFactory); @@ -248,10 +242,8 @@ private TraceContext createTraceContext(short serverType) { traceContext.setAgentInformation(this.agentInformation); traceContext.setPriorityDataSender(this.tcpDataSender); - traceContext.setProfilerConfig(profilerConfig); - return traceContext; } @@ -274,33 +266,33 @@ private Sampler createSampler() { } protected PinpointSocketFactory createPinpointSocketFactory() { - Map properties = this.agentInformation.toMap(); - properties.put(AgentPropertiesType.IP.getName(), serverInfo.getHostip()); + Map properties = this.agentInformation.toMap(); + properties.put(AgentPropertiesType.IP.getName(), serverInfo.getHostip()); - PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); + PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); pinpointSocketFactory.setTimeoutMillis(1000 * 5); pinpointSocketFactory.setProperties(properties); return pinpointSocketFactory; - } - + } + protected PinpointSocket createPinpointSocket(String host, int port, PinpointSocketFactory factory) { - return createPinpointSocket(host, port, factory, false); + return createPinpointSocket(host, port, factory, false); } - + protected PinpointSocket createPinpointSocket(String host, int port, PinpointSocketFactory factory, boolean useMessageListener) { - // 1.2 버전이 Tcp Data Command 허용하는 버전이 아니기 떄문에 true이던 false이던 무조건 SimpleLoggingMessageListener를 이용하게 함 - // SimpleLoggingMessageListener.LISTENER 는 서로 통신을 하지 않게 설정되어 있음 (테스트코드는 pinpoint-rpc에 존재) - // 1.3 버전으로 할 경우 아래 분기에서 MessageListener 변경 필요 - MessageListener messageListener = null; - if (useMessageListener) { - messageListener = SimpleLoggingMessageListener.LISTENER; - } else { - messageListener = SimpleLoggingMessageListener.LISTENER; - } - - PinpointSocket socket = null; - for (int i = 0; i < 3; i++) { + // 1.2 버전이 Tcp Data Command 허용하는 버전이 아니기 떄문에 true이던 false이던 무조건 SimpleLoggingMessageListener를 이용하게 함 + // SimpleLoggingMessageListener.LISTENER 는 서로 통신을 하지 않게 설정되어 있음 (테스트코드는 pinpoint-rpc에 존재) + // 1.3 버전으로 할 경우 아래 분기에서 MessageListener 변경 필요 + MessageListener messageListener = null; + if (useMessageListener) { + messageListener = SimpleLoggingMessageListener.LISTENER; + } else { + messageListener = SimpleLoggingMessageListener.LISTENER; + } + + PinpointSocket socket = null; + for (int i = 0; i < 3; i++) { try { socket = factory.connect(host, port, messageListener); logger.info("tcp connect success:{}/{}", host, port); @@ -311,34 +303,33 @@ protected PinpointSocket createPinpointSocket(String host, int port, PinpointSoc } logger.warn("change background tcp connect mode {}/{} ", host, port); socket = factory.scheduledConnect(host, port, messageListener); - + return socket; } protected EnhancedDataSender createTcpDataSender(PinpointSocket socket) { return new TcpDataSender(socket); } - + protected DataSender createUdpDataSender(int port, String threadName, int writeQueueSize, int timeout, int sendBufferSize) { return new UdpDataSender(this.profilerConfig.getCollectorServerIp(), port, threadName, writeQueueSize, timeout, sendBufferSize); } - - protected EnhancedDataSender getTcpDataSender() { - return tcpDataSender; - } - protected DataSender getStatDataSender() { - return statDataSender; - } + protected EnhancedDataSender getTcpDataSender() { + return tcpDataSender; + } - protected DataSender getSpanDataSender() { - return spanDataSender; - } + protected DataSender getStatDataSender() { + return statDataSender; + } - public void addConnector(String protocol, int port){ - this.serverInfo.addConnector(protocol, port); + protected DataSender getSpanDataSender() { + return spanDataSender; } + public void addConnector(String protocol, int port) { + this.serverInfo.addConnector(protocol, port); + } public ServerInfo getServerInfo() { return this.serverInfo; @@ -352,28 +343,31 @@ public AgentInformation getAgentInformation() { return agentInformation; } - public boolean isRunning() { - return agentStatus == AgentStatus.RUNNING; - } - - // TODO 필요없을것 같음 started를 start로 바꿔도 될 듯... @Override public void start() { + synchronized (this) { + if (this.agentStatus == AgentStatus.INITIALIZING) { + changeStatus(AgentStatus.RUNNING); + } else { + logger.warn("Agent already started."); + return; + } + } logger.info("Starting {} Agent.", ProductInfo.CAMEL_NAME); - } - - /** - * org/apache/catalina/startup/Catalina/await함수가 호출되기 전에 실행된다. - * Tomcat이 구동되고 context가 모두 로드 된 다음 사용자의 요청을 처리할 수 있게 되었을 때 실행됨. - */ - public void started() { - changeStatus(AgentStatus.RUNNING); this.heartBitChecker.start(); this.agentStatMonitor.start(); } @Override public void stop() { + synchronized (this) { + if (this.agentStatus == AgentStatus.RUNNING) { + changeStatus(AgentStatus.STOPPED); + } else { + logger.warn("Cannot stop agent. Current status = [{}]", this.agentStatus); + return; + } + } logger.info("Stopping {} Agent.", ProductInfo.CAMEL_NAME); this.heartBitChecker.stop(); @@ -383,8 +377,6 @@ public void stop() { this.tcpDataSender.send(tAgentInfo); // TODO send tAgentInfo alive false후 send 메시지의 처리가 정확하지 않음 - changeStatus(AgentStatus.STOPPING); - this.agentStatMonitor.stop(); // 종료 처리 필요. @@ -393,13 +385,11 @@ public void stop() { this.tcpDataSender.stop(); if (this.socket != null) { - this.socket.close(); + this.socket.close(); } if (this.factory != null) { - this.factory.release(); + this.factory.release(); } - - changeStatus(AgentStatus.STOPPED); } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/LifeCycleEventListener.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/LifeCycleEventListener.java index 633005632bdb..436f53b1a2ab 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/LifeCycleEventListener.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/LifeCycleEventListener.java @@ -7,13 +7,13 @@ /** * @author emeroad + * @author hyungil.jeong */ public class LifeCycleEventListener { private final static PLogger logger = PLoggerFactory.getLogger(LifeCycleEventListener.class.getName()); - private Agent agent; - private boolean started = false; + private final Agent agent; public LifeCycleEventListener(Agent agent) { if (agent == null) { @@ -22,26 +22,13 @@ public LifeCycleEventListener(Agent agent) { this.agent = agent; } - public synchronized void start() { + public void start() { logger.info("LifeCycleEventListener start"); - - if (started) { - logger.info("already started"); - return; - } - agent.start(); - started = true; } - public synchronized void stop() { + public void stop() { logger.info("LifeCycleEventListener stop"); - - if (!started) { - logger.info("already stopped"); - return; - } - started = false; agent.stop(); } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java index 96ef673d031b..4b74563faf63 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java @@ -62,10 +62,9 @@ import com.nhn.pinpoint.profiler.modifier.servlet.HttpServletModifier; import com.nhn.pinpoint.profiler.modifier.servlet.SpringFrameworkServletModifier; import com.nhn.pinpoint.profiler.modifier.spring.orm.ibatis.SqlMapClientTemplateModifier; -import com.nhn.pinpoint.profiler.modifier.tomcat.CatalinaModifier; import com.nhn.pinpoint.profiler.modifier.tomcat.StandardHostValveInvokeModifier; +import com.nhn.pinpoint.profiler.modifier.tomcat.StandardServiceModifier; import com.nhn.pinpoint.profiler.modifier.tomcat.TomcatConnectorModifier; -import com.nhn.pinpoint.profiler.modifier.tomcat.TomcatStandardServiceModifier; /** * @author emeroad @@ -203,14 +202,11 @@ public void addTomcatModifier() { SpringFrameworkServletModifier springServletModifier = new SpringFrameworkServletModifier(byteCodeInstrumentor, agent); addModifier(springServletModifier); - Modifier tomcatStandardServiceModifier = new TomcatStandardServiceModifier(byteCodeInstrumentor, agent); + Modifier tomcatStandardServiceModifier = new StandardServiceModifier(byteCodeInstrumentor, agent); addModifier(tomcatStandardServiceModifier); Modifier tomcatConnectorModifier = new TomcatConnectorModifier(byteCodeInstrumentor, agent); addModifier(tomcatConnectorModifier); - - Modifier tomcatCatalinaModifier = new CatalinaModifier(byteCodeInstrumentor, agent); - addModifier(tomcatCatalinaModifier); } public void addJdbcModifier() { From 0373759e92a6de97266de4aad624ca9a5b8c7091 Mon Sep 17 00:00:00 2001 From: Woonduk Kang Date: Thu, 18 Sep 2014 19:06:54 +0900 Subject: [PATCH 12/18] [#10] support jtds driver(ms sqlserver) - add testcase --- .../modifier/db/jtds/JtdsConnectionTest.java | 176 ++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java new file mode 100644 index 000000000000..ea97cbcc9b6f --- /dev/null +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java @@ -0,0 +1,176 @@ +package com.nhn.pinpoint.profiler.modifier.db.jtds; + +import com.nhn.pinpoint.bootstrap.context.DatabaseInfo; +import com.nhn.pinpoint.bootstrap.interceptor.tracevalue.DatabaseInfoTraceValue; +import com.nhn.pinpoint.common.bo.SpanEventBo; +import com.nhn.pinpoint.profiler.junit4.BasePinpointTest; +import org.junit.Assert; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +import java.sql.*; +import java.sql.Driver; +import java.util.List; +import java.util.Properties; + +/** + * @author emeroad + */ +public class JtdsConnectionTest extends BasePinpointTest { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + + @Test + public void executeQueryAndexecuteUpdate() throws SQLException { + Connection connect = connectDB(); + + PreparedStatement preparedStatement = connect.prepareStatement("select 1 "); +// preparedStatement.setInt(1, 1); + ResultSet resultSet = preparedStatement.executeQuery(); + if (resultSet.next()) { + logger.debug("---" + resultSet.getObject(1)); + } + } + + private Connection connectDB() throws SQLException { + Driver driver = new net.sourceforge.jtds.jdbc.Driver(); + Properties properties = new Properties(); + properties.setProperty("user", "pinpoint_user"); + properties.setProperty("password", "pinpoint!234"); + return driver.connect("jdbc:jtds:sqlserver://10.99.220.85:1433/pinpoint_test", properties); + } + + + @Test + public void testModify() throws Exception { + + Connection connection = connectDB(); + + logger.info("Connection class name:{}", connection.getClass().getName()); + logger.info("Connection class cl:{}", connection.getClass().getClassLoader()); + + DatabaseInfo url = ((DatabaseInfoTraceValue) connection).__getTraceDatabaseInfo(); + Assert.assertNotNull(url); + List currentSpanEvents = getCurrentSpanEvents(); + logger.debug("spanEvent:{}", currentSpanEvents.remove(0)); + logger.debug("{}", currentSpanEvents); + + statement(connection); + logger.debug("spanEvent:{}", currentSpanEvents.remove(0)); + logger.debug("{}", currentSpanEvents); + + preparedStatement(connection); + + preparedStatement2(connection); + + preparedStatement3(connection); + + preparedStatement4(connection); + + preparedStatement5(connection); + + preparedStatement6(connection); + + preparedStatement7(connection); + + preparedStatement8(connection); + + + connection.close(); + DatabaseInfo clearUrl = ((DatabaseInfoTraceValue) connection).__getTraceDatabaseInfo(); + Assert.assertNull(clearUrl); + + } + + + private void statement(Connection connection) throws SQLException { + Statement statement = connection.createStatement(); + statement.executeQuery("select 1"); + statement.close(); + } + + private void preparedStatement(Connection connection) throws SQLException { + PreparedStatement preparedStatement = connection.prepareStatement("select 1"); + logger.info("PreparedStatement className:" + preparedStatement.getClass().getName()); + ResultSet resultSet = preparedStatement.executeQuery(); + resultSet.close(); + preparedStatement.close(); + } + + + private void preparedStatement2(Connection connection) throws SQLException { + PreparedStatement preparedStatement = connection.prepareStatement("select * from member where id = ?"); + preparedStatement.setInt(1, 1); + ResultSet resultSet = preparedStatement.executeQuery(); + resultSet.close(); + preparedStatement.close(); + } + + private void preparedStatement3(Connection connection) throws SQLException { + connection.setAutoCommit(false); + + PreparedStatement preparedStatement = connection.prepareStatement("select * from member where id = ? or id = ? or id = ?"); + preparedStatement.setInt(1, 1); + preparedStatement.setInt(2, 2); + preparedStatement.setString(3, "3"); + ResultSet resultSet = preparedStatement.executeQuery(); + resultSet.close(); + preparedStatement.close(); + + connection.commit(); + + + connection.setAutoCommit(true); + } + + private void preparedStatement4(Connection connection) throws SQLException { +// Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS + PreparedStatement preparedStatement = connection.prepareStatement("select 1", Statement.RETURN_GENERATED_KEYS); + logger.info("PreparedStatement className:{}", preparedStatement.getClass().getName()); + ResultSet resultSet = preparedStatement.executeQuery(); + resultSet.close(); + preparedStatement.close(); + } + + private void preparedStatement5(Connection connection) throws SQLException { +// Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS + PreparedStatement preparedStatement = connection.prepareStatement("select 1", new String[]{"test"}); + logger.info("PreparedStatement className:{}", preparedStatement.getClass().getName()); + ResultSet resultSet = preparedStatement.executeQuery(); + resultSet.close(); + preparedStatement.close(); + } + + private void preparedStatement6(Connection connection) throws SQLException { +// Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS + int[] columnIndex = {1}; + PreparedStatement preparedStatement = connection.prepareStatement("select 1", columnIndex); + logger.info("PreparedStatement className:{}", preparedStatement.getClass().getName()); + ResultSet resultSet = preparedStatement.executeQuery(); + resultSet.close(); + preparedStatement.close(); + } + + private void preparedStatement7(Connection connection) throws SQLException { +// Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS + PreparedStatement preparedStatement = connection.prepareStatement("select 1", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + logger.info("PreparedStatement className:{}", preparedStatement.getClass().getName()); + ResultSet resultSet = preparedStatement.executeQuery(); + resultSet.close(); + preparedStatement.close(); + } + + private void preparedStatement8(Connection connection) throws SQLException { +// Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS +// ResultSet.HOLD_CURSORS_OVER_COMMIT or ResultSet.CLOSE_CURSORS_AT_COMMIT + PreparedStatement preparedStatement = connection.prepareStatement("select 1", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); + logger.info("PreparedStatement className:{}", preparedStatement.getClass().getName()); + ResultSet resultSet = preparedStatement.executeQuery(); + resultSet.close(); + preparedStatement.close(); + } + +} From 6d2e9b3caa6dbeecdb6cfb45b0d5326108e95859 Mon Sep 17 00:00:00 2001 From: Woonduk Kang Date: Fri, 19 Sep 2014 18:31:46 +0900 Subject: [PATCH 13/18] [#10] testcase refactoring --- .../db/cubrid/CubridConnectionTest.java | 60 +++++------------ .../modifier/db/jtds/JtdsConnectionTest.java | 9 +-- .../MySQLConnectionImplModifierTest.java | 66 ++++--------------- 3 files changed, 32 insertions(+), 103 deletions(-) diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionTest.java index 64d6377a2d48..29b88d1b685e 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionTest.java @@ -6,6 +6,7 @@ import com.nhn.pinpoint.bootstrap.logging.PLoggerFactory; import com.nhn.pinpoint.common.ServiceType; import com.nhn.pinpoint.profiler.DefaultAgent; +import com.nhn.pinpoint.profiler.junit4.BasePinpointTest; import com.nhn.pinpoint.profiler.logging.Slf4jLoggerBinder; import com.nhn.pinpoint.profiler.util.MockAgent; import com.nhn.pinpoint.profiler.util.TestClassLoader; @@ -22,55 +23,38 @@ /** * @author emeroad */ -public class CubridConnectionTest { +public class CubridConnectionTest extends BasePinpointTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private TestClassLoader loader; @Test - public void executeQueryAndexecuteUpdate() throws SQLException { - CUBRIDDriver driver = new CUBRIDDriver(); - Properties properties = new Properties(); - properties.setProperty("user", "dba"); - properties.setProperty("password", "nhn!@#123"); - Connection connect = driver.connect("jdbc:cubrid:10.101.57.233:30102:pinpoint:::", properties); + public void executeQueryAndExecuteUpdate() throws SQLException { + Connection connection = connectDB(); - PreparedStatement preparedStatement = connect.prepareStatement("select 1 from db_root where 1=?"); + PreparedStatement preparedStatement = connection.prepareStatement("select 1 from db_root where 1=?"); preparedStatement.setInt(1, 1); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { - System.out.println("---" + resultSet.getObject(1)); + logger.debug("---{}", resultSet.getObject(1)); } + connection.close(); } - @Before - public void setUp() throws Exception { - PLoggerFactory.initialize(new Slf4jLoggerBinder()); - - ProfilerConfig profilerConfig = new ProfilerConfig(); - // profiler config를 setter를 열어두는것도 괜찮을듯 하다. - String path = MockAgent.class.getClassLoader().getResource("pinpoint.config").getPath(); - profilerConfig.readConfigFile(path); - - profilerConfig.setApplicationServerType(ServiceType.TEST_STAND_ALONE); - DefaultAgent agent = new MockAgent("", profilerConfig); - loader = new TestClassLoader(agent); - // agent가 로드한 모든 Modifier를 자동으로 찾도록 변경함. + private Connection connectDB() throws SQLException { + Driver driver = new CUBRIDDriver(); + Properties properties = new Properties(); + properties.setProperty("user", "dba"); + properties.setProperty("password", "nhn!@#123"); + return driver.connect("jdbc:cubrid:10.101.57.233:30102:pinpoint:::", properties); + } - loader.initialize(); - } @Test public void testModify() throws Exception { - Driver driver = loadClass(); - - Properties properties = new Properties(); - properties.setProperty("user", "dba"); - properties.setProperty("password", "nhn!@#123"); - Connection connection = driver.connect("jdbc:cubrid:10.101.57.233:30102:pinpoint:::", properties); + Connection connection = connectDB(); logger.info("Connection class name:{}", connection.getClass().getName()); logger.info("Connection class cl:{}", connection.getClass().getClassLoader()); @@ -103,20 +87,6 @@ public void testModify() throws Exception { } - private Driver loadClass() throws ClassNotFoundException, InstantiationException, IllegalAccessException { - Class driverClazz = (Class) loader.loadClass("cubrid.jdbc.driver.CUBRIDDriver"); - - Driver driver = driverClazz.newInstance(); - logger.info("Driver class name:{}", driverClazz.getName()); - logger.info("Driver class cl:{}", driverClazz.getClassLoader()); - - - Class version = loader.loadClass("com.nhn.pinpoint.common.Version"); - Assert.assertSame("check classLoader", this.getClass().getClassLoader(), version.getClassLoader()); - logger.debug("common cl:{}", version.getClassLoader()); - return driver; - } - private void statement(Connection connection) throws SQLException { Statement statement = connection.createStatement(); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java index ea97cbcc9b6f..44cda6f72bb5 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java @@ -24,15 +24,16 @@ public class JtdsConnectionTest extends BasePinpointTest { @Test - public void executeQueryAndexecuteUpdate() throws SQLException { - Connection connect = connectDB(); + public void executeQueryAndExecuteUpdate() throws SQLException { + Connection connection = connectDB(); - PreparedStatement preparedStatement = connect.prepareStatement("select 1 "); + PreparedStatement preparedStatement = connection.prepareStatement("select 1 "); // preparedStatement.setInt(1, 1); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { - logger.debug("---" + resultSet.getObject(1)); + logger.debug("---{}", resultSet.getObject(1)); } + connection.close(); } private Connection connectDB() throws SQLException { diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLConnectionImplModifierTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLConnectionImplModifierTest.java index a471ce0476fb..0cb890d47e5e 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLConnectionImplModifierTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLConnectionImplModifierTest.java @@ -1,6 +1,7 @@ package com.nhn.pinpoint.profiler.modifier.db.mysql; import com.mysql.jdbc.JDBC4PreparedStatement; +import com.mysql.jdbc.NonRegisteringDriver; import com.nhn.pinpoint.bootstrap.interceptor.tracevalue.DatabaseInfoTraceValue; import com.nhn.pinpoint.common.ServiceType; import com.nhn.pinpoint.profiler.DefaultAgent; @@ -8,6 +9,7 @@ import com.nhn.pinpoint.bootstrap.context.DatabaseInfo; import com.nhn.pinpoint.bootstrap.logging.PLoggerFactory; +import com.nhn.pinpoint.profiler.junit4.BasePinpointTest; import com.nhn.pinpoint.profiler.logging.Slf4jLoggerBinder; @@ -28,40 +30,14 @@ /** * @author emeroad */ -public class MySQLConnectionImplModifierTest { +public class MySQLConnectionImplModifierTest extends BasePinpointTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private TestClassLoader loader; - - - @Before - public void setUp() throws Exception { - PLoggerFactory.initialize(new Slf4jLoggerBinder()); - - ProfilerConfig profilerConfig = new ProfilerConfig(); - // profiler config를 setter를 열어두는것도 괜찮을듯 하다. - String path = MockAgent.class.getClassLoader().getResource("pinpoint.config").getPath(); - profilerConfig.readConfigFile(path); - - profilerConfig.setApplicationServerType(ServiceType.TEST_STAND_ALONE); - DefaultAgent agent = new MockAgent("", profilerConfig); - loader = new TestClassLoader(agent); - // agent가 로드한 모든 Modifier를 자동으로 찾도록 변경함. - - - loader.initialize(); - } - @Test public void testModify() throws Exception { - Driver driver = loadClass(); - - Properties properties = new Properties(); - properties.setProperty("user", "lucytest"); - properties.setProperty("password", "testlucy"); - Connection connection = driver.connect("jdbc:mysql://10.98.133.22:3306/hippo", properties); + Connection connection = connectDB("jdbc:mysql://10.98.133.22:3306/hippo"); logger.info("Connection class name:{}", connection.getClass().getName()); logger.info("Connection class cl:{}", connection.getClass().getClassLoader()); @@ -78,41 +54,24 @@ public void testModify() throws Exception { preparedStatement3(connection); connection.close(); + DatabaseInfo clearUrl = ((DatabaseInfoTraceValue)connection).__getTraceDatabaseInfo(); Assert.assertNull(clearUrl); } - private Driver loadClass() throws ClassNotFoundException, InstantiationException, IllegalAccessException { - Class driverClazz = (Class) loader.loadClass("com.mysql.jdbc.NonRegisteringDriver"); -// Driver nonRegisteringDriver = new NonRegisteringDriver(); -// Class driverClazz = (Class) nonRegisteringDriver.getClass(); - - Driver driver = driverClazz.newInstance(); - logger.info("Driver class name:{}", driverClazz.getName()); - logger.info("Driver class cl:{}", driverClazz.getClassLoader()); - - - Class aClass = loader.loadClass("com.mysql.jdbc.StringUtils"); -// 이게 loader와 동일하게 로드 되는게 정확한건지 애매함. 하위에 로드되는게 좋을것 같은데. -// Assert.assertNotSame("check classLoader", aClass.getClassLoader(), loader); - logger.debug("mysql cl:{}", aClass.getClassLoader()); - - Class version = loader.loadClass("com.nhn.pinpoint.common.Version"); - Assert.assertSame("check classLoader", this.getClass().getClassLoader(), version.getClassLoader()); - logger.debug("common cl:{}", version.getClassLoader()); - return driver; + private Connection connectDB(String url) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException { + Driver driver = new NonRegisteringDriver(); + Properties properties = new Properties(); + properties.setProperty("user", "lucytest"); + properties.setProperty("password", "testlucy"); + return driver.connect(url, properties); } @Test public void loadBalancedUrlModify() throws Exception { - Driver driver = loadClass(); - - Properties properties = new Properties(); - properties.setProperty("user", "lucytest"); - properties.setProperty("password", "testlucy"); - Connection connection = driver.connect("jdbc:mysql:loadbalance://10.98.133.23:3306,10.98.133.22:3306/hippo", properties); + Connection connection = connectDB("jdbc:mysql:loadbalance://10.98.133.23:3306,10.98.133.22:3306/hippo"); logger.info("Connection class name:{}", connection.getClass().getName()); logger.info("Connection class cl:{}", connection.getClass().getClassLoader()); @@ -188,7 +147,6 @@ private void preparedStatement3(Connection connection) throws SQLException { connection.commit(); - connection.setAutoCommit(true); } From 231dc3d7726e0f0f2098c787d01eb40c5dc09f2c Mon Sep 17 00:00:00 2001 From: Woonduk Kang Date: Wed, 24 Sep 2014 11:38:21 +0900 Subject: [PATCH 14/18] [#10] add mssqlserver test, testcase refactoring --- .gitignore | 1 + .../config/CollectorConfiguration.java | 2 +- ...t.xml => applicationContext-collector.xml} | 0 collector/src/main/webapp/WEB-INF/web.xml | 2 +- .../receiver/tcp/TCPReceiverBOTest.java | 2 +- .../pinpoint/common/ServiceType.java | 4 +- .../pinpoint/common/bo/AgentInfoBo.java | 11 +- .../common/util/ClassLoaderUtils.java | 26 + .../pinpoint/common/util/PropertyUtils.java | 74 +- .../common/hbase/HbaseTemplate2Test.java | 3 +- .../common/util/ClassLoaderUtilsTest.java | 51 ++ .../common/util/PropertyUtilsTest.java | 28 + commons/src/test/resources/test.properties | 1 + .../javaassist/TestBootstrapClass.java | 12 +- .../junit4/PinpointJUnit4ClassRunner.java | 7 +- .../db/cubrid/CubridConnectionTest.java | 35 +- .../modifier/db/jtds/JtdsConnectionTest.java | 20 +- .../MySQLConnectionImplModifierTest.java | 43 +- .../src/test/resources/database.properties | 24 + .../ApacheClosableAsyncHttpClient.java | 3 +- ...acheClosableAsyncHttpClientController.java | 71 +- .../testweb/controller/BLOC4Controller.java | 22 +- .../testweb/controller/CubridController.java | 66 +- .../testweb/controller/DemoController.java | 323 +++++---- .../controller/DoNothingController.java | 18 +- .../controller/ExceptionalCaseController.java | 41 +- .../controller/HelloWorldController.java | 640 +++++++++--------- .../controller/HttpClient4Controller.java | 73 +- .../testweb/controller/MainController.java | 200 +++--- .../controller/MsSqlServerController.java | 47 ++ .../testweb/controller/MySqlController.java | 169 ++--- .../NHNEntHttpClientController.java | 62 +- .../testweb/controller/NIMMController.java | 51 +- .../testweb/controller/NPCController.java | 409 ++++++----- .../NingAsyncHTTPClientController.java | 201 +++--- .../testweb/controller/OracleController.java | 44 +- .../testweb/controller/OrmController.java | 206 +++--- .../ControllerMappingInfo.java} | 6 +- .../testweb/repository/CubridDao.java | 4 +- .../testweb/repository/CubridDaoIbatis.java | 12 +- .../testweb/repository/MsSqlServerDao.java | 11 + .../pinpoint/testweb/repository/MySqlDao.java | 2 +- .../testweb/repository/MySqlDaoIbatis.java | 7 +- .../testweb/repository/OracleDao.java | 2 +- .../testweb/repository/OracleDaoIbatis.java | 7 +- .../ibatis/SqlMapClientMemberDao.java | 2 +- .../testweb/service/MsSqlServerService.java | 12 + .../service/MsSqlServerServiceImpl.java | 27 + .../applicationContext-datasource.xml | 119 ++-- ...ext.xml => applicationContext-testweb.xml} | 172 +++-- .../src/main/resources/database.properties | 22 + .../resources/mssqlserver/SqlMapConfig.xml | 11 + .../main/resources/mssqlserver/sql-member.xml | 33 + .../main/resources/mssqlserver/test-sql.xml | 13 + .../orm/mybatis/mybatis-dao-config.xml | 4 +- .../src/main/resources/servlet-context.xml | 33 +- .../main/webapp/WEB-INF/views/orm/ibatis.jsp | 4 +- .../main/webapp/WEB-INF/views/orm/mybatis.jsp | 4 +- testweb/src/main/webapp/WEB-INF/web.xml | 6 +- testweb/src/main/webapp/index.html | 51 -- testweb/src/main/webapp/jsp.jsp | 1 - .../repository/MemberDaoIbatisTest.java | 2 +- .../testweb/repository/MemberDaoJdbcTest.java | 2 +- .../ApacheClosableAsyncHttpClientTest.java | 2 +- ...Context.xml => applicationContext-web.xml} | 0 web/src/main/webapp/WEB-INF/web.xml | 2 +- .../pinpoint/web/cluster/ClusterTest.java | 2 +- .../web/dao/hbase/HbaseAgentStatDaoTest.java | 2 +- .../filter/HbaseFilterPerformanceTest.java | 4 +- 69 files changed, 1873 insertions(+), 1700 deletions(-) rename collector/src/main/resources/{applicationContext.xml => applicationContext-collector.xml} (100%) create mode 100644 commons/src/main/java/com/navercorp/pinpoint/common/util/ClassLoaderUtils.java create mode 100644 commons/src/test/java/com/navercorp/pinpoint/common/util/ClassLoaderUtilsTest.java create mode 100644 commons/src/test/java/com/navercorp/pinpoint/common/util/PropertyUtilsTest.java create mode 100644 commons/src/test/resources/test.properties create mode 100644 profiler/src/test/resources/database.properties create mode 100644 testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MsSqlServerController.java rename testweb/src/main/java/com/nhn/pinpoint/testweb/{vo/RequestMappingInfo.java => domain/ControllerMappingInfo.java} (77%) create mode 100644 testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDao.java create mode 100644 testweb/src/main/java/com/nhn/pinpoint/testweb/service/MsSqlServerService.java create mode 100644 testweb/src/main/java/com/nhn/pinpoint/testweb/service/MsSqlServerServiceImpl.java rename testweb/src/main/resources/{root-context.xml => applicationContext-testweb.xml} (64%) create mode 100644 testweb/src/main/resources/mssqlserver/SqlMapConfig.xml create mode 100644 testweb/src/main/resources/mssqlserver/sql-member.xml create mode 100644 testweb/src/main/resources/mssqlserver/test-sql.xml delete mode 100644 testweb/src/main/webapp/jsp.jsp rename web/src/main/resources/{applicationContext.xml => applicationContext-web.xml} (100%) diff --git a/.gitignore b/.gitignore index 6df2d7096383..b559f5331c95 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ /.settings/ /.idea /*.iml +/deploy diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java b/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java index 027f066e7e5a..dc3299b1382e 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java @@ -147,7 +147,7 @@ public void readConfigFile() { } try { - Properties prop = PropertyUtils.readProperties(configFileName); + Properties prop = PropertyUtils.loadProperty(configFileName); readPropertyValues(prop); } catch (FileNotFoundException fe) { logger.error("File '{}' is not exists. Please check configuration.", configFileName, fe); diff --git a/collector/src/main/resources/applicationContext.xml b/collector/src/main/resources/applicationContext-collector.xml similarity index 100% rename from collector/src/main/resources/applicationContext.xml rename to collector/src/main/resources/applicationContext-collector.xml diff --git a/collector/src/main/webapp/WEB-INF/web.xml b/collector/src/main/webapp/WEB-INF/web.xml index e592b4154b31..d44141aa1382 100644 --- a/collector/src/main/webapp/WEB-INF/web.xml +++ b/collector/src/main/webapp/WEB-INF/web.xml @@ -17,7 +17,7 @@ contextConfigLocation - classpath:applicationContext.xml + classpath:applicationContext-collector.xml diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiverBOTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiverBOTest.java index 5dca2df40c35..d045011c7973 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiverBOTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiverBOTest.java @@ -30,7 +30,7 @@ /** * @author koo.taejin */ -@ContextConfiguration("classpath:applicationContext.xml") +@ContextConfiguration("classpath:applicationContext-collector.xml") @RunWith(SpringJUnit4ClassRunner.class) public class TCPReceiverBOTest { diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java b/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java index 3dc39c20eeee..118b9ab378d6 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java @@ -65,8 +65,8 @@ public enum ServiceType { MYSQL((short) 2100, "MYSQL", TERMINAL, !RECORD_STATISTICS, INCLUDE_DESTINATION, NORMAL_SCHEMA), MYSQL_EXECUTE_QUERY((short) 2101, "MYSQL", TERMINAL, RECORD_STATISTICS, INCLUDE_DESTINATION, NORMAL_SCHEMA), - MSSQL((short) 2200, "MSSQL", TERMINAL, !RECORD_STATISTICS, INCLUDE_DESTINATION, NORMAL_SCHEMA), - MSSQL_EXECUTE_QUERY((short) 2201, "MSSQL", TERMINAL, RECORD_STATISTICS, INCLUDE_DESTINATION, NORMAL_SCHEMA), + MSSQL((short) 2200, "MSSQLSERVER", TERMINAL, !RECORD_STATISTICS, INCLUDE_DESTINATION, NORMAL_SCHEMA), + MSSQL_EXECUTE_QUERY((short) 2201, "MSSQLSERVER", TERMINAL, RECORD_STATISTICS, INCLUDE_DESTINATION, NORMAL_SCHEMA), ORACLE((short) 2300, "ORACLE", TERMINAL, !RECORD_STATISTICS, INCLUDE_DESTINATION, NORMAL_SCHEMA), ORACLE_EXECUTE_QUERY((short) 2301, "ORACLE", TERMINAL, RECORD_STATISTICS, INCLUDE_DESTINATION, NORMAL_SCHEMA), diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/bo/AgentInfoBo.java b/commons/src/main/java/com/navercorp/pinpoint/common/bo/AgentInfoBo.java index 00be5a0120bd..b51a1685c2cf 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/bo/AgentInfoBo.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/bo/AgentInfoBo.java @@ -5,7 +5,6 @@ import com.nhn.pinpoint.common.buffer.Buffer; import com.nhn.pinpoint.common.buffer.FixedBuffer; import com.nhn.pinpoint.thrift.dto.TAgentInfo; -import org.apache.commons.lang.StringUtils; import java.util.Comparator; @@ -18,10 +17,14 @@ public class AgentInfoBo { @Override public int compare(AgentInfoBo that, AgentInfoBo other) { // null 일때 상황이 애매할수 있어서 그냥 ""으로 처리함. - final String thatAgentId = StringUtils.defaultString(that.agentId); - final String otherAgentId = StringUtils.defaultString(other.agentId); + final String thatAgentId = defaultString(that.agentId); + final String otherAgentId = defaultString(other.agentId); return thatAgentId.compareTo(otherAgentId); } + + private String defaultString(String string) { + return string == null ? "" : string; + } }; @@ -150,7 +153,7 @@ public byte[] writeValue() { buffer.putPrefixedString(this.getApplicationName()); buffer.put(this.serviceType.getCode()); buffer.put(this.getPid()); - buffer.putPrefixedString(this.getVersion());; + buffer.putPrefixedString(this.getVersion()); buffer.put(this.getStartTime()); buffer.put(this.getEndTimeStamp()); diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/ClassLoaderUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/ClassLoaderUtils.java new file mode 100644 index 000000000000..fcd1e7b7e9a8 --- /dev/null +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/ClassLoaderUtils.java @@ -0,0 +1,26 @@ +package com.nhn.pinpoint.common.util; + +/** + * @author emeroad + */ +public final class ClassLoaderUtils { + + public static ClassLoader getClassLoader() { + return getDefaultClassLoader(ClassLoaderUtils.class.getClassLoader()); + } + + public static ClassLoader getDefaultClassLoader(ClassLoader defaultClassLoader) { + ClassLoader classLoader = null; + try { + final Thread th = Thread.currentThread(); + classLoader = th.getContextClassLoader(); + } catch (Throwable e) { + // skip + } + if (classLoader == null) { + return defaultClassLoader; + } + return classLoader; + } + +} diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/PropertyUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/PropertyUtils.java index ba4d2483c517..e327717d690d 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/PropertyUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/PropertyUtils.java @@ -7,29 +7,69 @@ * @author emeroad */ public class PropertyUtils { + public static final String DEFAULT_ENCODING = "UTF-8"; - public static Properties readProperties(String propertyPath) throws IOException { - Properties properties = new Properties(); + public static interface InputStreamFactory { + InputStream openInputStream() throws IOException; + } + + public static Properties loadProperty(final String filePath) throws IOException { + if (filePath == null) { + throw new NullPointerException("filePath must not be null"); + } + final InputStreamFactory inputStreamFactory = new InputStreamFactory() { + @Override + public InputStream openInputStream() throws IOException { + return new FileInputStream(filePath); + } + }; + return loadProperty(new Properties(), inputStreamFactory, DEFAULT_ENCODING); + } + + public static Properties loadPropertyFromClassPath(final String classPath) throws IOException { + if (classPath == null) { + throw new NullPointerException("classPath must not be null"); + } + final InputStreamFactory inputStreamFactory = new InputStreamFactory() { + @Override + public InputStream openInputStream() throws IOException { + return ClassLoaderUtils.getDefaultClassLoader(PropertyUtils.class.getClassLoader()).getResourceAsStream(classPath); + } + }; + return loadProperty(new Properties(), inputStreamFactory, DEFAULT_ENCODING); + } + + + public static Properties loadProperty(Properties properties, InputStreamFactory inputStreamFactory, String encoding) throws IOException { + if (properties == null) { + throw new NullPointerException("properties must not be null"); + } + if (inputStreamFactory == null) { + throw new NullPointerException("inputStreamFactory must not be null"); + } + if (encoding == null) { + throw new NullPointerException("encoding must not be null"); + } InputStream in = null; Reader reader = null; try { - in = new FileInputStream(propertyPath); - reader = new InputStreamReader(in, "UTF-8"); + in = inputStreamFactory.openInputStream(); + reader = new InputStreamReader(in, encoding); properties.load(reader); } finally { - if (in != null) { - try { - in.close(); - } catch (IOException ignore) { - } - } - if (reader != null) { - try { - reader.close(); - } catch (IOException ignore) { - } - } + close(reader); + close(in); } return properties; - } + } + + private static void close(Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException ignore) { + } + } + } + } diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2Test.java b/commons/src/test/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2Test.java index 6658d093bc81..b979b2af77d9 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2Test.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2Test.java @@ -27,8 +27,7 @@ public class HbaseTemplate2Test { @BeforeClass public static void beforeClass() throws IOException { - String path = HbaseTemplate2Test.class.getClassLoader().getResource("test-hbase.properties").getPath(); - Properties properties = PropertyUtils.readProperties(path); + Properties properties = PropertyUtils.loadPropertyFromClassPath("test-hbase.properties"); Configuration cfg = HBaseConfiguration.create(); cfg.set("hbase.zookeeper.quorum", properties.getProperty("hbase.client.host")); diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/ClassLoaderUtilsTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/ClassLoaderUtilsTest.java new file mode 100644 index 000000000000..cc62a98e7d08 --- /dev/null +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/ClassLoaderUtilsTest.java @@ -0,0 +1,51 @@ +package com.nhn.pinpoint.common.util; + +import junit.framework.Assert; +import org.junit.Test; + +import java.net.URL; +import java.net.URLClassLoader; + +public class ClassLoaderUtilsTest { + + private static final URLClassLoader FAKE_CLASS_LOADER = new URLClassLoader(new URL[0]); + + @Test + public void testGetClassLoader1() throws Exception { + final Thread thread = Thread.currentThread(); + final ClassLoader contextClassLoader = thread.getContextClassLoader(); + + ClassLoader classLoader = ClassLoaderUtils.getClassLoader(); + + Assert.assertSame(contextClassLoader, classLoader); + } + + @Test + public void testGetClassLoader2() throws Exception { + final Thread thread = Thread.currentThread(); + final ClassLoader old = Thread.currentThread().getContextClassLoader(); + + thread.setContextClassLoader(FAKE_CLASS_LOADER); + ClassLoader classLoader = ClassLoaderUtils.getClassLoader(); + try { + Assert.assertSame(classLoader, FAKE_CLASS_LOADER); + } finally { + thread.setContextClassLoader(old); + } + } + + @Test + public void testGetClassLoader3() throws Exception { + final Thread thread = Thread.currentThread(); + final ClassLoader old = thread.getContextClassLoader(); + + thread.setContextClassLoader(null); + + ClassLoader classLoader = ClassLoaderUtils.getDefaultClassLoader(FAKE_CLASS_LOADER); + try { + Assert.assertSame(classLoader, FAKE_CLASS_LOADER); + } finally { + thread.setContextClassLoader(old); + } + } +} \ No newline at end of file diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/PropertyUtilsTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/PropertyUtilsTest.java new file mode 100644 index 000000000000..0b51e95ef52d --- /dev/null +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/PropertyUtilsTest.java @@ -0,0 +1,28 @@ +package com.nhn.pinpoint.common.util; + +import junit.framework.Assert; +import org.junit.Test; + +import java.util.Properties; + +public class PropertyUtilsTest { + + @Test + public void testLoadProperty() throws Exception { + String path = PropertyUtils.class.getClassLoader().getResource("test.properties").getPath(); + + Properties properties = PropertyUtils.loadProperty(path); + assertProperty(properties); + } + + @Test + public void testLoadPropertyFromClassPath() throws Exception { + Properties properties = PropertyUtils.loadPropertyFromClassPath("test.properties"); + assertProperty(properties); + } + + private void assertProperty(Properties properties) { + String test = properties.getProperty("test"); + Assert.assertEquals("pinpoint", test); + } +} \ No newline at end of file diff --git a/commons/src/test/resources/test.properties b/commons/src/test/resources/test.properties new file mode 100644 index 000000000000..1757282f7f02 --- /dev/null +++ b/commons/src/test/resources/test.properties @@ -0,0 +1 @@ +test=pinpoint \ No newline at end of file diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/javaassist/TestBootstrapClass.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/javaassist/TestBootstrapClass.java index 735cfd662521..55a268eedea4 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/javaassist/TestBootstrapClass.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/javaassist/TestBootstrapClass.java @@ -42,7 +42,7 @@ public void test() throws ClassNotFoundException, NoSuchMethodException, Invocat defineClass(defineClass1, systemClassLoader, new Object[]{"com.test.Test", bytes, 0, bytes.length}); Class aClass = systemClassLoader.loadClass("com.test.Test"); - logger.info("" + aClass.getClass().getClassLoader()); + logger.info("{}", aClass.getClass().getClassLoader()); } @@ -65,14 +65,14 @@ public void testJdkClassClassLoader() throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); logger.info(urlConnection.toString()); - logger.info("" + urlConnection.getClass().getClassLoader()); + logger.info("{}", urlConnection.getClass().getClassLoader()); ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); ClassLoader parent = systemClassLoader.getParent(); - logger.info("parent:" + parent); - logger.info("pparent:" + parent.getParent()); + logger.info("parent:{}", parent); + logger.info("pparent:{}", parent.getParent()); - logger.info("" + String.class.getClassLoader()); - logger.info("" + TestBootstrapClass.class.getClassLoader()); + logger.info("{}", String.class.getClassLoader()); + logger.info("{}", TestBootstrapClass.class.getClassLoader()); urlConnection.disconnect(); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java index aff1cc685a9b..7a96078d1d79 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java @@ -121,12 +121,13 @@ private TestClassLoader createTestClassLoader(Class< protected void runChild(FrameworkMethod method, RunNotifier notifier) { TraceContext traceContext = this.testAgent.getTraceContext(); beginTracing(traceContext); - ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + final Thread thread = Thread.currentThread(); + final ClassLoader originalClassLoader = thread.getContextClassLoader(); try { - Thread.currentThread().setContextClassLoader(this.testClassLoader); + thread.setContextClassLoader(this.testClassLoader); super.runChild(method, notifier); } finally { - Thread.currentThread().setContextClassLoader(originalClassLoader); + thread.setContextClassLoader(originalClassLoader); endTracing(traceContext); } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionTest.java index 29b88d1b685e..99a78dacda16 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionTest.java @@ -1,18 +1,14 @@ package com.nhn.pinpoint.profiler.modifier.db.cubrid; -import com.nhn.pinpoint.bootstrap.config.ProfilerConfig; import com.nhn.pinpoint.bootstrap.context.DatabaseInfo; import com.nhn.pinpoint.bootstrap.interceptor.tracevalue.DatabaseInfoTraceValue; -import com.nhn.pinpoint.bootstrap.logging.PLoggerFactory; -import com.nhn.pinpoint.common.ServiceType; -import com.nhn.pinpoint.profiler.DefaultAgent; + +import com.nhn.pinpoint.common.util.PropertyUtils; import com.nhn.pinpoint.profiler.junit4.BasePinpointTest; -import com.nhn.pinpoint.profiler.logging.Slf4jLoggerBinder; -import com.nhn.pinpoint.profiler.util.MockAgent; -import com.nhn.pinpoint.profiler.util.TestClassLoader; + import cubrid.jdbc.driver.CUBRIDDriver; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,6 +23,12 @@ public class CubridConnectionTest extends BasePinpointTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private static Properties db; + + @BeforeClass + public static void beforeClass() throws Exception { + db = PropertyUtils.loadPropertyFromClassPath("database.properties"); + } @Test public void executeQueryAndExecuteUpdate() throws SQLException { @@ -42,15 +44,18 @@ public void executeQueryAndExecuteUpdate() throws SQLException { } private Connection connectDB() throws SQLException { + String url = db.getProperty("cubrid.url"); + String user = db.getProperty("cubrid.user"); + String password = db.getProperty("cubrid.password"); + Driver driver = new CUBRIDDriver(); Properties properties = new Properties(); - properties.setProperty("user", "dba"); - properties.setProperty("password", "nhn!@#123"); - return driver.connect("jdbc:cubrid:10.101.57.233:30102:pinpoint:::", properties); + properties.setProperty("user", user); + properties.setProperty("password", password); + return driver.connect(url, properties); } - @Test public void testModify() throws Exception { @@ -59,7 +64,7 @@ public void testModify() throws Exception { logger.info("Connection class name:{}", connection.getClass().getName()); logger.info("Connection class cl:{}", connection.getClass().getClassLoader()); - DatabaseInfo url = ((DatabaseInfoTraceValue)connection).__getTraceDatabaseInfo(); + DatabaseInfo url = ((DatabaseInfoTraceValue) connection).__getTraceDatabaseInfo(); Assert.assertNotNull(url); statement(connection); @@ -82,7 +87,7 @@ public void testModify() throws Exception { connection.close(); - DatabaseInfo clearUrl = ((DatabaseInfoTraceValue)connection).__getTraceDatabaseInfo(); + DatabaseInfo clearUrl = ((DatabaseInfoTraceValue) connection).__getTraceDatabaseInfo(); Assert.assertNull(clearUrl); } @@ -148,7 +153,7 @@ private void preparedStatement5(Connection connection) throws SQLException { private void preparedStatement6(Connection connection) throws SQLException { // Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS - int[] columnIndex = {1,2,3}; + int[] columnIndex = {1, 2, 3}; PreparedStatement preparedStatement = connection.prepareStatement("select 1", columnIndex); logger.info("PreparedStatement className:{}", preparedStatement.getClass().getName()); ResultSet resultSet = preparedStatement.executeQuery(); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java index 44cda6f72bb5..a8ccdd41b29e 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/jtds/JtdsConnectionTest.java @@ -3,15 +3,15 @@ import com.nhn.pinpoint.bootstrap.context.DatabaseInfo; import com.nhn.pinpoint.bootstrap.interceptor.tracevalue.DatabaseInfoTraceValue; import com.nhn.pinpoint.common.bo.SpanEventBo; +import com.nhn.pinpoint.common.util.PropertyUtils; import com.nhn.pinpoint.profiler.junit4.BasePinpointTest; import org.junit.Assert; +import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import java.sql.*; -import java.sql.Driver; import java.util.List; import java.util.Properties; @@ -22,6 +22,12 @@ public class JtdsConnectionTest extends BasePinpointTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private static Properties db; + + @BeforeClass + public static void beforeClass() throws Exception { + db = PropertyUtils.loadPropertyFromClassPath("database.properties"); + } @Test public void executeQueryAndExecuteUpdate() throws SQLException { @@ -37,11 +43,15 @@ public void executeQueryAndExecuteUpdate() throws SQLException { } private Connection connectDB() throws SQLException { + String url = db.getProperty("mssqlserver.url"); + String user = db.getProperty("mssqlserver.user"); + String password = db.getProperty("mssqlserver.password"); + Driver driver = new net.sourceforge.jtds.jdbc.Driver(); Properties properties = new Properties(); - properties.setProperty("user", "pinpoint_user"); - properties.setProperty("password", "pinpoint!234"); - return driver.connect("jdbc:jtds:sqlserver://10.99.220.85:1433/pinpoint_test", properties); + properties.setProperty("user", user); + properties.setProperty("password", password); + return driver.connect(url, properties); } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLConnectionImplModifierTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLConnectionImplModifierTest.java index 0cb890d47e5e..cdb7409a942e 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLConnectionImplModifierTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/mysql/MySQLConnectionImplModifierTest.java @@ -2,21 +2,12 @@ import com.mysql.jdbc.JDBC4PreparedStatement; import com.mysql.jdbc.NonRegisteringDriver; -import com.nhn.pinpoint.bootstrap.interceptor.tracevalue.DatabaseInfoTraceValue; -import com.nhn.pinpoint.common.ServiceType; -import com.nhn.pinpoint.profiler.DefaultAgent; -import com.nhn.pinpoint.bootstrap.config.ProfilerConfig; import com.nhn.pinpoint.bootstrap.context.DatabaseInfo; - -import com.nhn.pinpoint.bootstrap.logging.PLoggerFactory; +import com.nhn.pinpoint.bootstrap.interceptor.tracevalue.DatabaseInfoTraceValue; +import com.nhn.pinpoint.common.util.PropertyUtils; import com.nhn.pinpoint.profiler.junit4.BasePinpointTest; -import com.nhn.pinpoint.profiler.logging.Slf4jLoggerBinder; - - -import com.nhn.pinpoint.profiler.util.MockAgent; -import com.nhn.pinpoint.profiler.util.TestClassLoader; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,15 +25,22 @@ public class MySQLConnectionImplModifierTest extends BasePinpointTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private static Properties db; + + @BeforeClass + public static void beforeClass() throws Exception { + db = PropertyUtils.loadPropertyFromClassPath("database.properties"); + } + @Test public void testModify() throws Exception { - Connection connection = connectDB("jdbc:mysql://10.98.133.22:3306/hippo"); + Connection connection = connectDB(db.getProperty("mysql.url")); logger.info("Connection class name:{}", connection.getClass().getName()); logger.info("Connection class cl:{}", connection.getClass().getClassLoader()); - DatabaseInfo url = ((DatabaseInfoTraceValue)connection).__getTraceDatabaseInfo(); + DatabaseInfo url = ((DatabaseInfoTraceValue) connection).__getTraceDatabaseInfo(); Assert.assertNotNull(url); statement(connection); @@ -55,23 +53,26 @@ public void testModify() throws Exception { connection.close(); - DatabaseInfo clearUrl = ((DatabaseInfoTraceValue)connection).__getTraceDatabaseInfo(); + DatabaseInfo clearUrl = ((DatabaseInfoTraceValue) connection).__getTraceDatabaseInfo(); Assert.assertNull(clearUrl); } private Connection connectDB(String url) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException { + String user = db.getProperty("mysql.user"); + String password = db.getProperty("mysql.password"); + Driver driver = new NonRegisteringDriver(); Properties properties = new Properties(); - properties.setProperty("user", "lucytest"); - properties.setProperty("password", "testlucy"); + properties.setProperty("user", user); + properties.setProperty("password", password); return driver.connect(url, properties); } @Test public void loadBalancedUrlModify() throws Exception { - Connection connection = connectDB("jdbc:mysql:loadbalance://10.98.133.23:3306,10.98.133.22:3306/hippo"); + Connection connection = connectDB(db.getProperty("mysql.url.loadbalance")); logger.info("Connection class name:{}", connection.getClass().getName()); logger.info("Connection class cl:{}", connection.getClass().getClassLoader()); @@ -85,7 +86,7 @@ public void loadBalancedUrlModify() throws Exception { Object internalConnection = current.get(invocationHandler); - DatabaseInfo url = ((DatabaseInfoTraceValue)internalConnection).__getTraceDatabaseInfo(); + DatabaseInfo url = ((DatabaseInfoTraceValue) internalConnection).__getTraceDatabaseInfo(); Assert.assertNotNull(url); statement(connection); @@ -107,7 +108,7 @@ public void loadBalancedUrlModify() throws Exception { preparedStatement8(connection); connection.close(); - DatabaseInfo clearUrl = ((DatabaseInfoTraceValue)internalConnection).__getTraceDatabaseInfo(); + DatabaseInfo clearUrl = ((DatabaseInfoTraceValue) internalConnection).__getTraceDatabaseInfo(); Assert.assertNull(clearUrl); } @@ -171,7 +172,7 @@ private void preparedStatement5(Connection connection) throws SQLException { private void preparedStatement6(Connection connection) throws SQLException { // Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS - int[] columnIndex = {1,2,3}; + int[] columnIndex = {1, 2, 3}; PreparedStatement preparedStatement = connection.prepareStatement("select 1", columnIndex); logger.info("PreparedStatement className:{}", preparedStatement.getClass().getName()); ResultSet resultSet = preparedStatement.executeQuery(); diff --git a/profiler/src/test/resources/database.properties b/profiler/src/test/resources/database.properties new file mode 100644 index 000000000000..0a1b6e31d42c --- /dev/null +++ b/profiler/src/test/resources/database.properties @@ -0,0 +1,24 @@ +# oracle +oracle.url=jdbc:oracle:thin:@10.98.133.174:1725:INDEV +oracle.user=lucy +oracle.password=lucy!234 + +# ms sqlserver +mssqlserver.url=jdbc:jtds:sqlserver://10.99.220.85:1433/pinpoint_test +mssqlserver.user=pinpoint_user +mssqlserver.password=pinpoint!234 + +# mysql +#mysql.url=jdbc:mysql://10.98.133.22:3306/hippo +#mysql.url.loadbalance=jdbc:mysql:loadbalance://10.98.133.23:3306,10.98.133.22:3306/hippo +#mysql.user=lucytest +#mysql.password=testlucy +# ʿ. +mysql.url=jdbc:mysql://10.25.149.61:3306/MySQL?characterEncoding=UTF-8 +mysql.user=pinpoint +mysql.password=nhn!@#123 + +# cubrid +cubrid.url=jdbc:cubrid:10.101.57.233:30102:pinpoint::: +cubrid.user=dba +cubrid.password=nhn!@#123 \ No newline at end of file diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/connector/apachehttp4/ApacheClosableAsyncHttpClient.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/connector/apachehttp4/ApacheClosableAsyncHttpClient.java index 9ce5fdd10422..e0e1281e6c53 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/connector/apachehttp4/ApacheClosableAsyncHttpClient.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/connector/apachehttp4/ApacheClosableAsyncHttpClient.java @@ -67,8 +67,7 @@ public String post() { return result; } catch (Exception e) { - e.printStackTrace(); - return null; + throw new RuntimeException(e); } } } \ No newline at end of file diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/ApacheClosableAsyncHttpClientController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/ApacheClosableAsyncHttpClientController.java index e3a34588f37f..8d6975cebd78 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/ApacheClosableAsyncHttpClientController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/ApacheClosableAsyncHttpClientController.java @@ -1,52 +1,49 @@ package com.nhn.pinpoint.testweb.controller; +import com.nhn.pinpoint.testweb.connector.apachehttp4.ApacheClosableAsyncHttpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import com.nhn.pinpoint.testweb.connector.apachehttp4.ApacheClosableAsyncHttpClient; - /** - * * @author netspider - * */ @Controller public class ApacheClosableAsyncHttpClientController { - @Autowired - private ApacheClosableAsyncHttpClient client; - - @RequestMapping(value = "/apacheClosableAsyncHttp/get") - public @ResponseBody - String requestGet(Model model) { - return "NOT_IMPLEMENTED"; - } - - @RequestMapping(value = "/apacheClosableAsyncHttp/getWithParam") - public @ResponseBody - String requestGetWithParam(Model model) { - return "NOT_IMPLEMENTED"; - } - - @RequestMapping(value = "/apacheClosableAsyncHttp/post") - public @ResponseBody - String requestPost(Model model) { - client.post(); - return "OK"; - } - - @RequestMapping(value = "/apacheClosableAsyncHttp/postWithBody") - public @ResponseBody - String requestPostWithBody(Model model) { - return "NOT_IMPLEMENTED"; - } - - @RequestMapping(value = "/apacheClosableAsyncHttp/postWithMultipart") - public @ResponseBody - String requestPostWithMultipart(Model model) { - return "NOT_IMPLEMENTED"; - } + @Autowired + private ApacheClosableAsyncHttpClient client; + + @RequestMapping(value = "/apacheClosableAsyncHttp/get") + @ResponseBody + public String requestGet() { + return "NOT_IMPLEMENTED"; + } + + @RequestMapping(value = "/apacheClosableAsyncHttp/getWithParam") + @ResponseBody + public String requestGetWithParam() { + return "NOT_IMPLEMENTED"; + } + + @RequestMapping(value = "/apacheClosableAsyncHttp/post") + @ResponseBody + public String requestPost() { + client.post(); + return "OK"; + } + + @RequestMapping(value = "/apacheClosableAsyncHttp/postWithBody") + @ResponseBody + public String requestPostWithBody() { + return "NOT_IMPLEMENTED"; + } + + @RequestMapping(value = "/apacheClosableAsyncHttp/postWithMultipart") + @ResponseBody + public String requestPostWithMultipart() { + return "NOT_IMPLEMENTED"; + } } \ No newline at end of file diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/BLOC4Controller.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/BLOC4Controller.java index 480719d3563b..ec460adf36a2 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/BLOC4Controller.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/BLOC4Controller.java @@ -1,28 +1,24 @@ package com.nhn.pinpoint.testweb.controller; +import com.nhn.pinpoint.testweb.connector.apachehttp4.nhnent.HttpUtil; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; -import com.nhn.pinpoint.testweb.connector.apachehttp4.nhnent.HttpUtil; - /** - * * @author netspider - * */ @Controller public class BLOC4Controller { - private final String LOCAL_BLOC4_FORMAT = "http://%s:%s/welcome/test/hello?name=netspider"; + private final String LOCAL_BLOC4_FORMAT = "http://%s:%s/welcome/test/hello?name=netspider"; - @RequestMapping(value = "/bloc4/callLocal") - public @ResponseBody - String requestGet(Model model, - @RequestParam(required = false, defaultValue = "localhost") String host, - @RequestParam(required = false, defaultValue = "5001") String port) { - return HttpUtil.url(String.format(LOCAL_BLOC4_FORMAT, host, port)).method(HttpUtil.Method.GET).connectionTimeout(10000).readTimeout(10000).getContents(); - } + @RequestMapping(value = "/bloc4/callLocal") + @ResponseBody + public String requestGet( + @RequestParam(required = false, defaultValue = "localhost") String host, + @RequestParam(required = false, defaultValue = "5001") String port) { + return HttpUtil.url(String.format(LOCAL_BLOC4_FORMAT, host, port)).method(HttpUtil.Method.GET).connectionTimeout(10000).readTimeout(10000).getContents(); + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/CubridController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/CubridController.java index 4c2ee4e7c7ed..3dbacef461fe 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/CubridController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/CubridController.java @@ -1,55 +1,43 @@ package com.nhn.pinpoint.testweb.controller; +import com.nhn.pinpoint.testweb.service.CubridService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import com.nhn.pinpoint.testweb.service.CubridService; - /** * */ @Controller public class CubridController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - private CubridService cubridService; - - @RequestMapping(value = "/cubrid/selectOne") - public @ResponseBody - String selectOne(Model model) { - try { - logger.info("selectOne start"); - - int i = cubridService.selectOne(); - - logger.info("selectOne end:{}", i); - return "OK"; - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - } - - @RequestMapping(value = "/cubrid/createStatement") - public @ResponseBody - String oracleStatement(Model model) { - try { - logger.info("createStatement start"); - - cubridService.createStatement(); - - logger.info("createStatement end:{}"); - return "OK"; - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + private CubridService cubridService; + + @RequestMapping(value = "/cubrid/selectOne") + @ResponseBody + public String selectOne() { + logger.info("selectOne start"); + + int i = cubridService.selectOne(); + + logger.info("selectOne end:{}", i); + return "OK"; + } + + @RequestMapping(value = "/cubrid/createStatement") + @ResponseBody + public String createStatement() { + logger.info("createStatement start"); + + cubridService.createStatement(); + + logger.info("createStatement end:{}"); + return "OK"; + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/DemoController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/DemoController.java index 7329ecbd5e7f..6d9192bbc9ec 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/DemoController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/DemoController.java @@ -1,22 +1,5 @@ package com.nhn.pinpoint.testweb.controller; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; - import com.nhn.pinpoint.testweb.configuration.DemoURLHolder; import com.nhn.pinpoint.testweb.connector.apachehttp4.ApacheHttpClient4; import com.nhn.pinpoint.testweb.connector.apachehttp4.HttpConnectorOptions; @@ -25,157 +8,171 @@ import com.nhn.pinpoint.testweb.service.CubridService; import com.nhn.pinpoint.testweb.service.MemberService; import com.ning.http.client.cookie.Cookie; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.*; /** - * * @author netspider - * */ @Controller public class DemoController { - private final DemoURLHolder urls; - - private final Random random = new Random(); - - @Autowired - private CacheService cacheService; - - @Autowired - @Qualifier("memberService") - private MemberService mysqlService; - - @Autowired - private CubridService cubridService; - - @Autowired - private NingAsyncHttpClient ningAsyncHttpClient; - - @Autowired - private ApacheHttpClient4 apacheHttpClient; - - public DemoController() { - urls = DemoURLHolder.getHolder(); - } - - @RequestMapping(value = "/netspider") - public @ResponseBody - String demo1() { - accessNaverBlog(); - accessNaverCafe(); - randomSlowMethod(); - callRemote(urls.getBackendApiURL()); - return "OK"; - } - - @RequestMapping(value = "/emeroad") - public @ResponseBody - String demo2() { - randomSlowMethod(); - callRemote(urls.getBackendWebURL()); - return "OK"; - } - - @RequestMapping(value = "/harebox") - public @ResponseBody - String demo3() { - cacheService.memcached(); - accessNaver(); - return "OK"; - } - - @RequestMapping(value = "/denny") - public @ResponseBody - String demo4() { - mysqlService.list(); - randomSlowMethod(); - return "OK"; - } - - @RequestMapping(value = "/backendweb") - public @ResponseBody - String backendweb() { - cacheService.arcus(); - mysqlService.list(); - if (random.nextBoolean()) { - callRemote(urls.getBackendApiURL()); - } - return "OK"; - } - - @RequestMapping(value = "/backendapi") - public @ResponseBody - String backendapi() { - mysqlService.list(); - cubrid(); - return "OK"; - } - - private void callRemote(String url) { - apacheHttpClient.execute(url, new HashMap()); - } - - private void cubrid() { - switch (new Random().nextInt(3)) { - case 1: - cubridService.createErrorStatement(); - case 2: - cubridService.createStatement(); - case 3: - cubridService.selectOne(); - } - } - - private void accessNaver() { - Map params = new HashMap(); - params.put("query", "naver"); - params.put("ie", "utf8"); - - Map headers = new HashMap(); - headers.put("header1", "header1"); - headers.put("header2", "header2"); - - List cookies = new ArrayList(); - cookies.add(new Cookie("cookieName1", "cookieValue1", "cookieRawValue1", "", "/", 10, 10, false, false)); - cookies.add(new Cookie("cookieName2", "cookieValue2", "cookieRawValue2", "", "/", 10, 10, false, false)); - - ningAsyncHttpClient.requestGet("http://search.naver.com/search.naver?where=nexearch", params, headers, cookies); - } - - private void accessNaverBlog() { - ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); - client.execute("http://section.blog.naver.com/", new HashMap()); - } - - private void accessNaverCafe() { - HttpURLConnection connection = null; - BufferedReader reader = null; - try { - connection = (HttpURLConnection) new URL("http://section.cafe.naver.com/").openConnection(); - connection.connect(); - - reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - try { - if (reader != null) { - reader.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - if (connection != null) { - connection.disconnect(); - } - } - } - - private void randomSlowMethod() { - try { - Thread.sleep(((new Random().nextInt(90)) + 10) * 10L); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final DemoURLHolder urls; + + private final Random random = new Random(); + + @Autowired + private CacheService cacheService; + + @Autowired + @Qualifier("memberService") + private MemberService mysqlService; + + @Autowired + private CubridService cubridService; + + @Autowired + private NingAsyncHttpClient ningAsyncHttpClient; + + @Autowired + private ApacheHttpClient4 apacheHttpClient; + + public DemoController() { + urls = DemoURLHolder.getHolder(); + } + + @RequestMapping(value = "/netspider") + @ResponseBody + public String demo1() { + accessNaverBlog(); + accessNaverCafe(); + randomSlowMethod(); + callRemote(urls.getBackendApiURL()); + return "OK"; + } + + @RequestMapping(value = "/emeroad") + @ResponseBody + public String demo2() { + randomSlowMethod(); + callRemote(urls.getBackendWebURL()); + return "OK"; + } + + @RequestMapping(value = "/harebox") + @ResponseBody + public String demo3() { + cacheService.memcached(); + accessNaver(); + return "OK"; + } + + @RequestMapping(value = "/denny") + @ResponseBody + public String demo4() { + mysqlService.list(); + randomSlowMethod(); + return "OK"; + } + + @RequestMapping(value = "/backendweb") + @ResponseBody + public String backendweb() { + cacheService.arcus(); + mysqlService.list(); + if (random.nextBoolean()) { + callRemote(urls.getBackendApiURL()); + } + return "OK"; + } + + @RequestMapping(value = "/backendapi") + @ResponseBody + public String backendapi() { + mysqlService.list(); + cubrid(); + return "OK"; + } + + private void callRemote(String url) { + apacheHttpClient.execute(url, new HashMap()); + } + + private void cubrid() { + switch (new Random().nextInt(3)) { + case 1: + cubridService.createErrorStatement(); + case 2: + cubridService.createStatement(); + case 3: + cubridService.selectOne(); + } + } + + private void accessNaver() { + Map params = new HashMap(); + params.put("query", "naver"); + params.put("ie", "utf8"); + + Map headers = new HashMap(); + headers.put("header1", "header1"); + headers.put("header2", "header2"); + + List cookies = new ArrayList(); + cookies.add(new Cookie("cookieName1", "cookieValue1", "cookieRawValue1", "", "/", 10, 10, false, false)); + cookies.add(new Cookie("cookieName2", "cookieValue2", "cookieRawValue2", "", "/", 10, 10, false, false)); + + ningAsyncHttpClient.requestGet("http://search.naver.com/search.naver?where=nexearch", params, headers, cookies); + } + + private void accessNaverBlog() { + ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); + client.execute("http://section.blog.naver.com/", new HashMap()); + } + + private void accessNaverCafe() { + HttpURLConnection connection = null; + BufferedReader reader = null; + try { + connection = (HttpURLConnection) new URL("http://section.cafe.naver.com/").openConnection(); + connection.connect(); + + reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + try { + if (reader != null) { + reader.close(); + } + } catch (IOException e) { + logger.warn("reader.close() error {}", e.getMessage(), e); + } + if (connection != null) { + connection.disconnect(); + } + } + } + + private void randomSlowMethod() { + try { + Thread.sleep(((new Random().nextInt(90)) + 10) * 10L); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/DoNothingController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/DoNothingController.java index 290b9216db85..275c0327877f 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/DoNothingController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/DoNothingController.java @@ -1,23 +1,19 @@ package com.nhn.pinpoint.testweb.controller; +import com.nhn.pinpoint.testweb.util.Description; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import com.nhn.pinpoint.testweb.util.Description; - /** - * * @author netspider - * */ @Controller public class DoNothingController { - @Description("아무일도 하지 않음.") - @RequestMapping(value = "/donothing") - public @ResponseBody - String donothing(Model model) { - return "OK"; - } + @Description("아무일도 하지 않음.") + @RequestMapping(value = "/donothing") + @ResponseBody + public String donothing() { + return "OK"; + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/ExceptionalCaseController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/ExceptionalCaseController.java index 2141bd6484a9..72cf7b5447dc 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/ExceptionalCaseController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/ExceptionalCaseController.java @@ -1,9 +1,8 @@ package com.nhn.pinpoint.testweb.controller; -import com.nhn.pinpoint.testweb.connector.apachehttp4.HttpConnectorOptions; import com.nhn.pinpoint.testweb.connector.apachehttp4.ApacheHttpClient4; +import com.nhn.pinpoint.testweb.connector.apachehttp4.HttpConnectorOptions; import com.nhn.pinpoint.testweb.util.Description; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; @@ -14,23 +13,23 @@ @Controller public class ExceptionalCaseController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - /** - * 루트의 완성이 지연될 경우 먼저 끝난 rpc콜을 정상적으로 읽을수 있는지 테스트 - */ - @Description("root의 완료가 지연될경우 parent가 완료된 데이터를 정상적으로 확인가능지.") - @RequestMapping(value = "/exceptionalcase/rootslow") - public void rootSlow() { - ApacheHttpClient4 client2 = new ApacheHttpClient4(new HttpConnectorOptions()); - client2.execute("http://localhost:8080/donothing.pinpoint", new HashMap()); - - try { - final int sleep = 1000 * 30; - logger.info("sleep:{}", sleep); - Thread.sleep(sleep); - } catch (InterruptedException e) { - - } - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + /** + * 루트의 완성이 지연될 경우 먼저 끝난 rpc콜을 정상적으로 읽을수 있는지 테스트 + */ + @Description("root의 완료가 지연될경우 parent가 완료된 데이터를 정상적으로 확인가능지.") + @RequestMapping(value = "/exceptionalcase/rootslow") + public void rootSlow() { + ApacheHttpClient4 client2 = new ApacheHttpClient4(new HttpConnectorOptions()); + client2.execute("http://localhost:8080/donothing.pinpoint", new HashMap()); + + try { + final int sleep = 1000 * 30; + logger.info("sleep:{}", sleep); + Thread.sleep(sleep); + } catch (InterruptedException e) { + + } + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/HelloWorldController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/HelloWorldController.java index d8d5c5e65810..835ba30a57a2 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/HelloWorldController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/HelloWorldController.java @@ -1,19 +1,18 @@ package com.nhn.pinpoint.testweb.controller; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - +import com.nhn.pinpoint.testweb.connector.apachehttp4.ApacheHttpClient4; +import com.nhn.pinpoint.testweb.connector.apachehttp4.HttpConnectorOptions; +import com.nhn.pinpoint.testweb.domain.Member; +import com.nhn.pinpoint.testweb.service.CacheService; +import com.nhn.pinpoint.testweb.service.DummyService; +import com.nhn.pinpoint.testweb.service.MemberService; +import com.nhn.pinpoint.testweb.util.Description; +import com.nhncorp.lucy.net.invoker.InvocationFuture; +import com.nhncorp.lucy.npc.connector.NpcHessianConnector; import net.spy.memcached.AddrUtil; import net.spy.memcached.ArcusClient; import net.spy.memcached.ConnectionFactoryBuilder; import net.spy.memcached.MemcachedClient; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; @@ -24,329 +23,312 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; - import perftest.LevelManager; -import com.nhn.pinpoint.testweb.connector.apachehttp4.HttpConnectorOptions; -import com.nhn.pinpoint.testweb.connector.apachehttp4.ApacheHttpClient4; -import com.nhn.pinpoint.testweb.domain.Member; -import com.nhn.pinpoint.testweb.service.CacheService; -import com.nhn.pinpoint.testweb.service.DummyService; -import com.nhn.pinpoint.testweb.service.MemberService; -import com.nhn.pinpoint.testweb.util.Description; -import com.nhncorp.lucy.net.invoker.InvocationFuture; -import com.nhncorp.lucy.npc.connector.NpcHessianConnector; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; @Controller @Deprecated public class HelloWorldController implements DisposableBean { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - private final ArcusClient arcus; - private final MemcachedClient memcached; - private final LevelManager levelManager; - - public HelloWorldController() throws IOException { - arcus = ArcusClient.createArcusClient("dev.arcuscloud.nhncorp.com:17288", "dev", new ConnectionFactoryBuilder()); - memcached = new MemcachedClient(AddrUtil.getAddresses("10.25.149.80:11244,10.25.149.80:11211,10.25.149.79:11211")); - levelManager = new LevelManager(); - } - - @Autowired - @Qualifier("memberService") - private MemberService service; - - @Autowired - private DummyService dummyService; - - @Autowired - private CacheService cacheService; - - private void randomSlowMethod() { - try { - Thread.sleep((new Random().nextInt(3)) * 1000L); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - @RequestMapping(value = "/dummy") - public @ResponseBody - String dummy(Model model) { - dummyService.doSomething(); - return "OK"; - } - - @RequestMapping(value = "/encoding") - public @ResponseBody - String encoding(Model model, @RequestParam("name") String name) { - logger.debug("name=" + name); - return "OK"; - } - - @RequestMapping(value = "/arcus") - public @ResponseBody - String arcus(Model model) { - cacheService.arcus(); - return "OK"; - } - - @RequestMapping(value = "/memcached") - public @ResponseBody - String memcached(Model model) { - cacheService.memcached(); - return "OK"; - } - - @RequestMapping(value = "/mysql") - public @ResponseBody - String mysql(Model model) { - int id = (new Random()).nextInt(); - - Member member = new Member(); - member.setId(id); - member.setName("chisu"); - member.setJoined(new Date()); - - // add - service.add(member); - - // list - service.list(); - - // del - service.delete(id); - - return "OK"; - } - - @Description("바인드 변수 + 상수값 파싱 로직테스트") - @RequestMapping(value = "/mysqlStatement") - public @ResponseBody - String mysqlStatement(Model model) { - int id = (new Random()).nextInt(); - - Member member = new Member(); - member.setId(id); - member.setName("chisu"); - member.setJoined(new Date()); - - // add - service.addStatement(member); - - // list - service.list(); - - // del - service.delete(id); - - return "OK"; - } - - @RequestMapping(value = "/nested") - public @ResponseBody - String nested(Model model) { - ApacheHttpClient4 client2 = new ApacheHttpClient4(new HttpConnectorOptions()); - client2.execute("http://localhost:8080/donothing.pinpoint", new HashMap()); - - ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); - client.execute("http://www.naver.com/", new HashMap()); - mysql(model); - return "OK"; - } - - @RequestMapping(value = "/remotecombination") - public @ResponseBody - String remotecombination(Model model) { - String[] ports = new String[] { "9080", "10080", "11080" }; - Random random = new Random(); - String port = ports[random.nextInt(3)]; - - ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); - client.execute("http://localhost:" + port + "/combination.pinpoint", new HashMap()); - - ApacheHttpClient4 client2 = new ApacheHttpClient4(new HttpConnectorOptions()); - client2.execute("http://localhost:8080/arcus.pinpoint", new HashMap()); - - client.execute("http://www.naver.com/", new HashMap()); - client.execute("http://www.naver.com/", new HashMap()); - try { - client.execute("http://very.very.very.long.long.url/", new HashMap()); - client.execute("http://url1/", new HashMap()); - client.execute("http://url2/", new HashMap()); - client.execute("http://url2/", new HashMap()); - client.execute("http://url3/", new HashMap()); - client.execute("http://url3/", new HashMap()); - client.execute("http://url3/", new HashMap()); - } catch (Exception e) { - } - return "OK"; - } - - @RequestMapping(value = "/remotearcus") - public @ResponseBody - String remotearcus(Model model) { - arcus(model); - - String[] ports = new String[] { "9080", "10080", "11080" }; - Random random = new Random(); - String port = ports[random.nextInt(3)]; - ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); - client.execute("http://localhost:" + port + "/arcus.pinpoint", new HashMap()); - return "OK"; - } - - @RequestMapping(value = "/combination") - public @ResponseBody - String combination(Model model) { - try { - mysql(model); - } catch (Exception e) { - e.printStackTrace(); - } - - try { - arcus(model); - } catch (Exception e) { - e.printStackTrace(); - } - - try { - memcached(model); - } catch (Exception e) { - e.printStackTrace(); - } - - randomSlowMethod(); - - ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); - client.execute("http://www.naver.com/", new HashMap()); - client.execute("http://www.naver.com/", new HashMap()); - - client.execute("http://section.cafe.naver.com/", new HashMap()); - client.execute("http://section.cafe.naver.com/", new HashMap()); - - npc(model); - - return "OK"; - } - - @RequestMapping(value = "/httperror") - public @ResponseBody - String httperror(Model model) { - ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); - client.execute("http://127.0.0.1/", new HashMap()); - return "OK"; - } - - @RequestMapping(value = "/error500") - public @ResponseBody - String error500(Model model) { - try { - int i = 1 / 0; - return "OK"; - } catch (Exception e) { - return e.getMessage(); - } - } - - @RequestMapping(value = "/slow") - public @ResponseBody - String slow(Model model) { - try { - Thread.sleep(new Random().nextInt(10) * 100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return "OK"; - } - - @RequestMapping(value = "/throwexception") - public @ResponseBody - String exception(Model model) { - throw new RuntimeException("Exception test"); - } - - @RequestMapping(value = "/arcustimeout") - public @ResponseBody - String arcustimeout(Model model) { - Future future = null; - try { - future = arcus.set("pinpoint:expect-timeout", 10, "Hello, Timeout."); - future.get(10L, TimeUnit.MICROSECONDS); - } catch (Exception e) { - if (future != null) - future.cancel(true); - e.printStackTrace(); - return e.getMessage(); - } - return "OK"; - } - - @RequestMapping(value = "/remotesimple") - public @ResponseBody - String remotesimple(Model model) { - String[] ports = new String[] { "9080", "10080", "11080" }; - Random random = new Random(); - String port = ports[random.nextInt(3)]; - - arcus(model); - - ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); - client.execute("http://localhost:" + port + "/arcus.pinpoint", new HashMap()); - return "OK"; - } - - @RequestMapping(value = "/remoteerror") - public @ResponseBody - String remoteError(Model model) { - ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); - client.execute("http://localhost:10080/rpcerror.pinpoint", new HashMap()); - return "OK"; - } - - @RequestMapping(value = "/rpcerror") - public @ResponseBody - String rpcError(Model model) { - ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); - client.execute("UNKNOWN_URL", new HashMap()); - return "OK"; - } - - @RequestMapping(value = "/npc") - public @ResponseBody - String npc(Model model) { - try { - InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); - NpcHessianConnector connector = new NpcHessianConnector(serverAddress, true); - - Map params = new HashMap(); - params.put("message", "hello pinpoint"); - - InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); - - future.await(); - - // Object result = future.get(); - Object result = future.getReturnValue(); - System.out.println("npc result=" + result); - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - return "OK"; - } - - @RequestMapping(value = "/perftest") - public @ResponseBody - String perfTest(Model model) { - levelManager.traverse(); - return "OK"; - } - - @Override - public void destroy() throws Exception { - arcus.shutdown(); - memcached.shutdown(); - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final ArcusClient arcus; + private final MemcachedClient memcached; + private final LevelManager levelManager; + + public HelloWorldController() throws IOException { + arcus = ArcusClient.createArcusClient("dev.arcuscloud.nhncorp.com:17288", "dev", new ConnectionFactoryBuilder()); + memcached = new MemcachedClient(AddrUtil.getAddresses("10.25.149.80:11244,10.25.149.80:11211,10.25.149.79:11211")); + levelManager = new LevelManager(); + } + + @Autowired + @Qualifier("memberService") + private MemberService service; + + @Autowired + private DummyService dummyService; + + @Autowired + private CacheService cacheService; + + private void randomSlowMethod() { + try { + Thread.sleep((new Random().nextInt(3)) * 1000L); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + @RequestMapping(value = "/dummy") + @ResponseBody + public String dummy() { + dummyService.doSomething(); + return "OK"; + } + + @RequestMapping(value = "/encoding") + @ResponseBody + public String encoding(Model model, @RequestParam("name") String name) { + logger.debug("name=" + name); + return "OK"; + } + + @RequestMapping(value = "/arcus") + @ResponseBody + public String arcus() { + cacheService.arcus(); + return "OK"; + } + + @RequestMapping(value = "/memcached") + @ResponseBody + public String memcached() { + cacheService.memcached(); + return "OK"; + } + + @RequestMapping(value = "/mysql") + @ResponseBody + public String mysql() { + int id = (new Random()).nextInt(); + + Member member = new Member(); + member.setId(id); + member.setName("pinpoint_user"); + member.setJoined(new Date()); + + // add + service.add(member); + + // list + service.list(); + + // del + service.delete(id); + + return "OK"; + } + + @Description("바인드 변수 + 상수값 파싱 로직테스트") + @RequestMapping(value = "/mysqlStatement") + @ResponseBody + public String mysqlStatement() { + int id = (new Random()).nextInt(); + + Member member = new Member(); + member.setId(id); + member.setName("pinpoint_user"); + member.setJoined(new Date()); + + // add + service.addStatement(member); + + // list + service.list(); + + // del + service.delete(id); + + return "OK"; + } + + @RequestMapping(value = "/nested") + @ResponseBody + public String nested() { + ApacheHttpClient4 client2 = new ApacheHttpClient4(new HttpConnectorOptions()); + client2.execute("http://localhost:8080/donothing.pinpoint", new HashMap()); + + ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); + client.execute("http://www.naver.com/", new HashMap()); + mysql(); + return "OK"; + } + + @RequestMapping(value = "/remotecombination") + @ResponseBody + public String remotecombination() { + String[] ports = new String[]{"9080", "10080", "11080"}; + Random random = new Random(); + String port = ports[random.nextInt(3)]; + + ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); + client.execute("http://localhost:" + port + "/combination.pinpoint", new HashMap()); + + ApacheHttpClient4 client2 = new ApacheHttpClient4(new HttpConnectorOptions()); + client2.execute("http://localhost:8080/arcus.pinpoint", new HashMap()); + + client.execute("http://www.naver.com/", new HashMap()); + client.execute("http://www.naver.com/", new HashMap()); + try { + client.execute("http://very.very.very.long.long.url/", new HashMap()); + client.execute("http://url1/", new HashMap()); + client.execute("http://url2/", new HashMap()); + client.execute("http://url2/", new HashMap()); + client.execute("http://url3/", new HashMap()); + client.execute("http://url3/", new HashMap()); + client.execute("http://url3/", new HashMap()); + } catch (Exception e) { + } + return "OK"; + } + + @RequestMapping(value = "/remotearcus") + @ResponseBody + public String remotearcus() { + arcus(); + + String[] ports = new String[]{"9080", "10080", "11080"}; + Random random = new Random(); + String port = ports[random.nextInt(3)]; + ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); + client.execute("http://localhost:" + port + "/arcus.pinpoint", new HashMap()); + return "OK"; + } + + @RequestMapping(value = "/combination") + @ResponseBody + public String combination() { + + mysql(); + + arcus(); + + memcached(); + + + randomSlowMethod(); + + ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); + client.execute("http://www.naver.com/", new HashMap()); + client.execute("http://www.naver.com/", new HashMap()); + + client.execute("http://section.cafe.naver.com/", new HashMap()); + client.execute("http://section.cafe.naver.com/", new HashMap()); + + npc(); + + return "OK"; + } + + @RequestMapping(value = "/httperror") + @ResponseBody + public String httperror() { + ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); + client.execute("http://127.0.0.1/", new HashMap()); + return "OK"; + } + + @RequestMapping(value = "/error500") + @ResponseBody + public String error500() { + int i = 1 / 0; + return "OK"; + + } + + @RequestMapping(value = "/slow") + @ResponseBody + public String slow() { + try { + Thread.sleep(new Random().nextInt(10) * 100); + } catch (InterruptedException e) { + } + return "OK"; + } + + @RequestMapping(value = "/throwexception") + @ResponseBody + public String exception() { + throw new RuntimeException("Exception test"); + } + + @RequestMapping(value = "/arcustimeout") + @ResponseBody + public String arcustimeout() { + Future future = null; + try { + future = arcus.set("pinpoint:expect-timeout", 10, "Hello, Timeout."); + future.get(10L, TimeUnit.MICROSECONDS); + } catch (Exception e) { + if (future != null) { + future.cancel(true); + } + throw new RuntimeException(e); + } + return "OK"; + } + + @RequestMapping(value = "/remotesimple") + @ResponseBody + public String remotesimple() { + String[] ports = new String[]{"9080", "10080", "11080"}; + Random random = new Random(); + String port = ports[random.nextInt(3)]; + + arcus(); + + ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); + client.execute("http://localhost:" + port + "/arcus.pinpoint", new HashMap()); + return "OK"; + } + + @RequestMapping(value = "/remoteerror") + @ResponseBody + public String remoteError() { + ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); + client.execute("http://localhost:10080/rpcerror.pinpoint", new HashMap()); + return "OK"; + } + + @RequestMapping(value = "/rpcerror") + @ResponseBody + public String rpcError() { + ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); + client.execute("UNKNOWN_URL", new HashMap()); + return "OK"; + } + + @RequestMapping(value = "/npc") + @ResponseBody + public String npc() { + try { + InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); + NpcHessianConnector connector = new NpcHessianConnector(serverAddress, true); + + Map params = new HashMap(); + params.put("message", "hello pinpoint"); + + InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); + + future.await(); + + // Object result = future.get(); + Object result = future.getReturnValue(); + logger.debug("npc result={}", result); + } catch (Exception e) { + throw new RuntimeException(e); + } + return "OK"; + } + + @RequestMapping(value = "/perftest") + @ResponseBody + public String perfTest() { + levelManager.traverse(); + return "OK"; + } + + @Override + public void destroy() throws Exception { + arcus.shutdown(); + memcached.shutdown(); + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/HttpClient4Controller.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/HttpClient4Controller.java index 85f4a75ac65a..cdb1a4feb78a 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/HttpClient4Controller.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/HttpClient4Controller.java @@ -1,7 +1,8 @@ package com.nhn.pinpoint.testweb.controller; -import java.util.HashMap; - +import com.nhn.pinpoint.testweb.connector.apachehttp4.ApacheHttpClient4; +import com.nhn.pinpoint.testweb.connector.apachehttp4.HttpConnectorOptions; +import com.nhn.pinpoint.testweb.util.Description; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; @@ -9,46 +10,42 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import com.nhn.pinpoint.testweb.connector.apachehttp4.ApacheHttpClient4; -import com.nhn.pinpoint.testweb.connector.apachehttp4.HttpConnectorOptions; -import com.nhn.pinpoint.testweb.util.Description; +import java.util.HashMap; /** - * * @author netspider - * */ @Controller public class HttpClient4Controller { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Description("에러시 cookie덤프") - @RequestMapping(value = "/httpclient4/cookie") - public @ResponseBody - String cookie(@RequestHeader(value = "Cookie", required = false) String cookie) { - logger.info("Cookie:{}", cookie); - - ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); - client.execute("http://localhost:" + 9999 + "/combination.pinpoint", new HashMap(), cookie); - - return "OK"; - } - - @Description("에러시 post덤프") - @RequestMapping(value = "/httpclient4/post") - public @ResponseBody - String post() { - logger.info("Post"); - // String[] ports = new String[] { "9080", "10080", "11080" }; - // Random random = new Random(); - // String port = ports[random.nextInt(3)]; - // - ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); - HashMap post = new HashMap(); - post.put("test", "1"); - post.put("test2", "2"); - client.execute("http://localhost:" + 9999 + "/combination.pinpoint", post); - - return "OK"; - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Description("에러시 cookie덤프") + @RequestMapping(value = "/httpclient4/cookie") + @ResponseBody + public String cookie(@RequestHeader(value = "Cookie", required = false) String cookie) { + logger.info("Cookie:{}", cookie); + + ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); + client.execute("http://localhost:" + 9999 + "/combination.pinpoint", new HashMap(), cookie); + + return "OK"; + } + + @Description("에러시 post덤프") + @RequestMapping(value = "/httpclient4/post") + @ResponseBody + public String post() { + logger.info("Post"); + // String[] ports = new String[] { "9080", "10080", "11080" }; + // Random random = new Random(); + // String port = ports[random.nextInt(3)]; + // + ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); + HashMap post = new HashMap(); + post.put("test", "1"); + post.put("test2", "2"); + client.execute("http://localhost:" + 9999 + "/combination.pinpoint", post); + + return "OK"; + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MainController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MainController.java index 8221a5bfcb63..00ed9765ae99 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MainController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MainController.java @@ -1,128 +1,102 @@ package com.nhn.pinpoint.testweb.controller; -import java.io.File; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - +import com.nhn.pinpoint.testweb.domain.ControllerMappingInfo; +import com.nhn.pinpoint.testweb.util.Description; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; -import com.nhn.pinpoint.testweb.vo.RequestMappingInfo; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.*; /** - * * @author netspider - * */ @Controller public class MainController { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final RequestMappingHandlerMapping handlerMapping; + + @Autowired + public MainController(RequestMappingHandlerMapping handlerMapping) { + this.handlerMapping = handlerMapping; + } + + + @RequestMapping(value = "/docs", method = RequestMethod.GET) + public String getEndPointsInView(Model model) { + model.addAttribute("mapping", getMappingInfo()); + return "docs"; + } + + + public Map> getMappingInfo() { + Map> info = new TreeMap>(); + + Map handlerMethods = handlerMapping.getHandlerMethods(); + for (Map.Entry requestMappingInfoHandlerMethodEntry : handlerMethods.entrySet()) { + RequestMappingInfo requestMappingInfoKey = requestMappingInfoHandlerMethodEntry.getKey(); + HandlerMethod handlerMethod = requestMappingInfoHandlerMethodEntry.getValue(); + Method method = handlerMethod.getMethod(); + Class declaringClass = method.getDeclaringClass(); + + List controllerMappingInfoList = info.get(declaringClass.getSimpleName()); + if (controllerMappingInfoList == null) { + controllerMappingInfoList = new ArrayList(); + info.put(declaringClass.getSimpleName(), controllerMappingInfoList); + } + + List requestInfo = createRequestMappingInfo(requestMappingInfoKey, handlerMethod); + controllerMappingInfoList.addAll(requestInfo); + } + sort(info); + + logger.debug("{}", info); + return info; + } + + private void sort(Map> info) { + for (List controllerMappingInfos : info.values()) { + Collections.sort(controllerMappingInfos, new Comparator() { + @Override + public int compare(ControllerMappingInfo o1, ControllerMappingInfo o2) { + return o1.getUrl().compareTo(o2.getUrl()); + } + }); + } + } + + private List createRequestMappingInfo(RequestMappingInfo requestMappingInfo, HandlerMethod handlerMethod) { + List requestInfo = new ArrayList(); + + Set patterns = requestMappingInfo.getPatternsCondition().getPatterns(); + for (String pattern : patterns) { + Description description = getDescription(handlerMethod); + ControllerMappingInfo info = new ControllerMappingInfo(pattern, (description == null) ? "" : description.value()); + requestInfo.add(info); + } + + return requestInfo; + } + + private Description getDescription(HandlerMethod handlerMethod) { + Annotation[] annotations = handlerMethod.getMethod().getAnnotations(); + for (Annotation annotation : annotations) { + if (annotation instanceof com.nhn.pinpoint.testweb.util.Description) { + return (Description) annotation; + } + } + + return null; + } - @RequestMapping(value = "/docs", method = RequestMethod.GET) - public String getEndPointsInView(Model model) { - model.addAttribute("mapping", getMappingInfo()); - return "docs"; - } - - public Map> getMappingInfo() { - Map> info = new HashMap>(); - try { - String packaze = "com.nhn.pinpoint.testweb.controller"; - ArrayList classNamesFromPackage = MainController.getClassNamesFromPackage(packaze); - - for (String className : classNamesFromPackage) { - Class clazz = Class.forName(packaze + "." + className); - - List requestInfo = new ArrayList(); - - Method[] methods = clazz.getDeclaredMethods(); - - for (Method m : methods) { - Annotation[] annotations = m.getDeclaredAnnotations(); - - org.springframework.web.bind.annotation.RequestMapping mappingInfo = null; - com.nhn.pinpoint.testweb.util.Description description = null; - - for (Annotation a : annotations) { - if (a instanceof org.springframework.web.bind.annotation.RequestMapping) { - mappingInfo = (org.springframework.web.bind.annotation.RequestMapping) a; - } - if (a instanceof com.nhn.pinpoint.testweb.util.Description) { - description = (com.nhn.pinpoint.testweb.util.Description) a; - } - } - - if (mappingInfo != null) { - requestInfo.add(new RequestMappingInfo(mappingInfo.value()[0], (description == null) ? "" : description.value())); - } - } - - if (requestInfo.size() > 0) { - info.put(clazz.getSimpleName(), requestInfo); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - return info; - } - - // spring에서 제공하는 기능이 있는것 같긴 하지만 그냥 구식으로. - public static ArrayList getClassNamesFromPackage(String packageName) throws IOException, URISyntaxException { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - URL packageURL; - ArrayList names = new ArrayList(); - - packageName = packageName.replace(".", "/"); - packageURL = classLoader.getResource(packageName); - - if (packageURL.getProtocol().equals("jar")) { - String jarFileName; - JarFile jf; - Enumeration jarEntries; - String entryName; - - // build jar file name, then loop through zipped entries - jarFileName = URLDecoder.decode(packageURL.getFile(), "UTF-8"); - jarFileName = jarFileName.substring(5, jarFileName.indexOf("!")); - System.out.println(">" + jarFileName); - jf = new JarFile(jarFileName); - jarEntries = jf.entries(); - while (jarEntries.hasMoreElements()) { - entryName = jarEntries.nextElement().getName(); - if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) { - entryName = entryName.substring(packageName.length(), entryName.lastIndexOf('.')); - names.add(entryName); - } - } - - // loop through files in classpath - } else { - URI uri = new URI(packageURL.toString()); - File folder = new File(uri.getPath()); - // won't work with path which contains blank (%20) - // File folder = new File(packageURL.getFile()); - File[] contenuti = folder.listFiles(); - String entryName; - for (File actual : contenuti) { - entryName = actual.getName(); - entryName = entryName.substring(0, entryName.lastIndexOf('.')); - names.add(entryName); - } - } - return names; - } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MsSqlServerController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MsSqlServerController.java new file mode 100644 index 000000000000..07794ff7d7e8 --- /dev/null +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MsSqlServerController.java @@ -0,0 +1,47 @@ +package com.nhn.pinpoint.testweb.controller; + +import com.nhn.pinpoint.testweb.service.MsSqlServerService; +import com.nhn.pinpoint.testweb.util.Description; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * + */ +@Controller +public class MsSqlServerController { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + private MsSqlServerService msSqlServerService; + + + @Description("preparedStatement 테스트. resultset은 가지고 오지 않음.") + @RequestMapping(value = "/mssqlserver/selectOne") + @ResponseBody + public String selectOne() { + logger.info("selectOne start"); + + int i = msSqlServerService.selectOne(); + + logger.info("selectOne end:{}", i); + return "OK"; + } + + @Description("statement 테스트. resultset은 가지고 오지 않음.") + @RequestMapping(value = "/mssqlserver/createStatement") + @ResponseBody + public String createStatement() { + logger.info("createStatement start"); + + msSqlServerService.createStatement(); + + logger.info("createStatement end:{}"); + + return "OK"; + } +} diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MySqlController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MySqlController.java index 71377f1cfc5e..a0e8eb3585e8 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MySqlController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/MySqlController.java @@ -1,111 +1,92 @@ package com.nhn.pinpoint.testweb.controller; -import java.util.Date; -import java.util.Random; - +import com.nhn.pinpoint.testweb.domain.Member; +import com.nhn.pinpoint.testweb.service.MemberService; +import com.nhn.pinpoint.testweb.service.MySqlService; +import com.nhn.pinpoint.testweb.util.Description; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import com.nhn.pinpoint.testweb.domain.Member; -import com.nhn.pinpoint.testweb.service.MemberService; -import com.nhn.pinpoint.testweb.service.MySqlService; -import com.nhn.pinpoint.testweb.util.Description; +import java.util.Date; +import java.util.Random; /** * */ @Controller public class MySqlController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - private MySqlService mySqlService; - - @Autowired - @Qualifier("memberService") - private MemberService service; - - @RequestMapping(value = "/mysql/crud") - public @ResponseBody - String crud(Model model) { - try { - int id = (new Random()).nextInt(); - - Member member = new Member(); - member.setId(id); - member.setName("chisu"); - member.setJoined(new Date()); - - service.add(member); - service.list(); - service.delete(id); - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - - return "OK"; - } - - @RequestMapping(value = "/mysql/crudWithStatement") - public @ResponseBody - String crudWithStatement(Model model) { - try { - int id = (new Random()).nextInt(); - - Member member = new Member(); - member.setId(id); - member.setName("chisu"); - member.setJoined(new Date()); - - service.addStatement(member); - service.list(); - service.delete(id); - - return "OK"; - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - } - - @Description("preparedStatement 테스트. resultset은 가지고 오지 않음.") - @RequestMapping(value = "/mysql/selectOne") - public @ResponseBody - String selectOne(Model model) { - try { - logger.info("selectOne start"); - - int i = mySqlService.selectOne(); - - logger.info("selectOne end:{}", i); - return "OK"; - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - } - - @Description("statement 테스트. resultset은 가지고 오지 않음.") - @RequestMapping(value = "/mysql/createStatement") - public @ResponseBody - String oracleStatement(Model model) { - try { - logger.info("createStatement start"); - - mySqlService.createStatement(); - - logger.info("createStatement end:{}"); - return "OK"; - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + private MySqlService mySqlService; + + @Autowired + @Qualifier("memberService") + private MemberService service; + + @RequestMapping(value = "/mysql/crud") + @ResponseBody + public String crud() { + int id = (new Random()).nextInt(); + + Member member = new Member(); + member.setId(id); + member.setName("pinpoint_user"); + member.setJoined(new Date()); + + service.add(member); + service.list(); + service.delete(id); + + return "OK"; + } + + @RequestMapping(value = "/mysql/crudWithStatement") + @ResponseBody + public String crudWithStatement() { + + int id = (new Random()).nextInt(); + + Member member = new Member(); + member.setId(id); + member.setName("pinpoint_user"); + member.setJoined(new Date()); + + service.addStatement(member); + service.list(); + service.delete(id); + + return "OK"; + } + + @Description("preparedStatement 테스트. resultset은 가지고 오지 않음.") + @RequestMapping(value = "/mysql/selectOne") + @ResponseBody + public String selectOne() { + logger.info("selectOne start"); + + int i = mySqlService.selectOne(); + + logger.info("selectOne end:{}", i); + return "OK"; + + } + + @Description("statement 테스트. resultset은 가지고 오지 않음.") + @RequestMapping(value = "/mysql/createStatement") + @ResponseBody + public String createStatement() { + logger.info("createStatement start"); + + mySqlService.createStatement(); + + logger.info("createStatement end:{}"); + return "OK"; + + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NHNEntHttpClientController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NHNEntHttpClientController.java index 4f38754e6a90..6b870a4ac178 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NHNEntHttpClientController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NHNEntHttpClientController.java @@ -1,48 +1,44 @@ package com.nhn.pinpoint.testweb.controller; +import com.nhn.pinpoint.testweb.connector.apachehttp4.nhnent.HttpUtil; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; -import com.nhn.pinpoint.testweb.connector.apachehttp4.nhnent.HttpUtil; - /** - * * @author netspider - * */ @Controller public class NHNEntHttpClientController { - @RequestMapping(value = "/nhnent/get") - public @ResponseBody - String requestGet(Model model, @RequestParam(required = false, defaultValue = "http") String protocol) { - return HttpUtil.url(protocol + "://www.naver.com").method(HttpUtil.Method.GET).connectionTimeout(10000).readTimeout(10000).getContents(); - } - - @RequestMapping(value = "/nhnent/getWithParam") - public @ResponseBody - String requestGetWithParam(Model model) { - return "NOT_IMPLEMENTED"; - } - - @RequestMapping(value = "/nhnent/post") - public @ResponseBody - String requestPost(Model model, @RequestParam(required = false, defaultValue = "http") String protocol) { - return HttpUtil.url(protocol + "://www.naver.com").method(HttpUtil.Method.POST).connectionTimeout(10000).readTimeout(10000).getContents(); - } - - @RequestMapping(value = "/nhnent/postWithBody") - public @ResponseBody - String requestPostWithBody(Model model) { - return "NOT_IMPLEMENTED"; - } - - @RequestMapping(value = "/nhnent/postWithMultipart") - public @ResponseBody - String requestPostWithMultipart(Model model) { - return "NOT_IMPLEMENTED"; - } + @RequestMapping(value = "/nhnent/get") + @ResponseBody + public String requestGet(Model model, @RequestParam(required = false, defaultValue = "http") String protocol) { + return HttpUtil.url(protocol + "://www.naver.com").method(HttpUtil.Method.GET).connectionTimeout(10000).readTimeout(10000).getContents(); + } + + @RequestMapping(value = "/nhnent/getWithParam") + @ResponseBody + public String requestGetWithParam() { + return "NOT_IMPLEMENTED"; + } + + @RequestMapping(value = "/nhnent/post") + @ResponseBody + public String requestPost(Model model, @RequestParam(required = false, defaultValue = "http") String protocol) { + return HttpUtil.url(protocol + "://www.naver.com").method(HttpUtil.Method.POST).connectionTimeout(10000).readTimeout(10000).getContents(); + } + + @RequestMapping(value = "/nhnent/postWithBody") + @ResponseBody + public String requestPostWithBody() { + return "NOT_IMPLEMENTED"; + } + + @RequestMapping(value = "/nhnent/postWithMultipart") + public String requestPostWithMultipart() { + return "NOT_IMPLEMENTED"; + } } \ No newline at end of file diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NIMMController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NIMMController.java index fb05d2982048..2a69e2e0f2b5 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NIMMController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NIMMController.java @@ -1,48 +1,43 @@ package com.nhn.pinpoint.testweb.controller; +import com.nhn.pinpoint.testweb.nimm.mockupserver.NimmInvokerTest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import com.nhn.pinpoint.testweb.nimm.mockupserver.NimmInvokerTest; - /** - * * @author netspider - * */ @Controller public class NIMMController implements DisposableBean { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private NimmInvokerTest nimm; + @Autowired + private NimmInvokerTest nimm; - @RequestMapping(value = "/nimm/1") - public @ResponseBody - String npc(Model model) { - try { - nimm.testInvoke(); - } catch (Exception e) { - e.printStackTrace(); - return e.getMessage(); - } - return "OK"; - } + @RequestMapping(value = "/nimm/1") + @ResponseBody + public String npc() { + try { + nimm.testInvoke(); + } catch (Exception e) { + throw new RuntimeException(e); + } + return "OK"; + } - @Override - public void destroy() throws Exception { - try { - nimm.tearDown(); - } catch (Exception e) { - logger.warn("tearDown() error Caused:" + e.getMessage(), e); - } - nimm.dispose(); - } + @Override + public void destroy() throws Exception { + try { + nimm.tearDown(); + } catch (Exception e) { + logger.warn("tearDown() error Caused:" + e.getMessage(), e); + } + nimm.dispose(); + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NPCController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NPCController.java index 23b185dedc55..12a90e85eba3 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NPCController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NPCController.java @@ -1,230 +1,207 @@ package com.nhn.pinpoint.testweb.controller; -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Map; - +import com.nhncorp.lucy.net.invoker.InvocationFuture; +import com.nhncorp.lucy.net.invoker.InvocationFutureListener; +import com.nhncorp.lucy.npc.connector.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import com.nhncorp.lucy.net.invoker.InvocationFuture; -import com.nhncorp.lucy.net.invoker.InvocationFutureListener; -import com.nhncorp.lucy.npc.connector.ConnectionFactory; -import com.nhncorp.lucy.npc.connector.KeepAliveNpcHessianConnector; -import com.nhncorp.lucy.npc.connector.NpcConnectionFactory; -import com.nhncorp.lucy.npc.connector.NpcHessianConnector; +import java.net.InetSocketAddress; +import java.util.HashMap; +import java.util.Map; /** - * * @author netspider - * */ @Controller public class NPCController { - /** - * using basic connector - * - * @param model - * @return - */ - @RequestMapping(value = "/npc/1") - public @ResponseBody - String npc(Model model) { - NpcHessianConnector connector = null; - try { - InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); - connector = new NpcHessianConnector(serverAddress, true); - - Map params = new HashMap(); - params.put("message", "hello pinpoint"); - - InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); - - future.await(); - - // Object result = future.get(); - Object result = future.getReturnValue(); - System.out.println("npc result=" + result); - } catch (Exception e) { - e.printStackTrace(); - return e.getMessage(); - } finally { - if (connector != null) { - connector.dispose(); - } - } - return "OK"; - } - - /** - * using keepalive connector - * - * @param model - * @return - */ - @RequestMapping(value = "/npc/2") - public @ResponseBody - String npc2(Model model) { - KeepAliveNpcHessianConnector connector = null; - try { - InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); - - connector = new KeepAliveNpcHessianConnector(serverAddress); - - Map params = new HashMap(); - params.put("message", "hello pinpoint"); - - InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); - - future.await(); - - // Object result = future.get(); - Object result = future.getReturnValue(); - System.out.println("npc result=" + result); - } catch (Exception e) { - e.printStackTrace(); - return e.getMessage(); - } finally { - if (connector != null) { - connector.dispose(); - } - } - return "OK"; - } - - /** - * using connection factory - * - * @param model - * @return - */ - @RequestMapping(value = "/npc/3") - public @ResponseBody - String npc3(Model model) { - NpcHessianConnector connector = null; - try { - InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); - - ConnectionFactory npcConnectionFactory = new NpcConnectionFactory(); - - npcConnectionFactory.setTimeout(1000L); - npcConnectionFactory.setAddress(serverAddress); - - connector = npcConnectionFactory.create(); - - Map params = new HashMap(); - params.put("message", "hello pinpoint"); - - InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); - - future.await(); - - // Object result = future.get(); - Object result = future.getReturnValue(); - System.out.println("npc result=" + result); - } catch (Exception e) { - e.printStackTrace(); - return e.getMessage(); - } finally { - if (connector != null) { - connector.dispose(); - } - } - return "OK"; - } - - /** - * using lightweight connector - * - * @param model - * @return - */ - @RequestMapping(value = "/npc/4") - public @ResponseBody - String npc4(Model model) { - NpcHessianConnector connector = null; - try { - InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); - - ConnectionFactory npcConnectionFactory = new NpcConnectionFactory(); - - npcConnectionFactory.setTimeout(1000L); - npcConnectionFactory.setAddress(serverAddress); - npcConnectionFactory.setLightWeight(true); - - connector = npcConnectionFactory.create(); - - Map params = new HashMap(); - params.put("message", "hello pinpoint"); - - InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); - - future.await(); - - // Object result = future.get(); - Object result = future.getReturnValue(); - System.out.println("npc result=" + result); - } catch (Exception e) { - e.printStackTrace(); - return e.getMessage(); - } finally { - if (connector != null) { - connector.dispose(); - } - } - return "OK"; - } - - /** - * using lightweight connector and listener - * - * @param model - * @return - */ - @RequestMapping(value = "/npc/5") - public @ResponseBody - String npc5(Model model) { - NpcHessianConnector connector = null; - try { - InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); - - ConnectionFactory npcConnectionFactory = new NpcConnectionFactory(); - - npcConnectionFactory.setTimeout(1000L); - npcConnectionFactory.setAddress(serverAddress); - npcConnectionFactory.setLightWeight(true); - - connector = npcConnectionFactory.create(); - - Map params = new HashMap(); - params.put("message", "hello pinpoint"); - - InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); - - future.addListener(new InvocationFutureListener() { - @Override - public void invocationComplete(InvocationFuture future) throws Exception { - Object result = future.getReturnValue(); - System.out.println("npc result=" + result); - } - }); - } catch (Exception e) { - e.printStackTrace(); - return e.getMessage(); - } finally { - if (connector != null) { - connector.dispose(); - } - } - return "OK"; - } - - @RequestMapping(value = "/npc/6") - public @ResponseBody - String npcStream(Model model) { - return "NOT_IMPLEMENTED"; - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + /** + * using basic connector + * + * @return + */ + @RequestMapping(value = "/npc/1") + @ResponseBody + public String npc() throws Exception { + NpcHessianConnector connector = null; + try { + InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); + connector = new NpcHessianConnector(serverAddress, true); + + Map params = new HashMap(); + params.put("message", "hello pinpoint"); + + InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); + + future.await(); + + // Object result = future.get(); + Object result = future.getReturnValue(); + logger.debug("npc result={}", result); + } finally { + if (connector != null) { + connector.dispose(); + } + } + return "OK"; + } + + /** + * using keepalive connector + * + * @return + */ + @RequestMapping(value = "/npc/2") + @ResponseBody + public String npc2() throws Exception { + KeepAliveNpcHessianConnector connector = null; + try { + InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); + + connector = new KeepAliveNpcHessianConnector(serverAddress); + + Map params = new HashMap(); + params.put("message", "hello pinpoint"); + + InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); + + future.await(); + + // Object result = future.get(); + Object result = future.getReturnValue(); + logger.debug("npc result={}", result); + } finally { + if (connector != null) { + connector.dispose(); + } + } + return "OK"; + } + + /** + * using connection factory + * + * @return + */ + @RequestMapping(value = "/npc/3") + @ResponseBody + public String npc3() throws Exception { + NpcHessianConnector connector = null; + try { + InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); + + ConnectionFactory npcConnectionFactory = new NpcConnectionFactory(); + + npcConnectionFactory.setTimeout(1000L); + npcConnectionFactory.setAddress(serverAddress); + + connector = npcConnectionFactory.create(); + + Map params = new HashMap(); + params.put("message", "hello pinpoint"); + + InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); + + future.await(); + + // Object result = future.get(); + Object result = future.getReturnValue(); + logger.debug("npc result={}", result); + } finally { + if (connector != null) { + connector.dispose(); + } + } + return "OK"; + } + + /** + * using lightweight connector + * + * @return + */ + @RequestMapping(value = "/npc/4") + @ResponseBody + public String npc4() throws Exception { + NpcHessianConnector connector = null; + try { + InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); + + ConnectionFactory npcConnectionFactory = new NpcConnectionFactory(); + + npcConnectionFactory.setTimeout(1000L); + npcConnectionFactory.setAddress(serverAddress); + npcConnectionFactory.setLightWeight(true); + + connector = npcConnectionFactory.create(); + + Map params = new HashMap(); + params.put("message", "hello pinpoint"); + + InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); + + future.await(); + + // Object result = future.get(); + Object result = future.getReturnValue(); + logger.debug("npc result={}", result); + } finally { + if (connector != null) { + connector.dispose(); + } + } + return "OK"; + } + + /** + * using lightweight connector and listener + * + * @return + */ + @RequestMapping(value = "/npc/5") + @ResponseBody + public String npc5() throws NpcCallException { + NpcHessianConnector connector = null; + try { + InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000); + + ConnectionFactory npcConnectionFactory = new NpcConnectionFactory(); + + npcConnectionFactory.setTimeout(1000L); + npcConnectionFactory.setAddress(serverAddress); + npcConnectionFactory.setLightWeight(true); + + connector = npcConnectionFactory.create(); + + Map params = new HashMap(); + params.put("message", "hello pinpoint"); + + InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params); + + future.addListener(new InvocationFutureListener() { + @Override + public void invocationComplete(InvocationFuture future) throws Exception { + Object result = future.getReturnValue(); + logger.debug("npc result={}", result); + } + }); + } finally { + if (connector != null) { + connector.dispose(); + } + } + return "OK"; + } + + @RequestMapping(value = "/npc/6") + @ResponseBody + public String npcStream() { + return "NOT_IMPLEMENTED"; + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NingAsyncHTTPClientController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NingAsyncHTTPClientController.java index dc8dd00ccdeb..c7fb8ec7cbbc 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NingAsyncHTTPClientController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/NingAsyncHTTPClientController.java @@ -1,130 +1,105 @@ package com.nhn.pinpoint.testweb.controller; -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.nhn.pinpoint.testweb.connector.ningasync.NingAsyncHttpClient; +import com.ning.http.client.Part; +import com.ning.http.client.Response; +import com.ning.http.client.cookie.Cookie; +import com.ning.http.multipart.StringPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import com.nhn.pinpoint.testweb.connector.ningasync.NingAsyncHttpClient; -import com.ning.http.client.Part; -import com.ning.http.client.Response; -import com.ning.http.client.cookie.Cookie; -import com.ning.http.multipart.StringPart; +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** - * * @author netspider - * */ @Controller public class NingAsyncHTTPClientController { - private static final Logger logger = LoggerFactory.getLogger(NingAsyncHTTPClientController.class); - - @Autowired - private NingAsyncHttpClient ningAsyncHttpClient; - - @Autowired - private NingAsyncHttpClient httpInvoker; - - @RequestMapping(value = "/ningAsyncHttp/get") - public @ResponseBody - String requestGet(Model model) { - try { - Response r = httpInvoker.requestGet("http://www.naver.com", null, null, null); - logger.debug("r={}" + r.toString()); - return "OK"; - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - } - - @RequestMapping(value = "/ningAsyncHttp/getWithParam") - public @ResponseBody - String requestGetWithParam(Model model) { - try { - Map params = new HashMap(); - params.put("query", "naver"); - params.put("ie", "utf8"); - - Map headers = new HashMap(); - headers.put("header1", "header1"); - headers.put("header2", "header2"); - - List cookies = new ArrayList(); - cookies.add(new Cookie("cookieName1", "cookieValue1", "cookieRawValue1", "", "/", 10, 10, false, false)); - cookies.add(new Cookie("cookieName2", "cookieValue2", "cookieRawValue2", "", "/", 10, 10, false, false)); - - Response r = httpInvoker.requestGet("http://search.naver.com/search.naver?where=nexearch", params, headers, cookies); - logger.debug("r={}" + r.toString()); - return "OK"; - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - } - - @RequestMapping(value = "/ningAsyncHttp/post") - public @ResponseBody - String requestPost(Model model) { - try { - Response r = httpInvoker.requestPost("http://www.naver.com", null, null); - logger.debug("r={}" + r.toString()); - return "OK"; - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - } - - @RequestMapping(value = "/ningAsyncHttp/postWithBody") - public @ResponseBody - String requestPostWithBody(Model model) { - try { - Map headers = new HashMap(); - headers.put("header1", "header1"); - headers.put("header2", "header2"); - - Response r = httpInvoker.requestPost("http://www.naver.com", headers, "postbody"); - logger.debug("r={}" + r.toString()); - return "OK"; - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - } - - @RequestMapping(value = "/ningAsyncHttp/postWithMultipart") - public @ResponseBody - String requestPostWithMultipart(Model model) { - try { - Map headers = new HashMap(); - headers.put("header1", "header1"); - headers.put("header2", "header2"); - - List parts = new ArrayList(); - parts.add(new com.ning.http.client.ByteArrayPart("name1", "filename1", "data".getBytes(), "plain/text", "utf-8")); - parts.add(new com.ning.http.client.FilePart("name2", new File("./test"), "mimeType", "utf-8")); - parts.add(new com.ning.http.client.StringPart("name3", "value3")); - parts.add(new com.ning.http.multipart.FilePart("name4", new File("./test"))); - parts.add(new StringPart("name5", "value5")); - - Response r = httpInvoker.requestMultipart("http://www.naver.com", headers, parts); - logger.debug("r={}" + r.toString()); - return "OK"; - } catch (Exception e) { - logger.error(e.getMessage(), e); - return e.getMessage(); - } - } + private static final Logger logger = LoggerFactory.getLogger(NingAsyncHTTPClientController.class); + + @Autowired + private NingAsyncHttpClient ningAsyncHttpClient; + + @Autowired + private NingAsyncHttpClient httpInvoker; + + @RequestMapping(value = "/ningAsyncHttp/get") + @ResponseBody + public String requestGet() { + Response r = httpInvoker.requestGet("http://www.naver.com", null, null, null); + logger.debug("r={}" + r.toString()); + return "OK"; + } + + @RequestMapping(value = "/ningAsyncHttp/getWithParam") + @ResponseBody + public String requestGetWithParam() { + Map params = new HashMap(); + params.put("query", "naver"); + params.put("ie", "utf8"); + + Map headers = new HashMap(); + headers.put("header1", "header1"); + headers.put("header2", "header2"); + + List cookies = new ArrayList(); + cookies.add(new Cookie("cookieName1", "cookieValue1", "cookieRawValue1", "", "/", 10, 10, false, false)); + cookies.add(new Cookie("cookieName2", "cookieValue2", "cookieRawValue2", "", "/", 10, 10, false, false)); + + Response r = httpInvoker.requestGet("http://search.naver.com/search.naver?where=nexearch", params, headers, cookies); + logger.debug("r={}" + r.toString()); + return "OK"; + + } + + @RequestMapping(value = "/ningAsyncHttp/post") + @ResponseBody + public String requestPost() { + Response r = httpInvoker.requestPost("http://www.naver.com", null, null); + logger.debug("r={}" + r.toString()); + return "OK"; + + } + + @RequestMapping(value = "/ningAsyncHttp/postWithBody") + public String requestPostWithBody() { + Map headers = new HashMap(); + headers.put("header1", "header1"); + headers.put("header2", "header2"); + + Response r = httpInvoker.requestPost("http://www.naver.com", headers, "postbody"); + logger.debug("r={}" + r.toString()); + return "OK"; + + } + + @RequestMapping(value = "/ningAsyncHttp/postWithMultipart") + @ResponseBody + public String requestPostWithMultipart() throws FileNotFoundException { + Map headers = new HashMap(); + headers.put("header1", "header1"); + headers.put("header2", "header2"); + + List parts = new ArrayList(); + parts.add(new com.ning.http.client.ByteArrayPart("name1", "filename1", "data".getBytes(), "plain/text", "utf-8")); + parts.add(new com.ning.http.client.FilePart("name2", new File("./test"), "mimeType", "utf-8")); + parts.add(new com.ning.http.client.StringPart("name3", "value3")); + parts.add(new com.ning.http.multipart.FilePart("name4", new File("./test"))); + parts.add(new StringPart("name5", "value5")); + + Response r = httpInvoker.requestMultipart("http://www.naver.com", headers, parts); + logger.debug("r={}" + r.toString()); + return "OK"; + + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/OracleController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/OracleController.java index 77da745b741a..c1e4560c0153 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/OracleController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/OracleController.java @@ -2,12 +2,10 @@ import com.nhn.pinpoint.testweb.service.OracleService; import com.nhn.pinpoint.testweb.util.Description; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @@ -17,32 +15,32 @@ @Controller public class OracleController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private OracleService oracleService; + @Autowired + private OracleService oracleService; - @Description("preparedStatement 테스트. resultset은 가지고 오지 않음.") - @RequestMapping(value = "/oracle/selectOne") - public @ResponseBody - String selectOne(Model model) { - logger.info("selectOne start"); + @Description("preparedStatement 테스트. resultset은 가지고 오지 않음.") + @RequestMapping(value = "/oracle/selectOne") + @ResponseBody + public String selectOne() { + logger.info("selectOne start"); - int i = oracleService.selectOne(); + int i = oracleService.selectOne(); - logger.info("selectOne end:{}", i); - return "OK"; - } + logger.info("selectOne end:{}", i); + return "OK"; + } - @Description("statement 테스트. resultset은 가지고 오지 않음") - @RequestMapping(value = "/oracle/createStatement") - public @ResponseBody - String oracleStatement(Model model) { - logger.info("createStatement start"); + @Description("statement 테스트. resultset은 가지고 오지 않음") + @RequestMapping(value = "/oracle/createStatement") + @ResponseBody + public String createStatement() { + logger.info("createStatement start"); - oracleService.createStatement(); + oracleService.createStatement(); - logger.info("createStatement end:{}"); - return "OK"; - } + logger.info("createStatement end:{}"); + return "OK"; + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/OrmController.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/OrmController.java index 86d97ec42427..b507ca76a7c9 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/OrmController.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/controller/OrmController.java @@ -1,120 +1,118 @@ package com.nhn.pinpoint.testweb.controller; -import java.util.Date; - +import com.nhn.pinpoint.testweb.domain.Member; +import com.nhn.pinpoint.testweb.service.MemberService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; -import com.nhn.pinpoint.testweb.domain.Member; -import com.nhn.pinpoint.testweb.service.MemberService; +import java.util.Date; /** * @author Hyun Jeong */ @Controller public class OrmController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public static final String IBATIS_VIEW = "orm/ibatis"; - public static final String MYBATIS_VIEW = "orm/mybatis"; - - @Autowired - @Qualifier("sqlMapClientMemberService") - private MemberService sqlMapClientMemberService; - - @Autowired - @Qualifier("sqlMapSessionMemberService") - private MemberService sqlMapSessionMemberService; - - @Autowired - @Qualifier("myBatisMemberService") - private MemberService myBatisMemberService; - - @RequestMapping(value = "/orm/ibatis/sqlMapClient/query") - public String iBatisSqlMapClientQuery(Model model) { - logger.info("/orm/ibatis/sqlMapClient/query"); - - this.sqlMapClientMemberService.get(0); - - return IBATIS_VIEW; - } - - @RequestMapping(value = "/orm/ibatis/sqlMapClient/transaction") - public String iBatisSqlMapClientTranscation(Model model) { - logger.info("/orm/ibatis/sqlMapClient/transaction - add, update, get, delete"); - - runTransaction(this.sqlMapClientMemberService); - - return IBATIS_VIEW; - } - - @RequestMapping(value = "/orm/ibatis/sqlMapSession/query") - public String iBatisSqlMapSessionQuery(Model model) { - logger.info("/orm/ibatis/sqlMapSession/query"); - - this.sqlMapSessionMemberService.get(0); - - return IBATIS_VIEW; - } - - @RequestMapping(value = "/orm/ibatis/sqlMapSession/transaction") - public String iBatisSqlMapSessionTransaction(Model model) { - logger.info("/orm/ibatis/sqlMapSession/transaction - add, update, get, delete"); - - runTransaction(this.sqlMapSessionMemberService); - - return IBATIS_VIEW; - } - - @RequestMapping(value = "/orm/mybatis/sqlSessionTemplate/query") - public String myBatisSqlSessionTemplateQuery(Model model) { - logger.info("/orm/mybatis/sqlSessionTemplate/query"); - - this.myBatisMemberService.get(0); - - return MYBATIS_VIEW; - } - - @RequestMapping(value = "/orm/mybatis/sqlSessionTemplate/transaction") - public String myBatisSqlSessionTemplateTransaction(Model model) { - logger.info("/orm/mybatis/sqlSessionTemplate/transaction"); - - runTransaction(this.myBatisMemberService); - - return MYBATIS_VIEW; - } - - @RequestMapping(value = "/orm/mybatis/sqlSessionTemplate/invalid") - public String myBatisSqlSessionTemplateInvalid(Model model) { - logger.info("/orm/mybatis/sqlSessionTemplate/invalid"); - - this.myBatisMemberService.list(); - - return MYBATIS_VIEW; - } - - private void runTransaction(MemberService memberService) { - - final int memberId = 1574; - - Member member = new Member(); - member.setId(memberId); - member.setName("test User"); - member.setJoined(new Date(System.currentTimeMillis())); - - memberService.add(member); - - member.setName("updated test User"); - memberService.update(member); - - memberService.get(memberId); - logger.info("\tId:[" + member.getId() + "], name:[" + member.getName() + "]"); - - memberService.delete(memberId); - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public static final String IBATIS_VIEW = "orm/ibatis"; + public static final String MYBATIS_VIEW = "orm/mybatis"; + + @Autowired + @Qualifier("sqlMapClientMemberService") + private MemberService sqlMapClientMemberService; + + @Autowired + @Qualifier("sqlMapSessionMemberService") + private MemberService sqlMapSessionMemberService; + + @Autowired + @Qualifier("myBatisMemberService") + private MemberService myBatisMemberService; + + @RequestMapping(value = "/orm/ibatis/sqlMapClient/query") + public String iBatisSqlMapClientQuery() { + logger.info("/orm/ibatis/sqlMapClient/query"); + + this.sqlMapClientMemberService.get(0); + + return IBATIS_VIEW; + } + + @RequestMapping(value = "/orm/ibatis/sqlMapClient/transaction") + public String iBatisSqlMapClientTranscation() { + logger.info("/orm/ibatis/sqlMapClient/transaction - add, update, get, delete"); + + runTransaction(this.sqlMapClientMemberService); + + return IBATIS_VIEW; + } + + @RequestMapping(value = "/orm/ibatis/sqlMapSession/query") + public String iBatisSqlMapSessionQuery() { + logger.info("/orm/ibatis/sqlMapSession/query"); + + this.sqlMapSessionMemberService.get(0); + + return IBATIS_VIEW; + } + + @RequestMapping(value = "/orm/ibatis/sqlMapSession/transaction") + public String iBatisSqlMapSessionTransaction() { + logger.info("/orm/ibatis/sqlMapSession/transaction - add, update, get, delete"); + + runTransaction(this.sqlMapSessionMemberService); + + return IBATIS_VIEW; + } + + @RequestMapping(value = "/orm/mybatis/sqlSessionTemplate/query") + public String myBatisSqlSessionTemplateQuery() { + logger.info("/orm/mybatis/sqlSessionTemplate/query"); + + this.myBatisMemberService.get(0); + + return MYBATIS_VIEW; + } + + @RequestMapping(value = "/orm/mybatis/sqlSessionTemplate/transaction") + public String myBatisSqlSessionTemplateTransaction() { + logger.info("/orm/mybatis/sqlSessionTemplate/transaction"); + + runTransaction(this.myBatisMemberService); + + return MYBATIS_VIEW; + } + + @RequestMapping(value = "/orm/mybatis/sqlSessionTemplate/invalid") + public String myBatisSqlSessionTemplateInvalid() { + logger.info("/orm/mybatis/sqlSessionTemplate/invalid"); + + this.myBatisMemberService.list(); + + return MYBATIS_VIEW; + } + + private void runTransaction(MemberService memberService) { + + final int memberId = 1574; + + Member member = new Member(); + member.setId(memberId); + member.setName("test User"); + member.setJoined(new Date(System.currentTimeMillis())); + + memberService.add(member); + + member.setName("updated test User"); + memberService.update(member); + + memberService.get(memberId); + logger.info("\tId:[" + member.getId() + "], name:[" + member.getName() + "]"); + + memberService.delete(memberId); + } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/vo/RequestMappingInfo.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/domain/ControllerMappingInfo.java similarity index 77% rename from testweb/src/main/java/com/nhn/pinpoint/testweb/vo/RequestMappingInfo.java rename to testweb/src/main/java/com/nhn/pinpoint/testweb/domain/ControllerMappingInfo.java index 960b1d91789b..215f5c42b4a0 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/vo/RequestMappingInfo.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/domain/ControllerMappingInfo.java @@ -1,10 +1,10 @@ -package com.nhn.pinpoint.testweb.vo; +package com.nhn.pinpoint.testweb.domain; -public class RequestMappingInfo { +public class ControllerMappingInfo { private String url; private String description; - public RequestMappingInfo(String url, String description) { + public ControllerMappingInfo(String url, String description) { this.url = url; this.description = description; } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/CubridDao.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/CubridDao.java index c940d3deb49d..d55716872128 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/CubridDao.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/CubridDao.java @@ -6,7 +6,7 @@ public interface CubridDao { int selectOne(); - void createStatement(); + boolean createStatement(); - void createErrorStatement(); + boolean createErrorStatement(); } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/CubridDaoIbatis.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/CubridDaoIbatis.java index 4b0a25e280cd..841b991b00e8 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/CubridDaoIbatis.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/CubridDaoIbatis.java @@ -21,7 +21,7 @@ public class CubridDaoIbatis implements CubridDao { private SqlMapClientTemplate sqlMapClientTemplate; @Autowired - @Qualifier("cubridDatasource") + @Qualifier("cubridDataSource") private DataSource datasource; @Override @@ -30,13 +30,13 @@ public int selectOne() { } @Override - public void createStatement() { + public boolean createStatement() { Connection connection = null; Statement statement = null; try { connection = datasource.getConnection(); statement = connection.createStatement(); - statement.execute("select 1"); + return statement.execute("select 1"); } catch (SQLException e) { throw new RuntimeException(e); } finally { @@ -54,17 +54,16 @@ public void createStatement() { } } - //To change body of implemented methods use File | Settings | File Templates. } @Override - public void createErrorStatement() { + public boolean createErrorStatement() { Connection connection = null; Statement statement = null; try { connection = datasource.getConnection(); statement = connection.createStatement(); - statement.execute("SELECT * FROM NOT_EXISTS_TABLE"); + return statement.execute("SELECT * FROM NOT_EXISTS_TABLE"); } catch (SQLException e) { throw new RuntimeException(e); } finally { @@ -82,6 +81,5 @@ public void createErrorStatement() { } } - //To change body of implemented methods use File | Settings | File Templates. } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDao.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDao.java new file mode 100644 index 000000000000..816f09a7d924 --- /dev/null +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDao.java @@ -0,0 +1,11 @@ +package com.nhn.pinpoint.testweb.repository; + +/** + * @author emeroad + */ +public interface MsSqlServerDao { + int selectOne(); + + boolean createStatement(); + +} diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MySqlDao.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MySqlDao.java index 475317d413bc..6ddc70f3f86d 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MySqlDao.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MySqlDao.java @@ -7,5 +7,5 @@ public interface MySqlDao { int selectOne(); - void createStatement(); + boolean createStatement(); } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MySqlDaoIbatis.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MySqlDaoIbatis.java index d607e158c692..31eee4da2d09 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MySqlDaoIbatis.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MySqlDaoIbatis.java @@ -21,7 +21,7 @@ public class MySqlDaoIbatis implements MySqlDao { private SqlMapClientTemplate sqlMapClientTemplate; @Autowired - @Qualifier("mysqlDatasource") + @Qualifier("mysqlDataSource") private DataSource datasource; @Override @@ -30,13 +30,13 @@ public int selectOne() { } @Override - public void createStatement() { + public boolean createStatement() { Connection connection = null; Statement statement = null; try { connection = datasource.getConnection(); statement = connection.createStatement(); - statement.execute("select 1"); + return statement.execute("select 1"); } catch (SQLException e) { throw new RuntimeException(e); } finally { @@ -54,6 +54,5 @@ public void createStatement() { } } - //To change body of implemented methods use File | Settings | File Templates. } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/OracleDao.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/OracleDao.java index d18df9b05275..1ea770bf0d59 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/OracleDao.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/OracleDao.java @@ -6,5 +6,5 @@ public interface OracleDao { int selectOne(); - void createStatement(); + boolean createStatement(); } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/OracleDaoIbatis.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/OracleDaoIbatis.java index 66b1b71982ab..73285c1a9087 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/OracleDaoIbatis.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/OracleDaoIbatis.java @@ -21,7 +21,7 @@ public class OracleDaoIbatis implements OracleDao { private SqlMapClientTemplate sqlMapClientTemplate; @Autowired - @Qualifier("oracleDatasource") + @Qualifier("oracleDataSource") private DataSource datasource; @Override @@ -30,13 +30,13 @@ public int selectOne() { } @Override - public void createStatement() { + public boolean createStatement() { Connection connection = null; Statement statement = null; try { connection = datasource.getConnection(); statement = connection.createStatement(); - statement.execute("select 1 from dual"); + return statement.execute("select 1 from dual"); } catch (SQLException e) { throw new RuntimeException(e); } finally { @@ -54,6 +54,5 @@ public void createStatement() { } } - //To change body of implemented methods use File | Settings | File Templates. } } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/ibatis/SqlMapClientMemberDao.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/ibatis/SqlMapClientMemberDao.java index 5726f2e6038b..07f31a767773 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/ibatis/SqlMapClientMemberDao.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/ibatis/SqlMapClientMemberDao.java @@ -25,7 +25,7 @@ public class SqlMapClientMemberDao implements MemberDao { @Override public void add(Member member) { try { - this.sqlMapClientTemplate.getSqlMapClient().insert("add", member); + this.sqlMapClientTemplate.getSqlMapClient().insert("add", member); } catch (SQLException e) { throw translateSqlException("SqlMapClient add", e); } diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/service/MsSqlServerService.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/service/MsSqlServerService.java new file mode 100644 index 000000000000..fdb560a0844d --- /dev/null +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/service/MsSqlServerService.java @@ -0,0 +1,12 @@ +package com.nhn.pinpoint.testweb.service; + +/** + * + */ +public interface MsSqlServerService { + + int selectOne(); + + void createStatement(); + +} diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/service/MsSqlServerServiceImpl.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/service/MsSqlServerServiceImpl.java new file mode 100644 index 000000000000..836c86935819 --- /dev/null +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/service/MsSqlServerServiceImpl.java @@ -0,0 +1,27 @@ +package com.nhn.pinpoint.testweb.service; + +import com.nhn.pinpoint.testweb.repository.MsSqlServerDao; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * + */ +@Service +@Transactional("msSqlServerTransactionManager") +public class MsSqlServerServiceImpl implements MsSqlServerService { + + @Autowired + private MsSqlServerDao msSqlServerDao; + + @Override + public int selectOne() { + return msSqlServerDao.selectOne(); + } + + @Override + public void createStatement() { + msSqlServerDao.createStatement(); + } +} diff --git a/testweb/src/main/resources/applicationContext-datasource.xml b/testweb/src/main/resources/applicationContext-datasource.xml index 56fa6db1f68b..fe6c614497a4 100644 --- a/testweb/src/main/resources/applicationContext-datasource.xml +++ b/testweb/src/main/resources/applicationContext-datasource.xml @@ -12,86 +12,85 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> - + + + - - + - - - + + + + + - - - + + + + - - - - - + + + - - - - - - - - + + - - + + + + + + + + + - + - - - + + + - - - + - - - - - + - - - - + + + + + + + + + + - - - + + - + + + + + - - - - - - - - - - + - - - + + + + + + + diff --git a/testweb/src/main/resources/root-context.xml b/testweb/src/main/resources/applicationContext-testweb.xml similarity index 64% rename from testweb/src/main/resources/root-context.xml rename to testweb/src/main/resources/applicationContext-testweb.xml index 8b498a52fc75..26ea5d329a52 100644 --- a/testweb/src/main/resources/root-context.xml +++ b/testweb/src/main/resources/applicationContext-testweb.xml @@ -1,74 +1,98 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/testweb/src/main/resources/database.properties b/testweb/src/main/resources/database.properties index d3d651a89fb2..bcdd15f9a315 100755 --- a/testweb/src/main/resources/database.properties +++ b/testweb/src/main/resources/database.properties @@ -1 +1,23 @@ hibernate.dialect=org.hibernate.dialect.HSQLDialect + + +# oracle +oracle.url=jdbc:oracle:thin:@10.98.133.174:1725:INDEV +oracle.user=lucy +oracle.password=lucy + +# ms sqlserver +mssqlserver.url=jdbc:jtds:sqlserver://10.99.220.85:1433/pinpoint_test +mssqlserver.user=pinpoint_user +mssqlserver.password=pinpoint!234 + +# mysql +mysql.url=jdbc:mysql://10.98.133.22:3306/hippo +mysql.url.loadbalance=jdbc:mysql:loadbalance://10.98.133.23:3306,10.98.133.22:3306/hippo +mysql.user=lucytest +mysql.password=testlucy + +# cubrid +cubrid.url=jdbc:cubrid:10.101.57.233:30102:pinpoint::: +cubrid.user=dba +cubrid.password=nhn!@#123 \ No newline at end of file diff --git a/testweb/src/main/resources/mssqlserver/SqlMapConfig.xml b/testweb/src/main/resources/mssqlserver/SqlMapConfig.xml new file mode 100644 index 000000000000..d0dd17437e2d --- /dev/null +++ b/testweb/src/main/resources/mssqlserver/SqlMapConfig.xml @@ -0,0 +1,11 @@ + + + + + + + + + \ No newline at end of file diff --git a/testweb/src/main/resources/mssqlserver/sql-member.xml b/testweb/src/main/resources/mssqlserver/sql-member.xml new file mode 100644 index 000000000000..3ba4ad238c76 --- /dev/null +++ b/testweb/src/main/resources/mssqlserver/sql-member.xml @@ -0,0 +1,33 @@ + + + + + + + + delete from member where id = #id# + + + + insert into member (id, name, joined) values(#id#, #name#, #joined#) + + + + insert into member (id, name, joined) values($id$, $name$, #joined#); + + + + + update member set name = #name#, joined = #joined# where id = #id# + + + + + + diff --git a/testweb/src/main/resources/mssqlserver/test-sql.xml b/testweb/src/main/resources/mssqlserver/test-sql.xml new file mode 100644 index 000000000000..031f2844cb35 --- /dev/null +++ b/testweb/src/main/resources/mssqlserver/test-sql.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/testweb/src/main/resources/orm/mybatis/mybatis-dao-config.xml b/testweb/src/main/resources/orm/mybatis/mybatis-dao-config.xml index 91311b399369..6b903e019933 100644 --- a/testweb/src/main/resources/orm/mybatis/mybatis-dao-config.xml +++ b/testweb/src/main/resources/orm/mybatis/mybatis-dao-config.xml @@ -10,7 +10,7 @@ - + @@ -30,7 +30,7 @@ - + diff --git a/testweb/src/main/resources/servlet-context.xml b/testweb/src/main/resources/servlet-context.xml index 968ddb05626c..5431834479c8 100644 --- a/testweb/src/main/resources/servlet-context.xml +++ b/testweb/src/main/resources/servlet-context.xml @@ -1,29 +1,22 @@ - - + + - - - - - - + + + + + + + - - \ No newline at end of file diff --git a/testweb/src/main/webapp/WEB-INF/views/orm/ibatis.jsp b/testweb/src/main/webapp/WEB-INF/views/orm/ibatis.jsp index aecc0b2235aa..c8e9d152c41e 100644 --- a/testweb/src/main/webapp/WEB-INF/views/orm/ibatis.jsp +++ b/testweb/src/main/webapp/WEB-INF/views/orm/ibatis.jsp @@ -1,3 +1,3 @@ -<%@ page language="java" contentType="text/html; charset=EUC-KR" - pageEncoding="EUC-KR" %> +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8" %> IBATIS diff --git a/testweb/src/main/webapp/WEB-INF/views/orm/mybatis.jsp b/testweb/src/main/webapp/WEB-INF/views/orm/mybatis.jsp index 3458e66ab2f7..b75108e80337 100644 --- a/testweb/src/main/webapp/WEB-INF/views/orm/mybatis.jsp +++ b/testweb/src/main/webapp/WEB-INF/views/orm/mybatis.jsp @@ -1,3 +1,3 @@ -<%@ page language="java" contentType="text/html; charset=EUC-KR" - pageEncoding="EUC-KR" %> +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8" %> MYBATIS diff --git a/testweb/src/main/webapp/WEB-INF/web.xml b/testweb/src/main/webapp/WEB-INF/web.xml index 3cbf84a8782b..601c41dc0e9c 100644 --- a/testweb/src/main/webapp/WEB-INF/web.xml +++ b/testweb/src/main/webapp/WEB-INF/web.xml @@ -16,7 +16,7 @@ contextConfigLocation - classpath:root-context.xml + classpath:applicationContext-testweb.xml @@ -56,6 +56,10 @@ /* + + index.html + + default *.css diff --git a/testweb/src/main/webapp/index.html b/testweb/src/main/webapp/index.html index 58caf2b0306d..8a9f55b2b7a8 100644 --- a/testweb/src/main/webapp/index.html +++ b/testweb/src/main/webapp/index.html @@ -11,57 +11,6 @@ pinpoint Test web -
-
-
-/combination.pinpoint
-/mysql.pinpoint
- -/mysqlStatement.pinpoint 바인드 변수 + 상수값 파싱 로직테스트.
-/donothing.pinpoint
-/remotecombination.pinpoint
- -/httperror.pinpoint
- - -/remotecombination2.pinpoint
-/combination2.pinpoint
-

-oracle -
-/selectOne.pinpoint preparedStatement 테스트. resultset은 가지고 오지 않음.
-/createStatement.pinpoint statement 테스트. resultset은 가지고 오지 않음.
- -mysql -
-/selectOne.pinpoint preparedStatement 테스트. resultset은 가지고 오지 않음.
-/createStatement.pinpoint statement 테스트. resultset은 가지고 오지 않음.
-

- -arcus -
-/arcus
-

- -nestedcall test -
-/nested.pinpoint
-

- -/httpclient4 -
-/httpclient4/cookie.pinpoint 에러시 cookie덤프
-
-/httpclient4/post.pinpoint 에러시 post덤프
-

- - -/exceptionalcase/rootslow - -
-/exceptionalcase/rootslow.pinpoint root의 완료가 지연될경우 parent가 완료된 데이터를 정상적으로 확인가능지.
-
-

diff --git a/testweb/src/main/webapp/jsp.jsp b/testweb/src/main/webapp/jsp.jsp deleted file mode 100644 index 2226753c8d1b..000000000000 --- a/testweb/src/main/webapp/jsp.jsp +++ /dev/null @@ -1 +0,0 @@ -This is JSP. \ No newline at end of file diff --git a/testweb/src/test/java/com/nhn/pinpoint/testweb/repository/MemberDaoIbatisTest.java b/testweb/src/test/java/com/nhn/pinpoint/testweb/repository/MemberDaoIbatisTest.java index 53e6e4debf00..6f9a88f662f6 100755 --- a/testweb/src/test/java/com/nhn/pinpoint/testweb/repository/MemberDaoIbatisTest.java +++ b/testweb/src/test/java/com/nhn/pinpoint/testweb/repository/MemberDaoIbatisTest.java @@ -17,7 +17,7 @@ import com.nhn.pinpoint.testweb.domain.Member; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/root-context.xml", "/servlet-context.xml" }) +@ContextConfiguration({"/applicationContext-testweb.xml", "/servlet-context.xml" }) @Transactional public class MemberDaoIbatisTest extends DBUnitSupport { diff --git a/testweb/src/test/java/com/nhn/pinpoint/testweb/repository/MemberDaoJdbcTest.java b/testweb/src/test/java/com/nhn/pinpoint/testweb/repository/MemberDaoJdbcTest.java index 8c66d1e63095..f104c9884405 100755 --- a/testweb/src/test/java/com/nhn/pinpoint/testweb/repository/MemberDaoJdbcTest.java +++ b/testweb/src/test/java/com/nhn/pinpoint/testweb/repository/MemberDaoJdbcTest.java @@ -17,7 +17,7 @@ import com.nhn.pinpoint.testweb.domain.Member; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/root-context.xml", "/servlet-context.xml" }) +@ContextConfiguration({"/applicationContext-testweb.xml", "/servlet-context.xml" }) @Transactional public class MemberDaoJdbcTest extends DBUnitSupport { diff --git a/testweb/src/test/java/com/nhn/pinpoint/testweb/service/http/ApacheClosableAsyncHttpClientTest.java b/testweb/src/test/java/com/nhn/pinpoint/testweb/service/http/ApacheClosableAsyncHttpClientTest.java index 99d54ad98880..fcb008e9f84e 100644 --- a/testweb/src/test/java/com/nhn/pinpoint/testweb/service/http/ApacheClosableAsyncHttpClientTest.java +++ b/testweb/src/test/java/com/nhn/pinpoint/testweb/service/http/ApacheClosableAsyncHttpClientTest.java @@ -14,7 +14,7 @@ * */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/root-context.xml", "/servlet-context.xml" }) +@ContextConfiguration({"/applicationContext-testweb.xml", "/servlet-context.xml" }) public class ApacheClosableAsyncHttpClientTest { @Autowired diff --git a/web/src/main/resources/applicationContext.xml b/web/src/main/resources/applicationContext-web.xml similarity index 100% rename from web/src/main/resources/applicationContext.xml rename to web/src/main/resources/applicationContext-web.xml diff --git a/web/src/main/webapp/WEB-INF/web.xml b/web/src/main/webapp/WEB-INF/web.xml index 116445a71f3d..e88a647f27af 100644 --- a/web/src/main/webapp/WEB-INF/web.xml +++ b/web/src/main/webapp/WEB-INF/web.xml @@ -17,7 +17,7 @@ contextConfigLocation - classpath:applicationContext.xml + classpath:applicationContext-web.xml diff --git a/web/src/test/java/com/navercorp/pinpoint/web/cluster/ClusterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/cluster/ClusterTest.java index d340f1099742..0d428c3cfa34 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/cluster/ClusterTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/cluster/ClusterTest.java @@ -27,7 +27,7 @@ import com.nhn.pinpoint.web.server.PinpointSocketManager; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:applicationContext.xml") +@ContextConfiguration("classpath:applicationContext-web.xml") public class ClusterTest { private static final int DEFAULT_ACCEPTOR_PORT = 9995; diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDaoTest.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDaoTest.java index 4b5eae677c48..dc7a71427c31 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDaoTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDaoTest.java @@ -16,7 +16,7 @@ * @author hyungil.jeong */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:applicationContext.xml") +@ContextConfiguration("classpath:applicationContext-web.xml") public class HbaseAgentStatDaoTest { @Autowired diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/HbaseFilterPerformanceTest.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/HbaseFilterPerformanceTest.java index 7aadcec8e6b2..368cd85057a5 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/HbaseFilterPerformanceTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/HbaseFilterPerformanceTest.java @@ -42,9 +42,7 @@ public class HbaseFilterPerformanceTest { @BeforeClass public static void beforeClass() throws IOException { - // String path = - // HbaseFilterPerformanceTest.class.getClassLoader().getResource("hbase.properties").getPath(); - // Properties properties = PropertyUtils.readProperties(path); +// Properties properties = PropertyUtils.loadPropertyFromClassPath("hbase.properties"); Configuration cfg = HBaseConfiguration.create(); cfg.set("hbase.zookeeper.quorum", "dev.zk.pinpoint.navercorp.com"); From 38da1174342ec5132dfb2f11e525160e9bf35696 Mon Sep 17 00:00:00 2001 From: Woonduk Kang Date: Wed, 24 Sep 2014 13:29:04 +0900 Subject: [PATCH 15/18] [#10] add mssqlserver test, testcase refactoring --- .../repository/MsSqlServerDaoIbatis.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDaoIbatis.java diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDaoIbatis.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDaoIbatis.java new file mode 100644 index 000000000000..586472d01f36 --- /dev/null +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDaoIbatis.java @@ -0,0 +1,58 @@ +package com.nhn.pinpoint.testweb.repository; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.orm.ibatis.SqlMapClientTemplate; +import org.springframework.stereotype.Repository; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +/** + * + */ +@Repository +public class MsSqlServerDaoIbatis implements MsSqlServerDao { + + @Autowired + @Qualifier("mysqlSqlMapClientTemplate") + private SqlMapClientTemplate sqlMapClientTemplate; + + @Autowired + @Qualifier("jtdsDataSource") + private DataSource datasource; + + @Override + public int selectOne() { + return (Integer) sqlMapClientTemplate.queryForObject("selectOne"); + } + + @Override + public boolean createStatement() { + Connection connection = null; + Statement statement = null; + try { + connection = datasource.getConnection(); + statement = connection.createStatement(); + return statement.execute("select 1"); + } catch (SQLException e) { + throw new RuntimeException(e); + } finally { + if (statement != null) { + try { + statement.close(); + } catch (SQLException e) { + } + } + if (connection != null) { + try { + connection.close(); + } catch (SQLException e) { + } + } + + } + } +} From 295da683eb5278c99536d5038916524ba790194e Mon Sep 17 00:00:00 2001 From: Woonduk Kang Date: Wed, 24 Sep 2014 13:43:55 +0900 Subject: [PATCH 16/18] [#10] add mssqlserver test, testcase refactoring --- .../profiler/junit4/PinpointJUnit4ClassRunner.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java index 0fb3a3c740a1..ff55e2622760 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/junit4/PinpointJUnit4ClassRunner.java @@ -125,12 +125,13 @@ private TestClassLoader createTestClassLoader(Class< @Override protected void runChild(FrameworkMethod method, RunNotifier notifier) { beginTracing(method); - ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + final Thread thread = Thread.currentThread(); + final ClassLoader originalClassLoader = thread.getContextClassLoader(); try { - Thread.currentThread().setContextClassLoader(this.testClassLoader); + thread.setContextClassLoader(this.testClassLoader); super.runChild(method, notifier); } finally { - Thread.currentThread().setContextClassLoader(originalClassLoader); + thread.setContextClassLoader(originalClassLoader); endTracing(method, notifier); } } From a585fb456ef6d9a8fcd3e91409eda0a7ae2a9b01 Mon Sep 17 00:00:00 2001 From: Woonduk Kang Date: Wed, 24 Sep 2014 15:31:57 +0900 Subject: [PATCH 17/18] [#10] add mssqlserver test, testcase refactoring --- .../nhn/pinpoint/testweb/repository/MsSqlServerDaoIbatis.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDaoIbatis.java b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDaoIbatis.java index 586472d01f36..6a22fc4a543a 100644 --- a/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDaoIbatis.java +++ b/testweb/src/main/java/com/nhn/pinpoint/testweb/repository/MsSqlServerDaoIbatis.java @@ -17,7 +17,7 @@ public class MsSqlServerDaoIbatis implements MsSqlServerDao { @Autowired - @Qualifier("mysqlSqlMapClientTemplate") + @Qualifier("msSqlServerSqlMapClientTemplate") private SqlMapClientTemplate sqlMapClientTemplate; @Autowired From 3b17dc6f90956848e49167cf6d51bbf20fc4cf4e Mon Sep 17 00:00:00 2001 From: Woonduk Kang Date: Wed, 24 Sep 2014 18:06:05 +0900 Subject: [PATCH 18/18] code cleanup : remove deprecated testcase, remove Sys.out --- .../bootstrap/config/ProfilerConfig.java | 2 +- .../interceptor/InterceptorRegistry.java | 4 +- .../bootstrap/config/ProfilerConfigTest.java | 4 +- .../src/main/resources-local/hbase.properties | 5 + .../receiver/tcp/TCPReceiverBOTest.java | 6 +- .../receiver/udp/NettyUdpReceiverTest.java | 6 +- .../pinpoint/common/AnnotationKey.java | 3 +- .../pinpoint/common/ServiceType.java | 1 + .../pinpoint/common/util/BytesUtils.java | 117 +--- .../pinpoint/common/util/JvmUtils.java | 3 - .../common/{ => util}/JvmVersion.java | 108 ++-- .../common/{ => util}/SystemPropertyKey.java | 54 +- .../common/{ => util/apache}/IntHashMap.java | 512 +++++++++--------- .../pinpoint/common/AnnotationKeyTest.java | 8 +- .../pinpoint/common/ServiceTypeTest.java | 6 +- .../common/util/AnnotationTranscoderTest.java | 4 +- .../pinpoint/common/util/ByteSizeTest.java | 12 +- .../pinpoint/common/util/BytesUtilsTest.java | 33 -- .../pinpoint/common/util/HashCodeTest.java | 121 ----- .../common/util/InetAddressUtilsTest.java | 10 +- .../common/{ => util}/JvmVersionTest.java | 206 +++---- .../util/PinpointThreadFactoryTest.java | 12 +- .../common/util/PropertyUtilsTest.java | 4 +- .../pinpoint/common/util/SqlParserTest.java | 44 +- .../storage/BufferedStorageFactory.java | 2 +- .../profiler/context/storage/Storage.java | 2 - .../cpu/CpuLoadMetricSetSelector.java | 2 +- .../monitor/metric/StaticAcceptHistogram.java | 2 +- .../pinpoint/profiler/context/HeaderTest.java | 8 +- .../interceptor/AroundInterceptor.java | 24 +- .../interceptor/InterceptorContext.java | 140 ++--- .../interceptor/InterceptorRegistryTest.java | 2 - .../profiler/interceptor/bci/FormatTest.java | 25 +- .../interceptor/bci/ReflectionTest.java | 28 +- .../profiler/javaassist/JavaAssistTest.java | 4 +- .../metadata/AgentIdentifierCompareTest.java | 8 +- .../modifier/mapping/MappingTableTest.java | 19 - .../codahale/MetricMonitorRegistryTest.java | 12 +- .../metric/WasStaticAcceptHistogramTest.java | 5 +- .../profiler/sampler/SimpleSamplerTest.java | 9 +- ...oavaCacheTest.java => GuavaCacheTest.java} | 55 +- .../util/PreparedStatementUtilsTest.java | 7 +- .../bindvalue/BindValueConverterTest.java | 8 +- .../rpc/server/MessageListenerTest.java | 4 +- .../handlers/HttpCustomServerHandler.java | 4 +- .../apachehttp4/nhnent/HttpUtilTest.java | 9 +- .../com/nhn/pinpoint/testweb/npc/NPCTest.java | 6 +- .../ApacheClosableAsyncHttpClientTest.java | 5 +- .../pinpoint/testweb/util/HTClientTest.java | 6 +- .../web/dao/hbase/HbaseAgentStatDaoTest.java | 5 +- .../filter/HbaseFilterPerformanceTest.java | 10 +- .../dao/hbase/filter/PrefixFilterTest.java | 8 +- .../navercorp/pinpoint/web/path/PathTest.java | 8 +- .../pinpoint/web/vo/TransactionIdTest.java | 10 +- 54 files changed, 767 insertions(+), 955 deletions(-) rename commons/src/main/java/com/navercorp/pinpoint/common/{ => util}/JvmVersion.java (93%) rename commons/src/main/java/com/navercorp/pinpoint/common/{ => util}/SystemPropertyKey.java (90%) rename commons/src/main/java/com/navercorp/pinpoint/common/{ => util/apache}/IntHashMap.java (96%) delete mode 100644 commons/src/test/java/com/navercorp/pinpoint/common/util/HashCodeTest.java rename commons/src/test/java/com/navercorp/pinpoint/common/{ => util}/JvmVersionTest.java (94%) rename {bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap => profiler/src/test/java/com/navercorp/pinpoint/profiler}/interceptor/AroundInterceptor.java (72%) rename {bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap => profiler/src/test/java/com/navercorp/pinpoint/profiler}/interceptor/InterceptorContext.java (91%) delete mode 100644 profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/mapping/MappingTableTest.java rename profiler/src/test/java/com/navercorp/pinpoint/profiler/util/{GoavaCacheTest.java => GuavaCacheTest.java} (66%) diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java index 436ff05bd46d..21b15161a2cf 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java @@ -318,7 +318,7 @@ public boolean isIoBufferingEnable() { return ioBufferingEnable; } - public int getIoBufferingBufferBufferSize() { + public int getIoBufferingBufferSize() { return ioBufferingBufferSize; } diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistry.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistry.java index 790e2cda649a..d141c8075f02 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistry.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistry.java @@ -37,7 +37,7 @@ public int addInterceptor0(StaticAroundInterceptor interceptor) { if (interceptor == null) { return -1; } - int newId = nextId(); + final int newId = nextId(); if (newId >= max) { throw new IndexOutOfBoundsException("size=" + index.length + " id=" + id); } @@ -55,7 +55,7 @@ int addSimpleInterceptor0(SimpleAroundInterceptor interceptor) { if (interceptor == null) { return -1; } - int newId = nextId(); + final int newId = nextId(); if (newId >= max) { throw new IndexOutOfBoundsException("size=" + index.length + " id=" + id); } diff --git a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfigTest.java b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfigTest.java index 02519606808b..cfadad7ec005 100644 --- a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfigTest.java +++ b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfigTest.java @@ -67,7 +67,7 @@ public void ioBuffering_test() throws IOException { profilerConfig.readConfigFile(path); Assert.assertEquals(profilerConfig.isIoBufferingEnable(), false); - Assert.assertEquals(profilerConfig.getIoBufferingBufferBufferSize(), 30); + Assert.assertEquals(profilerConfig.getIoBufferingBufferSize(), 30); } @Test @@ -79,7 +79,7 @@ public void ioBuffering_default() throws IOException { profilerConfig.readConfigFile(path); Assert.assertEquals(profilerConfig.isIoBufferingEnable(), true); - Assert.assertEquals(profilerConfig.getIoBufferingBufferBufferSize(), 10); + Assert.assertEquals(profilerConfig.getIoBufferingBufferSize(), 10); } @Test diff --git a/collector/src/main/resources-local/hbase.properties b/collector/src/main/resources-local/hbase.properties index 9a0cb44b9e38..193fa84810ee 100644 --- a/collector/src/main/resources-local/hbase.properties +++ b/collector/src/main/resources-local/hbase.properties @@ -1,5 +1,10 @@ +# local #hbase.client.host=localhost +# dev +#hbase.client.host=dev.zk.pinpoint.navercorp.com +# local-dev hbase.client.host=10.101.17.108 +# ?? #hbase.client.host=10.25.149.61 hbase.client.port=2181 hbase.htable.threads.max=4 \ No newline at end of file diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiverBOTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiverBOTest.java index d045011c7973..e7d57a61be07 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiverBOTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiverBOTest.java @@ -14,6 +14,8 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -33,6 +35,8 @@ @ContextConfiguration("classpath:applicationContext-collector.xml") @RunWith(SpringJUnit4ClassRunner.class) public class TCPReceiverBOTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + @Autowired private TCPReceiver tcpReceiver; @@ -99,7 +103,7 @@ private ResponsePacket readAndDecode(InputStream is, long waitTimeMillis) throws is.read(payload); for (byte b : payload) { - System.out.print("!!" + b); + logger.warn("!!!{}", b); } ChannelBuffer cb = ChannelBuffers.wrappedBuffer(payload); diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NettyUdpReceiverTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NettyUdpReceiverTest.java index 49488c05a875..640034fa1318 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NettyUdpReceiverTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NettyUdpReceiverTest.java @@ -39,7 +39,7 @@ public void server() throws IOException, InterruptedException { public void run() { udpServer.bind(new InetSocketAddress("127.0.0.1", PORT)); try { - System.out.println("server-await"); + logger.debug("server-await"); latch.await(); } catch (InterruptedException e) { } @@ -47,7 +47,7 @@ public void run() { }); thread.start(); Thread.sleep(1000); - System.out.println("start--------"); + logger.debug("start--------"); // ExecutorService executorService = Executors.newFixedThreadPool(10); // for (int i =0; i< 10; i++) { // executorService.execute(new Runnable() { @@ -90,7 +90,7 @@ public ChannelPipeline getPipeline() throws Exception { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String name = Thread.currentThread().getName(); - System.out.println("sleep-------------------" + name); + logger.debug("sleep-------------------{}", name); Thread.sleep(10000); // if (!name.equals("New I/O worker #1")) { logger.info("messageReceived thread-{} message:", Thread.currentThread().getName()); diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/AnnotationKey.java b/commons/src/main/java/com/navercorp/pinpoint/common/AnnotationKey.java index 69faf95c18d0..a97b4facaace 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/AnnotationKey.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/AnnotationKey.java @@ -1,7 +1,6 @@ package com.nhn.pinpoint.common; -import java.util.HashMap; -import java.util.Map; +import com.nhn.pinpoint.common.util.apache.IntHashMap; /** * @author netspider diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java b/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java index 118b9ab378d6..8d8021a14935 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java @@ -13,6 +13,7 @@ import java.util.Map; import com.nhn.pinpoint.common.util.RpcCodeRange; +import com.nhn.pinpoint.common.util.apache.IntHashMap; /** * @author emeroad diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java index e2b0f986f4c0..8500e3d2a576 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java @@ -21,13 +21,6 @@ public final class BytesUtils { private static final String UTF8 = "UTF-8"; private static final Logger LOGGER = Logger.getLogger(BytesUtils.class.getName()); - @Deprecated - public static byte[] longLongToBytes(final long value1, final long value2) { - final byte[] buffer = new byte[LONG_LONG_BYTE_LENGTH]; - writeFirstLong0(value1, buffer); - writeSecondLong0(value2, buffer); - return buffer; - } public static byte[] stringLongLongToBytes(final String string, final int maxStringSize, final long value1, final long value2) { if (string == null) { @@ -60,22 +53,6 @@ public static void writeBytes(final byte[] buffer, int offset, final byte[] stri System.arraycopy(stringBytes, 0, buffer, offset, stringBytes.length); } - @Deprecated - public static long[] bytesToLongLong(final byte[] buf) { - if (buf == null) { - throw new NullPointerException("buf must not be null"); - } - if (buf.length < LONG_LONG_BYTE_LENGTH) { - throw new IllegalArgumentException("Illegal buf size."); - } - final long[] result = new long[2]; - - result[0] = bytesToFirstLong0(buf); - result[1] = bytesToSecondLong0(buf); - - return result; - } - public static long bytesToLong(final byte[] buf, final int offset) { if (buf == null) { throw new NullPointerException("buf must not be null"); @@ -137,51 +114,6 @@ public static short bytesToShort(final byte byte1, final byte byte2) { return (short) (((byte1 & 0xff) << 8) | ((byte2 & 0xff))); } - public static long bytesToFirstLong(final byte[] buf) { - if (buf == null) { - throw new NullPointerException("buf must not be null"); - } - if (buf.length < LONG_BYTE_LENGTH) { - throw new IllegalArgumentException("buf.length is too small(8). buf.length:" + buf.length); - } - - return bytesToFirstLong0(buf); - } - - private static long bytesToFirstLong0(byte[] buf) { - final long rv = (((long) buf[0] & 0xff) << 56) - | (((long) buf[1] & 0xff) << 48) - | (((long) buf[2] & 0xff) << 40) - | (((long) buf[3] & 0xff) << 32) - | (((long) buf[4] & 0xff) << 24) - | (((long) buf[5] & 0xff) << 16) - | (((long) buf[6] & 0xff) << 8) - | (((long) buf[7] & 0xff)); - return rv; - } - - public static long bytesToSecondLong(final byte[] buf) { - if (buf == null) { - throw new NullPointerException("buf must not be null"); - } - if (buf.length < LONG_LONG_BYTE_LENGTH) { - throw new IllegalArgumentException("buf.length is too small(16). buf.length:" + buf.length); - } - - return bytesToSecondLong0(buf); - } - - private static long bytesToSecondLong0(final byte[] buf) { - final long rv = (((long) buf[8] & 0xff) << 56) - | (((long) buf[9] & 0xff) << 48) - | (((long) buf[10] & 0xff) << 40) - | (((long) buf[11] & 0xff) << 32) - | (((long) buf[12] & 0xff) << 24) - | (((long) buf[13] & 0xff) << 16) - | (((long) buf[14] & 0xff) << 8) - | (((long) buf[15] & 0xff)); - return rv; - } public static int writeLong(final long value, final byte[] buf, int offset) { if (buf == null) { @@ -284,30 +216,9 @@ public static int writeVar64(long value, final byte[] buf, int offset) { } } - @Deprecated - public static void writeFirstLong(final long value, final byte[] buf) { - if (buf == null) { - throw new NullPointerException("buf must not be null"); - } - if (buf.length < LONG_BYTE_LENGTH) { - throw new IllegalArgumentException("buf.length is too small(8). buf.length:" + buf.length); - } - writeFirstLong0(value, buf); - } - - private static void writeFirstLong0(final long value, final byte[] buf) { - buf[0] = (byte) (value >> 56); - buf[1] = (byte) (value >> 48); - buf[2] = (byte) (value >> 40); - buf[3] = (byte) (value >> 32); - buf[4] = (byte) (value >> 24); - buf[5] = (byte) (value >> 16); - buf[6] = (byte) (value >> 8); - buf[7] = (byte) (value); - } private static void writeFirstLong0(final long value, final byte[] buf, int offset) { - buf[0 + offset] = (byte) (value >> 56); + buf[offset] = (byte) (value >> 56); buf[1 + offset] = (byte) (value >> 48); buf[2 + offset] = (byte) (value >> 40); buf[3 + offset] = (byte) (value >> 32); @@ -317,32 +228,11 @@ private static void writeFirstLong0(final long value, final byte[] buf, int offs buf[7 + offset] = (byte) (value); } - @Deprecated - public static void writeSecondLong(final long value, final byte[] buf) { - if (buf == null) { - throw new NullPointerException("buf must not be null"); - } - if (buf.length < LONG_LONG_BYTE_LENGTH) { - throw new IllegalArgumentException("buf.length is too small(16). buf.length:" + buf.length); - } - writeSecondLong0(value, buf); - } - private static Logger getLogger() { return Logger.getLogger(BytesUtils.class.getName()); } - private static void writeSecondLong0(final long value, final byte[] buf) { - buf[8] = (byte) (value >> 56); - buf[9] = (byte) (value >> 48); - buf[10] = (byte) (value >> 40); - buf[11] = (byte) (value >> 32); - buf[12] = (byte) (value >> 24); - buf[13] = (byte) (value >> 16); - buf[14] = (byte) (value >> 8); - buf[15] = (byte) (value); - } private static void writeSecondLong0(final long value, final byte[] buf, int offset) { buf[8 + offset] = (byte) (value >> 56); @@ -459,14 +349,15 @@ public static long zigzagToLong(final long n) { public static byte[] concat(final byte[]... arrays) { int totalLength = 0; - for (int i = 0; i < arrays.length; i++) { + final int length = arrays.length; + for (int i = 0; i < length; i++) { totalLength += arrays[i].length; } byte[] result = new byte[totalLength]; int currentIndex = 0; - for (int i = 0; i < arrays.length; i++) { + for (int i = 0; i < length; i++) { System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length); currentIndex += arrays[i].length; } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmUtils.java index 7d248e2e2a4e..20d775246389 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmUtils.java @@ -4,9 +4,6 @@ import java.lang.management.RuntimeMXBean; import java.util.Map; -import com.nhn.pinpoint.common.SystemPropertyKey; -import com.nhn.pinpoint.common.JvmVersion; - /** * @author hyungil.jeong */ diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/JvmVersion.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmVersion.java similarity index 93% rename from commons/src/main/java/com/navercorp/pinpoint/common/JvmVersion.java rename to commons/src/main/java/com/navercorp/pinpoint/common/util/JvmVersion.java index 8873f4b3efcc..8a049665f6a8 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/JvmVersion.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmVersion.java @@ -1,54 +1,54 @@ -package com.nhn.pinpoint.common; - -/** - * @author hyungil.jeong - */ -public enum JvmVersion { - JAVA_5(1.5, 49), - JAVA_6(1.6, 50), - JAVA_7(1.7, 51), - JAVA_8(1.8, 52), - UNSUPPORTED(-1, -1); - - private final double version; - private final int classVersion; - - private JvmVersion(double version, int classVersion) { - this.version = version; - this.classVersion = classVersion; - } - - public boolean onOrAfter(JvmVersion other) { - if (this == UNSUPPORTED || other == UNSUPPORTED) { - return false; - } - return this == other || this.version > other.version; - } - - public static JvmVersion getFromVersion(String javaVersion) { - try { - double version = Double.parseDouble(javaVersion); - return getFromVersion(version); - } catch (NumberFormatException e) { - return UNSUPPORTED; - } - } - - public static JvmVersion getFromVersion(double javaVersion) { - for (JvmVersion version : JvmVersion.values()) { - if (version.version == javaVersion) { - return version; - } - } - return JvmVersion.UNSUPPORTED; - } - - public static JvmVersion getFromClassVersion(int classVersion) { - for (JvmVersion version : JvmVersion.values()) { - if (version.classVersion == classVersion) { - return version; - } - } - return JvmVersion.UNSUPPORTED; - } -} +package com.nhn.pinpoint.common.util; + +/** + * @author hyungil.jeong + */ +public enum JvmVersion { + JAVA_5(1.5, 49), + JAVA_6(1.6, 50), + JAVA_7(1.7, 51), + JAVA_8(1.8, 52), + UNSUPPORTED(-1, -1); + + private final double version; + private final int classVersion; + + private JvmVersion(double version, int classVersion) { + this.version = version; + this.classVersion = classVersion; + } + + public boolean onOrAfter(JvmVersion other) { + if (this == UNSUPPORTED || other == UNSUPPORTED) { + return false; + } + return this == other || this.version > other.version; + } + + public static JvmVersion getFromVersion(String javaVersion) { + try { + double version = Double.parseDouble(javaVersion); + return getFromVersion(version); + } catch (NumberFormatException e) { + return UNSUPPORTED; + } + } + + public static JvmVersion getFromVersion(double javaVersion) { + for (JvmVersion version : JvmVersion.values()) { + if (version.version == javaVersion) { + return version; + } + } + return JvmVersion.UNSUPPORTED; + } + + public static JvmVersion getFromClassVersion(int classVersion) { + for (JvmVersion version : JvmVersion.values()) { + if (version.classVersion == classVersion) { + return version; + } + } + return JvmVersion.UNSUPPORTED; + } +} diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/SystemPropertyKey.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/SystemPropertyKey.java similarity index 90% rename from commons/src/main/java/com/navercorp/pinpoint/common/SystemPropertyKey.java rename to commons/src/main/java/com/navercorp/pinpoint/common/util/SystemPropertyKey.java index 9c07db3efdd0..3b8a496778f6 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/SystemPropertyKey.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/SystemPropertyKey.java @@ -1,27 +1,27 @@ -package com.nhn.pinpoint.common; - -/** - * @author hyungil.jeong - */ -public enum SystemPropertyKey { - - JAVA_VERSION("java.version"), - JAVA_RUNTIME_VERSION("java.runtime.version"), - JAVA_RUNTIME_NAME("java.runtime.name"), - JAVA_SPECIFICATION_VERSION("java.specification.version"), - JAVA_CLASS_VERSION("java.class.version"), - JAVA_VM_NAME("java.vm.name"), - JAVA_VM_VERSION("java.vm.version"), - JAVA_VM_INFO("java.vm.info"), - JAVA_VM_SPECIFICATION_VERSION("java.vm.specification.version"); - - private final String key; - - private SystemPropertyKey(String key) { - this.key = key; - } - - public String getKey() { - return this.key; - } -} +package com.nhn.pinpoint.common.util; + +/** + * @author hyungil.jeong + */ +public enum SystemPropertyKey { + + JAVA_VERSION("java.version"), + JAVA_RUNTIME_VERSION("java.runtime.version"), + JAVA_RUNTIME_NAME("java.runtime.name"), + JAVA_SPECIFICATION_VERSION("java.specification.version"), + JAVA_CLASS_VERSION("java.class.version"), + JAVA_VM_NAME("java.vm.name"), + JAVA_VM_VERSION("java.vm.version"), + JAVA_VM_INFO("java.vm.info"), + JAVA_VM_SPECIFICATION_VERSION("java.vm.specification.version"); + + private final String key; + + private SystemPropertyKey(String key) { + this.key = key; + } + + public String getKey() { + return this.key; + } +} diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/IntHashMap.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/apache/IntHashMap.java similarity index 96% rename from commons/src/main/java/com/navercorp/pinpoint/common/IntHashMap.java rename to commons/src/main/java/com/navercorp/pinpoint/common/util/apache/IntHashMap.java index d16a12f2b1e8..2e13ac5c2e86 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/IntHashMap.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/apache/IntHashMap.java @@ -1,256 +1,256 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/* - * Note: originally released under the GNU LGPL v2.1, - * but rereleased by the original author under the ASF license (above). - */ -package com.nhn.pinpoint.common; - -/** - *

A hash map that uses primitive ints for the key rather than objects.

- * - *

Note that this class is for internal optimization purposes only, and may - * not be supported in future releases of Apache Commons Lang. Utilities of - * this sort may be included in future releases of Apache Commons Collections.

- * - * @author Apache Software Foundation - * @author Justin Couch - * @author Alex Chaffee (alex@apache.org) - * @since 2.0 - * @version $Revision$ - * @see java.util.HashMap - */ -// 내부 튜닝용 가져다 사용하지 말것 -public class IntHashMap { - - /** - * The hash table data. - */ - private transient Entry table[]; - - /** - * The total number of entries in the hash table. - */ - private transient int count; - - /** - * The table is rehashed when its size exceeds this threshold. (The - * value of this field is (int)(capacity * loadFactor).) - * - * @serial - */ - private int threshold; - - /** - * The load factor for the hashtable. - * - * @serial - */ - private final float loadFactor; - - /** - *

Innerclass that acts as a datastructure to create a new entry in the - * table.

- */ - private static class Entry { - final int hash; - final int key; // TODO not read; seems to be always same as hash - T value; - Entry next; - - /** - *

Create a new entry with the given values.

- * - * @param hash The code used to hash the object with - * @param key The key used to enter this in the table - * @param value The value for this key - * @param next A reference to the next entry in the table - */ - protected Entry(int hash, int key, T value, Entry next) { - this.hash = hash; - this.key = key; - this.value = value; - this.next = next; - } - } - - /** - *

Constructs a new, empty hashtable with a default capacity and load - * factor, which is 20 and 0.75 respectively.

- */ - public IntHashMap() { - this(20, 0.75f); - } - - /** - *

Constructs a new, empty hashtable with the specified initial capacity - * and default load factor, which is 0.75.

- * - * @param initialCapacity the initial capacity of the hashtable. - * @throws IllegalArgumentException if the initial capacity is less - * than zero. - */ - public IntHashMap(int initialCapacity) { - this(initialCapacity, 0.75f); - } - - /** - *

Constructs a new, empty hashtable with the specified initial - * capacity and the specified load factor.

- * - * @param initialCapacity the initial capacity of the hashtable. - * @param loadFactor the load factor of the hashtable. - * @throws IllegalArgumentException if the initial capacity is less - * than zero, or if the load factor is nonpositive. - */ - public IntHashMap(int initialCapacity, float loadFactor) { - super(); - if (initialCapacity < 0) { - throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); - } - if (loadFactor <= 0) { - throw new IllegalArgumentException("Illegal Load: " + loadFactor); - } - if (initialCapacity == 0) { - initialCapacity = 1; - } - - this.loadFactor = loadFactor; - table = new Entry[initialCapacity]; - threshold = (int) (initialCapacity * loadFactor); - } - - /** - *

Returns the number of keys in this hashtable.

- * - * @return the number of keys in this hashtable. - */ - public int size() { - return count; - } - - /** - *

Tests if this hashtable maps no keys to values.

- * - * @return true if this hashtable maps no keys to values; - * false otherwise. - */ - public boolean isEmpty() { - return count == 0; - } - - - /** - *

Returns the value to which the specified key is mapped in this map.

- * - * @param key a key in the hashtable. - * @return the value to which the key is mapped in this hashtable; - * null if the key is not mapped to any value in - * this hashtable. - * @see #put(int, T) - */ - public T get(int key) { - Entry tab[] = table; - int hash = key; - int index = (hash & 0x7FFFFFFF) % tab.length; - for (Entry e = tab[index]; e != null; e = e.next) { - if (e.hash == hash) { - return e.value; - } - } - return null; - } - - /** - *

Increases the capacity of and internally reorganizes this - * hashtable, in order to accommodate and access its entries more - * efficiently.

- * - *

This method is called automatically when the number of keys - * in the hashtable exceeds this hashtable's capacity and load - * factor.

- */ - protected void rehash() { - int oldCapacity = table.length; - Entry oldMap[] = table; - - int newCapacity = oldCapacity * 2 + 1; - Entry newMap[] = new Entry[newCapacity]; - - threshold = (int) (newCapacity * loadFactor); - table = newMap; - - for (int i = oldCapacity; i-- > 0;) { - for (Entry old = oldMap[i]; old != null;) { - Entry e = old; - old = old.next; - - int index = (e.hash & 0x7FFFFFFF) % newCapacity; - e.next = newMap[index]; - newMap[index] = e; - } - } - } - - /** - *

Maps the specified key to the specified - * value in this hashtable. The key cannot be - * null.

- * - *

The value can be retrieved by calling the get method - * with a key that is equal to the original key.

- * - * @param key the hashtable key. - * @param value the value. - * @return the previous value of the specified key in this hashtable, - * or null if it did not have one. - * @throws NullPointerException if the key is null. - * @see #get(int) - */ - public T put(int key, T value) { - // Makes sure the key is not already in the hashtable. - Entry tab[] = table; - int hash = key; - int index = (hash & 0x7FFFFFFF) % tab.length; - for (Entry e = tab[index]; e != null; e = e.next) { - if (e.hash == hash) { - T old = e.value; - e.value = value; - return old; - } - } - - if (count >= threshold) { - // Rehash the table if the threshold is exceeded - rehash(); - - tab = table; - index = (hash & 0x7FFFFFFF) % tab.length; - } - - // Creates the new entry. - Entry e = new Entry(hash, key, value, tab[index]); - tab[index] = e; - count++; - return null; - } - - - -} - +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ + +/* + * Note: originally released under the GNU LGPL v2.1, + * but rereleased by the original author under the ASF license (above). + */ +package com.nhn.pinpoint.common.util.apache; + +/** + *

A hash map that uses primitive ints for the key rather than objects.

+ * + *

Note that this class is for internal optimization purposes only, and may + * not be supported in future releases of Apache Commons Lang. Utilities of + * this sort may be included in future releases of Apache Commons Collections.

+ * + * @author Apache Software Foundation + * @author Justin Couch + * @author Alex Chaffee (alex@apache.org) + * @since 2.0 + * @version $Revision$ + * @see java.util.HashMap + */ +// 내부 튜닝용 가져다 사용하지 말것 +public class IntHashMap { + + /** + * The hash table data. + */ + private transient Entry table[]; + + /** + * The total number of entries in the hash table. + */ + private transient int count; + + /** + * The table is rehashed when its size exceeds this threshold. (The + * value of this field is (int)(capacity * loadFactor).) + * + * @serial + */ + private int threshold; + + /** + * The load factor for the hashtable. + * + * @serial + */ + private final float loadFactor; + + /** + *

Innerclass that acts as a datastructure to create a new entry in the + * table.

+ */ + private static class Entry { + final int hash; + final int key; // TODO not read; seems to be always same as hash + T value; + Entry next; + + /** + *

Create a new entry with the given values.

+ * + * @param hash The code used to hash the object with + * @param key The key used to enter this in the table + * @param value The value for this key + * @param next A reference to the next entry in the table + */ + protected Entry(int hash, int key, T value, Entry next) { + this.hash = hash; + this.key = key; + this.value = value; + this.next = next; + } + } + + /** + *

Constructs a new, empty hashtable with a default capacity and load + * factor, which is 20 and 0.75 respectively.

+ */ + public IntHashMap() { + this(20, 0.75f); + } + + /** + *

Constructs a new, empty hashtable with the specified initial capacity + * and default load factor, which is 0.75.

+ * + * @param initialCapacity the initial capacity of the hashtable. + * @throws IllegalArgumentException if the initial capacity is less + * than zero. + */ + public IntHashMap(int initialCapacity) { + this(initialCapacity, 0.75f); + } + + /** + *

Constructs a new, empty hashtable with the specified initial + * capacity and the specified load factor.

+ * + * @param initialCapacity the initial capacity of the hashtable. + * @param loadFactor the load factor of the hashtable. + * @throws IllegalArgumentException if the initial capacity is less + * than zero, or if the load factor is nonpositive. + */ + public IntHashMap(int initialCapacity, float loadFactor) { + super(); + if (initialCapacity < 0) { + throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); + } + if (loadFactor <= 0) { + throw new IllegalArgumentException("Illegal Load: " + loadFactor); + } + if (initialCapacity == 0) { + initialCapacity = 1; + } + + this.loadFactor = loadFactor; + table = new Entry[initialCapacity]; + threshold = (int) (initialCapacity * loadFactor); + } + + /** + *

Returns the number of keys in this hashtable.

+ * + * @return the number of keys in this hashtable. + */ + public int size() { + return count; + } + + /** + *

Tests if this hashtable maps no keys to values.

+ * + * @return true if this hashtable maps no keys to values; + * false otherwise. + */ + public boolean isEmpty() { + return count == 0; + } + + + /** + *

Returns the value to which the specified key is mapped in this map.

+ * + * @param key a key in the hashtable. + * @return the value to which the key is mapped in this hashtable; + * null if the key is not mapped to any value in + * this hashtable. + * @see #put(int, T) + */ + public T get(int key) { + Entry tab[] = table; + int hash = key; + int index = (hash & 0x7FFFFFFF) % tab.length; + for (Entry e = tab[index]; e != null; e = e.next) { + if (e.hash == hash) { + return e.value; + } + } + return null; + } + + /** + *

Increases the capacity of and internally reorganizes this + * hashtable, in order to accommodate and access its entries more + * efficiently.

+ * + *

This method is called automatically when the number of keys + * in the hashtable exceeds this hashtable's capacity and load + * factor.

+ */ + protected void rehash() { + int oldCapacity = table.length; + Entry oldMap[] = table; + + int newCapacity = oldCapacity * 2 + 1; + Entry newMap[] = new Entry[newCapacity]; + + threshold = (int) (newCapacity * loadFactor); + table = newMap; + + for (int i = oldCapacity; i-- > 0;) { + for (Entry old = oldMap[i]; old != null;) { + Entry e = old; + old = old.next; + + int index = (e.hash & 0x7FFFFFFF) % newCapacity; + e.next = newMap[index]; + newMap[index] = e; + } + } + } + + /** + *

Maps the specified key to the specified + * value in this hashtable. The key cannot be + * null.

+ * + *

The value can be retrieved by calling the get method + * with a key that is equal to the original key.

+ * + * @param key the hashtable key. + * @param value the value. + * @return the previous value of the specified key in this hashtable, + * or null if it did not have one. + * @throws NullPointerException if the key is null. + * @see #get(int) + */ + public T put(int key, T value) { + // Makes sure the key is not already in the hashtable. + Entry tab[] = table; + int hash = key; + int index = (hash & 0x7FFFFFFF) % tab.length; + for (Entry e = tab[index]; e != null; e = e.next) { + if (e.hash == hash) { + T old = e.value; + e.value = value; + return old; + } + } + + if (count >= threshold) { + // Rehash the table if the threshold is exceeded + rehash(); + + tab = table; + index = (hash & 0x7FFFFFFF) % tab.length; + } + + // Creates the new entry. + Entry e = new Entry(hash, key, value, tab[index]); + tab[index] = e; + count++; + return null; + } + + + +} + diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/AnnotationKeyTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/AnnotationKeyTest.java index 73d6f3dcf2bf..b84ff5b53ce7 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/AnnotationKeyTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/AnnotationKeyTest.java @@ -2,11 +2,15 @@ import junit.framework.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @author emeroad */ public class AnnotationKeyTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + @Test public void getCode() { @@ -18,9 +22,9 @@ public void getCode() { // @Test public void intSize() { // 2147483647 - System.out.println(Integer.MAX_VALUE); + logger.debug("{}", Integer.MAX_VALUE); // -2147483648 - System.out.println(Integer.MIN_VALUE); + logger.debug("{}", Integer.MIN_VALUE); } @Test diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/ServiceTypeTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/ServiceTypeTest.java index a09be2b72c4b..39a463b084a1 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/ServiceTypeTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/ServiceTypeTest.java @@ -13,9 +13,9 @@ public class ServiceTypeTest { @Test public void testIndexable() { - System.out.println(ServiceType.TOMCAT.isIndexable()); - System.out.println(ServiceType.BLOC.isIndexable()); - System.out.println(ServiceType.ARCUS.isIndexable()); + logger.debug("{}", ServiceType.TOMCAT.isIndexable()); + logger.debug("{}", ServiceType.BLOC.isIndexable()); + logger.debug("{}", ServiceType.ARCUS.isIndexable()); } @Test diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/AnnotationTranscoderTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/AnnotationTranscoderTest.java index 355a2df55d3e..344fe9493b89 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/util/AnnotationTranscoderTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/AnnotationTranscoderTest.java @@ -92,10 +92,10 @@ private void typeBinaryCode(byte[] value) { @Test public void testGetTypeCode() throws Exception { int i = 2 << 8; - System.out.println(i); + logger.debug("{}", i); write(i); int j = 3 << 8; - System.out.println(j); + logger.debug("{}", j); write(j); write(10); write(512); diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/ByteSizeTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/ByteSizeTest.java index 1abe69d06c07..b07e7e06e3a7 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/util/ByteSizeTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/ByteSizeTest.java @@ -5,15 +5,19 @@ import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TIOStreamTransport; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; -import java.util.Arrays; import java.util.concurrent.TimeUnit; /** * */ public class ByteSizeTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Test public void test() throws TException { TCompactProtocol.Factory factory = new TCompactProtocol.Factory(); @@ -23,12 +27,12 @@ public void test() throws TException { TProtocol protocol = factory.getProtocol(transport); long l = TimeUnit.DAYS.toMillis(1); - System.out.println("day:" + l); + logger.debug("day:{}", l); long currentTime = System.currentTimeMillis(); - System.out.println("currentTime:" + currentTime); + logger.debug("currentTime:{}" + currentTime); protocol.writeI64(l); byte[] buffer = baos.toByteArray(); - System.out.println(buffer.length); + logger.debug("{}", buffer.length); } diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/BytesUtilsTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/BytesUtilsTest.java index c09d78f28921..9e23c45eaf69 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/util/BytesUtilsTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/BytesUtilsTest.java @@ -16,16 +16,6 @@ public class BytesUtilsTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Test - public void testLongLongToBytes() throws Exception { - long most = Long.MAX_VALUE; - long least = Long.MAX_VALUE - 1; - - test(most, least); - - UUID uuid = UUID.randomUUID(); - test(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits()); - } @Test public void testStringLongLongToBytes() throws Exception { @@ -77,29 +67,6 @@ private void checkInt(int i) { Assert.assertEquals(i, i3); } - private void test(long most, long least) { - byte[] bytes1 = Bytes.toBytes(most); - byte[] bytes2 = Bytes.toBytes(least); - byte[] add = Bytes.add(bytes1, bytes2); - byte[] bytes = BytesUtils.longLongToBytes(most, least); - Assert.assertArrayEquals(add, bytes); - - - long[] longLong = BytesUtils.bytesToLongLong(bytes); - Assert.assertEquals(most, longLong[0]); - Assert.assertEquals(least, longLong[1]); - - - long bMost = BytesUtils.bytesToLong(bytes, 0); - long bLeast = BytesUtils.bytesToLong(bytes, 8); - Assert.assertEquals(most, bMost); - Assert.assertEquals(least, bLeast); - - byte bBytes[] = new byte[16]; - BytesUtils.writeLong(most, bBytes, 0); - BytesUtils.writeLong(least, bBytes, 8); - Assert.assertArrayEquals(add, bBytes); - } @Test public void testAddStringLong() throws Exception { diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/HashCodeTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/HashCodeTest.java deleted file mode 100644 index 900e844ded9f..000000000000 --- a/commons/src/test/java/com/navercorp/pinpoint/common/util/HashCodeTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.nhn.pinpoint.common.util; - -import org.junit.Test; - -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** - * test를 위해 hashcode를 찾을때 돌려볼수 있는 코드 - */ -public class HashCodeTest { - // @Test - public void test2() throws InterruptedException { -// "test" -// "tetU" -// "uGTt" -// System.out.println((int)'A'); -// System.out.println((int)'Z'); - System.out.println("test".hashCode()); - System.out.println("tfUU".hashCode()); - String a = "23 123"; - System.out.println(a.hashCode()); - System.out.println("test:" + a.hashCode()); - final int hashCode = a.hashCode(); - final ExecutorService es = Executors.newFixedThreadPool(4); - Runnable runnable = new Runnable() { - @Override - public void run() { - execute(hashCode); - } - }; - es.execute(runnable); - es.execute(runnable); - es.execute(runnable); - es.execute(runnable); - es.awaitTermination(1, TimeUnit.HOURS); -// execute(hashCode, random); -// test -// -1757224452 - - - } - - private void execute(int hashCode) { - Random random = new Random(); - while (true) { - int i = random.nextInt(30); -// System.out.println(i); - StringBuilder sb = new StringBuilder(); -// sb.append("12 "); - for (int j = 0; j < i; j++) { - char c = get(random); - sb.append(c); - } - sb.append(" 7"); - String s = sb.toString(); -// System.out.println(s.hashCode()); -// System.out.println(s); - if (hashCode == s.hashCode()) { -// if(a.equals(s)) { -// continue; -// } - System.out.println("find!!! equals:" + s); - break; - } - } - } - - // @Test - public void test() { -// "test" -// "tetU" -// "uGTt" -// System.out.println((int)'A'); -// System.out.println((int)'Z'); - String a = "test"; - System.out.println("test:" + a.hashCode()); - int hashCode = a.hashCode(); - Random random = new Random(); - while (true) { - int i = random.nextInt(50); -// System.out.println(i); - StringBuilder sb = new StringBuilder(); - for (int j = 0; j < i; j++) { - char c = get(random); - sb.append(c); - } - String s = sb.toString(); -// System.out.println(s); - if (hashCode == s.hashCode()) { - if ("test".equals(s)) { - continue; - } - System.out.println("equals:" + s); - break; - } - } -// test -// -1757224452 - } - - char get(Random rand) { -// 65->90 : 25 -// 97->122; 25 - int choice = (char) rand.nextInt(2); - char ch; - if (choice == 0) { - ch = (char) ((rand.nextInt(25)) + 97); - } else { - ch = (char) ((rand.nextInt(25)) + 65); - } - - while (true) { - if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') { - return ch; - } - } - } -} diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/InetAddressUtilsTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/InetAddressUtilsTest.java index 42da6f2709a1..d8b7e125a70d 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/util/InetAddressUtilsTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/InetAddressUtilsTest.java @@ -1,6 +1,8 @@ package com.nhn.pinpoint.common.util; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; @@ -9,14 +11,16 @@ * */ public class InetAddressUtilsTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + @Test public void test() throws UnknownHostException { InetAddress byName = InetAddress.getByName("0:0:0:0:0:0:0:1"); - System.out.println(byName); - System.out.println(byName.getAddress().length); + logger.debug("{}", byName); + logger.debug("{}", byName.getAddress().length); InetAddress ipv4= InetAddress.getByName("127.0.0.1"); - System.out.println(ipv4); + logger.debug("{}", ipv4); } } diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/JvmVersionTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/JvmVersionTest.java similarity index 94% rename from commons/src/test/java/com/navercorp/pinpoint/common/JvmVersionTest.java rename to commons/src/test/java/com/navercorp/pinpoint/common/util/JvmVersionTest.java index 0ebb0b312c37..69d371999e8b 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/JvmVersionTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/JvmVersionTest.java @@ -1,103 +1,103 @@ -package com.nhn.pinpoint.common; - -import static org.junit.Assert.*; -import static com.nhn.pinpoint.common.JvmVersion.*; - -import org.junit.Test; - -/** - * @author hyungil.jeong - */ -public class JvmVersionTest { - - @Test - public void testOnOrAfter() { - // JDK 5 - assertTrue(JAVA_5.onOrAfter(JAVA_5)); - assertFalse(JAVA_5.onOrAfter(JAVA_6)); - assertFalse(JAVA_5.onOrAfter(JAVA_7)); - assertFalse(JAVA_5.onOrAfter(JAVA_8)); - assertFalse(JAVA_5.onOrAfter(UNSUPPORTED)); - // JDK 6 - assertTrue(JAVA_6.onOrAfter(JAVA_5)); - assertTrue(JAVA_6.onOrAfter(JAVA_6)); - assertFalse(JAVA_6.onOrAfter(JAVA_7)); - assertFalse(JAVA_6.onOrAfter(JAVA_8)); - assertFalse(JAVA_6.onOrAfter(UNSUPPORTED)); - // JDK 7 - assertTrue(JAVA_7.onOrAfter(JAVA_5)); - assertTrue(JAVA_7.onOrAfter(JAVA_6)); - assertTrue(JAVA_7.onOrAfter(JAVA_7)); - assertFalse(JAVA_7.onOrAfter(JAVA_8)); - assertFalse(JAVA_7.onOrAfter(UNSUPPORTED)); - // JDK 8 - assertTrue(JAVA_8.onOrAfter(JAVA_5)); - assertTrue(JAVA_8.onOrAfter(JAVA_6)); - assertTrue(JAVA_8.onOrAfter(JAVA_7)); - assertTrue(JAVA_8.onOrAfter(JAVA_8)); - assertFalse(JAVA_8.onOrAfter(UNSUPPORTED)); - // Unsupported - assertFalse(UNSUPPORTED.onOrAfter(JAVA_5)); - assertFalse(UNSUPPORTED.onOrAfter(JAVA_6)); - assertFalse(UNSUPPORTED.onOrAfter(JAVA_7)); - assertFalse(UNSUPPORTED.onOrAfter(JAVA_8)); - assertFalse(UNSUPPORTED.onOrAfter(UNSUPPORTED)); - } - - @Test - public void testGetFromDoubleVersion() { - // JDK 5 - final JvmVersion java_5 = JvmVersion.getFromVersion(1.5); - assertSame(java_5, JAVA_5); - // JDK 6 - final JvmVersion java_6 = JvmVersion.getFromVersion(1.6); - assertSame(java_6, JAVA_6); - // JDK 7 - final JvmVersion java_7 = JvmVersion.getFromVersion(1.7); - assertSame(java_7, JAVA_7); - // JDK 8 - final JvmVersion java_8 = JvmVersion.getFromVersion(1.8); - assertSame(java_8, JAVA_8); - // Unsupported - final JvmVersion java_unsupported = JvmVersion.getFromVersion(0.9); - assertSame(java_unsupported, UNSUPPORTED); - } - - @Test - public void testGetFromStringVersion() { - // JDK 5 - final JvmVersion java_5 = JvmVersion.getFromVersion("1.5"); - assertSame(java_5, JAVA_5); - // JDK 6 - final JvmVersion java_6 = JvmVersion.getFromVersion("1.6"); - assertSame(java_6, JAVA_6); - // JDK 7 - final JvmVersion java_7 = JvmVersion.getFromVersion("1.7"); - assertSame(java_7, JAVA_7); - // JDK 8 - final JvmVersion java_8 = JvmVersion.getFromVersion("1.8"); - assertSame(java_8, JAVA_8); - // Unsupported - final JvmVersion java_unsupported = JvmVersion.getFromVersion("abc"); - assertSame(java_unsupported, UNSUPPORTED); - } - - @Test - public void testGetFromClassVersion() { - // JDK 5 - final JvmVersion java_5 = JvmVersion.getFromClassVersion(49); - assertSame(java_5, JAVA_5); - // JDK 6 - final JvmVersion java_6 = JvmVersion.getFromClassVersion(50); - assertSame(java_6, JAVA_6); - // JDK 7 - final JvmVersion java_7 = JvmVersion.getFromClassVersion(51); - assertSame(java_7, JAVA_7); - // JDK 8 - final JvmVersion java_8 = JvmVersion.getFromClassVersion(52); - assertSame(java_8, JAVA_8); - // Unsupported - final JvmVersion java_unsupported = JvmVersion.getFromClassVersion(-1); - assertSame(java_unsupported, UNSUPPORTED); - } -} +package com.nhn.pinpoint.common.util; + +import static org.junit.Assert.*; +import static com.nhn.pinpoint.common.util.JvmVersion.*; + +import org.junit.Test; + +/** + * @author hyungil.jeong + */ +public class JvmVersionTest { + + @Test + public void testOnOrAfter() { + // JDK 5 + assertTrue(JAVA_5.onOrAfter(JAVA_5)); + assertFalse(JAVA_5.onOrAfter(JAVA_6)); + assertFalse(JAVA_5.onOrAfter(JAVA_7)); + assertFalse(JAVA_5.onOrAfter(JAVA_8)); + assertFalse(JAVA_5.onOrAfter(UNSUPPORTED)); + // JDK 6 + assertTrue(JAVA_6.onOrAfter(JAVA_5)); + assertTrue(JAVA_6.onOrAfter(JAVA_6)); + assertFalse(JAVA_6.onOrAfter(JAVA_7)); + assertFalse(JAVA_6.onOrAfter(JAVA_8)); + assertFalse(JAVA_6.onOrAfter(UNSUPPORTED)); + // JDK 7 + assertTrue(JAVA_7.onOrAfter(JAVA_5)); + assertTrue(JAVA_7.onOrAfter(JAVA_6)); + assertTrue(JAVA_7.onOrAfter(JAVA_7)); + assertFalse(JAVA_7.onOrAfter(JAVA_8)); + assertFalse(JAVA_7.onOrAfter(UNSUPPORTED)); + // JDK 8 + assertTrue(JAVA_8.onOrAfter(JAVA_5)); + assertTrue(JAVA_8.onOrAfter(JAVA_6)); + assertTrue(JAVA_8.onOrAfter(JAVA_7)); + assertTrue(JAVA_8.onOrAfter(JAVA_8)); + assertFalse(JAVA_8.onOrAfter(UNSUPPORTED)); + // Unsupported + assertFalse(UNSUPPORTED.onOrAfter(JAVA_5)); + assertFalse(UNSUPPORTED.onOrAfter(JAVA_6)); + assertFalse(UNSUPPORTED.onOrAfter(JAVA_7)); + assertFalse(UNSUPPORTED.onOrAfter(JAVA_8)); + assertFalse(UNSUPPORTED.onOrAfter(UNSUPPORTED)); + } + + @Test + public void testGetFromDoubleVersion() { + // JDK 5 + final JvmVersion java_5 = JvmVersion.getFromVersion(1.5); + assertSame(java_5, JAVA_5); + // JDK 6 + final JvmVersion java_6 = JvmVersion.getFromVersion(1.6); + assertSame(java_6, JAVA_6); + // JDK 7 + final JvmVersion java_7 = JvmVersion.getFromVersion(1.7); + assertSame(java_7, JAVA_7); + // JDK 8 + final JvmVersion java_8 = JvmVersion.getFromVersion(1.8); + assertSame(java_8, JAVA_8); + // Unsupported + final JvmVersion java_unsupported = JvmVersion.getFromVersion(0.9); + assertSame(java_unsupported, UNSUPPORTED); + } + + @Test + public void testGetFromStringVersion() { + // JDK 5 + final JvmVersion java_5 = JvmVersion.getFromVersion("1.5"); + assertSame(java_5, JAVA_5); + // JDK 6 + final JvmVersion java_6 = JvmVersion.getFromVersion("1.6"); + assertSame(java_6, JAVA_6); + // JDK 7 + final JvmVersion java_7 = JvmVersion.getFromVersion("1.7"); + assertSame(java_7, JAVA_7); + // JDK 8 + final JvmVersion java_8 = JvmVersion.getFromVersion("1.8"); + assertSame(java_8, JAVA_8); + // Unsupported + final JvmVersion java_unsupported = JvmVersion.getFromVersion("abc"); + assertSame(java_unsupported, UNSUPPORTED); + } + + @Test + public void testGetFromClassVersion() { + // JDK 5 + final JvmVersion java_5 = JvmVersion.getFromClassVersion(49); + assertSame(java_5, JAVA_5); + // JDK 6 + final JvmVersion java_6 = JvmVersion.getFromClassVersion(50); + assertSame(java_6, JAVA_6); + // JDK 7 + final JvmVersion java_7 = JvmVersion.getFromClassVersion(51); + assertSame(java_7, JAVA_7); + // JDK 8 + final JvmVersion java_8 = JvmVersion.getFromClassVersion(52); + assertSame(java_8, JAVA_8); + // Unsupported + final JvmVersion java_unsupported = JvmVersion.getFromClassVersion(-1); + assertSame(java_unsupported, UNSUPPORTED); + } +} diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/PinpointThreadFactoryTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/PinpointThreadFactoryTest.java index 2b8cd34aa0d7..ffe932c4f09b 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/util/PinpointThreadFactoryTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/PinpointThreadFactoryTest.java @@ -15,20 +15,22 @@ public class PinpointThreadFactoryTest { @Test public void testCreateThreadFactory() throws Exception { - final AtomicInteger test = new AtomicInteger(0); + final AtomicInteger counter = new AtomicInteger(0); PinpointThreadFactory pinpoint = new PinpointThreadFactory("pinpoint"); Thread thread = pinpoint.newThread(new Runnable() { @Override public void run() { - test.getAndIncrement(); + counter.getAndIncrement(); } }); thread.start(); thread.join(); - Assert.assertEquals(test.get(), 1); + + Assert.assertEquals(counter.get(), 1); + String threadName = thread.getName(); - logger.info(threadName); + logger.debug(threadName); Assert.assertTrue(threadName.startsWith("pinpoint(")); Assert.assertTrue(threadName.endsWith(")")); @@ -37,7 +39,7 @@ public void run() { public void run() { } }); - logger.info(thread2.getName()); + logger.debug(thread2.getName()); } } diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/PropertyUtilsTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/PropertyUtilsTest.java index 0b51e95ef52d..08642ef6ecfc 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/util/PropertyUtilsTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/PropertyUtilsTest.java @@ -3,13 +3,15 @@ import junit.framework.Assert; import org.junit.Test; +import java.net.URL; import java.util.Properties; public class PropertyUtilsTest { @Test public void testLoadProperty() throws Exception { - String path = PropertyUtils.class.getClassLoader().getResource("test.properties").getPath(); + URL resource = PropertyUtils.class.getClassLoader().getResource("test.properties"); + String path = resource.getPath(); Properties properties = PropertyUtils.loadProperty(path); assertProperty(properties); diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/SqlParserTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/SqlParserTest.java index c75bb9e1609c..53dd701dce38 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/util/SqlParserTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/SqlParserTest.java @@ -3,6 +3,8 @@ import junit.framework.Assert; import junit.framework.AssertionFailedError; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; @@ -10,6 +12,9 @@ * @author emeroad */ public class SqlParserTest { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private SqlParser sqlParser = new SqlParser(); private OutputParameterParser outputParameterParser = new OutputParameterParser(); @@ -19,27 +24,26 @@ public void normalizedSql() { ParsingResult parsingResult = sqlParser.normalizedSql("select * from table a = 1 and b=50 and c=? and d='11'"); String s = parsingResult.getSql(); - System.out.println(s); - System.out.println(parsingResult.getOutput()); + logger.debug(s); + logger.debug(parsingResult.getOutput()); ParsingResult parsingResult2 = sqlParser.normalizedSql(" "); String s2 = parsingResult2.getSql(); - System.out.println(s2); + logger.debug(s2); - System.out.println((char) -1); + logger.debug("{}", (char) -1); String str = "s"; - System.out.println(str.codePointAt(0)); - System.out.println((int) str.charAt(0)); - System.out.println("high" + (char) Character.MAX_HIGH_SURROGATE); - System.out.println("low" + (char) Character.MIN_LOW_SURROGATE); - - System.out.println((int) Character.MIN_LOW_SURROGATE); - System.out.println((int) Character.MAX_HIGH_SURROGATE); + logger.debug("{}", str.codePointAt(0)); + logger.debug("{}", (int) str.charAt(0)); + logger.debug("high:{}", Character.MAX_HIGH_SURROGATE); + logger.debug("low:{}", Character.MIN_LOW_SURROGATE); + logger.debug("{}", (int) Character.MIN_LOW_SURROGATE); + logger.debug("{}", (int) Character.MAX_HIGH_SURROGATE); ParsingResult parsingResult3 = sqlParser.normalizedSql("''"); String s3 = parsingResult3.getSql(); - System.out.println("s3:" + s3); - System.out.println("sb3:" + parsingResult3.getOutput()); + logger.debug("s3:{}", s3); + logger.debug("sb3:{}", parsingResult3.getOutput()); } @Test @@ -178,7 +182,7 @@ public void symbolState() { // @Test public void charout() { for (int i = 11; i < 67; i++) { - System.out.println((char) i); + logger.debug("{}", (char) i); } } @@ -203,7 +207,7 @@ public void sepratorTest() { assertEqual("'1234''456,7'", "'0$'", "1234''456,,7"); ParsingResult parsingResult2 = this.sqlParser.normalizedSql("'1234''456,7'"); - System.out.println(parsingResult2); + logger.debug("{}", parsingResult2); // 문자열 토큰 @@ -255,7 +259,7 @@ private void assertEqual(String expected) { try { Assert.assertEquals(expected, normalizedSql); } catch (AssertionFailedError e) { - System.err.println("Original :" + expected); + logger.warn("Original :{}", expected); throw e; } } @@ -266,7 +270,7 @@ private void assertEqual(String expected, String actual) { try { Assert.assertEquals(actual, normalizedSql); } catch (AssertionFailedError e) { - System.err.println("Original :" + expected); + logger.warn("Original :{}", expected); throw e; } } @@ -277,11 +281,11 @@ private void assertEqual(String expected, String actual, String ouputExpected) { String output = parsingResult.getOutput(); List outputParams = outputParameterParser.parseOutputParameter(output); String s = sqlParser.combineOutputParams(normalizedSql, outputParams); - System.out.println("combine:" + s); + logger.debug("combine:" + s); try { Assert.assertEquals("normalizedSql check", actual, normalizedSql); } catch (AssertionFailedError e) { - System.err.println("Original :" + expected); + logger.warn("Original :{}", expected); throw e; } @@ -295,7 +299,7 @@ private void assertEqualObject(String expected) { Assert.assertEquals("normalizedSql check", expected, normalizedSql); Assert.assertSame(expected, normalizedSql); } catch (AssertionFailedError e) { - System.err.println("Original :" + expected); + logger.warn("Original :{}", expected); throw e; } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/BufferedStorageFactory.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/BufferedStorageFactory.java index 92b0a22d1ad2..301fc5655012 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/BufferedStorageFactory.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/BufferedStorageFactory.java @@ -23,7 +23,7 @@ public BufferedStorageFactory(DataSender dataSender, ProfilerConfig config, Agen } this.dataSender = dataSender; - this.bufferSize = config.getIoBufferingBufferBufferSize(); + this.bufferSize = config.getIoBufferingBufferSize(); this.spanChunkFactory = new SpanChunkFactory(agentInformation); } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/Storage.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/Storage.java index 3289b105f477..a9c832a956a0 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/Storage.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/storage/Storage.java @@ -10,14 +10,12 @@ public interface Storage { /** - * store(SpanEvent spanEvent)와 store(Span span)간 동기화가 구현되어 있어야 한다. * * @param spanEvent */ void store(SpanEvent spanEvent); /** - * store(SpanEvent spanEvent)와 store(Span span)간 동기화가 구현되어 있어야 한다. * * @param span */ diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadMetricSetSelector.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadMetricSetSelector.java index 0a7bdfc89353..213ada777203 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadMetricSetSelector.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadMetricSetSelector.java @@ -3,7 +3,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.nhn.pinpoint.common.JvmVersion; +import com.nhn.pinpoint.common.util.JvmVersion; import com.nhn.pinpoint.common.util.JvmUtils; import com.nhn.pinpoint.profiler.monitor.codahale.cpu.metric.CpuLoadMetricSet; import com.nhn.pinpoint.profiler.monitor.codahale.cpu.metric.DefaultCpuLoadMetricSet; diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/StaticAcceptHistogram.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/StaticAcceptHistogram.java index 583a979e6255..32dd551c48a2 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/StaticAcceptHistogram.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/StaticAcceptHistogram.java @@ -1,6 +1,6 @@ package com.nhn.pinpoint.profiler.monitor.metric; -import com.nhn.pinpoint.common.IntHashMap; +import com.nhn.pinpoint.common.util.apache.IntHashMap; import com.nhn.pinpoint.common.ServiceType; import java.util.concurrent.ConcurrentHashMap; diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/HeaderTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/HeaderTest.java index a1118793f700..aa7b0c254ad4 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/HeaderTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/HeaderTest.java @@ -2,10 +2,16 @@ import com.nhn.pinpoint.bootstrap.context.Header; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class HeaderTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Test public void testToString() throws Exception { - System.out.println(Header.HTTP_FLAGS); + logger.debug("{}", Header.HTTP_FLAGS); } } diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/AroundInterceptor.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/AroundInterceptor.java similarity index 72% rename from bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/AroundInterceptor.java rename to profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/AroundInterceptor.java index eec2bf884fcf..3367d955c380 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/AroundInterceptor.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/AroundInterceptor.java @@ -1,12 +1,12 @@ -package com.nhn.pinpoint.bootstrap.interceptor; - -/** - * @author emeroad - */ -@Deprecated -public interface AroundInterceptor { - - void before(InterceptorContext ctx); - - void after(InterceptorContext ctx); -} +package com.nhn.pinpoint.profiler.interceptor; + +/** + * @author emeroad + */ +@Deprecated +public interface AroundInterceptor { + + void before(InterceptorContext ctx); + + void after(InterceptorContext ctx); +} diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorContext.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorContext.java similarity index 91% rename from bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorContext.java rename to profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorContext.java index 1a9dc5d52c91..ac663f152253 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorContext.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorContext.java @@ -1,70 +1,70 @@ -package com.nhn.pinpoint.bootstrap.interceptor; - -import java.util.Arrays; - -/** - * @author emeroad - */ -@Deprecated -public class InterceptorContext { - private Object target; - private String className; - private String methodName; - private Object[] parameter; - private Object value; - - private Object result; - - public Object getTarget() { - return target; - } - - public void setTarget(Object target) { - this.target = target; - } - - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public String getMethodName() { - return methodName; - } - - public void setMethodName(String methodName) { - this.methodName = methodName; - } - - public Object[] getParameter() { - return parameter; - } - - public void setParameter(Object[] parameter) { - this.parameter = parameter; - } - - public Object getResult() { - return result; - } - - public void setResult(Object result) { - this.result = result; - } - - public Object getValue() { - return value; - } - - public void setValue(Object value) { - this.value = value; - } - - @Override - public String toString() { - return "InterceptorContext{" + "target=" + target + ", className='" + className + '\'' + ", methodName='" + methodName + '\'' + ", parameter=" + (parameter == null ? null : Arrays.asList(parameter)) + ", value=" + value + ", result=" + result + '}'; - } -} +package com.nhn.pinpoint.profiler.interceptor; + +import java.util.Arrays; + +/** + * @author emeroad + */ +@Deprecated +public class InterceptorContext { + private Object target; + private String className; + private String methodName; + private Object[] parameter; + private Object value; + + private Object result; + + public Object getTarget() { + return target; + } + + public void setTarget(Object target) { + this.target = target; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public Object[] getParameter() { + return parameter; + } + + public void setParameter(Object[] parameter) { + this.parameter = parameter; + } + + public Object getResult() { + return result; + } + + public void setResult(Object result) { + this.result = result; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + @Override + public String toString() { + return "InterceptorContext{" + "target=" + target + ", className='" + className + '\'' + ", methodName='" + methodName + '\'' + ", parameter=" + (parameter == null ? null : Arrays.asList(parameter)) + ", value=" + value + ", result=" + result + '}'; + } +} diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorRegistryTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorRegistryTest.java index 9a622831f266..cf8cc15ed30b 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorRegistryTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorRegistryTest.java @@ -1,8 +1,6 @@ package com.nhn.pinpoint.profiler.interceptor; -import com.nhn.pinpoint.bootstrap.interceptor.AroundInterceptor; import com.nhn.pinpoint.bootstrap.interceptor.Interceptor; -import com.nhn.pinpoint.bootstrap.interceptor.InterceptorContext; import com.nhn.pinpoint.bootstrap.interceptor.InterceptorRegistry; import com.nhn.pinpoint.profiler.interceptor.bci.TestObject; import javassist.*; diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/FormatTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/FormatTest.java index f54597e31a71..5be76f2be939 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/FormatTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/FormatTest.java @@ -1,6 +1,9 @@ package com.nhn.pinpoint.profiler.interceptor.bci; +import junit.framework.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.text.Format; import java.util.Formatter; @@ -9,22 +12,24 @@ * @author emeroad */ public class FormatTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + @Test public void format() { - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb); - formatter.format("interceptor.after(%1s)", "tsest"); + StringBuilder buffer = new StringBuilder(); + Formatter formatter = new Formatter(buffer); + formatter.format("%1s", "ab"); - formatter.format("interceptor.afteddddr(%1s)", "tsest", "dd"); - System.out.println(); + formatter.format("%3s", "a"); + Assert.assertEquals(buffer.toString(), "ab a"); } + @Test public void format2() { - StringBuilder sb = new StringBuilder(); - sb.append("dddd"); - Formatter formatter = new Formatter(sb); + StringBuilder buffer = new StringBuilder(); + Formatter formatter = new Formatter(buffer); + formatter.format("(%s, %s, %s)", 1, 2, 3); - formatter.format("interceptor.afteddddr(%s, %s, %s)", 16, 34234, 333); - System.out.println(sb.toString()); + Assert.assertEquals(buffer.toString(), "(1, 2, 3)"); } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/ReflectionTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/ReflectionTest.java index 6190aa48fafd..a44b1d35b6a5 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/ReflectionTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/ReflectionTest.java @@ -3,6 +3,8 @@ import javassist.*; import org.junit.Before; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Method; @@ -12,6 +14,8 @@ * @author emeroad */ public class ReflectionTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private ClassPool pool = new ClassPool(); @Before public void setUp() throws Exception { @@ -22,14 +26,14 @@ public void setUp() throws Exception { public void test() throws NotFoundException { Constructor[] constructors = String.class.getConstructors(); for(Constructor c: constructors) { - System.out.println(c.getName()); + logger.debug(c.getName()); } CtClass ctClass = pool.get("java.lang.String"); CtConstructor[] constructors1 = ctClass.getConstructors(); for(CtConstructor cc : constructors1) { - System.out.println(cc.getName()); - System.out.println(cc.getLongName()); - System.out.println(cc.getSignature()); + logger.debug(cc.getName()); + logger.debug(cc.getLongName()); + logger.debug(cc.getSignature()); } @@ -39,17 +43,15 @@ public void methodName() throws NotFoundException, ClassNotFoundException, NoSuc CtClass ctClass = pool.get("java.lang.String"); CtMethod subString = ctClass.getDeclaredMethod("substring", new CtClass[]{pool.get("int")}); - System.out.println("getLongName:" + subString.getLongName()); - System.out.println("getName:"+ subString.getName()); - System.out.println("getDescriptor:"+ subString.getMethodInfo().getDescriptor()); - System.out.println("getDescriptor2:"+ subString.getMethodInfo2().getDescriptor()); - System.out.println("getSignature:"+ subString.getSignature()); + logger.debug("getLongName:{}", subString.getLongName()); + logger.debug("getName:{}", subString.getName()); + logger.debug("getDescriptor:{}", subString.getMethodInfo().getDescriptor()); + logger.debug("getDescriptor2:{}", subString.getMethodInfo2().getDescriptor()); + logger.debug("getSignature:{}", subString.getSignature()); Method substring = String.class.getMethod("substring", int.class); - System.out.println(substring.toString()); - System.out.println(Arrays.toString(substring.getParameterTypes())); - -// M + logger.debug(substring.toString()); + logger.debug(Arrays.toString(substring.getParameterTypes())); } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/javaassist/JavaAssistTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/javaassist/JavaAssistTest.java index 4438cac18d91..2a495706edab 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/javaassist/JavaAssistTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/javaassist/JavaAssistTest.java @@ -43,8 +43,8 @@ public void testAssist() throws NotFoundException, NoSuchMethodException { // ctClass.getMethod("valueOf", "(D)"); CtMethod[] methods = ctClass.getMethods(); -// for(CtMethod method : methods) { -// System.out.println(method.getMethodInfo() +" " + method.getSignature()); +// for (CtMethod method : methods) { +// logger.debug("{} {}", method.getMethodInfo(), method.getSignature()); // } CtMethod endsWith = ctClass.getMethod("endsWith", "(Ljava/lang/String;)Z"); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/metadata/AgentIdentifierCompareTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/metadata/AgentIdentifierCompareTest.java index 7193733a0334..98dc2ee9985d 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/metadata/AgentIdentifierCompareTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/metadata/AgentIdentifierCompareTest.java @@ -1,6 +1,8 @@ package com.nhn.pinpoint.profiler.metadata; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -10,16 +12,18 @@ * @author emeroad */ public class AgentIdentifierCompareTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + @Test public void test() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long l = System.currentTimeMillis(); Date date = new Date(l); - System.out.println(simpleDateFormat.format(date)); + logger.debug(simpleDateFormat.format(date)); int max = Integer.MAX_VALUE; Date maxAfter = new Date(l+max); - System.out.println(simpleDateFormat.format(maxAfter)); + logger.debug(simpleDateFormat.format(maxAfter)); // Agent의 identifer대신에 서버시작시간 - 실행시간을 구해서 int type으로 전달하는건 좋은 생각아 아님 // int max를 더하더라도 최대 한달 정도가 한계임, unsigned type으로 해도 두달 그냥 사이즈 빼서 가변 인코딩 long으로 보내야 함. // 2013-05-25 15:39:09 diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/mapping/MappingTableTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/mapping/MappingTableTest.java deleted file mode 100644 index 21bf7c8aa775..000000000000 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/mapping/MappingTableTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.nhn.pinpoint.profiler.modifier.mapping; - -import org.junit.Test; - -/** - * @author emeroad - */ -public class MappingTableTest { - @Test - public void testLookupMethodDescriptor() throws Exception { - // 2147483647 - // xxxxxxxx - yyy xxxx는 class 명, yyy는 함수명매칭하자. 하자. - int maxValue = Integer.MAX_VALUE; - int i = 2147483647 / 100; - System.out.println(i); - - - } -} diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricMonitorRegistryTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricMonitorRegistryTest.java index 167e288f2008..7da68da1de24 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricMonitorRegistryTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricMonitorRegistryTest.java @@ -21,8 +21,12 @@ import com.nhn.pinpoint.thrift.dto.TAgentStat._Fields; import com.nhn.pinpoint.profiler.monitor.codahale.MetricHistogramMonitor; import com.nhn.pinpoint.profiler.monitor.codahale.MetricMonitorRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MetricMonitorRegistryTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + MetricMonitorRegistry registry = new MetricMonitorRegistry(); @@ -111,18 +115,18 @@ public void mapper() { MetricRegistry r = registry.getRegistry(); Map map = r.getGauges(); // for (Entry each : map.entrySet()) { -// System.out.println(each.getKey() + " : " + each.getValue().getValue().getClass()); +// logger.debug(each.getKey() + " : " + each.getValue().getValue().getClass()); // } // for (Entry<_Fields, FieldMetaData> each : TAgentStat.metaDataMap.entrySet()) { - System.out.println(toMetricName(each.getKey().name())); + logger.debug(toMetricName(each.getKey().name())); Gauge value = map.get(toMetricName(each.getKey().name())); if (value != null) { agentStat.setFieldValue(each.getKey(), value.getValue()); } } - - System.out.println(agentStat); + + logger.debug("{}", agentStat); } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/metric/WasStaticAcceptHistogramTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/metric/WasStaticAcceptHistogramTest.java index e47f3fd95c46..2fdb39897019 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/metric/WasStaticAcceptHistogramTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/metric/WasStaticAcceptHistogramTest.java @@ -3,12 +3,15 @@ import com.nhn.pinpoint.common.ServiceType; import junit.framework.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class WasStaticAcceptHistogramTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Test public void testLookUp() throws Exception { @@ -64,7 +67,7 @@ public void run() { } latch.await(); } - System.out.println(System.currentTimeMillis() - l); + logger.debug("{}", System.currentTimeMillis() - l); executors.shutdown(); } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/sampler/SimpleSamplerTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/sampler/SimpleSamplerTest.java index b3a97e50c3e2..893d79012da1 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/sampler/SimpleSamplerTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/sampler/SimpleSamplerTest.java @@ -4,11 +4,16 @@ import com.nhn.pinpoint.profiler.sampler.SamplingRateSampler; import org.junit.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @author emeroad */ public class SimpleSamplerTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Test public void test() { SamplingRateSampler simpleSampler = new SamplingRateSampler(1); @@ -27,10 +32,10 @@ public void test() { @Test public void mod() { int i = 0 % 101; - System.out.println("" + i); + logger.debug("{}", i); int j = Math.abs(-102) % 101; - System.out.println("" + j); + logger.debug("{}", j); } private void assertDrop(SamplingRateSampler simpleSampler) { diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/GoavaCacheTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/GuavaCacheTest.java similarity index 66% rename from profiler/src/test/java/com/navercorp/pinpoint/profiler/util/GoavaCacheTest.java rename to profiler/src/test/java/com/navercorp/pinpoint/profiler/util/GuavaCacheTest.java index 8490e61cac98..0249313a460b 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/GoavaCacheTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/GuavaCacheTest.java @@ -1,25 +1,30 @@ -package com.nhn.pinpoint.profiler.util; - -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import org.junit.Test; - -/** - * @author emeroad - */ -public class GoavaCacheTest { - @Test - public void test() { - CacheBuilder builder = CacheBuilder.newBuilder(); - builder.concurrencyLevel(8); - builder.maximumSize(1); - builder.initialCapacity(1); - Cache cache = builder.build(); - - cache.put("test1", "1"); - System.out.println(cache.size()); - cache.put("test3", "2"); - System.out.println(cache.size()); - - } -} +package com.nhn.pinpoint.profiler.util; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author emeroad + */ +public class GuavaCacheTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + + @Test + public void test() { + CacheBuilder builder = CacheBuilder.newBuilder(); + builder.concurrencyLevel(8); + builder.maximumSize(1); + builder.initialCapacity(1); + Cache cache = builder.build(); + + cache.put("test1", "1"); + logger.debug("{}", cache.size()); + cache.put("test3", "2"); + logger.debug("{}", cache.size()); + + } +} diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/PreparedStatementUtilsTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/PreparedStatementUtilsTest.java index e2dc9e480c50..95fde98d25f4 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/PreparedStatementUtilsTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/PreparedStatementUtilsTest.java @@ -2,6 +2,8 @@ import org.junit.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.List; @@ -10,11 +12,14 @@ * @author emeroad */ public class PreparedStatementUtilsTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Test public void testBindSetMethod() { List bindVariableSetMethod = PreparedStatementUtils.findBindVariableSetMethod(); for (Method method : bindVariableSetMethod) { - System.out.println(method); + logger.debug("{}", method); } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/bindvalue/BindValueConverterTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/bindvalue/BindValueConverterTest.java index 34ab8af8bc30..482089896d9c 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/bindvalue/BindValueConverterTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/bindvalue/BindValueConverterTest.java @@ -2,19 +2,23 @@ import junit.framework.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Date; public class BindValueConverterTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + @Test public void testBindValueToString() throws Exception { Date d = new Date(); - System.out.println(d); + logger.debug("{}", d); byte[] bytes = new byte[] {1, 2, 4}; String s = Arrays.toString(bytes); - System.out.println(s); + logger.debug(s); } @Test diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/MessageListenerTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/MessageListenerTest.java index aeb9d843031d..ec1a75218a40 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/MessageListenerTest.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/MessageListenerTest.java @@ -259,7 +259,7 @@ public void handleSend(SendPacket sendPacket, Channel channel) { sendPacketRepository.add(sendPacket); byte[] payload = sendPacket.getPayload(); - System.out.println(new String(payload)); + logger.debug(new String(payload)); } @Override @@ -267,7 +267,7 @@ public void handleRequest(RequestPacket requestPacket, Channel channel) { requestPacketRepository.add(requestPacket); byte[] payload = requestPacket.getPayload(); - System.out.println(new String(payload)); + logger.debug(new String(payload)); channel.write(new ResponsePacket(requestPacket.getRequestId(), requestPacket.getPayload())); } diff --git a/testweb/src/main/java/com/linecorp/games/common/baseFramework/handlers/HttpCustomServerHandler.java b/testweb/src/main/java/com/linecorp/games/common/baseFramework/handlers/HttpCustomServerHandler.java index aae9541c4d93..218c2471776a 100644 --- a/testweb/src/main/java/com/linecorp/games/common/baseFramework/handlers/HttpCustomServerHandler.java +++ b/testweb/src/main/java/com/linecorp/games/common/baseFramework/handlers/HttpCustomServerHandler.java @@ -68,7 +68,7 @@ public HttpCustomServerHandler() { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { - System.out.println("HttpCustomServerHandler.messageReceived (" + Thread.currentThread().getName() + ")"); + logger.debug("HttpCustomServerHandler.messageReceived ({})", Thread.currentThread().getName()); this.listeningExecutorService.submit(new InvokeTask(ctx, e)); } @@ -102,7 +102,7 @@ public InvokeTask(ChannelHandlerContext ctx, MessageEvent e) { } public void run() { - System.out.println("InvokeTask.run (" + Thread.currentThread().getName() + ")"); + logger.debug("InvokeTask.run ({}}", Thread.currentThread().getName()); if (!(e.getMessage() instanceof HttpRequest)) { logger.debug("[n/a] received message is illegal."); diff --git a/testweb/src/test/java/com/nhn/pinpoint/testweb/connector/apachehttp4/nhnent/HttpUtilTest.java b/testweb/src/test/java/com/nhn/pinpoint/testweb/connector/apachehttp4/nhnent/HttpUtilTest.java index 009a759fc235..e80a25e3f038 100644 --- a/testweb/src/test/java/com/nhn/pinpoint/testweb/connector/apachehttp4/nhnent/HttpUtilTest.java +++ b/testweb/src/test/java/com/nhn/pinpoint/testweb/connector/apachehttp4/nhnent/HttpUtilTest.java @@ -1,6 +1,8 @@ package com.nhn.pinpoint.testweb.connector.apachehttp4.nhnent; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -8,18 +10,17 @@ * */ public class HttpUtilTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final String URL = "http://www.naver.com/"; @Test public void callUrl() { - String response = null; try { - response = HttpUtil.url(URL).method(HttpUtil.Method.POST).connectionTimeout(10000).readTimeout(10000).getContents(); + String response = HttpUtil.url(URL).method(HttpUtil.Method.POST).connectionTimeout(10000).readTimeout(10000).getContents(); + logger.debug(response); } catch (HttpUtilException e) { } - - System.out.println(response); } } diff --git a/testweb/src/test/java/com/nhn/pinpoint/testweb/npc/NPCTest.java b/testweb/src/test/java/com/nhn/pinpoint/testweb/npc/NPCTest.java index 9b8a966a2ce5..17be2fe3ede9 100644 --- a/testweb/src/test/java/com/nhn/pinpoint/testweb/npc/NPCTest.java +++ b/testweb/src/test/java/com/nhn/pinpoint/testweb/npc/NPCTest.java @@ -10,8 +10,12 @@ import com.nhncorp.lucy.net.invoker.InvocationFuture; import com.nhncorp.lucy.npc.connector.NpcHessianConnector; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class NPCTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + @Test public void connect() { @@ -29,7 +33,7 @@ public void connect() { // Object result = future.get(); Object result = future.getReturnValue(); - System.out.println(result); + logger.debug("{}", result); Assert.assertNotNull(result); } catch (Exception e) { e.printStackTrace(); diff --git a/testweb/src/test/java/com/nhn/pinpoint/testweb/service/http/ApacheClosableAsyncHttpClientTest.java b/testweb/src/test/java/com/nhn/pinpoint/testweb/service/http/ApacheClosableAsyncHttpClientTest.java index fcb008e9f84e..63e8a6a97862 100644 --- a/testweb/src/test/java/com/nhn/pinpoint/testweb/service/http/ApacheClosableAsyncHttpClientTest.java +++ b/testweb/src/test/java/com/nhn/pinpoint/testweb/service/http/ApacheClosableAsyncHttpClientTest.java @@ -2,6 +2,8 @@ import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -16,6 +18,7 @@ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/applicationContext-testweb.xml", "/servlet-context.xml" }) public class ApacheClosableAsyncHttpClientTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private ApacheClosableAsyncHttpClient apacheClosableAsyncHttpClient; @@ -23,6 +26,6 @@ public class ApacheClosableAsyncHttpClientTest { @Test public void requestPost() { String requestPost = apacheClosableAsyncHttpClient.post(); - System.out.println(requestPost); + logger.debug(requestPost); } } \ No newline at end of file diff --git a/testweb/src/test/java/com/nhn/pinpoint/testweb/util/HTClientTest.java b/testweb/src/test/java/com/nhn/pinpoint/testweb/util/HTClientTest.java index 6370c69f6f50..3d3226f9ef9b 100644 --- a/testweb/src/test/java/com/nhn/pinpoint/testweb/util/HTClientTest.java +++ b/testweb/src/test/java/com/nhn/pinpoint/testweb/util/HTClientTest.java @@ -6,14 +6,18 @@ import com.nhn.pinpoint.testweb.connector.apachehttp4.HttpConnectorOptions; import com.nhn.pinpoint.testweb.connector.apachehttp4.ApacheHttpClient4; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HTClientTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + @Test public void test() { ApacheHttpClient4 client = new ApacheHttpClient4(new HttpConnectorOptions()); String executeToBloc = client.execute("http://localhost:9080/", new HashMap()); - System.out.println(executeToBloc); + logger.debug(executeToBloc); } } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDaoTest.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDaoTest.java index dc7a71427c31..110d9d672f08 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDaoTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDaoTest.java @@ -7,6 +7,8 @@ import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -18,6 +20,7 @@ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext-web.xml") public class HbaseAgentStatDaoTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private HbaseAgentStatDao dao; @@ -27,7 +30,7 @@ public void selectAgentStat() { long timestamp = System.currentTimeMillis(); Range range = new Range(timestamp - 100000, timestamp); List result = dao.scanAgentStatList("FRONT-WEB1", range); - System.out.println(result); + logger.debug("{}", result); } } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/HbaseFilterPerformanceTest.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/HbaseFilterPerformanceTest.java index 368cd85057a5..90f4f6a9b24a 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/HbaseFilterPerformanceTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/HbaseFilterPerformanceTest.java @@ -2,7 +2,6 @@ import java.io.IOException; import java.util.List; -import java.util.Properties; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; @@ -17,6 +16,8 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.data.hadoop.hbase.HbaseConfigurationFactoryBean; import org.springframework.data.hadoop.hbase.HbaseSystemException; @@ -24,7 +25,6 @@ import com.nhn.pinpoint.common.buffer.Buffer; import com.nhn.pinpoint.common.hbase.HBaseTables; import com.nhn.pinpoint.common.hbase.HbaseTemplate2; -import com.nhn.pinpoint.common.util.PropertyUtils; import com.nhn.pinpoint.common.util.SpanUtils; import com.nhn.pinpoint.web.mapper.TraceIndexScatterMapper; import com.nhn.pinpoint.web.vo.Range; @@ -36,6 +36,8 @@ import com.sematext.hbase.wd.RowKeyDistributorByHashPrefix.OneByteSimpleHash; public class HbaseFilterPerformanceTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private static HbaseConfigurationFactoryBean hbaseConfigurationFactoryBean; private static AbstractRowKeyDistributor traceIdRowKeyDistributor; @@ -125,8 +127,8 @@ public void usingFilter() throws Exception { long startTime = System.currentTimeMillis(); List> dotListList = hbaseTemplate2.find(HBaseTables.APPLICATION_TRACE_INDEX, scan, traceIdRowKeyDistributor, fetchLimit, new TraceIndexScatterMapper()); - System.out.println("elapsed : " + (System.currentTimeMillis() - startTime) + "ms"); - System.out.println("fetched size : " + dotListList.size()); + logger.debug("elapsed : {}ms", (System.currentTimeMillis() - startTime)); + logger.debug("fetched size : {}", dotListList.size()); } catch (HbaseSystemException e) { e.printStackTrace(); } finally { diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/PrefixFilterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/PrefixFilterTest.java index 605867d31039..e86296a9623d 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/PrefixFilterTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/PrefixFilterTest.java @@ -5,8 +5,12 @@ import org.junit.Test; import com.nhn.pinpoint.common.util.BytesUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class PrefixFilterTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + @Test public void prefixInt() { @@ -17,11 +21,11 @@ public void prefixInt() { byte[] buffer = new byte[4]; BytesUtils.writeVar32(i, buffer, 0); - System.out.println(compare(before, buffer) + ", " + compare(buffer, before) + ", " + compare(buffer, buffer)); + logger.debug(compare(before, buffer) + ", " + compare(buffer, before) + ", " + compare(buffer, buffer)); before = Arrays.copyOf(buffer, 4); - System.out.println(Arrays.toString(buffer)); + logger.debug(Arrays.toString(buffer)); } } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/path/PathTest.java b/web/src/test/java/com/navercorp/pinpoint/web/path/PathTest.java index 57a1aa46fcc6..fbc241b4b892 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/path/PathTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/path/PathTest.java @@ -5,12 +5,16 @@ import org.junit.Test; import com.nhn.pinpoint.thrift.dto.TSpan; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * */ public class PathTest { - int index; + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + int index; SimpleDateFormat format = new SimpleDateFormat("ss.SSS"); @Test @@ -36,7 +40,7 @@ public void printSpan(String msg, TSpan span) { // System.out.println(msg + " id:" + span.getSpanID() + " pid:" + // span.getParentSpanId() + " time:" + format.format(new // Date(span.getTimestamp()))); - System.out.println(msg + " id:" + span.getSpanId() + " pid:" + span.getParentSpanId() + " time:" + span.getStartTime()); + logger.debug(msg + " id:" + span.getSpanId() + " pid:" + span.getParentSpanId() + " time:" + span.getStartTime()); } // private Span root() { // TraceID traceID = TraceID.newTraceId(); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/vo/TransactionIdTest.java b/web/src/test/java/com/navercorp/pinpoint/web/vo/TransactionIdTest.java index e815ace4a64c..8f8d17b55e85 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/vo/TransactionIdTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/vo/TransactionIdTest.java @@ -9,9 +9,13 @@ import junit.framework.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class TransactionIdTest { - @Test + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Test public void sameAll() { TransactionId id1 = new TransactionId("A1", 1, 1); TransactionId id2 = new TransactionId("A1", 1, 1); @@ -58,13 +62,13 @@ public void order() { for (int i = 0; i < 10; i++) { list.add(new TransactionId("A", 1, numbers.get(i))); } - System.out.println(list); + logger.debug("{}", list); SortedSet set = new TreeSet(list); for (int i = 0; i < 10; i++) { set.add(list.get(i)); } - System.out.println(set); + logger.debug("{}", set); } }