提交 e11d2071 编写于 作者: A aderm 提交者: wu-sheng

Add elasticsearch 6.x plugin & elasticsearch 6.x test scenario (#3803)

* Add elasticsearch 6.x plugin & elasticsearch 6.x test scenario
上级 3fbaec42
......@@ -67,6 +67,7 @@ pipeline {
sh './mvnw -f test/plugin/pom.xml clean package -DskipTests docker:build'
}
}
stage('Test Cases Report (136)') {
steps {
echo "Test Cases Report"
......
......@@ -68,7 +68,7 @@ pipeline {
}
}
stage('Test Cases Report (153)') {
stage('Test Cases Report (154)') {
steps {
echo "Test Cases Report"
}
......@@ -84,6 +84,12 @@ pipeline {
parallel {
stage('Group1') {
stages {
stage('elasticsearch-6.x-scenario 6.7.1-6.8.4 (7)') {
steps {
sh 'bash test/plugin/run.sh elasticsearch-6.x-scenario'
}
}
stage('kafka 0.11.0.0-2.3.0 (16)') {
steps {
sh 'bash test/plugin/run.sh kafka-scenario'
......
......@@ -143,4 +143,6 @@ public class ComponentsDefine {
public static final OfficialComponent EHCACHE = new OfficialComponent(75, "Ehcache");
public static final OfficialComponent SOCKET_IO = new OfficialComponent(76, "SocketIO");
public static final OfficialComponent REST_HIGH_LEVEL_CLIENT = new OfficialComponent(77, "rest-high-level-client");
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>apm-sdk-plugin</artifactId>
<groupId>org.apache.skywalking</groupId>
<version>6.6.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>apm-elasticsearch-6.x-plugin</artifactId>
<packaging>jar</packaging>
<name>elasticsearch-6.x-plugin</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<elasticsearch.rest.high.level.client.version>6.7.1</elasticsearch.rest.high.level.client.version>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.rest.high.level.client.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6;
/**
*
* Used for store ES connection related information, remotePeers will store the IP address and port,
* separated by commas when multiple connections are made.
*
* @author aderm
*/
public class RemotePeerCache {
private String remotePeers = "";
public void addRemotePeer(String host, int port) {
String hostPort = host + ":" + String.valueOf(port);
if (remotePeers.isEmpty()) {
remotePeers = hostPort;
} else {
remotePeers = "," + hostPort;
}
}
public String getRemotePeers() {
return remotePeers;
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6;
import org.apache.http.HttpHost;
/**
* @author aderm
*/
public class RestClientEnhanceInfo {
private RemotePeerCache remotePeerCache = new RemotePeerCache();
public void addHttpHost(HttpHost httpHost) {
remotePeerCache.addRemotePeer(httpHost.getHostName(), httpHost.getPort());
}
public String getPeers() {
return remotePeerCache.getRemotePeers();
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.define;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static org.apache.skywalking.apm.agent.core.plugin.match.NameMatch.byName;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.ConstructorInterceptPoint;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.StaticMethodsInterceptPoint;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.ClassEnhancePluginDefine;
import org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.Constants;
/**
*
* {@link IndicesClientInstrumentation} enhance the <code>create createAsync delete deleteAsync</code> method without argument in
* <code>org.elasticsearch.client.IndicesClient</code> by <code>org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.IndicesClientCreateMethodsInterceptor
* org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.IndicesClientDeleteMethodsInterceptor</code>
*
* @author aderm
*/
public class IndicesClientInstrumentation extends ClassEnhancePluginDefine {
public static final String ENHANCE_CLASS = "org.elasticsearch.client.IndicesClient";
@Override
protected ClassMatch enhanceClass() {
return byName(ENHANCE_CLASS);
}
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
return new ConstructorInterceptPoint[0];
}
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
return new InstanceMethodsInterceptPoint[] {
new InstanceMethodsInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getMethodsMatcher() {
return named("create").or(named("createAsync"));
}
@Override
public String getMethodsInterceptor() {
return Constants.INDICES_CLIENT_CREATE_METHODS_INTERCEPTOR;
}
@Override
public boolean isOverrideArgs() {
return false;
}
},
new InstanceMethodsInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getMethodsMatcher() {
return named("delete").or(named("deleteAsync"));
}
@Override
public String getMethodsInterceptor() {
return Constants.INDICES_CLIENT_DELETE_METHODS_INTERCEPTOR;
}
@Override
public boolean isOverrideArgs() {
return false;
}
}
};
}
@Override
public StaticMethodsInterceptPoint[] getStaticMethodsInterceptPoints() {
return new StaticMethodsInterceptPoint[0];
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.define;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static org.apache.skywalking.apm.agent.core.plugin.bytebuddy.ArgumentTypeNameMatch.takesArgumentWithType;
import static org.apache.skywalking.apm.agent.core.plugin.match.NameMatch.byName;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.ConstructorInterceptPoint;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.StaticMethodsInterceptPoint;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.ClassEnhancePluginDefine;
import org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.Constants;
/**
*
* {@link RestHighLevelClientInstrumentation} enhance the constructor method without argument in
* <code>org.elasticsearch.client.RestHighLevelClient</code> by <code>org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientConInterceptor</code>
* also enhance the <code>performRequestAndParseEntity</code> method in <code>org.elasticsearch.client.RestHighLevelClient</code> by <code>org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.IndicesClientCreateMethodsInterceptor</code>,
* also enhance the <code>get getAsync search searchAsync index indexAsync update updateAsync</code> method in <code>org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientGetMethodsInterceptor
* org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientSearchMethodsInterceptor org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientIndexMethodsInterceptor
* org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientUpdateMethodsInterceptor</code>,
* also enhance the <code>indices</code> method in <code>org.elasticsearch.client.RestHighLevelClient</code> by <code>org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientIndicesMethodsInterceptor</code>
*
* @author aderm
*/
public class RestHighLevelClientInstrumentation extends ClassEnhancePluginDefine {
public static final String ENHANCE_CLASS = "org.elasticsearch.client.RestHighLevelClient";
@Override
protected ClassMatch enhanceClass() {
return byName(ENHANCE_CLASS);
}
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
return new ConstructorInterceptPoint[] {
new ConstructorInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getConstructorMatcher() {
return takesArgumentWithType(0, "org.elasticsearch.client.RestClientBuilder");
}
@Override
public String getConstructorInterceptor() {
return Constants.REST_HIGH_LEVEL_CLIENT_CON_INTERCEPTOR;
}
}
};
}
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
return new InstanceMethodsInterceptPoint[] {
new InstanceMethodsInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getMethodsMatcher() {
return named("performRequestAndParseEntity").and(takesArgumentWithType(0, "org.elasticsearch.client.indices.CreateIndexRequest"));
}
@Override
public String getMethodsInterceptor() {
return Constants.INDICES_CLIENT_CREATE_METHODS_INTERCEPTOR;
}
@Override
public boolean isOverrideArgs() {
return false;
}
},
new InstanceMethodsInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getMethodsMatcher() {
return named("get").or(named("getAsync"));
}
@Override
public String getMethodsInterceptor() {
return Constants.REST_HIGH_LEVEL_CLIENT_GET_METHODS_INTERCEPTOR;
}
@Override
public boolean isOverrideArgs() {
return false;
}
},
new InstanceMethodsInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getMethodsMatcher() {
return named("search").or(named("searchAsync"));
}
@Override
public String getMethodsInterceptor() {
return Constants.REST_HIGH_LEVEL_CLIENT_SEARCH_METHODS_INTERCEPTOR;
}
@Override
public boolean isOverrideArgs() {
return false;
}
},
new InstanceMethodsInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getMethodsMatcher() {
return named("index").or(named("indexAsync"));
}
@Override
public String getMethodsInterceptor() {
return Constants.REST_HIGH_LEVEL_CLIENT_INDEX_METHODS_INTERCEPTOR;
}
@Override
public boolean isOverrideArgs() {
return false;
}
},
new InstanceMethodsInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getMethodsMatcher() {
return named("update").or(named("updateAsync"));
}
@Override
public String getMethodsInterceptor() {
return Constants.REST_HIGH_LEVEL_CLIENT_UPDATE_METHODS_INTERCEPTOR;
}
@Override
public boolean isOverrideArgs() {
return false;
}
},
new InstanceMethodsInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getMethodsMatcher() {
return named("indices");
}
@Override
public String getMethodsInterceptor() {
return Constants.REST_HIGH_LEVEL_CLIENT_INDICES_METHODS_INTERCEPTOR;
}
@Override
public boolean isOverrideArgs() {
return false;
}
}
};
}
@Override
public StaticMethodsInterceptPoint[] getStaticMethodsInterceptPoints() {
return new StaticMethodsInterceptPoint[0];
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
/**
* @author aderm
*/
public class Constants {
//interceptor class
public static final String REST_HIGH_LEVEL_CLIENT_CON_INTERCEPTOR = "org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientConInterceptor";
public static final String INDICES_CLIENT_CREATE_METHODS_INTERCEPTOR = "org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.IndicesClientCreateMethodsInterceptor";
public static final String INDICES_CLIENT_DELETE_METHODS_INTERCEPTOR = "org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.IndicesClientDeleteMethodsInterceptor";
public static final String REST_HIGH_LEVEL_CLIENT_GET_METHODS_INTERCEPTOR = "org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientGetMethodsInterceptor";
public static final String REST_HIGH_LEVEL_CLIENT_SEARCH_METHODS_INTERCEPTOR = "org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientSearchMethodsInterceptor";
public static final String REST_HIGH_LEVEL_CLIENT_UPDATE_METHODS_INTERCEPTOR = "org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientUpdateMethodsInterceptor";
public static final String REST_HIGH_LEVEL_CLIENT_INDEX_METHODS_INTERCEPTOR = "org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientIndexMethodsInterceptor";
public static final String REST_HIGH_LEVEL_CLIENT_INDICES_METHODS_INTERCEPTOR = "org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.RestHighLevelClientIndicesMethodsInterceptor";
//es operator name
public static final String CREATE_OPERATOR_NAME = "Elasticsearch/CreateRequest";
public static final String DELETE_OPERATOR_NAME = "Elasticsearch/DeleteRequest";
public static final String GET_OPERATOR_NAME = "Elasticsearch/GetRequest";
public static final String INDEX_OPERATOR_NAME = "Elasticsearch/IndexRequest";
public static final String SEARCH_OPERATOR_NAME = "Elasticsearch/SearchRequest";
public static final String UPDATE_OPERATOR_NAME = "Elasticsearch/UpdateRequest";
public static final String DB_TYPE = "Elasticsearch";
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.apache.skywalking.apm.agent.core.conf.Config.Plugin.Elasticsearch.TRACE_DSL;
import static org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.Constants.DB_TYPE;
import java.lang.reflect.Method;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.client.indices.CreateIndexRequest;
/**
* @author aderm
*/
public class IndicesClientCreateMethodsInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
CreateIndexRequest createIndexRequest = (CreateIndexRequest)(allArguments[0]);
RestClientEnhanceInfo restClientEnhanceInfo = (RestClientEnhanceInfo) (objInst
.getSkyWalkingDynamicField());
if (restClientEnhanceInfo != null) {
AbstractSpan span = ContextManager
.createExitSpan(Constants.CREATE_OPERATOR_NAME,
restClientEnhanceInfo.getPeers());
span.setComponent(ComponentsDefine.REST_HIGH_LEVEL_CLIENT);
Tags.DB_TYPE.set(span, DB_TYPE);
Tags.DB_INSTANCE.set(span, createIndexRequest.index());
if (TRACE_DSL) {
//Store es mapping parameters
Tags.DB_STATEMENT
.set(span, createIndexRequest.mappings().utf8ToString());
}
SpanLayer.asDB(span);
}
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Object ret) throws Throwable {
RestClientEnhanceInfo restClientEnhanceInfo = (RestClientEnhanceInfo) (objInst
.getSkyWalkingDynamicField());
if (restClientEnhanceInfo != null) {
ContextManager.stopSpan();
}
return ret;
}
@Override
public void handleMethodException(EnhancedInstance objInst, Method method,
Object[] allArguments, Class<?>[] argumentsTypes, Throwable t) {
RestClientEnhanceInfo restClientEnhanceInfo = (RestClientEnhanceInfo) (objInst
.getSkyWalkingDynamicField());
if (restClientEnhanceInfo != null) {
ContextManager.activeSpan().errorOccurred().log(t);
}
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.Constants.DB_TYPE;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
/**
* @author aderm
*/
public class IndicesClientDeleteMethodsInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
DeleteIndexRequest deleteIndexRequest = (DeleteIndexRequest)(allArguments[0]);
RestClientEnhanceInfo restClientEnhanceInfo = (RestClientEnhanceInfo) (objInst
.getSkyWalkingDynamicField());
if (restClientEnhanceInfo != null) {
AbstractSpan span = ContextManager
.createExitSpan(Constants.DELETE_OPERATOR_NAME,
restClientEnhanceInfo.getPeers());
span.setComponent(ComponentsDefine.REST_HIGH_LEVEL_CLIENT);
Tags.DB_TYPE.set(span, DB_TYPE);
Tags.DB_INSTANCE.set(span, Arrays.asList(deleteIndexRequest.indices()).toString());
SpanLayer.asDB(span);
}
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Object ret) throws Throwable {
RestClientEnhanceInfo restClientEnhanceInfo = (RestClientEnhanceInfo) (objInst
.getSkyWalkingDynamicField());
if (restClientEnhanceInfo != null) {
ContextManager.stopSpan();
}
return ret;
}
@Override
public void handleMethodException(EnhancedInstance objInst, Method method,
Object[] allArguments, Class<?>[] argumentsTypes, Throwable t) {
RestClientEnhanceInfo restClientEnhanceInfo = (RestClientEnhanceInfo) (objInst
.getSkyWalkingDynamicField());
if (restClientEnhanceInfo != null) {
ContextManager.activeSpan().errorOccurred().log(t);
}
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import java.util.List;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
/**
* @author aderm
*/
public class RestHighLevelClientConInterceptor implements InstanceConstructorInterceptor {
private static final ILog logger = LogManager.getLogger(RestHighLevelClientConInterceptor.class);
@Override
public void onConstruct(EnhancedInstance objInst, Object[] allArguments) {
RestClientBuilder restClientBuilder = (RestClientBuilder)(allArguments[0]);
RestClient restClient = restClientBuilder.build();
RestClientEnhanceInfo restClientEnhanceInfo = new RestClientEnhanceInfo();
List<Node> nodeList = restClient.getNodes();
for (Node node : nodeList) {
restClientEnhanceInfo.addHttpHost(node.getHost());
}
objInst.setSkyWalkingDynamicField(restClientEnhanceInfo);
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.apache.skywalking.apm.agent.core.conf.Config.Plugin.Elasticsearch.TRACE_DSL;
import static org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.Constants.DB_TYPE;
import java.lang.reflect.Method;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.action.get.GetRequest;
/**
* @author aderm
*/
public class RestHighLevelClientGetMethodsInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
GetRequest getRequest = (GetRequest)(allArguments[0]);
RestClientEnhanceInfo restClientEnhanceInfo = (RestClientEnhanceInfo)(objInst.getSkyWalkingDynamicField());
AbstractSpan span = ContextManager
.createExitSpan(Constants.GET_OPERATOR_NAME, restClientEnhanceInfo.getPeers());
span.setComponent(ComponentsDefine.REST_HIGH_LEVEL_CLIENT);
Tags.DB_TYPE.set(span, DB_TYPE);
Tags.DB_INSTANCE.set(span, getRequest.index());
if (TRACE_DSL) {
Tags.DB_STATEMENT.set(span, getRequest.toString());
}
SpanLayer.asDB(span);
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Object ret) throws Throwable {
ContextManager.stopSpan();
return ret;
}
@Override
public void handleMethodException(EnhancedInstance objInst, Method method,
Object[] allArguments, Class<?>[] argumentsTypes, Throwable t) {
ContextManager.activeSpan().errorOccurred().log(t);
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.apache.skywalking.apm.agent.core.conf.Config.Plugin.Elasticsearch.TRACE_DSL;
import static org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.Constants.DB_TYPE;
import java.lang.reflect.Method;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.action.index.IndexRequest;
/**
* @author aderm
*/
public class RestHighLevelClientIndexMethodsInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
IndexRequest indexRequest = (IndexRequest)(allArguments[0]);
RestClientEnhanceInfo restClientEnhanceInfo = (RestClientEnhanceInfo)(objInst.getSkyWalkingDynamicField());
AbstractSpan span = ContextManager
.createExitSpan(Constants.INDEX_OPERATOR_NAME, restClientEnhanceInfo.getPeers());
span.setComponent(ComponentsDefine.REST_HIGH_LEVEL_CLIENT);
Tags.DB_TYPE.set(span, DB_TYPE);
Tags.DB_INSTANCE.set(span, indexRequest.index());
if (TRACE_DSL) {
Tags.DB_STATEMENT.set(span, indexRequest.toString());
}
SpanLayer.asDB(span);
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Object ret) throws Throwable {
ContextManager.stopSpan();
return ret;
}
@Override
public void handleMethodException(EnhancedInstance objInst, Method method,
Object[] allArguments, Class<?>[] argumentsTypes, Throwable t) {
ContextManager.activeSpan().errorOccurred().log(t);
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import java.lang.reflect.Method;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
/**
* @author aderm
*/
public class RestHighLevelClientIndicesMethodsInterceptor implements
InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Object ret) throws Throwable {
if (ret instanceof EnhancedInstance) {
((EnhancedInstance)ret).setSkyWalkingDynamicField((RestClientEnhanceInfo)(objInst.getSkyWalkingDynamicField()));
}
return ret;
}
@Override
public void handleMethodException(EnhancedInstance objInst, Method method,
Object[] allArguments, Class<?>[] argumentsTypes, Throwable t) {
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.apache.skywalking.apm.agent.core.conf.Config.Plugin.Elasticsearch.TRACE_DSL;
import static org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.Constants.DB_TYPE;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.action.search.SearchRequest;
/**
* @author aderm
*/
public class RestHighLevelClientSearchMethodsInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
SearchRequest searchRequest = (SearchRequest)(allArguments[0]);
RestClientEnhanceInfo restClientEnhanceInfo = (RestClientEnhanceInfo)(objInst.getSkyWalkingDynamicField());
AbstractSpan span = ContextManager
.createExitSpan(Constants.SEARCH_OPERATOR_NAME, restClientEnhanceInfo.getPeers());
span.setComponent(ComponentsDefine.REST_HIGH_LEVEL_CLIENT);
Tags.DB_TYPE.set(span, DB_TYPE);
Tags.DB_INSTANCE.set(span, Arrays.asList(searchRequest.indices()).toString());
if (TRACE_DSL) {
Tags.DB_STATEMENT.set(span, searchRequest.toString());
}
SpanLayer.asDB(span);
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Object ret) throws Throwable {
ContextManager.stopSpan();
return ret;
}
@Override
public void handleMethodException(EnhancedInstance objInst, Method method,
Object[] allArguments, Class<?>[] argumentsTypes, Throwable t) {
ContextManager.activeSpan().errorOccurred().log(t);
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.apache.skywalking.apm.agent.core.conf.Config.Plugin.Elasticsearch.TRACE_DSL;
import static org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor.Constants.DB_TYPE;
import java.lang.reflect.Method;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.action.update.UpdateRequest;
/**
* @author aderm
*/
public class RestHighLevelClientUpdateMethodsInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
UpdateRequest updateRequest = (UpdateRequest)(allArguments[0]);
RestClientEnhanceInfo restClientEnhanceInfo = (RestClientEnhanceInfo)(objInst.getSkyWalkingDynamicField());
AbstractSpan span = ContextManager
.createExitSpan(Constants.UPDATE_OPERATOR_NAME, restClientEnhanceInfo.getPeers());
span.setComponent(ComponentsDefine.REST_HIGH_LEVEL_CLIENT);
Tags.DB_TYPE.set(span, DB_TYPE);
Tags.DB_INSTANCE.set(span, updateRequest.index());
if (TRACE_DSL) {
Tags.DB_STATEMENT.set(span, updateRequest.toString());
}
SpanLayer.asDB(span);
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Object ret) throws Throwable {
ContextManager.stopSpan();
return ret;
}
@Override
public void handleMethodException(EnhancedInstance objInst, Method method,
Object[] allArguments, Class<?>[] argumentsTypes, Throwable t) {
ContextManager.activeSpan().errorOccurred().log(t);
}
}
# 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.
elasticsearch-6.x=org.apache.skywalking.apm.plugin.elasticsearch.v6.define.RestHighLevelClientInstrumentation
elasticsearch-6.x=org.apache.skywalking.apm.plugin.elasticsearch.v6.define.IndicesClientInstrumentation
/*
* 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.
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.apache.skywalking.apm.agent.core.conf.Config.Plugin.Elasticsearch.TRACE_DSL;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.ExitSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.context.util.TagValuePair;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.test.helper.SegmentHelper;
import org.apache.skywalking.apm.agent.test.helper.SpanHelper;
import org.apache.skywalking.apm.agent.test.tools.AgentServiceRule;
import org.apache.skywalking.apm.agent.test.tools.SegmentStorage;
import org.apache.skywalking.apm.agent.test.tools.SegmentStoragePoint;
import org.apache.skywalking.apm.agent.test.tools.SpanAssert;
import org.apache.skywalking.apm.agent.test.tools.TracingSegmentRunner;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.bytes.BytesReference;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
/**
* @author aderm
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(TracingSegmentRunner.class)
public class IndicesClientCreateMethodsInterceptorTest {
@SegmentStoragePoint
private SegmentStorage segmentStorage;
@Rule
public AgentServiceRule serviceRule = new AgentServiceRule();
@Mock
private EnhancedInstance enhancedInstance;
@Mock
private CreateIndexRequest createIndexRequest;
private Object[] allArguments;
@Mock
private RestClientEnhanceInfo restClientEnhanceInfo;
private IndicesClientCreateMethodsInterceptor interceptor;
@Mock
private BytesReference bytesReference;
@Before
public void setUp() throws Exception {
when(restClientEnhanceInfo.getPeers()).thenReturn("172.0.0.1:9200");
allArguments = new Object[] {createIndexRequest};
when(createIndexRequest.index()).thenReturn("index");
when(createIndexRequest.mappings()).thenReturn(bytesReference);
when(bytesReference.utf8ToString()).thenReturn("mappings");
when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn(restClientEnhanceInfo);
interceptor = new IndicesClientCreateMethodsInterceptor();
}
@Test
public void testMethodsAround() throws Throwable {
TRACE_DSL = true;
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan createSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertCreateSpan(createSpan);
}
private void assertCreateSpan(AbstractTracingSpan createSpan) {
assertThat(createSpan instanceof ExitSpan, is(true));
ExitSpan exitSpan = (ExitSpan)createSpan;
assertThat(exitSpan.getOperationName(), is("Elasticsearch/CreateRequest"));
assertThat(exitSpan.getPeer(), is("172.0.0.1:9200"));
assertThat(SpanHelper.getComponentId(exitSpan), is(77));
List<TagValuePair> tags = SpanHelper.getTags(exitSpan);
assertThat(tags.size(), is(3));
assertThat(tags.get(0).getValue(), is("Elasticsearch"));
assertThat(tags.get(1).getValue(), is("index"));
assertThat(tags.get(2).getValue(), is("mappings"));
}
@Test
public void testMethodsAroundError() throws Throwable {
TRACE_DSL = true;
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.handleMethodException(enhancedInstance, null, allArguments, null, new RuntimeException());
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan createSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertCreateSpan(createSpan);
Assert.assertEquals(true, SpanHelper.getErrorOccurred(createSpan));
SpanAssert.assertException(SpanHelper.getLogs(createSpan).get(0), RuntimeException.class);
}
}
/*
* 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.
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.ExitSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.context.util.TagValuePair;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.test.helper.SegmentHelper;
import org.apache.skywalking.apm.agent.test.helper.SpanHelper;
import org.apache.skywalking.apm.agent.test.tools.AgentServiceRule;
import org.apache.skywalking.apm.agent.test.tools.SegmentStorage;
import org.apache.skywalking.apm.agent.test.tools.SegmentStoragePoint;
import org.apache.skywalking.apm.agent.test.tools.SpanAssert;
import org.apache.skywalking.apm.agent.test.tools.TracingSegmentRunner;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
/**
* @author aderm
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(TracingSegmentRunner.class)
public class IndicesClientDeleteMethodsInterceptorTest {
@SegmentStoragePoint
private SegmentStorage segmentStorage;
@Rule
public AgentServiceRule serviceRule = new AgentServiceRule();
@Mock
private EnhancedInstance enhancedInstance;
@Mock
private DeleteIndexRequest deleteIndexRequest;
private Object[] allArguments;
@Mock
private RestClientEnhanceInfo restClientEnhanceInfo;
private IndicesClientDeleteMethodsInterceptor interceptor;
@Before
public void setUp() throws Exception {
when(restClientEnhanceInfo.getPeers()).thenReturn("172.0.0.1:9200");
allArguments = new Object[] {deleteIndexRequest};
when(deleteIndexRequest.indices()).thenReturn(new String[] {"index"});
when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn(restClientEnhanceInfo);
interceptor = new IndicesClientDeleteMethodsInterceptor();
}
@Test
public void testMethodsAround() throws Throwable {
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan deleteSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertDeleteSpan(deleteSpan);
}
private void assertDeleteSpan(AbstractTracingSpan deleteSpan) {
assertThat(deleteSpan instanceof ExitSpan, is(true));
ExitSpan exitSpan = (ExitSpan)deleteSpan;
assertThat(exitSpan.getOperationName(), is("Elasticsearch/DeleteRequest"));
assertThat(exitSpan.getPeer(), is("172.0.0.1:9200"));
assertThat(SpanHelper.getComponentId(exitSpan), is(77));
List<TagValuePair> tags = SpanHelper.getTags(exitSpan);
assertThat(tags.size(), is(2));
assertThat(tags.get(0).getValue(), is("Elasticsearch"));
assertThat(tags.get(1).getValue(), is("[index]"));
}
@Test
public void testMethodsAroundError() throws Throwable {
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.handleMethodException(enhancedInstance, null, allArguments, null, new RuntimeException());
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan deleteSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertDeleteSpan(deleteSpan);
Assert.assertEquals(true, SpanHelper.getErrorOccurred(deleteSpan));
SpanAssert.assertException(SpanHelper.getLogs(deleteSpan).get(0), RuntimeException.class);
}
}
/*
* 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.
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpHost;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.test.tools.TracingSegmentRunner;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
/**
* @author aderm
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(TracingSegmentRunner.class)
@PrepareForTest(value = {RestClientBuilder.class, HttpHost.class})
public class RestHighLevelClientConInterceptorTest {
@Mock
private RestClientBuilder restClientBuilder;
@Mock
private RestClient restClient;
@Mock
private HttpHost httpHost;
private Object[] allArguments;
private RestHighLevelClientConInterceptor restHighLevelClientConInterceptor;
@Before
public void setUp() throws Exception {
when(httpHost.getHostName()).thenReturn("127.0.0.1");
when(httpHost.getPort()).thenReturn(9200);
List<Node> nodeList = new ArrayList<Node>();
nodeList.add(new Node(httpHost));
restHighLevelClientConInterceptor = new RestHighLevelClientConInterceptor();
when(restClientBuilder.build()).thenReturn(restClient);
when(restClient.getNodes()).thenReturn(nodeList);
allArguments = new Object[]{restClientBuilder};
}
@Test
public void testConstruct() throws Throwable {
final EnhancedInstance objInst = new EnhancedInstance() {
private Object object = null;
@Override
public Object getSkyWalkingDynamicField() {
return object;
}
@Override
public void setSkyWalkingDynamicField(Object value) {
this.object = value;
}
};
restHighLevelClientConInterceptor = new RestHighLevelClientConInterceptor();
restHighLevelClientConInterceptor.onConstruct(objInst, allArguments);
assertThat(objInst.getSkyWalkingDynamicField() instanceof RestClientEnhanceInfo, is(true));
assertThat(((RestClientEnhanceInfo)objInst.getSkyWalkingDynamicField()).getPeers(), is("127.0.0.1:9200"));
}
}
/*
* 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.
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.apache.skywalking.apm.agent.core.conf.Config.Plugin.Elasticsearch.TRACE_DSL;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.ExitSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.context.util.TagValuePair;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.test.helper.SegmentHelper;
import org.apache.skywalking.apm.agent.test.helper.SpanHelper;
import org.apache.skywalking.apm.agent.test.tools.AgentServiceRule;
import org.apache.skywalking.apm.agent.test.tools.SegmentStorage;
import org.apache.skywalking.apm.agent.test.tools.SegmentStoragePoint;
import org.apache.skywalking.apm.agent.test.tools.SpanAssert;
import org.apache.skywalking.apm.agent.test.tools.TracingSegmentRunner;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.action.get.GetRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
/**
* @author aderm
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(TracingSegmentRunner.class)
public class RestHighLevelClientGetMethodsInterceptorTest {
@SegmentStoragePoint
private SegmentStorage segmentStorage;
@Rule
public AgentServiceRule serviceRule = new AgentServiceRule();
@Mock
private EnhancedInstance enhancedInstance;
@Mock
private GetRequest getRequest;
private Object[] allArguments;
@Mock
private RestClientEnhanceInfo restClientEnhanceInfo;
@Mock
private RestHighLevelClientGetMethodsInterceptor interceptor;
@Before
public void setUp() throws Exception {
when(restClientEnhanceInfo.getPeers()).thenReturn("172.0.0.1:9200");
allArguments = new Object[] {getRequest};
when(getRequest.index()).thenReturn("index");
when(getRequest.toString()).thenReturn("getRequest");
when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn(restClientEnhanceInfo);
interceptor = new RestHighLevelClientGetMethodsInterceptor();
}
@Test
public void testMethodsAround() throws Throwable {
TRACE_DSL = true;
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan getSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertGetSpan(getSpan);
}
private void assertGetSpan(AbstractTracingSpan getSpan) {
assertThat(getSpan instanceof ExitSpan, is(true));
ExitSpan exitSpan = (ExitSpan)getSpan;
assertThat(exitSpan.getOperationName(), is("Elasticsearch/GetRequest"));
assertThat(exitSpan.getPeer(), is("172.0.0.1:9200"));
assertThat(SpanHelper.getComponentId(exitSpan), is(77));
List<TagValuePair> tags = SpanHelper.getTags(exitSpan);
assertThat(tags.size(), is(3));
assertThat(tags.get(0).getValue(), is("Elasticsearch"));
assertThat(tags.get(1).getValue(), is("index"));
assertThat(tags.get(2).getValue(), is("getRequest"));
}
@Test
public void testMethodsAroundError() throws Throwable {
TRACE_DSL = true;
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.handleMethodException(enhancedInstance, null, allArguments, null, new RuntimeException());
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan getSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertGetSpan(getSpan);
Assert.assertEquals(true, SpanHelper.getErrorOccurred(getSpan));
SpanAssert.assertException(SpanHelper.getLogs(getSpan).get(0), RuntimeException.class);
}
}
/*
* 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.
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.apache.skywalking.apm.agent.core.conf.Config.Plugin.Elasticsearch.TRACE_DSL;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.ExitSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.context.util.TagValuePair;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.test.helper.SegmentHelper;
import org.apache.skywalking.apm.agent.test.helper.SpanHelper;
import org.apache.skywalking.apm.agent.test.tools.AgentServiceRule;
import org.apache.skywalking.apm.agent.test.tools.SegmentStorage;
import org.apache.skywalking.apm.agent.test.tools.SegmentStoragePoint;
import org.apache.skywalking.apm.agent.test.tools.SpanAssert;
import org.apache.skywalking.apm.agent.test.tools.TracingSegmentRunner;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.action.index.IndexRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
/**
* @author aderm
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(TracingSegmentRunner.class)
public class RestHighLevelClientIndexMethodsInterceptorTest {
@SegmentStoragePoint
private SegmentStorage segmentStorage;
@Rule
public AgentServiceRule serviceRule = new AgentServiceRule();
@Mock
private EnhancedInstance enhancedInstance;
@Mock
private IndexRequest indexRequest;
private Object[] allArguments;
@Mock
private RestClientEnhanceInfo restClientEnhanceInfo;
@Mock
private RestHighLevelClientIndexMethodsInterceptor interceptor;
@Before
public void setUp() throws Exception {
when(restClientEnhanceInfo.getPeers()).thenReturn("172.0.0.1:9200");
allArguments = new Object[] {indexRequest};
when(indexRequest.index()).thenReturn("indexName");
when(indexRequest.toString()).thenReturn("indexRequest");
when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn(restClientEnhanceInfo);
interceptor = new RestHighLevelClientIndexMethodsInterceptor();
}
@Test
public void testMethodsAround() throws Throwable {
TRACE_DSL = true;
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan indexSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertIndexSpan(indexSpan);
}
private void assertIndexSpan(AbstractTracingSpan getSpan) {
assertThat(getSpan instanceof ExitSpan, is(true));
ExitSpan exitSpan = (ExitSpan)getSpan;
assertThat(exitSpan.getOperationName(), is("Elasticsearch/IndexRequest"));
assertThat(exitSpan.getPeer(), is("172.0.0.1:9200"));
assertThat(SpanHelper.getComponentId(exitSpan), is(77));
List<TagValuePair> tags = SpanHelper.getTags(exitSpan);
assertThat(tags.size(), is(3));
assertThat(tags.get(0).getValue(), is("Elasticsearch"));
assertThat(tags.get(1).getValue(), is("indexName"));
assertThat(tags.get(2).getValue(), is("indexRequest"));
}
@Test
public void testMethodsAroundError() throws Throwable {
TRACE_DSL = true;
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.handleMethodException(enhancedInstance, null, allArguments, null, new RuntimeException());
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan indexSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertIndexSpan(indexSpan);
Assert.assertEquals(true, SpanHelper.getErrorOccurred(indexSpan));
SpanAssert.assertException(SpanHelper.getLogs(indexSpan).get(0), RuntimeException.class);
}
}
/*
* 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.
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.apache.skywalking.apm.agent.core.conf.Config.Plugin.Elasticsearch.TRACE_DSL;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.ExitSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.context.util.TagValuePair;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.test.helper.SegmentHelper;
import org.apache.skywalking.apm.agent.test.helper.SpanHelper;
import org.apache.skywalking.apm.agent.test.tools.AgentServiceRule;
import org.apache.skywalking.apm.agent.test.tools.SegmentStorage;
import org.apache.skywalking.apm.agent.test.tools.SegmentStoragePoint;
import org.apache.skywalking.apm.agent.test.tools.SpanAssert;
import org.apache.skywalking.apm.agent.test.tools.TracingSegmentRunner;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.action.search.SearchRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
/**
* @author aderm
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(TracingSegmentRunner.class)
@PrepareForTest(SearchRequest.class)
public class RestHighLevelClientSearchMethodsInterceptorTest {
@SegmentStoragePoint
private SegmentStorage segmentStorage;
@Rule
public AgentServiceRule serviceRule = new AgentServiceRule();
@Mock
private EnhancedInstance enhancedInstance;
@Mock
private SearchRequest searchRequest;
private Object[] allArguments;
@Mock
private RestClientEnhanceInfo restClientEnhanceInfo;
@Mock
private RestHighLevelClientSearchMethodsInterceptor interceptor;
@Before
public void setUp() throws Exception {
when(restClientEnhanceInfo.getPeers()).thenReturn("172.0.0.1:9200");
allArguments = new Object[] {searchRequest};
when(searchRequest.indices()).thenReturn(new String[] {"indexName"});
when(searchRequest.toString()).thenReturn("searchRequest");
when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn(restClientEnhanceInfo);
interceptor = new RestHighLevelClientSearchMethodsInterceptor();
}
@Test
public void testMethodsAround() throws Throwable {
TRACE_DSL = true;
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan searchSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertSearchSpan(searchSpan);
}
private void assertSearchSpan(AbstractTracingSpan getSpan) {
assertThat(getSpan instanceof ExitSpan, is(true));
ExitSpan exitSpan = (ExitSpan)getSpan;
assertThat(exitSpan.getOperationName(), is("Elasticsearch/SearchRequest"));
assertThat(exitSpan.getPeer(), is("172.0.0.1:9200"));
assertThat(SpanHelper.getComponentId(exitSpan), is(77));
List<TagValuePair> tags = SpanHelper.getTags(exitSpan);
assertThat(tags.size(), is(3));
assertThat(tags.get(0).getValue(), is("Elasticsearch"));
assertThat(tags.get(1).getValue(), is("[indexName]"));
assertThat(tags.get(2).getValue(), is("searchRequest"));
}
@Test
public void testMethodsAroundError() throws Throwable {
TRACE_DSL = true;
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.handleMethodException(enhancedInstance, null, allArguments, null, new RuntimeException());
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan searchSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertSearchSpan(searchSpan);
Assert.assertEquals(true, SpanHelper.getErrorOccurred(searchSpan));
SpanAssert.assertException(SpanHelper.getLogs(searchSpan).get(0), RuntimeException.class);
}
}
/*
* 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.
*/
package org.apache.skywalking.apm.plugin.elasticsearch.v6.interceptor;
import static org.apache.skywalking.apm.agent.core.conf.Config.Plugin.Elasticsearch.TRACE_DSL;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.ExitSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.context.util.TagValuePair;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.test.helper.SegmentHelper;
import org.apache.skywalking.apm.agent.test.helper.SpanHelper;
import org.apache.skywalking.apm.agent.test.tools.AgentServiceRule;
import org.apache.skywalking.apm.agent.test.tools.SegmentStorage;
import org.apache.skywalking.apm.agent.test.tools.SegmentStoragePoint;
import org.apache.skywalking.apm.agent.test.tools.SpanAssert;
import org.apache.skywalking.apm.agent.test.tools.TracingSegmentRunner;
import org.apache.skywalking.apm.plugin.elasticsearch.v6.RestClientEnhanceInfo;
import org.elasticsearch.action.update.UpdateRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
/**
* @author aderm
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(TracingSegmentRunner.class)
public class RestHighLevelClientUpdateMethodsInterceptorTest {
@SegmentStoragePoint
private SegmentStorage segmentStorage;
@Rule
public AgentServiceRule serviceRule = new AgentServiceRule();
@Mock
private EnhancedInstance enhancedInstance;
@Mock
private UpdateRequest updateRequest;
private Object[] allArguments;
@Mock
private RestClientEnhanceInfo restClientEnhanceInfo;
@Mock
private RestHighLevelClientUpdateMethodsInterceptor interceptor;
@Before
public void setUp() throws Exception {
when(restClientEnhanceInfo.getPeers()).thenReturn("172.0.0.1:9200");
allArguments = new Object[] {updateRequest};
when(updateRequest.index()).thenReturn("indexName");
when(updateRequest.toString()).thenReturn("updateRequest");
when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn(restClientEnhanceInfo);
interceptor = new RestHighLevelClientUpdateMethodsInterceptor();
}
@Test
public void testMethodsAround() throws Throwable {
TRACE_DSL = true;
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan updateSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertUpdateSpan(updateSpan);
}
private void assertUpdateSpan(AbstractTracingSpan getSpan) {
assertThat(getSpan instanceof ExitSpan, is(true));
ExitSpan exitSpan = (ExitSpan)getSpan;
assertThat(exitSpan.getOperationName(), is("Elasticsearch/UpdateRequest"));
assertThat(exitSpan.getPeer(), is("172.0.0.1:9200"));
assertThat(SpanHelper.getComponentId(exitSpan), is(77));
List<TagValuePair> tags = SpanHelper.getTags(exitSpan);
assertThat(tags.size(), is(3));
assertThat(tags.get(0).getValue(), is("Elasticsearch"));
assertThat(tags.get(1).getValue(), is("indexName"));
assertThat(tags.get(2).getValue(), is("updateRequest"));
}
@Test
public void testMethodsAroundError() throws Throwable {
TRACE_DSL = true;
interceptor.beforeMethod(enhancedInstance, null, allArguments, null, null);
interceptor.handleMethodException(enhancedInstance, null, allArguments, null, new RuntimeException());
interceptor.afterMethod(enhancedInstance, null, allArguments, null, null);
List<TraceSegment> traceSegmentList = segmentStorage.getTraceSegments();
Assert.assertThat(traceSegmentList.size(), is(1));
TraceSegment traceSegment = traceSegmentList.get(0);
AbstractTracingSpan updateSpan = SegmentHelper.getSpans(traceSegment).get(0);
assertUpdateSpan(updateSpan);
Assert.assertEquals(true, SpanHelper.getErrorOccurred(updateSpan));
SpanAssert.assertException(SpanHelper.getLogs(updateSpan).get(0), RuntimeException.class);
}
}
......@@ -32,6 +32,10 @@ public class SessionRequestConstructorInterceptor implements InstanceConstructor
@Override
public void onConstruct(EnhancedInstance objInst, Object[] allArguments) {
if (ContextManager.isActive()) {
if (ContextManager.activeSpan().isExit()) {
CONTEXT_LOCAL.remove();
return;
}
ContextSnapshot snapshot = ContextManager.capture();
objInst.setSkyWalkingDynamicField(new Object[]{snapshot, CONTEXT_LOCAL.get()});
}
......
......@@ -65,6 +65,7 @@
<module>sofarpc-plugin</module>
<module>activemq-5.x-plugin</module>
<module>elasticsearch-5.x-plugin</module>
<module>elasticsearch-6.x-plugin</module>
<module>undertow-plugins</module>
<module>rabbitmq-5.x-plugin</module>
<module>dubbo-conflict-patch</module>
......
......@@ -612,12 +612,12 @@ stage('Run Agent Plugin Tests') {
Find the button 'detail' of your Workload in the PR page. Enter to the page and get the elapsed time of your task.
### Workload 1
#### Group 1 (2164.287s)
#### Group 1 (2247.00s)
scenario name | versions | elapsed time (sec)
---|---|---
apm-toolkit-trace | 1 | 84.69
jetty 9.x | 63 | 1970.88
netty-socketio 1.x | 4 | 108.70
apm-toolkit-trace | 1 | 87.00
jetty 9.x | 63 | 2043.00
netty-socketio 1.x | 4 | 117.00
#### Group 2 (2119.991s)
scenario name | versions | elapsed time (sec)
......@@ -659,13 +659,14 @@ spring async 4.3.x-5.1.x | 35 | 967.70
mongodb 3.4.0-3.11.1 | 17 | 1465.63
### Workload 4
#### Group 1 (2397.45s)
#### Group 1 (2463.00s)
scenario name | versions | elapsed time (sec)
---|---|---
kafka 0.11.0.0-2.3.0 | 16 | 704.75
ehcache 2.8.x-2.10.x | 19 | 440.71
undertow 1.3.0-2.0.27 | 23 | 633.00
jedis 2.4.0-2.9.0 | 18 | 619
elasticsearch-6.x-scenario | 7 | 273.00
kafka 0.11.0.0-2.3.0 | 16 | 628.00
ehcache 2.8.x-2.10.x | 19 | 442.00
undertow 1.3.0-2.0.27 | 23 | 596.00
jedis 2.4.0-2.9.0 | 18 | 524.00
#### Group 2 (2148.155s)
scenario name | versions | elapsed time (sec)
......
......@@ -57,6 +57,7 @@
* [Xmemcached](https://github.com/killme2008/xmemcached) 2.x
* [Elasticsearch](https://github.com/elastic/elasticsearch)
* [transport-client](https://github.com/elastic/elasticsearch/tree/master/client/transport) 5.2.x-5.6.x
* [rest-high-level-client](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.7/index.html) 6.7.1-6.8.4
* [Solr](https://github.com/apache/lucene-solr/)
* [SolrJ](https://github.com/apache/lucene-solr/tree/master/solr/solrj) 7.x
* [Cassandra](https://github.com/apache/cassandra) 3.x
......
......@@ -257,6 +257,9 @@ Ehcache:
SocketIO:
id: 76
languages: Java
rest-high-level-client:
id: 77
languages: Java
# .NET/.NET Core components
# [3000, 4000) for C#/.NET only
......@@ -359,4 +362,5 @@ Component-Server-Mappings:
SolrJ: Solr
cassandra-java-driver: Cassandra
pulsar-producer: Pulsar
pulsar-consumer: Pulsar
\ No newline at end of file
pulsar-consumer: Pulsar
rest-high-level-client: Elasticsearch
#!/bin/bash
# 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.
home="$(cd "$(dirname $0)"; pwd)"
java -jar ${agent_opts} -Dskywalking.plugin.elasticsearch.trace_dsl=true ${home}/../libs/elasticsearch-6.x-scenario.jar &
# 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.
registryItems:
applications:
- {elasticsearch-6.x-scenario: nq 0}
instances:
- {elasticsearch-6.x-scenario: 1}
operationNames:
- elasticsearch-6.x-scenario: [Elasticsearch/CreateRequest, Elasticsearch/IndexRequest,
Elasticsearch/GetRequest, Elasticsearch/SearchRequest,
Elasticsearch/UpdateRequest, Elasticsearch/DeleteRequest,
/elasticsearch-case/case/elasticsearch]
heartbeat: []
segmentItems:
- applicationCode: elasticsearch-6.x-scenario
segmentSize: ge 1
segments:
- segmentId: not null
spans:
- operationName: Elasticsearch/CreateRequest
operationId: 0
parentSpanId: 0
spanId: 1
spanLayer: Database
startTime: nq 0
endTime: nq 0
componentId: 77
componentName: ''
isError: false
spanType: Exit
peer: not null
peerId: 0
tags:
- {key: db.type, value: Elasticsearch}
- {key: db.instance, value: not null}
- {key: db.statement, value: not null}
- operationName: Elasticsearch/IndexRequest
operationId: 0
parentSpanId: 0
spanId: 2
spanLayer: Database
startTime: nq 0
endTime: nq 0
componentId: 77
componentName: ''
isError: false
spanType: Exit
peer: not null
peerId: 0
tags:
- {key: db.type, value: Elasticsearch}
- {key: db.instance, value: not null}
- {key: db.statement, value: not null}
- operationName: Elasticsearch/GetRequest
operationId: 0
parentSpanId: 0
spanId: 3
spanLayer: Database
startTime: nq 0
endTime: nq 0
componentId: 77
componentName: ''
isError: false
spanType: Exit
peer: not null
peerId: 0
tags:
- {key: db.type, value: Elasticsearch}
- {key: db.instance, value: not null}
- {key: db.statement, value: not null}
- operationName: Elasticsearch/SearchRequest
operationId: 0
parentSpanId: 0
spanId: 4
spanLayer: Database
startTime: nq 0
endTime: nq 0
componentId: 77
componentName: ''
isError: false
spanType: Exit
peer: not null
peerId: 0
tags:
- {key: db.type, value: Elasticsearch}
- {key: db.instance, value: not null}
- {key: db.statement, value: not null}
- operationName: Elasticsearch/UpdateRequest
operationId: 0
parentSpanId: 0
spanId: 5
spanLayer: Database
startTime: nq 0
endTime: nq 0
componentId: 77
componentName: ''
isError: false
spanType: Exit
peer: not null
peerId: 0
tags:
- {key: db.type, value: Elasticsearch}
- {key: db.instance, value: not null}
- {key: db.statement, value: not null}
- operationName: Elasticsearch/DeleteRequest
operationId: 0
parentSpanId: 0
spanId: 6
spanLayer: Database
startTime: nq 0
endTime: nq 0
componentId: 77
componentName: ''
isError: false
spanType: Exit
peer: not null
peerId: 0
tags:
- {key: db.type, value: Elasticsearch}
- {key: db.instance, value: not null}
- operationName: /elasticsearch-case/case/elasticsearch
operationId: 0
parentSpanId: -1
spanId: 0
spanLayer: Http
startTime: nq 0
endTime: nq 0
componentId: 1
componentName: ''
isError: false
spanType: Entry
peer: ''
peerId: 0
tags:
- {key: url, value: 'http://localhost:8080/elasticsearch-case/case/elasticsearch'}
- {key: http.method, value: GET}
# 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.
type: jvm
entryService: http://localhost:8080/elasticsearch-case/case/elasticsearch
healthCheck: http://localhost:8080/elasticsearch-case/case/healthcheck
startScript: ./bin/startup.sh
framework: elasticsearch
environment:
- elasticsearch.server=elasticsearch-server:9200
dependencies:
elasticsearch-server:
image: elasticsearch:6.7.1
hostname: elasticsearch-server
expose:
- 9200
environment:
- cluster.name=docker-node
- xpack.security.enabled=false
- bootstrap.memory_lock=true
- "ES_JAVA_OPTS=-Xms256m -Xmx256m"
- discovery.type=single-node
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.apache.skywalking</groupId>
<artifactId>elasticsearch-6.x-scenario</artifactId>
<version>5.0.0</version>
<name>skywalking-elasticsearch-6.x-scenario</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler.version>1.8</compiler.version>
<test.framework.version>6.7.1</test.framework.version>
<docker.image.version>${test.framework.version}</docker.image.version>
<spring-boot.version>2.1.4.RELEASE</spring-boot.version>
<log4j.version>2.8.1</log4j.version>
</properties>
<dependencies>
<!-- spring boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot.version}</version>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-logging</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<!-- elasticsearch rest-high-level-client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${test.framework.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${test.framework.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
<build>
<finalName>elasticsearch-6.x-scenario</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>${compiler.version}</source>
<target>${compiler.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.9.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>assemble</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptors>
<descriptor>src/main/assembly/assembly.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
~
-->
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<formats>
<format>zip</format>
</formats>
<fileSets>
<fileSet>
<directory>./bin</directory>
<fileMode>0775</fileMode>
</fileSet>
</fileSets>
<files>
<file>
<source>${project.build.directory}/elasticsearch-6.x-scenario.jar</source>
<outputDirectory>./libs</outputDirectory>
<fileMode>0775</fileMode>
</file>
</files>
</assembly>
/*
* 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.
*
*/
package org.apache.skywalking.apm.testcase.elasticsearch;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
try {
SpringApplication.run(Application.class, args);
} catch (Exception e) {
// Never do this
}
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.testcase.elasticsearch.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author aderm
*/
@Configuration
public class ElasticsearchConfig {
@Value("${elasticsearch.server}")
private String elasticsearchHost;
@Bean(destroyMethod = "close")
public RestHighLevelClient client() {
HttpHost[] httpHostArry = parseEsHost();
RestHighLevelClient client = new RestHighLevelClient((RestClient.builder(httpHostArry)));
return client;
}
private HttpHost[] parseEsHost() {
HttpHost[] httpHostArray = null;
if (!elasticsearchHost.isEmpty()) {
String[] hostIp = elasticsearchHost.split(",");
httpHostArray = new HttpHost[hostIp.length];
for (int i = 0; i < hostIp.length; ++i) {
String[] hostIpItem = hostIp[i].split(":");
String ip = hostIpItem[0].trim();
String port = hostIpItem[1].trim();
httpHostArray[i] = new HttpHost(ip, Integer.parseInt(port), "http");
}
}
return httpHostArray;
}
}
/*
* 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.
*
*/
package org.apache.skywalking.apm.testcase.elasticsearch.controller;
import static java.util.Collections.singletonMap;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.flush.FlushRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/elasticsearch-case/case")
public class CaseController {
private static Logger logger = LogManager.getLogger(CaseController.class);
@Autowired
private RestHighLevelClient client;
@GetMapping("/healthcheck")
public String healthcheck() throws Exception {
ClusterHealthRequest request = new ClusterHealthRequest();
request.timeout(TimeValue.timeValueSeconds(10));
request.waitForStatus(ClusterHealthStatus.GREEN);
ClusterHealthResponse response = client.cluster().health(request, RequestOptions.DEFAULT);
if (response.isTimedOut()) {
String message = "elastic search node start fail!";
logger.error(message);
throw new RuntimeException(message);
}
return "Success";
}
@GetMapping("/elasticsearch")
public String elasticsearch() throws Exception {
String indexName = UUID.randomUUID().toString();
try {
//create
createIndex(client, indexName);
// index
index(client, indexName);
client.indices().flush(new FlushRequest(indexName), RequestOptions.DEFAULT);
//get
get(client, indexName);
// search
search(client, indexName);
// update
update(client, indexName);
// delete
delete(client, indexName);
} finally {
if (null != client) {
client.close();
}
}
return "Success";
}
private void createIndex(RestHighLevelClient client, String indexName) throws IOException {
CreateIndexRequest request = new CreateIndexRequest(indexName);
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.startObject("properties");
{
builder.startObject("author");
{
builder.field("type", "keyword");
}
builder.endObject();
builder.startObject("title");
{
builder.field("type", "keyword");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
request.mapping(builder);
request.settings(Settings.builder()
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 0)
);
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
if (createIndexResponse.isAcknowledged() == false) {
String message = "elasticsearch create index fail.";
logger.error(message);
throw new RuntimeException(message);
}
}
private void index(RestHighLevelClient client, String indexName) throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.field("author", "Marker");
builder.field("title", "Java programing.");
}
builder.endObject();
IndexRequest indexRequest = new IndexRequest(indexName,"_doc", "1").source(builder);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
if (indexResponse.status().getStatus() >= 400) {
String message = "elasticsearch index data fail.";
logger.error(message);
throw new RuntimeException(message);
}
}
private void get(RestHighLevelClient client, String indexName) throws IOException {
GetRequest getRequest = new GetRequest(indexName, "_doc", "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
if (!getResponse.isExists()) {
String message = "elasticsearch get data fail.";
logger.error(message);
throw new RuntimeException(message);
}
}
private void update(RestHighLevelClient client, String indexName) throws IOException {
UpdateRequest request = new UpdateRequest(indexName, "_doc", "1");
Map<String, Object> parameters = singletonMap("title", "c++ programing.");
Script inline = new Script(ScriptType.INLINE, "painless", "ctx._source.title = params.title", parameters);
request.script(inline);
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
if (updateResponse.getVersion() != 2) {
String message = "elasticsearch update data fail.";
logger.error(message);
throw new RuntimeException(message);
}
}
private void delete(RestHighLevelClient client, String indexName) throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest(indexName);
AcknowledgedResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT);
if (!deleteIndexResponse.isAcknowledged()) {
String message = "elasticsearch delete index fail.";
logger.error(message);
throw new RuntimeException(message);
}
}
private void search(RestHighLevelClient client, String indexName) throws IOException {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery("author", "Marker"));
sourceBuilder.from(0);
sourceBuilder.size(10);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(indexName);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
if (!(searchResponse.getHits().totalHits > 0)) {
String message = "elasticsearch search data fail.";
logger.error(message);
throw new RuntimeException(message);
}
}
}
# 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.
server:
port: 8080
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
~
-->
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_ERR">
<PatternLayout charset="UTF-8" pattern="[%d{yyyy-MM-dd HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="WARN">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
\ No newline at end of file
# 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.
6.7.1
6.7.2
6.8.0
6.8.1
6.8.2
6.8.3
6.8.4
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册