instance_id
stringlengths 17
39
| repo
stringclasses 8
values | issue_id
stringlengths 14
34
| pr_id
stringlengths 14
34
| linking_methods
sequencelengths 1
3
| base_commit
stringlengths 40
40
| merge_commit
stringlengths 0
40
⌀ | hints_text
sequencelengths 0
106
| resolved_comments
sequencelengths 0
119
| created_at
unknown | labeled_as
sequencelengths 0
7
| problem_title
stringlengths 7
174
| problem_statement
stringlengths 0
55.4k
| gold_files
sequencelengths 0
10
| gold_files_postpatch
sequencelengths 1
10
| test_files
sequencelengths 0
60
| gold_patch
stringlengths 220
5.83M
| test_patch
stringlengths 386
194k
⌀ | split_random
stringclasses 3
values | split_time
stringclasses 3
values | issue_start_time
unknown | issue_created_at
unknown | issue_by_user
stringlengths 3
21
| split_repo
stringclasses 3
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pinpoint-apm/pinpoint/611_616 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/611 | pinpoint-apm/pinpoint/616 | [
"keyword_pr_to_issue"
] | a1409559e43a7943f533ed3cf8a39233167b9cea | d6c5e08b6287086729f29b10a265ffd9dcc6b60a | [
"fix applied to 1.1.x branch\n"
] | [] | "2015-06-15T09:23:16Z" | [
"bug",
"enhancement"
] | Handle cases where services have the same application name with different service type. | Backporting fixes to 1.1.0.
Issue resolves the following cases.
1. Services with the same application name but different service types should be selectable separately - #214
2. User nodes now take the destination's service type along with the application name when drawing the server map - #254
| [
"commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java"
] | [
"commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java"
] | [] | diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java
index a0ff208e00d1..948e912ba191 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java
@@ -103,6 +103,12 @@ public static String getDestApplicationNameFromColumnName(byte[] bytes) {
return BytesUtils.toStringAndRightTrim(bytes, 6, length);
}
+ public static String getDestApplicationNameFromColumnNameForUser(byte[] bytes, ServiceType destServiceType) {
+ String destApplicationName = getDestApplicationNameFromColumnName(bytes);
+ String destServiceTypeName = destServiceType.name();
+ return destApplicationName + "_" + destServiceTypeName;
+ }
+
public static String getHost(byte[] bytes) {
int offset = 6 + BytesUtils.bytesToShort(bytes, 4);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java
index f4ef0055002f..9b5d1cc420f3 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.web.dao.hbase;
+import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
@@ -45,7 +46,7 @@ public class HbaseApplicationIndexDao implements ApplicationIndexDao {
@Autowired
@Qualifier("applicationNameMapper")
- private RowMapper<Application> applicationNameMapper;
+ private RowMapper<List<Application>> applicationNameMapper;
@Autowired
@Qualifier("agentIdMapper")
@@ -55,7 +56,12 @@ public class HbaseApplicationIndexDao implements ApplicationIndexDao {
public List<Application> selectAllApplicationNames() {
Scan scan = new Scan();
scan.setCaching(30);
- return hbaseOperations2.find(HBaseTables.APPLICATION_INDEX, scan, applicationNameMapper);
+ List<List<Application>> results = hbaseOperations2.find(HBaseTables.APPLICATION_INDEX, scan, applicationNameMapper);
+ List<Application> applications = new ArrayList<Application>();
+ for (List<Application> result : results) {
+ applications.addAll(result);
+ }
+ return applications;
}
@Override
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java
index 186e061e0c3e..62220fc0f37e 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java
@@ -16,25 +16,50 @@
package com.navercorp.pinpoint.web.mapper;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.hadoop.hbase.Cell;
+import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.data.hadoop.hbase.RowMapper;
import org.springframework.stereotype.Component;
+import com.navercorp.pinpoint.common.ServiceType;
import com.navercorp.pinpoint.web.vo.Application;
/**
*
*/
@Component
-public class ApplicationNameMapper implements RowMapper<Application> {
+public class ApplicationNameMapper implements RowMapper<List<Application>> {
+
@Override
- public Application mapRow(Result result, int rowNum) throws Exception {
+ public List<Application> mapRow(Result result, int rowNum) throws Exception {
if (result.isEmpty()) {
- return null;
+ return Collections.emptyList();
}
+ Set<Short> uniqueTypeCodes = new HashSet<Short>();
String applicationName = Bytes.toString(result.getRow());
- short serviceType = Bytes.toShort(result.value());
- return new Application(applicationName, serviceType);
+
+ List<Cell> list = result.listCells();
+ if (list == null) {
+ return Collections.emptyList();
+ }
+
+ for (Cell cell : list) {
+ short serviceTypeCode = Bytes.toShort(CellUtil.cloneValue(cell));
+ uniqueTypeCodes.add(serviceTypeCode);
+ }
+ List<Application> applications = new ArrayList<Application>();
+ for (short serviceTypeCode : uniqueTypeCodes) {
+ applications.add(new Application(applicationName, ServiceType.findServiceType(serviceTypeCode)));
+ }
+
+ return applications;
}
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java
index 2040310f4724..6afdf3812b55 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.web.mapper;
+import com.navercorp.pinpoint.common.ServiceType;
import com.navercorp.pinpoint.common.buffer.Buffer;
import com.navercorp.pinpoint.common.buffer.FixedBuffer;
import com.navercorp.pinpoint.common.util.ApplicationMapStatisticsUtils;
@@ -71,7 +72,7 @@ public LinkDataMap mapRow(Result result, int rowNum) throws Exception {
for (Cell cell : result.rawCells()) {
final byte[] qualifier = CellUtil.cloneQualifier(cell);
- final Application callerApplication = readCallerApplication(qualifier);
+ final Application callerApplication = readCallerApplication(qualifier, calleeApplication.getServiceType());
if (filter.filter(callerApplication)) {
continue;
}
@@ -98,9 +99,15 @@ public LinkDataMap mapRow(Result result, int rowNum) throws Exception {
return linkDataMap;
}
- private Application readCallerApplication(byte[] qualifier) {
- String callerApplicationName = ApplicationMapStatisticsUtils.getDestApplicationNameFromColumnName(qualifier);
- short callerServiceType = ApplicationMapStatisticsUtils.getDestServiceTypeFromColumnName(qualifier);
+ private Application readCallerApplication(byte[] qualifier, ServiceType calleeServiceType) {
+ short callerServiceType = ApplicationMapStatisticsUtils.getDestServiceTypeFromColumnName(qualifier);// Caller may be a user node, and user nodes may call nodes with the same application name but different service type.
+ // To distinguish between these user nodes, append callee's service type to the application name.
+ String callerApplicationName;
+ if (ServiceType.findServiceType(callerServiceType).isUser()) {
+ callerApplicationName = ApplicationMapStatisticsUtils.getDestApplicationNameFromColumnNameForUser(qualifier, calleeServiceType);
+ } else {
+ callerApplicationName = ApplicationMapStatisticsUtils.getDestApplicationNameFromColumnName(qualifier);
+ }
return new Application(callerApplicationName, callerServiceType);
}
| null | val | train | "2015-06-11T11:18:26" | "2015-06-15T06:05:42Z" | Xylus | test |
pinpoint-apm/pinpoint/623_629 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/623 | pinpoint-apm/pinpoint/629 | [
"keyword_pr_to_issue"
] | be3c85556a34d843b2af6ab27313d6ad4435b5fe | 97ac4234852739913df3ae6093c6631adeb9152f | [] | [] | "2015-06-17T02:07:21Z" | [
"bug"
] | Thrift plugin depends on commons-lang3 | Thrift plugin seems like developed based on Thrift 0.9.1, which dependes on commons-lang3. The plugin uses classes of commons-lang3 too. But Thrfit 0.9.2 removed commons-lang3 dependency. As a result, when pinpoint is applied to an application which uses Thrift 0.9.2 but not commons-lang3, an exception occurs:
```
java.lang.NoClassDefFoundError: org/apache/commons/lang3/StringUtils
at com.navercorp.pinpoint.plugin.thrift.ThriftUtils.getClientServiceName(ThriftUtils.java:59)
at com.navercorp.pinpoint.plugin.thrift.interceptor.client.TServiceClientSendBaseInterceptor.before(TServiceClientSendBaseInterceptor.java:124)
at com.navercorp.pinpoint.profiler.plugin.interceptor.GroupedSimpleAroundInterceptor.before(GroupedSimpleAroundInterceptor.java:48)
at org.apache.thrift.TServiceClient.sendBase(TServiceClient.java)
```
| [
"plugins/thrift/pom.xml",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java"
] | [
"plugins/thrift/pom.xml",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java"
] | [
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftSimpleServerIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadPoolServerIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java"
] | diff --git a/plugins/thrift/pom.xml b/plugins/thrift/pom.xml
index dbd629f00323..630b56c2d087 100644
--- a/plugins/thrift/pom.xml
+++ b/plugins/thrift/pom.xml
@@ -24,11 +24,6 @@
<artifactId>libthrift</artifactId>
<scope>provided</scope>
</dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </dependency>
<!-- Logging depedencies -->
<dependency>
@@ -50,7 +45,6 @@
<artifactId>log4j</artifactId>
<scope>compile</scope>
</dependency>
-
</dependencies>
</project>
\ No newline at end of file
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java
index 7d14d13af088..0391047e6a49 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java
@@ -18,8 +18,8 @@
import java.net.InetSocketAddress;
import java.net.SocketAddress;
+import java.util.regex.Pattern;
-import org.apache.commons.lang3.StringUtils;
import org.apache.thrift.TBaseAsyncProcessor;
import org.apache.thrift.TBaseProcessor;
import org.apache.thrift.TServiceClient;
@@ -29,16 +29,25 @@
* @author HyunGil Jeong
*/
public class ThriftUtils implements ThriftConstants {
+
+ private static final Pattern DOT_PATTERN = Pattern.compile("\\.");
private ThriftUtils() {}
+ private static String convertDotPathToUriPath(String dotPath) {
+ if (dotPath == null) {
+ return "";
+ }
+ return DOT_PATTERN.matcher(dotPath).replaceAll("/");
+ }
+
/**
* Returns the name of the specified {@link org.apache.thrift.TBaseProcessor TBaseProcessor}
* as uri to be used in Pinpoint.
*/
public static String getProcessorNameAsUri(TBaseProcessor<?> processor) {
String actualProcessorName = processor.getClass().getName();
- return StringUtils.replace(PROCESSOR_PATTERN.matcher(actualProcessorName).replaceAll("."), ".", "/");
+ return convertDotPathToUriPath(PROCESSOR_PATTERN.matcher(actualProcessorName).replaceAll("."));
}
/**
@@ -47,7 +56,7 @@ public static String getProcessorNameAsUri(TBaseProcessor<?> processor) {
*/
public static String getAsyncProcessorNameAsUri(TBaseAsyncProcessor<?> asyncProcessor) {
String actualAsyncProcessorName = asyncProcessor.getClass().getName();
- return StringUtils.replace(ASYNC_PROCESSOR_PATTERN.matcher(actualAsyncProcessorName).replaceAll("."), ".", "/");
+ return convertDotPathToUriPath(ASYNC_PROCESSOR_PATTERN.matcher(actualAsyncProcessorName).replaceAll("."));
}
/**
@@ -56,7 +65,7 @@ public static String getAsyncProcessorNameAsUri(TBaseAsyncProcessor<?> asyncProc
*/
public static String getClientServiceName(TServiceClient client) {
String clientClassName = client.getClass().getName();
- return StringUtils.replace(CLIENT_PATTERN.split(clientClassName)[0], ".", "/");
+ return convertDotPathToUriPath(CLIENT_PATTERN.split(clientClassName)[0]);
}
/**
@@ -65,7 +74,7 @@ public static String getClientServiceName(TServiceClient client) {
*/
public static String getAsyncMethodCallName(TAsyncMethodCall<?> asyncMethodCall) {
String asyncMethodCallClassName = asyncMethodCall.getClass().getName();
- return StringUtils.replace(ASYNC_METHOD_CALL_PATTERN.matcher(asyncMethodCallClassName).replaceAll("."), ".", "/");
+ return convertDotPathToUriPath(ASYNC_METHOD_CALL_PATTERN.matcher(asyncMethodCallClassName).replaceAll("."));
}
/**
| diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java
index f81d7d27c7f1..f8c577307007 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java
@@ -40,7 +40,7 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "org.apache.commons:commons-lang3:3.3.2", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
+@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
public class ThriftHalfSyncHalfAsyncServerAsyncIT extends EchoTestRunner<THsHaServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java
index 36c9fb62d2db..670fd1b23c9d 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java
@@ -40,7 +40,7 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "org.apache.commons:commons-lang3:3.3.2", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
+@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
public class ThriftNonblockingServerAsyncIT extends EchoTestRunner<TNonblockingServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java
index 2f8711004520..ec81e47e930f 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java
@@ -40,7 +40,7 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "org.apache.commons:commons-lang3:3.3.2", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
+@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
public class ThriftThreadedSelectorServerAsyncIT extends EchoTestRunner<TThreadedSelectorServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java
index aaabaf9717b8..f426093024f1 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java
@@ -40,7 +40,7 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "org.apache.commons:commons-lang3:3.3.2", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
+@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
public class ThriftHalfSyncHalfAsyncServerIT extends EchoTestRunner<THsHaServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java
index 041f4ccd1652..58ae440ea8f3 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java
@@ -40,7 +40,7 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "org.apache.commons:commons-lang3:3.3.2", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
+@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
public class ThriftNonblockingServerIT extends EchoTestRunner<TNonblockingServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftSimpleServerIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftSimpleServerIT.java
index 99b26c536411..dcd375e32c93 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftSimpleServerIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftSimpleServerIT.java
@@ -40,7 +40,7 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.1,)", "org.apache.commons:commons-lang3:3.3.2", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
+@Dependency({ "org.apache.thrift:libthrift:[0.9.1,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
public class ThriftSimpleServerIT extends EchoTestRunner<TSimpleServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadPoolServerIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadPoolServerIT.java
index 66829a4caa55..05895c3a1232 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadPoolServerIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadPoolServerIT.java
@@ -40,7 +40,7 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.1,)", "org.apache.commons:commons-lang3:3.3.2", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
+@Dependency({ "org.apache.thrift:libthrift:[0.9.1,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
public class ThriftThreadPoolServerIT extends EchoTestRunner<TThreadPoolServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java
index cb2a34f2142b..8efe3d3ab1e9 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java
@@ -40,7 +40,7 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "org.apache.commons:commons-lang3:3.3.2", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
+@Dependency({ "org.apache.thrift:libthrift:[0.9.2,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.5.8" })
public class ThriftThreadedSelectorServerIT extends EchoTestRunner<TThreadedSelectorServer> {
@Override
| train | train | "2015-06-17T03:53:01" | "2015-06-16T08:02:25Z" | lioolli | test |
pinpoint-apm/pinpoint/612_669 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/612 | pinpoint-apm/pinpoint/669 | [
"keyword_pr_to_issue"
] | aefc6bf0aa4ff96a194c986eaaae4a99878b0bb8 | 47e8a959c8a89e033ed0c33c612bd81b92c2d1c9 | [] | [] | "2015-06-25T01:38:37Z" | [
"enhancement"
] | [Collector] refactoring udp collector | - UDPReceiver
- extract L4CheckFilter, NetworkAvailabilityCheckPacketFilter
| [
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java"
] | [
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java"
] | [] | diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java
index 2bcbc36e0cd9..57afcead1ff6 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java
@@ -43,7 +43,7 @@ public void run() {
final DatagramPacket packet = pooledObject.getObject();
try {
packetHandler.receive(packet);
- } catch (Exception e) {
+ } finally {
pooledObject.returnObject();
}
}
| null | train | train | "2015-06-24T07:25:58" | "2015-06-15T06:19:21Z" | emeroad | test |
pinpoint-apm/pinpoint/737_739 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/737 | pinpoint-apm/pinpoint/739 | [
"keyword_pr_to_issue"
] | 4e969e7c5ae0a6d66698b36c3d2bb239cd7c9d07 | dbd49e3ba68753eee1ab9ad044cb41b461bb0902 | [] | [] | "2015-07-17T05:35:32Z" | [
"bug"
] | PreparedStatementExecuteQueryInterceptor.toBindVariable() array index bug fix. | incorrect array index handling of SqlBindValue
#736
| [
"plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java",
"plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java"
] | [
"plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java",
"plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java"
] | diff --git a/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java b/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java
index 5cc7ed292c49..72ccd7954431 100644
--- a/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java
+++ b/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java
@@ -18,14 +18,51 @@
import com.navercorp.pinpoint.bootstrap.util.StringUtils;
+import java.util.Map;
+
/**
+ * duplicate : com.navercorp.pinpoint.profiler.modifier.db.interceptor.BindValueUtils
* @author emeroad
*/
-public class BindValueUtils {
+public final class BindValueUtils {
private BindValueUtils() {
}
+ public static String bindValueToString(final Map<Integer, String> bindValueMap, int limit) {
+ if (bindValueMap == null) {
+ return "";
+ }
+ if (bindValueMap.isEmpty()) {
+ return "";
+ }
+ final int maxParameterIndex = getMaxParameterIndex(bindValueMap);
+ if (maxParameterIndex <= 0) {
+ return "";
+ }
+ final String[] temp = new String[maxParameterIndex];
+ for (Map.Entry<Integer, String> entry : bindValueMap.entrySet()) {
+ final int parameterIndex = entry.getKey() - 1;
+ if (parameterIndex < 0) {
+ // invalid index. PreparedStatement first parameterIndex is 1
+ continue;
+ }
+ if (temp.length <= parameterIndex) {
+ continue;
+ }
+ temp[parameterIndex] = entry.getValue();
+ }
+ return bindValueToString(temp, limit);
+ }
+
+ private static int getMaxParameterIndex(Map<Integer, String> bindValueMap) {
+ int maxIndex = 0;
+ for (Integer idx : bindValueMap.keySet()) {
+ maxIndex = Math.max(maxIndex, idx);
+ }
+ return maxIndex;
+ }
+
public static String bindValueToString(String[] bindValueArray, int limit) {
if (bindValueArray == null) {
return "";
@@ -39,7 +76,8 @@ public static String bindValueToString(String[] bindValueArray, int limit) {
appendLength(sb, length);
break;
}
- StringUtils.appendDrop(sb, bindValueArray[i], limit);
+ final String bindValue = StringUtils.defaultString(bindValueArray[i], "");
+ StringUtils.appendDrop(sb, bindValue, limit);
if (i < end) {
sb.append(", ");
}
diff --git a/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java b/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java
index 815734ba5931..ee7c6bcb7f1e 100644
--- a/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java
+++ b/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java
@@ -130,17 +130,7 @@ private void clean(Object target) {
}
private String toBindVariable(Map<Integer, String> bindValue) {
- final String[] temp = new String[bindValue.size()];
- for (Map.Entry<Integer, String> entry : bindValue.entrySet()) {
- Integer key = entry.getKey() - 1;
- if (temp.length <= key) {
- continue;
- }
- temp[key] = entry.getValue();
- }
-
- return BindValueUtils.bindValueToString(temp, maxSqlBindValueLength);
-
+ return BindValueUtils.bindValueToString(bindValue, maxSqlBindValueLength);
}
@Override
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java
index 815f613b2bb8..50c78810eef4 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java
@@ -18,14 +18,50 @@
import com.navercorp.pinpoint.bootstrap.util.StringUtils;
+import java.util.Map;
+
/**
* @author emeroad
*/
-public class BindValueUtils {
+public final class BindValueUtils {
private BindValueUtils() {
}
+ public static String bindValueToString(final Map<Integer, String> bindValueMap, int limit) {
+ if (bindValueMap == null) {
+ return "";
+ }
+ if (bindValueMap.isEmpty()) {
+ return "";
+ }
+ final int maxParameterIndex = getMaxParameterIndex(bindValueMap);
+ if (maxParameterIndex <= 0) {
+ return "";
+ }
+ final String[] temp = new String[maxParameterIndex];
+ for (Map.Entry<Integer, String> entry : bindValueMap.entrySet()) {
+ final int parameterIndex = entry.getKey() - 1;
+ if (parameterIndex < 0) {
+ // invalid index. PreparedStatement first parameterIndex is 1
+ continue;
+ }
+ if (temp.length <= parameterIndex) {
+ continue;
+ }
+ temp[parameterIndex] = entry.getValue();
+ }
+ return bindValueToString(temp, limit);
+ }
+
+ private static int getMaxParameterIndex(Map<Integer, String> bindValueMap) {
+ int maxIndex = 0;
+ for (Integer idx : bindValueMap.keySet()) {
+ maxIndex = Math.max(maxIndex, idx);
+ }
+ return maxIndex;
+ }
+
public static String bindValueToString(String[] bindValueArray, int limit) {
if (bindValueArray == null) {
return "";
@@ -39,7 +75,8 @@ public static String bindValueToString(String[] bindValueArray, int limit) {
appendLength(sb, length);
break;
}
- StringUtils.appendDrop(sb, bindValueArray[i], limit);
+ final String bindValue = StringUtils.defaultString(bindValueArray[i], "");
+ StringUtils.appendDrop(sb, bindValue, limit);
if (i < end) {
sb.append(", ");
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java
index 0b1f9da3d938..4ea56ffcf2db 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java
@@ -106,17 +106,7 @@ private void clean(Object target) {
}
private String toBindVariable(Map<Integer, String> bindValue) {
- final String[] temp = new String[bindValue.size()];
- for (Map.Entry<Integer, String> entry : bindValue.entrySet()) {
- Integer key = entry.getKey() - 1;
- if (temp.length < key) {
- continue;
- }
- temp[key] = entry.getValue();
- }
-
- return BindValueUtils.bindValueToString(temp, maxSqlBindValueLength);
-
+ return BindValueUtils.bindValueToString(bindValue, maxSqlBindValueLength);
}
@Override
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java
index a903ed82965a..765e628c2b82 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java
@@ -17,10 +17,10 @@
package com.navercorp.pinpoint.profiler.modifier.db.interceptor;
import org.junit.Assert;
-
import org.junit.Test;
-import com.navercorp.pinpoint.profiler.modifier.db.interceptor.BindValueUtils;
+import java.util.HashMap;
+import java.util.Map;
public class BindValueUtilsTest {
@@ -85,7 +85,7 @@ public void testBindValueToString_limit7() throws Exception {
@Test
public void testBindValueToString_null() throws Exception {
- String result = BindValueUtils.bindValueToString(null, 10);
+ String result = BindValueUtils.bindValueToString((String[])null, 10);
Assert.assertEquals("", result);
}
@@ -109,4 +109,56 @@ public void testBindValueToString_twoLargeString() throws Exception {
String result = BindValueUtils.bindValueToString(bindValue, 5);
Assert.assertEquals("12345...(6), ...(2)", result);
}
+
+ // #737 https://github.com/naver/pinpoint/issues/737
+ @Test
+ public void test_734_bug_regression() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(1, "1");
+ bindValue.put(2, "2");
+ // skip 3
+ bindValue.put(4, "4");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ Assert.assertEquals("1, 2, , 4", bindValueToString);
+ }
+
+ @Test
+ public void test_index_error_zero() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(0, "0");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ Assert.assertEquals("", bindValueToString);
+ }
+
+ @Test
+ public void test_index_error_negative() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(-2, "-2");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ Assert.assertEquals("", bindValueToString);
+ }
+
+ @Test
+ public void test_index_error_complex() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(-2, "-2");
+ bindValue.put(0, "0");
+ bindValue.put(1, "1");
+ bindValue.put(3, "3");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ Assert.assertEquals("1, , 3", bindValueToString);
+ }
+
+ @Test
+ public void test_NullElement() throws Exception {
+ String[] temp = {"1", null, "3"};
+ String bindValueToString = BindValueUtils.bindValueToString(temp, 100);
+ Assert.assertEquals("1, , 3", bindValueToString);
+ }
+
+
}
\ No newline at end of file
| train | train | "2015-07-16T08:36:50" | "2015-07-16T09:04:23Z" | emeroad | test |
pinpoint-apm/pinpoint/740_741 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/740 | pinpoint-apm/pinpoint/741 | [
"keyword_pr_to_issue"
] | 9d13573d6cf7192ab0575979fd932b86c5603fb0 | 49c200f68fa739be359b75db1839d5980f1494af | [] | [] | "2015-07-17T06:01:21Z" | [
"bug"
] | #737 backport. array index bug fix. | backport #737
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java"
] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java
index 815f613b2bb8..e9964f8b96a2 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java
@@ -18,14 +18,50 @@
import com.navercorp.pinpoint.bootstrap.util.StringUtils;
+import java.util.Map;
+
/**
* @author emeroad
*/
-public class BindValueUtils {
+public final class BindValueUtils {
private BindValueUtils() {
}
+ public static String bindValueToString(final Map<Integer, String> bindValueMap, int limit) {
+ if (bindValueMap == null) {
+ return "";
+ }
+ if (bindValueMap.isEmpty()) {
+ return "";
+ }
+ final int maxParameterIndex = getMaxParameterIndex(bindValueMap);
+ if (maxParameterIndex <= 0) {
+ return "";
+ }
+ final String[] temp = new String[maxParameterIndex];
+ for (Map.Entry<Integer, String> entry : bindValueMap.entrySet()) {
+ final int parameterIndex = entry.getKey() - 1;
+ if (parameterIndex < 0) {
+ // invalid index. PreparedStatement first parameterIndex is 1
+ continue;
+ }
+ if (temp.length <= parameterIndex) {
+ continue;
+ }
+ temp[parameterIndex] = entry.getValue();
+ }
+ return bindValueToString(temp, limit);
+ }
+
+ private static int getMaxParameterIndex(Map<Integer, String> bindValueMap) {
+ int maxIndex = 0;
+ for (Integer idx : bindValueMap.keySet()) {
+ maxIndex = Math.max(maxIndex, idx);
+ }
+ return maxIndex;
+ }
+
public static String bindValueToString(String[] bindValueArray, int limit) {
if (bindValueArray == null) {
return "";
@@ -39,7 +75,8 @@ public static String bindValueToString(String[] bindValueArray, int limit) {
appendLength(sb, length);
break;
}
- StringUtils.appendDrop(sb, bindValueArray[i], limit);
+ final String bindValue = StringUtils.defaultString(bindValueArray[i], "");
+ StringUtils.appendDrop(sb, bindValue, limit);
if (i < end) {
sb.append(", ");
}
@@ -57,4 +94,4 @@ private static void appendLength(StringBuilder sb, int length) {
public static String bindValueToString(String[] stringArray) {
return bindValueToString(stringArray, Integer.MAX_VALUE);
}
-}
+}
\ No newline at end of file
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java
index 0523f541eacf..abc56d7223fe 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java
@@ -106,17 +106,7 @@ private void clean(Object target) {
}
private String toBindVariable(Map<Integer, String> bindValue) {
- final String[] temp = new String[bindValue.size()];
- for (Map.Entry<Integer, String> entry : bindValue.entrySet()) {
- Integer key = entry.getKey() - 1;
- if (temp.length < key) {
- continue;
- }
- temp[key] = entry.getValue();
- }
-
- return BindValueUtils.bindValueToString(temp, maxSqlBindValueLength);
-
+ return BindValueUtils.bindValueToString(bindValue, maxSqlBindValueLength);
}
@Override
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java
index d228dc68da77..38bed9145b04 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java
@@ -22,6 +22,9 @@
import com.navercorp.pinpoint.profiler.modifier.db.interceptor.BindValueUtils;
+import java.util.HashMap;
+import java.util.Map;
+
public class BindValueUtilsTest {
@Test
@@ -85,7 +88,7 @@ public void testBindValueToString_limit7() throws Exception {
@Test
public void testBindValueToString_null() throws Exception {
- String result = BindValueUtils.bindValueToString(null, 10);
+ String result = BindValueUtils.bindValueToString((String[])null, 10);
Assert.assertEquals("", result);
}
@@ -109,4 +112,57 @@ public void testBindValueToString_twoLargeString() throws Exception {
String result = BindValueUtils.bindValueToString(bindValue, 5);
Assert.assertEquals("12345...(6), ...(2)", result);
}
+
+
+ // #737 https://github.com/naver/pinpoint/issues/737
+ @Test
+ public void test_734_bug_regression() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(1, "1");
+ bindValue.put(2, "2");
+ // skip 3
+ bindValue.put(4, "4");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ org.junit.Assert.assertEquals("1, 2, , 4", bindValueToString);
+ }
+
+ @Test
+ public void test_index_error_zero() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(0, "0");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ org.junit.Assert.assertEquals("", bindValueToString);
+ }
+
+ @Test
+ public void test_index_error_negative() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(-2, "-2");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ org.junit.Assert.assertEquals("", bindValueToString);
+ }
+
+ @Test
+ public void test_index_error_complex() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(-2, "-2");
+ bindValue.put(0, "0");
+ bindValue.put(1, "1");
+ bindValue.put(3, "3");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ org.junit.Assert.assertEquals("1, , 3", bindValueToString);
+ }
+
+ @Test
+ public void test_NullElement() throws Exception {
+ String[] temp = {"1", null, "3"};
+ String bindValueToString = BindValueUtils.bindValueToString(temp, 100);
+ org.junit.Assert.assertEquals("1, , 3", bindValueToString);
+ }
+
+
}
\ No newline at end of file
| train | train | "2015-07-15T07:19:30" | "2015-07-17T05:43:16Z" | emeroad | test |
pinpoint-apm/pinpoint/737_742 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/737 | pinpoint-apm/pinpoint/742 | [
"keyword_pr_to_issue"
] | 4e969e7c5ae0a6d66698b36c3d2bb239cd7c9d07 | 716d801fb966cb706426c4d12b821b8a690070c4 | [] | [] | "2015-07-17T06:19:49Z" | [
"bug"
] | PreparedStatementExecuteQueryInterceptor.toBindVariable() array index bug fix. | incorrect array index handling of SqlBindValue
#736
| [
"plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java",
"plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java"
] | [
"plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java",
"plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java"
] | diff --git a/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java b/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java
index 5cc7ed292c49..72ccd7954431 100644
--- a/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java
+++ b/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/bindvalue/BindValueUtils.java
@@ -18,14 +18,51 @@
import com.navercorp.pinpoint.bootstrap.util.StringUtils;
+import java.util.Map;
+
/**
+ * duplicate : com.navercorp.pinpoint.profiler.modifier.db.interceptor.BindValueUtils
* @author emeroad
*/
-public class BindValueUtils {
+public final class BindValueUtils {
private BindValueUtils() {
}
+ public static String bindValueToString(final Map<Integer, String> bindValueMap, int limit) {
+ if (bindValueMap == null) {
+ return "";
+ }
+ if (bindValueMap.isEmpty()) {
+ return "";
+ }
+ final int maxParameterIndex = getMaxParameterIndex(bindValueMap);
+ if (maxParameterIndex <= 0) {
+ return "";
+ }
+ final String[] temp = new String[maxParameterIndex];
+ for (Map.Entry<Integer, String> entry : bindValueMap.entrySet()) {
+ final int parameterIndex = entry.getKey() - 1;
+ if (parameterIndex < 0) {
+ // invalid index. PreparedStatement first parameterIndex is 1
+ continue;
+ }
+ if (temp.length <= parameterIndex) {
+ continue;
+ }
+ temp[parameterIndex] = entry.getValue();
+ }
+ return bindValueToString(temp, limit);
+ }
+
+ private static int getMaxParameterIndex(Map<Integer, String> bindValueMap) {
+ int maxIndex = 0;
+ for (Integer idx : bindValueMap.keySet()) {
+ maxIndex = Math.max(maxIndex, idx);
+ }
+ return maxIndex;
+ }
+
public static String bindValueToString(String[] bindValueArray, int limit) {
if (bindValueArray == null) {
return "";
@@ -39,7 +76,8 @@ public static String bindValueToString(String[] bindValueArray, int limit) {
appendLength(sb, length);
break;
}
- StringUtils.appendDrop(sb, bindValueArray[i], limit);
+ final String bindValue = StringUtils.defaultString(bindValueArray[i], "");
+ StringUtils.appendDrop(sb, bindValue, limit);
if (i < end) {
sb.append(", ");
}
diff --git a/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java b/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java
index 815734ba5931..ee7c6bcb7f1e 100644
--- a/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java
+++ b/plugins/jdbc-driver/src/main/java/com/navercorp/pinpoint/plugin/jdbc/common/interceptor/PreparedStatementExecuteQueryInterceptor.java
@@ -130,17 +130,7 @@ private void clean(Object target) {
}
private String toBindVariable(Map<Integer, String> bindValue) {
- final String[] temp = new String[bindValue.size()];
- for (Map.Entry<Integer, String> entry : bindValue.entrySet()) {
- Integer key = entry.getKey() - 1;
- if (temp.length <= key) {
- continue;
- }
- temp[key] = entry.getValue();
- }
-
- return BindValueUtils.bindValueToString(temp, maxSqlBindValueLength);
-
+ return BindValueUtils.bindValueToString(bindValue, maxSqlBindValueLength);
}
@Override
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java
index 815f613b2bb8..50c78810eef4 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtils.java
@@ -18,14 +18,50 @@
import com.navercorp.pinpoint.bootstrap.util.StringUtils;
+import java.util.Map;
+
/**
* @author emeroad
*/
-public class BindValueUtils {
+public final class BindValueUtils {
private BindValueUtils() {
}
+ public static String bindValueToString(final Map<Integer, String> bindValueMap, int limit) {
+ if (bindValueMap == null) {
+ return "";
+ }
+ if (bindValueMap.isEmpty()) {
+ return "";
+ }
+ final int maxParameterIndex = getMaxParameterIndex(bindValueMap);
+ if (maxParameterIndex <= 0) {
+ return "";
+ }
+ final String[] temp = new String[maxParameterIndex];
+ for (Map.Entry<Integer, String> entry : bindValueMap.entrySet()) {
+ final int parameterIndex = entry.getKey() - 1;
+ if (parameterIndex < 0) {
+ // invalid index. PreparedStatement first parameterIndex is 1
+ continue;
+ }
+ if (temp.length <= parameterIndex) {
+ continue;
+ }
+ temp[parameterIndex] = entry.getValue();
+ }
+ return bindValueToString(temp, limit);
+ }
+
+ private static int getMaxParameterIndex(Map<Integer, String> bindValueMap) {
+ int maxIndex = 0;
+ for (Integer idx : bindValueMap.keySet()) {
+ maxIndex = Math.max(maxIndex, idx);
+ }
+ return maxIndex;
+ }
+
public static String bindValueToString(String[] bindValueArray, int limit) {
if (bindValueArray == null) {
return "";
@@ -39,7 +75,8 @@ public static String bindValueToString(String[] bindValueArray, int limit) {
appendLength(sb, length);
break;
}
- StringUtils.appendDrop(sb, bindValueArray[i], limit);
+ final String bindValue = StringUtils.defaultString(bindValueArray[i], "");
+ StringUtils.appendDrop(sb, bindValue, limit);
if (i < end) {
sb.append(", ");
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java
index 0b1f9da3d938..4ea56ffcf2db 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java
@@ -106,17 +106,7 @@ private void clean(Object target) {
}
private String toBindVariable(Map<Integer, String> bindValue) {
- final String[] temp = new String[bindValue.size()];
- for (Map.Entry<Integer, String> entry : bindValue.entrySet()) {
- Integer key = entry.getKey() - 1;
- if (temp.length < key) {
- continue;
- }
- temp[key] = entry.getValue();
- }
-
- return BindValueUtils.bindValueToString(temp, maxSqlBindValueLength);
-
+ return BindValueUtils.bindValueToString(bindValue, maxSqlBindValueLength);
}
@Override
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java
index a903ed82965a..765e628c2b82 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/db/interceptor/BindValueUtilsTest.java
@@ -17,10 +17,10 @@
package com.navercorp.pinpoint.profiler.modifier.db.interceptor;
import org.junit.Assert;
-
import org.junit.Test;
-import com.navercorp.pinpoint.profiler.modifier.db.interceptor.BindValueUtils;
+import java.util.HashMap;
+import java.util.Map;
public class BindValueUtilsTest {
@@ -85,7 +85,7 @@ public void testBindValueToString_limit7() throws Exception {
@Test
public void testBindValueToString_null() throws Exception {
- String result = BindValueUtils.bindValueToString(null, 10);
+ String result = BindValueUtils.bindValueToString((String[])null, 10);
Assert.assertEquals("", result);
}
@@ -109,4 +109,56 @@ public void testBindValueToString_twoLargeString() throws Exception {
String result = BindValueUtils.bindValueToString(bindValue, 5);
Assert.assertEquals("12345...(6), ...(2)", result);
}
+
+ // #737 https://github.com/naver/pinpoint/issues/737
+ @Test
+ public void test_734_bug_regression() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(1, "1");
+ bindValue.put(2, "2");
+ // skip 3
+ bindValue.put(4, "4");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ Assert.assertEquals("1, 2, , 4", bindValueToString);
+ }
+
+ @Test
+ public void test_index_error_zero() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(0, "0");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ Assert.assertEquals("", bindValueToString);
+ }
+
+ @Test
+ public void test_index_error_negative() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(-2, "-2");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ Assert.assertEquals("", bindValueToString);
+ }
+
+ @Test
+ public void test_index_error_complex() throws Exception {
+ Map<Integer, String> bindValue = new HashMap<Integer, String>();
+ bindValue.put(-2, "-2");
+ bindValue.put(0, "0");
+ bindValue.put(1, "1");
+ bindValue.put(3, "3");
+
+ String bindValueToString = BindValueUtils.bindValueToString(bindValue, 100);
+ Assert.assertEquals("1, , 3", bindValueToString);
+ }
+
+ @Test
+ public void test_NullElement() throws Exception {
+ String[] temp = {"1", null, "3"};
+ String bindValueToString = BindValueUtils.bindValueToString(temp, 100);
+ Assert.assertEquals("1, , 3", bindValueToString);
+ }
+
+
}
\ No newline at end of file
| test | train | "2015-07-16T08:36:50" | "2015-07-16T09:04:23Z" | emeroad | test |
pinpoint-apm/pinpoint/745_746 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/745 | pinpoint-apm/pinpoint/746 | [
"keyword_pr_to_issue"
] | c0a58f198ac0ce817d8d4a1b28b24169c6f7aaa7 | 69701b460d474efeef2d4c17ecaf44c4334a122c | [] | [] | "2015-07-20T07:49:59Z" | [
"bug"
] | backport #732 FilterWizard bug fix. incorrect agent mapping | backport #732
| [
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Node.java",
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java",
"web/src/main/java/com/navercorp/pinpoint/web/controller/BusinessTransactionController.java",
"web/src/main/java/com/navercorp/pinpoint/web/view/LinkSerializer.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Node.java",
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java",
"web/src/main/java/com/navercorp/pinpoint/web/controller/BusinessTransactionController.java",
"web/src/main/java/com/navercorp/pinpoint/web/view/LinkSerializer.java"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceListTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/view/ServerInstanceListSerializerTest.java"
] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java
index aaa0dd4b4faa..8b81b41fb3d1 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java
@@ -384,6 +384,9 @@ private void appendServerInfo(Node node, LinkDataDuplexMap linkDataDuplexMap, Ag
} else if (nodeServiceType.isWas()) {
Set<AgentInfoBo> agentList = agentInfoService.selectAgent(node.getApplication().getName(), range);
if (agentList.isEmpty()) {
+ logger.warn("agentInfo not found. applicationName:{}", node.getApplication());
+ // avoid NPE
+ node.setServerInstanceList(new ServerInstanceList());
return;
}
logger.debug("add agentInfo. {}, {}", node.getApplication(), agentList);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Node.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Node.java
index 5d9fa0780bb1..f22b0b645668 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Node.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Node.java
@@ -43,8 +43,8 @@ public class Node {
public static final String NODE_DELIMITER = "^";
private final Application application;
-
- private ServerInstanceList serverInstanceList;
+ // avoid NPE
+ private ServerInstanceList serverInstanceList = new ServerInstanceList();
private NodeHistogram nodeHistogram;
@@ -74,8 +74,11 @@ public String getApplicationTextName() {
}
}
-
+ // TODO remove setter
public void setServerInstanceList(ServerInstanceList serverInstanceList) {
+ if (serverInstanceList == null) {
+ throw new NullPointerException("serverInstanceList must not be null");
+ }
this.serverInstanceList = serverInstanceList;
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerBuilder.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerBuilder.java
index 5ac29c4824df..bade9a8a2288 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerBuilder.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerBuilder.java
@@ -37,11 +37,17 @@ public class ServerBuilder {
private final AgentHistogramList agentHistogramList;
private final Set<AgentInfoBo> agentSet;
- private MatcherGroup matcherGroup = null;
+ private final MatcherGroup matcherGroup;
+
+ public ServerBuilder() {
+ // TODO FIX
+ this(null);
+ }
public ServerBuilder(MatcherGroup matcherGroup) {
this.agentHistogramList = new AgentHistogramList();
this.agentSet = new HashSet<AgentInfoBo>();
+ // TODO avoid null
this.matcherGroup = matcherGroup;
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java
index c90bcc6bdfd1..eb337295f007 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java
@@ -16,12 +16,9 @@
package com.navercorp.pinpoint.web.applicationmap;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
+import java.util.*;
+import com.navercorp.pinpoint.common.bo.AgentInfoBo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -58,6 +55,19 @@ public Map<String, List<ServerInstance>> getServerInstanceList() {
return serverInstanceList;
}
+ public List<String> getAgentIdList() {
+ final Collection<List<ServerInstance>> serverInstanceValueList = this.serverInstanceList.values();
+
+ final List<String> agentList = new ArrayList<String>();
+ for (List<ServerInstance> serverInstanceList : serverInstanceValueList) {
+ for (ServerInstance serverInstance : serverInstanceList) {
+ AgentInfoBo agentInfo = serverInstance.getAgentInfo();
+ agentList.add(agentInfo.getAgentId());
+ }
+ }
+ return agentList;
+ }
+
public int getInstanceCount() {
int count = 0;
for (List<ServerInstance> entry : serverInstanceList.values()) {
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/BusinessTransactionController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/BusinessTransactionController.java
index 015af8204c1a..bf7973ec164e 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/controller/BusinessTransactionController.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/BusinessTransactionController.java
@@ -178,6 +178,7 @@ public ModelAndView transactionInfo(@RequestParam("traceId") String traceIdParam
if (viewVersion == 2) {
+ // TODO remove hashformat
mv.setViewName("transactionInfoJsonHash");
} else {
mv.setViewName("transactionInfoJson");
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/LinkSerializer.java b/web/src/main/java/com/navercorp/pinpoint/web/view/LinkSerializer.java
index df10cb70ef6e..622e02ca656d 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/view/LinkSerializer.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/view/LinkSerializer.java
@@ -18,6 +18,7 @@
import com.navercorp.pinpoint.web.applicationmap.Link;
import com.navercorp.pinpoint.web.applicationmap.Node;
+import com.navercorp.pinpoint.web.applicationmap.ServerInstanceList;
import com.navercorp.pinpoint.web.applicationmap.histogram.Histogram;
import com.navercorp.pinpoint.web.applicationmap.rawdata.AgentHistogram;
import com.navercorp.pinpoint.web.applicationmap.rawdata.AgentHistogramList;
@@ -45,6 +46,9 @@ public void serialize(Link link, JsonGenerator jgen, SerializerProvider provider
jgen.writeStringField("from", link.getFrom().getNodeName()); // necessary for go.js
jgen.writeStringField("to", link.getTo().getNodeName()); // necessary for go.js
+ // for FilterWizard. from, to agent mapping data
+ writeAgentId("fromAgent", link.getFrom(), jgen);
+ writeAgentId("toAgent", link.getTo(), jgen);
writeSimpleNode("sourceInfo", link.getFrom(), jgen);
writeSimpleNode("targetInfo", link.getTo(), jgen);
@@ -79,6 +83,20 @@ public void serialize(Link link, JsonGenerator jgen, SerializerProvider provider
jgen.writeEndObject();
}
+ private void writeAgentId(String fieldName, Node node, JsonGenerator jgen) throws IOException {
+ if (node.getServiceType().isWas()) {
+ jgen.writeFieldName(fieldName);
+ jgen.writeStartArray();
+ ServerInstanceList serverInstanceList = node.getServerInstanceList();
+ if (serverInstanceList!= null) {
+ for (String agentId : serverInstanceList.getAgentIdList()) {
+ jgen.writeObject(agentId);
+ }
+ }
+ jgen.writeEndArray();
+ }
+ }
+
private void writeWasToWasTargetRpcList(Link link, JsonGenerator jgen) throws IOException {
// write additional information to be used for filtering failed WAS -> WAS call events.
jgen.writeFieldName("filterTargetRpcList");
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceListTest.java b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceListTest.java
new file mode 100644
index 000000000000..fad0981ab419
--- /dev/null
+++ b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceListTest.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2014 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.applicationmap;
+
+import com.navercorp.pinpoint.common.bo.AgentInfoBo;
+import com.navercorp.pinpoint.common.ServiceType;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.*;
+
+/**
+ * @author emeroad
+ */
+public class ServerInstanceListTest {
+
+ @Test
+ public void testGetAgentIdList() throws Exception {
+
+ AgentInfoBo agentInfoBo1 = createAgentInfo("agentId1", "testHost");
+ AgentInfoBo agentInfoBo2 = createAgentInfo("agentId2", "testHost");
+
+ Set<AgentInfoBo> agentInfoBoSet = new HashSet<AgentInfoBo>();
+ agentInfoBoSet.add(agentInfoBo1);
+ agentInfoBoSet.add(agentInfoBo2);
+
+ ServerBuilder builder = new ServerBuilder();
+ builder.addAgentInfo(agentInfoBoSet);
+ ServerInstanceList serverInstanceList = builder.build();
+ List<String> agentIdList = serverInstanceList.getAgentIdList();
+
+ Assert.assertEquals(agentIdList.size(), 2);
+ Assert.assertEquals(agentIdList.get(0), "agentId1");
+ Assert.assertEquals(agentIdList.get(1), "agentId2");
+ }
+
+ public static AgentInfoBo createAgentInfo(String agentId, String hostName) {
+ AgentInfoBo.Builder agentInfoBuilder = new AgentInfoBo.Builder();
+ agentInfoBuilder.agentId(agentId);
+
+ ServiceType serviceType = ServiceType.TEST_STAND_ALONE;
+ agentInfoBuilder.serviceType(serviceType);
+
+ agentInfoBuilder.hostName(hostName);
+
+ return agentInfoBuilder.build();
+ }
+}
\ No newline at end of file
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/view/ServerInstanceListSerializerTest.java b/web/src/test/java/com/navercorp/pinpoint/web/view/ServerInstanceListSerializerTest.java
index d4e630242d36..c8f23b77e289 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/view/ServerInstanceListSerializerTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/view/ServerInstanceListSerializerTest.java
@@ -16,18 +16,18 @@
package com.navercorp.pinpoint.web.view;
-import com.navercorp.pinpoint.common.ServiceType;
-import com.navercorp.pinpoint.common.bo.AgentInfoBo;
-import com.navercorp.pinpoint.web.applicationmap.ServerBuilder;
-import com.navercorp.pinpoint.web.applicationmap.ServerInstanceList;
+import java.util.HashSet;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.codehaus.jackson.map.ObjectWriter;
+import com.navercorp.pinpoint.web.applicationmap.ServerInstanceListTest;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.HashSet;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectWriter;
+import com.navercorp.pinpoint.common.bo.AgentInfoBo;
+import com.navercorp.pinpoint.web.applicationmap.ServerBuilder;
+import com.navercorp.pinpoint.web.applicationmap.ServerInstanceList;
/**
* @author emeroad
@@ -39,18 +39,15 @@ public class ServerInstanceListSerializerTest {
@Test
public void testSerialize() throws Exception {
- AgentInfoBo.Builder agentInfoBuilder = new AgentInfoBo.Builder();
- agentInfoBuilder.agentId("agentId");
- agentInfoBuilder.serviceType(ServiceType.TOMCAT);
- agentInfoBuilder.hostName("testcomputer");
+ AgentInfoBo agentInfoBo = ServerInstanceListTest.createAgentInfo("agentId1", "testHost");
- AgentInfoBo agentInfoBo = agentInfoBuilder.build();
+ HashSet<AgentInfoBo> agentInfoBoSet = new HashSet<AgentInfoBo>();
+ agentInfoBoSet.add(agentInfoBo);
- HashSet<AgentInfoBo> set = new HashSet<AgentInfoBo>();
- set.add(agentInfoBo);
ServerBuilder builder = new ServerBuilder(null);
- builder.addAgentInfo(set);
+ builder.addAgentInfo(agentInfoBoSet);
+
ServerInstanceList serverInstanceList = builder.build();
ObjectWriter objectWriter = mapper.writerWithDefaultPrettyPrinter();
String json = objectWriter.writeValueAsString(serverInstanceList);
| test | train | "2015-07-17T08:01:24" | "2015-07-17T10:38:28Z" | emeroad | test |
pinpoint-apm/pinpoint/914_916 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/914 | pinpoint-apm/pinpoint/916 | [
"keyword_pr_to_issue"
] | 07b1cb664ed44b63014501a27828c913e95dff51 | f7db12864beff438b6d5ce36806537fc9600e184 | [] | [] | "2015-09-03T07:59:18Z" | [
"bug"
] | Handle cases where collected cpu load is NaN | There was a case where calling `OperatingSystemMXBean.getSystemCpuLoad()` returned Double.NaN (the agent was ran on a virtual machine).
The data collected was as follows:
```
TAgentStatBatch(agentId:test-agent, startTimestamp:1441085794300, agentStats:[
TAgentStat(timestamp:1441087205292, cpuLoad:TCpuLoad(systemCpuLoad:0.026276276276276277, jvmCpuLoad:5.983020928131048E-4), gc:TJvmGc(...)),
TAgentStat(timestamp:1441087802597, cpuLoad:TCpuLoad(systemCpuLoad:0.13733025877530106, jvmCpuLoad:9.909711377187762E-6), gc:TJvmGc(...)),
TAgentStat(timestamp:1441087802597, cpuLoad:TCpuLoad(systemCpuLoad:NaN, jvmCpuLoad:0.14527027027027026), gc:TJvmGc(...)),
TAgentStat(timestamp:1441087802597, cpuLoad:TCpuLoad(systemCpuLoad:NaN, jvmCpuLoad:0.1275), gc:TJvmGc(...)),
TAgentStat(timestamp:1441087802597, cpuLoad:TCpuLoad(systemCpuLoad:NaNjvmCpuLoad:0.125), gc:TJvmGc(...)),
TAgentStat(timestamp:1441087802597, cpuLoad:TCpuLoad(systemCpuLoad:0.0jvmCpuLoad:0.125), gc:TJvmGc(...))
])
```
Need a NaN check - use `Double.isNaN()`.
(equals check does not work on NaNs as `Double.NaN != Double.NaN`)
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadCollector.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadCollector.java"
] | [] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadCollector.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadCollector.java
index 3b47af433e2a..547864abe179 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadCollector.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadCollector.java
@@ -61,6 +61,6 @@ public TCpuLoad collectCpuLoad() {
}
private boolean notCollected(double cpuLoad) {
- return cpuLoad < 0;
+ return cpuLoad < 0 || Double.isNaN(cpuLoad);
}
}
| null | val | train | "2015-09-03T09:51:49" | "2015-09-03T07:16:56Z" | Xylus | test |
pinpoint-apm/pinpoint/956_957 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/956 | pinpoint-apm/pinpoint/957 | [
"keyword_pr_to_issue"
] | b2d4902ebb93a99d96fb8397edcb7dd97f9d0057 | e8f058d895a234dbf2a5bf095716d800a2b10482 | [] | [] | "2015-09-09T10:33:54Z" | [
"enhancement"
] | Allow main class detection for valid war/zip java executables | Valid java executables may be packaged as war/zip files.
Currently however, main class detection only works for valid executable jars.
Extend main class detection to valid executable war/zip files (such as Spring Boot application packaged as an executable war).
| [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java"
] | [] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java
index 3343a6486066..ac9c8b4a3410 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.bootstrap.resolver.condition;
+import java.io.IOException;
import java.util.jar.JarFile;
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
@@ -88,21 +89,28 @@ private String getMainClassName(SimpleProperty property) {
if (javaCommand.isEmpty()) {
logger.warn("Error retrieving main class from [{}]", property.getClass().getName());
return NOT_FOUND;
- } else if (javaCommand.endsWith(".jar")) {
- return extractMainClassFromJar(javaCommand);
} else {
- return javaCommand;
+ try {
+ JarFile executableArchive = new JarFile(javaCommand);
+ return extractMainClassFromArchive(executableArchive);
+ } catch (IOException e) {
+ // If it's not a valid java archive, VM shouldn't start in the first place.
+ // Thus this would simply be a main class
+ return javaCommand;
+ } catch (Exception e) {
+ // fail-safe, application shouldn't not start because of this
+ logger.warn("Error retrieving main class from java command : [{}]", javaCommand, e);
+ return NOT_FOUND;
+ }
}
}
- private String extractMainClassFromJar(String jarName) {
- try {
- JarFile bootstrapJar = new JarFile(jarName);
- return bootstrapJar.getManifest().getMainAttributes().getValue(MANIFEST_MAIN_CLASS_KEY);
- } catch (Throwable t) {
- logger.warn("Error retrieveing main class from jar file : [{}]", jarName, t);
+ private String extractMainClassFromArchive(JarFile bootstrapJar) throws IOException {
+ String mainClassFromManifest = bootstrapJar.getManifest().getMainAttributes().getValue(MANIFEST_MAIN_CLASS_KEY);
+ if (mainClassFromManifest == null) {
return NOT_FOUND;
}
+ return mainClassFromManifest;
}
}
| null | train | train | "2015-09-09T11:52:23" | "2015-09-09T10:28:16Z" | Xylus | test |
pinpoint-apm/pinpoint/968_973 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/968 | pinpoint-apm/pinpoint/973 | [
"keyword_pr_to_issue"
] | 1110f7402ca2a15cc23042b51ea81afa128b53e6 | 2722bfda27b987c4d6728babc70c3c28b066334f | [] | [] | "2015-09-17T09:31:59Z" | [
"bug"
] | Server map fails to link nodes on HTTP calls made to non-80 ports | Related to Google Groups [issue](https://groups.google.com/forum/#!topic/pinpoint_user/5zxtnFo1y3Q).
The server map currently fails to recognize the target node when a node makes a http call with the port number specified.
![image](https://cloud.githubusercontent.com/assets/10057488/9922689/82890674-5d26-11e5-943e-39050c3a9a9b.png)
The above image should correctly render like the image below.
![image](https://cloud.githubusercontent.com/assets/10057488/9922703/a250f9ee-5d26-11e5-879f-6df676f6f332.png)
Needs a fix.
| [
"plugins/httpclient3/src/main/java/com/navercorp/pinpoint/plugin/httpclient3/interceptor/HttpMethodBaseExecuteMethodInterceptor.java",
"plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/DefaultClientExchangeHandlerImplStartMethodInterceptor.java",
"plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/HttpRequestExecutorExecuteMethodInterceptor.java",
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java",
"plugins/ning-asynchttpclient/src/main/java/com/navercorp/pinpoint/plugin/ning/asynchttpclient/interceptor/ExecuteRequestInterceptor.java"
] | [
"plugins/httpclient3/src/main/java/com/navercorp/pinpoint/plugin/httpclient3/interceptor/HttpMethodBaseExecuteMethodInterceptor.java",
"plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/DefaultClientExchangeHandlerImplStartMethodInterceptor.java",
"plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/HttpRequestExecutorExecuteMethodInterceptor.java",
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java",
"plugins/ning-asynchttpclient/src/main/java/com/navercorp/pinpoint/plugin/ning/asynchttpclient/interceptor/ExecuteRequestInterceptor.java"
] | [] | diff --git a/plugins/httpclient3/src/main/java/com/navercorp/pinpoint/plugin/httpclient3/interceptor/HttpMethodBaseExecuteMethodInterceptor.java b/plugins/httpclient3/src/main/java/com/navercorp/pinpoint/plugin/httpclient3/interceptor/HttpMethodBaseExecuteMethodInterceptor.java
index f6ce373a3269..5e784a71a6d8 100644
--- a/plugins/httpclient3/src/main/java/com/navercorp/pinpoint/plugin/httpclient3/interceptor/HttpMethodBaseExecuteMethodInterceptor.java
+++ b/plugins/httpclient3/src/main/java/com/navercorp/pinpoint/plugin/httpclient3/interceptor/HttpMethodBaseExecuteMethodInterceptor.java
@@ -164,7 +164,8 @@ public Object createAttachment() {
private String getHost(HttpMethod httpMethod) {
try {
- return httpMethod.getURI().getHost();
+ URI url = httpMethod.getURI();
+ return getEndpoint(url.getHost(), url.getPort());
} catch (URIException e) {
logger.error("Fail get URI", e);
}
diff --git a/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/DefaultClientExchangeHandlerImplStartMethodInterceptor.java b/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/DefaultClientExchangeHandlerImplStartMethodInterceptor.java
index 5857e692d930..6ad0e980c81f 100644
--- a/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/DefaultClientExchangeHandlerImplStartMethodInterceptor.java
+++ b/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/DefaultClientExchangeHandlerImplStartMethodInterceptor.java
@@ -125,7 +125,13 @@ public void before(Object target, Object[] args) {
httpRequest.setHeader(Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(traceContext.getServerTypeCode()));
final NameIntValuePair<String> host = getHost(target);
if (host != null) {
- httpRequest.setHeader(Header.HTTP_HOST.toString(), host.getName());
+ final StringBuilder hostStringBuilder = new StringBuilder(host.getName());
+ if (host.getValue() > 0) {
+ hostStringBuilder.append(":").append(host.getValue());
+ }
+ final String hostString = hostStringBuilder.toString();
+ logger.debug("Get host {}", hostString);
+ httpRequest.setHeader(Header.HTTP_HOST.toString(), hostString);
}
}
diff --git a/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/HttpRequestExecutorExecuteMethodInterceptor.java b/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/HttpRequestExecutorExecuteMethodInterceptor.java
index 2ee9c6704b30..036aeca16f8b 100644
--- a/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/HttpRequestExecutorExecuteMethodInterceptor.java
+++ b/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/HttpRequestExecutorExecuteMethodInterceptor.java
@@ -148,8 +148,13 @@ public void before(Object target, Object[] args) {
httpRequest.setHeader(Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(traceContext.getServerTypeCode()));
final NameIntValuePair<String> host = getHost();
if (host != null) {
- logger.debug("Get host {}", host.getName());
- httpRequest.setHeader(Header.HTTP_HOST.toString(), host.getName());
+ final StringBuilder hostStringBuilder = new StringBuilder(host.getName());
+ if (host.getValue() > 0) {
+ hostStringBuilder.append(":").append(host.getValue());
+ }
+ final String hostString = hostStringBuilder.toString();
+ logger.debug("Get host {}", hostString);
+ httpRequest.setHeader(Header.HTTP_HOST.toString(), hostString);
}
}
diff --git a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java
index 74ddac604a87..4ac8870852b4 100644
--- a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java
+++ b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java
@@ -97,6 +97,8 @@ public void before(Object target, Object[] args) {
final URL url = request.getURL();
final String host = url.getHost();
final int port = url.getPort();
+ // TODO How to represent protocol?
+ String endpoint = getEndpoint(host, port);
request.setRequestProperty(Header.HTTP_TRACE_ID.toString(), nextId.getTransactionId());
request.setRequestProperty(Header.HTTP_SPAN_ID.toString(), String.valueOf(nextId.getSpanId()));
@@ -106,13 +108,10 @@ public void before(Object target, Object[] args) {
request.setRequestProperty(Header.HTTP_PARENT_APPLICATION_NAME.toString(), traceContext.getApplicationName());
request.setRequestProperty(Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(traceContext.getServerTypeCode()));
if(host != null) {
- request.setRequestProperty(Header.HTTP_HOST.toString(), host);
+ request.setRequestProperty(Header.HTTP_HOST.toString(), endpoint);
}
recorder.recordServiceType(SERVICE_TYPE);
-
- // TODO How to represent protocol?
- String endpoint = getEndpoint(host, port);
// Don't record end point because it's same with destination id.
recorder.recordDestinationId(endpoint);
diff --git a/plugins/ning-asynchttpclient/src/main/java/com/navercorp/pinpoint/plugin/ning/asynchttpclient/interceptor/ExecuteRequestInterceptor.java b/plugins/ning-asynchttpclient/src/main/java/com/navercorp/pinpoint/plugin/ning/asynchttpclient/interceptor/ExecuteRequestInterceptor.java
index f222ad9406bb..0b8911bf348b 100644
--- a/plugins/ning-asynchttpclient/src/main/java/com/navercorp/pinpoint/plugin/ning/asynchttpclient/interceptor/ExecuteRequestInterceptor.java
+++ b/plugins/ning-asynchttpclient/src/main/java/com/navercorp/pinpoint/plugin/ning/asynchttpclient/interceptor/ExecuteRequestInterceptor.java
@@ -122,9 +122,9 @@ public void before(Object target, Object[] args) {
putHeader(httpRequestHeaders, Header.HTTP_FLAGS.toString(), String.valueOf(nextId.getFlags()));
putHeader(httpRequestHeaders, Header.HTTP_PARENT_APPLICATION_NAME.toString(), traceContext.getApplicationName());
putHeader(httpRequestHeaders, Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(traceContext.getServerTypeCode()));
- final String host = httpRequest.getURI().getHost();
- if(host != null) {
- putHeader(httpRequestHeaders, Header.HTTP_HOST.toString(), host);
+ final String hostString = getEndpoint(httpRequest.getURI().getHost(), httpRequest.getURI().getPort());
+ if(hostString != null) {
+ putHeader(httpRequestHeaders, Header.HTTP_HOST.toString(), hostString);
}
}
}
| null | train | train | "2015-09-17T10:57:43" | "2015-09-17T01:27:30Z" | Xylus | test |
pinpoint-apm/pinpoint/1020_1022 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1020 | pinpoint-apm/pinpoint/1022 | [
"keyword_pr_to_issue"
] | ed8a9d50c886ad888d2de28a0f8ef3b627099ac8 | 04821d1255bc708934126446d394b0a8ea9a4eed | [] | [] | "2015-10-02T05:30:23Z" | [
"enhancement"
] | Avoid serializing detailed agent information when rendering server map | The server map does not use any of the detailed agent information such as those shown in the Inspector view. Removing them would abolish unnecessary overhead (although minute) as these information can be quite large.
Note that this has already been applied in 1.5.0 through #926
| [
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstance.java",
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstance.java",
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstance.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstance.java
index 4f105fc19ee3..d1e41ce25d4d 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstance.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstance.java
@@ -37,9 +37,6 @@ public class ServerInstance {
private final ServerType serverType;
- private final AgentInfoBo agentInfo;
-
-
// it is better for something else to inject this.
// it's difficult to do that since it is new'ed within logic
private static final MatcherGroup MATCHER_GROUP = new MatcherGroup();
@@ -53,7 +50,6 @@ public ServerInstance(AgentInfoBo agentInfo) {
this.hostName = agentInfo.getHostName();
this.name = agentInfo.getAgentId();
this.serviceType = agentInfo.getServiceType();
- this.agentInfo = agentInfo;
this.serverType = ServerType.Physical;
this.match = MATCHER_GROUP.match(hostName);
}
@@ -71,7 +67,6 @@ public ServerInstance(String hostName, String physicalName, ServiceType serviceT
this.hostName = hostName;
this.name = physicalName;
this.serviceType = serviceType;
- this.agentInfo = null;
this.serverType = ServerType.Logical;
this.match = MATCHER_GROUP.match(hostName);
}
@@ -96,11 +91,6 @@ public ServerType getServerType() {
return serverType;
}
- @JsonProperty("agentInfo")
- public AgentInfoBo getAgentInfo() {
- return agentInfo;
- }
-
@JsonProperty("linkName")
public String getLinkName() {
return match.getLinkName();
@@ -120,7 +110,6 @@ public boolean hasInspector() {
}
}
-
@Override
public boolean equals(Object o) {
if (this == o) return true;
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java
index eb337295f007..2f816f60063a 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java
@@ -18,7 +18,6 @@
import java.util.*;
-import com.navercorp.pinpoint.common.bo.AgentInfoBo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -61,8 +60,7 @@ public List<String> getAgentIdList() {
final List<String> agentList = new ArrayList<String>();
for (List<ServerInstance> serverInstanceList : serverInstanceValueList) {
for (ServerInstance serverInstance : serverInstanceList) {
- AgentInfoBo agentInfo = serverInstance.getAgentInfo();
- agentList.add(agentInfo.getAgentId());
+ agentList.add(serverInstance.getName());
}
}
return agentList;
| null | val | train | "2015-10-01T09:19:56" | "2015-10-02T04:54:01Z" | Xylus | test |
pinpoint-apm/pinpoint/1103_1131 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1103 | pinpoint-apm/pinpoint/1131 | [
"keyword_pr_to_issue"
] | 5b36315f429390c478ae04101effbb7dd4793d07 | 11daa83173a4fba92e1d60d932c25d19c8793710 | [
"Generate id differently (currently divides the `Long` space into 4)\nBetter to leave some space for future use.\n"
] | [] | "2015-10-29T08:59:27Z" | [
"enhancement"
] | Separate id used for internal trace map from transaction id used for context propagation | A single id was used for both `transactionId` for context propagation, and trace map cache (as key).
This approach however does not work well for cases when a transaction is continued. For a continued transaction, using the `transactionId` as the map key may conflict with `transactionId` issued for new transactions.
Separating id used for trace map key (at least for continued transactions) would fix the problem.
This should be done using the least amount of atomic counters that covers id generation for 4 cases:
1. New Sampled Trace
2. New Unsampled Trace
3. Continued Sampled Trace
4. Continued Unsampled Trace
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTransactionCounter.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/IdGenerator.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTransactionCounter.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/IdGenerator.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultTransactionCounterTest.java"
] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTransactionCounter.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTransactionCounter.java
index 6a68c5b172a6..004ae45d6580 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTransactionCounter.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTransactionCounter.java
@@ -29,7 +29,7 @@ public DefaultTransactionCounter(IdGenerator idGenerator) {
}
this.idGenerator = idGenerator;
}
-
+
@Override
public long getTransactionCount(SamplingType samplingType) {
// overflow improbable
@@ -37,11 +37,11 @@ public long getTransactionCount(SamplingType samplingType) {
case SAMPLED_NEW:
return idGenerator.currentTransactionId() - IdGenerator.INITIAL_TRANSACTION_ID;
case SAMPLED_CONTINUATION:
- return Math.abs(idGenerator.currentContinuedTransactionId() - IdGenerator.INITIAL_CONTINUED_TRANSACTION_ID);
+ return Math.abs(idGenerator.currentContinuedTransactionId() - IdGenerator.INITIAL_CONTINUED_TRANSACTION_ID) / IdGenerator.DECREMENT_CYCLE;
case UNSAMPLED_NEW:
- return Math.abs(idGenerator.currentDisabledId() - IdGenerator.INITIAL_DISABLED_ID);
+ return Math.abs(idGenerator.currentDisabledId() - IdGenerator.INITIAL_DISABLED_ID) / IdGenerator.DECREMENT_CYCLE;
case UNSAMPLED_CONTINUATION:
- return idGenerator.currentContinuedDisabledId() - IdGenerator.INITIAL_CONTINUED_DISABLED_ID;
+ return Math.abs(idGenerator.currentContinuedDisabledId() - IdGenerator.INITIAL_CONTINUED_DISABLED_ID) / IdGenerator.DECREMENT_CYCLE;
default:
return 0L;
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/IdGenerator.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/IdGenerator.java
index 4daf8c250021..6fa0d2979082 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/IdGenerator.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/IdGenerator.java
@@ -24,14 +24,22 @@
*/
public class IdGenerator {
- // Positive value for sampled traces
- public static final long INITIAL_TRANSACTION_ID = 1L;
- public static final long INITIAL_CONTINUED_TRANSACTION_ID = Long.MAX_VALUE;
- // Negative value for unsampled traces
- public static final long INITIAL_DISABLED_ID = -1L;
- public static final long INITIAL_CONTINUED_DISABLED_ID = Long.MIN_VALUE;
+ // TODO might be a good idea to refactor these into SamplingType
+ // Reserved negative space (0 ~ -1000)
public static final long UNTRACKED_ID = 0L;
+ public static final long RESERVED_MAX = 0L;
+ public static final long RESERVED_MIN = -1000;
+
+ // Positive value for sampled new traces
+ public static final long INITIAL_TRANSACTION_ID = 1L;
+ // Negative value for sampled continuations, and unsampled new traces/continuations
+ public static final long INITIAL_CONTINUED_TRANSACTION_ID = RESERVED_MIN - 1; // -1001
+ public static final long INITIAL_DISABLED_ID = RESERVED_MIN - 2; // -1002
+ public static final long INITIAL_CONTINUED_DISABLED_ID = RESERVED_MIN - 3; // -1003
+
+ public static final int DECREMENT_CYCLE = 3;
+ public static final int NEGATIVE_DECREMENT_CYCLE = DECREMENT_CYCLE * -1;
// Unique id for tracing a internal stacktrace and calculating a slow time of activethreadcount
// moved here in order to make codes simpler for now
@@ -49,15 +57,15 @@ public long nextTransactionId() {
}
public long nextContinuedTransactionId() {
- return this.continuedTransactionId.getAndDecrement();
+ return this.continuedTransactionId.getAndAdd(NEGATIVE_DECREMENT_CYCLE);
}
public long nextDisabledId() {
- return this.disabledId.getAndDecrement();
+ return this.disabledId.getAndAdd(NEGATIVE_DECREMENT_CYCLE);
}
public long nextContinuedDisabledId() {
- return this.continuedDisabledId.getAndIncrement();
+ return this.continuedDisabledId.getAndAdd(NEGATIVE_DECREMENT_CYCLE);
}
public long currentTransactionId() {
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultTransactionCounterTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultTransactionCounterTest.java
new file mode 100644
index 000000000000..ddb7832e37d1
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultTransactionCounterTest.java
@@ -0,0 +1,210 @@
+/*
+ * Copyright 2015 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.context;
+
+import static org.junit.Assert.*;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.navercorp.pinpoint.profiler.context.TransactionCounter.SamplingType;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class DefaultTransactionCounterTest {
+
+ private IdGenerator idGenerator;
+ private TransactionCounter transactionCounter;
+
+ @Before
+ public void setUp() throws Exception {
+ this.idGenerator = new IdGenerator();
+ this.transactionCounter = new DefaultTransactionCounter(this.idGenerator);
+ }
+
+ @Test
+ public void testNoTransaction_SAMPLED_NEW() {
+ // Given
+ final long expectedTransactionCount = 0L;
+ // When
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.SAMPLED_NEW);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testNoTransaction_SAMPLED_CONTINUATION() {
+ // Given
+ final long expectedTransactionCount = 0L;
+ // When
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.SAMPLED_CONTINUATION);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testNoTransaction_UNSAMPLED_NEW() {
+ // Given
+ final long expectedTransactionCount = 0L;
+ // When
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.UNSAMPLED_NEW);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testNoTransaction_UNSAMPLED_CONTINUATION() {
+ // Given
+ final long expectedTransactionCount = 0L;
+ // When
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.UNSAMPLED_CONTINUATION);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testSingleTransaction_SAMPLED_NEW() {
+ // Given
+ final long expectedTransactionCount = 1L;
+ // When
+ this.idGenerator.nextTransactionId();
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.SAMPLED_NEW);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testSingleTransaction_SAMPLED_CONTINUATION() {
+ // Given
+ final long expectedTransactionCount = 1L;
+ // When
+ this.idGenerator.nextContinuedTransactionId();
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.SAMPLED_CONTINUATION);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testSingleTransaction_UNSAMPLED_NEW() {
+ // Given
+ final long expectedTransactionCount = 1L;
+ // When
+ this.idGenerator.nextDisabledId();
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.UNSAMPLED_NEW);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testSingleTransaction_UNSAMPLED_CONTINUATION() {
+ // Given
+ final long expectedTransactionCount = 1L;
+ // When
+ this.idGenerator.nextContinuedDisabledId();
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.UNSAMPLED_CONTINUATION);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testMultipleTransaction_SAMPLED_NEW() {
+ // Given
+ final long expectedTransactionCount = 99L;
+ // When
+ for (int i = 0; i < expectedTransactionCount; ++i) {
+ this.idGenerator.nextTransactionId();
+ }
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.SAMPLED_NEW);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testMultipleTransaction_SAMPLED_CONTINUATION() {
+ // Given
+ final long expectedTransactionCount = 99L;
+ // When
+ for (int i = 0; i < expectedTransactionCount; ++i) {
+ this.idGenerator.nextContinuedTransactionId();
+ }
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.SAMPLED_CONTINUATION);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testMultipleTransaction_UNSAMPLED_NEW() {
+ // Given
+ final long expectedTransactionCount = 99L;
+ // When
+ for (int i = 0; i < expectedTransactionCount; ++i) {
+ this.idGenerator.nextDisabledId();
+ }
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.UNSAMPLED_NEW);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testMultipleTransaction_UNSAMPLED_CONTINUATION() {
+ // Given
+ final long expectedTransactionCount = 99L;
+ // When
+ for (int i = 0; i < expectedTransactionCount; ++i) {
+ this.idGenerator.nextContinuedDisabledId();
+ }
+ final long actualCount = this.transactionCounter.getTransactionCount(SamplingType.UNSAMPLED_CONTINUATION);
+ // Then
+ assertEquals(expectedTransactionCount, actualCount);
+ }
+
+ @Test
+ public void testTotalTransaction() {
+ // Given
+ final long expectedSampledNewCount = 19L;
+ final long expectedSampledContinuationCount = 29L;
+ final long expectedUnsampledNewCount = 0L;
+ final long expectedUnsampledContinuationCount = 9L;
+ final long expectedTotalCount = expectedSampledNewCount + expectedSampledContinuationCount + expectedUnsampledNewCount + expectedUnsampledContinuationCount;
+ // When
+ for (int i = 0; i < expectedSampledNewCount; ++i) {
+ this.idGenerator.nextTransactionId();
+ }
+ for (int i = 0; i < expectedSampledContinuationCount; ++i) {
+ this.idGenerator.nextContinuedTransactionId();
+ }
+ for (int i = 0; i < expectedUnsampledNewCount; ++i) {
+ this.idGenerator.nextDisabledId();
+ }
+ for (int i = 0; i < expectedUnsampledContinuationCount; ++i) {
+ this.idGenerator.nextContinuedDisabledId();
+ }
+ final long actualSampledNewCount = this.transactionCounter.getTransactionCount(SamplingType.SAMPLED_NEW);
+ final long actualSampledContinuationCount = this.transactionCounter.getTransactionCount(SamplingType.SAMPLED_CONTINUATION);
+ final long actualUnsampledNewCount = this.transactionCounter.getTransactionCount(SamplingType.UNSAMPLED_NEW);
+ final long actualUnsampledContinuationCount = this.transactionCounter.getTransactionCount(SamplingType.UNSAMPLED_CONTINUATION);
+ final long actualTotalCount = this.transactionCounter.getTotalTransactionCount();
+ // Then
+ assertEquals(expectedSampledNewCount, actualSampledNewCount);
+ assertEquals(expectedSampledContinuationCount, actualSampledContinuationCount);
+ assertEquals(expectedUnsampledNewCount, actualUnsampledNewCount);
+ assertEquals(expectedUnsampledContinuationCount, actualUnsampledContinuationCount);
+ assertEquals(expectedTotalCount, actualTotalCount);
+ }
+
+}
| train | train | "2015-10-29T06:42:19" | "2015-10-23T01:40:04Z" | Xylus | test |
pinpoint-apm/pinpoint/1069_1133 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1069 | pinpoint-apm/pinpoint/1133 | [
"keyword_pr_to_issue"
] | 06e004d78e2691d7279857f1dcc9dba4ac04c515 | cd659ee85b0513fe3f349fc73bc124a80338859d | [
"Currently tps is calculated by factoring in the following situations:\n1. When a new trace is created and should be sampled.\n2. When a new trace is created and should not be sampled.\n3. When a trace is continued with sampling set false.\n\nNeed to consider 1 more situation:\n1. When a trace is continued, and sampling is set true.\n",
"Should continue after #1103 \n",
"Changing spec to collect the number of transaction over a certain period of time.\nTps calculation will be done when querying using this data.\n",
"Reopening to remove `version` field.\n",
"Reopening for UI\n"
] | [] | "2015-10-29T09:49:56Z" | [
"enhancement"
] | Add Transaction metric collection | Add per-agent transaction count metric collection support for all 4 types of transactions:
1. Sampled New
2. Unsampled New
3. Sampled Continuation
4. Unsampled Continuation
| [
"collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentStatDao.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseTables.java",
"thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/TTransaction.java",
"thrift/src/main/thrift/Pinpoint.thrift",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/AgentStatMapper.java",
"web/src/main/java/com/navercorp/pinpoint/web/vo/AgentStat.java"
] | [
"collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentStatDao.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseTables.java",
"thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/TTransaction.java",
"thrift/src/main/thrift/Pinpoint.thrift",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/AgentStatMapper.java",
"web/src/main/java/com/navercorp/pinpoint/web/vo/AgentStat.java"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/mapper/AgentStatMapperTest.java"
] | diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentStatDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentStatDao.java
index 3ca792249ffa..2b46f592c385 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentStatDao.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentStatDao.java
@@ -90,7 +90,6 @@ private Put createPut(TAgentStat agentStat) {
// Transaction
if (agentStat.isSetTransaction()) {
TTransaction transaction = agentStat.getTransaction();
- put.addColumn(AGENT_STAT_CF_STATISTICS, AGENT_STAT_COL_TRANSACTION_VERSION, Bytes.toBytes(transaction.getVersion()));
put.addColumn(AGENT_STAT_CF_STATISTICS, AGENT_STAT_COL_TRANSACTION_SAMPLED_NEW, Bytes.toBytes(transaction.getSampledNewCount()));
put.addColumn(AGENT_STAT_CF_STATISTICS, AGENT_STAT_COL_TRANSACTION_SAMPLED_CONTINUATION, Bytes.toBytes(transaction.getSampledContinuationCount()));
put.addColumn(AGENT_STAT_CF_STATISTICS, AGENT_STAT_COL_TRANSACTION_UNSAMPLED_NEW, Bytes.toBytes(transaction.getUnsampledNewCount()));
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseTables.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseTables.java
index 0335e86c269a..7e69d3951889 100644
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseTables.java
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseTables.java
@@ -50,7 +50,6 @@ public final class HBaseTables {
public static final byte[] AGENT_STAT_COL_NON_HEAP_MAX = Bytes.toBytes("nHpM"); // qualifier for non-heap max
public static final byte[] AGENT_STAT_COL_JVM_CPU = Bytes.toBytes("jvmCpu"); // qualifier for JVM CPU usage
public static final byte[] AGENT_STAT_COL_SYS_CPU = Bytes.toBytes("sysCpu"); // qualifier for system CPU usage
- public static final byte[] AGENT_STAT_COL_TRANSACTION_VERSION = Bytes.toBytes("tV"); // qualifier for transaction version
public static final byte[] AGENT_STAT_COL_TRANSACTION_SAMPLED_NEW = Bytes.toBytes("tSN"); // qualifier for sampled new count
public static final byte[] AGENT_STAT_COL_TRANSACTION_SAMPLED_CONTINUATION = Bytes.toBytes("tSC"); // qualifier for sampled continuation count
public static final byte[] AGENT_STAT_COL_TRANSACTION_UNSAMPLED_NEW = Bytes.toBytes("tUnSN"); // qualifier for unsampled new count
diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/TTransaction.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/TTransaction.java
index 0955d8ee8a37..0ca3744ebe32 100644
--- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/TTransaction.java
+++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/TTransaction.java
@@ -34,11 +34,10 @@
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
-@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2015-10-27")
+@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2015-10-29")
public class TTransaction implements org.apache.thrift.TBase<TTransaction, TTransaction._Fields>, java.io.Serializable, Cloneable, Comparable<TTransaction> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TTransaction");
- private static final org.apache.thrift.protocol.TField VERSION_FIELD_DESC = new org.apache.thrift.protocol.TField("version", org.apache.thrift.protocol.TType.I16, (short)1);
private static final org.apache.thrift.protocol.TField SAMPLED_NEW_COUNT_FIELD_DESC = new org.apache.thrift.protocol.TField("sampledNewCount", org.apache.thrift.protocol.TType.I64, (short)2);
private static final org.apache.thrift.protocol.TField SAMPLED_CONTINUATION_COUNT_FIELD_DESC = new org.apache.thrift.protocol.TField("sampledContinuationCount", org.apache.thrift.protocol.TType.I64, (short)3);
private static final org.apache.thrift.protocol.TField UNSAMPLED_NEW_COUNT_FIELD_DESC = new org.apache.thrift.protocol.TField("unsampledNewCount", org.apache.thrift.protocol.TType.I64, (short)4);
@@ -50,7 +49,6 @@ public class TTransaction implements org.apache.thrift.TBase<TTransaction, TTran
schemes.put(TupleScheme.class, new TTransactionTupleSchemeFactory());
}
- private short version; // required
private long sampledNewCount; // optional
private long sampledContinuationCount; // optional
private long unsampledNewCount; // optional
@@ -58,7 +56,6 @@ public class TTransaction implements org.apache.thrift.TBase<TTransaction, TTran
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
- VERSION((short)1, "version"),
SAMPLED_NEW_COUNT((short)2, "sampledNewCount"),
SAMPLED_CONTINUATION_COUNT((short)3, "sampledContinuationCount"),
UNSAMPLED_NEW_COUNT((short)4, "unsampledNewCount"),
@@ -77,8 +74,6 @@ public enum _Fields implements org.apache.thrift.TFieldIdEnum {
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
- case 1: // VERSION
- return VERSION;
case 2: // SAMPLED_NEW_COUNT
return SAMPLED_NEW_COUNT;
case 3: // SAMPLED_CONTINUATION_COUNT
@@ -127,18 +122,15 @@ public String getFieldName() {
}
// isset id assignments
- private static final int __VERSION_ISSET_ID = 0;
- private static final int __SAMPLEDNEWCOUNT_ISSET_ID = 1;
- private static final int __SAMPLEDCONTINUATIONCOUNT_ISSET_ID = 2;
- private static final int __UNSAMPLEDNEWCOUNT_ISSET_ID = 3;
- private static final int __UNSAMPLEDCONTINUATIONCOUNT_ISSET_ID = 4;
+ private static final int __SAMPLEDNEWCOUNT_ISSET_ID = 0;
+ private static final int __SAMPLEDCONTINUATIONCOUNT_ISSET_ID = 1;
+ private static final int __UNSAMPLEDNEWCOUNT_ISSET_ID = 2;
+ private static final int __UNSAMPLEDCONTINUATIONCOUNT_ISSET_ID = 3;
private byte __isset_bitfield = 0;
private static final _Fields optionals[] = {_Fields.SAMPLED_NEW_COUNT,_Fields.SAMPLED_CONTINUATION_COUNT,_Fields.UNSAMPLED_NEW_COUNT,_Fields.UNSAMPLED_CONTINUATION_COUNT};
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.VERSION, new org.apache.thrift.meta_data.FieldMetaData("version", org.apache.thrift.TFieldRequirementType.DEFAULT,
- new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16)));
tmpMap.put(_Fields.SAMPLED_NEW_COUNT, new org.apache.thrift.meta_data.FieldMetaData("sampledNewCount", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.SAMPLED_CONTINUATION_COUNT, new org.apache.thrift.meta_data.FieldMetaData("sampledContinuationCount", org.apache.thrift.TFieldRequirementType.OPTIONAL,
@@ -152,16 +144,6 @@ public String getFieldName() {
}
public TTransaction() {
- this.version = (short)0;
-
- }
-
- public TTransaction(
- short version)
- {
- this();
- this.version = version;
- setVersionIsSet(true);
}
/**
@@ -169,7 +151,6 @@ public TTransaction(
*/
public TTransaction(TTransaction other) {
__isset_bitfield = other.__isset_bitfield;
- this.version = other.version;
this.sampledNewCount = other.sampledNewCount;
this.sampledContinuationCount = other.sampledContinuationCount;
this.unsampledNewCount = other.unsampledNewCount;
@@ -182,8 +163,6 @@ public TTransaction deepCopy() {
@Override
public void clear() {
- this.version = (short)0;
-
setSampledNewCountIsSet(false);
this.sampledNewCount = 0;
setSampledContinuationCountIsSet(false);
@@ -194,28 +173,6 @@ public void clear() {
this.unsampledContinuationCount = 0;
}
- public short getVersion() {
- return this.version;
- }
-
- public void setVersion(short version) {
- this.version = version;
- setVersionIsSet(true);
- }
-
- public void unsetVersion() {
- __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __VERSION_ISSET_ID);
- }
-
- /** Returns true if field version is set (has been assigned a value) and false otherwise */
- public boolean isSetVersion() {
- return EncodingUtils.testBit(__isset_bitfield, __VERSION_ISSET_ID);
- }
-
- public void setVersionIsSet(boolean value) {
- __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __VERSION_ISSET_ID, value);
- }
-
public long getSampledNewCount() {
return this.sampledNewCount;
}
@@ -306,14 +263,6 @@ public void setUnsampledContinuationCountIsSet(boolean value) {
public void setFieldValue(_Fields field, Object value) {
switch (field) {
- case VERSION:
- if (value == null) {
- unsetVersion();
- } else {
- setVersion((Short)value);
- }
- break;
-
case SAMPLED_NEW_COUNT:
if (value == null) {
unsetSampledNewCount();
@@ -351,9 +300,6 @@ public void setFieldValue(_Fields field, Object value) {
public Object getFieldValue(_Fields field) {
switch (field) {
- case VERSION:
- return Short.valueOf(getVersion());
-
case SAMPLED_NEW_COUNT:
return Long.valueOf(getSampledNewCount());
@@ -377,8 +323,6 @@ public boolean isSet(_Fields field) {
}
switch (field) {
- case VERSION:
- return isSetVersion();
case SAMPLED_NEW_COUNT:
return isSetSampledNewCount();
case SAMPLED_CONTINUATION_COUNT:
@@ -404,15 +348,6 @@ public boolean equals(TTransaction that) {
if (that == null)
return false;
- boolean this_present_version = true;
- boolean that_present_version = true;
- if (this_present_version || that_present_version) {
- if (!(this_present_version && that_present_version))
- return false;
- if (this.version != that.version)
- return false;
- }
-
boolean this_present_sampledNewCount = true && this.isSetSampledNewCount();
boolean that_present_sampledNewCount = true && that.isSetSampledNewCount();
if (this_present_sampledNewCount || that_present_sampledNewCount) {
@@ -456,11 +391,6 @@ public boolean equals(TTransaction that) {
public int hashCode() {
List<Object> list = new ArrayList<Object>();
- boolean present_version = true;
- list.add(present_version);
- if (present_version)
- list.add(version);
-
boolean present_sampledNewCount = true && (isSetSampledNewCount());
list.add(present_sampledNewCount);
if (present_sampledNewCount)
@@ -492,16 +422,6 @@ public int compareTo(TTransaction other) {
int lastComparison = 0;
- lastComparison = Boolean.valueOf(isSetVersion()).compareTo(other.isSetVersion());
- if (lastComparison != 0) {
- return lastComparison;
- }
- if (isSetVersion()) {
- lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.version, other.version);
- if (lastComparison != 0) {
- return lastComparison;
- }
- }
lastComparison = Boolean.valueOf(isSetSampledNewCount()).compareTo(other.isSetSampledNewCount());
if (lastComparison != 0) {
return lastComparison;
@@ -562,11 +482,7 @@ public String toString() {
StringBuilder sb = new StringBuilder("TTransaction(");
boolean first = true;
- sb.append("version:");
- sb.append(this.version);
- first = false;
if (isSetSampledNewCount()) {
- if (!first) sb.append(", ");
sb.append("sampledNewCount:");
sb.append(this.sampledNewCount);
first = false;
@@ -634,14 +550,6 @@ public void read(org.apache.thrift.protocol.TProtocol iprot, TTransaction struct
break;
}
switch (schemeField.id) {
- case 1: // VERSION
- if (schemeField.type == org.apache.thrift.protocol.TType.I16) {
- struct.version = iprot.readI16();
- struct.setVersionIsSet(true);
- } else {
- org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
- }
- break;
case 2: // SAMPLED_NEW_COUNT
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.sampledNewCount = iprot.readI64();
@@ -687,9 +595,6 @@ public void write(org.apache.thrift.protocol.TProtocol oprot, TTransaction struc
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
- oprot.writeFieldBegin(VERSION_FIELD_DESC);
- oprot.writeI16(struct.version);
- oprot.writeFieldEnd();
if (struct.isSetSampledNewCount()) {
oprot.writeFieldBegin(SAMPLED_NEW_COUNT_FIELD_DESC);
oprot.writeI64(struct.sampledNewCount);
@@ -728,25 +633,19 @@ private static class TTransactionTupleScheme extends TupleScheme<TTransaction> {
public void write(org.apache.thrift.protocol.TProtocol prot, TTransaction struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
- if (struct.isSetVersion()) {
- optionals.set(0);
- }
if (struct.isSetSampledNewCount()) {
- optionals.set(1);
+ optionals.set(0);
}
if (struct.isSetSampledContinuationCount()) {
- optionals.set(2);
+ optionals.set(1);
}
if (struct.isSetUnsampledNewCount()) {
- optionals.set(3);
+ optionals.set(2);
}
if (struct.isSetUnsampledContinuationCount()) {
- optionals.set(4);
- }
- oprot.writeBitSet(optionals, 5);
- if (struct.isSetVersion()) {
- oprot.writeI16(struct.version);
+ optionals.set(3);
}
+ oprot.writeBitSet(optionals, 4);
if (struct.isSetSampledNewCount()) {
oprot.writeI64(struct.sampledNewCount);
}
@@ -764,24 +663,20 @@ public void write(org.apache.thrift.protocol.TProtocol prot, TTransaction struct
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, TTransaction struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
- BitSet incoming = iprot.readBitSet(5);
+ BitSet incoming = iprot.readBitSet(4);
if (incoming.get(0)) {
- struct.version = iprot.readI16();
- struct.setVersionIsSet(true);
- }
- if (incoming.get(1)) {
struct.sampledNewCount = iprot.readI64();
struct.setSampledNewCountIsSet(true);
}
- if (incoming.get(2)) {
+ if (incoming.get(1)) {
struct.sampledContinuationCount = iprot.readI64();
struct.setSampledContinuationCountIsSet(true);
}
- if (incoming.get(3)) {
+ if (incoming.get(2)) {
struct.unsampledNewCount = iprot.readI64();
struct.setUnsampledNewCountIsSet(true);
}
- if (incoming.get(4)) {
+ if (incoming.get(3)) {
struct.unsampledContinuationCount = iprot.readI64();
struct.setUnsampledContinuationCountIsSet(true);
}
diff --git a/thrift/src/main/thrift/Pinpoint.thrift b/thrift/src/main/thrift/Pinpoint.thrift
index 28bbb06877c9..c7da81bce868 100644
--- a/thrift/src/main/thrift/Pinpoint.thrift
+++ b/thrift/src/main/thrift/Pinpoint.thrift
@@ -54,7 +54,6 @@ struct TCpuLoad {
}
struct TTransaction {
- 1: i16 version = 0
2: optional i64 sampledNewCount
3: optional i64 sampledContinuationCount
4: optional i64 unsampledNewCount
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/AgentStatMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/AgentStatMapper.java
index 140d34e9e954..846acee859ef 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/AgentStatMapper.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/AgentStatMapper.java
@@ -106,9 +106,6 @@ public List<AgentStat> mapRow(Result result, int rowNum) throws Exception {
if (qualifierMap.containsKey(AGENT_STAT_COL_SYS_CPU)) {
agentStat.setSystemCpuUsage(Bytes.toDouble(qualifierMap.get(AGENT_STAT_COL_SYS_CPU)));
}
- if (qualifierMap.containsKey(AGENT_STAT_COL_TRANSACTION_VERSION)) {
- agentStat.setTransactionVersion(Bytes.toShort(qualifierMap.get(AGENT_STAT_COL_TRANSACTION_VERSION)));
- }
if (qualifierMap.containsKey(AGENT_STAT_COL_TRANSACTION_SAMPLED_NEW)) {
agentStat.setSampledNewCount(Bytes.toLong(qualifierMap.get(AGENT_STAT_COL_TRANSACTION_SAMPLED_NEW)));
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentStat.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentStat.java
index d5d9bd8626df..1060a3242fd7 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentStat.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentStat.java
@@ -39,7 +39,6 @@ public class AgentStat {
private double jvmCpuUsage = NOT_COLLECTED;
private double systemCpuUsage = NOT_COLLECTED;
- private short transactionVersion;
private long sampledNewCount = NOT_COLLECTED;
private long sampledContinuationCount = NOT_COLLECTED;
private long unsampledNewCount = NOT_COLLECTED;
@@ -144,14 +143,6 @@ public void setSystemCpuUsage(double systemCpuUsage) {
this.systemCpuUsage = systemCpuUsage;
}
- public short getTransactionVersion() {
- return transactionVersion;
- }
-
- public void setTransactionVersion(short transactionVersion) {
- this.transactionVersion = transactionVersion;
- }
-
public long getSampledNewCount() {
return sampledNewCount;
}
@@ -190,9 +181,8 @@ public String toString() {
+ ", gcType=" + gcType + ", gcOldCount=" + gcOldCount + ", gcOldTime=" + gcOldTime
+ ", heapUsed=" + heapUsed + ", heapMax=" + heapMax + ", nonHeapUsed=" + nonHeapUsed
+ ", nonHeapMax=" + nonHeapMax + ", jvmCpuUsage=" + jvmCpuUsage + ", systemCpuUsage="+ systemCpuUsage
- + ", transactionVersion=" + transactionVersion + ", sampledNewCount=" + sampledNewCount
- + ", sampledContinuationCount=" + sampledContinuationCount + ", unsampledNewCount=" + unsampledNewCount
- + ", unsampledContinuationCount=" + unsampledContinuationCount + "]";
+ + ", sampledNewCount=" + sampledNewCount + ", sampledContinuationCount=" + sampledContinuationCount
+ + ", unsampledNewCount=" + unsampledNewCount + ", unsampledContinuationCount=" + unsampledContinuationCount + "]";
}
}
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/mapper/AgentStatMapperTest.java b/web/src/test/java/com/navercorp/pinpoint/web/mapper/AgentStatMapperTest.java
index 166b086331fc..a54924ffc855 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/mapper/AgentStatMapperTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/mapper/AgentStatMapperTest.java
@@ -77,7 +77,6 @@ public class AgentStatMapperTest {
private static final double JVM_CPU_USAGE = 10;
private static final double SYS_CPU_USAGE = 20;
- private static final short TRANSACTION_VERSION = 1;
private static final long SAMPLED_NEW_COUNT = 100L;
private static final long SAMPLED_CONTINUATION_COUNT = 200L;
private static final long UNSAMPLED_NEW_COUNT = 50L;
@@ -109,7 +108,6 @@ public void test_current() throws Exception {
createCell(AGENT_STAT_COL_NON_HEAP_MAX, Bytes.toBytes(NON_HEAP_MAX)),
createCell(AGENT_STAT_COL_JVM_CPU, Bytes.toBytes(JVM_CPU_USAGE)),
createCell(AGENT_STAT_COL_SYS_CPU, Bytes.toBytes(SYS_CPU_USAGE)),
- createCell(AGENT_STAT_COL_TRANSACTION_VERSION, Bytes.toBytes(TRANSACTION_VERSION)),
createCell(AGENT_STAT_COL_TRANSACTION_SAMPLED_NEW, Bytes.toBytes(SAMPLED_NEW_COUNT)),
createCell(AGENT_STAT_COL_TRANSACTION_SAMPLED_CONTINUATION, Bytes.toBytes(SAMPLED_CONTINUATION_COUNT)),
createCell(AGENT_STAT_COL_TRANSACTION_UNSAMPLED_NEW, Bytes.toBytes(UNSAMPLED_NEW_COUNT)),
@@ -143,7 +141,6 @@ public void test_legacy_with_AGENT_STAT_CF_STATISTICS_V1() throws Exception {
assertJvmGc(agentStat);
assertEquals(AgentStat.NOT_COLLECTED, agentStat.getJvmCpuUsage(), DELTA);
assertEquals(AgentStat.NOT_COLLECTED, agentStat.getSystemCpuUsage(), DELTA);
- assertEquals(0, agentStat.getTransactionVersion());
assertEquals(AgentStat.NOT_COLLECTED, agentStat.getSampledNewCount());
assertEquals(AgentStat.NOT_COLLECTED, agentStat.getSampledContinuationCount());
assertEquals(AgentStat.NOT_COLLECTED, agentStat.getUnsampledNewCount());
@@ -164,7 +161,6 @@ public void test_legacy_serialized_BOs() throws Exception {
assertEquals(0, agentStat.getCollectInterval());
assertJvmGc(agentStat);
assertCpuUsage(agentStat);
- assertEquals(0, agentStat.getTransactionVersion());
assertEquals(AgentStat.NOT_COLLECTED, agentStat.getSampledNewCount());
assertEquals(AgentStat.NOT_COLLECTED, agentStat.getSampledContinuationCount());
assertEquals(AgentStat.NOT_COLLECTED, agentStat.getUnsampledNewCount());
@@ -189,7 +185,6 @@ private void assertCpuUsage(AgentStat agentStat) {
}
private void assertTransaction(AgentStat agentStat) {
- assertEquals(TRANSACTION_VERSION, agentStat.getTransactionVersion());
assertEquals(SAMPLED_NEW_COUNT, agentStat.getSampledNewCount());
assertEquals(SAMPLED_CONTINUATION_COUNT, agentStat.getSampledContinuationCount());
assertEquals(UNSAMPLED_NEW_COUNT, agentStat.getUnsampledNewCount());
| train | train | "2015-10-29T10:19:42" | "2015-10-13T09:04:34Z" | Xylus | test |
pinpoint-apm/pinpoint/1069_1138 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1069 | pinpoint-apm/pinpoint/1138 | [
"keyword_pr_to_issue"
] | 476f8acdb9715d664512d10b331a4c5afe595abb | 2eab59a4bf9aa0f25d607c7ef765d8c7aad50604 | [
"Currently tps is calculated by factoring in the following situations:\n1. When a new trace is created and should be sampled.\n2. When a new trace is created and should not be sampled.\n3. When a trace is continued with sampling set false.\n\nNeed to consider 1 more situation:\n1. When a trace is continued, and sampling is set true.\n",
"Should continue after #1103 \n",
"Changing spec to collect the number of transaction over a certain period of time.\nTps calculation will be done when querying using this data.\n",
"Reopening to remove `version` field.\n",
"Reopening for UI\n"
] | [] | "2015-10-30T08:15:54Z" | [
"enhancement"
] | Add Transaction metric collection | Add per-agent transaction count metric collection support for all 4 types of transactions:
1. Sampled New
2. Unsampled New
3. Sampled Continuation
4. Unsampled Continuation
| [
"web/src/main/webapp/common/help/help-content-en.js",
"web/src/main/webapp/common/help/help-content-ko.js",
"web/src/main/webapp/common/services/agent-dao.service.js",
"web/src/main/webapp/features/agentInfo/agent-info.directive.js",
"web/src/main/webapp/features/agentInfo/agentInfoMain.html",
"web/src/main/webapp/index.html"
] | [
"web/src/main/webapp/common/help/help-content-en.js",
"web/src/main/webapp/common/help/help-content-ko.js",
"web/src/main/webapp/common/services/agent-dao.service.js",
"web/src/main/webapp/features/agentInfo/agent-info.directive.js",
"web/src/main/webapp/features/agentInfo/agentInfoMain.html",
"web/src/main/webapp/features/tpsChart/tps-chart.directive.js",
"web/src/main/webapp/index.html"
] | [] | diff --git a/web/src/main/webapp/common/help/help-content-en.js b/web/src/main/webapp/common/help/help-content-en.js
index 57b9ed66761a..76154867f583 100644
--- a/web/src/main/webapp/common/help/help-content-en.js
+++ b/web/src/main/webapp/common/help/help-content-en.js
@@ -467,7 +467,19 @@
desc: "Both the JVM's and the system's CPU usage are collected"
}]
}]
- }
+ },
+ tps: {
+ mainStyle: "",
+ title: "TPS",
+ desc: "Transactions per second received by the server",
+ category: [{
+ title: "[Legend]",
+ items: [{
+ name: "TPS",
+ desc: "Number of transactions received by the server every second"
+ }]
+ }]
+ }
},
callTree: {
column: {
diff --git a/web/src/main/webapp/common/help/help-content-ko.js b/web/src/main/webapp/common/help/help-content-ko.js
index 6c7871afe53c..daefa105c6e7 100644
--- a/web/src/main/webapp/common/help/help-content-ko.js
+++ b/web/src/main/webapp/common/help/help-content-ko.js
@@ -486,7 +486,19 @@
desc: "JVM과 전체 시스템의 CPU 사용량 모두 수집됩니다."
}]
}]
- }
+ },
+ tps: {
+ mainStyle: "",
+ title: "TPS",
+ desc: "서버로 인입된 초당 트랜잭션 수",
+ category: [{
+ title: "[범례]",
+ items: [{
+ name: "TPS",
+ desc: "초당 트랜잭션 수"
+ }]
+ }]
+ }
},
callTree: {
column: {
diff --git a/web/src/main/webapp/common/services/agent-dao.service.js b/web/src/main/webapp/common/services/agent-dao.service.js
index 897939699447..4c4c0fd96736 100644
--- a/web/src/main/webapp/common/services/agent-dao.service.js
+++ b/web/src/main/webapp/common/services/agent-dao.service.js
@@ -167,6 +167,38 @@
return newData;
};
+
+ /**
+ * parse tps chart data for amcharts
+ * @param tps
+ * @param agentStat
+ * @returns {Array}
+ */
+ this.parseTpsChartDataForAmcharts = function (tps, agentStat) {
+ // TPS data availability check
+ var totalTpsData = agentStat.charts['TPS_TOTAL'];
+ if (totalTpsData) {
+ tps.isAvailable = true;
+ } else {
+ return;
+ }
+ var newData = [],
+ DATA_UNAVAILABLE = -1,
+ pointsTotalTps = totalTpsData.points;
+
+ for (var i = 0; i < pointsTotalTps.length; ++i) {
+ var thisData = {
+ time: moment(pointsTotalTps[i].timestamp).toString('YYYY-MM-dd HH:mm:ss')
+ };
+ var totalTps = typeof agentStat.charts['TPS_TOTAL'].points[i].avgVal == "number" ? agentStat.charts['TPS_TOTAL'].points[i].avgVal.toFixed(2) : 0.00;
+ if (!(totalTps < 0)) {
+ thisData.totalTps = totalTps;
+ }
+ newData.push(thisData);
+ }
+
+ return newData;
+ }
}
]);
})();
\ No newline at end of file
diff --git a/web/src/main/webapp/features/agentInfo/agent-info.directive.js b/web/src/main/webapp/features/agentInfo/agent-info.directive.js
index fbee377c5ff2..218c93177b85 100644
--- a/web/src/main/webapp/features/agentInfo/agent-info.directive.js
+++ b/web/src/main/webapp/features/agentInfo/agent-info.directive.js
@@ -24,7 +24,7 @@
// define private variables of methods
var getAgentStat, getLink, initServiceInfo, showCharts, parseMemoryChartDataForAmcharts, parseCpuLoadChartDataForAmcharts,
- broadcastToCpuLoadChart, resetServerMetaDataDiv, initTooltip;
+ broadcastToCpuLoadChart, broadcastToTpsChart, resetServerMetaDataDiv, initTooltip;
// initialize
scope.agentInfoTemplate = 'features/agentInfo/agentInfoReady.html';
@@ -55,6 +55,13 @@
position: "top",
trigger: "click"
});
+ jQuery('.tpsTooltip').tooltipster({
+ content: function() {
+ return helpContentTemplate(helpContentService.inspector.tps);
+ },
+ position: "top",
+ trigger: "click"
+ });
}
};
@@ -112,26 +119,30 @@
*/
showCharts = function (agentStat) {
- var heap = { id: 'heap', title: 'Heap', span: 'span12', line: [
+ var heap = { id: 'heap', title: 'Heap Usage', span: 'span12', line: [
{ id: 'JVM_MEMORY_HEAP_USED', key: 'Used', values: [], isFgc: false },
{ id: 'JVM_MEMORY_HEAP_MAX', key: 'Max', values: [], isFgc: false },
{ id: 'fgc', key: 'FGC', values: [], bar: true, isFgc: true }
]};
- var nonheap = { id: 'nonheap', title: 'PermGen', span: 'span12', line: [
+ var nonheap = { id: 'nonheap', title: 'PermGen Usage', span: 'span12', line: [
{ id: 'JVM_MEMORY_NON_HEAP_USED', key: 'Used', values: [], isFgc: false },
{ id: 'JVM_MEMORY_NON_HEAP_MAX', key: 'Max', values: [], isFgc: false },
{ id: 'fgc', key: 'FGC', values: [], bar: true, isFgc: true }
]};
var cpuLoad = { id: 'cpuLoad', title: 'JVM/System Cpu Usage', span: 'span12', isAvailable: false};
+
+ var tps = { id: 'tps', title: 'Transactions Per Second', span: 'span12', isAvailable: false };
scope.memoryGroup = [ heap, nonheap ];
scope.cpuLoadChart = cpuLoad;
+ scope.tpsChart = tps;
scope.$broadcast('jvmMemoryChartDirective.initAndRenderWithData.forHeap', AgentDaoService.parseMemoryChartDataForAmcharts(heap, agentStat), '100%', '270px');
scope.$broadcast('jvmMemoryChartDirective.initAndRenderWithData.forNonHeap', AgentDaoService.parseMemoryChartDataForAmcharts(nonheap, agentStat), '100%', '270px');
scope.$broadcast('cpuLoadChartDirective.initAndRenderWithData.forCpuLoad', AgentDaoService.parseCpuLoadChartDataForAmcharts(cpuLoad, agentStat), '100%', '270px');
+ scope.$broadcast('tpsChartDirective.initAndRenderWithData.forTps', AgentDaoService.parseTpsChartDataForAmcharts(tps, agentStat), '100%', '270px');
};
/**
@@ -182,6 +193,12 @@
}
}
+ broadcastToTpsChart = function(e, event) {
+ if (scope.tpsChart.isAvailable) {
+ scope.$broadcast('tpsChartDirective.showCursorAt.forTps', event.index);
+ }
+ }
+
scope.openDetail = function() {
$('#serverMetaDataDiv').modal({});
};
@@ -202,6 +219,7 @@
scope.$on('jvmMemoryChartDirective.cursorChanged.forHeap', function (e, event) {
scope.$broadcast('jvmMemoryChart.showCursorAt.forNonHeap', event.index);
broadcastToCpuLoadChart(e, event);
+ broadcastToTpsChart(e, event);
});
/**
@@ -210,6 +228,7 @@
scope.$on('jvmMemoryChartDirective.cursorChanged.forNonHeap', function (e, event) {
scope.$broadcast('jvmMemoryChartDirective.showCursorAt.forHeap', event.index);
broadcastToCpuLoadChart(e, event);
+ broadcastToTpsChart(e, event);
});
/**
@@ -218,7 +237,17 @@
scope.$on('cpuLoadChartDirective.cursorChanged.forCpuLoad', function (e, event) {
scope.$broadcast('jvmMemoryChartDirective.showCursorAt.forHeap', event.index);
scope.$broadcast('jvmMemoryChartDirective.showCursorAt.forNonHeap', event.index);
+ broadcastToTpsChart(e, event);
});
+
+ /**
+ * scope event on tpsChart.cursorChanged.forTps
+ */
+ scope.$on('tpsChartDirective.cursorChanged.forTps', function (e, event) {
+ scope.$broadcast('jvmMemoryChartDirective.showCursorAt.forHeap', event.index);
+ scope.$broadcast('jvmMemoryChartDirective.showCursorAt.forNonHeap', event.index);
+ broadcastToCpuLoadChart(e, event);
+ });
}
};
}
diff --git a/web/src/main/webapp/features/agentInfo/agentInfoMain.html b/web/src/main/webapp/features/agentInfo/agentInfoMain.html
index 2c54ba0b5582..d62599d493e6 100644
--- a/web/src/main/webapp/features/agentInfo/agentInfoMain.html
+++ b/web/src/main/webapp/features/agentInfo/agentInfoMain.html
@@ -56,25 +56,26 @@ <h3>Information</h3>
</div>
</div>
<div>
- <h3>Memory & Garbage Collection</h3>
<div class="row">
<div class="col-md-6">
- <h5><span class="glyphicon glyphicon-question-sign heapTooltip" style="cursor:pointer;float:right;"></span> {{memoryGroup[0].title}}</h5>
+ <h4><span class="glyphicon glyphicon-question-sign heapTooltip" style="cursor:pointer;float:right;"></span> {{memoryGroup[0].title}}</h4>
<jvm-memory-chart-directive namespace="forHeap"></jvm-memory-chart-directive>
</div>
<div class="col-md-6">
- <h5><span class="glyphicon glyphicon-question-sign permGenTooltip" style="cursor:pointer;float:right;"></span> {{memoryGroup[1].title}}</h5>
+ <h4><span class="glyphicon glyphicon-question-sign permGenTooltip" style="cursor:pointer;float:right;"></span> {{memoryGroup[1].title}}</h4>
<jvm-memory-chart-directive namespace="forNonHeap"></jvm-memory-chart-directive>
</div>
</div>
- </div>
- <div>
- <h3>Cpu Usage</h3>
+ <hr>
<div class="row">
<div class="col-md-6">
- <h5><span class="glyphicon glyphicon-question-sign cpuUsageTooltip" style="cursor:pointer;float:right;"></span> {{cpuLoadChart.title}}</h5>
+ <h4><span class="glyphicon glyphicon-question-sign cpuUsageTooltip" style="cursor:pointer;float:right;"></span> {{cpuLoadChart.title}}</h4>
<cpu-load-chart-directive namespace="forCpuLoad"></cpu-load-chart-directive>
</div>
+ <div class="col-md-6">
+ <h4><span class="glyphicon glyphicon-question-sign tpsTooltip" style="cursor:pointer;float:right;"></span> {{tpsChart.title}}</h4>
+ <tps-chart-directive namespace="forTps"></tps-chart-directive>
+ </div>
</div>
</div>
<div class="modal fade bs-modal-lg center" id="serverMetaDataDiv" tabindex="-1" role="dialog" aria-labelledby="myServerMetaDataDiv"
diff --git a/web/src/main/webapp/features/tpsChart/tps-chart.directive.js b/web/src/main/webapp/features/tpsChart/tps-chart.directive.js
new file mode 100644
index 000000000000..3e4e4dad6bc5
--- /dev/null
+++ b/web/src/main/webapp/features/tpsChart/tps-chart.directive.js
@@ -0,0 +1,164 @@
+(function() {
+ 'use strict';
+ /**
+ * (en)tpsChartDirective
+ * @ko tpsChartDirective
+ * @group Directive
+ * @name tpsChartDirective
+ * @class
+ */
+ angular.module('pinpointApp').directive('tpsChartDirective', ['$timeout',
+ function ($timeout) {
+ return {
+ template: '<div></div>',
+ replace: true,
+ restrict: 'E',
+ scope: {
+ namespace: '@' // string value
+ },
+ link: function postLink(scope, element, attrs) {
+
+ // define variables
+ var sId, oChart;
+
+ // define variables of methods
+ var setIdAutomatically, setWidthHeight, render, showCursorAt, resize;
+
+ /**
+ * set id automatically
+ */
+ setIdAutomatically = function () {
+ sId = 'multipleValueAxesId-' + scope.namespace;
+ element.attr('id', sId);
+ };
+
+ /**
+ * set width height
+ * @param w
+ * @param h
+ */
+ setWidthHeight = function (w, h) {
+ if (w) element.css('width', w);
+ if (h) element.css('height', h);
+ };
+
+ /**
+ * render
+ * @param chartData
+ */
+ render = function (chartData) {
+ var options = {
+ "type": "serial",
+ "theme": "light",
+ "autoMargins": false,
+ "marginTop": 10,
+ "marginLeft": 70,
+ "marginRight": 70,
+ "marginBottom": 30,
+ "legend": {
+ "useGraphSettings": true,
+ "autoMargins": true,
+ "align" : "right",
+ "position": "top",
+ "valueWidth": 70
+ },
+ "usePrefixes": true,
+ "dataProvider": chartData,
+ "valueAxes": [
+ {
+ "id": "v1",
+ "gridAlpha": 0,
+ "axisAlpha": 1,
+ "position": "left",
+ "title": "TPS",
+ "minimum" : 0
+ },
+ ],
+ "graphs": [
+ {
+ "valueAxis": "v1",
+ "balloonText": "[[value]]",
+ "legendValueText": "[[value]]",
+ "lineColor": "rgb(31, 119, 180)",
+ "fillColor": "rgb(31, 119, 180)",
+ "title": "TPS",
+ "valueField": "totalTps",
+ "fillAlphas": 0.4,
+ "connect": false
+ }
+ ],
+ "chartCursor": {
+ "categoryBalloonAlpha": 0.7,
+ "fullWidth": true,
+ "cursorAlpha": 0.1
+ },
+ "categoryField": "time",
+ "categoryAxis": {
+ "axisColor": "#DADADA",
+ "startOnAxis": true,
+ "gridPosition": "start",
+ "labelFunction": function (valueText, serialDataItem, categoryAxis) {
+ return moment(valueText).format("HH:mm:ss");
+ }
+ }
+ };
+ $timeout(function () {
+ oChart = AmCharts.makeChart(sId, options);
+ oChart.chartCursor.addListener('changed', function (event) {
+ scope.$emit('tpsChartDirective.cursorChanged.' + scope.namespace, event);
+ });
+ });
+ };
+
+ /**
+ * show cursor at
+ * @param category
+ */
+ showCursorAt = function (category) {
+ if (category) {
+ if (angular.isNumber(category)) {
+ category = oChart.dataProvider[category].time;
+ }
+ oChart.chartCursor.showCursorAt(category);
+ } else {
+ oChart.chartCursor.hideCursor();
+ }
+ };
+
+ /**
+ * resize
+ */
+ resize = function () {
+ if (oChart) {
+ oChart.validateNow();
+ oChart.validateSize();
+ }
+ };
+
+ /**
+ * scope event on tpsChartDirective.initAndRenderWithData.namespace
+ */
+ scope.$on('tpsChartDirective.initAndRenderWithData.' + scope.namespace, function (event, data, w, h) {
+ setIdAutomatically();
+ setWidthHeight(w, h);
+ render(data);
+ });
+
+ /**
+ * scope event on tpsChartDirective.showCursorAt.namespace
+ */
+ scope.$on('tpsChartDirective.showCursorAt.' + scope.namespace, function (event, category) {
+ showCursorAt(category)
+ });
+
+ /**
+ * scope event on tpsChartDirective.resize.namespace
+ */
+ scope.$on('tpsChartDirective.resize.' + scope.namespace, function (event) {
+ resize();
+ });
+ }
+ };
+ }
+ ]);
+})();
\ No newline at end of file
diff --git a/web/src/main/webapp/index.html b/web/src/main/webapp/index.html
index 7aee7b539ac0..3af87681f428 100644
--- a/web/src/main/webapp/index.html
+++ b/web/src/main/webapp/index.html
@@ -493,6 +493,7 @@ <h4>한글</h4>
<script src="features/loadChart/load-chart.directive.js?v=${buildTime}"></script>
<script src="features/jvmMemoryChart/jvm-memory-chart.directive.js?v=${buildTime}"></script>
<script src="features/cpuLoadChart/cpu-load-chart.directive.js?v=${buildTime}"></script>
+<script src="features/tpsChart/tps-chart.directive.js?v=${buildTime}"></script>
<script src="features/loading/loading.directive.js?v=${buildTime}"></script>
<script src="features/configuration/configuration.controller.js?v=${buildTime}"></script>
<script src="features/configuration/help/help.controller.js?v=${buildTime}"></script>
| null | test | train | "2015-10-30T09:11:33" | "2015-10-13T09:04:34Z" | Xylus | test |
pinpoint-apm/pinpoint/1117_1160 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1117 | pinpoint-apm/pinpoint/1160 | [
"keyword_pr_to_issue"
] | b28425fc8b06d16f73d808fb43ed73234c512db4 | 58a288af73399ae5b70082fb3544aa042b02362b | [] | [] | "2015-11-05T08:18:08Z" | [
"enhancement"
] | Need a way to refresh row timestamp for AgentInfo | Data in AgentInfo table lives for the duration of TTL. If an agent stays alive for longer than the TTL value without a restart, it gets deleted.
There needs to be a way to refresh (or append) AgentInfo to stop this from happening for agents that are alive.
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java"
] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java
index 0996060cd3db..75447968e480 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java
@@ -18,13 +18,13 @@
import java.util.ArrayList;
import java.util.List;
-import java.util.Map.Entry;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,56 +39,70 @@
import com.navercorp.pinpoint.thrift.dto.TServerMetaData;
import com.navercorp.pinpoint.thrift.dto.TServiceInfo;
-
/**
* @author emeroad
* @author koo.taejin
- * @author hyungil.jeong
+ * @author HyunGil Jeong
*/
public class AgentInfoSender implements ServerMetaDataListener {
- private static final Logger LOGGER = LoggerFactory.getLogger(AgentInfoSender.class);
+ // refresh daily
+ public static final long DEFAULT_AGENT_INFO_REFRESH_INTERVAL_MS = 24 * 60 * 60 * 1000L;
+ // retry every 3 seconds
+ public static final long DEFAULT_AGENT_INFO_SEND_INTERVAL_MS = 3 * 1000L;
+ // retry 3 times per attempt
+ public static final int DEFAULT_MAX_TRY_COUNT_PER_ATTEMPT = 3;
+ private static final Logger LOGGER = LoggerFactory.getLogger(AgentInfoSender.class);
private static final ThreadFactory THREAD_FACTORY = new PinpointThreadFactory("Pinpoint-agentInfo-sender", true);
-
- private final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor(THREAD_FACTORY);
- private final long agentInfoSendIntervalMs;
+
+ private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(THREAD_FACTORY);
+
private final EnhancedDataSender dataSender;
+ private final long refreshIntervalMs;
+ private final long sendIntervalMs;
+ private final int maxTryPerAttempt;
private final AgentInformation agentInformation;
- public AgentInfoSender(EnhancedDataSender dataSender, long agentInfoSendIntervalMs, AgentInformation agentInformation) {
- if (dataSender == null) {
- throw new NullPointerException("dataSender must not be null");
- }
- if (agentInformation == null) {
- throw new NullPointerException("agentInformation must not be null");
- }
- this.agentInfoSendIntervalMs = agentInfoSendIntervalMs;
- this.dataSender = dataSender;
- this.agentInformation = agentInformation;
- }
+ private volatile ServerMetaData serverMetaData;
- public void start() {
- final TAgentInfo agentInfo = createTAgentInfo();
- if (LOGGER.isInfoEnabled()) {
- LOGGER.info("AgentInfoSender started. Sending startup information to Pinpoint server via {}. agentInfo={}", dataSender.getClass().getSimpleName(), agentInfo);
- }
- send(agentInfo);
+ private AgentInfoSender(Builder builder) {
+ this.dataSender = builder.dataSender;
+ this.agentInformation = builder.agentInformation;
+ this.refreshIntervalMs = builder.refreshIntervalMs;
+ this.sendIntervalMs = builder.sendIntervalMs;
+ this.maxTryPerAttempt = builder.maxTryPerAttempt;
}
-
+
@Override
public void publishServerMetaData(ServerMetaData serverMetaData) {
- final TAgentInfo agentInfo = createTAgentInfo(serverMetaData);
- if (LOGGER.isInfoEnabled()) {
- LOGGER.info("Sending AgentInfo with ServerMetaData. {}", agentInfo);
+ this.serverMetaData = serverMetaData;
+ submit(this.maxTryPerAttempt);
+ }
+
+ public void start() {
+ submit(Integer.MAX_VALUE);
+ this.executor.scheduleWithFixedDelay(new Runnable() {
+ @Override
+ public void run() {
+ submit(maxTryPerAttempt);
+ }
+ }, this.refreshIntervalMs, this.refreshIntervalMs, TimeUnit.MILLISECONDS);
+ }
+
+ public void stop() {
+ this.executor.shutdown();
+ try {
+ this.executor.awaitTermination(3000, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
}
- send(agentInfo);
+ LOGGER.info("AgentInfoSender stopped");
}
-
- private void send(final TAgentInfo agentInfo) {
- final AgentInfoSendRunnable agentInfoSendJob = new AgentInfoSendRunnable(agentInfo);
- new AgentInfoSendRunnableWrapper(agentInfoSendJob).repeatWithFixedDelay(EXECUTOR_SERVICE, 0, this.agentInfoSendIntervalMs, TimeUnit.MILLISECONDS);
+
+ private void submit(final int maxTryPerAttempt) {
+ new AgentInfoSendRunnableWrapper(new AgentInfoSendRunnable(), maxTryPerAttempt).repeatWithFixedDelay(this.executor, 0, this.sendIntervalMs, TimeUnit.MILLISECONDS);
}
-
+
private TAgentInfo createTAgentInfo() {
final TAgentInfo agentInfo = new TAgentInfo();
agentInfo.setIp(this.agentInformation.getHostIp());
@@ -101,31 +115,13 @@ private TAgentInfo createTAgentInfo() {
agentInfo.setServiceType(this.agentInformation.getServerType().getCode());
agentInfo.setVmVersion(this.agentInformation.getJvmVersion());
agentInfo.setAgentVersion(Version.VERSION);
- return agentInfo;
- }
-
- private TAgentInfo createTAgentInfo(final ServerMetaData serverMetaData) {
- final StringBuilder ports = new StringBuilder();
- for (Entry<Integer, String> entry : serverMetaData.getConnectors().entrySet()) {
- ports.append(" ");
- ports.append(entry.getKey());
+ if (this.serverMetaData != null) {
+ agentInfo.setServerMetaData(createTServiceInfo());
}
- final TAgentInfo agentInfo = new TAgentInfo();
- agentInfo.setIp(this.agentInformation.getHostIp());
- agentInfo.setHostname(this.agentInformation.getMachineName());
- agentInfo.setPorts(ports.toString());
- agentInfo.setAgentId(this.agentInformation.getAgentId());
- agentInfo.setApplicationName(this.agentInformation.getApplicationName());
- agentInfo.setPid(this.agentInformation.getPid());
- agentInfo.setStartTimestamp(this.agentInformation.getStartTime());
- agentInfo.setServiceType(this.agentInformation.getServerType().getCode());
- agentInfo.setVmVersion(this.agentInformation.getJvmVersion());
- agentInfo.setAgentVersion(Version.VERSION);
- agentInfo.setServerMetaData(createTServiceInfo(serverMetaData));
return agentInfo;
}
-
- private TServerMetaData createTServiceInfo(final ServerMetaData serverMetaData) {
+
+ private TServerMetaData createTServiceInfo() {
TServerMetaData tServerMetaData = new TServerMetaData();
tServerMetaData.setServerInfo(serverMetaData.getServerInfo());
tServerMetaData.setVmArgs(serverMetaData.getVmArgs());
@@ -139,59 +135,106 @@ private TServerMetaData createTServiceInfo(final ServerMetaData serverMetaData)
tServerMetaData.setServiceInfos(tServiceInfos);
return tServerMetaData;
}
-
+
private static class AgentInfoSendRunnableWrapper implements Runnable {
private final AgentInfoSendRunnable delegate;
- private ScheduledFuture<?> self;
-
- private AgentInfoSendRunnableWrapper(AgentInfoSendRunnable agentInfoSendRunnable) {
+ private final int maxTryCount;
+ private final AtomicInteger tryCount = new AtomicInteger();;
+ private volatile ScheduledFuture<?> self;
+
+ private AgentInfoSendRunnableWrapper(AgentInfoSendRunnable agentInfoSendRunnable, int maxTryCount) {
+ if (agentInfoSendRunnable == null) {
+ throw new NullPointerException("agentInfoSendRunnable must not be null");
+ }
+ if (maxTryCount < 0) {
+ throw new IllegalArgumentException("maxTryCount must not be less than 0");
+ }
this.delegate = agentInfoSendRunnable;
+ this.maxTryCount = maxTryCount;
}
@Override
public void run() {
- // Cancel self when delegated runnable is completed successfully.
- if (this.delegate.isSuccessful()) {
- this.self.cancel(true);
+ // Cancel self when delegated runnable is completed successfully, or when max try count has been reached
+ if (this.delegate.isSuccessful() || this.tryCount.getAndIncrement() == this.maxTryCount) {
+ this.self.cancel(false);
} else {
this.delegate.run();
}
}
-
+
private void repeatWithFixedDelay(ScheduledExecutorService scheduledExecutorService, long initialDelay, long delay, TimeUnit unit) {
this.self = scheduledExecutorService.scheduleWithFixedDelay(this, initialDelay, delay, unit);
}
}
-
+
private class AgentInfoSendRunnable implements Runnable {
private final AtomicBoolean isSuccessful = new AtomicBoolean(false);
private final AgentInfoSenderListener agentInfoSenderListener = new AgentInfoSenderListener(this.isSuccessful);
private final TAgentInfo agentInfo;
-
- private AgentInfoSendRunnable(TAgentInfo agentInfo) {
- this.agentInfo = agentInfo;
+
+ private AgentInfoSendRunnable() {
+ this.agentInfo = createTAgentInfo();
}
-
+
@Override
public void run() {
if (!isSuccessful.get()) {
- dataSender.request(agentInfo, this.agentInfoSenderListener);
+ LOGGER.info("Sending AgentInfo {}", agentInfo);
+ dataSender.request(this.agentInfo, this.agentInfoSenderListener);
}
}
-
+
public boolean isSuccessful() {
return this.isSuccessful.get();
}
}
- public void stop() {
- EXECUTOR_SERVICE.shutdown();
- try {
- EXECUTOR_SERVICE.awaitTermination(3000, TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
+ public static class Builder {
+ private final EnhancedDataSender dataSender;
+ private final AgentInformation agentInformation;
+ private long refreshIntervalMs = DEFAULT_AGENT_INFO_REFRESH_INTERVAL_MS;
+ private long sendIntervalMs = DEFAULT_AGENT_INFO_SEND_INTERVAL_MS;
+ private int maxTryPerAttempt = DEFAULT_MAX_TRY_COUNT_PER_ATTEMPT;
+
+ public Builder(EnhancedDataSender dataSender, AgentInformation agentInformation) {
+ if (dataSender == null) {
+ throw new NullPointerException("enhancedDataSender must not be null");
+ }
+ if (agentInformation == null) {
+ throw new NullPointerException("agentInformation must not be null");
+ }
+ this.dataSender = dataSender;
+ this.agentInformation = agentInformation;
+ }
+
+ public Builder refreshInterval(long refreshIntervalMs) {
+ this.refreshIntervalMs = refreshIntervalMs;
+ return this;
+ }
+
+ public Builder sendInterval(long sendIntervalMs) {
+ this.sendIntervalMs = sendIntervalMs;
+ return this;
+ }
+
+ public Builder maxTryPerAttempt(int maxTryCountPerAttempt) {
+ this.maxTryPerAttempt = maxTryCountPerAttempt;
+ return this;
+ }
+
+ public AgentInfoSender build() {
+ if (this.refreshIntervalMs <= 0) {
+ throw new IllegalStateException("agentInfoRefreshIntervalMs must be greater than 0");
+ }
+ if (this.sendIntervalMs <= 0) {
+ throw new IllegalStateException("agentInfoSendIntervalMs must be greater than 0");
+ }
+ if (this.maxTryPerAttempt <= 0) {
+ throw new IllegalStateException("maxTryPerAttempt must be greater than 0");
+ }
+ return new AgentInfoSender(this);
}
- LOGGER.info("AgentInfoSender 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 25106c8a2545..5f3b013244ab 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java
@@ -191,7 +191,7 @@ public DefaultAgent(AgentOption agentOption, final InterceptorRegistryBinder int
addCommandService(commandDispatcher, traceContext);
- this.agentInfoSender = new AgentInfoSender(tcpDataSender, profilerConfig.getAgentInfoSendRetryInterval(), this.agentInformation);
+ this.agentInfoSender = new AgentInfoSender.Builder(tcpDataSender, this.agentInformation).sendInterval(profilerConfig.getAgentInfoSendRetryInterval()).build();
this.serverMetaDataHolder.addListener(this.agentInfoSender);
AgentStatCollectorFactory agentStatCollectorFactory = new AgentStatCollectorFactory(this.getTransactionCounter(this.traceContext));
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java
index 6bd0e3c34073..453b7cb17d0b 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java
@@ -29,6 +29,7 @@
import com.navercorp.pinpoint.rpc.PinpointSocket;
import com.navercorp.pinpoint.rpc.client.PinpointClient;
import com.navercorp.pinpoint.rpc.client.PinpointClientFactory;
+import com.navercorp.pinpoint.rpc.client.PinpointClientReconnectEventListener;
import com.navercorp.pinpoint.rpc.packet.*;
import com.navercorp.pinpoint.rpc.server.PinpointServer;
import com.navercorp.pinpoint.rpc.server.PinpointServerAcceptor;
@@ -37,6 +38,7 @@
import com.navercorp.pinpoint.thrift.dto.TResult;
import com.navercorp.pinpoint.thrift.io.HeaderTBaseSerializer;
import com.navercorp.pinpoint.thrift.io.HeaderTBaseSerializerFactory;
+
import org.apache.thrift.TException;
import org.junit.Test;
import org.slf4j.Logger;
@@ -60,7 +62,7 @@ public class AgentInfoSenderTest {
public void agentInfoShouldBeSent() throws InterruptedException {
final AtomicInteger requestCount = new AtomicInteger();
final AtomicInteger successCount = new AtomicInteger();
- final long agentInfoSendRetryIntervalMs = 1000L;
+ final long agentInfoSendRetryIntervalMs = 100L;
ResponseServerMessageListener serverListener = new ResponseServerMessageListener(requestCount, successCount);
@@ -69,12 +71,12 @@ public void agentInfoShouldBeSent() throws InterruptedException {
PinpointClientFactory clientFactory = createPinpointClientFactory();
PinpointClient pinpointClient = ClientFactoryUtils.createPinpointClient(HOST, PORT, clientFactory);
- TcpDataSender sender = new TcpDataSender(pinpointClient);
- AgentInfoSender agentInfoSender = new AgentInfoSender(sender, agentInfoSendRetryIntervalMs, getAgentInfo());
+ TcpDataSender dataSender = new TcpDataSender(pinpointClient);
+ AgentInfoSender agentInfoSender = new AgentInfoSender.Builder(dataSender, getAgentInfo()).sendInterval(agentInfoSendRetryIntervalMs).build();
try {
agentInfoSender.start();
- Thread.sleep(10000L);
+ Thread.sleep(1000L);
} finally {
closeAll(serverAcceptor, agentInfoSender, pinpointClient, clientFactory);
}
@@ -86,8 +88,8 @@ public void agentInfoShouldBeSent() throws InterruptedException {
public void agentInfoShouldRetryUntilSuccess() throws InterruptedException {
final AtomicInteger requestCount = new AtomicInteger();
final AtomicInteger successCount = new AtomicInteger();
- final long agentInfoSendRetryIntervalMs = 1000L;
- final int expectedTriesUntilSuccess = 5;
+ final long agentInfoSendRetryIntervalMs = 100L;
+ final int expectedTriesUntilSuccess = AgentInfoSender.DEFAULT_MAX_TRY_COUNT_PER_ATTEMPT;
ResponseServerMessageListener serverListener = new ResponseServerMessageListener(requestCount, successCount, expectedTriesUntilSuccess);
@@ -97,7 +99,7 @@ public void agentInfoShouldRetryUntilSuccess() throws InterruptedException {
PinpointClient pinpointClient = ClientFactoryUtils.createPinpointClient(HOST, PORT, socketFactory);
TcpDataSender dataSender = new TcpDataSender(pinpointClient);
- AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo());
+ AgentInfoSender agentInfoSender = new AgentInfoSender.Builder(dataSender, getAgentInfo()).sendInterval(agentInfoSendRetryIntervalMs).build();
try {
agentInfoSender.start();
@@ -109,11 +111,83 @@ public void agentInfoShouldRetryUntilSuccess() throws InterruptedException {
assertEquals(1, successCount.get());
}
+ @Test
+ public void agentInfoShouldInitiallyRetryIndefinitely() throws InterruptedException {
+ final AtomicInteger requestCount = new AtomicInteger();
+ final AtomicInteger successCount = new AtomicInteger();
+ final long agentInfoSendRetryIntervalMs = 100L;
+ final int expectedTriesUntilSuccess = 15;
+
+ ResponseServerMessageListener serverListener = new ResponseServerMessageListener(requestCount, successCount, expectedTriesUntilSuccess);
+
+ PinpointServerAcceptor serverAcceptor = createServerAcceptor(serverListener);
+
+ PinpointClientFactory socketFactory = createPinpointClientFactory();
+ PinpointClient pinpointClient = ClientFactoryUtils.createPinpointClient(HOST, PORT, socketFactory);
+
+ TcpDataSender dataSender = new TcpDataSender(pinpointClient);
+ AgentInfoSender agentInfoSender = new AgentInfoSender.Builder(dataSender, getAgentInfo()).sendInterval(agentInfoSendRetryIntervalMs).build();
+
+ try {
+ agentInfoSender.start();
+ Thread.sleep(agentInfoSendRetryIntervalMs * expectedTriesUntilSuccess);
+ } finally {
+ closeAll(serverAcceptor, agentInfoSender, pinpointClient, socketFactory);
+ }
+ assertEquals(expectedTriesUntilSuccess, requestCount.get());
+ assertEquals(1, successCount.get());
+ }
+
+ @Test
+ public void agentInfoShouldRetryUntilAttemptsAreExhaustedWhenRefreshing() throws InterruptedException {
+ final AtomicInteger requestCount = new AtomicInteger();
+ final AtomicInteger successCount = new AtomicInteger();
+ final long agentInfoSendRetryIntervalMs = 100L;
+ final long agentInfoSendRefreshIntervalMs = 1000L;
+ final int expectedTries = AgentInfoSender.DEFAULT_MAX_TRY_COUNT_PER_ATTEMPT + 1;
+ final CountDownLatch agentReconnectLatch = new CountDownLatch(1);
+
+ ResponseServerMessageListener successServerListener = new ResponseServerMessageListener(requestCount, successCount);
+ ResponseServerMessageListener failServerListener = new ResponseServerMessageListener(requestCount, successCount, Integer.MAX_VALUE);
+
+ PinpointServerAcceptor successServerAcceptor = createServerAcceptor(successServerListener);
+ PinpointServerAcceptor failServerAcceptor = null;
+
+ PinpointClientFactory socketFactory = createPinpointClientFactory();
+ PinpointClient pinpointClient = ClientFactoryUtils.createPinpointClient(HOST, PORT, socketFactory);
+
+ TcpDataSender dataSender = new TcpDataSender(pinpointClient);
+ dataSender.addReconnectEventListener(new PinpointClientReconnectEventListener() {
+ @Override
+ public void reconnectPerformed(PinpointClient client) {
+ agentReconnectLatch.countDown();
+ }
+ });
+ AgentInfoSender agentInfoSender = new AgentInfoSender.Builder(dataSender, getAgentInfo())
+ .refreshInterval(agentInfoSendRefreshIntervalMs)
+ .sendInterval(agentInfoSendRetryIntervalMs)
+ .build();
+ try {
+ agentInfoSender.start();
+ Thread.sleep(agentInfoSendRetryIntervalMs);
+ successServerAcceptor.close();
+ // wait till agent reconnects
+ failServerAcceptor = createServerAcceptor(failServerListener);
+ agentReconnectLatch.await();
+ Thread.sleep(agentInfoSendRefreshIntervalMs);
+ } finally {
+ closeAll(failServerAcceptor, agentInfoSender, pinpointClient, socketFactory);
+ }
+ assertEquals(1, successCount.get());
+ assertEquals(expectedTries, requestCount.get());
+ }
+
@Test
public void agentInfoShouldBeSentOnlyOnceEvenAfterReconnect() throws InterruptedException {
final AtomicInteger requestCount = new AtomicInteger();
final AtomicInteger successCount = new AtomicInteger();
- final long agentInfoSendRetryIntervalMs = 1000L;
+ final long agentInfoSendRetryIntervalMs = 100L;
+ final int maxTryCountPerAttempt = Integer.MAX_VALUE;
ResponseServerMessageListener serverListener = new ResponseServerMessageListener(requestCount, successCount);
@@ -121,30 +195,33 @@ public void agentInfoShouldBeSentOnlyOnceEvenAfterReconnect() throws Interrupted
PinpointClient pinpointClient = ClientFactoryUtils.createPinpointClient(HOST, PORT, clientFactory);
TcpDataSender dataSender = new TcpDataSender(pinpointClient);
- AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo());
+ AgentInfoSender agentInfoSender = new AgentInfoSender.Builder(dataSender, getAgentInfo())
+ .sendInterval(agentInfoSendRetryIntervalMs)
+ .maxTryPerAttempt(maxTryCountPerAttempt)
+ .build();
try {
agentInfoSender.start();
- createAndDeleteServer(serverListener, 5000L);
- Thread.sleep(1000L);
- createAndDeleteServer(serverListener, 5000L);
- Thread.sleep(1000L);
- createAndDeleteServer(serverListener, 5000L);
+ createAndDeleteServer(serverListener, 1000L);
+ Thread.sleep(500L);
+ createAndDeleteServer(serverListener, 1000L);
+ Thread.sleep(500L);
+ createAndDeleteServer(serverListener, 1000L);
} finally {
closeAll(null, agentInfoSender, pinpointClient, clientFactory);
}
- assertEquals(1, requestCount.get());
assertEquals(1, successCount.get());
}
@Test
- public void agentInfoShouldKeepRetrying() throws InterruptedException {
+ public void agentInfoShouldKeepRefreshing() throws InterruptedException {
final AtomicInteger requestCount = new AtomicInteger();
final AtomicInteger successCount = new AtomicInteger();
- final long agentInfoSendRetryIntervalMs = 1000L;
- final long minimumAgentInfoSendRetryCount = 10;
+ final long agentInfoSendRetryIntervalMs = 100L;
+ final long agentInfoSendRefreshIntervalMs = 1000L;
+ final int expectedRefreshCount = 5;
- ResponseServerMessageListener serverListener = new ResponseServerMessageListener(requestCount, successCount, Integer.MAX_VALUE);
+ ResponseServerMessageListener serverListener = new ResponseServerMessageListener(requestCount, successCount);
PinpointServerAcceptor serverAcceptor = createServerAcceptor(serverListener);
@@ -152,18 +229,21 @@ public void agentInfoShouldKeepRetrying() throws InterruptedException {
PinpointClient pinpointClient = ClientFactoryUtils.createPinpointClient(HOST, PORT, socketFactory);
TcpDataSender dataSender = new TcpDataSender(pinpointClient);
- AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo());
+ AgentInfoSender agentInfoSender = new AgentInfoSender.Builder(dataSender, getAgentInfo())
+ .refreshInterval(agentInfoSendRefreshIntervalMs)
+ .sendInterval(agentInfoSendRetryIntervalMs)
+ .build();
try {
agentInfoSender.start();
- Thread.sleep(agentInfoSendRetryIntervalMs * minimumAgentInfoSendRetryCount);
+ Thread.sleep(agentInfoSendRefreshIntervalMs * expectedRefreshCount);
} finally {
closeAll(serverAcceptor, agentInfoSender, pinpointClient, socketFactory);
}
- assertTrue(requestCount.get() >= minimumAgentInfoSendRetryCount);
- assertEquals(0, successCount.get());
+ assertTrue(requestCount.get() >= expectedRefreshCount);
+ assertTrue(successCount.get() >= expectedRefreshCount);
}
-
+
@Test
public void serverMetaDataShouldBeSentOnPublish() throws InterruptedException {
// Given
@@ -178,14 +258,14 @@ public void serverMetaDataShouldBeSentOnPublish() throws InterruptedException {
PinpointClientFactory clientFactory = createPinpointClientFactory();
PinpointClient pinpointClient = ClientFactoryUtils.createPinpointClient(HOST, PORT, clientFactory);
- TcpDataSender sender = new TcpDataSender(pinpointClient);
- AgentInfoSender agentInfoSender = new AgentInfoSender(sender, agentInfoSendRetryIntervalMs, getAgentInfo());
+ TcpDataSender dataSender = new TcpDataSender(pinpointClient);
+ AgentInfoSender agentInfoSender = new AgentInfoSender.Builder(dataSender, getAgentInfo()).sendInterval(agentInfoSendRetryIntervalMs).build();
final List<ServerMetaData> serverMetaDataObjects = new ArrayList<ServerMetaData>();
- serverMetaDataObjects.add(new DefaultServerMetaData("server1", Collections.<String>emptyList(), Collections.<Integer, String>emptyMap(), Collections.<ServiceInfo>emptyList()));
- serverMetaDataObjects.add(new DefaultServerMetaData("server2", Collections.<String>emptyList(), Collections.<Integer, String>emptyMap(), Collections.<ServiceInfo>emptyList()));
- serverMetaDataObjects.add(new DefaultServerMetaData("server3", Collections.<String>emptyList(), Collections.<Integer, String>emptyMap(), Collections.<ServiceInfo>emptyList()));
- serverMetaDataObjects.add(new DefaultServerMetaData("server4", Collections.<String>emptyList(), Collections.<Integer, String>emptyMap(), Collections.<ServiceInfo>emptyList()));
- serverMetaDataObjects.add(new DefaultServerMetaData("server5", Collections.<String>emptyList(), Collections.<Integer, String>emptyMap(), Collections.<ServiceInfo>emptyList()));
+ serverMetaDataObjects.add(new DefaultServerMetaData("server1", Collections.<String> emptyList(), Collections.<Integer, String> emptyMap(), Collections.<ServiceInfo> emptyList()));
+ serverMetaDataObjects.add(new DefaultServerMetaData("server2", Collections.<String> emptyList(), Collections.<Integer, String> emptyMap(), Collections.<ServiceInfo> emptyList()));
+ serverMetaDataObjects.add(new DefaultServerMetaData("server3", Collections.<String> emptyList(), Collections.<Integer, String> emptyMap(), Collections.<ServiceInfo> emptyList()));
+ serverMetaDataObjects.add(new DefaultServerMetaData("server4", Collections.<String> emptyList(), Collections.<Integer, String> emptyMap(), Collections.<ServiceInfo> emptyList()));
+ serverMetaDataObjects.add(new DefaultServerMetaData("server5", Collections.<String> emptyList(), Collections.<Integer, String> emptyMap(), Collections.<ServiceInfo> emptyList()));
// When
try {
for (ServerMetaData serverMetaData : serverMetaDataObjects) {
@@ -199,7 +279,7 @@ public void serverMetaDataShouldBeSentOnPublish() throws InterruptedException {
assertEquals(5, requestCount.get());
assertEquals(5, successCount.get());
}
-
+
@Test
public void serverMetaDataCouldBePublishedFromMultipleThreads() throws InterruptedException {
// Given
@@ -220,9 +300,9 @@ public void serverMetaDataCouldBePublishedFromMultipleThreads() throws Interrupt
PinpointClientFactory clientFactory = createPinpointClientFactory();
PinpointClient pinpointClient = ClientFactoryUtils.createPinpointClient(HOST, PORT, clientFactory);
- TcpDataSender sender = new TcpDataSender(pinpointClient);
- AgentInfoSender agentInfoSender = new AgentInfoSender(sender, agentInfoSendRetryIntervalMs, getAgentInfo());
- final ServerMetaDataHolder metaDataContext = new DefaultServerMetaDataHolder(Collections.<String>emptyList());
+ TcpDataSender dataSender = new TcpDataSender(pinpointClient);
+ AgentInfoSender agentInfoSender = new AgentInfoSender.Builder(dataSender, getAgentInfo()).sendInterval(agentInfoSendRetryIntervalMs).build();
+ final ServerMetaDataHolder metaDataContext = new DefaultServerMetaDataHolder(Collections.<String> emptyList());
metaDataContext.addListener(agentInfoSender);
// When
for (int i = 0; i < threadCount; ++i) {
@@ -263,7 +343,8 @@ public void reconnectionStressTest() throws InterruptedException {
final long stressTestTime = 60 * 1000L;
final int randomMaxTime = 3000;
final long agentInfoSendRetryIntervalMs = 1000L;
- final int expectedTriesUntilSuccess = (int)stressTestTime / (randomMaxTime * 2);
+ final int maxTryPerAttempt = Integer.MAX_VALUE;
+ final int expectedTriesUntilSuccess = (int) stressTestTime / (randomMaxTime * 2);
ResponseServerMessageListener serverListener = new ResponseServerMessageListener(requestCount, successCount, expectedTriesUntilSuccess);
@@ -271,7 +352,10 @@ public void reconnectionStressTest() throws InterruptedException {
PinpointClient pinpointClient = ClientFactoryUtils.createPinpointClient(HOST, PORT, clientFactory);
TcpDataSender dataSender = new TcpDataSender(pinpointClient);
- AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo());
+ AgentInfoSender agentInfoSender = new AgentInfoSender.Builder(dataSender, getAgentInfo())
+ .sendInterval(agentInfoSendRetryIntervalMs)
+ .maxTryPerAttempt(maxTryPerAttempt)
+ .build();
long startTime = System.currentTimeMillis();
@@ -393,11 +477,11 @@ public void handlePing(PingPacket pingPacket, PinpointServer pinpointServer) {
logger.info("ping received {} {} ", pingPacket, pinpointServer);
}
}
-
+
private PinpointClientFactory createPinpointClientFactory() {
PinpointClientFactory clientFactory = new PinpointClientFactory();
clientFactory.setTimeoutMillis(1000 * 5);
- clientFactory.setProperties(Collections.<String, Object>emptyMap());
+ clientFactory.setProperties(Collections.<String, Object> emptyMap());
return clientFactory;
}
| train | train | "2015-11-05T08:47:42" | "2015-10-27T06:03:33Z" | Xylus | test |
pinpoint-apm/pinpoint/1171_1173 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1171 | pinpoint-apm/pinpoint/1173 | [
"keyword_pr_to_issue"
] | cd182945f1b1bb1e6be6091869bbd7ba64b3c504 | 7d88207d86e84fd4a7c2695307714622a95bdd17 | [] | [] | "2015-11-11T05:56:03Z" | [
"bug"
] | Fixed a side effect of Arcus interceptor | Side effect : faild to failover.
Root cause : Unnecessary reverse DNS lookup
Bug fix : Avoid DNS lookup API.
- ApiInterceptor.java
- FutureGetInterceptor.java
``` java
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
...
final Operation op = (Operation) getOperation.invoke(target);
if (op != null) {
MemcachedNode handlingNode = op.getHandlingNode();
if (handlingNode != null) {
SocketAddress socketAddress = handlingNode.getSocketAddress();
if (socketAddress instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) socketAddress;
// ROOT Cause : Unnecessary DNS look -> InetSocketAddress.getHostName()
trace.recordEndPoint(address.getHostName() + ":" + address.getPort());
}
} else {
logger.info("no handling node");
}
} else {
logger.info("operation not found");
}
}
```
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptor.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptor.java"
] | [] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptor.java
index e9d33e86a0ee..d90c717676c6 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptor.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptor.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.profiler.modifier.arcus.interceptor;
+import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.Future;
@@ -61,11 +62,12 @@ public void doInAfterTrace(RecordableTrace trace, Object target, Object[] args,
if (result instanceof Future && !(result instanceof FrontCacheGetFuture)) {
final Operation op = getOperation(result);
if (op != null) {
- MemcachedNode handlingNode = op.getHandlingNode();
- SocketAddress socketAddress = handlingNode.getSocketAddress();
- if (socketAddress instanceof InetSocketAddress) {
- InetSocketAddress address = (InetSocketAddress) socketAddress;
- trace.recordEndPoint(address.getHostName() + ":" + address.getPort());
+ final MemcachedNode handlingNode = op.getHandlingNode();
+ if (handlingNode != null) {
+ final String endPoint = getEndPoint(handlingNode);
+ if (endPoint != null) {
+ trace.recordEndPoint(endPoint);
+ }
}
} else {
logger.info("operation not found");
@@ -85,6 +87,40 @@ public void doInAfterTrace(RecordableTrace trace, Object target, Object[] args,
trace.markAfterTime();
}
+ private String getEndPoint(MemcachedNode handlingNode) {
+ // TODO duplicated code : ApiInterceptor, FutureGetInterceptor
+ final SocketAddress socketAddress = handlingNode.getSocketAddress();
+ if (socketAddress instanceof InetSocketAddress) {
+ final InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
+ final String hostAddress = getHostAddress(inetSocketAddress);
+ if (hostAddress == null) {
+ // TODO return "Unknown Host"; ?
+ logger.debug("hostAddress is null");
+ return null;
+ }
+ return hostAddress + ":" + inetSocketAddress.getPort();
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("invalid socketAddress:{}", socketAddress);
+ }
+ return null;
+ }
+ }
+
+ private String getHostAddress(InetSocketAddress inetSocketAddress) {
+ if (inetSocketAddress == null) {
+ return null;
+ }
+ // TODO JDK 1.7 InetSocketAddress.getHostString();
+ // Warning : Avoid unnecessary DNS lookup (warning:InetSocketAddress.getHostName())
+ final InetAddress inetAddress = inetSocketAddress.getAddress();
+ if (inetAddress == null) {
+ return null;
+ }
+ return inetAddress.getHostAddress();
+ }
+
private Operation getOperation(Object result) {
// __operation -> ObjectTraceValue1.class
final Object operationObject = ObjectTraceValue1Utils.__getTraceObject1(result, null);
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptor.java
index 6e5579a9aef0..1d0ca160a8d0 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptor.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptor.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.profiler.modifier.arcus.interceptor;
+import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
@@ -77,12 +78,11 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
// find the target node
final Operation op = getOperation(target);
if (op != null) {
- MemcachedNode handlingNode = op.getHandlingNode();
+ final MemcachedNode handlingNode = op.getHandlingNode();
if (handlingNode != null) {
- SocketAddress socketAddress = handlingNode.getSocketAddress();
- if (socketAddress instanceof InetSocketAddress) {
- InetSocketAddress address = (InetSocketAddress) socketAddress;
- trace.recordEndPoint(address.getHostName() + ":" + address.getPort());
+ final String endPoint = getEndPoint(handlingNode);
+ if (endPoint != null) {
+ trace.recordEndPoint(endPoint);
}
trace.recordException(op.getException());
} else {
@@ -113,6 +113,40 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
}
}
+ private String getEndPoint(MemcachedNode handlingNode) {
+ // TODO duplicated code : ApiInterceptor, FutureGetInterceptor
+ final SocketAddress socketAddress = handlingNode.getSocketAddress();
+ if (socketAddress instanceof InetSocketAddress) {
+ final InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
+ final String hostAddress = getHostAddress(inetSocketAddress);
+ if (hostAddress == null) {
+ // TODO return "Unknown Host";
+ logger.debug("hostAddress is null");
+ return null;
+ }
+ return hostAddress + ":" + inetSocketAddress.getPort();
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("invalid socketAddress:{}", socketAddress);
+ }
+ return null;
+ }
+ }
+
+ private String getHostAddress(InetSocketAddress inetSocketAddress) {
+ if (inetSocketAddress == null) {
+ return null;
+ }
+ // TODO JDK 1.7 InetSocketAddress.getHostString();
+ // Warning : Avoid unnecessary DNS lookup (warning:InetSocketAddress.getHostName())
+ final InetAddress inetAddress = inetSocketAddress.getAddress();
+ if (inetAddress == null) {
+ return null;
+ }
+ return inetAddress.getHostAddress();
+ }
+
// __operation -> ObjectTraceValue1.class
private Operation getOperation(Object target) {
final Object operationObject = ObjectTraceValue1Utils.__getTraceObject1(target, null);
| null | train | train | "2015-10-20T04:42:20" | "2015-11-11T05:49:57Z" | emeroad | test |
pinpoint-apm/pinpoint/1174_1175 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1174 | pinpoint-apm/pinpoint/1175 | [
"keyword_pr_to_issue"
] | 8eca78ba09f0411bc95812896e2b783104205da4 | 22a5b4f149788f798f50623f4f7f80a802c56c05 | [] | [] | "2015-11-11T06:13:02Z" | [
"bug"
] | 1.5.0 Porting : Fixed a side effect of Arcus interceptor #1171 | **1.5.0 porting** #1171
Side effect : faild to failover.
Root cause : Unnecessary reverse DNS lookup
Bug fix : Avoid DNS lookup API.
- ApiInterceptor.java
- FutureGetInterceptor.java
``` java
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
...
final Operation op = (Operation) getOperation.invoke(target);
if (op != null) {
MemcachedNode handlingNode = op.getHandlingNode();
if (handlingNode != null) {
SocketAddress socketAddress = handlingNode.getSocketAddress();
if (socketAddress instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) socketAddress;
// ROOT Cause : Unnecessary DNS look -> InetSocketAddress.getHostName()
trace.recordEndPoint(address.getHostName() + ":" + address.getPort());
}
} else {
logger.info("no handling node");
}
} else {
logger.info("operation not found");
}
}
```
| [
"plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java",
"plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java"
] | [
"plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java",
"plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java"
] | [] | diff --git a/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java b/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java
index 0a1d7f07315a..f1567e99d221 100644
--- a/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java
+++ b/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java
@@ -14,6 +14,7 @@
*/
package com.navercorp.pinpoint.plugin.arcus.interceptor;
+import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.Future;
@@ -126,15 +127,14 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
// find the target node
if (result instanceof Future && result instanceof OperationAccessor) {
- Operation op = ((OperationAccessor)result)._$PINPOINT$_getOperation();
-
+ final Operation op = ((OperationAccessor)result)._$PINPOINT$_getOperation();
if (op != null) {
- MemcachedNode handlingNode = op.getHandlingNode();
- SocketAddress socketAddress = handlingNode.getSocketAddress();
-
- if (socketAddress instanceof InetSocketAddress) {
- InetSocketAddress address = (InetSocketAddress) socketAddress;
- recorder.recordEndPoint(address.getHostName() + ":" + address.getPort());
+ final MemcachedNode handlingNode = op.getHandlingNode();
+ if (handlingNode != null) {
+ final String endPoint = getEndPoint(handlingNode);
+ if (endPoint != null) {
+ recorder.recordEndPoint(endPoint);
+ }
}
} else {
logger.info("operation not found");
@@ -179,6 +179,40 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
}
}
+ private String getEndPoint(MemcachedNode handlingNode) {
+ // TODO duplicated code : ApiInterceptor, FutureGetInterceptor
+ final SocketAddress socketAddress = handlingNode.getSocketAddress();
+ if (socketAddress instanceof InetSocketAddress) {
+ final InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
+ final String hostAddress = getHostAddress(inetSocketAddress);
+ if (hostAddress == null) {
+ // TODO return "Unknown Host"; ?
+ logger.debug("hostAddress is null");
+ return null;
+ }
+ return hostAddress + ":" + inetSocketAddress.getPort();
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("invalid socketAddress:{}", socketAddress);
+ }
+ return null;
+ }
+ }
+
+ private String getHostAddress(InetSocketAddress inetSocketAddress) {
+ if (inetSocketAddress == null) {
+ return null;
+ }
+ // TODO JDK 1.7 InetSocketAddress.getHostString();
+ // Warning : Avoid unnecessary DNS lookup (warning:InetSocketAddress.getHostName())
+ final InetAddress inetAddress = inetSocketAddress.getAddress();
+ if (inetAddress == null) {
+ return null;
+ }
+ return inetAddress.getHostAddress();
+ }
+
private boolean isAsynchronousInvocation(final Object target, final Object[] args, Object result, Throwable throwable) {
if (throwable != null || result == null) {
return false;
diff --git a/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java b/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java
index 57569a165c77..3ba470e5a60d 100644
--- a/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java
+++ b/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java
@@ -14,6 +14,7 @@
*/
package com.navercorp.pinpoint.plugin.arcus.interceptor;
+import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
@@ -64,13 +65,14 @@ protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[
}
recorder.recordException(op.getException());
- MemcachedNode handlingNode = op.getHandlingNode();
+
+ final MemcachedNode handlingNode = op.getHandlingNode();
if (handlingNode != null) {
- SocketAddress socketAddress = handlingNode.getSocketAddress();
- if (socketAddress instanceof InetSocketAddress) {
- InetSocketAddress address = (InetSocketAddress) socketAddress;
- recorder.recordEndPoint(address.getHostName() + ":" + address.getPort());
+ final String endPoint = getEndPoint(handlingNode);
+ if (endPoint != null) {
+ recorder.recordEndPoint(endPoint);
}
+ recorder.recordException(op.getException());
} else {
logger.info("no handling node");
}
@@ -84,4 +86,38 @@ protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[
}
}
}
+
+ private String getEndPoint(MemcachedNode handlingNode) {
+ // TODO duplicated code : ApiInterceptor, FutureGetInterceptor
+ final SocketAddress socketAddress = handlingNode.getSocketAddress();
+ if (socketAddress instanceof InetSocketAddress) {
+ final InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
+ final String hostAddress = getHostAddress(inetSocketAddress);
+ if (hostAddress == null) {
+ // TODO return "Unknown Host";
+ logger.debug("hostAddress is null");
+ return null;
+ }
+ return hostAddress + ":" + inetSocketAddress.getPort();
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("invalid socketAddress:{}", socketAddress);
+ }
+ return null;
+ }
+ }
+
+ private String getHostAddress(InetSocketAddress inetSocketAddress) {
+ if (inetSocketAddress == null) {
+ return null;
+ }
+ // TODO JDK 1.7 InetSocketAddress.getHostString();
+ // Warning : Avoid unnecessary DNS lookup (warning:InetSocketAddress.getHostName())
+ final InetAddress inetAddress = inetSocketAddress.getAddress();
+ if (inetAddress == null) {
+ return null;
+ }
+ return inetAddress.getHostAddress();
+ }
}
\ No newline at end of file
| null | train | train | "2015-11-10T09:12:51" | "2015-11-11T05:58:24Z" | emeroad | test |
pinpoint-apm/pinpoint/1171_1175 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1171 | pinpoint-apm/pinpoint/1175 | [
"keyword_pr_to_issue"
] | 8eca78ba09f0411bc95812896e2b783104205da4 | 22a5b4f149788f798f50623f4f7f80a802c56c05 | [] | [] | "2015-11-11T06:13:02Z" | [
"bug"
] | Fixed a side effect of Arcus interceptor | Side effect : faild to failover.
Root cause : Unnecessary reverse DNS lookup
Bug fix : Avoid DNS lookup API.
- ApiInterceptor.java
- FutureGetInterceptor.java
``` java
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
...
final Operation op = (Operation) getOperation.invoke(target);
if (op != null) {
MemcachedNode handlingNode = op.getHandlingNode();
if (handlingNode != null) {
SocketAddress socketAddress = handlingNode.getSocketAddress();
if (socketAddress instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) socketAddress;
// ROOT Cause : Unnecessary DNS look -> InetSocketAddress.getHostName()
trace.recordEndPoint(address.getHostName() + ":" + address.getPort());
}
} else {
logger.info("no handling node");
}
} else {
logger.info("operation not found");
}
}
```
| [
"plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java",
"plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java"
] | [
"plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java",
"plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java"
] | [] | diff --git a/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java b/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java
index 0a1d7f07315a..f1567e99d221 100644
--- a/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java
+++ b/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/ApiInterceptor.java
@@ -14,6 +14,7 @@
*/
package com.navercorp.pinpoint.plugin.arcus.interceptor;
+import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.Future;
@@ -126,15 +127,14 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
// find the target node
if (result instanceof Future && result instanceof OperationAccessor) {
- Operation op = ((OperationAccessor)result)._$PINPOINT$_getOperation();
-
+ final Operation op = ((OperationAccessor)result)._$PINPOINT$_getOperation();
if (op != null) {
- MemcachedNode handlingNode = op.getHandlingNode();
- SocketAddress socketAddress = handlingNode.getSocketAddress();
-
- if (socketAddress instanceof InetSocketAddress) {
- InetSocketAddress address = (InetSocketAddress) socketAddress;
- recorder.recordEndPoint(address.getHostName() + ":" + address.getPort());
+ final MemcachedNode handlingNode = op.getHandlingNode();
+ if (handlingNode != null) {
+ final String endPoint = getEndPoint(handlingNode);
+ if (endPoint != null) {
+ recorder.recordEndPoint(endPoint);
+ }
}
} else {
logger.info("operation not found");
@@ -179,6 +179,40 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
}
}
+ private String getEndPoint(MemcachedNode handlingNode) {
+ // TODO duplicated code : ApiInterceptor, FutureGetInterceptor
+ final SocketAddress socketAddress = handlingNode.getSocketAddress();
+ if (socketAddress instanceof InetSocketAddress) {
+ final InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
+ final String hostAddress = getHostAddress(inetSocketAddress);
+ if (hostAddress == null) {
+ // TODO return "Unknown Host"; ?
+ logger.debug("hostAddress is null");
+ return null;
+ }
+ return hostAddress + ":" + inetSocketAddress.getPort();
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("invalid socketAddress:{}", socketAddress);
+ }
+ return null;
+ }
+ }
+
+ private String getHostAddress(InetSocketAddress inetSocketAddress) {
+ if (inetSocketAddress == null) {
+ return null;
+ }
+ // TODO JDK 1.7 InetSocketAddress.getHostString();
+ // Warning : Avoid unnecessary DNS lookup (warning:InetSocketAddress.getHostName())
+ final InetAddress inetAddress = inetSocketAddress.getAddress();
+ if (inetAddress == null) {
+ return null;
+ }
+ return inetAddress.getHostAddress();
+ }
+
private boolean isAsynchronousInvocation(final Object target, final Object[] args, Object result, Throwable throwable) {
if (throwable != null || result == null) {
return false;
diff --git a/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java b/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java
index 57569a165c77..3ba470e5a60d 100644
--- a/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java
+++ b/plugins/arcus/src/main/java/com/navercorp/pinpoint/plugin/arcus/interceptor/FutureGetInterceptor.java
@@ -14,6 +14,7 @@
*/
package com.navercorp.pinpoint.plugin.arcus.interceptor;
+import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
@@ -64,13 +65,14 @@ protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[
}
recorder.recordException(op.getException());
- MemcachedNode handlingNode = op.getHandlingNode();
+
+ final MemcachedNode handlingNode = op.getHandlingNode();
if (handlingNode != null) {
- SocketAddress socketAddress = handlingNode.getSocketAddress();
- if (socketAddress instanceof InetSocketAddress) {
- InetSocketAddress address = (InetSocketAddress) socketAddress;
- recorder.recordEndPoint(address.getHostName() + ":" + address.getPort());
+ final String endPoint = getEndPoint(handlingNode);
+ if (endPoint != null) {
+ recorder.recordEndPoint(endPoint);
}
+ recorder.recordException(op.getException());
} else {
logger.info("no handling node");
}
@@ -84,4 +86,38 @@ protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[
}
}
}
+
+ private String getEndPoint(MemcachedNode handlingNode) {
+ // TODO duplicated code : ApiInterceptor, FutureGetInterceptor
+ final SocketAddress socketAddress = handlingNode.getSocketAddress();
+ if (socketAddress instanceof InetSocketAddress) {
+ final InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
+ final String hostAddress = getHostAddress(inetSocketAddress);
+ if (hostAddress == null) {
+ // TODO return "Unknown Host";
+ logger.debug("hostAddress is null");
+ return null;
+ }
+ return hostAddress + ":" + inetSocketAddress.getPort();
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("invalid socketAddress:{}", socketAddress);
+ }
+ return null;
+ }
+ }
+
+ private String getHostAddress(InetSocketAddress inetSocketAddress) {
+ if (inetSocketAddress == null) {
+ return null;
+ }
+ // TODO JDK 1.7 InetSocketAddress.getHostString();
+ // Warning : Avoid unnecessary DNS lookup (warning:InetSocketAddress.getHostName())
+ final InetAddress inetAddress = inetSocketAddress.getAddress();
+ if (inetAddress == null) {
+ return null;
+ }
+ return inetAddress.getHostAddress();
+ }
}
\ No newline at end of file
| null | train | train | "2015-11-10T09:12:51" | "2015-11-11T05:49:57Z" | emeroad | test |
pinpoint-apm/pinpoint/1217_1218 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1217 | pinpoint-apm/pinpoint/1218 | [
"keyword_pr_to_issue"
] | 4e00b1d227be734b3dd20f88c9d8152d570aeeee | e478c0af99862910693195c83eaba6d7b52dcd8a | [] | [] | "2015-11-18T05:32:39Z" | [
"enhancement",
"module:plugin"
] | Add configuration for tracing request parameters received by Tomcat | HTTP request parameters may contain sensitive information.
There needs to be configuration to enable/disable tracing request parameters received by Tomcat.
| [
"agent/src/main/resources/pinpoint.config",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardHostValveInvokeInterceptor.java"
] | [
"agent/src/main/resources/pinpoint.config",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardHostValveInvokeInterceptor.java"
] | [] | diff --git a/agent/src/main/resources/pinpoint.config b/agent/src/main/resources/pinpoint.config
index 25e075431723..57d19c34319f 100644
--- a/agent/src/main/resources/pinpoint.config
+++ b/agent/src/main/resources/pinpoint.config
@@ -98,6 +98,7 @@ profiler.user.include=
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
+profiler.tomcat.tracerequestparam=true
# original IP address header
# https://en.wikipedia.org/wiki/X-Forwarded-For
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
index 66edc7e2b709..0d62daa431f8 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
@@ -112,6 +112,7 @@ public static ProfilerConfig load(String pinpointConfigFileName) throws IOExcept
private int maxSqlBindValueSize = 1024;
private boolean tomcatHidePinpointHeader = true;
+ private boolean tomcatTraceRequestParam = true;
private Filter<String> tomcatExcludeUrlFilter = new SkipFilter<String>();
private String tomcatRealIpHeader;
private String tomcatRealIpEmptyValue;
@@ -325,6 +326,11 @@ public boolean isTomcatHidePinpointHeader() {
return tomcatHidePinpointHeader;
}
+ @Override
+ public boolean isTomcatTraceRequestParam() {
+ return tomcatTraceRequestParam;
+ }
+
@Override
public Filter<String> getTomcatExcludeUrlFilter() {
return tomcatExcludeUrlFilter;
@@ -560,6 +566,7 @@ void readPropertyValues() {
this.traceSqlBindValue = readBoolean("profiler.jdbc.tracesqlbindvalue", false);
this.tomcatHidePinpointHeader = readBoolean("profiler.tomcat.hidepinpointheader", true);
+ this.tomcatTraceRequestParam = readBoolean("profiler.tomcat.tracerequestparam", true);
final String tomcatExcludeURL = readString("profiler.tomcat.excludeurl", "");
if (!tomcatExcludeURL.isEmpty()) {
this.tomcatExcludeUrlFilter = new ExcludeUrlFilter(tomcatExcludeURL);
@@ -785,6 +792,8 @@ public String toString() {
builder.append(maxSqlBindValueSize);
builder.append(", tomcatHidePinpointHeader=");
builder.append(tomcatHidePinpointHeader);
+ builder.append(", tomcatTraceRequestParam=");
+ builder.append(tomcatTraceRequestParam);
builder.append(", tomcatExcludeUrlFilter=");
builder.append(tomcatExcludeUrlFilter);
builder.append(", tomcatExcludeProfileMethodFilter=");
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java
index 75e44cf80abe..8806047ead0d 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java
@@ -77,6 +77,8 @@ public interface ProfilerConfig {
boolean isTomcatHidePinpointHeader();
+ boolean isTomcatTraceRequestParam();
+
Filter<String> getTomcatExcludeUrlFilter();
String getTomcatRealIpHeader();
diff --git a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardHostValveInvokeInterceptor.java b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardHostValveInvokeInterceptor.java
index 3321ba89de8d..548ac2028a13 100644
--- a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardHostValveInvokeInterceptor.java
+++ b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardHostValveInvokeInterceptor.java
@@ -52,31 +52,32 @@ public class StandardHostValveInvokeInterceptor implements AroundInterceptor {
private final boolean isDebug = logger.isDebugEnabled();
private final boolean isTrace = logger.isTraceEnabled();
+ private final boolean isTraceRequestParam;
+ private final Filter<String> excludeUrlFilter;
+ private final Filter<String> excludeProfileMethodFilter;
+ private final RemoteAddressResolver<HttpServletRequest> remoteAddressResolver;
+
private MethodDescriptor methodDescriptor;
private TraceContext traceContext;
- private Filter<String> excludeUrlFilter;
- private Filter<String> excludeProfileMethodFilter;
-
- private RemoteAddressResolver<HttpServletRequest> remoteAddressResolver;
-
public StandardHostValveInvokeInterceptor(TraceContext traceContext, MethodDescriptor descriptor, Filter<String> excludeFilter) {
this.traceContext = traceContext;
this.methodDescriptor = descriptor;
this.excludeUrlFilter = excludeFilter;
- this.excludeProfileMethodFilter = traceContext.getProfilerConfig().getTomcatExcludeProfileMethodFilter();
-
- traceContext.cacheApi(SERVLET_ASYNCHRONOUS_API_TAG);
- traceContext.cacheApi(SERVLET_SYNCHRONOUS_API_TAG);
ProfilerConfig profilerConfig = traceContext.getProfilerConfig();
final String proxyIpHeader = profilerConfig.getTomcatRealIpHeader();
if (proxyIpHeader == null || proxyIpHeader.isEmpty()) {
- remoteAddressResolver = new Bypass<HttpServletRequest>();
+ this.remoteAddressResolver = new Bypass<HttpServletRequest>();
} else {
final String tomcatRealIpEmptyValue = profilerConfig.getTomcatRealIpEmptyValue();
- remoteAddressResolver = new RealIpHeaderResolver<HttpServletRequest>(proxyIpHeader, tomcatRealIpEmptyValue);
+ this.remoteAddressResolver = new RealIpHeaderResolver<HttpServletRequest>(proxyIpHeader, tomcatRealIpEmptyValue);
}
+ this.isTraceRequestParam = profilerConfig.isTomcatTraceRequestParam();
+ this.excludeProfileMethodFilter = profilerConfig.getTomcatExcludeProfileMethodFilter();
+
+ traceContext.cacheApi(SERVLET_ASYNCHRONOUS_API_TAG);
+ traceContext.cacheApi(SERVLET_SYNCHRONOUS_API_TAG);
}
@Override
@@ -115,7 +116,7 @@ public String resolve(T servletRequest) {
public static class RealIpHeaderResolver<T extends HttpServletRequest> implements RemoteAddressResolver<T> {
public static final String X_FORWARDED_FOR = "x-forwarded-for";
- public static final String X_REAL_IP = "x-real-ip";
+ public static final String X_REAL_IP = "x-real-ip";
public static final String UNKNOWN = "unknown";
private final String realIpHeaderName;
@@ -200,11 +201,11 @@ private Trace createTrace(Object target, Object[] args) {
recordRootSpan(recorder, request);
setTraceMetadata(request, trace);
if (isDebug) {
- logger.debug("TraceID exist. continue trace. traceId:{}, requestUrl:{}, remoteAddr:{}", new Object[] { traceId, request.getRequestURI(), request.getRemoteAddr() });
+ logger.debug("TraceID exist. continue trace. traceId:{}, requestUrl:{}, remoteAddr:{}", new Object[]{traceId, request.getRequestURI(), request.getRemoteAddr()});
}
} else {
if (isDebug) {
- logger.debug("TraceID exist. camSampled is false. skip trace. traceId:{}, requestUrl:{}, remoteAddr:{}", new Object[] { traceId, request.getRequestURI(), request.getRemoteAddr() });
+ logger.debug("TraceID exist. camSampled is false. skip trace. traceId:{}, requestUrl:{}, remoteAddr:{}", new Object[]{traceId, request.getRequestURI(), request.getRemoteAddr()});
}
}
return trace;
@@ -228,7 +229,7 @@ private Trace createTrace(Object target, Object[] args) {
private void setTraceMetadata(final Request request, final Trace trace) {
if (request instanceof TraceAccessor) {
- ((TraceAccessor)request)._$PINPOINT$_setTrace(trace);
+ ((TraceAccessor) request)._$PINPOINT$_setTrace(trace);
}
}
@@ -237,7 +238,7 @@ private Trace getTraceMetadata(final Request request) {
return null;
}
- return ((TraceAccessor)request)._$PINPOINT$_getTrace();
+ return ((TraceAccessor) request)._$PINPOINT$_getTrace();
}
private boolean getAsyncMetadata(final Request request) {
@@ -245,7 +246,7 @@ private boolean getAsyncMetadata(final Request request) {
return false;
}
- return ((AsyncAccessor)request)._$PINPOINT$_isAsync();
+ return ((AsyncAccessor) request)._$PINPOINT$_isAsync();
}
private boolean isAsynchronousProcess(final Request request) {
@@ -267,7 +268,7 @@ private void recordRootSpan(final SpanRecorder recorder, final HttpServletReques
final String endPoint = request.getServerName() + ":" + port;
recorder.recordEndPoint(endPoint);
- final String remoteAddr = remoteAddressResolver.resolve(request);
+ final String remoteAddr = remoteAddressResolver.resolve(request);
recorder.recordRemoteAddress(remoteAddr);
if (!recorder.isRoot()) {
@@ -310,12 +311,14 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
// ------------------------------------------------------
try {
SpanEventRecorder recorder = trace.currentSpanEventRecorder();
- final HttpServletRequest request = (HttpServletRequest) args[0];
- if (!excludeProfileMethodFilter.filter(request.getMethod())) {
- final String parameters = getRequestParameter(request, 64, 512);
- if (parameters != null && parameters.length() > 0) {
- recorder.recordAttribute(AnnotationKey.HTTP_PARAM, parameters);
+ if (this.isTraceRequestParam) {
+ final HttpServletRequest request = (HttpServletRequest) args[0];
+ if (!excludeProfileMethodFilter.filter(request.getMethod())) {
+ final String parameters = getRequestParameter(request, 64, 512);
+ if (parameters != null && parameters.length() > 0) {
+ recorder.recordAttribute(AnnotationKey.HTTP_PARAM, parameters);
+ }
}
}
| null | train | train | "2015-11-18T03:55:08" | "2015-11-18T05:27:38Z" | Xylus | test |
pinpoint-apm/pinpoint/1244_1247 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1244 | pinpoint-apm/pinpoint/1247 | [
"keyword_pr_to_issue"
] | 197ac8ba08da4eec9aeac5339f18b88632a58aaa | 174b1800f63d8cafd9b2ff10ffd7db83a9b8c98f | [] | [] | "2015-11-23T08:45:58Z" | [
"bug"
] | [PinpiontWeb] fix a ActiveThread concurrency problem | TreeMap of ActiveThreadCountResponseAggregator is not thread safe
- local variable : activeThreadCountWorkerRepository
| [
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
index 749a8cc15438..2b114950fd78 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
@@ -40,6 +40,7 @@
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -59,7 +60,7 @@ public class ActiveThreadCountHandler extends TextWebSocketHandler implements Pi
private final Object lock = new Object();
private final AgentService agentSerivce;
private final List<WebSocketSession> sessionRepository = new CopyOnWriteArrayList<>();
- private final Map<String, PinpointWebSocketResponseAggregator> aggregatorRepository = new HashMap<>();
+ private final Map<String, PinpointWebSocketResponseAggregator> aggregatorRepository = new ConcurrentHashMap<>();
private PinpointWebSocketMessageConverter messageConverter = new PinpointWebSocketMessageConverter();
private static final String DEFAULT_REQUEST_MAPPING = "/agent/activeThread";
| null | train | train | "2015-11-23T09:18:35" | "2015-11-23T07:40:10Z" | emeroad | test |
pinpoint-apm/pinpoint/1271_1272 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1271 | pinpoint-apm/pinpoint/1272 | [
"keyword_pr_to_issue",
"keyword_issue_to_pr"
] | df606e80ff905ae81d51192708ae9e409967c69d | 684077ab5e29cdb33a06bb83d9eac797b2413b36 | [
"fixed via #1272 \n"
] | [] | "2015-11-27T10:35:52Z" | [
"bug"
] | Unsampled Continuation is not collected for transaction metric. | Metric Gauge for TRANSACTION_UNSAMPLED_CONTINUATION is missing.
Unsampled continuation gauge instead uses TRANSACTION_UNSAMPLED_NEW, which is wrong.
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/tps/TransactionMetricCollector.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/tps/TransactionMetricCollector.java"
] | [] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/tps/TransactionMetricCollector.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/tps/TransactionMetricCollector.java
index d505a228f80d..f52520d70384 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/tps/TransactionMetricCollector.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/tps/TransactionMetricCollector.java
@@ -49,7 +49,7 @@ public TransactionMetricCollector(TransactionMetricSet transactionMetricSet) {
this.sampledNewGauge = (Gauge<Long>)MetricMonitorValues.getMetric(metrics, TRANSACTION_SAMPLED_NEW, UNSUPPORTED_GAUGE);
this.sampledContinuationGauge = (Gauge<Long>)MetricMonitorValues.getMetric(metrics, TRANSACTION_SAMPLED_CONTINUATION, UNSUPPORTED_GAUGE);
this.unsampledNewGauge = (Gauge<Long>)MetricMonitorValues.getMetric(metrics, TRANSACTION_UNSAMPLED_NEW, UNSUPPORTED_GAUGE);
- this.unsampledContinuationGuage = (Gauge<Long>)MetricMonitorValues.getMetric(metrics, TRANSACTION_UNSAMPLED_NEW, UNSUPPORTED_GAUGE);
+ this.unsampledContinuationGuage = (Gauge<Long>)MetricMonitorValues.getMetric(metrics, TRANSACTION_UNSAMPLED_CONTINUATION, UNSUPPORTED_GAUGE);
}
@Override
| null | test | train | "2015-11-27T11:12:52" | "2015-11-27T10:27:45Z" | Xylus | test |
pinpoint-apm/pinpoint/1298_1304 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1298 | pinpoint-apm/pinpoint/1304 | [
"keyword_pr_to_issue"
] | d5284f671dd45ece2707238a98bb0daf07ada238 | 8a02cdf915df1a297988a2bb73a4d412ae43fbca | [] | [] | "2015-12-03T06:50:19Z" | [
"bug"
] | fix unsafe resource cleanup of profiler | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/DefaultInterceptorRegistryAdaptor.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/InterceptorRegistry.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/DefaultInterceptorRegistryAdaptor.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/EmptyRegistryAdaptor.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/InterceptorRegistry.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/test/junit4/TestContext.java"
] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java
index 9f072384ecb5..d1525d3d1b77 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java
@@ -23,7 +23,7 @@
/**
* @author emeroad
*/
-public class LoggingInterceptor implements StaticAroundInterceptor, AroundInterceptor {
+public class LoggingInterceptor implements StaticAroundInterceptor, AroundInterceptor, AroundInterceptor0, AroundInterceptor1, AroundInterceptor2, AroundInterceptor3, AroundInterceptor4, AroundInterceptor5, ApiIdAwareAroundInterceptor {
private final Logger logger;
@@ -63,4 +63,72 @@ public static String defaultString(final Object object) {
return String.valueOf(object);
}
+ @Override
+ public void before(Object target, int apiId, Object[] args) {
+ }
+
+ @Override
+ public void after(Object target, int apiId, Object[] args, Object result, Throwable throwable) {
+
+ }
+
+ @Override
+ public void before(Object target) {
+
+ }
+
+ @Override
+ public void after(Object target, Object result, Throwable throwable) {
+
+ }
+
+ @Override
+ public void before(Object target, Object arg0) {
+
+ }
+
+ @Override
+ public void after(Object target, Object arg0, Object result, Throwable throwable) {
+
+ }
+
+ @Override
+ public void before(Object target, Object arg0, Object arg1) {
+
+ }
+
+ @Override
+ public void after(Object target, Object arg0, Object arg1, Object result, Throwable throwable) {
+
+ }
+
+ @Override
+ public void before(Object target, Object arg0, Object arg1, Object arg2) {
+
+ }
+
+ @Override
+ public void after(Object target, Object arg0, Object arg1, Object arg2, Object result, Throwable throwable) {
+
+ }
+
+ @Override
+ public void before(Object target, Object arg0, Object arg1, Object arg2, Object arg3) {
+
+ }
+
+ @Override
+ public void after(Object target, Object arg0, Object arg1, Object arg2, Object arg3, Object result, Throwable throwable) {
+
+ }
+
+ @Override
+ public void before(Object target, Object arg0, Object arg1, Object arg2, Object arg3, Object arg4) {
+
+ }
+
+ @Override
+ public void after(Object target, Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object result, Throwable throwable) {
+
+ }
}
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/DefaultInterceptorRegistryAdaptor.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/DefaultInterceptorRegistryAdaptor.java
index eee307ca0fcb..970b2bc578bc 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/DefaultInterceptorRegistryAdaptor.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/DefaultInterceptorRegistryAdaptor.java
@@ -11,8 +11,6 @@
public final class DefaultInterceptorRegistryAdaptor implements InterceptorRegistryAdaptor {
private static final LoggingInterceptor LOGGING_INTERCEPTOR = new LoggingInterceptor("com.navercorp.pinpoint.profiler.interceptor.LOGGING_INTERCEPTOR");
- public static final InterceptorRegistry REGISTRY = new InterceptorRegistry();
-
private final static int DEFAULT_MAX = 4096;
private final int registrySize;
@@ -52,7 +50,11 @@ private int nextId() {
}
public Interceptor getInterceptor(int key) {
- Interceptor interceptor = this.index.get(key);
- return interceptor == null ? LOGGING_INTERCEPTOR : interceptor;
+ final Interceptor interceptor = this.index.get(key);
+ if (interceptor == null) {
+ return LOGGING_INTERCEPTOR;
+ } else {
+ return interceptor;
+ }
}
}
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/EmptyRegistryAdaptor.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/EmptyRegistryAdaptor.java
new file mode 100644
index 000000000000..c98dbec26cb4
--- /dev/null
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/EmptyRegistryAdaptor.java
@@ -0,0 +1,45 @@
+/*
+ * *
+ * * Copyright 2014 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.bootstrap.interceptor.registry;
+
+import com.navercorp.pinpoint.bootstrap.interceptor.Interceptor;
+import com.navercorp.pinpoint.bootstrap.interceptor.LoggingInterceptor;
+
+/**
+ * @author emeroad
+ */
+public final class EmptyRegistryAdaptor implements InterceptorRegistryAdaptor {
+
+ public static final InterceptorRegistryAdaptor EMPTY = new EmptyRegistryAdaptor();
+
+ private static final LoggingInterceptor LOGGING_INTERCEPTOR = new LoggingInterceptor("com.navercorp.pinpoint.profiler.interceptor.EMPTY");
+
+ public EmptyRegistryAdaptor() {
+ }
+
+
+ @Override
+ public int addInterceptor(Interceptor interceptor) {
+ return -1;
+ }
+
+
+ public Interceptor getInterceptor(int key) {
+ return LOGGING_INTERCEPTOR;
+ }
+}
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/InterceptorRegistry.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/InterceptorRegistry.java
index bd070556817e..e12ef7c61e0d 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/InterceptorRegistry.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/registry/InterceptorRegistry.java
@@ -26,7 +26,7 @@ public final class InterceptorRegistry {
private static final Locker LOCK = new DefaultLocker();
- private static InterceptorRegistryAdaptor REGISTRY;
+ private static InterceptorRegistryAdaptor REGISTRY = EmptyRegistryAdaptor.EMPTY;
public static void bind(final InterceptorRegistryAdaptor interceptorRegistryAdaptor, final Object lock) {
if (interceptorRegistryAdaptor == null) {
@@ -42,7 +42,7 @@ public static void bind(final InterceptorRegistryAdaptor interceptorRegistryAdap
public static void unbind(final Object lock) {
if (LOCK.unlock(lock)) {
- REGISTRY = null;
+ REGISTRY = EmptyRegistryAdaptor.EMPTY;
} else {
throw new IllegalStateException("unbind failed.");
}
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 6a68fdfbb50a..a25f5b714e38 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java
@@ -390,6 +390,10 @@ public void start() {
@Override
public void stop() {
+ stop(false);
+ }
+
+ public void stop(boolean staticResourceCleanup) {
synchronized (this) {
if (this.agentStatus == AgentStatus.RUNNING) {
changeStatus(AgentStatus.STOPPED);
@@ -408,9 +412,11 @@ public void stop() {
this.statDataSender.stop();
closeTcpDataSender();
-
- PLoggerFactory.unregister(this.binder);
- this.interceptorRegistryBinder.unbind();
+ // for testcase
+ if (staticResourceCleanup) {
+ PLoggerFactory.unregister(this.binder);
+ this.interceptorRegistryBinder.unbind();
+ }
}
private void closeTcpDataSender() {
| diff --git a/profiler/src/main/java/com/navercorp/pinpoint/test/junit4/TestContext.java b/profiler/src/main/java/com/navercorp/pinpoint/test/junit4/TestContext.java
index f4f8f3984d9c..6147b72306c7 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/test/junit4/TestContext.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/test/junit4/TestContext.java
@@ -88,7 +88,7 @@ public Class<?> getBaseTestClass() {
@Override
public void close() throws IOException {
if (mockAgent != null) {
- mockAgent.stop();
+ mockAgent.stop(true);
}
PLoggerFactory.unregister(loggerBinder);
}
| test | train | "2015-12-02T10:51:15" | "2015-12-02T11:22:03Z" | emeroad | test |
|
pinpoint-apm/pinpoint/1318_1325 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1318 | pinpoint-apm/pinpoint/1325 | [
"keyword_pr_to_issue"
] | aa574ce45bd6219e05262f582d7149cdc3168c97 | e255eee71b16fd5292710e31ba585c2830cb6f25 | [
"Api change affects transaction list queries - reopening issue.\n",
"Reopening issue to add configuration option for the duration determining agent inactivity.\n"
] | [] | "2015-12-07T06:19:35Z" | [
"enhancement"
] | Add time filtering when querying agents for Realtime data | When querying for realtime data such as the active thread chart, servers that are no longer in use are of no interest. These servers are currently displayed as _NOT_FOUND_ and will continue to be displayed until the TTL value set in HBase.
It might be a good idea to set a reasonable time buffer (perhaps a week?) when querying for these agents so that servers that were down for longer than a week does not show up in the active thread chart and confuse everyone.
| [
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java
index 644bd9dd52bc..e623937fcf0b 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java
@@ -38,6 +38,8 @@ public interface AgentInfoService {
Set<AgentInfo> getAgentsByApplicationName(String applicationName, long timestamp);
+ Set<AgentInfo> getAgentsByApplicationName(String applicationName, long timestamp, long timeDiff);
+
AgentInfo getAgentInfo(String agentId, long timestamp);
AgentStatus getAgentStatus(String agentId, long timestamp);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java
index 4f180b4d82cf..582deca402f2 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java
@@ -134,9 +134,23 @@ public ApplicationAgentList getApplicationAgentList(ApplicationAgentList.Key app
@Override
public Set<AgentInfo> getAgentsByApplicationName(String applicationName, long timestamp) {
+ long timeDiff = timestamp;
+ return this.getAgentsByApplicationName(applicationName, timestamp, timeDiff);
+ }
+
+ @Override
+ public Set<AgentInfo> getAgentsByApplicationName(String applicationName, long timestamp, long timeDiff) {
if (applicationName == null) {
throw new NullPointerException("applicationName must not be null");
}
+ if (timeDiff < 0) {
+ throw new IllegalArgumentException("timeDiff must not be less than 0");
+ }
+ if (timeDiff > timestamp) {
+ throw new IllegalArgumentException("timeDiff must not be greater than timestamp");
+ }
+
+ final long eventTimestampFloor = timestamp - timeDiff;
List<String> agentIds = this.applicationIndexDao.selectAgentIds(applicationName);
Set<AgentInfo> agentSet = new HashSet<>();
@@ -145,9 +159,12 @@ public Set<AgentInfo> getAgentsByApplicationName(String applicationName, long ti
// (As we do not yet have a way to accurately record the agent's lifecycle.)
AgentInfoBo agentInfoBo = this.agentInfoDao.getAgentInfo(agentId, timestamp);
if (agentInfoBo != null) {
- AgentInfo agentInfo = new AgentInfo(agentInfoBo);
- agentInfo.setStatus(this.getAgentStatus(agentId, timestamp));
- agentSet.add(agentInfo);
+ AgentStatus agentStatus = this.getAgentStatus(agentId, timestamp);
+ if (AgentLifeCycleState.UNKNOWN == agentStatus.getState() || eventTimestampFloor <= agentStatus.getEventTimestamp()) {
+ AgentInfo agentInfo = new AgentInfo(agentInfoBo);
+ agentInfo.setStatus(agentStatus);
+ agentSet.add(agentInfo);
+ }
}
}
return agentSet;
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentService.java
index ce6340ab7cfb..251844d8d570 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentService.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentService.java
@@ -42,7 +42,8 @@ public interface AgentService {
AgentInfo getAgentInfo(String applicationName, String agentId, long startTimeStamp);
AgentInfo getAgentInfo(String applicationName, String agentId, long startTimeStamp, boolean checkDB);
- List<AgentInfo> getAgentInfoList(String applicationName);
+ List<AgentInfo> getRecentAgentInfoList(String applicationName);
+ List<AgentInfo> getRecentAgentInfoList(String applicationName, long timeDiff);
boolean isConnected(AgentInfo agentInfo);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java
index 241476db44e9..596565e88def 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java
@@ -51,6 +51,7 @@
import org.springframework.stereotype.Service;
import java.util.*;
+import java.util.concurrent.TimeUnit;
/**
* @author HyunGil Jeong
@@ -61,6 +62,9 @@ public class AgentServiceImpl implements AgentService {
private static final long DEFAULT_FUTURE_TIMEOUT = 3000;
+ private static final long DEFAULT_TIME_DIFF_DAYS = 7;
+ private static final long DEFAULT_TIME_DIFF_MS = TimeUnit.MILLISECONDS.convert(DEFAULT_TIME_DIFF_DAYS, TimeUnit.DAYS);
+
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
@@ -135,12 +139,17 @@ public AgentInfo getAgentInfo(String applicationName, String agentId, long start
}
@Override
- public List<AgentInfo> getAgentInfoList(String applicationName) {
+ public List<AgentInfo> getRecentAgentInfoList(String applicationName) {
+ return this.getRecentAgentInfoList(applicationName, DEFAULT_TIME_DIFF_MS);
+ }
+
+ @Override
+ public List<AgentInfo> getRecentAgentInfoList(String applicationName, long timeDiff) {
List<AgentInfo> agentInfoList = new ArrayList<>();
long currentTime = System.currentTimeMillis();
- Set<AgentInfo> agentInfos = agentInfoService.getAgentsByApplicationName(applicationName, currentTime);
+ Set<AgentInfo> agentInfos = agentInfoService.getAgentsByApplicationName(applicationName, currentTime, timeDiff);
for (AgentInfo agentInfo : agentInfos) {
ListUtils.addIfValueNotNull(agentInfoList, agentInfo);
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java
index 3b12fd75711a..b048ebbe9796 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java
@@ -110,7 +110,7 @@ public void addWebSocketSession(WebSocketSession webSocketSession) {
logger.info("addWebSocketSession. applicationName:{}, webSocketSession:{}", applicationName, webSocketSession);
- List<AgentInfo> agentInfoList = agentService.getAgentInfoList(applicationName);
+ List<AgentInfo> agentInfoList = agentService.getRecentAgentInfoList(applicationName);
synchronized (workerManagingLock) {
if (isStopped) {
return;
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java b/web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java
index d6a609c48c5f..1f614a2256fb 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java
@@ -148,7 +148,7 @@ public void run(Timeout timeout) throws Exception {
logger.info("AgentCheckTimerTask started.");
try {
- List<AgentInfo> agentInfoList = agentService.getAgentInfoList(applicationName);
+ List<AgentInfo> agentInfoList = agentService.getRecentAgentInfoList(applicationName);
for (AgentInfo agentInfo : agentInfoList) {
String agentId = agentInfo.getAgentId();
if (defaultAgentIdList.contains(agentId)) {
| null | train | train | "2015-12-07T07:24:10" | "2015-12-04T10:07:22Z" | Xylus | test |
pinpoint-apm/pinpoint/1358_1359 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1358 | pinpoint-apm/pinpoint/1359 | [
"keyword_pr_to_issue"
] | 16ef118ddd8550a8571638513f5aa3d7b115d6cd | 1102bad51c928da5dacb73b8e70dbf6874855ac2 | [] | [] | "2015-12-17T04:33:38Z" | [
"enhancement"
] | Add durational agent event types | For better handling in Web
| [
"commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventType.java",
"commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventTypeCategory.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentEventServiceImpl.java",
"web/src/main/java/com/navercorp/pinpoint/web/vo/AgentEvent.java"
] | [
"commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventType.java",
"commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventTypeCategory.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentEventServiceImpl.java",
"web/src/main/java/com/navercorp/pinpoint/web/vo/AgentEvent.java",
"web/src/main/java/com/navercorp/pinpoint/web/vo/DurationalAgentEvent.java"
] | [] | diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventType.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventType.java
index 7c254f1ffa4f..1d650b6ea81d 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventType.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventType.java
@@ -29,12 +29,12 @@
* @author HyunGil Jeong
*/
public enum AgentEventType {
- AGENT_CONNECTED(10100, "Agent connected", Void.class, AGENT_LIFECYCLE),
+ AGENT_CONNECTED(10100, "Agent connected", Void.class, DURATIONAL, AGENT_LIFECYCLE),
AGENT_PING(10199, "Agent ping", Void.class, AGENT_LIFECYCLE),
- AGENT_SHUTDOWN(10200, "Agent shutdown", Void.class, AGENT_LIFECYCLE),
- AGENT_UNEXPECTED_SHUTDOWN(10201, "Agent unexpected shutdown", Void.class, AGENT_LIFECYCLE),
- AGENT_CLOSED_BY_SERVER(10300, "Agent connection closed by server", Void.class, AGENT_LIFECYCLE),
- AGENT_UNEXPECTED_CLOSE_BY_SERVER(10301, "Agent connection unexpectedly closed by server", Void.class, AGENT_LIFECYCLE),
+ AGENT_SHUTDOWN(10200, "Agent shutdown", Void.class, DURATIONAL, AGENT_LIFECYCLE),
+ AGENT_UNEXPECTED_SHUTDOWN(10201, "Agent unexpected shutdown", Void.class, DURATIONAL, AGENT_LIFECYCLE),
+ AGENT_CLOSED_BY_SERVER(10300, "Agent connection closed by server", Void.class, DURATIONAL, AGENT_LIFECYCLE),
+ AGENT_UNEXPECTED_CLOSE_BY_SERVER(10301, "Agent connection unexpectedly closed by server", Void.class, DURATIONAL, AGENT_LIFECYCLE),
USER_THREAD_DUMP(20100, "Thread dump by user", TCommandThreadDumpResponse.class, USER_REQUEST, THREAD_DUMP),
OTHER(-1, "Other event", String.class, AgentEventTypeCategory.OTHER);
diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventTypeCategory.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventTypeCategory.java
index 1fabb4cbded4..6f7b8d869018 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventTypeCategory.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentEventTypeCategory.java
@@ -20,6 +20,7 @@
* @author HyunGil Jeong
*/
public enum AgentEventTypeCategory {
+ DURATIONAL,
AGENT_LIFECYCLE,
USER_REQUEST,
THREAD_DUMP,
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentEventServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentEventServiceImpl.java
index c3dc4e5f672b..c7e28415a114 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentEventServiceImpl.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentEventServiceImpl.java
@@ -19,8 +19,12 @@
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.Iterator;
import java.util.List;
+import java.util.PriorityQueue;
+import com.navercorp.pinpoint.common.util.AgentEventTypeCategory;
+import com.navercorp.pinpoint.web.vo.DurationalAgentEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -54,13 +58,8 @@ public List<AgentEvent> getAgentEvents(String agentId, Range range) {
}
final boolean includeEventMessage = false;
List<AgentEventBo> agentEventBos = this.agentEventDao.getAgentEvents(agentId, range);
- List<AgentEvent> agentEvents = new ArrayList<>(agentEventBos.size());
- for (AgentEventBo agentEventBo : agentEventBos) {
- if (agentEventBo != null) {
- agentEvents.add(createAgentEvent(agentEventBo, includeEventMessage));
- }
- }
- Collections.sort(agentEvents, AgentEvent.EVENT_TIMESTAMP_DESC_COMPARATOR);
+ List<AgentEvent> agentEvents = createAgentEvents(agentEventBos, includeEventMessage);
+ Collections.sort(agentEvents, AgentEvent.EVENT_TIMESTAMP_ASC_COMPARATOR);
return agentEvents;
}
@@ -84,21 +83,54 @@ public AgentEvent getAgentEvent(String agentId, long eventTimestamp, int eventTy
return null;
}
+ private List<AgentEvent> createAgentEvents(List<AgentEventBo> agentEventBos, boolean includeEventMessage) {
+ List<AgentEvent> agentEvents = new ArrayList<>(agentEventBos.size());
+ PriorityQueue<DurationalAgentEvent> durationalAgentEvents = new PriorityQueue<>(agentEventBos.size(), AgentEvent.EVENT_TIMESTAMP_ASC_COMPARATOR);
+ for (AgentEventBo agentEventBo : agentEventBos) {
+ if (agentEventBo.getEventType().isCategorizedAs(AgentEventTypeCategory.DURATIONAL)) {
+ durationalAgentEvents.add(createDurationalAgentEvent(agentEventBo, includeEventMessage));
+ } else {
+ agentEvents.add(createAgentEvent(agentEventBo, includeEventMessage));
+ }
+ }
+ long durationStartTimestamp = DurationalAgentEvent.UNKNOWN_TIMESTAMP;
+ while (!durationalAgentEvents.isEmpty()) {
+ DurationalAgentEvent currentEvent = durationalAgentEvents.remove();
+ currentEvent.setDurationStartTimestamp(durationStartTimestamp);
+ DurationalAgentEvent nextEvent = durationalAgentEvents.peek();
+ if (nextEvent != null) {
+ long nextEventTimestamp = nextEvent.getEventTimestamp();
+ currentEvent.setDurationEndTimestamp(nextEventTimestamp);
+ durationStartTimestamp = nextEventTimestamp;
+ }
+ agentEvents.add(currentEvent);
+ }
+ return agentEvents;
+ }
+
private AgentEvent createAgentEvent(AgentEventBo agentEventBo, boolean includeEventMessage) {
- final String agentId = agentEventBo.getAgentId();
- final long eventTimestamp = agentEventBo.getEventTimestamp();
- final AgentEventType eventType = agentEventBo.getEventType();
- AgentEvent agentEvent = new AgentEvent(agentId, eventTimestamp, eventType);
- agentEvent.setStartTimestamp(agentEventBo.getStartTimestamp());
+ AgentEvent agentEvent = new AgentEvent(agentEventBo);
if (includeEventMessage) {
- try {
- agentEvent.setEventMessage(this.agentEventMessageDeserializer.deserialize(eventType,
- agentEventBo.getEventBody()));
- } catch (UnsupportedEncodingException e) {
- logger.warn("error deserializing event message", e);
- }
+ agentEvent.setEventMessage(deserializeEventMessage(agentEventBo));
}
return agentEvent;
}
+ private DurationalAgentEvent createDurationalAgentEvent(AgentEventBo agentEventBo, boolean includeEventMessage) {
+ DurationalAgentEvent durationalAgentEvent = new DurationalAgentEvent(agentEventBo);
+ if (includeEventMessage) {
+ durationalAgentEvent.setEventMessage(deserializeEventMessage(agentEventBo));
+ }
+ return durationalAgentEvent;
+ }
+
+ private Object deserializeEventMessage(AgentEventBo agentEventBo) {
+ try {
+ return this.agentEventMessageDeserializer.deserialize(agentEventBo.getEventType(), agentEventBo.getEventBody());
+ } catch (UnsupportedEncodingException e) {
+ logger.warn("error deserializing event message", e);
+ return null;
+ }
+ }
+
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentEvent.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentEvent.java
index 91737a998c6e..da9630207d00 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentEvent.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentEvent.java
@@ -21,6 +21,7 @@
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
+import com.navercorp.pinpoint.common.bo.AgentEventBo;
import com.navercorp.pinpoint.common.util.AgentEventType;
/**
@@ -29,6 +30,17 @@
@JsonInclude(Include.NON_NULL)
public class AgentEvent {
+ public static final Comparator<AgentEvent> EVENT_TIMESTAMP_ASC_COMPARATOR = new Comparator<AgentEvent>() {
+ @Override
+ public int compare(AgentEvent o1, AgentEvent o2) {
+ int eventTimestampComparison = Long.compare(o1.eventTimestamp, o2.eventTimestamp);
+ if (eventTimestampComparison == 0) {
+ return o2.eventTypeCode - o1.eventTypeCode;
+ }
+ return eventTimestampComparison;
+ }
+ };
+
public static final Comparator<AgentEvent> EVENT_TIMESTAMP_DESC_COMPARATOR = new Comparator<AgentEvent>() {
@Override
public int compare(AgentEvent o1, AgentEvent o2) {
@@ -56,23 +68,16 @@ public int compare(AgentEvent o1, AgentEvent o2) {
private final boolean hasEventMessage;
@JsonProperty
- private long startTimestamp;
+ private final long startTimestamp;
@JsonProperty
private Object eventMessage;
- public AgentEvent(String agentId, long eventTimestamp, AgentEventType eventType) {
- if (agentId == null) {
- throw new NullPointerException("agentId must not be null");
- }
- if (eventTimestamp < 0) {
- throw new IllegalArgumentException("eventTimestamp must not be null");
- }
- if (eventType == null) {
- throw new NullPointerException("eventType must not be null");
- }
- this.agentId = agentId;
- this.eventTimestamp = eventTimestamp;
+ public AgentEvent(AgentEventBo agentEventBo) {
+ this.agentId = agentEventBo.getAgentId();
+ this.eventTimestamp = agentEventBo.getEventTimestamp();
+ this.startTimestamp = agentEventBo.getStartTimestamp();
+ AgentEventType eventType = agentEventBo.getEventType();
this.eventTypeCode = eventType.getCode();
this.eventTypeDesc = eventType.getDesc();
this.hasEventMessage = eventType.getMessageType() != Void.class;
@@ -102,10 +107,6 @@ public long getStartTimestamp() {
return startTimestamp;
}
- public void setStartTimestamp(long startTimestamp) {
- this.startTimestamp = startTimestamp;
- }
-
public Object getEventMessage() {
return eventMessage;
}
@@ -161,6 +162,6 @@ public boolean equals(Object obj) {
public String toString() {
return "AgentEvent [agentId=" + agentId + ", eventTimestamp=" + eventTimestamp + ", eventTypeCode="
+ eventTypeCode + ", eventTypeDesc=" + eventTypeDesc + ", hasEventMessage=" + hasEventMessage
- + ", startTimestamp=" + startTimestamp + ", eventMessage=" + eventMessage + "]";
+ + ", eventMessage=" + eventMessage + ", startTimestamp=" + startTimestamp + "]";
}
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/DurationalAgentEvent.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/DurationalAgentEvent.java
new file mode 100644
index 000000000000..1300f0320f64
--- /dev/null
+++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/DurationalAgentEvent.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2015 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.vo;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.navercorp.pinpoint.common.bo.AgentEventBo;
+import com.navercorp.pinpoint.common.util.AgentEventType;
+
+/**
+ * @author HyunGil Jeong
+ */
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class DurationalAgentEvent extends AgentEvent {
+
+ public static final long UNKNOWN_TIMESTAMP = -1;
+
+ @JsonProperty
+ private long durationStartTimestamp = UNKNOWN_TIMESTAMP;
+
+ @JsonProperty
+ private long durationEndTimestamp = UNKNOWN_TIMESTAMP;
+
+ public DurationalAgentEvent(AgentEventBo agentEventBo) {
+ super(agentEventBo);
+ }
+
+ public long getDurationStartTimestamp() {
+ return this.durationStartTimestamp;
+ }
+
+ public void setDurationStartTimestamp(long durationStartTimestamp) {
+ this.durationStartTimestamp = durationStartTimestamp;
+ }
+
+ public long getDurationEndTimestamp() {
+ return this.durationEndTimestamp;
+ }
+
+ public void setDurationEndTimestamp(long durationEndTimestamp) {
+ this.durationEndTimestamp = durationEndTimestamp;
+ }
+
+ @Override
+ public String toString() {
+ return "DurationalAgentEvent{" +
+ "agentId=" + super.getAgentId() +
+ ", eventTimestamp=" + super.getEventTimestamp() +
+ ", eventTypeCode=" + super.getEventTypeCode() +
+ ", eventTypeDesc=" + super.getEventTypeDesc() +
+ ", hasEventMessage=" + super.hasEventMessage() +
+ ", eventMessage=" + super.getEventMessage() +
+ ", startTimestamp=" + super.getStartTimestamp() +
+ ", durationStartTimestamp=" + durationStartTimestamp +
+ ", durationEndTimestamp=" + durationEndTimestamp +
+ '}';
+ }
+}
| null | val | train | "2015-12-16T07:50:14" | "2015-12-17T02:24:52Z" | Xylus | test |
pinpoint-apm/pinpoint/1362_1381 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1362 | pinpoint-apm/pinpoint/1381 | [
"keyword_pr_to_issue"
] | 5af2146bda1b710bceee101f23faab7eea34d9ac | 16b99b67324a315c162155f4a4ef480bed439ed3 | [
"Reopening as scanner creations may be done in parallel as well, and this may cut some time during scanner creation.\n",
"Reopening to apply parallel scan for finding accept applications for nodes when drawing the server map.\n"
] | [] | "2015-12-28T08:32:17Z" | [
"enhancement"
] | Implement parallel result scanner for scanning rows distributed with RowKeyDistributor | Allow distributed scanners to run in parallel that would theoretically allow for better performance when scanning rows that are well distributed using `RowKeyDistributor`
| [
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AbstractDistributedScannerTableCallback.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/DistributedScannerTableCallback.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelDistributedScannerTableCallback.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelResultScanner.java",
"docker/pinpoint-web/hbase.properties",
"quickstart/web/src/main/resources/hbase.properties"
] | [
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTask.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskConfig.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskException.java",
"docker/pinpoint-web/hbase.properties",
"quickstart/web/src/main/resources/hbase.properties"
] | [] | diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AbstractDistributedScannerTableCallback.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AbstractDistributedScannerTableCallback.java
deleted file mode 100644
index bf5f36ddf462..000000000000
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AbstractDistributedScannerTableCallback.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.common.hbase;
-
-import com.navercorp.pinpoint.common.util.StopWatch;
-import com.sematext.hbase.wd.AbstractRowKeyDistributor;
-import org.apache.hadoop.hbase.client.HTableInterface;
-import org.apache.hadoop.hbase.client.ResultScanner;
-import org.apache.hadoop.hbase.client.Scan;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.data.hadoop.hbase.ResultsExtractor;
-import org.springframework.data.hadoop.hbase.TableCallback;
-
-import java.io.IOException;
-
-/**
- * @author HyunGil Jeong
- */
-public abstract class AbstractDistributedScannerTableCallback<T> implements TableCallback<T> {
-
- protected final Logger logger = LoggerFactory.getLogger(getClass());
- protected final boolean debugEnabled = this.logger.isDebugEnabled();
-
- protected final Scan scan;
- protected final AbstractRowKeyDistributor rowKeyDistributor;
- protected final ResultsExtractor<T> resultsExtractor;
-
- protected AbstractDistributedScannerTableCallback(Scan scan, AbstractRowKeyDistributor rowKeyDistributor, ResultsExtractor<T> resultsExtractor) {
- this.scan = scan;
- this.rowKeyDistributor = rowKeyDistributor;
- this.resultsExtractor = resultsExtractor;
- }
-
- @Override
- public T doInTable(HTableInterface table) throws Throwable {
- StopWatch watch = null;
- if (debugEnabled) {
- watch = new StopWatch();
- watch.start();
- }
- final ResultScanner[] splitScanners = splitScanners(table);
- final ResultScanner scanner = createResultScanner(splitScanners);
- if (debugEnabled) {
- logger.debug("DistributedScanner createTime:{}", watch.stop());
- watch.start();
- }
- try {
- return resultsExtractor.extractData(scanner);
- } finally {
- scanner.close();
- if (debugEnabled) {
- logger.debug("DistributedScanner scanTime:{}", watch.stop());
- }
- }
- }
-
- protected abstract ResultScanner createResultScanner(ResultScanner[] scanners) throws IOException;
-
- private ResultScanner[] splitScanners(HTableInterface htable) throws IOException {
- Scan[] scans = this.rowKeyDistributor.getDistributedScans(this.scan);
- final int length = scans.length;
- for(int i = 0; i < length; i++) {
- Scan scan = scans[i];
- // other properties are already set upon construction
- scan.setId(this.scan.getId() + "-" + i);
- }
-
- ResultScanner[] scanners = new ResultScanner[length];
- boolean success = false;
- try {
- for (int i = 0; i < length; i++) {
- scanners[i] = htable.getScanner(scans[i]);
- }
- success = true;
- } finally {
- if (!success) {
- closeScanner(scanners);
- }
- }
- return scanners;
- }
-
- private void closeScanner(ResultScanner[] scannerList ) {
- for (ResultScanner scanner : scannerList) {
- if (scanner != null) {
- try {
- scanner.close();
- } catch (Exception e) {
- logger.warn("Scanner.close() error Caused:{}", e.getMessage(), e);
- }
- }
- }
- }
-}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/DistributedScannerTableCallback.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/DistributedScannerTableCallback.java
deleted file mode 100644
index d0addee89c8d..000000000000
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/DistributedScannerTableCallback.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.common.hbase;
-
-import com.sematext.hbase.wd.AbstractRowKeyDistributor;
-import com.sematext.hbase.wd.DistributedScanner;
-import org.apache.hadoop.hbase.client.ResultScanner;
-import org.apache.hadoop.hbase.client.Scan;
-import org.springframework.data.hadoop.hbase.ResultsExtractor;
-
-import java.io.IOException;
-
-/**
- * @author HyunGil Jeong
- */
-public class DistributedScannerTableCallback<T> extends AbstractDistributedScannerTableCallback<T> {
-
- protected DistributedScannerTableCallback(Scan scan, AbstractRowKeyDistributor rowKeyDistributor, ResultsExtractor<T> resultsExtractor) {
- super(scan, rowKeyDistributor, resultsExtractor);
- }
-
- @Override
- protected ResultScanner createResultScanner(ResultScanner[] scanners) throws IOException {
- return new DistributedScanner(super.rowKeyDistributor, scanners);
- }
-
-}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java
index 911a1fd0a9a0..c9eb1ee64e85 100644
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java
@@ -16,6 +16,8 @@
package com.navercorp.pinpoint.common.hbase;
+import com.navercorp.pinpoint.common.hbase.parallel.ParallelResultScanner;
+import com.navercorp.pinpoint.common.hbase.parallel.ScanTaskException;
import com.navercorp.pinpoint.common.util.ExecutorFactory;
import com.navercorp.pinpoint.common.util.PinpointThreadFactory;
import com.navercorp.pinpoint.common.util.StopWatch;
@@ -48,6 +50,7 @@ public class HbaseTemplate2 extends HbaseTemplate implements HbaseOperations2, I
private static final int DEFAULT_MAX_THREADS_PER_PARALLEL_SCAN = 1;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
+ private final boolean debugEnabled = this.logger.isDebugEnabled();
private ExecutorService executor;
private boolean enableParallelScan = false;
@@ -358,24 +361,87 @@ public <T> List<List<T>> find(String tableName, List<Scan> scanList, RowMapper<T
@Override
public <T> List<T> find(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final RowMapper<T> action) {
final ResultsExtractor<List<T>> resultsExtractor = new RowMapperResultsExtractor<>(action);
- return execute(tableName, new DistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor));
+ return executeDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor);
}
@Override
public <T> List<T> find(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final int limit, final RowMapper<T> action) {
final ResultsExtractor<List<T>> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit);
- return execute(tableName, new DistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor));
+ return executeDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor);
}
@Override
public <T> List<T> find(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, int limit, final RowMapper<T> action, final LimitEventHandler limitEventHandler) {
final LimitRowMapperResultsExtractor<T> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit, limitEventHandler);
- return execute(tableName, new DistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor));
+ return executeDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor);
}
@Override
public <T> T find(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final ResultsExtractor<T> action) {
- return execute(tableName, new DistributedScannerTableCallback<>(scan, rowKeyDistributor, action));
+ return executeDistributedScan(tableName, scan, rowKeyDistributor, action);
+ }
+
+ protected final <T> T executeDistributedScan(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final ResultsExtractor<T> action) {
+ return execute(tableName, new TableCallback<T>() {
+ @Override
+ public T doInTable(HTableInterface table) throws Throwable {
+ StopWatch watch = null;
+ if (debugEnabled) {
+ watch = new StopWatch();
+ watch.start();
+ }
+ final ResultScanner[] splitScanners = splitScan(table, scan, rowKeyDistributor);
+ final ResultScanner scanner = new DistributedScanner(rowKeyDistributor, splitScanners);
+ if (debugEnabled) {
+ logger.debug("DistributedScanner createTime: {}ms", watch.stop());
+ watch.start();
+ }
+ try {
+ return action.extractData(scanner);
+ } finally {
+ scanner.close();
+ if (debugEnabled) {
+ logger.debug("DistributedScanner scanTime: {}ms", watch.stop());
+ }
+ }
+ }
+ });
+ }
+
+ private ResultScanner[] splitScan(HTableInterface htable, Scan originalScan, AbstractRowKeyDistributor rowKeyDistributor) throws IOException {
+ Scan[] scans = rowKeyDistributor.getDistributedScans(originalScan);
+ final int length = scans.length;
+ for(int i = 0; i < length; i++) {
+ Scan scan = scans[i];
+ // other properties are already set upon construction
+ scan.setId(scan.getId() + "-" + i);
+ }
+
+ ResultScanner[] scanners = new ResultScanner[length];
+ boolean success = false;
+ try {
+ for (int i = 0; i < length; i++) {
+ scanners[i] = htable.getScanner(scans[i]);
+ }
+ success = true;
+ } finally {
+ if (!success) {
+ closeScanner(scanners);
+ }
+ }
+ return scanners;
+ }
+
+ private void closeScanner(ResultScanner[] scannerList ) {
+ for (ResultScanner scanner : scannerList) {
+ if (scanner != null) {
+ try {
+ scanner.close();
+ } catch (Exception e) {
+ logger.warn("Scanner.close() error Caused:{}", e.getMessage(), e);
+ }
+ }
+ }
}
@Override
@@ -386,7 +452,7 @@ public <T> List<T> findParallel(String tableName, Scan scan, AbstractRowKeyDistr
} else {
int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan;
final ResultsExtractor<List<T>> resultsExtractor = new RowMapperResultsExtractor<>(action);
- return execute(tableName, new ParallelDistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor, this.executor, numThreadsUsed));
+ return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor, numThreadsUsed);
}
}
@@ -398,7 +464,7 @@ public <T> List<T> findParallel(String tableName, Scan scan, AbstractRowKeyDistr
} else {
int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan;
final ResultsExtractor<List<T>> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit);
- return execute(tableName, new ParallelDistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor, this.executor, numThreadsUsed));
+ return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor, numThreadsUsed);
}
}
@@ -410,7 +476,7 @@ public <T> List<T> findParallel(String tableName, Scan scan, AbstractRowKeyDistr
} else {
int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan;
final LimitRowMapperResultsExtractor<T> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit, limitEventHandler);
- return execute(tableName, new ParallelDistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor, this.executor, numThreadsUsed));
+ return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor, numThreadsUsed);
}
}
@@ -421,7 +487,42 @@ public <T> T findParallel(String tableName, Scan scan, AbstractRowKeyDistributor
return find(tableName, scan, rowKeyDistributor, action);
} else {
int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan;
- return execute(tableName, new ParallelDistributedScannerTableCallback<>(scan, rowKeyDistributor, action, this.executor, numThreadsUsed));
+ return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, action, numThreadsUsed);
+ }
+ }
+
+ protected final <T> T executeParallelDistributedScan(String tableName, Scan scan, AbstractRowKeyDistributor rowKeyDistributor, ResultsExtractor<T> action, int numParallelThreads) {
+ try {
+ StopWatch watch = null;
+ if (debugEnabled) {
+ watch = new StopWatch();
+ watch.start();
+ }
+ ParallelResultScanner scanner = new ParallelResultScanner(tableName, this, this.executor, scan, rowKeyDistributor, numParallelThreads);
+ if (debugEnabled) {
+ logger.debug("ParallelDistributedScanner createTime: {}ms", watch.stop());
+ watch.start();
+ }
+ try {
+ return action.extractData(scanner);
+ } finally {
+ scanner.close();
+ if (debugEnabled) {
+ logger.debug("ParallelDistributedScanner scanTime: {}ms", watch.stop());
+ }
+ }
+ } catch (Throwable th) {
+ Throwable throwable = th;
+ if (th instanceof ScanTaskException) {
+ throwable = th.getCause();
+ }
+ if (throwable instanceof Error) {
+ throw ((Error) th);
+ }
+ if (throwable instanceof RuntimeException) {
+ throw ((RuntimeException) th);
+ }
+ throw convertHbaseAccessException((Exception) throwable);
}
}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelDistributedScannerTableCallback.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelDistributedScannerTableCallback.java
deleted file mode 100644
index f02715a63745..000000000000
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelDistributedScannerTableCallback.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.common.hbase;
-
-import com.sematext.hbase.wd.AbstractRowKeyDistributor;
-import com.sematext.hbase.wd.DistributedScanner;
-import org.apache.hadoop.hbase.client.ResultScanner;
-import org.apache.hadoop.hbase.client.Scan;
-import org.springframework.data.hadoop.hbase.ResultsExtractor;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-
-/**
- * @author HyunGil Jeong
- */
-public class ParallelDistributedScannerTableCallback<T> extends AbstractDistributedScannerTableCallback<T> {
-
- private final ExecutorService executor;
- private final int numCaching;
- private final int numParallelThreads;
-
- protected ParallelDistributedScannerTableCallback(Scan scan, AbstractRowKeyDistributor rowKeyDistributor, ResultsExtractor<T> resultsExtractor, ExecutorService executor, int numParallelThreads) {
- super(scan, rowKeyDistributor, resultsExtractor);
- this.executor = executor;
- this.numCaching = scan.getCaching();
- this.numParallelThreads = numParallelThreads;
- }
-
- @Override
- protected ResultScanner createResultScanner(ResultScanner[] scanners) throws IOException {
- if (scanners.length < this.numParallelThreads) {
- return new ParallelResultScanner(this.executor, this.numCaching, rowKeyDistributor, scanners);
- } else {
- ResultScanner[] distributedScanners = createDistributedScanners(scanners);
- return new ParallelResultScanner(this.executor, this.numCaching, rowKeyDistributor, distributedScanners);
- }
- }
-
- private ResultScanner[] createDistributedScanners(ResultScanner[] scanners) throws IOException {
- int maxIndividualScans = (scanners.length + (this.numParallelThreads - 1)) / this.numParallelThreads;
- List<List<ResultScanner>> scannerDistributions = new ArrayList<>(this.numParallelThreads);
- for (int i = 0; i < this.numParallelThreads; ++i) {
- scannerDistributions.add(new ArrayList<ResultScanner>(maxIndividualScans));
- }
- for (int i = 0; i < scanners.length; ++i) {
- scannerDistributions.get(i % this.numParallelThreads).add(scanners[i]);
- }
- DistributedScanner[] distributedScanners = new DistributedScanner[this.numParallelThreads];
- for (int i = 0; i < distributedScanners.length; ++i) {
- List<ResultScanner> scannerDistribution = scannerDistributions.get(i);
- ResultScanner[] scannersForDistributedScanner = scannerDistribution.toArray(new ResultScanner[scannerDistribution.size()]);
- distributedScanners[i] = new DistributedScanner(rowKeyDistributor, scannersForDistributedScanner);
- }
- return distributedScanners;
- }
-
-}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelResultScanner.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java
similarity index 66%
rename from commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelResultScanner.java
rename to commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java
index 0e016130607f..11cf4ca36040 100644
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelResultScanner.java
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java
@@ -14,19 +14,19 @@
* limitations under the License.
*/
-package com.navercorp.pinpoint.common.hbase;
+package com.navercorp.pinpoint.common.hbase.parallel;
import com.sematext.hbase.wd.AbstractRowKeyDistributor;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
+import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
+import org.springframework.data.hadoop.hbase.HbaseAccessor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
/**
@@ -34,34 +34,70 @@
*/
public class ParallelResultScanner implements ResultScanner {
- private static final int DEFAULT_SCAN_TASK_QUEUE_SIZE = 100;
-
private final AbstractRowKeyDistributor keyDistributor;
private final List<ScanTask> scanTasks;
private final Result[] nextResults;
private Result next = null;
- public ParallelResultScanner(ExecutorService executor, int numCaching, AbstractRowKeyDistributor keyDistributor, ResultScanner[] scanners) throws IOException {
+ public ParallelResultScanner(String tableName, HbaseAccessor hbaseAccessor, ExecutorService executor, Scan originalScan, AbstractRowKeyDistributor keyDistributor, int numParallelThreads) throws IOException {
+ if (hbaseAccessor == null) {
+ throw new NullPointerException("hbaseAccessor must not be null");
+ }
if (executor == null) {
throw new NullPointerException("executor must not be null");
}
if (keyDistributor == null) {
throw new NullPointerException("keyDistributor must not be null");
}
- if (scanners == null) {
- throw new NullPointerException("scanners must not be null");
+ if (originalScan == null) {
+ throw new NullPointerException("originalScan must not be null");
}
this.keyDistributor = keyDistributor;
- this.nextResults = new Result[scanners.length];
- this.scanTasks = new ArrayList<>(scanners.length);
- final int scanTaskQueueSize = numCaching < DEFAULT_SCAN_TASK_QUEUE_SIZE ? numCaching : DEFAULT_SCAN_TASK_QUEUE_SIZE;
- for (ResultScanner scanner : scanners) {
- ScanTask scanTask = new ScanTask(scanner, scanTaskQueueSize);
- this.scanTasks.add(scanTask);
+
+ final ScanTaskConfig scanTaskConfig = new ScanTaskConfig(tableName, hbaseAccessor, keyDistributor, originalScan.getCaching());
+ final Scan[] splitScans = splitScans(originalScan);
+
+ this.scanTasks = createScanTasks(scanTaskConfig, splitScans, numParallelThreads);
+ this.nextResults = new Result[scanTasks.size()];
+ for (ScanTask scanTask : scanTasks) {
executor.execute(scanTask);
}
}
+ private Scan[] splitScans(Scan originalScan) throws IOException {
+ Scan[] scans = this.keyDistributor.getDistributedScans(originalScan);
+ for (int i = 0; i < scans.length; ++i) {
+ Scan scan = scans[i];
+ scan.setId(originalScan.getId() + "-" + i);
+ }
+ return scans;
+ }
+
+ private List<ScanTask> createScanTasks(ScanTaskConfig scanTaskConfig, Scan[] splitScans, int numParallelThreads) {
+ if (splitScans.length <= numParallelThreads) {
+ List<ScanTask> scanTasks = new ArrayList<>(splitScans.length);
+ for (Scan scan : splitScans) {
+ scanTasks.add(new ScanTask(scanTaskConfig, scan));
+ }
+ return scanTasks;
+ } else {
+ int maxIndividualScans = (splitScans.length + (numParallelThreads - 1)) / numParallelThreads;
+ List<List<Scan>> scanDistributions = new ArrayList<>(numParallelThreads);
+ for (int i = 0; i < numParallelThreads; ++i) {
+ scanDistributions.add(new ArrayList<Scan>(maxIndividualScans));
+ }
+ for (int i = 0; i < splitScans.length; ++i) {
+ scanDistributions.get(i % numParallelThreads).add(splitScans[i]);
+ }
+ List<ScanTask> scanTasks = new ArrayList<>(numParallelThreads);
+ for (List<Scan> scanDistribution : scanDistributions) {
+ Scan[] scansForSingleTask = scanDistribution.toArray(new Scan[scanDistribution.size()]);
+ scanTasks.add(new ScanTask(scanTaskConfig, scansForSingleTask));
+ }
+ return scanTasks;
+ }
+ }
+
private boolean hasNext() throws IOException {
if (next != null) {
return true;
@@ -85,6 +121,8 @@ private Result nextInternal() throws IOException {
int indexOfResultToUse = -1;
for (int i = 0; i < this.scanTasks.size(); ++i) {
ScanTask scanTask = this.scanTasks.get(i);
+ // fail fast in case of errors
+ checkTask(scanTask);
if (nextResults[i] == null) {
try {
nextResults[i] = scanTask.getResult();
@@ -108,57 +146,10 @@ private Result nextInternal() throws IOException {
return result;
}
- private static class ScanTask implements Runnable {
-
- private static final Result END_RESULT = new Result();
-
- private final ResultScanner scanner;
- private final BlockingQueue<Result> resultQueue;
- private volatile boolean isQueueClosed = false;
- private volatile boolean isFinished = false;
-
- private ScanTask(ResultScanner scanner, int queueSize) {
- this.scanner = scanner;
- this.resultQueue = new ArrayBlockingQueue<>(queueSize);
- }
-
- @Override
- public void run() {
- try {
- for (Result result : this.scanner) {
- this.resultQueue.put(result);
- if (this.isFinished) {
- break;
- }
- }
- this.resultQueue.put(END_RESULT);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- this.resultQueue.clear();
- this.resultQueue.add(END_RESULT);
- } finally {
- this.isFinished = true;
- this.scanner.close();
- }
- }
-
- public Result getResult() throws InterruptedException {
- if (this.isQueueClosed) {
- return null;
- }
- Result take = this.resultQueue.take();
- if (take == END_RESULT) {
- this.isQueueClosed = true;
- return null;
- }
- return take;
- }
-
- public void close() {
- this.isFinished = true;
- // signal threads blocked on resultQueue
- this.resultQueue.clear();
- this.resultQueue.offer(END_RESULT);
+ private void checkTask(ScanTask scanTask) {
+ Throwable th = scanTask.getThrowable();
+ if (th != null) {
+ throw new ScanTaskException(th);
}
}
@@ -229,6 +220,5 @@ public void remove() {
throw new UnsupportedOperationException();
}
};
-
}
}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTask.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTask.java
new file mode 100644
index 000000000000..75fd80fd73bb
--- /dev/null
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTask.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2015 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.common.hbase.parallel;
+
+import com.sematext.hbase.wd.AbstractRowKeyDistributor;
+import com.sematext.hbase.wd.DistributedScanner;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.client.HTableInterface;
+import org.apache.hadoop.hbase.client.HTableInterfaceFactory;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.ResultScanner;
+import org.apache.hadoop.hbase.client.Scan;
+import org.springframework.data.hadoop.hbase.HbaseUtils;
+
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class ScanTask implements Runnable {
+
+ private static final Result END_RESULT = new Result();
+
+ private final String tableName;
+ private final Configuration configuration;
+ private final Charset charset;
+ private final HTableInterfaceFactory tableFactory;
+ private final AbstractRowKeyDistributor rowKeyDistributor;
+
+ private final Scan[] scans;
+ private final BlockingQueue<Result> resultQueue;
+
+ private volatile Throwable throwable;
+ private volatile boolean isQueueClosed = false;
+ private volatile boolean isDone = false;
+
+ public ScanTask(ScanTaskConfig scanTaskConfig, Scan... scans) {
+ if (scanTaskConfig == null) {
+ throw new NullPointerException("scanTaskConfig must not be null");
+ }
+ if (scans == null) {
+ throw new NullPointerException("scans must not be null");
+ }
+ if (scans.length == 0) {
+ throw new IllegalArgumentException("scans must not be empty");
+ }
+ this.tableName = scanTaskConfig.getTableName();
+ this.configuration = scanTaskConfig.getConfiguration();
+ this.charset = scanTaskConfig.getCharset();
+ this.tableFactory = scanTaskConfig.getTableFactory();
+ this.rowKeyDistributor = scanTaskConfig.getRowKeyDistributor();
+ this.scans = scans;
+ this.resultQueue = new ArrayBlockingQueue<>(scanTaskConfig.getScanTaskQueueSize());
+ }
+
+ @Override
+ public void run() {
+ HTableInterface table = null;
+ try {
+ table = HbaseUtils.getHTable(this.tableName, this.configuration, this.charset, this.tableFactory);
+ ResultScanner scanner = createResultScanner(table);
+ try {
+ for (Result result : scanner) {
+ this.resultQueue.put(result);
+ if (this.isDone) {
+ break;
+ }
+ }
+ } finally {
+ this.isDone = true;
+ this.resultQueue.put(END_RESULT);
+ scanner.close();
+ }
+ } catch (Throwable th) {
+ this.throwable = th;
+ this.resultQueue.clear();
+ this.resultQueue.offer(END_RESULT);
+ } finally {
+ HbaseUtils.releaseTable(this.tableName, table);
+ }
+ }
+
+ private ResultScanner createResultScanner(HTableInterface table) throws IOException {
+ if (scans.length == 1) {
+ Scan scan = scans[0];
+ return table.getScanner(scan);
+ } else {
+ ResultScanner[] scanners = new ResultScanner[this.scans.length];
+ for (int i = 0; i < scanners.length; ++i) {
+ scanners[i] = table.getScanner(this.scans[i]);
+ }
+ return new DistributedScanner(this.rowKeyDistributor, scanners);
+ }
+ }
+
+ public Result getResult() throws InterruptedException {
+ if (this.isQueueClosed) {
+ return null;
+ }
+ Result take = this.resultQueue.take();
+ if (take == END_RESULT) {
+ this.isQueueClosed = true;
+ return null;
+ }
+ return take;
+ }
+
+ public void close() {
+ this.isDone = true;
+ // signal threads blocked on resultQueue
+ this.resultQueue.clear();
+ this.resultQueue.add(END_RESULT);
+ }
+
+ public Throwable getThrowable() {
+ return this.throwable;
+ }
+
+}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskConfig.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskConfig.java
new file mode 100644
index 000000000000..f17d9ec3923d
--- /dev/null
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskConfig.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2015 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.common.hbase.parallel;
+
+import com.sematext.hbase.wd.AbstractRowKeyDistributor;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.client.HTableInterfaceFactory;
+import org.springframework.data.hadoop.hbase.HbaseAccessor;
+
+import java.nio.charset.Charset;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class ScanTaskConfig {
+
+ private final String tableName;
+ private final Configuration configuration;
+ private final Charset charset;
+ private final HTableInterfaceFactory tableFactory;
+
+ private final AbstractRowKeyDistributor rowKeyDistributor;
+ private final int scanTaskQueueSize;
+
+ public ScanTaskConfig(String tableName, HbaseAccessor hbaseAccessor, AbstractRowKeyDistributor rowKeyDistributor, int scanCaching) {
+ this(tableName, hbaseAccessor.getConfiguration(), hbaseAccessor.getCharset(), hbaseAccessor.getTableFactory(), rowKeyDistributor, scanCaching);
+ }
+
+ public ScanTaskConfig(String tableName, Configuration configuration, Charset charset, HTableInterfaceFactory tableFactory, AbstractRowKeyDistributor rowKeyDistributor, int scanCaching) {
+ if (tableName == null) {
+ throw new NullPointerException("No table specified");
+ }
+ if (rowKeyDistributor == null) {
+ throw new NullPointerException("rowKeyDistributor must not be null");
+ }
+ this.tableName = tableName;
+ this.configuration = configuration;
+ this.charset = charset;
+ this.tableFactory = tableFactory;
+ this.rowKeyDistributor = rowKeyDistributor;
+ if (scanCaching > 0) {
+ this.scanTaskQueueSize = scanCaching;
+ } else {
+ this.scanTaskQueueSize = configuration.getInt(
+ HConstants.HBASE_CLIENT_SCANNER_CACHING,
+ HConstants.DEFAULT_HBASE_CLIENT_SCANNER_CACHING);
+ }
+ }
+
+ public String getTableName() {
+ return tableName;
+ }
+
+ public Configuration getConfiguration() {
+ return configuration;
+ }
+
+ public Charset getCharset() {
+ return charset;
+ }
+
+ public HTableInterfaceFactory getTableFactory() {
+ return tableFactory;
+ }
+
+ public AbstractRowKeyDistributor getRowKeyDistributor() {
+ return rowKeyDistributor;
+ }
+
+ public int getScanTaskQueueSize() {
+ return scanTaskQueueSize;
+ }
+}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskException.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskException.java
new file mode 100644
index 000000000000..1df0a24953a1
--- /dev/null
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskException.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2015 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.common.hbase.parallel;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class ScanTaskException extends RuntimeException {
+
+ private static final long serialVersionUID = 8554224683436066023L;
+
+ public ScanTaskException(Throwable th) {
+ super(th);
+ }
+
+ public ScanTaskException(String message, Throwable th) {
+ super(message, th);
+ }
+}
diff --git a/docker/pinpoint-web/hbase.properties b/docker/pinpoint-web/hbase.properties
index 4161185c010c..b94b1893aa93 100644
--- a/docker/pinpoint-web/hbase.properties
+++ b/docker/pinpoint-web/hbase.properties
@@ -19,4 +19,10 @@ hbase.ipc.client.socket.timeout.write=60000
hbase.client.thread.max=128
hbase.client.threadPool.queueSize=5120
# prestartAllCoreThreads
-hbase.client.threadPool.prestart=false
\ No newline at end of file
+hbase.client.threadPool.prestart=false
+
+#==================================================================================
+# hbase parallel scan options
+hbase.client.parallel.scan.enable=false
+hbase.client.parallel.scan.maxthreads=128
+hbase.client.parallel.scan.maxthreadsperscan=16
\ No newline at end of file
diff --git a/quickstart/web/src/main/resources/hbase.properties b/quickstart/web/src/main/resources/hbase.properties
index be6e5ea43e88..ac1e4a555505 100644
--- a/quickstart/web/src/main/resources/hbase.properties
+++ b/quickstart/web/src/main/resources/hbase.properties
@@ -20,4 +20,10 @@ hbase.ipc.client.socket.timeout.write=60000
hbase.client.thread.max=128
hbase.client.threadPool.queueSize=5120
# prestartAllCoreThreads
-hbase.client.threadPool.prestart=false
\ No newline at end of file
+hbase.client.threadPool.prestart=false
+
+#==================================================================================
+# hbase parallel scan options
+hbase.client.parallel.scan.enable=false
+hbase.client.parallel.scan.maxthreads=128
+hbase.client.parallel.scan.maxthreadsperscan=16
\ No newline at end of file
| null | train | train | "2015-12-24T09:28:54" | "2015-12-18T10:17:24Z" | Xylus | test |
pinpoint-apm/pinpoint/1380_1381 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1380 | pinpoint-apm/pinpoint/1381 | [
"keyword_pr_to_issue"
] | 5af2146bda1b710bceee101f23faab7eea34d9ac | 16b99b67324a315c162155f4a4ef480bed439ed3 | [
"quickstart web에 `hbase.properties` 옵션 중 하나가 없어서 그런 것 같습니다. 수정해서 commit 하겠습니다.\n",
"bug fix merge 되었습니다. 코드 업데이트 받으시고 재실행 부탁드립니다~\n"
] | [] | "2015-12-28T08:32:17Z" | [
"bug"
] | 윈도우7 환경에서 quickstart/bin/start-web.cmd 실행시 오류가 발생합니다. | quickstart.web.log 내용입니다.
hbase.client.parallel.scan.enable 이 값이 문제가 있는거 같은데 도움부탁드립니다.
16:11:17 INFO (o.s.w.c.ContextLoader :285) Root WebApplicationContext: initialization started
16:11:17 INFO (o.s.w.c.s.XmlWebApplicationContext :511) Refreshing Root WebApplicationContext: startup date [Mon Dec 28 16:11:17 KST 2015]; root of context hierarchy
16:11:17 INFO (o.s.b.f.x.XmlBeanDefinitionReader :317) Loading XML bean definitions from class path resource [applicationContext-web.xml]
16:11:17 INFO (o.s.b.f.x.XmlBeanDefinitionReader :317) Loading XML bean definitions from class path resource [applicationContext-hbase.xml]
16:11:17 INFO (o.s.b.f.x.XmlBeanDefinitionReader :317) Loading XML bean definitions from class path resource [applicationContext-datasource.xml]
16:11:17 INFO (o.s.b.f.x.XmlBeanDefinitionReader :317) Loading XML bean definitions from class path resource [applicationContext-dao-config.xml]
16:11:17 INFO (o.s.b.f.x.XmlBeanDefinitionReader :317) Loading XML bean definitions from class path resource [applicationContext-cache.xml]
16:11:17 INFO (o.s.b.f.x.XmlBeanDefinitionReader :317) Loading XML bean definitions from class path resource [applicationContext-websocket.xml]
16:11:17 INFO (.s.b.f.s.DefaultListableBeanFactory:822) Overriding bean definition for bean 'spanMapper': replacing [Generic bean: class [com.navercorp.pinpoint.web.mapper.SpanMapper]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\pinpoint\quickstart\web\target\deploy\WEB-INF\classes\com\navercorp\pinpoint\web\mapper\SpanMapper.class]] with [Generic bean: class [com.navercorp.pinpoint.web.mapper.SpanMapper]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [applicationContext-web.xml]]
16:11:18 INFO (b.f.c.PropertyPlaceholderConfigurer:172) Loading properties file from class path resource [hbase.properties]
16:11:18 INFO (b.f.c.PropertyPlaceholderConfigurer:172) Loading properties file from class path resource [jdbc.properties]
16:11:18 WARN (o.s.w.c.s.XmlWebApplicationContext :487) Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'hbaseTemplate' defined in class path resource [applicationContext-hbase.xml]: Could not resolve placeholder 'hbase.client.parallel.scan.enable' in string value "${hbase.client.parallel.scan.enable}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'hbase.client.parallel.scan.enable' in string value "${hbase.client.parallel.scan.enable}"
at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:211)
at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:222)
at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:86)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:162)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:607)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:434)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'hbase.client.parallel.scan.enable' in string value "${hbase.client.parallel.scan.enable}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer$PlaceholderResolvingStringValueResolver.resolveStringValue(PropertyPlaceholderConfigurer.java:258)
at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveStringValue(BeanDefinitionVisitor.java:282)
at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveValue(BeanDefinitionVisitor.java:204)
at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitPropertyValues(BeanDefinitionVisitor.java:141)
at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitBeanDefinition(BeanDefinitionVisitor.java:82)
at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:208)
... 18 more
16:11:18 ERROR(o.s.w.c.ContextLoader :331) Context initialization failed
| [
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AbstractDistributedScannerTableCallback.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/DistributedScannerTableCallback.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelDistributedScannerTableCallback.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelResultScanner.java",
"docker/pinpoint-web/hbase.properties",
"quickstart/web/src/main/resources/hbase.properties"
] | [
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTask.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskConfig.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskException.java",
"docker/pinpoint-web/hbase.properties",
"quickstart/web/src/main/resources/hbase.properties"
] | [] | diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AbstractDistributedScannerTableCallback.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AbstractDistributedScannerTableCallback.java
deleted file mode 100644
index bf5f36ddf462..000000000000
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AbstractDistributedScannerTableCallback.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.common.hbase;
-
-import com.navercorp.pinpoint.common.util.StopWatch;
-import com.sematext.hbase.wd.AbstractRowKeyDistributor;
-import org.apache.hadoop.hbase.client.HTableInterface;
-import org.apache.hadoop.hbase.client.ResultScanner;
-import org.apache.hadoop.hbase.client.Scan;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.data.hadoop.hbase.ResultsExtractor;
-import org.springframework.data.hadoop.hbase.TableCallback;
-
-import java.io.IOException;
-
-/**
- * @author HyunGil Jeong
- */
-public abstract class AbstractDistributedScannerTableCallback<T> implements TableCallback<T> {
-
- protected final Logger logger = LoggerFactory.getLogger(getClass());
- protected final boolean debugEnabled = this.logger.isDebugEnabled();
-
- protected final Scan scan;
- protected final AbstractRowKeyDistributor rowKeyDistributor;
- protected final ResultsExtractor<T> resultsExtractor;
-
- protected AbstractDistributedScannerTableCallback(Scan scan, AbstractRowKeyDistributor rowKeyDistributor, ResultsExtractor<T> resultsExtractor) {
- this.scan = scan;
- this.rowKeyDistributor = rowKeyDistributor;
- this.resultsExtractor = resultsExtractor;
- }
-
- @Override
- public T doInTable(HTableInterface table) throws Throwable {
- StopWatch watch = null;
- if (debugEnabled) {
- watch = new StopWatch();
- watch.start();
- }
- final ResultScanner[] splitScanners = splitScanners(table);
- final ResultScanner scanner = createResultScanner(splitScanners);
- if (debugEnabled) {
- logger.debug("DistributedScanner createTime:{}", watch.stop());
- watch.start();
- }
- try {
- return resultsExtractor.extractData(scanner);
- } finally {
- scanner.close();
- if (debugEnabled) {
- logger.debug("DistributedScanner scanTime:{}", watch.stop());
- }
- }
- }
-
- protected abstract ResultScanner createResultScanner(ResultScanner[] scanners) throws IOException;
-
- private ResultScanner[] splitScanners(HTableInterface htable) throws IOException {
- Scan[] scans = this.rowKeyDistributor.getDistributedScans(this.scan);
- final int length = scans.length;
- for(int i = 0; i < length; i++) {
- Scan scan = scans[i];
- // other properties are already set upon construction
- scan.setId(this.scan.getId() + "-" + i);
- }
-
- ResultScanner[] scanners = new ResultScanner[length];
- boolean success = false;
- try {
- for (int i = 0; i < length; i++) {
- scanners[i] = htable.getScanner(scans[i]);
- }
- success = true;
- } finally {
- if (!success) {
- closeScanner(scanners);
- }
- }
- return scanners;
- }
-
- private void closeScanner(ResultScanner[] scannerList ) {
- for (ResultScanner scanner : scannerList) {
- if (scanner != null) {
- try {
- scanner.close();
- } catch (Exception e) {
- logger.warn("Scanner.close() error Caused:{}", e.getMessage(), e);
- }
- }
- }
- }
-}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/DistributedScannerTableCallback.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/DistributedScannerTableCallback.java
deleted file mode 100644
index d0addee89c8d..000000000000
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/DistributedScannerTableCallback.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.common.hbase;
-
-import com.sematext.hbase.wd.AbstractRowKeyDistributor;
-import com.sematext.hbase.wd.DistributedScanner;
-import org.apache.hadoop.hbase.client.ResultScanner;
-import org.apache.hadoop.hbase.client.Scan;
-import org.springframework.data.hadoop.hbase.ResultsExtractor;
-
-import java.io.IOException;
-
-/**
- * @author HyunGil Jeong
- */
-public class DistributedScannerTableCallback<T> extends AbstractDistributedScannerTableCallback<T> {
-
- protected DistributedScannerTableCallback(Scan scan, AbstractRowKeyDistributor rowKeyDistributor, ResultsExtractor<T> resultsExtractor) {
- super(scan, rowKeyDistributor, resultsExtractor);
- }
-
- @Override
- protected ResultScanner createResultScanner(ResultScanner[] scanners) throws IOException {
- return new DistributedScanner(super.rowKeyDistributor, scanners);
- }
-
-}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java
index 911a1fd0a9a0..c9eb1ee64e85 100644
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java
@@ -16,6 +16,8 @@
package com.navercorp.pinpoint.common.hbase;
+import com.navercorp.pinpoint.common.hbase.parallel.ParallelResultScanner;
+import com.navercorp.pinpoint.common.hbase.parallel.ScanTaskException;
import com.navercorp.pinpoint.common.util.ExecutorFactory;
import com.navercorp.pinpoint.common.util.PinpointThreadFactory;
import com.navercorp.pinpoint.common.util.StopWatch;
@@ -48,6 +50,7 @@ public class HbaseTemplate2 extends HbaseTemplate implements HbaseOperations2, I
private static final int DEFAULT_MAX_THREADS_PER_PARALLEL_SCAN = 1;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
+ private final boolean debugEnabled = this.logger.isDebugEnabled();
private ExecutorService executor;
private boolean enableParallelScan = false;
@@ -358,24 +361,87 @@ public <T> List<List<T>> find(String tableName, List<Scan> scanList, RowMapper<T
@Override
public <T> List<T> find(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final RowMapper<T> action) {
final ResultsExtractor<List<T>> resultsExtractor = new RowMapperResultsExtractor<>(action);
- return execute(tableName, new DistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor));
+ return executeDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor);
}
@Override
public <T> List<T> find(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final int limit, final RowMapper<T> action) {
final ResultsExtractor<List<T>> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit);
- return execute(tableName, new DistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor));
+ return executeDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor);
}
@Override
public <T> List<T> find(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, int limit, final RowMapper<T> action, final LimitEventHandler limitEventHandler) {
final LimitRowMapperResultsExtractor<T> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit, limitEventHandler);
- return execute(tableName, new DistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor));
+ return executeDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor);
}
@Override
public <T> T find(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final ResultsExtractor<T> action) {
- return execute(tableName, new DistributedScannerTableCallback<>(scan, rowKeyDistributor, action));
+ return executeDistributedScan(tableName, scan, rowKeyDistributor, action);
+ }
+
+ protected final <T> T executeDistributedScan(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final ResultsExtractor<T> action) {
+ return execute(tableName, new TableCallback<T>() {
+ @Override
+ public T doInTable(HTableInterface table) throws Throwable {
+ StopWatch watch = null;
+ if (debugEnabled) {
+ watch = new StopWatch();
+ watch.start();
+ }
+ final ResultScanner[] splitScanners = splitScan(table, scan, rowKeyDistributor);
+ final ResultScanner scanner = new DistributedScanner(rowKeyDistributor, splitScanners);
+ if (debugEnabled) {
+ logger.debug("DistributedScanner createTime: {}ms", watch.stop());
+ watch.start();
+ }
+ try {
+ return action.extractData(scanner);
+ } finally {
+ scanner.close();
+ if (debugEnabled) {
+ logger.debug("DistributedScanner scanTime: {}ms", watch.stop());
+ }
+ }
+ }
+ });
+ }
+
+ private ResultScanner[] splitScan(HTableInterface htable, Scan originalScan, AbstractRowKeyDistributor rowKeyDistributor) throws IOException {
+ Scan[] scans = rowKeyDistributor.getDistributedScans(originalScan);
+ final int length = scans.length;
+ for(int i = 0; i < length; i++) {
+ Scan scan = scans[i];
+ // other properties are already set upon construction
+ scan.setId(scan.getId() + "-" + i);
+ }
+
+ ResultScanner[] scanners = new ResultScanner[length];
+ boolean success = false;
+ try {
+ for (int i = 0; i < length; i++) {
+ scanners[i] = htable.getScanner(scans[i]);
+ }
+ success = true;
+ } finally {
+ if (!success) {
+ closeScanner(scanners);
+ }
+ }
+ return scanners;
+ }
+
+ private void closeScanner(ResultScanner[] scannerList ) {
+ for (ResultScanner scanner : scannerList) {
+ if (scanner != null) {
+ try {
+ scanner.close();
+ } catch (Exception e) {
+ logger.warn("Scanner.close() error Caused:{}", e.getMessage(), e);
+ }
+ }
+ }
}
@Override
@@ -386,7 +452,7 @@ public <T> List<T> findParallel(String tableName, Scan scan, AbstractRowKeyDistr
} else {
int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan;
final ResultsExtractor<List<T>> resultsExtractor = new RowMapperResultsExtractor<>(action);
- return execute(tableName, new ParallelDistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor, this.executor, numThreadsUsed));
+ return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor, numThreadsUsed);
}
}
@@ -398,7 +464,7 @@ public <T> List<T> findParallel(String tableName, Scan scan, AbstractRowKeyDistr
} else {
int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan;
final ResultsExtractor<List<T>> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit);
- return execute(tableName, new ParallelDistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor, this.executor, numThreadsUsed));
+ return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor, numThreadsUsed);
}
}
@@ -410,7 +476,7 @@ public <T> List<T> findParallel(String tableName, Scan scan, AbstractRowKeyDistr
} else {
int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan;
final LimitRowMapperResultsExtractor<T> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit, limitEventHandler);
- return execute(tableName, new ParallelDistributedScannerTableCallback<>(scan, rowKeyDistributor, resultsExtractor, this.executor, numThreadsUsed));
+ return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor, numThreadsUsed);
}
}
@@ -421,7 +487,42 @@ public <T> T findParallel(String tableName, Scan scan, AbstractRowKeyDistributor
return find(tableName, scan, rowKeyDistributor, action);
} else {
int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan;
- return execute(tableName, new ParallelDistributedScannerTableCallback<>(scan, rowKeyDistributor, action, this.executor, numThreadsUsed));
+ return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, action, numThreadsUsed);
+ }
+ }
+
+ protected final <T> T executeParallelDistributedScan(String tableName, Scan scan, AbstractRowKeyDistributor rowKeyDistributor, ResultsExtractor<T> action, int numParallelThreads) {
+ try {
+ StopWatch watch = null;
+ if (debugEnabled) {
+ watch = new StopWatch();
+ watch.start();
+ }
+ ParallelResultScanner scanner = new ParallelResultScanner(tableName, this, this.executor, scan, rowKeyDistributor, numParallelThreads);
+ if (debugEnabled) {
+ logger.debug("ParallelDistributedScanner createTime: {}ms", watch.stop());
+ watch.start();
+ }
+ try {
+ return action.extractData(scanner);
+ } finally {
+ scanner.close();
+ if (debugEnabled) {
+ logger.debug("ParallelDistributedScanner scanTime: {}ms", watch.stop());
+ }
+ }
+ } catch (Throwable th) {
+ Throwable throwable = th;
+ if (th instanceof ScanTaskException) {
+ throwable = th.getCause();
+ }
+ if (throwable instanceof Error) {
+ throw ((Error) th);
+ }
+ if (throwable instanceof RuntimeException) {
+ throw ((RuntimeException) th);
+ }
+ throw convertHbaseAccessException((Exception) throwable);
}
}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelDistributedScannerTableCallback.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelDistributedScannerTableCallback.java
deleted file mode 100644
index f02715a63745..000000000000
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelDistributedScannerTableCallback.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.common.hbase;
-
-import com.sematext.hbase.wd.AbstractRowKeyDistributor;
-import com.sematext.hbase.wd.DistributedScanner;
-import org.apache.hadoop.hbase.client.ResultScanner;
-import org.apache.hadoop.hbase.client.Scan;
-import org.springframework.data.hadoop.hbase.ResultsExtractor;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-
-/**
- * @author HyunGil Jeong
- */
-public class ParallelDistributedScannerTableCallback<T> extends AbstractDistributedScannerTableCallback<T> {
-
- private final ExecutorService executor;
- private final int numCaching;
- private final int numParallelThreads;
-
- protected ParallelDistributedScannerTableCallback(Scan scan, AbstractRowKeyDistributor rowKeyDistributor, ResultsExtractor<T> resultsExtractor, ExecutorService executor, int numParallelThreads) {
- super(scan, rowKeyDistributor, resultsExtractor);
- this.executor = executor;
- this.numCaching = scan.getCaching();
- this.numParallelThreads = numParallelThreads;
- }
-
- @Override
- protected ResultScanner createResultScanner(ResultScanner[] scanners) throws IOException {
- if (scanners.length < this.numParallelThreads) {
- return new ParallelResultScanner(this.executor, this.numCaching, rowKeyDistributor, scanners);
- } else {
- ResultScanner[] distributedScanners = createDistributedScanners(scanners);
- return new ParallelResultScanner(this.executor, this.numCaching, rowKeyDistributor, distributedScanners);
- }
- }
-
- private ResultScanner[] createDistributedScanners(ResultScanner[] scanners) throws IOException {
- int maxIndividualScans = (scanners.length + (this.numParallelThreads - 1)) / this.numParallelThreads;
- List<List<ResultScanner>> scannerDistributions = new ArrayList<>(this.numParallelThreads);
- for (int i = 0; i < this.numParallelThreads; ++i) {
- scannerDistributions.add(new ArrayList<ResultScanner>(maxIndividualScans));
- }
- for (int i = 0; i < scanners.length; ++i) {
- scannerDistributions.get(i % this.numParallelThreads).add(scanners[i]);
- }
- DistributedScanner[] distributedScanners = new DistributedScanner[this.numParallelThreads];
- for (int i = 0; i < distributedScanners.length; ++i) {
- List<ResultScanner> scannerDistribution = scannerDistributions.get(i);
- ResultScanner[] scannersForDistributedScanner = scannerDistribution.toArray(new ResultScanner[scannerDistribution.size()]);
- distributedScanners[i] = new DistributedScanner(rowKeyDistributor, scannersForDistributedScanner);
- }
- return distributedScanners;
- }
-
-}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelResultScanner.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java
similarity index 66%
rename from commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelResultScanner.java
rename to commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java
index 0e016130607f..11cf4ca36040 100644
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ParallelResultScanner.java
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java
@@ -14,19 +14,19 @@
* limitations under the License.
*/
-package com.navercorp.pinpoint.common.hbase;
+package com.navercorp.pinpoint.common.hbase.parallel;
import com.sematext.hbase.wd.AbstractRowKeyDistributor;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
+import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
+import org.springframework.data.hadoop.hbase.HbaseAccessor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
/**
@@ -34,34 +34,70 @@
*/
public class ParallelResultScanner implements ResultScanner {
- private static final int DEFAULT_SCAN_TASK_QUEUE_SIZE = 100;
-
private final AbstractRowKeyDistributor keyDistributor;
private final List<ScanTask> scanTasks;
private final Result[] nextResults;
private Result next = null;
- public ParallelResultScanner(ExecutorService executor, int numCaching, AbstractRowKeyDistributor keyDistributor, ResultScanner[] scanners) throws IOException {
+ public ParallelResultScanner(String tableName, HbaseAccessor hbaseAccessor, ExecutorService executor, Scan originalScan, AbstractRowKeyDistributor keyDistributor, int numParallelThreads) throws IOException {
+ if (hbaseAccessor == null) {
+ throw new NullPointerException("hbaseAccessor must not be null");
+ }
if (executor == null) {
throw new NullPointerException("executor must not be null");
}
if (keyDistributor == null) {
throw new NullPointerException("keyDistributor must not be null");
}
- if (scanners == null) {
- throw new NullPointerException("scanners must not be null");
+ if (originalScan == null) {
+ throw new NullPointerException("originalScan must not be null");
}
this.keyDistributor = keyDistributor;
- this.nextResults = new Result[scanners.length];
- this.scanTasks = new ArrayList<>(scanners.length);
- final int scanTaskQueueSize = numCaching < DEFAULT_SCAN_TASK_QUEUE_SIZE ? numCaching : DEFAULT_SCAN_TASK_QUEUE_SIZE;
- for (ResultScanner scanner : scanners) {
- ScanTask scanTask = new ScanTask(scanner, scanTaskQueueSize);
- this.scanTasks.add(scanTask);
+
+ final ScanTaskConfig scanTaskConfig = new ScanTaskConfig(tableName, hbaseAccessor, keyDistributor, originalScan.getCaching());
+ final Scan[] splitScans = splitScans(originalScan);
+
+ this.scanTasks = createScanTasks(scanTaskConfig, splitScans, numParallelThreads);
+ this.nextResults = new Result[scanTasks.size()];
+ for (ScanTask scanTask : scanTasks) {
executor.execute(scanTask);
}
}
+ private Scan[] splitScans(Scan originalScan) throws IOException {
+ Scan[] scans = this.keyDistributor.getDistributedScans(originalScan);
+ for (int i = 0; i < scans.length; ++i) {
+ Scan scan = scans[i];
+ scan.setId(originalScan.getId() + "-" + i);
+ }
+ return scans;
+ }
+
+ private List<ScanTask> createScanTasks(ScanTaskConfig scanTaskConfig, Scan[] splitScans, int numParallelThreads) {
+ if (splitScans.length <= numParallelThreads) {
+ List<ScanTask> scanTasks = new ArrayList<>(splitScans.length);
+ for (Scan scan : splitScans) {
+ scanTasks.add(new ScanTask(scanTaskConfig, scan));
+ }
+ return scanTasks;
+ } else {
+ int maxIndividualScans = (splitScans.length + (numParallelThreads - 1)) / numParallelThreads;
+ List<List<Scan>> scanDistributions = new ArrayList<>(numParallelThreads);
+ for (int i = 0; i < numParallelThreads; ++i) {
+ scanDistributions.add(new ArrayList<Scan>(maxIndividualScans));
+ }
+ for (int i = 0; i < splitScans.length; ++i) {
+ scanDistributions.get(i % numParallelThreads).add(splitScans[i]);
+ }
+ List<ScanTask> scanTasks = new ArrayList<>(numParallelThreads);
+ for (List<Scan> scanDistribution : scanDistributions) {
+ Scan[] scansForSingleTask = scanDistribution.toArray(new Scan[scanDistribution.size()]);
+ scanTasks.add(new ScanTask(scanTaskConfig, scansForSingleTask));
+ }
+ return scanTasks;
+ }
+ }
+
private boolean hasNext() throws IOException {
if (next != null) {
return true;
@@ -85,6 +121,8 @@ private Result nextInternal() throws IOException {
int indexOfResultToUse = -1;
for (int i = 0; i < this.scanTasks.size(); ++i) {
ScanTask scanTask = this.scanTasks.get(i);
+ // fail fast in case of errors
+ checkTask(scanTask);
if (nextResults[i] == null) {
try {
nextResults[i] = scanTask.getResult();
@@ -108,57 +146,10 @@ private Result nextInternal() throws IOException {
return result;
}
- private static class ScanTask implements Runnable {
-
- private static final Result END_RESULT = new Result();
-
- private final ResultScanner scanner;
- private final BlockingQueue<Result> resultQueue;
- private volatile boolean isQueueClosed = false;
- private volatile boolean isFinished = false;
-
- private ScanTask(ResultScanner scanner, int queueSize) {
- this.scanner = scanner;
- this.resultQueue = new ArrayBlockingQueue<>(queueSize);
- }
-
- @Override
- public void run() {
- try {
- for (Result result : this.scanner) {
- this.resultQueue.put(result);
- if (this.isFinished) {
- break;
- }
- }
- this.resultQueue.put(END_RESULT);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- this.resultQueue.clear();
- this.resultQueue.add(END_RESULT);
- } finally {
- this.isFinished = true;
- this.scanner.close();
- }
- }
-
- public Result getResult() throws InterruptedException {
- if (this.isQueueClosed) {
- return null;
- }
- Result take = this.resultQueue.take();
- if (take == END_RESULT) {
- this.isQueueClosed = true;
- return null;
- }
- return take;
- }
-
- public void close() {
- this.isFinished = true;
- // signal threads blocked on resultQueue
- this.resultQueue.clear();
- this.resultQueue.offer(END_RESULT);
+ private void checkTask(ScanTask scanTask) {
+ Throwable th = scanTask.getThrowable();
+ if (th != null) {
+ throw new ScanTaskException(th);
}
}
@@ -229,6 +220,5 @@ public void remove() {
throw new UnsupportedOperationException();
}
};
-
}
}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTask.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTask.java
new file mode 100644
index 000000000000..75fd80fd73bb
--- /dev/null
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTask.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2015 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.common.hbase.parallel;
+
+import com.sematext.hbase.wd.AbstractRowKeyDistributor;
+import com.sematext.hbase.wd.DistributedScanner;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.client.HTableInterface;
+import org.apache.hadoop.hbase.client.HTableInterfaceFactory;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.ResultScanner;
+import org.apache.hadoop.hbase.client.Scan;
+import org.springframework.data.hadoop.hbase.HbaseUtils;
+
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class ScanTask implements Runnable {
+
+ private static final Result END_RESULT = new Result();
+
+ private final String tableName;
+ private final Configuration configuration;
+ private final Charset charset;
+ private final HTableInterfaceFactory tableFactory;
+ private final AbstractRowKeyDistributor rowKeyDistributor;
+
+ private final Scan[] scans;
+ private final BlockingQueue<Result> resultQueue;
+
+ private volatile Throwable throwable;
+ private volatile boolean isQueueClosed = false;
+ private volatile boolean isDone = false;
+
+ public ScanTask(ScanTaskConfig scanTaskConfig, Scan... scans) {
+ if (scanTaskConfig == null) {
+ throw new NullPointerException("scanTaskConfig must not be null");
+ }
+ if (scans == null) {
+ throw new NullPointerException("scans must not be null");
+ }
+ if (scans.length == 0) {
+ throw new IllegalArgumentException("scans must not be empty");
+ }
+ this.tableName = scanTaskConfig.getTableName();
+ this.configuration = scanTaskConfig.getConfiguration();
+ this.charset = scanTaskConfig.getCharset();
+ this.tableFactory = scanTaskConfig.getTableFactory();
+ this.rowKeyDistributor = scanTaskConfig.getRowKeyDistributor();
+ this.scans = scans;
+ this.resultQueue = new ArrayBlockingQueue<>(scanTaskConfig.getScanTaskQueueSize());
+ }
+
+ @Override
+ public void run() {
+ HTableInterface table = null;
+ try {
+ table = HbaseUtils.getHTable(this.tableName, this.configuration, this.charset, this.tableFactory);
+ ResultScanner scanner = createResultScanner(table);
+ try {
+ for (Result result : scanner) {
+ this.resultQueue.put(result);
+ if (this.isDone) {
+ break;
+ }
+ }
+ } finally {
+ this.isDone = true;
+ this.resultQueue.put(END_RESULT);
+ scanner.close();
+ }
+ } catch (Throwable th) {
+ this.throwable = th;
+ this.resultQueue.clear();
+ this.resultQueue.offer(END_RESULT);
+ } finally {
+ HbaseUtils.releaseTable(this.tableName, table);
+ }
+ }
+
+ private ResultScanner createResultScanner(HTableInterface table) throws IOException {
+ if (scans.length == 1) {
+ Scan scan = scans[0];
+ return table.getScanner(scan);
+ } else {
+ ResultScanner[] scanners = new ResultScanner[this.scans.length];
+ for (int i = 0; i < scanners.length; ++i) {
+ scanners[i] = table.getScanner(this.scans[i]);
+ }
+ return new DistributedScanner(this.rowKeyDistributor, scanners);
+ }
+ }
+
+ public Result getResult() throws InterruptedException {
+ if (this.isQueueClosed) {
+ return null;
+ }
+ Result take = this.resultQueue.take();
+ if (take == END_RESULT) {
+ this.isQueueClosed = true;
+ return null;
+ }
+ return take;
+ }
+
+ public void close() {
+ this.isDone = true;
+ // signal threads blocked on resultQueue
+ this.resultQueue.clear();
+ this.resultQueue.add(END_RESULT);
+ }
+
+ public Throwable getThrowable() {
+ return this.throwable;
+ }
+
+}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskConfig.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskConfig.java
new file mode 100644
index 000000000000..f17d9ec3923d
--- /dev/null
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskConfig.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2015 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.common.hbase.parallel;
+
+import com.sematext.hbase.wd.AbstractRowKeyDistributor;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.client.HTableInterfaceFactory;
+import org.springframework.data.hadoop.hbase.HbaseAccessor;
+
+import java.nio.charset.Charset;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class ScanTaskConfig {
+
+ private final String tableName;
+ private final Configuration configuration;
+ private final Charset charset;
+ private final HTableInterfaceFactory tableFactory;
+
+ private final AbstractRowKeyDistributor rowKeyDistributor;
+ private final int scanTaskQueueSize;
+
+ public ScanTaskConfig(String tableName, HbaseAccessor hbaseAccessor, AbstractRowKeyDistributor rowKeyDistributor, int scanCaching) {
+ this(tableName, hbaseAccessor.getConfiguration(), hbaseAccessor.getCharset(), hbaseAccessor.getTableFactory(), rowKeyDistributor, scanCaching);
+ }
+
+ public ScanTaskConfig(String tableName, Configuration configuration, Charset charset, HTableInterfaceFactory tableFactory, AbstractRowKeyDistributor rowKeyDistributor, int scanCaching) {
+ if (tableName == null) {
+ throw new NullPointerException("No table specified");
+ }
+ if (rowKeyDistributor == null) {
+ throw new NullPointerException("rowKeyDistributor must not be null");
+ }
+ this.tableName = tableName;
+ this.configuration = configuration;
+ this.charset = charset;
+ this.tableFactory = tableFactory;
+ this.rowKeyDistributor = rowKeyDistributor;
+ if (scanCaching > 0) {
+ this.scanTaskQueueSize = scanCaching;
+ } else {
+ this.scanTaskQueueSize = configuration.getInt(
+ HConstants.HBASE_CLIENT_SCANNER_CACHING,
+ HConstants.DEFAULT_HBASE_CLIENT_SCANNER_CACHING);
+ }
+ }
+
+ public String getTableName() {
+ return tableName;
+ }
+
+ public Configuration getConfiguration() {
+ return configuration;
+ }
+
+ public Charset getCharset() {
+ return charset;
+ }
+
+ public HTableInterfaceFactory getTableFactory() {
+ return tableFactory;
+ }
+
+ public AbstractRowKeyDistributor getRowKeyDistributor() {
+ return rowKeyDistributor;
+ }
+
+ public int getScanTaskQueueSize() {
+ return scanTaskQueueSize;
+ }
+}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskException.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskException.java
new file mode 100644
index 000000000000..1df0a24953a1
--- /dev/null
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ScanTaskException.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2015 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.common.hbase.parallel;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class ScanTaskException extends RuntimeException {
+
+ private static final long serialVersionUID = 8554224683436066023L;
+
+ public ScanTaskException(Throwable th) {
+ super(th);
+ }
+
+ public ScanTaskException(String message, Throwable th) {
+ super(message, th);
+ }
+}
diff --git a/docker/pinpoint-web/hbase.properties b/docker/pinpoint-web/hbase.properties
index 4161185c010c..b94b1893aa93 100644
--- a/docker/pinpoint-web/hbase.properties
+++ b/docker/pinpoint-web/hbase.properties
@@ -19,4 +19,10 @@ hbase.ipc.client.socket.timeout.write=60000
hbase.client.thread.max=128
hbase.client.threadPool.queueSize=5120
# prestartAllCoreThreads
-hbase.client.threadPool.prestart=false
\ No newline at end of file
+hbase.client.threadPool.prestart=false
+
+#==================================================================================
+# hbase parallel scan options
+hbase.client.parallel.scan.enable=false
+hbase.client.parallel.scan.maxthreads=128
+hbase.client.parallel.scan.maxthreadsperscan=16
\ No newline at end of file
diff --git a/quickstart/web/src/main/resources/hbase.properties b/quickstart/web/src/main/resources/hbase.properties
index be6e5ea43e88..ac1e4a555505 100644
--- a/quickstart/web/src/main/resources/hbase.properties
+++ b/quickstart/web/src/main/resources/hbase.properties
@@ -20,4 +20,10 @@ hbase.ipc.client.socket.timeout.write=60000
hbase.client.thread.max=128
hbase.client.threadPool.queueSize=5120
# prestartAllCoreThreads
-hbase.client.threadPool.prestart=false
\ No newline at end of file
+hbase.client.threadPool.prestart=false
+
+#==================================================================================
+# hbase parallel scan options
+hbase.client.parallel.scan.enable=false
+hbase.client.parallel.scan.maxthreads=128
+hbase.client.parallel.scan.maxthreadsperscan=16
\ No newline at end of file
| null | test | train | "2015-12-24T09:28:54" | "2015-12-28T08:00:33Z" | panta21 | test |
pinpoint-apm/pinpoint/1362_1406 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1362 | pinpoint-apm/pinpoint/1406 | [
"keyword_pr_to_issue"
] | d26789c096920fad0907af22caadbd78fdba281f | 10e23870e16c60067284a49987092d4348db6b13 | [
"Reopening as scanner creations may be done in parallel as well, and this may cut some time during scanner creation.\n",
"Reopening to apply parallel scan for finding accept applications for nodes when drawing the server map.\n"
] | [] | "2016-01-06T07:05:51Z" | [
"enhancement"
] | Implement parallel result scanner for scanning rows distributed with RowKeyDistributor | Allow distributed scanners to run in parallel that would theoretically allow for better performance when scanning rows that are well distributed using `RowKeyDistributor`
| [
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java
index c577b5fa3482..ff47ecdf7fc3 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java
@@ -53,6 +53,8 @@
@Repository
public class HbaseHostApplicationMapDao implements HostApplicationMapDao {
+ private static final int HOST_APPLICATION_MAP_VER2_NUM_PARTITIONS = 4;
+
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private int scanCacheSize = 10;
@@ -127,7 +129,7 @@ public Set<AcceptApplication> findAcceptApplicationName(Application fromApplicat
throw new NullPointerException("fromApplication must not be null");
}
final Scan scan = createScan(fromApplication, range);
- final List<List<AcceptApplication>> result = hbaseOperations2.find(HBaseTables.HOST_APPLICATION_MAP_VER2, scan, acceptApplicationRowKeyDistributor, hostApplicationMapperVer2);
+ final List<List<AcceptApplication>> result = hbaseOperations2.findParallel(HBaseTables.HOST_APPLICATION_MAP_VER2, scan, acceptApplicationRowKeyDistributor, hostApplicationMapperVer2, HOST_APPLICATION_MAP_VER2_NUM_PARTITIONS);
if (CollectionUtils.isNotEmpty(result)) {
final Set<AcceptApplication> resultSet = new HashSet<>();
for (List<AcceptApplication> resultList : result) {
| null | val | train | "2016-01-06T03:39:39" | "2015-12-18T10:17:24Z" | Xylus | test |
pinpoint-apm/pinpoint/1443_1457 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1443 | pinpoint-apm/pinpoint/1457 | [
"keyword_pr_to_issue"
] | dd7c6f23472ca9bf0a8eef571c694921113145ee | 6ec1897e324542354f8999ec30460c9f2b6ded3b | [] | [] | "2016-01-15T09:04:38Z" | [
"bug"
] | Fixed invalid classloading when using the AspectJ + Spring AOP | - support spring aspectj weaving
- support OSGI (atlassian jira)
- #1583 Enhancement PlaingClassLoaderHandler for Jira.
| [
"bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointStarter.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java"
] | [
"bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointStarter.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java"
] | [] | diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointStarter.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointStarter.java
index 056da3801769..7beb09d8df76 100644
--- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointStarter.java
+++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointStarter.java
@@ -127,7 +127,7 @@ public void start() {
agentClassLoader.setBootClass(bootClass);
logger.info("pinpoint agent [" + bootClass + "] starting...");
- AgentOption option = createAgentOption(agentArgs, instrumentation, profilerConfig, pluginJars, bootStrapCore, serviceTypeRegistryService, annotationKeyRegistryService, bootStrapCoreJar);
+ AgentOption option = createAgentOption(agentArgs, instrumentation, profilerConfig, pluginJars, bootStrapCore, serviceTypeRegistryService, annotationKeyRegistryService);
Agent pinpointAgent = agentClassLoader.boot(option);
pinpointAgent.start();
registerShutdownHook(pinpointAgent);
@@ -139,9 +139,9 @@ public void start() {
}
}
- private AgentOption createAgentOption(String agentArgs, Instrumentation instrumentation, ProfilerConfig profilerConfig, URL[] pluginJars, String bootStrapJarPath, ServiceTypeRegistryService serviceTypeRegistryService, AnnotationKeyRegistryService annotationKeyRegistryService, String bootStrapCoreJar) {
+ private AgentOption createAgentOption(String agentArgs, Instrumentation instrumentation, ProfilerConfig profilerConfig, URL[] pluginJars, String bootStrapJarCorePath, ServiceTypeRegistryService serviceTypeRegistryService, AnnotationKeyRegistryService annotationKeyRegistryService) {
- return new DefaultAgentOption(agentArgs, instrumentation, profilerConfig, pluginJars, bootStrapJarPath, serviceTypeRegistryService, annotationKeyRegistryService);
+ return new DefaultAgentOption(agentArgs, instrumentation, profilerConfig, pluginJars, bootStrapJarCorePath, serviceTypeRegistryService, annotationKeyRegistryService);
}
// for test
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java
index bafcb5cb51f9..1733f61f1c9e 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java
@@ -215,7 +215,7 @@ private Class<?> injectToPlainClassLoader(ClassPool pool, ClassLoader classLoade
}
}
if (logger.isInfoEnabled()) {
- logger.debug("defineClass pluginClass:{} cl:{}", className, classLoader);
+ logger.info("defineClass pluginClass:{} cl:{}", className, classLoader);
}
final byte[] bytes = ct.toBytecode();
return (Class<?>)DEFINE_CLASS.invoke(classLoader, ct.getName(), bytes, 0, bytes.length);
| null | train | train | "2016-01-15T09:56:35" | "2016-01-14T06:03:04Z" | emeroad | test |
pinpoint-apm/pinpoint/1462_1464 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1462 | pinpoint-apm/pinpoint/1464 | [
"keyword_pr_to_issue"
] | e97d3bef6e5210af8fb2c7707ad71df37ca0763b | 0bb3140cbd5e2553c06fb1acdf2beb1c1c2d5464 | [
"~~Reopening to add service type to request parameter.~~\nReopening to modify response for `/getInactiveAgents`.\n",
"Reopening to add API for removing all inactive agents from index.\n"
] | [] | "2016-01-19T07:29:09Z" | [
"enhancement"
] | Add APIs for managing registered agents | There is currently not a lot of ways to manage agent ids once they're mapped to an application. These data tend to linger around until the TTL has passed and ends up clogging the application index.
There needs to be APIs for doing 2 things:
1. Detect inactive agents (those that were registered, but are no longer in use) and provide a way to delete them (and their application name mapping)
2. Identify duplicate agent ids that are mapped to more than 1 application name.
| [
"web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/AgentStatDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/AgentStatDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/alarm/AlarmPartitionerTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/GcCountCheckerTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/HeapUsageRateCheckerTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/JvmCpuUsageRateCheckerTest.java"
] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java
index fedae0275299..5aae7f08b41a 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java
@@ -26,6 +26,9 @@
import com.navercorp.pinpoint.web.service.AdminService;
+import java.util.List;
+import java.util.Map;
+
/**
* @author netspider
* @author HyunGil Jeong
@@ -67,4 +70,25 @@ public String removeAgentId(
}
}
+ @RequestMapping(value = "/agentIdMap")
+ @ResponseBody
+ public Map<String, List<String>> agentIdMap() {
+ return this.adminService.getAgentIdMap();
+ }
+
+ @RequestMapping(value = "/duplicateAgentIdMap")
+ @ResponseBody
+ public Map<String, List<String>> duplicateAgentIdMap() {
+ return this.adminService.getDuplicateAgentIdMap();
+ }
+
+ @RequestMapping(value = "/getInactiveAgents")
+ @ResponseBody
+ public Map<String, List<String>> getInactiveAgents(
+ @RequestParam(value = "applicationName", required = true) String applicationName,
+ @RequestParam(value = "durationDays", defaultValue = "30") int durationDays) {
+ logger.info("get inactive agents - applicationName: [{}], duration: {} days.", applicationName, durationDays);
+ return this.adminService.getInactiveAgents(applicationName, durationDays);
+ }
+
}
\ No newline at end of file
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentStatDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentStatDao.java
index 0a7bcd616284..00a989e87867 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentStatDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentStatDao.java
@@ -28,4 +28,6 @@ public interface AgentStatDao {
List<AgentStat> scanAgentStatList(String agentId, Range range);
+ boolean agentStatExists(String agentId, Range range);
+
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDao.java
index 61d7a106e453..12eaaa777824 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDao.java
@@ -30,11 +30,14 @@
import com.navercorp.pinpoint.web.vo.AgentStat;
import com.navercorp.pinpoint.web.vo.Range;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
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.data.hadoop.hbase.ResultsExtractor;
import org.springframework.data.hadoop.hbase.RowMapper;
import org.springframework.stereotype.Repository;
@@ -66,6 +69,7 @@ public void setScanCacheSize(int scanCacheSize) {
this.scanCacheSize = scanCacheSize;
}
+ @Override
public List<AgentStat> scanAgentStatList(String agentId, Range range) {
if (agentId == null) {
throw new NullPointerException("agentId must not be null");
@@ -84,16 +88,61 @@ public List<AgentStat> scanAgentStatList(String agentId, Range range) {
List<List<AgentStat>> intermediate = hbaseOperations2.find(HBaseTables.AGENT_STAT, scan, rowKeyDistributor, agentStatMapper);
- int expectedSize = (int)(range.getRange() / 5000); // data for 5 seconds
+ int expectedSize = (int) (range.getRange() / 5000); // data for 5 seconds
List<AgentStat> merged = new ArrayList<>(expectedSize);
- for(List<AgentStat> each : intermediate) {
+ for (List<AgentStat> each : intermediate) {
merged.addAll(each);
}
return merged;
}
+ @Override
+ public boolean agentStatExists(String agentId, Range range) {
+ if (agentId == null) {
+ throw new NullPointerException("agentId must not be null");
+ }
+ if (range == null) {
+ throw new NullPointerException("range must not be null");
+ }
+
+ if (logger.isDebugEnabled()) {
+ logger.debug("checking for stat data existence : agentId={}, {}", agentId, range);
+ }
+
+ Scan scan = createScan(agentId, range);
+ scan.setCaching(1);
+ scan.addFamily(HBaseTables.AGENT_STAT_CF_STATISTICS);
+
+ return hbaseOperations2.find(HBaseTables.AGENT_STAT, scan, rowKeyDistributor, new AgentStatDataExistsResultsExtractor(this.agentStatMapper));
+ }
+
+ private class AgentStatDataExistsResultsExtractor implements ResultsExtractor<Boolean> {
+
+ private final RowMapper<List<AgentStat>> agentStatMapper;
+
+ private AgentStatDataExistsResultsExtractor(RowMapper<List<AgentStat>> agentStatMapper) {
+ this.agentStatMapper = agentStatMapper;
+ }
+
+ @Override
+ public Boolean extractData(ResultScanner results) throws Exception {
+ int matchCnt = 0;
+ for (Result result : results) {
+ if (!result.isEmpty()) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("stat data exists, most recent data : {}", this.agentStatMapper.mapRow(result, matchCnt++));
+ }
+ return true;
+ } else {
+ return false;
+ }
+ }
+ return false;
+ }
+ }
+
/**
* make a row key based on timestamp
* FIXME there is the same duplicate code at collector's dao module
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java
index e22ed83964c7..2e7e51948ece 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java
@@ -16,6 +16,9 @@
package com.navercorp.pinpoint.web.service;
+import java.util.List;
+import java.util.Map;
+
/**
* @author netspider
* @author HyunGil Jeong
@@ -25,5 +28,11 @@ public interface AdminService {
void removeApplicationName(String applicationName);
void removeAgentId(String applicationName, String agentId);
-
+
+ Map<String, List<String>> getAgentIdMap();
+
+ Map<String, List<String>> getDuplicateAgentIdMap();
+
+ Map<String, List<String>> getInactiveAgents(String applicationName, int durationDays);
+
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java
index 279ffb0dcff8..f55f5a3c2792 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java
@@ -16,11 +16,23 @@
package com.navercorp.pinpoint.web.service;
+import com.google.common.collect.Ordering;
+import com.navercorp.pinpoint.web.dao.AgentStatDao;
+import com.navercorp.pinpoint.web.vo.Application;
+import com.navercorp.pinpoint.web.vo.Range;
+import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.navercorp.pinpoint.web.dao.ApplicationIndexDao;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
/**
* @author netspider
* @author HyunGil Jeong
@@ -31,6 +43,9 @@ public class AdminServiceImpl implements AdminService {
@Autowired
private ApplicationIndexDao applicationIndexDao;
+ @Autowired
+ private AgentStatDao agentStatDao;
+
@Override
public void removeApplicationName(String applicationName) {
applicationIndexDao.deleteApplicationName(applicationName);
@@ -41,4 +56,69 @@ public void removeAgentId(String applicationName, String agentId) {
applicationIndexDao.deleteAgentId(applicationName, agentId);
}
+ @Override
+ public Map<String, List<String>> getAgentIdMap() {
+ Map<String, List<String>> agentIdMap = new TreeMap<>(Ordering.usingToString());
+ List<Application> applications = this.applicationIndexDao.selectAllApplicationNames();
+ for (Application application : applications) {
+ List<String> agentIds = this.applicationIndexDao.selectAgentIds(application.getName());
+ for (String agentId : agentIds) {
+ if (!agentIdMap.containsKey(agentId)) {
+ agentIdMap.put(agentId, new ArrayList<String>());
+ }
+ agentIdMap.get(agentId).add(application.toString());
+ }
+ }
+ return agentIdMap;
+ }
+
+ @Override
+ public Map<String, List<String>> getDuplicateAgentIdMap() {
+ Map<String, List<String>> duplicateAgentIdMap = new TreeMap<>(Ordering.usingToString());
+ Map<String, List<String>> agentIdMap = this.getAgentIdMap();
+ for (Map.Entry<String, List<String>> entry : agentIdMap.entrySet()) {
+ String agentId = entry.getKey();
+ List<String> applications = entry.getValue();
+ if (applications.size() > 1) {
+ duplicateAgentIdMap.put(agentId, applications);
+ }
+ }
+ return duplicateAgentIdMap;
+ }
+
+ @Override
+ public Map<String, List<String>> getInactiveAgents(String applicationName, int durationDays) {
+ if (applicationName == null) {
+ throw new NullPointerException("applicationName must not be null");
+ }
+ if (durationDays < 30) {
+ throw new IllegalArgumentException("duration may not be less than 30 days");
+ }
+ if (durationDays > 180) {
+ throw new IllegalArgumentException("duration may not be greater than 180 days");
+ }
+ List<String> agentIds = this.applicationIndexDao.selectAgentIds(applicationName);
+ if (CollectionUtils.isEmpty(agentIds)) {
+ return Collections.emptyMap();
+ }
+
+ final long toTimestamp = System.currentTimeMillis();
+ Calendar cal = Calendar.getInstance();
+ cal.add(Calendar.DATE, durationDays * -1);
+ final long fromTimestamp = cal.getTimeInMillis();
+ Range queryRange = new Range(fromTimestamp, toTimestamp);
+
+ Map<String, List<String>> agentIdMap = this.getAgentIdMap();
+
+ Map<String, List<String>> inactiveAgentMap = new TreeMap<>(Ordering.usingToString());
+ for (String agentId : agentIds) {
+ boolean dataExists = this.agentStatDao.agentStatExists(agentId, queryRange);
+ if (!dataExists) {
+ List<String> applications = agentIdMap.get(agentId);
+ inactiveAgentMap.put(agentId, applications);
+ }
+ }
+ return inactiveAgentMap;
+ }
+
}
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/alarm/AlarmPartitionerTest.java b/web/src/test/java/com/navercorp/pinpoint/web/alarm/AlarmPartitionerTest.java
index 0375b105a0f4..ed0f1e1fffd8 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/alarm/AlarmPartitionerTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/alarm/AlarmPartitionerTest.java
@@ -26,7 +26,6 @@
import org.springframework.batch.item.ExecutionContext;
import com.navercorp.pinpoint.common.trace.ServiceType;
-import com.navercorp.pinpoint.web.alarm.AlarmPartitioner;
import com.navercorp.pinpoint.web.dao.ApplicationIndexDao;
import com.navercorp.pinpoint.web.vo.Application;
@@ -55,7 +54,7 @@ public List<Application> selectAllApplicationNames() {
return apps;
}
-
+
@Override
public List<String> selectAgentIds(String applicationName) {
return null;
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/GcCountCheckerTest.java b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/GcCountCheckerTest.java
index b3890aae2973..50a5ca025d25 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/GcCountCheckerTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/GcCountCheckerTest.java
@@ -53,6 +53,11 @@ public List<AgentStat> scanAgentStatList(String agentId, Range range) {
return agentStatList;
}
+
+ @Override
+ public boolean agentStatExists(String agentId, Range range) {
+ return true;
+ }
};
applicationIndexDao = new ApplicationIndexDao() {
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/HeapUsageRateCheckerTest.java b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/HeapUsageRateCheckerTest.java
index 64c9a96a3290..a95897a3a3c5 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/HeapUsageRateCheckerTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/HeapUsageRateCheckerTest.java
@@ -29,8 +29,6 @@
import com.navercorp.pinpoint.web.alarm.CheckerCategory;
import com.navercorp.pinpoint.web.alarm.DataCollectorFactory;
import com.navercorp.pinpoint.web.alarm.DataCollectorFactory.DataCollectorCategory;
-import com.navercorp.pinpoint.web.alarm.checker.AgentChecker;
-import com.navercorp.pinpoint.web.alarm.checker.HeapUsageRateChecker;
import com.navercorp.pinpoint.web.alarm.collector.AgentStatDataCollector;
import com.navercorp.pinpoint.web.alarm.vo.Rule;
import com.navercorp.pinpoint.web.dao.AgentStatDao;
@@ -66,6 +64,11 @@ public List<AgentStat> scanAgentStatList(String agentId, Range range) {
return agentStatList;
}
+
+ @Override
+ public boolean agentStatExists(String agentId, Range range) {
+ return true;
+ }
};
applicationIndexDao = new ApplicationIndexDao() {
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/JvmCpuUsageRateCheckerTest.java b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/JvmCpuUsageRateCheckerTest.java
index 318aeb1bc136..2819bd30edd9 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/JvmCpuUsageRateCheckerTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/JvmCpuUsageRateCheckerTest.java
@@ -28,8 +28,6 @@
import com.navercorp.pinpoint.web.alarm.CheckerCategory;
import com.navercorp.pinpoint.web.alarm.DataCollectorFactory;
import com.navercorp.pinpoint.web.alarm.DataCollectorFactory.DataCollectorCategory;
-import com.navercorp.pinpoint.web.alarm.checker.AgentChecker;
-import com.navercorp.pinpoint.web.alarm.checker.JvmCpuUsageRateChecker;
import com.navercorp.pinpoint.web.alarm.collector.AgentStatDataCollector;
import com.navercorp.pinpoint.web.alarm.vo.Rule;
import com.navercorp.pinpoint.web.dao.AgentStatDao;
@@ -63,6 +61,11 @@ public List<AgentStat> scanAgentStatList(String agentId, Range range) {
return agentStatList;
}
+
+ @Override
+ public boolean agentStatExists(String agentId, Range range) {
+ return true;
+ }
};
applicationIndexDao = new ApplicationIndexDao() {
| train | train | "2016-01-19T08:49:58" | "2016-01-19T06:18:53Z" | Xylus | test |
pinpoint-apm/pinpoint/1469_1471 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1469 | pinpoint-apm/pinpoint/1471 | [
"keyword_pr_to_issue"
] | daeb0bd398f7dc8ea98a486694fd5c531b91ead9 | c402940564acb3814a673b18a707b1ee13419691 | [] | [] | "2016-01-20T09:46:28Z" | [
"enhancement"
] | Remove unnecessary agent status queries when drawing the server map | Agent status check is necessary to add agent to nodes that do not have call statistics.
Agents that do have these statistics should be added to the server map node regardless of their current status, which makes checking for their status unnecessary.
Removing these unnecessary agent status queries should speed up server map creation time.
| [
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/AgentLifeCycleDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/AgentLifeCycleDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java
index a40d58645ede..fac29651ea52 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilder.java
@@ -57,17 +57,17 @@ public ApplicationMap build(Application application, AgentInfoService agentInfoS
Node node = new Node(application);
Set<AgentInfo> agentInfos = agentInfoService.getAgentsByApplicationName(application.getName(), range.getTo());
- for (Iterator<AgentInfo> iterator = agentInfos.iterator(); iterator.hasNext();) {
- AgentInfo agentInfo = iterator.next();
- if (!isAgentRunning(agentInfo)) {
- iterator.remove();
+ Set<AgentInfo> runningAgents = new HashSet<>();
+ for (AgentInfo agentInfo : agentInfos) {
+ if (isAgentRunning(agentInfo)) {
+ runningAgents.add(agentInfo);
}
}
- if (agentInfos.isEmpty()) {
+ if (runningAgents.isEmpty()) {
return new ApplicationMap(range, nodeList, emptyLinkList);
} else {
ServerBuilder serverBuilder = new ServerBuilder();
- serverBuilder.addAgentInfo(agentInfos);
+ serverBuilder.addAgentInfo(runningAgents);
ServerInstanceList serverInstanceList = serverBuilder.build();
node.setServerInstanceList(serverInstanceList);
node.setNodeHistogram(new NodeHistogram(application, range));
@@ -100,7 +100,8 @@ public ApplicationMap build(LinkDataDuplexMap linkDataDuplexMap, final AgentInfo
AgentInfoPopulator agentInfoPopulator = new AgentInfoPopulator() {
@Override
public void addAgentInfos(Node node) {
- Set<AgentInfo> agentList = agentInfoService.getAgentsByApplicationName(node.getApplication().getName(), range.getTo());
+ long timestamp = range.getTo();
+ Set<AgentInfo> agentList = agentInfoService.getAgentsByApplicationNameWithoutStatus(node.getApplication().getName(), timestamp);
if (agentList.isEmpty()) {
logger.warn("agentInfo not found. applicationName:{}", node.getApplication());
// avoid NPE
@@ -109,7 +110,7 @@ public void addAgentInfos(Node node) {
}
logger.debug("add agentInfo. {}, {}", node.getApplication(), agentList);
ServerBuilder builder = new ServerBuilder();
- agentList = filterAgentInfoByResponseData(agentList, node);
+ agentList = filterAgentInfoByResponseData(agentList, timestamp, node, agentInfoService);
builder.addAgentInfo(agentList);
ServerInstanceList serverInstanceList = builder.build();
@@ -447,7 +448,7 @@ private void appendServerInfo(Node node, LinkDataDuplexMap linkDataDuplexMap, Ag
* Filters AgentInfo by whether they actually have response data.
* For agents that do not have response data, check their status and include those that were alive.
*/
- private Set<AgentInfo> filterAgentInfoByResponseData(Set<AgentInfo> agentList, Node node) {
+ private Set<AgentInfo> filterAgentInfoByResponseData(Set<AgentInfo> agentList, long timestamp, Node node, AgentInfoService agentInfoService) {
Set<AgentInfo> filteredAgentInfo = new HashSet<>();
NodeHistogram nodeHistogram = node.getNodeHistogram();
@@ -457,12 +458,15 @@ private Set<AgentInfo> filterAgentInfoByResponseData(Set<AgentInfo> agentList, N
if (agentHistogramMap.containsKey(agentId)) {
filteredAgentInfo.add(agentInfo);
} else {
+ AgentStatus status = agentInfoService.getAgentStatus(agentId, timestamp);
+ agentInfo.setStatus(status);
if (isAgentRunning(agentInfo)) {
filteredAgentInfo.add(agentInfo);
}
}
}
+
return filteredAgentInfo;
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentLifeCycleDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentLifeCycleDao.java
index b0315761580f..efebaae3eb29 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentLifeCycleDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentLifeCycleDao.java
@@ -19,7 +19,7 @@
import com.navercorp.pinpoint.web.vo.AgentInfo;
import com.navercorp.pinpoint.web.vo.AgentStatus;
-import java.util.List;
+import java.util.Collection;
/**
* @author HyunGil Jeong
@@ -30,6 +30,6 @@ public interface AgentLifeCycleDao {
void populateAgentStatus(AgentInfo agentInfo, long timestamp);
- void populateAgentStatuses(List<AgentInfo> agentInfos, long timestamp);
+ void populateAgentStatuses(Collection<AgentInfo> agentInfos, long timestamp);
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDao.java
index 64f64a49b7ab..071caa285666 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDao.java
@@ -17,10 +17,10 @@
package com.navercorp.pinpoint.web.dao.hbase;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
import com.navercorp.pinpoint.common.util.AgentLifeCycleState;
-import com.navercorp.pinpoint.web.mapper.AgentLifeCycleMapper;
import com.navercorp.pinpoint.web.vo.AgentInfo;
import com.navercorp.pinpoint.web.vo.AgentStatus;
import org.apache.commons.collections.CollectionUtils;
@@ -93,7 +93,7 @@ public void populateAgentStatus(AgentInfo agentInfo, long timestamp) {
}
@Override
- public void populateAgentStatuses(List<AgentInfo> agentInfos, long timestamp) {
+ public void populateAgentStatuses(Collection<AgentInfo> agentInfos, long timestamp) {
if (CollectionUtils.isEmpty(agentInfos)) {
return;
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java
index f6ee044ad004..ac107b5de669 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java
@@ -41,7 +41,9 @@ public interface AgentInfoService {
Set<AgentInfo> getAgentsByApplicationName(String applicationName, long timestamp);
- Set<AgentInfo> getAgentsByApplicationName(String applicationName, long timestamp, long timeDiff);
+ Set<AgentInfo> getAgentsByApplicationNameWithoutStatus(String applicationName, long timestamp);
+
+ Set<AgentInfo> getRecentAgentsByApplicationName(String applicationName, long timestamp, long timeDiff);
AgentInfo getAgentInfo(String agentId, long timestamp);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java
index a1e787a58875..7c110b411878 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java
@@ -166,29 +166,39 @@ private List<String> getApplicationNameList(List<Application> applications) {
@Override
public Set<AgentInfo> getAgentsByApplicationName(String applicationName, long timestamp) {
- return this.getAgentsByApplicationName(applicationName, timestamp, timestamp);
+ Set<AgentInfo> agentInfos = this.getAgentsByApplicationNameWithoutStatus(applicationName, timestamp);
+ this.agentLifeCycleDao.populateAgentStatuses(agentInfos, timestamp);
+ return agentInfos;
}
@Override
- public Set<AgentInfo> getAgentsByApplicationName(String applicationName, long timestamp, long timeDiff) {
+ public Set<AgentInfo> getAgentsByApplicationNameWithoutStatus(String applicationName, long timestamp) {
if (applicationName == null) {
throw new NullPointerException("applicationName must not be null");
}
if (timestamp < 0) {
throw new IllegalArgumentException("timestamp must not be less than 0");
}
+
+ List<String> agentIds = this.applicationIndexDao.selectAgentIds(applicationName);
+ List<AgentInfo> agentInfos = this.agentInfoDao.getAgentInfos(agentIds, timestamp);
+ CollectionUtils.filter(agentInfos, PredicateUtils.notNullPredicate());
+ if (CollectionUtils.isEmpty(agentInfos)) {
+ return Collections.emptySet();
+ }
+ return new HashSet<>(agentInfos);
+ }
+
+ @Override
+ public Set<AgentInfo> getRecentAgentsByApplicationName(String applicationName, long timestamp, long timeDiff) {
if (timeDiff > timestamp) {
throw new IllegalArgumentException("timeDiff must not be greater than timestamp");
}
+
+ Set<AgentInfo> unfilteredAgentInfos = this.getAgentsByApplicationName(applicationName, timestamp);
+
final long eventTimestampFloor = timestamp - timeDiff;
- List<String> agentIds = this.applicationIndexDao.selectAgentIds(applicationName);
- List<AgentInfo> unfilteredAgentInfos = this.agentInfoDao.getAgentInfos(agentIds, timestamp);
- if (unfilteredAgentInfos == null || unfilteredAgentInfos.isEmpty()) {
- return Collections.emptySet();
- }
- CollectionUtils.filter(unfilteredAgentInfos, PredicateUtils.notNullPredicate());
- this.agentLifeCycleDao.populateAgentStatuses(unfilteredAgentInfos, timestamp);
Set<AgentInfo> filteredAgentInfos = new HashSet<>();
for (AgentInfo agentInfo : unfilteredAgentInfos) {
AgentStatus agentStatus = agentInfo.getStatus();
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java
index 3bb34fa88fa7..00053762d74e 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java
@@ -149,7 +149,7 @@ public List<AgentInfo> getRecentAgentInfoList(String applicationName, long timeD
long currentTime = System.currentTimeMillis();
- Set<AgentInfo> agentInfos = agentInfoService.getAgentsByApplicationName(applicationName, currentTime, timeDiff);
+ Set<AgentInfo> agentInfos = agentInfoService.getRecentAgentsByApplicationName(applicationName, currentTime, timeDiff);
for (AgentInfo agentInfo : agentInfos) {
ListUtils.addIfValueNotNull(agentInfoList, agentInfo);
}
| null | train | train | "2016-01-20T10:25:48" | "2016-01-20T07:24:10Z" | Xylus | test |
pinpoint-apm/pinpoint/1472_1477 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1472 | pinpoint-apm/pinpoint/1477 | [
"keyword_pr_to_issue"
] | 47dd0f9bc38de692d0bdab23f86770d75b04fab9 | 782de33e236cf4936c3c52dc82bd9473d5b3ea5e | [] | [] | "2016-01-21T06:59:40Z" | [
"bug"
] | fixed possibility of npe in ZookeeperClusterDataManager. | fixed possibility of npe.
Conditions
- If ZookeeperClusterDataManager's process method invoke, before ZookeeperClient constructor has completed.
| [
"collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/DefaultZookeeperClient.java",
"web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClient.java"
] | [
"collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/DefaultZookeeperClient.java",
"web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClient.java"
] | [] | diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/DefaultZookeeperClient.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/DefaultZookeeperClient.java
index cf7a4b75e313..99ba6bb91079 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/DefaultZookeeperClient.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/DefaultZookeeperClient.java
@@ -23,7 +23,6 @@
import com.navercorp.pinpoint.collector.cluster.zookeeper.exception.PinpointZookeeperException;
import com.navercorp.pinpoint.collector.cluster.zookeeper.exception.TimeoutException;
import com.navercorp.pinpoint.collector.cluster.zookeeper.exception.UnknownException;
-import com.navercorp.pinpoint.common.util.concurrent.CommonState;
import com.navercorp.pinpoint.common.util.concurrent.CommonStateContext;
import com.navercorp.pinpoint.rpc.util.TimerFactory;
import org.apache.zookeeper.CreateMode;
@@ -92,7 +91,7 @@ public void connect() throws IOException {
@Override
public void reconnectWhenSessionExpired() {
- if (stateContext.getCurrentState() != CommonState.STARTED) {
+ if (!stateContext.isStarted()) {
logger.warn("ZookeeperClient.reconnectWhenSessionExpired() failed. Error: Already closed.");
return;
}
@@ -111,7 +110,7 @@ public void reconnectWhenSessionExpired() {
}
ZooKeeper newZookeeper = createNewZookeeper();
- if (stateContext.getCurrentState() != CommonState.STARTED) {
+ if (!stateContext.isStarted()) {
logger.warn("ZookeeperClient.reconnectWhenSessionExpired() failed. Error: Already closed.");
return;
}
@@ -277,7 +276,7 @@ private void checkState() throws PinpointZookeeperException {
@Override
public boolean isConnected() {
- if (!watcher.isConnected() || stateContext.getCurrentState() != CommonState.STARTED) {
+ if (!watcher.isConnected() || !stateContext.isStarted()) {
return false;
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClient.java b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClient.java
index 8d5c4cfddfdc..d68f804b23e1 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClient.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClient.java
@@ -17,7 +17,6 @@
package com.navercorp.pinpoint.web.cluster.zookeeper;
-import com.navercorp.pinpoint.common.util.concurrent.CommonState;
import com.navercorp.pinpoint.common.util.concurrent.CommonStateContext;
import com.navercorp.pinpoint.rpc.util.TimerFactory;
import com.navercorp.pinpoint.web.cluster.zookeeper.exception.AuthException;
@@ -94,7 +93,7 @@ public void connect() throws IOException {
}
public void reconnectWhenSessionExpired() {
- if (stateContext.getCurrentState() != CommonState.STARTED) {
+ if (!stateContext.isStarted()) {
logger.warn("ZookeeperClient.reconnectWhenSessionExpired() failed. Error: Already closed.");
return;
}
@@ -259,7 +258,7 @@ public boolean exists(String path) throws PinpointZookeeperException, Interrupte
}
private void checkState() throws PinpointZookeeperException {
- if (!zookeeperDataManager.isConnected() || stateContext.getCurrentState() != CommonState.STARTED) {
+ if (!zookeeperDataManager.isConnected() || !stateContext.isStarted()) {
throw new ConnectionException("Instance must be connected.");
}
}
| null | test | train | "2016-01-21T07:05:59" | "2016-01-21T02:01:33Z" | koo-taejin | test |
pinpoint-apm/pinpoint/1479_1480 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1479 | pinpoint-apm/pinpoint/1480 | [
"keyword_pr_to_issue"
] | 8fef0a433f6479da48c19ae576b31d355da8326d | 1340497c4256931783168bb5c2e505218254f7cc | [] | [] | "2016-01-22T07:56:47Z" | [
"enhancement"
] | Add addSetter API to InstrumentClass | Add addSetter API to InstrumentClass, similar to how getters and accessors are available.
Use case mentioned in #1439
| [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/InstrumentClass.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/InstrumentClass.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/SetterAnalyzer.java"
] | [] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/InstrumentClass.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/InstrumentClass.java
index b230a3040661..9f2671bc48f3 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/InstrumentClass.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/InstrumentClass.java
@@ -69,6 +69,10 @@ public interface InstrumentClass {
void addGetter(String getterTypeName, String fieldName) throws InstrumentException;
+ void addSetter(String setterTypeName, String fieldName) throws InstrumentException;
+
+ void addSetter(String setterTypeName, String fieldName, boolean removeFinal) throws InstrumentException;
+
int addInterceptor(String interceptorClassName) throws InstrumentException;
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java
index 5ab2d1515596..a4b3846419ad 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java
@@ -31,6 +31,7 @@
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewMethod;
+import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.MethodInfo;
@@ -48,6 +49,7 @@
import com.navercorp.pinpoint.exception.PinpointException;
import com.navercorp.pinpoint.profiler.instrument.AccessorAnalyzer.AccessorDetails;
import com.navercorp.pinpoint.profiler.instrument.GetterAnalyzer.GetterDetails;
+import com.navercorp.pinpoint.profiler.instrument.SetterAnalyzer.SetterDetails;
import com.navercorp.pinpoint.profiler.instrument.aspect.AspectWeaverClass;
import com.navercorp.pinpoint.profiler.interceptor.registry.InterceptorRegistryBinder;
import com.navercorp.pinpoint.profiler.objectfactory.AutoBindingObjectFactory;
@@ -385,10 +387,66 @@ public void addGetter(String getterTypeName, String fieldName) throws Instrument
CtClass ctInterface = ctClass.getClassPool().get(getterTypeName);
ctClass.addInterface(ctInterface);
} catch (Exception e) {
- throw new InstrumentException("Fail to add getter: " + getterTypeName, e);
+ throw new InstrumentException("Failed to add getter: " + getterTypeName, e);
}
}
+ @Override
+ public void addSetter(String setterTypeName, String fieldName) throws InstrumentException {
+ this.addSetter(setterTypeName, fieldName, false);
+ }
+
+ @Override
+ public void addSetter(String setterTypeName, String fieldName, boolean removeFinalFlag) throws InstrumentException {
+ try {
+ Class<?> setterType = pluginContext.injectClass(classLoader, setterTypeName);
+
+ SetterDetails setterDetails = new SetterAnalyzer().analyze(setterType);
+
+ CtField field = ctClass.getField(fieldName);
+
+ if (!field.getType().getName().equals(setterDetails.getFieldType().getName())) {
+ throw new IllegalArgumentException("Argument type of the setter is different with the field type. setterMethod: " + setterDetails.getSetter() + ", fieldType: " + field.getType().getName());
+ }
+
+ final int originalModifiers = field.getModifiers();
+ if (Modifier.isStatic(originalModifiers)) {
+ throw new IllegalArgumentException("Cannot add setter to static fields. setterMethod: " + setterDetails.getSetter().getName() + ", fieldName: " + fieldName);
+ }
+
+ boolean finalRemoved = false;
+ if (Modifier.isFinal(originalModifiers)) {
+ if (!removeFinalFlag) {
+ throw new IllegalArgumentException("Cannot add setter to final field. setterMethod: " + setterDetails.getSetter().getName() + ", fieldName: " + fieldName);
+ } else {
+ final int modifiersWithFinalRemoved = Modifier.clear(originalModifiers, Modifier.FINAL);
+ field.setModifiers(modifiersWithFinalRemoved);
+ finalRemoved = true;
+ }
+ }
+
+ try {
+ CtMethod setterMethod = CtNewMethod.setter(setterDetails.getSetter().getName(), field);
+ if (setterMethod.getDeclaringClass() != ctClass) {
+ setterMethod = CtNewMethod.copy(setterMethod, ctClass, null);
+ }
+ ctClass.addMethod(setterMethod);
+
+ CtClass ctInterface = ctClass.getClassPool().get(setterTypeName);
+ ctClass.addInterface(ctInterface);
+ }
+ catch (Exception e) {
+ if (finalRemoved) {
+ field.setModifiers(originalModifiers);
+ }
+ throw e;
+ }
+ } catch (Exception e) {
+ throw new InstrumentException("Failed to add setter: " + setterTypeName, e);
+ }
+
+ }
+
@Override
public int addInterceptor(String interceptorClassName) throws InstrumentException {
Asserts.notNull(interceptorClassName, "interceptorClassName");
@@ -514,7 +572,7 @@ private int addInterceptor0(String interceptorClassName, Object[] constructorArg
private int addInterceptor0(TargetConstructor c, String interceptorClassName, InterceptorScope scope, ExecutionPolicy executionPolicy, Object... constructorArgs) throws InstrumentException {
final InstrumentMethod constructor = getConstructor(c.value());
-
+
if (constructor == null) {
throw new NotFoundInstrumentException("Cannot find constructor with parameter types: " + Arrays.toString(c.value()));
}
@@ -567,7 +625,7 @@ public int addInterceptor(MethodFilter filter, String interceptorClassName) thro
Asserts.notNull(interceptorClassName, "interceptorClassName");
return addScopedInterceptor0(filter, interceptorClassName, null, null, null);
}
-
+
@Override
public int addInterceptor(MethodFilter filter, String interceptorClassName, Object[] constructorArgs) throws InstrumentException {
Asserts.notNull(filter, "filter");
@@ -658,5 +716,5 @@ public List<InstrumentClass> getNestedClasses(ClassFilter filter) {
return list;
}
-
+
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/SetterAnalyzer.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/SetterAnalyzer.java
new file mode 100644
index 000000000000..f45a5a36c417
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/SetterAnalyzer.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.instrument;
+
+import com.navercorp.pinpoint.common.util.Asserts;
+
+import java.lang.reflect.Method;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class SetterAnalyzer {
+
+ public SetterDetails analyze(Class<?> setterType) {
+ Asserts.notNull(setterType, "setterType");
+
+ if (!setterType.isInterface()) {
+ throw new IllegalArgumentException("setterType " + setterType + "is not an interface");
+ }
+
+ Method[] methods = setterType.getDeclaredMethods();
+
+ if (methods.length != 1) {
+ throw new IllegalArgumentException("Setter interface must have only one method: " + setterType.getName());
+ }
+
+ Method setter = methods[0];
+ Class<?>[] arguments = setter.getParameterTypes();
+
+ if (arguments.length != 1) {
+ throw new IllegalArgumentException("Setter interface method must have exactly 1 argument: " + setterType.getName());
+ }
+
+ Class<?> fieldType = arguments[0];
+
+ Class<?> returnType = setter.getReturnType();
+
+ if (returnType != void.class) {
+ throw new IllegalArgumentException("Setter must have return type void: " + setterType.getName());
+ }
+
+ return new SetterDetails(setter, fieldType);
+ }
+
+ public static final class SetterDetails {
+ private final Method setter;
+ private final Class<?> fieldType;
+
+ public SetterDetails(Method setter, Class<?> fieldType) {
+ this.setter = setter;
+ this.fieldType = fieldType;
+ }
+
+ public Method getSetter() {
+ return setter;
+ }
+
+ public Class<?> getFieldType() {
+ return fieldType;
+ }
+ }
+}
| null | val | train | "2016-01-21T08:00:10" | "2016-01-22T06:27:15Z" | Xylus | test |
pinpoint-apm/pinpoint/1482_1483 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1482 | pinpoint-apm/pinpoint/1483 | [
"keyword_pr_to_issue"
] | 8b7341d30ba5a6c19b001b36e4366dae1feda1f6 | e8a48068313e06ec76d1c73853b3b0da06ea5a5f | [] | [] | "2016-01-26T02:18:03Z" | [
"bug"
] | [PinpiontWeb] fix a ActiveThread concurrency problem | If multiple threads invokes WebSocketSession's sendMessage method at the same time, ;
then it is possible to makes IllegalStateException.
| [
"rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/LoggingStreamChannelMessageListener.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java"
] | [
"rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/LoggingStreamChannelMessageListener.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java"
] | [] | diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/LoggingStreamChannelMessageListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/LoggingStreamChannelMessageListener.java
index bee01d05c1bd..0cffad4c72a2 100644
--- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/LoggingStreamChannelMessageListener.java
+++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/LoggingStreamChannelMessageListener.java
@@ -52,7 +52,7 @@ static class Client implements ClientStreamChannelMessageListener {
@Override
public void handleStreamData(ClientStreamChannelContext streamChannelContext, StreamResponsePacket packet) {
- LOGGER.info("handleStreamData StreamChannel:{}, Packet:{}", streamChannelContext, packet);
+ LOGGER.debug("handleStreamData StreamChannel:{}, Packet:{}", streamChannelContext, packet);
}
@Override
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
index a721c8047912..3b2fb7a187b0 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
@@ -33,7 +33,6 @@
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
-import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -374,7 +373,7 @@ public void run() {
private void closeSession(WebSocketSession session, CloseStatus status) {
try {
session.close(status);
- } catch (IOException e) {
+ } catch (Exception e) {
logger.warn(e.getMessage(), e);
}
}
@@ -382,8 +381,9 @@ private void closeSession(WebSocketSession session, CloseStatus status) {
private void sendPingMessage(WebSocketSession session, TextMessage pingMessage) {
try {
session.sendMessage(pingMessage);
- } catch (IOException e) {
+ } catch (Exception e) {
logger.warn(e.getMessage(), e);
+ closeSession(session, CloseStatus.SERVER_ERROR);
}
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java
index 3b4fcee83726..ef0658552a33 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java
@@ -29,7 +29,6 @@
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
-import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -37,6 +36,7 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicInteger;
/**
* @Author Taejin Koo
@@ -48,6 +48,7 @@ public class ActiveThreadCountResponseAggregator implements PinpointWebSocketRes
private static final String TIME_STAMP = "timeStamp";
private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
private final String applicationName;
private final AgentService agentService;
private final Timer timer;
@@ -59,6 +60,9 @@ public class ActiveThreadCountResponseAggregator implements PinpointWebSocketRes
private final Object aggregatorLock = new Object();
private final PinpointWebSocketMessageConverter messageConverter;
+ private final AtomicInteger flushCount = new AtomicInteger(0);
+ private final int flushLogRecordRate = 60;
+
private volatile boolean isStopped = false;
private WorkerActiveManager workerActiveManager;
@@ -201,7 +205,9 @@ public void response(AgentActiveThreadCount activeThreadCount) {
@Override
public void flush() throws Exception {
- logger.info("flush started. applicationName:{}", applicationName);
+ if ((flushCount.getAndIncrement() % flushLogRecordRate) == 0) {
+ logger.info("flush started. applicationName:{}", applicationName);
+ }
if (isStopped) {
return;
@@ -234,12 +240,12 @@ private void flush0(AgentActiveThreadCountList activeThreadCountList) {
try {
logger.debug("flush webSocketSession:{}, response:{}", webSocketSession, responseTextMessage);
webSocketSession.sendMessage(responseTextMessage);
- } catch (IOException e) {
- logger.warn(e.getMessage(), e);
+ } catch (Exception e) {
+ logger.warn("failed while flush message(applicationName:{}, session:{}). Error:{}", webSocketSession, applicationName, e.getMessage(), e);
}
}
} catch (JsonProcessingException e) {
- logger.warn("json convert failed. original:{}, message:{}.", resultMap, e.getMessage(), e);
+ logger.warn("failed while convert message. applicationName:{}, original:{}, message:{}.", applicationName, resultMap, e.getMessage(), e);
}
}
| null | train | train | "2016-01-22T09:33:37" | "2016-01-25T05:29:30Z" | koo-taejin | test |
pinpoint-apm/pinpoint/1487_1488 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1487 | pinpoint-apm/pinpoint/1488 | [
"keyword_pr_to_issue"
] | 875a4a42f0a24dfeeca0b65a56baac02f23f48af | 46c5ed0e9a6f1dd3034ee25de383b5a1327ea2b0 | [] | [] | "2016-01-26T10:32:40Z" | [
"bug"
] | Link data missing on emulated application nodes | Call counts on edges pointing to emulated application nodes are calculated from callee statistics rather than caller statistics. This is done because the caller cannot differentiate which emulated application node it has called as the caller only knows the host name of it's target (and emulated application nodes share the same host name).
When such emulated application nodes sit on the edge of the callee search depth (for example, inbound depth=1, outbound depth=2 on a `USER -> SELECTED NODE -> EMULATED NODE -> some node`), the callee statistics of the `EMULATED_NODE` is not fetched as the inbound depth limit is 1.
In these situations, the server map incorrectly renders the above as `USER --N--> SELECTED NODE --0--> --N--> some node`.
| [
"web/src/main/java/com/navercorp/pinpoint/web/service/BFSLinkSelector.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/service/BFSLinkSelector.java"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/BFSLinkSelector.java b/web/src/main/java/com/navercorp/pinpoint/web/service/BFSLinkSelector.java
index 82dad1e34577..7eda23ea776d 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/BFSLinkSelector.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/BFSLinkSelector.java
@@ -196,7 +196,7 @@ private List<LinkData> checkRpcCallAccepted(LinkData linkData, Range range) {
}
private List<LinkData> createVirtualLinkData(LinkData linkData, Application toApplication, Set<AcceptApplication> acceptApplicationList) {
- logger.warn("ono to N replaced. node:{}->host:{} accept:{}", linkData.getFromApplication(), toApplication.getName(), acceptApplicationList);
+ logger.warn("one to N replaced. node:{}->host:{} accept:{}", linkData.getFromApplication(), toApplication.getName(), acceptApplicationList);
List<LinkData> emulationLink = new ArrayList<>();
for (AcceptApplication acceptApplication : acceptApplicationList) {
@@ -234,7 +234,7 @@ private Set<AcceptApplication> findAcceptApplication(Application fromApplication
return acceptApplication;
}
- private void fillEmulationLink(LinkDataDuplexMap linkDataDuplexMap) {
+ private void fillEmulationLink(LinkDataDuplexMap linkDataDuplexMap, Range range) {
// TODO need to be reimplemented - virtual node creation logic needs an overhaul.
// Currently, only the reversed relationship node is displayed. We need to create a virtual node and convert the rpc data appropriately.
logger.debug("this.emulationLinkMarker:{}", this.emulationLinkMarker);
@@ -248,10 +248,18 @@ private void fillEmulationLink(LinkDataDuplexMap linkDataDuplexMap) {
LinkKey findLinkKey = new LinkKey(emulationLinkData.getFromApplication(), emulationLinkData.getToApplication());
LinkData targetLinkData = linkDataDuplexMap.getTargetLinkData(findLinkKey);
if (targetLinkData == null) {
- // There has been a case where targetLinkData was null, but exact event could not be captured for analysis.
- // Logging the case for further analysis should it happen again in the future.
- logger.error("targetLinkData not found findLinkKey:{}", findLinkKey);
- continue;
+ // This is a case where the emulation target node has been only "partially" visited, (ie. does not have a target link data)
+ // Most likely due to the limit imposed by inbound search depth.
+ // Must go fetch the target link data here.
+ final Application targetApplication = emulationLinkData.getToApplication();
+ final LinkDataMap callee = mapStatisticsCalleeDao.selectCallee(targetApplication, range);
+ targetLinkData = callee.getLinkData(findLinkKey);
+ if (targetLinkData == null) {
+ // There has been a case where targetLinkData was null, but exact event could not be captured for analysis.
+ // Logging the case for further analysis should it happen again in the future.
+ logger.error("targetLinkData not found findLinkKey:{}", findLinkKey);
+ continue;
+ }
}
// create reversed link data - convert data accepted by the target to target's call data
@@ -332,7 +340,7 @@ public LinkDataDuplexMap select(Application sourceApplication, Range range, Sear
logger.debug("Link emulation size:{}", emulationLinkMarker.size());
// special case
checkUnsearchEmulationCalleeNode(linkDataDuplexMap, range);
- fillEmulationLink(linkDataDuplexMap);
+ fillEmulationLink(linkDataDuplexMap, range);
}
return linkDataDuplexMap;
| null | train | train | "2016-01-26T08:51:19" | "2016-01-26T07:56:24Z" | Xylus | test |
pinpoint-apm/pinpoint/1462_1493 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1462 | pinpoint-apm/pinpoint/1493 | [
"keyword_pr_to_issue"
] | 2fa319bd19b6098cf2a8ea3b839687ef65fc4345 | 78db74702e416406a3274dbb4dece6e65a71b330 | [
"~~Reopening to add service type to request parameter.~~\nReopening to modify response for `/getInactiveAgents`.\n",
"Reopening to add API for removing all inactive agents from index.\n"
] | [] | "2016-01-28T05:50:23Z" | [
"enhancement"
] | Add APIs for managing registered agents | There is currently not a lot of ways to manage agent ids once they're mapped to an application. These data tend to linger around until the TTL has passed and ends up clogging the application index.
There needs to be APIs for doing 2 things:
1. Detect inactive agents (those that were registered, but are no longer in use) and provide a way to delete them (and their application name mapping)
2. Identify duplicate agent ids that are mapped to more than 1 application name.
| [
"web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/alarm/AlarmPartitionerTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/alarm/ReaderTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/GcCountCheckerTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/HeapUsageRateCheckerTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/JvmCpuUsageRateCheckerTest.java"
] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java
index 037b02b4882e..75f3e86475b1 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java
@@ -71,6 +71,19 @@ public String removeAgentId(
}
}
+ @RequestMapping(value = "/removeInactiveAgents")
+ @ResponseBody
+ public String removeInactiveAgents(@RequestParam(value = "durationDays", defaultValue = "30") int durationDays) {
+ logger.info("removing inactive agents for the last {} days.", durationDays);
+ try {
+ this.adminService.removeInactiveAgents(durationDays);
+ return "OK";
+ } catch (Exception e) {
+ logger.error("error while removing inactive agents for the last " + durationDays + " days.", e);
+ return e.getMessage();
+ }
+ }
+
@RequestMapping(value = "/agentIdMap")
@ResponseBody
public Map<String, List<Application>> agentIdMap() {
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java
index 59810d1eea99..08e17e54c855 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java
@@ -17,6 +17,7 @@
package com.navercorp.pinpoint.web.dao;
import java.util.List;
+import java.util.Map;
import com.navercorp.pinpoint.web.vo.Application;
@@ -32,5 +33,7 @@ public interface ApplicationIndexDao {
void deleteApplicationName(String applicationName);
+ void deleteAgentIds(Map<String, List<String>> applicationAgentIdMap);
+
void deleteAgentId(String applicationName, String agentId);
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java
index bc11abf47b0f..3de442c31d58 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java
@@ -18,7 +18,10 @@
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
@@ -84,6 +87,34 @@ public void deleteApplicationName(String applicationName) {
hbaseOperations2.delete(HBaseTables.APPLICATION_INDEX, delete);
}
+ @Override
+ public void deleteAgentIds(Map<String, List<String>> applicationAgentIdMap) {
+ if (MapUtils.isEmpty(applicationAgentIdMap)) {
+ return;
+ }
+
+ List<Delete> deletes = new ArrayList<>(applicationAgentIdMap.size());
+
+ for (Map.Entry<String, List<String>> entry : applicationAgentIdMap.entrySet()) {
+ String applicationName = entry.getKey();
+ List<String> agentIds = entry.getValue();
+ if (StringUtils.isEmpty(applicationName) || CollectionUtils.isEmpty(agentIds)) {
+ continue;
+ }
+ Delete delete = new Delete(Bytes.toBytes(applicationName));
+ for (String agentId : agentIds) {
+ if (!StringUtils.isEmpty(agentId)) {
+ delete.addColumns(HBaseTables.APPLICATION_INDEX_CF_AGENTS, Bytes.toBytes(agentId));
+ }
+ }
+ // don't delete if nothing has been specified except row
+ if (!delete.getFamilyCellMap().isEmpty()) {
+ deletes.add(delete);
+ }
+ }
+ hbaseOperations2.delete(HBaseTables.APPLICATION_INDEX, deletes);
+ }
+
@Override
public void deleteAgentId(String applicationName, String agentId) {
if (StringUtils.isEmpty(applicationName)) {
@@ -95,7 +126,7 @@ public void deleteAgentId(String applicationName, String agentId) {
byte[] rowKey = Bytes.toBytes(applicationName);
Delete delete = new Delete(rowKey);
byte[] qualifier = Bytes.toBytes(agentId);
- delete.addColumn(HBaseTables.APPLICATION_INDEX_CF_AGENTS, qualifier);
+ delete.addColumns(HBaseTables.APPLICATION_INDEX_CF_AGENTS, qualifier);
hbaseOperations2.delete(HBaseTables.APPLICATION_INDEX, delete);
}
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java
index f2228ca3d9a1..734aa3ba68d6 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java
@@ -31,6 +31,8 @@ public interface AdminService {
void removeAgentId(String applicationName, String agentId);
+ void removeInactiveAgents(int durationDays);
+
Map<String, List<Application>> getAgentIdMap();
Map<String, List<Application>> getDuplicateAgentIdMap();
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java
index e4650b133953..a8bc5c2997d0 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java
@@ -21,6 +21,8 @@
import com.navercorp.pinpoint.web.vo.Application;
import com.navercorp.pinpoint.web.vo.Range;
import org.apache.commons.collections.CollectionUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -31,7 +33,9 @@
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.TreeMap;
+import java.util.TreeSet;
/**
* @author netspider
@@ -40,6 +44,10 @@
@Service
public class AdminServiceImpl implements AdminService {
+ private static final int MIN_DURATION_DAYS_FOR_INACTIVITY = 30;
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
@Autowired
private ApplicationIndexDao applicationIndexDao;
@@ -56,6 +64,33 @@ public void removeAgentId(String applicationName, String agentId) {
applicationIndexDao.deleteAgentId(applicationName, agentId);
}
+ @Override
+ public void removeInactiveAgents(int durationDays) {
+ if (durationDays < MIN_DURATION_DAYS_FOR_INACTIVITY) {
+ throw new IllegalArgumentException("duration may not be less than " + MIN_DURATION_DAYS_FOR_INACTIVITY + " days");
+ }
+ Map<String, List<String>> inactiveAgentMap = new TreeMap<>(Ordering.usingToString());
+
+ List<Application> applications = this.applicationIndexDao.selectAllApplicationNames();
+ Set<String> applicationNames = new TreeSet<>(Ordering.usingToString());
+ // remove duplicates (same application name but different service type)
+ for (Application application : applications) {
+ applicationNames.add(application.getName());
+ }
+ for (String applicationName : applicationNames) {
+ List<String> agentIds = this.applicationIndexDao.selectAgentIds(applicationName);
+ Collections.sort(agentIds);
+ List<String> inactiveAgentIds = filterInactiveAgents(agentIds, durationDays);
+ if (!CollectionUtils.isEmpty(inactiveAgentIds)) {
+ inactiveAgentMap.put(applicationName, inactiveAgentIds);
+ }
+ }
+ // map may become big, but realistically won't cause OOM
+ // if it becomes an issue, consider deleting inside the loop above
+ logger.info("deleting {}", inactiveAgentMap);
+ this.applicationIndexDao.deleteAgentIds(inactiveAgentMap);
+ }
+
@Override
public Map<String, List<Application>> getAgentIdMap() {
Map<String, List<Application>> agentIdMap = new TreeMap<>(Ordering.usingToString());
@@ -91,34 +126,40 @@ public Map<String, List<Application>> getInactiveAgents(String applicationName,
if (applicationName == null) {
throw new NullPointerException("applicationName must not be null");
}
- if (durationDays < 30) {
- throw new IllegalArgumentException("duration may not be less than 30 days");
- }
- if (durationDays > 180) {
- throw new IllegalArgumentException("duration may not be greater than 180 days");
+ if (durationDays < MIN_DURATION_DAYS_FOR_INACTIVITY) {
+ throw new IllegalArgumentException("duration may not be less than " + MIN_DURATION_DAYS_FOR_INACTIVITY + " days");
}
List<String> agentIds = this.applicationIndexDao.selectAgentIds(applicationName);
if (CollectionUtils.isEmpty(agentIds)) {
return Collections.emptyMap();
}
+ Map<String, List<Application>> agentIdMap = this.getAgentIdMap();
+ Map<String, List<Application>> inactiveAgentMap = new TreeMap<>(Ordering.usingToString());
+ List<String> inactiveAgentIds = filterInactiveAgents(agentIds, durationDays);
+ for (String inactiveAgentId : inactiveAgentIds) {
+ List<Application> applications = agentIdMap.get(inactiveAgentId);
+ inactiveAgentMap.put(inactiveAgentId, applications);
+ }
+ return inactiveAgentMap;
+ }
+ private List<String> filterInactiveAgents(List<String> agentIds, int durationDays) {
+ if (CollectionUtils.isEmpty(agentIds)) {
+ return Collections.emptyList();
+ }
+ List<String> inactiveAgentIds = new ArrayList<>();
final long toTimestamp = System.currentTimeMillis();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, durationDays * -1);
final long fromTimestamp = cal.getTimeInMillis();
Range queryRange = new Range(fromTimestamp, toTimestamp);
-
- Map<String, List<Application>> agentIdMap = this.getAgentIdMap();
-
- Map<String, List<Application>> inactiveAgentMap = new TreeMap<>(Ordering.usingToString());
for (String agentId : agentIds) {
boolean dataExists = this.agentStatDao.agentStatExists(agentId, queryRange);
if (!dataExists) {
- List<Application> applications = agentIdMap.get(agentId);
- inactiveAgentMap.put(agentId, applications);
+ inactiveAgentIds.add(agentId);
}
}
- return inactiveAgentMap;
+ return inactiveAgentIds;
}
}
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/alarm/AlarmPartitionerTest.java b/web/src/test/java/com/navercorp/pinpoint/web/alarm/AlarmPartitionerTest.java
index ed0f1e1fffd8..1621879c85f4 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/alarm/AlarmPartitionerTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/alarm/AlarmPartitionerTest.java
@@ -64,6 +64,10 @@ public List<String> selectAgentIds(String applicationName) {
public void deleteApplicationName(String applicationName) {
}
+ @Override
+ public void deleteAgentIds(Map<String, List<String>> applicationAgentIdMap) {
+ }
+
@Override
public void deleteAgentId(String applicationName, String agentId) {
}
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/alarm/ReaderTest.java b/web/src/test/java/com/navercorp/pinpoint/web/alarm/ReaderTest.java
index 2bd1a807b987..1beb5bca60f1 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/alarm/ReaderTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/alarm/ReaderTest.java
@@ -117,6 +117,10 @@ public List<Application> selectAllApplicationNames() {
@Override public List<String> selectAgentIds(String applicationName) {return null;}
@Override public void deleteApplicationName(String applicationName) { }
+
+ @Override
+ public void deleteAgentIds(Map<String, List<String>> applicationAgentIdMap) {}
+
@Override public void deleteAgentId(String applicationName, String agentId) {}
};
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/GcCountCheckerTest.java b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/GcCountCheckerTest.java
index 50a5ca025d25..68c3c7bd46f4 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/GcCountCheckerTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/GcCountCheckerTest.java
@@ -18,6 +18,7 @@
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import org.junit.BeforeClass;
@@ -34,9 +35,9 @@ public class GcCountCheckerTest {
private static final String SERVICE_TYPE = "tomcat";
private static ApplicationIndexDao applicationIndexDao;
-
+
private static AgentStatDao agentStatDao;
-
+
@BeforeClass
public static void before() {
agentStatDao = new AgentStatDao() {
@@ -59,7 +60,7 @@ public boolean agentStatExists(String agentId, Range range) {
return true;
}
};
-
+
applicationIndexDao = new ApplicationIndexDao() {
@Override
@@ -74,7 +75,7 @@ public List<String> selectAgentIds(String applicationName) {
agentIds.add("local_tomcat");
return agentIds;
}
-
+
throw new IllegalArgumentException();
}
@@ -83,11 +84,16 @@ public void deleteApplicationName(String applicationName) {
throw new UnsupportedOperationException();
}
+ @Override
+ public void deleteAgentIds(Map<String, List<String>> applicationAgentIdMap) {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void deleteAgentId(String applicationName, String agentId) {
throw new UnsupportedOperationException();
}
-
+
};
}
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/HeapUsageRateCheckerTest.java b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/HeapUsageRateCheckerTest.java
index a95897a3a3c5..a7546fd85b56 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/HeapUsageRateCheckerTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/HeapUsageRateCheckerTest.java
@@ -21,6 +21,7 @@
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -94,6 +95,11 @@ public void deleteApplicationName(String applicationName) {
throw new UnsupportedOperationException();
}
+ @Override
+ public void deleteAgentIds(Map<String, List<String>> applicationAgentIdMap) {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void deleteAgentId(String applicationName, String agentId) {
throw new UnsupportedOperationException();
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/JvmCpuUsageRateCheckerTest.java b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/JvmCpuUsageRateCheckerTest.java
index 2819bd30edd9..69e6e35340b8 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/JvmCpuUsageRateCheckerTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/JvmCpuUsageRateCheckerTest.java
@@ -20,6 +20,7 @@
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -91,6 +92,11 @@ public void deleteApplicationName(String applicationName) {
throw new UnsupportedOperationException();
}
+ @Override
+ public void deleteAgentIds(Map<String, List<String>> applicationAgentIdMap) {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void deleteAgentId(String applicationName, String agentId) {
throw new UnsupportedOperationException();
| train | train | "2016-01-27T11:31:41" | "2016-01-19T06:18:53Z" | Xylus | test |
pinpoint-apm/pinpoint/1318_1497 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1318 | pinpoint-apm/pinpoint/1497 | [
"keyword_pr_to_issue"
] | ac09671a48c0b57f74a81efa05fedf7330f7965d | 4e7d02aa40f452eeeeb7d60233b361085f8099d6 | [
"Api change affects transaction list queries - reopening issue.\n",
"Reopening issue to add configuration option for the duration determining agent inactivity.\n"
] | [] | "2016-01-28T07:29:43Z" | [
"enhancement"
] | Add time filtering when querying agents for Realtime data | When querying for realtime data such as the active thread chart, servers that are no longer in use are of no interest. These servers are currently displayed as _NOT_FOUND_ and will continue to be displayed until the TTL value set in HBase.
It might be a good idea to set a reasonable time buffer (perhaps a week?) when querying for these agents so that servers that were down for longer than a week does not show up in the active thread chart and confuse everyone.
| [
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java",
"web/src/main/resources/pinpoint-web.properties"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java",
"web/src/main/resources/pinpoint-web.properties"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java
index 00053762d74e..0112e4e0b42c 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java
@@ -48,6 +48,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.*;
@@ -62,11 +63,10 @@ public class AgentServiceImpl implements AgentService {
private static final long DEFAULT_FUTURE_TIMEOUT = 3000;
- private static final long DEFAULT_TIME_DIFF_DAYS = 7;
- private static final long DEFAULT_TIME_DIFF_MS = TimeUnit.MILLISECONDS.convert(DEFAULT_TIME_DIFF_DAYS, TimeUnit.DAYS);
-
private final Logger logger = LoggerFactory.getLogger(this.getClass());
+ private long timeDiffMs;
+
@Autowired
private AgentInfoService agentInfoService;
@@ -79,6 +79,11 @@ public class AgentServiceImpl implements AgentService {
@Autowired
private DeserializerFactory<HeaderTBaseDeserializer> commandDeserializerFactory;
+ @Value("#{pinpointWebProps['web.activethread.activeAgent.duration.days'] ?: 7}")
+ private void setTimeDiffMs(int durationDays) {
+ this.timeDiffMs = TimeUnit.MILLISECONDS.convert(durationDays, TimeUnit.DAYS);
+ }
+
@Override
public AgentInfo getAgentInfo(String applicationName, String agentId) {
long currentTime = System.currentTimeMillis();
@@ -140,7 +145,7 @@ public AgentInfo getAgentInfo(String applicationName, String agentId, long start
@Override
public List<AgentInfo> getRecentAgentInfoList(String applicationName) {
- return this.getRecentAgentInfoList(applicationName, DEFAULT_TIME_DIFF_MS);
+ return this.getRecentAgentInfoList(applicationName, this.timeDiffMs);
}
@Override
diff --git a/web/src/main/resources/pinpoint-web.properties b/web/src/main/resources/pinpoint-web.properties
index 29fc033e67ce..61153f362543 100644
--- a/web/src/main/resources/pinpoint-web.properties
+++ b/web/src/main/resources/pinpoint-web.properties
@@ -20,3 +20,5 @@ config.editUserInfo=true
web.hbase.selectSpans.limit=500
web.hbase.selectAllSpans.limit=500
+
+web.activethread.activeAgent.duration.days=7
\ No newline at end of file
| null | train | train | "2016-01-28T07:58:18" | "2015-12-04T10:07:22Z" | Xylus | test |
pinpoint-apm/pinpoint/1443_1500 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1443 | pinpoint-apm/pinpoint/1500 | [
"keyword_pr_to_issue"
] | 7e535524373ec71fddc2ff9fb57c37e530462169 | a9d54ac14c97fee60beb89198c60ab8a0f5399e1 | [] | [] | "2016-01-29T12:20:43Z" | [
"bug"
] | Fixed invalid classloading when using the AspectJ + Spring AOP | - support spring aspectj weaving
- support OSGI (atlassian jira)
- #1583 Enhancement PlaingClassLoaderHandler for Jira.
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/PluginConfig.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/ProfilerPluginLoader.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/BootstrapClassLoaderHandler.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/PlainClassLoaderHandler.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/URLClassLoaderHandler.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/ClassNameFilterChain.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/PinpointProfilerPackageSkipFilter.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/PluginConfig.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/ProfilerPluginLoader.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjectorTest.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/ClassNameFilterChainTest.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/PinpointProfilerPackageSkipFilterTest.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/PluginPackageFilterTest.java"
] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/BootstrapClassLoaderHandler.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/BootstrapClassLoaderHandler.java
new file mode 100644
index 000000000000..91be6fb7a63e
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/BootstrapClassLoaderHandler.java
@@ -0,0 +1,89 @@
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.instrument;
+
+import com.navercorp.pinpoint.exception.PinpointException;
+import com.navercorp.pinpoint.profiler.plugin.PluginConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class BootstrapClassLoaderHandler implements ClassInjector {
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ private final PluginConfig pluginConfig;
+
+ private final Object lock = new Object();
+ private boolean injectedToRoot = false;
+
+ public BootstrapClassLoaderHandler(PluginConfig pluginConfig) {
+ if (pluginConfig == null) {
+ throw new NullPointerException("pluginConfig must not be null");
+ }
+ this.pluginConfig = pluginConfig;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public <T> Class<? extends T> injectClass(ClassLoader classLoader, String className) {
+ try {
+ if (classLoader == null) {
+ return (Class<T>)injectClass0(className);
+ }
+ } catch (Exception e) {
+ logger.warn("Failed to load plugin class {} with classLoader {}", className, classLoader, e);
+ throw new PinpointException("Failed to load plugin class " + className + " with classLoader " + classLoader, e);
+ }
+ throw new PinpointException("invalid ClassLoader");
+ }
+
+ private Class<?> injectClass0(String className) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
+ synchronized (lock) {
+ if (this.injectedToRoot == false) {
+ this.injectedToRoot = true;
+ pluginConfig.getInstrumentation().appendToBootstrapClassLoaderSearch(pluginConfig.getPluginJarFile());
+ pluginConfig.getClassPool().appendToBootstrapClassPath(pluginConfig.getPluginJarFile().getName());
+ }
+ }
+ return Class.forName(className, false, null);
+ }
+
+
+}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java
index 1733f61f1c9e..565ac8031d78 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjector.java
@@ -3,9 +3,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -14,20 +14,9 @@
*/
package com.navercorp.pinpoint.profiler.instrument;
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.URL;
import java.net.URLClassLoader;
-import java.util.*;
-import com.navercorp.pinpoint.profiler.plugin.ClassLoadingChecker;
import com.navercorp.pinpoint.profiler.plugin.PluginConfig;
-import javassist.CannotCompileException;
-import javassist.ClassPool;
-import javassist.CtClass;
-import javassist.LoaderClassPath;
-import javassist.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -40,37 +29,18 @@
*/
public class JarProfilerPluginClassInjector implements ClassInjector {
private final Logger logger = LoggerFactory.getLogger(JarProfilerPluginClassInjector.class);
- private final boolean isDebug = logger.isDebugEnabled();
-
- private static final Method ADD_URL;
- private static final Method DEFINE_CLASS;
-
- static {
- try {
- ADD_URL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
- ADD_URL.setAccessible(true);
- } catch (Exception e) {
- throw new PinpointException("Cannot access URLClassLoader.addURL(URL)", e);
- }
-
- try {
- DEFINE_CLASS = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class);
- DEFINE_CLASS.setAccessible(true);
- } catch (Exception e) {
- throw new PinpointException("Cannot access ClassLoader.defineClass(String, byte[], int, int)", e);
- }
- }
-
- private final PluginConfig pluginConfig;
- private final Object lock = new Object();
- private boolean injectedToRoot = false;
+ private final ClassInjector bootstrapClassLoaderHandler;
+ private final ClassInjector urlClassLoaderHandler;
+ private final ClassInjector plainClassLoaderHandler;
public JarProfilerPluginClassInjector(PluginConfig pluginConfig) {
if (pluginConfig == null) {
throw new NullPointerException("pluginConfig must not be null");
}
- this.pluginConfig = pluginConfig;
+ this.bootstrapClassLoaderHandler = new BootstrapClassLoaderHandler(pluginConfig);
+ this.urlClassLoaderHandler = new URLClassLoaderHandler(pluginConfig);
+ this.plainClassLoaderHandler = new PlainClassLoaderHandler(pluginConfig);
}
@Override
@@ -78,12 +48,12 @@ public JarProfilerPluginClassInjector(PluginConfig pluginConfig) {
public <T> Class<? extends T> injectClass(ClassLoader classLoader, String className) {
try {
if (classLoader == null) {
- return (Class<T>)injectToBootstrapClassLoader(className);
+ return (Class<T>)bootstrapClassLoaderHandler.injectClass(null, className);
} else if (classLoader instanceof URLClassLoader) {
final URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
- return (Class<T>)injectToURLClassLoader(urlClassLoader, className);
+ return (Class<T>)urlClassLoaderHandler.injectClass(urlClassLoader, className);
} else {
- return (Class<T>)injectToPlainClassLoader(classLoader, className);
+ return (Class<T>)plainClassLoaderHandler.injectClass(classLoader, className);
}
} catch (Exception e) {
logger.warn("Failed to load plugin class {} with classLoader {}", className, classLoader, e);
@@ -91,134 +61,4 @@ public <T> Class<? extends T> injectClass(ClassLoader classLoader, String classN
}
}
- private Class<?> injectToBootstrapClassLoader(String className) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
- synchronized (lock) {
- if (this.injectedToRoot == false) {
- this.injectedToRoot = true;
- pluginConfig.getInstrumentation().appendToBootstrapClassLoaderSearch(pluginConfig.getPluginJarFile());
- pluginConfig.getClassPool().appendToBootstrapClassPath(pluginConfig.getPluginJarFile().getName());
- }
- }
-
- return Class.forName(className, false, null);
- }
-
- private Class<?> injectToURLClassLoader(URLClassLoader classLoader, String className) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
- final URL[] urls = classLoader.getURLs();
- if (urls != null) {
-
- boolean hasPluginJar = false;
- for (URL url : urls) {
- // if (url.equals(pluginJarURL)) { fix very slow
- // http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html
- final String externalForm = url.toExternalForm();
- if (pluginConfig.getPluginJarURLExternalForm().equals(externalForm)) {
- hasPluginJar = true;
- break;
- }
- }
-
- if (!hasPluginJar) {
- ADD_URL.invoke(classLoader, pluginConfig.getPluginJar());
- }
- }
-
- return classLoader.loadClass(className);
- }
-
- private Class<?> injectToPlainClassLoader(ClassLoader classLoader, String className) throws NotFoundException, IllegalArgumentException, IOException, CannotCompileException, IllegalAccessException, InvocationTargetException {
- if (isDebug) {
- logger.debug("injectToPlainClassLoader className:{} cl:{}", className, classLoader);
- }
- logger.info("bootstrapCoreJarPath:{}", pluginConfig.getBootstrapCoreJarPath());
-
- final ClassPool pool = createClassPool(classLoader);
-
- // TODO ClassLoader + ClassName key?
- // TODO concurrent class loading
- final ClassLoadingChecker classLoadingChecker = new ClassLoadingChecker();
- return injectToPlainClassLoader(pool, classLoader, className, classLoadingChecker);
- }
-
- private ClassPool createClassPool(ClassLoader classLoader) throws NotFoundException {
- final ClassPool pool = new ClassPool();
- pool.appendClassPath(pluginConfig.getBootstrapCoreJarPath());
-
- pool.appendClassPath(new LoaderClassPath(classLoader));
- pool.appendClassPath(pluginConfig.getPluginJarFile().getName());
- return pool;
- }
-
- private Class<?> injectToPlainClassLoader(ClassPool pool, ClassLoader classLoader, String className, ClassLoadingChecker classLoadingChecker) throws NotFoundException, IOException, CannotCompileException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
- if (pluginConfig.getProfilerPackageFilter().accept(className)) {
- if (isDebug) {
- logger.debug("ProfilerFilter skip class {}", className);
- }
- return null;
- }
- if (!pluginConfig.getPluginPackageFilter().accept(className)) {
- if (isDebug) {
- logger.debug("PluginFilter skip class:{}", className);
- }
- return null;
- }
- if (!classLoadingChecker.isFirstLoad(className)) {
- if (isDebug) {
- logger.debug("skip already loaded class:{}", className);
- }
- return null;
- }
-
- Class<?> c = null;
- try {
- c = classLoader.loadClass(className);
- if (isDebug) {
- logger.debug("loadClass:{}", className);
- }
- } catch (ClassNotFoundException ex) {
- if (isDebug) {
- logger.debug("ClassNotFound {}", ex.getMessage());
- }
- }
- if (c != null) {
- return c;
- }
-
- final CtClass ct = pool.getOrNull(className);
- if (ct == null) {
- throw new NotFoundException(className);
- }
-
-
- final CtClass superClass = ct.getSuperclass();
- if (superClass != null) {
- if ("java.lang.Object".equals(superClass.getName())) {
- return null;
- }
- injectToPlainClassLoader(pool, classLoader, superClass.getName(), classLoadingChecker);
- }
-
- final CtClass[] interfaces = ct.getInterfaces();
- for (CtClass ctInterface : interfaces) {
- injectToPlainClassLoader(pool, classLoader, ctInterface.getName(), classLoadingChecker);
- }
- @SuppressWarnings("unchecked")
- final Collection<String> referenceClassList = ct.getRefClasses();
- if (isDebug) {
- logger.debug("target:{} referenceClassList:{}", className, referenceClassList);
- }
- for (String referenceClass : referenceClassList) {
- try {
- injectToPlainClassLoader(pool, classLoader, referenceClass, classLoadingChecker);
- } catch (NotFoundException e) {
- logger.warn("Skip a referenced class because of NotFoundException : {}", e.getMessage(), e);
- }
- }
- if (logger.isInfoEnabled()) {
- logger.info("defineClass pluginClass:{} cl:{}", className, classLoader);
- }
- final byte[] bytes = ct.toBytecode();
- return (Class<?>)DEFINE_CLASS.invoke(classLoader, ct.getName(), bytes, 0, bytes.length);
- }
-
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/PlainClassLoaderHandler.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/PlainClassLoaderHandler.java
new file mode 100644
index 000000000000..0596326dd427
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/PlainClassLoaderHandler.java
@@ -0,0 +1,186 @@
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.instrument;
+
+import com.navercorp.pinpoint.exception.PinpointException;
+import com.navercorp.pinpoint.profiler.plugin.ClassLoadingChecker;
+import com.navercorp.pinpoint.profiler.plugin.PluginConfig;
+import javassist.CannotCompileException;
+import javassist.ClassPool;
+import javassist.CtClass;
+import javassist.LoaderClassPath;
+import javassist.NotFoundException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import java.util.Collection;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class PlainClassLoaderHandler implements ClassInjector {
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+ private final boolean isDebug = logger.isDebugEnabled();
+
+ private static final Method DEFINE_CLASS;
+
+ static {
+ try {
+ DEFINE_CLASS = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class);
+ DEFINE_CLASS.setAccessible(true);
+ } catch (Exception e) {
+ throw new PinpointException("Cannot access ClassLoader.defineClass(String, byte[], int, int)", e);
+ }
+ }
+
+ private final PluginConfig pluginConfig;
+
+
+ public PlainClassLoaderHandler(PluginConfig pluginConfig) {
+ if (pluginConfig == null) {
+ throw new NullPointerException("pluginConfig must not be null");
+ }
+ this.pluginConfig = pluginConfig;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public <T> Class<? extends T> injectClass(ClassLoader classLoader, String className) {
+ try {
+ return (Class<T>)injectClass0(classLoader, className);
+ } catch (Exception e) {
+ logger.warn("Failed to load plugin class {} with classLoader {}", className, classLoader, e);
+ throw new PinpointException("Failed to load plugin class " + className + " with classLoader " + classLoader, e);
+ }
+ }
+
+
+ private Class<?> injectClass0(ClassLoader classLoader, String className) throws NotFoundException, IllegalArgumentException, IOException, CannotCompileException, IllegalAccessException, InvocationTargetException {
+ if (isDebug) {
+ logger.debug("injectClass0 className:{} cl:{}", className, classLoader);
+ }
+ logger.info("bootstrapCoreJarPath:{}", pluginConfig.getBootstrapCoreJarPath());
+
+ final ClassPool pool = createClassPool(classLoader);
+
+ // TODO ClassLoader + ClassName key?
+ // TODO concurrent class loading
+ final ClassLoadingChecker classLoadingChecker = new ClassLoadingChecker();
+ return injectClass0(pool, classLoader, className, classLoadingChecker);
+ }
+
+ private ClassPool createClassPool(ClassLoader classLoader) throws NotFoundException {
+ final ClassPool pool = new ClassPool();
+ final String bootstrapCoreJarPath = pluginConfig.getBootstrapCoreJarPath();
+ pool.appendClassPath(bootstrapCoreJarPath);
+
+ final LoaderClassPath loaderClassPath = new LoaderClassPath(classLoader);
+ pool.appendClassPath(loaderClassPath);
+
+ final String pluginJarFileName = pluginConfig.getPluginJarFile().getName();
+ pool.appendClassPath(pluginJarFileName);
+ return pool;
+ }
+
+ private Class<?> injectClass0(ClassPool pool, ClassLoader classLoader, String className, ClassLoadingChecker classLoadingChecker) throws NotFoundException, IOException, CannotCompileException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
+ if (!pluginConfig.getPluginPackageFilter().accept(className)) {
+ if (isDebug) {
+ logger.debug("PluginFilter skip class:{}", className);
+ }
+ return null;
+ }
+ if (!classLoadingChecker.isFirstLoad(className)) {
+ if (isDebug) {
+ logger.debug("skip already loaded class:{}", className);
+ }
+ return null;
+ }
+
+ Class<?> c = null;
+ try {
+ c = classLoader.loadClass(className);
+ if (isDebug) {
+ logger.debug("loadClass:{}", className);
+ }
+ } catch (ClassNotFoundException ex) {
+ if (isDebug) {
+ logger.debug("ClassNotFound {}", ex.getMessage());
+ }
+ }
+ if (c != null) {
+ return c;
+ }
+
+ final CtClass ct = pool.getOrNull(className);
+ if (ct == null) {
+ throw new NotFoundException(className);
+ }
+
+
+ final CtClass superClass = ct.getSuperclass();
+ if (superClass != null) {
+ if ("java.lang.Object".equals(superClass.getName())) {
+ return null;
+ }
+ injectClass0(pool, classLoader, superClass.getName(), classLoadingChecker);
+ }
+
+ final CtClass[] interfaces = ct.getInterfaces();
+ for (CtClass ctInterface : interfaces) {
+ injectClass0(pool, classLoader, ctInterface.getName(), classLoadingChecker);
+ }
+ @SuppressWarnings("unchecked")
+ final Collection<String> referenceClassList = ct.getRefClasses();
+ if (isDebug) {
+ logger.debug("target:{} referenceClassList:{}", className, referenceClassList);
+ }
+ for (String referenceClass : referenceClassList) {
+ try {
+ injectClass0(pool, classLoader, referenceClass, classLoadingChecker);
+ } catch (NotFoundException e) {
+ logger.warn("Skip a referenced class because of NotFoundException : {}", e.getMessage(), e);
+ }
+ }
+ if (logger.isInfoEnabled()) {
+ logger.info("defineClass pluginClass:{} cl:{}", className, classLoader);
+ }
+ final byte[] bytes = ct.toBytecode();
+ return (Class<?>)DEFINE_CLASS.invoke(classLoader, ct.getName(), bytes, 0, bytes.length);
+ }
+}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/URLClassLoaderHandler.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/URLClassLoaderHandler.java
new file mode 100644
index 000000000000..1e9498a7e173
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/URLClassLoaderHandler.java
@@ -0,0 +1,122 @@
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.instrument;
+
+import com.navercorp.pinpoint.exception.PinpointException;
+import com.navercorp.pinpoint.profiler.plugin.PluginConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLClassLoader;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class URLClassLoaderHandler implements ClassInjector {
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ private static final Method ADD_URL;
+
+ static {
+ try {
+ ADD_URL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
+ ADD_URL.setAccessible(true);
+ } catch (Exception e) {
+ throw new PinpointException("Cannot access URLClassLoader.addURL(URL)", e);
+ }
+ }
+
+ private final URL pluginURL;
+ private final String pluginURLString;
+
+ public URLClassLoaderHandler(PluginConfig pluginConfig) {
+ if (pluginConfig == null) {
+ throw new NullPointerException("pluginConfig must not be null");
+ }
+ this.pluginURL = pluginConfig.getPluginJar();
+ this.pluginURLString = pluginURL.toExternalForm();
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public <T> Class<? extends T> injectClass(ClassLoader classLoader, String className) {
+ try {
+ if (classLoader instanceof URLClassLoader) {
+ final URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
+ return (Class<T>)injectClass0(urlClassLoader, className);
+ }
+ } catch (Exception e) {
+ logger.warn("Failed to load plugin class {} with classLoader {}", className, classLoader, e);
+ throw new PinpointException("Failed to load plugin class " + className + " with classLoader " + classLoader, e);
+ }
+ throw new PinpointException("invalid ClassLoader");
+ }
+
+
+
+ private Class<?> injectClass0(URLClassLoader classLoader, String className) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
+ final URL[] urls = classLoader.getURLs();
+ if (urls != null) {
+
+ final boolean hasPluginJar = hasPluginJar(urls);
+
+ if (!hasPluginJar) {
+ logger.debug("add Jar:{}", pluginURLString);
+ ADD_URL.invoke(classLoader, pluginURL);
+ }
+ }
+
+ return classLoader.loadClass(className);
+ }
+
+ private boolean hasPluginJar(URL[] urls) {
+ for (URL url : urls) {
+ // if (url.equals(pluginJarURL)) { fix very slow
+ // http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html
+ final String externalForm = url.toExternalForm();
+ if (pluginURLString.equals(externalForm)) {
+
+ return true;
+ }
+ }
+ return false;
+ }
+
+
+}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/ClassNameFilterChain.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/ClassNameFilterChain.java
new file mode 100644
index 000000000000..801abc09b176
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/ClassNameFilterChain.java
@@ -0,0 +1,47 @@
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.plugin;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class ClassNameFilterChain implements ClassNameFilter {
+
+ private final List<ClassNameFilter> filterChain;
+
+ public ClassNameFilterChain(List<ClassNameFilter> filterChain) {
+ if (filterChain == null) {
+ throw new NullPointerException("filterChain must not be null");
+ }
+ this.filterChain = new ArrayList<ClassNameFilter>(filterChain);
+ }
+
+
+ @Override
+ public boolean accept(String className) {
+ for (ClassNameFilter classNameFilter : this.filterChain) {
+ if (!classNameFilter.accept(className)) {
+ return REJECT;
+ }
+ }
+ return ACCEPT;
+ }
+}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/PinpointProfilerPackageSkipFilter.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/PinpointProfilerPackageSkipFilter.java
new file mode 100644
index 000000000000..5ce71bc9ec60
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/PinpointProfilerPackageSkipFilter.java
@@ -0,0 +1,74 @@
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.plugin;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class PinpointProfilerPackageSkipFilter implements ClassNameFilter {
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+ private final List<String> packageList;
+
+ public PinpointProfilerPackageSkipFilter() {
+ this(getPinpointPackageList());
+ }
+
+ public PinpointProfilerPackageSkipFilter(List<String> packageList) {
+ if (packageList == null) {
+ throw new NullPointerException("packageList must not be null");
+ }
+ this.packageList = new ArrayList<String>(packageList);
+ }
+
+
+
+ @Override
+ public boolean accept(String className) {
+ if (className == null) {
+ throw new NullPointerException("className must not be null");
+ }
+
+ for (String packageName : packageList) {
+ if (className.startsWith(packageName)) {
+ if (logger.isDebugEnabled()) {
+ logger.info("skip ProfilerPackage:{} Class:{}", packageName, className);
+ }
+ return REJECT;
+ }
+ }
+ return ACCEPT;
+ }
+
+ private static List<String> getPinpointPackageList() {
+ List<String> pinpointPackageList = new ArrayList<String>();
+ pinpointPackageList.add("com.navercorp.pinpoint.bootstrap");
+ pinpointPackageList.add("com.navercorp.pinpoint.profiler");
+ pinpointPackageList.add("com.navercorp.pinpoint.common");
+ pinpointPackageList.add("com.navercorp.pinpoint.exception");
+ // TODO move test package
+ pinpointPackageList.add("com.navercorp.pinpoint.test");
+ return pinpointPackageList;
+ }
+}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/PluginConfig.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/PluginConfig.java
index 3ea006ffe3fd..7543b58d138c 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/PluginConfig.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/PluginConfig.java
@@ -19,7 +19,6 @@
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentClassPool;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPlugin;
-import com.navercorp.pinpoint.bootstrap.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -31,9 +30,7 @@
import java.net.URL;
import java.util.Collections;
import java.util.List;
-import java.util.jar.Attributes;
import java.util.jar.JarFile;
-import java.util.jar.Manifest;
/**
* @author Woonduk Kang(emeroad)
@@ -50,15 +47,14 @@ public class PluginConfig {
private String pluginJarURLExternalForm;
private final ProfilerPlugin plugin;
- private final Manifest manifest;
private final Instrumentation instrumentation;
private final InstrumentClassPool classPool;
private final String bootstrapCoreJarPath;
+
private final ClassNameFilter pluginPackageFilter;
- private final ClassNameFilter profilerPackageFilter;
- public PluginConfig(URL pluginJar, ProfilerPlugin plugin, Instrumentation instrumentation, InstrumentClassPool classPool, String bootstrapCoreJarPath) {
+ public PluginConfig(URL pluginJar, ProfilerPlugin plugin, Instrumentation instrumentation, InstrumentClassPool classPool, String bootstrapCoreJarPath, ClassNameFilter pluginPackageFilter) {
if (pluginJar == null) {
throw new NullPointerException("pluginJar must not be null");
}
@@ -68,37 +64,16 @@ public PluginConfig(URL pluginJar, ProfilerPlugin plugin, Instrumentation instru
this.pluginJar = pluginJar;
this.pluginJarFile = createJarFile(pluginJar);
this.plugin = plugin;
- this.manifest = this.getManifest();
this.instrumentation = instrumentation;
this.classPool = classPool;
this.bootstrapCoreJarPath = bootstrapCoreJarPath;
- final List<String> pluginPackageList = getPluginPackage(manifest);
- if (logger.isInfoEnabled()) {
- logger.info("{} Plugin Package:{}", plugin.getClass(), pluginPackageList);
- }
- this.pluginPackageFilter = new PluginPackageFilter(pluginPackageList);
- this.profilerPackageFilter = new PinpointProfilerPackageFilter();
+ this.pluginPackageFilter = pluginPackageFilter;
}
- private Manifest getManifest() {
- try {
- return pluginJarFile.getManifest();
- } catch (IOException e) {
- // return empty
- return new Manifest();
- }
- }
- public List<String> getPluginPackage(Manifest manifest) {
- final Attributes attributes = manifest.getMainAttributes();
- final String pluginPackage = attributes.getValue(PINPOINT_PLUGIN_PACKAGE);
- if (pluginPackage == null) {
- return DEFAULT_PINPOINT_PLUGIN_PACKAGE_NAME;
- }
- return StringUtils.splitAndTrim(pluginPackage, ",");
- }
+
public ProfilerPlugin getPlugin() {
return plugin;
@@ -146,7 +121,5 @@ public ClassNameFilter getPluginPackageFilter() {
return pluginPackageFilter;
}
- public ClassNameFilter getProfilerPackageFilter() {
- return profilerPackageFilter;
- }
-}
+
+}
\ No newline at end of file
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/ProfilerPluginLoader.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/ProfilerPluginLoader.java
index df996756da4b..7a4d8b8e30a9 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/ProfilerPluginLoader.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/ProfilerPluginLoader.java
@@ -14,14 +14,23 @@
*/
package com.navercorp.pinpoint.profiler.plugin;
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
import com.navercorp.pinpoint.bootstrap.instrument.GuardInstrumentContext;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentContext;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplate;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplateAware;
+import com.navercorp.pinpoint.bootstrap.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,6 +48,8 @@ public class ProfilerPluginLoader {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final DefaultAgent agent;
+ private final ClassNameFilter profilerPackageFilter = new PinpointProfilerPackageSkipFilter();
+
public ProfilerPluginLoader(DefaultAgent agent) {
if (agent == null) {
throw new NullPointerException("agent must not be null");
@@ -51,31 +62,87 @@ public List<DefaultProfilerPluginContext> load(URL[] pluginJars) {
List<String> disabled = agent.getProfilerConfig().getDisabledPlugins();
for (URL jar : pluginJars) {
- List<ProfilerPlugin> plugins = PluginLoader.load(ProfilerPlugin.class, new URL[] { jar });
-
+
+ final JarFile pluginJarFile = createJarFile(jar);
+ final List<String> pluginPackageList = getPluginPackage(pluginJarFile);
+
+ final ClassNameFilter pluginFilterChain = createPluginFilterChain(pluginPackageList);
+
+ final List<ProfilerPlugin> plugins = PluginLoader.load(ProfilerPlugin.class, new URL[] { jar });
+
for (ProfilerPlugin plugin : plugins) {
if (disabled.contains(plugin.getClass().getName())) {
logger.info("Skip disabled plugin: {}", plugin.getClass().getName());
continue;
}
+ if (logger.isInfoEnabled()) {
+ logger.info("{} Plugin {}:{}", plugin.getClass(), PluginConfig.PINPOINT_PLUGIN_PACKAGE, pluginPackageList);
+ }
- logger.info("Loading plugin: {}", plugin.getClass().getName());
+ logger.info("Loading plugin:{} pluginPackage:{}", plugin.getClass().getName(), plugin);
- PluginConfig pluginConfig = new PluginConfig(jar, plugin, agent.getInstrumentation(), agent.getClassPool(), agent.getBootstrapCoreJar());
+ PluginConfig pluginConfig = new PluginConfig(jar, plugin, agent.getInstrumentation(), agent.getClassPool(), agent.getBootstrapCoreJar(), pluginFilterChain);
final DefaultProfilerPluginContext context = setupPlugin(pluginConfig);
pluginContexts.add(context);
}
}
-
+
return pluginContexts;
}
+ private ClassNameFilter createPluginFilterChain(List<String> packageList) {
+
+ final ClassNameFilter pluginPackageFilter = new PluginPackageFilter(packageList);
+
+ final List<ClassNameFilter> chain = Arrays.asList(profilerPackageFilter, pluginPackageFilter);
+
+ final ClassNameFilter filterChain = new ClassNameFilterChain(chain);
+
+ return filterChain;
+ }
+
+ private JarFile createJarFile(URL pluginJar) {
+ try {
+ final URI uri = pluginJar.toURI();
+ return new JarFile(new File(uri));
+ } catch (URISyntaxException e) {
+ throw new RuntimeException("URISyntax error. " + e.getCause(), e);
+ } catch (IOException e) {
+ throw new RuntimeException("IO error. " + e.getCause(), e);
+ }
+ }
+ private Manifest getManifest(JarFile pluginJarFile) {
+ try {
+ return pluginJarFile.getManifest();
+ } catch (IOException ex) {
+ logger.info("{} IoError :{}", pluginJarFile.getName(), ex.getMessage(), ex);
+ return null;
+ }
+ }
+
+ public List<String> getPluginPackage(JarFile pluginJarFile) {
+
+ final Manifest manifest = getManifest(pluginJarFile);
+ if (manifest == null) {
+ return PluginConfig.DEFAULT_PINPOINT_PLUGIN_PACKAGE_NAME;
+ }
+
+ final Attributes attributes = manifest.getMainAttributes();
+ final String pluginPackage = attributes.getValue(PluginConfig.PINPOINT_PLUGIN_PACKAGE);
+ if (pluginPackage == null) {
+ return PluginConfig.DEFAULT_PINPOINT_PLUGIN_PACKAGE_NAME;
+ }
+ return StringUtils.splitAndTrim(pluginPackage, ",");
+ }
+
+
private GuardInstrumentContext preparePlugin(ProfilerPlugin plugin, InstrumentContext context) {
+
final GuardInstrumentContext guardInstrumentContext = new GuardInstrumentContext(context);
if (plugin instanceof TransformTemplateAware) {
if (logger.isDebugEnabled()) {
- logger.debug("setTransformTemplate {}", plugin.getClass().getName());
+ logger.debug("{}.setTransformTemplate", plugin.getClass().getName());
}
final TransformTemplate transformTemplate = new TransformTemplate(guardInstrumentContext);
((TransformTemplateAware) plugin).setTransformTemplate(transformTemplate);
@@ -92,6 +159,9 @@ private DefaultProfilerPluginContext setupPlugin(PluginConfig pluginConfig) {
try {
// WARN external plugin api
final ProfilerPlugin plugin = pluginConfig.getPlugin();
+ if (logger.isInfoEnabled()) {
+ logger.info("{} Plugin setup", plugin.getClass().getName());
+ }
plugin.setup(guardPluginContext);
} finally {
guardPluginContext.close();
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjectorTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjectorTest.java
new file mode 100644
index 000000000000..b7147acbc0ce
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/JarProfilerPluginClassInjectorTest.java
@@ -0,0 +1,129 @@
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.instrument;
+
+import com.navercorp.pinpoint.bootstrap.LibClass;
+import com.navercorp.pinpoint.bootstrap.PinpointURLClassLoader;
+import com.navercorp.pinpoint.bootstrap.instrument.InstrumentClassPool;
+import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPlugin;
+import com.navercorp.pinpoint.profiler.plugin.PluginConfig;
+import com.navercorp.pinpoint.profiler.plugin.PluginPackageFilter;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.util.ReflectionUtils;
+
+import java.lang.instrument.Instrumentation;
+import java.lang.reflect.Constructor;
+import java.net.URL;
+import java.security.CodeSource;
+import java.util.Arrays;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class JarProfilerPluginClassInjectorTest {
+
+ public static final String CONTEXT_TYPE_MATCH_CLASS_LOADER = "org.springframework.context.support.ContextTypeMatchClassLoader";
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ @Test
+ public void testInjectClass() throws Exception {
+ final URL sampleJar = getSampleJar(Logger.class);
+
+ final ClassLoader contextTypeMatchClassLoader = createContextTypeMatchClassLoader(new URL[]{sampleJar});
+
+ InstrumentClassPool pool = Mockito.mock(InstrumentClassPool.class);
+ final Instrumentation instrumentation = Mockito.mock(Instrumentation.class);
+ final ProfilerPlugin profilerPlugin = Mockito.mock(ProfilerPlugin.class);
+
+
+// final PluginPackageFilter filter = new PluginPackageFilter(Arrays.asList("test"));
+ final String packageName = logger.getClass().getPackage().getName();
+ final PluginPackageFilter filter = new PluginPackageFilter(Arrays.asList(packageName));
+ PluginConfig pluginConfig = new PluginConfig(sampleJar, profilerPlugin, instrumentation, pool, sampleJar.getPath(), filter);
+
+ PlainClassLoaderHandler injector = new PlainClassLoaderHandler(pluginConfig);
+ final Class<?> loggerClass = injector.injectClass(contextTypeMatchClassLoader, logger.getClass().getName());
+
+ logger.debug("ClassLoader{}", loggerClass.getClassLoader());
+ Assert.assertEquals("check className", loggerClass.getName(), "org.slf4j.impl.Log4jLoggerAdapter");
+ Assert.assertEquals("check ClassLoader", loggerClass.getClassLoader().getClass().getName(), CONTEXT_TYPE_MATCH_CLASS_LOADER);
+
+ }
+
+ private ClassLoader createContextTypeMatchClassLoader(URL[] urlArray) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException {
+ final ClassLoader classLoader = this.getClass().getClassLoader();
+ final Class<ClassLoader> aClass = (Class<ClassLoader>) classLoader.loadClass(CONTEXT_TYPE_MATCH_CLASS_LOADER);
+ final Constructor<ClassLoader> constructor = aClass.getConstructor(ClassLoader.class);
+ ReflectionUtils.makeAccessible(constructor);
+
+ final LibClass libClassFilter = new LibClass() {
+ @Override
+ public boolean onLoadClass(String clazzName) {
+ if (clazzName.startsWith("org.slf4j")) {
+ logger.debug("Loading {}", clazzName);
+ return ON_LOAD_CLASS;
+ }
+ return DELEGATE_PARENT;
+ }
+ };
+ PinpointURLClassLoader testClassLoader = new PinpointURLClassLoader(urlArray, ClassLoader.getSystemClassLoader(), libClassFilter);
+
+ final ClassLoader contextTypeMatchClassLoader = constructor.newInstance(testClassLoader);
+
+ logger.debug("cl:{}",contextTypeMatchClassLoader);
+
+// final Method excludePackage = aClass.getMethod("excludePackage", String.class);
+// ReflectionUtils.invokeMethod(excludePackage, contextTypeMatchClassLoader, "org.slf4j");
+
+
+ return contextTypeMatchClassLoader;
+ }
+
+
+ private URL getSampleJar(Class clazz) {
+ final CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
+ final URL location = codeSource.getLocation();
+
+ logger.debug("url:{}", location);
+
+ return location;
+ }
+
+}
\ No newline at end of file
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/ClassNameFilterChainTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/ClassNameFilterChainTest.java
new file mode 100644
index 000000000000..12920ad04752
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/ClassNameFilterChainTest.java
@@ -0,0 +1,43 @@
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.plugin;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.Arrays;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class ClassNameFilterChainTest {
+
+ @Test
+ public void testAccept() throws Exception {
+ PluginPackageFilter include = new PluginPackageFilter(Arrays.asList("com.include"));
+ PinpointProfilerPackageSkipFilter exclude = new PinpointProfilerPackageSkipFilter(Arrays.asList("com.exclude"));
+
+ ClassNameFilterChain chain = new ClassNameFilterChain(Arrays.asList(include, exclude));
+
+
+ Assert.assertTrue(chain.accept("com.include"));
+ Assert.assertFalse(chain.accept("com.exclude"));
+
+ Assert.assertFalse(chain.accept("unknown"));
+ }
+}
\ No newline at end of file
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/PinpointProfilerPackageSkipFilterTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/PinpointProfilerPackageSkipFilterTest.java
new file mode 100644
index 000000000000..3207cb84a9de
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/PinpointProfilerPackageSkipFilterTest.java
@@ -0,0 +1,37 @@
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.plugin;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class PinpointProfilerPackageSkipFilterTest {
+
+ @Test
+ public void testAccept() throws Exception {
+
+ PinpointProfilerPackageSkipFilter filter = new PinpointProfilerPackageSkipFilter();
+ Assert.assertFalse("skip", filter.accept("com.navercorp.pinpoint.bootstrap.test.class"));
+
+ Assert.assertTrue("include", filter.accept("test"));
+
+ }
+}
\ No newline at end of file
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/PluginPackageFilterTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/PluginPackageFilterTest.java
new file mode 100644
index 000000000000..7d5fb6da87aa
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/plugin/PluginPackageFilterTest.java
@@ -0,0 +1,40 @@
+/*
+ * *
+ * * Copyright 2016 NAVER Corp.
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.plugin;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.Arrays;
+
+import static org.junit.Assert.*;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class PluginPackageFilterTest {
+
+ @Test
+ public void testAccept() throws Exception {
+ PluginPackageFilter filter = new PluginPackageFilter(Arrays.asList("com.plugin"));
+
+ Assert.assertTrue(filter.accept("com.plugin.test.module"));
+
+ Assert.assertFalse(filter.accept("test"));
+ }
+}
\ No newline at end of file
| test | train | "2016-01-29T11:08:10" | "2016-01-14T06:03:04Z" | emeroad | test |
pinpoint-apm/pinpoint/1541_1555 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1541 | pinpoint-apm/pinpoint/1555 | [
"keyword_pr_to_issue"
] | c0460d167571dda9f4b40c6f2d0c3aa3a685624a | 5687954f0b68ccedb477ac9cc1645dfe84094b67 | [] | [] | "2016-02-25T09:24:48Z" | [
"enhancement"
] | Add trace support when using JDBC CallableStatements | Current JDBC tracers do not propagate server information when using `CallableStatement`, and results in rendering an _unknown_db_ node. Adding an interceptor for `CallableStatement` similar to what's done for `PrepareStatement` should fix the issue.
| [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/PreparedStatementCreateInterceptor.java",
"plugins/cubrid-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/cubrid/CubridPlugin.java",
"plugins/jtds/src/main/java/com/navercorp/pinpoint/plugin/jdbc/jtds/JtdsPlugin.java",
"plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java",
"plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java",
"plugins/oracle-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/oracle/OraclePlugin.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementBindVariableInterceptor.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementExecuteQueryInterceptor.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementRegisterOutParameterInterceptor.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/PreparedStatementCreateInterceptor.java",
"plugins/cubrid-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/cubrid/CubridPlugin.java",
"plugins/jtds/src/main/java/com/navercorp/pinpoint/plugin/jdbc/jtds/JtdsPlugin.java",
"plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java",
"plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java",
"plugins/oracle-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/oracle/OraclePlugin.java"
] | [
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_IT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_IT_Base.java",
"agent/src/test/resources/jdbc/mariadb/init.sql"
] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementBindVariableInterceptor.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementBindVariableInterceptor.java
new file mode 100644
index 000000000000..1471633ebfa0
--- /dev/null
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementBindVariableInterceptor.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor;
+
+import com.navercorp.pinpoint.bootstrap.context.TraceContext;
+import com.navercorp.pinpoint.bootstrap.interceptor.annotation.TargetFilter;
+
+/**
+ * @author HyunGil Jeong
+ */
+@TargetFilter(type = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.PreparedStatementBindingMethodFilter", singleton = true)
+public class CallableStatementBindVariableInterceptor extends PreparedStatementBindVariableInterceptor {
+
+ public CallableStatementBindVariableInterceptor(TraceContext traceContext) {
+ super(traceContext);
+ }
+
+}
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementExecuteQueryInterceptor.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementExecuteQueryInterceptor.java
new file mode 100644
index 000000000000..0f1bad6654d2
--- /dev/null
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementExecuteQueryInterceptor.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor;
+
+import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
+import com.navercorp.pinpoint.bootstrap.context.TraceContext;
+import com.navercorp.pinpoint.bootstrap.interceptor.annotation.TargetMethod;
+import com.navercorp.pinpoint.bootstrap.interceptor.annotation.TargetMethods;
+
+/**
+ * @author HyunGil Jeong
+ */
+@TargetMethods({
+ @TargetMethod(name = "execute"),
+ @TargetMethod(name = "executeQuery"),
+ @TargetMethod(name = "executeUpdate")
+})
+public class CallableStatementExecuteQueryInterceptor extends PreparedStatementExecuteQueryInterceptor {
+
+ public CallableStatementExecuteQueryInterceptor(TraceContext traceContext, MethodDescriptor descriptor) {
+ super(traceContext, descriptor);
+ }
+
+ public CallableStatementExecuteQueryInterceptor(TraceContext traceContext, MethodDescriptor descriptor, int maxSqlBindValue) {
+ super(traceContext, descriptor, maxSqlBindValue);
+ }
+
+}
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementRegisterOutParameterInterceptor.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementRegisterOutParameterInterceptor.java
new file mode 100644
index 000000000000..e21d6a264ebf
--- /dev/null
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/CallableStatementRegisterOutParameterInterceptor.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor;
+
+import com.navercorp.pinpoint.bootstrap.context.DatabaseInfo;
+import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
+import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
+import com.navercorp.pinpoint.bootstrap.context.TraceContext;
+import com.navercorp.pinpoint.bootstrap.interceptor.SpanEventSimpleAroundInterceptorForPlugin;
+import com.navercorp.pinpoint.bootstrap.interceptor.annotation.TargetMethod;
+import com.navercorp.pinpoint.bootstrap.interceptor.annotation.TargetMethods;
+import com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor;
+import com.navercorp.pinpoint.bootstrap.plugin.jdbc.UnKnownDatabaseInfo;
+
+/**
+ * @author HyunGil Jeong
+ */
+@TargetMethods({
+ @TargetMethod(name = "registerOutParameter", paramTypes = {"int", "int"}),
+ @TargetMethod(name = "registerOutParameter", paramTypes = {"int", "int", "int"}),
+ @TargetMethod(name = "registerOutParameter", paramTypes = {"int", "int", "java.lang.String"})
+})
+public class CallableStatementRegisterOutParameterInterceptor extends SpanEventSimpleAroundInterceptorForPlugin {
+
+ public CallableStatementRegisterOutParameterInterceptor(TraceContext traceContext, MethodDescriptor descriptor) {
+ super(traceContext, descriptor);
+ }
+
+ @Override
+ protected void doInBeforeTrace(SpanEventRecorder recorder, Object target, Object[] args) {
+ }
+
+ @Override
+ protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
+ DatabaseInfo databaseInfo = (target instanceof DatabaseInfoAccessor) ? ((DatabaseInfoAccessor)target)._$PINPOINT$_getDatabaseInfo() : null;
+
+ if (databaseInfo == null) {
+ databaseInfo = UnKnownDatabaseInfo.INSTANCE;
+ }
+
+ recorder.recordServiceType(databaseInfo.getType());
+ recorder.recordEndPoint(databaseInfo.getMultipleHost());
+ recorder.recordDestinationId(databaseInfo.getDatabaseId());
+
+ recorder.recordApi(methodDescriptor, args);
+ recorder.recordException(throwable);
+ }
+}
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/PreparedStatementCreateInterceptor.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/PreparedStatementCreateInterceptor.java
index 47b317fbbda9..5cae250b0df2 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/PreparedStatementCreateInterceptor.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/jdbc/interceptor/PreparedStatementCreateInterceptor.java
@@ -38,7 +38,10 @@
@TargetMethod(name="prepareStatement", paramTypes={ "java.lang.String", "int[]" }),
@TargetMethod(name="prepareStatement", paramTypes={ "java.lang.String", "java.lang.String[]" }),
@TargetMethod(name="prepareStatement", paramTypes={ "java.lang.String", "int", "int" }),
- @TargetMethod(name="prepareStatement", paramTypes={ "java.lang.String", "int", "int", "int" })
+ @TargetMethod(name="prepareStatement", paramTypes={ "java.lang.String", "int", "int", "int" }),
+ @TargetMethod(name="prepareCall", paramTypes={ "java.lang.String" }),
+ @TargetMethod(name="prepareCall", paramTypes={ "java.lang.String", "int", "int" }),
+ @TargetMethod(name="prepareCall", paramTypes={ "java.lang.String", "int", "int", "int" })
})
public class PreparedStatementCreateInterceptor extends SpanEventSimpleAroundInterceptorForPlugin {
diff --git a/plugins/cubrid-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/cubrid/CubridPlugin.java b/plugins/cubrid-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/cubrid/CubridPlugin.java
index ee1b31a7a930..1af6bd882248 100644
--- a/plugins/cubrid-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/cubrid/CubridPlugin.java
+++ b/plugins/cubrid-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/cubrid/CubridPlugin.java
@@ -43,6 +43,7 @@ public void setup(ProfilerPluginSetupContext context) {
addCUBRIDConnectionTransformer(config);
addCUBRIDDriverTransformer();
addCUBRIDPreparedStatementTransformer(config);
+ addCUBRIDCallableStatementTransformer();
addCUBRIDStatementTransformer();
}
@@ -113,6 +114,24 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
}
});
}
+
+ private void addCUBRIDCallableStatementTransformer() {
+ transformTemplate.transform("cubrid.jdbc.driver.CUBRIDCallableStatement", new TransformCallback() {
+
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.BindValueAccessor");
+
+ target.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.CallableStatementRegisterOutParameterInterceptor", CubridConstants.CUBRID_SCOPE);
+
+ return target.toBytecode();
+ }
+ });
+ }
private void addCUBRIDStatementTransformer() {
transformTemplate.transform("cubrid.jdbc.driver.CUBRIDStatement", new TransformCallback() {
diff --git a/plugins/jtds/src/main/java/com/navercorp/pinpoint/plugin/jdbc/jtds/JtdsPlugin.java b/plugins/jtds/src/main/java/com/navercorp/pinpoint/plugin/jdbc/jtds/JtdsPlugin.java
index ff21ffd6a2d4..47739759252c 100644
--- a/plugins/jtds/src/main/java/com/navercorp/pinpoint/plugin/jdbc/jtds/JtdsPlugin.java
+++ b/plugins/jtds/src/main/java/com/navercorp/pinpoint/plugin/jdbc/jtds/JtdsPlugin.java
@@ -42,6 +42,7 @@ public void setup(ProfilerPluginSetupContext context) {
addConnectionTransformer(config);
addDriverTransformer();
addPreparedStatementTransformer(config);
+ addCallableStatementTransformer();
addStatementTransformer();
}
@@ -115,6 +116,24 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
});
}
+ private void addCallableStatementTransformer() {
+ transformTemplate.transform("net.sourceforge.jtds.jdbc.JtdsCallableStatement", new TransformCallback() {
+
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.BindValueAccessor");
+
+ target.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.CallableStatementRegisterOutParameterInterceptor", JtdsConstants.JTDS_SCOPE);
+
+ return target.toBytecode();
+ }
+ });
+ }
+
private void addStatementTransformer() {
transformTemplate.transform("net.sourceforge.jtds.jdbc.JtdsStatement", new TransformCallback() {
diff --git a/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java b/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java
index b594f217f812..590c4abc5502 100644
--- a/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java
+++ b/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java
@@ -44,7 +44,12 @@ public void setup(ProfilerPluginSetupContext context) {
addDriverTransformer();
addPreparedStatementTransformer(config);
addPreparedStatementBindVariableTransformer(config);
+ addCallableStatementTransformer();
addStatementTransformer();
+
+ // MariaDb 1.3.x's CallableStatements are completely separated from PreparedStatements (similar to MySQL)
+ // Separate interceptors must be injected.
+ add_1_3_x_CallableStatementTransformer(config);
}
private void addConnectionTransformer(final MariaDBConfig config) {
@@ -206,6 +211,54 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
}
+ private void addCallableStatementTransformer() {
+ TransformCallback transformer = new TransformCallback() {
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className,
+ Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
+ byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.BindValueAccessor");
+
+ target.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.CallableStatementRegisterOutParameterInterceptor", MariaDBConstants.MARIADB_SCOPE);
+
+ return target.toBytecode();
+ }
+ };
+
+ transformTemplate.transform("org.mariadb.jdbc.AbstractCallableProcedureStatement", transformer);
+ transformTemplate.transform("org.mariadb.jdbc.AbstractCallableFunctionStatement", transformer);
+ }
+
+ private void add_1_3_x_CallableStatementTransformer(final MariaDBConfig config) {
+ transformTemplate.transform("org.mariadb.jdbc.MariaDbCallableStatement", new TransformCallback() {
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className,
+ Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
+ byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.BindValueAccessor");
+
+ int maxBindValueSize = config.getMaxSqlBindValueSize();
+
+ target.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.CallableStatementExecuteQueryInterceptor", va(maxBindValueSize), MariaDBConstants.MARIADB_SCOPE);
+ target.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.CallableStatementRegisterOutParameterInterceptor", MariaDBConstants.MARIADB_SCOPE);
+
+ if (config.isTraceSqlBindValue()) {
+ target.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.CallableStatementBindVariableInterceptor", MariaDBConstants.MARIADB_SCOPE);
+ }
+
+ return target.toBytecode();
+ }
+ });
+ }
+
@Override
public void setTransformTemplate(TransformTemplate transformTemplate) {
this.transformTemplate = transformTemplate;
diff --git a/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java
index ba730858995a..58d668c4c7b8 100644
--- a/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java
+++ b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java
@@ -44,10 +44,12 @@ public void setup(ProfilerPluginSetupContext context) {
addDriverTransformer();
addStatementTransformer();
addPreparedStatementTransformer(config);
+ addCallableStatementTransformer(config);
// From MySQL driver 5.1.x, backward compatibility is broken.
// Driver returns not com.mysql.jdbc.Connection but com.mysql.jdbc.JDBC4Connection which extends com.mysql.jdbc.ConnectionImpl from 5.1.x
addJDBC4PreparedStatementTransformer(config);
+ addJDBC4CallableStatementTransformer(config);
}
private void addConnectionTransformer(final MySqlConfig config) {
@@ -127,6 +129,32 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
});
}
+ private void addCallableStatementTransformer(final MySqlConfig config) {
+ transformTemplate.transform("com.mysql.jdbc.CallableStatement", new TransformCallback() {
+
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.BindValueAccessor");
+
+ int maxBindValueSize = config.getMaxSqlBindValueSize();
+
+ target.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.CallableStatementExecuteQueryInterceptor", va(maxBindValueSize), MySqlConstants.MYSQL_SCOPE);
+ target.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.CallableStatementRegisterOutParameterInterceptor", MySqlConstants.MYSQL_SCOPE);
+
+ if (config.isTraceSqlBindValue()) {
+ final PreparedStatementBindingMethodFilter excludes = PreparedStatementBindingMethodFilter.excludes("setRowId", "setNClob", "setSQLXML");
+ target.addScopedInterceptor(excludes, "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.CallableStatementBindVariableInterceptor", MySqlConstants.MYSQL_SCOPE, ExecutionPolicy.BOUNDARY);
+ }
+
+ return target.toBytecode();
+ }
+ });
+ }
+
private void addJDBC4PreparedStatementTransformer(final MySqlConfig config) {
transformTemplate.transform("com.mysql.jdbc.JDBC4PreparedStatement", new TransformCallback() {
@@ -144,6 +172,22 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
});
}
+ private void addJDBC4CallableStatementTransformer(final MySqlConfig config) {
+ transformTemplate.transform("com.mysql.jdbc.JDBC4CallableStatement", new TransformCallback() {
+
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+
+ if (config.isTraceSqlBindValue()) {
+ final PreparedStatementBindingMethodFilter includes = PreparedStatementBindingMethodFilter.includes("setRowId", "setNClob", "setSQLXML");
+ target.addScopedInterceptor(includes, "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.CallableStatementBindVariableInterceptor", MySqlConstants.MYSQL_SCOPE, ExecutionPolicy.BOUNDARY);
+ }
+
+ return target.toBytecode();
+ }
+ });
+ }
private void addStatementTransformer() {
TransformCallback transformer = new TransformCallback() {
diff --git a/plugins/oracle-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/oracle/OraclePlugin.java b/plugins/oracle-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/oracle/OraclePlugin.java
index acd14910e520..452a53a51b32 100644
--- a/plugins/oracle-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/oracle/OraclePlugin.java
+++ b/plugins/oracle-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/oracle/OraclePlugin.java
@@ -37,6 +37,8 @@ public class OraclePlugin implements ProfilerPlugin, TransformTemplateAware {
private static final String CLASS_STATEMENT = "oracle.jdbc.driver.OracleStatement";
private static final String CLASS_PREPARED_STATEMENT_WRAPPER = "oracle.jdbc.driver.OraclePreparedStatementWrapper";
private static final String CLASS_PREPARED_STATEMENT = "oracle.jdbc.driver.OraclePreparedStatement";
+ private static final String CLASS_CALLABLE_STATEMENT_WRAPPER = "oracle.jdbc.driver.OracleCallableStatementWrapper";
+ private static final String CLASS_CALLABLE_STATEMENT = "oracle.jdbc.driver.OracleCallableStatement";
private TransformTemplate transformTemplate;
@@ -47,6 +49,7 @@ public void setup(ProfilerPluginSetupContext context) {
addConnectionTransformer(config);
addDriverTransformer();
addPreparedStatementTransformer(config);
+ addCallableStatementTransformer();
addStatementTransformer();
}
@@ -128,6 +131,32 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
transformTemplate.transform(CLASS_PREPARED_STATEMENT_WRAPPER, transformer);
}
+ private void addCallableStatementTransformer() {
+ TransformCallback transformer = new TransformCallback() {
+
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+ if (className.equals(CLASS_CALLABLE_STATEMENT)) {
+ if (instrumentor.exist(loader, CLASS_CALLABLE_STATEMENT_WRAPPER)) {
+ return null;
+ }
+ }
+
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.BindValueAccessor");
+
+ target.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.CallableStatementRegisterOutParameterInterceptor", OracleConstants.ORACLE_SCOPE);
+
+ return target.toBytecode();
+ }
+ };
+
+ transformTemplate.transform(CLASS_CALLABLE_STATEMENT, transformer);
+ transformTemplate.transform(CLASS_CALLABLE_STATEMENT_WRAPPER, transformer);
+ }
+
private void addStatementTransformer() {
TransformCallback transformer = new TransformCallback() {
| diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBIT.java
deleted file mode 100644
index 11748fe5c665..000000000000
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBIT.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package com.navercorp.pinpoint.plugin.jdbc.mariadb;
-
-import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.*;
-import static org.junit.Assert.*;
-
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.Statement;
-import java.util.Properties;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mariadb.jdbc.Driver;
-import org.mariadb.jdbc.MariaDbConnection;
-import org.mariadb.jdbc.MariaDbServerPreparedStatement;
-import org.mariadb.jdbc.MariaDbStatement;
-
-import ch.vorburger.mariadb4j.DB;
-
-import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
-import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
-import com.navercorp.pinpoint.test.plugin.Dependency;
-import com.navercorp.pinpoint.test.plugin.JvmVersion;
-import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
-import com.navercorp.pinpoint.test.plugin.Repository;
-
-@RunWith(PinpointPluginTestSuite.class)
-@JvmVersion(7)
-@Repository("http://jcenter.bintray.com")
-@Dependency({ "org.mariadb.jdbc:mariadb-java-client:[1.3.4,)", "ch.vorburger.mariaDB4j:mariaDB4j:2.1.3" })
-public class MariaDBIT {
-
- private static final String JDBC_URL = "jdbc:mariadb://127.0.0.1:13306/test";
- private static final String PREPARED_STATEMENT = "SELECT * FROM playground where id = ?";
-
- private DB db;
-
- @Before
- public void init() throws Exception {
- db = DB.newEmbeddedDB(13306);
- db.start();
- db.createDB("test");
- db.source("jdbc/mariadb/init.sql");
- }
-
- @Test
- public void testConnection() throws Exception {
- PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
-
- Connection connection = DriverManager.getConnection(JDBC_URL, "root", null);
-
-// verifier.verifyTraceCount(1);
-
- Statement statement = connection.createStatement();
- ResultSet result = statement.executeQuery("SELECT count(1) FROM playground");
- result.first();
- assertEquals(3, result.getInt(1));
-
- verifier.printCache();
-
- verifier.verifyTraceCount(2);
- verifier.verifyTrace(event("MARIADB", Driver.class.getMethod("connect", String.class, Properties.class), cachedArgs(JDBC_URL)));
- verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", MariaDbStatement.class.getMethod("executeQuery", String.class), sql("SELECT count(0#) FROM playground", "1")));
-
- PreparedStatement ps = connection.prepareStatement(PREPARED_STATEMENT);
- ps.setInt(1, 3);
- result = ps.executeQuery();
- result.first();
- assertEquals("THREE", result.getString(2));
-
- verifier.printCache();
- verifier.verifyTraceCount(2);
- verifier.verifyTrace(event("MARIADB", MariaDbConnection.class.getMethod("prepareStatement", String.class), sql(PREPARED_STATEMENT, null)));
- verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", MariaDbServerPreparedStatement.class.getMethod("executeQuery"), sql(PREPARED_STATEMENT, null, "3")));
- }
-
- @After
- public void cleanUp() throws Exception {
- db.stop();
- }
-
-}
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java
new file mode 100644
index 000000000000..8ceeee24d745
--- /dev/null
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java
@@ -0,0 +1,104 @@
+package com.navercorp.pinpoint.plugin.jdbc.mariadb;
+
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.*;
+
+import java.lang.reflect.Method;
+import java.util.Properties;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.JvmVersion;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import com.navercorp.pinpoint.test.plugin.Repository;
+
+@RunWith(PinpointPluginTestSuite.class)
+@JvmVersion(7)
+@Repository("http://jcenter.bintray.com")
+@Dependency({"org.mariadb.jdbc:mariadb-java-client:[1.3.0,1.3.max]", "ch.vorburger.mariaDB4j:mariaDB4j:2.1.3"})
+public class MariaDB_1_3_x_IT extends MariaDB_IT_Base {
+
+ // see CallableParameterMetaData#queryMetaInfos
+ private static final String CALLABLE_QUERY_META_INFOS_QUERY = "select param_list,returns from mysql.proc where db=database() and name='0$'";
+
+ @Test
+ public void testStatement() throws Exception {
+ super.executeStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+ verifier.verifyTraceCount(2);
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbStatement#executeQuery(String)
+ Class<?> mariaDbStatementClass = Class.forName("org.mariadb.jdbc.MariaDbStatement");
+ Method executeQuery = mariaDbStatementClass.getDeclaredMethod("executeQuery", String.class);
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQuery, null, URL, DATABASE_NAME, sql(STATEMENT_NORMALIZED_QUERY, "1")));
+ }
+
+ @Test
+ public void testPreparedStatement() throws Exception {
+ super.executePreparedStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+ verifier.verifyTraceCount(3);
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbConnection#prepareStatement(String)
+ Class<?> mariaDbConnectionClass = Class.forName("org.mariadb.jdbc.MariaDbConnection");
+ Method prepareStatement = mariaDbConnectionClass.getDeclaredMethod("prepareStatement", String.class);
+ verifier.verifyTrace(event("MARIADB", prepareStatement, null, URL, DATABASE_NAME, sql(PREPARED_STATEMENT_QUERY, null)));
+
+ // MariaDbServerPreparedStatement#executeQuery
+ Class<?> mariaDbServerPreparedStatementClass = Class.forName("org.mariadb.jdbc.MariaDbServerPreparedStatement");
+ Method executeQuery = mariaDbServerPreparedStatementClass.getDeclaredMethod("executeQuery");
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQuery, null, URL, DATABASE_NAME, sql(PREPARED_STATEMENT_QUERY, null, "3")));
+ }
+
+ @Test
+ public void testCallableStatement() throws Exception {
+ super.executeCallableStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+ verifier.verifyTraceCount(5);
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbConnection#prepareCall(String)
+ Class<?> mariaDbConnectionClass = Class.forName("org.mariadb.jdbc.MariaDbConnection");
+ Method prepareCall = mariaDbConnectionClass.getDeclaredMethod("prepareCall", String.class);
+ verifier.verifyTrace(event("MARIADB", prepareCall, null, URL, DATABASE_NAME, sql(CALLABLE_STATEMENT_QUERY, null)));
+
+ // MariaDbClientCallableStatement#registerOutParameter(int, int)
+ Class<?> mariaDbClientCallableStatementClass = Class.forName("org.mariadb.jdbc.MariaDbCallableStatement");
+ Method registerOutParameter = mariaDbClientCallableStatementClass.getDeclaredMethod("registerOutParameter", int.class, int.class);
+ verifier.verifyTrace(event("MARIADB", registerOutParameter, null, URL, DATABASE_NAME, args(2, CALLABLE_STATMENT_OUTPUT_PARAM_TYPE)));
+
+ // MariaDbCallableStatement#executeQuery
+ Class<?> mariaDbCallableStatementClass = Class.forName("org.mariadb.jdbc.MariaDbCallableStatement");
+ Method callableStatementExecuteQuery = mariaDbCallableStatementClass.getDeclaredMethod("executeQuery");
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", callableStatementExecuteQuery, null, URL, DATABASE_NAME, sql(CALLABLE_STATEMENT_QUERY, null, CALLABLE_STATEMENT_INPUT_PARAM)));
+
+ // MariaDbStatement#executeQuery
+ Class<?> mariaDbStatementClass = Class.forName("org.mariadb.jdbc.MariaDbStatement");
+ Method statementExecuteQuery = mariaDbStatementClass.getDeclaredMethod("executeQuery", String.class);
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", statementExecuteQuery, null, URL, DATABASE_NAME, sql(CALLABLE_QUERY_META_INFOS_QUERY, PROCEDURE_NAME)));
+ }
+
+}
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_IT.java
new file mode 100644
index 000000000000..76fd14be8c25
--- /dev/null
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_IT.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.jdbc.mariadb;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.JvmVersion;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import com.navercorp.pinpoint.test.plugin.Repository;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.lang.reflect.Method;
+import java.util.Properties;
+
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.*;
+
+/**
+ * @author HyunGil Jeong
+ */
+
+@RunWith(PinpointPluginTestSuite.class)
+@JvmVersion(7)
+@Repository("http://jcenter.bintray.com")
+@Dependency({ "org.mariadb.jdbc:mariadb-java-client:[1.4.min,1.4.max]", "ch.vorburger.mariaDB4j:mariaDB4j:2.1.3" })
+public class MariaDB_1_4_x_IT extends MariaDB_IT_Base {
+
+ // see CallableParameterMetaData#queryMetaInfos
+ private static final String CALLABLE_QUERY_META_INFOS_QUERY = "select param_list, returns, db, type from mysql.proc where db=DATABASE() and name=?";
+
+ @Test
+ public void testStatement() throws Exception {
+ super.executeStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbStatement#executeQuery(String)
+ Class<?> mariaDbStatementClass = Class.forName("org.mariadb.jdbc.MariaDbStatement");
+ Method executeQuery = mariaDbStatementClass.getDeclaredMethod("executeQuery", String.class);
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQuery, null, URL, DATABASE_NAME, sql(STATEMENT_NORMALIZED_QUERY, "1")));
+ }
+
+ @Test
+ public void testPreparedStatement() throws Exception {
+ super.executePreparedStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+ verifier.verifyTraceCount(3);
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbConnection#prepareStatement(String)
+ Class<?> mariaDbConnectionClass = Class.forName("org.mariadb.jdbc.MariaDbConnection");
+ Method prepareStatement = mariaDbConnectionClass.getDeclaredMethod("prepareStatement", String.class);
+ verifier.verifyTrace(event("MARIADB", prepareStatement, null, URL, DATABASE_NAME, sql(PREPARED_STATEMENT_QUERY, null)));
+
+ // MariaDbServerPreparedStatement#executeQuery
+ Class<?> mariaDbServerPreparedStatementClass = Class.forName("org.mariadb.jdbc.MariaDbServerPreparedStatement");
+ Method executeQuery = mariaDbServerPreparedStatementClass.getDeclaredMethod("executeQuery");
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQuery, null, URL, DATABASE_NAME, sql(PREPARED_STATEMENT_QUERY, null, "3")));
+ }
+
+ @Test
+ public void testCallableStatement() throws Exception {
+ super.executeCallableStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+ verifier.verifyTraceCount(6);
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbConnection#prepareCall(String)
+ Class<?> mariaDbConnectionClass = Class.forName("org.mariadb.jdbc.MariaDbConnection");
+ Method prepareCall = mariaDbConnectionClass.getDeclaredMethod("prepareCall", String.class);
+ verifier.verifyTrace(event("MARIADB", prepareCall, null, URL, DATABASE_NAME, sql(CALLABLE_STATEMENT_QUERY, null)));
+
+ // AbstractCallableProcedureStatement#registerOutParameter
+ Class<?> abstractCallableProcedureStatementClass = Class.forName("org.mariadb.jdbc.AbstractCallableProcedureStatement");
+ Method registerOutParameter = abstractCallableProcedureStatementClass.getMethod("registerOutParameter", int.class, int.class);
+ verifier.verifyTrace(event("MARIADB", registerOutParameter, null, URL, DATABASE_NAME, args(2, CALLABLE_STATMENT_OUTPUT_PARAM_TYPE)));
+
+ // MariaDbServerPreparedStatement#executeQuery
+ Class<?> mariaDbServerPreparedStatementClass = Class.forName("org.mariadb.jdbc.MariaDbServerPreparedStatement");
+ Method executeQuery = mariaDbServerPreparedStatementClass.getDeclaredMethod("executeQuery");
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQuery, null, URL, DATABASE_NAME, sql(CALLABLE_STATEMENT_QUERY, null, CALLABLE_STATEMENT_INPUT_PARAM)));
+
+ // MariaDbConnection#prepareStatement(String)
+ Method prepareStatement = mariaDbConnectionClass.getDeclaredMethod("prepareStatement", String.class);
+ verifier.verifyTrace(event("MARIADB", prepareStatement, null, URL, DATABASE_NAME, sql(CALLABLE_QUERY_META_INFOS_QUERY, null)));
+
+ // MariaDbServerPreparedStatement#executeQuery
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQuery, null, URL, DATABASE_NAME, sql(CALLABLE_QUERY_META_INFOS_QUERY, null, PROCEDURE_NAME)));
+ }
+}
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_IT_Base.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_IT_Base.java
new file mode 100644
index 000000000000..f0fb3c4f00dc
--- /dev/null
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_IT_Base.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.jdbc.mariadb;
+
+import ch.vorburger.mariadb4j.DB;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class MariaDB_IT_Base {
+
+ private static final int PORT = 13306;
+ protected static final String URL = "127.0.0.1:" + PORT;
+ protected static final String DATABASE_NAME = "test";
+
+ protected static final String JDBC_URL = "jdbc:mariadb://" + URL + "/" + DATABASE_NAME;
+
+ // for Statement
+ protected static final String STATEMENT_QUERY = "SELECT count(1) FROM playground";
+ protected static final String STATEMENT_NORMALIZED_QUERY = "SELECT count(0#) FROM playground";
+
+ // for Prepared Statement
+ protected static final String PREPARED_STATEMENT_QUERY = "SELECT * FROM playground where id = ?";
+
+ // for Callable Statement
+ protected static final String PROCEDURE_NAME = "getPlaygroundByName";
+ protected static final String CALLABLE_STATEMENT_QUERY = "{ CALL " + PROCEDURE_NAME + "(?, ?) }";
+ protected static final String CALLABLE_STATEMENT_INPUT_PARAM = "TWO";
+ protected static final int CALLABLE_STATMENT_OUTPUT_PARAM_TYPE = Types.INTEGER;
+
+ private static DB TEST_DATABASE;
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ TEST_DATABASE = DB.newEmbeddedDB(PORT);
+ TEST_DATABASE.start();
+ TEST_DATABASE.createDB("test");
+ TEST_DATABASE.source("jdbc/mariadb/init.sql");
+ }
+
+ protected final void executeStatement() throws Exception {
+ Connection connection = null;
+ try {
+ connection = DriverManager.getConnection(JDBC_URL, "root", null);
+
+ Statement statement = null;
+ try {
+ statement = connection.createStatement();
+
+ ResultSet result = null;
+ try {
+ result = statement.executeQuery(STATEMENT_QUERY);
+ result.first();
+ assertEquals(3, result.getInt(1));
+ } finally {
+ closeResultSet(result);
+ }
+ } finally {
+ closeStatement(statement);
+ }
+ } finally {
+ closeConnection(connection);
+ }
+ }
+
+ protected final void executePreparedStatement() throws Exception {
+ Connection connection = null;
+ try {
+ connection = DriverManager.getConnection(JDBC_URL, "root", null);
+
+ PreparedStatement ps = null;
+ try {
+ ps = connection.prepareStatement(PREPARED_STATEMENT_QUERY);
+ ps.setInt(1, 3);
+
+ ResultSet result = null;
+ try {
+ result = ps.executeQuery();
+ result.first();
+ assertEquals("THREE", result.getString(2));
+ } finally {
+ closeResultSet(result);
+ }
+ } finally {
+ closeStatement(ps);
+ }
+ } finally {
+ closeConnection(connection);
+ }
+ }
+
+ protected final void executeCallableStatement() throws Exception {
+
+ final int expectedTotalCount = 3;
+ final int expectedMatchingCount = 1;
+ final int expectedMatchingId = 2;
+ final String outputParamCountName = "outputParamCount";
+
+ Connection conn = null;
+ try {
+ conn = DriverManager.getConnection(JDBC_URL, "root", null);
+
+ CallableStatement cs = null;
+ try {
+ cs = conn.prepareCall(CALLABLE_STATEMENT_QUERY);
+ cs.setString(1, CALLABLE_STATEMENT_INPUT_PARAM);
+ cs.registerOutParameter(2, CALLABLE_STATMENT_OUTPUT_PARAM_TYPE);
+
+ ResultSet rs = null;
+ try {
+ rs = cs.executeQuery();
+ int matchingCount = 0;
+ while (rs.next()) {
+ ++matchingCount;
+ if (matchingCount > expectedMatchingCount) {
+ fail();
+ }
+ assertEquals(expectedMatchingId, rs.getInt(1));
+ assertEquals(CALLABLE_STATEMENT_INPUT_PARAM, rs.getString(2));
+ }
+ assertEquals(expectedMatchingCount, matchingCount);
+ } finally {
+ closeResultSet(rs);
+ }
+ final int totalCount = cs.getInt(outputParamCountName);
+ assertEquals(expectedTotalCount, totalCount);
+ } finally {
+ closeStatement(cs);
+ }
+ } finally {
+ closeConnection(conn);
+ }
+ }
+
+ private void closeConnection(Connection conn) throws SQLException {
+ if (conn != null) {
+ conn.close();
+ }
+ }
+
+ private void closeResultSet(ResultSet rs) throws SQLException {
+ if (rs != null) {
+ rs.close();
+ }
+ }
+
+ private void closeStatement(Statement statement) throws SQLException {
+ if (statement != null) {
+ statement.close();
+ }
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() throws Exception {
+ TEST_DATABASE.stop();
+ }
+}
diff --git a/agent/src/test/resources/jdbc/mariadb/init.sql b/agent/src/test/resources/jdbc/mariadb/init.sql
index 975d93386f07..0833e4865210 100644
--- a/agent/src/test/resources/jdbc/mariadb/init.sql
+++ b/agent/src/test/resources/jdbc/mariadb/init.sql
@@ -2,4 +2,13 @@ USE test;
CREATE TABLE IF NOT EXISTS playground (id int(5) NOT NULL, name varchar(50) DEFAULT NULL);
INSERT INTO playground VALUES (1, 'ONE');
INSERT INTO playground VALUES (2, 'TWO');
-INSERT INTO playground VALUES (3, 'THREE');
\ No newline at end of file
+INSERT INTO playground VALUES (3, 'THREE');
+
+DELIMITER //
+CREATE PROCEDURE getPlaygroundByName (IN inputParamName VARCHAR(50), OUT outputParamCount INT)
+ BEGIN
+ SELECT count(*) INTO outputParamCount FROM playground;
+ SELECT id, name FROM playground WHERE name = inputParamName ORDER BY id ASC;
+ END;
+//
+DELIMITER ;
\ No newline at end of file
| train | train | "2016-02-25T08:05:26" | "2016-02-16T09:13:06Z" | Xylus | test |
pinpoint-apm/pinpoint/1319_1586 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1319 | pinpoint-apm/pinpoint/1586 | [
"keyword_pr_to_issue"
] | 4e490b1e27e0a2f9b917eefd0521cab13c07ddc6 | 8143ad8a3f3871e37092783b0776aeb855317b91 | [] | [] | "2016-03-10T02:08:14Z" | [
"enhancement",
"module:plugin"
] | Reduce trace scope for asynchronous calls made by the Thrift client | The current implementation of the asynchronous tracing model cannot guarantee the closure of _AsyncTrace_ unless it spans a single method.
For tracing asynchronous calls made by Thrift clients, the _AsyncTrace_ begins in `TAsyncMethodCall.start()` and ends in one of `TAsyncMethodCall.doWritingRequestBody()`, `TAsyncMethodCall.doReadingResponseBody()`, or `TAsyncMethodCall.onError()`.
If in future versions of Thrift adds a new code path that passes through `TAsyncMethodCall.start()` but not the one of ending methods, the _AsyncTrace_ will be pushed(start) but not popped(end).
To prevent these situations from every becoming a problem, it might be a good idea to reduce the scope of _AsyncTrace_ to the ending methods. The trace data might not be as detailed, but it would be safer this way.
| [
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncClientManagerCallInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallCleanUpAndFireCallbackInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallDoReadingResponseBodyInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallDoWritingRequestBodyInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallInternalMethodInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallOnErrorInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallStartInterceptor.java"
] | [
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncClientManagerCallInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallCleanUpAndFireCallbackInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallOnErrorInterceptor.java"
] | [
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java"
] | diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java
index acdf4ea59573..6f4c7fdf3dd2 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java
@@ -51,8 +51,6 @@ private ThriftConstants() {
public static final Pattern CLIENT_PATTERN = Pattern.compile("\\$Client");
public static final Pattern ASYNC_METHOD_CALL_PATTERN = Pattern.compile("\\$AsyncClient\\$");
- public static final String ATTRIBUTE_CONFIG = "thriftPluginConfig";
-
// field names
public static final String T_ASYNC_METHOD_CALL_FIELD_TRANSPORT = "transport";
public static final String FRAME_BUFFER_FIELD_TRANS_ = "trans_";
@@ -60,11 +58,7 @@ private ThriftConstants() {
// custom field injector (accessor) FQCN
private static final String FIELD_ACCESSOR_BASE = "com.navercorp.pinpoint.plugin.thrift.field.accessor.";
- public static final String FIELD_ACCESSOR_ASYNC_CALL_END_FLAG = FIELD_ACCESSOR_BASE + "AsyncCallEndFlagFieldAccessor";
- public static final String FIELD_ACCESSOR_ASYNC_CALL_REMOTE_ADDRESS = FIELD_ACCESSOR_BASE + "AsyncCallRemoteAddressFieldAccessor";
public static final String FIELD_ACCESSOR_ASYNC_MARKER_FLAG = FIELD_ACCESSOR_BASE + "AsyncMarkerFlagFieldAccessor";
- public static final String FIELD_ACCESSOR_ASYNC_NEXT_SPAN_ID = FIELD_ACCESSOR_BASE + "AsyncNextSpanIdFieldAccessor";
- public static final String FIELD_ACCESSOR_ASYNC_TRACE_ID = FIELD_ACCESSOR_BASE + "AsyncTraceIdFieldAccessor";
public static final String FIELD_ACCESSOR_SERVER_MARKER_FLAG = FIELD_ACCESSOR_BASE + "ServerMarkerFlagFieldAccessor";
public static final String FIELD_ACCESSOR_SOCKET_ADDRESS = FIELD_ACCESSOR_BASE + "SocketAddressFieldAccessor";
public static final String FIELD_ACCESSOR_SOCKET = FIELD_ACCESSOR_BASE + "SocketFieldAccessor";
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java
index 4e031a3ee026..47afb2694ec3 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java
@@ -19,6 +19,7 @@
import java.security.ProtectionDomain;
import java.util.List;
+import com.navercorp.pinpoint.bootstrap.async.AsyncTraceIdAccessor;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentClass;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentException;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentMethod;
@@ -146,12 +147,8 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
final InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+ target.addField(AsyncTraceIdAccessor.class.getName());
target.addField(ThriftConstants.FIELD_ACCESSOR_SOCKET_ADDRESS);
- target.addField(ThriftConstants.FIELD_ACCESSOR_ASYNC_MARKER_FLAG);
- target.addField(ThriftConstants.FIELD_ACCESSOR_ASYNC_TRACE_ID);
- target.addField(ThriftConstants.FIELD_ACCESSOR_ASYNC_NEXT_SPAN_ID);
- target.addField(ThriftConstants.FIELD_ACCESSOR_ASYNC_CALL_END_FLAG);
- target.addField(ThriftConstants.FIELD_ACCESSOR_ASYNC_CALL_REMOTE_ADDRESS);
target.addGetter(ThriftConstants.FIELD_GETTER_T_NON_BLOCKING_TRANSPORT, ThriftConstants.T_ASYNC_METHOD_CALL_FIELD_TRANSPORT);
// TAsyncMethodCall(TAsyncClient, TProtocolFactory, TNonblockingTransport, AsyncMethodCallback<T>, boolean)
@@ -163,48 +160,6 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
constructor.addInterceptor(interceptor);
}
- // TAsyncMethodCall.start(Selector)
- final InstrumentMethod start = target.getDeclaredMethod("start", "java.nio.channels.Selector");
- if (start != null) {
- String interceptor = "com.navercorp.pinpoint.plugin.thrift.interceptor.client.async.TAsyncMethodCallStartInterceptor";
- start.addInterceptor(interceptor);
- }
-
- // TAsyncMethodCall.doConnecting(SelectionKey)
- final InstrumentMethod doConnecting = target.getDeclaredMethod("doConnecting", "java.nio.channels.SelectionKey");
- if (doConnecting != null) {
- String interceptor = "com.navercorp.pinpoint.plugin.thrift.interceptor.client.async.TAsyncMethodCallInternalMethodInterceptor";
- doConnecting.addInterceptor(interceptor);
- }
-
- // TAsyncMethodCall.doWritingRequestSize()
- final InstrumentMethod doWritingRequestSize = target.getDeclaredMethod("doWritingRequestSize");
- if (doWritingRequestSize != null) {
- String interceptor = "com.navercorp.pinpoint.plugin.thrift.interceptor.client.async.TAsyncMethodCallInternalMethodInterceptor";
- doWritingRequestSize.addInterceptor(interceptor);
- }
-
- // TAsyncMethodCall.doWritingRequestBody(SelectionKey)
- final InstrumentMethod doWritingRequestBody = target.getDeclaredMethod("doWritingRequestBody", "java.nio.channels.SelectionKey");
- if (doWritingRequestBody != null) {
- String interceptor = "com.navercorp.pinpoint.plugin.thrift.interceptor.client.async.TAsyncMethodCallDoWritingRequestBodyInterceptor";
- doWritingRequestBody.addInterceptor(interceptor);
- }
-
- // TAsyncMethodCall.doReadingResponseSize()
- final InstrumentMethod doReadingResponseSize = target.getDeclaredMethod("doReadingResponseSize");
- if (doReadingResponseSize != null) {
- String interceptor = "com.navercorp.pinpoint.plugin.thrift.interceptor.client.async.TAsyncMethodCallInternalMethodInterceptor";
- doReadingResponseSize.addInterceptor(interceptor);
- }
-
- // TAsyncMethodCall.doReadingResponseBody(SelectionKey)
- final InstrumentMethod doReadingResponseBody = target.getDeclaredMethod("doReadingResponseBody", "java.nio.channels.SelectionKey");
- if (doReadingResponseBody != null) {
- String interceptor = "com.navercorp.pinpoint.plugin.thrift.interceptor.client.async.TAsyncMethodCallDoReadingResponseBodyInterceptor";
- doReadingResponseBody.addInterceptor(interceptor);
- }
-
// TAsyncMethodCall.cleanUpAndFireCallback(SelectionKey)
final InstrumentMethod cleanUpAndFireCallback = target.getDeclaredMethod("cleanUpAndFireCallback", "java.nio.channels.SelectionKey");
if (cleanUpAndFireCallback != null) {
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncClientManagerCallInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncClientManagerCallInterceptor.java
index 0a0458466919..b6d1637ede9e 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncClientManagerCallInterceptor.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncClientManagerCallInterceptor.java
@@ -20,6 +20,7 @@
import java.net.SocketAddress;
+import com.navercorp.pinpoint.bootstrap.async.AsyncTraceIdAccessor;
import com.navercorp.pinpoint.bootstrap.context.AsyncTraceId;
import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
@@ -37,10 +38,8 @@
import com.navercorp.pinpoint.plugin.thrift.ThriftConstants;
import com.navercorp.pinpoint.plugin.thrift.ThriftRequestProperty;
import com.navercorp.pinpoint.plugin.thrift.ThriftUtils;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncCallRemoteAddressFieldAccessor;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncNextSpanIdFieldAccessor;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncTraceIdFieldAccessor;
import com.navercorp.pinpoint.plugin.thrift.field.accessor.SocketAddressFieldAccessor;
+import org.apache.thrift.async.TAsyncMethodCall;
/**
* @author HyunGil Jeong
@@ -90,8 +89,6 @@ public void before(Object target, Object[] args) {
// inject async trace info to AsyncMethodCall object
final AsyncTraceId asyncTraceId = injectAsyncTraceId(asyncMethodCallObj, trace);
- recorder.recordServiceType(ThriftConstants.THRIFT_CLIENT_INTERNAL);
-
// retrieve connection information
String remoteAddress = getRemoteAddress(asyncMethodCallObj);
@@ -109,8 +106,14 @@ public void before(Object target, Object[] args) {
parentTraceInfo.setParentApplicationType(this.traceContext.getServerTypeCode());
parentTraceInfo.setAcceptorHost(remoteAddress);
- ((AsyncCallRemoteAddressFieldAccessor)asyncMethodCallObj)._$PINPOINT$_setAsyncCallRemoteAddress(remoteAddress);
- ((AsyncNextSpanIdFieldAccessor)asyncMethodCallObj)._$PINPOINT$_setAsyncNextSpanId(nextSpanId);
+
+ recorder.recordServiceType(ThriftConstants.THRIFT_CLIENT);
+ recorder.recordNextSpanId(nextSpanId);
+ recorder.recordDestinationId(remoteAddress);
+
+ String methodUri = ThriftUtils.getAsyncMethodCallName((TAsyncMethodCall<?>) asyncMethodCallObj);
+ String thriftUrl = remoteAddress + "/" + methodUri;
+ recorder.recordAttribute(ThriftConstants.THRIFT_URL, thriftUrl);
}
InterceptorScopeInvocation currentTransaction = this.scope.getCurrentInvocation();
currentTransaction.setAttachment(parentTraceInfo);
@@ -154,23 +157,9 @@ private boolean validate(final Object target, final Object[] args) {
return false;
}
- if (!(asyncMethodCallObj instanceof AsyncTraceIdFieldAccessor)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", AsyncTraceIdFieldAccessor.class.getName());
- }
- return false;
- }
-
- if (!(asyncMethodCallObj instanceof AsyncNextSpanIdFieldAccessor)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", AsyncNextSpanIdFieldAccessor.class.getName());
- }
- return false;
- }
-
- if (!(asyncMethodCallObj instanceof AsyncCallRemoteAddressFieldAccessor)) {
+ if (!(asyncMethodCallObj instanceof AsyncTraceIdAccessor)) {
if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", AsyncCallRemoteAddressFieldAccessor.class.getName());
+ logger.debug("Invalid target object. Need field accessor({}).", AsyncTraceIdAccessor.class.getName());
}
return false;
}
@@ -182,7 +171,7 @@ private AsyncTraceId injectAsyncTraceId(final Object asyncMethodCallObj, final T
final AsyncTraceId asyncTraceId = trace.getAsyncTraceId();
SpanEventRecorder recorder = trace.currentSpanEventRecorder();
recorder.recordNextAsyncId(asyncTraceId.getAsyncId());
- ((AsyncTraceIdFieldAccessor)asyncMethodCallObj)._$PINPOINT$_setAsyncTraceId(asyncTraceId);
+ ((AsyncTraceIdAccessor) asyncMethodCallObj)._$PINPOINT$_setAsyncTraceId(asyncTraceId);
if (isDebug) {
logger.debug("Set asyncTraceId metadata {}", asyncTraceId);
}
@@ -194,7 +183,7 @@ private String getRemoteAddress(Object asyncMethodCallObj) {
return ThriftConstants.UNKNOWN_ADDRESS;
}
SocketAddress socketAddress = ((SocketAddressFieldAccessor)asyncMethodCallObj)._$PINPOINT$_getSocketAddress();
- return ThriftUtils.getHostPort((SocketAddress)socketAddress);
+ return ThriftUtils.getHostPort(socketAddress);
}
}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallCleanUpAndFireCallbackInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallCleanUpAndFireCallbackInterceptor.java
index 4e02b6c62825..432ca2c38381 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallCleanUpAndFireCallbackInterceptor.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallCleanUpAndFireCallbackInterceptor.java
@@ -1,56 +1,47 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.plugin.thrift.interceptor.client.async;
-
-import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
-import com.navercorp.pinpoint.bootstrap.context.TraceContext;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncCallEndFlagFieldAccessor;
-
-/**
- * @author HyunGil Jeong
- */
-public class TAsyncMethodCallCleanUpAndFireCallbackInterceptor extends TAsyncMethodCallInternalMethodInterceptor {
-
- public TAsyncMethodCallCleanUpAndFireCallbackInterceptor(
- TraceContext traceContext,
- MethodDescriptor methodDescriptor) {
- super(traceContext, methodDescriptor);
- }
-
- @Override
- public void after(Object target, Object[] args, Object result, Throwable throwable) {
- super.after(target, args, result, throwable);
-
- // Set a flag to end async trace block if this method completed successfully
- if (throwable != null) {
- return;
- }
- ((AsyncCallEndFlagFieldAccessor)target)._$PINPOINT$_setAsyncCallEndFlag(true);
- }
-
- @Override
- protected boolean validate(Object target) {
- if (!(target instanceof AsyncCallEndFlagFieldAccessor)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", AsyncCallEndFlagFieldAccessor.class.getName());
- }
- return false;
- }
- return super.validate(target);
- }
-
-}
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.thrift.interceptor.client.async;
+
+import com.navercorp.pinpoint.bootstrap.context.AsyncTraceId;
+import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
+import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
+import com.navercorp.pinpoint.bootstrap.context.TraceContext;
+import com.navercorp.pinpoint.bootstrap.interceptor.SpanAsyncEventSimpleAroundInterceptor;
+import com.navercorp.pinpoint.plugin.thrift.ThriftConstants;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class TAsyncMethodCallCleanUpAndFireCallbackInterceptor extends SpanAsyncEventSimpleAroundInterceptor {
+
+ public TAsyncMethodCallCleanUpAndFireCallbackInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
+ super(traceContext, methodDescriptor);
+ }
+
+ @Override
+ protected void doInBeforeTrace(SpanEventRecorder recorder, AsyncTraceId asyncTraceId, Object target, Object[] args) {
+ // Do nothing
+ }
+
+ @Override
+ protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
+ recorder.recordServiceType(ThriftConstants.THRIFT_CLIENT_INTERNAL);
+ recorder.recordApi(methodDescriptor);
+ recorder.recordException(throwable);
+ }
+
+}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallDoReadingResponseBodyInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallDoReadingResponseBodyInterceptor.java
deleted file mode 100644
index db9a6810a235..000000000000
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallDoReadingResponseBodyInterceptor.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.plugin.thrift.interceptor.client.async;
-
-import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
-import com.navercorp.pinpoint.bootstrap.context.Trace;
-import com.navercorp.pinpoint.bootstrap.context.TraceContext;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncCallEndFlagFieldAccessor;
-
-/**
- * @author HyunGil Jeong
- */
-public class TAsyncMethodCallDoReadingResponseBodyInterceptor extends TAsyncMethodCallInternalMethodInterceptor {
-
- public TAsyncMethodCallDoReadingResponseBodyInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
- super(traceContext, methodDescriptor);
- }
-
- @Override
- public void after(Object target, Object[] args, Object result, Throwable throwable) {
- super.after(target, args, result, throwable);
-
- // End async trace block if TAsyncMethodCall.cleanUpAndFireCallback(...) call completed successfully
- // if there was an exception, TAsyncMethodCall.onError(...) will be called and the async trace block will be ended there
- if (throwable != null) {
- return;
- }
- boolean endAsyncBlock = ((AsyncCallEndFlagFieldAccessor)target)._$PINPOINT$_getAsyncCallEndFlag();
- if (endAsyncBlock) {
- final Trace trace = super.traceContext.currentTraceObject();
- // shouldn't be null
- if (trace == null) {
- return;
- }
-
- if (trace.isAsync() && trace.isRootStack()) {
- trace.close();
- super.traceContext.removeTraceObject();
- }
- }
- }
-
- @Override
- protected boolean validate(Object target) {
- if (!(target instanceof AsyncCallEndFlagFieldAccessor)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", AsyncCallEndFlagFieldAccessor.class.getName());
- }
- return false;
- }
- return super.validate(target);
- }
-
-}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallDoWritingRequestBodyInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallDoWritingRequestBodyInterceptor.java
deleted file mode 100644
index ac2bc37fcd71..000000000000
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallDoWritingRequestBodyInterceptor.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.plugin.thrift.interceptor.client.async;
-
-import com.navercorp.pinpoint.plugin.thrift.ThriftConstants;
-import org.apache.thrift.async.TAsyncMethodCall;
-
-import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
-import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
-import com.navercorp.pinpoint.bootstrap.context.Trace;
-import com.navercorp.pinpoint.bootstrap.context.TraceContext;
-import com.navercorp.pinpoint.common.trace.ServiceType;
-import com.navercorp.pinpoint.plugin.thrift.ThriftUtils;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncCallEndFlagFieldAccessor;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncCallRemoteAddressFieldAccessor;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncNextSpanIdFieldAccessor;
-
-/**
- * @author HyunGil Jeong
- */
-public class TAsyncMethodCallDoWritingRequestBodyInterceptor extends TAsyncMethodCallInternalMethodInterceptor {
-
- public TAsyncMethodCallDoWritingRequestBodyInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
- super(traceContext, methodDescriptor);
- }
-
- @Override
- protected void doInBeforeTrace(SpanEventRecorder recorder, Object target, Object[] args) {
- super.doInBeforeTrace(recorder, target, args);
-
- Long nextSpanId = ((AsyncNextSpanIdFieldAccessor)target)._$PINPOINT$_getAsyncNextSpanId();
- recorder.recordNextSpanId(nextSpanId);
-
- String remoteAddress = ((AsyncCallRemoteAddressFieldAccessor)target)._$PINPOINT$_getAsyncCallRemoteAddress();
- recorder.recordDestinationId(remoteAddress);
-
- String methodUri = ThriftUtils.getAsyncMethodCallName((TAsyncMethodCall<?>)target);
- String thriftUrl = remoteAddress + "/" + methodUri;
- recorder.recordAttribute(ThriftConstants.THRIFT_URL, thriftUrl);
- }
-
- @Override
- public void after(Object target, Object[] args, Object result, Throwable throwable) {
- super.after(target, args, result, throwable);
-
- // End async trace block if TAsyncMethodCall.cleanUpAndFireCallback(...) call completed successfully
- // if there was an exception, TAsyncMethodCall.onError(...) will be called and the async trace block will be ended there
- if (throwable != null) {
- return;
- }
- boolean endAsyncBlock = ((AsyncCallEndFlagFieldAccessor)target)._$PINPOINT$_getAsyncCallEndFlag();
- if (endAsyncBlock) {
- final Trace trace = super.traceContext.currentTraceObject();
- // shouldn't be null
- if (trace == null) {
- return;
- }
-
- if (trace.isAsync() && trace.isRootStack()) {
- trace.close();
- super.traceContext.removeTraceObject();
- }
- }
- }
-
- @Override
- protected boolean validate(Object target) {
- if (!(target instanceof AsyncNextSpanIdFieldAccessor)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", AsyncNextSpanIdFieldAccessor.class.getName());
- }
- return false;
- }
- if (!(target instanceof AsyncCallRemoteAddressFieldAccessor)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", AsyncCallRemoteAddressFieldAccessor.class.getName());
- }
- return false;
- }
- if (!(target instanceof AsyncCallEndFlagFieldAccessor)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", AsyncCallEndFlagFieldAccessor.class.getName());
- }
- return false;
- }
- return super.validate(target);
- }
-
- @Override
- protected ServiceType getServiceType() {
- return ThriftConstants.THRIFT_CLIENT;
- }
-}
\ No newline at end of file
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallInternalMethodInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallInternalMethodInterceptor.java
deleted file mode 100644
index 34b5a189a3a6..000000000000
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallInternalMethodInterceptor.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.plugin.thrift.interceptor.client.async;
-
-import org.apache.thrift.async.TAsyncMethodCall;
-
-import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
-import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
-import com.navercorp.pinpoint.bootstrap.context.Trace;
-import com.navercorp.pinpoint.bootstrap.context.TraceContext;
-import com.navercorp.pinpoint.bootstrap.interceptor.AroundInterceptor;
-import com.navercorp.pinpoint.bootstrap.logging.PLogger;
-import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
-import com.navercorp.pinpoint.common.trace.ServiceType;
-import com.navercorp.pinpoint.plugin.thrift.ThriftConstants;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncMarkerFlagFieldAccessor;
-
-/**
- * @author HyunGil Jeong
- */
-public class TAsyncMethodCallInternalMethodInterceptor implements AroundInterceptor {
- protected final PLogger logger = PLoggerFactory.getLogger(getClass());
- protected final boolean isDebug = logger.isDebugEnabled();
-
- protected final TraceContext traceContext;
- protected final MethodDescriptor methodDescriptor;
-
- public TAsyncMethodCallInternalMethodInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
- this.traceContext = traceContext;
- this.methodDescriptor = methodDescriptor;
- }
-
- @Override
- public void before(Object target, Object[] args) {
- if (isDebug) {
- logger.beforeInterceptor(target, args);
- }
-
- if (!validate(target)) {
- return;
- }
-
- final Trace trace = traceContext.currentTraceObject();
- if (trace == null) {
- return;
- }
- try {
- trace.traceBlockBegin();
- SpanEventRecorder recorder = trace.currentSpanEventRecorder();
- recorder.recordServiceType(getServiceType());
- doInBeforeTrace(recorder, target, args);
- } catch (Throwable th) {
- if (logger.isWarnEnabled()) {
- logger.warn("BEFORE. Caused:{}", th.getMessage(), th);
- }
- }
- }
-
- protected void doInBeforeTrace(SpanEventRecorder recorder, final Object target, final Object[] args) {
- }
-
- @Override
- public void after(Object target, Object[] args, Object result, Throwable throwable) {
- if (isDebug) {
- logger.afterInterceptor(target, args, result, throwable);
- }
-
- if (!validate0(target)) {
- return;
- }
-
- final Trace trace = traceContext.currentTraceObject();
- if (trace == null) {
- return;
- }
-
- try {
- SpanEventRecorder recorder = trace.currentSpanEventRecorder();
- recorder.recordApi(this.methodDescriptor);
- recorder.recordException(throwable);
- doInAfterTrace(recorder, target, args, result, throwable);
- } catch (Throwable th) {
- if (logger.isWarnEnabled()) {
- logger.warn("AFTER error. Caused:{}", th.getMessage(), th);
- }
- } finally {
- trace.traceBlockEnd();
- }
- }
-
- protected void doInAfterTrace(SpanEventRecorder recorder, final Object target, final Object[] args, final Object result, Throwable throwable) {
- }
-
- private boolean validate0(Object target) {
- if (!(target instanceof TAsyncMethodCall)) {
- return false;
- }
- if (!(target instanceof AsyncMarkerFlagFieldAccessor)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", AsyncMarkerFlagFieldAccessor.class.getName());
- }
- return false;
- }
- return validate(target);
- }
-
- protected boolean validate(Object target) {
- return true;
- }
-
- protected ServiceType getServiceType() {
- return ThriftConstants.THRIFT_CLIENT_INTERNAL;
- }
-
-}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallOnErrorInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallOnErrorInterceptor.java
index 655dc72ff4a7..d1d1a9185149 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallOnErrorInterceptor.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallOnErrorInterceptor.java
@@ -1,58 +1,51 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.plugin.thrift.interceptor.client.async;
-
-import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
-import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
-import com.navercorp.pinpoint.bootstrap.context.Trace;
-import com.navercorp.pinpoint.bootstrap.context.TraceContext;
-import com.navercorp.pinpoint.common.trace.AnnotationKey;
-
-/**
- * @author HyunGil Jeong
- */
-public class TAsyncMethodCallOnErrorInterceptor extends TAsyncMethodCallInternalMethodInterceptor {
-
- public TAsyncMethodCallOnErrorInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
- super(traceContext, methodDescriptor);
- }
-
- @Override
- public void after(Object target, Object[] args, Object result, Throwable throwable) {
- super.after(target, args, result, throwable);
-
- // End async trace block
- final Trace trace = super.traceContext.currentTraceObject();
- // shouldn't be null
- if (trace == null) {
- return;
- }
-
- if (trace.isAsync() && trace.isRootStack()) {
- trace.close();
- super.traceContext.removeTraceObject();
- }
- }
-
- @Override
- public void doInBeforeTrace(SpanEventRecorder recorder, final Object target, final Object[] args) {
- if (args.length == 1) {
- recorder.recordAttribute(AnnotationKey.ARGS0, args[0]);
- }
- }
-
-}
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.thrift.interceptor.client.async;
+
+import com.navercorp.pinpoint.bootstrap.context.AsyncTraceId;
+import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
+import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
+import com.navercorp.pinpoint.bootstrap.context.TraceContext;
+import com.navercorp.pinpoint.bootstrap.interceptor.SpanAsyncEventSimpleAroundInterceptor;
+import com.navercorp.pinpoint.common.trace.AnnotationKey;
+import com.navercorp.pinpoint.plugin.thrift.ThriftConstants;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class TAsyncMethodCallOnErrorInterceptor extends SpanAsyncEventSimpleAroundInterceptor {
+
+ public TAsyncMethodCallOnErrorInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
+ super(traceContext, methodDescriptor);
+ }
+
+ @Override
+ protected void doInBeforeTrace(SpanEventRecorder recorder, AsyncTraceId asyncTraceId, Object target, Object[] args) {
+ // Do nothing
+ }
+
+ @Override
+ protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
+ if (args != null && args.length == 1) {
+ recorder.recordAttribute(AnnotationKey.ARGS0, args[0]);
+ }
+ recorder.recordServiceType(ThriftConstants.THRIFT_CLIENT_INTERNAL);
+ recorder.recordApi(methodDescriptor);
+ recorder.recordException(throwable);
+ }
+
+}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallStartInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallStartInterceptor.java
deleted file mode 100644
index 1405f5e4764a..000000000000
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/async/TAsyncMethodCallStartInterceptor.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2015 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.plugin.thrift.interceptor.client.async;
-
-import com.navercorp.pinpoint.bootstrap.context.AsyncTraceId;
-import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
-import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
-import com.navercorp.pinpoint.bootstrap.context.Trace;
-import com.navercorp.pinpoint.bootstrap.context.TraceContext;
-import com.navercorp.pinpoint.common.trace.ServiceType;
-import com.navercorp.pinpoint.plugin.thrift.descriptor.ThriftAsyncClientMethodDescriptor;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncMarkerFlagFieldAccessor;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncTraceIdFieldAccessor;
-
-/**
- * @author HyunGil Jeong
- */
-public class TAsyncMethodCallStartInterceptor extends TAsyncMethodCallInternalMethodInterceptor {
-
- private final ThriftAsyncClientMethodDescriptor thriftAsyncClientMethodDescriptor = new ThriftAsyncClientMethodDescriptor();
-
- public TAsyncMethodCallStartInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
- super(traceContext, methodDescriptor);
- this.traceContext.cacheApi(this.thriftAsyncClientMethodDescriptor);
- }
-
- @Override
- public void before(Object target, Object[] args) {
- if (!validate0(target)) {
- return;
- }
-
- // Retrieve asyncTraceId
- final AsyncTraceId asyncTraceId = ((AsyncTraceIdFieldAccessor)target)._$PINPOINT$_getAsyncTraceId();
- Trace trace = traceContext.currentTraceObject();
- // Check if the method was invoked by the same thread or not, probabaly safe not to check but just in case.
- if (trace == null) {
- // another thread has invoked the method
- trace = traceContext.continueAsyncTraceObject(asyncTraceId, asyncTraceId.getAsyncId(), asyncTraceId.getSpanStartTime());
- if (trace == null) {
- logger.warn("Failed to continue async trace. 'result is null'");
- return;
- }
- SpanEventRecorder recorder = trace.currentSpanEventRecorder();
- recorder.recordServiceType(ServiceType.ASYNC);
- recorder.recordApi(this.thriftAsyncClientMethodDescriptor);
- ((AsyncMarkerFlagFieldAccessor)target)._$PINPOINT$_setAsyncMarkerFlag(Boolean.TRUE);
- }
- super.before(target, args);
- }
-
- private boolean validate0(Object target) {
- if (!(target instanceof AsyncTraceIdFieldAccessor)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", AsyncTraceIdFieldAccessor.class.getName());
- }
- return false;
- }
- if (!(target instanceof AsyncMarkerFlagFieldAccessor)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", AsyncMarkerFlagFieldAccessor.class.getName());
- }
- return false;
- }
- return true;
- }
-
-}
| diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
index 56a3fd9442b0..6eb3bb1c20aa 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
@@ -22,7 +22,6 @@
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
import java.util.concurrent.CountDownLatch;
import org.apache.thrift.TBase;
@@ -85,42 +84,8 @@ public String echo(String message) throws TException {
public void verifyTraces(PluginTestVerifier verifier, String expectedMessage) throws Exception {
final InetSocketAddress actualServerAddress = this.environment.getServerAddress();
// ********** Asynchronous Traces
- // SpanEvent - Thrift Asynchronous Client Invocation
- ExpectedTrace asyncClientInvocationTrace = event("ASYNC", "Thrift Asynchronous Client Invocation");
-
- // SpanEvent - TAsyncMethodCall.start
- Method start = TAsyncMethodCall.class.getDeclaredMethod("start", Selector.class);
- ExpectedTrace startTrace = event("THRIFT_CLIENT_INTERNAL", start);
-
- // SpanEvent - TAsyncMethodCall.doConnecting
- Method doConnecting = TAsyncMethodCall.class.getDeclaredMethod("doConnecting", SelectionKey.class);
- ExpectedTrace doConnectingTrace = event("THRIFT_CLIENT_INTERNAL", doConnecting);
-
- // SpanEvent - TAsyncMethodCall.doWritingRequestSize
- Method doWritingRequestSize = TAsyncMethodCall.class.getDeclaredMethod("doWritingRequestSize");
- ExpectedTrace doWritingRequestSizeTrace = event("THRIFT_CLIENT_INTERNAL", doWritingRequestSize);
-
- // SpanEvent - TAsyncMethodCall.doWritingRequestBody
- Method doWritingRequestBody = TAsyncMethodCall.class.getDeclaredMethod("doWritingRequestBody",
- SelectionKey.class);
- ExpectedAnnotation thriftUrl = Expectations.annotation("thrift.url", actualServerAddress.getHostName() + ":"
- + actualServerAddress.getPort() + "/com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo_call");
- ExpectedTrace doWritingRequestBodyTrace = event("THRIFT_CLIENT", // ServiceType
- doWritingRequestBody, // Method
- null, // rpc
- null, // endPoint
- actualServerAddress.getHostName() + ":" + actualServerAddress.getPort(), // destinationId
- thriftUrl // Annotation("thrift.url")
- );
-
- // SpanEvent - TAsyncMethodCall.doReadingResponseSize
- Method doReadingResponseSize = TAsyncMethodCall.class.getDeclaredMethod("doReadingResponseSize");
- ExpectedTrace doReadingResponseSizeTrace = event("THRIFT_CLIENT_INTERNAL", doReadingResponseSize);
-
- // SpanEvent - TAsyncMethodCall.doReadingResponseBody
- Method doReadingResponseBody = TAsyncMethodCall.class.getDeclaredMethod("doReadingResponseBody",
- SelectionKey.class);
- ExpectedTrace doReadingResponseBodyTrace = event("THRIFT_CLIENT_INTERNAL", doReadingResponseBody);
+ // SpanEvent - Asynchronous Invocation
+ ExpectedTrace asyncInvocationTrace = event("ASYNC", "Asynchronous Invocation");
// SpanEvent - TAsyncMethodCall.cleanUpAndFireCallback
Method cleanUpAndFireCallback = TAsyncMethodCall.class.getDeclaredMethod("cleanUpAndFireCallback",
@@ -139,9 +104,16 @@ public void verifyTraces(PluginTestVerifier verifier, String expectedMessage) th
// ********** Root trace for Asynchronous traces
// SpanEvent - TAsyncClientManager.call
Method call = TAsyncClientManager.class.getDeclaredMethod("call", TAsyncMethodCall.class);
- verifier.verifyTrace(async(Expectations.event("THRIFT_CLIENT_INTERNAL", call), asyncClientInvocationTrace,
- startTrace, doConnectingTrace, doWritingRequestSizeTrace, doWritingRequestBodyTrace,
- doReadingResponseSizeTrace, doReadingResponseBodyTrace, cleanUpAndFireCallbackTrace, receiveBaseTrace));
+ ExpectedAnnotation thriftUrl = Expectations.annotation("thrift.url", actualServerAddress.getHostName() + ":"
+ + actualServerAddress.getPort() + "/com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo_call");
+ ExpectedTrace callTrace = event("THRIFT_CLIENT", // ServiceType
+ call, // Method
+ null, // rpc
+ null, // endPoint
+ actualServerAddress.getHostName() + ":" + actualServerAddress.getPort(), // destinationId
+ thriftUrl // Annotation("thrift.url")
+ );
+ verifier.verifyTrace(async(callTrace, asyncInvocationTrace, cleanUpAndFireCallbackTrace, receiveBaseTrace));
}
private static class AsyncEchoResultHolder {
| train | train | "2016-03-09T08:00:59" | "2015-12-04T10:17:09Z" | Xylus | test |
pinpoint-apm/pinpoint/1606_1608 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1606 | pinpoint-apm/pinpoint/1608 | [
"keyword_pr_to_issue"
] | 3552bc753142684f999a2687c33d013d02b18f95 | 777464fd916b89f5da94229edfea90ad3bf8ed7c | [] | [] | "2016-03-16T06:15:31Z" | [
"enhancement"
] | Add prefix encoding to hbase schema script | Apply [prefix encoding](https://hbase.apache.org/book.html#compression) to hbase tables. This should save quite a bit of space as most of our row keys tend to repeat a lot (ie. agent id, agent start time).
| [
"hbase/scripts/hbase-create-snappy.hbase",
"hbase/scripts/hbase-create.hbase"
] | [
"hbase/scripts/hbase-create-snappy.hbase",
"hbase/scripts/hbase-create.hbase"
] | [] | diff --git a/hbase/scripts/hbase-create-snappy.hbase b/hbase/scripts/hbase-create-snappy.hbase
index 5ec49aa776ae..ecabd3207af4 100644
--- a/hbase/scripts/hbase-create-snappy.hbase
+++ b/hbase/scripts/hbase-create-snappy.hbase
@@ -1,22 +1,22 @@
-create 'AgentInfo', { NAME => 'Info', TTL => 31536000, COMPRESSION => 'SNAPPY' }
-create 'AgentStat', { NAME => 'S', TTL => 5184000, COMPRESSION => 'SNAPPY' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApplicationIndex', { NAME => 'Agents', TTL => 31536000, COMPRESSION => 'SNAPPY' }
-create 'AgentLifeCycle', { NAME => 'S', TTL => 5184000, COMPRESSION => 'SNAPPY' }
-create 'AgentEvent', { NAME => 'E', TTL => 5184000, COMPRESSION => 'SNAPPY' }
+create 'AgentInfo', { NAME => 'Info', TTL => 31536000, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }
+create 'AgentStat', { NAME => 'S', TTL => 5184000, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApplicationIndex', { NAME => 'Agents', TTL => 31536000, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }
+create 'AgentLifeCycle', { NAME => 'S', TTL => 5184000, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }
+create 'AgentEvent', { NAME => 'E', TTL => 5184000, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }
-create 'StringMetaData', { NAME => 'Str', COMPRESSION => 'SNAPPY', TTL => 15552000 }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApiMetaData', { NAME => 'Api', COMPRESSION => 'SNAPPY', TTL => 31536000 }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'StringMetaData', { NAME => 'Str', COMPRESSION => 'SNAPPY', TTL => 15552000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApiMetaData', { NAME => 'Api', COMPRESSION => 'SNAPPY', TTL => 31536000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'SqlMetaData_Ver2', { NAME => 'Sql', COMPRESSION => 'SNAPPY', TTL => 15552000 }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'SqlMetaData_Ver2', { NAME => 'Sql', COMPRESSION => 'SNAPPY', TTL => 15552000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'Traces', { NAME => 'S', TTL => 5184000, COMPRESSION => 'SNAPPY' }, { NAME => 'A', TTL => 5184000, COMPRESSION => 'SNAPPY' }, { NAME => 'T', TTL => 5184000, COMPRESSION => 'SNAPPY' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x17\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x19\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x21\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x22\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x23\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x25\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x26\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x27\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x28\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x29\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x30\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x31\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x33\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x34\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x35\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x36\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x37\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x38\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x39\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApplicationTraceIndex', { NAME => 'I', TTL => 5184000, COMPRESSION => 'SNAPPY' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'Traces', { NAME => 'S', TTL => 5184000, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }, { NAME => 'A', TTL => 5184000, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }, { NAME => 'T', TTL => 5184000, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x17\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x19\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x21\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x22\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x23\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x25\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x26\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x27\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x28\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x29\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x30\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x31\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x33\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x34\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x35\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x36\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x37\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x38\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x39\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApplicationTraceIndex', { NAME => 'I', TTL => 5184000, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApplicationMapStatisticsCaller_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1, COMPRESSION => 'SNAPPY' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApplicationMapStatisticsCallee_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1, COMPRESSION => 'SNAPPY' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApplicationMapStatisticsSelf_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1, COMPRESSION => 'SNAPPY' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApplicationMapStatisticsCaller_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApplicationMapStatisticsCallee_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApplicationMapStatisticsSelf_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'HostApplicationMap_Ver2', { NAME => 'M', TTL => 5184000, VERSION => 1, COMPRESSION => 'SNAPPY' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'HostApplicationMap_Ver2', { NAME => 'M', TTL => 5184000, VERSION => 1, COMPRESSION => 'SNAPPY', DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
list
diff --git a/hbase/scripts/hbase-create.hbase b/hbase/scripts/hbase-create.hbase
index 954f84546733..93611602bf79 100644
--- a/hbase/scripts/hbase-create.hbase
+++ b/hbase/scripts/hbase-create.hbase
@@ -1,22 +1,22 @@
-create 'AgentInfo', { NAME => 'Info', TTL => 31536000 }
-create 'AgentStat', { NAME => 'S', TTL => 5184000 }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApplicationIndex', { NAME => 'Agents', TTL => 31536000 }
-create 'AgentLifeCycle', { NAME => 'S', TTL => 5184000 }
-create 'AgentEvent', { NAME => 'E', TTL => 5184000 }
+create 'AgentInfo', { NAME => 'Info', TTL => 31536000, DATA_BLOCK_ENCODING => 'PREFIX' }
+create 'AgentStat', { NAME => 'S', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApplicationIndex', { NAME => 'Agents', TTL => 31536000, DATA_BLOCK_ENCODING => 'PREFIX' }
+create 'AgentLifeCycle', { NAME => 'S', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }
+create 'AgentEvent', { NAME => 'E', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }
-create 'StringMetaData', { NAME => 'Str', TTL => 15552000 }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApiMetaData', { NAME => 'Api', TTL => 31536000 }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'StringMetaData', { NAME => 'Str', TTL => 15552000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApiMetaData', { NAME => 'Api', TTL => 31536000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'SqlMetaData_Ver2', { NAME => 'Sql', TTL => 15552000 }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'SqlMetaData_Ver2', { NAME => 'Sql', TTL => 15552000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'Traces', { NAME => 'S', TTL => 5184000 }, { NAME => 'A', TTL => 5184000 }, { NAME => 'T', TTL => 5184000 }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x17\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x19\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x21\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x22\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x23\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x25\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x26\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x27\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x28\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x29\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x30\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x31\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x33\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x34\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x35\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x36\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x37\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x38\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x39\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApplicationTraceIndex', { NAME => 'I', TTL => 5184000 }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'Traces', { NAME => 'S', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }, { NAME => 'A', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }, { NAME => 'T', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x17\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x19\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x21\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x22\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x23\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x25\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x26\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x27\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x28\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x29\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x2f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x30\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x31\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x33\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x34\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x35\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x36\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x37\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x38\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x39\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x3f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApplicationTraceIndex', { NAME => 'I', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApplicationMapStatisticsCaller_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1 }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApplicationMapStatisticsCallee_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1 }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'ApplicationMapStatisticsSelf_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1 }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApplicationMapStatisticsCaller_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApplicationMapStatisticsCallee_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'ApplicationMapStatisticsSelf_Ver2', { NAME => 'C', TTL => 5184000, VERSION => 1, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
-create 'HostApplicationMap_Ver2', { NAME => 'M', TTL => 5184000, VERSION => 1 }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
+create 'HostApplicationMap_Ver2', { NAME => 'M', TTL => 5184000, VERSION => 1, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]}
list
| null | train | train | "2016-03-15T09:57:39" | "2016-03-16T05:42:28Z" | Xylus | test |
pinpoint-apm/pinpoint/1621_1642 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1621 | pinpoint-apm/pinpoint/1642 | [
"keyword_pr_to_issue"
] | 61ae9701f5d40578764e2349645e16dc086ee558 | 492b52a0de6aac86fb865927d79ff806c09a10b1 | [
"+1, nice feature. as many projects prefer spring boot for integration.\n"
] | [] | "2016-03-22T07:02:43Z" | [
"enhancement"
] | Collect service information for Spring Boot applications | Service information (loaded libraries) are not collected for Spring Boot applications except for cases where they are packaged as _war_ files and are loaded on a container (such as Tomcat).
A lot of Spring Boot applications are run as an executable jar (or war), so it would be useful to collect these information in these cases as well.
| [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java",
"plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootConstants.java",
"plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootPlugin.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/ConnectorInitializeInterceptor.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/WebappLoaderStartInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java",
"plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootConstants.java",
"plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootPlugin.java",
"plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/interceptor/LauncherLaunchInterceptor.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/ConnectorInitializeInterceptor.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/WebappLoaderStartInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolderTest.java"
] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java
index 9dd936122cbd..ced882dfec78 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java
@@ -33,7 +33,7 @@ public interface ServerMetaDataHolder {
void removeListener(ServerMetaDataListener listener);
- void publishServerMetaData();
+ void notifyListeners();
interface ServerMetaDataListener {
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java
index ac9c8b4a3410..71343f464083 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java
@@ -90,8 +90,9 @@ private String getMainClassName(SimpleProperty property) {
logger.warn("Error retrieving main class from [{}]", property.getClass().getName());
return NOT_FOUND;
} else {
+ JarFile executableArchive = null;
try {
- JarFile executableArchive = new JarFile(javaCommand);
+ executableArchive = new JarFile(javaCommand);
return extractMainClassFromArchive(executableArchive);
} catch (IOException e) {
// If it's not a valid java archive, VM shouldn't start in the first place.
@@ -101,6 +102,14 @@ private String getMainClassName(SimpleProperty property) {
// fail-safe, application shouldn't not start because of this
logger.warn("Error retrieving main class from java command : [{}]", javaCommand, e);
return NOT_FOUND;
+ } finally {
+ if (executableArchive != null) {
+ try {
+ executableArchive.close();
+ } catch (IOException e) {
+ logger.warn("Error closing jarFile : [{}]", executableArchive.getName(), e);
+ }
+ }
}
}
}
diff --git a/plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootConstants.java b/plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootConstants.java
index 89da3cd0205c..83c66de9ee4c 100644
--- a/plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootConstants.java
+++ b/plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootConstants.java
@@ -32,4 +32,6 @@ private SpringBootConstants() {
public static final ServiceType SERVICE_TYPE = ServiceTypeFactory.of(1210, NAME, RECORD_STATISTICS);
public static final String BOOTSTRAP_MAIN_PREFIX = "org.springframework.boot.loader.";
+
+ public static final String ROOT_CONTEXT_KEY = "Spring Boot";
}
diff --git a/plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootPlugin.java b/plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootPlugin.java
index 852a369aced6..d4c109edf520 100644
--- a/plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootPlugin.java
+++ b/plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/SpringBootPlugin.java
@@ -16,17 +16,54 @@
package com.navercorp.pinpoint.plugin.spring.boot;
+import com.navercorp.pinpoint.bootstrap.instrument.InstrumentClass;
+import com.navercorp.pinpoint.bootstrap.instrument.InstrumentException;
+import com.navercorp.pinpoint.bootstrap.instrument.InstrumentMethod;
+import com.navercorp.pinpoint.bootstrap.instrument.Instrumentor;
+import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformCallback;
+import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplate;
+import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplateAware;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPlugin;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPluginSetupContext;
+import java.security.ProtectionDomain;
+
/**
* @author HyunGil Jeong
*/
-public class SpringBootPlugin implements ProfilerPlugin {
+public class SpringBootPlugin implements ProfilerPlugin, TransformTemplateAware {
+
+ private TransformTemplate transformTemplate;
@Override
public void setup(ProfilerPluginSetupContext context) {
context.addApplicationTypeDetector(new SpringBootDetector());
+
+ addLauncherEditor();
+ }
+
+ @Override
+ public void setTransformTemplate(TransformTemplate transformTemplate) {
+ this.transformTemplate = transformTemplate;
}
+ private void addLauncherEditor() {
+ transformTemplate.transform("org.springframework.boot.loader.Launcher", new TransformCallback() {
+
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader, String className,
+ Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
+ byte[] classfileBuffer) throws InstrumentException {
+
+ InstrumentClass target = instrumentor.getInstrumentClass(classLoader, className, classfileBuffer);
+ InstrumentMethod method = target.getDeclaredMethod("launch", "java.lang.String[]", "java.lang.String", "java.lang.ClassLoader");
+ if (method != null) {
+ method.addInterceptor("com.navercorp.pinpoint.plugin.spring.boot.interceptor.LauncherLaunchInterceptor");
+ }
+
+ return target.toBytecode();
+ }
+
+ });
+ }
}
diff --git a/plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/interceptor/LauncherLaunchInterceptor.java b/plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/interceptor/LauncherLaunchInterceptor.java
new file mode 100644
index 000000000000..852d7637f379
--- /dev/null
+++ b/plugins/spring-boot/src/main/java/com/navercorp/pinpoint/plugin/spring/boot/interceptor/LauncherLaunchInterceptor.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.spring.boot.interceptor;
+
+import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder;
+import com.navercorp.pinpoint.bootstrap.context.TraceContext;
+import com.navercorp.pinpoint.bootstrap.interceptor.AroundInterceptor;
+import com.navercorp.pinpoint.bootstrap.logging.PLogger;
+import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
+import com.navercorp.pinpoint.plugin.spring.boot.SpringBootConstants;
+
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class LauncherLaunchInterceptor implements AroundInterceptor {
+
+ private final static String PATH_SEPARATOR = "/";
+ private final static String JAR_SEPARATOR = "!";
+
+ private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
+ private final boolean isDebug = logger.isDebugEnabled();
+
+ private final TraceContext traceContext;
+
+ public LauncherLaunchInterceptor(TraceContext traceContext) {
+ this.traceContext = traceContext;
+ }
+
+ @Override
+ public void before(Object target, Object[] args) {
+ if (isDebug) {
+ logger.beforeInterceptor(target, args);
+ }
+ if (!validate(target, args)) {
+ return;
+ }
+ String serviceName = createServiceName(target);
+ URLClassLoader classLoader = (URLClassLoader) args[2];
+ URL[] urls = classLoader.getURLs();
+ List<String> loadedJarNames = new ArrayList<String>(extractLibJarNamesFromURLs(urls));
+ ServerMetaDataHolder holder = this.traceContext.getServerMetaDataHolder();
+ holder.addServiceInfo(serviceName, loadedJarNames);
+ holder.notifyListeners();
+ }
+
+ @Override
+ public void after(Object target, Object[] args, Object result, Throwable throwable) {
+ // Do nothing
+ }
+
+ private String createServiceName(Object target) {
+ StringBuilder sb = new StringBuilder(SpringBootConstants.ROOT_CONTEXT_KEY);
+ sb.append(" (").append(target.getClass().getSimpleName()).append(")");
+ return sb.toString();
+ }
+
+ private boolean validate(Object target, Object[] args) {
+ if (target == null || args == null) {
+ return false;
+ }
+ if (args.length < 3) {
+ return false;
+ }
+ if (!(args[2] instanceof URLClassLoader)) {
+ return false;
+ }
+ return true;
+ }
+
+ private Set<String> extractLibJarNamesFromURLs(URL[] urls) {
+ if (urls == null) {
+ return Collections.emptySet();
+ }
+ Set<String> libJarNames = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
+ for (URL url : urls) {
+ try {
+ String libJarName = extractLibJarName(url);
+ if (libJarName.length() > 0) {
+ libJarNames.add(libJarName);
+ }
+ } catch (Exception e) {
+ // safety net
+ logger.warn("Error extracting library name", e);
+ }
+ }
+ return libJarNames;
+ }
+
+ private String extractLibJarName(URL url) {
+ String protocol = url.getProtocol();
+ String path = url.getPath().replaceAll("\\\\", PATH_SEPARATOR);
+ if (protocol.equals("file")) {
+ return extractNameFromFile(path);
+ } else if (protocol.equals("jar")) {
+ return extractNameFromJar(path);
+ } else {
+ return "";
+ }
+ }
+
+ private String extractNameFromFile(String fileUri) {
+ int lastIndexOfSeparator = fileUri.lastIndexOf(PATH_SEPARATOR);
+ if (lastIndexOfSeparator < 0) {
+ return fileUri;
+ } else {
+ return fileUri.substring(lastIndexOfSeparator + 1);
+ }
+ }
+
+ private String extractNameFromJar(String jarUri) {
+ String uri = jarUri.substring(0, jarUri.lastIndexOf(JAR_SEPARATOR));
+ int rootJarEndIndex = uri.indexOf(JAR_SEPARATOR);
+ if (rootJarEndIndex < 0) {
+ return extractNameFromFile(uri);
+ }
+ String rootJarFileUri = extractNameFromFile(uri.substring(0, rootJarEndIndex));
+ StringBuilder sb = new StringBuilder(rootJarFileUri);
+ sb.append(uri.substring(rootJarEndIndex));
+ return sb.toString();
+ }
+
+}
diff --git a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java
index 0917e1c0d732..81766e7fe549 100644
--- a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java
+++ b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java
@@ -177,16 +177,17 @@ private void addWebappLoaderEditor() {
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
InstrumentClass target = instrumentor.getInstrumentClass(classLoader, className, classfileBuffer);
- // Tomcat 6 - org.apache.catalina.loader.WebappLoader.start()
- InstrumentMethod startEditor = target.getDeclaredMethod("start");
- if (startEditor != null) {
- startEditor.addInterceptor("com.navercorp.pinpoint.plugin.tomcat.interceptor.WebappLoaderStartInterceptor");
+ InstrumentMethod startMethod = null;
+ if (target.hasDeclaredMethod("start")) {
+ // Tomcat 6 - org.apache.catalina.loader.WebappLoader.start()
+ startMethod = target.getDeclaredMethod("start");
+ } else if (target.hasDeclaredMethod("startInternal")) {
+ // Tomcat 7, 8 - org.apache.catalina.loader.WebappLoader.startInternal()
+ startMethod = target.getDeclaredMethod("startInternal");
}
- // Tomcat 7, 8 - org.apache.catalina.loader.WebappLoader.startInternal()
- InstrumentMethod startInternalEditor = target.getDeclaredMethod("startInternal");
- if (startInternalEditor != null) {
- startInternalEditor.addInterceptor("com.navercorp.pinpoint.plugin.tomcat.interceptor.WebappLoaderStartInterceptor");
+ if (startMethod != null) {
+ startMethod.addInterceptor("com.navercorp.pinpoint.plugin.tomcat.interceptor.WebappLoaderStartInterceptor");
}
return target.toBytecode();
diff --git a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/ConnectorInitializeInterceptor.java b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/ConnectorInitializeInterceptor.java
index 9e961e25efd9..26e90855be09 100644
--- a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/ConnectorInitializeInterceptor.java
+++ b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/ConnectorInitializeInterceptor.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.plugin.tomcat.interceptor;
+import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder;
import org.apache.catalina.connector.Connector;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
@@ -49,7 +50,9 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
}
if (target instanceof Connector) {
final Connector connector = (Connector) target;
- this.traceContext.getServerMetaDataHolder().addConnector(connector.getProtocol(), connector.getPort());
+ ServerMetaDataHolder holder = this.traceContext.getServerMetaDataHolder();
+ holder.addConnector(connector.getProtocol(), connector.getPort());
+ holder.notifyListeners();
}
}
}
diff --git a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java
index ecc3bfbb6fc2..b0cb2dab25db 100644
--- a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java
+++ b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.plugin.tomcat.interceptor;
+import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder;
import org.apache.catalina.util.ServerInfo;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
@@ -50,8 +51,8 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
}
String serverInfo = ServerInfo.getServerInfo();
- this.traceContext.getServerMetaDataHolder().setServerName(serverInfo);
- // Service started. Publish server meta data.
- this.traceContext.getServerMetaDataHolder().publishServerMetaData();
+ ServerMetaDataHolder holder = this.traceContext.getServerMetaDataHolder();
+ holder.setServerName(serverInfo);
+ holder.notifyListeners();
}
}
diff --git a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/WebappLoaderStartInterceptor.java b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/WebappLoaderStartInterceptor.java
index a980fefba7e6..0b663c228d6b 100644
--- a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/WebappLoaderStartInterceptor.java
+++ b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/WebappLoaderStartInterceptor.java
@@ -18,12 +18,15 @@
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+import java.net.URI;
+import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
@@ -139,19 +142,24 @@ private List<String> extractLibJarNamesFromURLs(URL[] urls) {
}
List<String> libJarNames = new ArrayList<String>(urls.length);
for (URL url : urls) {
- String libJarName = extractLibJarName(url);
- if (libJarName.length() > 0) {
- libJarNames.add(libJarName);
+ try {
+ URI uri = url.toURI();
+ String libJarName = extractLibJarName(uri);
+ if (libJarName.length() > 0) {
+ libJarNames.add(libJarName);
+ }
+ } catch (URISyntaxException e) {
+ // ignore invalid formats
+ logger.warn("Invalid library url found : [{}]", url, e);
+ } catch (Exception e) {
+ logger.warn("Error extracting library name", e);
}
}
return libJarNames;
}
- private String extractLibJarName(URL url) {
- if (url == null) {
- return "";
- }
- String jarName = url.toString();
+ private String extractLibJarName(URI uri) {
+ String jarName = uri.toString();
if (jarName == null) {
return "";
}
@@ -164,7 +172,9 @@ private String extractLibJarName(URL url) {
}
private void dispatchLibJars(String contextKey, List<String> libJars) {
- this.traceContext.getServerMetaDataHolder().addServiceInfo(contextKey, libJars);
+ ServerMetaDataHolder holder = this.traceContext.getServerMetaDataHolder();
+ holder.addServiceInfo(contextKey, libJars);
+ holder.notifyListeners();
}
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java
index 0b9f34830219..40bf8971a8d0 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java
@@ -73,7 +73,7 @@ public void removeListener(ServerMetaDataListener listener) {
}
@Override
- public void publishServerMetaData() {
+ public void notifyListeners() {
final ServerMetaData serverMetaData = createServerMetaData();
for (ServerMetaDataListener listener : this.listeners) {
listener.publishServerMetaData(serverMetaData);
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java
index 487f1b70eeb3..451b671b814c 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java
@@ -359,13 +359,15 @@ public void serverMetaDataCouldBePublishedFromMultipleThreads() throws Interrupt
metaDataContext.addListener(agentInfoSender);
// When
for (int i = 0; i < threadCount; ++i) {
+ final String serviceName = "/name" + i;
executorService.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
initLatch.countDown();
try {
startLatch.await();
- metaDataContext.publishServerMetaData();
+ metaDataContext.addServiceInfo(serviceName, Collections.<String>emptyList());
+ metaDataContext.notifyListeners();
} catch (final Throwable t) {
exceptions.add(t);
} finally {
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolderTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolderTest.java
index 2d51b4582380..bced0b1ee73b 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolderTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolderTest.java
@@ -35,7 +35,6 @@
import com.navercorp.pinpoint.bootstrap.context.ServerMetaData;
import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder;
-import com.navercorp.pinpoint.profiler.context.DefaultServerMetaDataHolder;
import com.navercorp.pinpoint.test.TestableServerMetaDataListener;
/**
@@ -83,7 +82,7 @@ public Void call() throws Exception {
try {
startLatch.await();
metaDataContext.addServiceInfo(serviceName, serviceLibs);
- metaDataContext.publishServerMetaData();
+ metaDataContext.notifyListeners();
} catch (final Throwable t) {
exceptions.add(t);
} finally {
@@ -129,7 +128,7 @@ public Void call() throws Exception {
try {
startLatch.await();
metaDataContext.addServiceInfo(serviceName, serviceLibs);
- metaDataContext.publishServerMetaData();
+ metaDataContext.notifyListeners();
} catch (Throwable t) {
exceptions.add(t);
} finally {
| val | train | "2016-03-22T07:15:07" | "2016-03-17T08:17:14Z" | Xylus | test |
pinpoint-apm/pinpoint/1825_1826 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1825 | pinpoint-apm/pinpoint/1826 | [
"keyword_pr_to_issue"
] | f0ae3d7ab6048df4ffa1a5e46e5181c3b1a3cdaf | 61eba41fcfae4ba3df34b77ee79e6e709832dece | [] | [] | "2016-06-02T08:04:22Z" | [
"enhancement"
] | Remove assembly plugin usage from profiler module | [
"agent/pom.xml",
"agent/src/assembly/distribution.xml",
"plugins/assembly.xml",
"plugins/pom.xml"
] | [
"agent/pom.xml",
"agent/src/assembly/distribution.xml",
"plugins/pom.xml"
] | [] | diff --git a/agent/pom.xml b/agent/pom.xml
index 0e44b8803f33..f951ca638a61 100644
--- a/agent/pom.xml
+++ b/agent/pom.xml
@@ -31,7 +31,7 @@
<dependency>
<groupId>com.navercorp.pinpoint</groupId>
<artifactId>pinpoint-plugins</artifactId>
- <type>zip</type>
+ <type>pom</type>
<scope>runtime</scope>
</dependency>
diff --git a/agent/src/assembly/distribution.xml b/agent/src/assembly/distribution.xml
index 758cb1490c63..ab1048e79d52 100644
--- a/agent/src/assembly/distribution.xml
+++ b/agent/src/assembly/distribution.xml
@@ -52,8 +52,12 @@
<includes>
<include>com.navercorp.pinpoint:pinpoint-plugins</include>
</includes>
+ <excludes>
+ <exclude>*:pom</exclude>
+ </excludes>
<outputDirectory>plugin</outputDirectory>
- <unpack>true</unpack>
+ <useProjectArtifact>false</useProjectArtifact>
+ <useTransitiveFiltering>true</useTransitiveFiltering>
</dependencySet>
<dependencySet>
<includes>
diff --git a/plugins/assembly.xml b/plugins/assembly.xml
deleted file mode 100644
index a4cea45a22e8..000000000000
--- a/plugins/assembly.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
-
- <id>plugins</id>
- <formats>
- <format>zip</format>
- </formats>
- <includeBaseDirectory>false</includeBaseDirectory>
- <dependencySets>
- <dependencySet>
- <outputDirectory>/</outputDirectory>
- <useProjectArtifact>false</useProjectArtifact>
- <useTransitiveDependencies>false</useTransitiveDependencies>
- <scope>runtime</scope>
- </dependencySet>
- </dependencySets>
-</assembly>
\ No newline at end of file
diff --git a/plugins/pom.xml b/plugins/pom.xml
index bbd90c0b51af..f948bbf1a1f5 100644
--- a/plugins/pom.xml
+++ b/plugins/pom.xml
@@ -203,29 +203,4 @@
</dependency>
</dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <version>2.5.3</version>
- <configuration>
- <descriptors>
- <descriptor>assembly.xml</descriptor>
-
- </descriptors>
- <appendAssemblyId>false</appendAssemblyId>
- </configuration>
- <executions>
- <execution>
- <id>create-zip</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
</project>
| null | train | train | "2016-06-02T09:44:17" | "2016-06-02T07:56:33Z" | Xylus | test |
|
pinpoint-apm/pinpoint/1838_1851 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1838 | pinpoint-apm/pinpoint/1851 | [
"keyword_pr_to_issue"
] | 34bea749dd6061ff6e04e8761edd8074f19e3725 | 41ff1f19d2188256f4c38928e7a5dd837c5d2edd | [] | [] | "2016-06-16T02:56:44Z" | [
"enhancement"
] | Buffer API enhancement | [Buffer](https://github.com/naver/pinpoint/blob/master/commons/src/main/java/com/navercorp/pinpoint/common/buffer/Buffer.java) API enhancement
- add remaining()
- add hasRemaining()
- add wrapByteBuffer()
- deprecated limit()
- change put($Type) -> put$Type()
- change putVar($Type) -> putV$Type()
- change readVar$Type() -> readV$Type();
- fixed incorrect buffer expend multiplier : multiplier 4 -> multiplier 2
| [
"commons/src/main/java/com/navercorp/pinpoint/common/buffer/FixedBuffer.java"
] | [
"commons/src/main/java/com/navercorp/pinpoint/common/buffer/FixedBuffer.java"
] | [] | diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/buffer/FixedBuffer.java b/commons/src/main/java/com/navercorp/pinpoint/common/buffer/FixedBuffer.java
index dbcd0a20371e..f1e699ef61df 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/buffer/FixedBuffer.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/buffer/FixedBuffer.java
@@ -300,7 +300,7 @@ public void putBytes(final byte[] v) {
@Deprecated
@Override
public void put(final byte[] v) {
- put(v);
+ putBytes(v);
}
@Override
| null | train | train | "2016-06-15T12:13:37" | "2016-06-10T09:46:02Z" | emeroad | test |
pinpoint-apm/pinpoint/1858_1861 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1858 | pinpoint-apm/pinpoint/1861 | [
"keyword_issue_to_pr"
] | 6c96aa3c0ee19a37600ea9ea8b7a4f9b0f034084 | 21592684e8a52609534f026ccdc7dccef556adee | [
"Our quickstart web might be broken, will check and get back to you.\n",
"Yup, just reproduced your issue. We'll get right on this.\nIn the mean time, check out [1.5.2](https://github.com/naver/pinpoint/releases/tag/1.5.2) as this is our latest stable release.\n\nWill let you know once a fix is up.\nThanks!\n",
"Fix applied.\nPlease pull source and rebuild.\n",
"Hi , I have pull source again and rebuild and retry. The major dashboard appeared and it's very nice.\nBut still found one chart keep \"Loading\" as attached screenshot.\n\n<img width=\"1429\" alt=\"pinpoint_one_chart_loading\" src=\"https://cloud.githubusercontent.com/assets/2519527/16197191/af87dff0-3733-11e6-9ed0-3c6098c7d945.png\">\n",
"Yup, sorry about that, it's just been fixed I think via #1861 \nPlease give it a try again.\n",
"Thanks, Now it's working\n"
] | [] | "2016-06-21T00:34:05Z" | [
"bug",
"help wanted"
] | quickstart: web UI keep showing "loading" without any data/chart output or completed. | I have followed the quickstart guide and installed hbase/collector/web_ui/testapp on single CentOS 7 VM to give it a try.
After finally launched the testapp, I then directored to pinpoint's web UI and testapp's web UI.
In pinpoint's web UI, the TESTAPP is registered and can be selected. But it kept showing loading without data/chart output or end as attached screenshot.
The pinpoint Web logs are as below:
Starting ProtocolHandler ["http-bio-28080"]
13:35:46 INFO (p.w.c.z.ZookeeperClusterDataManager:131) Handle Zookeeper Event(WatchedEvent state:SyncConnected type:NodeDataChanged path:/pinpoint-cluster/collector/105723@centos_head) started.
13:35:46 INFO (p.w.c.z.ZookeeperClusterDataManager:270) pushCollectorClusterData() started.
13:35:46 INFO (p.w.c.z.ZookeeperClusterDataManager:277) pushCollectorClusterData() completed.
13:35:46 INFO (p.w.c.z.ZookeeperClusterDataManager:158) Handle Zookeeper Event(WatchedEvent state:SyncConnected type:NodeDataChanged path:/pinpoint-cluster/collector/105723@centos_head) completed.
13:37:51 DEBUG(c.n.p.w.c.MainController :50 ) /applications [TESTAPP(STAND_ALONE:1000)]
13:40:31 DEBUG(c.n.p.r.s.PinpointServerAcceptor :55 ) ping write success channel:[id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
13:40:31 DEBUG(c.n.p.r.s.PinpointServerAcceptor :282) newPingTimeout
13:40:31 DEBUG(c.n.p.r.c.PacketDecoder :96 ) receive pong. [id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
13:40:32 DEBUG(c.n.p.r.s.DefaultPinpointServer :418) DefaultPinpointServer@1afb3544 handlePingPacket() started. packet:PingPacket{pingId:1(RUN_DUPLEX)}
13:40:32 DEBUG(c.n.p.w.c.c.ClusterAcceptor :105) ping received PingPacket{pingId:1(RUN_DUPLEX)} DefaultPinpointServer@1afb3544(remote:/192.168.255.128:58215, state:RUN_DUPLEX)
13:40:32 DEBUG(c.n.p.r.s.DefaultPinpointServer :55 ) pong write success. channel:[id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
13:45:31 DEBUG(c.n.p.r.s.PinpointServerAcceptor :282) newPingTimeout
13:45:31 DEBUG(c.n.p.r.s.PinpointServerAcceptor :55 ) ping write success channel:[id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
13:45:31 DEBUG(c.n.p.r.c.PacketDecoder :96 ) receive pong. [id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
13:45:32 DEBUG(c.n.p.r.s.DefaultPinpointServer :418) DefaultPinpointServer@1afb3544 handlePingPacket() started. packet:PingPacket{pingId:2(RUN_DUPLEX)}
13:45:32 DEBUG(c.n.p.w.c.c.ClusterAcceptor :105) ping received PingPacket{pingId:2(RUN_DUPLEX)} DefaultPinpointServer@1afb3544(remote:/192.168.255.128:58215, state:RUN_DUPLEX)
13:45:32 DEBUG(c.n.p.r.s.DefaultPinpointServer :55 ) pong write success. channel:[id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
13:50:32 DEBUG(c.n.p.r.s.PinpointServerAcceptor :282) newPingTimeout
13:50:32 DEBUG(c.n.p.r.s.PinpointServerAcceptor :55 ) ping write success channel:[id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
13:50:32 DEBUG(c.n.p.r.c.PacketDecoder :96 ) receive pong. [id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
13:50:32 DEBUG(c.n.p.r.s.DefaultPinpointServer :418) DefaultPinpointServer@1afb3544 handlePingPacket() started. packet:PingPacket{pingId:3(RUN_DUPLEX)}
13:50:32 DEBUG(c.n.p.w.c.c.ClusterAcceptor :105) ping received PingPacket{pingId:3(RUN_DUPLEX)} DefaultPinpointServer@1afb3544(remote:/192.168.255.128:58215, state:RUN_DUPLEX)
13:50:32 DEBUG(c.n.p.r.s.DefaultPinpointServer :55 ) pong write success. channel:[id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
13:55:32 DEBUG(c.n.p.r.s.PinpointServerAcceptor :282) newPingTimeout
13:55:32 DEBUG(c.n.p.r.s.PinpointServerAcceptor :55 ) ping write success channel:[id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
13:55:32 DEBUG(c.n.p.r.c.PacketDecoder :96 ) receive pong. [id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
13:55:32 DEBUG(c.n.p.r.s.DefaultPinpointServer :418) DefaultPinpointServer@1afb3544 handlePingPacket() started. packet:PingPacket{pingId:4(RUN_DUPLEX)}
13:55:32 DEBUG(c.n.p.w.c.c.ClusterAcceptor :105) ping received PingPacket{pingId:4(RUN_DUPLEX)} DefaultPinpointServer@1afb3544(remote:/192.168.255.128:58215, state:RUN_DUPLEX)
13:55:32 DEBUG(c.n.p.r.s.DefaultPinpointServer :55 ) pong write success. channel:[id: 0x96ac7d3c, /192.168.255.128:58215 => /192.168.255.128:29997]
#
The collector logs is as below
06-19 14:05:32 [DEBUG](c.n.p.r.c.PacketDecoder :113) received ping. sending pong. [id: 0x77c8d299, /192.168.255.128:58215 => /192.168.255.128:29997]
06-19 14:05:32 [DEBUG](c.n.p.r.c.PacketDecoder :55) pong write success. channel:[id: 0x77c8d299, /192.168.255.128:58215 => /192.168.255.128:29997]
06-19 14:05:32 [DEBUG](c.n.p.r.c.DefaultPinpointClientHandler:236) DefaultPinpointClientHandler@558c6868 writePing() started. channel:[id: 0x77c8d299, /192.168.255.128:58215 => /192.168.255.128:29997]
06-19 14:05:32 [DEBUG](c.n.p.r.c.DefaultPinpointClientHandler:55) ping write success. channel:[id: 0x77c8d299, /192.168.255.128:58215 => /192.168.255.128:29997]
06-19 14:05:32 [DEBUG](c.n.p.r.c.PacketDecoder :96) receive pong. [id: 0x77c8d299, /192.168.255.128:58215 => /192.168.255.128:29997]
06-19 14:05:46 [DEBUG](c.n.p.c.h.AgentStatHandler :67) Received AgentStats=TAgentStatBatch(agentId:test-agent, startTimestamp:1466314545225, agentStats:[TAgentStat(timestamp:1466316321359, collect
Interval:5001, gc:TJvmGc(type:PARALLEL, jvmMemoryHeapUsed:79618104, jvmMemoryHeapMax:427294720, jvmMemoryNonHeapUsed:81700616, jvmMemoryNonHeapMax:-1, jvmGcOldCount:3, jvmGcOldTime:259, jvmGcDetailed:TJvm
GcDetailed(jvmGcNewCount:20, jvmGcNewTime:332, jvmPoolCodeCacheUsed:0.06694437662760416, jvmPoolNewGenUsed:0.09821334251990685, jvmPoolOldGenUsed:0.17922481655489209, jvmPoolSurvivorSpaceUsed:0.4384948730
46875, jvmPoolMetaspaceUsed:0.9626290338424217)), cpuLoad:TCpuLoad(jvmCpuLoad:0.00202020202020202, systemCpuLoad:0.01717171717171717), transaction:TTransaction(sampledNewCount:0, sampledContinuationCount:
0, unsampledNewCount:0, unsampledContinuationCount:0), activeTrace:TActiveTrace(histogram:TActiveTraceHistogram(version:0, histogramSchemaType:2, activeTraceCount:[0, 0, 0, 0]))), TAgentStat(timestamp:146
6316326358, collectInterval:4999, gc:TJvmGc(type:PARALLEL, jvmMemoryHeapUsed:79618104, jvmMemoryHeapMax:427294720, jvmMemoryNonHeapUsed:81700616, jvmMemoryNonHeapMax:-1, jvmGcOldCount:3, jvmGcOldTime:259,
jvmGcDetailed:TJvmGcDetailed(jvmGcNewCount:20, jvmGcNewTime:332, jvmPoolCodeCacheUsed:0.06694437662760416, jvmPoolNewGenUsed:0.09821334251990685, jvmPoolOldGenUsed:0.17922481655489209, jvmPoolSurvivorSpa
ceUsed:0.438494873046875, jvmPoolMetaspaceUsed:0.9626290338424217)), cpuLoad:TCpuLoad(jvmCpuLoad:0.002014098690835851, systemCpuLoad:0.014098690835850957), transaction:TTransaction(sampledNewCount:0, samp
ledContinuationCount:0, unsampledNewCount:0, unsampledContinuationCount:0), activeTrace:TActiveTrace(histogram:TActiveTraceHistogram(version:0, histogramSchemaType:2, activeTraceCount:[0, 0, 0, 0]))), TAg
entStat(timestamp:1466316331358, collectInterval:5000, gc:TJvmGc(type:PARALLEL, jvmMemoryHeapUsed:79618104, jvmMemoryHeapMax:427294720, jvmMemoryNonHeapUsed:81700616, jvmMemoryNonHeapMax:-1, jvmGcOldCount
:3, jvmGcOldTime:259, jvmGcDetailed:TJvmGcDetailed(jvmGcNewCount:20, jvmGcNewTime:332, jvmPoolCodeCacheUsed:0.06694437662760416, jvmPoolNewGenUsed:0.09821334251990685, jvmPoolOldGenUsed:0.1792248165548920
9, jvmPoolSurvivorSpaceUsed:0.438494873046875, jvmPoolMetaspaceUsed:0.9626290338424217)), cpuLoad:TCpuLoad(jvmCpuLoad:0.0020181634712411706, systemCpuLoad:0.018163471241170535), transaction:TTransaction(s
ampledNewCount:0, sampledContinuationCount:0, unsampledNewCount:0, unsampledContinuationCount:0), activeTrace:TActiveTrace(histogram:TActiveTraceHistogram(version:0, histogramSchemaType:2, activeTraceCoun
t:[0, 0, 0, 0]))), TAgentStat(timestamp:1466316336358, collectInterval:5000, gc:TJvmGc(type:PARALLEL, jvmMemoryHeapUsed:79618104, jvmMemoryHeapMax:427294720, jvmMemoryNonHeapUsed:81700616, jvmMemoryNonHea
pMax:-1, jvmGcOldCount:3, jvmGcOldTime:259, jvmGcDetailed:TJvmGcDetailed(jvmGcNewCount:20, jvmGcNewTime:332, jvmPoolCodeCacheUsed:0.06694437662760416, jvmPoolNewGenUsed:0.09821334251990685, jvmPoolOldGenU
sed:0.17922481655489209, jvmPoolSurvivorSpaceUsed:0.438494873046875, jvmPoolMetaspaceUsed:0.9626290338424217)), cpuLoad:TCpuLoad(jvmCpuLoad:0.0010090817356205853, systemCpuLoad:0.015136226034308779), tran
saction:TTransaction(sampledNewCount:0, sampledContinuationCount:0, unsampledNewCount:0, unsampledContinuationCount:0), activeTrace:TActiveTrace(histogram:TActiveTraceHistogram(version:0, histogramSchemaT
ype:2, activeTraceCount:[0, 0, 0, 0]))), TAgentStat(timestamp:1466316341358, collectInterval:5000, gc:TJvmGc(type:PARALLEL, jvmMemoryHeapUsed:79618104, jvmMemoryHeapMax:427294720, jvmMemoryNonHeapUsed:817
01816, jvmMemoryNonHeapMax:-1, jvmGcOldCount:3, jvmGcOldTime:259, jvmGcDetailed:TJvmGcDetailed(jvmGcNewCount:20, jvmGcNewTime:332, jvmPoolCodeCacheUsed:0.06694793701171875, jvmPoolNewGenUsed:0.09821334251
990685, jvmPoolOldGenUsed:0.17922481655489209, jvmPoolSurvivorSpaceUsed:0.438494873046875, jvmPoolMetaspaceUsed:0.9626341055077218)), cpuLoad:TCpuLoad(jvmCpuLoad:0.002014098690835851, systemCpuLoad:0.0151
05740181268883), transaction:TTransaction(sampledNewCount:0, sampledContinuationCount:0, unsampledNewCount:0, unsampledContinuationCount:0), activeTrace:TActiveTrace(histogram:TActiveTraceHistogram(versio
n:0, histogramSchemaType:2, activeTraceCount:[0, 0, 0, 0]))), TAgentStat(timestamp:1466316346358, collectInterval:5000, gc:TJvmGc(type:PARALLEL, jvmMemoryHeapUsed:79618104, jvmMemoryHeapMax:427294720, jvm
MemoryNonHeapUsed:81701816, jvmMemoryNonHeapMax:-1, jvmGcOldCount:3, jvmGcOldTime:259, jvmGcDetailed:TJvmGcDetailed(jvmGcNewCount:20, jvmGcNewTime:332, jvmPoolCodeCacheUsed:0.06694793701171875, jvmPoolNew
GenUsed:0.09821334251990685, jvmPoolOldGenUsed:0.17922481655489209, jvmPoolSurvivorSpaceUsed:0.438494873046875, jvmPoolMetaspaceUsed:0.9626341055077218)), cpuLoad:TCpuLoad(jvmCpuLoad:0.0010090817356205853
, systemCpuLoad:0.014127144298688193), transaction:TTransaction(sampledNewCount:0, sampledContinuationCount:0, unsampledNewCount:0, unsampledContinuationCount:0), activeTrace:TActiveTrace(histogram:TActiv
eTraceHistogram(version:0, histogramSchemaType:2, activeTraceCount:[0, 0, 0, 0])))])
06-19 14:05:46 [DEBUG](c.n.p.r.s.DefaultPinpointServer :418) DefaultPinpointServer@31d15709 handlePingPacket() started. packet:PingPacket{pingId:6(RUN_DUPLEX)}
06-19 14:05:46 [INFO ](c.n.p.c.r.h.AgentLifeCycleHandler :65) handle lifecycle event - pinpointServer:DefaultPinpointServer@31d15709(remote:/127.0.0.1:41894, state:RUN_DUPLEX), state:Running
06-19 14:05:46 [DEBUG](c.n.p.c.d.h.HbaseAgentLifeCycleDao :54) insert agent life cycle. AgentLifeCycleBo{version=0, agentId='test-agent', startTimestamp=1466314545225, eventTimestamp=1466316346737, eventI
dentifier=4294967302, state=Running
06-19 14:05:46 [DEBUG](c.n.p.r.s.DefaultPinpointServer :55) pong write success. channel:[id: 0x15937931, /127.0.0.1:41894 => /127.0.0.1:29994]
06-19 14:05:46 [INFO ](c.n.p.c.r.h.AgentEventHandler :128) handle event: AgentEventBo{version=0, agentId='test-agent', startTimestamp=1466314545225, eventTimestamp=1466316346737, eventType='Agent pin
g'
06-19 14:05:46 [DEBUG](c.n.p.c.d.h.HbaseAgentEventDao :56) insert event. AgentEventBo{version=0, agentId='test-agent', startTimestamp=1466314545225, eventTimestamp=1466316346737, eventType='Agent ping
'
#
<img width="1007" alt="pinpoint_web" src="https://cloud.githubusercontent.com/assets/2519527/16175635/374b6cee-3627-11e6-95fd-fb83f0b4c8ef.png">
[quickstart_log.zip](https://github.com/naver/pinpoint/files/322142/quickstart_log.zip)
detailed logs are attached.
Thanks,
| [
"web/src/main/webapp/common/services/url-vo.service.js",
"web/src/main/webapp/features/navbar/navbar.directive.js"
] | [
"web/src/main/webapp/common/services/url-vo.service.js",
"web/src/main/webapp/features/navbar/navbar.directive.js"
] | [] | diff --git a/web/src/main/webapp/common/services/url-vo.service.js b/web/src/main/webapp/common/services/url-vo.service.js
index 3af09e4b5769..11474699973e 100644
--- a/web/src/main/webapp/common/services/url-vo.service.js
+++ b/web/src/main/webapp/common/services/url-vo.service.js
@@ -25,11 +25,16 @@
this.initUrlVo = function( pageName, $routeParams ) {
switch( pageName ) {
case "main":
- this.setApplication( $routeParams.application )
- .setReadablePeriod( $routeParams.readablePeriod )
- .setQueryEndDateTime( $routeParams.queryEndDateTime )
- .setCallee( PreferenceService.getCalleeByApp($routeParams.application) )
- .setCaller( PreferenceService.getCallerByApp($routeParams.application) );
+ if ( $routeParams.readablePeriod === oPeriodType.REALTIME ) {
+ this.setApplication( $routeParams.application )
+ .setReadablePeriod( $routeParams.readablePeriod );
+ } else {
+ this.setApplication( $routeParams.application )
+ .setReadablePeriod( $routeParams.readablePeriod )
+ .setQueryEndDateTime( $routeParams.queryEndDateTime )
+ .setCallee( PreferenceService.getCalleeByApp($routeParams.application) )
+ .setCaller( PreferenceService.getCallerByApp($routeParams.application) );
+ }
break;
case "filteredMap":
this.setApplication( $routeParams.application )
diff --git a/web/src/main/webapp/features/navbar/navbar.directive.js b/web/src/main/webapp/features/navbar/navbar.directive.js
index 92714db6a9f8..9300d8b7996c 100644
--- a/web/src/main/webapp/features/navbar/navbar.directive.js
+++ b/web/src/main/webapp/features/navbar/navbar.directive.js
@@ -16,8 +16,8 @@
}
});
- pinpointApp.directive('navbarDirective', [ "navbarDirectiveConfig", "$route", "$rootScope", "$http","$document", "$timeout", "$window", "webStorage", "helpContentService", "AnalyticsService", "PreferenceService", "TooltipService", "CommonAjaxService",
- function (cfg, $route, $rootScope, $http, $document, $timeout, $window, webStorage, helpContentService, analyticsService, preferenceService, tooltipService, commonAjaxService) {
+ pinpointApp.directive('navbarDirective', [ "navbarDirectiveConfig", "$route", "$rootScope", "$http","$document", "$timeout", "$window", "webStorage", "helpContentService", "UrlVoService", "AnalyticsService", "PreferenceService", "TooltipService", "CommonAjaxService",
+ function (cfg, $route, $rootScope, $http, $document, $timeout, $window, webStorage, helpContentService, UrlVoService, analyticsService, preferenceService, tooltipService, commonAjaxService) {
return {
restrict: 'EA',
replace: true,
@@ -287,6 +287,9 @@
oNavbarVoService.setReadablePeriod(scope.readablePeriod);
oNavbarVoService.setQueryEndDateTime(moment(currentServerTime).format('YYYY-MM-DD-HH-mm-ss'));
oNavbarVoService.autoCalculateByQueryEndDateTimeAndReadablePeriod();
+ UrlVoService.setReadablePeriod(scope.readablePeriod);
+ UrlVoService.setQueryEndDateTime(moment(currentServerTime).format('YYYY-MM-DD-HH-mm-ss'));
+ UrlVoService.autoCalculateByQueryEndDateTimeAndReadablePeriod();
emitAsChanged();
setDateTime($fromPicker, oNavbarVoService.getQueryStartTime());
setDateTime($toPicker, oNavbarVoService.getQueryEndTime());
@@ -297,6 +300,9 @@
oNavbarVoService.setReadablePeriod( preferenceService.getRealtimeScatterXRangeStr() );
oNavbarVoService.setQueryEndDateTime(moment(currentServerTime).format('YYYY-MM-DD-HH-mm-ss'));
oNavbarVoService.autoCalculateByQueryEndDateTimeAndReadablePeriod();
+ UrlVoService.setReadablePeriod( preferenceService.getRealtimeScatterXRangeStr() );
+ UrlVoService.setQueryEndDateTime(moment(currentServerTime).format('YYYY-MM-DD-HH-mm-ss'));
+ UrlVoService.autoCalculateByQueryEndDateTimeAndReadablePeriod();
emitAsChanged();
setDateTime($fromPicker, oNavbarVoService.getQueryStartTime());
setDateTime($toPicker, oNavbarVoService.getQueryEndTime());
@@ -306,6 +312,10 @@
oNavbarVoService.setQueryStartTime(getQueryStartTime());
oNavbarVoService.setQueryEndTime(getQueryEndTime());
oNavbarVoService.autoCalcultateByQueryStartTimeAndQueryEndTime();
+ UrlVoService.setPeriodType( cfg.periodType.RANGE );
+ UrlVoService.setQueryStartTime(getQueryStartTime());
+ UrlVoService.setQueryEndTime(getQueryEndTime());
+ UrlVoService.autoCalcultateByQueryStartTimeAndQueryEndTime();
emitAsChanged();
}
};
| null | val | train | "2016-06-20T06:41:43" | "2016-06-19T06:13:34Z" | deadjoe | test |
pinpoint-apm/pinpoint/1838_1866 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1838 | pinpoint-apm/pinpoint/1866 | [
"keyword_pr_to_issue"
] | 1914e38f73962537738e380b969824ca9e338402 | 58493e326b1ae376ff763796cc3b32f402bf476d | [] | [] | "2016-06-22T10:21:09Z" | [
"enhancement"
] | Buffer API enhancement | [Buffer](https://github.com/naver/pinpoint/blob/master/commons/src/main/java/com/navercorp/pinpoint/common/buffer/Buffer.java) API enhancement
- add remaining()
- add hasRemaining()
- add wrapByteBuffer()
- deprecated limit()
- change put($Type) -> put$Type()
- change putVar($Type) -> putV$Type()
- change readVar$Type() -> readV$Type();
- fixed incorrect buffer expend multiplier : multiplier 4 -> multiplier 2
| [
"commons/src/main/java/com/navercorp/pinpoint/common/buffer/AutomaticBuffer.java"
] | [
"commons/src/main/java/com/navercorp/pinpoint/common/buffer/AutomaticBuffer.java"
] | [
"commons/src/test/java/com/navercorp/pinpoint/common/buffer/AutomaticBufferTest.java"
] | diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/buffer/AutomaticBuffer.java b/commons/src/main/java/com/navercorp/pinpoint/common/buffer/AutomaticBuffer.java
index 92da68ec55c8..e29676de9c2b 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/buffer/AutomaticBuffer.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/buffer/AutomaticBuffer.java
@@ -58,7 +58,7 @@ protected void checkExpand(final int size) {
protected int computeExpandedBufferSize(final int size, int length, int remain) {
int expandedBufferSize = 0;
while (remain < size) {
- length <<= 2;
+ length <<= 1;
expandedBufferSize = length;
remain = expandedBufferSize - offset;
}
| diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/buffer/AutomaticBufferTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/buffer/AutomaticBufferTest.java
index c27508507097..9b2b66c82c1b 100644
--- a/commons/src/test/java/com/navercorp/pinpoint/common/buffer/AutomaticBufferTest.java
+++ b/commons/src/test/java/com/navercorp/pinpoint/common/buffer/AutomaticBufferTest.java
@@ -308,7 +308,7 @@ public void testUdp() throws Exception {
}
@Test
- public void test_remaining() throws Exception {
+ public void testRemaining() throws Exception {
final byte[] bytes = new byte[BytesUtils.INT_BYTE_LENGTH];
Buffer buffer = new AutomaticBuffer(bytes);
Assert.assertEquals(buffer.remaining(), 4);
@@ -326,4 +326,43 @@ public void test_remaining() throws Exception {
}
+
+ @Test
+ public void testExpendMultiplier_2multiplier() throws Exception {
+ int bufferSize = 4;
+ Buffer buffer = new AutomaticBuffer(bufferSize);
+
+ buffer.putBytes(new byte[8]);
+ logger.debug("bufferSize:{} offset:{}", buffer.getInternalBuffer().length, buffer.getOffset());
+ Assert.assertEquals(buffer.getInternalBuffer().length, 8);
+
+ buffer.putBytes(new byte[8]);
+
+ logger.debug("bufferSize:{} offset:{}", buffer.getInternalBuffer().length, buffer.getOffset());
+ Assert.assertEquals(buffer.getInternalBuffer().length, 16);
+
+
+ buffer.putBytes(new byte[8]);
+ logger.debug("bufferSize:{} offset:{}", buffer.getInternalBuffer().length, buffer.getOffset());
+ Assert.assertEquals(buffer.getInternalBuffer().length, 32);
+ }
+
+ @Test
+ public void testExpendMultiplier_4multiplier() throws Exception {
+ int bufferSize = 4;
+ Buffer buffer = new AutomaticBuffer(bufferSize);
+
+ buffer.putBytes(new byte[5*4]);
+
+ logger.debug("bufferSize:{} offset:{}", buffer.getInternalBuffer().length, buffer.getOffset());
+ Assert.assertEquals(buffer.getInternalBuffer().length, 32);
+
+ buffer.putBytes(new byte[8*4]);
+
+ logger.debug("bufferSize:{} offset:{}", buffer.getInternalBuffer().length, buffer.getOffset());
+ Assert.assertEquals(buffer.getInternalBuffer().length, 64);
+
+
+ }
+
}
| train | train | "2016-06-22T11:37:33" | "2016-06-10T09:46:02Z" | emeroad | test |
pinpoint-apm/pinpoint/1879_1880 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1879 | pinpoint-apm/pinpoint/1880 | [
"keyword_pr_to_issue"
] | 5d06efb45dbc0e0143e23fc69fc8766682893616 | df6f342d88c5390196f5ff16c3ed94b796eeaa99 | [] | [] | "2016-06-29T02:47:43Z" | [
"bug"
] | Fails to inject array-typed fields, or getters/setters for array-typed fields | https://groups.google.com/forum/#!topic/pinpoint_user/-PutLtVn5rc
When injecting array-typed fields:
The agent currently invokes `Class.getName()` on the field's type to generate the field signature when injecting a field into a class. The `getName()` method on an array class returns a form not suitable for generating signatures (ie int[] -> [I).
When adding getter/setter for array-typed fields
Type checking is done by comparing Javassist's `CtClass.getName()` and `Class.getName()`. This comparison fails for array classes due to reason similar to above.
For an array of int, `CtClass.getName()` returns int[] whereas `Class.getName()` again returns [I, failing the check.
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/util/JavaAssistUtils.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/util/JavaAssistUtils.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArrayGetter.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArraySetter.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArrayTraceValue.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntSetter.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArrayGetter.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArraySetter.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArrayTraceValue.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/JavassistClassTest.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject3.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject4.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/util/JavaAssistUtilsTest.java"
] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java
index a4b3846419ad..b8988f55a108 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistClass.java
@@ -342,7 +342,10 @@ private void addField0(String accessorTypeName, String initValExp) throws Instru
final AccessorAnalyzer accessorAnalyzer = new AccessorAnalyzer();
final AccessorDetails accessorDetails = accessorAnalyzer.analyze(accessorType);
- final CtField newField = CtField.make("private " + accessorDetails.getFieldType().getName() + " " + FIELD_PREFIX + accessorTypeName.replace('.', '_').replace('$', '_') + ";", ctClass);
+ Class<?> fieldType = accessorDetails.getFieldType();
+ String fieldTypeName = JavaAssistUtils.javaClassNameToObjectName(fieldType.getName());
+
+ final CtField newField = CtField.make("private " + fieldTypeName + " " + FIELD_PREFIX + accessorTypeName.replace('.', '_').replace('$', '_') + ";", ctClass);
if (initValExp == null) {
ctClass.addField(newField);
@@ -371,8 +374,9 @@ public void addGetter(String getterTypeName, String fieldName) throws Instrument
GetterDetails getterDetails = new GetterAnalyzer().analyze(getterType);
CtField field = ctClass.getField(fieldName);
+ String fieldTypeName = JavaAssistUtils.javaClassNameToObjectName(getterDetails.getFieldType().getName());
- if (!field.getType().getName().equals(getterDetails.getFieldType().getName())) {
+ if (!field.getType().getName().equals(fieldTypeName)) {
throw new IllegalArgumentException("Return type of the getter is different with the field type. getterMethod: " + getterDetails.getGetter() + ", fieldType: " + field.getType().getName());
}
@@ -404,8 +408,9 @@ public void addSetter(String setterTypeName, String fieldName, boolean removeFin
SetterDetails setterDetails = new SetterAnalyzer().analyze(setterType);
CtField field = ctClass.getField(fieldName);
+ String fieldTypeName = JavaAssistUtils.javaClassNameToObjectName(setterDetails.getFieldType().getName());
- if (!field.getType().getName().equals(setterDetails.getFieldType().getName())) {
+ if (!field.getType().getName().equals(fieldTypeName)) {
throw new IllegalArgumentException("Argument type of the setter is different with the field type. setterMethod: " + setterDetails.getSetter() + ", fieldType: " + field.getType().getName());
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/JavaAssistUtils.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/JavaAssistUtils.java
index d0435d269ea6..7b90d8947d52 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/JavaAssistUtils.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/JavaAssistUtils.java
@@ -230,6 +230,16 @@ public static String[] parseParameterSignature(String signature) {
return objectType;
}
+ public static String javaClassNameToObjectName(String javaClassName) {
+ final char scheme = javaClassName.charAt(0);
+ switch (scheme) {
+ case '[':
+ return toArrayType(javaClassName);
+ default:
+ return javaClassName;
+ }
+ }
+
private static String byteCodeSignatureToObjectType(String signature, int startIndex) {
final char scheme = signature.charAt(startIndex);
switch (scheme) {
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArrayGetter.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArrayGetter.java
new file mode 100644
index 000000000000..b02e42053623
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArrayGetter.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.interceptor.bci;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface IntArrayGetter {
+ int[] _$PINPOINT$_getIntArray();
+}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArraySetter.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArraySetter.java
new file mode 100644
index 000000000000..a8ab44f32daa
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArraySetter.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.interceptor.bci;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface IntArraySetter {
+ void _$PINPOINT$_setIntArray(int[] integers);
+}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArrayTraceValue.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArrayTraceValue.java
new file mode 100644
index 000000000000..0f58ed20ec09
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntArrayTraceValue.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.interceptor.bci;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface IntArrayTraceValue {
+ void _$PINPOINT$_setTraceIntArray(int[] values);
+ int[] _$PINPOINT$_getTraceIntArray();
+}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntSetter.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntSetter.java
new file mode 100644
index 000000000000..96cc1ea10c04
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntSetter.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.interceptor.bci;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface IntSetter {
+ void _$PINPOINT$_setInt(int integer);
+}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArrayGetter.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArrayGetter.java
new file mode 100644
index 000000000000..5984febcfa54
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArrayGetter.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.interceptor.bci;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface IntegerArrayGetter {
+ Integer[] _$PINPOINT$_getIntegerArray();
+}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArraySetter.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArraySetter.java
new file mode 100644
index 000000000000..b49308fcd687
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArraySetter.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.interceptor.bci;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface IntegerArraySetter {
+ void _$PINPOINT$_setIntegerArray(Integer[] integers);
+}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArrayTraceValue.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArrayTraceValue.java
new file mode 100644
index 000000000000..0b69a32c4104
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/IntegerArrayTraceValue.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.interceptor.bci;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface IntegerArrayTraceValue {
+ void _$PINPOINT$_setTraceIntegerArray(Integer[] values);
+ Integer[] _$PINPOINT$_getTraceIntegerArray();
+}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/JavassistClassTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/JavassistClassTest.java
index 905a2c7f480c..0d817815e4b3 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/JavassistClassTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/JavassistClassTest.java
@@ -152,6 +152,8 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
aClass.addField(ObjectTraceValue.class.getName());
aClass.addField(IntTraceValue.class.getName());
+ aClass.addField(IntArrayTraceValue.class.getName());
+ aClass.addField(IntegerArrayTraceValue.class.getName());
aClass.addField(DatabaseInfoTraceValue.class.getName());
aClass.addField(BindValueTraceValue.class.getName());
@@ -180,13 +182,27 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
Object get = objectTraceValue.getMethod("_$PINPOINT$_getTraceObject").invoke(testObject);
Assert.assertEquals("a", get);
-
Class<?> intTraceValue = loader.loadClass(IntTraceValue.class.getName());
Assert.assertTrue("IntTraceValue implements fail", intTraceValue.isInstance(testObject));
intTraceValue.getMethod("_$PINPOINT$_setTraceInt", int.class).invoke(testObject, 1);
int a = (Integer)intTraceValue.getMethod("_$PINPOINT$_getTraceInt").invoke(testObject);
Assert.assertEquals(1, a);
+ Class<?> intArrayTraceValue = loader.loadClass(IntArrayTraceValue.class.getName());
+ Assert.assertTrue("IntArrayTraceValue implements fail", intArrayTraceValue.isInstance(testObject));
+ int[] expectedInts = {1, 2, 3};
+ intArrayTraceValue.getMethod("_$PINPOINT$_setTraceIntArray", int[].class).invoke(testObject, expectedInts);
+ int[] ints = (int[]) intArrayTraceValue.getMethod("_$PINPOINT$_getTraceIntArray").invoke(testObject);
+ Assert.assertEquals(expectedInts, ints);
+
+ Class<?> integerArrayTraceValue = loader.loadClass(IntegerArrayTraceValue.class.getName());
+ Assert.assertTrue("IntegerArrayTraceValue implements fail", integerArrayTraceValue.isInstance(testObject));
+ Integer[] expectedIntegers = {1, 2};
+ // wrap due to vararg expansion
+ Object[] wrappedExpectedIntegers = new Object[]{expectedIntegers};
+ integerArrayTraceValue.getMethod("_$PINPOINT$_setTraceIntegerArray", Integer[].class).invoke(testObject, wrappedExpectedIntegers);
+ Integer[] integers = (Integer[]) integerArrayTraceValue.getMethod("_$PINPOINT$_getTraceIntegerArray").invoke(testObject);
+ Assert.assertArrayEquals(expectedIntegers, integers);
Class<?> databaseTraceValue = loader.loadClass(DatabaseInfoTraceValue.class.getName());
Assert.assertTrue("DatabaseInfoTraceValue implements fail", databaseTraceValue.isInstance(testObject));
@@ -335,7 +351,8 @@ public void nullDescriptor() {
public void testAddGetter() throws Exception {
final TestClassLoader loader = getTestClassLoader();
final String targetClassName = "com.navercorp.pinpoint.profiler.interceptor.bci.TestObject3";
-
+
+
loader.addTransformer(targetClassName, new TransformCallback() {
@Override
@@ -346,6 +363,8 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader,
aClass.addGetter(StringGetter.class.getName(), "value");
aClass.addGetter(IntGetter.class.getName(), "intValue");
+ aClass.addGetter(IntArrayGetter.class.getName(), "intValues");
+ aClass.addGetter(IntegerArrayGetter.class.getName(), "integerValues");
return aClass.toBytecode();
} catch (InstrumentException e) {
@@ -360,12 +379,18 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader,
Class<?> stringGetter = loader.loadClass(StringGetter.class.getName());
Class<?> intGetter = loader.loadClass(IntGetter.class.getName());
+ Class<?> intsGetter = loader.loadClass(IntArrayGetter.class.getName());
+ Class<?> integersGetter = loader.loadClass(IntegerArrayGetter.class.getName());
Assert.assertTrue(stringGetter.isInstance(testObject));
Assert.assertTrue(intGetter.isInstance(testObject));
+ Assert.assertTrue(intsGetter.isInstance(testObject));
+ Assert.assertTrue(integersGetter.isInstance(testObject));
String value = "hehe";
int intValue = 99;
+ int[] intValues = {99, 100};
+ Integer[] integerValues = {99, 100};
Method method = testObject.getClass().getMethod("setValue", String.class);
method.invoke(testObject, value);
@@ -379,6 +404,77 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader,
Method getInt = intGetter.getMethod("_$PINPOINT$_getInt");
Assert.assertEquals(intValue, getInt.invoke(testObject));
+ Method setIntValues = testObject.getClass().getMethod("setIntValues", int[].class);
+ setIntValues.invoke(testObject, intValues);
+
+ Method getIntValues = intsGetter.getMethod("_$PINPOINT$_getIntArray");
+ Assert.assertEquals(intValues, getIntValues.invoke(testObject));
+
+ Method setIntegerValues = testObject.getClass().getMethod("setIntegerValues", Integer[].class);
+ // wrap due to vararg expansion
+ Object[] wrappedIntegerValues = new Object[]{integerValues};
+ setIntegerValues.invoke(testObject, wrappedIntegerValues);
+
+ Method getIntegerValues = integersGetter.getMethod("_$PINPOINT$_getIntegerArray");
+ Assert.assertEquals(integerValues, getIntegerValues.invoke(testObject));
+
+ }
+
+ @Test
+ public void testAddSetter() throws Exception {
+ final TestClassLoader loader = getTestClassLoader();
+ final String targetClassName = "com.navercorp.pinpoint.profiler.interceptor.bci.TestObject4";
+
+ loader.addTransformer(targetClassName, new TransformCallback() {
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ try {
+ logger.info("modify cl:{}", classLoader);
+ InstrumentClass testClass = instrumentor.getInstrumentClass(classLoader, className, classfileBuffer);
+
+ testClass.addSetter(IntSetter.class.getName(), "intValue");
+ testClass.addSetter(IntArraySetter.class.getName(), "intValues");
+ testClass.addSetter(IntegerArraySetter.class.getName(), "integerValues");
+
+ return testClass.toBytecode();
+ } catch (InstrumentException e) {
+ throw new RuntimeException(e.getMessage(), e);
+ }
+ }
+ });
+
+ loader.initialize();
+
+ Object testObject = loader.loadClass(targetClassName).newInstance();
+
+ Class<?> intSetter = loader.loadClass(IntSetter.class.getName());
+ Class<?> intsSetter = loader.loadClass(IntArraySetter.class.getName());
+ Class<?> integersSetter = loader.loadClass(IntegerArraySetter.class.getName());
+
+ Assert.assertTrue(intSetter.isInstance(testObject));
+ Assert.assertTrue(intsSetter.isInstance(testObject));
+ Assert.assertTrue(integersSetter.isInstance(testObject));
+
+ int intValue = 99;
+ int[] intValues = {99, 100};
+ Integer[] integerValues = {99, 100};
+
+ Method setInt = intSetter.getMethod("_$PINPOINT$_setInt", int.class);
+ setInt.invoke(testObject, intValue);
+ Method getInt = testObject.getClass().getMethod("getIntValue");
+ Assert.assertEquals(intValue, getInt.invoke(testObject));
+
+ Method setInts = intsSetter.getMethod("_$PINPOINT$_setIntArray", int[].class);
+ setInts.invoke(testObject, intValues);
+ Method getInts = testObject.getClass().getMethod("getIntValues");
+ Assert.assertEquals(intValues, getInts.invoke(testObject));
+
+ Method setIntegers = integersSetter.getMethod("_$PINPOINT$_setIntegerArray", Integer[].class);
+ // wrap due to vararg expansion
+ Object[] wrappedIntegerValues = new Object[]{integerValues};
+ setIntegers.invoke(testObject, wrappedIntegerValues);
+ Method getIntegers = testObject.getClass().getMethod("getIntegerValues");
+ Assert.assertEquals(integerValues, getIntegers.invoke(testObject));
}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject3.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject3.java
index 8ee9b70e3b15..fb6549fe6706 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject3.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject3.java
@@ -21,6 +21,8 @@
public class TestObject3 {
private String value;
private int intValue;
+ private int[] intValues;
+ private Integer[] integerValues;
public void setValue(String value) {
this.value = value;
@@ -30,6 +32,14 @@ public void setIntValue(int value) {
this.intValue = value;
}
+ public void setIntValues(int[] values) {
+ this.intValues = values;
+ }
+
+ public void setIntegerValues(Integer[] values) {
+ this.integerValues = values;
+ }
+
@Override
public String toString() {
return value;
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject4.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject4.java
new file mode 100644
index 000000000000..ffd244e45fff
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject4.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.interceptor.bci;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class TestObject4 {
+ private int intValue;
+ private int[] intValues;
+ private Integer[] integerValues;
+
+ public int getIntValue() {
+ return this.intValue;
+ }
+
+ public int[] getIntValues() {
+ return this.intValues;
+ }
+
+ public Integer[] getIntegerValues() {
+ return this.integerValues;
+ }
+}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/JavaAssistUtilsTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/JavaAssistUtilsTest.java
index e9d97df81828..62f404196836 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/JavaAssistUtilsTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/util/JavaAssistUtilsTest.java
@@ -24,10 +24,10 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.navercorp.pinpoint.profiler.util.ApiUtils;
-import com.navercorp.pinpoint.profiler.util.JavaAssistUtils;
-
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
/**
* @author emeroad
@@ -71,6 +71,56 @@ public void javaArraySize() {
Assert.assertEquals(JavaAssistUtils.getJavaObjectArraySize("java.lang.String[][]"), 2);
}
+ @Test
+ public void javaClassNameToObjectName() {
+ // primitives
+ Assert.assertEquals("boolean", JavaAssistUtils.javaClassNameToObjectName(boolean.class.getName()));
+ Assert.assertEquals("byte", JavaAssistUtils.javaClassNameToObjectName(byte.class.getName()));
+ Assert.assertEquals("char", JavaAssistUtils.javaClassNameToObjectName(char.class.getName()));
+ Assert.assertEquals("double", JavaAssistUtils.javaClassNameToObjectName(double.class.getName()));
+ Assert.assertEquals("float", JavaAssistUtils.javaClassNameToObjectName(float.class.getName()));
+ Assert.assertEquals("int", JavaAssistUtils.javaClassNameToObjectName(int.class.getName()));
+ Assert.assertEquals("short", JavaAssistUtils.javaClassNameToObjectName(short.class.getName()));
+
+ // wrappers
+ Assert.assertEquals("java.lang.Integer", JavaAssistUtils.javaClassNameToObjectName(Integer.class.getName()));
+ Assert.assertEquals("java.lang.String", JavaAssistUtils.javaClassNameToObjectName(String.class.getName()));
+
+ // classes
+ Assert.assertEquals("java.util.List", JavaAssistUtils.javaClassNameToObjectName(List.class.getName()));
+ Assert.assertEquals("java.util.ArrayList", JavaAssistUtils.javaClassNameToObjectName(new ArrayList<Integer>().getClass().getName()));
+
+ // arrays
+ Assert.assertEquals("boolean[]", JavaAssistUtils.javaClassNameToObjectName(boolean[].class.getName()));
+ Assert.assertEquals("byte[]", JavaAssistUtils.javaClassNameToObjectName(byte[].class.getName()));
+ Assert.assertEquals("java.lang.String[]", JavaAssistUtils.javaClassNameToObjectName(String[].class.getName()));
+
+ // inner/nested classes
+ Assert.assertEquals(
+ this.getClass().getName() + "$1",
+ JavaAssistUtils.javaClassNameToObjectName(new Comparable<Long>() {
+ @Override
+ public int compareTo(Long o) {
+ return 0;
+ }
+ }.getClass().getName()));
+ class SomeComparable implements Comparable<Long> {
+ @Override
+ public int compareTo(Long o) {
+ return 0;
+ }
+ }
+ SomeComparable inner = new SomeComparable();
+ Assert.assertEquals(
+ this.getClass().getName() + "$1SomeComparable",
+ JavaAssistUtils.javaClassNameToObjectName(inner.getClass().getName())); // assume nothing else is defined in this class
+ Assert.assertEquals(
+ this.getClass().getName() + "$1SomeComparable[]",
+ JavaAssistUtils.javaClassNameToObjectName(new SomeComparable[] {inner}.getClass().getName()));
+ Assert.assertEquals("java.util.Map$Entry", JavaAssistUtils.javaClassNameToObjectName(Map.Entry.class.getName()));
+ Assert.assertEquals("java.util.Map$Entry[]", JavaAssistUtils.javaClassNameToObjectName(Map.Entry[].class.getName()));
+ }
+
@Test
public void toJvmSignature() {
| train | train | "2016-06-27T10:32:43" | "2016-06-28T07:28:53Z" | Xylus | test |
pinpoint-apm/pinpoint/2010_2011 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2010 | pinpoint-apm/pinpoint/2011 | [
"keyword_pr_to_issue"
] | 2e39615c5c4b283d821aa3dba607a5d6d3fd856b | b905ee487cdecf1b47b84ab7ed728bfe696934bc | [] | [] | "2016-08-25T03:06:18Z" | [
"bug"
] | Jdk's HttpUrlConnection's target nodes are not rendered in the server map | Http calls made using `HttpUrlConnection` is currently being traced, but the server map does not seem to be rendering the target nodes,
Related google groups post - https://groups.google.com/forum/#!topic/pinpoint_user/OgwAB9sPnak
| [
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpConstants.java"
] | [
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpConstants.java"
] | [] | diff --git a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpConstants.java b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpConstants.java
index 184baf89b519..3a6bfa4ea7a0 100644
--- a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpConstants.java
+++ b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpConstants.java
@@ -17,6 +17,8 @@
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.common.trace.ServiceTypeFactory;
+import static com.navercorp.pinpoint.common.trace.ServiceTypeProperty.RECORD_STATISTICS;
+
/**
* @author Jongho Moon
*
@@ -25,5 +27,5 @@ public final class JdkHttpConstants {
private JdkHttpConstants() {
}
- public static final ServiceType SERVICE_TYPE = ServiceTypeFactory.of(9055, "JDK_HTTPURLCONNECTOR", "JDK_HTTPCONNECTOR");
+ public static final ServiceType SERVICE_TYPE = ServiceTypeFactory.of(9055, "JDK_HTTPURLCONNECTOR", "JDK_HTTPCONNECTOR", RECORD_STATISTICS);
}
| null | train | train | "2016-08-24T10:44:14" | "2016-08-25T03:02:16Z" | Xylus | test |
pinpoint-apm/pinpoint/2072_2073 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2072 | pinpoint-apm/pinpoint/2073 | [
"keyword_pr_to_issue"
] | 13aff5f3d45377833ebfc79401a83266cc4de300 | 36fe15fafb7a11ecbcb536b3ec61aefa6ade0298 | [] | [] | "2016-09-08T02:16:55Z" | [
"bug"
] | MariaDB4j moved to maven central | MariaDB4j is now published to maven central, instead of the previous jcenter.bintray.
Dependency should be fixed accordingly.
Reported - https://groups.google.com/forum/#!topic/pinpoint_user/sasP_WVAOZM
| [
"agent/pom.xml"
] | [
"agent/pom.xml"
] | [
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_IT.java"
] | diff --git a/agent/pom.xml b/agent/pom.xml
index 2eec80ad79b7..0a345c5563c2 100644
--- a/agent/pom.xml
+++ b/agent/pom.xml
@@ -85,7 +85,7 @@
<dependency>
<groupId>ch.vorburger.mariaDB4j</groupId>
<artifactId>mariaDB4j</artifactId>
- <version>2.1.3</version>
+ <version>2.2.2</version>
<scope>test</scope>
</dependency>
| diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java
index 8ceeee24d745..c1a855fc2491 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java
@@ -13,12 +13,10 @@
import com.navercorp.pinpoint.test.plugin.Dependency;
import com.navercorp.pinpoint.test.plugin.JvmVersion;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
-import com.navercorp.pinpoint.test.plugin.Repository;
@RunWith(PinpointPluginTestSuite.class)
@JvmVersion(7)
-@Repository("http://jcenter.bintray.com")
-@Dependency({"org.mariadb.jdbc:mariadb-java-client:[1.3.0,1.3.max]", "ch.vorburger.mariaDB4j:mariaDB4j:2.1.3"})
+@Dependency({"org.mariadb.jdbc:mariadb-java-client:[1.3.0,1.3.max]", "ch.vorburger.mariaDB4j:mariaDB4j:2.2.2"})
public class MariaDB_1_3_x_IT extends MariaDB_IT_Base {
// see CallableParameterMetaData#queryMetaInfos
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_IT.java
index 76fd14be8c25..44f96058386b 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_IT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_IT.java
@@ -21,7 +21,6 @@
import com.navercorp.pinpoint.test.plugin.Dependency;
import com.navercorp.pinpoint.test.plugin.JvmVersion;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
-import com.navercorp.pinpoint.test.plugin.Repository;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -36,8 +35,7 @@
@RunWith(PinpointPluginTestSuite.class)
@JvmVersion(7)
-@Repository("http://jcenter.bintray.com")
-@Dependency({ "org.mariadb.jdbc:mariadb-java-client:[1.4.min,1.4.max]", "ch.vorburger.mariaDB4j:mariaDB4j:2.1.3" })
+@Dependency({ "org.mariadb.jdbc:mariadb-java-client:[1.4.min,1.4.max]", "ch.vorburger.mariaDB4j:mariaDB4j:2.2.2" })
public class MariaDB_1_4_x_IT extends MariaDB_IT_Base {
// see CallableParameterMetaData#queryMetaInfos
| val | train | "2016-09-07T11:45:59" | "2016-09-08T01:59:29Z" | Xylus | test |
pinpoint-apm/pinpoint/2077_2078 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2077 | pinpoint-apm/pinpoint/2078 | [
"keyword_pr_to_issue"
] | 0f94b21205ca84f01d18283b381615f5e88f3f55 | 4f7a442ae4ffb00b4a14e06a9cb46455c173cb09 | [] | [] | "2016-09-08T09:16:21Z" | [
"bug"
] | Tomcat plugin fails to trace when profiler.tomcat.excludeurl is empty | Tomcat plugin fails to inject interceptor to `StandardHostValve.invoke(...)` when _pinpoint.config_'s `profiler.tomcat.excludeurl` option is empty.
| [
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfiguration.java"
] | [
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfiguration.java"
] | [] | diff --git a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfiguration.java b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfiguration.java
index 0c0ba3bfcf18..3f7e8089f61f 100644
--- a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfiguration.java
+++ b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfiguration.java
@@ -14,9 +14,9 @@
*/
package com.navercorp.pinpoint.plugin.tomcat;
-import com.navercorp.pinpoint.bootstrap.config.ExcludePathFilter;
import com.navercorp.pinpoint.bootstrap.config.Filter;
import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
+import com.navercorp.pinpoint.bootstrap.config.SkipFilter;
/**
* @author Jongho Moon
@@ -24,14 +24,14 @@
*/
public class TomcatConfiguration {
private final boolean tomcatHidePinpointHeader;
- private Filter<String> tomcatExcludeUrlFilter;
+ private final Filter<String> tomcatExcludeUrlFilter;
public TomcatConfiguration(ProfilerConfig config) {
this.tomcatHidePinpointHeader = config.readBoolean("profiler.tomcat.hidepinpointheader", true);
- final String tomcatExcludeURL = config.readString("profiler.tomcat.excludeurl", "");
-
- if (!tomcatExcludeURL.isEmpty()) {
- this.tomcatExcludeUrlFilter = new ExcludePathFilter(tomcatExcludeURL);
+ if (config.getTomcatExcludeProfileMethodFilter() == null) {
+ this.tomcatExcludeUrlFilter = new SkipFilter<String>();
+ } else {
+ this.tomcatExcludeUrlFilter = config.getTomcatExcludeUrlFilter();
}
}
| null | val | train | "2016-09-08T07:52:34" | "2016-09-08T08:51:22Z" | Xylus | test |
pinpoint-apm/pinpoint/2106_2110 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2106 | pinpoint-apm/pinpoint/2110 | [
"keyword_issue_to_pr"
] | 48ab977b9cabf40c9e3629f67dff7243f5a373a6 | 54f35e108e29a92db1d5df1f832b95ae0a1ccb3a | [
"**The thrift plugin has been enabled , while it can not trace the data.** \n\nprofiler.thrift.client=true\nprofiler.thrift.client.async=true\nprofiler.thrift.processor=true\nprofiler.thrift.processor.async=true\nprofiler.thrift.service.args=true\nprofiler.thrift.service.result=true\n",
"Hi duwupeng,\nCould you give a short explanation on how you defined your processors? Are you using the default processor auto-generated from the IDL?\n",
"Hell Xylus ,\nThanks for four reply。\n As you said , we defined the processors using the thrift Compiler (0.9.2) from IDL, and the services has been brought up by the TThreadedSelectorServer in a java main process. \n",
"Hmm..that's weird, will definitely need to look into it further.\nCould you post the agent log please? It should be under '$AGENT_DIR/logs' directory.\nThanks!\n",
"sure. The the agent log and processor are as below. \n\n**1. The agent log:**\n\n```\n2016-09-26 18:55:56 [DEBUG](c.n.p.p.t.i.s.ProcessFunctionProcessInterceptor:96 ) BEFORE com.kuaisu.infra.thrift.service.HeartBeatService$Processor$hello args:(1, StoredMessageProtocol, TCompactProtocol, HeartBeatServiceImpl)\n2016-09-26 18:55:56 [DEBUG](c.n.p.p.t.i.s.ProcessFunctionProcessInterceptor:288) Invalid target object. Need field accessor(com.navercorp.pinpoint.plugin.thrift.field.accessor.ServerMarkerFlagFieldAccessor).\n2016-09-26 18:55:56 [DEBUG](c.n.p.p.t.i.t.s.TProtocolReadFieldBeginInterceptor:121) AFTER org.apache.thrift.protocol.TCompactProtocol args:() result:TField\n2016-09-26 18:55:56 [DEBUG](c.n.p.p.t.i.t.s.TProtocolReadMessageEndInterceptor:121) AFTER org.apache.thrift.protocol.TCompactProtocol args:() result:null\n2016-09-26 18:55:56 [DEBUG](c.n.p.b.i.s.ScopedInterceptor :298) tryBefore() returns false: interceptorScopeTransaction: InterceptorScopeInvocation(ThriftClientScope)[depth=0], executionPoint: INTERNAL. Skip interceptor class com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.client.TProtocolWriteFieldStopInterceptor\n2016-09-26 18:55:56 [DEBUG](c.n.p.b.i.s.ScopedInterceptor :298) tryAfter() returns false: interceptorScopeTransaction: InterceptorScopeInvocation(ThriftClientScope)[depth=0], executionPoint: INTERNAL. Skip interceptor class com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.client.TProtocolWriteFieldStopInterceptor\n2016-09-26 18:55:56 [DEBUG](c.n.p.p.t.i.s.ProcessFunctionProcessInterceptor:121) AFTER com.kuaisu.infra.thrift.service.HeartBeatService$Processor$hello args:(1, StoredMessageProtocol, TCompactProtocol, HeartBeatServiceImpl) result:null\n2016-09-26 18:55:56 [DEBUG](c.n.p.b.i.s.ScopedInterceptor :298) tryBefore() returns false: interceptorScopeTransaction: InterceptorScopeInvocation(ThriftServerScope)[depth=0], executionPoint: INTERNAL. Skip interceptor class com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadMessageBeginInterceptor\n2016-09-26 18:55:56 [DEBUG](c.n.p.b.i.s.ScopedInterceptor :298) tryAfter() returns false: interceptorScopeTransaction: InterceptorScopeInvocation(ThriftServerScope)[depth=0], executionPoint: INTERNAL. Skip interceptor class com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadMessageBeginInterceptor\n```\n\n**2. The processor :**\n /**\n- Autogenerated by Thrift Compiler (0.9.2)\n *\n- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n- @generated\n */\n package com.kuaisu.infra.thrift.service;\n\nimport org.apache.thrift.TException;\nimport org.apache.thrift.async.AsyncMethodCallback;\nimport org.apache.thrift.protocol.TTupleProtocol;\nimport org.apache.thrift.scheme.IScheme;\nimport org.apache.thrift.scheme.SchemeFactory;\nimport org.apache.thrift.scheme.StandardScheme;\nimport org.apache.thrift.scheme.TupleScheme;\nimport org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.annotation.Generated;\nimport java.util.*;\n\n@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.2)\", date = \"2015-5-27\")\npublic class HeartBeatService {\n\n /**\n- Common interface\n */\n public interface Iface {\n \n /**\n - Heart Beart\n */\n public void hello() throws org.apache.thrift.TException;\n \n }\n \n public interface AsyncIface {\n \n public void hello(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\n \n }\n \n public static class Client extends org.apache.thrift.TServiceClient implements Iface {\n public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {\n public Factory() {}\n public Client getClient(org.apache.thrift.protocol.TProtocol prot) {\n return new Client(prot);\n }\n public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\n return new Client(iprot, oprot);\n }\n }\n ...\n",
"@duwupeng It looks like you're using `TTupleProtocol`, and unfortunately I don't think the Thrift plugin supports tracing it (I think only the `TBinaryProtocol`, `TCompactProtocol`, and `TJSONProtocol` are supported currently). There probably was a reason why I left `TTupleProtocol` out but I don't quite remember exactly why as it's been a while since I developed it. I'll look into this so that I can give you a better answer.\n\nIn the mean time, you could try adding `TTupleProtocol` support yourself if you're building from source (master).\nSimply add `addTProtocolInterceptors(config, \"org.apache.thrift.protocol.TTupleProtocol\");` to [ThriftPlugin.java](https://github.com/naver/pinpoint/blob/master/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java#L420) and build the _plugins_ and _agent_ module. Then use this agent and see if it works.\n",
"@Xylus , Thanks a lot for you investigation . and I am afraid that I am using the TCompactProtocol\nThe following is my app server . \n\n```\nimport org.apache.thrift.TMultiplexedProcessor;\nimport org.apache.thrift.TProcessor;\nimport org.apache.thrift.protocol.TCompactProtocol;\nimport org.apache.thrift.protocol.TProtocolFactory;\nimport org.apache.thrift.server.TServer;\nimport org.apache.thrift.server.TThreadedSelectorServer;\nimport org.apache.thrift.transport.TFramedTransport;\nimport org.apache.thrift.transport.TNonblockingServerSocket;\nimport org.apache.thrift.transport.TNonblockingServerTransport;\nimport org.apache.thrift.transport.TTransportFactory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport java.util.concurrent.*;\nimport java.util.concurrent.atomic.AtomicInteger;\npublic class AppServer {\n protected static ClassPathXmlApplicationContext context;\n public static void main(String[] args) {\n String logDir = System.getProperty(\"log.dir\");\n if (logDir == null) {\n System.setProperty(\"log.dir\", \".\");\n }\n final Logger logger = LoggerFactory.getLogger(AppServer.class);\n PropertyConfigurator.configure(AppServer.class.getClassLoader().getResource(\"logback.xml\"));\n context = new ClassPathXmlApplicationContext(\"spring/root.xml\");\n SpringInstanceProvider provider = new SpringInstanceProvider(context);\n InstanceFactory.setInstanceProvider(provider);\n\n Integer port = (Integer) context.getBean(\"port\");\n System.setProperty(\"serverPort\", String.valueOf(port));\n\n logger.info(\"serverPort:{}\", port);\n\n try {\n TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(port);\n\n TTransportFactory transportFactory = new TFramedTransport.Factory();\n\n TProtocolFactory proFactory = new TCompactProtocol.Factory();\n\n TMultiplexedProcessor processor = new TMultiplexedProcessor();\n\n String[] strings = context.getBeanNamesForType(org.apache.thrift.TProcessor.class);\n for (String beanName : strings) {\n TProcessor bean = (TProcessor) context.getBean(beanName);\n if (bean == null) {\n logger.warn(\">>>>{}<<<<Register failed\", beanName);\n continue;\n }\n beanName = bean.toString().split(\"\\\\$\")[0];\n beanName = beanName.substring(beanName.lastIndexOf(\".\") + 1);\n\n logger.info(\"registerProcessor:{}\", beanName);\n processor.registerProcessor(beanName, bean);\n }\n\n int corePoolSize = 100;\n int maximumPoolSize = 200;\n long keepAliveTime = 60;\n TimeUnit unit = TimeUnit.SECONDS;\n BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(50);\n ThreadFactory threadFactory = new DefaultThreadFactory();\n\n ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);\n\n TThreadedSelectorServer.Args args1 = new TThreadedSelectorServer.Args(serverTransport)\n .protocolFactory(proFactory)\n .transportFactory(transportFactory)\n .processor(processor)\n //.workerThreads(35)\n //.acceptQueueSizePerThread(30)\n .executorService(poolExecutor);\n\n args1.maxReadBufferBytes = 1024 * 1024 * 5; // 5M\n\n //Create the server\n TServer server = new TThreadedSelectorServer(args1);\n\n logger.info(\"Start server on port {}...\", port);\n RunModeHelper.initStart();\n server.serve();\n } catch (Exception e) {\n logger.error(e.getMessage(), e);\n }\n }\n static class DefaultThreadFactory implements ThreadFactory {\n final AtomicInteger threadNumber = new AtomicInteger(1);\n\n public Thread newThread(Runnable r) {\n return new Thread(r, \"ks-trans-\" + threadNumber.getAndIncrement());\n }\n }\n}\n```\n",
"@duwupeng Ah I see! Thanks for the code example.\nI'll test it out and figure out why it's not being traced.\n",
"@Xylus , Thanks a lot, looking forward to your further reply\nAnd I would like to provide the URL that wish you can accesss.\nhttp://120.25.79.51:10128/stat.html.\nI am with the trouble of tracing the **sandbox4-ksservices** which is the thrift Server. \n",
"@duwupeng \nLooks like it's because we don't have support for `TMultiplexedProcessor` yet.\nWe'll take a look at adding support for `TMultiplexedProcessor` but it'll take some time.\n\nIf you can, could you try testing it by registering a `TProcessor` object directly to the server and see if that works?\n",
"@duwupeng So upon further inspection, the actual culprit of all this was that when using `TMultiplexedProcessor`, the actual input protocol is wrapped by `TMultiplexedProcessor$StoredMessageProtocol`.\nSo when `ProcessFunction.process()` is invoked, the interceptor injects the server marker into this decorated object and not the actual input protocol, stopping any trace from being generated.\n\nYou can test this out once #2110 is merged if you're building from source.\nLet me know if anything looks weird.\n\nThanks!\n",
"@duwupeng With the latest source, you should now be able to trace your application.\nPlease reopen the issue if you have more questions.\n",
"Yep I have tried 1.6.0, it worked.",
"@DevotedTangLiu Awesome, thanks for testing this out! Please let us know if there's anything broken."
] | [] | "2016-09-28T07:48:03Z" | [
"help wanted"
] | Can we trace the standlone thrift RPC server? | Hi All,
First of all, Thank you so much for the lovely tool. I have gone through it and found really interesting.
I have checked this by configuring agent on Tomcat and it's showing more than I expected.
Now, The question is :- Can we trace the thrift RPC client and server?
I look forward for your response.
Cheers,
duwupeng
2016-09-26 17:49:03 [DEBUG](c.n.p.b.i.s.ScopedInterceptor :298) tryBefore() returns false: interceptorScopeTransaction: InterceptorScopeInvocation(ThriftClientScope)[depth=0], executionPoint: INTERNAL. Skip interceptor class com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.client.TProtocolWriteFieldStopInterceptor
2016-09-26 17:49:03 [DEBUG](c.n.p.b.i.s.ScopedInterceptor :298) tryAfter() returns false: interceptorScopeTransaction: InterceptorScopeInvocation(ThriftClientScope)[depth=0], executionPoint: INTERNAL. Skip interceptor class com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.client.TProtocolWriteFieldStopInterceptor
| [
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/ProcessFunctionProcessInterceptor.java"
] | [
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/field/getter/TProtocolFieldGetter.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/ProcessFunctionProcessInterceptor.java"
] | [] | diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java
index 6f4c7fdf3dd2..ca70c0df91b0 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java
@@ -67,4 +67,5 @@ private ThriftConstants() {
private static final String FIELD_GETTER_BASE = "com.navercorp.pinpoint.plugin.thrift.field.getter.";
public static final String FIELD_GETTER_T_NON_BLOCKING_TRANSPORT = FIELD_GETTER_BASE + "TNonblockingTransportFieldGetter";
public static final String FIELD_GETTER_T_TRANSPORT = FIELD_GETTER_BASE + "TTransportFieldGetter";
+ public static final String FIELD_GETTER_T_PROTOCOL = FIELD_GETTER_BASE + "TProtocolFieldGetter";
}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java
index 47afb2694ec3..e8a24dbfefab 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java
@@ -418,6 +418,7 @@ private void addTProtocolEditors(ThriftPluginConfig config) {
addTProtocolInterceptors(config, "org.apache.thrift.protocol.TBinaryProtocol");
addTProtocolInterceptors(config, "org.apache.thrift.protocol.TCompactProtocol");
addTProtocolInterceptors(config, "org.apache.thrift.protocol.TJSONProtocol");
+ addTProtocolDecoratorEditor();
}
private void addTProtocolInterceptors(ThriftPluginConfig config, String tProtocolClassName) {
@@ -485,6 +486,20 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
});
}
+ private void addTProtocolDecoratorEditor() {
+ transformTemplate.transform("org.apache.thrift.protocol.TProtocolDecorator", new TransformCallback() {
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined,
+ ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+
+ final InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+
+ target.addGetter(ThriftConstants.FIELD_GETTER_T_PROTOCOL, "concreteProtocol");
+ return target.toBytecode();
+ }
+ });
+ }
+
@Override
public void setTransformTemplate(TransformTemplate transformTemplate) {
this.transformTemplate = transformTemplate;
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/field/getter/TProtocolFieldGetter.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/field/getter/TProtocolFieldGetter.java
new file mode 100644
index 000000000000..224af69a451a
--- /dev/null
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/field/getter/TProtocolFieldGetter.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.thrift.field.getter;
+
+import org.apache.thrift.protocol.TProtocol;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface TProtocolFieldGetter {
+ TProtocol _$PINPOINT$_getTProtocol();
+}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/ProcessFunctionProcessInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/ProcessFunctionProcessInterceptor.java
index 102a3b0d1328..c4c85fce2f88 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/ProcessFunctionProcessInterceptor.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/ProcessFunctionProcessInterceptor.java
@@ -19,6 +19,7 @@
import static com.navercorp.pinpoint.plugin.thrift.ThriftScope.THRIFT_SERVER_SCOPE;
import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope;
+import com.navercorp.pinpoint.plugin.thrift.field.getter.TProtocolFieldGetter;
import org.apache.thrift.ProcessFunction;
import org.apache.thrift.protocol.TProtocol;
@@ -82,8 +83,10 @@ public void before(Object target, Object[] args) {
// When this happens, TProtocol interceptors for clients are triggered since technically they're still within THRIFT_SERVER_SCOPE.
// We set the marker inside server's input protocol to safeguard against such cases.
Object iprot = args[1];
- if (validateInputProtocol(iprot)) {
- ((ServerMarkerFlagFieldAccessor)iprot)._$PINPOINT$_setServerMarkerFlag(true);
+ // With the addition of TProtocolDecorator, iprot may actually be a wrapper around the actual input protocol
+ Object rootInputProtocol = getRootInputProtocol(iprot);
+ if (validateInputProtocol(rootInputProtocol)) {
+ ((ServerMarkerFlagFieldAccessor)rootInputProtocol)._$PINPOINT$_setServerMarkerFlag(true);
}
}
@@ -101,6 +104,14 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
}
}
+ private Object getRootInputProtocol(Object iprot) {
+ if (iprot instanceof TProtocolFieldGetter) {
+ return getRootInputProtocol(((TProtocolFieldGetter) iprot)._$PINPOINT$_getTProtocol());
+ } else {
+ return iprot;
+ }
+ }
+
private boolean validateInputProtocol(Object iprot) {
if (iprot instanceof TProtocol) {
if (iprot instanceof ServerMarkerFlagFieldAccessor) {
| null | val | train | "2016-09-26T02:34:52" | "2016-09-26T09:50:50Z" | duwupeng | test |
pinpoint-apm/pinpoint/1482_2167 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1482 | pinpoint-apm/pinpoint/2167 | [
"keyword_pr_to_issue"
] | 56f53d5130fe8ff1c7f5bd06f8f950fd75b6cef0 | 4cf078d62c71e128fe34a928be131b9460cb6fe7 | [] | [] | "2016-10-18T08:10:36Z" | [
"bug"
] | [PinpiontWeb] fix a ActiveThread concurrency problem | If multiple threads invokes WebSocketSession's sendMessage method at the same time, ;
then it is possible to makes IllegalStateException.
| [
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
index 2b865789c33f..8da38eea614e 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
@@ -214,7 +214,11 @@ private void handleRequestMessage0(WebSocketSession webSocketSession, RequestMes
}
unbindingResponseAggregator(webSocketSession);
- bindingResponseAggregator(webSocketSession, applicationName);
+ if (webSocketSession.isOpen()) {
+ bindingResponseAggregator(webSocketSession, applicationName);
+ } else {
+ logger.warn("WebSocketSession is not opened. skip binding.");
+ }
}
}
}
| null | test | train | "2016-10-18T04:31:59" | "2016-01-25T05:29:30Z" | koo-taejin | test |
pinpoint-apm/pinpoint/2178_2179 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2178 | pinpoint-apm/pinpoint/2179 | [
"keyword_pr_to_issue"
] | 387b127dc729016923d0528c424b5c03b8d973e2 | 187c315e116e8f869717e575a014c2a6c8202bc6 | [] | [] | "2016-10-20T07:19:28Z" | [
"enhancement"
] | Allow conditional registration of transformers for when JBoss and Tomcat plugins are both enabled | JBoss and Tomcat plugins both add transformers for `org.apache.catalina.core.StandardHostValve`.
When both plugins are enabled, the agent throws an exception, complaining that there are more than 1 transformer for the class and it does not know which one to use for instrumentation.
The best solution would be to have the agent "automagically" figure out which transformer to use when the class is loaded, but this is currently out of reach.
Instead, we'll simply (and crudely) add conditional checks that does the following:
- If the application is a Tomcat application, or a SpringBoot application (launched by their respective main-classes), add Tomcat transformers.
- If the application is a JBoss application, add JBoss transformers.
There should also be an option that disables these checks completely in _pinpoint.config_ - `profiler.tomcat.conditional.transform`, `profiler.jboss.conditional.transform`.
One drawback to the solution above would be that standalone applications that run embedded Tomcat (or SpringBoot applications running Tomcat launched from an IDE) will not automatically register Tomcat transformers for their relevant classes. For such cases, `profiler.tomcat.conditional.transform` should be set to `false`.
| [
"agent/src/main/resources-local/pinpoint.config",
"agent/src/main/resources-release/pinpoint.config",
"agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config",
"plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossConfig.java",
"plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossPlugin.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfig.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java",
"quickstart/agent/src/main/resources/pinpoint.config",
"quickstart/conf/pinpoint.config"
] | [
"agent/src/main/resources-local/pinpoint.config",
"agent/src/main/resources-release/pinpoint.config",
"agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config",
"plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossConfig.java",
"plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossPlugin.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfig.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java",
"quickstart/agent/src/main/resources/pinpoint.config",
"quickstart/conf/pinpoint.config"
] | [
"agent/src/test/resources/activemq/client/pinpoint-activemq-client.config",
"agent/src/test/resources/pinpoint-disabled-plugin-test.config",
"agent/src/test/resources/pinpoint-spring-bean-test.config",
"plugins/google-httpclient/src/test/resources/pinpoint.config",
"plugins/httpclient3/src/test/resources/pinpoint.config",
"plugins/httpclient4/src/test/resources/pinpoint.config",
"plugins/jboss/src/test/resources/pinpoint.config",
"plugins/redis/src/test/resources/pinpoint.config",
"plugins/tomcat/src/test/resources/pinpoint.config",
"plugins/user/src/test/resources/pinpoint.config",
"profiler-optional/profiler-optional-jdk8/src/test/resources/pinpoint-lambda-test.config",
"profiler/src/test/resources/pinpoint-spring-bean-test.config",
"profiler/src/test/resources/pinpoint.config"
] | diff --git a/agent/src/main/resources-local/pinpoint.config b/agent/src/main/resources-local/pinpoint.config
index 265767ad7530..54a256029d61 100644
--- a/agent/src/main/resources-local/pinpoint.config
+++ b/agent/src/main/resources-local/pinpoint.config
@@ -120,9 +120,17 @@ profiler.entrypoint=
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
+# HTTP Request methods to exclude from tracing
+#profiler.tomcat.excludemethod=
profiler.tomcat.tracerequestparam=true
# original IP address header
@@ -140,6 +148,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -154,9 +163,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/agent/src/main/resources-release/pinpoint.config b/agent/src/main/resources-release/pinpoint.config
index 4ebec25be7f5..d0e655c8d090 100644
--- a/agent/src/main/resources-release/pinpoint.config
+++ b/agent/src/main/resources-release/pinpoint.config
@@ -116,8 +116,14 @@ profiler.entrypoint=
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -136,6 +142,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -150,9 +157,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config b/agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config
index 44faab44b9b5..f7189b224f9b 100644
--- a/agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config
+++ b/agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config
@@ -107,8 +107,14 @@ profiler.entrypoint=
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -127,6 +133,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -141,9 +148,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossConfig.java b/plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossConfig.java
index dd7ab00fcdad..548ff6fd041f 100644
--- a/plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossConfig.java
+++ b/plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossConfig.java
@@ -42,6 +42,7 @@ public class JbossConfig {
private final boolean jbossEnable;
private final List<String> jbossBootstrapMains;
+ private final boolean jbossConditionalTransformEnable;
private final String jbossRealIpHeader;
private final String jbossRealIpEmptyValue;
@@ -58,6 +59,7 @@ public JbossConfig(final ProfilerConfig config) {
this.jbossTraceEjb = config.readBoolean("profiler.jboss.traceEjb", false);
this.jbossBootstrapMains = config.readList("profiler.jboss.bootstrap.main");
+ this.jbossConditionalTransformEnable = config.readBoolean("profiler.jboss.conditional.transform", true);
this.jbossHidePinpointHeader = config.readBoolean("profiler.jboss.hidepinpointheader", true);
this.jbossTraceRequestParam = config.readBoolean("profiler.jboss.tracerequestparam", true);
@@ -86,6 +88,10 @@ public List<String> getJbossBootstrapMains() {
return jbossBootstrapMains;
}
+ public boolean isJbossConditionalTransformEnable() {
+ return jbossConditionalTransformEnable;
+ }
+
/**
* Checks if is jboss hide pinpoint header.
*
diff --git a/plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossPlugin.java b/plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossPlugin.java
index e9388f596ea8..e071ebbd21f8 100644
--- a/plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossPlugin.java
+++ b/plugins/jboss/src/main/java/com/navercorp/pinpoint/plugin/jboss/JbossPlugin.java
@@ -28,6 +28,7 @@
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPlugin;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPluginSetupContext;
+import com.navercorp.pinpoint.bootstrap.resolver.ConditionProvider;
/**
* The Class JbossPlugin.
@@ -61,6 +62,26 @@ public void setup(final ProfilerPluginSetupContext context) {
JbossDetector jbossDetector = new JbossDetector(jbossConfig.getJbossBootstrapMains());
context.addApplicationTypeDetector(jbossDetector);
+ if (shouldAddTransformers(jbossConfig)) {
+ logger.info("Adding JBoss transformers");
+ addTransformers(jbossConfig);
+ } else {
+ logger.info("Not adding JBoss transformers");
+ }
+ }
+
+ private boolean shouldAddTransformers(JbossConfig jbossConfig) {
+ // Transform if conditional check is disabled
+ if (!jbossConfig.isJbossConditionalTransformEnable()) {
+ return true;
+ }
+ // Only transform if it's a JBoss application
+ ConditionProvider conditionProvider = ConditionProvider.DEFAULT_CONDITION_PROVIDER;
+ boolean isJbossApplication = conditionProvider.checkMainClass(jbossConfig.getJbossBootstrapMains());
+ return isJbossApplication;
+ }
+
+ private void addTransformers(JbossConfig jbossConfig) {
// Instrumenting class on the base of ejb based application or rest based application.
if (jbossConfig.isJbossTraceEjb()) {
addMethodInvocationMessageHandlerEditor();
diff --git a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfig.java b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfig.java
index 87d7ad6a37dd..56c63e8eed04 100644
--- a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfig.java
+++ b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatConfig.java
@@ -32,6 +32,7 @@ public class TomcatConfig {
private final boolean tomcatEnable;
private final List<String> tomcatBootstrapMains;
+ private final boolean tomcatConditionalTransformEnable;
private final boolean tomcatHidePinpointHeader;
private final boolean tomcatTraceRequestParam;
@@ -40,6 +41,9 @@ public class TomcatConfig {
private final String tomcatRealIpEmptyValue;
private final Filter<String> tomcatExcludeProfileMethodFilter;
+ // for transform conditional check
+ private final List<String> springBootBootstrapMains;
+
public TomcatConfig(ProfilerConfig config) {
if (config == null) {
throw new NullPointerException("config must not be null");
@@ -48,6 +52,7 @@ public TomcatConfig(ProfilerConfig config) {
// plugin
this.tomcatEnable = config.readBoolean("profiler.tomcat.enable", true);
this.tomcatBootstrapMains = config.readList("profiler.tomcat.bootstrap.main");
+ this.tomcatConditionalTransformEnable = config.readBoolean("profiler.tomcat.conditional.transform", true);
this.tomcatHidePinpointHeader = config.readBoolean("profiler.tomcat.hidepinpointheader", true);
// runtime
@@ -67,6 +72,8 @@ public TomcatConfig(ProfilerConfig config) {
} else {
this.tomcatExcludeProfileMethodFilter = new SkipFilter<String>();
}
+
+ this.springBootBootstrapMains = config.readList("profiler.springboot.bootstrap.main");
}
public boolean isTomcatEnable() {
@@ -77,6 +84,10 @@ public List<String> getTomcatBootstrapMains() {
return tomcatBootstrapMains;
}
+ public boolean isTomcatConditionalTransformEnable() {
+ return tomcatConditionalTransformEnable;
+ }
+
public boolean isTomcatHidePinpointHeader() {
return tomcatHidePinpointHeader;
}
@@ -101,12 +112,16 @@ public Filter<String> getTomcatExcludeProfileMethodFilter() {
return tomcatExcludeProfileMethodFilter;
}
+ public List<String> getSpringBootBootstrapMains() {
+ return springBootBootstrapMains;
+ }
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("TomcatConfig{");
sb.append("tomcatEnable=").append(tomcatEnable);
sb.append(", tomcatBootstrapMains=").append(tomcatBootstrapMains);
+ sb.append(", tomcatConditionalTransformEnable=").append(tomcatConditionalTransformEnable);
sb.append(", tomcatHidePinpointHeader=").append(tomcatHidePinpointHeader);
sb.append(", tomcatTraceRequestParam=").append(tomcatTraceRequestParam);
sb.append(", tomcatExcludeUrlFilter=").append(tomcatExcludeUrlFilter);
diff --git a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java
index fe3344b7c1b3..308c07e80584 100644
--- a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java
+++ b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/TomcatPlugin.java
@@ -29,6 +29,7 @@
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPlugin;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPluginSetupContext;
+import com.navercorp.pinpoint.bootstrap.resolver.ConditionProvider;
/**
* @author Jongho Moon
@@ -61,6 +62,27 @@ public void setup(ProfilerPluginSetupContext context) {
TomcatDetector tomcatDetector = new TomcatDetector(config.getTomcatBootstrapMains());
context.addApplicationTypeDetector(tomcatDetector);
+ if (shouldAddTransformers(config)) {
+ logger.info("Adding Tomcat transformers");
+ addTransformers(config);
+ } else {
+ logger.info("Not adding Tomcat transfomers");
+ }
+ }
+
+ private boolean shouldAddTransformers(TomcatConfig config) {
+ // Transform if conditional check is disabled
+ if (!config.isTomcatConditionalTransformEnable()) {
+ return true;
+ }
+ // Only transform if it's a Tomcat application or SpringBoot application
+ ConditionProvider conditionProvider = ConditionProvider.DEFAULT_CONDITION_PROVIDER;
+ boolean isTomcatApplication = conditionProvider.checkMainClass(config.getTomcatBootstrapMains());
+ boolean isSpringBootApplication = conditionProvider.checkMainClass(config.getSpringBootBootstrapMains());
+ return isTomcatApplication || isSpringBootApplication;
+}
+
+ private void addTransformers(TomcatConfig config) {
if (config.isTomcatHidePinpointHeader()) {
addRequestFacadeEditor();
}
diff --git a/quickstart/agent/src/main/resources/pinpoint.config b/quickstart/agent/src/main/resources/pinpoint.config
index e08a6947c0b5..965997a52c8a 100644
--- a/quickstart/agent/src/main/resources/pinpoint.config
+++ b/quickstart/agent/src/main/resources/pinpoint.config
@@ -74,8 +74,14 @@ profiler.entrypoint=
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -94,6 +100,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -108,9 +115,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/quickstart/conf/pinpoint.config b/quickstart/conf/pinpoint.config
index bb3ec20b4973..271de615831e 100644
--- a/quickstart/conf/pinpoint.config
+++ b/quickstart/conf/pinpoint.config
@@ -73,8 +73,14 @@ profiler.include=
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -93,6 +99,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -107,9 +114,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
| diff --git a/agent/src/test/resources/activemq/client/pinpoint-activemq-client.config b/agent/src/test/resources/activemq/client/pinpoint-activemq-client.config
index b63689c79753..4714a421dad8 100644
--- a/agent/src/test/resources/activemq/client/pinpoint-activemq-client.config
+++ b/agent/src/test/resources/activemq/client/pinpoint-activemq-client.config
@@ -101,8 +101,14 @@ profiler.entrypoint=
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -121,6 +127,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -135,9 +142,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/agent/src/test/resources/pinpoint-disabled-plugin-test.config b/agent/src/test/resources/pinpoint-disabled-plugin-test.config
index bfebde28776e..26d06b8aacdf 100644
--- a/agent/src/test/resources/pinpoint-disabled-plugin-test.config
+++ b/agent/src/test/resources/pinpoint-disabled-plugin-test.config
@@ -78,8 +78,14 @@ profiler.include=
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -98,6 +104,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -112,9 +119,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/agent/src/test/resources/pinpoint-spring-bean-test.config b/agent/src/test/resources/pinpoint-spring-bean-test.config
index 570e16c0b06f..8293feca11d2 100644
--- a/agent/src/test/resources/pinpoint-spring-bean-test.config
+++ b/agent/src/test/resources/pinpoint-spring-bean-test.config
@@ -77,8 +77,14 @@ profiler.include=
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -97,6 +103,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -111,9 +118,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/plugins/google-httpclient/src/test/resources/pinpoint.config b/plugins/google-httpclient/src/test/resources/pinpoint.config
index 65785e99a9a2..9aa7a20f71ac 100644
--- a/plugins/google-httpclient/src/test/resources/pinpoint.config
+++ b/plugins/google-httpclient/src/test/resources/pinpoint.config
@@ -67,8 +67,14 @@ profiler.include=com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpo
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -87,6 +93,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -101,9 +108,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/plugins/httpclient3/src/test/resources/pinpoint.config b/plugins/httpclient3/src/test/resources/pinpoint.config
index b1d906d2a2d2..d9341029f156 100644
--- a/plugins/httpclient3/src/test/resources/pinpoint.config
+++ b/plugins/httpclient3/src/test/resources/pinpoint.config
@@ -67,8 +67,14 @@ profiler.include=com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpo
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -87,6 +93,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -101,9 +108,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/plugins/httpclient4/src/test/resources/pinpoint.config b/plugins/httpclient4/src/test/resources/pinpoint.config
index b1d906d2a2d2..d9341029f156 100644
--- a/plugins/httpclient4/src/test/resources/pinpoint.config
+++ b/plugins/httpclient4/src/test/resources/pinpoint.config
@@ -67,8 +67,14 @@ profiler.include=com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpo
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -87,6 +93,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -101,9 +108,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/plugins/jboss/src/test/resources/pinpoint.config b/plugins/jboss/src/test/resources/pinpoint.config
index 0bcbaf8c550f..d9a73913980f 100644
--- a/plugins/jboss/src/test/resources/pinpoint.config
+++ b/plugins/jboss/src/test/resources/pinpoint.config
@@ -71,8 +71,14 @@ profiler.include=com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpo
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -91,6 +97,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -108,6 +115,25 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=false
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/plugins/redis/src/test/resources/pinpoint.config b/plugins/redis/src/test/resources/pinpoint.config
index b1d906d2a2d2..d9341029f156 100644
--- a/plugins/redis/src/test/resources/pinpoint.config
+++ b/plugins/redis/src/test/resources/pinpoint.config
@@ -67,8 +67,14 @@ profiler.include=com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpo
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -87,6 +93,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -101,9 +108,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/plugins/tomcat/src/test/resources/pinpoint.config b/plugins/tomcat/src/test/resources/pinpoint.config
index dfb1d942a132..8dc31e670045 100644
--- a/plugins/tomcat/src/test/resources/pinpoint.config
+++ b/plugins/tomcat/src/test/resources/pinpoint.config
@@ -71,8 +71,14 @@ profiler.include=com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpo
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=false
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -91,6 +97,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -105,9 +112,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/plugins/user/src/test/resources/pinpoint.config b/plugins/user/src/test/resources/pinpoint.config
index b1d906d2a2d2..d9341029f156 100644
--- a/plugins/user/src/test/resources/pinpoint.config
+++ b/plugins/user/src/test/resources/pinpoint.config
@@ -67,8 +67,14 @@ profiler.include=com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpo
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -87,6 +93,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -101,9 +108,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/profiler-optional/profiler-optional-jdk8/src/test/resources/pinpoint-lambda-test.config b/profiler-optional/profiler-optional-jdk8/src/test/resources/pinpoint-lambda-test.config
index 6a9bde2f1117..0ba404b6aa40 100644
--- a/profiler-optional/profiler-optional-jdk8/src/test/resources/pinpoint-lambda-test.config
+++ b/profiler-optional/profiler-optional-jdk8/src/test/resources/pinpoint-lambda-test.config
@@ -74,8 +74,14 @@ profiler.include=
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -94,6 +100,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -108,9 +115,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/profiler/src/test/resources/pinpoint-spring-bean-test.config b/profiler/src/test/resources/pinpoint-spring-bean-test.config
index 7b0edc0ac9af..34bd2d4a14ce 100644
--- a/profiler/src/test/resources/pinpoint-spring-bean-test.config
+++ b/profiler/src/test/resources/pinpoint-spring-bean-test.config
@@ -72,8 +72,14 @@ profiler.include=
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -92,6 +98,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -106,9 +113,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
diff --git a/profiler/src/test/resources/pinpoint.config b/profiler/src/test/resources/pinpoint.config
index 8b2f50cd30fe..03a3760e963a 100644
--- a/profiler/src/test/resources/pinpoint.config
+++ b/profiler/src/test/resources/pinpoint.config
@@ -71,8 +71,14 @@ profiler.include=com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpo
profiler.tomcat.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.tomcat.bootstrap.main=org.apache.catalina.startup.Bootstrap
+# Check pre-conditions when registering class file transformers mainly due to JBoss plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.apache.catalina.startup.Bootstrap,
+# or SpringBoot's launchers.
+# Set this to false to bypass this check entirely (such as when launching standalone applications running embedded Tomcat).
+profiler.tomcat.conditional.transform=true
# Hide pinpoint headers.
profiler.tomcat.hidepinpointheader=true
+# URLs to exclude from tracing
profiler.tomcat.excludeurl=/aa/test.html, /bb/exclude.html
profiler.tomcat.tracerequestparam=true
@@ -91,6 +97,7 @@ profiler.tomcat.tracerequestparam=true
profiler.jetty.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jetty.bootstrap.main=org.eclipse.jetty.start.Main
+# URLs to exclude from tracing
profiler.jetty.excludeUrl=
@@ -105,9 +112,28 @@ profiler.dubbo.bootstrap.main=com.alibaba.dubbo.container.Main
###########################################################
# JBOSS #
###########################################################
-profiler.jboss.enable=false
+profiler.jboss.enable=true
# Classes for detecting application server type. Comma separated list of fully qualified class names. Wildcard not supported.
profiler.jboss.bootstrap.main=org.jboss.modules.Main
+# Check pre-conditions when registering class file transformers mainly due to Tomcat plugin transforming the same class.
+# Setting this to true currently adds transformers only if the application was launched via org.jboss.modules.Main.
+# Set this to false to bypass this check entirely.
+profiler.jboss.conditional.transform=true
+# Hide pinpoint headers.
+profiler.jboss.hidepinpointheader=true
+# URLs to exclude from tracing
+profiler.jboss.excludeurl=
+# HTTP Request methods to exclude from tracing
+#profiler.jboss.excludemethod=
+profiler.jboss.tracerequestparam=true
+
+# original IP address header
+# https://en.wikipedia.org/wiki/X-Forwarded-For
+#profiler.jboss.realipheader=X-Forwarded-For
+# nginx real ip header
+#profiler.jboss.realipheader=X-Real-IP
+# optional parameter, If the header value is ${profiler.jboss.realipemptyvalue}, Ignore header value.
+#profiler.jboss.realipemptyvalue=unknown
###########################################################
| train | train | "2016-10-20T09:51:44" | "2016-10-20T06:04:05Z" | Xylus | test |
pinpoint-apm/pinpoint/2187_2196 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2187 | pinpoint-apm/pinpoint/2196 | [
"keyword_pr_to_issue"
] | 116bfced6c2fc2f6eba930876e0cd820bf07d7d8 | 03d7d5ba4c0068ed7a8992dc78e036dfdf0fa252 | [] | [] | "2016-10-27T09:20:32Z" | [
"enhancement"
] | Allow collector and web to fail fast when required tables for span/stat compatibility versions do not exist | With the introduction of span/stat v2 tables new configuration options were added to ensure smooth transition from v1 -> v2.
The relevant configuration options are as follows:
**Collector** - _pinpoint-collector.properties_
```
collector.experimental.span.format.compatibility.version=v1|v2|dualWrite
collector.experimental.stat.format.compatibility.version=v1|v2|dualWrite
```
**Web** - _pinpoint-web.properties_
```
web.experimental.span.format.compatibility.version=v1|v2|compatibilityMode|dualRead
web.experimental.stat.format.compatibility.version=v1|v2|compatibilityMode
```
As it is currently, if the option is set without having the necessary table (for example setting `collector.experimental.span.format.compatibility.version=v2` without actually having the table `TraceV2`), the error is thrown late during runtime after collector startup. This could be especially undesirable for the collector as it could cause data losses.
It would be better to simply stop the collector from starting up correctly at all, and let developers know about it before traffic starts flowing in.
Current plan is to stop the collector/web from starting up under the following circumstances:
- v1 - Fail if `Traces` or `AgentStat` tables are missing
- v2 - Fail if `TraceV2` or `AgentStatV2` tables are missing
- dualWrite/dualRead/compatibilityMode - Fail if either of the v1, v2 tables is missing.
| [
"collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java"
] | [
"collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java"
] | [
"collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactoryTest.java",
"collector/src/test/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactoryTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactoryTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactoryTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactoryTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactoryTest.java"
] | diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java
index 20189d724b50..1d0856a78669 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java
@@ -1,6 +1,9 @@
package com.navercorp.pinpoint.collector.dao.hbase;
import com.navercorp.pinpoint.collector.dao.TraceDao;
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
+import org.apache.hadoop.hbase.TableName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
@@ -25,6 +28,9 @@ public class HbaseTraceDaoFactory implements FactoryBean<TraceDao> {
@Qualifier("hbaseTraceDaoV2")
private TraceDao v2;
+ @Autowired
+ private HBaseAdminTemplate adminTemplate;
+
@Value("#{pinpoint_collector_properties['collector.experimental.span.format.compatibility.version'] ?: 'v1'}")
private String mode = "v1";
@@ -33,17 +39,38 @@ public TraceDao getObject() throws Exception {
logger.info("TraceDao Compatibility {}", mode);
+ final TableName v1TableName = HBaseTables.TRACES;
+ final TableName v2TableName = HBaseTables.TRACE_V2;
+
if (mode.equalsIgnoreCase("v1")) {
- return v1;
+ if (this.adminTemplate.tableExists(v1TableName)) {
+ return v1;
+ } else {
+ logger.error("TraceDao configured for v1, but {} table does not exist", v1TableName);
+ throw new IllegalStateException(v1TableName + " table does not exist");
+ }
}
else if (mode.equalsIgnoreCase("v2")) {
- return v2;
+ if (this.adminTemplate.tableExists(v2TableName)) {
+ return v2;
+ } else {
+ logger.error("TraceDao configured for v2, but {} table does not exist", v2TableName);
+ throw new IllegalStateException(v2TableName + " table does not exist");
+ }
}
else if(mode.equalsIgnoreCase("dualWrite")) {
- return new DualWriteHbaseTraceDao(v1, v2);
+ boolean v1TableExists = this.adminTemplate.tableExists(v1TableName);
+ boolean v2TableExists = this.adminTemplate.tableExists(v2TableName);
+ if (v1TableExists && v2TableExists) {
+ return new DualWriteHbaseTraceDao(v1, v2);
+ } else {
+ logger.error("TraceDao configured for dualWrite, but {} and {} tables do not exist", v1TableName, v2TableName);
+ throw new IllegalStateException(v1TableName + ", " + v2TableName + " tables do not exist");
+ }
+ }
+ else {
+ throw new IllegalStateException("Unknown TraceDao configuration : " + mode);
}
-
- return v1;
}
@Override
diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java
index 746d128ec17c..679f7766ef53 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java
@@ -16,6 +16,9 @@
package com.navercorp.pinpoint.collector.handler;
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
+import org.apache.hadoop.hbase.TableName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
@@ -41,20 +44,45 @@ public class AgentStatHandlerFactory implements FactoryBean<Handler> {
@Qualifier("agentStatHandlerV2")
private AgentStatHandlerV2 v2;
+ @Autowired
+ private HBaseAdminTemplate adminTemplate;
+
@Value("#{pinpoint_collector_properties['collector.experimental.stat.format.compatibility.version'] ?: 'v0'}")
private String mode = "v1";
@Override
public Handler getObject() throws Exception {
logger.info("AgentStatHandler Mode {}", mode);
+
+ final TableName v1TableName = HBaseTables.AGENT_STAT;
+ final TableName v2TableName = HBaseTables.AGENT_STAT_VER2;
+
if (mode.equalsIgnoreCase("v1")) {
- return v1;
+ if (this.adminTemplate.tableExists(v1TableName)) {
+ return v1;
+ } else {
+ logger.error("AgentStatHandler configured for v1, but {} table does not exist", v1TableName);
+ throw new IllegalStateException(v1TableName + " table does not exist");
+ }
} else if (mode.equalsIgnoreCase("v2")) {
- return v2;
+ if (this.adminTemplate.tableExists(v2TableName)) {
+ return v2;
+ } else {
+ logger.error("AgentStatHandler configured for v2, but {} table does not exist", v2TableName);
+ throw new IllegalStateException(v2TableName + " table does not exist");
+ }
} else if (mode.equalsIgnoreCase("dualWrite")) {
- return new DualAgentStatHandler(v1, v2);
+ boolean v1TableExists = this.adminTemplate.tableExists(v1TableName);
+ boolean v2TableExists = this.adminTemplate.tableExists(v2TableName);
+ if (v1TableExists && v2TableExists) {
+ return new DualAgentStatHandler(v1, v2);
+ } else {
+ logger.error("AgentStatHandler configured for dualWrite, but {} and {} tables do not exist", v1TableName, v2TableName);
+ throw new IllegalStateException(v1TableName + ", " + v2TableName + " tables do not exist");
+ }
+ } else {
+ throw new IllegalStateException("Unknown AgentStatHandler configuration : " + mode);
}
- return v1;
}
@Override
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java
index 3bef590cdb0f..1294c329cc54 100644
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java
@@ -54,20 +54,19 @@ public boolean createTableIfNotExist(HTableDescriptor htd) {
}
}
- public boolean tableExists(String tableName) {
+ public boolean tableExists(TableName tableName) {
try {
- return admin.tableExists(TableName.valueOf(tableName));
+ return admin.tableExists(tableName);
} catch (IOException e) {
throw new HbaseSystemException(e);
}
}
- public boolean dropTableIfExist(String tableName) {
- TableName tn = TableName.valueOf(tableName);
+ public boolean dropTableIfExist(TableName tableName) {
try {
- if (admin.tableExists(tn)) {
- this.admin.disableTable(tn);
- this.admin.deleteTable(tn);
+ if (admin.tableExists(tableName)) {
+ this.admin.disableTable(tableName);
+ this.admin.deleteTable(tableName);
return true;
}
return false;
@@ -76,11 +75,10 @@ public boolean dropTableIfExist(String tableName) {
}
}
- public void dropTable(String tableName) {
- TableName tn = TableName.valueOf(tableName);
+ public void dropTable(TableName tableName) {
try {
- this.admin.disableTable(tn);
- this.admin.deleteTable(tn);
+ this.admin.disableTable(tableName);
+ this.admin.deleteTable(tableName);
} catch (IOException e) {
throw new HbaseSystemException(e);
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java
index 097cb10f00de..703881b47eac 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java
@@ -1,6 +1,9 @@
package com.navercorp.pinpoint.web.dao.hbase;
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
import com.navercorp.pinpoint.web.dao.TraceDao;
+import org.apache.hadoop.hbase.TableName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
@@ -9,6 +12,8 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
+import java.io.IOException;
+
/**
* TraceDao Factory for compatibility
* @author Woonduk Kang(emeroad)
@@ -26,6 +31,8 @@ public class HbaseTraceDaoFactory implements FactoryBean<TraceDao> {
@Qualifier("hbaseTraceDaoV2")
private TraceDao v2;
+ @Autowired
+ private HBaseAdminTemplate adminTemplate;
@Value("#{pinpointWebProps['web.experimental.span.format.compatibility.version'] ?: 'v1'}")
private String mode = "v1";
@@ -35,19 +42,48 @@ public TraceDao getObject() throws Exception {
logger.info("TraceDao Compatibility {}", mode);
+ final TableName v1TableName = HBaseTables.TRACES;
+ final TableName v2TableName = HBaseTables.TRACE_V2;
+
if (mode.equalsIgnoreCase("v1")) {
- return v1;
+ if (this.adminTemplate.tableExists(v1TableName)) {
+ return v1;
+ } else {
+ logger.error("TraceDao configured for v1, but {} table does not exist", v1TableName);
+ throw new IllegalStateException(v1TableName + " table does not exist");
+ }
}
else if (mode.equalsIgnoreCase("v2")) {
- return v2;
+ if (this.adminTemplate.tableExists(v2TableName)) {
+ return v2;
+ } else {
+ logger.error("TraceDao configured for v2, but {} table does not exist", v2TableName);
+ throw new IllegalStateException(v2TableName + " table does not exist");
+ }
}
else if (mode.equalsIgnoreCase("compatibilityMode")) {
- return new HbaseTraceCompatibilityDao(v2, v1);
+ boolean v1TableExists = this.adminTemplate.tableExists(v1TableName);
+ boolean v2TableExists = this.adminTemplate.tableExists(v2TableName);
+ if (v1TableExists && v2TableExists) {
+ return new HbaseTraceCompatibilityDao(v2, v1);
+ } else {
+ logger.error("TraceDao configured for compatibilityMode, but {} and {} tables do not exist", v1TableName, v2TableName);
+ throw new IllegalStateException(v1TableName + ", " + v2TableName + " tables do not exist");
+ }
}
else if (mode.equalsIgnoreCase("dualRead")) {
- return new HbaseDualReadDao(v2, v1);
+ boolean v1TableExists = this.adminTemplate.tableExists(v1TableName);
+ boolean v2TableExists = this.adminTemplate.tableExists(v2TableName);
+ if (v1TableExists && v2TableExists) {
+ return new HbaseDualReadDao(v2, v1);
+ } else {
+ logger.error("TraceDao configured for dualRead, but {} and {} tables do not exist", v1TableName, v2TableName);
+ throw new IllegalStateException(v1TableName + ", " + v2TableName + " tables do not exist");
+ }
+ }
+ else {
+ throw new IllegalStateException("Unknown TraceDao configuration : " + mode);
}
- return v1;
}
@Override
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java
index 6751738f6a59..a50e285cbaee 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java
@@ -16,6 +16,8 @@
package com.navercorp.pinpoint.web.dao.hbase.stat;
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
import com.navercorp.pinpoint.common.server.bo.stat.ActiveTraceBo;
import com.navercorp.pinpoint.common.server.bo.stat.AgentStatDataPoint;
import com.navercorp.pinpoint.common.server.bo.stat.CpuLoadBo;
@@ -29,6 +31,7 @@
import com.navercorp.pinpoint.web.dao.stat.JvmGcDao;
import com.navercorp.pinpoint.web.dao.stat.JvmGcDetailedDao;
import com.navercorp.pinpoint.web.dao.stat.TransactionDao;
+import org.apache.hadoop.hbase.TableName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
@@ -47,19 +50,44 @@ abstract class AgentStatDaoFactory<T extends AgentStatDataPoint, D extends Agent
protected D v1;
protected D v2;
+ @Autowired
+ private HBaseAdminTemplate adminTemplate;
+
@Value("#{pinpointWebProps['web.experimental.stat.format.compatibility.version'] ?: 'v1'}")
private String mode = "v1";
D getDao() throws Exception {
logger.info("AgentStatDao Compatibility {}", mode);
+
+ final TableName v1TableName = HBaseTables.AGENT_STAT;
+ final TableName v2TableName = HBaseTables.AGENT_STAT_VER2;
+
if (mode.equalsIgnoreCase("v1")) {
- return v1;
+ if (this.adminTemplate.tableExists(v1TableName)) {
+ return v1;
+ } else {
+ logger.error("AgentStatDao configured for v1, but {} table does not exist", v1TableName);
+ throw new IllegalStateException(v1TableName + " table does not exist");
+ }
} else if (mode.equalsIgnoreCase("v2")) {
- return v2;
+ if (this.adminTemplate.tableExists(v2TableName)) {
+ return v2;
+ } else {
+ logger.error("AgentStatDao configured for v2, but {} table does not exist", v2TableName);
+ throw new IllegalStateException(v2TableName + " table does not exist");
+ }
} else if (mode.equalsIgnoreCase("compatibilityMode")) {
- return getCompatibilityDao(this.v1, this.v2);
+ boolean v1TableExists = this.adminTemplate.tableExists(v1TableName);
+ boolean v2TableExists = this.adminTemplate.tableExists(v2TableName);
+ if (v1TableExists && v2TableExists) {
+ return getCompatibilityDao(this.v1, this.v2);
+ } else {
+ logger.error("AgentStatDao configured for compatibilityMode, but {} and {} tables do not exist", v1TableName, v2TableName);
+ throw new IllegalStateException(v1TableName + ", " + v2TableName + " tables do not exist");
+ }
+ } else {
+ throw new IllegalStateException("Unknown AgentStatDao configuration : " + mode);
}
- return v1;
}
abstract D getCompatibilityDao(D v1, D v2);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java
index 0ccabe2cf2c8..5d70785f4a02 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java
@@ -16,6 +16,8 @@
package com.navercorp.pinpoint.web.dao.hbase.stat;
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
import com.navercorp.pinpoint.web.dao.SampledAgentStatDao;
import com.navercorp.pinpoint.web.dao.hbase.stat.compatibility.HbaseSampledAgentStatDualReadDao;
import com.navercorp.pinpoint.web.dao.stat.SampledActiveTraceDao;
@@ -29,6 +31,7 @@
import com.navercorp.pinpoint.web.vo.stat.SampledJvmGc;
import com.navercorp.pinpoint.web.vo.stat.SampledJvmGcDetailed;
import com.navercorp.pinpoint.web.vo.stat.SampledTransaction;
+import org.apache.hadoop.hbase.TableName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
@@ -47,19 +50,44 @@ abstract class SampledAgentStatDaoFactory<S extends SampledAgentStatDataPoint, D
protected D v1;
protected D v2;
+ @Autowired
+ private HBaseAdminTemplate adminTemplate;
+
@Value("#{pinpointWebProps['web.experimental.stat.format.compatibility.version'] ?: 'v1'}")
private String mode = "v1";
D getDao() throws Exception {
logger.info("SampledAgentStatDao Compatibility {}", mode);
+
+ final TableName v1TableName = HBaseTables.AGENT_STAT;
+ final TableName v2TableName = HBaseTables.AGENT_STAT_VER2;
+
if (mode.equalsIgnoreCase("v1")) {
- return v1;
+ if (this.adminTemplate.tableExists(v1TableName)) {
+ return v1;
+ } else {
+ logger.error("SampledAgentStatDao configured for v1, but {} table does not exist", v1TableName);
+ throw new IllegalStateException(v1TableName + " table does not exist");
+ }
} else if (mode.equalsIgnoreCase("v2")) {
- return v2;
+ if (this.adminTemplate.tableExists(v2TableName)) {
+ return v2;
+ } else {
+ logger.error("SampledAgentStatDao configured for v2, but {} table does not exist", v2TableName);
+ throw new IllegalStateException(v2TableName + " table does not exist");
+ }
} else if (mode.equalsIgnoreCase("compatibilityMode")) {
- return getCompatibilityDao(this.v1, this.v2);
+ boolean v1TableExists = this.adminTemplate.tableExists(v1TableName);
+ boolean v2TableExists = this.adminTemplate.tableExists(v2TableName);
+ if (v1TableExists && v2TableExists) {
+ return getCompatibilityDao(this.v1, this.v2);
+ } else {
+ logger.error("SampledAgentStatDao configured for compatibilityMode, but {} and {} tables do not exist", v1TableName, v2TableName);
+ throw new IllegalStateException(v1TableName + ", " + v2TableName + " tables do not exist");
+ }
+ } else {
+ throw new IllegalStateException("Unknown SampledAgentStatDao configuration : " + mode);
}
- return v1;
}
abstract D getCompatibilityDao(D v1, D v2);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java
index 90649f57755f..95eaba293bc0 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java
@@ -16,6 +16,9 @@
package com.navercorp.pinpoint.web.service.stat;
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
+import org.apache.hadoop.hbase.TableName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
@@ -48,17 +51,42 @@ public class LegacyAgentStatChartServiceFactory implements FactoryBean<LegacyAge
@Qualifier("legacyAgentStatChartCompatibilityService")
private LegacyAgentStatChartService compatibility;
+ @Autowired
+ private HBaseAdminTemplate adminTemplate;
+
@Override
public LegacyAgentStatChartService getObject() throws Exception {
logger.info("LegacyAgentStatService Compatibility {}", mode);
+
+ final TableName v1TableName = HBaseTables.AGENT_STAT;
+ final TableName v2TableName = HBaseTables.AGENT_STAT_VER2;
+
if (mode.equalsIgnoreCase("v1")) {
- return v1;
+ if (this.adminTemplate.tableExists(v1TableName)) {
+ return v1;
+ } else {
+ logger.error("LegacyAgentStatService configured for v1, but {} table does not exist", v1TableName);
+ throw new IllegalStateException(v1TableName + " table does not exist");
+ }
} else if (mode.equalsIgnoreCase("v2")) {
- return v2;
+ if (this.adminTemplate.tableExists(v2TableName)) {
+ return v2;
+ } else {
+ logger.error("LegacyAgentStatService configured for v2, but {} table does not exist", v2TableName);
+ throw new IllegalStateException(v2TableName + " table does not exist");
+ }
} else if (mode.equalsIgnoreCase("compatibilityMode")) {
- return compatibility;
+ boolean v1TableExists = this.adminTemplate.tableExists(v1TableName);
+ boolean v2TableExists = this.adminTemplate.tableExists(v2TableName);
+ if (v1TableExists && v2TableExists) {
+ return compatibility;
+ } else {
+ logger.error("LegacyAgentStatService configured for compatibilityMode, but {} and {} tables do not exist", v1TableName, v2TableName);
+ throw new IllegalStateException(v1TableName + ", " + v2TableName + " tables do not exist");
+ }
+ } else {
+ throw new IllegalStateException("Unknown LegacyAgentStatService configuration : " + mode);
}
- return v1;
}
@Override
| diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactoryTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactoryTest.java
new file mode 100644
index 000000000000..ead314980c13
--- /dev/null
+++ b/collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactoryTest.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.collector.dao.hbase;
+
+import com.navercorp.pinpoint.collector.dao.TraceDao;
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.mockito.Mockito.when;
+
+/**
+ * @author HyunGil Jeong
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class HbaseTraceDaoFactoryTest {
+
+ @Mock
+ private TraceDao v1;
+
+ @Mock
+ private TraceDao v2;
+
+ @Mock
+ private HBaseAdminTemplate adminTemplate;
+
+ @InjectMocks
+ private final HbaseTraceDaoFactory traceDaoFactory = new HbaseTraceDaoFactory();
+
+ @Test
+ public void v1Mode_v1TableExists() throws Exception {
+ // Given
+ final TraceDao expectedDao = v1;
+ final String mode = "v1";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(true);
+ // When
+ TraceDao actualDao = traceDaoFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedDao, actualDao);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v1Mode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v1";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(false);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void v2Mode_v2TableExists() throws Exception {
+ // Given
+ final TraceDao expectedDao = v2;
+ final String mode = "v2";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(true);
+ // When
+ TraceDao actualDao = traceDaoFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedDao, actualDao);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v2Mode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v2";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(false);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void dualWriteMode_bothTablesExist() throws Exception {
+ // Given
+ final Class<? extends TraceDao> expectedDaoClass = DualWriteHbaseTraceDao.class;
+ final String mode = "dualWrite";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(true);
+ // When
+ TraceDao actualDao = traceDaoFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedDaoClass, actualDao.getClass());
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void dualWriteMode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "dualWrite";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(true);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void dualWriteMode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "dualWrite";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(false);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void dualWriteMode_bothTablesDoNotExist() throws Exception {
+ // Given
+ final String mode = "dualWrite";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(false);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+}
diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactoryTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactoryTest.java
new file mode 100644
index 000000000000..7422d6c79cdc
--- /dev/null
+++ b/collector/src/test/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactoryTest.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.collector.handler;
+
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.mockito.Mockito.when;
+
+/**
+ * @author HyunGil Jeong
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class AgentStatHandlerFactoryTest {
+
+ @Mock
+ private AgentStatHandler v1;
+
+ @Mock
+ private AgentStatHandlerV2 v2;
+
+ @Mock
+ private HBaseAdminTemplate adminTemplate;
+
+ @InjectMocks
+ private final AgentStatHandlerFactory handlerFactory = new AgentStatHandlerFactory();
+
+ @Test
+ public void v1Mode_v1TableExists() throws Exception {
+ // Given
+ final Handler expectedHandler = v1;
+ final String mode = "v1";
+ ReflectionTestUtils.setField(handlerFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ // When
+ Handler actualHandler = handlerFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedHandler, actualHandler);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v1Mode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v1";
+ ReflectionTestUtils.setField(handlerFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ // When
+ handlerFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void v2Mode_v2TableExists() throws Exception {
+ // Given
+ final Handler expectedHandler = v2;
+ final String mode = "v2";
+ ReflectionTestUtils.setField(handlerFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ Handler actualHandler = handlerFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedHandler, actualHandler);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v2Mode_v2TablesDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v2";
+ ReflectionTestUtils.setField(handlerFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ handlerFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void dualWriteMode_bothTablesExist() throws Exception {
+ // Given
+ final Class<? extends Handler> expectedHandlerClass = DualAgentStatHandler.class;
+ final String mode = "dualWrite";
+ ReflectionTestUtils.setField(handlerFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ Handler actualHandler = handlerFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedHandlerClass, actualHandler.getClass());
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void dualWriteMode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "dualWrite";
+ ReflectionTestUtils.setField(handlerFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ handlerFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void dualWriteMode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "dualWrite";
+ ReflectionTestUtils.setField(handlerFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ handlerFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void dualWriteMode_bothTablesDoNotExist() throws Exception {
+ // Given
+ final String mode = "dualWrite";
+ ReflectionTestUtils.setField(handlerFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ handlerFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+}
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactoryTest.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactoryTest.java
new file mode 100644
index 000000000000..e142d634c52b
--- /dev/null
+++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactoryTest.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.dao.hbase;
+
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
+import com.navercorp.pinpoint.web.dao.TraceDao;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.mockito.Mockito.when;
+
+/**
+ * @author HyunGil Jeong
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class HbaseTraceDaoFactoryTest {
+
+ @Mock
+ private TraceDao v1;
+
+ @Mock
+ private TraceDao v2;
+
+ @Mock
+ private HBaseAdminTemplate adminTemplate;
+
+ @InjectMocks
+ private final HbaseTraceDaoFactory traceDaoFactory = new HbaseTraceDaoFactory();
+
+ @Test
+ public void v1Mode_v1TableExists() throws Exception {
+ // Given
+ final TraceDao expectedDao = v1;
+ final String mode = "v1";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(true);
+ // When
+ TraceDao actualDao = traceDaoFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedDao, actualDao);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v1Mode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v1";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(false);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void v2Mode_v2TableExists() throws Exception {
+ // Given
+ final TraceDao expectedDao = v2;
+ final String mode = "v2";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(true);
+ // When
+ TraceDao actualDao = traceDaoFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedDao, actualDao);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v2Mode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v2";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(false);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void compatibilityMode_bothTablesExist() throws Exception {
+ // Given
+ final Class<? extends TraceDao> expectedTraceDaoClass = HbaseTraceCompatibilityDao.class;
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(true);
+ // When
+ TraceDao actualDao = traceDaoFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedTraceDaoClass, actualDao.getClass());
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(true);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(false);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_bothTablesDoNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(false);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void dualReadMode_bothTablesExist() throws Exception {
+ // Given
+ final Class<? extends TraceDao> expectedTraceDaoClass = HbaseDualReadDao.class;
+ final String mode = "dualRead";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(true);
+ // When
+ TraceDao actualDao = traceDaoFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedTraceDaoClass, actualDao.getClass());
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void dualReadMode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "dualRead";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(true);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void dualReadMode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "dualRead";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(false);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void dualReadMode_bothTablesDoNotExist() throws Exception {
+ // Given
+ final String mode = "dualRead";
+ ReflectionTestUtils.setField(traceDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.TRACES)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.TRACE_V2)).thenReturn(false);
+ // When
+ traceDaoFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+}
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactoryTest.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactoryTest.java
new file mode 100644
index 000000000000..0e02cdac1bdf
--- /dev/null
+++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactoryTest.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.dao.hbase.stat;
+
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
+import com.navercorp.pinpoint.common.server.bo.stat.AgentStatDataPoint;
+import com.navercorp.pinpoint.web.dao.hbase.stat.compatibility.HbaseAgentStatDualReadDao;
+import com.navercorp.pinpoint.web.dao.stat.AgentStatDao;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.mockito.Mockito.when;
+
+/**
+ * @author HyunGil Jeong
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class AgentStatDaoFactoryTest {
+
+ @Mock
+ private AgentStatDao<AgentStatDataPoint> v1;
+
+ @Mock
+ private AgentStatDao<AgentStatDataPoint> v2;
+
+ @Mock
+ private HBaseAdminTemplate adminTemplate;
+
+ @InjectMocks
+ private TestAgentStatDaoFactory agentStatDaoFactory = new TestAgentStatDaoFactory();
+
+ private final HbaseAgentStatDualReadDao<AgentStatDataPoint> compatibilityDao = new TestAgentStatDualReadDao(v1, v2);
+
+ private static class TestAgentStatDualReadDao extends HbaseAgentStatDualReadDao<AgentStatDataPoint> {
+ public TestAgentStatDualReadDao(AgentStatDao<AgentStatDataPoint> master, AgentStatDao<AgentStatDataPoint> slave) {
+ super(master, slave);
+ }
+ }
+
+ private class TestAgentStatDaoFactory extends AgentStatDaoFactory<AgentStatDataPoint, AgentStatDao<AgentStatDataPoint>> {
+ @Override
+ HbaseAgentStatDualReadDao<AgentStatDataPoint> getCompatibilityDao(
+ AgentStatDao<AgentStatDataPoint> v1,
+ AgentStatDao<AgentStatDataPoint> v2) {
+ return compatibilityDao;
+ }
+ }
+
+ @Test
+ public void v1Mode_v1TableExists() throws Exception {
+ // Given
+ final AgentStatDao<AgentStatDataPoint> expectedDao = v1;
+ final String mode = "v1";
+ ReflectionTestUtils.setField(agentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ // When
+ AgentStatDao<AgentStatDataPoint> actualDao = agentStatDaoFactory.getDao();
+ // Then
+ Assert.assertEquals(expectedDao, actualDao);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v1Mode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v1";
+ ReflectionTestUtils.setField(agentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ // When
+ agentStatDaoFactory.getDao();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void v2Mode_v2TableExists() throws Exception {
+ // Given
+ final AgentStatDao<AgentStatDataPoint> expectedDao = v2;
+ final String mode = "v2";
+ ReflectionTestUtils.setField(agentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ AgentStatDao<AgentStatDataPoint> actualDao = agentStatDaoFactory.getDao();
+ // Then
+ Assert.assertEquals(expectedDao, actualDao);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v2Mode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v2";
+ ReflectionTestUtils.setField(agentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ agentStatDaoFactory.getDao();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void compatibilityMode_bothTablesExist() throws Exception {
+ // Given
+ final HbaseAgentStatDualReadDao<AgentStatDataPoint> expectedDao = compatibilityDao;
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(agentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ AgentStatDao<AgentStatDataPoint> actualDao = agentStatDaoFactory.getDao();
+ // Then
+ Assert.assertEquals(expectedDao, actualDao);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(agentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ agentStatDaoFactory.getDao();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(agentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ agentStatDaoFactory.getDao();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_bothTablesDoNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(agentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ agentStatDaoFactory.getDao();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+}
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactoryTest.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactoryTest.java
new file mode 100644
index 000000000000..15fd7ea53f93
--- /dev/null
+++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactoryTest.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.dao.hbase.stat;
+
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
+import com.navercorp.pinpoint.web.dao.SampledAgentStatDao;
+import com.navercorp.pinpoint.web.dao.hbase.stat.compatibility.HbaseSampledAgentStatDualReadDao;
+import com.navercorp.pinpoint.web.vo.stat.SampledAgentStatDataPoint;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.mockito.Mockito.when;
+
+/**
+ * @author HyunGil Jeong
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class SampledAgentStatDaoFactoryTest {
+
+ @Mock
+ private SampledAgentStatDao<SampledAgentStatDataPoint> v1;
+
+ @Mock
+ private SampledAgentStatDao<SampledAgentStatDataPoint> v2;
+
+ @Mock
+ private HBaseAdminTemplate adminTemplate;
+
+ @InjectMocks
+ private TestSampledAgentStatDaoFactory sampledAgentStatDaoFactory = new TestSampledAgentStatDaoFactory();
+
+ private final HbaseSampledAgentStatDualReadDao<SampledAgentStatDataPoint> compatibilityDao = new TestSampledAgentStatDualReadDao(v1, v2);
+
+ private static class TestSampledAgentStatDualReadDao extends HbaseSampledAgentStatDualReadDao<SampledAgentStatDataPoint> {
+ public TestSampledAgentStatDualReadDao(SampledAgentStatDao<SampledAgentStatDataPoint> master, SampledAgentStatDao<SampledAgentStatDataPoint> slave) {
+ super(master, slave);
+ }
+ }
+
+ private class TestSampledAgentStatDaoFactory extends SampledAgentStatDaoFactory<SampledAgentStatDataPoint, SampledAgentStatDao<SampledAgentStatDataPoint>> {
+ @Override
+ HbaseSampledAgentStatDualReadDao<SampledAgentStatDataPoint> getCompatibilityDao(
+ SampledAgentStatDao<SampledAgentStatDataPoint> v1,
+ SampledAgentStatDao<SampledAgentStatDataPoint> v2) {
+ return compatibilityDao;
+ }
+ }
+
+ @Test
+ public void v1Mode_v1TableExists() throws Exception {
+ // Given
+ final SampledAgentStatDao<SampledAgentStatDataPoint> expectedDao = v1;
+ final String mode = "v1";
+ ReflectionTestUtils.setField(sampledAgentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ // When
+ SampledAgentStatDao<SampledAgentStatDataPoint> actualDao = sampledAgentStatDaoFactory.getDao();
+ // Then
+ Assert.assertEquals(expectedDao, actualDao);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v1Mode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v1";
+ ReflectionTestUtils.setField(sampledAgentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ // When
+ sampledAgentStatDaoFactory.getDao();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void v2Mode_v2TableExists() throws Exception {
+ // Given
+ final SampledAgentStatDao<SampledAgentStatDataPoint> expectedDao = v2;
+ final String mode = "v2";
+ ReflectionTestUtils.setField(sampledAgentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ SampledAgentStatDao<SampledAgentStatDataPoint> actualDao = sampledAgentStatDaoFactory.getDao();
+ // Then
+ Assert.assertEquals(expectedDao, actualDao);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v2Mode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v2";
+ ReflectionTestUtils.setField(sampledAgentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ sampledAgentStatDaoFactory.getDao();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void compatibiltyMode_bothTablesExist() throws Exception {
+ // Given
+ final HbaseSampledAgentStatDualReadDao<SampledAgentStatDataPoint> expectedDao = compatibilityDao;
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(sampledAgentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ SampledAgentStatDao<SampledAgentStatDataPoint> actualDao = sampledAgentStatDaoFactory.getDao();
+ // Then
+ Assert.assertEquals(expectedDao, actualDao);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(sampledAgentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ sampledAgentStatDaoFactory.getDao();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(sampledAgentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ sampledAgentStatDaoFactory.getDao();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_bothTablesDoNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(sampledAgentStatDaoFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ sampledAgentStatDaoFactory.getDao();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+}
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactoryTest.java b/web/src/test/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactoryTest.java
new file mode 100644
index 000000000000..a8a35545b0e1
--- /dev/null
+++ b/web/src/test/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactoryTest.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2016 Naver Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.service.stat;
+
+import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
+import com.navercorp.pinpoint.common.hbase.HBaseTables;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.mockito.Mockito.when;
+
+/**
+ * @author HyunGil Jeong
+ */
+@Deprecated
+@RunWith(MockitoJUnitRunner.class)
+public class LegacyAgentStatChartServiceFactoryTest {
+
+ @Mock
+ private LegacyAgentStatChartService v1;
+
+ @Mock
+ private LegacyAgentStatChartService v2;
+
+ @Mock
+ private LegacyAgentStatChartService compatibility;
+
+ @Mock
+ private HBaseAdminTemplate adminTemplate;
+
+ @InjectMocks
+ private LegacyAgentStatChartServiceFactory serviceFactory = new LegacyAgentStatChartServiceFactory();
+
+ @Test
+ public void v1Mode_v1TableExists() throws Exception {
+ // Given
+ final LegacyAgentStatChartService expectedService = v1;
+ final String mode = "v1";
+ ReflectionTestUtils.setField(serviceFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ // When
+ LegacyAgentStatChartService actualService = serviceFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedService, actualService);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v1Mode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v1";
+ ReflectionTestUtils.setField(serviceFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ // When
+ serviceFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void v2Mode_v2TableExists() throws Exception {
+ // Given
+ final LegacyAgentStatChartService expectedService = v2;
+ final String mode = "v2";
+ ReflectionTestUtils.setField(serviceFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ LegacyAgentStatChartService actualService = serviceFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedService, actualService);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void v2Mode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "v2";
+ ReflectionTestUtils.setField(serviceFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ serviceFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test
+ public void compatibilityMode_bothTablesExist() throws Exception {
+ // Given
+ final LegacyAgentStatChartService expectedService = compatibility;
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(serviceFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ LegacyAgentStatChartService actualService = serviceFactory.getObject();
+ // Then
+ Assert.assertEquals(expectedService, actualService);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_v1TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(serviceFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(true);
+ // When
+ serviceFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_v2TableDoesNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(serviceFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(true);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ serviceFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void compatibilityMode_bothTablesDoNotExist() throws Exception {
+ // Given
+ final String mode = "compatibilityMode";
+ ReflectionTestUtils.setField(serviceFactory, "mode", mode);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT)).thenReturn(false);
+ when(adminTemplate.tableExists(HBaseTables.AGENT_STAT_VER2)).thenReturn(false);
+ // When
+ serviceFactory.getObject();
+ // Then
+ Assert.fail("Should have thrown IllegalStateException.");
+ }
+}
| train | train | "2016-10-27T08:34:39" | "2016-10-24T10:30:30Z" | Xylus | test |
pinpoint-apm/pinpoint/2198_2199 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2198 | pinpoint-apm/pinpoint/2199 | [
"keyword_pr_to_issue"
] | 9471f72b60f25e1c21b9c1c42f7ee7d74ddd87af | 702de7ac6d3ba5c57edde3b3c173ed956e60c0f7 | [] | [] | "2016-10-28T06:25:14Z" | [
"bug"
] | Fixed send retry policy in TCPDataSender | Retry policy in TCPDataSender is not working properly, so Fixed it.
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryQueue.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java",
"rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointClientFactory.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryQueue.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java",
"rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointClientFactory.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/RetryMessageTest.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/RetryQueueTest.java"
] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java
index 40ea43709aab..13ef7c3ac506 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java
@@ -16,22 +16,60 @@
package com.navercorp.pinpoint.profiler.sender;
+import org.apache.commons.lang.StringUtils;
+
/**
* @author emeroad
*/
public class RetryMessage {
- private int retryCount;
- private byte[] bytes;
- public RetryMessage(int retryCount, byte[] bytes) {
+ private int retryCount = 0;
+ private final int maxRetryCount;
+
+ private final byte[] bytes;
+ private final String messageDescription;
+
+ public RetryMessage(int maxRetryCount, byte[] bytes) {
+ this(0, maxRetryCount, bytes, "");
+ }
+
+ public RetryMessage(int retryCount, int maxRetryCount, byte[] bytes) {
+ this(retryCount, maxRetryCount, bytes, "");
+ }
+
+ public RetryMessage(int maxRetryCount, byte[] bytes, String messageDescription) {
+ this(0, maxRetryCount, bytes, messageDescription);
+ }
+
+ public RetryMessage(int retryCount, int maxRetryCount, byte[] bytes, String messageDescription) {
+ if (retryCount < 0) {
+ throw new IllegalArgumentException("retryCount:" + retryCount + " must be positive number");
+ }
+ if (maxRetryCount < 0) {
+ throw new IllegalArgumentException("maxRetryCount:" + maxRetryCount + " must be positive number");
+ }
+ if (retryCount > maxRetryCount) {
+ throw new IllegalArgumentException("maxRetryCount(" + maxRetryCount + ") must be greater than retryCount(" + retryCount + ")");
+ }
+
this.retryCount = retryCount;
+ this.maxRetryCount = maxRetryCount;
this.bytes = bytes;
+ this.messageDescription = messageDescription;
}
public int getRetryCount() {
return retryCount;
}
+ public int getMaxRetryCount() {
+ return maxRetryCount;
+ }
+
+ public boolean isRetryAvailable() {
+ return retryCount < maxRetryCount;
+ }
+
public byte[] getBytes() {
return bytes;
}
@@ -39,4 +77,19 @@ public byte[] getBytes() {
public int fail() {
return ++retryCount;
}
+
+ @Override
+ public String toString() {
+ StringBuffer toString = new StringBuffer();
+ toString.append("RetryMessage{");
+ if (!StringUtils.isEmpty(messageDescription)) {
+ toString.append("message:" + messageDescription + ", ");
+ }
+ toString.append("size=" + bytes.length + ", ");
+ toString.append("retry=" + retryCount + "/" + maxRetryCount);
+ toString.append("}");
+
+ return toString.toString();
+ }
+
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryQueue.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryQueue.java
index 30b203628850..8fbeaf7d5874 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryQueue.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryQueue.java
@@ -31,15 +31,15 @@ public class RetryQueue {
// But PriorityQueue of JDK has no size limit, so let's do it without priority for now.
private final BlockingQueue<RetryMessage> queue;
private final int capacity;
- private final int maxRetry;
+ private final int maxRetryCount;
private final int halfCapacity;
- public RetryQueue(int capacity, int maxRetry) {
+ public RetryQueue(int capacity, int maxRetryCount) {
this.queue = new LinkedBlockingQueue<RetryMessage>();
this.capacity = capacity;
this.halfCapacity = capacity / 2;
- this.maxRetry = maxRetry;
+ this.maxRetryCount = maxRetryCount;
}
public RetryQueue() {
@@ -51,9 +51,13 @@ public void add(RetryMessage retryMessage) {
throw new NullPointerException("retryMessage must not be null");
}
- final int retryCount = retryMessage.getRetryCount();
- if (retryCount >= this.maxRetry) {
- logger.warn("discard retry message. retryCount:{}", retryCount);
+ if (!retryMessage.isRetryAvailable()) {
+ logger.warn("discard retry message({}).", retryMessage);
+ return;
+ }
+ int retryCount = retryMessage.getRetryCount();
+ if (retryCount >= this.maxRetryCount) {
+ logger.warn("discard retry message({}). queue-maxRetryCount:{}", retryMessage, maxRetryCount);
return;
}
final int queueSize = queue.size();
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java
index 3f565e639cb1..2e0e8479db0d 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java
@@ -17,6 +17,19 @@
package com.navercorp.pinpoint.profiler.sender;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.thrift.TBase;
+import org.jboss.netty.buffer.ChannelBuffers;
+import org.jboss.netty.util.HashedWheelTimer;
+import org.jboss.netty.util.Timeout;
+import org.jboss.netty.util.Timer;
+import org.jboss.netty.util.TimerTask;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import com.navercorp.pinpoint.rpc.Future;
import com.navercorp.pinpoint.rpc.FutureListener;
import com.navercorp.pinpoint.rpc.ResponseMessage;
@@ -28,18 +41,6 @@
import com.navercorp.pinpoint.thrift.io.HeaderTBaseDeserializerFactory;
import com.navercorp.pinpoint.thrift.io.HeaderTBaseSerializer;
import com.navercorp.pinpoint.thrift.io.HeaderTBaseSerializerFactory;
-import org.apache.thrift.TBase;
-import org.jboss.netty.buffer.ChannelBuffers;
-import org.jboss.netty.util.HashedWheelTimer;
-import org.jboss.netty.util.Timeout;
-import org.jboss.netty.util.Timer;
-import org.jboss.netty.util.TimerTask;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author emeroad
@@ -142,7 +143,7 @@ protected void sendPacket(Object message) {
if (copy == null) {
return;
}
-
+
if (futureListener != null) {
doRequest(copy, futureListener);
} else {
@@ -162,7 +163,8 @@ private void doSend(byte[] copy) {
write.setListener(writeFailFutureListener);
}
- private void doRequest(final byte[] requestPacket, final int retryCount, final Object targetClass) {
+ // Separate doRequest method to avoid creating unnecessary objects. (Generally, sending message is successed when firt attempt.)
+ private void doRequest(final byte[] requestPacket, final int maxRetryCount, final Object targetClass) {
FutureListener futureListener = (new FutureListener<ResponseMessage>() {
@Override
public void onComplete(Future<ResponseMessage> future) {
@@ -175,18 +177,20 @@ public void onComplete(Future<ResponseMessage> future) {
if (result.isSuccess()) {
logger.debug("result success");
} else {
- logger.warn("request fail. clazz:{} Caused:{}", targetClass, result.getMessage());
- retryRequest(requestPacket, retryCount, targetClass.getClass().getSimpleName());
+ logger.info("request fail. request:{} Caused:{}", targetClass, result.getMessage());
+ RetryMessage retryMessage = new RetryMessage(1, maxRetryCount, requestPacket, targetClass.getClass().getSimpleName());
+ retryRequest(retryMessage);
}
} else {
- logger.warn("Invalid ResponseMessage. {}", response);
+ logger.warn("Invalid respose:{}", response);
// This is not retransmission. need to log for debugging
// it could be null
// retryRequest(requestPacket);
}
} else {
- logger.warn("request fail. clazz:{} Caused:{}", targetClass, future.getCause().getMessage(), future.getCause());
- retryRequest(requestPacket, retryCount, targetClass.getClass().getSimpleName());
+ logger.info("request fail. request:{} Caused:{}", targetClass, future.getCause().getMessage(), future.getCause());
+ RetryMessage retryMessage = new RetryMessage(1, maxRetryCount, requestPacket, targetClass.getClass().getSimpleName());
+ retryRequest(retryMessage);
}
}
});
@@ -194,8 +198,40 @@ public void onComplete(Future<ResponseMessage> future) {
doRequest(requestPacket, futureListener);
}
- private void retryRequest(byte[] requestPacket, int retryCount, final String className) {
- RetryMessage retryMessage = new RetryMessage(retryCount, requestPacket);
+ // Separate doRequest method to avoid creating unnecessary objects. (Generally, sending message is successed when firt attempt.)
+ private void doRequest(final RetryMessage retryMessage) {
+ FutureListener futureListener = (new FutureListener<ResponseMessage>() {
+ @Override
+ public void onComplete(Future<ResponseMessage> future) {
+ if (future.isSuccess()) {
+ // Should cache?
+ HeaderTBaseDeserializer deserializer = HeaderTBaseDeserializerFactory.DEFAULT_FACTORY.createDeserializer();
+ TBase<?, ?> response = deserialize(deserializer, future.getResult());
+ if (response instanceof TResult) {
+ TResult result = (TResult) response;
+ if (result.isSuccess()) {
+ logger.debug("result success");
+ } else {
+ logger.info("request fail. request:{}, Caused:{}", retryMessage, result.getMessage());
+ retryRequest(retryMessage);
+ }
+ } else {
+ logger.warn("Invalid response:{}", response);
+ // This is not retransmission. need to log for debugging
+ // it could be null
+// retryRequest(requestPacket);
+ }
+ } else {
+ logger.info("request fail. request:{}, caused:{}", retryMessage, future.getCause().getMessage(), future.getCause());
+ retryRequest(retryMessage);
+ }
+ }
+ });
+
+ doRequest(retryMessage.getBytes(), futureListener);
+ }
+
+ private void retryRequest(RetryMessage retryMessage) {
retryQueue.add(retryMessage);
if (fireTimeout()) {
timer.newTimeout(new TimerTask() {
@@ -209,7 +245,7 @@ public void run(Timeout timeout) throws Exception {
return;
}
int fail = retryMessage.fail();
- doRequest(retryMessage.getBytes(), fail, className);
+ doRequest(retryMessage);
}
}
}, 1000 * 10, TimeUnit.MILLISECONDS);
diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointClientFactory.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointClientFactory.java
index eec6ac3e743c..683c4d8dbe63 100644
--- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointClientFactory.java
+++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointClientFactory.java
@@ -17,6 +17,35 @@
package com.navercorp.pinpoint.rpc.client;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.jboss.netty.bootstrap.ClientBootstrap;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelFuture;
+import org.jboss.netty.channel.ChannelFutureListener;
+import org.jboss.netty.channel.ChannelPipeline;
+import org.jboss.netty.channel.ChannelPipelineException;
+import org.jboss.netty.channel.socket.nio.NioClientBossPool;
+import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
+import org.jboss.netty.channel.socket.nio.NioWorkerPool;
+import org.jboss.netty.util.HashedWheelTimer;
+import org.jboss.netty.util.ThreadNameDeterminer;
+import org.jboss.netty.util.Timeout;
+import org.jboss.netty.util.Timer;
+import org.jboss.netty.util.TimerTask;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import com.navercorp.pinpoint.common.util.PinpointThreadFactory;
import com.navercorp.pinpoint.rpc.MessageListener;
import com.navercorp.pinpoint.rpc.PinpointSocketException;
@@ -28,24 +57,6 @@
import com.navercorp.pinpoint.rpc.util.AssertUtils;
import com.navercorp.pinpoint.rpc.util.LoggerFactorySetup;
import com.navercorp.pinpoint.rpc.util.TimerFactory;
-import org.jboss.netty.bootstrap.ClientBootstrap;
-import org.jboss.netty.channel.*;
-import org.jboss.netty.channel.socket.nio.NioClientBossPool;
-import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
-import org.jboss.netty.channel.socket.nio.NioWorkerPool;
-import org.jboss.netty.util.*;
-import org.jboss.netty.util.Timer;
-import org.jboss.netty.util.TimerTask;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.util.*;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
/**
* @author emeroad
@@ -352,7 +363,7 @@ public void run(Timeout timeout) {
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
Channel channel = future.getChannel();
- logger.warn("reconnect success {}, {}", socketAddress, channel);
+ logger.info("reconnect success {}, {}", socketAddress, channel);
pinpointClient.reconnectSocketHandler(pinpointClientHandler);
} else {
if (!pinpointClient.isClosed()) {
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/RetryMessageTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/RetryMessageTest.java
new file mode 100644
index 000000000000..ebe5e2d124fb
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/RetryMessageTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.sender;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * @author Taejin Koo
+ */
+public class RetryMessageTest {
+
+ @Test
+ public void availableTest1() throws Exception {
+ RetryMessage retryMessage = new RetryMessage(1, new byte[0]);
+ Assert.assertTrue(retryMessage.isRetryAvailable());
+
+ retryMessage.fail();
+ Assert.assertFalse(retryMessage.isRetryAvailable());
+ }
+
+ @Test
+ public void availableTest2() throws Exception {
+ RetryMessage retryMessage = new RetryMessage(1, 2, new byte[0]);
+ Assert.assertTrue(retryMessage.isRetryAvailable());
+
+ retryMessage.fail();
+ Assert.assertFalse(retryMessage.isRetryAvailable());
+ }
+
+ @Test
+ public void availableTest3() throws Exception {
+ RetryMessage retryMessage = new RetryMessage(2, 2, new byte[0]);
+ Assert.assertFalse(retryMessage.isRetryAvailable());
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void illegalArgumentTest1() {
+ RetryMessage retryMessage = new RetryMessage(-1, new byte[0]);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void illegalArgumentTest2() {
+ RetryMessage retryMessage = new RetryMessage(-1, 5, new byte[0]);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void illegalArgumentTest3() {
+ RetryMessage retryMessage = new RetryMessage(10, 9, new byte[0]);
+ }
+
+
+}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/RetryQueueTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/RetryQueueTest.java
index 0a6ac48e7090..77b97cb6c503 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/RetryQueueTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/RetryQueueTest.java
@@ -17,25 +17,19 @@
package com.navercorp.pinpoint.profiler.sender;
import org.junit.Assert;
-
import org.junit.Test;
-import com.navercorp.pinpoint.profiler.sender.RetryMessage;
-import com.navercorp.pinpoint.profiler.sender.RetryQueue;
-
/**
* @author emeroad
*/
public class RetryQueueTest {
@Test
public void size() {
-
RetryQueue retryQueue = new RetryQueue(1, 1);
- retryQueue.add(new RetryMessage(0, new byte[0]));
- retryQueue.add(new RetryMessage(0, new byte[0]));
+ retryQueue.add(new RetryMessage(1, new byte[0]));
+ retryQueue.add(new RetryMessage(1, new byte[0]));
Assert.assertEquals(1, retryQueue.size());
-
}
@Test
@@ -48,7 +42,6 @@ public void size2() {
@Test
public void maxRetryTest() {
-
RetryQueue retryQueue = new RetryQueue(3, 2);
RetryMessage retryMessage = new RetryMessage(0, new byte[0]);
retryMessage.fail();
@@ -62,12 +55,25 @@ public void maxRetryTest() {
}
@Test
- public void add() {
+ public void maxRetryTest2() {
+ RetryQueue retryQueue = new RetryQueue(3, 1);
+ RetryMessage retryMessage = new RetryMessage(5, new byte[0]);
+ retryMessage.fail();
+ retryMessage.fail();
+
+ retryQueue.add(retryMessage);
+ retryQueue.add(retryMessage);
+
+ Assert.assertEquals(retryQueue.size(), 0);
+ }
+
+ @Test
+ public void add() {
RetryQueue retryQueue = new RetryQueue(3, 2);
- retryQueue.add(new RetryMessage(0, new byte[0]));
+ retryQueue.add(new RetryMessage(1, new byte[0]));
// If we add a failed message and it makes the queue filled more than half, the queue must discard it.
- RetryMessage retryMessage = new RetryMessage(0, new byte[0]);
+ RetryMessage retryMessage = new RetryMessage(1, new byte[0]);
retryMessage.fail();
retryQueue.add(retryMessage);
| train | train | "2016-10-28T07:06:38" | "2016-10-28T05:21:40Z" | koo-taejin | test |
pinpoint-apm/pinpoint/2198_2200 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2198 | pinpoint-apm/pinpoint/2200 | [
"keyword_pr_to_issue"
] | 702de7ac6d3ba5c57edde3b3c173ed956e60c0f7 | ee3fa7ba4b476f0d834b82968bc4e886fab203f7 | [] | [] | "2016-10-28T07:54:20Z" | [
"bug"
] | Fixed send retry policy in TCPDataSender | Retry policy in TCPDataSender is not working properly, so Fixed it.
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java"
] | [] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java
index 13ef7c3ac506..09c98d0a3067 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/RetryMessage.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.profiler.sender;
+import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
/**
@@ -80,12 +81,12 @@ public int fail() {
@Override
public String toString() {
- StringBuffer toString = new StringBuffer();
+ StringBuilder toString = new StringBuilder();
toString.append("RetryMessage{");
if (!StringUtils.isEmpty(messageDescription)) {
toString.append("message:" + messageDescription + ", ");
}
- toString.append("size=" + bytes.length + ", ");
+ toString.append("size=" + ArrayUtils.getLength(bytes) + ", ");
toString.append("retry=" + retryCount + "/" + maxRetryCount);
toString.append("}");
| null | test | train | "2016-10-28T09:28:09" | "2016-10-28T05:21:40Z" | koo-taejin | test |
pinpoint-apm/pinpoint/1807_2204 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/1807 | pinpoint-apm/pinpoint/2204 | [
"keyword_pr_to_issue"
] | ac002af686b2d6c5cdc21c15a77aee8485a8a5f6 | 43b1d97f9d0a7b22de7f8b57679e24c70c3a352d | [
"fixed: https://github.com/jboss-javassist/javassist/issues/83\n",
"There is Javassist 3.21.0-GA version available with fix for this issue.\n",
"Thanks. I fixed it.\n"
] | [] | "2016-10-31T10:35:12Z" | [
"bug"
] | Javassist bug : Incorrect StackMap Frame generation | Incorrect StackMapFrame generation
bug regression code
``` java
public class InvalidStackMapFrame {
public void bytecodeVerifyError() {
// javassist bug : invalid stack map frame
List<Integer> test = new ArrayList<Integer>();
String[] newLine = new String[10];
for (Integer idx : test) {
String address = newLine[1];
int tabPos = -1;
if (tabPos != -1) {
address = address.substring(tabPos + 1);
}
newLine[4] = address;
}
}
}
```
Here is the error message
```
16:40:54 [DEBUG](b.j.JavassistVerifyErrorTest :49 ) verifyError:Bad type on operand stack in aaload
Exception Details:
Location:
bug_regression_jdk7/javassist/InvalidStackMapFrame.bytecodeVerifyError()V @46: aaload
Reason:
Type 'java/lang/Object' (current frame, stack[0]) is not assignable to reference type
Current Frame:
bci: @46
flags: { }
locals: { 'bug_regression_jdk7/javassist/InvalidStackMapFrame', 'java/util/ArrayList', 'java/lang/Object', 'java/util/Iterator', 'java/lang/Integer', top, top, integer }
stack: { 'java/lang/Object', integer }
Bytecode:
0000000: 0436 07bb 0002 59b7 0003 4c10 0abd 0004
0000010: 4d2b b900 0501 004e 2db9 0006 0100 9900
0000020: 2f2d b900 0701 00c0 0008 3a04 2c04 323a
0000030: 0502 3606 1506 029f 000e 1905 1506 0460
0000040: b600 093a 052c 0719 0553 a7ff ceb1
Stackmap Table:
full_frame(@24,{Object[#40],Object[#2],Object[#11],Object[#48],Top,Top,Top,Integer},{})
full_frame(@69,{Object[#40],Object[#2],Object[#11],Object[#48],Object[#38],Object[#11],Integer,Integer},{})
full_frame(@77,{Object[#40],Object[#2],Object[#11],Object[#48],Top,Top,Top,Integer},{})
```
dump stackmap frame
```
dumpVerify:<init>()V
00000 InvalidStackMapFrame : : ALOAD 0
00001 InvalidStackMapFrame : InvalidStackMapFrame : INVOKESPECIAL java/lang/Object.<init> ()V
00002 InvalidStackMapFrame : : RETURN
bytecodeVerifyError()V
00000 InvalidStackMapFrame . . . . . . . : : ICONST_1
00001 InvalidStackMapFrame . . . . . . . : I : ISTORE 7
00002 InvalidStackMapFrame . . . . . . I : : NEW java/util/ArrayList
00003 InvalidStackMapFrame . . . . . . I : ArrayList : DUP
00004 InvalidStackMapFrame . . . . . . I : ArrayList ArrayList : INVOKESPECIAL java/util/ArrayList.<init> ()V
00005 InvalidStackMapFrame . . . . . . I : ArrayList : ASTORE 1
00006 InvalidStackMapFrame ArrayList . . . . . I : : BIPUSH 10
00007 InvalidStackMapFrame ArrayList . . . . . I : I : ANEWARRAY java/lang/String
00008 InvalidStackMapFrame ArrayList . . . . . I : String : ASTORE 2
00009 InvalidStackMapFrame ArrayList String . . . . I : : ALOAD 1
00010 InvalidStackMapFrame ArrayList String . . . . I : ArrayList : INVOKEINTERFACE java/util/List.iterator ()Ljava/util/Iterator;
00011 InvalidStackMapFrame ArrayList String . . . . I : Iterator : ASTORE 3
00012 InvalidStackMapFrame ArrayList String Iterator . . . I : : L0
00013 InvalidStackMapFrame ArrayList String Iterator . . . I : : FRAME FULL
--> invalid frame java/lang/Object->[Ljava/lang/String;
--> [bug_regression_jdk7/javassist/InvalidStackMapFrame java/util/ArrayList java/lang/Object->[Ljava/lang/String; java/util/Iterator T T T I] []
[bug_regression_jdk7/javassist/InvalidStackMapFrame java/util/ArrayList java/lang/Object java/util/Iterator T T T I] []
00014 InvalidStackMapFrame ArrayList String Iterator . . . I : : ALOAD 3
00015 InvalidStackMapFrame ArrayList String Iterator . . . I : Iterator : INVOKEINTERFACE java/util/Iterator.hasNext ()Z
00016 InvalidStackMapFrame ArrayList String Iterator . . . I : I : IFEQ L1
00017 InvalidStackMapFrame ArrayList String Iterator . . . I : : ALOAD 3
00018 InvalidStackMapFrame ArrayList String Iterator . . . I : Iterator : INVOKEINTERFACE java/util/Iterator.next ()Ljava/lang/Object;
00019 InvalidStackMapFrame ArrayList String Iterator . . . I : Object : CHECKCAST java/lang/Integer
00020 InvalidStackMapFrame ArrayList String Iterator . . . I : Integer : ASTORE 4
00021 InvalidStackMapFrame ArrayList String Iterator Integer . . I : : ALOAD 2
00022 InvalidStackMapFrame ArrayList String Iterator Integer . . I : String : ICONST_1
00023 InvalidStackMapFrame ArrayList String Iterator Integer . . I : String I : AALOAD
00024 InvalidStackMapFrame ArrayList String Iterator Integer . . I : String : ASTORE 5
00025 InvalidStackMapFrame ArrayList String Iterator Integer String . I : : ICONST_M1
00026 InvalidStackMapFrame ArrayList String Iterator Integer String . I : I : ISTORE 6
00027 InvalidStackMapFrame ArrayList String Iterator Integer String I I : : ILOAD 6
00028 InvalidStackMapFrame ArrayList String Iterator Integer String I I : I : ICONST_M1
00029 InvalidStackMapFrame ArrayList String Iterator Integer String I I : I I : IF_ICMPEQ L2
00030 InvalidStackMapFrame ArrayList String Iterator Integer String I I : : ALOAD 5
00031 InvalidStackMapFrame ArrayList String Iterator Integer String I I : String : ILOAD 6
00032 InvalidStackMapFrame ArrayList String Iterator Integer String I I : String I : ICONST_1
00033 InvalidStackMapFrame ArrayList String Iterator Integer String I I : String I I : IADD
00034 InvalidStackMapFrame ArrayList String Iterator Integer String I I : String I : INVOKEVIRTUAL java/lang/String.substring (I)Ljava/lang/String;
00035 InvalidStackMapFrame ArrayList String Iterator Integer String I I : String : ASTORE 5
00036 InvalidStackMapFrame ArrayList String Iterator Integer String I I : : L2
--> invalid frame
00037 InvalidStackMapFrame ArrayList String Iterator Integer String I I : : FRAME FULL [bug_regression_jdk7/javassist/InvalidStackMapFrame java/util/ArrayList java/lang/Object java/util/Iterator java/lang/Integer java/lang/Object I I] []
00038 InvalidStackMapFrame ArrayList String Iterator Integer String I I : : ALOAD 2
00039 InvalidStackMapFrame ArrayList String Iterator Integer String I I : String : ICONST_4
00040 InvalidStackMapFrame ArrayList String Iterator Integer String I I : String I : ALOAD 5
00041 InvalidStackMapFrame ArrayList String Iterator Integer String I I : String I String : AASTORE
00042 InvalidStackMapFrame ArrayList String Iterator Integer String I I : : GOTO L0
00043 InvalidStackMapFrame ArrayList String Iterator . . . I : : L1
--> invalid frame
00044 InvalidStackMapFrame ArrayList String Iterator . . . I : : FRAME FULL [bug_regression_jdk7/javassist/InvalidStackMapFrame java/util/ArrayList java/lang/Object java/util/Iterator T T T I] []
00045 InvalidStackMapFrame ArrayList String Iterator . . . I : : RETURN
```
| [
"pom.xml"
] | [
"pom.xml"
] | [
"profiler-optional/profiler-optional-jdk7/src/test/java/bug_regression_jdk7/javassist/JavassistVerifyErrorTest.java"
] | diff --git a/pom.xml b/pom.xml
index 776bed69e1e7..64159fea9537 100644
--- a/pom.xml
+++ b/pom.xml
@@ -568,7 +568,7 @@
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
- <version>3.20.0-GA</version>
+ <version>3.21.0-GA</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
| diff --git a/profiler-optional/profiler-optional-jdk7/src/test/java/bug_regression_jdk7/javassist/JavassistVerifyErrorTest.java b/profiler-optional/profiler-optional-jdk7/src/test/java/bug_regression_jdk7/javassist/JavassistVerifyErrorTest.java
index 206073ae3c6f..ba5bf79185b3 100644
--- a/profiler-optional/profiler-optional-jdk7/src/test/java/bug_regression_jdk7/javassist/JavassistVerifyErrorTest.java
+++ b/profiler-optional/profiler-optional-jdk7/src/test/java/bug_regression_jdk7/javassist/JavassistVerifyErrorTest.java
@@ -24,6 +24,7 @@
import javassist.CtMethod;
import javassist.LoaderClassPath;
import org.junit.Assert;
+import org.junit.Ignore;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
@@ -48,6 +49,7 @@ public class JavassistVerifyErrorTest {
* https://github.com/naver/pinpoint/issues/1807
* @throws Exception
*/
+ @Ignore("fixed Javassist 3.21.0-GA")
@Test
public void bug_regression_BytecodeVerifyError_Invalid_StackMapFrame() throws Exception {
| train | train | "2016-10-31T11:07:45" | "2016-05-26T08:42:04Z" | emeroad | test |
pinpoint-apm/pinpoint/2212_2213 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2212 | pinpoint-apm/pinpoint/2213 | [
"keyword_issue_to_pr"
] | 4bef0404edbc8094c0eb6ccf12ee16ed1e513048 | a3b21aa83d7e90fa9c79646173db528dbfbe3b67 | [
"merged via #2213 \n"
] | [] | "2016-11-02T07:44:10Z" | [
"enhancement"
] | Change default span/stat format configuration options | In preparation for 1.6.0 release, change the default span/stat formats to the following values, and remove the "experimental" keyword.
**pinpoint-collector.properties**
```
collector.experimental.span.format.compatibility.version=v1 -> collector.span.format.compatibility.version=v2
collector.experimental.stat.format.compatibility.version=v1 -> collector.stat.format.compatibility.version=v2
```
**pinpoint-web.properties**
```
web.experimental.span.format.compatibility.version=v1 -> web.span.format.compatibility.version=compatibilityMode
web.experimental.stat.format.compatibility.version=v1 -> web.stat.format.compatibility.version=compatibilityMode
``` | [
"collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java",
"collector/src/main/resources/pinpoint-collector.properties",
"quickstart/collector/src/main/resources/pinpoint-collector.properties",
"quickstart/web/src/main/resources/pinpoint-web.properties",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java",
"web/src/main/resources/pinpoint-web.properties"
] | [
"collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java",
"collector/src/main/resources/pinpoint-collector.properties",
"quickstart/collector/src/main/resources/pinpoint-collector.properties",
"quickstart/web/src/main/resources/pinpoint-web.properties",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java",
"web/src/main/resources/pinpoint-web.properties"
] | [] | diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java
index 1d0856a78669..291abeeb4de9 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoFactory.java
@@ -31,8 +31,8 @@ public class HbaseTraceDaoFactory implements FactoryBean<TraceDao> {
@Autowired
private HBaseAdminTemplate adminTemplate;
- @Value("#{pinpoint_collector_properties['collector.experimental.span.format.compatibility.version'] ?: 'v1'}")
- private String mode = "v1";
+ @Value("#{pinpoint_collector_properties['collector.span.format.compatibility.version'] ?: 'v2'}")
+ private String mode = "v2";
@Override
public TraceDao getObject() throws Exception {
diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java
index 679f7766ef53..e08f6d34eb67 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentStatHandlerFactory.java
@@ -47,8 +47,8 @@ public class AgentStatHandlerFactory implements FactoryBean<Handler> {
@Autowired
private HBaseAdminTemplate adminTemplate;
- @Value("#{pinpoint_collector_properties['collector.experimental.stat.format.compatibility.version'] ?: 'v0'}")
- private String mode = "v1";
+ @Value("#{pinpoint_collector_properties['collector.stat.format.compatibility.version'] ?: 'v2'}")
+ private String mode = "v2";
@Override
public Handler getObject() throws Exception {
diff --git a/collector/src/main/resources/pinpoint-collector.properties b/collector/src/main/resources/pinpoint-collector.properties
index 08fe18ef4a7d..b2d38553e9d2 100644
--- a/collector/src/main/resources/pinpoint-collector.properties
+++ b/collector/src/main/resources/pinpoint-collector.properties
@@ -79,10 +79,10 @@ cluster.listen.port=
collector.spanEvent.sequence.limit=10000
-# span.binary format compatibility = v1 or v2 (WARNING : experimental feature)
-# experimental feature span format v2 : https://github.com/naver/pinpoint/issues/1819
-collector.experimental.span.format.compatibility.version=v1
+# span.binary format compatibility = v1 or v2 or dualWrite
+# span format v2 : https://github.com/naver/pinpoint/issues/1819
+collector.span.format.compatibility.version=v2
-# stat handling compatibility = v1 or v2 (WARNING : experimental feature)
-# experimental feature AgentStat data format v2 : https://github.com/naver/pinpoint/issues/1533
-collector.experimental.stat.format.compatibility.version=v1
+# stat handling compatibility = v1 or v2 or dualWrite
+# AgentStatV2 table : https://github.com/naver/pinpoint/issues/1533
+collector.stat.format.compatibility.version=v2
diff --git a/quickstart/collector/src/main/resources/pinpoint-collector.properties b/quickstart/collector/src/main/resources/pinpoint-collector.properties
index d046f8533f8f..3f06af7064bf 100644
--- a/quickstart/collector/src/main/resources/pinpoint-collector.properties
+++ b/quickstart/collector/src/main/resources/pinpoint-collector.properties
@@ -69,10 +69,10 @@ cluster.listen.port=
collector.spanEvent.sequence.limit=5000
-# span.binary format compatibility = v1 or v2 (WARNING : experimental feature)
-# experimental feature span format v2 : https://github.com/naver/pinpoint/issues/1819
-collector.experimental.span.format.compatibility.version=v1
+# span.binary format compatibility = v1 or v2 or dualWrite
+# span format v2 : https://github.com/naver/pinpoint/issues/1819
+collector.span.format.compatibility.version=v2
-# stat handling compatibility = v1 or v2 (WARNING : experimental feature)
-# experimental feature AgentStat data format v2 : https://github.com/naver/pinpoint/issues/1533
-collector.experimental.stat.format.compatibility.version=v1
+# stat handling compatibility = v1 or v2 or dualWrite
+# AgentStatV2 table : https://github.com/naver/pinpoint/issues/1533
+collector.stat.format.compatibility.version=v2
diff --git a/quickstart/web/src/main/resources/pinpoint-web.properties b/quickstart/web/src/main/resources/pinpoint-web.properties
index 68c51ddbb368..64a6bd3fe2c4 100644
--- a/quickstart/web/src/main/resources/pinpoint-web.properties
+++ b/quickstart/web/src/main/resources/pinpoint-web.properties
@@ -32,10 +32,10 @@ web.hbase.selectAllSpans.limit=500
web.activethread.activeAgent.duration.days=7
-# span.binary format compatibility = v1 or v2 (WARNING : experimental feature)
-# experimental feature span format v2 : https://github.com/naver/pinpoint/issues/1819
-web.experimental.span.format.compatibility.version=compatibilityMode
+# span.binary format compatibility = v1 or v2 or compatibilityMode
+# span format v2 : https://github.com/naver/pinpoint/issues/1819
+web.span.format.compatibility.version=compatibilityMode
-# stat handling compatibility = v1 or v2 or compatibilityMode (WARNING : experimental feature)
-# experimental feature AgentStat data format v1 : https://github.com/naver/pinpoint/issues/1533
-web.experimental.stat.format.compatibility.version=compatibilityMode
+# stat handling compatibility = v1 or v2 or compatibilityMode
+# AgentStatV2 table : https://github.com/naver/pinpoint/issues/1533
+web.stat.format.compatibility.version=compatibilityMode
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java
index 703881b47eac..53bfb6cab959 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDaoFactory.java
@@ -34,8 +34,8 @@ public class HbaseTraceDaoFactory implements FactoryBean<TraceDao> {
@Autowired
private HBaseAdminTemplate adminTemplate;
- @Value("#{pinpointWebProps['web.experimental.span.format.compatibility.version'] ?: 'v1'}")
- private String mode = "v1";
+ @Value("#{pinpointWebProps['web.span.format.compatibility.version'] ?: 'v2'}")
+ private String mode = "v2";
@Override
public TraceDao getObject() throws Exception {
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java
index a50e285cbaee..3c43ec916089 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/AgentStatDaoFactory.java
@@ -53,8 +53,8 @@ abstract class AgentStatDaoFactory<T extends AgentStatDataPoint, D extends Agent
@Autowired
private HBaseAdminTemplate adminTemplate;
- @Value("#{pinpointWebProps['web.experimental.stat.format.compatibility.version'] ?: 'v1'}")
- private String mode = "v1";
+ @Value("#{pinpointWebProps['web.stat.format.compatibility.version'] ?: 'v2'}")
+ private String mode = "v2";
D getDao() throws Exception {
logger.info("AgentStatDao Compatibility {}", mode);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java
index 5d70785f4a02..d54522ee0f6f 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/SampledAgentStatDaoFactory.java
@@ -53,8 +53,8 @@ abstract class SampledAgentStatDaoFactory<S extends SampledAgentStatDataPoint, D
@Autowired
private HBaseAdminTemplate adminTemplate;
- @Value("#{pinpointWebProps['web.experimental.stat.format.compatibility.version'] ?: 'v1'}")
- private String mode = "v1";
+ @Value("#{pinpointWebProps['web.stat.format.compatibility.version'] ?: 'v2'}")
+ private String mode = "v2";
D getDao() throws Exception {
logger.info("SampledAgentStatDao Compatibility {}", mode);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java
index 95eaba293bc0..2654f559ae31 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java
@@ -36,8 +36,8 @@ public class LegacyAgentStatChartServiceFactory implements FactoryBean<LegacyAge
private final Logger logger = LoggerFactory.getLogger(this.getClass());
- @Value("#{pinpointWebProps['web.experimental.stat.format.compatibility.version'] ?: 'v1'}")
- private String mode = "v1";
+ @Value("#{pinpointWebProps['web.stat.format.compatibility.version'] ?: 'v2'}")
+ private String mode = "v2";
@Autowired
@Qualifier("legacyAgentStatChartV1Service")
diff --git a/web/src/main/resources/pinpoint-web.properties b/web/src/main/resources/pinpoint-web.properties
index b4a2c4e3980c..581eb49f17f3 100644
--- a/web/src/main/resources/pinpoint-web.properties
+++ b/web/src/main/resources/pinpoint-web.properties
@@ -38,10 +38,10 @@ web.hbase.selectAllSpans.limit=500
web.activethread.activeAgent.duration.days=7
-# span.binary format compatibility = v1 or v2 (WARNING : experimental feature)
-# experimental feature span format v2 : https://github.com/naver/pinpoint/issues/1819
-web.experimental.span.format.compatibility.version=v1
+# span.binary format compatibility = v1 or v2 or compatibilityMode
+# span format v2 : https://github.com/naver/pinpoint/issues/1819
+web.span.format.compatibility.version=compatibilityMode
-# stat handling compatibility = v1 or v2 or compatibilityMode (WARNING : experimental feature)
-# experimental feature AgentStat data format v1 : https://github.com/naver/pinpoint/issues/1533
-web.experimental.stat.format.compatibility.version=v1
+# stat handling compatibility = v1 or v2 or compatibilityMode
+# AgentStatV2 table : https://github.com/naver/pinpoint/issues/1533
+web.stat.format.compatibility.version=compatibilityMode
| null | train | train | "2016-11-02T03:20:36" | "2016-11-02T05:44:31Z" | Xylus | test |
pinpoint-apm/pinpoint/2215_2216 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2215 | pinpoint-apm/pinpoint/2216 | [
"keyword_issue_to_pr"
] | a3b21aa83d7e90fa9c79646173db528dbfbe3b67 | a2ff727d0defda6184d1681c992566d69b7f9da2 | [
"merged via #2216 \n",
"Btw. why did you decide on this change?\n",
"Hi @otisg \nIt was mostly due to performance/feature reasons, ASM seemed to offer better performance and faster startup time, and more features for the agent to expand upon.\n"
] | [] | "2016-11-02T08:51:07Z" | [
"enhancement"
] | Change default instrumentation engine to ASM | Starting from 1.6.0, agent's bytecode instrumentation will use ASM instead of Javassist. | [
"agent/src/main/resources-local/pinpoint.config",
"agent/src/main/resources-release/pinpoint.config",
"agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java",
"quickstart/agent/src/main/resources/pinpoint.config",
"quickstart/conf/pinpoint.config"
] | [
"agent/src/main/resources-local/pinpoint.config",
"agent/src/main/resources-release/pinpoint.config",
"agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java",
"quickstart/agent/src/main/resources/pinpoint.config",
"quickstart/conf/pinpoint.config"
] | [
"agent/src/test/resources/pinpoint-disabled-plugin-test.config"
] | diff --git a/agent/src/main/resources-local/pinpoint.config b/agent/src/main/resources-local/pinpoint.config
index b98f423f1317..960913a0a3c6 100644
--- a/agent/src/main/resources-local/pinpoint.config
+++ b/agent/src/main/resources-local/pinpoint.config
@@ -77,7 +77,7 @@ profiler.callstack.max.depth=64
profiler.interceptor.exception.propagate=false
# Allow bytecode framework (JAVASSIST or ASM)
-profiler.instrument.engine=JAVASSIST
+profiler.instrument.engine=ASM
# bytecode dump option
# java bytecode debug option
diff --git a/agent/src/main/resources-release/pinpoint.config b/agent/src/main/resources-release/pinpoint.config
index 0b74038e98d5..7aff500ebbae 100644
--- a/agent/src/main/resources-release/pinpoint.config
+++ b/agent/src/main/resources-release/pinpoint.config
@@ -73,7 +73,7 @@ profiler.callstack.max.depth=64
profiler.interceptor.exception.propagate=false
# Allow bytecode framework (JAVASSIST or ASM)
-profiler.instrument.engine=JAVASSIST
+profiler.instrument.engine=ASM
# bytecode dump option
# java bytecode debug option
diff --git a/agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config b/agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config
index f7189b224f9b..d0e8f912c8a5 100644
--- a/agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config
+++ b/agent/src/main/resources/pinpoint-real-env-lowoverhead-sample.config
@@ -65,7 +65,7 @@ profiler.callstack.max.depth=64
profiler.interceptor.exception.propagate=false
# Allow bytecode framework (JAVASSIST or ASM)
-profiler.instrument.engine=JAVASSIST
+profiler.instrument.engine=ASM
# java bytecode dump option
bytecode.dump.enable=false
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
index e2c7bd61caa4..c36125f3c338 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
@@ -43,6 +43,7 @@ public class DefaultProfilerConfig implements ProfilerConfig {
private final Properties properties;
private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}");
+ @Deprecated
public static final String INSTRUMENT_ENGINE_JAVASSIST = "JAVASSIST";
public static final String INSTRUMENT_ENGINE_ASM = "ASM";
@@ -370,7 +371,7 @@ void readPropertyValues() {
final ValueResolver placeHolderResolver = new PlaceHolderResolver();
this.profileEnable = readBoolean("profiler.enable", true);
- this.profileInstrumentEngine = readString("profiler.instrument.engine", INSTRUMENT_ENGINE_JAVASSIST);
+ this.profileInstrumentEngine = readString("profiler.instrument.engine", INSTRUMENT_ENGINE_ASM);
this.interceptorRegistrySize = readInt("profiler.interceptorregistry.size", 1024*8);
diff --git a/quickstart/agent/src/main/resources/pinpoint.config b/quickstart/agent/src/main/resources/pinpoint.config
index 41268735acb4..9723796f9d57 100644
--- a/quickstart/agent/src/main/resources/pinpoint.config
+++ b/quickstart/agent/src/main/resources/pinpoint.config
@@ -55,6 +55,25 @@ profiler.tcpdatasender.command.accept.enable=true
# Trace Agent active thread info
profiler.pinpoint.activethread=true
+## Call Stack
+# Set max depth, if -1 is unlimited and min is 2.
+profiler.callstack.max.depth=64
+
+# weather or not to propagate exceptions occurred at interceptor
+profiler.interceptor.exception.propagate=false
+
+# Allow bytecode framework (JAVASSIST or ASM)
+profiler.instrument.engine=ASM
+
+# bytecode dump option
+# java bytecode debug option
+bytecode.dump.enable=false
+#bytecode.dump.classlist=com.naver.user.UserService,com.pinpoint.debug.TestClass
+bytecode.dump.classlist=
+bytecode.dump.bytecode=false
+bytecode.dump.verify=false
+bytecode.dump.asm=false
+
###########################################################
# application type #
###########################################################
diff --git a/quickstart/conf/pinpoint.config b/quickstart/conf/pinpoint.config
index e1a164eea5d5..abccb3d27a1c 100644
--- a/quickstart/conf/pinpoint.config
+++ b/quickstart/conf/pinpoint.config
@@ -55,6 +55,25 @@ profiler.tcpdatasender.command.accept.enable=true
# Trace Agent active thread info
profiler.pinpoint.activethread=true
+## Call Stack
+# Set max depth, if -1 is unlimited and min is 2.
+profiler.callstack.max.depth=64
+
+# weather or not to propagate exceptions occurred at interceptor
+profiler.interceptor.exception.propagate=false
+
+# Allow bytecode framework (JAVASSIST or ASM)
+profiler.instrument.engine=ASM
+
+# bytecode dump option
+# java bytecode debug option
+bytecode.dump.enable=false
+#bytecode.dump.classlist=com.naver.user.UserService,com.pinpoint.debug.TestClass
+bytecode.dump.classlist=
+bytecode.dump.bytecode=false
+bytecode.dump.verify=false
+bytecode.dump.asm=false
+
###########################################################
# application type #
###########################################################
| diff --git a/agent/src/test/resources/pinpoint-disabled-plugin-test.config b/agent/src/test/resources/pinpoint-disabled-plugin-test.config
index 26d06b8aacdf..623d868e3591 100644
--- a/agent/src/test/resources/pinpoint-disabled-plugin-test.config
+++ b/agent/src/test/resources/pinpoint-disabled-plugin-test.config
@@ -51,7 +51,7 @@ profiler.agentInfo.send.retry.interval=300000
profiler.tcpdatasender.command.accept.enable=true
# Allow bytecode framework (JAVASSIST or ASM)
-profiler.instrument.engine=JAVASSIST
+profiler.instrument.engine=ASM
###########################################################
| train | train | "2016-11-02T09:34:46" | "2016-11-02T08:38:48Z" | Xylus | test |
pinpoint-apm/pinpoint/2259_2260 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2259 | pinpoint-apm/pinpoint/2260 | [
"keyword_pr_to_issue"
] | 6465a0f3fddb959c9a7f029d36210db75d6c9ca6 | ca24c0592cd8973520229e864994f0a1fc80c134 | [] | [] | "2016-11-17T10:38:19Z" | [
"bug"
] | Fix potential thread safe problem in InterceptorScope | InterceptorScopePool Field of DefaultProfilerPluginContext is not thread safe.
fixed version : 1.6.0-RC2 | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultProfilerPluginContext.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/xml/interceptor/AnnotatedInterceptorInjector.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/util/NameValueList.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/ConcurrentPool.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/InterceptorScopeFactory.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/Pool.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/PoolObjectFactory.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultProfilerPluginContext.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/xml/interceptor/AnnotatedInterceptorInjector.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/util/NameValueList.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/context/scope/ConcurrentPoolTest.java"
] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/ConcurrentPool.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/ConcurrentPool.java
new file mode 100644
index 000000000000..8d8c83b031b5
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/ConcurrentPool.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.context.scope;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class ConcurrentPool<K, V> implements Pool<K, V> {
+
+ private final ConcurrentMap<K, V> pool = new ConcurrentHashMap<K, V>();
+
+ private final PoolObjectFactory<K, V> objectFactory;
+
+ public ConcurrentPool(PoolObjectFactory<K, V> objectFactory) {
+ if (objectFactory == null) {
+ throw new NullPointerException("objectFactory must not be null");
+ }
+ this.objectFactory = objectFactory;
+ }
+
+ @Override
+ public V get(K key) {
+ if (key == null) {
+ throw new IllegalArgumentException("key must not be null");
+ }
+
+ return pool.get(key);
+ }
+
+ @Override
+ public V add(K key) {
+ if (key == null) {
+ throw new IllegalArgumentException("name must not be null");
+ }
+
+ final V alreadyExist = this.pool.get(key);
+ if (alreadyExist != null) {
+ return alreadyExist;
+ }
+
+ final V newValue = this.objectFactory.create(key);
+ final V oldValue = this.pool.putIfAbsent(key, newValue);
+ if (oldValue != null) {
+ return oldValue;
+ }
+ return newValue;
+ }
+
+
+}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/InterceptorScopeFactory.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/InterceptorScopeFactory.java
new file mode 100644
index 000000000000..f72fd5b5cce9
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/InterceptorScopeFactory.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.context.scope;
+
+import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope;
+import com.navercorp.pinpoint.profiler.interceptor.scope.DefaultInterceptorScope;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class InterceptorScopeFactory implements PoolObjectFactory<String, InterceptorScope> {
+ @Override
+ public InterceptorScope create(String scopeName) {
+ return new DefaultInterceptorScope(scopeName);
+ }
+}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/Pool.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/Pool.java
new file mode 100644
index 000000000000..44259a89d0ef
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/Pool.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.context.scope;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public interface Pool<K, V> {
+
+ V get(K key);
+
+ V add(K key);
+
+}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/PoolObjectFactory.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/PoolObjectFactory.java
new file mode 100644
index 000000000000..707c569dd611
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/scope/PoolObjectFactory.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.context.scope;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public interface PoolObjectFactory<K, V> {
+ V create(K key);
+}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultProfilerPluginContext.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultProfilerPluginContext.java
index 87c3875ade85..a2eb93556591 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultProfilerPluginContext.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultProfilerPluginContext.java
@@ -34,11 +34,13 @@
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPluginSetupContext;
import com.navercorp.pinpoint.profiler.DefaultAgent;
import com.navercorp.pinpoint.profiler.DynamicTransformService;
+import com.navercorp.pinpoint.profiler.context.scope.ConcurrentPool;
+import com.navercorp.pinpoint.profiler.context.scope.InterceptorScopeFactory;
+import com.navercorp.pinpoint.profiler.context.scope.Pool;
import com.navercorp.pinpoint.profiler.instrument.ClassInjector;
import com.navercorp.pinpoint.profiler.instrument.PluginClassInjector;
-import com.navercorp.pinpoint.profiler.interceptor.scope.DefaultInterceptorScope;
import com.navercorp.pinpoint.profiler.util.JavaAssistUtils;
-import com.navercorp.pinpoint.profiler.util.NameValueList;
+
public class DefaultProfilerPluginContext implements ProfilerPluginSetupContext, InstrumentContext {
private final DefaultAgent agent;
@@ -47,7 +49,7 @@ public class DefaultProfilerPluginContext implements ProfilerPluginSetupContext,
private final List<ApplicationTypeDetector> serverTypeDetectors = new ArrayList<ApplicationTypeDetector>();
private final List<ClassFileTransformer> classTransformers = new ArrayList<ClassFileTransformer>();
- private final NameValueList<InterceptorScope> interceptorScopeList = new NameValueList<InterceptorScope>();
+ private final Pool<String, InterceptorScope> interceptorScopePool = new ConcurrentPool<String, InterceptorScope>(new InterceptorScopeFactory());
public DefaultProfilerPluginContext(DefaultAgent agent, ClassInjector classInjector) {
if (agent == null) {
@@ -187,13 +189,7 @@ public InterceptorScope getInterceptorScope(String name) {
if (name == null) {
throw new NullPointerException("name must not be null");
}
- InterceptorScope scope = interceptorScopeList.get(name);
-
- if (scope == null) {
- scope = new DefaultInterceptorScope(name);
- interceptorScopeList.add(name, scope);
- }
-
- return scope;
+
+ return interceptorScopePool.add(name);
}
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/xml/interceptor/AnnotatedInterceptorInjector.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/xml/interceptor/AnnotatedInterceptorInjector.java
index 9fa30d0a69b7..8edddd903935 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/xml/interceptor/AnnotatedInterceptorInjector.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/xml/interceptor/AnnotatedInterceptorInjector.java
@@ -60,7 +60,7 @@ private InterceptorScope getScope() {
if (scopeName == null) {
return null;
} else {
- return pluginContext.getInterceptorScope(scopeName);
+ return pluginContext.getInterceptorScope(scopeName);
}
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/NameValueList.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/NameValueList.java
index f01b7d09ea76..a62c064d1554 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/NameValueList.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/NameValueList.java
@@ -15,13 +15,14 @@
package com.navercorp.pinpoint.profiler.util;
import java.util.ArrayList;
+import java.util.List;
/**
* @author Jongho Moon
*
*/
public class NameValueList<T> {
- private final ArrayList<NameValue<T>> list;
+ private final List<NameValue<T>> list;
public NameValueList() {
this(0);
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/scope/ConcurrentPoolTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/scope/ConcurrentPoolTest.java
new file mode 100644
index 000000000000..0f08dbd40e40
--- /dev/null
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/scope/ConcurrentPoolTest.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package com.navercorp.pinpoint.profiler.context.scope;
+
+import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope;
+import org.junit.Assert;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * @author Woonduk Kang(emeroad)
+ */
+public class ConcurrentPoolTest {
+ @Test
+ public void testConcurrentPool() throws Exception {
+
+ InterceptorScopeFactory traceScopeFactory = new InterceptorScopeFactory();
+ Pool<String, InterceptorScope> pool = new ConcurrentPool<String, InterceptorScope>(traceScopeFactory);
+
+ final String OBJECT_NAME = "test";
+
+ Assert.assertNull(pool.get(OBJECT_NAME));
+
+ InterceptorScope addedScope = pool.add(OBJECT_NAME);
+ Assert.assertSame(pool.get(OBJECT_NAME), addedScope);
+
+ InterceptorScope exist = pool.add(OBJECT_NAME);
+ Assert.assertSame(exist, addedScope);
+ }
+
+}
\ No newline at end of file
| train | train | "2016-11-16T08:58:18" | "2016-11-17T10:03:58Z" | emeroad | test |
pinpoint-apm/pinpoint/2279_2280 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2279 | pinpoint-apm/pinpoint/2280 | [
"keyword_pr_to_issue"
] | 5448dba36fec6cd017b503124df44d135a4d17ee | 340116e6bbf559ad894a7933071030a5239e83e1 | [
"@gitzalm Thanks for the bug report!",
"@gitzalm I fixed bad field name which related to AgentStatics. \r\nThanks for the bug report! :)",
"Great, that was a quick fix."
] | [] | "2016-11-23T05:26:24Z" | [
"bug"
] | Error in logs when using alarms on Mysql | #### Description
I got some error logs when using alarms:
```
Error MySQL com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'date_time' in 'field list' (alarm)
```
I found in IBatis mapper /web/target/deploy/WEB-INF/classes/mapper/AgentStaticsMapper.xml:
```
INSERT INTO agent_statistics (date_time, agent_count)
```
Whereas in web/src/main/resources/sql/CreateTableStatement-mysql.sql there is:
```
CREATE TABLE `agent_statistics` (
`agent_count` INT(10) UNSIGNED NOT NULL,
`date_val`DATETIME NOT NULL,
PRIMARY KEY (`date_val`)
);
```
Which of date_val ou date_time is the right value ?
I hope to find the fix for this before the coming great 1.6.0 release !
#### Environment
* Pinpoint version: 1.6.0-SNAPSHOT (current master)
* Linux CentOS
* Using alarms batch job on mysql
| [
"web/src/main/java/com/navercorp/pinpoint/web/vo/AgentCountStatistics.java",
"web/src/main/resources/batch/applicationContext-batch-schedule.xml",
"web/src/main/resources/mapper/AgentStaticsMapper.xml",
"web/src/main/resources/sql/CreateTableStatement-mysql.sql"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/vo/AgentCountStatistics.java",
"web/src/main/resources/batch/applicationContext-batch-schedule.xml",
"web/src/main/resources/mapper/AgentStaticsMapper.xml",
"web/src/main/resources/sql/CreateTableStatement-mysql.sql"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentCountStatistics.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentCountStatistics.java
index e4dcd6f6dba4..c10b085b08f6 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentCountStatistics.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentCountStatistics.java
@@ -56,11 +56,11 @@ public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
- public String getDateTime() {
+ public String getDateVal() {
return DateUtils.longToDateStr(timestamp, DATE_TIME_FORMAT);
}
- public void setDateTime(String dateTime) throws ParseException {
+ public void setDateVal(String dateTime) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FORMAT);
Date parsedDate = format.parse(dateTime);
diff --git a/web/src/main/resources/batch/applicationContext-batch-schedule.xml b/web/src/main/resources/batch/applicationContext-batch-schedule.xml
index d654595eb0c4..20ff94a9fcc7 100644
--- a/web/src/main/resources/batch/applicationContext-batch-schedule.xml
+++ b/web/src/main/resources/batch/applicationContext-batch-schedule.xml
@@ -13,14 +13,14 @@
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<task:scheduled-tasks scheduler="scheduler">
<task:scheduled ref="batchJobLauncher" method="alarmJob" cron="0 0/3 * * * *" />
- <task:scheduled ref="batchJobLauncher" method="agentCountJob" cron="0 0 2 * * *" />
+ <task:scheduled ref="batchJobLauncher" method="agentCountJob" cron="0 0 2 * * *" />
</task:scheduled-tasks>
<task:scheduler id="scheduler" pool-size="1"/>
<import resource="classpath:batch/applicationContext-batch.xml" />
<import resource="classpath:batch/applicationContext-alarmJob.xml" />
- <import resource="classpath:batch/applicationContext-agentCountJob.xml" />
+ <import resource="classpath:batch/applicationContext-agentCountJob.xml" />
+
-
</beans>
\ No newline at end of file
diff --git a/web/src/main/resources/mapper/AgentStaticsMapper.xml b/web/src/main/resources/mapper/AgentStaticsMapper.xml
index 670cb1359de8..09fc5cd593f3 100644
--- a/web/src/main/resources/mapper/AgentStaticsMapper.xml
+++ b/web/src/main/resources/mapper/AgentStaticsMapper.xml
@@ -4,12 +4,12 @@
<mapper namespace="com.navercorp.pinpoint.web.dao.mysql.MysqlAgentStatisticsDao">
<insert id="insertAgentCount" parameterType="AgentCountStatistics">
- INSERT INTO agent_statistics (date_time, agent_count)
+ INSERT INTO agent_statistics (date_val, agent_count)
VALUES
- (#{dateTime}, #{agentCount})
+ (#{dateVal}, #{agentCount})
ON DUPLICATE KEY UPDATE
<trim suffixOverrides=",">
- <if test="dateTime != null">date_time = #{dateTime},</if>
+ <if test="dateVal != null">date_val = #{dateVal},</if>
<if test="agentCount != null">agent_count = #{agentCount},</if>
</trim>
</insert>
@@ -17,7 +17,7 @@
<select id="selectAgentCount" parameterType="Range" resultType="AgentCountStatistics">
SELECT *
FROM agent_statistics
- WHERE date_time
+ WHERE date_val
BETWEEN #{fromDateTime} AND #{toDateTime}
</select>
diff --git a/web/src/main/resources/sql/CreateTableStatement-mysql.sql b/web/src/main/resources/sql/CreateTableStatement-mysql.sql
index 9e6a520e946e..48e75eb2cc2f 100644
--- a/web/src/main/resources/sql/CreateTableStatement-mysql.sql
+++ b/web/src/main/resources/sql/CreateTableStatement-mysql.sql
@@ -55,7 +55,7 @@ CREATE TABLE `alarm_history` (
ALTER TABLE alarm_history ADD UNIQUE KEY application_id_checker_name_idx (application_id, checker_name);
CREATE TABLE `agent_statistics` (
- `agent_count` INT(10) UNSIGNED NOT NULL,
- `date_val`DATETIME NOT NULL,
- PRIMARY KEY (`date_val`)
+ `agent_count` INT(10) UNSIGNED NOT NULL,
+ `date_val`DATETIME NOT NULL,
+ PRIMARY KEY (`date_val`)
);
| null | val | train | "2016-11-22T10:22:02" | "2016-11-22T14:07:52Z" | gitzalm | test |
pinpoint-apm/pinpoint/2299_2300 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2299 | pinpoint-apm/pinpoint/2300 | [
"keyword_pr_to_issue"
] | 81ebb90849ce25ab24eaf7b05d5e1c202eb5d777 | 56eb10db6cf31de2cc3ec2e1c37dd3822304d621 | [
"@ofauchon \r\nSorry it is bug of scatter chart.\r\nGUI value stored in localStorage. if you want to remove your setting you must clear your localStorage.\r\n",
"@ofauchon \r\nI fixed this issue. \r\nCould you retry it using current master branch.\r\n\r\nThanks for reporting!",
"I'll rebuild from master and test that ASAP. \r\n\r\nThanks for the fix.\r\n\r\n "
] | [] | "2016-12-07T05:56:38Z" | [
"bug"
] | Scatter chart stuck, how to reset settings | Hi.
I use Pinpoint RC2
No idea why my scatter chart is not working anymore (It was fine for a couple of weeks)
![image](https://cloud.githubusercontent.com/assets/561441/20931919/0fa15564-bbd3-11e6-860f-fa790eb5066c.png)
... Maybe after I set Y Axis to 30 ms , but I can't change it anymore, as I can't click on options gear
(the cursor is in crosshair mode, no click possible)
I could find that the following request: http://server/getScatterData.pinpoint?to=1481038925000&from=1481038625000&limit=5000&filter=&application=APPLICATION&xGroupUnit=987&yGroupUnit=0
returns:
"java.lang.IllegalArgumentException: **yGroupUnit(0)** must be positive number\r\n\tat com.navercorp.pinpoint.web.controller.ScatterChartController.getScatterData(ScatterChartController.java:156)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.lang.reflect.Method.invoke(Method.java:497)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:775)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)\r\n\tat
....
Could you please tell me:
- Where are stored these GUI settings (they seem permanent) and how to reset to defaults ?
- What is yGroupUnit ? Is it related to Y max value on the graph ?
Thanks
| [
"web/src/main/java/com/navercorp/pinpoint/web/controller/ScatterChartController.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/controller/ScatterChartController.java"
] | [] | 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 6e09b6b564dd..e90a79c52755 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
@@ -16,23 +16,6 @@
package com.navercorp.pinpoint.web.controller;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.lang3.StringUtils;
-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 org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.servlet.ModelAndView;
-
import com.navercorp.pinpoint.common.server.bo.SpanBo;
import com.navercorp.pinpoint.common.util.DateUtils;
import com.navercorp.pinpoint.common.util.TransactionId;
@@ -48,6 +31,22 @@
import com.navercorp.pinpoint.web.vo.LimitedScanResult;
import com.navercorp.pinpoint.web.vo.Range;
import com.navercorp.pinpoint.web.vo.TransactionMetadataQuery;
+import org.apache.commons.lang3.StringUtils;
+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 org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.servlet.ModelAndView;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
/**
* @author netspider
@@ -152,8 +151,8 @@ public ModelAndView getScatterData(
if (xGroupUnit <= 0) {
throw new IllegalArgumentException("xGroupUnit(" + xGroupUnit + ") must be positive number");
}
- if (yGroupUnit <= 0) {
- throw new IllegalArgumentException("yGroupUnit(" + yGroupUnit + ") must be positive number");
+ if (yGroupUnit < 0) {
+ throw new IllegalArgumentException("yGroupUnit(" + yGroupUnit + ") may not be negative number");
}
limit = LimitUtils.checkRange(limit);
@@ -167,9 +166,9 @@ public ModelAndView getScatterData(
ModelAndView mv = null;
if (StringUtils.isEmpty(filterText)) {
- mv = selectScatterData(applicationName, range, xGroupUnit, yGroupUnit, limit, backwardDirection, version);
+ mv = selectScatterData(applicationName, range, xGroupUnit, Math.max(yGroupUnit, 1), limit, backwardDirection, version);
} else {
- mv = selectFilterScatterData(applicationName, range, xGroupUnit, yGroupUnit, limit, backwardDirection, filterText, version);
+ mv = selectFilterScatterData(applicationName, range, xGroupUnit, Math.max(yGroupUnit, 1), limit, backwardDirection, filterText, version);
}
if (jsonpCallback == null) {
| null | test | train | "2016-12-06T10:51:13" | "2016-12-06T15:59:52Z" | ofauchon | test |
pinpoint-apm/pinpoint/2334_2336 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2334 | pinpoint-apm/pinpoint/2336 | [
"keyword_pr_to_issue"
] | 6d42e5ebae55dbda7367f39cc4ec2aad0cfba924 | c45cd9a20caa997b947f49c1616333487ba2f409 | [] | [] | "2016-12-13T01:31:56Z" | [
"bug"
] | Fix executing fail networktest script |
#### Description
Sometimes "icmp port unreachble error" occure when executing networktest script.
| [
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/BaseUDPHandlerFactory.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/ChunkedUDPPacketHandlerFactory.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/NetworkAvailabilityCheckPacketFilter.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PacketHandler.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/SpanStreamUDPPacketHandlerFactory.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilter.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilterChain.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/UDPReceiver.java"
] | [
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/BaseUDPHandlerFactory.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/ChunkedUDPPacketHandlerFactory.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/NetworkAvailabilityCheckPacketFilter.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PacketHandler.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/SpanStreamUDPPacketHandlerFactory.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilter.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilterChain.java",
"collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/UDPReceiver.java"
] | [
"collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NetworkAvailabilityCheckPacketFilterTest.java",
"collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/SpanStreamUDPSenderTest.java",
"collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/TestUDPReceiver.java"
] | diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/BaseUDPHandlerFactory.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/BaseUDPHandlerFactory.java
index 3b40b32f1add..df6aad145185 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/BaseUDPHandlerFactory.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/BaseUDPHandlerFactory.java
@@ -27,6 +27,7 @@
import org.slf4j.LoggerFactory;
import java.net.DatagramPacket;
+import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
@@ -103,7 +104,7 @@ private DispatchPacket() {
}
@Override
- public void receive(T packet) {
+ public void receive(DatagramSocket localSocket, T packet) {
if (isIgnoreAddress(packet.getAddress())) {
return;
}
@@ -114,7 +115,7 @@ public void receive(T packet) {
try {
tBase = deserializer.deserialize(packet.getData());
- if (filter.filter(tBase, socketAddress) == TBaseFilter.BREAK) {
+ if (filter.filter(localSocket, tBase, socketAddress) == TBaseFilter.BREAK) {
return;
}
// dispatch signifies business logic execution
diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/ChunkedUDPPacketHandlerFactory.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/ChunkedUDPPacketHandlerFactory.java
index ef20dd7a87b2..db96f377e57a 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/ChunkedUDPPacketHandlerFactory.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/ChunkedUDPPacketHandlerFactory.java
@@ -64,7 +64,7 @@ private DispatchPacket() {
}
@Override
- public void receive(T packet) {
+ public void receive(DatagramSocket localSocket, T packet) {
final ChunkHeaderTBaseDeserializer deserializer = deserializerFactory.createDeserializer();
try {
List<TBase<?, ?>> list = deserializer.deserialize(packet.getData(), packet.getOffset(), packet.getLength());
@@ -73,7 +73,7 @@ public void receive(T packet) {
}
for (TBase<?, ?> tBase : list) {
- if (filter.filter(tBase, packet.getSocketAddress()) == TBaseFilter.BREAK) {
+ if (filter.filter(localSocket, tBase, packet.getSocketAddress()) == TBaseFilter.BREAK) {
return;
}
// dispatch signifies business logic execution
diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/NetworkAvailabilityCheckPacketFilter.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/NetworkAvailabilityCheckPacketFilter.java
index 7b5bf4bb0a55..aebf1c3fff8c 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/NetworkAvailabilityCheckPacketFilter.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/NetworkAvailabilityCheckPacketFilter.java
@@ -31,31 +31,23 @@
public class NetworkAvailabilityCheckPacketFilter<T extends SocketAddress> implements TBaseFilter<T>, DisposableBean {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
- private final DatagramSocket socket;
-
public NetworkAvailabilityCheckPacketFilter() {
- try {
- this.socket = new DatagramSocket();
- logger.info("port:{}", this.socket.getLocalAddress());
- } catch (SocketException ex) {
- throw new RuntimeException("socket create fail. error:" + ex.getMessage(), ex);
- }
}
@Override
- public boolean filter(TBase<?, ?> tBase, T remoteHostAddress) {
+ public boolean filter(DatagramSocket localSocket, TBase<?, ?> tBase, T remoteHostAddress) {
// Network port availability check packet
if (tBase instanceof NetworkAvailabilityCheckPacket) {
if (logger.isInfoEnabled()) {
logger.info("received udp network availability check packet. remoteAddress:{}", remoteHostAddress);
}
- responseOK(remoteHostAddress);
+ responseOK(localSocket, remoteHostAddress);
return BREAK;
}
return CONTINUE;
}
- private void responseOK(T remoteHostAddress) {
+ private void responseOK(DatagramSocket socket, T remoteHostAddress) {
try {
byte[] okBytes = NetworkAvailabilityCheckPacket.DATA_OK;
DatagramPacket pongPacket = new DatagramPacket(okBytes, okBytes.length, remoteHostAddress);
@@ -70,12 +62,6 @@ private void responseOK(T remoteHostAddress) {
@Override
public void destroy() throws Exception {
- if (socket!= null) {
- try {
- socket.close();
- } catch (Exception e) {
- logger.warn("socket.close() error:" + e.getMessage(), e);
- }
- }
}
+
}
diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PacketHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PacketHandler.java
index 88fbf1dee902..5bb26a0f557c 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PacketHandler.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PacketHandler.java
@@ -16,9 +16,13 @@
package com.navercorp.pinpoint.collector.receiver.udp;
+import java.net.DatagramSocket;
+
/**
* @author emeroad
*/
public interface PacketHandler<T> {
- void receive(T packet);
+
+ void receive(DatagramSocket localSocket, T packet);
+
}
diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java
index 57afcead1ff6..a7f57923d04a 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/PooledPacketWrap.java
@@ -19,21 +19,27 @@
import com.navercorp.pinpoint.collector.util.PooledObject;
import java.net.DatagramPacket;
+import java.net.DatagramSocket;
/**
* @author emeroad
*/
public class PooledPacketWrap implements Runnable {
+ private final DatagramSocket localSocket;
private final PacketHandler<DatagramPacket> packetHandler;
private final PooledObject<DatagramPacket> pooledObject;
- public PooledPacketWrap(PacketHandler<DatagramPacket> packetHandler, PooledObject<DatagramPacket> pooledObject) {
+ public PooledPacketWrap(DatagramSocket localSocket, PacketHandler<DatagramPacket> packetHandler, PooledObject<DatagramPacket> pooledObject) {
+ if (localSocket == null) {
+ throw new NullPointerException("localSocket may not be null");
+ }
if (packetHandler == null) {
throw new NullPointerException("packetReceiveHandler must not be null");
}
if (pooledObject == null) {
throw new NullPointerException("pooledObject must not be null");
}
+ this.localSocket = localSocket;
this.packetHandler = packetHandler;
this.pooledObject = pooledObject;
}
@@ -42,7 +48,7 @@ public PooledPacketWrap(PacketHandler<DatagramPacket> packetHandler, PooledObjec
public void run() {
final DatagramPacket packet = pooledObject.getObject();
try {
- packetHandler.receive(packet);
+ packetHandler.receive(localSocket, packet);
} finally {
pooledObject.returnObject();
}
diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/SpanStreamUDPPacketHandlerFactory.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/SpanStreamUDPPacketHandlerFactory.java
index 58f11d111052..aa83ac1bb4d0 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/SpanStreamUDPPacketHandlerFactory.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/SpanStreamUDPPacketHandlerFactory.java
@@ -27,6 +27,7 @@
import org.slf4j.LoggerFactory;
import java.net.DatagramPacket;
+import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
@@ -70,7 +71,7 @@ private DispatchPacket() {
}
@Override
- public void receive(DatagramPacket packet) {
+ public void receive(DatagramSocket localSocket, DatagramPacket packet) {
final HeaderTBaseDeserializer deserializer = deserializerFactory.createDeserializer();
ByteBuffer requestBuffer = ByteBuffer.wrap(packet.getData());
@@ -104,7 +105,7 @@ public void receive(DatagramPacket packet) {
}
if (tbaseList.size() == 1) {
- if (filter.filter(tbaseList.get(0), socketAddress) == TBaseFilter.BREAK) {
+ if (filter.filter(localSocket, tbaseList.get(0), socketAddress) == TBaseFilter.BREAK) {
continue;
}
}
diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilter.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilter.java
index 0eb686911d45..82125213f5f8 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilter.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilter.java
@@ -18,6 +18,7 @@
import org.apache.thrift.TBase;
+import java.net.DatagramSocket;
import java.net.SocketAddress;
/**
@@ -27,13 +28,15 @@ public interface TBaseFilter<T> {
boolean CONTINUE = true;
boolean BREAK = false;
- boolean filter(TBase<?, ?> tBase, T remoteHostAddress);
+ boolean filter(DatagramSocket localSocket, TBase<?, ?> tBase, T remoteHostAddress);
// TODO fix generic type
TBaseFilter CONTINUE_FILTER = new TBaseFilter<SocketAddress>() {
+
@Override
- public boolean filter(TBase<?, ?> tBase, SocketAddress remoteHostAddress) {
+ public boolean filter(DatagramSocket localSocket, TBase<?, ?> tBase, SocketAddress remoteHostAddress) {
return CONTINUE;
}
+
};
}
diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilterChain.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilterChain.java
index c0de0d64d90f..a7ebef410210 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilterChain.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/TBaseFilterChain.java
@@ -18,6 +18,7 @@
import org.apache.thrift.TBase;
+import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
@@ -37,12 +38,13 @@ public TBaseFilterChain(List<TBaseFilter<T>> tBaseFilter) {
}
@Override
- public boolean filter(TBase<?, ?> tBase, T remoteHostAddress) {
+ public boolean filter(DatagramSocket localSocket, TBase<?, ?> tBase, T remoteHostAddress) {
for (TBaseFilter tBaseFilter : filterChain) {
- if (tBaseFilter.filter(tBase, remoteHostAddress) == TBaseFilter.BREAK) {
+ if (tBaseFilter.filter(localSocket, tBase, remoteHostAddress) == TBaseFilter.BREAK) {
return BREAK;
}
}
return TBaseFilter.CONTINUE;
}
+
}
diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/UDPReceiver.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/UDPReceiver.java
index f635613a56cd..e428c9b43453 100644
--- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/UDPReceiver.java
+++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/UDPReceiver.java
@@ -16,6 +16,25 @@
package com.navercorp.pinpoint.collector.receiver.udp;
+import com.codahale.metrics.MetricRegistry;
+import com.navercorp.pinpoint.collector.monitor.MonitoredExecutorService;
+import com.navercorp.pinpoint.collector.receiver.DataReceiver;
+import com.navercorp.pinpoint.collector.receiver.WorkerOption;
+import com.navercorp.pinpoint.collector.util.DatagramPacketFactory;
+import com.navercorp.pinpoint.collector.util.DefaultObjectPool;
+import com.navercorp.pinpoint.collector.util.ObjectPool;
+import com.navercorp.pinpoint.collector.util.PacketUtils;
+import com.navercorp.pinpoint.collector.util.PooledObject;
+import com.navercorp.pinpoint.common.util.ExecutorFactory;
+import com.navercorp.pinpoint.common.util.PinpointThreadFactory;
+import com.navercorp.pinpoint.rpc.util.CpuUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.util.Assert;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
@@ -31,27 +50,6 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.util.Assert;
-
-import com.codahale.metrics.MetricRegistry;
-import com.navercorp.pinpoint.collector.monitor.MonitoredExecutorService;
-import com.navercorp.pinpoint.collector.receiver.DataReceiver;
-import com.navercorp.pinpoint.collector.receiver.WorkerOption;
-import com.navercorp.pinpoint.collector.util.DatagramPacketFactory;
-import com.navercorp.pinpoint.collector.util.DefaultObjectPool;
-import com.navercorp.pinpoint.collector.util.ObjectPool;
-import com.navercorp.pinpoint.collector.util.PacketUtils;
-import com.navercorp.pinpoint.collector.util.PooledObject;
-import com.navercorp.pinpoint.common.util.ExecutorFactory;
-import com.navercorp.pinpoint.common.util.PinpointThreadFactory;
-import com.navercorp.pinpoint.rpc.util.CpuUtils;
-
/**
* @author emeroad
* @author netspider
@@ -183,7 +181,7 @@ private Runnable wrapDispatchTask(final PooledObject<DatagramPacket> pooledPacke
@Override
public void run() {
PacketHandler<DatagramPacket> dispatchPacket = packetHandlerFactory.createPacketHandler();
- PooledPacketWrap pooledPacketWrap = new PooledPacketWrap(dispatchPacket, pooledPacket);
+ PooledPacketWrap pooledPacketWrap = new PooledPacketWrap(socket, dispatchPacket, pooledPacket);
Runnable execution = pooledPacketWrap;
execution.run();
}
| diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NetworkAvailabilityCheckPacketFilterTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NetworkAvailabilityCheckPacketFilterTest.java
index 9ad0e614eed4..c25578201734 100644
--- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NetworkAvailabilityCheckPacketFilterTest.java
+++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NetworkAvailabilityCheckPacketFilterTest.java
@@ -38,33 +38,42 @@ public class NetworkAvailabilityCheckPacketFilterTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private NetworkAvailabilityCheckPacketFilter filter;
- private DatagramSocket datagramSocket;
+ private DatagramSocket senderSocket;
+ private DatagramSocket receiverSocket;
@Before
public void setUp() throws Exception {
filter = new NetworkAvailabilityCheckPacketFilter();
- datagramSocket = new DatagramSocket(0);
+ senderSocket = new DatagramSocket(0);
+ receiverSocket = new DatagramSocket(0);
}
@After
public void tearDown() throws Exception {
filter.destroy();
- datagramSocket.close();
+ try {
+ senderSocket.close();
+ } catch (Exception e) {
+ }
+ try {
+ receiverSocket.close();
+ } catch (Exception e) {
+ }
}
@Test
public void testFilter() throws Exception {
- SocketAddress localSocketAddress = datagramSocket.getLocalSocketAddress();
+ SocketAddress localSocketAddress = senderSocket.getLocalSocketAddress();
logger.debug("localSocket:{}", localSocketAddress);
NetworkAvailabilityCheckPacket packet = new NetworkAvailabilityCheckPacket();
- boolean skipResult = filter.filter(packet, new InetSocketAddress("localhost", datagramSocket.getLocalPort()));
+ boolean skipResult = filter.filter(receiverSocket, packet, new InetSocketAddress("localhost", senderSocket.getLocalPort()));
Assert.assertEquals(skipResult, TBaseFilter.BREAK);
DatagramPacket receivePacket = new DatagramPacket(new byte[100], 100);
- datagramSocket.receive(receivePacket);
+ senderSocket.receive(receivePacket);
Assert.assertEquals(receivePacket.getLength(), NetworkAvailabilityCheckPacket.DATA_OK.length);
Assert.assertArrayEquals(Arrays.copyOf(receivePacket.getData(), NetworkAvailabilityCheckPacket.DATA_OK.length), NetworkAvailabilityCheckPacket.DATA_OK);
@@ -74,11 +83,11 @@ public void testFilter() throws Exception {
@Test
public void testFilter_Continue() throws Exception {
- SocketAddress localSocketAddress = datagramSocket.getLocalSocketAddress();
+ SocketAddress localSocketAddress = senderSocket.getLocalSocketAddress();
logger.debug("localSocket:{}", localSocketAddress);
TSpan skip = new TSpan();
- boolean skipResult = filter.filter(skip, null);
+ boolean skipResult = filter.filter(receiverSocket, skip, null);
Assert.assertEquals(skipResult, TBaseFilter.CONTINUE);
diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/SpanStreamUDPSenderTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/SpanStreamUDPSenderTest.java
index 4691a5baab28..c2464836c021 100644
--- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/SpanStreamUDPSenderTest.java
+++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/SpanStreamUDPSenderTest.java
@@ -44,6 +44,7 @@
import org.springframework.util.SocketUtils;
import java.io.IOException;
+import java.net.DatagramSocket;
import java.util.ArrayList;
import java.util.List;
@@ -234,7 +235,7 @@ static class TestTBaseFilter<T> implements TBaseFilter<T> {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
- public boolean filter(TBase<?, ?> tBase, T remoteHostAddress) {
+ public boolean filter(DatagramSocket localSocket, TBase<?, ?> tBase, T remoteHostAddress) {
logger.debug("filter");
return false;
}
diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/TestUDPReceiver.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/TestUDPReceiver.java
index 18f97e7f2ed5..f7b76080dc18 100644
--- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/TestUDPReceiver.java
+++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/TestUDPReceiver.java
@@ -16,6 +16,21 @@
package com.navercorp.pinpoint.collector.receiver.udp;
+import com.navercorp.pinpoint.collector.receiver.DataReceiver;
+import com.navercorp.pinpoint.collector.util.DatagramPacketFactory;
+import com.navercorp.pinpoint.collector.util.DefaultObjectPool;
+import com.navercorp.pinpoint.collector.util.ObjectPool;
+import com.navercorp.pinpoint.collector.util.PacketUtils;
+import com.navercorp.pinpoint.collector.util.PooledObject;
+import com.navercorp.pinpoint.common.util.ExecutorFactory;
+import com.navercorp.pinpoint.common.util.PinpointThreadFactory;
+import com.navercorp.pinpoint.rpc.util.CpuUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.util.Assert;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
@@ -31,23 +46,6 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.util.Assert;
-
-import com.navercorp.pinpoint.collector.receiver.DataReceiver;
-import com.navercorp.pinpoint.collector.util.DatagramPacketFactory;
-import com.navercorp.pinpoint.collector.util.DefaultObjectPool;
-import com.navercorp.pinpoint.collector.util.ObjectPool;
-import com.navercorp.pinpoint.collector.util.PacketUtils;
-import com.navercorp.pinpoint.collector.util.PooledObject;
-import com.navercorp.pinpoint.common.util.ExecutorFactory;
-import com.navercorp.pinpoint.common.util.PinpointThreadFactory;
-import com.navercorp.pinpoint.rpc.util.CpuUtils;
-
public class TestUDPReceiver implements DataReceiver {
private final Logger logger;
@@ -155,7 +153,7 @@ private Runnable wrapDispatchTask(final PooledObject<DatagramPacket> pooledPacke
@Override
public void run() {
PacketHandler<DatagramPacket> dispatchPacket = packetHandlerFactory.createPacketHandler();
- PooledPacketWrap pooledPacketWrap = new PooledPacketWrap(dispatchPacket, pooledPacket);
+ PooledPacketWrap pooledPacketWrap = new PooledPacketWrap(socket, dispatchPacket, pooledPacket);
Runnable execution = pooledPacketWrap;
execution.run();
}
| test | train | "2016-12-12T11:07:11" | "2016-12-12T08:08:03Z" | koo-taejin | test |
pinpoint-apm/pinpoint/2391_2392 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2391 | pinpoint-apm/pinpoint/2392 | [
"keyword_pr_to_issue"
] | 1e98aaf016873ea97b2978b1027b480abffc4c4d | 62285cf140333e95f0b3ddf3a8ebc6105ae91f39 | [] | [] | "2016-12-26T05:20:23Z" | [
"bug"
] | Fix that the profiler.jdbc.dbcp option is not working. | Currently, there is a problem that does not apply when setting profiler.jdbc.dbcp in pinpoint.config. (always:true)
I will fix it.
| [
"plugins/dbcp/src/main/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpPlugin.java"
] | [
"plugins/dbcp/src/main/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpConfig.java",
"plugins/dbcp/src/main/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpPlugin.java"
] | [
"plugins/dbcp/src/test/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpConfigTest.java"
] | diff --git a/plugins/dbcp/src/main/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpConfig.java b/plugins/dbcp/src/main/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpConfig.java
new file mode 100644
index 000000000000..faec905908d3
--- /dev/null
+++ b/plugins/dbcp/src/main/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpConfig.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.commons.dbcp;
+
+import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
+
+/**
+ * @author Taejin Koo
+ */
+public class CommonsDbcpConfig {
+
+ static final String DBCP_PLUGIN_ENABLE = "profiler.jdbc.dbcp";
+ static final String DBCP_PROFILE_CONNECTIONCLOSE_ENABLE = "profiler.jdbc.dbcp.connectionclose";
+
+ private final boolean pluginEnable;
+ private final boolean profileClose;
+
+ public CommonsDbcpConfig(ProfilerConfig config) {
+ pluginEnable = config.readBoolean(DBCP_PLUGIN_ENABLE, false);
+ profileClose = config.readBoolean(DBCP_PROFILE_CONNECTIONCLOSE_ENABLE, false);
+ }
+
+ public boolean isPluginEnable() {
+ return pluginEnable;
+ }
+
+ public boolean isProfileClose() {
+ return profileClose;
+ }
+
+}
diff --git a/plugins/dbcp/src/main/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpPlugin.java b/plugins/dbcp/src/main/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpPlugin.java
index cca71f8db740..34a30f6e38e9 100644
--- a/plugins/dbcp/src/main/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpPlugin.java
+++ b/plugins/dbcp/src/main/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpPlugin.java
@@ -15,35 +15,46 @@
*/
package com.navercorp.pinpoint.plugin.commons.dbcp;
-import java.security.ProtectionDomain;
-
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentClass;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentException;
import com.navercorp.pinpoint.bootstrap.instrument.Instrumentor;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformCallback;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplate;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplateAware;
+import com.navercorp.pinpoint.bootstrap.logging.PLogger;
+import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPlugin;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPluginSetupContext;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.common.trace.ServiceTypeFactory;
+import java.security.ProtectionDomain;
+
/**
* @author Jongho Moon
*/
public class CommonsDbcpPlugin implements ProfilerPlugin, TransformTemplateAware {
+
+ private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
+
+
public static final ServiceType DBCP_SERVICE_TYPE = ServiceTypeFactory.of(6050, "DBCP");
public static final String DBCP_SCOPE = "DBCP_SCOPE";
+ private CommonsDbcpConfig config;
+
private TransformTemplate transformTemplate;
@Override
public void setup(ProfilerPluginSetupContext context) {
+ config = new CommonsDbcpConfig(context.getConfig());
+ if (!config.isPluginEnable()) {
+ logger.info("Disable commons dbcp option. 'profiler.jdbc.dbcp=false'");
+ return;
+ }
+
addBasicDataSourceTransformer();
-
- boolean profileClose = context.getConfig().readBoolean("profiler.jdbc.dbcp.connectionclose", false);
-
- if (profileClose) {
+ if (config.isProfileClose()) {
addPoolGuardConnectionWrapperTransformer();
}
}
| diff --git a/plugins/dbcp/src/test/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpConfigTest.java b/plugins/dbcp/src/test/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpConfigTest.java
new file mode 100644
index 000000000000..fb24d26bef44
--- /dev/null
+++ b/plugins/dbcp/src/test/java/com/navercorp/pinpoint/plugin/commons/dbcp/CommonsDbcpConfigTest.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.commons.dbcp;
+
+import com.navercorp.pinpoint.bootstrap.config.DefaultProfilerConfig;
+import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.Properties;
+
+/**
+ * @author Taejin Koo
+ */
+public class CommonsDbcpConfigTest {
+
+ @Test
+ public void configTest1() throws Exception {
+ CommonsDbcpConfig commonsDbcpConfig = createCommonsDbcpConfig("false", "false");
+
+ Assert.assertFalse(commonsDbcpConfig.isPluginEnable());
+ Assert.assertFalse(commonsDbcpConfig.isProfileClose());
+ }
+
+ @Test
+ public void configTest2() throws Exception {
+ CommonsDbcpConfig commonsDbcpConfig = createCommonsDbcpConfig("false", "true");
+
+ Assert.assertFalse(commonsDbcpConfig.isPluginEnable());
+ Assert.assertTrue(commonsDbcpConfig.isProfileClose());
+ }
+
+ @Test
+ public void configTest3() throws Exception {
+ CommonsDbcpConfig commonsDbcpConfig = createCommonsDbcpConfig("true", "false");
+
+ Assert.assertTrue(commonsDbcpConfig.isPluginEnable());
+ Assert.assertFalse(commonsDbcpConfig.isProfileClose());
+ }
+
+ @Test
+ public void configTest4() throws Exception {
+ CommonsDbcpConfig commonsDbcpConfig = createCommonsDbcpConfig("true", "true");
+
+ Assert.assertTrue(commonsDbcpConfig.isPluginEnable());
+ Assert.assertTrue(commonsDbcpConfig.isProfileClose());
+ }
+
+ private CommonsDbcpConfig createCommonsDbcpConfig(String pluginEnable, String profileConnectionCloseEnable) {
+ Properties properties = new Properties();
+ properties.put(CommonsDbcpConfig.DBCP_PLUGIN_ENABLE, pluginEnable);
+ properties.put(CommonsDbcpConfig.DBCP_PROFILE_CONNECTIONCLOSE_ENABLE, profileConnectionCloseEnable);
+
+ ProfilerConfig profilerConfig = new DefaultProfilerConfig(properties);
+
+ return new CommonsDbcpConfig(profilerConfig);
+ }
+
+}
| train | train | "2016-12-21T08:30:38" | "2016-12-26T02:11:05Z" | koo-taejin | test |
pinpoint-apm/pinpoint/2394_2395 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2394 | pinpoint-apm/pinpoint/2395 | [
"keyword_pr_to_issue"
] | b19d39339b665b6424b6cd4de7e7ba28471ff476 | 2d33b55fe052a4d63faffac8f3989c1c7d0febd1 | [] | [] | "2016-12-26T06:53:47Z" | [
"bug"
] | LinkKey hash function always returns 0 | #### Description
The `hashCode()` method in [LinkKey](https://github.com/naver/pinpoint/blob/master/web/src/main/java/com/navercorp/pinpoint/web/vo/LinkKey.java#L106) class always returns 0. resulting in N * N equals comparisons for caller/callee pairs when querying server map. | [
"web/src/main/java/com/navercorp/pinpoint/web/vo/LinkKey.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/vo/LinkKey.java"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/LinkKey.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/LinkKey.java
index 58bffa661265..eb92600afcfe 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/vo/LinkKey.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/LinkKey.java
@@ -103,7 +103,7 @@ public boolean equals(Object o) {
@Override
public int hashCode() {
final int hash = this.hash;
- if (hash == 0) {
+ if (hash != 0) {
return hash;
}
int result = fromApplication.hashCode();
| null | test | train | "2016-12-26T07:33:18" | "2016-12-26T06:31:23Z" | Xylus | test |
pinpoint-apm/pinpoint/2403_2404 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2403 | pinpoint-apm/pinpoint/2404 | [
"keyword_pr_to_issue"
] | 38b5860e4fb60d38221fd946cb78ae2f06f96281 | b152cab0e88e736782435a41991ae305f2a39177 | [] | [] | "2016-12-27T07:11:19Z" | [
"enhancement"
] | Add support for MariaDB java client 1.5.6 | #### Description
SQL bind values are not traced in MariaDB java client 1.5.6 due to a change in class name : `org.mariadb.jdbc.AbstractMariaDbPrepareStatement` -> `org.mariadb.jdbc.AbstractPrepareStatement`. | [
"plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java"
] | [
"plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java"
] | [] | diff --git a/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java b/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java
index 840a465006e3..03074c785110 100644
--- a/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java
+++ b/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java
@@ -185,6 +185,8 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
};
transformTemplate.transform("org.mariadb.jdbc.AbstractMariaDbPrepareStatement", transformer);
+ // Class renamed in 1.5.6 - https://github.com/MariaDB/mariadb-connector-j/commit/16c8313960cf4fbc6b2b83136504d1ba9e662919
+ transformTemplate.transform("org.mariadb.jdbc.AbstractPrepareStatement", transformer);
}
| null | train | train | "2016-12-27T08:07:01" | "2016-12-27T07:07:17Z" | Xylus | test |
pinpoint-apm/pinpoint/2345_2407 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2345 | pinpoint-apm/pinpoint/2407 | [
"keyword_pr_to_issue"
] | 698042eacda733bb747ba450c4945989e95a7c28 | 4e4b675fb91fd75ddafac3a667da9c9d6709faa7 | [] | [] | "2016-12-29T07:38:50Z" | [
"enhancement"
] | Make use of agent start timestamp when calculating gc count and time | #### Description
With the addition of #2282, gc count and gc time calculation should take agent start timestamp into account. This brings in added benefits such as more precise calculation when data is sampled over a period with application restarts, or packet losses.
Calculations should also be done server side to take burden off the client. | [
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/v2/HbaseAgentStatDaoOperationsV2.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/ActiveTraceSampler.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/AgentStatSampler.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/CpuLoadSampler.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcDetailedSampler.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcSampler.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/SampledAgentStatResultExtractor.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/TransactionSampler.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/v2/HbaseAgentStatDaoOperationsV2.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/AbstractAgentStatSampler.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/ActiveTraceSampler.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/AgentStatSampler.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/CpuLoadSampler.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcDetailedSampler.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcSampler.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/SampledAgentStatResultExtractor.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/TransactionSampler.java"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/mapper/stat/SampledAgentStatResultExtractorTest.java"
] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/v2/HbaseAgentStatDaoOperationsV2.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/v2/HbaseAgentStatDaoOperationsV2.java
index 333daed9f9fc..490eb9682bd0 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/v2/HbaseAgentStatDaoOperationsV2.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/stat/v2/HbaseAgentStatDaoOperationsV2.java
@@ -86,7 +86,7 @@ <T extends AgentStatDataPoint> boolean agentStatExists(AgentStatType agentStatTy
logger.debug("checking for stat data existence : agentId={}, {}", agentId, range);
}
- int resultLimit = 1;
+ int resultLimit = 20;
Scan scan = this.createScan(agentStatType, agentId, range, resultLimit);
List<List<T>> result = hbaseOperations2.findParallel(HBaseTables.AGENT_STAT_VER2, scan, this.operationFactory.getRowKeyDistributor(), resultLimit, mapper, AGENT_STAT_VER2_NUM_PARTITIONS);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/AbstractAgentStatSampler.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/AbstractAgentStatSampler.java
new file mode 100644
index 000000000000..0e19f9366d76
--- /dev/null
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/AbstractAgentStatSampler.java
@@ -0,0 +1,151 @@
+package com.navercorp.pinpoint.web.mapper.stat;
+
+import com.navercorp.pinpoint.common.server.bo.stat.AgentStatDataPoint;
+import com.navercorp.pinpoint.web.util.TimeWindow;
+import com.navercorp.pinpoint.web.vo.stat.SampledAgentStatDataPoint;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * @author HyunGil Jeong
+ */
+public abstract class AbstractAgentStatSampler<T extends AgentStatDataPoint, S extends SampledAgentStatDataPoint> implements AgentStatSampler<T, S> {
+
+ private static final int INITIAL_TIME_WINDOW_INDEX = -1;
+ private static final Comparator<Long> REVERSE_TIMESTAMP_COMPARATOR = new Comparator<Long>() {
+ @Override
+ public int compare(Long o1, Long o2) {
+ return o2.compareTo(o1);
+ }
+ };
+
+ @Override
+ public final List<S> sampleDataPoints(TimeWindow timeWindow, List<T> dataPoints) {
+ Map<Long, List<T>> dataPointPartitions = partitionDataPoints(dataPoints);
+
+ Map<Long, Map<Long, S>> sampledPointProjection = mapProjection(timeWindow, dataPointPartitions);
+
+ List<S> sampledDataPoints = new ArrayList<>(sampledPointProjection.size());
+ for (Map<Long, S> sampledPointCandidates : sampledPointProjection.values()) {
+ sampledDataPoints.add(reduceSampledPoints(sampledPointCandidates));
+ }
+ return sampledDataPoints;
+ }
+
+ /**
+ * Returns a map of data points partitioned by the start timestamp of the agent. This is mainly to distinguish
+ * between different agent life cycles, and prevent stats from being mixed up when there are multiple agents with
+ * the same agent id.
+ *
+ * @param dataPoints a list of data points to partition
+ * @return a map of data points partitioned by agent start timestamps
+ */
+ private Map<Long, List<T>> partitionDataPoints(List<T> dataPoints) {
+ Map<Long, List<T>> dataPointPartitions = new HashMap<>();
+ for (T jvmGcBo : dataPoints) {
+ long startTimestamp = jvmGcBo.getStartTimestamp();
+ List<T> dataPointPartition = dataPointPartitions.get(startTimestamp);
+ if (dataPointPartition == null) {
+ dataPointPartition = new ArrayList<>(dataPoints.size());
+ dataPointPartitions.put(startTimestamp, dataPointPartition);
+ }
+ dataPointPartition.add(jvmGcBo);
+ }
+ return dataPointPartitions;
+ }
+
+ /**
+ * Collapses multiple projections of sampled data points into a single map with key sorted by timeslot timestamp,
+ * and values being sampled data points of different agent life cycles mapped by their agent start timestamp.
+ *
+ * @param timeWindow the TimeWindow used to create the timeslot map
+ * @param dataPointPartitions a map of data points partitioned by their agent start timestamp
+ * @return a map of timeslots with sampled data points mapped by their agent start timestamp as values
+ */
+ private Map<Long, Map<Long, S>> mapProjection(TimeWindow timeWindow, Map<Long, List<T>> dataPointPartitions) {
+ Map<Long, Map<Long, S>> sampledPointProjection = new TreeMap<>();
+ for (Map.Entry<Long, List<T>> dataPointPartitionEntry : dataPointPartitions.entrySet()) {
+ Long startTimestamp = dataPointPartitionEntry.getKey();
+ List<T> dataPointPartition = dataPointPartitionEntry.getValue();
+ Map<Long, S> sampledDataPointPartition = sampleDataPointPartition(timeWindow, dataPointPartition);
+
+ for (Map.Entry<Long, S> e : sampledDataPointPartition.entrySet()) {
+ Long timeslotTimestamp = e.getKey();
+ S sampledDataPoint = e.getValue();
+ Map<Long, S> timeslotSampleEntry = sampledPointProjection.get(timeslotTimestamp);
+ if (timeslotSampleEntry == null) {
+ timeslotSampleEntry = new TreeMap<>(REVERSE_TIMESTAMP_COMPARATOR);
+ sampledPointProjection.put(timeslotTimestamp, timeslotSampleEntry);
+ }
+ timeslotSampleEntry.put(startTimestamp, sampledDataPoint);
+ }
+ }
+ return sampledPointProjection;
+ }
+
+ /**
+ * Returns a map of timeslot timestamps with sampled data points as value.
+ *
+ * @param timeWindow the TimeWindow used to create the timeslot map
+ * @param dataPoints a list of data points to sample
+ * @return a map of timeslots with sampled data points as values
+ */
+ private Map<Long, S> sampleDataPointPartition(TimeWindow timeWindow, List<T> dataPoints) {
+ Map<Long, S> sampledDataPoints = new HashMap<>((int) timeWindow.getWindowRangeCount());
+ T previous;
+ List<T> currentBatch = new ArrayList<>();
+ int currentTimeWindowIndex = INITIAL_TIME_WINDOW_INDEX;
+ long currentTimeslotTimestamp = 0;
+ for (T dataPoint : dataPoints) {
+ long timestamp = dataPoint.getTimestamp();
+ int timeWindowIndex = timeWindow.getWindowIndex(timestamp);
+ if (currentTimeWindowIndex == INITIAL_TIME_WINDOW_INDEX || currentTimeWindowIndex == timeWindowIndex) {
+ currentBatch.add(dataPoint);
+ } else if (timeWindowIndex < currentTimeWindowIndex) {
+ previous = dataPoint;
+ // currentBatch shouldn't be empty at this point
+ S sampledBatch = sampleDataPoints(currentTimeslotTimestamp, currentBatch, previous);
+ sampledDataPoints.put(currentTimeslotTimestamp, sampledBatch);
+ currentBatch = new ArrayList<>(currentBatch.size());
+ currentBatch.add(dataPoint);
+ } else {
+ // Results should be sorted in a descending order of their actual timestamp values
+ // as they are stored using reverse timestamp.
+ throw new IllegalStateException("Out of order AgentStatDataPoint");
+ }
+ currentTimeslotTimestamp = timeWindow.refineTimestamp(timestamp);
+ currentTimeWindowIndex = timeWindowIndex;
+ }
+ if (!currentBatch.isEmpty()) {
+ S sampledBatch = sampleDataPoints(currentTimeslotTimestamp, currentBatch, null);
+ sampledDataPoints.put(currentTimeslotTimestamp, sampledBatch);
+ }
+ return sampledDataPoints;
+ }
+
+ /**
+ * Returns the sampled data point of the most recently started agent out of multiple candidates.
+ *
+ * @param sampledPointCandidates a map of sampled data points to reduce mapped by their agent start timestamp
+ * @return sampled data point of the most recently started agent
+ */
+ protected S reduceSampledPoints(Map<Long, S> sampledPointCandidates) {
+ long latestStartTimestamp = -1L;
+ S sampledPointToUse = null;
+ for (Map.Entry<Long, S> e : sampledPointCandidates.entrySet()) {
+ long startTimestamp = e.getKey();
+ if (startTimestamp > latestStartTimestamp) {
+ latestStartTimestamp = startTimestamp;
+ sampledPointToUse = e.getValue();
+ }
+ }
+ return sampledPointToUse;
+ }
+
+ protected abstract S sampleDataPoints(long timestamp, List<T> dataPoints, T previousDataPoint);
+}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/ActiveTraceSampler.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/ActiveTraceSampler.java
index 673cbbabfb0a..306d1474062d 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/ActiveTraceSampler.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/ActiveTraceSampler.java
@@ -36,7 +36,7 @@
* @author HyunGil Jeong
*/
@Component
-public class ActiveTraceSampler implements AgentStatSampler<ActiveTraceBo, SampledActiveTrace> {
+public class ActiveTraceSampler extends AbstractAgentStatSampler<ActiveTraceBo, SampledActiveTrace> {
public static final DownSampler<Integer> INTEGER_DOWN_SAMPLER = DownSamplers.getIntegerDownSampler(ActiveTraceBo.UNCOLLECTED_ACTIVE_TRACE_COUNT);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/AgentStatSampler.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/AgentStatSampler.java
index fcb2650c8244..5f31e46bc798 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/AgentStatSampler.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/AgentStatSampler.java
@@ -1,6 +1,7 @@
package com.navercorp.pinpoint.web.mapper.stat;
import com.navercorp.pinpoint.common.server.bo.stat.AgentStatDataPoint;
+import com.navercorp.pinpoint.web.util.TimeWindow;
import com.navercorp.pinpoint.web.vo.stat.SampledAgentStatDataPoint;
import java.util.List;
@@ -10,5 +11,5 @@
*/
public interface AgentStatSampler<T extends AgentStatDataPoint, S extends SampledAgentStatDataPoint> {
- S sampleDataPoints(long timestamp, List<T> dataPoints, T previousDataPoint);
+ List<S> sampleDataPoints(TimeWindow timeWindow, List<T> dataPoints);
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/CpuLoadSampler.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/CpuLoadSampler.java
index 4d5afdf7d2b7..58c1d11b40cb 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/CpuLoadSampler.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/CpuLoadSampler.java
@@ -31,7 +31,7 @@
* @author HyunGil Jeong
*/
@Component
-public class CpuLoadSampler implements AgentStatSampler<CpuLoadBo, SampledCpuLoad> {
+public class CpuLoadSampler extends AbstractAgentStatSampler<CpuLoadBo, SampledCpuLoad> {
private static final int NUM_DECIMAL_PLACES = 1;
public static final DownSampler<Double> DOUBLE_DOWN_SAMPLER = DownSamplers.getDoubleDownSampler(CpuLoadBo.UNCOLLECTED_VALUE, NUM_DECIMAL_PLACES);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcDetailedSampler.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcDetailedSampler.java
index 414793d36a53..1125520bbe84 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcDetailedSampler.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcDetailedSampler.java
@@ -31,7 +31,7 @@
* @author HyunGil Jeong
*/
@Component
-public class JvmGcDetailedSampler implements AgentStatSampler<JvmGcDetailedBo, SampledJvmGcDetailed> {
+public class JvmGcDetailedSampler extends AbstractAgentStatSampler<JvmGcDetailedBo, SampledJvmGcDetailed> {
private static final int NUM_DECIMAL_PLACES = 1;
public static final DownSampler<Long> LONG_DOWN_SAMPLER = DownSamplers.getLongDownSampler(JvmGcDetailedBo.UNCOLLECTED_VALUE);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcSampler.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcSampler.java
index 68162d82abc0..f75c9c45784f 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcSampler.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/JvmGcSampler.java
@@ -32,7 +32,7 @@
* @author HyunGil Jeong
*/
@Component
-public class JvmGcSampler implements AgentStatSampler<JvmGcBo, SampledJvmGc> {
+public class JvmGcSampler extends AbstractAgentStatSampler<JvmGcBo, SampledJvmGc> {
public static final DownSampler<Long> LONG_DOWN_SAMPLER = DownSamplers.getLongDownSampler(JvmGcBo.UNCOLLECTED_VALUE);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/SampledAgentStatResultExtractor.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/SampledAgentStatResultExtractor.java
index 34ee8517dbf5..de8eab93a397 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/SampledAgentStatResultExtractor.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/SampledAgentStatResultExtractor.java
@@ -24,6 +24,7 @@
import org.apache.hadoop.hbase.client.ResultScanner;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
@@ -32,12 +33,9 @@
*/
public class SampledAgentStatResultExtractor<T extends AgentStatDataPoint, S extends SampledAgentStatDataPoint> implements ResultsExtractor<List<S>> {
- private static final int INITIAL_TIME_WINDOW_INDEX = -1;
-
private final TimeWindow timeWindow;
private final AgentStatMapper<T> rowMapper;
private final AgentStatSampler<T, S> sampler;
- private final List<S> sampledDataPoints;
public SampledAgentStatResultExtractor(TimeWindow timeWindow, AgentStatMapper<T> rowMapper, AgentStatSampler<T, S> sampler) {
if (timeWindow.getWindowRangeCount() > Integer.MAX_VALUE) {
@@ -46,48 +44,22 @@ public SampledAgentStatResultExtractor(TimeWindow timeWindow, AgentStatMapper<T>
this.timeWindow = timeWindow;
this.rowMapper = rowMapper;
this.sampler = sampler;
- this.sampledDataPoints = new ArrayList<>((int) timeWindow.getWindowRangeCount());
}
@Override
public List<S> extractData(ResultScanner results) throws Exception {
int rowNum = 0;
- // Sample straight away, tossing out already sampled data points so they can be garbage collected
- // as soon as possible.
- // This is mainly important when querying over a long period of time where sampling after all the data has been
- // deserialized would consume too much memory.
- T previous;
- List<T> currentBatch = new ArrayList<>();
- int currentTimeWindowIndex = INITIAL_TIME_WINDOW_INDEX;
- long currentTimeslotTimestamp = 0;
+ List<T> aggregatedDataPoints = new ArrayList<>();
for (Result result : results) {
- List<T> dataPoints = this.rowMapper.mapRow(result, rowNum++);
- for (T dataPoint : dataPoints) {
- long timestamp = dataPoint.getTimestamp();
- int timeWindowIndex = this.timeWindow.getWindowIndex(timestamp);
- if (currentTimeWindowIndex == INITIAL_TIME_WINDOW_INDEX || currentTimeWindowIndex == timeWindowIndex) {
- currentBatch.add(dataPoint);
- } else if (timeWindowIndex < currentTimeWindowIndex) {
- previous = dataPoint;
- // currentBatch shouldn't be empty at this point
- S sampledBatch = sampler.sampleDataPoints(currentTimeslotTimestamp, currentBatch, previous);
- this.sampledDataPoints.add(sampledBatch);
- currentBatch = new ArrayList<>();
- currentBatch.add(dataPoint);
- } else {
- // Results should be sorted in a descending order of their actual timestamp values
- // as they are stored using reverse timestamp.
- throw new IllegalStateException("Out of order AgentStatDataPoint");
- }
- currentTimeslotTimestamp = this.timeWindow.refineTimestamp(timestamp);
- currentTimeWindowIndex = timeWindowIndex;
- }
+ aggregatedDataPoints.addAll(this.rowMapper.mapRow(result, rowNum++));
}
- if (!currentBatch.isEmpty()) {
- S sampledBatch = sampler.sampleDataPoints(currentTimeslotTimestamp, currentBatch, null);
- sampledDataPoints.add(sampledBatch);
+ List<S> sampledDataPoints;
+ if (aggregatedDataPoints.isEmpty()) {
+ sampledDataPoints = Collections.emptyList();
+ } else {
+ sampledDataPoints = sampler.sampleDataPoints(timeWindow, aggregatedDataPoints);
}
- return this.sampledDataPoints;
+ return sampledDataPoints;
}
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/TransactionSampler.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/TransactionSampler.java
index a8a420ec92c6..a14320f3326b 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/TransactionSampler.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/TransactionSampler.java
@@ -32,7 +32,7 @@
* @author HyunGil Jeong
*/
@Component
-public class TransactionSampler implements AgentStatSampler<TransactionBo, SampledTransaction> {
+public class TransactionSampler extends AbstractAgentStatSampler<TransactionBo, SampledTransaction> {
private static final double UNCOLLECTED_TPS = -1D;
private static final int NUM_DECIMAL_PLACES = 1;
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/mapper/stat/SampledAgentStatResultExtractorTest.java b/web/src/test/java/com/navercorp/pinpoint/web/mapper/stat/SampledAgentStatResultExtractorTest.java
index e0e05bf02606..e438b0c52796 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/mapper/stat/SampledAgentStatResultExtractorTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/mapper/stat/SampledAgentStatResultExtractorTest.java
@@ -175,7 +175,7 @@ private List<TestAgentStatDataPoint> createDataPoints(long finalTimestamp, long
return dataPoints;
}
- private static class TestAgentStatSampler implements AgentStatSampler<TestAgentStatDataPoint, TestSampledAgentStatDataPoint> {
+ private static class TestAgentStatSampler extends AbstractAgentStatSampler<TestAgentStatDataPoint, TestSampledAgentStatDataPoint> {
@Override
public TestSampledAgentStatDataPoint sampleDataPoints(long timestamp, List<TestAgentStatDataPoint> dataPoints, TestAgentStatDataPoint previousDataPoint) {
| train | train | "2016-12-27T08:54:06" | "2016-12-14T10:08:11Z" | Xylus | test |
pinpoint-apm/pinpoint/2332_2429 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2332 | pinpoint-apm/pinpoint/2429 | [
"keyword_pr_to_issue"
] | b424c45031ae9b26cfe47e90b220dae99726209e | 227ecb27df36c21ece2fd91d55efd05a8061cb13 | [] | [] | "2017-01-04T05:38:41Z" | [
"bug"
] | Agents running on OpenJDK does not collect CPU stats | #### Description
`CpuLoadMetricSetSelector` currently returns `EmptyCpuLoadMetricSet` when running on open jdk. Since open jdk can use the same cpu load collector as the one used on oracle jvm, adding a simple check should fix this problem - related to #2330
#### Environment
<!--- Include as many relevant details about the environment you experienced the bug in -->
* Pinpoint version: 1.6.0
* OS, WAS, affected library, etc: Affects agents running on OpenJDK vm
* Additional details (e.g. how your collector/web is set up): not applicable
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadMetricSetSelector.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/CpuLoadMetricSetSelector.java"
] | [] | 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 c3f841fde9c0..8111cb620b40 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
@@ -52,7 +52,7 @@ public static CpuLoadMetricSet getCpuLoadMetricSet(String vendorName) {
vmType = JvmUtils.getType();
}
JvmVersion vmVersion = JvmUtils.getVersion();
- if (vmType == JvmType.ORACLE) {
+ if (vmType == JvmType.ORACLE || vmType == JvmType.OPENJDK) {
if (vmVersion.onOrAfter(JvmVersion.JAVA_7)) {
classToLoad = ORACLE_CPU_LOAD_METRIC_SET_FQCN;
} else if (vmVersion.onOrAfter(JvmVersion.JAVA_5)) {
| null | train | train | "2017-01-04T05:47:59" | "2016-12-12T06:56:28Z" | Xylus | test |
pinpoint-apm/pinpoint/2436_2437 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2436 | pinpoint-apm/pinpoint/2437 | [
"keyword_pr_to_issue"
] | 6f44a94502412ba7b688d3c4574bf35ec2f24bbf | ffe7c9989a4553d35fd1d5041d0cece0a673a0c8 | [] | [] | "2017-01-05T02:30:47Z" | [
"bug"
] | Fix execution failed networktest.sh script | #### Description
Corrects failures when invoking a collector configured with a load balancer. | [
"tools/src/main/java/com/navercorp/pinpoint/tools/network/UDPChecker.java"
] | [
"tools/src/main/java/com/navercorp/pinpoint/tools/network/UDPChecker.java"
] | [] | diff --git a/tools/src/main/java/com/navercorp/pinpoint/tools/network/UDPChecker.java b/tools/src/main/java/com/navercorp/pinpoint/tools/network/UDPChecker.java
index 0e8886af9c54..068a2d828850 100644
--- a/tools/src/main/java/com/navercorp/pinpoint/tools/network/UDPChecker.java
+++ b/tools/src/main/java/com/navercorp/pinpoint/tools/network/UDPChecker.java
@@ -41,9 +41,9 @@ protected boolean check(InetSocketAddress address) throws IOException {
protected boolean check(InetSocketAddress address, byte[] requestData, byte[] expectedResponseData) {
DatagramSocket socket = null;
try {
- socket = createSocket(address);
+ socket = createSocket();
- write(socket, requestData);
+ write(socket, requestData, address);
byte[] responseData = read(socket, expectedResponseData.length);
return Arrays.equals(expectedResponseData, responseData);
@@ -57,6 +57,13 @@ protected boolean check(InetSocketAddress address, byte[] requestData, byte[] ex
return false;
}
+ private DatagramSocket createSocket() throws IOException {
+ DatagramSocket socket = new DatagramSocket();
+
+ socket.setSoTimeout(3000);
+ return socket;
+ }
+
private DatagramSocket createSocket(InetSocketAddress socketAddress) throws IOException {
DatagramSocket socket = new DatagramSocket();
socket.connect(socketAddress);
@@ -65,8 +72,8 @@ private DatagramSocket createSocket(InetSocketAddress socketAddress) throws IOEx
return socket;
}
- private void write(DatagramSocket socket, byte[] requestData) throws IOException {
- DatagramPacket datagramPacket = new DatagramPacket(requestData, requestData.length);
+ private void write(DatagramSocket socket, byte[] requestData, InetSocketAddress address) throws IOException {
+ DatagramPacket datagramPacket = new DatagramPacket(requestData, requestData.length, address);
socket.send(datagramPacket);
}
| null | val | train | "2017-01-04T09:18:32" | "2017-01-05T01:45:56Z" | koo-taejin | test |
pinpoint-apm/pinpoint/2385_2697 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2385 | pinpoint-apm/pinpoint/2697 | [
"keyword_pr_to_issue"
] | 60d6311a78b4f44c81c2ffc38f923ad9241b4faa | d8d3e023518d62f92ec2a554fa1b678ae0c2391d | [] | [] | "2017-03-13T10:48:06Z" | [
"enhancement"
] | Add better logging for when application's main class cannot be deduced from properties | #### Description
The application's main class is currently deduced by reading in `sun.java.command` property. For Java versions prior to 1.6.0_25, this property is not present (other JVMs may not have this at all).
The log should be improved when this property is not found to let users spot the problem easier and to possibly let them know of a solution/workaround.
(Looking through the call stack to retrieve the main class would be another option but this is a different issue entirely)
| [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java"
] | [] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java
index 71343f464083..9d237fbd3d1e 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java
@@ -21,6 +21,7 @@
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
+import com.navercorp.pinpoint.common.util.JvmUtils;
import com.navercorp.pinpoint.common.util.SimpleProperty;
import com.navercorp.pinpoint.common.util.SystemProperty;
import com.navercorp.pinpoint.common.util.SystemPropertyKey;
@@ -47,6 +48,12 @@ public MainClassCondition(SimpleProperty property) {
throw new IllegalArgumentException("properties should not be null");
}
this.applicationMainClassName = getMainClassName(property);
+ if (this.applicationMainClassName == NOT_FOUND) {
+ logger.info("Main class could not be deduced, please set 'profiler.applicationservertype' in pinpoint.config.");
+ logger.info("If you're running on 1.6.0_24 or prior version of Java, consider upgrading to 1.6.0_25+.");
+ logger.info("If you're running Tomcat or Tomcat on Spring Boot, please set 'profiler.tomcat.conditional.transform' to false");
+ logger.info("If you're running Jboss, please set 'profiler.tomcat.conditional.transform' to false");
+ }
}
/**
@@ -87,7 +94,8 @@ public String getValue() {
private String getMainClassName(SimpleProperty property) {
String javaCommand = property.getProperty(SystemPropertyKey.SUN_JAVA_COMMAND.getKey(), "").split(" ")[0];
if (javaCommand.isEmpty()) {
- logger.warn("Error retrieving main class from [{}]", property.getClass().getName());
+ String jreVersion = property.getProperty(SystemPropertyKey.JAVA_RUNTIME_VERSION.getKey());
+ logger.warn("Error retrieving main class using '{}', jre : {}", SystemPropertyKey.SUN_JAVA_COMMAND.getKey(), jreVersion);
return NOT_FOUND;
} else {
JarFile executableArchive = null;
@@ -100,7 +108,7 @@ private String getMainClassName(SimpleProperty property) {
return javaCommand;
} catch (Exception e) {
// fail-safe, application shouldn't not start because of this
- logger.warn("Error retrieving main class from java command : [{}]", javaCommand, e);
+ logger.warn("Error retrieving main class", e);
return NOT_FOUND;
} finally {
if (executableArchive != null) {
| null | val | train | "2017-03-13T11:27:56" | "2016-12-21T05:57:02Z" | Xylus | test |
pinpoint-apm/pinpoint/2522_2830 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2522 | pinpoint-apm/pinpoint/2830 | [
"keyword_pr_to_issue"
] | fff109d32fb554121ec4880338f996145b01c472 | 9cebba0c669cda2cb9975f4bebf7a175a66cf982 | [
"Skipping 0.10.x integration tests due to conflict in pinpoint agent's internal thrift version.\r\nThrift plugin currently works with libthrift 0.10.0.",
"Reopening issue to see if progress can be made here now that pinpoint's thrift version is upgraded to 0.10.0 (#2725)",
"Keep testing libthrift 0.9.x for regression.",
"Above change breaks all IT as giving libthrift test scope makes libthrift unavailable at runtime, should revert back to testing 0.10.x."
] | [] | "2017-04-18T05:49:59Z" | [
"enhancement",
"module:plugin"
] | Fix Thrift plugin integration tests to run on 0.10.x | #### Description
~~Thrift 0.10.0 is out with some internal changes that is currently not compatible with the thrift plugin.
Thrift plugin needs to be updated to support this.~~
Thrift 0.10.0 introduces breaking changes to auto-generated `AsyncIface` methods, which requires regenerating test service to run on libthrift 0.10.0.
The internals have not been changed as far as tracing with Thrift plugin is concerned. Only integration tests need fixing. | [
"agent/pom.xml"
] | [
"agent/pom.xml"
] | [
"agent/src/test/resources/thrift/Echo.thrift"
] | diff --git a/agent/pom.xml b/agent/pom.xml
index 626a559b26fb..b134b426d37f 100644
--- a/agent/pom.xml
+++ b/agent/pom.xml
@@ -194,6 +194,13 @@
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.thrift</groupId>
+ <artifactId>libthrift</artifactId>
+ <version>0.9.3</version>
+ <scope>test</scope>
+ </dependency>
+
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
| diff --git a/agent/src/test/resources/thrift/Echo.thrift b/agent/src/test/resources/thrift/Echo.thrift
new file mode 100644
index 000000000000..c8eed567f3cb
--- /dev/null
+++ b/agent/src/test/resources/thrift/Echo.thrift
@@ -0,0 +1,6 @@
+namespace java com.navercorp.pinpoint.plugin.thrift.dto
+
+service EchoService
+{
+ string echo(1:string message)
+}
\ No newline at end of file
| train | train | "2017-04-17T11:26:52" | "2017-01-23T07:01:33Z" | Xylus | test |
pinpoint-apm/pinpoint/2522_2831 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2522 | pinpoint-apm/pinpoint/2831 | [
"keyword_pr_to_issue"
] | 9cebba0c669cda2cb9975f4bebf7a175a66cf982 | eb0915af355afa967613533c6a9a07de3c0729a5 | [
"Skipping 0.10.x integration tests due to conflict in pinpoint agent's internal thrift version.\r\nThrift plugin currently works with libthrift 0.10.0.",
"Reopening issue to see if progress can be made here now that pinpoint's thrift version is upgraded to 0.10.0 (#2725)",
"Keep testing libthrift 0.9.x for regression.",
"Above change breaks all IT as giving libthrift test scope makes libthrift unavailable at runtime, should revert back to testing 0.10.x."
] | [] | "2017-04-18T07:51:52Z" | [
"enhancement",
"module:plugin"
] | Fix Thrift plugin integration tests to run on 0.10.x | #### Description
~~Thrift 0.10.0 is out with some internal changes that is currently not compatible with the thrift plugin.
Thrift plugin needs to be updated to support this.~~
Thrift 0.10.0 introduces breaking changes to auto-generated `AsyncIface` methods, which requires regenerating test service to run on libthrift 0.10.0.
The internals have not been changed as far as tracing with Thrift plugin is concerned. Only integration tests need fixing. | [
"agent/pom.xml"
] | [
"agent/pom.xml"
] | [
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/dto/EchoService.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java"
] | diff --git a/agent/pom.xml b/agent/pom.xml
index b134b426d37f..626a559b26fb 100644
--- a/agent/pom.xml
+++ b/agent/pom.xml
@@ -194,13 +194,6 @@
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.apache.thrift</groupId>
- <artifactId>libthrift</artifactId>
- <version>0.9.3</version>
- <scope>test</scope>
- </dependency>
-
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
| diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
index 2fb969f85d4b..0a952a5be2f6 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
@@ -60,7 +60,7 @@ private AsyncEchoTestClient(TestEnvironment environment) throws IOException {
public String echo(String message) throws TException {
final CountDownLatch latch = new CountDownLatch(1);
final AsyncEchoResultHolder resultHolder = new AsyncEchoResultHolder();
- final AsyncMethodCallback<EchoService.AsyncClient.echo_call> callback = new EchoMethodCallback(latch, resultHolder);
+ final AsyncMethodCallback<String> callback = new EchoMethodCallback(latch, resultHolder);
this.asyncClient.echo(message, callback);
boolean isInterrupted = false;
while (true) {
@@ -135,7 +135,7 @@ public void close() {
}
}
- private static class EchoMethodCallback implements AsyncMethodCallback<EchoService.AsyncClient.echo_call> {
+ private static class EchoMethodCallback implements AsyncMethodCallback<String> {
private final CountDownLatch completeLatch;
private final AsyncEchoResultHolder resultHolder;
@@ -146,15 +146,9 @@ private EchoMethodCallback(final CountDownLatch completeLatch, final AsyncEchoRe
}
@Override
- public void onComplete(EchoService.AsyncClient.echo_call response) {
- try {
- String result = response.getResult();
- this.resultHolder.setResult(result);
- } catch (TException e) {
- this.resultHolder.setResult(e.toString());
- } finally {
- this.completeLatch.countDown();
- }
+ public void onComplete(String response) {
+ this.resultHolder.setResult(response);
+ this.completeLatch.countDown();
}
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/dto/EchoService.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/dto/EchoService.java
index 70674c7a0e95..0f4464a789c5 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/dto/EchoService.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/dto/EchoService.java
@@ -1,969 +1,969 @@
+/*
+ * Copyright 2017 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
/**
- * Autogenerated by Thrift Compiler (0.9.1)
+ * Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.navercorp.pinpoint.plugin.thrift.dto;
-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.TMessage;
-import org.apache.thrift.protocol.TProtocol;
-import org.apache.thrift.protocol.TTupleProtocol;
-import org.apache.thrift.TException;
-import org.apache.thrift.async.AsyncMethodCallback;
-import org.apache.thrift.server.AbstractNonblockingServer.*;
-
-import java.util.Map;
-import java.util.HashMap;
-import java.util.EnumMap;
-import java.util.EnumSet;
-import java.util.Collections;
-import java.util.BitSet;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
+@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
+@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-01-25")
public class EchoService {
- public interface Iface {
+ public interface Iface {
- public String echo(String message) throws org.apache.thrift.TException;
+ public String echo(String message) throws org.apache.thrift.TException;
- }
+ }
- public interface AsyncIface {
+ public interface AsyncIface {
- public void echo(String message, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
+ public void echo(String message, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws org.apache.thrift.TException;
- }
+ }
- public static class Client extends org.apache.thrift.TServiceClient implements Iface {
- public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
- public Factory() {}
- public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
- return new Client(prot);
- }
- public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
- return new Client(iprot, oprot);
- }
- }
-
- public Client(org.apache.thrift.protocol.TProtocol prot)
- {
- super(prot, prot);
- }
+ public static class Client extends org.apache.thrift.TServiceClient implements Iface {
+ public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
+ public Factory() {}
+ public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
+ return new Client(prot);
+ }
+ public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
+ return new Client(iprot, oprot);
+ }
+ }
- public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
- super(iprot, oprot);
- }
+ public Client(org.apache.thrift.protocol.TProtocol prot)
+ {
+ super(prot, prot);
+ }
- public String echo(String message) throws org.apache.thrift.TException
- {
- send_echo(message);
- return recv_echo();
- }
+ public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
+ super(iprot, oprot);
+ }
- public void send_echo(String message) throws org.apache.thrift.TException
- {
- echo_args args = new echo_args();
- args.setMessage(message);
- sendBase("echo", args);
- }
+ public String echo(String message) throws org.apache.thrift.TException
+ {
+ send_echo(message);
+ return recv_echo();
+ }
- public String recv_echo() throws org.apache.thrift.TException
- {
- echo_result result = new echo_result();
- receiveBase(result, "echo");
- if (result.isSetSuccess()) {
- return result.success;
- }
- throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echo failed: unknown result");
- }
+ public void send_echo(String message) throws org.apache.thrift.TException
+ {
+ echo_args args = new echo_args();
+ args.setMessage(message);
+ sendBase("echo", args);
+ }
+ public String recv_echo() throws org.apache.thrift.TException
+ {
+ echo_result result = new echo_result();
+ receiveBase(result, "echo");
+ if (result.isSetSuccess()) {
+ return result.success;
+ }
+ throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echo failed: unknown result");
}
- public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
- public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
- private org.apache.thrift.async.TAsyncClientManager clientManager;
- private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
- public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
- this.clientManager = clientManager;
- this.protocolFactory = protocolFactory;
- }
- public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
- return new AsyncClient(protocolFactory, clientManager, transport);
- }
- }
- public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
- super(protocolFactory, clientManager, transport);
- }
+ }
+ public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
+ public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
+ private org.apache.thrift.async.TAsyncClientManager clientManager;
+ private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
+ public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
+ this.clientManager = clientManager;
+ this.protocolFactory = protocolFactory;
+ }
+ public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
+ return new AsyncClient(protocolFactory, clientManager, transport);
+ }
+ }
- public void echo(String message, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
- checkReady();
- echo_call method_call = new echo_call(message, resultHandler, this, ___protocolFactory, ___transport);
- this.___currentMethod = method_call;
- ___manager.call(method_call);
- }
+ public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
+ super(protocolFactory, clientManager, transport);
+ }
- public static class echo_call extends org.apache.thrift.async.TAsyncMethodCall {
- private String message;
- public echo_call(String message, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
- super(client, protocolFactory, transport, resultHandler, false);
- this.message = message;
- }
+ public void echo(String message, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws org.apache.thrift.TException {
+ checkReady();
+ echo_call method_call = new echo_call(message, resultHandler, this, ___protocolFactory, ___transport);
+ this.___currentMethod = method_call;
+ ___manager.call(method_call);
+ }
- public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
- prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echo", org.apache.thrift.protocol.TMessageType.CALL, 0));
- echo_args args = new echo_args();
- args.setMessage(message);
- args.write(prot);
- prot.writeMessageEnd();
- }
+ public static class echo_call extends org.apache.thrift.async.TAsyncMethodCall<String> {
+ private String message;
+ public echo_call(String message, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
+ super(client, protocolFactory, transport, resultHandler, false);
+ this.message = message;
+ }
+
+ public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
+ prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echo", org.apache.thrift.protocol.TMessageType.CALL, 0));
+ echo_args args = new echo_args();
+ args.setMessage(message);
+ args.write(prot);
+ prot.writeMessageEnd();
+ }
+
+ public String getResult() throws org.apache.thrift.TException {
+ if (getState() != State.RESPONSE_READ) {
+ throw new IllegalStateException("Method call not finished!");
+ }
+ org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
+ org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
+ return (new Client(prot)).recv_echo();
+ }
+ }
- public String getResult() throws org.apache.thrift.TException {
- if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
- throw new IllegalStateException("Method call not finished!");
- }
- org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
- org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
- return (new Client(prot)).recv_echo();
- }
- }
+ }
+ public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
+ private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName());
+ public Processor(I iface) {
+ super(iface, getProcessMap(new java.util.HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
}
- public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
- private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());
- public Processor(I iface) {
- super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
- }
+ protected Processor(I iface, java.util.Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
+ super(iface, getProcessMap(processMap));
+ }
- protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
- super(iface, getProcessMap(processMap));
- }
+ private static <I extends Iface> java.util.Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(java.util.Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
+ processMap.put("echo", new echo());
+ return processMap;
+ }
- private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
- processMap.put("echo", new echo());
- return processMap;
- }
+ public static class echo<I extends Iface> extends org.apache.thrift.ProcessFunction<I, echo_args> {
+ public echo() {
+ super("echo");
+ }
- public static class echo<I extends Iface> extends org.apache.thrift.ProcessFunction<I, echo_args> {
- public echo() {
- super("echo");
- }
+ public echo_args getEmptyArgsInstance() {
+ return new echo_args();
+ }
- public echo_args getEmptyArgsInstance() {
- return new echo_args();
- }
+ protected boolean isOneway() {
+ return false;
+ }
- protected boolean isOneway() {
- return false;
- }
+ public echo_result getResult(I iface, echo_args args) throws org.apache.thrift.TException {
+ echo_result result = new echo_result();
+ result.success = iface.echo(args.message);
+ return result;
+ }
+ }
- public echo_result getResult(I iface, echo_args args) throws org.apache.thrift.TException {
- echo_result result = new echo_result();
- result.success = iface.echo(args.message);
- return result;
- }
- }
+ }
+ public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
+ private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName());
+ public AsyncProcessor(I iface) {
+ super(iface, getProcessMap(new java.util.HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
}
- public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
- private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());
- public AsyncProcessor(I iface) {
- super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
- }
-
- protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
- super(iface, getProcessMap(processMap));
- }
+ protected AsyncProcessor(I iface, java.util.Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
+ super(iface, getProcessMap(processMap));
+ }
- private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
- processMap.put("echo", new echo());
- return processMap;
- }
+ private static <I extends AsyncIface> java.util.Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(java.util.Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
+ processMap.put("echo", new echo());
+ return processMap;
+ }
- public static class echo<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, echo_args, String> {
- public echo() {
- super("echo");
- }
+ public static class echo<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, echo_args, String> {
+ public echo() {
+ super("echo");
+ }
- public echo_args getEmptyArgsInstance() {
- return new echo_args();
- }
+ public echo_args getEmptyArgsInstance() {
+ return new echo_args();
+ }
- public AsyncMethodCallback<String> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {
- final org.apache.thrift.AsyncProcessFunction fcall = this;
- return new AsyncMethodCallback<String>() {
- public void onComplete(String o) {
- echo_result result = new echo_result();
- result.success = o;
- try {
- fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
- return;
- } catch (Exception e) {
- LOGGER.error("Exception writing to internal frame buffer", e);
- }
- fb.close();
- }
- public void onError(Exception e) {
- byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
-
- /* THRIFT-2157 generated code would cause ClassCastException
- org.apache.thrift.TBase msg;
+ public org.apache.thrift.async.AsyncMethodCallback<String> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
+ final org.apache.thrift.AsyncProcessFunction fcall = this;
+ return new org.apache.thrift.async.AsyncMethodCallback<String>() {
+ public void onComplete(String o) {
+ echo_result result = new echo_result();
+ result.success = o;
+ try {
+ fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
+ } catch (org.apache.thrift.transport.TTransportException e) {
+ _LOGGER.error("TTransportException writing to internal frame buffer", e);
+ fb.close();
+ } catch (Exception e) {
+ _LOGGER.error("Exception writing to internal frame buffer", e);
+ onError(e);
+ }
+ }
+ public void onError(Exception e) {
+ byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
+ org.apache.thrift.TSerializable msg;
echo_result result = new echo_result();
- {
+ if (e instanceof org.apache.thrift.transport.TTransportException) {
+ _LOGGER.error("TTransportException inside handler", e);
+ fb.close();
+ return;
+ } else if (e instanceof org.apache.thrift.TApplicationException) {
+ _LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
- msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
+ msg = (org.apache.thrift.TApplicationException)e;
+ } else {
+ _LOGGER.error("Exception inside handler", e);
+ msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
+ msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
- return;
} catch (Exception ex) {
- LOGGER.error("Exception writing to internal frame buffer", ex);
- }
- */
- org.apache.thrift.TApplicationException msg;
- echo_result result = new echo_result();
- {
- msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
- msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
- }
- try {
- TProtocol oprot = fb.getOutputProtocol();
-
- oprot.writeMessageBegin(new TMessage(fcall.getMethodName(), msgType, seqid));
- msg.write(oprot);
- oprot.writeMessageEnd();
- oprot.getTransport().flush();
-
- fb.responseReady();
- return;
- } catch (Exception ex) {
- LOGGER.error("Exception writing to internal frame buffer", ex);
- }
-
- fb.close();
- }
- };
+ _LOGGER.error("Exception writing to internal frame buffer", ex);
+ fb.close();
}
+ }
+ };
+ }
- protected boolean isOneway() {
- return false;
- }
-
- public void start(I iface, echo_args args, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws TException {
- iface.echo(args.message,resultHandler);
- }
- }
+ protected boolean isOneway() {
+ return false;
+ }
+ public void start(I iface, echo_args args, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws org.apache.thrift.TException {
+ iface.echo(args.message,resultHandler);
+ }
}
- public static class echo_args implements org.apache.thrift.TBase<echo_args, echo_args._Fields>, java.io.Serializable, Cloneable, Comparable<echo_args> {
- private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_args");
-
- 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<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
- static {
- schemes.put(StandardScheme.class, new echo_argsStandardSchemeFactory());
- schemes.put(TupleScheme.class, new echo_argsTupleSchemeFactory());
- }
-
- 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<String, _Fields> byName = new HashMap<String, _Fields>();
-
- 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(echo_args.class, metaDataMap);
- }
-
- public echo_args() {
- }
-
- public echo_args(
- String message)
- {
- this();
- this.message = message;
- }
+ }
- /**
- * Performs a deep copy on <i>other</i>.
- */
- public echo_args(echo_args other) {
- if (other.isSetMessage()) {
- this.message = other.message;
- }
- }
+ public static class echo_args implements org.apache.thrift.TBase<echo_args, echo_args._Fields>, java.io.Serializable, Cloneable, Comparable<echo_args> {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_args");
- public echo_args deepCopy() {
- return new echo_args(this);
- }
+ 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);
- @Override
- public void clear() {
- this.message = null;
- }
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new echo_argsStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new echo_argsTupleSchemeFactory();
- public String getMessage() {
- return this.message;
- }
+ private String message; // required
- public void setMessage(String message) {
- this.message = message;
- }
+ /** 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");
- public void unsetMessage() {
- this.message = null;
- }
+ private static final java.util.Map<String, _Fields> byName = new java.util.HashMap<String, _Fields>();
- /** Returns true if field message is set (has been assigned a value) and false otherwise */
- public boolean isSetMessage() {
- return this.message != null;
+ static {
+ for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
+ byName.put(field.getFieldName(), field);
}
+ }
- public void setMessageIsSet(boolean value) {
- if (!value) {
- this.message = null;
- }
+ /**
+ * 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;
}
+ }
- public void setFieldValue(_Fields field, Object value) {
- switch (field) {
- case MESSAGE:
- if (value == null) {
- unsetMessage();
- } else {
- setMessage((String)value);
- }
- break;
+ /**
+ * 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;
+ }
- }
- }
-
- public Object getFieldValue(_Fields field) {
- switch (field) {
- case MESSAGE:
- return getMessage();
+ /**
+ * Find the _Fields constant that matches name, or null if its not found.
+ */
+ public static _Fields findByName(String name) {
+ return byName.get(name);
+ }
- }
- throw new IllegalStateException();
- }
+ private final short _thriftId;
+ private final String _fieldName;
- /** 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();
- }
+ _Fields(short thriftId, String fieldName) {
+ _thriftId = thriftId;
+ _fieldName = fieldName;
+ }
- switch (field) {
- case MESSAGE:
- return isSetMessage();
- }
- throw new IllegalStateException();
- }
+ public short getThriftFieldId() {
+ return _thriftId;
+ }
- @Override
- public boolean equals(Object that) {
- if (that == null)
- return false;
- if (that instanceof echo_args)
- return this.equals((echo_args)that);
- return false;
- }
+ public String getFieldName() {
+ return _fieldName;
+ }
+ }
- public boolean equals(echo_args 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;
- }
+ // isset id assignments
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.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 = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echo_args.class, metaDataMap);
+ }
- return true;
- }
+ public echo_args() {
+ }
- @Override
- public int hashCode() {
- return 0;
- }
+ public echo_args(
+ String message)
+ {
+ this();
+ this.message = message;
+ }
- @Override
- public int compareTo(echo_args other) {
- if (!getClass().equals(other.getClass())) {
- return getClass().getName().compareTo(other.getClass().getName());
- }
+ /**
+ * Performs a deep copy on <i>other</i>.
+ */
+ public echo_args(echo_args other) {
+ if (other.isSetMessage()) {
+ this.message = other.message;
+ }
+ }
- int lastComparison = 0;
+ public echo_args deepCopy() {
+ return new echo_args(this);
+ }
- 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;
- }
+ @Override
+ public void clear() {
+ this.message = null;
+ }
- public _Fields fieldForId(int fieldId) {
- return _Fields.findByThriftId(fieldId);
- }
+ public String getMessage() {
+ return this.message;
+ }
- public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
- schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
- schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
- }
+ public void unsetMessage() {
+ this.message = null;
+ }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("echo_args(");
- boolean first = true;
+ /** Returns true if field message is set (has been assigned a value) and false otherwise */
+ public boolean isSetMessage() {
+ return this.message != null;
+ }
- sb.append("message:");
- if (this.message == null) {
- sb.append("null");
- } else {
- sb.append(this.message);
- }
- first = false;
- sb.append(")");
- return sb.toString();
- }
+ public void setMessageIsSet(boolean value) {
+ if (!value) {
+ this.message = null;
+ }
+ }
- public void validate() throws org.apache.thrift.TException {
- // check for required fields
- // check for sub-struct validity
+ public void setFieldValue(_Fields field, Object value) {
+ switch (field) {
+ case MESSAGE:
+ if (value == null) {
+ unsetMessage();
+ } else {
+ setMessage((String)value);
}
+ break;
- 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);
- }
- }
+ public Object getFieldValue(_Fields field) {
+ switch (field) {
+ case MESSAGE:
+ return getMessage();
- private static class echo_argsStandardSchemeFactory implements SchemeFactory {
- public echo_argsStandardScheme getScheme() {
- return new echo_argsStandardScheme();
- }
- }
+ }
+ throw new IllegalStateException();
+ }
- private static class echo_argsStandardScheme extends StandardScheme<echo_args> {
-
- public void read(org.apache.thrift.protocol.TProtocol iprot, echo_args 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();
- }
+ /** 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();
+ }
- public void write(org.apache.thrift.protocol.TProtocol oprot, echo_args 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();
- }
+ @Override
+ public boolean equals(Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof echo_args)
+ return this.equals((echo_args)that);
+ return false;
+ }
- }
+ public boolean equals(echo_args that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ 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;
+ }
- private static class echo_argsTupleSchemeFactory implements SchemeFactory {
- public echo_argsTupleScheme getScheme() {
- return new echo_argsTupleScheme();
- }
- }
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
- private static class echo_argsTupleScheme extends TupleScheme<echo_args> {
-
- @Override
- public void write(org.apache.thrift.protocol.TProtocol prot, echo_args 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);
- }
- }
+ hashCode = hashCode * 8191 + ((isSetMessage()) ? 131071 : 524287);
+ if (isSetMessage())
+ hashCode = hashCode * 8191 + message.hashCode();
- @Override
- public void read(org.apache.thrift.protocol.TProtocol prot, echo_args 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);
- }
- }
- }
+ return hashCode;
+ }
+ @Override
+ public int compareTo(echo_args 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 static class echo_result implements org.apache.thrift.TBase<echo_result, echo_result._Fields>, java.io.Serializable, Cloneable, Comparable<echo_result> {
- private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_result");
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
- private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0);
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
- private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
- static {
- schemes.put(StandardScheme.class, new echo_resultStandardSchemeFactory());
- schemes.put(TupleScheme.class, new echo_resultTupleSchemeFactory());
- }
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
- private String success; // required
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder("echo_args(");
+ 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();
+ }
- /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
- public enum _Fields implements org.apache.thrift.TFieldIdEnum {
- SUCCESS((short)0, "success");
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ }
- private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
+ 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);
+ }
+ }
- static {
- for (_Fields field : EnumSet.allOf(_Fields.class)) {
- byName.put(field.getFieldName(), field);
- }
- }
+ 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);
+ }
+ }
- /**
- * Find the _Fields constant that matches fieldId, or null if its not found.
- */
- public static _Fields findByThriftId(int fieldId) {
- switch(fieldId) {
- case 0: // SUCCESS
- return SUCCESS;
- default:
- return null;
- }
- }
+ private static class echo_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public echo_argsStandardScheme getScheme() {
+ return new echo_argsStandardScheme();
+ }
+ }
- /**
- * 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;
- }
+ private static class echo_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme<echo_args> {
- /**
- * Find the _Fields constant that matches name, or null if its not found.
- */
- public static _Fields findByName(String name) {
- return byName.get(name);
- }
+ public void read(org.apache.thrift.protocol.TProtocol iprot, echo_args 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, echo_args 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 final short _thriftId;
- private final String _fieldName;
+ }
- _Fields(short thriftId, String fieldName) {
- _thriftId = thriftId;
- _fieldName = fieldName;
- }
+ private static class echo_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public echo_argsTupleScheme getScheme() {
+ return new echo_argsTupleScheme();
+ }
+ }
- public short getThriftFieldId() {
- return _thriftId;
- }
+ private static class echo_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme<echo_args> {
- public String getFieldName() {
- return _fieldName;
- }
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, echo_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet optionals = new java.util.BitSet();
+ if (struct.isSetMessage()) {
+ optionals.set(0);
}
-
- // 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.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", 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(echo_result.class, metaDataMap);
+ oprot.writeBitSet(optionals, 1);
+ if (struct.isSetMessage()) {
+ oprot.writeString(struct.message);
}
+ }
- public echo_result() {
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, echo_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet incoming = iprot.readBitSet(1);
+ if (incoming.get(0)) {
+ struct.message = iprot.readString();
+ struct.setMessageIsSet(true);
}
+ }
+ }
- public echo_result(
- String success)
- {
- this();
- this.success = success;
- }
+ private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
+ }
+ }
+
+ public static class echo_result implements org.apache.thrift.TBase<echo_result, echo_result._Fields>, java.io.Serializable, Cloneable, Comparable<echo_result> {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_result");
+
+ private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0);
+
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new echo_resultStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new echo_resultTupleSchemeFactory();
+
+ private String success; // 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 {
+ SUCCESS((short)0, "success");
+
+ private static final java.util.Map<String, _Fields> byName = new java.util.HashMap<String, _Fields>();
+
+ static {
+ for (_Fields field : java.util.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 0: // SUCCESS
+ return SUCCESS;
+ 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;
+ }
+ }
- /**
- * Performs a deep copy on <i>other</i>.
- */
- public echo_result(echo_result other) {
- if (other.isSetSuccess()) {
- this.success = other.success;
- }
- }
+ // isset id assignments
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
+ tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
+ metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echo_result.class, metaDataMap);
+ }
- public echo_result deepCopy() {
- return new echo_result(this);
- }
+ public echo_result() {
+ }
- @Override
- public void clear() {
- this.success = null;
- }
+ public echo_result(
+ String success)
+ {
+ this();
+ this.success = success;
+ }
- public String getSuccess() {
- return this.success;
- }
+ /**
+ * Performs a deep copy on <i>other</i>.
+ */
+ public echo_result(echo_result other) {
+ if (other.isSetSuccess()) {
+ this.success = other.success;
+ }
+ }
- public void setSuccess(String success) {
- this.success = success;
- }
+ public echo_result deepCopy() {
+ return new echo_result(this);
+ }
- public void unsetSuccess() {
- this.success = null;
- }
+ @Override
+ public void clear() {
+ this.success = null;
+ }
- /** Returns true if field success is set (has been assigned a value) and false otherwise */
- public boolean isSetSuccess() {
- return this.success != null;
- }
+ public String getSuccess() {
+ return this.success;
+ }
- public void setSuccessIsSet(boolean value) {
- if (!value) {
- this.success = null;
- }
- }
+ public void setSuccess(String success) {
+ this.success = success;
+ }
- public void setFieldValue(_Fields field, Object value) {
- switch (field) {
- case SUCCESS:
- if (value == null) {
- unsetSuccess();
- } else {
- setSuccess((String)value);
- }
- break;
+ public void unsetSuccess() {
+ this.success = null;
+ }
- }
- }
+ /** Returns true if field success is set (has been assigned a value) and false otherwise */
+ public boolean isSetSuccess() {
+ return this.success != null;
+ }
- public Object getFieldValue(_Fields field) {
- switch (field) {
- case SUCCESS:
- return getSuccess();
+ public void setSuccessIsSet(boolean value) {
+ if (!value) {
+ this.success = null;
+ }
+ }
- }
- throw new IllegalStateException();
+ public void setFieldValue(_Fields field, Object value) {
+ switch (field) {
+ case SUCCESS:
+ if (value == null) {
+ unsetSuccess();
+ } else {
+ setSuccess((String)value);
}
+ break;
- /** 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 SUCCESS:
- return isSetSuccess();
- }
- throw new IllegalStateException();
- }
+ public Object getFieldValue(_Fields field) {
+ switch (field) {
+ case SUCCESS:
+ return getSuccess();
- @Override
- public boolean equals(Object that) {
- if (that == null)
- return false;
- if (that instanceof echo_result)
- return this.equals((echo_result)that);
- return false;
- }
+ }
+ throw new IllegalStateException();
+ }
- public boolean equals(echo_result that) {
- if (that == null)
- return false;
-
- boolean this_present_success = true && this.isSetSuccess();
- boolean that_present_success = true && that.isSetSuccess();
- if (this_present_success || that_present_success) {
- if (!(this_present_success && that_present_success))
- return false;
- if (!this.success.equals(that.success))
- return false;
- }
+ /** 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 SUCCESS:
+ return isSetSuccess();
+ }
+ throw new IllegalStateException();
+ }
- return true;
- }
+ @Override
+ public boolean equals(Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof echo_result)
+ return this.equals((echo_result)that);
+ return false;
+ }
- @Override
- public int hashCode() {
- return 0;
- }
+ public boolean equals(echo_result that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ boolean this_present_success = true && this.isSetSuccess();
+ boolean that_present_success = true && that.isSetSuccess();
+ if (this_present_success || that_present_success) {
+ if (!(this_present_success && that_present_success))
+ return false;
+ if (!this.success.equals(that.success))
+ return false;
+ }
+
+ return true;
+ }
- @Override
- public int compareTo(echo_result other) {
- if (!getClass().equals(other.getClass())) {
- return getClass().getName().compareTo(other.getClass().getName());
- }
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
- int lastComparison = 0;
+ hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287);
+ if (isSetSuccess())
+ hashCode = hashCode * 8191 + success.hashCode();
- lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
- if (lastComparison != 0) {
- return lastComparison;
- }
- if (isSetSuccess()) {
- lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
- if (lastComparison != 0) {
- return lastComparison;
- }
- }
- return 0;
- }
+ return hashCode;
+ }
- public _Fields fieldForId(int fieldId) {
- return _Fields.findByThriftId(fieldId);
- }
+ @Override
+ public int compareTo(echo_result other) {
+ if (!getClass().equals(other.getClass())) {
+ return getClass().getName().compareTo(other.getClass().getName());
+ }
+
+ int lastComparison = 0;
+
+ lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetSuccess()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ return 0;
+ }
- public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
- schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
- }
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
- public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
- schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
- }
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("echo_result(");
- boolean first = true;
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder("echo_result(");
+ boolean first = true;
+
+ sb.append("success:");
+ if (this.success == null) {
+ sb.append("null");
+ } else {
+ sb.append(this.success);
+ }
+ first = false;
+ sb.append(")");
+ return sb.toString();
+ }
- sb.append("success:");
- if (this.success == null) {
- sb.append("null");
- } else {
- sb.append(this.success);
- }
- first = false;
- sb.append(")");
- return sb.toString();
- }
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ }
- 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 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 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 echo_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public echo_resultStandardScheme getScheme() {
+ return new echo_resultStandardScheme();
+ }
+ }
- private static class echo_resultStandardSchemeFactory implements SchemeFactory {
- public echo_resultStandardScheme getScheme() {
- return new echo_resultStandardScheme();
- }
- }
+ private static class echo_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme<echo_result> {
- private static class echo_resultStandardScheme extends StandardScheme<echo_result> {
-
- public void read(org.apache.thrift.protocol.TProtocol iprot, echo_result 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 0: // SUCCESS
- if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
- struct.success = iprot.readString();
- struct.setSuccessIsSet(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 read(org.apache.thrift.protocol.TProtocol iprot, echo_result 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 0: // SUCCESS
+ if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
+ struct.success = iprot.readString();
+ struct.setSuccessIsSet(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, echo_result struct) throws org.apache.thrift.TException {
+ struct.validate();
+
+ oprot.writeStructBegin(STRUCT_DESC);
+ if (struct.success != null) {
+ oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
+ oprot.writeString(struct.success);
+ oprot.writeFieldEnd();
+ }
+ oprot.writeFieldStop();
+ oprot.writeStructEnd();
+ }
- public void write(org.apache.thrift.protocol.TProtocol oprot, echo_result struct) throws org.apache.thrift.TException {
- struct.validate();
-
- oprot.writeStructBegin(STRUCT_DESC);
- if (struct.success != null) {
- oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
- oprot.writeString(struct.success);
- oprot.writeFieldEnd();
- }
- oprot.writeFieldStop();
- oprot.writeStructEnd();
- }
+ }
- }
+ private static class echo_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public echo_resultTupleScheme getScheme() {
+ return new echo_resultTupleScheme();
+ }
+ }
- private static class echo_resultTupleSchemeFactory implements SchemeFactory {
- public echo_resultTupleScheme getScheme() {
- return new echo_resultTupleScheme();
- }
- }
+ private static class echo_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme<echo_result> {
- private static class echo_resultTupleScheme extends TupleScheme<echo_result> {
-
- @Override
- public void write(org.apache.thrift.protocol.TProtocol prot, echo_result struct) throws org.apache.thrift.TException {
- TTupleProtocol oprot = (TTupleProtocol) prot;
- BitSet optionals = new BitSet();
- if (struct.isSetSuccess()) {
- optionals.set(0);
- }
- oprot.writeBitSet(optionals, 1);
- if (struct.isSetSuccess()) {
- oprot.writeString(struct.success);
- }
- }
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, echo_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet optionals = new java.util.BitSet();
+ if (struct.isSetSuccess()) {
+ optionals.set(0);
+ }
+ oprot.writeBitSet(optionals, 1);
+ if (struct.isSetSuccess()) {
+ oprot.writeString(struct.success);
+ }
+ }
- @Override
- public void read(org.apache.thrift.protocol.TProtocol prot, echo_result struct) throws org.apache.thrift.TException {
- TTupleProtocol iprot = (TTupleProtocol) prot;
- BitSet incoming = iprot.readBitSet(1);
- if (incoming.get(0)) {
- struct.success = iprot.readString();
- struct.setSuccessIsSet(true);
- }
- }
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, echo_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet incoming = iprot.readBitSet(1);
+ if (incoming.get(0)) {
+ struct.success = iprot.readString();
+ struct.setSuccessIsSet(true);
}
+ }
+ }
+ private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
+ }
-}
\ No newline at end of file
+}
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java
index fdc53c1bb08a..ca81c84c6703 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java
@@ -33,15 +33,16 @@
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
/**
- * Integration test for THsHaServer with asynchronous processor.
+ * <p>Integration test for THsHaServer with asynchronous processor.</p>
*
- * Tests against libthrift 0.9.2+ due to THRIFT-2274
+ * <p><strike>Tests against libthrift 0.9.2+ due to THRIFT-2274</strike><br/>
+ * Tests against libthrift 0.10.0+ (0.9.x -> 0.10.x introduces breaking change to generated thrift code)</p>
*
* @author HyunGil Jeong
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,0.9.max]", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
public class ThriftHalfSyncHalfAsyncServerAsyncIT extends EchoTestRunner<THsHaServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java
index f5f635dc4d0e..f4cbce4e686b 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java
@@ -33,15 +33,16 @@
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
/**
- * Integration test for TNonblockingServer with asynchronous processor.
+ * <p>Integration test for TNonblockingServer with asynchronous processor.</p>
*
- * Tests against libthrift 0.9.2+ due to THRIFT-2274
+ * <p><strike>Tests against libthrift 0.9.2+ due to THRIFT-2274</strike><br/>
+ * Tests against libthrift 0.10.0+ (0.9.x -> 0.10.x introduces breaking change to generated thrift code)</p>
*
* @author HyunGil Jeong
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,0.9.max]", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
public class ThriftNonblockingServerAsyncIT extends EchoTestRunner<TNonblockingServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java
index 91ef74403d40..a4a4a7d41a81 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java
@@ -33,15 +33,16 @@
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
/**
- * Integration test for TThreadedSelectorServer with asynchronous processor.
+ * <p>Integration test for TThreadedSelectorServer with asynchronous processor.</p>
*
- * Tests against libthrift 0.9.2+ due to THRIFT-2274
+ * <p><strike>Tests against libthrift 0.9.2+ due to THRIFT-2274</strike><br/>
+ * Tests against libthrift 0.10.0+ (0.9.x -> 0.10.x introduces breaking change to generated thrift code)</p>
*
* @author HyunGil Jeong
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,0.9.max]", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
public class ThriftThreadedSelectorServerAsyncIT extends EchoTestRunner<TThreadedSelectorServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java
index 7cd07fca6b03..3586061edcc1 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java
@@ -33,15 +33,16 @@
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
/**
- * Integration test for THsHaServer with synchronous processor.
+ * <p>Integration test for THsHaServer with synchronous processor.</p>
*
- * Tests against libthrift 0.9.2+ due to THRIFT-2274
+ * <p><strike>Tests against libthrift 0.9.2+ due to THRIFT-2274</strike><br/>
+ * Tests against libthrift 0.10.0+ (0.9.x -> 0.10.x introduces breaking change to generated thrift code)</p>
*
* @author HyunGil Jeong
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,0.9.max]", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
public class ThriftHalfSyncHalfAsyncServerIT extends EchoTestRunner<THsHaServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java
index a42c5653e7bf..ee8178541fe0 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java
@@ -33,15 +33,16 @@
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
/**
- * Integration test for TNonblockingServer with synchronous processor.
+ * <p>Integration test for TNonblockingServer with synchronous processor.</p>
*
- * Tests against libthrift 0.9.2+ due to THRIFT-2274
+ * <p><strike>Tests against libthrift 0.9.2+ due to THRIFT-2274</strike>
+ * Tests against libthrift 0.10.0+ (0.9.x -> 0.10.x introduces breaking change to generated thrift code)</p>
*
* @author HyunGil Jeong
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,0.9.max]", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
public class ThriftNonblockingServerIT extends EchoTestRunner<TNonblockingServer> {
@Override
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java
index fcabe4fb69ce..a1cdd41e107a 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java
@@ -33,15 +33,16 @@
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
/**
- * Integration test for TThreadedSelectorServer with synchronous processor.
+ * <p>Integration test for TThreadedSelectorServer with synchronous processor.</p>
*
- * Tests against libthrift 0.9.2+ due to THRIFT-2274
+ * <p><strike>Tests against libthrift 0.9.2+ due to THRIFT-2274</strike>
+ * Tests against libthrift 0.10.0+ (0.9.x -> 0.10.x introduces breaking change to generated thrift code)</p>
*
* @author HyunGil Jeong
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.2,0.9.max]", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
public class ThriftThreadedSelectorServerIT extends EchoTestRunner<TThreadedSelectorServer> {
@Override
| val | train | "2017-04-18T08:03:33" | "2017-01-23T07:01:33Z" | Xylus | test |
pinpoint-apm/pinpoint/2924_2947 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2924 | pinpoint-apm/pinpoint/2947 | [
"keyword_pr_to_issue"
] | a797a7bd6ef18c53f9d230737f3a193ede8b1984 | e839a5ff27b0aa5edce9131bc46b1b3eaae89272 | [] | [] | "2017-05-23T05:11:47Z" | [
"bug",
"module:web"
] | Fix url pattern filtering for WAS to Unknown nodes | #### Description
Filtering transactions to unknown nodes by url pattern via the filter wizard does not work currently. It only takes the path (ie the address) into account when filtering.
URL pattern, if specified, should also be used to filter out transactions. | [
"commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java"
] | [
"commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/util/ServiceTypeRegistryMockFactory.java"
] | diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java b/commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java
index 5144585c76da..4a99bc785a84 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java
@@ -121,6 +121,8 @@
* <tr><td>8200</td><td>REDIS</td></tr>
* <tr><td>8250</td><td><i>RESERVED</i></td></tr>
* <tr><td>8251</td><td><i>RESERVED</i></td></tr>
+ * <tr><td>8310</td><td><i>ACTIVEMQ_CLIENT</i></td></tr>
+ * <tr><td>8311</td><td><i>ACTIVEMQ_CLIENT_INTERNAL</i></td></tr>
* </table>
* <h3>Cache Library Sandbox (8900 ~ 8999) Histogram type: Fast </h3>
*
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java
index 28c3d43dce1b..c6ceb65f4005 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java
@@ -23,6 +23,7 @@
import java.util.ArrayList;
import java.util.List;
+import com.navercorp.pinpoint.common.service.AnnotationKeyRegistryService;
import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import org.apache.commons.lang3.StringUtils;
@@ -50,6 +51,9 @@ public class DefaultFilterBuilder implements FilterBuilder {
@Autowired
private ServiceTypeRegistryService serviceTypeRegistryService;
+ @Autowired
+ private AnnotationKeyRegistryService annotationKeyRegistryService;
+
@Override
public Filter build(String filterText) {
if (StringUtils.isEmpty(filterText)) {
@@ -122,7 +126,7 @@ private List<LinkFilter> createLinkFilter(String jsonFilterText, List<FilterDesc
}
logger.debug("FilterDescriptor={}", descriptor);
- final LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService);
+ final LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
result.add(linkFilter);
}
return result;
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
index 27afac63730c..b21497dea399 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
@@ -45,14 +45,14 @@ public FilterHint(List<RpcHint> rpcHintList) {
}
- public List<RpcHint> getRpcHintList(String sourceApplicationName) {
- if (sourceApplicationName == null) {
- throw new NullPointerException("sourceApplicationName must not be null");
+ public List<RpcHint> getRpcHintList(String targetApplicationName) {
+ if (targetApplicationName == null) {
+ throw new NullPointerException("targetApplicationName must not be null");
}
final List<RpcHint> findRpcHintList = new ArrayList<>();
for (RpcHint rpcHint : rpcHintList) {
// TODO miss serviceType
- if (rpcHint.getApplicationName().equals(sourceApplicationName)) {
+ if (rpcHint.getApplicationName().equals(targetApplicationName)) {
findRpcHintList.add(rpcHint);
}
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java
index 44d045c3e7a1..fdd193de09ce 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2014 NAVER Corp.
+ * Copyright 2017 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +23,7 @@
import com.navercorp.pinpoint.common.server.bo.SpanBo;
import com.navercorp.pinpoint.common.server.bo.SpanEventBo;
+import com.navercorp.pinpoint.common.service.AnnotationKeyRegistryService;
import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.web.filter.agent.*;
@@ -31,6 +32,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
+import org.springframework.util.StringUtils;
/**
*
@@ -61,18 +63,28 @@ public class LinkFilter implements Filter {
private final List<RpcHint> rpcHintList;
- private final URLPatternFilter acceptURLFilter;
-
private final ServiceTypeRegistryService serviceTypeRegistryService;
+ private final AnnotationKeyRegistryService annotationKeyRegistryService;
+
+ private final URLPatternFilter acceptURLFilter;
+ private final URLPatternFilter rpcUrlFilter;
- public LinkFilter(FilterDescriptor filterDescriptor, FilterHint filterHint, ServiceTypeRegistryService serviceTypeRegistryService) {
+ public LinkFilter(FilterDescriptor filterDescriptor, FilterHint filterHint, ServiceTypeRegistryService serviceTypeRegistryService, AnnotationKeyRegistryService annotationKeyRegistryService) {
if (filterDescriptor == null) {
throw new NullPointerException("filter descriptor must not be null");
}
if (filterHint == null) {
throw new NullPointerException("filterHint must not be null");
}
+ if (serviceTypeRegistryService == null) {
+ throw new NullPointerException("serviceTypeRegistryService must not be null");
+ }
+ if (annotationKeyRegistryService == null) {
+ throw new NullPointerException("annotationKeyRegistryService must not be null");
+ }
+
this.serviceTypeRegistryService = serviceTypeRegistryService;
+ this.annotationKeyRegistryService = annotationKeyRegistryService;
final String fromServiceType = filterDescriptor.getFromServiceType();
this.fromServiceDescList = serviceTypeRegistryService.findDesc(fromServiceType);
@@ -110,20 +122,29 @@ public LinkFilter(FilterDescriptor filterDescriptor, FilterHint filterHint, Serv
this.filterType = getFilterType();
logger.info("filterType:{}", filterType);
- this.rpcHintList = this.filterHint.getRpcHintList(fromApplicationName);
+ this.rpcHintList = this.filterHint.getRpcHintList(toApplicationName);
+
// TODO fix : fromSpan base rpccall filter
- this.acceptURLFilter = createPatternFilter(filterDescriptor);
+ this.acceptURLFilter = createAcceptUrlFilter(filterDescriptor);
+ this.rpcUrlFilter = createRpcUrlFilter(filterDescriptor);
logger.info("acceptURLFilter:{}", acceptURLFilter);
}
- private URLPatternFilter createPatternFilter(FilterDescriptor filterDescriptor) {
- if (filterDescriptor.getUrlPattern() == null) {
+ private URLPatternFilter createAcceptUrlFilter(FilterDescriptor filterDescriptor) {
+ if (StringUtils.isEmpty(filterDescriptor.getUrlPattern())) {
return new BypassURLPatternFilter();
}
// TODO remove decode
return new AcceptUrlFilter(filterDescriptor.getUrlPattern());
}
+ private URLPatternFilter createRpcUrlFilter(FilterDescriptor filterDescriptor) {
+ if (StringUtils.isEmpty(filterDescriptor.getUrlPattern())) {
+ return new BypassURLPatternFilter();
+ }
+ return new RpcURLPatternFilter(filterDescriptor.getUrlPattern(), serviceTypeRegistryService, annotationKeyRegistryService);
+ }
+
private ResponseTimeFilter createResponseTimeFilter(FilterDescriptor filterDescriptor) {
final ResponseTimeFilterFactory factory = new ResponseTimeFilterFactory(filterDescriptor.getFromResponseTime(), filterDescriptor.getResponseTo());
return factory.createFilter();
@@ -161,7 +182,7 @@ private FilterType getFilterType() {
if (includeWas(fromServiceDescList) && includeWas(toServiceDescList)) {
return FilterType.WAS_TO_WAS;
}
- if (includeServiceType(fromServiceDescList, ServiceType.USER) && includeWas(toServiceDescList)) {
+ if (includeUser(fromServiceDescList) && includeWas(toServiceDescList)) {
return FilterType.USER_TO_WAS;
}
if (includeWas(fromServiceDescList) && includeUnknown(toServiceDescList)) {
@@ -263,6 +284,9 @@ private boolean wasToUnknownFilter(List<SpanBo> transaction) {
* WAS -> UNKNOWN
*/
final List<SpanBo> fromNode = findFromNode(transaction);
+ if (!rpcUrlFilter.accept(fromNode)) {
+ return false;
+ }
for (SpanBo span : fromNode) {
final List<SpanEventBo> eventBoList = span.getSpanEventBoList();
if (eventBoList == null) {
@@ -312,7 +336,7 @@ private boolean wasToBackendFilter(List<SpanBo> transaction) {
private boolean wasToWasFilter(List<SpanBo> transaction) {
/*
* WAS -> WAS
- * if destination is a "WAS", the span of src and dest may exists. need to check if be circular or not.
+ * if destination is a "WAS", the span of src and dest may exist. need to check if be circular or not.
* find src first. span (from, to) may exist more than one. so (spanId == parentSpanID) should be checked.
*/
@@ -336,9 +360,11 @@ private boolean wasToWasFilter(List<SpanBo> transaction) {
return false;
}
- if (!rpcHintList.isEmpty()) {
+ // Check for url pattern should now be done on the caller side (from spans) as to spans are missing at this point
+ if (!rpcUrlFilter.accept(fromSpanList)) {
return false;
}
+
// if agent filter is FromAgentFilter or AcceptAgentFilter(agent filter is not selected), url filtering is available.
return fromBaseFilter(fromSpanList);
}
@@ -372,6 +398,10 @@ private boolean fromBaseFilter(List<SpanBo> fromSpanList) {
// exceptional case
// 1. remote call fail
// 2. span packet lost.
+ if (rpcHintList.isEmpty()) {
+ // fast skip. There is nothing more we can do if rpcHintList is empty.
+ return false;
+ }
for (SpanBo fromSpan : fromSpanList) {
final List<SpanEventBo> eventBoList = fromSpan.getSpanEventBoList();
if (eventBoList == null) {
@@ -379,13 +409,16 @@ private boolean fromBaseFilter(List<SpanBo> fromSpanList) {
}
for (SpanEventBo event : eventBoList) {
final ServiceType eventServiceType = serviceTypeRegistryService.findServiceType(event.getServiceType());
- if (!eventServiceType.isRpcClient() || !eventServiceType.isQueue()) {
+ if (!eventServiceType.isRpcClient() && !eventServiceType.isQueue()) {
continue;
}
if (!eventServiceType.isRecordStatistics()) {
continue;
}
// check rpc call fail
+ // There are also cases where multiple applications receiving the same request from the caller node
+ // but not all of them have agents installed. RpcHint is used for such cases as acceptUrlFilter will
+ // reject these transactions.
for (RpcHint rpcHint : rpcHintList) {
for (RpcType rpcType : rpcHint.getRpcTypeList()) {
if (rpcType.isMatched(event.getDestinationId(), eventServiceType.getCode())) {
@@ -445,16 +478,16 @@ private List<SpanBo> findToNode(List<SpanBo> transaction) {
private List<SpanBo> findNode(List<SpanBo> nodeList, String findApplicationName, List<ServiceType> findServiceCode, AgentFilter agentFilter) {
List<SpanBo> findList = null;
for (SpanBo span : nodeList) {
- final ServiceType applicationServiceType = serviceTypeRegistryService.findServiceType(span.getApplicationServiceType());
- if (findApplicationName.equals(span.getApplicationId()) && includeServiceType(findServiceCode, applicationServiceType)) {
- // apply preAgentFilter
- if (agentFilter.accept(span.getAgentId())) {
- if (findList == null) {
- findList = new ArrayList<>();
- }
- findList.add(span);
+ final ServiceType applicationServiceType = serviceTypeRegistryService.findServiceType(span.getApplicationServiceType());
+ if (findApplicationName.equals(span.getApplicationId()) && includeServiceType(findServiceCode, applicationServiceType)) {
+ // apply preAgentFilter
+ if (agentFilter.accept(span.getAgentId())) {
+ if (findList == null) {
+ findList = new ArrayList<>();
}
+ findList.add(span);
}
+ }
}
if (findList == null) {
return Collections.emptyList();
@@ -468,6 +501,15 @@ private boolean isToNode(String applicationId, ServiceType serviceType) {
return this.toApplicationName.equals(applicationId) && includeServiceType(this.toServiceDescList, serviceType);
}
+ private boolean includeUser(List<ServiceType> serviceTypeList) {
+ for (ServiceType serviceType : serviceTypeList) {
+ if (serviceType.isUser()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
private boolean includeUnknown(List<ServiceType> serviceTypeList) {
for (ServiceType serviceType : serviceTypeList) {
if (serviceType.isUnknown()) {
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java
index 5e06570a2d25..88422925bc03 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.web.filter;
+import com.google.common.collect.ImmutableSet;
import com.navercorp.pinpoint.common.server.bo.AnnotationBo;
import com.navercorp.pinpoint.common.server.bo.SpanBo;
import com.navercorp.pinpoint.common.server.bo.SpanEventBo;
@@ -28,7 +29,10 @@
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
+import java.util.HashSet;
import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Set;
/**
* @author emeroad
@@ -42,21 +46,46 @@ public class RpcURLPatternFilter implements URLPatternFilter {
private final ServiceTypeRegistryService serviceTypeRegistryService;
private final AnnotationKeyRegistryService annotationKeyRegistryService;
- // TODO remove. hard coded annotation for compatibility
- @Deprecated
- private final AnnotationKey npcUrl;
+ // TODO remove. hard coded annotation for compatibility, need a better to group rpc url annotations
+ private final Set<Integer> rpcEndpointAnnotationCodes;
public RpcURLPatternFilter(String urlPattern, ServiceTypeRegistryService serviceTypeRegistryService, AnnotationKeyRegistryService annotationKeyRegistryService) {
if (urlPattern == null) {
throw new NullPointerException("urlPattern must not be null");
}
+ if (serviceTypeRegistryService == null) {
+ throw new NullPointerException("serviceTypeRegistryService must not be null");
+ }
+ if (annotationKeyRegistryService == null) {
+ throw new NullPointerException("annotationKeyRegistryService must not be null");
+ }
// TODO remove decode
this.urlPattern = new String(Base64.decodeBase64(urlPattern), UTF8);
// TODO serviceType rpctype
this.serviceTypeRegistryService = serviceTypeRegistryService;
this.annotationKeyRegistryService = annotationKeyRegistryService;
- this.npcUrl = this.annotationKeyRegistryService.findAnnotationKeyByName("npc.url");
+ // TODO remove. hard coded annotation for compatibility, need a better to group rpc url annotations
+ this.rpcEndpointAnnotationCodes = initRpcEndpointAnnotations(
+ AnnotationKey.HTTP_URL.getName(), AnnotationKey.MESSAGE_QUEUE_URI.getName(),
+ "thrift.url", "npc.url", "nimm.url"
+ );
+ }
+
+ private Set<Integer> initRpcEndpointAnnotations(String... annotationKeyNames) {
+ Set<Integer> rpcEndPointAnnotationCodes = new HashSet<>();
+ for (String annotationKeyName : annotationKeyNames) {
+ AnnotationKey pluginRpcEndpointAnnotationKey = null;
+ try {
+ pluginRpcEndpointAnnotationKey = annotationKeyRegistryService.findAnnotationKeyByName(annotationKeyName);
+ } catch (NoSuchElementException e) {
+ // ignore
+ }
+ if (pluginRpcEndpointAnnotationKey != null) {
+ rpcEndPointAnnotationCodes.add(pluginRpcEndpointAnnotationKey.getCode());
+ }
+ }
+ return ImmutableSet.copyOf(rpcEndPointAnnotationCodes);
}
@Override
@@ -101,7 +130,7 @@ public boolean accept(List<SpanBo> fromSpanList) {
}
private boolean isURL(int key) {
- return key == AnnotationKey.HTTP_URL.getCode() || key == npcUrl.getCode();
+ return rpcEndpointAnnotationCodes.contains(key);
}
private String getPath(String endPoint) {
@@ -109,15 +138,16 @@ private String getPath(String endPoint) {
return null;
}
// is URI format
- final int authorityIndex = endPoint.indexOf("://");
+ final String authoritySeparator = "://";
+ final int authorityIndex = endPoint.indexOf(authoritySeparator);
if (authorityIndex == -1) {
return endPoint;
}
- final int pathIndex = endPoint.indexOf('/', authorityIndex + 1);
+ final int pathIndex = endPoint.indexOf('/', authorityIndex + authoritySeparator.length());
if (pathIndex == -1) {
// ???
return endPoint;
}
- return endPoint.substring(pathIndex+1);
+ return endPoint.substring(pathIndex);
}
}
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java
index a96b51f49e6e..a9e060627063 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java
@@ -1,38 +1,88 @@
package com.navercorp.pinpoint.web.filter;
+import com.navercorp.pinpoint.common.server.bo.AnnotationBo;
+import com.navercorp.pinpoint.common.server.bo.SpanEventBo;
+import com.navercorp.pinpoint.common.service.AnnotationKeyRegistryService;
import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
+import com.navercorp.pinpoint.common.trace.AnnotationKey;
+import com.navercorp.pinpoint.common.trace.AnnotationKeyFactory;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.common.server.bo.SpanBo;
import com.navercorp.pinpoint.web.util.ServiceTypeRegistryMockFactory;
+import org.apache.hadoop.hbase.util.Base64;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
+import static com.navercorp.pinpoint.common.trace.ServiceTypeProperty.*;
+
/**
* @author emeroad
*/
public class LinkFilterTest {
+
+ private static final short UNKNOWN_TYPE_CODE = ServiceType.UNKNOWN.getCode();
+ private static final String UNKNOWN_TYPE_NAME = ServiceType.UNKNOWN.getName();
+ private static final short USER_TYPE_CODE = ServiceType.USER.getCode();
+ private static final String USER_TYPE_NAME = ServiceType.USER.getName();
+ private static final short TOMCAT_TYPE_CODE = 1010;
+ private static final String TOMCAT_TYPE_NAME = "TOMCAT";
+ private static final short RPC_TYPE_CODE = 9999;
+ private static final String RPC_TYPE_NAME = "RPC";
+ private static final short BACKEND_TYPE_CODE = 2100;
+ private static final String BACKEND_TYPE_NAME = "BACKEND";
+ private static final short MESSAGE_QUEUE_TYPE_CODE = 8310;
+ private static final String MESSAGE_QUEUE_TYPE_NAME = "MESSAGE_QUEUE";
+
+ private static final int RPC_ANNOTATION_CODE = -1;
+ private static final String RPC_ANNOTATION_NAME = "rpc.url";
+
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final ServiceTypeRegistryService serviceTypeRegistryService = mockServiceTypeRegistryService();
+ private final AnnotationKeyRegistryService annotationKeyRegistryService = mockAnnotationKeyRegistryService();
private ServiceTypeRegistryService mockServiceTypeRegistryService() {
- final short tomcatTypeCode = 1010;
- final String tomcatTypeName = "TOMCAT";
ServiceTypeRegistryMockFactory mockFactory = new ServiceTypeRegistryMockFactory();
- mockFactory.addServiceTypeMock(tomcatTypeCode, tomcatTypeName);
+ mockFactory.addServiceTypeMock(UNKNOWN_TYPE_CODE, UNKNOWN_TYPE_NAME, RECORD_STATISTICS);
+ mockFactory.addServiceTypeMock(USER_TYPE_CODE, USER_TYPE_NAME, RECORD_STATISTICS);
+ mockFactory.addServiceTypeMock(TOMCAT_TYPE_CODE, TOMCAT_TYPE_NAME, RECORD_STATISTICS);
+ mockFactory.addServiceTypeMock(RPC_TYPE_CODE, RPC_TYPE_NAME, RECORD_STATISTICS);
+ mockFactory.addServiceTypeMock(BACKEND_TYPE_CODE, BACKEND_TYPE_NAME, TERMINAL, INCLUDE_DESTINATION_ID);
+ mockFactory.addServiceTypeMock(MESSAGE_QUEUE_TYPE_CODE, MESSAGE_QUEUE_TYPE_NAME, QUEUE, RECORD_STATISTICS);
return mockFactory.createMockServiceTypeRegistryService();
}
+ private AnnotationKeyRegistryService mockAnnotationKeyRegistryService() {
+ final AnnotationKey rpcUrlAnnotationKey = AnnotationKeyFactory.of(RPC_ANNOTATION_CODE, RPC_ANNOTATION_NAME);
+ return new AnnotationKeyRegistryService() {
+ @Override
+ public AnnotationKey findAnnotationKey(int annotationCode) {
+ return rpcUrlAnnotationKey;
+ }
+
+ @Override
+ public AnnotationKey findAnnotationKeyByName(String keyName) {
+ return rpcUrlAnnotationKey;
+ }
+
+ @Override
+ public AnnotationKey findApiErrorCode(int annotationCode) {
+ return rpcUrlAnnotationKey;
+ }
+ };
+ }
+
@Test
public void fromToFilterTest() {
- ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName("TOMCAT");
+ ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
final short tomcatServiceType = tomcat.getCode();
FilterDescriptor descriptor = new FilterDescriptor();
@@ -44,9 +94,9 @@ public void fromToFilterTest() {
descriptor.setToServiceType(tomcat.getName());
// descriptor.setToAgentId("AGENT_B");
- FilterHint hint = new FilterHint(Collections.<RpcHint>emptyList());
+ FilterHint hint = new FilterHint(Collections.emptyList());
- LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService);
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
logger.debug(linkFilter.toString());
SpanBo fromSpanBo = new SpanBo();
@@ -74,7 +124,7 @@ public void fromToFilterTest() {
@Test
public void fromToFilterAgentTest() {
- final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName("TOMCAT");
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
final short tomcatServiceType = tomcat.getCode();
FilterDescriptor descriptor = new FilterDescriptor();
@@ -86,9 +136,9 @@ public void fromToFilterAgentTest() {
descriptor.setToServiceType(tomcat.getName());
descriptor.setToAgentId("AGENT_B");
- FilterHint hint = new FilterHint(Collections.<RpcHint>emptyList());
+ FilterHint hint = new FilterHint(Collections.emptyList());
- LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService);
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
logger.debug(linkFilter.toString());
SpanBo fromSpanBo = new SpanBo();
@@ -111,9 +161,345 @@ public void fromToFilterAgentTest() {
Assert.assertTrue(linkFilter.include(Arrays.asList(fromSpanBo, toSpanBO)));
Assert.assertFalse(linkFilter.include(Arrays.asList(fromSpanBo, spanBoC)));
+ }
+
+ @Test
+ public void userToWasFilter() {
+ final ServiceType user = serviceTypeRegistryService.findServiceTypeByName(USER_TYPE_NAME);
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("USER");
+ descriptor.setFromServiceType(user.getName());
+ descriptor.setToApplicationName("APP_A");
+ descriptor.setToServiceType(tomcat.getName());
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ SpanBo user_appA = new SpanBo();
+ user_appA.setSpanId(1);
+ user_appA.setParentSpanId(-1);
+ user_appA.setApplicationId("APP_A");
+ user_appA.setApplicationServiceType(tomcat.getCode());
+ SpanBo appA_appB = new SpanBo();
+ appA_appB.setSpanId(2);
+ appA_appB.setParentSpanId(1);
+ appA_appB.setApplicationId("APP_B");
+ appA_appB.setApplicationServiceType(tomcat.getCode());
+ SpanBo appB_appA = new SpanBo();
+ appB_appA.setSpanId(3);
+ appB_appA.setParentSpanId(2);
+ appB_appA.setApplicationId("APP_A");
+ appB_appA.setApplicationServiceType(tomcat.getCode());
+
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(user_appA)));
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(appA_appB)));
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(appB_appA)));
+ Assert.assertTrue(linkFilter.include(Arrays.asList(user_appA, appA_appB, appB_appA)));
+ }
+
+ @Test
+ public void wasToUnknownFilter() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+ final ServiceType unknown = serviceTypeRegistryService.findServiceTypeByName(UNKNOWN_TYPE_NAME);
+
+ final String rpcHost = "some.domain.name";
+ final String rpcUrl = "http://" + rpcHost + "/some/test/path";
+ final String urlPattern = "/some/test/**";
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName(rpcHost);
+ descriptor.setToServiceType(unknown.getName());
+ descriptor.setUrl(encodeUrl(urlPattern));
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ // Reject - no rpc span event
+ SpanBo spanBo = new SpanBo();
+ spanBo.setSpanId(1);
+ spanBo.setParentSpanId(-1);
+ spanBo.setApplicationId("APP_A");
+ spanBo.setApplicationServiceType(tomcat.getCode());
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(spanBo)));
+
+ // Accept - has matching rpc span event
+ AnnotationBo rpcAnnotation = new AnnotationBo();
+ rpcAnnotation.setKey(RPC_ANNOTATION_CODE);
+ rpcAnnotation.setValue(rpcUrl);
+ SpanEventBo rpcSpanEvent = new SpanEventBo();
+ rpcSpanEvent.setServiceType(RPC_TYPE_CODE);
+ rpcSpanEvent.setDestinationId(rpcHost);
+ rpcSpanEvent.setAnnotationBoList(Collections.singletonList(rpcAnnotation));
+ spanBo.addSpanEvent(rpcSpanEvent);
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(spanBo)));
+ }
+
+ @Test
+ public void wasToWasFilter_perfectMatch() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName("APP_B");
+ descriptor.setToServiceType(tomcat.getName());
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ // Accept - perfect match
+ SpanBo user_appA = new SpanBo();
+ user_appA.setSpanId(1);
+ user_appA.setParentSpanId(-1);
+ user_appA.setApplicationId("APP_A");
+ user_appA.setApplicationServiceType(tomcat.getCode());
+ SpanBo appA_appB = new SpanBo();
+ appA_appB.setSpanId(2);
+ appA_appB.setParentSpanId(1);
+ appA_appB.setApplicationId("APP_B");
+ appA_appB.setApplicationServiceType(tomcat.getCode());
+ Assert.assertTrue(linkFilter.include(Arrays.asList(user_appA, appA_appB)));
+ }
+
+ @Test
+ public void wasToWasFilter_noMatch() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName("APP_B");
+ descriptor.setToServiceType(tomcat.getName());
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ // Reject - fromNode different
+ SpanBo user_appC = new SpanBo();
+ user_appC.setSpanId(1);
+ user_appC.setParentSpanId(-1);
+ user_appC.setApplicationId("APP_C");
+ user_appC.setApplicationServiceType(tomcat.getCode());
+ SpanBo appC_appB = new SpanBo();
+ appC_appB.setSpanId(2);
+ appC_appB.setParentSpanId(1);
+ appC_appB.setApplicationId("APP_B");
+ appC_appB.setApplicationServiceType(tomcat.getCode());
+ Assert.assertFalse(linkFilter.include(Arrays.asList(user_appC, appC_appB)));
+
+ // Reject - toNode different
+ SpanBo user_appA = new SpanBo();
+ user_appA.setSpanId(1);
+ user_appA.setParentSpanId(-1);
+ user_appA.setApplicationId("APP_A");
+ user_appA.setApplicationServiceType(tomcat.getCode());
+ SpanBo appA_appC = new SpanBo();
+ appA_appC.setSpanId(2);
+ appA_appC.setParentSpanId(1);
+ appA_appC.setApplicationId("APP_C");
+ appA_appC.setApplicationServiceType(tomcat.getCode());
+ Assert.assertFalse(linkFilter.include(Arrays.asList(user_appA, appA_appC)));
}
+ @Test
+ public void wasToWasFilter_noMatch_missingReceivingSpan() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+
+ final String rpcHost = "some.domain.name";
+ final String rpcUrl = "http://" + rpcHost + "/some/test/path";
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName("APP_B");
+ descriptor.setToServiceType(tomcat.getName());
+
+ FilterHint emptyHint = new FilterHint(Collections.emptyList());
+ FilterHint unmatchingHint = new FilterHint(Collections.singletonList(
+ new RpcHint("APP_B", Collections.singletonList(
+ new RpcType("different.domain.name", RPC_TYPE_CODE)))));
+ FilterHint matchingHint = new FilterHint(Collections.singletonList(
+ new RpcHint("APP_B", Collections.singletonList(
+ new RpcType(rpcHost, RPC_TYPE_CODE)))));
+
+ LinkFilter emptyHintLinkFilter = new LinkFilter(descriptor, emptyHint, serviceTypeRegistryService, annotationKeyRegistryService);
+ LinkFilter unmatchingHintLinkFilter = new LinkFilter(descriptor, unmatchingHint, serviceTypeRegistryService, annotationKeyRegistryService);
+ LinkFilter matchingHintLinkFilter = new LinkFilter(descriptor, matchingHint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug("emptyHintLinkFilter : {}", emptyHintLinkFilter.toString());
+ logger.debug("unmatchingHintLinkFilter : {}", unmatchingHintLinkFilter.toString());
+ logger.debug("matchingHintLinkFilter : {}", matchingHintLinkFilter.toString());
+
+ SpanBo fromSpan = new SpanBo();
+ fromSpan.setSpanId(1);
+ fromSpan.setParentSpanId(-1);
+ fromSpan.setApplicationId("APP_A");
+ fromSpan.setApplicationServiceType(tomcat.getCode());
+ AnnotationBo rpcAnnotation = new AnnotationBo();
+ rpcAnnotation.setKey(RPC_ANNOTATION_CODE);
+ rpcAnnotation.setValue(rpcUrl);
+ SpanEventBo rpcSpanEvent = new SpanEventBo();
+ rpcSpanEvent.setServiceType(RPC_TYPE_CODE);
+ rpcSpanEvent.setDestinationId(rpcHost);
+ rpcSpanEvent.setAnnotationBoList(Collections.singletonList(rpcAnnotation));
+ fromSpan.addSpanEvent(rpcSpanEvent);
+ // Reject - filter hint empty
+ Assert.assertFalse(emptyHintLinkFilter.include(Collections.singletonList(fromSpan)));
+ // Reject - filter hint does not match
+ Assert.assertFalse(unmatchingHintLinkFilter.include(Collections.singletonList(fromSpan)));
+ // Accept - filter hint matches
+ Assert.assertTrue(matchingHintLinkFilter.include(Collections.singletonList(fromSpan)));
+
+ // Check rpc url as well
+ final String unmatchingUrlPattern = "/other/test/**";
+ final String matchingUrlPattern = "/some/test/**";
+ // Reject - url pattern does not match
+ descriptor.setUrl(unmatchingUrlPattern);
+ LinkFilter matchingHintLinkFilterWithUnmatchingUrlPattern = new LinkFilter(descriptor, matchingHint, serviceTypeRegistryService, annotationKeyRegistryService);
+ Assert.assertFalse(matchingHintLinkFilterWithUnmatchingUrlPattern.include(Collections.singletonList(fromSpan)));
+ // Accept - url pattern matches
+ descriptor.setUrl(encodeUrl(matchingUrlPattern));
+ LinkFilter matchingHintLinkFilterWithMatchingUrlPattern = new LinkFilter(descriptor, matchingHint, serviceTypeRegistryService, annotationKeyRegistryService);
+ Assert.assertTrue(matchingHintLinkFilterWithMatchingUrlPattern.include(Collections.singletonList(fromSpan)));
+ }
+
+ @Test
+ public void wasToBackendFilter() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+ final ServiceType backend = serviceTypeRegistryService.findServiceTypeByName(BACKEND_TYPE_NAME);
+
+ final String destinationA = "BACKEND_A";
+ final String destinationB = "BACKEND_B";
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName(destinationA);
+ descriptor.setToServiceType(backend.getName());
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ SpanBo matchingSpan = new SpanBo();
+ matchingSpan.setApplicationId("APP_A");
+ matchingSpan.setApplicationServiceType(tomcat.getCode());
+ SpanEventBo spanEventDestinationA = new SpanEventBo();
+ spanEventDestinationA.setDestinationId(destinationA);
+ spanEventDestinationA.setServiceType(BACKEND_TYPE_CODE);
+ matchingSpan.addSpanEvent(spanEventDestinationA);
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(matchingSpan)));
+
+ SpanBo unmatchingSpan = new SpanBo();
+ unmatchingSpan.setApplicationId("APP_A");
+ unmatchingSpan.setApplicationServiceType(tomcat.getCode());
+ SpanEventBo spanEventDestinationB = new SpanEventBo();
+ spanEventDestinationB.setDestinationId(destinationB);
+ spanEventDestinationB.setServiceType(BACKEND_TYPE_CODE);
+ unmatchingSpan.addSpanEvent(spanEventDestinationB);
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(unmatchingSpan)));
+
+ Assert.assertTrue(linkFilter.include(Arrays.asList(matchingSpan, unmatchingSpan)));
+
+ SpanBo bothSpan = new SpanBo();
+ bothSpan.setApplicationId("APP_A");
+ bothSpan.setApplicationServiceType(tomcat.getCode());
+ bothSpan.addSpanEventBoList(Arrays.asList(spanEventDestinationA, spanEventDestinationB));
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(bothSpan)));
+ }
+ @Test
+ public void wasToQueueFilter() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+ final ServiceType messageQueue = serviceTypeRegistryService.findServiceTypeByName(MESSAGE_QUEUE_TYPE_NAME);
+
+ final String messageQueueA = "QUEUE_A";
+ final String messageQueueB = "QUEUE_B";
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName(messageQueueA);
+ descriptor.setToServiceType(messageQueue.getName());
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ SpanBo matchingSpan = new SpanBo();
+ matchingSpan.setApplicationId("APP_A");
+ matchingSpan.setApplicationServiceType(tomcat.getCode());
+ SpanEventBo spanEventDestinationA = new SpanEventBo();
+ spanEventDestinationA.setDestinationId(messageQueueA);
+ spanEventDestinationA.setServiceType(MESSAGE_QUEUE_TYPE_CODE);
+ matchingSpan.addSpanEvent(spanEventDestinationA);
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(matchingSpan)));
+
+ SpanBo unmatchingSpan = new SpanBo();
+ unmatchingSpan.setApplicationId("APP_A");
+ unmatchingSpan.setApplicationServiceType(tomcat.getCode());
+ SpanEventBo spanEventDestinationB = new SpanEventBo();
+ spanEventDestinationB.setDestinationId(messageQueueB);
+ spanEventDestinationB.setServiceType(MESSAGE_QUEUE_TYPE_CODE);
+ unmatchingSpan.addSpanEvent(spanEventDestinationB);
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(unmatchingSpan)));
+
+ Assert.assertTrue(linkFilter.include(Arrays.asList(matchingSpan, unmatchingSpan)));
+
+ SpanBo bothSpan = new SpanBo();
+ bothSpan.setApplicationId("APP_A");
+ bothSpan.setApplicationServiceType(tomcat.getCode());
+ bothSpan.addSpanEventBoList(Arrays.asList(spanEventDestinationA, spanEventDestinationB));
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(bothSpan)));
+ }
+
+ @Test
+ public void queueToWasFilter() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+ final ServiceType messageQueue = serviceTypeRegistryService.findServiceTypeByName(MESSAGE_QUEUE_TYPE_NAME);
+
+ final String messageQueueA = "QUEUE_A";
+ final String messageQueueB = "QUEUE_B";
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName(messageQueueA);
+ descriptor.setFromServiceType(messageQueue.getName());
+ descriptor.setToApplicationName("APP_A");
+ descriptor.setToServiceType(tomcat.getName());
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ SpanBo matchingSpan = new SpanBo();
+ matchingSpan.setApplicationId("APP_A");
+ matchingSpan.setApplicationServiceType(tomcat.getCode());
+ matchingSpan.setAcceptorHost(messageQueueA);
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(matchingSpan)));
+
+ SpanBo unmatchingSpan = new SpanBo();
+ unmatchingSpan.setApplicationId("APP_A");
+ unmatchingSpan.setApplicationServiceType(tomcat.getCode());
+ unmatchingSpan.setAcceptorHost(messageQueueB);
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(unmatchingSpan)));
+ }
+
+ private String encodeUrl(String value) {
+ return Base64.encodeBytes(value.getBytes(StandardCharsets.UTF_8));
+ }
}
\ No newline at end of file
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java
new file mode 100644
index 000000000000..25bcd1b9eb33
--- /dev/null
+++ b/web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright 2017 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.filter;
+
+import com.navercorp.pinpoint.common.server.bo.AnnotationBo;
+import com.navercorp.pinpoint.common.server.bo.SpanBo;
+import com.navercorp.pinpoint.common.server.bo.SpanEventBo;
+import com.navercorp.pinpoint.common.service.AnnotationKeyRegistryService;
+import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
+import com.navercorp.pinpoint.common.trace.AnnotationKey;
+import com.navercorp.pinpoint.common.trace.AnnotationKeyFactory;
+import com.navercorp.pinpoint.common.trace.ServiceType;
+import com.navercorp.pinpoint.common.trace.ServiceTypeFactory;
+import com.navercorp.pinpoint.common.trace.ServiceTypeProperty;
+import org.apache.hadoop.hbase.util.Base64;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class RpcURLPatternFilterTest {
+
+ private final AnnotationKey TEST_RPC_URL_ANNOTATION_KEY = AnnotationKeyFactory.of(-1, "rpc.url");
+ private final short TEST_RPC_SERVICE_TYPE_CODE = 9999;
+ private final String TEST_RPC_SERVICE_TYPE_NAME = "TEST_RPC";
+ private final ServiceType TEST_RPC_SERVICE_TYPE = ServiceTypeFactory.of(TEST_RPC_SERVICE_TYPE_CODE, TEST_RPC_SERVICE_TYPE_NAME, ServiceTypeProperty.RECORD_STATISTICS);
+
+ private ServiceTypeRegistryService serviceTypeRegistryService;
+
+ private AnnotationKeyRegistryService annotationKeyRegistryService;
+
+ @Before
+ public void setUp() {
+ serviceTypeRegistryService = new ServiceTypeRegistryService() {
+ @Override
+ public ServiceType findServiceType(short serviceType) {
+ return TEST_RPC_SERVICE_TYPE;
+ }
+
+ @Override
+ public ServiceType findServiceTypeByName(String typeName) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public List<ServiceType> findDesc(String desc) {
+ throw new UnsupportedOperationException();
+ }
+ };
+ annotationKeyRegistryService = new AnnotationKeyRegistryService() {
+ @Override
+ public AnnotationKey findAnnotationKey(int annotationCode) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public AnnotationKey findAnnotationKeyByName(String keyName) {
+ return TEST_RPC_URL_ANNOTATION_KEY;
+ }
+
+ @Override
+ public AnnotationKey findApiErrorCode(int annotationCode) {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+
+ @Test
+ public void emptyPatternShouldReject() {
+ // Given
+ final String urlPattern = "";
+ final String rpcUrl = "http://a.b.c";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertFalse(accept);
+ }
+
+ @Test
+ public void testPath() {
+ // Given
+ final String urlPattern = "/test/**";
+ final String rpcUrl = "/test/rpc/path";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertTrue(accept);
+ }
+
+ @Test
+ public void testFullUrl() {
+ // Given
+ final String urlPattern = "/test/**";
+ final String rpcUrl = "http://some.test.domain:8080/test/rpc/path";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertTrue(accept);
+ }
+
+ @Test
+ public void testDomainAndPath() {
+ // Given
+ final String urlPattern = "some.test.domain/test/rpc/**";
+ final String rpcUrl = "some.test.domain/test/rpc/test?value=11";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertTrue(accept);
+ }
+
+ @Test
+ public void testString() {
+ // Given
+ final String urlPattern = "some*";
+ final String rpcUrl = "someName";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertTrue(accept);
+ }
+
+ @Test
+ public void testWeirdPath() {
+ // Given
+ final String urlPattern = ":/**";
+ final String rpcUrl = ":/invalid/uri";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertTrue(accept);
+ }
+
+ private String encode(String value) {
+ return Base64.encodeBytes(value.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private List<SpanBo> createTestRpcSpans(String... rpcUrls) {
+ List<SpanBo> spanBos = new ArrayList<>();
+ for (String rpcUrl : rpcUrls) {
+ SpanEventBo testRpcSpanEvent = new SpanEventBo();
+ testRpcSpanEvent.setServiceType(TEST_RPC_SERVICE_TYPE_CODE);
+ AnnotationBo testRpcAnnotationBo = new AnnotationBo();
+ testRpcAnnotationBo.setKey(TEST_RPC_URL_ANNOTATION_KEY.getCode());
+ testRpcAnnotationBo.setValue(rpcUrl);
+ testRpcSpanEvent.setAnnotationBoList(Collections.singletonList(testRpcAnnotationBo));
+ SpanBo spanBo = new SpanBo();
+ spanBo.addSpanEvent(testRpcSpanEvent);
+ spanBos.add(spanBo);
+ }
+ return spanBos;
+ }
+}
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/util/ServiceTypeRegistryMockFactory.java b/web/src/test/java/com/navercorp/pinpoint/web/util/ServiceTypeRegistryMockFactory.java
index 5a8143f32b0e..52e183e38786 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/util/ServiceTypeRegistryMockFactory.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/util/ServiceTypeRegistryMockFactory.java
@@ -19,6 +19,7 @@
import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.common.trace.ServiceTypeCategory;
+import com.navercorp.pinpoint.common.trace.ServiceTypeProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -38,16 +39,43 @@ public class ServiceTypeRegistryMockFactory {
private final Map<Short, ServiceType> serviceTypeMap = new HashMap<>();
- public void addServiceTypeMock(short typeCode, String typeName) {
+ public void addServiceTypeMock(short typeCode, String typeName, ServiceTypeProperty... serviceTypeProperties) {
// setup serviceType
ServiceType mockServiceType = mock(ServiceType.class);
when(mockServiceType.getCode()).thenReturn(typeCode);
when(mockServiceType.getName()).thenReturn(typeName);
+ if (ServiceType.USER.getName().equals(typeName)) {
+ when(mockServiceType.isUser()).thenReturn(true);
+ }
+ if (ServiceType.UNKNOWN.getName().equals(typeName)) {
+ when(mockServiceType.isUnknown()).thenReturn(true);
+ }
if (ServiceTypeCategory.SERVER.contains(typeCode)) {
- logger.debug("mark isWas() {}/{}", mockServiceType.getName(), mockServiceType.getCode());
when(mockServiceType.isWas()).thenReturn(true);
}
+ if (ServiceTypeCategory.RPC.contains(typeCode)) {
+ when(mockServiceType.isRpcClient()).thenReturn(true);
+ }
+
+ for (ServiceTypeProperty serviceTypeProperty : serviceTypeProperties) {
+ switch (serviceTypeProperty) {
+ case TERMINAL:
+ when(mockServiceType.isTerminal()).thenReturn(true);
+ break;
+ case QUEUE:
+ when(mockServiceType.isQueue()).thenReturn(true);
+ break;
+ case RECORD_STATISTICS:
+ when(mockServiceType.isRecordStatistics()).thenReturn(true);
+ break;
+ case INCLUDE_DESTINATION_ID:
+ when(mockServiceType.isIncludeDestinationId()).thenReturn(true);
+ break;
+ default:
+ throw new IllegalArgumentException("Unknown serviceTypeProperty : " + serviceTypeProperty);
+ }
+ }
this.serviceTypeMap.put(typeCode, mockServiceType);
}
| train | val | "2017-05-23T03:45:22" | "2017-05-15T05:57:07Z" | Xylus | test |
pinpoint-apm/pinpoint/2939_2947 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2939 | pinpoint-apm/pinpoint/2947 | [
"keyword_pr_to_issue"
] | a797a7bd6ef18c53f9d230737f3a193ede8b1984 | e839a5ff27b0aa5edce9131bc46b1b3eaae89272 | [] | [] | "2017-05-23T05:11:47Z" | [
"bug",
"module:web"
] | Fix WAS to WAS filtering when destination nodes have receiving spans missing | #### Description
When filtering on WAS to WAS links, the destination node may very well have receiving spans missing due to packet losses, or simply because agents were only installed partially.
The latter case would be for example, when there is node A invoking RPC calls to node B (which has multiple instances) on a single address, but node B does not have agents installed on all of it's instances.
When filtering on WAS to WAS links, the calling span's spanId and the receiving span's parentSpanId are checked. But in the cases above, there is no receiving span so we must check using only the calling span to decide if a particular transaction should be included or not.
`RpcHint`s were introduced to aid in such cases but was reliable.
This issue attempts to fix this. | [
"commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java"
] | [
"commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/util/ServiceTypeRegistryMockFactory.java"
] | diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java b/commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java
index 5144585c76da..4a99bc785a84 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/trace/ServiceType.java
@@ -121,6 +121,8 @@
* <tr><td>8200</td><td>REDIS</td></tr>
* <tr><td>8250</td><td><i>RESERVED</i></td></tr>
* <tr><td>8251</td><td><i>RESERVED</i></td></tr>
+ * <tr><td>8310</td><td><i>ACTIVEMQ_CLIENT</i></td></tr>
+ * <tr><td>8311</td><td><i>ACTIVEMQ_CLIENT_INTERNAL</i></td></tr>
* </table>
* <h3>Cache Library Sandbox (8900 ~ 8999) Histogram type: Fast </h3>
*
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java
index 28c3d43dce1b..c6ceb65f4005 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java
@@ -23,6 +23,7 @@
import java.util.ArrayList;
import java.util.List;
+import com.navercorp.pinpoint.common.service.AnnotationKeyRegistryService;
import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import org.apache.commons.lang3.StringUtils;
@@ -50,6 +51,9 @@ public class DefaultFilterBuilder implements FilterBuilder {
@Autowired
private ServiceTypeRegistryService serviceTypeRegistryService;
+ @Autowired
+ private AnnotationKeyRegistryService annotationKeyRegistryService;
+
@Override
public Filter build(String filterText) {
if (StringUtils.isEmpty(filterText)) {
@@ -122,7 +126,7 @@ private List<LinkFilter> createLinkFilter(String jsonFilterText, List<FilterDesc
}
logger.debug("FilterDescriptor={}", descriptor);
- final LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService);
+ final LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
result.add(linkFilter);
}
return result;
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
index 27afac63730c..b21497dea399 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
@@ -45,14 +45,14 @@ public FilterHint(List<RpcHint> rpcHintList) {
}
- public List<RpcHint> getRpcHintList(String sourceApplicationName) {
- if (sourceApplicationName == null) {
- throw new NullPointerException("sourceApplicationName must not be null");
+ public List<RpcHint> getRpcHintList(String targetApplicationName) {
+ if (targetApplicationName == null) {
+ throw new NullPointerException("targetApplicationName must not be null");
}
final List<RpcHint> findRpcHintList = new ArrayList<>();
for (RpcHint rpcHint : rpcHintList) {
// TODO miss serviceType
- if (rpcHint.getApplicationName().equals(sourceApplicationName)) {
+ if (rpcHint.getApplicationName().equals(targetApplicationName)) {
findRpcHintList.add(rpcHint);
}
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java
index 44d045c3e7a1..fdd193de09ce 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2014 NAVER Corp.
+ * Copyright 2017 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +23,7 @@
import com.navercorp.pinpoint.common.server.bo.SpanBo;
import com.navercorp.pinpoint.common.server.bo.SpanEventBo;
+import com.navercorp.pinpoint.common.service.AnnotationKeyRegistryService;
import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.web.filter.agent.*;
@@ -31,6 +32,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
+import org.springframework.util.StringUtils;
/**
*
@@ -61,18 +63,28 @@ public class LinkFilter implements Filter {
private final List<RpcHint> rpcHintList;
- private final URLPatternFilter acceptURLFilter;
-
private final ServiceTypeRegistryService serviceTypeRegistryService;
+ private final AnnotationKeyRegistryService annotationKeyRegistryService;
+
+ private final URLPatternFilter acceptURLFilter;
+ private final URLPatternFilter rpcUrlFilter;
- public LinkFilter(FilterDescriptor filterDescriptor, FilterHint filterHint, ServiceTypeRegistryService serviceTypeRegistryService) {
+ public LinkFilter(FilterDescriptor filterDescriptor, FilterHint filterHint, ServiceTypeRegistryService serviceTypeRegistryService, AnnotationKeyRegistryService annotationKeyRegistryService) {
if (filterDescriptor == null) {
throw new NullPointerException("filter descriptor must not be null");
}
if (filterHint == null) {
throw new NullPointerException("filterHint must not be null");
}
+ if (serviceTypeRegistryService == null) {
+ throw new NullPointerException("serviceTypeRegistryService must not be null");
+ }
+ if (annotationKeyRegistryService == null) {
+ throw new NullPointerException("annotationKeyRegistryService must not be null");
+ }
+
this.serviceTypeRegistryService = serviceTypeRegistryService;
+ this.annotationKeyRegistryService = annotationKeyRegistryService;
final String fromServiceType = filterDescriptor.getFromServiceType();
this.fromServiceDescList = serviceTypeRegistryService.findDesc(fromServiceType);
@@ -110,20 +122,29 @@ public LinkFilter(FilterDescriptor filterDescriptor, FilterHint filterHint, Serv
this.filterType = getFilterType();
logger.info("filterType:{}", filterType);
- this.rpcHintList = this.filterHint.getRpcHintList(fromApplicationName);
+ this.rpcHintList = this.filterHint.getRpcHintList(toApplicationName);
+
// TODO fix : fromSpan base rpccall filter
- this.acceptURLFilter = createPatternFilter(filterDescriptor);
+ this.acceptURLFilter = createAcceptUrlFilter(filterDescriptor);
+ this.rpcUrlFilter = createRpcUrlFilter(filterDescriptor);
logger.info("acceptURLFilter:{}", acceptURLFilter);
}
- private URLPatternFilter createPatternFilter(FilterDescriptor filterDescriptor) {
- if (filterDescriptor.getUrlPattern() == null) {
+ private URLPatternFilter createAcceptUrlFilter(FilterDescriptor filterDescriptor) {
+ if (StringUtils.isEmpty(filterDescriptor.getUrlPattern())) {
return new BypassURLPatternFilter();
}
// TODO remove decode
return new AcceptUrlFilter(filterDescriptor.getUrlPattern());
}
+ private URLPatternFilter createRpcUrlFilter(FilterDescriptor filterDescriptor) {
+ if (StringUtils.isEmpty(filterDescriptor.getUrlPattern())) {
+ return new BypassURLPatternFilter();
+ }
+ return new RpcURLPatternFilter(filterDescriptor.getUrlPattern(), serviceTypeRegistryService, annotationKeyRegistryService);
+ }
+
private ResponseTimeFilter createResponseTimeFilter(FilterDescriptor filterDescriptor) {
final ResponseTimeFilterFactory factory = new ResponseTimeFilterFactory(filterDescriptor.getFromResponseTime(), filterDescriptor.getResponseTo());
return factory.createFilter();
@@ -161,7 +182,7 @@ private FilterType getFilterType() {
if (includeWas(fromServiceDescList) && includeWas(toServiceDescList)) {
return FilterType.WAS_TO_WAS;
}
- if (includeServiceType(fromServiceDescList, ServiceType.USER) && includeWas(toServiceDescList)) {
+ if (includeUser(fromServiceDescList) && includeWas(toServiceDescList)) {
return FilterType.USER_TO_WAS;
}
if (includeWas(fromServiceDescList) && includeUnknown(toServiceDescList)) {
@@ -263,6 +284,9 @@ private boolean wasToUnknownFilter(List<SpanBo> transaction) {
* WAS -> UNKNOWN
*/
final List<SpanBo> fromNode = findFromNode(transaction);
+ if (!rpcUrlFilter.accept(fromNode)) {
+ return false;
+ }
for (SpanBo span : fromNode) {
final List<SpanEventBo> eventBoList = span.getSpanEventBoList();
if (eventBoList == null) {
@@ -312,7 +336,7 @@ private boolean wasToBackendFilter(List<SpanBo> transaction) {
private boolean wasToWasFilter(List<SpanBo> transaction) {
/*
* WAS -> WAS
- * if destination is a "WAS", the span of src and dest may exists. need to check if be circular or not.
+ * if destination is a "WAS", the span of src and dest may exist. need to check if be circular or not.
* find src first. span (from, to) may exist more than one. so (spanId == parentSpanID) should be checked.
*/
@@ -336,9 +360,11 @@ private boolean wasToWasFilter(List<SpanBo> transaction) {
return false;
}
- if (!rpcHintList.isEmpty()) {
+ // Check for url pattern should now be done on the caller side (from spans) as to spans are missing at this point
+ if (!rpcUrlFilter.accept(fromSpanList)) {
return false;
}
+
// if agent filter is FromAgentFilter or AcceptAgentFilter(agent filter is not selected), url filtering is available.
return fromBaseFilter(fromSpanList);
}
@@ -372,6 +398,10 @@ private boolean fromBaseFilter(List<SpanBo> fromSpanList) {
// exceptional case
// 1. remote call fail
// 2. span packet lost.
+ if (rpcHintList.isEmpty()) {
+ // fast skip. There is nothing more we can do if rpcHintList is empty.
+ return false;
+ }
for (SpanBo fromSpan : fromSpanList) {
final List<SpanEventBo> eventBoList = fromSpan.getSpanEventBoList();
if (eventBoList == null) {
@@ -379,13 +409,16 @@ private boolean fromBaseFilter(List<SpanBo> fromSpanList) {
}
for (SpanEventBo event : eventBoList) {
final ServiceType eventServiceType = serviceTypeRegistryService.findServiceType(event.getServiceType());
- if (!eventServiceType.isRpcClient() || !eventServiceType.isQueue()) {
+ if (!eventServiceType.isRpcClient() && !eventServiceType.isQueue()) {
continue;
}
if (!eventServiceType.isRecordStatistics()) {
continue;
}
// check rpc call fail
+ // There are also cases where multiple applications receiving the same request from the caller node
+ // but not all of them have agents installed. RpcHint is used for such cases as acceptUrlFilter will
+ // reject these transactions.
for (RpcHint rpcHint : rpcHintList) {
for (RpcType rpcType : rpcHint.getRpcTypeList()) {
if (rpcType.isMatched(event.getDestinationId(), eventServiceType.getCode())) {
@@ -445,16 +478,16 @@ private List<SpanBo> findToNode(List<SpanBo> transaction) {
private List<SpanBo> findNode(List<SpanBo> nodeList, String findApplicationName, List<ServiceType> findServiceCode, AgentFilter agentFilter) {
List<SpanBo> findList = null;
for (SpanBo span : nodeList) {
- final ServiceType applicationServiceType = serviceTypeRegistryService.findServiceType(span.getApplicationServiceType());
- if (findApplicationName.equals(span.getApplicationId()) && includeServiceType(findServiceCode, applicationServiceType)) {
- // apply preAgentFilter
- if (agentFilter.accept(span.getAgentId())) {
- if (findList == null) {
- findList = new ArrayList<>();
- }
- findList.add(span);
+ final ServiceType applicationServiceType = serviceTypeRegistryService.findServiceType(span.getApplicationServiceType());
+ if (findApplicationName.equals(span.getApplicationId()) && includeServiceType(findServiceCode, applicationServiceType)) {
+ // apply preAgentFilter
+ if (agentFilter.accept(span.getAgentId())) {
+ if (findList == null) {
+ findList = new ArrayList<>();
}
+ findList.add(span);
}
+ }
}
if (findList == null) {
return Collections.emptyList();
@@ -468,6 +501,15 @@ private boolean isToNode(String applicationId, ServiceType serviceType) {
return this.toApplicationName.equals(applicationId) && includeServiceType(this.toServiceDescList, serviceType);
}
+ private boolean includeUser(List<ServiceType> serviceTypeList) {
+ for (ServiceType serviceType : serviceTypeList) {
+ if (serviceType.isUser()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
private boolean includeUnknown(List<ServiceType> serviceTypeList) {
for (ServiceType serviceType : serviceTypeList) {
if (serviceType.isUnknown()) {
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java
index 5e06570a2d25..88422925bc03 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilter.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.web.filter;
+import com.google.common.collect.ImmutableSet;
import com.navercorp.pinpoint.common.server.bo.AnnotationBo;
import com.navercorp.pinpoint.common.server.bo.SpanBo;
import com.navercorp.pinpoint.common.server.bo.SpanEventBo;
@@ -28,7 +29,10 @@
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
+import java.util.HashSet;
import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Set;
/**
* @author emeroad
@@ -42,21 +46,46 @@ public class RpcURLPatternFilter implements URLPatternFilter {
private final ServiceTypeRegistryService serviceTypeRegistryService;
private final AnnotationKeyRegistryService annotationKeyRegistryService;
- // TODO remove. hard coded annotation for compatibility
- @Deprecated
- private final AnnotationKey npcUrl;
+ // TODO remove. hard coded annotation for compatibility, need a better to group rpc url annotations
+ private final Set<Integer> rpcEndpointAnnotationCodes;
public RpcURLPatternFilter(String urlPattern, ServiceTypeRegistryService serviceTypeRegistryService, AnnotationKeyRegistryService annotationKeyRegistryService) {
if (urlPattern == null) {
throw new NullPointerException("urlPattern must not be null");
}
+ if (serviceTypeRegistryService == null) {
+ throw new NullPointerException("serviceTypeRegistryService must not be null");
+ }
+ if (annotationKeyRegistryService == null) {
+ throw new NullPointerException("annotationKeyRegistryService must not be null");
+ }
// TODO remove decode
this.urlPattern = new String(Base64.decodeBase64(urlPattern), UTF8);
// TODO serviceType rpctype
this.serviceTypeRegistryService = serviceTypeRegistryService;
this.annotationKeyRegistryService = annotationKeyRegistryService;
- this.npcUrl = this.annotationKeyRegistryService.findAnnotationKeyByName("npc.url");
+ // TODO remove. hard coded annotation for compatibility, need a better to group rpc url annotations
+ this.rpcEndpointAnnotationCodes = initRpcEndpointAnnotations(
+ AnnotationKey.HTTP_URL.getName(), AnnotationKey.MESSAGE_QUEUE_URI.getName(),
+ "thrift.url", "npc.url", "nimm.url"
+ );
+ }
+
+ private Set<Integer> initRpcEndpointAnnotations(String... annotationKeyNames) {
+ Set<Integer> rpcEndPointAnnotationCodes = new HashSet<>();
+ for (String annotationKeyName : annotationKeyNames) {
+ AnnotationKey pluginRpcEndpointAnnotationKey = null;
+ try {
+ pluginRpcEndpointAnnotationKey = annotationKeyRegistryService.findAnnotationKeyByName(annotationKeyName);
+ } catch (NoSuchElementException e) {
+ // ignore
+ }
+ if (pluginRpcEndpointAnnotationKey != null) {
+ rpcEndPointAnnotationCodes.add(pluginRpcEndpointAnnotationKey.getCode());
+ }
+ }
+ return ImmutableSet.copyOf(rpcEndPointAnnotationCodes);
}
@Override
@@ -101,7 +130,7 @@ public boolean accept(List<SpanBo> fromSpanList) {
}
private boolean isURL(int key) {
- return key == AnnotationKey.HTTP_URL.getCode() || key == npcUrl.getCode();
+ return rpcEndpointAnnotationCodes.contains(key);
}
private String getPath(String endPoint) {
@@ -109,15 +138,16 @@ private String getPath(String endPoint) {
return null;
}
// is URI format
- final int authorityIndex = endPoint.indexOf("://");
+ final String authoritySeparator = "://";
+ final int authorityIndex = endPoint.indexOf(authoritySeparator);
if (authorityIndex == -1) {
return endPoint;
}
- final int pathIndex = endPoint.indexOf('/', authorityIndex + 1);
+ final int pathIndex = endPoint.indexOf('/', authorityIndex + authoritySeparator.length());
if (pathIndex == -1) {
// ???
return endPoint;
}
- return endPoint.substring(pathIndex+1);
+ return endPoint.substring(pathIndex);
}
}
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java
index a96b51f49e6e..a9e060627063 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java
@@ -1,38 +1,88 @@
package com.navercorp.pinpoint.web.filter;
+import com.navercorp.pinpoint.common.server.bo.AnnotationBo;
+import com.navercorp.pinpoint.common.server.bo.SpanEventBo;
+import com.navercorp.pinpoint.common.service.AnnotationKeyRegistryService;
import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
+import com.navercorp.pinpoint.common.trace.AnnotationKey;
+import com.navercorp.pinpoint.common.trace.AnnotationKeyFactory;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.common.server.bo.SpanBo;
import com.navercorp.pinpoint.web.util.ServiceTypeRegistryMockFactory;
+import org.apache.hadoop.hbase.util.Base64;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
+import static com.navercorp.pinpoint.common.trace.ServiceTypeProperty.*;
+
/**
* @author emeroad
*/
public class LinkFilterTest {
+
+ private static final short UNKNOWN_TYPE_CODE = ServiceType.UNKNOWN.getCode();
+ private static final String UNKNOWN_TYPE_NAME = ServiceType.UNKNOWN.getName();
+ private static final short USER_TYPE_CODE = ServiceType.USER.getCode();
+ private static final String USER_TYPE_NAME = ServiceType.USER.getName();
+ private static final short TOMCAT_TYPE_CODE = 1010;
+ private static final String TOMCAT_TYPE_NAME = "TOMCAT";
+ private static final short RPC_TYPE_CODE = 9999;
+ private static final String RPC_TYPE_NAME = "RPC";
+ private static final short BACKEND_TYPE_CODE = 2100;
+ private static final String BACKEND_TYPE_NAME = "BACKEND";
+ private static final short MESSAGE_QUEUE_TYPE_CODE = 8310;
+ private static final String MESSAGE_QUEUE_TYPE_NAME = "MESSAGE_QUEUE";
+
+ private static final int RPC_ANNOTATION_CODE = -1;
+ private static final String RPC_ANNOTATION_NAME = "rpc.url";
+
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final ServiceTypeRegistryService serviceTypeRegistryService = mockServiceTypeRegistryService();
+ private final AnnotationKeyRegistryService annotationKeyRegistryService = mockAnnotationKeyRegistryService();
private ServiceTypeRegistryService mockServiceTypeRegistryService() {
- final short tomcatTypeCode = 1010;
- final String tomcatTypeName = "TOMCAT";
ServiceTypeRegistryMockFactory mockFactory = new ServiceTypeRegistryMockFactory();
- mockFactory.addServiceTypeMock(tomcatTypeCode, tomcatTypeName);
+ mockFactory.addServiceTypeMock(UNKNOWN_TYPE_CODE, UNKNOWN_TYPE_NAME, RECORD_STATISTICS);
+ mockFactory.addServiceTypeMock(USER_TYPE_CODE, USER_TYPE_NAME, RECORD_STATISTICS);
+ mockFactory.addServiceTypeMock(TOMCAT_TYPE_CODE, TOMCAT_TYPE_NAME, RECORD_STATISTICS);
+ mockFactory.addServiceTypeMock(RPC_TYPE_CODE, RPC_TYPE_NAME, RECORD_STATISTICS);
+ mockFactory.addServiceTypeMock(BACKEND_TYPE_CODE, BACKEND_TYPE_NAME, TERMINAL, INCLUDE_DESTINATION_ID);
+ mockFactory.addServiceTypeMock(MESSAGE_QUEUE_TYPE_CODE, MESSAGE_QUEUE_TYPE_NAME, QUEUE, RECORD_STATISTICS);
return mockFactory.createMockServiceTypeRegistryService();
}
+ private AnnotationKeyRegistryService mockAnnotationKeyRegistryService() {
+ final AnnotationKey rpcUrlAnnotationKey = AnnotationKeyFactory.of(RPC_ANNOTATION_CODE, RPC_ANNOTATION_NAME);
+ return new AnnotationKeyRegistryService() {
+ @Override
+ public AnnotationKey findAnnotationKey(int annotationCode) {
+ return rpcUrlAnnotationKey;
+ }
+
+ @Override
+ public AnnotationKey findAnnotationKeyByName(String keyName) {
+ return rpcUrlAnnotationKey;
+ }
+
+ @Override
+ public AnnotationKey findApiErrorCode(int annotationCode) {
+ return rpcUrlAnnotationKey;
+ }
+ };
+ }
+
@Test
public void fromToFilterTest() {
- ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName("TOMCAT");
+ ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
final short tomcatServiceType = tomcat.getCode();
FilterDescriptor descriptor = new FilterDescriptor();
@@ -44,9 +94,9 @@ public void fromToFilterTest() {
descriptor.setToServiceType(tomcat.getName());
// descriptor.setToAgentId("AGENT_B");
- FilterHint hint = new FilterHint(Collections.<RpcHint>emptyList());
+ FilterHint hint = new FilterHint(Collections.emptyList());
- LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService);
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
logger.debug(linkFilter.toString());
SpanBo fromSpanBo = new SpanBo();
@@ -74,7 +124,7 @@ public void fromToFilterTest() {
@Test
public void fromToFilterAgentTest() {
- final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName("TOMCAT");
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
final short tomcatServiceType = tomcat.getCode();
FilterDescriptor descriptor = new FilterDescriptor();
@@ -86,9 +136,9 @@ public void fromToFilterAgentTest() {
descriptor.setToServiceType(tomcat.getName());
descriptor.setToAgentId("AGENT_B");
- FilterHint hint = new FilterHint(Collections.<RpcHint>emptyList());
+ FilterHint hint = new FilterHint(Collections.emptyList());
- LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService);
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
logger.debug(linkFilter.toString());
SpanBo fromSpanBo = new SpanBo();
@@ -111,9 +161,345 @@ public void fromToFilterAgentTest() {
Assert.assertTrue(linkFilter.include(Arrays.asList(fromSpanBo, toSpanBO)));
Assert.assertFalse(linkFilter.include(Arrays.asList(fromSpanBo, spanBoC)));
+ }
+
+ @Test
+ public void userToWasFilter() {
+ final ServiceType user = serviceTypeRegistryService.findServiceTypeByName(USER_TYPE_NAME);
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("USER");
+ descriptor.setFromServiceType(user.getName());
+ descriptor.setToApplicationName("APP_A");
+ descriptor.setToServiceType(tomcat.getName());
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ SpanBo user_appA = new SpanBo();
+ user_appA.setSpanId(1);
+ user_appA.setParentSpanId(-1);
+ user_appA.setApplicationId("APP_A");
+ user_appA.setApplicationServiceType(tomcat.getCode());
+ SpanBo appA_appB = new SpanBo();
+ appA_appB.setSpanId(2);
+ appA_appB.setParentSpanId(1);
+ appA_appB.setApplicationId("APP_B");
+ appA_appB.setApplicationServiceType(tomcat.getCode());
+ SpanBo appB_appA = new SpanBo();
+ appB_appA.setSpanId(3);
+ appB_appA.setParentSpanId(2);
+ appB_appA.setApplicationId("APP_A");
+ appB_appA.setApplicationServiceType(tomcat.getCode());
+
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(user_appA)));
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(appA_appB)));
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(appB_appA)));
+ Assert.assertTrue(linkFilter.include(Arrays.asList(user_appA, appA_appB, appB_appA)));
+ }
+
+ @Test
+ public void wasToUnknownFilter() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+ final ServiceType unknown = serviceTypeRegistryService.findServiceTypeByName(UNKNOWN_TYPE_NAME);
+
+ final String rpcHost = "some.domain.name";
+ final String rpcUrl = "http://" + rpcHost + "/some/test/path";
+ final String urlPattern = "/some/test/**";
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName(rpcHost);
+ descriptor.setToServiceType(unknown.getName());
+ descriptor.setUrl(encodeUrl(urlPattern));
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ // Reject - no rpc span event
+ SpanBo spanBo = new SpanBo();
+ spanBo.setSpanId(1);
+ spanBo.setParentSpanId(-1);
+ spanBo.setApplicationId("APP_A");
+ spanBo.setApplicationServiceType(tomcat.getCode());
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(spanBo)));
+
+ // Accept - has matching rpc span event
+ AnnotationBo rpcAnnotation = new AnnotationBo();
+ rpcAnnotation.setKey(RPC_ANNOTATION_CODE);
+ rpcAnnotation.setValue(rpcUrl);
+ SpanEventBo rpcSpanEvent = new SpanEventBo();
+ rpcSpanEvent.setServiceType(RPC_TYPE_CODE);
+ rpcSpanEvent.setDestinationId(rpcHost);
+ rpcSpanEvent.setAnnotationBoList(Collections.singletonList(rpcAnnotation));
+ spanBo.addSpanEvent(rpcSpanEvent);
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(spanBo)));
+ }
+
+ @Test
+ public void wasToWasFilter_perfectMatch() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName("APP_B");
+ descriptor.setToServiceType(tomcat.getName());
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ // Accept - perfect match
+ SpanBo user_appA = new SpanBo();
+ user_appA.setSpanId(1);
+ user_appA.setParentSpanId(-1);
+ user_appA.setApplicationId("APP_A");
+ user_appA.setApplicationServiceType(tomcat.getCode());
+ SpanBo appA_appB = new SpanBo();
+ appA_appB.setSpanId(2);
+ appA_appB.setParentSpanId(1);
+ appA_appB.setApplicationId("APP_B");
+ appA_appB.setApplicationServiceType(tomcat.getCode());
+ Assert.assertTrue(linkFilter.include(Arrays.asList(user_appA, appA_appB)));
+ }
+
+ @Test
+ public void wasToWasFilter_noMatch() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName("APP_B");
+ descriptor.setToServiceType(tomcat.getName());
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ // Reject - fromNode different
+ SpanBo user_appC = new SpanBo();
+ user_appC.setSpanId(1);
+ user_appC.setParentSpanId(-1);
+ user_appC.setApplicationId("APP_C");
+ user_appC.setApplicationServiceType(tomcat.getCode());
+ SpanBo appC_appB = new SpanBo();
+ appC_appB.setSpanId(2);
+ appC_appB.setParentSpanId(1);
+ appC_appB.setApplicationId("APP_B");
+ appC_appB.setApplicationServiceType(tomcat.getCode());
+ Assert.assertFalse(linkFilter.include(Arrays.asList(user_appC, appC_appB)));
+
+ // Reject - toNode different
+ SpanBo user_appA = new SpanBo();
+ user_appA.setSpanId(1);
+ user_appA.setParentSpanId(-1);
+ user_appA.setApplicationId("APP_A");
+ user_appA.setApplicationServiceType(tomcat.getCode());
+ SpanBo appA_appC = new SpanBo();
+ appA_appC.setSpanId(2);
+ appA_appC.setParentSpanId(1);
+ appA_appC.setApplicationId("APP_C");
+ appA_appC.setApplicationServiceType(tomcat.getCode());
+ Assert.assertFalse(linkFilter.include(Arrays.asList(user_appA, appA_appC)));
}
+ @Test
+ public void wasToWasFilter_noMatch_missingReceivingSpan() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+
+ final String rpcHost = "some.domain.name";
+ final String rpcUrl = "http://" + rpcHost + "/some/test/path";
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName("APP_B");
+ descriptor.setToServiceType(tomcat.getName());
+
+ FilterHint emptyHint = new FilterHint(Collections.emptyList());
+ FilterHint unmatchingHint = new FilterHint(Collections.singletonList(
+ new RpcHint("APP_B", Collections.singletonList(
+ new RpcType("different.domain.name", RPC_TYPE_CODE)))));
+ FilterHint matchingHint = new FilterHint(Collections.singletonList(
+ new RpcHint("APP_B", Collections.singletonList(
+ new RpcType(rpcHost, RPC_TYPE_CODE)))));
+
+ LinkFilter emptyHintLinkFilter = new LinkFilter(descriptor, emptyHint, serviceTypeRegistryService, annotationKeyRegistryService);
+ LinkFilter unmatchingHintLinkFilter = new LinkFilter(descriptor, unmatchingHint, serviceTypeRegistryService, annotationKeyRegistryService);
+ LinkFilter matchingHintLinkFilter = new LinkFilter(descriptor, matchingHint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug("emptyHintLinkFilter : {}", emptyHintLinkFilter.toString());
+ logger.debug("unmatchingHintLinkFilter : {}", unmatchingHintLinkFilter.toString());
+ logger.debug("matchingHintLinkFilter : {}", matchingHintLinkFilter.toString());
+
+ SpanBo fromSpan = new SpanBo();
+ fromSpan.setSpanId(1);
+ fromSpan.setParentSpanId(-1);
+ fromSpan.setApplicationId("APP_A");
+ fromSpan.setApplicationServiceType(tomcat.getCode());
+ AnnotationBo rpcAnnotation = new AnnotationBo();
+ rpcAnnotation.setKey(RPC_ANNOTATION_CODE);
+ rpcAnnotation.setValue(rpcUrl);
+ SpanEventBo rpcSpanEvent = new SpanEventBo();
+ rpcSpanEvent.setServiceType(RPC_TYPE_CODE);
+ rpcSpanEvent.setDestinationId(rpcHost);
+ rpcSpanEvent.setAnnotationBoList(Collections.singletonList(rpcAnnotation));
+ fromSpan.addSpanEvent(rpcSpanEvent);
+ // Reject - filter hint empty
+ Assert.assertFalse(emptyHintLinkFilter.include(Collections.singletonList(fromSpan)));
+ // Reject - filter hint does not match
+ Assert.assertFalse(unmatchingHintLinkFilter.include(Collections.singletonList(fromSpan)));
+ // Accept - filter hint matches
+ Assert.assertTrue(matchingHintLinkFilter.include(Collections.singletonList(fromSpan)));
+
+ // Check rpc url as well
+ final String unmatchingUrlPattern = "/other/test/**";
+ final String matchingUrlPattern = "/some/test/**";
+ // Reject - url pattern does not match
+ descriptor.setUrl(unmatchingUrlPattern);
+ LinkFilter matchingHintLinkFilterWithUnmatchingUrlPattern = new LinkFilter(descriptor, matchingHint, serviceTypeRegistryService, annotationKeyRegistryService);
+ Assert.assertFalse(matchingHintLinkFilterWithUnmatchingUrlPattern.include(Collections.singletonList(fromSpan)));
+ // Accept - url pattern matches
+ descriptor.setUrl(encodeUrl(matchingUrlPattern));
+ LinkFilter matchingHintLinkFilterWithMatchingUrlPattern = new LinkFilter(descriptor, matchingHint, serviceTypeRegistryService, annotationKeyRegistryService);
+ Assert.assertTrue(matchingHintLinkFilterWithMatchingUrlPattern.include(Collections.singletonList(fromSpan)));
+ }
+
+ @Test
+ public void wasToBackendFilter() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+ final ServiceType backend = serviceTypeRegistryService.findServiceTypeByName(BACKEND_TYPE_NAME);
+
+ final String destinationA = "BACKEND_A";
+ final String destinationB = "BACKEND_B";
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName(destinationA);
+ descriptor.setToServiceType(backend.getName());
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ SpanBo matchingSpan = new SpanBo();
+ matchingSpan.setApplicationId("APP_A");
+ matchingSpan.setApplicationServiceType(tomcat.getCode());
+ SpanEventBo spanEventDestinationA = new SpanEventBo();
+ spanEventDestinationA.setDestinationId(destinationA);
+ spanEventDestinationA.setServiceType(BACKEND_TYPE_CODE);
+ matchingSpan.addSpanEvent(spanEventDestinationA);
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(matchingSpan)));
+
+ SpanBo unmatchingSpan = new SpanBo();
+ unmatchingSpan.setApplicationId("APP_A");
+ unmatchingSpan.setApplicationServiceType(tomcat.getCode());
+ SpanEventBo spanEventDestinationB = new SpanEventBo();
+ spanEventDestinationB.setDestinationId(destinationB);
+ spanEventDestinationB.setServiceType(BACKEND_TYPE_CODE);
+ unmatchingSpan.addSpanEvent(spanEventDestinationB);
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(unmatchingSpan)));
+
+ Assert.assertTrue(linkFilter.include(Arrays.asList(matchingSpan, unmatchingSpan)));
+
+ SpanBo bothSpan = new SpanBo();
+ bothSpan.setApplicationId("APP_A");
+ bothSpan.setApplicationServiceType(tomcat.getCode());
+ bothSpan.addSpanEventBoList(Arrays.asList(spanEventDestinationA, spanEventDestinationB));
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(bothSpan)));
+ }
+ @Test
+ public void wasToQueueFilter() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+ final ServiceType messageQueue = serviceTypeRegistryService.findServiceTypeByName(MESSAGE_QUEUE_TYPE_NAME);
+
+ final String messageQueueA = "QUEUE_A";
+ final String messageQueueB = "QUEUE_B";
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName("APP_A");
+ descriptor.setFromServiceType(tomcat.getName());
+ descriptor.setToApplicationName(messageQueueA);
+ descriptor.setToServiceType(messageQueue.getName());
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ SpanBo matchingSpan = new SpanBo();
+ matchingSpan.setApplicationId("APP_A");
+ matchingSpan.setApplicationServiceType(tomcat.getCode());
+ SpanEventBo spanEventDestinationA = new SpanEventBo();
+ spanEventDestinationA.setDestinationId(messageQueueA);
+ spanEventDestinationA.setServiceType(MESSAGE_QUEUE_TYPE_CODE);
+ matchingSpan.addSpanEvent(spanEventDestinationA);
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(matchingSpan)));
+
+ SpanBo unmatchingSpan = new SpanBo();
+ unmatchingSpan.setApplicationId("APP_A");
+ unmatchingSpan.setApplicationServiceType(tomcat.getCode());
+ SpanEventBo spanEventDestinationB = new SpanEventBo();
+ spanEventDestinationB.setDestinationId(messageQueueB);
+ spanEventDestinationB.setServiceType(MESSAGE_QUEUE_TYPE_CODE);
+ unmatchingSpan.addSpanEvent(spanEventDestinationB);
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(unmatchingSpan)));
+
+ Assert.assertTrue(linkFilter.include(Arrays.asList(matchingSpan, unmatchingSpan)));
+
+ SpanBo bothSpan = new SpanBo();
+ bothSpan.setApplicationId("APP_A");
+ bothSpan.setApplicationServiceType(tomcat.getCode());
+ bothSpan.addSpanEventBoList(Arrays.asList(spanEventDestinationA, spanEventDestinationB));
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(bothSpan)));
+ }
+
+ @Test
+ public void queueToWasFilter() {
+ final ServiceType tomcat = serviceTypeRegistryService.findServiceTypeByName(TOMCAT_TYPE_NAME);
+ final ServiceType messageQueue = serviceTypeRegistryService.findServiceTypeByName(MESSAGE_QUEUE_TYPE_NAME);
+
+ final String messageQueueA = "QUEUE_A";
+ final String messageQueueB = "QUEUE_B";
+
+ FilterDescriptor descriptor = new FilterDescriptor();
+ descriptor.setFromApplicationName(messageQueueA);
+ descriptor.setFromServiceType(messageQueue.getName());
+ descriptor.setToApplicationName("APP_A");
+ descriptor.setToServiceType(tomcat.getName());
+
+ FilterHint hint = new FilterHint(Collections.emptyList());
+
+ LinkFilter linkFilter = new LinkFilter(descriptor, hint, serviceTypeRegistryService, annotationKeyRegistryService);
+ logger.debug(linkFilter.toString());
+
+ SpanBo matchingSpan = new SpanBo();
+ matchingSpan.setApplicationId("APP_A");
+ matchingSpan.setApplicationServiceType(tomcat.getCode());
+ matchingSpan.setAcceptorHost(messageQueueA);
+ Assert.assertTrue(linkFilter.include(Collections.singletonList(matchingSpan)));
+
+ SpanBo unmatchingSpan = new SpanBo();
+ unmatchingSpan.setApplicationId("APP_A");
+ unmatchingSpan.setApplicationServiceType(tomcat.getCode());
+ unmatchingSpan.setAcceptorHost(messageQueueB);
+ Assert.assertFalse(linkFilter.include(Collections.singletonList(unmatchingSpan)));
+ }
+
+ private String encodeUrl(String value) {
+ return Base64.encodeBytes(value.getBytes(StandardCharsets.UTF_8));
+ }
}
\ No newline at end of file
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java
new file mode 100644
index 000000000000..25bcd1b9eb33
--- /dev/null
+++ b/web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright 2017 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.filter;
+
+import com.navercorp.pinpoint.common.server.bo.AnnotationBo;
+import com.navercorp.pinpoint.common.server.bo.SpanBo;
+import com.navercorp.pinpoint.common.server.bo.SpanEventBo;
+import com.navercorp.pinpoint.common.service.AnnotationKeyRegistryService;
+import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
+import com.navercorp.pinpoint.common.trace.AnnotationKey;
+import com.navercorp.pinpoint.common.trace.AnnotationKeyFactory;
+import com.navercorp.pinpoint.common.trace.ServiceType;
+import com.navercorp.pinpoint.common.trace.ServiceTypeFactory;
+import com.navercorp.pinpoint.common.trace.ServiceTypeProperty;
+import org.apache.hadoop.hbase.util.Base64;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class RpcURLPatternFilterTest {
+
+ private final AnnotationKey TEST_RPC_URL_ANNOTATION_KEY = AnnotationKeyFactory.of(-1, "rpc.url");
+ private final short TEST_RPC_SERVICE_TYPE_CODE = 9999;
+ private final String TEST_RPC_SERVICE_TYPE_NAME = "TEST_RPC";
+ private final ServiceType TEST_RPC_SERVICE_TYPE = ServiceTypeFactory.of(TEST_RPC_SERVICE_TYPE_CODE, TEST_RPC_SERVICE_TYPE_NAME, ServiceTypeProperty.RECORD_STATISTICS);
+
+ private ServiceTypeRegistryService serviceTypeRegistryService;
+
+ private AnnotationKeyRegistryService annotationKeyRegistryService;
+
+ @Before
+ public void setUp() {
+ serviceTypeRegistryService = new ServiceTypeRegistryService() {
+ @Override
+ public ServiceType findServiceType(short serviceType) {
+ return TEST_RPC_SERVICE_TYPE;
+ }
+
+ @Override
+ public ServiceType findServiceTypeByName(String typeName) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public List<ServiceType> findDesc(String desc) {
+ throw new UnsupportedOperationException();
+ }
+ };
+ annotationKeyRegistryService = new AnnotationKeyRegistryService() {
+ @Override
+ public AnnotationKey findAnnotationKey(int annotationCode) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public AnnotationKey findAnnotationKeyByName(String keyName) {
+ return TEST_RPC_URL_ANNOTATION_KEY;
+ }
+
+ @Override
+ public AnnotationKey findApiErrorCode(int annotationCode) {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+
+ @Test
+ public void emptyPatternShouldReject() {
+ // Given
+ final String urlPattern = "";
+ final String rpcUrl = "http://a.b.c";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertFalse(accept);
+ }
+
+ @Test
+ public void testPath() {
+ // Given
+ final String urlPattern = "/test/**";
+ final String rpcUrl = "/test/rpc/path";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertTrue(accept);
+ }
+
+ @Test
+ public void testFullUrl() {
+ // Given
+ final String urlPattern = "/test/**";
+ final String rpcUrl = "http://some.test.domain:8080/test/rpc/path";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertTrue(accept);
+ }
+
+ @Test
+ public void testDomainAndPath() {
+ // Given
+ final String urlPattern = "some.test.domain/test/rpc/**";
+ final String rpcUrl = "some.test.domain/test/rpc/test?value=11";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertTrue(accept);
+ }
+
+ @Test
+ public void testString() {
+ // Given
+ final String urlPattern = "some*";
+ final String rpcUrl = "someName";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertTrue(accept);
+ }
+
+ @Test
+ public void testWeirdPath() {
+ // Given
+ final String urlPattern = ":/**";
+ final String rpcUrl = ":/invalid/uri";
+ final RpcURLPatternFilter rpcURLPatternFilter = new RpcURLPatternFilter(encode(urlPattern), serviceTypeRegistryService, annotationKeyRegistryService);
+ // When
+ boolean accept = rpcURLPatternFilter.accept(createTestRpcSpans(rpcUrl));
+ // Then
+ Assert.assertTrue(accept);
+ }
+
+ private String encode(String value) {
+ return Base64.encodeBytes(value.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private List<SpanBo> createTestRpcSpans(String... rpcUrls) {
+ List<SpanBo> spanBos = new ArrayList<>();
+ for (String rpcUrl : rpcUrls) {
+ SpanEventBo testRpcSpanEvent = new SpanEventBo();
+ testRpcSpanEvent.setServiceType(TEST_RPC_SERVICE_TYPE_CODE);
+ AnnotationBo testRpcAnnotationBo = new AnnotationBo();
+ testRpcAnnotationBo.setKey(TEST_RPC_URL_ANNOTATION_KEY.getCode());
+ testRpcAnnotationBo.setValue(rpcUrl);
+ testRpcSpanEvent.setAnnotationBoList(Collections.singletonList(testRpcAnnotationBo));
+ SpanBo spanBo = new SpanBo();
+ spanBo.addSpanEvent(testRpcSpanEvent);
+ spanBos.add(spanBo);
+ }
+ return spanBos;
+ }
+}
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/util/ServiceTypeRegistryMockFactory.java b/web/src/test/java/com/navercorp/pinpoint/web/util/ServiceTypeRegistryMockFactory.java
index 5a8143f32b0e..52e183e38786 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/util/ServiceTypeRegistryMockFactory.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/util/ServiceTypeRegistryMockFactory.java
@@ -19,6 +19,7 @@
import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.common.trace.ServiceTypeCategory;
+import com.navercorp.pinpoint.common.trace.ServiceTypeProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -38,16 +39,43 @@ public class ServiceTypeRegistryMockFactory {
private final Map<Short, ServiceType> serviceTypeMap = new HashMap<>();
- public void addServiceTypeMock(short typeCode, String typeName) {
+ public void addServiceTypeMock(short typeCode, String typeName, ServiceTypeProperty... serviceTypeProperties) {
// setup serviceType
ServiceType mockServiceType = mock(ServiceType.class);
when(mockServiceType.getCode()).thenReturn(typeCode);
when(mockServiceType.getName()).thenReturn(typeName);
+ if (ServiceType.USER.getName().equals(typeName)) {
+ when(mockServiceType.isUser()).thenReturn(true);
+ }
+ if (ServiceType.UNKNOWN.getName().equals(typeName)) {
+ when(mockServiceType.isUnknown()).thenReturn(true);
+ }
if (ServiceTypeCategory.SERVER.contains(typeCode)) {
- logger.debug("mark isWas() {}/{}", mockServiceType.getName(), mockServiceType.getCode());
when(mockServiceType.isWas()).thenReturn(true);
}
+ if (ServiceTypeCategory.RPC.contains(typeCode)) {
+ when(mockServiceType.isRpcClient()).thenReturn(true);
+ }
+
+ for (ServiceTypeProperty serviceTypeProperty : serviceTypeProperties) {
+ switch (serviceTypeProperty) {
+ case TERMINAL:
+ when(mockServiceType.isTerminal()).thenReturn(true);
+ break;
+ case QUEUE:
+ when(mockServiceType.isQueue()).thenReturn(true);
+ break;
+ case RECORD_STATISTICS:
+ when(mockServiceType.isRecordStatistics()).thenReturn(true);
+ break;
+ case INCLUDE_DESTINATION_ID:
+ when(mockServiceType.isIncludeDestinationId()).thenReturn(true);
+ break;
+ default:
+ throw new IllegalArgumentException("Unknown serviceTypeProperty : " + serviceTypeProperty);
+ }
+ }
this.serviceTypeMap.put(typeCode, mockServiceType);
}
| test | val | "2017-05-23T03:45:22" | "2017-05-19T10:02:28Z" | Xylus | test |
pinpoint-apm/pinpoint/2789_2956 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2789 | pinpoint-apm/pinpoint/2956 | [
"keyword_pr_to_issue"
] | 910651fc8621c67bad794b59adda2c438837b23c | 5f4f53348b2db50e789d0296dc32cff3f06c2c04 | [] | [] | "2017-05-24T07:23:18Z" | [
"enhancement",
"module:project-common"
] | Update library dependency versions | #### Description
Update various library versions :
* ASM : 5.1 -> 5.2
* Guava : 19.0 -> 20.0
* Mockito : mockito-all 1.10.19 -> mockito-core 2.7.22
* commons-beanutils : 1.8.3 -> 1.9.3
* aspectjweaver : 1.8.9 -> 1.8.10
* Spring : 4.1.9.RELEASE -> 4.3.8.RELEASE
* Spring Batch : 2.2.7.RELEASE -> 3.0.7.RELEASE
* Spring Security : 4.0.4.RELEASE -> 4.2.2.RELEASE | [
"pom.xml",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/ASMClassNodeAdapter.java"
] | [
"pom.xml",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/ASMClassNodeAdapter.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/ASMClassNodeAdapterTest.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/ASMClassWriterTest.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/CollectJobTest.java"
] | diff --git a/pom.xml b/pom.xml
index de5d9b3e89f6..2d580d19c9b3 100644
--- a/pom.xml
+++ b/pom.xml
@@ -80,9 +80,9 @@
<httpcomponents.version>4.3</httpcomponents.version>
<jedis.version>2.4.2</jedis.version>
<cloverLicenseLocation>${basedir}/clover.license</cloverLicenseLocation>
- <spring.version>4.1.9.RELEASE</spring.version>
- <spring.batch.version>2.2.7.RELEASE</spring.batch.version>
- <spring.security.version>4.0.4.RELEASE</spring.security.version>
+ <spring.version>4.3.8.RELEASE</spring.version>
+ <spring.batch.version>3.0.7.RELEASE</spring.batch.version>
+ <spring.security.version>4.2.2.RELEASE</spring.security.version>
<docker.maven.plugin.version>0.4.3</docker.maven.plugin.version>
<cassandra.driver.version>2.1.7.1</cassandra.driver.version>
<sniffer.artifactid>java16</sniffer.artifactid>
@@ -101,7 +101,7 @@
</dependency>
<dependency>
<groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
+ <artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
@@ -538,7 +538,7 @@
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
- <version>1.8.3</version>
+ <version>1.9.3</version>
</dependency>
<dependency>
@@ -569,13 +569,13 @@
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-debug-all</artifactId>
- <version>5.1</version>
+ <version>5.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
- <version>1.8.9</version>
+ <version>1.8.10</version>
</dependency>
@@ -621,8 +621,8 @@
</dependency>
<dependency>
<groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <version>1.10.19</version>
+ <artifactId>mockito-core</artifactId>
+ <version>2.7.22</version>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
@@ -679,7 +679,7 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
- <version>19.0</version>
+ <version>20.0</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/ASMClassNodeAdapter.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/ASMClassNodeAdapter.java
index 3bff20f2273f..0252f99c8b15 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/ASMClassNodeAdapter.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/ASMClassNodeAdapter.java
@@ -47,8 +47,11 @@ public static ASMClassNodeAdapter get(final InstrumentContext pluginContext, fin
}
public static ASMClassNodeAdapter get(final InstrumentContext pluginContext, final ClassLoader classLoader, final String classInternalName, final boolean skipCode) {
- if (pluginContext == null || classInternalName == null) {
- throw new IllegalArgumentException("plugin context or class name must not be null.");
+ if (pluginContext == null) {
+ throw new NullPointerException("pluginContext must not be null");
+ }
+ if (classInternalName == null) {
+ throw new NullPointerException("classInternalName must not be null");
}
InputStream in = null;
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/ASMClassNodeAdapterTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/ASMClassNodeAdapterTest.java
index 90e38086d2e6..3327195fd8e5 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/ASMClassNodeAdapterTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/ASMClassNodeAdapterTest.java
@@ -216,7 +216,7 @@ public void handle(ClassNode classNode) {
@Test
public void hasAnnotation() throws Exception {
- ASMClassNodeAdapter classNodeAdapter = ASMClassNodeAdapter.get(pluginContext, null, "com/navercorp/pinpoint/profiler/instrument/mock/AnnotationClass");
+ ASMClassNodeAdapter classNodeAdapter = ASMClassNodeAdapter.get(pluginContext, ASMClassNodeLoader.getClassLoader(), "com/navercorp/pinpoint/profiler/instrument/mock/AnnotationClass");
Assert.assertTrue(classNodeAdapter.hasAnnotation(Aspect.class));
Assert.assertFalse(classNodeAdapter.hasAnnotation(Override.class));
}
@@ -243,7 +243,7 @@ public void handle(ClassNode classNode) {
@Test
public void subclassOf() {
- ASMClassNodeAdapter adapter = ASMClassNodeAdapter.get(pluginContext, null, "com/navercorp/pinpoint/profiler/instrument/mock/ExtendedClass");
+ ASMClassNodeAdapter adapter = ASMClassNodeAdapter.get(pluginContext, ASMClassNodeLoader.getClassLoader(), "com/navercorp/pinpoint/profiler/instrument/mock/ExtendedClass");
// self
assertEquals(true, adapter.subclassOf("com/navercorp/pinpoint/profiler/instrument/mock/ExtendedClass"));
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/ASMClassWriterTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/ASMClassWriterTest.java
index 0a2a248f44e5..7fc68f0aee53 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/ASMClassWriterTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/ASMClassWriterTest.java
@@ -19,6 +19,7 @@
import com.navercorp.pinpoint.profiler.util.JavaAssistUtils;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.ArgumentMatchers;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.objectweb.asm.tree.ClassNode;
@@ -28,6 +29,7 @@
import java.io.PrintWriter;
import static org.junit.Assert.*;
+import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -42,7 +44,7 @@ public class ASMClassWriterTest {
@Before
public void setUp() {
- when(pluginContext.injectClass(any(ClassLoader.class), any(String.class))).thenAnswer(new Answer<Class<?>>() {
+ when(pluginContext.injectClass(ArgumentMatchers.<ClassLoader>isNull(), anyString())).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(InvocationOnMock invocation) throws Throwable {
@@ -53,7 +55,7 @@ public Class<?> answer(InvocationOnMock invocation) throws Throwable {
}
});
- when(pluginContext.getResourceAsStream(any(ClassLoader.class), any(String.class))).thenAnswer(new Answer<InputStream>() {
+ when(pluginContext.getResourceAsStream(ArgumentMatchers.<ClassLoader>isNull(), anyString())).thenAnswer(new Answer<InputStream>() {
@Override
public InputStream answer(InvocationOnMock invocation) throws Throwable {
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/CollectJobTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/CollectJobTest.java
index 3fb01a5c0f0b..bc14c804ceb9 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/CollectJobTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/CollectJobTest.java
@@ -28,6 +28,7 @@
import com.navercorp.pinpoint.profiler.sender.DataSender;
import com.navercorp.pinpoint.profiler.util.TestInterceptorRegistryBinder;
import com.navercorp.pinpoint.thrift.dto.TAgentStat;
+import com.navercorp.pinpoint.thrift.dto.TAgentStatBatch;
import org.junit.Test;
import org.mockito.Mockito;
@@ -52,7 +53,7 @@ public void run() throws Exception {
CollectJob job = new CollectJob(dataSender, "agent", 0, agentStatMetricCollector, 1);
job.run();
- Mockito.verify(dataSender).send(any(TAgentStat.class));
+ Mockito.verify(dataSender).send(any(TAgentStatBatch.class));
}
| val | val | "2017-05-24T08:47:01" | "2017-04-12T09:44:50Z" | Xylus | test |
pinpoint-apm/pinpoint/3002_3012 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/3002 | pinpoint-apm/pinpoint/3012 | [
"keyword_pr_to_issue"
] | c65bc834f94c4851230699be8a54e0307d2a5a6d | a10b6e4af48a40f11a4705557580c59eab1cac12 | [] | [] | "2017-06-08T02:57:52Z" | [
"bug",
"module:plugin"
] | Dubbo consumer interceptor does not propagate disable sampling flag to remote nodes | #### Description
`DubboConsumerInterceptor` checks for the current trace using `TraceContext.currentTraceObject()`. This API returns the current trace object only if the current trace should be sampled. It returns null when no trace object exists **or** when the current trace shouldn't be sampled. So even if a disabled trace object exists, it doesn't propagate this information over RPC.
We should instead use `TraceContext.currentRawTraceObject()` and check for sampling with the returned trace object.
issue found from #2989 | [
"plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboConsumerInterceptor.java",
"plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboProviderInterceptor.java"
] | [
"plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboConsumerInterceptor.java",
"plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboProviderInterceptor.java"
] | [] | diff --git a/plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboConsumerInterceptor.java b/plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboConsumerInterceptor.java
index 70847b4ccd92..37508a894ddc 100644
--- a/plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboConsumerInterceptor.java
+++ b/plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboConsumerInterceptor.java
@@ -22,7 +22,12 @@ public DubboConsumerInterceptor(TraceContext traceContext, MethodDescriptor desc
@Override
public void before(Object target, Object arg0) {
- Trace trace = this.getTrace(target);
+ // Ignore monitor service
+ if (isMonitorService(target)) {
+ return;
+ }
+
+ Trace trace = traceContext.currentRawTraceObject();
if (trace == null) {
return;
}
@@ -58,7 +63,12 @@ public void before(Object target, Object arg0) {
@Override
public void after(Object target, Object arg0, Object result, Throwable throwable) {
- Trace trace = this.getTrace(target);
+ // Ignore monitor service
+ if (isMonitorService(target)) {
+ return;
+ }
+
+ Trace trace = traceContext.currentTraceObject();
if (trace == null) {
return;
}
@@ -87,14 +97,11 @@ public void after(Object target, Object arg0, Object result, Throwable throwable
}
}
- private Trace getTrace(Object target) {
- Invoker invoker = (Invoker) target;
- // Ignore monitor service.
- if (DubboConstants.MONITOR_SERVICE_FQCN.equals(invoker.getInterface().getName())) {
- return null;
+ private boolean isMonitorService(Object target) {
+ if (target instanceof Invoker) {
+ Invoker invoker = (Invoker) target;
+ return DubboConstants.MONITOR_SERVICE_FQCN.equals(invoker.getInterface().getName());
}
-
- return traceContext.currentRawTraceObject();
+ return false;
}
-
}
diff --git a/plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboProviderInterceptor.java b/plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboProviderInterceptor.java
index 422d19901f16..b1d2d57bfa2d 100644
--- a/plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboProviderInterceptor.java
+++ b/plugins/dubbo/src/main/java/com/navercorp/pinpoint/plugin/dubbo/interceptor/DubboProviderInterceptor.java
@@ -37,13 +37,10 @@ protected Trace createTrace(Object target, Object[] args) {
String transactionId = invocation.getAttachment(DubboConstants.META_TRANSACTION_ID);
// If there's no trasanction id, a new trasaction begins here.
+ // FIXME There seems to be cases where the invoke method is called after a span is already created.
+ // We'll have to check if a trace object already exists and create a span event instead of a span in that case.
if (transactionId == null) {
- Trace trace = traceContext.currentTraceObject();
- if (trace == null) {
- return traceContext.newTraceObject();
- } else {
- return trace;
- }
+ return traceContext.newTraceObject();
}
// otherwise, continue tracing with given data.
| null | val | val | "2017-06-08T04:44:53" | "2017-06-05T08:20:45Z" | Xylus | test |
pinpoint-apm/pinpoint/2906_3032 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2906 | pinpoint-apm/pinpoint/3032 | [
"keyword_pr_to_issue"
] | 1dac94ac011ecbfd9dc3009d3f67d65667b787a4 | f123b463a64fdf5319247e9b0194b87530193b7d | [
"@teambullseye \r\nHi~\r\nSorry. I can't understand your issue.\r\nPlease explain more detail.",
"Pinpoint version: 1.6.0\r\nwhen realtime is selected, the scatter chart is supposed to change to 1m interval, but there's a bug in the code causing scatter chart interval not to change from already selected interval.\r\nwhen 2 days is selected followed by realtime, it **freezes** the page, since scatter chart is trying to retrieve the data for last 2 days every 2 seconds",
"@teambullseye \r\nTime interval of scatter chart in realtime does not related with time period.\r\nTime interval of scatter chart in realtime always is about 2s when fast response.\r\nand x- range of scatter chart in realtime always is 5m.\r\n\r\nCan you capture request of scatter chart when freezes the page.",
"whats happening is the set timeperiod never updates when going to realtime this results in hbase overloading due ot the realtime status update request\r\n\r\nnavbar.directive.js\r\n\r\nhad this line removed aline similar to this UrlVoService.setReadablePeriod(cfg.periodType.REALTIME); on line 312 which caused this issue it needs to be there of when switching to real time the last set timeperiod attempts to do the real time refresh because it never recognizes the period type",
"we will make a pull request with the fix....if you go to a 2 day view and then back to real time (without refreshing) you should see the issue as long as you have a large amount of data in your hbase for that application already...then you have to refresh to get back to a normal view because the screen freezes",
"@teambullseye \r\nIn summary, does the period setting before realtime mode affect the scatter-chart's request parameters in realtime mode?",
"Yes but more so selecting real time fails to ever set a new default time period for realtime that applies back to the page modules",
"What does 'default time period' mean?\r\nYou can not modify the 'time period' in real-time mode. it is hard coded to 5m.\r\nAll 'time period' in real-time mode is a fixed value.",
"can this be reviewed we have referenced the fix...the real time period type was never being passed so it was always defaulting to the current previously selected time period which was causing the error it seems the added line was dropped during some previous commits so we added it back in to fix the issue",
"sorry. I will review your pr.",
"This issue/proposal has been automatically marked as stale because it hasn't had any recent activity. It will automatically be closed if no further activity occurs for 20days. If you think this should still be open, or the problem still persists, just pop a reply in the comments and one of the maintainers will (try!) to follow up. Thank you for your interest and contribution to the Pinpoint Community.\n"
] | [] | "2017-06-12T18:49:44Z" | [
"stale"
] | UI time period not updating properly when using real time view | <!--
If you're reporting a bug or seeking help because something is not working,
please fill out below.
For all else, feel free to DELETE everything and post away your issue!
-->
#### Description
<!--- Provide a more detailed introduction to the issue itself -->
#### Environment
<!--- Include as many relevant details about the environment you experienced the bug in -->
* Pinpoint version:
* OS, WAS, affected library, etc:
* Additional details (e.g. how your collector/web is set up):
#### Additional Info
<!--- Not obligatory, but things like logs can help if something's not working -->
| [
"web/src/main/webapp/features/navbar/navbar.directive.js"
] | [
"web/src/main/webapp/features/navbar/navbar.directive.js"
] | [] | diff --git a/web/src/main/webapp/features/navbar/navbar.directive.js b/web/src/main/webapp/features/navbar/navbar.directive.js
index 2d0427ac0c96..0938d3e3ac9a 100644
--- a/web/src/main/webapp/features/navbar/navbar.directive.js
+++ b/web/src/main/webapp/features/navbar/navbar.directive.js
@@ -309,6 +309,7 @@
oNavbarVoService.setReadablePeriod( PreferenceService.getRealtimeScatterXRangeStr() );
oNavbarVoService.setQueryEndDateTime( CommonUtilService.formatDate( currentServerTime ) );
oNavbarVoService.autoCalculateByQueryEndDateTimeAndReadablePeriod();
+ UrlVoService.setReadablePeriod(cfg.periodType.REALTIME);
UrlVoService.setQueryEndDateTime( CommonUtilService.formatDate( currentServerTime ) );
UrlVoService.autoCalculateByQueryEndDateTimeAndReadablePeriod();
emitAsChanged();
| null | test | val | "2017-06-12T14:30:21" | "2017-05-09T14:16:43Z" | teambullseye | test |
pinpoint-apm/pinpoint/3090_3098 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/3090 | pinpoint-apm/pinpoint/3098 | [
"keyword_pr_to_issue"
] | bdfe6006bde4dc9991ed1ca4b5b395f766e48ed0 | 59eb8f104bc0f7b92b8837ece3d403f59bdc6e3e | [
"Looks like a bug in the Cassandra datastax plugin.\r\nThanks for reporting!"
] | [] | "2017-06-29T05:10:34Z" | [
"bug",
"module:plugin"
] | Corrupted(Invalid Sequence) - Unable to trace DataStax Cassandra Batch Sql statement - CassandraStatementExecuteQueryInterceptor | During in one of my transaction I am observing the Corrupted(Invalid Sequence) for couple of my transactions, when looking at the agent logs we had observed the below exception
2017-06-27 15:07:50 [WARN ](draStatementExecuteQueryInterceptor) com.datastax.driver.core.BatchStatement cannot be cast to java.lang.String
java.lang.ClassCastException: com.datastax.driver.core.BatchStatement cannot be cast to java.lang.String
at com.navercorp.pinpoint.plugin.cassandra.interceptor.CassandraStatementExecuteQueryInterceptor.before(CassandraStatementExecuteQueryInterceptor.java:102)
at com.navercorp.pinpoint.bootstrap.interceptor.scope.ExceptionHandleScopedInterceptor.before(ExceptionHandleScopedInterceptor.java:57)
at com.datastax.driver.core.AbstractSession.execute(AbstractSession.java)
at com.target.oms.allocation.dao.NodeZonesDao.persist(NodeZonesDao.java:64)
at com.target.oms.allocation.dao.NodeZonesDao.save(NodeZonesDao.java:53)
at com.target.oms.allocation.dao.NodeZonesDao.save(NodeZonesDao.java:49)
at com.target.oms.allocation.dao.NodeZonesDao$$FastClassBySpringCGLIB$$90186cce.invoke(<generated>
From the exception its pretty clear that Pinpoint agent does not trace the Cassandra Datastax api call for Batch Sql statements
Specific code in CassandraStatementExecuteQueryInterceptor here where we are observing the issue
String sql;
if (args[0] instanceof BoundStatement) {
sql = ((BoundStatement) args[0]).preparedStatement().getQueryString();
} else if (args[0] instanceof RegularStatement) {
sql = ((RegularStatement) args[0]).getQueryString();
} else {
// we have string
sql = (String) args[0];
}
Kindly let me know If I have misinterpreted anything here | [
"plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java"
] | [
"plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java"
] | [
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastaxITBase.java"
] | diff --git a/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java b/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java
index dfeef8e456a9..551f0ca76bb5 100644
--- a/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java
+++ b/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java
@@ -19,8 +19,10 @@
import java.util.HashMap;
import java.util.Map;
+import com.datastax.driver.core.BatchStatement;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.RegularStatement;
+import com.datastax.driver.core.StatementWrapper;
import com.navercorp.pinpoint.bootstrap.context.DatabaseInfo;
import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.context.ParsingResult;
@@ -85,33 +87,27 @@ public void before(Object target, Object[] args) {
recorder.recordEndPoint(databaseInfo.getMultipleHost());
recorder.recordDestinationId(databaseInfo.getDatabaseId());
- String sql;
- if (args[0] instanceof BoundStatement) {
- sql = ((BoundStatement) args[0]).preparedStatement().getQueryString();
- } else if (args[0] instanceof RegularStatement) {
- sql = ((RegularStatement) args[0]).getQueryString();
- } else {
- // we have string
- sql = (String) args[0];
- }
+ String sql = retrieveSql(args[0]);
- ParsingResult parsingResult = traceContext.parseSql(sql);
- if (parsingResult != null) {
- ((ParsingResultAccessor) target)._$PINPOINT$_setParsingResult(parsingResult);
- } else {
- if (logger.isErrorEnabled()) {
- logger.error("sqlParsing fail. parsingResult is null sql:{}", sql);
+ if (sql != null) {
+ ParsingResult parsingResult = traceContext.parseSql(sql);
+ if (parsingResult != null) {
+ ((ParsingResultAccessor) target)._$PINPOINT$_setParsingResult(parsingResult);
+ } else {
+ if (logger.isErrorEnabled()) {
+ logger.error("sqlParsing fail. parsingResult is null sql:{}", sql);
+ }
}
- }
- Map<Integer, String> bindValue = ((BindValueAccessor) target)._$PINPOINT$_getBindValue();
- // TODO Add bind variable interceptors to BoundStatement's setter methods and bind method and pass it down
- // Extracting bind variables from already-serialized is too risky
- if (bindValue != null && !bindValue.isEmpty()) {
- String bindString = toBindVariable(bindValue);
- recorder.recordSqlParsingResult(parsingResult, bindString);
- } else {
- recorder.recordSqlParsingResult(parsingResult);
+ Map<Integer, String> bindValue = ((BindValueAccessor) target)._$PINPOINT$_getBindValue();
+ // TODO Add bind variable interceptors to BoundStatement's setter methods and bind method and pass it down
+ // Extracting bind variables from already-serialized is too risky
+ if (bindValue != null && !bindValue.isEmpty()) {
+ String bindString = toBindVariable(bindValue);
+ recorder.recordSqlParsingResult(parsingResult, bindString);
+ } else {
+ recorder.recordSqlParsingResult(parsingResult);
+ }
}
recorder.recordApi(descriptor);
@@ -124,6 +120,26 @@ public void before(Object target, Object[] args) {
}
}
+ private String retrieveSql(Object args0) {
+ String sql;
+ if (args0 instanceof BoundStatement) {
+ sql = ((BoundStatement) args0).preparedStatement().getQueryString();
+ } else if (args0 instanceof RegularStatement) {
+ sql = ((RegularStatement) args0).getQueryString();
+ } else if (args0 instanceof StatementWrapper) {
+ // method to get wrapped statement is package-private, skip.
+ sql = null;
+ } else if (args0 instanceof BatchStatement) {
+ // we could unroll all the batched statements and append ; between them if need be but it could be too long.
+ sql = null;
+ } else if (args0 instanceof String) {
+ sql = (String) args0;
+ } else {
+ sql = null;
+ }
+ return sql;
+ }
+
private void clean(Object target) {
if (target instanceof BindValueAccessor) {
((BindValueAccessor) target)._$PINPOINT$_setBindValue(new HashMap<Integer, String>());
| diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastaxITBase.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastaxITBase.java
index bc3cdb871887..c6f7550adf8a 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastaxITBase.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastaxITBase.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.plugin.jdk7.cassandra;
+import com.datastax.driver.core.BatchStatement;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PreparedStatement;
@@ -23,6 +24,7 @@
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.StatementWrapper;
import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
import com.navercorp.pinpoint.common.util.DefaultSqlParser;
@@ -94,7 +96,7 @@ public static void initializeCluster(String cassandraVersion) throws Exception {
}
@Test
- public void test() throws Exception {
+ public void testBoundStatement() throws Exception {
final int testId = 99;
final String testValue = "testValue";
@@ -157,6 +159,70 @@ public void test() throws Exception {
}
}
+ @Test
+ public void testBatchStatement_and_StatementWrapper() throws Exception {
+ final int testId1 = 998;
+ final String testValue1 = "testValue998";
+ final int testId2 = 999;
+ final String testValue2 = "testValue999";
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+
+ Session myKeyspaceSession = null;
+
+ try {
+ myKeyspaceSession = cluster.connect(TEST_KEYSPACE);
+
+ // ===============================================
+ // Insert Data 2 x (PreparedStatement, BoundStatement)
+ PreparedStatement preparedStatement = myKeyspaceSession.prepare(CQL_INSERT);
+ BoundStatement boundStatement1 = new BoundStatement(preparedStatement);
+ boundStatement1.bind(testId1, testValue1);
+ BoundStatement boundStatement2 = new BoundStatement(preparedStatement);
+ boundStatement2.bind(testId2, testValue2);
+
+ BatchStatement batchStatement = new BatchStatement();
+ batchStatement.add(boundStatement1);
+ batchStatement.add(boundStatement2);
+
+ myKeyspaceSession.execute(batchStatement);
+
+ verifier.printCache();
+ // Cluster#connect(String)
+ Class<?> clusterClass = Class.forName("com.datastax.driver.core.Cluster");
+ Method connect = clusterClass.getDeclaredMethod("connect", String.class);
+ verifier.verifyTrace(event(CASSANDRA, connect, null, CASSANDRA_ADDRESS, TEST_KEYSPACE));
+ // SessionManager#prepare(String) OR AbstractSession#prepare(String)
+ Class<?> sessionClass;
+ try {
+ sessionClass = Class.forName("com.datastax.driver.core.AbstractSession");
+ } catch (ClassNotFoundException e) {
+ sessionClass = Class.forName("com.datastax.driver.core.SessionManager");
+ }
+ Method prepare = sessionClass.getDeclaredMethod("prepare", String.class);
+ verifier.verifyTrace(event(CASSANDRA, prepare, null, CASSANDRA_ADDRESS, TEST_KEYSPACE, sql(CQL_INSERT, null)));
+ // SessionManager#execute(Statement) OR AbstractSession#execute(Statement)
+ Method execute = sessionClass.getDeclaredMethod("execute", Statement.class);
+ verifier.verifyTrace(event(CASSANDRA_EXECUTE_QUERY, execute, null, CASSANDRA_ADDRESS, TEST_KEYSPACE));
+
+ // ====================
+ final String cqlDelete = String.format("DELETE FROM %s.%s WHERE %s IN (? , ?)", TEST_KEYSPACE, TEST_TABLE, TEST_COL_ID);
+ PreparedStatement deletePreparedStatement = myKeyspaceSession.prepare(cqlDelete);
+ BoundStatement deleteBoundStatement = new BoundStatement(deletePreparedStatement);
+ deleteBoundStatement.bind(testId1, testId2);
+ Statement wrappedDeleteStatement = new StatementWrapper(deleteBoundStatement) {};
+ myKeyspaceSession.execute(wrappedDeleteStatement);
+
+ verifier.printCache();
+ // SessionManager#prepare(String) OR AbstractSession#prepare(String)
+ verifier.verifyTrace(event(CASSANDRA, prepare, null, CASSANDRA_ADDRESS, TEST_KEYSPACE, sql(cqlDelete, null)));
+ // SessionManager#execute(String, Object[]) OR AbstractSession#execute(String, Object[])
+ verifier.verifyTrace(event(CASSANDRA_EXECUTE_QUERY, execute, null, CASSANDRA_ADDRESS, TEST_KEYSPACE));
+ } finally {
+ closeSession(myKeyspaceSession);
+ }
+ }
+
private void verifySelect(ResultSet rs, int expectedTestId, String expectedTestValue) {
int resultCount = 0;
Iterator<Row> iter = rs.iterator();
| train | val | "2017-06-29T06:30:06" | "2017-06-28T09:03:12Z" | dinesh4747 | test |
pinpoint-apm/pinpoint/2013_3123 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2013 | pinpoint-apm/pinpoint/3123 | [
"keyword_pr_to_issue"
] | f6847a195f2984ab191985208619ce50cedac0a2 | 64fb81f5e8564ddfb50b9c3c95929497242b59f3 | [] | [] | "2017-07-07T08:43:13Z" | [
"enhancement",
"module:plugin"
] | Add support for MySQL connector 6 | A lot of previous classes that were transformed have been deprecated, and new classes are created under `com.mysql.cj.jdbc.Driver` - https://dev.mysql.com/doc/connector-j/6.0/en/connector-j-api-changes.html
| [
"plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java"
] | [
"plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java",
"plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/MySQL_6_X_ConnectionCreateInterceptor.java",
"plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/DatabaseGetter.java",
"plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/OrigHostToConnectToGetter.java",
"plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/OrigPortToConnectToGetter.java"
] | [] | diff --git a/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java
index e3c7d74bc986..c40113ddd0c8 100644
--- a/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java
+++ b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java
@@ -37,6 +37,7 @@
/**
* @author Jongho Moon
+ * @author HyunGil Jeong
*/
public class MySqlPlugin implements ProfilerPlugin, TransformTemplateAware {
@@ -82,8 +83,22 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
- InstrumentUtils.findConstructor(target, "java.lang.String", "int", "java.util.Properties", "java.lang.String", "java.lang.String")
- .addInterceptor("com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.MySQLConnectionCreateInterceptor");
+ InstrumentMethod constructor = target.getConstructor("java.lang.String", "int", "java.util.Properties", "java.lang.String", "java.lang.String");
+ if (constructor != null) {
+ constructor.addInterceptor("com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.MySQLConnectionCreateInterceptor");
+ }
+ // 6.0.2 ~ 6.0.3
+ InstrumentMethod constructor_6_X = target.getConstructor("com.mysql.cj.core.ConnectionString", "java.lang.String", "int", "java.util.Properties");
+ if (constructor_6_X == null) {
+ // 6.0.4+
+ constructor_6_X = target.getConstructor("com.mysql.cj.core.conf.url.HostInfo");
+ }
+ if (constructor_6_X != null) {
+ target.addGetter("com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.getter.OrigHostToConnectToGetter", "origHostToConnectTo");
+ target.addGetter("com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.getter.OrigPortToConnectToGetter", "origPortToConnectTo");
+ target.addGetter("com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.getter.DatabaseGetter", "database");
+ constructor_6_X.addInterceptor("com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.MySQL_6_X_ConnectionCreateInterceptor");
+ }
// close
InstrumentUtils.findMethod(target, "close")
@@ -142,10 +157,12 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
transformTemplate.transform("com.mysql.jdbc.Connection", transformer);
transformTemplate.transform("com.mysql.jdbc.ConnectionImpl", transformer);
+ // 6.x+
+ transformTemplate.transform("com.mysql.cj.jdbc.ConnectionImpl", transformer);
}
private void addDriverTransformer() {
- transformTemplate.transform("com.mysql.jdbc.NonRegisteringDriver", new TransformCallback() {
+ TransformCallback transformCallback = new TransformCallback() {
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
@@ -156,11 +173,14 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
return target.toBytecode();
}
- });
+ };
+ transformTemplate.transform("com.mysql.jdbc.NonRegisteringDriver", transformCallback);
+ // 6.x+
+ transformTemplate.transform("com.mysql.cj.jdbc.NonRegisteringDriver", transformCallback);
}
private void addPreparedStatementTransformer(final MySqlConfig config) {
- transformTemplate.transform("com.mysql.jdbc.PreparedStatement", new TransformCallback() {
+ TransformCallback transformCallback = new TransformCallback() {
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
@@ -190,11 +210,14 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
return target.toBytecode();
}
- });
+ };
+ transformTemplate.transform("com.mysql.jdbc.PreparedStatement", transformCallback);
+ // 6.x+
+ transformTemplate.transform("com.mysql.cj.jdbc.PreparedStatement", transformCallback);
}
private void addCallableStatementTransformer(final MySqlConfig config) {
- transformTemplate.transform("com.mysql.jdbc.CallableStatement", new TransformCallback() {
+ TransformCallback transformCallback = new TransformCallback() {
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
@@ -232,7 +255,10 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
return target.toBytecode();
}
- });
+ };
+ transformTemplate.transform("com.mysql.jdbc.CallableStatement", transformCallback);
+ // 6.x+
+ transformTemplate.transform("com.mysql.cj.jdbc.CallableStatement", transformCallback);
}
private void addJDBC4PreparedStatementTransformer(final MySqlConfig config) {
@@ -308,6 +334,8 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
transformTemplate.transform("com.mysql.jdbc.Statement", transformer);
transformTemplate.transform("com.mysql.jdbc.StatementImpl", transformer);
+ // 6.x+
+ transformTemplate.transform("com.mysql.cj.jdbc.StatementImpl", transformer);
}
diff --git a/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/MySQL_6_X_ConnectionCreateInterceptor.java b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/MySQL_6_X_ConnectionCreateInterceptor.java
new file mode 100644
index 000000000000..3ba860fcf68d
--- /dev/null
+++ b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/MySQL_6_X_ConnectionCreateInterceptor.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright 2017 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor;
+
+import com.navercorp.pinpoint.bootstrap.context.DatabaseInfo;
+import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
+import com.navercorp.pinpoint.bootstrap.context.Trace;
+import com.navercorp.pinpoint.bootstrap.context.TraceContext;
+import com.navercorp.pinpoint.bootstrap.interceptor.AroundInterceptor;
+import com.navercorp.pinpoint.bootstrap.logging.PLogger;
+import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
+import com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor;
+import com.navercorp.pinpoint.bootstrap.plugin.jdbc.DefaultDatabaseInfo;
+import com.navercorp.pinpoint.bootstrap.util.InterceptorUtils;
+import com.navercorp.pinpoint.plugin.jdbc.mysql.MySqlConstants;
+import com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.getter.DatabaseGetter;
+import com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.getter.OrigHostToConnectToGetter;
+import com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.getter.OrigPortToConnectToGetter;
+
+import java.util.Arrays;
+
+/**
+ * @author HyunGil Jeong
+ */
+// #1375 Workaround java level Deadlock
+// https://oss.navercorp.com/pinpoint/pinpoint-naver/issues/1375
+// @TargetConstructor({ "com.mysql.cj.core.ConnectionString", "java.lang.String", "int", "java.util.Properties" })
+public class MySQL_6_X_ConnectionCreateInterceptor implements AroundInterceptor {
+
+ private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
+ private final boolean isDebug = logger.isDebugEnabled();
+
+ private final TraceContext traceContext;
+
+ public MySQL_6_X_ConnectionCreateInterceptor(TraceContext traceContext) {
+ this.traceContext = traceContext;
+ }
+
+ @Override
+ public void after(Object target, Object[] args, Object result, Throwable throwable) {
+ if (isDebug) {
+ logger.afterInterceptor(target, args, result, throwable);
+ }
+
+ final String hostToConnectTo = getHostToConnectTo(target);
+ final Integer portToConnectTo = getPortToConnectTo(target);
+ final String databaseId = getDatabase(target);
+ // In case of loadbalance, connectUrl is modified.
+ // final String url = getString(args[4]);
+ DatabaseInfo databaseInfo = null;
+ if (hostToConnectTo != null && portToConnectTo != null && databaseId != null) {
+ // It's dangerous to use this url directly
+ databaseInfo = createDatabaseInfo(hostToConnectTo, portToConnectTo, databaseId);
+ if (InterceptorUtils.isSuccess(throwable)) {
+ // Set only if connection is success.
+ if (target instanceof DatabaseInfoAccessor) {
+ ((DatabaseInfoAccessor) target)._$PINPOINT$_setDatabaseInfo(databaseInfo);
+ }
+ }
+ }
+
+ final Trace trace = traceContext.currentTraceObject();
+ if (trace == null) {
+ return;
+ }
+
+ SpanEventRecorder recorder = trace.currentSpanEventRecorder();
+ // We must do this if current transaction is being recorded.
+ if (databaseInfo != null) {
+ recorder.recordServiceType(databaseInfo.getType());
+ recorder.recordEndPoint(databaseInfo.getMultipleHost());
+ recorder.recordDestinationId(databaseInfo.getDatabaseId());
+ }
+ }
+
+ private String getHostToConnectTo(Object target) {
+ if (target instanceof OrigHostToConnectToGetter) {
+ return ((OrigHostToConnectToGetter) target)._$PINPOINT$_getOrigHostToConnectTo();
+ }
+ return null;
+ }
+
+ private Integer getPortToConnectTo(Object target) {
+ if (target instanceof OrigPortToConnectToGetter) {
+ return ((OrigPortToConnectToGetter) target)._$PINPOINT$_getOrigPortToConnectTo();
+ }
+ return null;
+ }
+
+ private String getDatabase(Object target) {
+ if (target instanceof DatabaseGetter) {
+ return ((DatabaseGetter) target)._$PINPOINT$_getDatabase();
+ }
+ return null;
+ }
+
+ private DatabaseInfo createDatabaseInfo(String url, Integer port, String databaseId) {
+ if (url.indexOf(':') == -1) {
+ url += ":" + port;
+ }
+
+ DatabaseInfo databaseInfo = new DefaultDatabaseInfo(MySqlConstants.MYSQL, MySqlConstants.MYSQL_EXECUTE_QUERY, url, url, Arrays.asList(url), databaseId);
+ return databaseInfo;
+
+ }
+
+ private String getString(Object value) {
+ if (value instanceof String) {
+ return (String) value;
+ }
+ return null;
+ }
+
+ private Integer getInteger(Object value) {
+ if (value instanceof Integer) {
+ return (Integer) value;
+ }
+ return null;
+ }
+
+ @Override
+ public void before(Object target, Object[] args) {
+
+ }
+}
diff --git a/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/DatabaseGetter.java b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/DatabaseGetter.java
new file mode 100644
index 000000000000..436936376580
--- /dev/null
+++ b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/DatabaseGetter.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2017 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.getter;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface DatabaseGetter {
+ String _$PINPOINT$_getDatabase();
+}
diff --git a/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/OrigHostToConnectToGetter.java b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/OrigHostToConnectToGetter.java
new file mode 100644
index 000000000000..182dda8337a2
--- /dev/null
+++ b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/OrigHostToConnectToGetter.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2017 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.getter;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface OrigHostToConnectToGetter {
+ String _$PINPOINT$_getOrigHostToConnectTo();
+}
diff --git a/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/OrigPortToConnectToGetter.java b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/OrigPortToConnectToGetter.java
new file mode 100644
index 000000000000..dbb50c630caf
--- /dev/null
+++ b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/interceptor/getter/OrigPortToConnectToGetter.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2017 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.getter;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface OrigPortToConnectToGetter {
+ int _$PINPOINT$_getOrigPortToConnectTo();
+}
| null | train | val | "2017-07-07T10:28:20" | "2016-08-25T08:19:55Z" | Xylus | test |
pinpoint-apm/pinpoint/2817_3137 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2817 | pinpoint-apm/pinpoint/3137 | [
"keyword_pr_to_issue"
] | 19e54e4f678e5144875ab1c4c7f2ed19c5df0694 | fe9d4f0508b09e38d3de3267d120fc471bfe03b6 | [] | [] | "2017-07-10T10:33:06Z" | [
"enhancement",
"module:plugin"
] | Add support for Mariadb java client 1.6.x and 2.x | #### Description
Mariadb 1.6.x and 2.x are available and will need support as class names for callable and prepared statements are changed.
| [
"plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java"
] | [
"plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java"
] | [
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_to_1_6_0_IT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_6_x_to_2_0_0_IT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_2_x_IT.java"
] | diff --git a/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java b/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java
index fb19c2427606..7abd9072f949 100644
--- a/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java
+++ b/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBPlugin.java
@@ -195,6 +195,9 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
transformTemplate.transform("org.mariadb.jdbc.MariaDbServerPreparedStatement", transformer);
transformTemplate.transform("org.mariadb.jdbc.MariaDbClientPreparedStatement", transformer);
+ // 1.6.x
+ transformTemplate.transform("org.mariadb.jdbc.MariaDbPreparedStatementServer", transformer);
+ transformTemplate.transform("org.mariadb.jdbc.MariaDbPreparedStatementClient", transformer);
}
@@ -229,7 +232,8 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
transformTemplate.transform("org.mariadb.jdbc.AbstractMariaDbPrepareStatement", transformer);
// Class renamed in 1.5.6 - https://github.com/MariaDB/mariadb-connector-j/commit/16c8313960cf4fbc6b2b83136504d1ba9e662919
transformTemplate.transform("org.mariadb.jdbc.AbstractPrepareStatement", transformer);
-
+ // 1.6.x
+ transformTemplate.transform("org.mariadb.jdbc.BasePrepareStatement", transformer);
}
private void addStatementTransformer() {
@@ -295,6 +299,9 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
transformTemplate.transform("org.mariadb.jdbc.AbstractCallableProcedureStatement", transformer);
transformTemplate.transform("org.mariadb.jdbc.AbstractCallableFunctionStatement", transformer);
+ // 1.6.x
+ transformTemplate.transform("org.mariadb.jdbc.CallableProcedureStatement", transformer);
+ transformTemplate.transform("org.mariadb.jdbc.CallableFunctionStatement", transformer);
}
private void add_1_3_x_CallableStatementTransformer(final MariaDBConfig config) {
| diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java
index c1a855fc2491..a95a6bf301ea 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_3_x_IT.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright 2016 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package com.navercorp.pinpoint.plugin.jdbc.mariadb;
import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.*;
@@ -14,6 +30,9 @@
import com.navercorp.pinpoint.test.plugin.JvmVersion;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+/**
+ * @author HyunGil Jeong
+ */
@RunWith(PinpointPluginTestSuite.class)
@JvmVersion(7)
@Dependency({"org.mariadb.jdbc:mariadb-java-client:[1.3.0,1.3.max]", "ch.vorburger.mariaDB4j:mariaDB4j:2.2.2"})
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_to_1_6_0_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_to_1_6_0_IT.java
index 5e241d3d0b1d..3c8fcfea2270 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_to_1_6_0_IT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_4_x_to_1_6_0_IT.java
@@ -32,7 +32,6 @@
/**
* @author HyunGil Jeong
*/
-
@RunWith(PinpointPluginTestSuite.class)
@JvmVersion(7)
@Dependency({ "org.mariadb.jdbc:mariadb-java-client:[1.4.min,1.6.min)", "ch.vorburger.mariaDB4j:mariaDB4j:2.2.2" })
@@ -47,6 +46,7 @@ public void testStatement() throws Exception {
PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
verifier.printCache();
+ verifier.verifyTraceCount(2);
// Driver#connect(String, Properties)
Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_6_x_to_2_0_0_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_6_x_to_2_0_0_IT.java
new file mode 100644
index 000000000000..47394fb9af38
--- /dev/null
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_1_6_x_to_2_0_0_IT.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright 2017 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.jdbc.mariadb;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.JvmVersion;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.lang.reflect.Method;
+import java.util.Properties;
+
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.args;
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.cachedArgs;
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.event;
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.sql;
+
+/**
+ * <p>Notable class changes :<br/>
+ * <ul>
+ * <li><tt>org.mariadb.jdbc.AbstractPrepareStatement</tt> -> <tt>org.mariadb.jdbc.BasePrepareStatement</tt></li>
+ * <li><tt>org.mariadb.jdbc.MariaDbServerPreparedStatement</tt> -> <tt>org.mariadb.jdbc.MariaDbPreparedStatementServer</tt></li>
+ * <li><tt>org.mariadb.jdbc.MariaDbClientPreparedStatement</tt> -> <tt>org.mariadb.jdbc.MariaDbPreparedStatementClient</tt></li>
+ * <li><tt>org.mariadb.jdbc.AbstractCallableProcedureStatement</tt> -> <tt>org.mariadb.jdbc.CallableProcedureStatement</tt></li>
+ * <li><tt>org.mariadb.jdbc.AbstractCallableFunctionStatement</tt> -> <tt>org.mariadb.jdbc.CallableFunctionStatement</tt></li>
+ * </ul>
+ * </p>
+ * <p>useServerPrepStmts defaults to false (was true before 1.6.0)
+ * </p>
+ *
+ * @author HyunGil Jeong
+ */
+@RunWith(PinpointPluginTestSuite.class)
+@JvmVersion(7) // 1.6.2+ works with Java 6, but since the IT includes 1.6.0 and 1.6.1 just run on Java 7
+@Dependency({ "org.mariadb.jdbc:mariadb-java-client:[1.6.0,2.0.min)", "ch.vorburger.mariaDB4j:mariaDB4j:2.2.2" })
+public class MariaDB_1_6_x_to_2_0_0_IT extends MariaDB_IT_Base {
+
+ // see CallableParameterMetaData#queryMetaInfos
+ private static final String CALLABLE_QUERY_META_INFOS_QUERY = "select param_list, returns, db, type from mysql.proc where name=? and db=DATABASE()";
+
+ @Test
+ public void testStatement() throws Exception {
+ super.executeStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbStatement#executeQuery(String)
+ Class<?> mariaDbStatementClass = Class.forName("org.mariadb.jdbc.MariaDbStatement");
+ Method executeQuery = mariaDbStatementClass.getDeclaredMethod("executeQuery", String.class);
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQuery, null, URL, DATABASE_NAME, sql(STATEMENT_NORMALIZED_QUERY, "1")));
+ }
+
+ @Test
+ public void testPreparedStatement() throws Exception {
+ super.executePreparedStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+ verifier.verifyTraceCount(3);
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbConnection#prepareStatement(String)
+ Class<?> mariaDbConnectionClass = Class.forName("org.mariadb.jdbc.MariaDbConnection");
+ Method prepareStatement = mariaDbConnectionClass.getDeclaredMethod("prepareStatement", String.class);
+ verifier.verifyTrace(event("MARIADB", prepareStatement, null, URL, DATABASE_NAME, sql(PREPARED_STATEMENT_QUERY, null)));
+
+ // MariaDbPreparedStatementClient#executeQuery
+ Class<?> mariaDbServerPreparedStatementClass = Class.forName("org.mariadb.jdbc.MariaDbPreparedStatementClient");
+ Method executeQuery = mariaDbServerPreparedStatementClass.getDeclaredMethod("executeQuery");
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQuery, null, URL, DATABASE_NAME, sql(PREPARED_STATEMENT_QUERY, null, "3")));
+ }
+
+ @Test
+ public void testCallableStatement() throws Exception {
+ super.executeCallableStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+ verifier.verifyTraceCount(6);
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbConnection#prepareCall(String)
+ Class<?> mariaDbConnectionClass = Class.forName("org.mariadb.jdbc.MariaDbConnection");
+ Method prepareCall = mariaDbConnectionClass.getDeclaredMethod("prepareCall", String.class);
+ verifier.verifyTrace(event("MARIADB", prepareCall, null, URL, DATABASE_NAME, sql(CALLABLE_STATEMENT_QUERY, null)));
+
+ // CallableProcedureStatement#registerOutParameter
+ Class<?> abstractCallableProcedureStatementClass = Class.forName("org.mariadb.jdbc.CallableProcedureStatement");
+ Method registerOutParameter = abstractCallableProcedureStatementClass.getMethod("registerOutParameter", int.class, int.class);
+ verifier.verifyTrace(event("MARIADB", registerOutParameter, null, URL, DATABASE_NAME, args(2, CALLABLE_STATMENT_OUTPUT_PARAM_TYPE)));
+
+ // MariaDbPreparedStatementServer#executeQuery
+ Class<?> mariaDbPreparedStatementServerClass = Class.forName("org.mariadb.jdbc.MariaDbPreparedStatementServer");
+ Method executeQueryServer = mariaDbPreparedStatementServerClass.getDeclaredMethod("executeQuery");
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQueryServer, null, URL, DATABASE_NAME, sql(CALLABLE_STATEMENT_QUERY, null, CALLABLE_STATEMENT_INPUT_PARAM)));
+
+ // MariaDbConnection#prepareStatement(String)
+ Method prepareStatement = mariaDbConnectionClass.getDeclaredMethod("prepareStatement", String.class);
+ verifier.verifyTrace(event("MARIADB", prepareStatement, null, URL, DATABASE_NAME, sql(CALLABLE_QUERY_META_INFOS_QUERY, null)));
+
+ // MariaDbPreparedStatementClient#executeQuery
+ Class<?> mariaDbPreparedStatementClientClass = Class.forName("org.mariadb.jdbc.MariaDbPreparedStatementClient");
+ Method executeQueryClient = mariaDbPreparedStatementClientClass.getDeclaredMethod("executeQuery");
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQueryClient, null, URL, DATABASE_NAME, sql(CALLABLE_QUERY_META_INFOS_QUERY, null, PROCEDURE_NAME)));
+ }
+}
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_2_x_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_2_x_IT.java
new file mode 100644
index 000000000000..679a8440e552
--- /dev/null
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDB_2_x_IT.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright 2017 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.jdbc.mariadb;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.JvmVersion;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.lang.reflect.Method;
+import java.util.Properties;
+
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.args;
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.cachedArgs;
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.event;
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.sql;
+
+/**
+ * @author HyunGil Jeong
+ */
+@RunWith(PinpointPluginTestSuite.class)
+@JvmVersion(8) // 2.x+ requires Java 8
+@Dependency({ "org.mariadb.jdbc:mariadb-java-client:[2.0.1,)", "ch.vorburger.mariaDB4j:mariaDB4j:2.2.2" })
+public class MariaDB_2_x_IT extends MariaDB_IT_Base {
+
+ // see CallableParameterMetaData#queryMetaInfos
+ private static final String CALLABLE_QUERY_META_INFOS_QUERY = "select param_list, returns, db, type from mysql.proc where name=? and db=DATABASE()";
+
+ @Test
+ public void testStatement() throws Exception {
+ super.executeStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbStatement#executeQuery(String)
+ Class<?> mariaDbStatementClass = Class.forName("org.mariadb.jdbc.MariaDbStatement");
+ Method executeQuery = mariaDbStatementClass.getDeclaredMethod("executeQuery", String.class);
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQuery, null, URL, DATABASE_NAME, sql(STATEMENT_NORMALIZED_QUERY, "1")));
+ }
+
+ @Test
+ public void testPreparedStatement() throws Exception {
+ super.executePreparedStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+ verifier.verifyTraceCount(3);
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbConnection#prepareStatement(String)
+ Class<?> mariaDbConnectionClass = Class.forName("org.mariadb.jdbc.MariaDbConnection");
+ Method prepareStatement = mariaDbConnectionClass.getDeclaredMethod("prepareStatement", String.class);
+ verifier.verifyTrace(event("MARIADB", prepareStatement, null, URL, DATABASE_NAME, sql(PREPARED_STATEMENT_QUERY, null)));
+
+ // MariaDbPreparedStatementClient#executeQuery
+ Class<?> mariaDbServerPreparedStatementClass = Class.forName("org.mariadb.jdbc.MariaDbPreparedStatementClient");
+ Method executeQuery = mariaDbServerPreparedStatementClass.getDeclaredMethod("executeQuery");
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQuery, null, URL, DATABASE_NAME, sql(PREPARED_STATEMENT_QUERY, null, "3")));
+ }
+
+ @Test
+ public void testCallableStatement() throws Exception {
+ super.executeCallableStatement();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+ verifier.verifyTraceCount(6);
+
+ // Driver#connect(String, Properties)
+ Class<?> driverClass = Class.forName("org.mariadb.jdbc.Driver");
+ Method connect = driverClass.getDeclaredMethod("connect", String.class, Properties.class);
+ verifier.verifyTrace(event("MARIADB", connect, null, URL, DATABASE_NAME, cachedArgs(JDBC_URL)));
+
+ // MariaDbConnection#prepareCall(String)
+ Class<?> mariaDbConnectionClass = Class.forName("org.mariadb.jdbc.MariaDbConnection");
+ Method prepareCall = mariaDbConnectionClass.getDeclaredMethod("prepareCall", String.class);
+ verifier.verifyTrace(event("MARIADB", prepareCall, null, URL, DATABASE_NAME, sql(CALLABLE_STATEMENT_QUERY, null)));
+
+ // CallableProcedureStatement#registerOutParameter
+ Class<?> abstractCallableProcedureStatementClass = Class.forName("org.mariadb.jdbc.CallableProcedureStatement");
+ Method registerOutParameter = abstractCallableProcedureStatementClass.getMethod("registerOutParameter", int.class, int.class);
+ verifier.verifyTrace(event("MARIADB", registerOutParameter, null, URL, DATABASE_NAME, args(2, CALLABLE_STATMENT_OUTPUT_PARAM_TYPE)));
+
+ // MariaDbPreparedStatementServer#executeQuery
+ Class<?> mariaDbPreparedStatementServerClass = Class.forName("org.mariadb.jdbc.MariaDbPreparedStatementServer");
+ Method executeQueryServer = mariaDbPreparedStatementServerClass.getDeclaredMethod("executeQuery");
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQueryServer, null, URL, DATABASE_NAME, sql(CALLABLE_STATEMENT_QUERY, null, CALLABLE_STATEMENT_INPUT_PARAM)));
+
+ // MariaDbConnection#prepareStatement(String)
+ Method prepareStatement = mariaDbConnectionClass.getDeclaredMethod("prepareStatement", String.class);
+ verifier.verifyTrace(event("MARIADB", prepareStatement, null, URL, DATABASE_NAME, sql(CALLABLE_QUERY_META_INFOS_QUERY, null)));
+
+ // MariaDbPreparedStatementClient#executeQuery
+ Class<?> mariaDbPreparedStatementClientClass = Class.forName("org.mariadb.jdbc.MariaDbPreparedStatementClient");
+ Method executeQueryClient = mariaDbPreparedStatementClientClass.getDeclaredMethod("executeQuery");
+ verifier.verifyTrace(event("MARIADB_EXECUTE_QUERY", executeQueryClient, null, URL, DATABASE_NAME, sql(CALLABLE_QUERY_META_INFOS_QUERY, null, PROCEDURE_NAME)));
+ }
+}
| train | val | "2017-07-10T11:21:08" | "2017-04-17T02:54:48Z" | Xylus | test |
pinpoint-apm/pinpoint/2239_3159 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/2239 | pinpoint-apm/pinpoint/3159 | [
"keyword_pr_to_issue"
] | 80d08660afbbe6e965093bea675c1ecfb1394988 | 49791987769f8a735c82fd5c400f19ec312fda55 | [] | [] | "2017-07-13T10:01:46Z" | [
"enhancement",
"module:plugin"
] | Add trace support for Postgresql jdbc driver 9.4.1207+ | Looks like there was a major overhaul in postgresql jdbc driver code in 9.4.1207.
Postgresql plugin needs to support this change.
If anyone's willing to work on this this, please feel free to leave a message here.
related issue - #2157 | [
"plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/PostgreSqlPlugin.java",
"plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor1.java",
"plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor2.java",
"plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor3.java",
"pom.xml"
] | [
"plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/PostgreSqlPlugin.java",
"pom.xml"
] | [] | diff --git a/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/PostgreSqlPlugin.java b/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/PostgreSqlPlugin.java
index cfcfaec1a444..6c7f732b2738 100644
--- a/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/PostgreSqlPlugin.java
+++ b/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/PostgreSqlPlugin.java
@@ -37,7 +37,7 @@
/**
* @author Brad Hong
- *
+ * @author HyunGil Jeong
*/
public class PostgreSqlPlugin implements ProfilerPlugin, TransformTemplateAware {
@@ -60,35 +60,34 @@ public void setup(ProfilerPluginSetupContext context) {
context.addJdbcUrlParser(jdbcUrlParser);
- addConnectionTransformer(config);
addDriverTransformer();
- addPreparedStatementTransformer(config);
+ addConnectionTransformers(config);
+ addStatementTransformers(config);
+ addPreparedStatementTransformers(config);
+
+ // pre 9.4.1207
+ addLegacyConnectionTransformers(config);
+ addLegacyStatementTransformers(config);
}
- private void addConnectionTransformer(final PostgreSqlConfig config) {
- transformTemplate.transform("org.postgresql.jdbc4.Jdbc4Connection", new TransformCallback() {
+ private void addDriverTransformer() {
+ transformTemplate.transform("org.postgresql.Driver", new TransformCallback() {
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
- if (!target.isInterceptable()) {
- return null;
- }
-
- target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
-
- InstrumentUtils.findConstructor(target, "org.postgresql.util.HostSpec[]", "java.lang.String", "java.lang.String", "java.util.Properties", "java.lang.String")
- .addInterceptor("com.navercorp.pinpoint.plugin.jdbc.postgresql.interceptor.PostgreSQLConnectionCreateInterceptor");
-
- InstrumentUtils.findMethod(target,"prepareStatement", "java.lang.String", "int", "int", "int")
- .addScopedInterceptor("com.navercorp.pinpoint.plugin.jdbc.postgresql.interceptor.PostgreSqlPreparedStatementCreateInterceptor3", POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "connect", "java.lang.String", "java.util.Properties")
+ .addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.DriverConnectInterceptorV2",
+ va(PostgreSqlConstants.POSTGRESQL, false), POSTGRESQL_SCOPE, ExecutionPolicy.ALWAYS);
return target.toBytecode();
}
});
- transformTemplate.transform("org.postgresql.jdbc3.Jdbc3Connection", new TransformCallback() {
+ }
+ private void addConnectionTransformers(final PostgreSqlConfig config) {
+ transformTemplate.transform("org.postgresql.jdbc.PgConnection", new TransformCallback() {
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
@@ -97,8 +96,15 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
return null;
}
+ InstrumentUtils.findConstructor(target, "org.postgresql.util.HostSpec[]", "java.lang.String", "java.lang.String", "java.util.Properties", "java.lang.String")
+ .addInterceptor("com.navercorp.pinpoint.plugin.jdbc.postgresql.interceptor.PostgreSQLConnectionCreateInterceptor");
+
target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
+ // close
+ InstrumentUtils.findMethod(target, "close")
+ .addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.ConnectionCloseInterceptor", POSTGRESQL_SCOPE);
+
// createStatement
final String statementCreate = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.StatementCreateInterceptor";
InstrumentUtils.findMethod(target, "createStatement")
@@ -108,9 +114,134 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
InstrumentUtils.findMethod(target, "createStatement", "int", "int", "int")
.addScopedInterceptor(statementCreate, POSTGRESQL_SCOPE);
+ // prepareStatement
+ final String preparedStatementCreate = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.PreparedStatementCreateInterceptor";
+ InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String")
+ .addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "int")
+ .addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "int[]")
+ .addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "int", "int")
+ .addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "int", "int", "int")
+ .addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "java.lang.String[]")
+ .addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
+
+ if (config.isProfileSetAutoCommit()) {
+ InstrumentUtils.findMethod(target, "setAutoCommit", "boolean")
+ .addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.TransactionSetAutoCommitInterceptor", POSTGRESQL_SCOPE);
+ }
+
+ if (config.isProfileCommit()) {
+ InstrumentUtils.findMethod(target, "commit")
+ .addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.TransactionCommitInterceptor", POSTGRESQL_SCOPE);
+ }
+
+ if (config.isProfileRollback()) {
+ InstrumentUtils.findMethod(target, "rollback")
+ .addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.TransactionRollbackInterceptor", POSTGRESQL_SCOPE);
+ }
+
return target.toBytecode();
}
});
+ }
+
+ private void addStatementTransformers(final PostgreSqlConfig config) {
+ TransformCallback transformer = new TransformCallback() {
+
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+
+ if (!target.isInterceptable()) {
+ return null;
+ }
+
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
+
+ final String executeQueryInterceptor = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.StatementExecuteQueryInterceptor";
+ InstrumentUtils.findMethod(target, "executeQuery", "java.lang.String")
+ .addScopedInterceptor(executeQueryInterceptor, POSTGRESQL_SCOPE);
+
+ final String executeUpdateInterceptor = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.StatementExecuteUpdateInterceptor";
+ InstrumentUtils.findMethod(target, "executeUpdate", "java.lang.String")
+ .addScopedInterceptor(executeUpdateInterceptor, POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "executeUpdate", "java.lang.String", "int")
+ .addScopedInterceptor(executeUpdateInterceptor, POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "execute", "java.lang.String")
+ .addScopedInterceptor(executeUpdateInterceptor, POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "execute", "java.lang.String", "int")
+ .addScopedInterceptor(executeUpdateInterceptor, POSTGRESQL_SCOPE);
+
+ // 9.4.1207 has setX methods in PgStatement
+ final PreparedStatementBindingMethodFilter excludes = PreparedStatementBindingMethodFilter.excludes("setRowId", "setNClob", "setSQLXML");
+ final List<InstrumentMethod> declaredMethods = target.getDeclaredMethods(excludes);
+ if (!declaredMethods.isEmpty()) {
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.BindValueAccessor");
+
+ int maxBindValueSize = config.getMaxSqlBindValueSize();
+
+ final String preparedStatementInterceptor = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.PreparedStatementExecuteQueryInterceptor";
+ InstrumentUtils.findMethod(target, "execute")
+ .addScopedInterceptor(preparedStatementInterceptor, va(maxBindValueSize), POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "executeQuery")
+ .addScopedInterceptor(preparedStatementInterceptor, va(maxBindValueSize), POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "executeUpdate")
+ .addScopedInterceptor(preparedStatementInterceptor, va(maxBindValueSize), POSTGRESQL_SCOPE);
+
+ for (InstrumentMethod method : declaredMethods) {
+ method.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.PreparedStatementBindVariableInterceptor", POSTGRESQL_SCOPE, ExecutionPolicy.BOUNDARY);
+ }
+ }
+
+ return target.toBytecode();
+ }
+ };
+ transformTemplate.transform("org.postgresql.jdbc.PgStatement", transformer);
+ }
+
+ private void addPreparedStatementTransformers(final PostgreSqlConfig config) {
+ TransformCallback transformCallback = new TransformCallback() {
+
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
+
+ // 9.4.1207 has setX methods in PgStatement
+ final PreparedStatementBindingMethodFilter excludes = PreparedStatementBindingMethodFilter.excludes("setRowId", "setNClob", "setSQLXML");
+ final List<InstrumentMethod> declaredMethods = target.getDeclaredMethods(excludes);
+ if (!declaredMethods.isEmpty()) {
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor");
+ target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.BindValueAccessor");
+
+ int maxBindValueSize = config.getMaxSqlBindValueSize();
+
+ final String preparedStatementInterceptor = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.PreparedStatementExecuteQueryInterceptor";
+ InstrumentUtils.findMethod(target, "execute")
+ .addScopedInterceptor(preparedStatementInterceptor, va(maxBindValueSize), POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "executeQuery")
+ .addScopedInterceptor(preparedStatementInterceptor, va(maxBindValueSize), POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "executeUpdate")
+ .addScopedInterceptor(preparedStatementInterceptor, va(maxBindValueSize), POSTGRESQL_SCOPE);
+
+ for (InstrumentMethod method : declaredMethods) {
+ method.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.PreparedStatementBindVariableInterceptor", POSTGRESQL_SCOPE, ExecutionPolicy.BOUNDARY);
+ }
+ }
+
+ return target.toBytecode();
+ }
+ };
+ transformTemplate.transform("org.postgresql.jdbc.PgPreparedStatement", transformCallback);
+ }
+
+ private void addLegacyConnectionTransformers(final PostgreSqlConfig config) {
transformTemplate.transform("org.postgresql.jdbc2.AbstractJdbc2Connection", new TransformCallback() {
@Override
@@ -127,11 +258,18 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
InstrumentUtils.findMethod(target, "close")
.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.ConnectionCloseInterceptor", POSTGRESQL_SCOPE);
+ // createStatement
+ final String statementCreate = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.StatementCreateInterceptor";
+ InstrumentUtils.findMethod(target, "createStatement")
+ .addScopedInterceptor(statementCreate, POSTGRESQL_SCOPE);
+
+ // prepareStatement
+ final String preparedStatementCreate = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.PreparedStatementCreateInterceptor";
InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String")
- .addScopedInterceptor("com.navercorp.pinpoint.plugin.jdbc.postgresql.interceptor.PostgreSqlPreparedStatementCreateInterceptor1", POSTGRESQL_SCOPE);
+ .addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
if (config.isProfileSetAutoCommit()) {
- InstrumentUtils.findMethod(target, "setAutoCommit", "boolean")
+ InstrumentUtils.findMethod(target, "setAutoCommit", "boolean")
.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.TransactionSetAutoCommitInterceptor", POSTGRESQL_SCOPE);
}
@@ -159,41 +297,59 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
return null;
}
- target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
+ // createStatement
+ final String statementCreate = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.StatementCreateInterceptor";
+ InstrumentUtils.findMethod(target, "createStatement", "int", "int")
+ .addScopedInterceptor(statementCreate, POSTGRESQL_SCOPE);
- // preparedStatement
- final String preparedStatementCreate = "com.navercorp.pinpoint.plugin.jdbc.postgresql.interceptor.PostgreSqlPreparedStatementCreateInterceptor2";
- InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "int")
+ // prepareStatement
+ final String preparedStatementCreate = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.PreparedStatementCreateInterceptor";
+ InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "int")
.addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
- InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "int[]")
+ InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "int[]")
.addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
- InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "java.lang.String[]")
+ InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "int", "int")
.addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
- InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "int", "int")
+ InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "java.lang.String[]")
.addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
return target.toBytecode();
}
});
- }
- private void addDriverTransformer() {
- transformTemplate.transform("org.postgresql.Driver", new TransformCallback() {
+ TransformCallback concreteConnectionTransformCallback = new TransformCallback() {
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
- InstrumentUtils.findMethod(target, "connect", "java.lang.String", "java.util.Properties")
- .addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.DriverConnectInterceptorV2",
- va(PostgreSqlConstants.POSTGRESQL, false), POSTGRESQL_SCOPE, ExecutionPolicy.ALWAYS);
+ if (!target.isInterceptable()) {
+ return null;
+ }
+
+ InstrumentUtils.findConstructor(target, "org.postgresql.util.HostSpec[]", "java.lang.String", "java.lang.String", "java.util.Properties", "java.lang.String")
+ .addInterceptor("com.navercorp.pinpoint.plugin.jdbc.postgresql.interceptor.PostgreSQLConnectionCreateInterceptor");
+
+ // createStatement
+ final String statementCreate = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.StatementCreateInterceptor";
+ InstrumentUtils.findMethod(target, "createStatement", "int", "int", "int")
+ .addScopedInterceptor(statementCreate, POSTGRESQL_SCOPE);
+
+ // prepareStatement
+ final String preparedStatementCreate = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.PreparedStatementCreateInterceptor";
+ InstrumentUtils.findMethod(target, "prepareStatement", "java.lang.String", "int", "int", "int")
+ .addScopedInterceptor(preparedStatementCreate, POSTGRESQL_SCOPE);
return target.toBytecode();
}
- });
+ };
+ transformTemplate.transform("org.postgresql.jdbc3.Jdbc3Connection", concreteConnectionTransformCallback);
+ transformTemplate.transform("org.postgresql.jdbc3g.Jdbc3gConnection", concreteConnectionTransformCallback);
+ transformTemplate.transform("org.postgresql.jdbc4.Jdbc4Connection", concreteConnectionTransformCallback);
+ transformTemplate.transform("org.postgresql.jdbc42.Jdbc42Connection", concreteConnectionTransformCallback);
}
- private void addPreparedStatementTransformer(final PostgreSqlConfig config) {
+ private void addLegacyStatementTransformers(final PostgreSqlConfig config) {
transformTemplate.transform("org.postgresql.jdbc2.AbstractJdbc2Statement", new TransformCallback() {
@Override
@@ -214,18 +370,15 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
InstrumentUtils.findMethod(target, "executeUpdate")
.addScopedInterceptor(preparedStatementInterceptor, va(maxBindValueSize), POSTGRESQL_SCOPE);
- return target.toBytecode();
- }
- });
- transformTemplate.transform("org.postgresql.jdbc3.AbstractJdbc3Statement", new TransformCallback() {
-
- @Override
- public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
- InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+ final String executeQueryInterceptor = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.StatementExecuteQueryInterceptor";
+ InstrumentUtils.findMethod(target, "executeQuery", "java.lang.String")
+ .addScopedInterceptor(executeQueryInterceptor, POSTGRESQL_SCOPE);
- target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor");
- target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor");
- target.addField("com.navercorp.pinpoint.bootstrap.plugin.jdbc.BindValueAccessor");
+ final String executeUpdateInterceptor = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.StatementExecuteUpdateInterceptor";
+ InstrumentUtils.findMethod(target, "executeUpdate", "java.lang.String")
+ .addScopedInterceptor(executeUpdateInterceptor, POSTGRESQL_SCOPE);
+ InstrumentUtils.findMethod(target, "execute", "java.lang.String")
+ .addScopedInterceptor(executeUpdateInterceptor, POSTGRESQL_SCOPE);
final PreparedStatementBindingMethodFilter excludes = PreparedStatementBindingMethodFilter.excludes("setRowId", "setNClob", "setSQLXML");
final List<InstrumentMethod> declaredMethods = target.getDeclaredMethods(excludes);
@@ -233,18 +386,19 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
method.addScopedInterceptor("com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.PreparedStatementBindVariableInterceptor", POSTGRESQL_SCOPE, ExecutionPolicy.BOUNDARY);
}
- final String executeQueryInterceptor = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.StatementExecuteQueryInterceptor";
- InstrumentUtils.findMethod(target, "executeQuery", "java.lang.String")
- .addScopedInterceptor(executeQueryInterceptor, POSTGRESQL_SCOPE);
+ return target.toBytecode();
+ }
+ });
+ transformTemplate.transform("org.postgresql.jdbc3.AbstractJdbc3Statement", new TransformCallback() {
+
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
final String executeUpdateInterceptor = "com.navercorp.pinpoint.bootstrap.plugin.jdbc.interceptor.StatementExecuteUpdateInterceptor";
- InstrumentUtils.findMethod(target, "executeUpdate", "java.lang.String")
- .addScopedInterceptor(executeUpdateInterceptor, POSTGRESQL_SCOPE);
- InstrumentUtils.findMethod(target, "executeUpdate", "java.lang.String", "int")
- .addScopedInterceptor(executeUpdateInterceptor, POSTGRESQL_SCOPE);
- InstrumentUtils.findMethod(target, "execute", "java.lang.String")
+ InstrumentUtils.findMethod(target, "executeUpdate", "java.lang.String", "int")
.addScopedInterceptor(executeUpdateInterceptor, POSTGRESQL_SCOPE);
- InstrumentUtils.findMethod(target, "execute", "java.lang.String", "int")
+ InstrumentUtils.findMethod(target, "execute", "java.lang.String", "int")
.addScopedInterceptor(executeUpdateInterceptor, POSTGRESQL_SCOPE);
return target.toBytecode();
diff --git a/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor1.java b/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor1.java
deleted file mode 100644
index a62aa46c1b88..000000000000
--- a/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor1.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright 2014 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.plugin.jdbc.postgresql.interceptor;
-
-import com.navercorp.pinpoint.bootstrap.context.*;
-import com.navercorp.pinpoint.bootstrap.interceptor.SpanEventSimpleAroundInterceptorForPlugin;
-import com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor;
-import com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor;
-import com.navercorp.pinpoint.bootstrap.plugin.jdbc.UnKnownDatabaseInfo;
-import com.navercorp.pinpoint.bootstrap.util.InterceptorUtils;
-
-/**
- * @author Brad Hong
- */
-// #1375 Workaround java level Deadlock
-// https://oss.navercorp.com/pinpoint/pinpoint-naver/issues/1375
-//@TargetMethods({
-// @TargetMethod(name="prepareStatement", paramTypes={ "java.lang.String" })
-//})
-public class PostgreSqlPreparedStatementCreateInterceptor1 extends SpanEventSimpleAroundInterceptorForPlugin {
-
- public PostgreSqlPreparedStatementCreateInterceptor1(TraceContext context, MethodDescriptor descriptor) {
- super(context, descriptor);
- }
-
- @Override
- public void doInBeforeTrace(SpanEventRecorder recorder, Object target, Object[] args) {
- DatabaseInfo databaseInfo = null;
- if (target instanceof DatabaseInfoAccessor) {
- databaseInfo = ((DatabaseInfoAccessor)target)._$PINPOINT$_getDatabaseInfo();
- }
-
- if (databaseInfo == null) {
- databaseInfo = UnKnownDatabaseInfo.INSTANCE;
- }
-
- recorder.recordServiceType(databaseInfo.getType());
- recorder.recordEndPoint(databaseInfo.getMultipleHost());
- recorder.recordDestinationId(databaseInfo.getDatabaseId());
- }
-
- @Override
- protected void prepareAfterTrace(Object target, Object[] args, Object result, Throwable throwable) {
- final boolean success = InterceptorUtils.isSuccess(throwable);
- if (success) {
- if (target instanceof DatabaseInfoAccessor) {
- // set databaseInfo to PreparedStatement only when preparedStatement is generated successfully.
- final DatabaseInfo databaseInfo = ((DatabaseInfoAccessor)target)._$PINPOINT$_getDatabaseInfo();
- if (databaseInfo != null) {
- if (result instanceof DatabaseInfoAccessor) {
- ((DatabaseInfoAccessor)result)._$PINPOINT$_setDatabaseInfo(databaseInfo);
- }
- }
- }
- if (result instanceof ParsingResultAccessor) {
- // 1. Don't check traceContext. preparedStatement can be created in other thread.
- // 2. While sampling is active, the thread which creates preparedStatement could not be a sampling target. So record sql anyway.
- String sql = (String) args[0];
- final ParsingResult parsingResult = traceContext.parseSql(sql);
- if (parsingResult != null) {
- ((ParsingResultAccessor)result)._$PINPOINT$_setParsingResult(parsingResult);
- } else {
- if (logger.isErrorEnabled()) {
- logger.error("sqlParsing fail. parsingResult is null sql:{}", sql);
- }
- }
- }
- }
- }
-
- @Override
- public void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
- if (result instanceof ParsingResultAccessor) {
- ParsingResult parsingResult = ((ParsingResultAccessor)result)._$PINPOINT$_getParsingResult();
- recorder.recordSqlParsingResult(parsingResult);
- }
- recorder.recordException(throwable);
- recorder.recordApi(methodDescriptor);
- }
-}
diff --git a/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor2.java b/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor2.java
deleted file mode 100644
index 6a5c18c0faa5..000000000000
--- a/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor2.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright 2014 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.plugin.jdbc.postgresql.interceptor;
-
-import com.navercorp.pinpoint.bootstrap.context.*;
-import com.navercorp.pinpoint.bootstrap.interceptor.SpanEventSimpleAroundInterceptorForPlugin;
-import com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor;
-import com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor;
-import com.navercorp.pinpoint.bootstrap.plugin.jdbc.UnKnownDatabaseInfo;
-import com.navercorp.pinpoint.bootstrap.util.InterceptorUtils;
-
-/**
- * @author Brad Hong
- */
-// #1375 Workaround java level Deadlock
-// https://oss.navercorp.com/pinpoint/pinpoint-naver/issues/1375
-//@TargetMethods({
-// @TargetMethod(name="prepareStatement", paramTypes={ "java.lang.String", "int" }),
-// @TargetMethod(name="prepareStatement", paramTypes={ "java.lang.String", "int[]" }),
-// @TargetMethod(name="prepareStatement", paramTypes={ "java.lang.String", "java.lang.String[]" }),
-// @TargetMethod(name="prepareStatement", paramTypes={ "java.lang.String", "int", "int" })
-//})
-public class PostgreSqlPreparedStatementCreateInterceptor2 extends SpanEventSimpleAroundInterceptorForPlugin {
-
- public PostgreSqlPreparedStatementCreateInterceptor2(TraceContext context, MethodDescriptor descriptor) {
- super(context, descriptor);
- }
-
- @Override
- public void doInBeforeTrace(SpanEventRecorder recorder, Object target, Object[] args) {
- DatabaseInfo databaseInfo = null;
- if (target instanceof DatabaseInfoAccessor) {
- databaseInfo = ((DatabaseInfoAccessor)target)._$PINPOINT$_getDatabaseInfo();
- }
-
- if (databaseInfo == null) {
- databaseInfo = UnKnownDatabaseInfo.INSTANCE;
- }
-
- recorder.recordServiceType(databaseInfo.getType());
- recorder.recordEndPoint(databaseInfo.getMultipleHost());
- recorder.recordDestinationId(databaseInfo.getDatabaseId());
- }
-
- @Override
- protected void prepareAfterTrace(Object target, Object[] args, Object result, Throwable throwable) {
- final boolean success = InterceptorUtils.isSuccess(throwable);
- if (success) {
- if (target instanceof DatabaseInfoAccessor) {
- // set databaseInfo to PreparedStatement only when preparedStatement is generated successfully.
- DatabaseInfo databaseInfo = ((DatabaseInfoAccessor)target)._$PINPOINT$_getDatabaseInfo();
- if (databaseInfo != null) {
- if (result instanceof DatabaseInfoAccessor) {
- ((DatabaseInfoAccessor)result)._$PINPOINT$_setDatabaseInfo(databaseInfo);
- }
- }
- }
- if (result instanceof ParsingResultAccessor) {
- // 1. Don't check traceContext. preparedStatement can be created in other thread.
- // 2. While sampling is active, the thread which creates preparedStatement could not be a sampling target. So record sql anyway.
- String sql = (String) args[0];
- ParsingResult parsingResult = traceContext.parseSql(sql);
- if (parsingResult != null) {
- ((ParsingResultAccessor)result)._$PINPOINT$_setParsingResult(parsingResult);
- } else {
- if (logger.isErrorEnabled()) {
- logger.error("sqlParsing fail. parsingResult is null sql:{}", sql);
- }
- }
- }
- }
- }
-
- @Override
- public void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
- if (result instanceof ParsingResultAccessor) {
- ParsingResult parsingResult = ((ParsingResultAccessor)result)._$PINPOINT$_getParsingResult();
- recorder.recordSqlParsingResult(parsingResult);
- }
- recorder.recordException(throwable);
- recorder.recordApi(methodDescriptor);
- }
-}
diff --git a/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor3.java b/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor3.java
deleted file mode 100644
index aefc7d19a8d5..000000000000
--- a/plugins/postgresql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/postgresql/interceptor/PostgreSqlPreparedStatementCreateInterceptor3.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright 2014 NAVER Corp.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.navercorp.pinpoint.plugin.jdbc.postgresql.interceptor;
-
-import com.navercorp.pinpoint.bootstrap.context.*;
-import com.navercorp.pinpoint.bootstrap.interceptor.SpanEventSimpleAroundInterceptorForPlugin;
-import com.navercorp.pinpoint.bootstrap.plugin.jdbc.DatabaseInfoAccessor;
-import com.navercorp.pinpoint.bootstrap.plugin.jdbc.ParsingResultAccessor;
-import com.navercorp.pinpoint.bootstrap.plugin.jdbc.UnKnownDatabaseInfo;
-import com.navercorp.pinpoint.bootstrap.util.InterceptorUtils;
-
-/**
- * @author Brad Hong
- */
-// #1375 Workaround java level Deadlock
-// https://oss.navercorp.com/pinpoint/pinpoint-naver/issues/1375
-//@TargetMethods({
-// @TargetMethod(name="prepareStatement", paramTypes={ "java.lang.String", "int", "int", "int" })
-//})
-public class PostgreSqlPreparedStatementCreateInterceptor3 extends SpanEventSimpleAroundInterceptorForPlugin {
-
- public PostgreSqlPreparedStatementCreateInterceptor3(TraceContext context, MethodDescriptor descriptor) {
- super(context, descriptor);
- }
-
- @Override
- public void doInBeforeTrace(SpanEventRecorder recorder, Object target, Object[] args) {
- DatabaseInfo databaseInfo = null;
- if (target instanceof DatabaseInfoAccessor) {
- databaseInfo = ((DatabaseInfoAccessor)target)._$PINPOINT$_getDatabaseInfo();
- }
-
- if (databaseInfo == null) {
- databaseInfo = UnKnownDatabaseInfo.INSTANCE;
- }
-
- recorder.recordServiceType(databaseInfo.getType());
- recorder.recordEndPoint(databaseInfo.getMultipleHost());
- recorder.recordDestinationId(databaseInfo.getDatabaseId());
- }
-
- @Override
- protected void prepareAfterTrace(Object target, Object[] args, Object result, Throwable throwable) {
- final boolean success = InterceptorUtils.isSuccess(throwable);
- if (success) {
- if (target instanceof DatabaseInfoAccessor) {
- // set databaseInfo to PreparedStatement only when preparedStatement is generated successfully.
- DatabaseInfo databaseInfo = ((DatabaseInfoAccessor)target)._$PINPOINT$_getDatabaseInfo();
- if (databaseInfo != null) {
- if (result instanceof DatabaseInfoAccessor) {
- ((DatabaseInfoAccessor)result)._$PINPOINT$_setDatabaseInfo(databaseInfo);
- }
- }
- }
- if (result instanceof ParsingResultAccessor) {
- // 1. Don't check traceContext. preparedStatement can be created in other thread.
- // 2. While sampling is active, the thread which creates preparedStatement could not be a sampling target. So record sql anyway.
- String sql = (String) args[0];
- ParsingResult parsingResult = traceContext.parseSql(sql);
- if (parsingResult != null) {
- ((ParsingResultAccessor)result)._$PINPOINT$_setParsingResult(parsingResult);
- } else {
- if (logger.isErrorEnabled()) {
- logger.error("sqlParsing fail. parsingResult is null sql:{}", sql);
- }
- }
- }
- }
- }
-
- @Override
- public void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
- if (result instanceof ParsingResultAccessor) {
- ParsingResult parsingResult = ((ParsingResultAccessor)result)._$PINPOINT$_getParsingResult();
- recorder.recordSqlParsingResult(parsingResult);
- }
- recorder.recordException(throwable);
- recorder.recordApi(methodDescriptor);
- }
-}
diff --git a/pom.xml b/pom.xml
index fa363ab1d371..1289a392d151 100644
--- a/pom.xml
+++ b/pom.xml
@@ -402,9 +402,9 @@
<version>5.1.20</version>
</dependency>
<dependency>
- <groupId>postgresql</groupId>
+ <groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
- <version>9.1-901-1.jdbc4</version>
+ <version>9.4.1207</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jtds</groupId>
| null | train | val | "2017-07-13T11:25:29" | "2016-11-09T08:28:55Z" | Xylus | test |
pinpoint-apm/pinpoint/3368_3371 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/3368 | pinpoint-apm/pinpoint/3371 | [
"keyword_pr_to_issue"
] | 8df51a3a3e872a90e1733d72433b07d04cdc37ea | 65bd5d6b0881cfc0dd76e901d7fe6176c52197c4 | [] | [] | "2017-09-19T07:09:04Z" | [
"bug",
"module:agent"
] | Fix long division when calculating detailed memory usage | #### Description
Detailed memory usage metric calculation truncates decimal values due to long division. Need a cast to double on one of it's operands.
```return (double) (long / long)``` -> ```return long / (double) long``` | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/memory/DefaultDetailedMemoryMetric.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/memory/DefaultDetailedMemoryMetric.java"
] | [
"profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/metric/memory/DefaultDetailedMemoryMetricTest.java"
] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/memory/DefaultDetailedMemoryMetric.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/memory/DefaultDetailedMemoryMetric.java
index c5054703402f..e80e6eb1573a 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/memory/DefaultDetailedMemoryMetric.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/memory/DefaultDetailedMemoryMetric.java
@@ -82,13 +82,10 @@ private double calculateUsage(MemoryUsage memoryUsage) {
return UNCOLLECTED_USAGE;
}
long max = memoryUsage.getMax() == -1 ? memoryUsage.getCommitted() : memoryUsage.getMax();
- if (max == -1) {
+ if (max == -1 || max == 0) {
return UNCOLLECTED_USAGE;
}
- if (Double.isNaN(max) || Double.isInfinite(max) || max == 0) {
- return UNCOLLECTED_USAGE;
- }
- return memoryUsage.getUsed() / max;
+ return memoryUsage.getUsed() / (double) max;
}
private interface MemoryPoolMXBeanWrapper {
| diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/metric/memory/DefaultDetailedMemoryMetricTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/metric/memory/DefaultDetailedMemoryMetricTest.java
index e4c3e153a48e..6f8870492628 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/metric/memory/DefaultDetailedMemoryMetricTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/metric/memory/DefaultDetailedMemoryMetricTest.java
@@ -20,6 +20,12 @@
import org.junit.Assert;
import org.junit.Test;
+import java.lang.management.MemoryPoolMXBean;
+import java.lang.management.MemoryUsage;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
/**
* @author HyunGil Jeong
*/
@@ -60,4 +66,64 @@ public void testNullMemoryPoolMXBeans() {
Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getPermGenUsage());
Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getMetaspaceUsage());
}
+
+ @Test
+ public void testNullMemoryUsage() {
+ // Given
+ MemoryPoolMXBean mockMXBean = mock(MemoryPoolMXBean.class);
+ MemoryUsage nullMemoryUsage = null;
+ when(mockMXBean.getUsage()).thenReturn(nullMemoryUsage);
+ DetailedMemoryMetric detailedMemoryMetric = new DefaultDetailedMemoryMetric(MemoryPoolType.CMS, mockMXBean, mockMXBean, mockMXBean, mockMXBean, mockMXBean, mockMXBean);
+ // When
+ DetailedMemoryMetricSnapshot snapshot = detailedMemoryMetric.getSnapshot();
+ // Then
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getNewGenUsage());
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getOldGenUsage());
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getSurvivorSpaceUsage());
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getCodeCacheUsage());
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getPermGenUsage());
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getMetaspaceUsage());
+ }
+
+ @Test
+ public void testUnknownMax() {
+ // Given
+ MemoryPoolMXBean mockMXBean = mock(MemoryPoolMXBean.class);
+ MemoryUsage mockUsage = mock(MemoryUsage.class);
+ when(mockMXBean.getUsage()).thenReturn(mockUsage);
+ when(mockUsage.getMax()).thenReturn(-1L);
+ DetailedMemoryMetric detailedMemoryMetric = new DefaultDetailedMemoryMetric(MemoryPoolType.CMS, mockMXBean, mockMXBean, mockMXBean, mockMXBean, mockMXBean, mockMXBean);
+ // When
+ DetailedMemoryMetricSnapshot snapshot = detailedMemoryMetric.getSnapshot();
+ // Then
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getNewGenUsage());
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getOldGenUsage());
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getSurvivorSpaceUsage());
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getCodeCacheUsage());
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getPermGenUsage());
+ Assert.assertTrue(DetailedMemoryMetric.UNCOLLECTED_USAGE == snapshot.getMetaspaceUsage());
+ }
+
+ @Test
+ public void testValidMax() {
+ // Given
+ long givenUsed = 50L;
+ long givenMax = 100L;
+ double expectedUsage = givenUsed / (double) givenMax;
+ MemoryPoolMXBean mockMXBean = mock(MemoryPoolMXBean.class);
+ MemoryUsage mockUsage = mock(MemoryUsage.class);
+ when(mockMXBean.getUsage()).thenReturn(mockUsage);
+ when(mockUsage.getUsed()).thenReturn(50L);
+ when(mockUsage.getMax()).thenReturn(100L);
+ DetailedMemoryMetric detailedMemoryMetric = new DefaultDetailedMemoryMetric(MemoryPoolType.CMS, mockMXBean, mockMXBean, mockMXBean, mockMXBean, mockMXBean, mockMXBean);
+ // When
+ DetailedMemoryMetricSnapshot snapshot = detailedMemoryMetric.getSnapshot();
+ // Then
+ Assert.assertEquals(expectedUsage, snapshot.getNewGenUsage(), 0.01);
+ Assert.assertEquals(expectedUsage, snapshot.getOldGenUsage(), 0.01);
+ Assert.assertEquals(expectedUsage, snapshot.getSurvivorSpaceUsage(), 0.01);
+ Assert.assertEquals(expectedUsage, snapshot.getCodeCacheUsage(), 0.01);
+ Assert.assertEquals(expectedUsage, snapshot.getPermGenUsage(), 0.01);
+ Assert.assertEquals(expectedUsage, snapshot.getMetaspaceUsage(), 0.01);
+ }
}
| val | val | "2017-09-19T06:52:08" | "2017-09-19T05:29:48Z" | Xylus | test |
pinpoint-apm/pinpoint/3406_3414 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/3406 | pinpoint-apm/pinpoint/3414 | [
"keyword_pr_to_issue"
] | 248791b86f1e173bdac22941c406f95e4a6e1983 | c20c4349eefa9445cc7cfe191c9e4cd611fc3e9e | [
"Pinpoint collector needs similar treatment."
] | [] | "2017-09-27T08:07:54Z" | [
"enhancement",
"module:collector",
"module:web"
] | Update pinpoint web/collector spring mvc configuration | #### Description
Update deprecated configurations for pinpoint web. | [
"web/src/main/resources/servlet-context.xml"
] | [
"web/src/main/resources/servlet-context.xml"
] | [] | diff --git a/web/src/main/resources/servlet-context.xml b/web/src/main/resources/servlet-context.xml
index c2f65fd49608..e2c8cb0c7d87 100644
--- a/web/src/main/resources/servlet-context.xml
+++ b/web/src/main/resources/servlet-context.xml
@@ -1,20 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
- xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
- xmlns:beans="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
- xmlns:cache="http://www.springframework.org/schema/cache"
+ xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
- http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven>
@@ -45,16 +37,10 @@
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
-
- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<mvc:interceptors>
<bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0"/>
- <property name="useExpiresHeader" value="true"/>
- <property name="useCacheControlHeader" value="true"/>
- <property name="useCacheControlNoStore" value="true"/>
</bean>
<mvc:interceptor>
<mvc:mapping path="/admin/**" />
| null | train | val | "2017-09-27T08:40:53" | "2017-09-26T09:09:42Z" | Xylus | test |
pinpoint-apm/pinpoint/3777_3812 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/3777 | pinpoint-apm/pinpoint/3812 | [
"keyword_pr_to_issue"
] | ec93ebfd1a2d2fb1a194cac18be68fa323e9c6fa | dcfb665be43e25876bbdb5f1baa7828d6393e9f2 | [
"@himanshumps\r\nThanks for reporting, will get a fix right in, or please let me know if you'd like to fix it and throw us a PR :)"
] | [] | "2018-02-07T09:57:00Z" | [
"bug"
] | Context root for the quickstart application | <!--
If you're reporting a bug or seeking help because something is not working,
please fill out below.
For all else, feel free to DELETE everything and post away your issue!
-->
#### Description
The start/stop scripts under the quickstart/bin folder does not take quickstart.web.context.path, quickstart.testapp.context.path and quickstart.collector.context.path into account in the check URL which is invoked via curl
#### Environment
All
* Pinpoint version: 1.7.2-SNAPSHOT
* OS, WAS, affected library, etc:
* Additional details (e.g. how your collector/web is set up):
#### Additional Info
<!--- Not obligatory, but things like logs can help if something's not working -->
| [
"quickstart/bin/start-collector.sh",
"quickstart/bin/start-testapp.sh",
"quickstart/bin/start-web.sh"
] | [
"quickstart/bin/start-collector.sh",
"quickstart/bin/start-testapp.sh",
"quickstart/bin/start-web.sh"
] | [
"quickstart/testapp/src/main/webapp/WEB-INF/views/apis.jsp"
] | diff --git a/quickstart/bin/start-collector.sh b/quickstart/bin/start-collector.sh
index de6e138752c0..912b6ea384c0 100755
--- a/quickstart/bin/start-collector.sh
+++ b/quickstart/bin/start-collector.sh
@@ -38,6 +38,7 @@ CLOSE_WAIT_TIME=`expr $UNIT_TIME \* $CHECK_COUNT`
PROPERTIES=`cat $CONF_DIR/$CONF_FILE 2>/dev/null`
KEY_VERSION="quickstart.version"
+KEY_CONTEXT_PATH="quickstart.collector.context.path"
KEY_PORT="quickstart.collector.port"
function func_read_properties
@@ -112,8 +113,12 @@ function func_init_log
function func_check_running_pinpoint_collector
{
+ context_path=$( func_read_properties "$KEY_CONTEXT_PATH" )
+ if [ "$context_path" == "/" ]; then
+ context_path=""
+ fi
port=$( func_read_properties "$KEY_PORT" )
- check_url="http://localhost:"$port"/serverTime.pinpoint"
+ check_url="http://localhost:$port$context_path/serverTime.pinpoint"
process_status=`curl $check_url 2>/dev/null | grep 'currentServerTime'`
diff --git a/quickstart/bin/start-testapp.sh b/quickstart/bin/start-testapp.sh
index f02ec4b9cb83..4f0898fdaee6 100755
--- a/quickstart/bin/start-testapp.sh
+++ b/quickstart/bin/start-testapp.sh
@@ -48,6 +48,7 @@ CLOSE_WAIT_TIME=`expr $UNIT_TIME \* $CHECK_COUNT`
PROPERTIES=`cat $CONF_DIR/$CONF_FILE 2>/dev/null`
KEY_VERSION="quickstart.version"
+KEY_CONTEXT_PATH="quickstart.testapp.context.path"
KEY_PORT="quickstart.testapp.port"
function func_read_properties
@@ -147,8 +148,12 @@ function func_start_pinpoint_testapp
pinpoint_opt="-javaagent:$pinpoint_agent -Dpinpoint.agentId=test-agent -Dpinpoint.applicationName=TESTAPP"
export MAVEN_OPTS=$pinpoint_opt
+ context_path=$( func_read_properties "$KEY_CONTEXT_PATH" )
+ if [ "$context_path" == "/" ]; then
+ context_path=""
+ fi
port=$( func_read_properties "$KEY_PORT" )
- check_url="http://localhost:"$port"/getCurrentTimestamp.pinpoint"
+ check_url="http://localhost:$port$context_path/getCurrentTimestamp.pinpoint"
pid=`nohup ${bin}/../../mvnw -f $TESTAPP_DIR/pom.xml clean package tomcat7:run -D$IDENTIFIER -Dmaven.pinpoint.version=$version >> $LOGS_DIR/$LOG_FILE 2>&1 & echo $!`
echo $pid > $PID_DIR/$PID_FILE
diff --git a/quickstart/bin/start-web.sh b/quickstart/bin/start-web.sh
index 167f18f8aa86..177123e7eae7 100755
--- a/quickstart/bin/start-web.sh
+++ b/quickstart/bin/start-web.sh
@@ -38,6 +38,7 @@ CLOSE_WAIT_TIME=`expr $UNIT_TIME \* $CHECK_COUNT`
PROPERTIES=`cat $CONF_DIR/$CONF_FILE 2>/dev/null`
KEY_VERSION="quickstart.version"
+KEY_CONTEXT_PATH="quickstart.web.context.path"
KEY_PORT="quickstart.web.port"
function func_read_properties
@@ -112,9 +113,13 @@ function func_init_log
function func_start_pinpoint_web
{
version=$( func_read_properties "$KEY_VERSION" )
+ context_path=$( func_read_properties "$KEY_CONTEXT_PATH" )
+ if [ "$context_path" == "/" ]; then
+ context_path=""
+ fi
port=$( func_read_properties "$KEY_PORT" )
pid=`nohup ${bin}/../../mvnw -f $WEB_DIR/pom.xml clean package tomcat7:run -D$IDENTIFIER -Dmaven.pinpoint.version=$version > $LOGS_DIR/$LOG_FILE 2>&1 & echo $!`
- check_url="http://localhost:"$port"/serverTime.pinpoint"
+ check_url="http://localhost:$port$context_path/serverTime.pinpoint"
echo $pid > $PID_DIR/$PID_FILE
echo "---$WEB_IDENTIFIER initialization started. pid=$pid.---"
| diff --git a/quickstart/testapp/src/main/webapp/WEB-INF/views/apis.jsp b/quickstart/testapp/src/main/webapp/WEB-INF/views/apis.jsp
index 7b4a483c4b35..074a54f51c72 100644
--- a/quickstart/testapp/src/main/webapp/WEB-INF/views/apis.jsp
+++ b/quickstart/testapp/src/main/webapp/WEB-INF/views/apis.jsp
@@ -16,7 +16,7 @@
<h5>${apiMapping.key}</h5>
<dl>
<c:forEach items="${apiMapping.value}" var="api">
- <dt><a href="${api.mappedUri}.pinpoint">${api.mappedUri}</a></dt>
+ <dt><a href="${pageContext.request.contextPath}${api.mappedUri}.pinpoint">${api.mappedUri}</a></dt>
<dd><small>${api.description}</small></dd>
</c:forEach>
</dl>
| val | val | "2018-02-06T10:21:49" | "2018-01-31T15:16:50Z" | himanshumps | test |
pinpoint-apm/pinpoint/3857_3861 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/3857 | pinpoint-apm/pinpoint/3861 | [
"keyword_pr_to_issue"
] | 1ad9d356204237a8ad9b65a4390340a66cd4c7f3 | 46f60e5971a6965a09e4440726db54bb84df1804 | [] | [] | "2018-02-27T07:56:38Z" | [
"bug",
"module:plugin"
] | IllegalAccessError in Mariadb jdbc url parser | #### Description
There has been an [issue](https://groups.google.com/forum/#!topic/pinpoint_user/0-Wq1guD4wo) where Mariadb jdbc url would show up as *Unknown* due to **IllegalAccessError** on **MariaDBJdbcUrlParser$Type** as below.
```
public class MariaDBJdbcUrlParser implements JdbcUrlParserV2 {
@Override
public DatabaseInfo parse(String jdbcUrl) {
Type type = Type.findType(jdbcUrl);
...
}
private enum Type {
...
}
}
```
This is due to a difference in class load timing between **MariaDBJdbcUrlParser** and it's nested **MariaDBJdbcUrlParser$Type** when Mariadb Java driver is loaded directly by the system class loader (ie is in the system class path).
**MariaDBJdbcUrlParser** is loaded by pinpoint's plugin class loader before application startup and **MariaDBJdbcUrlParser$Type** is loaded only when it is first referenced (ie `Type type = Type.findType(jdbcUrl)`).
At this point, the system class loader would have Mariadb plugin in it's search path (in order to load the interceptors for transformation), so **MariaDBJdbcUrlParser$Type** is loaded by the system class loader.
However, due to the following, an **IllegalAccessError** would be thrown.
> At run time, a class or interface is determined not by its name alone, but by a pair: its binary name and its defining class loader. Each such class or interface belongs to a single run-time package. The run-time package of a class or interface is determined by the package name and defining class loader of the class or interface.
https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.3
> A class or interface C is accessible to a class or interface D if and only if either of the following is true: C is public, C and D are members of the same run-time package
https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.4
The issue did not manifest itself when ran on Tomcat as Tomcat has it's own class loader hierarchy and Mariadb plugin was not added to the system class loader's search path, but was instead added to Tomcat's webapp class loader's search path, and so the loading of **MariaDBJdbcUrlParser$Type** could not have been delegated to system class loader.
Fix would be to load **MariaDBJdbcUrlParser$Type** as well when **MariaDBJdbcUrlParser** is loaded by pinpoint's plugin class loader. | [
"plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBJdbcUrlParser.java"
] | [
"plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBJdbcUrlParser.java"
] | [] | diff --git a/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBJdbcUrlParser.java b/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBJdbcUrlParser.java
index e47c3e11033b..881f9bbb75a8 100644
--- a/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBJdbcUrlParser.java
+++ b/plugins/mariadb-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mariadb/MariaDBJdbcUrlParser.java
@@ -27,7 +27,9 @@
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.EnumSet;
import java.util.List;
+import java.util.Set;
/**
* @author dawidmalina
@@ -36,10 +38,11 @@ public class MariaDBJdbcUrlParser implements JdbcUrlParserV2 {
// jdbc:(mysql|mariadb):[replication:|failover|loadbalance:|aurora:]//<hostDescription>[,<hostDescription>]/[database>]
// jdbc:mariadb:loadbalance://10.22.33.44:3306,10.22.33.55:3306/MariaDB?characterEncoding=UTF-8
- private static final String URL_PREFIX = "jdbc:mariadb:";
-
+ private static final String MARIA_URL_PREFIX = "jdbc:mariadb:";
private static final String MYSQL_URL_PREFIX = "jdbc:mysql:";
+ private static final Set<Type> TYPES = EnumSet.allOf(Type.class);
+
private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
@Override
@@ -49,20 +52,18 @@ public DatabaseInfo parse(String jdbcUrl) {
return UnKnownDatabaseInfo.INSTANCE;
}
- Type type = Type.findType(jdbcUrl);
+ Type type = getType(jdbcUrl);
if (type == null) {
- logger.info("jdbcUrl has invalid prefix.(url:{}, prefix:{}, {})", jdbcUrl, URL_PREFIX, MYSQL_URL_PREFIX);
+ logger.info("jdbcUrl has invalid prefix.(url:{}, valid prefixes:{}, {})", jdbcUrl, MARIA_URL_PREFIX, MYSQL_URL_PREFIX);
return UnKnownDatabaseInfo.INSTANCE;
}
- DatabaseInfo result = null;
try {
- result = parse0(jdbcUrl, type);
+ return parse0(jdbcUrl, type);
} catch (Exception e) {
logger.info("MaridDBJdbcUrl parse error. url: {}, Caused: {}", jdbcUrl, e.getMessage(), e);
- result = UnKnownDatabaseInfo.createUnknownDataBase(MariaDBConstants.MARIADB, MariaDBConstants.MARIADB_EXECUTE_QUERY, jdbcUrl);
+ return UnKnownDatabaseInfo.createUnknownDataBase(MariaDBConstants.MARIADB, MariaDBConstants.MARIADB_EXECUTE_QUERY, jdbcUrl);
}
- return result;
}
private DatabaseInfo parse0(String url, Type type) {
@@ -119,8 +120,17 @@ public ServiceType getServiceType() {
return MariaDBConstants.MARIADB;
}
- private static enum Type {
- MARIA(URL_PREFIX),
+ private static Type getType(String jdbcUrl) {
+ for (Type type : TYPES) {
+ if (jdbcUrl.startsWith(type.getUrlPrefix())) {
+ return type;
+ }
+ }
+ return null;
+ }
+
+ private enum Type {
+ MARIA(MARIA_URL_PREFIX),
MYSQL(MYSQL_URL_PREFIX);
private final String urlPrefix;
@@ -136,19 +146,7 @@ private String getUrlPrefix() {
}
private String getLoadbalanceUrlPrefix() {
- return urlPrefix + "loadbalance:";
+ return loadbalanceUrlPrefix;
}
-
- private static Type findType(String jdbcUrl) {
- for (Type type : Type.values()) {
- if (jdbcUrl.startsWith(type.urlPrefix)) {
- return type;
- }
- }
-
- return null;
- }
-
}
-
}
| null | val | val | "2018-02-27T08:38:00" | "2018-02-27T03:23:45Z" | Xylus | test |
pinpoint-apm/pinpoint/3989_3991 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/3989 | pinpoint-apm/pinpoint/3991 | [
"keyword_pr_to_issue"
] | e5904be76b769b726fb726c5486962f84650350d | ba22650e6834e0abd86e30d64877e1a6249c6cd7 | [] | [] | "2018-04-05T10:15:34Z" | [
"enhancement",
"module:web"
] | Propagate security context to web socket background tasks | Timer tasks started and scheduled by web socket messages do not have access to security context.
Preserve the security context of whoever starts a *PinpointWebSocketResponseAggregator* and bind it to it's life cycle so that timer tasks that are created within them may have access to it. | [
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountWorker.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/task/TimerTaskDecorator.java",
"web/src/main/java/com/navercorp/pinpoint/web/task/TimerTaskDecoratorFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountWorker.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/PinpointWebSocketTimerTaskDecoratorFactory.java",
"web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/websocket/PinpointWebSocketTimerTaskDecoratorTest.java"
] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/task/TimerTaskDecorator.java b/web/src/main/java/com/navercorp/pinpoint/web/task/TimerTaskDecorator.java
new file mode 100644
index 000000000000..dc4180767d44
--- /dev/null
+++ b/web/src/main/java/com/navercorp/pinpoint/web/task/TimerTaskDecorator.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.task;
+
+import java.util.TimerTask;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface TimerTaskDecorator {
+
+ TimerTask decorate(TimerTask timerTask);
+}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/task/TimerTaskDecoratorFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/task/TimerTaskDecoratorFactory.java
new file mode 100644
index 000000000000..9394dcacd138
--- /dev/null
+++ b/web/src/main/java/com/navercorp/pinpoint/web/task/TimerTaskDecoratorFactory.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.task;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface TimerTaskDecoratorFactory {
+
+ TimerTaskDecorator createTimerTaskDecorator();
+}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
index 0b75c87a3a47..2433f4144103 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountHandler.java
@@ -22,6 +22,8 @@
import com.navercorp.pinpoint.rpc.util.MapUtils;
import com.navercorp.pinpoint.web.security.ServerMapDataFilter;
import com.navercorp.pinpoint.web.service.AgentService;
+import com.navercorp.pinpoint.web.task.TimerTaskDecorator;
+import com.navercorp.pinpoint.web.task.TimerTaskDecoratorFactory;
import com.navercorp.pinpoint.web.util.SimpleOrderedThreadPool;
import com.navercorp.pinpoint.web.websocket.message.PinpointWebSocketMessage;
import com.navercorp.pinpoint.web.websocket.message.PinpointWebSocketMessageConverter;
@@ -68,6 +70,7 @@ public class ActiveThreadCountHandler extends TextWebSocketHandler implements Pi
private final AtomicBoolean onTimerTask = new AtomicBoolean(false);
+
private SimpleOrderedThreadPool webSocketFlushExecutor;
private Timer flushTimer;
@@ -79,10 +82,13 @@ public class ActiveThreadCountHandler extends TextWebSocketHandler implements Pi
private final long healthCheckDelay;
private Timer reactiveTimer;
-
+
@Autowired(required=false)
ServerMapDataFilter serverMapDataFilter;
+ @Autowired(required = false)
+ private TimerTaskDecoratorFactory timerTaskDecoratorFactory = new PinpointWebSocketTimerTaskDecoratorFactory();
+
public ActiveThreadCountHandler(AgentService agentService) {
this(DEFAULT_REQUEST_MAPPING, agentService);
}
@@ -272,7 +278,8 @@ private void bindingResponseAggregator(WebSocketSession webSocketSession, WebSoc
PinpointWebSocketResponseAggregator responseAggregator = aggregatorRepository.get(applicationName);
if (responseAggregator == null) {
- responseAggregator = new ActiveThreadCountResponseAggregator(applicationName, agentService, reactiveTimer);
+ TimerTaskDecorator timerTaskDecorator = timerTaskDecoratorFactory.createTimerTaskDecorator();
+ responseAggregator = new ActiveThreadCountResponseAggregator(applicationName, agentService, reactiveTimer, timerTaskDecorator);
responseAggregator.start();
aggregatorRepository.put(applicationName, responseAggregator);
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java
index 766c233504f9..de1e1901bc03 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountResponseAggregator.java
@@ -19,6 +19,7 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.navercorp.pinpoint.common.server.util.AgentLifeCycleState;
import com.navercorp.pinpoint.web.service.AgentService;
+import com.navercorp.pinpoint.web.task.TimerTaskDecorator;
import com.navercorp.pinpoint.web.vo.AgentActiveThreadCount;
import com.navercorp.pinpoint.web.vo.AgentActiveThreadCountList;
import com.navercorp.pinpoint.web.vo.AgentInfo;
@@ -32,6 +33,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Timer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -55,6 +57,7 @@ public class ActiveThreadCountResponseAggregator implements PinpointWebSocketRes
private final String applicationName;
private final AgentService agentService;
private final Timer timer;
+ private final TimerTaskDecorator timerTaskDecorator;
private final Object workerManagingLock = new Object();
private final List<WebSocketSession> webSocketSessions = new CopyOnWriteArrayList<>();
@@ -70,11 +73,12 @@ public class ActiveThreadCountResponseAggregator implements PinpointWebSocketRes
private Map<String, AgentActiveThreadCount> activeThreadCountMap = new HashMap<>();
- public ActiveThreadCountResponseAggregator(String applicationName, AgentService agentService, Timer timer) {
- this.applicationName = applicationName;
- this.agentService = agentService;
+ public ActiveThreadCountResponseAggregator(String applicationName, AgentService agentService, Timer timer, TimerTaskDecorator timerTaskDecorator) {
+ this.applicationName = Objects.requireNonNull(applicationName, "applicationName must not be null");
+ this.agentService = Objects.requireNonNull(agentService, "agentService must not be null");
- this.timer = timer;
+ this.timer = Objects.requireNonNull(timer, "timer must not be null");
+ this.timerTaskDecorator = Objects.requireNonNull(timerTaskDecorator, "timerTaskDecorator must not be null");
this.messageConverter = new PinpointWebSocketMessageConverter();
}
@@ -82,7 +86,7 @@ public ActiveThreadCountResponseAggregator(String applicationName, AgentService
@Override
public void start() {
synchronized (workerManagingLock) {
- workerActiveManager = new WorkerActiveManager(this, agentService, timer);
+ workerActiveManager = new WorkerActiveManager(this, agentService, timer, timerTaskDecorator);
}
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountWorker.java b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountWorker.java
index 99bcbdbc8d7f..03008185a0a1 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountWorker.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/websocket/ActiveThreadCountWorker.java
@@ -39,6 +39,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.Objects;
+
/**
* @author Taejin Koo
*/
@@ -76,13 +78,12 @@ public ActiveThreadCountWorker(AgentService agentService, AgentInfo agentInfo, P
}
public ActiveThreadCountWorker(AgentService agentService, String applicationName, String agentId, PinpointWebSocketResponseAggregator webSocketResponseAggregator, WorkerActiveManager workerActiveManager) {
- this.agentService = agentService;
-
- this.applicationName = applicationName;
- this.agentId = agentId;
+ this.agentService = Objects.requireNonNull(agentService, "agentService must not be null");
+ this.applicationName = Objects.requireNonNull(applicationName, "applicationName must not be null");
+ this.agentId = Objects.requireNonNull(agentId, "agentId must not be null");
- this.responseAggregator = webSocketResponseAggregator;
- this.workerActiveManager = workerActiveManager;
+ this.responseAggregator = Objects.requireNonNull(webSocketResponseAggregator, "responseAggregator must not be null");
+ this.workerActiveManager = Objects.requireNonNull(workerActiveManager, "workerActiveManager must not be null");
AgentActiveThreadCountFactory failResponseFactory = new AgentActiveThreadCountFactory();
failResponseFactory.setAgentId(agentId);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/websocket/PinpointWebSocketTimerTaskDecoratorFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/websocket/PinpointWebSocketTimerTaskDecoratorFactory.java
new file mode 100644
index 000000000000..97a13170d317
--- /dev/null
+++ b/web/src/main/java/com/navercorp/pinpoint/web/websocket/PinpointWebSocketTimerTaskDecoratorFactory.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.websocket;
+
+import com.navercorp.pinpoint.web.task.TimerTaskDecorator;
+import com.navercorp.pinpoint.web.task.TimerTaskDecoratorFactory;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import java.util.TimerTask;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class PinpointWebSocketTimerTaskDecoratorFactory implements TimerTaskDecoratorFactory {
+
+ @Override
+ public TimerTaskDecorator createTimerTaskDecorator() {
+ return new SecurityContextPreservingTimerTaskDecorator();
+ }
+
+ private static class SecurityContextPreservingTimerTaskDecorator implements TimerTaskDecorator {
+
+ private final SecurityContext securityContext;
+
+ private SecurityContextPreservingTimerTaskDecorator() {
+ SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
+ SecurityContext currentSecurityContext = SecurityContextHolder.getContext();
+ Authentication authentication = currentSecurityContext.getAuthentication();
+ if (authentication != null) {
+ securityContext.setAuthentication(authentication);
+ }
+ this.securityContext = securityContext;
+ }
+
+ @Override
+ public TimerTask decorate(TimerTask timerTask) {
+ return new TimerTask() {
+ @Override
+ public void run() {
+ SecurityContext previousSecurityContext = SecurityContextHolder.getContext();
+ try {
+ SecurityContextHolder.setContext(securityContext);
+ timerTask.run();
+ } finally {
+ SecurityContextHolder.setContext(previousSecurityContext);
+ }
+ }
+ };
+ }
+ }
+}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java b/web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java
index 212295d10e49..f84bf24fd321 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/websocket/WorkerActiveManager.java
@@ -18,6 +18,7 @@
import com.navercorp.pinpoint.common.server.util.AgentLifeCycleState;
import com.navercorp.pinpoint.web.service.AgentService;
+import com.navercorp.pinpoint.web.task.TimerTaskDecorator;
import com.navercorp.pinpoint.web.vo.AgentInfo;
import com.navercorp.pinpoint.web.vo.AgentStatus;
import org.slf4j.Logger;
@@ -26,6 +27,7 @@
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
+import java.util.Objects;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
@@ -39,7 +41,7 @@
public class WorkerActiveManager {
private static final long DEFAULT_RECONNECT_DELAY = 5000;
- private static final long DEFAULT_AGENT_CHECk_DELAY = 10000;
+ private static final long DEFAULT_AGENT_CHECK_DELAY = 10000;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@@ -49,6 +51,7 @@ public class WorkerActiveManager {
private final AgentService agentService;
private final Timer timer;
+ private final TimerTaskDecorator timerTaskDecorator;
private final AtomicBoolean isStopped = new AtomicBoolean();
@@ -60,13 +63,14 @@ public class WorkerActiveManager {
private final AtomicBoolean onAgentCheckTimerTask = new AtomicBoolean(false);
private final List<String> defaultAgentIdList = new CopyOnWriteArrayList<>();
- public WorkerActiveManager(PinpointWebSocketResponseAggregator responseAggregator, AgentService agentService, Timer timer) {
- this.responseAggregator = responseAggregator;
+ public WorkerActiveManager(PinpointWebSocketResponseAggregator responseAggregator, AgentService agentService, Timer timer, TimerTaskDecorator timerTaskDecorator) {
+ this.responseAggregator = Objects.requireNonNull(responseAggregator, "responseAggregator must not be null");
+ this.agentService = Objects.requireNonNull(agentService, "agentService must not be null");
- this.applicationName = responseAggregator.getApplicationName();
- this.agentService = agentService;
+ this.timer = Objects.requireNonNull(timer, "timer must not be null");
+ this.timerTaskDecorator = Objects.requireNonNull(timerTaskDecorator, "timerTaskDecorator must not be null");
- this.timer = timer;
+ this.applicationName = this.responseAggregator.getApplicationName();
}
public void close() {
@@ -100,7 +104,8 @@ public void addReactiveWorker(String agentId) {
boolean turnOn = onReconnectTimerTask.compareAndSet(false, true);
logger.info("addReactiveWorker turnOn:{}", turnOn);
if (turnOn) {
- timer.schedule(new ReactiveTimerTask(), DEFAULT_RECONNECT_DELAY);
+ TimerTask reactiveTimerTask = timerTaskDecorator.decorate(new ReactiveTimerTask());
+ timer.schedule(reactiveTimerTask, DEFAULT_RECONNECT_DELAY);
}
}
}
@@ -110,7 +115,8 @@ public void startAgentCheckJob() {
boolean turnOn = onAgentCheckTimerTask.compareAndSet(false, true);
if (turnOn) {
- timer.schedule(new AgentCheckTimerTask(), DEFAULT_AGENT_CHECk_DELAY);
+ TimerTask agentCheckTimerTask = timerTaskDecorator.decorate(new AgentCheckTimerTask());
+ timer.schedule(agentCheckTimerTask, DEFAULT_AGENT_CHECK_DELAY);
}
}
@@ -170,7 +176,8 @@ public void run() {
}
} finally {
if (timer != null && onAgentCheckTimerTask.get() && !isStopped.get()) {
- timer.schedule(new AgentCheckTimerTask(), DEFAULT_AGENT_CHECk_DELAY);
+ TimerTask agentCheckTimerTask = timerTaskDecorator.decorate(new AgentCheckTimerTask());
+ timer.schedule(agentCheckTimerTask, DEFAULT_AGENT_CHECK_DELAY);
}
}
}
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/websocket/PinpointWebSocketTimerTaskDecoratorTest.java b/web/src/test/java/com/navercorp/pinpoint/web/websocket/PinpointWebSocketTimerTaskDecoratorTest.java
new file mode 100644
index 000000000000..4823408fc858
--- /dev/null
+++ b/web/src/test/java/com/navercorp/pinpoint/web/websocket/PinpointWebSocketTimerTaskDecoratorTest.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.web.websocket;
+
+import com.navercorp.pinpoint.web.task.TimerTaskDecoratorFactory;
+import org.junit.Assert;
+import org.junit.Test;
+import org.springframework.security.authentication.TestingAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.context.SecurityContextImpl;
+
+import java.util.Objects;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class PinpointWebSocketTimerTaskDecoratorTest {
+
+ private static final long DELAY_MS = 1000L;
+
+ private final TimerTaskDecoratorFactory timerTaskDecoratorFactory = new PinpointWebSocketTimerTaskDecoratorFactory();
+
+ @Test
+ public void testAuthenticationPropagation() throws InterruptedException {
+ final int numThreads = 3;
+ final Authentication[] authentications = new Authentication[numThreads];
+ for (int i = 0; i < authentications.length; i++) {
+ final String principal = "principal" + i;
+ final String credential = "credential" + i;
+ authentications[i] = new TestingAuthenticationToken(principal, credential);
+ }
+ final CountDownLatch schedulerLatch = new CountDownLatch(numThreads);
+ final Timer timer = new Timer();
+
+ for (Authentication authentication : authentications) {
+ new Thread(new Runnable() {
+ @Override
+ public void run() {
+ SecurityContext securityContext = new SecurityContextImpl();
+ securityContext.setAuthentication(authentication);
+ SecurityContextHolder.setContext(securityContext);
+ TimerTask timerTask = timerTaskDecoratorFactory.createTimerTaskDecorator().decorate(new TestTimerTask(schedulerLatch, authentication));
+ timer.schedule(timerTask, DELAY_MS);
+ }
+ }).start();
+ }
+ Assert.assertTrue("Timed out waiting for timer task completion", schedulerLatch.await(2 * DELAY_MS, TimeUnit.MILLISECONDS));
+ }
+
+ private static class TestTimerTask extends TimerTask {
+
+ private final CountDownLatch executeLatch;
+ private final Authentication expectedAuthentication;
+
+ private TestTimerTask(CountDownLatch executeLatch, Authentication expectedAuthentication) {
+ this.executeLatch = Objects.requireNonNull(executeLatch, "executeLatch must not be null");
+ this.expectedAuthentication = Objects.requireNonNull(expectedAuthentication, "expectedAuthentication must not be null");
+ }
+
+ @Override
+ public void run() {
+ try {
+ SecurityContext securityContext = SecurityContextHolder.getContext();
+ Assert.assertNotNull(securityContext);
+ Authentication actualAuthentication = securityContext.getAuthentication();
+ Assert.assertSame(expectedAuthentication, actualAuthentication);
+ } finally {
+ executeLatch.countDown();
+ }
+ }
+ }
+}
| train | val | "2018-04-05T04:40:44" | "2018-04-05T08:37:56Z" | Xylus | test |
pinpoint-apm/pinpoint/3990_3993 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/3990 | pinpoint-apm/pinpoint/3993 | [
"keyword_pr_to_issue"
] | e5904be76b769b726fb726c5486962f84650350d | f2bda3c7ec1e2345980004f7ade91d98d3cea9d0 | [] | [] | "2018-04-06T08:08:44Z" | [
"enhancement",
"module:plugin"
] | Add support for Spring amqp rabbit 1.7.7+ and 2.0.3+ | Spring amqp rabbit 1.7.7 and 2.0.3 have been released and introduced **BlockingQueueConsumer$ConsumerDecorator** which wraps **BlockingQueueConsumer$InternalConsumer**.
**BlockingQueueConsumer$ConsumerDecorator** also needs to be transformed to handle async trace propagation. | [
"plugins/rabbitmq/README.md",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java"
] | [
"plugins/rabbitmq/README.md",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java"
] | [
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_0_to_1_7_7_IT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_7_to_2_0_0_IT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_0_to_2_0_3_IT.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_3_to_2_x_IT.java"
] | diff --git a/plugins/rabbitmq/README.md b/plugins/rabbitmq/README.md
index 09d7df921660..95f0c651795c 100644
--- a/plugins/rabbitmq/README.md
+++ b/plugins/rabbitmq/README.md
@@ -36,4 +36,5 @@ The plugin has been tested on the following libraries.
```
com.rabbitmq:amqp-client - 2.7.0+
org.springframework.amqp:spring-rabbit - 1.3.3+
-```
\ No newline at end of file
+```
+*(Pinpoint 1.7.2 supports up to org.springframework.amqp:spring-rabbit 1.3.3 ~ 1.7.2, 2.0.1 and 2.0.2)*
\ No newline at end of file
diff --git a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
index 2e009167c9eb..d773d4fe46fd 100644
--- a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
+++ b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
@@ -402,6 +402,17 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
return null;
}
});
+ // Spring-rabbit 1.7.7+, 2.0.3+
+ transformTemplate.transform("org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$ConsumerDecorator", new TransformCallback() {
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+ if (addConsumerHandleDeliveryInterceptor(target)) {
+ return target.toBytecode();
+ }
+ return null;
+ }
+ });
}
}
| diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_0_to_2_0_0_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_0_to_1_7_7_IT.java
similarity index 99%
rename from agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_0_to_2_0_0_IT.java
rename to agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_0_to_1_7_7_IT.java
index c8cf2e558ba5..d6a0d9457d82 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_0_to_2_0_0_IT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_0_to_1_7_7_IT.java
@@ -49,9 +49,9 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointConfig("rabbitmq/client/pinpoint-rabbitmq.config")
-@Dependency({"org.springframework.amqp:spring-rabbit:[1.7.0.RELEASE,2.0.0.RELEASE)", "com.fasterxml.jackson.core:jackson-core:2.8.11", "org.apache.qpid:qpid-broker:6.1.1"})
+@Dependency({"org.springframework.amqp:spring-rabbit:[1.7.0.RELEASE,1.7.7.RELEASE)", "com.fasterxml.jackson.core:jackson-core:2.8.11", "org.apache.qpid:qpid-broker:6.1.1"})
@JvmArgument({"-Dpinpoint.configcenter=false"})
-public class SpringAmqpRabbit_1_7_0_to_2_0_0_IT {
+public class SpringAmqpRabbit_1_7_0_to_1_7_7_IT {
private static final TestBroker BROKER = new TestBroker();
private static final TestApplicationContext CONTEXT = new TestApplicationContext();
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_7_to_2_0_0_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_7_to_2_0_0_IT.java
new file mode 100644
index 000000000000..59671849e408
--- /dev/null
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_7_to_2_0_0_IT.java
@@ -0,0 +1,311 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.jdk7.rabbitmq.spring;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.Expectations;
+import com.navercorp.pinpoint.bootstrap.plugin.test.ExpectedTrace;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.common.trace.ServiceType;
+import com.navercorp.pinpoint.plugin.jdk7.rabbitmq.util.RabbitMQTestConstants;
+import com.navercorp.pinpoint.plugin.jdk7.rabbitmq.util.TestBroker;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.JvmArgument;
+import com.navercorp.pinpoint.test.plugin.PinpointConfig;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.PropagationMarker;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.config.CommonConfig;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.config.MessageListenerConfig_Post_1_4_0;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.config.ReceiverConfig_Post_1_6_0;
+import com.rabbitmq.client.AMQP;
+import com.rabbitmq.client.Channel;
+import com.rabbitmq.client.Consumer;
+import com.rabbitmq.client.Envelope;
+import com.rabbitmq.client.impl.AMQCommand;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.amqp.core.Message;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+
+/**
+ * <tt>BlockingQueueConsumer$ConsumerDecorator</tt> added in 2.0.3 has been backported to 1.7.7 as well.
+ *
+ * @author HyunGil Jeong
+ * @see SpringAmqpRabbit_2_0_3_to_2_x_IT
+ */
+@RunWith(PinpointPluginTestSuite.class)
+@PinpointConfig("rabbitmq/client/pinpoint-rabbitmq.config")
+@Dependency({"org.springframework.amqp:spring-rabbit:[1.7.7.RELEASE,2.0.0.RELEASE)", "com.fasterxml.jackson.core:jackson-core:2.8.11", "org.apache.qpid:qpid-broker:6.1.1"})
+@JvmArgument({"-Dpinpoint.configcenter=false"})
+public class SpringAmqpRabbit_1_7_7_to_2_0_0_IT {
+
+ private static final TestBroker BROKER = new TestBroker();
+ private static final TestApplicationContext CONTEXT = new TestApplicationContext();
+
+ private final SpringAmqpRabbitTestRunner testRunner = new SpringAmqpRabbitTestRunner(CONTEXT);
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ BROKER.start();
+ CONTEXT.init(
+ CommonConfig.class,
+ MessageListenerConfig_Post_1_4_0.class,
+ ReceiverConfig_Post_1_6_0.class);
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() {
+ CONTEXT.close();
+ BROKER.shutdown();
+ }
+
+ @Test
+ public void testPush() throws Exception {
+ final String remoteAddress = testRunner.getRemoteAddress();
+
+ Class<?> rabbitTemplateClass = Class.forName("org.springframework.amqp.rabbit.core.RabbitTemplate");
+ Method rabbitTemplateConvertAndSend = rabbitTemplateClass.getDeclaredMethod("convertAndSend", String.class, String.class, Object.class);
+ ExpectedTrace rabbitTemplateConvertAndSendTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateConvertAndSend); // method
+ // automatic recovery deliberately disabled as Spring has it's own recovery mechanism
+ Class<?> channelNClass = Class.forName("com.rabbitmq.client.impl.ChannelN");
+ Method channelNBasicPublish = channelNClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace channelNBasicPublishTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ channelNBasicPublish, // method
+ null, // rpc
+ remoteAddress, // endPoint
+ "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
+ Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
+ ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ "RabbitMQ Consumer Invocation", // method
+ "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
+ null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
+ remoteAddress, // remoteAddress
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
+ Class<?> consumerDispatcherClass = Class.forName("com.rabbitmq.client.impl.ConsumerDispatcher");
+ Method consumerDispatcherHandleDelivery = consumerDispatcherClass.getDeclaredMethod("handleDelivery", Consumer.class, String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace consumerDispatcherHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ consumerDispatcherHandleDelivery); // method
+ ExpectedTrace asynchronousInvocationTrace = Expectations.event(
+ ServiceType.ASYNC.getName(),
+ "Asynchronous Invocation");
+ Class<?> blockingQueueConsumerConsumerDecoratorClass = Class.forName("org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$ConsumerDecorator");
+ Method blockingQueueConsumerConsumerDecoratorHandleDelivery = blockingQueueConsumerConsumerDecoratorClass.getDeclaredMethod("handleDelivery", String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace blockingQueueConsumerConsumerDecoratorHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ blockingQueueConsumerConsumerDecoratorHandleDelivery);
+ Class<?> deliveryClass = Class.forName("org.springframework.amqp.rabbit.support.Delivery");
+ Constructor<?> deliveryConstructor = deliveryClass.getDeclaredConstructor(String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace deliveryConstructorTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ deliveryConstructor);
+ Class<?> abstractMessageListenerContainerClass = Class.forName("org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer");
+ Method abstractMessageListenerContainerExecuteListener = abstractMessageListenerContainerClass.getDeclaredMethod("executeListener", Channel.class, Message.class);
+ ExpectedTrace abstractMessageListenerContainerExecuteListenerTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ abstractMessageListenerContainerExecuteListener);
+ Class<?> propagationMarkerClass = PropagationMarker.class;
+ Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
+ ExpectedTrace markTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ propagationMarkerMark);
+
+ ExpectedTrace[] expectedTraces = {
+ rabbitTemplateConvertAndSendTrace,
+ channelNBasicPublishTrace,
+ rabbitMqConsumerInvocationTrace,
+ consumerDispatcherHandleDeliveryTrace,
+ asynchronousInvocationTrace,
+ blockingQueueConsumerConsumerDecoratorHandleDeliveryTrace,
+ deliveryConstructorTrace,
+ asynchronousInvocationTrace,
+ abstractMessageListenerContainerExecuteListenerTrace,
+ markTrace
+ };
+
+ final PluginTestVerifier verifier = testRunner.runPush(expectedTraces.length);
+
+ verifier.verifyTrace(expectedTraces);
+ verifier.verifyTraceCount(0);
+ }
+
+ @Test
+ public void testPull() throws Exception {
+ final String remoteAddress = testRunner.getRemoteAddress();
+
+ Class<?> rabbitTemplateClass = Class.forName("org.springframework.amqp.rabbit.core.RabbitTemplate");
+ // verify queue-initiated traces
+ Method rabbitTemplateConvertAndSend = rabbitTemplateClass.getDeclaredMethod("convertAndSend", String.class, String.class, Object.class);
+ ExpectedTrace rabbitTemplateConvertAndSendTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateConvertAndSend); // method
+ // automatic recovery deliberately disabled as Spring has it's own recovery mechanism
+ Class<?> channelNClass = Class.forName("com.rabbitmq.client.impl.ChannelN");
+ Method channelNBasicPublish = channelNClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace channelNBasicPublishTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ channelNBasicPublish, // method
+ null, // rpc
+ remoteAddress, // endPoint
+ "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
+ Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ "RabbitMQ Consumer Invocation", // method
+ "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
+ null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
+ remoteAddress, // remoteAddress
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ Class<?> amqChannelClass = Class.forName("com.rabbitmq.client.impl.AMQChannel");
+ Method amqChannelHandleCompleteInboundCommand = amqChannelClass.getDeclaredMethod("handleCompleteInboundCommand", AMQCommand.class);
+ ExpectedTrace amqChannelHandleCompleteInboundCommandTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // method
+ amqChannelHandleCompleteInboundCommand);
+
+ ExpectedTrace[] queueInitiatedTraces = {
+ rabbitTemplateConvertAndSendTrace,
+ channelNBasicPublishTrace,
+ rabbitMqConsumerInvocationTrace,
+ amqChannelHandleCompleteInboundCommandTrace
+ };
+
+ // verify client-initiated traces
+ Method rabbitTemplateReceive = rabbitTemplateClass.getDeclaredMethod("receive", String.class);
+ ExpectedTrace rabbitTemplateReceiveTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateReceive); // method
+ Method channelNBasicGet = channelNClass.getDeclaredMethod("basicGet", String.class, boolean.class);
+ ExpectedTrace channelNBasicGetTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL,
+ channelNBasicGet);
+ Class<?> propagationMarkerClass = PropagationMarker.class;
+ Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
+ ExpectedTrace markTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ propagationMarkerMark);
+
+ ExpectedTrace[] clientInitiatedTraces = {
+ rabbitTemplateReceiveTrace,
+ channelNBasicGetTrace,
+ markTrace
+ };
+
+ int expectedTraceCount = queueInitiatedTraces.length + clientInitiatedTraces.length;
+ final PluginTestVerifier verifier = testRunner.runPull(expectedTraceCount);
+
+ verifier.verifyDiscreteTrace(queueInitiatedTraces);
+ verifier.verifyDiscreteTrace(clientInitiatedTraces);
+
+ verifier.verifyTraceCount(0);
+ }
+
+ @Test
+ public void testPullWithTimeout() throws Exception {
+ final String remoteAddress = testRunner.getRemoteAddress();
+
+ Class<?> rabbitTemplateClass = Class.forName("org.springframework.amqp.rabbit.core.RabbitTemplate");
+ // verify queue-initiated traces
+ Method rabbitTemplateConvertAndSend = rabbitTemplateClass.getDeclaredMethod("convertAndSend", String.class, String.class, Object.class);
+ ExpectedTrace rabbitTemplateConvertAndSendTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateConvertAndSend); // method
+ // automatic recovery deliberately disabled as Spring has it's own recovery mechanism
+ Class<?> channelNClass = Class.forName("com.rabbitmq.client.impl.ChannelN");
+ Method channelNBasicPublish = channelNClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace channelNBasicPublishTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ channelNBasicPublish, // method
+ null, // rpc
+ remoteAddress, // endPoint
+ "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
+ Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ "RabbitMQ Consumer Invocation", // method
+ "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
+ null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
+ remoteAddress, // remoteAddress
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ Class<?> consumerDispatcherClass = Class.forName("com.rabbitmq.client.impl.ConsumerDispatcher");
+ Method consumerDispatcherHandleDelivery = consumerDispatcherClass.getDeclaredMethod("handleDelivery", Consumer.class, String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace consumerDispatcherHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ consumerDispatcherHandleDelivery); // method
+ ExpectedTrace asynchronousInvocationTrace = Expectations.event(
+ ServiceType.ASYNC.getName(),
+ "Asynchronous Invocation");
+ Class<?> queueingConsumerClass = Class.forName("com.rabbitmq.client.QueueingConsumer");
+ Method queueingConsumerHandleDelivery = queueingConsumerClass.getDeclaredMethod("handleDelivery", String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace queueingConsumerHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ queueingConsumerHandleDelivery);
+ Class<?> queueingConsumerDeliveryClass = Class.forName("com.rabbitmq.client.QueueingConsumer$Delivery");
+ Constructor queueingConsumerDeliveryConstructor = queueingConsumerDeliveryClass.getDeclaredConstructor(Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace queueingConsumerDeliveryConstructorTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL,
+ queueingConsumerDeliveryConstructor);
+
+ ExpectedTrace[] queueInitiatedTraces = {
+ rabbitTemplateConvertAndSendTrace,
+ channelNBasicPublishTrace,
+ rabbitMqConsumerInvocationTrace,
+ consumerDispatcherHandleDeliveryTrace,
+ asynchronousInvocationTrace,
+ queueingConsumerHandleDeliveryTrace,
+ queueingConsumerDeliveryConstructorTrace
+ };
+
+ // verify client-initiated traces
+ Method rabbitTemplateReceive = rabbitTemplateClass.getDeclaredMethod("receive", String.class, long.class);
+ ExpectedTrace rabbitTemplateReceiveTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateReceive); // method
+ Method queueingConsumerNextDelivery = queueingConsumerClass.getDeclaredMethod("nextDelivery", long.class);
+ ExpectedTrace queueingConsumerNextDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL,
+ queueingConsumerNextDelivery);
+ Class<?> propagationMarkerClass = PropagationMarker.class;
+ Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
+ ExpectedTrace markTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ propagationMarkerMark);
+
+ ExpectedTrace[] clientInitiatedTraces = {
+ rabbitTemplateReceiveTrace,
+ queueingConsumerNextDeliveryTrace,
+ markTrace
+ };
+
+ int expectedTraceCount = queueInitiatedTraces.length + clientInitiatedTraces.length;
+ final PluginTestVerifier verifier = testRunner.runPull(expectedTraceCount, 5000L);
+
+ verifier.verifyDiscreteTrace(queueInitiatedTraces);
+ verifier.verifyDiscreteTrace(clientInitiatedTraces);
+
+ verifier.verifyTraceCount(0);
+ }
+}
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_x_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_0_to_2_0_3_IT.java
similarity index 98%
rename from agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_x_IT.java
rename to agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_0_to_2_0_3_IT.java
index e4666733cb60..d0454261c2b4 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_x_IT.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_0_to_2_0_3_IT.java
@@ -58,10 +58,10 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointConfig("rabbitmq/client/pinpoint-rabbitmq.config")
-@Dependency({"org.springframework.amqp:spring-rabbit:[2.0.0.RELEASE,)", "com.fasterxml.jackson.core:jackson-core:2.8.11", "org.apache.qpid:qpid-broker:6.1.1"})
+@Dependency({"org.springframework.amqp:spring-rabbit:[2.0.0.RELEASE,2.0.3.RELEASE)", "com.fasterxml.jackson.core:jackson-core:2.8.11", "org.apache.qpid:qpid-broker:6.1.1"})
@JvmVersion(8)
@JvmArgument({"-Dpinpoint.configcenter=false"})
-public class SpringAmqpRabbit_2_x_IT {
+public class SpringAmqpRabbit_2_0_0_to_2_0_3_IT {
private static final TestBroker BROKER = new TestBroker();
private static final TestApplicationContext CONTEXT = new TestApplicationContext();
@@ -306,7 +306,6 @@ public void testPullWithTimeout() throws Exception {
int expectedTraceCount = queueInitiatedTraces.length + clientInitiatedTraces.length;
final PluginTestVerifier verifier = testRunner.runPull(expectedTraceCount, 5000L);
-// final PluginTestVerifier verifier = testRunner.runPull(9, 5000L);
verifier.verifyDiscreteTrace(queueInitiatedTraces);
verifier.verifyDiscreteTrace(clientInitiatedTraces);
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_3_to_2_x_IT.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_3_to_2_x_IT.java
new file mode 100644
index 000000000000..b9c9c067bbfe
--- /dev/null
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_3_to_2_x_IT.java
@@ -0,0 +1,314 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.jdk7.rabbitmq.spring;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.Expectations;
+import com.navercorp.pinpoint.bootstrap.plugin.test.ExpectedTrace;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.common.trace.ServiceType;
+import com.navercorp.pinpoint.plugin.jdk7.rabbitmq.util.RabbitMQTestConstants;
+import com.navercorp.pinpoint.plugin.jdk7.rabbitmq.util.TestBroker;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.JvmArgument;
+import com.navercorp.pinpoint.test.plugin.JvmVersion;
+import com.navercorp.pinpoint.test.plugin.PinpointConfig;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.PropagationMarker;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.config.CommonConfig;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.config.MessageListenerConfig_Post_1_4_0;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.config.ReceiverConfig_Post_1_6_0;
+import com.rabbitmq.client.AMQP;
+import com.rabbitmq.client.Channel;
+import com.rabbitmq.client.Consumer;
+import com.rabbitmq.client.Envelope;
+import com.rabbitmq.client.impl.AMQCommand;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.amqp.core.Message;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+
+/**
+ * <p>Spring-amqp rabbit 2.0.3 introduced <tt>BlockingQueueConsumer$ConsumerDecorator</tt>, which wraps
+ * <tt>BlockingQueueConsumer$InternalConsumer</tt>.
+ *
+ * <p>This affects asynchronous trace propagation as async trace object now gets attached to
+ * <tt>BlockingQueueConsumer$ConsumerDecorator</tt> instead of the previous
+ * <tt>BlockingQueueConsumer$InternalConsumer</tt>.
+ *
+ * @author HyunGil Jeong
+ */
+@RunWith(PinpointPluginTestSuite.class)
+@PinpointConfig("rabbitmq/client/pinpoint-rabbitmq.config")
+@Dependency({"org.springframework.amqp:spring-rabbit:[2.0.3.RELEASE,)", "com.fasterxml.jackson.core:jackson-core:2.8.11", "org.apache.qpid:qpid-broker:6.1.1"})
+@JvmVersion(8)
+@JvmArgument({"-Dpinpoint.configcenter=false"})
+public class SpringAmqpRabbit_2_0_3_to_2_x_IT {
+
+ private static final TestBroker BROKER = new TestBroker();
+ private static final TestApplicationContext CONTEXT = new TestApplicationContext();
+
+ private final SpringAmqpRabbitTestRunner testRunner = new SpringAmqpRabbitTestRunner(CONTEXT);
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ BROKER.start();
+ CONTEXT.init(
+ CommonConfig.class,
+ MessageListenerConfig_Post_1_4_0.class,
+ ReceiverConfig_Post_1_6_0.class);
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() {
+ CONTEXT.close();
+ BROKER.shutdown();
+ }
+
+ @Test
+ public void testPush() throws Exception {
+ final String remoteAddress = testRunner.getRemoteAddress();
+
+ Class<?> rabbitTemplateClass = Class.forName("org.springframework.amqp.rabbit.core.RabbitTemplate");
+ Method rabbitTemplateConvertAndSend = rabbitTemplateClass.getDeclaredMethod("convertAndSend", String.class, String.class, Object.class);
+ ExpectedTrace rabbitTemplateConvertAndSendTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateConvertAndSend); // method
+ // automatic recovery deliberately disabled as Spring has it's own recovery mechanism
+ Class<?> channelNClass = Class.forName("com.rabbitmq.client.impl.ChannelN");
+ Method channelNBasicPublish = channelNClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace channelNBasicPublishTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ channelNBasicPublish, // method
+ null, // rpc
+ remoteAddress, // endPoint
+ "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
+ Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
+ ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ "RabbitMQ Consumer Invocation", // method
+ "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
+ null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
+ remoteAddress, // remoteAddress
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
+ Class<?> consumerDispatcherClass = Class.forName("com.rabbitmq.client.impl.ConsumerDispatcher");
+ Method consumerDispatcherHandleDelivery = consumerDispatcherClass.getDeclaredMethod("handleDelivery", Consumer.class, String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace consumerDispatcherHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ consumerDispatcherHandleDelivery); // method
+ ExpectedTrace asynchronousInvocationTrace = Expectations.event(
+ ServiceType.ASYNC.getName(),
+ "Asynchronous Invocation");
+ Class<?> blockingQueueConsumerConsumerDecoratorClass = Class.forName("org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$ConsumerDecorator");
+ Method blockingQueueConsumerConsumerDecoratorHandleDelivery = blockingQueueConsumerConsumerDecoratorClass.getDeclaredMethod("handleDelivery", String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace blockingQueueConsumerConsumerDecoratorHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ blockingQueueConsumerConsumerDecoratorHandleDelivery);
+ Class<?> deliveryClass = Class.forName("org.springframework.amqp.rabbit.support.Delivery");
+ Constructor<?> deliveryConstructor = deliveryClass.getDeclaredConstructor(String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace deliveryConstructorTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ deliveryConstructor);
+ Class<?> abstractMessageListenerContainerClass = Class.forName("org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer");
+ Method abstractMessageListenerContainerExecuteListener = abstractMessageListenerContainerClass.getDeclaredMethod("executeListener", Channel.class, Message.class);
+ ExpectedTrace abstractMessageListenerContainerExecuteListenerTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ abstractMessageListenerContainerExecuteListener);
+ Class<?> propagationMarkerClass = PropagationMarker.class;
+ Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
+ ExpectedTrace markTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ propagationMarkerMark);
+
+ ExpectedTrace[] expectedTraces = {
+ rabbitTemplateConvertAndSendTrace,
+ channelNBasicPublishTrace,
+ rabbitMqConsumerInvocationTrace,
+ consumerDispatcherHandleDeliveryTrace,
+ asynchronousInvocationTrace,
+ blockingQueueConsumerConsumerDecoratorHandleDeliveryTrace,
+ deliveryConstructorTrace,
+ asynchronousInvocationTrace,
+ abstractMessageListenerContainerExecuteListenerTrace,
+ markTrace
+ };
+
+ final PluginTestVerifier verifier = testRunner.runPush(expectedTraces.length);
+
+ verifier.verifyTrace(expectedTraces);
+ verifier.verifyTraceCount(0);
+ }
+
+ @Test
+ public void testPull() throws Exception {
+ final String remoteAddress = testRunner.getRemoteAddress();
+
+ Class<?> rabbitTemplateClass = Class.forName("org.springframework.amqp.rabbit.core.RabbitTemplate");
+ // verify queue-initiated traces
+ Method rabbitTemplateConvertAndSend = rabbitTemplateClass.getDeclaredMethod("convertAndSend", String.class, String.class, Object.class);
+ ExpectedTrace rabbitTemplateConvertAndSendTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateConvertAndSend); // method
+ // automatic recovery deliberately disabled as Spring has it's own recovery mechanism
+ Class<?> channelNClass = Class.forName("com.rabbitmq.client.impl.ChannelN");
+ Method channelNBasicPublish = channelNClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace channelNBasicPublishTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ channelNBasicPublish, // method
+ null, // rpc
+ remoteAddress, // endPoint
+ "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
+ Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ "RabbitMQ Consumer Invocation", // method
+ "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
+ null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
+ remoteAddress, // remoteAddress
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ Class<?> amqChannelClass = Class.forName("com.rabbitmq.client.impl.AMQChannel");
+ Method amqChannelHandleCompleteInboundCommand = amqChannelClass.getDeclaredMethod("handleCompleteInboundCommand", AMQCommand.class);
+ ExpectedTrace amqChannelHandleCompleteInboundCommandTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // method
+ amqChannelHandleCompleteInboundCommand);
+
+ ExpectedTrace[] queueInitiatedTraces = {
+ rabbitTemplateConvertAndSendTrace,
+ channelNBasicPublishTrace,
+ rabbitMqConsumerInvocationTrace,
+ amqChannelHandleCompleteInboundCommandTrace
+ };
+
+ // verify client-initiated traces
+ Method rabbitTemplateReceive = rabbitTemplateClass.getDeclaredMethod("receive", String.class);
+ ExpectedTrace rabbitTemplateReceiveTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateReceive); // method
+ Method channelNBasicGet = channelNClass.getDeclaredMethod("basicGet", String.class, boolean.class);
+ ExpectedTrace channelNBasicGetTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL,
+ channelNBasicGet);
+ Class<?> propagationMarkerClass = PropagationMarker.class;
+ Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
+ ExpectedTrace markTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ propagationMarkerMark);
+
+ ExpectedTrace[] clientInitiatedTraces = {
+ rabbitTemplateReceiveTrace,
+ channelNBasicGetTrace,
+ markTrace
+ };
+
+ int expectedTraceCount = queueInitiatedTraces.length + clientInitiatedTraces.length;
+ final PluginTestVerifier verifier = testRunner.runPull(expectedTraceCount);
+
+ verifier.verifyDiscreteTrace(queueInitiatedTraces);
+ verifier.verifyDiscreteTrace(clientInitiatedTraces);
+
+ verifier.verifyTraceCount(0);
+ }
+
+ @Test
+ public void testPullWithTimeout() throws Exception {
+ final String remoteAddress = testRunner.getRemoteAddress();
+
+ Class<?> rabbitTemplateClass = Class.forName("org.springframework.amqp.rabbit.core.RabbitTemplate");
+ // verify queue-initiated traces
+ Method rabbitTemplateConvertAndSend = rabbitTemplateClass.getDeclaredMethod("convertAndSend", String.class, String.class, Object.class);
+ ExpectedTrace rabbitTemplateConvertAndSendTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateConvertAndSend); // method
+ // automatic recovery deliberately disabled as Spring has it's own recovery mechanism
+ Class<?> channelNClass = Class.forName("com.rabbitmq.client.impl.ChannelN");
+ Method channelNBasicPublish = channelNClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace channelNBasicPublishTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ channelNBasicPublish, // method
+ null, // rpc
+ remoteAddress, // endPoint
+ "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
+ Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ "RabbitMQ Consumer Invocation", // method
+ "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
+ null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
+ remoteAddress, // remoteAddress
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ Class<?> consumerDispatcherClass = Class.forName("com.rabbitmq.client.impl.ConsumerDispatcher");
+ Method consumerDispatcherHandleDelivery = consumerDispatcherClass.getDeclaredMethod("handleDelivery", Consumer.class, String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace consumerDispatcherHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ consumerDispatcherHandleDelivery); // method
+ ExpectedTrace asynchronousInvocationTrace = Expectations.event(
+ ServiceType.ASYNC.getName(),
+ "Asynchronous Invocation");
+ // RabbitTemplate internal consumer implementation - may change in future versions which will cause tests to
+ // fail, in which case the integration test needs to be updated to match code changes
+ Class<?> rabbitTemplateInternalConsumerClass = Class.forName("org.springframework.amqp.rabbit.core.RabbitTemplate$2");
+ Method rabbitTemplateInternalConsumerHandleDelivery = rabbitTemplateInternalConsumerClass.getDeclaredMethod("handleDelivery", String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace rabbitTemplateInternalConsumerHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateInternalConsumerHandleDelivery); // method
+ Class<?> deliveryClass = Class.forName("org.springframework.amqp.rabbit.support.Delivery");
+ Constructor<?> deliveryConstructor = deliveryClass.getDeclaredConstructor(String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace deliveryConstructorTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ deliveryConstructor);
+
+ ExpectedTrace[] queueInitiatedTraces = {
+ rabbitTemplateConvertAndSendTrace,
+ channelNBasicPublishTrace,
+ rabbitMqConsumerInvocationTrace,
+ consumerDispatcherHandleDeliveryTrace,
+ asynchronousInvocationTrace,
+ rabbitTemplateInternalConsumerHandleDeliveryTrace,
+ deliveryConstructorTrace
+ };
+
+ // verify client-initiated traces
+ Method rabbitTemplateReceive = rabbitTemplateClass.getDeclaredMethod("receive", String.class, long.class);
+ ExpectedTrace rabbitTemplateReceiveTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateReceive); // method
+ Class<?> propagationMarkerClass = PropagationMarker.class;
+ Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
+ ExpectedTrace markTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ propagationMarkerMark);
+
+ ExpectedTrace[] clientInitiatedTraces = {
+ rabbitTemplateReceiveTrace,
+ markTrace
+ };
+
+ int expectedTraceCount = queueInitiatedTraces.length + clientInitiatedTraces.length;
+ final PluginTestVerifier verifier = testRunner.runPull(expectedTraceCount, 5000L);
+
+ verifier.verifyDiscreteTrace(queueInitiatedTraces);
+ verifier.verifyDiscreteTrace(clientInitiatedTraces);
+
+ verifier.verifyTraceCount(0);
+ }
+}
| train | val | "2018-04-05T04:40:44" | "2018-04-05T10:13:02Z" | Xylus | test |
pinpoint-apm/pinpoint/4014_4023 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4014 | pinpoint-apm/pinpoint/4023 | [
"keyword_pr_to_issue"
] | ffa83ee79684369e90d75ee11ef961aa479d3c96 | 682041f1e650d8ceb0fc879cf3900b4474aa0908 | [] | [] | "2018-04-13T08:54:23Z" | [
"bug",
"module:plugin"
] | RabbitMQ plugin may propagate incorrect async trace context to consumers | #### Description
When **ConsumerDispatcher** receives a message, it delegates the message over to a consumer, which will handle the message in a different thread (**ExecutorService** in **ConsumerWorkService**).
In order to propagate trace over this thread boundary, **ConsumerDispatcher**'s interceptor injected async trace context directly to the consumer.
The consumer would then use the injected async trace context to continue tracing in a different thread.
Since the consumer is shared, a problem arises when the **ConsumerDispatcher** receives a new message before the consumer finishes handling the previous message (or the consumer might not have even started handling the previous message).
When this happens, the consumer will use the async trace context created from the new message, even if it's still handling the previous message.
Similar problem arises when the consumer's sampling rate is not 1 (100%). For example, if the sampling rate is set to 2 (50%), **ConsumerDispatcher** will create an async trace context for the first message and inject it into the consumer, and the consumer will use it to continue tracing. Then, when a second message arrives, **ConsumerDispatcher** will skip tracing, but the consumer still has the async trace context injected from the first message and will use it to continue tracing.
The resulting call stack for both cases would be jumbled up, with one of the transactions having both consumer traces, and the other having no consumer traces.
Having the **ConsumerDispatcher** inject async trace context into an object that is not shared would solve the problem. | [
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ConsumerHandleDeliveryInterceptor.java",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/RabbitMQConsumerDispatchInterceptor.java"
] | [
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ConsumerHandleDeliveryInterceptor.java",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/RabbitMQConsumerDispatchInterceptor.java"
] | [
"agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/RabbitMQTestRunner.java"
] | diff --git a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
index d773d4fe46fd..e31fdbf35cfc 100644
--- a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
+++ b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
@@ -146,6 +146,15 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
return target.toBytecode();
}
});
+ // Envelope - for asynchrnous trace propagation for consumers
+ transformTemplate.transform("com.rabbitmq.client.Envelope", new TransformCallback() {
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+ target.addField(AsyncContextAccessor.class.getName());
+ return target.toBytecode();
+ }
+ });
}
private void addAMQChannelEditor(final Filter<String> excludeExchangeFilter) {
@@ -187,7 +196,6 @@ private boolean addConsumerHandleDeliveryInterceptor(InstrumentClass target) thr
return false;
}
handleDelivery.addScopedInterceptor("com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.ConsumerHandleDeliveryInterceptor", RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE);
- target.addField(AsyncContextAccessor.class.getName());
return true;
}
diff --git a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ConsumerHandleDeliveryInterceptor.java b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ConsumerHandleDeliveryInterceptor.java
index 9e154410a270..c02d68c0f1bc 100644
--- a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ConsumerHandleDeliveryInterceptor.java
+++ b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ConsumerHandleDeliveryInterceptor.java
@@ -1,29 +1,184 @@
package com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor;
+import com.navercorp.pinpoint.bootstrap.async.AsyncContextAccessor;
+import com.navercorp.pinpoint.bootstrap.async.AsyncContextAccessorUtils;
import com.navercorp.pinpoint.bootstrap.context.*;
-import com.navercorp.pinpoint.bootstrap.interceptor.AsyncContextSpanEventSimpleAroundInterceptor;
+import com.navercorp.pinpoint.bootstrap.context.scope.TraceScope;
+import com.navercorp.pinpoint.bootstrap.interceptor.AroundInterceptor;
+import com.navercorp.pinpoint.bootstrap.logging.PLogger;
+import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.plugin.rabbitmq.client.RabbitMQClientConstants;
+import com.rabbitmq.client.Consumer;
+import com.rabbitmq.client.Envelope;
/**
* @author Jinkai.Ma
* @author Jiaqi Feng
* @author HyunGil Jeong
*/
-public class ConsumerHandleDeliveryInterceptor extends AsyncContextSpanEventSimpleAroundInterceptor {
+public class ConsumerHandleDeliveryInterceptor implements AroundInterceptor {
+
+ private final PLogger logger = PLoggerFactory.getLogger(getClass());
+ private final boolean isDebug = logger.isDebugEnabled();
+ private static final String ASYNC_TRACE_SCOPE = AsyncContext.ASYNC_TRACE_SCOPE;
+
+ private final MethodDescriptor methodDescriptor;
public ConsumerHandleDeliveryInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
- super(traceContext, methodDescriptor);
+ if (traceContext == null) {
+ throw new NullPointerException("traceContext must not be null");
+ }
+ if (methodDescriptor == null) {
+ throw new NullPointerException("methodDescriptor must not be null");
+ }
+ this.methodDescriptor = methodDescriptor;
}
@Override
- protected void doInBeforeTrace(SpanEventRecorder recorder, AsyncContext asyncContext, Object target, Object[] args) {
+ public void before(Object target, Object[] args) {
+ if (!validate(target, args)) {
+ return;
+ }
+ final AsyncContext asyncContext = AsyncContextAccessorUtils.getAsyncContext(args[1]);
+ if (asyncContext == null) {
+ return;
+ }
+
+ final Trace trace = getAsyncTrace(asyncContext);
+ if (trace == null) {
+ return;
+ }
+ if (isDebug) {
+ logger.beforeInterceptor(target, args);
+ }
+
+ // entry scope.
+ entryAsyncTraceScope(trace);
+
+ try {
+ // trace event for default & async
+ final SpanEventRecorder recorder = trace.traceBlockBegin();
+ recorder.recordServiceType(RabbitMQClientConstants.RABBITMQ_CLIENT_INTERNAL);
+ recorder.recordApi(methodDescriptor);
+ } catch (Throwable t) {
+ if (logger.isWarnEnabled()) {
+ logger.warn("BEFORE error.", t);
+ }
+ }
}
@Override
- protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
- recorder.recordApi(methodDescriptor);
- recorder.recordServiceType(RabbitMQClientConstants.RABBITMQ_CLIENT_INTERNAL);
- recorder.recordException(throwable);
+ public void after(Object target, Object[] args, Object result, Throwable throwable) {
+ if (!validate(target, args)) {
+ return;
+ }
+ final AsyncContext asyncContext = AsyncContextAccessorUtils.getAsyncContext(args[1]);
+ if (asyncContext == null) {
+ return;
+ }
+
+ final Trace trace = asyncContext.currentAsyncTraceObject();
+ if (trace == null) {
+ return;
+ }
+
+ if (isDebug) {
+ logger.afterInterceptor(target, args, result, throwable);
+ }
+
+ // leave scope
+ if (!leaveAsyncTraceScope(trace)) {
+ if (logger.isWarnEnabled()) {
+ logger.warn("Failed to leave scope of async trace {}.", trace);
+ }
+ // delete unstable trace
+ deleteAsyncContext(trace, asyncContext);
+ return;
+ }
+
+ try {
+ final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
+ if (throwable != null) {
+ recorder.recordException(throwable);
+ }
+ } catch (Throwable t) {
+ if (logger.isWarnEnabled()) {
+ logger.warn("AFTER error.", t);
+ }
+ } finally {
+ trace.traceBlockEnd();
+ if (isAsyncTraceDestination(trace)) {
+ deleteAsyncContext(trace, asyncContext);
+ }
+ }
+ }
+
+ private boolean validate(Object target, Object[] args) {
+ if (!(target instanceof Consumer)) {
+ return false;
+ }
+ if (args == null || args.length < 2) {
+ return false;
+ }
+ if (!(args[1] instanceof Envelope)) {
+ return false;
+ }
+ if (!(args[1] instanceof AsyncContextAccessor)) {
+ if (isDebug) {
+ logger.debug("Invalid args[1] object. Need accessor({}).", AsyncContextAccessor.class.getName());
+ }
+ return false;
+ }
+ return true;
+ }
+
+ private Trace getAsyncTrace(AsyncContext asyncContext) {
+ final Trace trace = asyncContext.continueAsyncTraceObject();
+ if (trace == null) {
+ if (logger.isWarnEnabled()) {
+ logger.warn("Failed to continue async trace. 'result is null'");
+ }
+ return null;
+ }
+ if (isDebug) {
+ logger.debug("getAsyncTrace() trace {}, asyncContext={}", trace, asyncContext);
+ }
+ return trace;
+ }
+
+ private void deleteAsyncContext(Trace trace, AsyncContext asyncContext) {
+ if (isDebug) {
+ logger.debug("Delete async trace {}.", trace);
+ }
+ trace.close();
+ asyncContext.close();
+ }
+
+ private void entryAsyncTraceScope(final Trace trace) {
+ final TraceScope scope = trace.getScope(ASYNC_TRACE_SCOPE);
+ if (scope != null) {
+ scope.tryEnter();
+ }
+ }
+
+ private boolean leaveAsyncTraceScope(final Trace trace) {
+ final TraceScope scope = trace.getScope(ASYNC_TRACE_SCOPE);
+ if (scope != null) {
+ if (scope.canLeave()) {
+ scope.leave();
+ } else {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean isAsyncTraceDestination(final Trace trace) {
+ if (!trace.isAsync()) {
+ return false;
+ }
+ final TraceScope scope = trace.getScope(ASYNC_TRACE_SCOPE);
+ return scope != null && !scope.isActive();
}
}
diff --git a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/RabbitMQConsumerDispatchInterceptor.java b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/RabbitMQConsumerDispatchInterceptor.java
index 078c3763b665..6089e1d94757 100644
--- a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/RabbitMQConsumerDispatchInterceptor.java
+++ b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/RabbitMQConsumerDispatchInterceptor.java
@@ -92,10 +92,10 @@ public void before(Object target, Object[] args) {
}
SpanEventRecorder recorder = trace.traceBlockBegin();
recorder.recordServiceType(RabbitMQClientConstants.RABBITMQ_CLIENT_INTERNAL);
- // args[0] would be com.rabbitmq.client.Consumer, implementing AsyncContextAccessor via plugin
- if (args[0] instanceof AsyncContextAccessor) {
+ // args[2] would be com.rabbitmq.client.Envelope, implementing AsyncContextAccessor via plugin
+ if (args[2] instanceof AsyncContextAccessor) {
AsyncContext asyncContext = recorder.recordNextAsyncContext();
- ((AsyncContextAccessor) args[0])._$PINPOINT$_setAsyncContext(asyncContext);
+ ((AsyncContextAccessor) args[2])._$PINPOINT$_setAsyncContext(asyncContext);
}
} catch (Throwable th) {
if (logger.isWarnEnabled()) {
| diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/RabbitMQTestRunner.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/RabbitMQTestRunner.java
index 26216d166445..94b63e549607 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/RabbitMQTestRunner.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/RabbitMQTestRunner.java
@@ -36,16 +36,18 @@
import org.junit.Assert;
import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
import java.util.concurrent.TimeUnit;
-
/**
* @author Jiaqi Feng
* @author HyunGil Jeong
*/
class RabbitMQTestRunner {
- private final ConnectionFactory connectionFactory;
+ private static final Random RANDOM = new Random();
RabbitMQTestRunner(ConnectionFactory connectionFactory) {
if (connectionFactory == null) {
@@ -54,7 +56,14 @@ class RabbitMQTestRunner {
this.connectionFactory = connectionFactory;
}
+ private final ConnectionFactory connectionFactory;
+
void runPushTest() throws Exception {
+ int numMessages = RANDOM.nextInt(10) + 1;
+ runPushTest(numMessages);
+ }
+
+ void runPushTest(int numMessages) throws Exception {
final String message = "hello rabbit mq";
@@ -66,13 +75,15 @@ void runPushTest() throws Exception {
producerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PUSH, false, false, false, null);
producerChannel.queueBind(RabbitMQTestConstants.QUEUE_PUSH, RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PUSH);
- AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
- producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PUSH, false, false, builder.appId("test").build(), message.getBytes());
+ for (int i = 0; i < numMessages; i++) {
+ AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
+ producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PUSH, false, false, builder.appId("test").build(), message.getBytes());
+ }
producerChannel.close();
producerConnection.close();
- //comsumer side
+ // consumer side
final Connection consumerConnection = connectionFactory.newConnection();
final Channel consumerChannel = consumerConnection.createChannel();
final String remoteAddress = consumerConnection.getAddress().getHostAddress() + ":" + consumerConnection.getPort();
@@ -82,17 +93,26 @@ void runPushTest() throws Exception {
TestConsumer<String> consumer = new TestConsumer<String>(consumerChannel, MessageConverter.FOR_TEST);
consumerChannel.basicConsume(RabbitMQTestConstants.QUEUE_PUSH, true, consumer);
- // wait consumer
- Assert.assertEquals(message, consumer.getMessage(10, TimeUnit.SECONDS));
+ List<String> actualMessages = new ArrayList<String>(numMessages);
+ for (int i = 0; i < numMessages; i++) {
+ actualMessages.add(consumer.getMessage(10, TimeUnit.SECONDS));
+ }
+
+ Assert.assertEquals(numMessages, actualMessages.size());
+ for (String actualMessage : actualMessages) {
+ Assert.assertEquals(message, actualMessage);
+ }
consumerChannel.close();
consumerConnection.close();
PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
// Wait till all traces are recorded (consumer traces are recorded from another thread)
- awaitAndVerifyTraceCount(verifier, 6, 5000L);
+ int expectedTraceCountPerMessage = 6;
+ awaitAndVerifyTraceCount(verifier, expectedTraceCountPerMessage * numMessages, 5000L);
verifier.printCache();
+
Class<?> producerChannelClass = producerChannel.getClass();
Method channelBasicPublish = producerChannelClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
ExpectedTrace channelBasicPublishTrace = Expectations.event(
@@ -128,13 +148,17 @@ void runPushTest() throws Exception {
ExpectedTrace markTrace = Expectations.event(
ServiceType.INTERNAL_METHOD.getName(),
propagationMarkerMark);
- verifier.verifyTrace(
- channelBasicPublishTrace,
- rabbitMqConsumerInvocationTrace,
- consumerDispatcherHandleDeliveryTrace,
- asynchronousInvocationTrace,
- consumerHandleDeliveryTrace,
- markTrace);
+
+ for (int i = 0; i < numMessages; i++) {
+ verifier.verifyDiscreteTrace(channelBasicPublishTrace);
+ verifier.verifyDiscreteTrace(
+ rabbitMqConsumerInvocationTrace,
+ Expectations.async(
+ consumerDispatcherHandleDeliveryTrace,
+ asynchronousInvocationTrace,
+ consumerHandleDeliveryTrace,
+ markTrace));
+ }
verifier.verifyTraceCount(0);
}
| train | val | "2018-04-13T10:49:46" | "2018-04-11T09:10:36Z" | Xylus | test |
pinpoint-apm/pinpoint/4069_4070 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4069 | pinpoint-apm/pinpoint/4070 | [
"keyword_pr_to_issue"
] | 1d63dac556ea3e4ac135e908cdedd3a911e9fe37 | cedacc534a60b3a86dac7bbceeb04b69bf27df19 | [
"Reopening to update maven wrapper as well to 0.4.0."
] | [] | "2018-04-27T08:44:47Z" | [] | Change required maven version to 3.5.3 | #### Description
Have maven wrapper use 3.5.3 binary. | [
".mvn/wrapper/maven-wrapper.properties"
] | [
".mvn/wrapper/maven-wrapper.properties"
] | [] | diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties
index 6637cedb28e9..33232336d09e 100644
--- a/.mvn/wrapper/maven-wrapper.properties
+++ b/.mvn/wrapper/maven-wrapper.properties
@@ -1,1 +1,1 @@
-distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
\ No newline at end of file
+distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip
\ No newline at end of file
| null | train | val | "2018-04-27T10:29:23" | "2018-04-27T08:32:15Z" | Xylus | test |
pinpoint-apm/pinpoint/4069_4077 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4069 | pinpoint-apm/pinpoint/4077 | [
"keyword_pr_to_issue"
] | cedacc534a60b3a86dac7bbceeb04b69bf27df19 | 9107256ab4354b86e962a690a3f1167431585786 | [
"Reopening to update maven wrapper as well to 0.4.0."
] | [] | "2018-04-30T02:47:48Z" | [] | Change required maven version to 3.5.3 | #### Description
Have maven wrapper use 3.5.3 binary. | [
".mvn/wrapper/maven-wrapper.properties",
"mvnw",
"mvnw.cmd"
] | [
".mvn/wrapper/MavenWrapperDownloader.java",
".mvn/wrapper/maven-wrapper.properties",
"mvnw",
"mvnw.cmd"
] | [] | diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java
new file mode 100644
index 000000000000..d475a89ce1d2
--- /dev/null
+++ b/.mvn/wrapper/MavenWrapperDownloader.java
@@ -0,0 +1,110 @@
+/*
+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.
+*/
+
+import java.net.*;
+import java.io.*;
+import java.nio.channels.*;
+import java.util.Properties;
+
+public class MavenWrapperDownloader {
+
+ /**
+ * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
+ */
+ private static final String DEFAULT_DOWNLOAD_URL =
+ "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar";
+
+ /**
+ * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
+ * use instead of the default one.
+ */
+ private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
+ ".mvn/wrapper/maven-wrapper.properties";
+
+ /**
+ * Path where the maven-wrapper.jar will be saved to.
+ */
+ private static final String MAVEN_WRAPPER_JAR_PATH =
+ ".mvn/wrapper/maven-wrapper.jar";
+
+ /**
+ * Name of the property which should be used to override the default download url for the wrapper.
+ */
+ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
+
+ public static void main(String args[]) {
+ System.out.println("- Downloader started");
+ File baseDirectory = new File(args[0]);
+ System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
+
+ // If the maven-wrapper.properties exists, read it and check if it contains a custom
+ // wrapperUrl parameter.
+ File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
+ String url = DEFAULT_DOWNLOAD_URL;
+ if(mavenWrapperPropertyFile.exists()) {
+ FileInputStream mavenWrapperPropertyFileInputStream = null;
+ try {
+ mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
+ Properties mavenWrapperProperties = new Properties();
+ mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
+ url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
+ } catch (IOException e) {
+ System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
+ } finally {
+ try {
+ if(mavenWrapperPropertyFileInputStream != null) {
+ mavenWrapperPropertyFileInputStream.close();
+ }
+ } catch (IOException e) {
+ // Ignore ...
+ }
+ }
+ }
+ System.out.println("- Downloading from: : " + url);
+
+ File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
+ if(!outputFile.getParentFile().exists()) {
+ if(!outputFile.getParentFile().mkdirs()) {
+ System.out.println(
+ "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
+ }
+ }
+ System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
+ try {
+ downloadFileFromURL(url, outputFile);
+ System.out.println("Done");
+ System.exit(0);
+ } catch (Throwable e) {
+ System.out.println("- Error downloading");
+ e.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ private static void downloadFileFromURL(String urlString, File destination) throws Exception {
+ URL website = new URL(urlString);
+ ReadableByteChannel rbc;
+ rbc = Channels.newChannel(website.openStream());
+ FileOutputStream fos = new FileOutputStream(destination);
+ fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
+ fos.close();
+ rbc.close();
+ }
+
+}
diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties
index 33232336d09e..42fa4da21999 100644
--- a/.mvn/wrapper/maven-wrapper.properties
+++ b/.mvn/wrapper/maven-wrapper.properties
@@ -1,1 +1,1 @@
-distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip
\ No newline at end of file
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip
\ No newline at end of file
diff --git a/mvnw b/mvnw
index 6ecc150ae0a5..961a82500138 100755
--- a/mvnw
+++ b/mvnw
@@ -54,38 +54,16 @@ case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
- #
- # Look for the Apple JDKs first to preserve the existing behaviour, and then look
- # for the new JDKs provided by Oracle.
- #
- if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
- #
- # Oracle JDKs
- #
- export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=`/usr/libexec/java_home`
- fi
- ;;
+ # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
+ # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
+ if [ -z "$JAVA_HOME" ]; then
+ if [ -x "/usr/libexec/java_home" ]; then
+ export JAVA_HOME="`/usr/libexec/java_home`"
+ else
+ export JAVA_HOME="/Library/Java/Home"
+ fi
+ fi
+ ;;
esac
if [ -z "$JAVA_HOME" ] ; then
@@ -130,7 +108,7 @@ if $cygwin ; then
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
-# For Migwn, ensure paths are in UNIX format before anything is touched
+# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
@@ -187,14 +165,25 @@ CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
- local basedir=$(pwd)
- local wdir=$(pwd)
+
+ if [ -z "$1" ]
+ then
+ echo "Path not specified to find_maven_basedir"
+ return 1
+ fi
+
+ basedir="$1"
+ wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
- wdir=$(cd "$wdir/.."; pwd)
+ # workaround for JBEAP-8937 (on Solaris 10/Sparc)
+ if [ -d "${wdir}" ]; then
+ wdir=`cd "$wdir/.."; pwd`
+ fi
+ # end of workaround
done
echo "${basedir}"
}
@@ -206,7 +195,74 @@ concat_lines() {
fi
}
-export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
+BASE_DIR=`find_maven_basedir "$(pwd)"`
+if [ -z "$BASE_DIR" ]; then
+ exit 1;
+fi
+
+##########################################################################################
+# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+# This allows using the maven wrapper in projects that prohibit checking in binary data.
+##########################################################################################
+if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found .mvn/wrapper/maven-wrapper.jar"
+ fi
+else
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
+ fi
+ jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar"
+ while IFS="=" read key value; do
+ case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
+ esac
+ done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Downloading from: $jarUrl"
+ fi
+ wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
+
+ if command -v wget > /dev/null; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found wget ... using wget"
+ fi
+ wget "$jarUrl" -O "$wrapperJarPath"
+ elif command -v curl > /dev/null; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found curl ... using curl"
+ fi
+ curl -o "$wrapperJarPath" "$jarUrl"
+ else
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Falling back to using Java to download"
+ fi
+ javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
+ if [ -e "$javaClass" ]; then
+ if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo " - Compiling MavenWrapperDownloader.java ..."
+ fi
+ # Compiling the Java class
+ ("$JAVA_HOME/bin/javac" "$javaClass")
+ fi
+ if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+ # Running the downloader
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo " - Running MavenWrapperDownloader.java ..."
+ fi
+ ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
+ fi
+ fi
+ fi
+fi
+##########################################################################################
+# End of extension
+##########################################################################################
+
+export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
+if [ "$MVNW_VERBOSE" = true ]; then
+ echo $MAVEN_PROJECTBASEDIR
+fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
@@ -221,14 +277,8 @@ if $cygwin; then
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
-# Provide a "standardized" way to retrieve the CLI args that will
-# work with both Windows and non-Windows executions.
-MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
-export MAVEN_CMD_LINE_ARGS
-
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
-# avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in $@
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
diff --git a/mvnw.cmd b/mvnw.cmd
index 6936c3e90d97..830073a17e4e 100644
--- a/mvnw.cmd
+++ b/mvnw.cmd
@@ -35,6 +35,8 @@
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
+@REM set title of command window
+title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@@ -80,8 +82,6 @@ goto error
:init
-set MAVEN_CMD_LINE_ARGS=%MAVEN_CONFIG% %*
-
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
@@ -117,10 +117,26 @@ for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do s
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
-
-set WRAPPER_JAR=""%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar""
+set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar"
+FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
+ IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
+)
+
+@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
+if exist %WRAPPER_JAR% (
+ echo Found %WRAPPER_JAR%
+) else (
+ echo Couldn't find %WRAPPER_JAR%, downloading it ...
+ echo Downloading from: %DOWNLOAD_URL%
+ powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
+ echo Finished downloading %WRAPPER_JAR%
+)
+@REM End of extension
+
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
| null | train | val | "2018-04-27T10:44:56" | "2018-04-27T08:32:15Z" | Xylus | test |
pinpoint-apm/pinpoint/4088_4105 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4088 | pinpoint-apm/pinpoint/4105 | [
"keyword_pr_to_issue"
] | 03bf606f73557867e1bb01c05b4760ceb8357031 | d8ea8afa28818b6c9260752f06a32c56abf66cb0 | [] | [] | "2018-05-08T08:58:23Z" | [
"enhancement"
] | Refactor hbase connection and table/admin factories | #### Description
**Admin** instances are light and not thread-safe, so it would make sense to obtain it whenever it is needed from hbase **Connection** (of which it's creation is a heavy-weight operation but thread-safe).
Since hbase **Table** creation also requires a connection, it would make sense to share a single connection between for **Table** and **Admin** factories. | [
"collector/src/main/resources/applicationContext-hbase.xml",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/PooledHTableFactory.java",
"flink/src/main/resources/applicationContext-hbase.xml",
"web/src/main/resources/applicationContext-hbase.xml"
] | [
"collector/src/main/resources/applicationContext-hbase.xml",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AdminFactory.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ConnectionFactoryBean.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseAdminFactory.java",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTableFactory.java",
"flink/src/main/resources/applicationContext-hbase.xml",
"web/src/main/resources/applicationContext-hbase.xml"
] | [
"commons-hbase/src/test/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2IT.java"
] | diff --git a/collector/src/main/resources/applicationContext-hbase.xml b/collector/src/main/resources/applicationContext-hbase.xml
index 0918686b2431..64f9860757f0 100644
--- a/collector/src/main/resources/applicationContext-hbase.xml
+++ b/collector/src/main/resources/applicationContext-hbase.xml
@@ -45,15 +45,19 @@
<property name="preStartAllCoreThreads" value="true"/>
</bean>
- <bean id="connectionFactory" class="com.navercorp.pinpoint.common.hbase.PooledHTableFactory">
+ <bean id="connectionFactory" class="com.navercorp.pinpoint.common.hbase.ConnectionFactoryBean">
<constructor-arg type="org.apache.hadoop.conf.Configuration" ref="hbaseConfiguration"/>
<constructor-arg type="java.util.concurrent.ExecutorService" ref="hbaseThreadPool"/>
</bean>
+ <bean id="hbaseTableFactory" class="com.navercorp.pinpoint.common.hbase.HbaseTableFactory">
+ <constructor-arg ref="connectionFactory"/>
+ </bean>
+
<bean class="org.apache.hadoop.util.ShutdownHookManagerProxy"/>
<bean id="asyncOperation" class="com.navercorp.pinpoint.common.hbase.HBaseAsyncOperationFactory" factory-method="create">
- <constructor-arg type="org.apache.hadoop.hbase.client.Connection" value="#{connectionFactory.getConnection()}"/>
+ <constructor-arg type="org.apache.hadoop.hbase.client.Connection" ref="connectionFactory"/>
<constructor-arg type="org.apache.hadoop.conf.Configuration" ref="hbaseConfiguration"/>
</bean>
@@ -63,12 +67,16 @@
<bean id="hbaseTemplate" class="com.navercorp.pinpoint.common.hbase.HbaseTemplate2" destroy-method="destroy">
<property name="configuration" ref="hbaseConfiguration"/>
- <property name="tableFactory" ref="connectionFactory"/>
+ <property name="tableFactory" ref="hbaseTableFactory"/>
<property name="asyncOperation" ref="asyncOperation"/>
</bean>
- <bean id="hBaseAdminTemplate" class="com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate" destroy-method="close">
- <constructor-arg ref="hbaseConfiguration" index="0"/>
+ <bean id="hbaseAdminFactory" class="com.navercorp.pinpoint.common.hbase.HbaseAdminFactory">
+ <constructor-arg ref="connectionFactory"/>
+ </bean>
+
+ <bean id="hbaseAdminTemplate" class="com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate">
+ <constructor-arg ref="hbaseAdminFactory"/>
</bean>
<bean id="applicationTraceIndexDistributor" class="com.sematext.hbase.wd.RowKeyDistributorByHashPrefix">
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AdminFactory.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AdminFactory.java
new file mode 100644
index 000000000000..a9785ad374b8
--- /dev/null
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/AdminFactory.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.common.hbase;
+
+import org.apache.hadoop.hbase.client.Admin;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface AdminFactory {
+
+ Admin getAdmin();
+
+ void releaseAdmin(Admin admin);
+
+}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ConnectionFactoryBean.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ConnectionFactoryBean.java
new file mode 100644
index 000000000000..8f922055b787
--- /dev/null
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/ConnectionFactoryBean.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.common.hbase;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.client.Connection;
+import org.apache.hadoop.hbase.client.ConnectionFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.DisposableBean;
+import org.springframework.beans.factory.FactoryBean;
+
+import java.io.IOException;
+import java.util.Objects;
+import java.util.concurrent.ExecutorService;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class ConnectionFactoryBean implements FactoryBean<Connection>, DisposableBean {
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ private final Connection connection;
+
+ public ConnectionFactoryBean(Configuration configuration) {
+ Objects.requireNonNull(configuration, " must not be null");
+ try {
+ connection = ConnectionFactory.createConnection(configuration);
+ } catch (IOException e) {
+ throw new HbaseSystemException(e);
+ }
+ }
+
+ public ConnectionFactoryBean(Configuration configuration, ExecutorService executorService) {
+ Objects.requireNonNull(configuration, "configuration must not be null");
+ Objects.requireNonNull(executorService, "executorService must not be null");
+ try {
+ connection = ConnectionFactory.createConnection(configuration, executorService);
+ } catch (IOException e) {
+ throw new HbaseSystemException(e);
+ }
+ }
+
+ @Override
+ public Connection getObject() throws Exception {
+ return connection;
+ }
+
+ @Override
+ public Class<?> getObjectType() {
+ if (connection == null) {
+ return Connection.class;
+ }
+ return connection.getClass();
+ }
+
+ @Override
+ public boolean isSingleton() {
+ return true;
+ }
+
+ @Override
+ public void destroy() throws Exception {
+ logger.info("Hbase Connection destroy()");
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (IOException e) {
+ logger.warn("Hbase Connection.close() error: " + e.getMessage(), e);
+ }
+ }
+ }
+}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java
index 1294c329cc54..da4d5b925337 100644
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HBaseAdminTemplate.java
@@ -17,79 +17,76 @@
package com.navercorp.pinpoint.common.hbase;
import java.io.IOException;
+import java.util.Objects;
-import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
-import org.apache.hadoop.hbase.client.Connection;
-import org.apache.hadoop.hbase.client.ConnectionFactory;
/**
* @author emeroad
+ * @author HyunGil Jeong
*/
public class HBaseAdminTemplate {
- private final Admin admin;
- private final Connection connection;
+ private final AdminFactory adminFactory;
- public HBaseAdminTemplate(Configuration configuration) {
- try {
- connection = ConnectionFactory.createConnection(configuration);
- admin = connection.getAdmin();
- } catch (Exception e) {
- throw new HbaseSystemException(e);
- }
+ public HBaseAdminTemplate(AdminFactory adminFactory) {
+ this.adminFactory = Objects.requireNonNull(adminFactory, "adminFactory must not be null");
}
public boolean createTableIfNotExist(HTableDescriptor htd) {
+ Admin admin = adminFactory.getAdmin();
try {
- if (!admin.tableExists(htd.getTableName())) {
- this.admin.createTable(htd);
+ TableName tableName = htd.getTableName();
+ if (!admin.tableExists(tableName)) {
+ admin.createTable(htd);
return true;
}
return false;
} catch (IOException e) {
throw new HbaseSystemException(e);
+ } finally {
+ adminFactory.releaseAdmin(admin);
}
}
public boolean tableExists(TableName tableName) {
+ Admin admin = adminFactory.getAdmin();
try {
return admin.tableExists(tableName);
} catch (IOException e) {
throw new HbaseSystemException(e);
+ } finally {
+ adminFactory.releaseAdmin(admin);
}
}
public boolean dropTableIfExist(TableName tableName) {
+ Admin admin = adminFactory.getAdmin();
try {
if (admin.tableExists(tableName)) {
- this.admin.disableTable(tableName);
- this.admin.deleteTable(tableName);
+ admin.disableTable(tableName);
+ admin.deleteTable(tableName);
return true;
}
return false;
} catch (IOException e) {
throw new HbaseSystemException(e);
+ } finally {
+ adminFactory.releaseAdmin(admin);
}
}
public void dropTable(TableName tableName) {
+ Admin admin = adminFactory.getAdmin();
try {
- this.admin.disableTable(tableName);
- this.admin.deleteTable(tableName);
- } catch (IOException e) {
- throw new HbaseSystemException(e);
- }
- }
-
- public void close() {
- try {
- this.admin.close();
- this.connection.close();
+ admin.disableTable(tableName);
+ admin.deleteTable(tableName);
} catch (IOException e) {
throw new HbaseSystemException(e);
+ } finally {
+ adminFactory.releaseAdmin(admin);
}
}
}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseAdminFactory.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseAdminFactory.java
new file mode 100644
index 000000000000..cdb2b87c779f
--- /dev/null
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseAdminFactory.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.common.hbase;
+
+import org.apache.hadoop.hbase.client.Admin;
+import org.apache.hadoop.hbase.client.Connection;
+
+import java.io.IOException;
+import java.util.Objects;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class HbaseAdminFactory implements AdminFactory {
+
+ private final Connection connection;
+
+ public HbaseAdminFactory(Connection connection) {
+ this.connection = Objects.requireNonNull(connection, "connection must not be null");
+ }
+
+ @Override
+ public Admin getAdmin() {
+ try {
+ return connection.getAdmin();
+ } catch (IOException e) {
+ throw new HbaseSystemException(e);
+ }
+ }
+
+ @Override
+ public void releaseAdmin(Admin admin) {
+ if (admin == null) {
+ return;
+ }
+ try {
+ admin.close();
+ } catch (IOException e) {
+ throw new HbaseSystemException(e);
+ }
+ }
+}
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/PooledHTableFactory.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTableFactory.java
similarity index 55%
rename from commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/PooledHTableFactory.java
rename to commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTableFactory.java
index 5cb3e591ddf3..cecd54e18daa 100644
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/PooledHTableFactory.java
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTableFactory.java
@@ -16,14 +16,9 @@
package com.navercorp.pinpoint.common.hbase;
-import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
-import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.DisposableBean;
import java.io.IOException;
import java.util.Objects;
@@ -32,35 +27,21 @@
/**
* HTableInterfaceFactory based on HTablePool.
* @author emeroad
- * @autor minwoo.jung
+ * @author minwoo.jung
+ * @author HyunGil Jeong
*/
-public class PooledHTableFactory implements TableFactory, DisposableBean {
+public class HbaseTableFactory implements TableFactory {
- private final Logger logger = LoggerFactory.getLogger(this.getClass());
-
- private final ExecutorService executor;
private final Connection connection;
- public PooledHTableFactory(Configuration config, ExecutorService executor) {
- Objects.requireNonNull(config, "config must not be null");
- this.executor = Objects.requireNonNull(executor, "executor must not be null");
-
- try {
- this.connection = ConnectionFactory.createConnection(config, executor);
- } catch (IOException e) {
- throw new HbaseSystemException(e);
- }
- }
-
- public Connection getConnection() {
- return connection;
+ public HbaseTableFactory(Connection connection) {
+ this.connection = Objects.requireNonNull(connection, "connection must not be null");
}
-
@Override
public Table getTable(TableName tableName) {
try {
- return connection.getTable(tableName, executor);
+ return connection.getTable(tableName);
} catch (IOException e) {
throw new HbaseSystemException(e);
}
@@ -87,18 +68,4 @@ public void releaseTable(Table table) {
throw new HbaseSystemException(ex);
}
}
-
-
- @Override
- public void destroy() throws Exception {
- logger.info("PooledHTableFactory.destroy()");
-
- if (connection != null) {
- try {
- this.connection.close();
- } catch (IOException ex) {
- logger.warn("Connection.close() error:" + ex.getMessage(), ex);
- }
- }
- }
}
diff --git a/flink/src/main/resources/applicationContext-hbase.xml b/flink/src/main/resources/applicationContext-hbase.xml
index 9296393004b6..1a7d83b447b9 100644
--- a/flink/src/main/resources/applicationContext-hbase.xml
+++ b/flink/src/main/resources/applicationContext-hbase.xml
@@ -57,13 +57,17 @@
<property name="preStartAllCoreThreads" value="true"/>
</bean>
- <bean id="connectionFactory" class="com.navercorp.pinpoint.common.hbase.PooledHTableFactory">
+ <bean id="connectionFactory" class="com.navercorp.pinpoint.common.hbase.ConnectionFactoryBean">
<constructor-arg type="org.apache.hadoop.conf.Configuration" ref="hbaseConfiguration"/>
<constructor-arg type="java.util.concurrent.ExecutorService" ref="hbaseThreadPool"/>
</bean>
+ <bean id="hbaseTableFactory" class="com.navercorp.pinpoint.common.hbase.HbaseTableFactory">
+ <constructor-arg ref="connectionFactory"/>
+ </bean>
+
<bean id="asyncOperation" class="com.navercorp.pinpoint.common.hbase.HBaseAsyncOperationFactory" factory-method="create">
- <constructor-arg value="#{connectionFactory.getConnection()}"/>
+ <constructor-arg ref="connectionFactory"/>
<constructor-arg ref="hbaseConfiguration"/>
</bean>
@@ -73,12 +77,16 @@
<bean id="hbaseTemplate" class="com.navercorp.pinpoint.common.hbase.HbaseTemplate2" destroy-method="destroy">
<property name="configuration" ref="hbaseConfiguration"/>
- <property name="tableFactory" ref="connectionFactory"/>
+ <property name="tableFactory" ref="hbaseTableFactory"/>
<property name="asyncOperation" ref="asyncOperation"/>
</bean>
- <bean id="hBaseAdminTemplate" class="com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate" destroy-method="close">
- <constructor-arg ref="hbaseConfiguration" index="0"></constructor-arg>
+ <bean id="hbaseAdminFactory" class="com.navercorp.pinpoint.common.hbase.HbaseAdminFactory">
+ <constructor-arg ref="connectionFactory"/>
+ </bean>
+
+ <bean id="hbaseAdminTemplate" class="com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate">
+ <constructor-arg ref="hbaseAdminFactory"/>
</bean>
<bean id="tableNameProvider" class="com.navercorp.pinpoint.common.hbase.HbaseTableNameProvider">
diff --git a/web/src/main/resources/applicationContext-hbase.xml b/web/src/main/resources/applicationContext-hbase.xml
index 798e3111b9fe..971906d9be0a 100644
--- a/web/src/main/resources/applicationContext-hbase.xml
+++ b/web/src/main/resources/applicationContext-hbase.xml
@@ -44,21 +44,29 @@
<property name="preStartAllCoreThreads" value="true"/>
</bean>
- <bean id="connectionFactory" class="com.navercorp.pinpoint.common.hbase.PooledHTableFactory">
- <constructor-arg ref="hbaseConfiguration"/>
- <constructor-arg ref="hbaseThreadPool"/>
+ <bean id="connectionFactory" class="com.navercorp.pinpoint.common.hbase.ConnectionFactoryBean">
+ <constructor-arg type="org.apache.hadoop.conf.Configuration" ref="hbaseConfiguration"/>
+ <constructor-arg type="java.util.concurrent.ExecutorService" ref="hbaseThreadPool"/>
+ </bean>
+
+ <bean id="hbaseTableFactory" class="com.navercorp.pinpoint.common.hbase.HbaseTableFactory">
+ <constructor-arg ref="connectionFactory"/>
</bean>
<bean id="hbaseTemplate" class="com.navercorp.pinpoint.common.hbase.HbaseTemplate2">
<property name="configuration" ref="hbaseConfiguration"/>
- <property name="tableFactory" ref="connectionFactory"/>
+ <property name="tableFactory" ref="hbaseTableFactory"/>
<property name="enableParallelScan" value="${hbase.client.parallel.scan.enable:false}"/>
<property name="maxThreads" value="${hbase.client.parallel.scan.maxthreads:16}"/>
<property name="maxThreadsPerParallelScan" value="${hbase.client.parallel.scan.maxthreadsperscan:4}"/>
</bean>
-
- <bean id="hBaseAdminTemplate" class="com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate" destroy-method="close">
- <constructor-arg ref="hbaseConfiguration" index="0"/>
+
+ <bean id="hbaseAdminFactory" class="com.navercorp.pinpoint.common.hbase.HbaseAdminFactory">
+ <constructor-arg ref="connectionFactory"/>
+ </bean>
+
+ <bean id="hbaseAdminTemplate" class="com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate">
+ <constructor-arg ref="hbaseAdminFactory"/>
</bean>
<bean class="org.apache.hadoop.util.ShutdownHookManagerProxy"/>
| diff --git a/commons-hbase/src/test/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2IT.java b/commons-hbase/src/test/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2IT.java
index f20a2d159310..9ad281f14e15 100644
--- a/commons-hbase/src/test/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2IT.java
+++ b/commons-hbase/src/test/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2IT.java
@@ -18,13 +18,13 @@
import java.io.IOException;
import java.util.Properties;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotFoundException;
+import org.apache.hadoop.hbase.client.Connection;
+import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException;
import org.junit.AfterClass;
import org.junit.Assert;
@@ -40,7 +40,7 @@
* @author minwoo.jung
*/
public class HbaseTemplate2IT {
- private static ExecutorService executorService;
+ private static Connection connection;
private static HbaseTemplate2 hbaseTemplate2;
@BeforeClass
@@ -51,10 +51,10 @@ public static void beforeClass() throws IOException {
cfg.set("hbase.zookeeper.quorum", properties.getProperty("hbase.client.host"));
cfg.set("hbase.zookeeper.property.clientPort", properties.getProperty("hbase.client.port"));
- executorService = Executors.newFixedThreadPool(10);
+ connection = ConnectionFactory.createConnection(cfg);
hbaseTemplate2 = new HbaseTemplate2();
hbaseTemplate2.setConfiguration(cfg);
- hbaseTemplate2.setTableFactory(new PooledHTableFactory(cfg, executorService));
+ hbaseTemplate2.setTableFactory(new HbaseTableFactory(connection));
hbaseTemplate2.afterPropertiesSet();
}
@@ -63,8 +63,8 @@ public static void afterClass() throws Exception {
if (hbaseTemplate2 != null) {
hbaseTemplate2.destroy();
}
- if (executorService != null) {
- executorService.shutdown();
+ if (connection != null) {
+ connection.close();
}
}
| train | val | "2018-05-08T08:58:33" | "2018-05-03T02:50:33Z" | Xylus | test |
pinpoint-apm/pinpoint/4113_4114 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4113 | pinpoint-apm/pinpoint/4114 | [
"keyword_pr_to_issue"
] | 78ad4a8dc17b369347bcf1a32e3c7c0554e71264 | 2f68bafe50e76381d04285f41b2c8acc6d3b26d7 | [] | [] | "2018-05-10T06:30:02Z" | [
"enhancement",
"module:plugin"
] | Trace https calls made via JDK http connector | #### Description
Https calls are not being traced when using JDK http connector ([details](https://github.com/naver/pinpoint/issues/4072#issuecomment-387960147)). | [
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java"
] | [
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java"
] | [] | diff --git a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java
index ffaf679c4977..c842f96f8851 100644
--- a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java
+++ b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java
@@ -63,6 +63,19 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
return target.toBytecode();
}
});
+
+ transformTemplate.transform("sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection", new TransformCallback() {
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+ final InstrumentMethod connectMethod = target.getDeclaredMethod("connect");
+ if (connectMethod == null) {
+ return null;
+ }
+ connectMethod.addScopedInterceptor("com.navercorp.pinpoint.plugin.jdk.http.interceptor.HttpURLConnectionInterceptor", "HttpURLConnection");
+ return target.toBytecode();
+ }
+ });
}
@Override
| null | test | val | "2018-05-09T10:20:07" | "2018-05-10T06:18:05Z" | Xylus | test |
pinpoint-apm/pinpoint/4312_4325 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4312 | pinpoint-apm/pinpoint/4325 | [
"keyword_pr_to_issue"
] | 5c7ddd0a1023eb52ae35bbacfede19da4024e569 | 4ce44f50a2130e27a5d51bb107170218fa9a2d51 | [
"Hi @zfaster \r\nIt might be a bug, though it may be the collector's serialization part that is the issue.\r\nWe'll look into it, thanks for reporting.\r\n\r\nThat said, I am not sure if changing **AGENT_NAME_MAX_LEN** to 32 is safe enough to ensure proper operation. (It will break any data that has been stored using the default length for one thing)\r\nPlease share your experience if you do decide to go with it anyway.",
"I want to send http header Pinpoint-TraceID、Pinpoint-SpanID from my browser client , that i can trace from browser to server ,I need to Pinpoint-TraceID unique so have to use uuid and change AGENT_NAME_MAX_LEN to 32, do you have some other suggest if i want to do this "
] | [] | "2018-07-03T08:14:59Z" | [
"bug",
"module:web"
] | change AGENT_NAME_MAX_LEN cause error | **What version of pinpoint are you using?**
v1.7.3
**Describe the bug**
when i change the param AGENT_NAME_MAX_LEN to 32 and APPLICATION_NAME_MAX_LEN remain 24 ,
com.navercorp.pinpoint.web.mapper.TraceIndexScatterMapper3#createDot the Dot reverseAcceptedTime read was 0, beacuse this
`long reverseAcceptedTime = BytesUtils.bytesToLong(cell.getRowArray(), cell.getRowOffset() + HBaseTables.APPLICATION_NAME_MAX_LEN + HBaseTables.APPLICATION_TRACE_INDEX_ROW_DISTRIBUTE_SIZE);
`
there why use HBaseTables.APPLICATION_NAME_MAX_LEN it is bug? i think there should use AGENT_NAME_MAX_LEN
my english no good,do you know what i mean?
| [
"commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/SpanUtils.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java"
] | [
"commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/SpanUtils.java",
"web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java"
] | [
"commons-server/src/test/java/com/navercorp/pinpoint/common/server/util/SpanUtilsTest.java"
] | diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/SpanUtils.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/SpanUtils.java
index 85af2741620c..96e8614817c3 100644
--- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/SpanUtils.java
+++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/SpanUtils.java
@@ -20,13 +20,11 @@
import com.navercorp.pinpoint.common.buffer.AutomaticBuffer;
import com.navercorp.pinpoint.common.buffer.Buffer;
-import com.navercorp.pinpoint.common.server.bo.BasicSpan;
import com.navercorp.pinpoint.common.util.BytesUtils;
import com.navercorp.pinpoint.common.util.TimeUtils;
import com.navercorp.pinpoint.common.util.TransactionId;
import com.navercorp.pinpoint.common.util.TransactionIdUtils;
import com.navercorp.pinpoint.thrift.dto.TSpan;
-import com.navercorp.pinpoint.thrift.dto.TSpanChunk;
/**
* @author emeroad
@@ -35,28 +33,19 @@ public final class SpanUtils {
private SpanUtils() {
}
- @Deprecated
- public static byte[] getAgentIdTraceIndexRowKey(String agentId, long timestamp) {
- if (agentId == null) {
- throw new IllegalArgumentException("agentId must not null");
- }
- final byte[] bAgentId = BytesUtils.toBytes(agentId);
- return RowKeyUtils.concatFixedByteAndLong(bAgentId, AGENT_NAME_MAX_LEN, TimeUtils.reverseTimeMillis(timestamp));
- }
-
public static byte[] getApplicationTraceIndexRowKey(String applicationName, long timestamp) {
if (applicationName == null) {
- throw new IllegalArgumentException("agentId must not null");
+ throw new IllegalArgumentException("applicationName must not null");
}
final byte[] bApplicationName = BytesUtils.toBytes(applicationName);
- return RowKeyUtils.concatFixedByteAndLong(bApplicationName, AGENT_NAME_MAX_LEN, TimeUtils.reverseTimeMillis(timestamp));
+ return RowKeyUtils.concatFixedByteAndLong(bApplicationName, APPLICATION_NAME_MAX_LEN, TimeUtils.reverseTimeMillis(timestamp));
}
- public static byte[] getTraceIndexRowKey(byte[] agentId, long timestamp) {
- if (agentId == null) {
- throw new NullPointerException("agentId must not be null");
+ public static byte[] getApplicationTraceIndexRowKey(byte[] applicationName, long timestamp) {
+ if (applicationName == null) {
+ throw new NullPointerException("applicationName must not be null");
}
- return RowKeyUtils.concatFixedByteAndLong(agentId, AGENT_NAME_MAX_LEN, TimeUtils.reverseTimeMillis(timestamp));
+ return RowKeyUtils.concatFixedByteAndLong(applicationName, APPLICATION_NAME_MAX_LEN, TimeUtils.reverseTimeMillis(timestamp));
}
public static byte[] getVarTransactionId(TSpan span) {
@@ -76,42 +65,4 @@ public static byte[] getVarTransactionId(TSpan span) {
buffer.putVLong(transactionId.getTransactionSequence());
return buffer.getBuffer();
}
-
- @Deprecated
- public static byte[] getTransactionId(TSpan span) {
- if (span == null) {
- throw new NullPointerException("span must not be null");
- }
- final byte[] transactionIdBytes = span.getTransactionId();
- TransactionId transactionId = TransactionIdUtils.parseTransactionId(transactionIdBytes);
- String agentId = transactionId.getAgentId();
- if (agentId == null) {
- agentId = span.getAgentId();
- }
- return BytesUtils.stringLongLongToBytes(agentId, AGENT_NAME_MAX_LEN, transactionId.getAgentStartTime(), transactionId.getTransactionSequence());
-
- }
-
- @Deprecated
- public static byte[] getTransactionId(TSpanChunk spanChunk) {
- if (spanChunk == null) {
- throw new NullPointerException("spanChunk must not be null");
- }
- final byte[] transactionIdBytes = spanChunk.getTransactionId();
- final TransactionId transactionId = TransactionIdUtils.parseTransactionId(transactionIdBytes);
- String agentId = transactionId.getAgentId();
- if (agentId == null) {
- agentId = spanChunk.getAgentId();
- }
- return BytesUtils.stringLongLongToBytes(agentId, AGENT_NAME_MAX_LEN, transactionId.getAgentStartTime(), transactionId.getTransactionSequence());
- }
-
- @Deprecated
- public static byte[] getTransactionId(BasicSpan basicSpan) {
- if (basicSpan == null) {
- throw new NullPointerException("basicSpan must not be null");
- }
- TransactionId transactionId = basicSpan.getTransactionId();
- return BytesUtils.stringLongLongToBytes(transactionId.getAgentId(), AGENT_NAME_MAX_LEN, transactionId.getAgentStartTime(), transactionId.getTransactionSequence());
- }
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java
index 77e2215a474f..2bdc90f85a5d 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java
@@ -232,8 +232,8 @@ private Scan createScan(String applicationName, Range range, boolean scanBackwar
scan.setCaching(this.scanCacheSize);
byte[] bApplicationName = Bytes.toBytes(applicationName);
- byte[] traceIndexStartKey = SpanUtils.getTraceIndexRowKey(bApplicationName, range.getFrom());
- byte[] traceIndexEndKey = SpanUtils.getTraceIndexRowKey(bApplicationName, range.getTo());
+ byte[] traceIndexStartKey = SpanUtils.getApplicationTraceIndexRowKey(bApplicationName, range.getFrom());
+ byte[] traceIndexEndKey = SpanUtils.getApplicationTraceIndexRowKey(bApplicationName, range.getTo());
if (scanBackward) {
// start key is replaced by end key because key has been reversed
| diff --git a/commons-server/src/test/java/com/navercorp/pinpoint/common/server/util/SpanUtilsTest.java b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/util/SpanUtilsTest.java
index de46906729f5..e89fddbdf82f 100644
--- a/commons-server/src/test/java/com/navercorp/pinpoint/common/server/util/SpanUtilsTest.java
+++ b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/util/SpanUtilsTest.java
@@ -20,11 +20,8 @@
import com.google.common.primitives.Longs;
import com.navercorp.pinpoint.common.PinpointConstants;
-import com.navercorp.pinpoint.common.server.bo.SpanBo;
-import com.navercorp.pinpoint.common.server.bo.serializer.trace.v2.TraceRowKeyDecoderV2;
import com.navercorp.pinpoint.common.util.BytesUtils;
import com.navercorp.pinpoint.common.util.TimeUtils;
-import com.navercorp.pinpoint.common.util.TransactionId;
import com.navercorp.pinpoint.thrift.dto.TSpan;
import org.junit.Assert;
@@ -35,71 +32,57 @@
*/
public class SpanUtilsTest {
@Test
- public void testGetTraceIndexRowKeyWhiteSpace() throws Exception {
- String agentId = "test test";
+ public void testGetTraceIndexRowKeyWhiteSpace() {
+ String applicationName = "test test";
long time = System.currentTimeMillis();
- check(agentId, time);
+ check(applicationName, time);
}
@Test
- public void testGetTraceIndexRowKey1() throws Exception {
- String agentId = "test";
+ public void testGetTraceIndexRowKey1() {
+ String applicationName = "test";
long time = System.currentTimeMillis();
- check(agentId, time);
+ check(applicationName, time);
}
@Test
- public void testGetTraceIndexRowKey2() throws Exception {
- String agentId = "";
- for (int i = 0; i < PinpointConstants.AGENT_NAME_MAX_LEN; i++) {
- agentId += "1";
+ public void testGetTraceIndexRowKey2() {
+ String applicationName = "";
+ for (int i = 0; i < PinpointConstants.APPLICATION_NAME_MAX_LEN; i++) {
+ applicationName += "1";
}
long time = System.currentTimeMillis();
- check(agentId, time);
+ check(applicationName, time);
}
@Test
- public void testGetTraceIndexRowKey3() throws Exception {
- String agentId = "";
- for (int i = 0; i < PinpointConstants.AGENT_NAME_MAX_LEN + 1; i++) {
- agentId += "1";
+ public void testGetTraceIndexRowKey3() {
+ String applicationName = "";
+ for (int i = 0; i < PinpointConstants.APPLICATION_NAME_MAX_LEN + 1; i++) {
+ applicationName += "1";
}
long time = System.currentTimeMillis();
try {
- check(agentId, time);
+ check(applicationName, time);
Assert.fail("error");
} catch (IndexOutOfBoundsException ignore) {
}
}
- private void check(String agentId0, long l1) {
+ private void check(String applicationName, long l1) {
TSpan span = new TSpan();
- span.setAgentId(agentId0);
+ span.setApplicationName(applicationName);
span.setStartTime(l1);
- byte[] traceIndexRowKey = SpanUtils.getAgentIdTraceIndexRowKey(span.getAgentId(), span.getStartTime());
+ byte[] traceIndexRowKey = SpanUtils.getApplicationTraceIndexRowKey(span.getApplicationName(), span.getStartTime());
- String agentId = BytesUtils.toString(traceIndexRowKey, 0, PinpointConstants.AGENT_NAME_MAX_LEN).trim();
- Assert.assertEquals(agentId0, agentId);
+ String agentId = BytesUtils.toString(traceIndexRowKey, 0, PinpointConstants.APPLICATION_NAME_MAX_LEN).trim();
+ Assert.assertEquals(applicationName, agentId);
- long time = Longs.fromByteArray(Arrays.copyOfRange(traceIndexRowKey, PinpointConstants.AGENT_NAME_MAX_LEN, PinpointConstants.AGENT_NAME_MAX_LEN + 8));
+ long time = Longs.fromByteArray(Arrays.copyOfRange(traceIndexRowKey, PinpointConstants.APPLICATION_NAME_MAX_LEN, PinpointConstants.APPLICATION_NAME_MAX_LEN + 8));
time = TimeUtils.recoveryTimeMillis(time);
Assert.assertEquals(time, l1);
}
-
- @Test
- public void testGetTransactionId_BasicSpan() {
- SpanBo spanBo = new SpanBo();
- TransactionId spanTransactionId = new TransactionId("traceAgentId", System.currentTimeMillis(), 1111);
- spanBo.setTransactionId(spanTransactionId);
-
- byte[] transactionIdRowkey = SpanUtils.getTransactionId(spanBo);
-
- TraceRowKeyDecoderV2 decoder = new TraceRowKeyDecoderV2();
- TransactionId transactionId = decoder.readTransactionId(transactionIdRowkey);
-
- Assert.assertEquals(transactionId, spanBo.getTransactionId());
- }
}
| val | val | "2018-07-03T11:10:15" | "2018-06-29T09:02:43Z" | zfaster | test |
pinpoint-apm/pinpoint/4346_4349 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4346 | pinpoint-apm/pinpoint/4349 | [
"keyword_issue_to_pr"
] | 338e51c76ad73011187e7ba9a0080334ce05b0f2 | 1a86a4f13a51f506fe02e4137cce9237e2fba810 | [
"closed via #4349"
] | [] | "2018-07-09T01:27:59Z" | [
"enhancement",
"module:project-common"
] | Allows the ClientOption setting in the setup file | #### description
Currently, ClientOption settings are forced to be programmatically.
Will change to allows the ClientOption setting in the setup file.
Then, User can customize it for user's environment.
| [
"agent/src/main/resources-local/pinpoint.config",
"agent/src/main/resources-release/pinpoint.config",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/PinpointClientFactoryProvider.java"
] | [
"agent/src/main/resources-local/pinpoint.config",
"agent/src/main/resources-release/pinpoint.config",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/PinpointClientFactoryProvider.java"
] | [] | diff --git a/agent/src/main/resources-local/pinpoint.config b/agent/src/main/resources-local/pinpoint.config
index 78ed42eeeb3f..8b1fcbe4f227 100644
--- a/agent/src/main/resources-local/pinpoint.config
+++ b/agent/src/main/resources-local/pinpoint.config
@@ -90,6 +90,12 @@ profiler.tcpdatasender.command.activethread.count.enable=true
profiler.tcpdatasender.command.activethread.threaddump.enable=true
profiler.tcpdatasender.command.activethread.threadlightdump.enable=true
+profiler.tcpdatasender.client.write.timeout=3000
+profiler.tcpdatasender.client.request.timeout=3000
+profiler.tcpdatasender.client.reconnect.interval=3000
+profiler.tcpdatasender.client.ping.interval=300000
+profiler.tcpdatasender.client.handshake.interval=60000
+
# Trace Agent active thread info.
profiler.pinpoint.activethread=true
diff --git a/agent/src/main/resources-release/pinpoint.config b/agent/src/main/resources-release/pinpoint.config
index 308aa99a5e04..2ae0975d3ed7 100644
--- a/agent/src/main/resources-release/pinpoint.config
+++ b/agent/src/main/resources-release/pinpoint.config
@@ -86,6 +86,12 @@ profiler.tcpdatasender.command.activethread.count.enable=true
profiler.tcpdatasender.command.activethread.threaddump.enable=true
profiler.tcpdatasender.command.activethread.threadlightdump.enable=true
+profiler.tcpdatasender.client.write.timeout=3000
+profiler.tcpdatasender.client.request.timeout=3000
+profiler.tcpdatasender.client.reconnect.interval=3000
+profiler.tcpdatasender.client.ping.interval=300000
+profiler.tcpdatasender.client.handshake.interval=60000
+
# Trace Agent active thread info.
profiler.pinpoint.activethread=true
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
index ff6a15922dc2..ed2029da3db5 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
@@ -131,6 +131,17 @@ public static ProfilerConfig load(String pinpointConfigFileName) throws IOExcept
private boolean tcpDataSenderCommandActiveThreadDumpEnable = false;
private boolean tcpDataSenderCommandActiveThreadLightDumpEnable = false;
+ private static long DEFAULT_DATA_SENDER_PINPOINT_CLIENT_WRITE_TIMEOUT = 3 * 1000;
+ private long tcpDataSenderPinpointClientWriteTimeout = DEFAULT_DATA_SENDER_PINPOINT_CLIENT_WRITE_TIMEOUT;
+ private static long DEFAULT_DATA_SENDER_PINPOINT_CLIENT_REQUEST_TIMEOUT = 3 * 1000;
+ private long tcpDataSenderPinpointClientRequestTimeout = DEFAULT_DATA_SENDER_PINPOINT_CLIENT_REQUEST_TIMEOUT;
+ private static long DEFAULT_DATA_SENDER_PINPOINT_CLIENT_RECONNECT_INTERVAL = 3 * 1000;
+ private long tcpDataSenderPinpointClientReconnectInterval = DEFAULT_DATA_SENDER_PINPOINT_CLIENT_RECONNECT_INTERVAL;
+ private static long DEFAULT_DATA_SENDER_PINPOINT_CLIENT_PING_INTERVAL = 60 * 1000 * 5;
+ private long tcpDataSenderPinpointClientPingInterval = DEFAULT_DATA_SENDER_PINPOINT_CLIENT_PING_INTERVAL;
+ private static long DEFAULT_DATA_SENDER_PINPOINT_CLIENT_HANDSHAKE_INTERVAL = 60 * 1000 * 1;
+ private long tcpDataSenderPinpointClientHandshakeInterval = DEFAULT_DATA_SENDER_PINPOINT_CLIENT_HANDSHAKE_INTERVAL;
+
private boolean traceAgentActiveThread = true;
private boolean traceAgentDataSource = false;
@@ -285,6 +296,31 @@ public boolean isTcpDataSenderCommandActiveThreadLightDumpEnable() {
return tcpDataSenderCommandActiveThreadLightDumpEnable;
}
+ @Override
+ public long getTcpDataSenderPinpointClientWriteTimeout() {
+ return tcpDataSenderPinpointClientWriteTimeout;
+ }
+
+ @Override
+ public long getTcpDataSenderPinpointClientRequestTimeout() {
+ return tcpDataSenderPinpointClientRequestTimeout;
+ }
+
+ @Override
+ public long getTcpDataSenderPinpointClientReconnectInterval() {
+ return tcpDataSenderPinpointClientReconnectInterval;
+ }
+
+ @Override
+ public long getTcpDataSenderPinpointClientPingInterval() {
+ return tcpDataSenderPinpointClientPingInterval;
+ }
+
+ @Override
+ public long getTcpDataSenderPinpointClientHandshakeInterval() {
+ return tcpDataSenderPinpointClientHandshakeInterval;
+ }
+
@Override
public boolean isTraceAgentActiveThread() {
return traceAgentActiveThread;
@@ -541,6 +577,12 @@ void readPropertyValues() {
this.tcpDataSenderCommandActiveThreadDumpEnable = readBoolean("profiler.tcpdatasender.command.activethread.threaddump.enable", false);
this.tcpDataSenderCommandActiveThreadLightDumpEnable = readBoolean("profiler.tcpdatasender.command.activethread.threadlightdump.enable", false);
+ this.tcpDataSenderPinpointClientWriteTimeout = readLong("profiler.tcpdatasender.client.write.timeout", DEFAULT_DATA_SENDER_PINPOINT_CLIENT_WRITE_TIMEOUT);
+ this.tcpDataSenderPinpointClientRequestTimeout = readLong("profiler.tcpdatasender.client.request.timeout", DEFAULT_DATA_SENDER_PINPOINT_CLIENT_REQUEST_TIMEOUT);
+ this.tcpDataSenderPinpointClientReconnectInterval = readLong("profiler.tcpdatasender.client.reconnect.interval", DEFAULT_DATA_SENDER_PINPOINT_CLIENT_RECONNECT_INTERVAL);
+ this.tcpDataSenderPinpointClientPingInterval = readLong("profiler.tcpdatasender.client.ping.interval", DEFAULT_DATA_SENDER_PINPOINT_CLIENT_PING_INTERVAL);
+ this.tcpDataSenderPinpointClientHandshakeInterval = readLong("profiler.tcpdatasender.client.handshake.interval", DEFAULT_DATA_SENDER_PINPOINT_CLIENT_HANDSHAKE_INTERVAL);
+
this.traceAgentActiveThread = readBoolean("profiler.pinpoint.activethread", true);
this.traceAgentDataSource = readBoolean("profiler.pinpoint.datasource", false);
@@ -742,6 +784,11 @@ public String toString() {
sb.append(", tcpDataSenderCommandActiveThreadCountEnable=").append(tcpDataSenderCommandActiveThreadCountEnable);
sb.append(", tcpDataSenderCommandActiveThreadDumpEnable=").append(tcpDataSenderCommandActiveThreadDumpEnable);
sb.append(", tcpDataSenderCommandActiveThreadLightDumpEnable=").append(tcpDataSenderCommandActiveThreadLightDumpEnable);
+ sb.append(", tcpDataSenderPinpointClientWriteTimeout=").append(tcpDataSenderPinpointClientWriteTimeout);
+ sb.append(", tcpDataSenderPinpointClientRequestTimeout=").append(tcpDataSenderPinpointClientRequestTimeout);
+ sb.append(", tcpDataSenderPinpointClientReconnectInterval=").append(tcpDataSenderPinpointClientReconnectInterval);
+ sb.append(", tcpDataSenderPinpointClientPingInterval=").append(tcpDataSenderPinpointClientPingInterval);
+ sb.append(", tcpDataSenderPinpointClientHandshakeInterval=").append(tcpDataSenderPinpointClientHandshakeInterval);
sb.append(", traceAgentActiveThread=").append(traceAgentActiveThread);
sb.append(", traceAgentDataSource=").append(traceAgentDataSource);
sb.append(", dataSourceTraceLimitSize=").append(dataSourceTraceLimitSize);
@@ -775,4 +822,5 @@ public String toString() {
sb.append('}');
return sb.toString();
}
+
}
\ No newline at end of file
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java
index 6f370c246e1a..e990dc946393 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfig.java
@@ -65,6 +65,16 @@ public interface ProfilerConfig {
boolean isTcpDataSenderCommandActiveThreadLightDumpEnable();
+ long getTcpDataSenderPinpointClientWriteTimeout();
+
+ long getTcpDataSenderPinpointClientRequestTimeout();
+
+ long getTcpDataSenderPinpointClientReconnectInterval();
+
+ long getTcpDataSenderPinpointClientPingInterval();
+
+ long getTcpDataSenderPinpointClientHandshakeInterval();
+
boolean isTraceAgentActiveThread();
boolean isTraceAgentDataSource();
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/PinpointClientFactoryProvider.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/PinpointClientFactoryProvider.java
index 81c77c43dde5..6d423254bfb4 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/PinpointClientFactoryProvider.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/PinpointClientFactoryProvider.java
@@ -61,8 +61,11 @@ public PinpointClientFactoryProvider(ProfilerConfig profilerConfig, Provider<Age
public PinpointClientFactory get() {
PinpointClientFactory pinpointClientFactory = new DefaultPinpointClientFactory(connectionFactoryProvider.get());
- pinpointClientFactory.setWriteTimeoutMillis(1000 * 3);
- pinpointClientFactory.setRequestTimeoutMillis(1000 * 5);
+ pinpointClientFactory.setWriteTimeoutMillis(profilerConfig.getTcpDataSenderPinpointClientWriteTimeout());
+ pinpointClientFactory.setRequestTimeoutMillis(profilerConfig.getTcpDataSenderPinpointClientRequestTimeout());
+ pinpointClientFactory.setReconnectDelay(profilerConfig.getTcpDataSenderPinpointClientReconnectInterval());
+ pinpointClientFactory.setPingDelay(profilerConfig.getTcpDataSenderPinpointClientPingInterval());
+ pinpointClientFactory.setEnableWorkerPacketDelay(profilerConfig.getTcpDataSenderPinpointClientHandshakeInterval());
AgentInformation agentInformation = this.agentInformation.get();
Map<String, Object> properties = toMap(agentInformation);
| null | val | val | "2018-07-06T07:52:54" | "2018-07-06T01:46:44Z" | koo-taejin | test |
pinpoint-apm/pinpoint/4385_4386 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4385 | pinpoint-apm/pinpoint/4386 | [
"keyword_pr_to_issue"
] | 93fc8764ebaa2279dddfb600d9207ac2c35d89f5 | ed00677771230eb98402e71a4fb9899e3c09f736 | [] | [] | "2018-07-20T01:49:25Z" | [
"enhancement",
"module:project-common"
] | Upgrade hbase client version | #### Description
The current hbase client (1.2.4) does not work on Java 9+ due to https://issues.apache.org/jira/browse/HBASE-17944.
Fix was introduced for 1.2.6, so a version up is required.
| [
"pom.xml"
] | [
"pom.xml"
] | [] | diff --git a/pom.xml b/pom.xml
index 3beca5cdc59f..fa58baee62a6 100644
--- a/pom.xml
+++ b/pom.xml
@@ -358,7 +358,7 @@
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-shaded-client</artifactId>
- <version>1.2.4</version>
+ <version>1.2.6.1</version>
</dependency>
<dependency>
| null | train | val | "2018-07-20T03:08:12" | "2018-07-20T01:46:11Z" | Xylus | test |
pinpoint-apm/pinpoint/4389_4427 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4389 | pinpoint-apm/pinpoint/4427 | [
"keyword_pr_to_issue"
] | 6e697f4db9084d80aec9eb93a137f7aeb728d1fe | 10905aff1796862195480c3f56f3a148d8b268bc | [
"@nickycheng Thanks for reporting, will fix in master."
] | [
"getHostString() in jdk6 is a package level accessor.\r\nSo all versions of jdk1.6 should be checked that method is included.\r\n",
"@koo-taejin Thanks for the reminder.\r\n`getHostString()` is present in 1.6.0_0 and in 1.6.0_45, so it should be there for other versions of 1.6 as well."
] | "2018-07-31T09:22:38Z" | [
"bug",
"module:plugin"
] | thrift plugin InetSocketAddress#getHostName issue | **What version of pinpoint are you using?**
v1.7.3
**Describe the bug**
when thrift plugin retrieve connection information, it use InetSocketAddress#getHostName method , and may block the bussiness thread.
**Expected behavior**
In order to avoid the main process blocked, this API should not be used.
background:
https://stackoverflow.com/questions/10420317/java-inetaddress-gethostname-taking-a-very-long-time-to-execute
From the InetAddress#getHostName() javadocs, that method will perform **a reverse hostname lookup**. So the performance of that method call depends on the performance of the network/technology stack between the JVM and the domain name server for the target host.
In brief, that method will make a system call to perform the reverse lookup (e.g. getaddrinfo(3)) and that call will be implemented by the operating system to perform the network actions required to gather the host information via the Name Server configured for your machine.
| [
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/util/SocketAddressUtils.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java"
] | [
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/SyncEchoTestClient.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/AsyncEchoTestServer.java",
"agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/SyncEchoTestServer.java",
"bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/plugin/util/SocketAddressUtilsTest.java"
] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/util/SocketAddressUtils.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/util/SocketAddressUtils.java
new file mode 100644
index 000000000000..77c75857598f
--- /dev/null
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/util/SocketAddressUtils.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.bootstrap.plugin.util;
+
+import com.navercorp.pinpoint.bootstrap.logging.PLogger;
+import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
+import com.navercorp.pinpoint.common.util.JvmUtils;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+
+/**
+ * @author HyunGil Jeong
+ */
+public final class SocketAddressUtils {
+
+ private static final PLogger LOGGER = PLoggerFactory.getLogger(SocketAddressUtils.class);
+
+ // TODO JDK 7 InetSocketAddress.getHostString() - reflection not needed once we drop JDK 6 support.
+ private static final HostStringAccessor HOST_STRING_ACCESSOR = createHostStringAccessor();
+
+ private static HostStringAccessor createHostStringAccessor() {
+ try {
+ final Method m = InetSocketAddress.class.getDeclaredMethod("getHostString");
+ m.setAccessible(true);
+ return new ReflectiveHostStringAccessor(m);
+ } catch (NoSuchMethodException e) {
+ LOGGER.error("[{}] {} - getHostString() not present in class InetSocketAddress.",
+ JvmUtils.getType(), JvmUtils.getVersion());
+ throw new IllegalStateException("Unexpected InetSocketAddress class", e);
+ }
+ }
+
+ private interface HostStringAccessor {
+ String getHostString(InetSocketAddress inetSocketAddress);
+ }
+
+ private static class ReflectiveHostStringAccessor implements HostStringAccessor {
+
+ private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
+
+ private final Method method;
+
+ private ReflectiveHostStringAccessor(Method method) {
+ if (method == null) {
+ throw new NullPointerException("method must not be null");
+ }
+ this.method = method;
+ }
+
+ @Override
+ public String getHostString(InetSocketAddress inetSocketAddress) {
+ try {
+ return (String) method.invoke(inetSocketAddress);
+ } catch (IllegalAccessException e) {
+ logger.error("[{}] {} - Cannot access method : {}",
+ JvmUtils.getType(), JvmUtils.getVersion(), method.getName(), e);
+ } catch (InvocationTargetException e) {
+ logger.error("[{}] {} - Error invoking method : {}",
+ JvmUtils.getType(), JvmUtils.getVersion(), method.getName(), e);
+ } catch (Exception e) {
+ logger.error("[{}] {} - Unexpected error retrieving hostString",
+ JvmUtils.getType(), JvmUtils.getVersion(), e);
+ }
+ return null;
+ }
+ }
+
+ private SocketAddressUtils() {}
+
+ /**
+ * Returns the hostname of the given {@link InetSocketAddress}, or the String form of the IP address
+ * if it does not have one. Returns {@code null} if neither can be retrieved.
+ *
+ * <p> This <b>does not</b> trigger a reverse DNS lookup if was created using an address and the hostname
+ * is not yet available.
+ *
+ * @param inetSocketAddress the socket address in which to retrieve the hostname from
+ * @return the hostname or the String representation of the address, or {@code null} if neither
+ * can be found.
+ *
+ * @see java.net.InetSocketAddress#getHostString()
+ */
+ public static String getHostNameFirst(InetSocketAddress inetSocketAddress) {
+ if (inetSocketAddress == null) {
+ return null;
+ }
+ return HOST_STRING_ACCESSOR.getHostString(inetSocketAddress);
+ }
+
+ /**
+ * Returns the hostname of the given {@link InetSocketAddress}, or the String form of the IP address
+ * if it does not have one. Returns {@code defaultHostName} if neither can be retrieved.
+ *
+ * <p>This <b>does not</b> trigger a reverse DNS lookup if was created using an address and the hostname
+ * is not yet available.
+ *
+ * @param inetSocketAddress the socket address in which to retrieve the hostname from
+ * @param defaultHostName the value to return if neither the hostname nor the string form of the
+ * address can be found
+ * @return the hostname or the String representation of the address, or the {@code defaultHostName}
+ * if neither can be found.
+ *
+ * @see java.net.InetSocketAddress#getHostString()
+ */
+ public static String getHostNameFirst(InetSocketAddress inetSocketAddress, String defaultHostName) {
+ String hostName = getHostNameFirst(inetSocketAddress);
+ if (hostName == null) {
+ return defaultHostName;
+ }
+ return hostName;
+ }
+
+ /**
+ * Returns the String form of the IP address of the given {@link InetSocketAddress}, or the hostname
+ * if it has not been resolved. Returns {@code null} if neither can be retrieved.
+ *
+ * <p>This <b>does not</b> trigger a DNS lookup if the address has not been resolved yet by simply
+ * returning the hostname.
+ *
+ * @param inetSocketAddress the socket address in which to retrieve the address from
+ * @return the String representation of the address or the hostname, or {@code null} if neither
+ * can be found.
+ *
+ * @see InetSocketAddress#isUnresolved()
+ */
+ public static String getAddressFirst(InetSocketAddress inetSocketAddress) {
+ if (inetSocketAddress == null) {
+ return null;
+ }
+ InetAddress inetAddress = inetSocketAddress.getAddress();
+ if (inetAddress != null) {
+ return inetAddress.getHostAddress();
+ }
+ // This won't trigger a DNS lookup as if it got to here, the hostName should not be null on the basis
+ // that InetSocketAddress does not allow both address and hostName fields to be null.
+ return inetSocketAddress.getHostName();
+ }
+
+ /**
+ * Returns the String form of the IP address of the given {@link InetSocketAddress}, or the hostname
+ * if it has not been resolved. Returns {@code defaultAddress} if neither can be retrieved.
+ *
+ * <p>This <b>does not</b> trigger a DNS lookup if the address has not been resolved yet by simply
+ * returning the hostname.
+ *
+ * @param inetSocketAddress the socket address in which to retrieve the address from
+ * @param defaultAddress the value to return if neither the string form of the address nor the
+ * hostname can be found
+ * @return the String representation of the address or the hostname, or {@code defaultAddress} if neither
+ * can be found.
+ *
+ * @see InetSocketAddress#isUnresolved()
+ */
+ public static String getAddressFirst(InetSocketAddress inetSocketAddress, String defaultAddress) {
+ String address = getAddressFirst(inetSocketAddress);
+ if (address == null) {
+ return defaultAddress;
+ }
+ return address;
+ }
+}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java
index f912d7918ea6..6276cf4e46cf 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java
@@ -16,6 +16,7 @@
package com.navercorp.pinpoint.plugin.thrift;
+import com.navercorp.pinpoint.bootstrap.plugin.util.SocketAddressUtils;
import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
import org.apache.thrift.TBaseAsyncProcessor;
import org.apache.thrift.TBaseProcessor;
@@ -85,16 +86,12 @@ public static String getAsyncMethodCallName(TAsyncMethodCall<?> asyncMethodCall)
* @return the ip address retrieved from the given <tt>socketAddress</tt>,
* or {@literal ThriftConstants.UNKNOWN_ADDRESS} if it cannot be retrieved
*/
- // TODO should probably be pulled up as a common API
public static String getIp(SocketAddress socketAddress) {
- if (socketAddress == null) {
- return ThriftConstants.UNKNOWN_ADDRESS;
- }
if (socketAddress instanceof InetSocketAddress) {
- InetSocketAddress addr = (InetSocketAddress)socketAddress;
- return addr.getAddress().getHostAddress();
+ InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
+ return SocketAddressUtils.getAddressFirst(inetSocketAddress, ThriftConstants.UNKNOWN_ADDRESS);
}
- return getSocketAddress(socketAddress);
+ return ThriftConstants.UNKNOWN_ADDRESS;
}
/**
@@ -104,16 +101,16 @@ public static String getIp(SocketAddress socketAddress) {
* @return the ip/port retrieved from the given <tt>socketAddress</tt>,
* or {@literal ThriftConstants.UNKNOWN_ADDRESS} if it cannot be retrieved
*/
- // TODO should probably be pulled up as a common API
public static String getIpPort(SocketAddress socketAddress) {
- if (socketAddress == null) {
- return ThriftConstants.UNKNOWN_ADDRESS;
- }
if (socketAddress instanceof InetSocketAddress) {
- InetSocketAddress addr = (InetSocketAddress)socketAddress;
- return HostAndPort.toHostAndPortString(addr.getAddress().getHostAddress(), addr.getPort());
+ InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
+ String address = SocketAddressUtils.getAddressFirst(inetSocketAddress);
+ if (address == null) {
+ return ThriftConstants.UNKNOWN_ADDRESS;
+ }
+ return HostAndPort.toHostAndPortString(address, inetSocketAddress.getPort());
}
- return getSocketAddress(socketAddress);
+ return ThriftConstants.UNKNOWN_ADDRESS;
}
/**
@@ -123,16 +120,12 @@ public static String getIpPort(SocketAddress socketAddress) {
* @return the host retrieved from the given <tt>socketAddress</tt>,
* or {@literal ThriftConstants.UNKNOWN_ADDRESS} if it cannot be retrieved
*/
- // TODO should probably be pulled up as a common API
public static String getHost(SocketAddress socketAddress) {
- if (socketAddress == null) {
- return ThriftConstants.UNKNOWN_ADDRESS;
- }
if (socketAddress instanceof InetSocketAddress) {
- InetSocketAddress addr = (InetSocketAddress)socketAddress;
- return addr.getHostName();
+ InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
+ return SocketAddressUtils.getHostNameFirst(inetSocketAddress, ThriftConstants.UNKNOWN_ADDRESS);
}
- return getSocketAddress(socketAddress);
+ return ThriftConstants.UNKNOWN_ADDRESS;
}
/**
@@ -142,32 +135,15 @@ public static String getHost(SocketAddress socketAddress) {
* @return the host/port retrieved from the given <tt>socketAddress</tt>,
* or {@literal ThriftConstants.UNKNOWN_ADDRESS} if it cannot be retrieved
*/
- // TODO should probably be pulled up as a common API
public static String getHostPort(SocketAddress socketAddress) {
- if (socketAddress == null) {
- return ThriftConstants.UNKNOWN_ADDRESS;
- }
if (socketAddress instanceof InetSocketAddress) {
- InetSocketAddress addr = (InetSocketAddress)socketAddress;
- return HostAndPort.toHostAndPortString(addr.getHostName(), addr.getPort());
- }
- return getSocketAddress(socketAddress);
- }
-
- private static String getSocketAddress(SocketAddress socketAddress) {
- String address = socketAddress.toString();
- int addressLength = address.length();
-
- if (addressLength > 0) {
- if (address.startsWith("/")) {
- return address.substring(1);
- } else {
- final int delimiterIndex = address.indexOf('/');
- if (delimiterIndex != -1 && delimiterIndex < addressLength) {
- return address.substring(address.indexOf('/') + 1);
- }
+ InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
+ String hostName = SocketAddressUtils.getHostNameFirst(inetSocketAddress);
+ if (hostName == null) {
+ return ThriftConstants.UNKNOWN_ADDRESS;
}
+ return HostAndPort.toHostAndPortString(hostName, inetSocketAddress.getPort());
}
- return address;
+ return ThriftConstants.UNKNOWN_ADDRESS;
}
}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java
index f09b89ac78ed..a29a9710d1ac 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java
@@ -16,12 +16,9 @@
package com.navercorp.pinpoint.plugin.thrift.interceptor.server;
-import java.net.Socket;
import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope;
import org.apache.thrift.TBaseProcessor;
-import org.apache.thrift.protocol.TProtocol;
-import org.apache.thrift.transport.TTransport;
import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
@@ -35,7 +32,6 @@
import com.navercorp.pinpoint.plugin.thrift.ThriftClientCallContext;
import com.navercorp.pinpoint.plugin.thrift.ThriftConstants;
import com.navercorp.pinpoint.plugin.thrift.ThriftUtils;
-import com.navercorp.pinpoint.plugin.thrift.field.accessor.SocketFieldAccessor;
/**
* Entry/exit point for tracing synchronous processors for Thrift services.
@@ -133,30 +129,6 @@ private void processTraceObject(final Trace trace, Object target, Object[] args,
SpanRecorder recorder = trace.getSpanRecorder();
String methodUri = getMethodUri(target);
recorder.recordRpcName(methodUri);
- // retrieve connection information
- String localIpPort = ThriftConstants.UNKNOWN_ADDRESS;
- String remoteAddress = ThriftConstants.UNKNOWN_ADDRESS;
- if (args.length == 2 && args[0] instanceof TProtocol) {
- TProtocol inputProtocol = (TProtocol)args[0];
- TTransport inputTransport = inputProtocol.getTransport();
- if (inputTransport instanceof SocketFieldAccessor) {
- Socket socket = ((SocketFieldAccessor)inputTransport)._$PINPOINT$_getSocket();
- if (socket != null) {
- localIpPort = ThriftUtils.getHostPort(socket.getLocalSocketAddress());
- remoteAddress = ThriftUtils.getHost(socket.getRemoteSocketAddress());
- }
- } else {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", SocketFieldAccessor.class.getName());
- }
- }
- }
- if (localIpPort != ThriftConstants.UNKNOWN_ADDRESS) {
- recorder.recordEndPoint(localIpPort);
- }
- if (remoteAddress != ThriftConstants.UNKNOWN_ADDRESS) {
- recorder.recordRemoteAddress(remoteAddress);
- }
}
private String getMethodUri(Object target) {
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java
index ebef5c275507..4e2d43fed7bd 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java
@@ -250,10 +250,10 @@ private void recordConnection(SpanRecorder recorder, TTransport transport) {
// retrieve connection information
String localIpPort = ThriftConstants.UNKNOWN_ADDRESS;
String remoteAddress = ThriftConstants.UNKNOWN_ADDRESS;
- Socket socket = ((SocketFieldAccessor)transport)._$PINPOINT$_getSocket();
+ Socket socket = ((SocketFieldAccessor) transport)._$PINPOINT$_getSocket();
if (socket != null) {
- localIpPort = ThriftUtils.getHostPort(socket.getLocalSocketAddress());
- remoteAddress = ThriftUtils.getHost(socket.getRemoteSocketAddress());
+ localIpPort = ThriftUtils.getIpPort(socket.getLocalSocketAddress());
+ remoteAddress = ThriftUtils.getIp(socket.getRemoteSocketAddress());
}
if (localIpPort != ThriftConstants.UNKNOWN_ADDRESS) {
recorder.recordEndPoint(localIpPort);
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 33e16c989fcc..d6185768d094 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java
@@ -23,6 +23,7 @@
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerBinder;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
+import com.navercorp.pinpoint.bootstrap.plugin.util.SocketAddressUtils;
import com.navercorp.pinpoint.common.util.Assert;
import com.navercorp.pinpoint.profiler.context.module.ApplicationContext;
import com.navercorp.pinpoint.profiler.context.module.DefaultApplicationContext;
@@ -83,6 +84,8 @@ public DefaultAgent(AgentOption agentOption) {
changeStatus(AgentStatus.INITIALIZING);
+ preloadOnStartup();
+
this.profilerConfig = agentOption.getProfilerConfig();
this.applicationContext = newApplicationContext(agentOption);
@@ -130,6 +133,11 @@ private void bindPLoggerFactory(PLoggerBinder binder) {
PLoggerFactory.initialize(binder);
}
+ private void preloadOnStartup() {
+ // Preload to fail fast on startup. This won't be necessary once JDK 6 support ends
+ // and reflective method handle is not needed.
+ SocketAddressUtils.getHostNameFirst(null);
+ }
@Override
public void start() {
| diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
index 0a952a5be2f6..8a97ef52d9c6 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
@@ -24,6 +24,8 @@
import java.nio.channels.SelectionKey;
import java.util.concurrent.CountDownLatch;
+import com.navercorp.pinpoint.bootstrap.plugin.util.SocketAddressUtils;
+import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.apache.thrift.TServiceClient;
@@ -79,7 +81,10 @@ public String echo(String message) throws TException {
@Override
public void verifyTraces(PluginTestVerifier verifier, String expectedMessage) throws Exception {
- final InetSocketAddress actualServerAddress = this.environment.getServerAddress();
+ final InetSocketAddress socketAddress = this.environment.getServerAddress();
+ final String hostName = SocketAddressUtils.getHostNameFirst(socketAddress);
+ // refer to com.navercorp.pinpoint.plugin.thrift.ThriftUtils#getHostPort
+ final String remoteAddress = HostAndPort.toHostAndPortString(hostName, socketAddress.getPort());
// ********** Asynchronous Traces
// SpanEvent - Asynchronous Invocation
ExpectedTrace asyncInvocationTrace = event("ASYNC", "Asynchronous Invocation");
@@ -101,13 +106,13 @@ public void verifyTraces(PluginTestVerifier verifier, String expectedMessage) th
// ********** Root trace for Asynchronous traces
// SpanEvent - TAsyncClientManager.call
Method call = TAsyncClientManager.class.getDeclaredMethod("call", TAsyncMethodCall.class);
- ExpectedAnnotation thriftUrl = Expectations.annotation("thrift.url", actualServerAddress.getHostName() + ":"
- + actualServerAddress.getPort() + "/com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo_call");
+ ExpectedAnnotation thriftUrl = Expectations.annotation("thrift.url",
+ remoteAddress + "/com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo_call");
ExpectedTrace callTrace = event("THRIFT_CLIENT", // ServiceType
call, // Method
null, // rpc
null, // endPoint
- actualServerAddress.getHostName() + ":" + actualServerAddress.getPort(), // destinationId
+ remoteAddress, // destinationId
thriftUrl // Annotation("thrift.url")
);
verifier.verifyTrace(async(callTrace, asyncInvocationTrace, cleanUpAndFireCallbackTrace, receiveBaseTrace));
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/SyncEchoTestClient.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/SyncEchoTestClient.java
index 0df82d87b6b4..0b4878c7612e 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/SyncEchoTestClient.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/SyncEchoTestClient.java
@@ -21,6 +21,7 @@
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
+import com.navercorp.pinpoint.bootstrap.plugin.util.SocketAddressUtils;
import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
@@ -60,14 +61,17 @@ public final String echo(String message) throws TException {
@Override
public void verifyTraces(PluginTestVerifier verifier, String expectedMessage) throws Exception {
- final InetSocketAddress actualServerAddress = this.environment.getServerAddress();
+ final InetSocketAddress socketAddress = this.environment.getServerAddress();
+ final String hostName = SocketAddressUtils.getHostNameFirst(socketAddress);
+ // refer to com.navercorp.pinpoint.plugin.thrift.ThriftUtils#getHostPort
+ final String remoteAddress = HostAndPort.toHostAndPortString(hostName, socketAddress.getPort());
// SpanEvent - TServiceClient.sendBase
Method sendBase = TServiceClient.class.getDeclaredMethod("sendBase", String.class, TBase.class);
// refer to com.navercorp.pinpoint.plugin.thrift.ThriftUtils#getClientServiceName
- ExpectedAnnotation thriftUrl = Expectations.annotation("thrift.url", actualServerAddress.getHostName() + ":"
- + actualServerAddress.getPort() + "/com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo");
- ExpectedAnnotation thriftArgs = Expectations.annotation("thrift.args", "echo_args(message:" + expectedMessage
- + ")");
+ ExpectedAnnotation thriftUrl = Expectations.annotation("thrift.url",
+ remoteAddress + "/com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo");
+ ExpectedAnnotation thriftArgs = Expectations.annotation("thrift.args",
+ "echo_args(message:" + expectedMessage + ")");
// SpanEvent - TServiceClient.receiveBase
Method receiveBase = TServiceClient.class.getDeclaredMethod("receiveBase", TBase.class, String.class);
@@ -78,7 +82,7 @@ public void verifyTraces(PluginTestVerifier verifier, String expectedMessage) th
sendBase, // Method
null, // rpc
null, // endPoint
- HostAndPort.toHostAndPortString(actualServerAddress.getHostName(), actualServerAddress.getPort()), // destinationId
+ remoteAddress, // destinationId
thriftUrl, // Annotation("thrift.url")
thriftArgs), // Annotation("thrift.args")
event("THRIFT_CLIENT_INTERNAL", // ServiceType
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/AsyncEchoTestServer.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/AsyncEchoTestServer.java
index ab901ae30f9c..187a493fcb77 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/AsyncEchoTestServer.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/AsyncEchoTestServer.java
@@ -22,6 +22,8 @@
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
+import com.navercorp.pinpoint.bootstrap.plugin.util.SocketAddressUtils;
+import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
import org.apache.thrift.TBaseAsyncProcessor;
import org.apache.thrift.TProcessor;
import org.apache.thrift.server.AbstractNonblockingServer;
@@ -49,15 +51,16 @@ protected AsyncEchoTestServer(T server, TestEnvironment environment) throws TTra
@Override
public void verifyServerTraces(PluginTestVerifier verifier) throws Exception {
- final InetSocketAddress actualServerAddress = super.environment.getServerAddress();
+ final InetSocketAddress socketAddress = super.environment.getServerAddress();
+ final String address = SocketAddressUtils.getAddressFirst(socketAddress);
verifier.verifyTraceCount(2);
Method process = TBaseAsyncProcessor.class.getDeclaredMethod("process", AsyncFrameBuffer.class);
// RootSpan
verifier.verifyTrace(root("THRIFT_SERVER", // ServiceType,
"Thrift Server Invocation", // Method
"com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo", // rpc
- actualServerAddress.getHostName() + ":" + actualServerAddress.getPort(), // endPoint
- actualServerAddress.getHostName() // remoteAddress
+ HostAndPort.toHostAndPortString(address, socketAddress.getPort()), // endPoint
+ address // remoteAddress
));
// SpanEvent - TBaseAsyncProcessor.process
verifier.verifyTrace(event("THRIFT_SERVER_INTERNAL", process));
diff --git a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/SyncEchoTestServer.java b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/SyncEchoTestServer.java
index fa8361b9dc0f..53e50c30f132 100644
--- a/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/SyncEchoTestServer.java
+++ b/agent/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/SyncEchoTestServer.java
@@ -22,6 +22,8 @@
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
+import com.navercorp.pinpoint.bootstrap.plugin.util.SocketAddressUtils;
+import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
import org.apache.thrift.TBaseProcessor;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TProtocol;
@@ -52,7 +54,8 @@ protected SyncEchoTestServer(T server, TestEnvironment environment) throws TTran
@Override
public void verifyServerTraces(PluginTestVerifier verifier) throws Exception {
- final InetSocketAddress actualServerAddress = super.environment.getServerAddress();
+ final InetSocketAddress socketAddress = super.environment.getServerAddress();
+ final String address = SocketAddressUtils.getAddressFirst(socketAddress);
verifier.verifyTraceCount(2);
Method process = TBaseProcessor.class.getDeclaredMethod("process", TProtocol.class, TProtocol.class);
verifier.verifyDiscreteTrace(
@@ -60,8 +63,8 @@ public void verifyServerTraces(PluginTestVerifier verifier) throws Exception {
root("THRIFT_SERVER", // ServiceType,
"Thrift Server Invocation", // Method
"com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo", // rpc
- actualServerAddress.getHostName() + ":" + actualServerAddress.getPort(), // endPoint
- actualServerAddress.getHostName()), // remoteAddress
+ HostAndPort.toHostAndPortString(address, socketAddress.getPort()), // endPoint
+ address), // remoteAddress
// SpanEvent - TBaseProcessor.process
event("THRIFT_SERVER_INTERNAL", process));
verifier.verifyTraceCount(0);
diff --git a/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/plugin/util/SocketAddressUtilsTest.java b/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/plugin/util/SocketAddressUtilsTest.java
new file mode 100644
index 000000000000..2ffa1c97abc1
--- /dev/null
+++ b/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/plugin/util/SocketAddressUtilsTest.java
@@ -0,0 +1,290 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.bootstrap.plugin.util;
+
+import com.navercorp.pinpoint.common.util.JvmUtils;
+import org.junit.Assert;
+import org.junit.Assume;
+import org.junit.AssumptionViolatedException;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import java.util.Collections;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class SocketAddressUtilsTest {
+
+ private static final String VALID_HOST = "naver.com";
+ private static final String INVALID_HOST = "pinpoint-none-existent-domain-hopefully";
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(SocketAddressUtilsTest.class);
+
+ private static NameServiceReplacer NAME_SERVICE_REPLACER;
+
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ NAME_SERVICE_REPLACER = createNameServiceReplacer();
+ }
+
+ @Test
+ public void fromValidHostName() {
+ String hostName = VALID_HOST;
+ InetSocketAddress socketAddress = new InetSocketAddress(hostName, 80);
+ assertResolved(socketAddress);
+
+ final String expectedHostName = hostName;
+ final String expectedAddress = socketAddress.getAddress().getHostAddress();
+
+ verify(socketAddress, expectedHostName, expectedAddress);
+ }
+
+ @Test
+ public void fromValidHostNameUnresolved() {
+ String hostName = VALID_HOST;
+ InetSocketAddress socketAddress = InetSocketAddress.createUnresolved(hostName, 80);
+ assertUnresolved(socketAddress);
+
+ final String expectedHostName = hostName;
+ final String expectedAddress = hostName;
+
+ verify(socketAddress, expectedHostName, expectedAddress);
+ }
+
+ @Test
+ public void fromInvalidHostName() {
+ String hostName = INVALID_HOST;
+ InetSocketAddress socketAddress = new InetSocketAddress(hostName, 80);
+ assertUnresolved(socketAddress);
+
+ final String expectedHostName = hostName;
+ final String expectedAddress = hostName;
+
+ verify(socketAddress, expectedHostName, expectedAddress);
+ }
+
+ @Test
+ public void fromAddress() {
+ String hostName = VALID_HOST;
+ InetAddress inetAddress = createAddressFromHostName(hostName);
+ Assume.assumeNotNull(inetAddress);
+
+ String address = inetAddress.getHostAddress();
+ InetSocketAddress socketAddress = new InetSocketAddress(address, 80);
+ assertResolved(socketAddress);
+
+ final String expectedHostName = address;
+ final String expectedAddress = address;
+
+ verify(socketAddress, expectedHostName, expectedAddress);
+ }
+
+ @Test
+ public void fromLookedUpAddress() {
+ String hostName = VALID_HOST;
+ InetAddress inetAddress = createAddressFromHostName(hostName);
+ Assume.assumeNotNull(inetAddress);
+
+ String address = inetAddress.getHostAddress();
+ InetSocketAddress socketAddress = new InetSocketAddress(address, 80);
+ assertResolved(socketAddress);
+
+ String expectedHostName = socketAddress.getHostName(); // lookup host name
+ String expectedAddress = address;
+
+ verify(socketAddress, expectedHostName, expectedAddress);
+ }
+
+ @Test
+ public void fromLocalAddress() {
+ InetAddress inetAddress = createLocalAddress();
+ Assume.assumeNotNull(inetAddress);
+
+ String address = inetAddress.getHostAddress();
+ InetSocketAddress socketAddress = new InetSocketAddress(address, 80);
+ assertResolved(socketAddress);
+
+ final String expectedHostName = address;
+ final String expectedAddress = address;
+
+ verify(socketAddress, expectedHostName, expectedAddress);
+ }
+
+ // Helpers
+
+ private static void assertResolved(InetSocketAddress socketAddress) {
+ Assert.assertFalse(socketAddress.isUnresolved());
+ }
+
+ private static void assertUnresolved(InetSocketAddress socketAddress) {
+ Assert.assertTrue(socketAddress.isUnresolved());
+ }
+
+ private static void verify(InetSocketAddress socketAddress, String expectedHostName, String expectedAddress) {
+ NAME_SERVICE_REPLACER.replace();
+ try {
+ String actualHostName = SocketAddressUtils.getHostNameFirst(socketAddress);
+ String actualAddress = SocketAddressUtils.getAddressFirst(socketAddress);
+ LOGGER.info("expectedHostName : {}, actualHostName : {}", expectedHostName, actualHostName);
+ LOGGER.info("expectedAddress : {}, actualAddress : {}", expectedAddress, actualAddress);
+ Assert.assertEquals(expectedHostName, actualHostName);
+ Assert.assertEquals(expectedAddress, actualAddress);
+ } finally {
+ NAME_SERVICE_REPLACER.rollback();
+ }
+ }
+
+ private static InetAddress createLocalAddress() {
+ try {
+ return InetAddress.getLocalHost();
+ } catch (UnknownHostException e) {
+ LOGGER.warn("Error creating local InetAddress", e);
+ return null;
+ }
+ }
+
+ private static InetAddress createAddressFromHostName(String hostName) {
+ try {
+ return InetAddress.getByName(hostName);
+ } catch (UnknownHostException e) {
+ LOGGER.warn("Error creating InetAddress from host : {}", hostName, e);
+ return null;
+ }
+ }
+
+ private interface NameServiceReplacer {
+ void replace();
+ void rollback();
+ }
+
+ private static NameServiceReplacer createNameServiceReplacer() {
+
+ Class<?> nameServiceClass = null;
+ try {
+ // pre jdk 9
+ nameServiceClass = Class.forName("sun.net.spi.nameservice.NameService");
+ } catch (ClassNotFoundException e) {
+ try {
+ // post jdk 9
+ nameServiceClass = Class.forName("java.net.InetAddress$NameService");
+ } catch (ClassNotFoundException e1) {
+ // ignore and skip test below
+ }
+ }
+
+ if (nameServiceClass == null) {
+ LOGGER.error("[{}] {} - NameService class not found, skipping test.",
+ JvmUtils.getType(), JvmUtils.getVersion());
+ throw new AssumptionViolatedException("NameService class required for test not found.");
+ }
+
+ ClassLoader cl = InetAddress.class.getClassLoader();
+ final Object proxy = Proxy.newProxyInstance(cl, new Class<?>[]{nameServiceClass}, new InvocationHandler() {
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ String methodName = method.getName();
+ if (methodName.equals("lookupAllHostAddr")) {
+ throw new UnsupportedOperationException("DNS lookup should not be made");
+ } else if (methodName.equals("getHostByAddr")) {
+ throw new UnsupportedOperationException("Reverse DNS lookup should not be made");
+ } else if (methodName.equals("toString")) {
+ return SocketAddressUtilsTest.class.getSimpleName() + " Name Service";
+ } else {
+ LOGGER.error("[{}] {} - Unexpected method invocation : {}",
+ JvmUtils.getType(), JvmUtils.getVersion(), methodName);
+ throw new IllegalStateException("Unknown method : " + methodName + " invoked");
+ }
+ }
+ });
+
+ // jdk 7, 8
+ final String nameServicesFieldName = "nameServices";
+ final Object nameServicesFieldValue = getNameServiceFieldValue(nameServicesFieldName);
+ if (nameServicesFieldValue != null) {
+ return new NameServiceReplacer() {
+ @Override
+ public void replace() {
+ setNameServiceFieldValue(nameServicesFieldName, Collections.singletonList(proxy));
+ }
+
+ @Override
+ public void rollback() {
+ setNameServiceFieldValue(nameServicesFieldName, nameServicesFieldValue);
+ }
+ };
+ }
+
+ // jdk 6, jdk 9+
+ final String nameServiceFieldName = "nameService";
+ final Object nameServiceFieldValue = getNameServiceFieldValue(nameServiceFieldName);
+ if (nameServiceFieldValue != null) {
+ return new NameServiceReplacer() {
+ @Override
+ public void replace() {
+ setNameServiceFieldValue(nameServiceFieldName, proxy);
+ }
+
+ @Override
+ public void rollback() {
+ setNameServiceFieldValue(nameServiceFieldName, nameServiceFieldValue);
+ }
+ };
+ }
+
+ LOGGER.error("[{}] {} - Field for name service not found.", JvmUtils.getType(), JvmUtils.getVersion());
+ throw new AssumptionViolatedException("Cannot find field for name service.");
+ }
+
+ private static Object getNameServiceFieldValue(String fieldName) {
+ try {
+ Field nameServiceField = InetAddress.class.getDeclaredField(fieldName);
+ nameServiceField.setAccessible(true);
+ return nameServiceField.get(null);
+ } catch (NoSuchFieldException e) {
+ // This can happen depending on jvm
+ return null;
+ } catch (Exception e) {
+ LOGGER.error("[{}] {} - Unexpected error while getting field [{}], skipping test",
+ JvmUtils.getType(), JvmUtils.getVersion(), fieldName, e);
+ throw new AssumptionViolatedException("Unexpected reflection exception", e);
+ }
+ }
+
+ private static void setNameServiceFieldValue(String fieldName, Object nameService) {
+ try {
+ Field nameServiceField = InetAddress.class.getDeclaredField(fieldName);
+ nameServiceField.setAccessible(true);
+ nameServiceField.set(null, nameService);
+ } catch (NoSuchFieldException e) {
+ throw new IllegalStateException("Expected field : [" + fieldName + "] not found");
+ } catch (Exception e) {
+ LOGGER.error("[{}] {} - Unexpected error while setting field [{}], skipping test",
+ JvmUtils.getType(), JvmUtils.getVersion(), fieldName, e);
+ throw new AssumptionViolatedException("Unexpected reflection exception", e);
+ }
+ }
+}
| train | val | "2018-08-01T03:12:50" | "2018-07-20T08:52:25Z" | nickycheng | test |
pinpoint-apm/pinpoint/4439_4440 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4439 | pinpoint-apm/pinpoint/4440 | [
"keyword_pr_to_issue"
] | 992ae5f6a1a84645c78df44623859ae6adec68f3 | 8ce5b4b41117961f909e6803d93d85c8bf018ab9 | [] | [] | "2018-08-02T06:37:59Z" | [
"module:agent",
"configuration"
] | Change default agent sampling rate to 100% | #### Description
Current pinpoint agent binary has `profiler.sampling.rate` set to 20. This caused too much confusion as only 1 out of 20 requests were being traced out of the box.
Changing this value to 1 would make it far less confusing.
If overhead becomes an issue, there is still the *pinpoint-real-env-lowoverhead-sample.config* to refer to. | [
"agent/src/assembly/distribution.xml",
"agent/src/main/resources-release/pinpoint.config"
] | [
"agent/src/assembly/distribution.xml",
"agent/src/main/resources-release/pinpoint.config"
] | [] | diff --git a/agent/src/assembly/distribution.xml b/agent/src/assembly/distribution.xml
index 8b7b28fadd1c..33de45f8385c 100644
--- a/agent/src/assembly/distribution.xml
+++ b/agent/src/assembly/distribution.xml
@@ -26,10 +26,6 @@
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
- <fileSet>
- <directory>${basedir}/src/main/resources</directory>
- <outputDirectory></outputDirectory>
- </fileSet>
<fileSet>
<directory>${basedir}/src/main/resources-${env}</directory>
<outputDirectory></outputDirectory>
diff --git a/agent/src/main/resources-release/pinpoint.config b/agent/src/main/resources-release/pinpoint.config
index 4db5fc799f37..7bcc34f06207 100644
--- a/agent/src/main/resources-release/pinpoint.config
+++ b/agent/src/main/resources-release/pinpoint.config
@@ -46,7 +46,7 @@ profiler.jvm.stat.collect.detailed.metrics=true
profiler.sampling.enable=true
# 1 out of n transactions will be sampled where n is the rate. (20: 5%)
-profiler.sampling.rate=20
+profiler.sampling.rate=1
# Allow buffering when flushing span to IO.
profiler.io.buffering.enable=true
| null | val | val | "2018-08-01T10:43:44" | "2018-08-02T06:31:09Z" | Xylus | test |
pinpoint-apm/pinpoint/4560_4600 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4560 | pinpoint-apm/pinpoint/4600 | [
"keyword_pr_to_issue"
] | 732fc77fdad8df8caaf7d28dd1095894e90a0e3d | 96eb38846f69a6369ef61f6f1099eb709704223b | [] | [] | "2018-09-10T07:07:08Z" | [
"module:web"
] | Remove container agents that are not relevant from Inspector View's agent list | #### Description
Since containers are meant to be regularly created and destroyed, new agent ids are usually set up to be created every time a container is created.
This will result in an ever-growing number of agents in Inspector View's agent list as containers are created and destroyed.
Showing only the agents that were running in the queried time period would be a way to keep the agent list relevant and easy to read. | [
"web/src/main/java/com/navercorp/pinpoint/web/batch/job/AgentCountReader.java",
"web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java",
"web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/batch/job/AgentCountReader.java",
"web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java",
"web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java",
"web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsListTest.java"
] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/batch/job/AgentCountReader.java b/web/src/main/java/com/navercorp/pinpoint/web/batch/job/AgentCountReader.java
index 173fd701c844..63ec81fe8bfe 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/batch/job/AgentCountReader.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/batch/job/AgentCountReader.java
@@ -42,7 +42,8 @@ public class AgentCountReader implements ItemReader<ApplicationAgentsList>, Step
@Override
public void beforeStep(StepExecution stepExecution) {
- ApplicationAgentsList applicationAgentList = agentInfoService.getAllApplicationAgentsList();
+ long timestamp = System.currentTimeMillis();
+ ApplicationAgentsList applicationAgentList = agentInfoService.getAllApplicationAgentsList(ApplicationAgentsList.Filter.NONE, timestamp);
queue.add(applicationAgentList);
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java
index 11ec10f200fe..56ae264db941 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java
@@ -17,6 +17,7 @@
package com.navercorp.pinpoint.web.controller;
import com.navercorp.pinpoint.common.PinpointConstants;
+import com.navercorp.pinpoint.common.server.util.AgentLifeCycleState;
import com.navercorp.pinpoint.common.util.IdValidateUtils;
import com.navercorp.pinpoint.web.service.AgentEventService;
import com.navercorp.pinpoint.web.service.AgentInfoService;
@@ -57,7 +58,8 @@ public class AgentInfoController {
@RequestMapping(value = "/getAgentList", method = RequestMethod.GET, params = {"!application"})
@ResponseBody
public ApplicationAgentsList getAgentList() {
- return this.agentInfoService.getAllApplicationAgentsList();
+ long timestamp = System.currentTimeMillis();
+ return getAgentList(timestamp);
}
@RequestMapping(value = "/getAgentList", method = RequestMethod.GET, params = {"!application", "from", "to"})
@@ -65,7 +67,8 @@ public ApplicationAgentsList getAgentList() {
public ApplicationAgentsList getAgentList(
@RequestParam("from") long from,
@RequestParam("to") long to) {
- return this.agentInfoService.getAllApplicationAgentsList(to);
+ long timestamp = to;
+ return this.agentInfoService.getAllApplicationAgentsList(ApplicationAgentsList.Filter.NONE, timestamp);
}
@PreAuthorize("hasPermission(#applicationName, 'application', 'inspector')")
@@ -73,14 +76,14 @@ public ApplicationAgentsList getAgentList(
@ResponseBody
public ApplicationAgentsList getAgentList(
@RequestParam("timestamp") long timestamp) {
- return this.agentInfoService.getAllApplicationAgentsList(timestamp);
+ return this.agentInfoService.getAllApplicationAgentsList(ApplicationAgentsList.Filter.NONE, timestamp);
}
@RequestMapping(value = "/getAgentList", method = RequestMethod.GET, params = {"application"})
@ResponseBody
- public ApplicationAgentsList getAgentList(
- @RequestParam("application") String applicationName) {
- return this.agentInfoService.getApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, applicationName);
+ public ApplicationAgentsList getAgentList(@RequestParam("application") String applicationName) {
+ long timestamp = System.currentTimeMillis();
+ return getAgentList(applicationName, timestamp);
}
@PreAuthorize("hasPermission(#applicationName, 'application', 'inspector')")
@@ -90,7 +93,17 @@ public ApplicationAgentsList getAgentList(
@RequestParam("application") String applicationName,
@RequestParam("from") long from,
@RequestParam("to") long to) {
- return this.agentInfoService.getApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, applicationName, to);
+ ApplicationAgentsList.Filter containerFilter = agentInfo -> {
+ if (agentInfo.isContainer()) {
+ AgentStatus agentStatus = agentInfo.getStatus();
+ if (agentStatus == null || agentStatus.getEventTimestamp() < from) {
+ return ApplicationAgentsList.Filter.REJECT;
+ }
+ }
+ return ApplicationAgentsList.Filter.ACCEPT;
+ };
+ long timestamp = to;
+ return this.agentInfoService.getApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, containerFilter, applicationName, timestamp);
}
@PreAuthorize("hasPermission(#applicationName, 'application', 'inspector')")
@@ -99,7 +112,16 @@ public ApplicationAgentsList getAgentList(
public ApplicationAgentsList getAgentList(
@RequestParam("application") String applicationName,
@RequestParam("timestamp") long timestamp) {
- return this.agentInfoService.getApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, applicationName, timestamp);
+ ApplicationAgentsList.Filter runningContainerFilter = agentInfo -> {
+ if (agentInfo.isContainer()) {
+ AgentStatus agentStatus = agentInfo.getStatus();
+ if (agentStatus == null || agentStatus.getState() != AgentLifeCycleState.RUNNING) {
+ return ApplicationAgentsList.Filter.REJECT;
+ }
+ }
+ return ApplicationAgentsList.Filter.ACCEPT;
+ };
+ return this.agentInfoService.getApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, runningContainerFilter, applicationName, timestamp);
}
@RequestMapping(value = "/getAgentInfo", method = RequestMethod.GET)
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java
index d3f96c542189..78c42b4542fb 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java
@@ -33,13 +33,9 @@
*/
public interface AgentInfoService {
- ApplicationAgentsList getAllApplicationAgentsList();
+ ApplicationAgentsList getAllApplicationAgentsList(ApplicationAgentsList.Filter filter, long timestamp);
- ApplicationAgentsList getAllApplicationAgentsList(long timestamp);
-
- ApplicationAgentsList getApplicationAgentsList(ApplicationAgentsList.GroupBy key, String applicationName);
-
- ApplicationAgentsList getApplicationAgentsList(ApplicationAgentsList.GroupBy key, String applicationName, long timestamp);
+ ApplicationAgentsList getApplicationAgentsList(ApplicationAgentsList.GroupBy key, ApplicationAgentsList.Filter filter, String applicationName, long timestamp);
ApplicationAgentHostList getApplicationAgentHostList(int offset, int limit);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java
index 636b2c87b725..e8dae1c1c31a 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java
@@ -85,35 +85,25 @@ public class AgentInfoServiceImpl implements AgentInfoService {
private AgentDownloadInfoDao agentDownloadInfoDao;
@Override
- public ApplicationAgentsList getAllApplicationAgentsList() {
- return getAllApplicationAgentsList(System.currentTimeMillis());
- }
-
- @Override
- public ApplicationAgentsList getAllApplicationAgentsList(long timestamp) {
+ public ApplicationAgentsList getAllApplicationAgentsList(ApplicationAgentsList.Filter filter, long timestamp) {
ApplicationAgentsList.GroupBy groupBy = ApplicationAgentsList.GroupBy.APPLICATION_NAME;
- ApplicationAgentsList applicationAgentList = new ApplicationAgentsList(groupBy);
+ ApplicationAgentsList applicationAgentList = new ApplicationAgentsList(groupBy, filter);
List<Application> applications = applicationIndexDao.selectAllApplicationNames();
for (Application application : applications) {
- applicationAgentList.merge(getApplicationAgentsList(groupBy, application.getName(), timestamp));
+ applicationAgentList.merge(getApplicationAgentsList(groupBy, filter, application.getName(), timestamp));
}
return applicationAgentList;
}
@Override
- public ApplicationAgentsList getApplicationAgentsList(ApplicationAgentsList.GroupBy groupBy, String applicationName) {
- return getApplicationAgentsList(groupBy, applicationName, System.currentTimeMillis());
- }
-
- @Override
- public ApplicationAgentsList getApplicationAgentsList(ApplicationAgentsList.GroupBy groupBy, String applicationName, long timestamp) {
+ public ApplicationAgentsList getApplicationAgentsList(ApplicationAgentsList.GroupBy groupBy, ApplicationAgentsList.Filter filter, String applicationName, long timestamp) {
if (applicationName == null) {
throw new NullPointerException("applicationName must not be null");
}
if (groupBy == null) {
throw new NullPointerException("groupBy must not be null");
}
- ApplicationAgentsList applicationAgentsList = new ApplicationAgentsList(groupBy);
+ ApplicationAgentsList applicationAgentsList = new ApplicationAgentsList(groupBy, filter);
Set<AgentInfo> agentInfos = getAgentsByApplicationName(applicationName, timestamp);
if (agentInfos.isEmpty()) {
logger.warn("agent list is empty for application:{}", applicationName);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java
index c8245c7a3f05..62529b25c1bc 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java
@@ -56,15 +56,29 @@ private interface GroupingKey<T extends GroupingKey<T>> extends Comparable<T> {
String value();
}
+ public interface Filter {
+
+ boolean ACCEPT = true;
+ boolean REJECT = false;
+
+ boolean filter(AgentInfo agentInfo);
+
+ Filter NONE = agentInfo -> ACCEPT;
+ }
+
private final GroupBy groupBy;
- private final SortedMap<GroupingKey, List<AgentInfo>> agentsMap;
+ private final Filter filter;
+ private final SortedMap<GroupingKey, List<AgentInfo>> agentsMap = new TreeMap<>();
- public ApplicationAgentsList(GroupBy groupBy) {
+ public ApplicationAgentsList(GroupBy groupBy, Filter filter) {
this.groupBy = Objects.requireNonNull(groupBy, "groupBy must not be null");
- this.agentsMap = new TreeMap<>();
+ this.filter = Objects.requireNonNull(filter, "filter must not be null");
}
public void add(AgentInfo agentInfo) {
+ if (filter.filter(agentInfo) == Filter.REJECT) {
+ return;
+ }
GroupingKey key = groupBy.extractKey(agentInfo);
List<AgentInfo> agentInfos = agentsMap.computeIfAbsent(key, k -> new ArrayList<>());
agentInfos.add(agentInfo);
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsListTest.java b/web/src/test/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsListTest.java
index 0f95c92c4e5c..db813b604f05 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsListTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsListTest.java
@@ -30,7 +30,7 @@ public class ApplicationAgentsListTest {
@Test
public void groupByApplicationName() {
- ApplicationAgentsList applicationAgentsList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.APPLICATION_NAME);
+ ApplicationAgentsList applicationAgentsList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.APPLICATION_NAME, ApplicationAgentsList.Filter.NONE);
AgentInfo app1Agent1 = createAgentInfo("APP_1", "app1-agent1", "Host11", true);
AgentInfo app1Agent2 = createAgentInfo("APP_1", "app1-agent2", "Host12", false);
AgentInfo app2Agent1 = createAgentInfo("APP_2", "app2-agent1", "Host21", false);
@@ -58,7 +58,7 @@ public void groupByApplicationName() {
@Test
public void groupByHostNameShouldHaveContainersLastAndGroupedSeparately() {
- ApplicationAgentsList applicationAgentsList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME);
+ ApplicationAgentsList applicationAgentsList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, ApplicationAgentsList.Filter.NONE);
AgentInfo host1Agent1 = createAgentInfo("APP_1", "host1-agent1", "Host1", false);
AgentInfo host2Agent1 = createAgentInfo("APP_1", "host2-agent1", "Host2", false);
AgentInfo containerAgent1 = createAgentInfo("APP_1", "container-agent1", "Host3", true);
@@ -97,9 +97,9 @@ public void mergeLists() {
AgentInfo containerAgent2 = createAgentInfo("APP_1", "container-agent2", "Host4", true);
List<AgentInfo> agentInfos = shuffleAgentInfos(containerAgent1, host1Agent1, host2Agent1, containerAgent2);
- ApplicationAgentsList applicationAgentsList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME);
+ ApplicationAgentsList applicationAgentsList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, ApplicationAgentsList.Filter.NONE);
applicationAgentsList.addAll(agentInfos.subList(0, agentInfos.size() / 2));
- ApplicationAgentsList applicationAgentsListToMerge = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME);
+ ApplicationAgentsList applicationAgentsListToMerge = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, ApplicationAgentsList.Filter.NONE);
applicationAgentsListToMerge.addAll(agentInfos.subList(agentInfos.size() / 2, agentInfos.size()));
applicationAgentsList.merge(applicationAgentsListToMerge);
@@ -132,9 +132,9 @@ public void mergeListsGroupedDifferently() {
AgentInfo agent1 = createAgentInfo("APP_1", "app1-agent1", "Host1", false);
AgentInfo agent2 = createAgentInfo("APP_2", "app2-agent1", "Host2", false);
AgentInfo agent3 = createAgentInfo("APP_2", "app2-agent2", "Host2", true);
- ApplicationAgentsList groupedByHostnameList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME);
+ ApplicationAgentsList groupedByHostnameList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, ApplicationAgentsList.Filter.NONE);
groupedByHostnameList.add(agent1);
- ApplicationAgentsList groupedByApplicationNameList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.APPLICATION_NAME);
+ ApplicationAgentsList groupedByApplicationNameList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.APPLICATION_NAME, ApplicationAgentsList.Filter.NONE);
groupedByApplicationNameList.add(agent2);
groupedByApplicationNameList.add(agent3);
| train | val | "2018-09-06T09:32:25" | "2018-08-28T09:17:59Z" | Xylus | test |
pinpoint-apm/pinpoint/4472_4639 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4472 | pinpoint-apm/pinpoint/4639 | [
"keyword_pr_to_issue"
] | 6d8947fef34c6521a72ed2d4574a063f7fe6c71f | 39e2f8064d4ec96767464c181701aa7c642f9cf4 | [] | [] | "2018-09-19T02:45:48Z" | [
"enhancement",
"module:plugin"
] | Propagate trace info when sending messages to ActiveMQ with null properties | #### Description
ActiveMQ plugin injects pinpoint-specific headers into ActiveMQ's **AMQP.BasicProperties** to propagate trace info over to the consumer.
However, it is valid to have the sender supply `null` for **AMQP.BasicProperties** in which case, ActiveMQ plugin cannot propagate trace info over to the consumer as it does not have any object in which to inject the headers.
We might have to delay the header injection in order to support these scenarios.
related issue - #4463 | [
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientConstants.java",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java"
] | [
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientConstants.java",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/aspect/ChannelAspect.java",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/AMQCommandConstructInterceptor.java",
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java"
] | [] | diff --git a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientConstants.java b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientConstants.java
index 70487fd9f64f..e3046c0b4f6d 100644
--- a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientConstants.java
+++ b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientConstants.java
@@ -36,7 +36,7 @@ private RabbitMQClientConstants() {
public static final ServiceType RABBITMQ_CLIENT = ServiceTypeFactory.of(8300, "RABBITMQ_CLIENT", QUEUE, RECORD_STATISTICS);
public static final ServiceType RABBITMQ_CLIENT_INTERNAL = ServiceTypeFactory.of(8301, "RABBITMQ_CLIENT_INTERNAL", "RABBITMQ_CLIENT");
- public static final String RABBITMQ_SCOPE = "rabbitmqScope";
+ public static final String RABBITMQ_PRODUCER_SCOPE = "rabbitmqProducerScope";
public static final String RABBITMQ_CONSUMER_SCOPE = "rabbitmqConsumerScope";
public static final String RABBITMQ_FRAME_HANDLER_CREATION_SCOPE = "rabbitmqFrameHandlerCreationScope";
public static final String RABBITMQ_TEMPLATE_API_SCOPE = "rabbitmqTemplateApiScope";
diff --git a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
index e31fdbf35cfc..fe0a042d21ef 100644
--- a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
+++ b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
@@ -93,9 +93,12 @@ private ChannelTransformCallback(boolean traceProducer, boolean traceConsumer) {
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
if (traceProducer) {
+ // copy AMQP.BasicProperties
+ target.weave("com.navercorp.pinpoint.plugin.rabbitmq.client.aspect.ChannelAspect");
+
final InstrumentMethod basicPublish = target.getDeclaredMethod("basicPublish", "java.lang.String", "java.lang.String", "boolean", "boolean", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]");
if (basicPublish != null) {
- basicPublish.addScopedInterceptor("com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.ChannelBasicPublishInterceptor", RabbitMQClientConstants.RABBITMQ_SCOPE);
+ basicPublish.addScopedInterceptor("com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.ChannelBasicPublishInterceptor", RabbitMQClientConstants.RABBITMQ_PRODUCER_SCOPE, ExecutionPolicy.BOUNDARY);
}
}
if (traceConsumer) {
@@ -155,6 +158,18 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
return target.toBytecode();
}
});
+ // AMQCommand - for pinpoint header propagation
+ transformTemplate.transform("com.rabbitmq.client.impl.AMQCommand", new TransformCallback() {
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+ InstrumentMethod constructor = target.getConstructor("com.rabbitmq.client.Method", "com.rabbitmq.client.impl.AMQContentHeader", "byte[]");
+ if (constructor != null) {
+ constructor.addScopedInterceptor("com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.AMQCommandConstructInterceptor", RabbitMQClientConstants.RABBITMQ_PRODUCER_SCOPE, ExecutionPolicy.INTERNAL);
+ }
+ return target.toBytecode();
+ }
+ });
}
private void addAMQChannelEditor(final Filter<String> excludeExchangeFilter) {
diff --git a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/aspect/ChannelAspect.java b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/aspect/ChannelAspect.java
new file mode 100644
index 000000000000..810ceb40bdbd
--- /dev/null
+++ b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/aspect/ChannelAspect.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.rabbitmq.client.aspect;
+
+import com.navercorp.pinpoint.bootstrap.instrument.aspect.Aspect;
+import com.navercorp.pinpoint.bootstrap.instrument.aspect.JointPoint;
+import com.navercorp.pinpoint.bootstrap.instrument.aspect.PointCut;
+import com.rabbitmq.client.AMQP;
+import com.rabbitmq.client.MessageProperties;
+
+/**
+ * Make a copy of {@code AMQP.BasicProperties} to inject pinpoint headers.
+ *
+ * @author HyunGil Jeong
+ */
+@Aspect
+public abstract class ChannelAspect {
+ @PointCut
+ public void basicPublish(String exchange, String routingKey,
+ boolean mandatory, boolean immediate,
+ AMQP.BasicProperties props, byte[] body) {
+ AMQP.BasicProperties sourceProps = props;
+ if (sourceProps == null) {
+ sourceProps = MessageProperties.MINIMAL_BASIC;
+ }
+ AMQP.BasicProperties useProps = copy(sourceProps);
+ __basicPublish(exchange, routingKey, mandatory, immediate, useProps, body);
+ }
+
+ private AMQP.BasicProperties copy(AMQP.BasicProperties source) {
+ AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
+ builder.contentType(source.getContentType());
+ builder.contentEncoding(source.getContentEncoding());
+ builder.headers(source.getHeaders());
+ builder.deliveryMode(source.getDeliveryMode());
+ builder.priority(source.getPriority());
+ builder.correlationId(source.getCorrelationId());
+ builder.replyTo(source.getReplyTo());
+ builder.expiration(source.getExpiration());
+ builder.messageId(source.getMessageId());
+ builder.timestamp(source.getTimestamp());
+ builder.type(source.getType());
+ builder.userId(source.getUserId());
+ builder.appId(source.getAppId());
+ builder.clusterId(source.getClusterId());
+ return builder.build();
+ }
+
+ @JointPoint
+ abstract void __basicPublish(String exchange, String routingKey,
+ boolean mandatory, boolean immediate,
+ AMQP.BasicProperties props, byte[] body);
+}
diff --git a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/AMQCommandConstructInterceptor.java b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/AMQCommandConstructInterceptor.java
new file mode 100644
index 000000000000..948e6333cd50
--- /dev/null
+++ b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/AMQCommandConstructInterceptor.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor;
+
+import com.navercorp.pinpoint.bootstrap.context.Trace;
+import com.navercorp.pinpoint.bootstrap.context.TraceContext;
+import com.navercorp.pinpoint.bootstrap.context.TraceId;
+import com.navercorp.pinpoint.bootstrap.interceptor.AroundInterceptor;
+import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope;
+import com.navercorp.pinpoint.bootstrap.logging.PLogger;
+import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
+import com.navercorp.pinpoint.common.util.MapUtils;
+import com.navercorp.pinpoint.plugin.rabbitmq.client.RabbitMQClientConstants;
+import com.navercorp.pinpoint.plugin.rabbitmq.client.field.setter.HeadersFieldSetter;
+import com.rabbitmq.client.AMQP;
+import com.rabbitmq.client.Method;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * <p>{@code AMQContentHeader} received as an argument to the constructor is sharable and can be reused, such as
+ * {@code MessageProperties.MINIMAL_BASIC}. Any changes made to it (ie injecting pinpoint headers) may have undesirable
+ * consequences.
+ *
+ * <p>Hence, we make a copy via {@code ChannelAspect} and add pinpoint headers to it when propagating trace, and have
+ * {@code AMQCommand} use this.
+ *
+ * @author HyunGil Jeong
+ *
+ * @see com.navercorp.pinpoint.plugin.rabbitmq.client.aspect.ChannelAspect
+ */
+public class AMQCommandConstructInterceptor implements AroundInterceptor {
+
+ // AMQP spec
+ private static final String AMQP_METHOD_TO_INTERCEPT = "basic.publish";
+
+ private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
+ private final boolean isDebug = logger.isDebugEnabled();
+
+ private final TraceContext traceContext;
+ private final InterceptorScope scope;
+
+ public AMQCommandConstructInterceptor(TraceContext traceContext, InterceptorScope scope) {
+ this.traceContext = traceContext;
+ this.scope = scope;
+ }
+
+ @Override
+ public void before(Object target, Object[] args) {
+ if (!validate(target, args)) {
+ return;
+ }
+
+ if (isDebug) {
+ logger.beforeInterceptor(target, args);
+ }
+
+ Trace trace = traceContext.currentRawTraceObject();
+ if (trace == null) {
+ return;
+ }
+
+ final AMQP.BasicProperties properties = (AMQP.BasicProperties) args[1];
+ final Map<String, Object> headers = createHeader(properties, trace);
+ if (headers != null) {
+ ((HeadersFieldSetter) properties)._$PINPOINT$_setHeaders(headers);
+ }
+ }
+
+ private Map<String, Object> createHeader(AMQP.BasicProperties properties, Trace trace) {
+ final Map<String, Object> headers = copyHeader(properties);
+ if (trace.canSampled()) {
+ TraceId nextId = retrieveNextTraceId();
+ if (nextId == null) {
+ return null;
+ }
+ headers.put(RabbitMQClientConstants.META_TRACE_ID, nextId.getTransactionId());
+ headers.put(RabbitMQClientConstants.META_SPAN_ID, Long.toString(nextId.getSpanId()));
+ headers.put(RabbitMQClientConstants.META_PARENT_SPAN_ID, Long.toString(nextId.getParentSpanId()));
+ headers.put(RabbitMQClientConstants.META_PARENT_APPLICATION_TYPE, Short.toString(traceContext.getServerTypeCode()));
+ headers.put(RabbitMQClientConstants.META_PARENT_APPLICATION_NAME, traceContext.getApplicationName());
+ headers.put(RabbitMQClientConstants.META_FLAGS, Short.toString(nextId.getFlags()));
+ } else {
+ headers.put(RabbitMQClientConstants.META_SAMPLED, "1");
+ }
+ return headers;
+ }
+
+ private Map<String, Object> copyHeader(AMQP.BasicProperties properties) {
+ final Map<String, Object> headers = properties.getHeaders();
+ if (MapUtils.isEmpty(headers)) {
+ return new HashMap<String, Object>();
+ }
+ // headers wrapped as unmodifiable map
+ return new HashMap<String, Object>(headers);
+ }
+
+ private TraceId retrieveNextTraceId() {
+ Object attachment = scope.getCurrentInvocation().getAttachment();
+ if (attachment == null) {
+ if (isDebug) {
+ logger.debug("Invalid attachment. Expected {}, but got null", TraceId.class.getName());
+ }
+ return null;
+ }
+ if (!(attachment instanceof TraceId)) {
+ if (isDebug) {
+ logger.debug("Invalid attachment. Expected {}, but got {}", TraceId.class.getName(), attachment.getClass());
+ }
+ return null;
+ }
+ return (TraceId) attachment;
+ }
+
+ @Override
+ public void after(Object target, Object[] args, Object result, Throwable throwable) {
+ if (!validate(target, args)) {
+ return;
+ }
+
+ if (isDebug) {
+ logger.afterInterceptor(target, args);
+ }
+ }
+
+ private boolean validate(Object target, Object[] args) {
+ if (args == null) {
+ if (isDebug) {
+ logger.debug("Expected arguments, but found none.");
+ }
+ return false;
+ }
+ if (args.length != 3) {
+ if (isDebug) {
+ logger.debug("Expected 3 arguments, but found {}", args.length);
+ }
+ return false;
+ }
+ Object method = args[0];
+ if (method == null) {
+ // valid, but this won't be null producer side
+ return false;
+ }
+ if (!(method instanceof Method)) {
+ if (isDebug) {
+ logger.debug("Expected args[0] to be {}, but was {}", Method.class.getName(), method.getClass().getName());
+ }
+ return false;
+ }
+ if (!AMQP_METHOD_TO_INTERCEPT.equals(((Method) method).protocolMethodName())) {
+ return false;
+ }
+ Object contentHeader = args[1];
+ if (!(contentHeader instanceof AMQP.BasicProperties)) {
+ // skip header injection for null, or non AMQP.BasicProperties header
+ return false;
+ }
+ if (!(contentHeader instanceof HeadersFieldSetter)) {
+ if (isDebug) {
+ logger.debug("Invalid args[1]({}) object. Need field setter({})", contentHeader, HeadersFieldSetter.class.getName());
+ }
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java
index aaf059a852c9..c3e0050d3469 100644
--- a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java
+++ b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java
@@ -7,25 +7,23 @@
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.bootstrap.context.TraceId;
import com.navercorp.pinpoint.bootstrap.interceptor.AroundInterceptor;
+import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope;
+import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScopeInvocation;
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
-import com.navercorp.pinpoint.common.util.MapUtils;
import com.navercorp.pinpoint.plugin.rabbitmq.client.RabbitMQClientPluginConfig;
import com.navercorp.pinpoint.plugin.rabbitmq.client.RabbitMQClientConstants;
import com.navercorp.pinpoint.plugin.rabbitmq.client.field.accessor.RemoteAddressAccessor;
-import com.navercorp.pinpoint.plugin.rabbitmq.client.field.setter.HeadersFieldSetter;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.impl.AMQConnection;
import com.rabbitmq.client.impl.FrameHandler;
-import java.util.HashMap;
-import java.util.Map;
-
/**
* @author Jinkai.Ma
* @author Jiaqi Feng
+ * @author HyunGil Jeong
*/
public class ChannelBasicPublishInterceptor implements AroundInterceptor {
@@ -34,11 +32,13 @@ public class ChannelBasicPublishInterceptor implements AroundInterceptor {
private final MethodDescriptor descriptor;
private final TraceContext traceContext;
+ private final InterceptorScope scope;
private final Filter<String> excludeExchangeFilter;
- public ChannelBasicPublishInterceptor(TraceContext traceContext, MethodDescriptor descriptor) {
+ public ChannelBasicPublishInterceptor(TraceContext traceContext, MethodDescriptor descriptor, InterceptorScope scope) {
this.descriptor = descriptor;
this.traceContext = traceContext;
+ this.scope = scope;
RabbitMQClientPluginConfig rabbitMQClientPluginConfig = new RabbitMQClientPluginConfig(traceContext.getProfilerConfig());
this.excludeExchangeFilter = rabbitMQClientPluginConfig.getExcludeExchangeFilter();
@@ -65,8 +65,6 @@ public void before(Object target, Object[] args) {
if (trace == null) {
return;
}
- final AMQP.BasicProperties properties = (AMQP.BasicProperties) args[4];
- final Map<String, Object> headers = copyHeader(properties);
if (trace.canSampled()) {
SpanEventRecorder recorder = trace.traceBlockBegin();
@@ -76,34 +74,11 @@ public void before(Object target, Object[] args) {
recorder.recordNextSpanId(nextId.getSpanId());
- headers.put(RabbitMQClientConstants.META_TRACE_ID, nextId.getTransactionId());
- headers.put(RabbitMQClientConstants.META_SPAN_ID, Long.toString(nextId.getSpanId()));
- headers.put(RabbitMQClientConstants.META_PARENT_SPAN_ID, Long.toString(nextId.getParentSpanId()));
- headers.put(RabbitMQClientConstants.META_PARENT_APPLICATION_TYPE, Short.toString(traceContext.getServerTypeCode()));
- headers.put(RabbitMQClientConstants.META_PARENT_APPLICATION_NAME, traceContext.getApplicationName());
- headers.put(RabbitMQClientConstants.META_FLAGS, Short.toString(nextId.getFlags()));
- } else {
- headers.put(RabbitMQClientConstants.META_SAMPLED, "1");
- }
-
- if (properties instanceof HeadersFieldSetter) {
- ((HeadersFieldSetter) properties)._$PINPOINT$_setHeaders(headers);
+ InterceptorScopeInvocation invocation = scope.getCurrentInvocation();
+ invocation.setAttachment(nextId);
}
}
- private Map<String, Object> copyHeader(AMQP.BasicProperties properties) {
- if (properties == null) {
- return new HashMap<String, Object>();
- }
-
- final Map<String, Object> headers = properties.getHeaders();
- if (MapUtils.isEmpty(headers)) {
- return new HashMap<String, Object>();
- }
-
- return new HashMap<String, Object>(headers);
- }
-
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
if (isDebug) {
| null | train | val | "2018-09-18T10:53:41" | "2018-08-07T06:45:04Z" | Xylus | test |
pinpoint-apm/pinpoint/4656_4659 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4656 | pinpoint-apm/pinpoint/4659 | [
"keyword_pr_to_issue"
] | c401f40fe645d85951c3ab654f70a1087d35a7f2 | 82b8c364dd4554678c7f90171d298d5b03760385 | [
"merged in 1.8.1-SNAPSHOT"
] | [] | "2018-09-20T07:25:16Z" | [
"enhancement",
"module:web"
] | Add an option to hide stack trace from web response | #### Description
Stack trace could be considered too sensitive to be exposed to users.
Giving an option to hide stack trace when an internal server error occurs in pinpoint web would be simple to implement. | [
"quickstart/web/src/main/resources/pinpoint-web.properties",
"web/src/main/java/com/navercorp/pinpoint/web/config/ConfigProperties.java",
"web/src/main/java/com/navercorp/pinpoint/web/controller/ConfigController.java",
"web/src/main/java/com/navercorp/pinpoint/web/controller/ControllerExceptionHandler.java",
"web/src/main/resources/pinpoint-web.properties"
] | [
"quickstart/web/src/main/resources/pinpoint-web.properties",
"web/src/main/java/com/navercorp/pinpoint/web/config/ConfigProperties.java",
"web/src/main/java/com/navercorp/pinpoint/web/controller/ConfigController.java",
"web/src/main/java/com/navercorp/pinpoint/web/controller/ControllerExceptionHandler.java",
"web/src/main/resources/pinpoint-web.properties"
] | [] | diff --git a/quickstart/web/src/main/resources/pinpoint-web.properties b/quickstart/web/src/main/resources/pinpoint-web.properties
index 400f157531cd..62273edece7b 100644
--- a/quickstart/web/src/main/resources/pinpoint-web.properties
+++ b/quickstart/web/src/main/resources/pinpoint-web.properties
@@ -28,6 +28,7 @@ config.sendUsage=true
config.editUserInfo=true
config.show.activeThread=true
config.show.activeThreadDump=true
+config.show.stackTraceOnError=true
config.enable.activeThreadDump=true
web.hbase.selectSpans.limit=500
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/config/ConfigProperties.java b/web/src/main/java/com/navercorp/pinpoint/web/config/ConfigProperties.java
index 92af34f85214..10fadb418139 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/config/ConfigProperties.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/config/ConfigProperties.java
@@ -45,13 +45,16 @@ public class ConfigProperties {
@Value("#{pinpointWebProps['config.openSource'] ?: true}")
private boolean openSource;
-
+
@Value("#{pinpointWebProps['security.guide.url']}")
private String securityGuideUrl;
@Value("#{pinpointWebProps['config.show.applicationStat'] ?: false}")
private boolean showApplicationStat;
+ @Value("#{pinpointWebProps['config.show.stackTraceOnError'] ?: true}")
+ private boolean showStackTraceOnError;
+
@Value("#{pinpointWebProps['websocket.allowedOrigins']}")
private String webSocketAllowedOrigins;
@@ -91,6 +94,10 @@ public boolean isShowApplicationStat() {
return this.showApplicationStat;
}
+ public boolean isShowStackTraceOnError() {
+ return showStackTraceOnError;
+ }
+
public String getWebSocketAllowedOrigins() {
return webSocketAllowedOrigins;
}
@@ -107,6 +114,7 @@ public String toString() {
sb.append(", openSource=").append(openSource);
sb.append(", securityGuideUrl='").append(securityGuideUrl).append('\'');
sb.append(", showApplicationStat=").append(showApplicationStat);
+ sb.append(", showStackTraceOnError=").append(showStackTraceOnError);
sb.append(", webSocketAllowedOrigins=").append(webSocketAllowedOrigins);
sb.append('}');
return sb.toString();
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/ConfigController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/ConfigController.java
index fec44e0dbeb0..b25ba225f03d 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/controller/ConfigController.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/ConfigController.java
@@ -59,6 +59,7 @@ public Map<String, Object> getProperties(@RequestHeader(value=SSO_USER, required
result.put("showActiveThreadDump", webProperties.isShowActiveThreadDump());
result.put("enableServerMapRealTime", webProperties.isEnableServerMapRealTime());
result.put("showApplicationStat", webProperties.isShowApplicationStat());
+ result.put("showStackTraceOnError", webProperties.isShowStackTraceOnError());
result.put("openSource", webProperties.isOpenSource());
result.put("version", Version.VERSION);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/ControllerExceptionHandler.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/ControllerExceptionHandler.java
index 2ff14fcb7f1a..bef8e0f8bea0 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/controller/ControllerExceptionHandler.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/ControllerExceptionHandler.java
@@ -26,8 +26,10 @@
import javax.servlet.http.HttpServletRequest;
+import com.navercorp.pinpoint.web.config.ConfigProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@@ -45,6 +47,8 @@ public class ControllerExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
+ @Autowired
+ private ConfigProperties webProperties;
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception exception) throws Exception {
@@ -66,7 +70,9 @@ private Map<String, Object> createExceptionResource(HttpServletRequest request,
Map<String, Object> exceptionMap = new HashMap<>();
exceptionMap.put("message", getExceptionMessage(throwable));
- exceptionMap.put("stacktrace", getExceptionStackTrace(throwable));
+ if (webProperties.isShowStackTraceOnError()) {
+ exceptionMap.put("stacktrace", getExceptionStackTrace(throwable));
+ }
exceptionMap.put("request", createRequestResource(request));
return exceptionMap;
diff --git a/web/src/main/resources/pinpoint-web.properties b/web/src/main/resources/pinpoint-web.properties
index ccf36a0fc854..818877d21591 100644
--- a/web/src/main/resources/pinpoint-web.properties
+++ b/web/src/main/resources/pinpoint-web.properties
@@ -36,6 +36,7 @@ config.show.activeThread=true
config.show.activeThreadDump=true
config.enable.activeThreadDump=true
config.show.applicationStat=false
+config.show.stackTraceOnError=true
# This option does not work because it is under development
config.enable.serverMapRealTime=false
| null | test | val | "2018-09-20T09:06:30" | "2018-09-20T06:01:40Z" | Xylus | test |
pinpoint-apm/pinpoint/4590_4694 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4590 | pinpoint-apm/pinpoint/4694 | [
"keyword_pr_to_issue"
] | f1e3a14ea2e65945f456c9aacc995a968a3dd0e0 | 071836693df5dd563215b9422ef33869c6cf52d5 | [] | [] | "2018-10-01T10:01:03Z" | [
"bug",
"module:agent"
] | Fix agent startup failure in certain ibm java versions | #### Description
Certain IBM java builds do not have `bootstrapClassLoader` field in **ClassLoader** and instead have `systemClassLoader` pointing to the bootstrap class loader. (Access to this field is needed in **J9BootLoader**)
Some IBM java runtimes also do not appear to have methods required for cpu usage metrics.
Java 6 - `com.ibm.lang.management.OperatingSystemMXBean.getProcessCpuTimeByNS()` reported via #4630
Java 7 - `com.ibm.lang.management.OperatingSystemMXBean.getProcessCpuLoad()` reported via #4585
This is weird as the IBM API reference does have the methods listed -
https://www.ibm.com/support/knowledgecenter/en/SSYKE2_6.0.0/com.ibm.java.api.60.doc/com.ibm.lang.management/com/ibm/lang/management/OperatingSystemMXBean.html
https://www.ibm.com/support/knowledgecenter/en/SSYKE2_7.0.0/com.ibm.java.api.70.doc/com.ibm.lang.management/com/ibm/lang/management/OperatingSystemMXBean.html
Either way, we'll need to add a check to see if the methods really do exist instead of blowing up during runtime. | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java",
"commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java",
"commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java"
] | [] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java
index f16ce008cb6e..da036fdac33a 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java
@@ -16,6 +16,9 @@
package com.navercorp.pinpoint.bootstrap.classloader;
+import com.navercorp.pinpoint.common.util.JvmType;
+import com.navercorp.pinpoint.common.util.JvmUtils;
+
/**
* @author Woonduk Kang(emeroad)
*/
@@ -40,17 +43,8 @@ public static BootLoader newBootLoader() {
}
private static boolean isJ9VM() {
- // ibm-j9 java.vm.name=IBM J9 VM;
- // openj9 java.vm.name=Eclipse OpenJ9 VM
-// if (System.getProperty("java.vm.name", "").contains("J9 VM")) {
-// return true;
-// }
- try {
- ClassLoader.class.getDeclaredField("bootstrapClassLoader");
- return true;
- } catch (NoSuchFieldException e) {
- return false;
- }
+ JvmType jvmType = JvmUtils.getType();
+ return jvmType == JvmType.IBM;
}
}
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java
index b615eaeae1e7..b0e11b3aa218 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java
@@ -44,12 +44,19 @@ public class J9BootLoader implements BootLoader {
}
private static ClassLoader findBootstrapClassLoader() {
+ Field bootstrapClassLoader;
+ try {
+ bootstrapClassLoader = ClassLoader.class.getDeclaredField("bootstrapClassLoader");
+ } catch (NoSuchFieldException e) {
+ try {
+ bootstrapClassLoader = ClassLoader.class.getDeclaredField("systemClassLoader");
+ } catch (NoSuchFieldException e2) {
+ throw new IllegalStateException("bootstrapClassLoader not found Caused by:" + e.getMessage() + ", and " + e2.getMessage(), e2);
+ }
+ }
try {
- Field bootstrapClassLoader = ClassLoader.class.getDeclaredField("bootstrapClassLoader");
bootstrapClassLoader.setAccessible(true);
return (ClassLoader) bootstrapClassLoader.get(ClassLoader.class);
- } catch (NoSuchFieldException e) {
- throw new IllegalStateException("bootstrapClassLoader not found Caused by:" + e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("bootstrapClassLoader access fail Caused by:" + e.getMessage(), e);
}
diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java
index a63af83b5fe7..2537eb561172 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java
@@ -23,7 +23,9 @@
*/
public enum JvmType {
UNKNOWN(null),
- IBM("IBM"),
+ // ibm-j9 java.vm.name=IBM J9 VM;
+ // openj9 java.vm.name=Eclipse OpenJ9 VM
+ IBM("J9"),
OPENJDK("OpenJDK"),
ORACLE("HotSpot");
diff --git a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java
index cee669e9b80e..a4c2bdf899c0 100644
--- a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java
+++ b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java
@@ -46,12 +46,14 @@ public double getJvmCpuUsage(final long cpuTimeNS, final long upTimeMS) {
final long diffUpTimeMS = upTimeMS - lastUpTimeMS;
final long totalUpTimeNS = (diffUpTimeMS * 1000000) * CPU_COUNT;
- final double cpuLoad = totalUpTimeNS > 0 ?
- Math.min(100F, totalCpuTimeNS / (float) totalUpTimeNS) : UNSUPPORTED;
+ double cpuUsage = UNSUPPORTED;
+ if (totalUpTimeNS > 0) {
+ cpuUsage = Math.min(100F, totalCpuTimeNS / (float) totalUpTimeNS);
+ }
this.lastCpuTimeNS = cpuTimeNS;
this.lastUpTimeMS = upTimeMS;
- return cpuLoad;
+ return cpuUsage;
}
}
diff --git a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java
index 6faf29537b21..d54426415f4c 100644
--- a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java
@@ -16,11 +16,15 @@
package com.navercorp.pinpoint.profiler.monitor.metric.cpu.ibm;
+import com.ibm.lang.management.OperatingSystemMXBean;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.JvmCpuUsageCalculator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
/**
@@ -28,32 +32,58 @@
*/
public class Java6CpuLoadMetric implements CpuLoadMetric {
- private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
- private final com.ibm.lang.management.OperatingSystemMXBean operatingSystemMXBean;
- private final RuntimeMXBean runtimeMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public Java6CpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ private CpuUsageProvider jvmCpuUsageProvider;
+
+ public Java6CpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+ RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
+ if (runtimeMXBean == null) {
+ throw new IllegalStateException("RuntimeMXBean not available");
}
- this.operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) operatingSystemMXBean;
- this.runtimeMXBean = runtimeMXBean;
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean, runtimeMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = UNCOLLECTED_USAGE;
- if (runtimeMXBean != null) {
- long cpuTimeNS = operatingSystemMXBean.getProcessCpuTimeByNS();
- long upTimeMS = runtimeMXBean.getUptime();
- jvmCpuUsage = jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
- }
- double systemCpuUsage = operatingSystemMXBean.getSystemCpuLoad();
- return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ return new CpuLoadMetricSnapshot(jvmCpuUsage, UNCOLLECTED_USAGE);
}
@Override
public String toString() {
return "CpuLoadMetric for IBM Java 1.6";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+ private final RuntimeMXBean runtimeMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ this.runtimeMXBean = runtimeMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ long cpuTimeNS = operatingSystemMXBean.getProcessCpuTimeByNS();
+ long upTimeMS = runtimeMXBean.getUptime();
+ return jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
+ }
+ }
}
diff --git a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java
index e3fe36eef104..d4f9ee627ac1 100644
--- a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java
@@ -18,9 +18,13 @@
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.JvmCpuUsageCalculator;
+import com.sun.management.OperatingSystemMXBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
/**
@@ -28,32 +32,58 @@
*/
public class Java6CpuLoadMetric implements CpuLoadMetric {
- private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
- private final com.sun.management.OperatingSystemMXBean operatingSystemMXBean;
- private final RuntimeMXBean runtimeMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public Java6CpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ private final CpuUsageProvider jvmCpuUsageProvider;
+
+ public Java6CpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+ final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
+ if (runtimeMXBean == null) {
+ throw new IllegalStateException("RuntimeMXBean not available");
}
- this.operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) operatingSystemMXBean;
- this.runtimeMXBean = runtimeMXBean;
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean, runtimeMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = UNCOLLECTED_USAGE;
- if (runtimeMXBean != null) {
- long cpuTimeNS = operatingSystemMXBean.getProcessCpuTime();
- long upTimeMS = runtimeMXBean.getUptime();
- jvmCpuUsage = jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
- }
- double systemCpuUsage = UNCOLLECTED_USAGE;
- return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ return new CpuLoadMetricSnapshot(jvmCpuUsage, UNCOLLECTED_USAGE);
}
@Override
public String toString() {
return "CpuLoadMetric for Oracle Java 1.6";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+ private final RuntimeMXBean runtimeMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ this.runtimeMXBean = runtimeMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ long cpuTimeNS = operatingSystemMXBean.getProcessCpuTime();
+ long upTimeMS = runtimeMXBean.getUptime();
+ return jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
+ }
+ }
}
diff --git a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java
index 7d6abb3b2c8b..1baeb68910f1 100644
--- a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java
@@ -16,29 +16,54 @@
package com.navercorp.pinpoint.profiler.monitor.metric.cpu.ibm;
+import com.ibm.lang.management.OperatingSystemMXBean;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
/**
* @author HyunGil Jeong
*/
public class DefaultCpuLoadMetric implements CpuLoadMetric {
- private final com.ibm.lang.management.OperatingSystemMXBean operatingSystemMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public DefaultCpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean) {
+ private final CpuUsageProvider jvmCpuUsageProvider;
+ private final CpuUsageProvider systemCpuUsageProvider;
+
+ public DefaultCpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
+
+ CpuUsageProvider systemCpuUsageProvider = new SystemCpuUsageProvider(operatingSystemMXBean);
+ try {
+ systemCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving system cpu usage. Cause : {}", e.getMessage());
+ systemCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
}
- this.operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) operatingSystemMXBean;
+ this.systemCpuUsageProvider = systemCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = operatingSystemMXBean.getProcessCpuLoad();
- double systemCpuUsage = operatingSystemMXBean.getSystemCpuLoad();
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ double systemCpuUsage = systemCpuUsageProvider.getCpuUsage();
return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
}
@@ -46,4 +71,32 @@ public CpuLoadMetricSnapshot getSnapshot() {
public String toString() {
return "CpuLoadMetric for IBM Java 1.7+";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getProcessCpuLoad();
+ }
+ }
+
+ private static class SystemCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private SystemCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getSystemCpuLoad();
+ }
+ }
}
diff --git a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java
index 9954ba770128..5f3d011674a4 100644
--- a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java
@@ -18,27 +18,52 @@
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
+import com.sun.management.OperatingSystemMXBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
/**
* @author HyunGil Jeong
*/
public class DefaultCpuLoadMetric implements CpuLoadMetric {
- private final com.sun.management.OperatingSystemMXBean operatingSystemMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public DefaultCpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean) {
+ private final CpuUsageProvider jvmCpuUsageProvider;
+ private final CpuUsageProvider systemCpuUsageProvider;
+
+ public DefaultCpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
+
+ CpuUsageProvider systemCpuUsageProvider = new SystemCpuUsageProvider(operatingSystemMXBean);
+ try {
+ systemCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving system cpu usage. Cause : {}", e.getMessage());
+ systemCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
}
- this.operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) operatingSystemMXBean;
+ this.systemCpuUsageProvider = systemCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = operatingSystemMXBean.getProcessCpuLoad();
- double systemCpuUsage = operatingSystemMXBean.getSystemCpuLoad();
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ double systemCpuUsage = systemCpuUsageProvider.getCpuUsage();
return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
}
@@ -46,4 +71,32 @@ public CpuLoadMetricSnapshot getSnapshot() {
public String toString() {
return "CpuLoadMetric for Oracle Java 1.7+";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getProcessCpuLoad();
+ }
+ }
+
+ private static class SystemCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private SystemCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getSystemCpuLoad();
+ }
+ }
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java
index 322e31d4b252..f4d6faa4db26 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java
@@ -26,9 +26,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.lang.management.ManagementFactory;
-import java.lang.management.OperatingSystemMXBean;
-import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Constructor;
/**
@@ -85,27 +82,15 @@ private CpuLoadMetric createCpuLoadMetric(String classToLoad) {
if (classToLoad == null) {
return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
}
- OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
- if (operatingSystemMXBean == null) {
- return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
- }
try {
@SuppressWarnings("unchecked")
Class<CpuLoadMetric> cpuLoadMetricClass = (Class<CpuLoadMetric>) Class.forName(classToLoad);
try {
- // Create CpuLoadMetric for Java 7+
- Constructor<CpuLoadMetric> cpuLoadMetricConstructor = cpuLoadMetricClass.getConstructor(OperatingSystemMXBean.class);
- return cpuLoadMetricConstructor.newInstance(operatingSystemMXBean);
- } catch (NoSuchMethodException e1) {
- try {
- // Create CpuLoadMetric for Java 6
- RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
- Constructor<CpuLoadMetric> cpuLoadMetricConstructor = cpuLoadMetricClass.getConstructor(OperatingSystemMXBean.class, RuntimeMXBean.class);
- return cpuLoadMetricConstructor.newInstance(operatingSystemMXBean, runtimeMXBean);
- } catch (NoSuchMethodException e2) {
- logger.warn("Unknown CpuLoadMetric : {}", classToLoad);
- return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
- }
+ Constructor<CpuLoadMetric> cpuLoadMetricConstructor = cpuLoadMetricClass.getConstructor();
+ return cpuLoadMetricConstructor.newInstance();
+ } catch (NoSuchMethodException e) {
+ logger.warn("Unknown CpuLoadMetric : {}", classToLoad);
+ return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
}
} catch (Exception e) {
logger.warn("Error creating CpuLoadMetric [" + classToLoad + "]", e);
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java
new file mode 100644
index 000000000000..66f0717134d1
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.navercorp.pinpoint.profiler.monitor.metric.cpu;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface CpuUsageProvider {
+
+ double getCpuUsage();
+
+ CpuUsageProvider UNSUPPORTED = new CpuUsageProvider() {
+ @Override
+ public double getCpuUsage() {
+ return CpuLoadMetric.UNCOLLECTED_USAGE;
+ }
+ };
+}
| null | train | test | "2018-10-01T10:11:31" | "2018-09-06T07:52:38Z" | Xylus | test |