diff --git a/.github/workflows/gitee-sync.yml b/.github/workflows/gitee-sync.yml new file mode 100644 index 00000000..088b52ad --- /dev/null +++ b/.github/workflows/gitee-sync.yml @@ -0,0 +1,27 @@ +on: + push: + branches: + - master + tags: + - "*" + +name: Sync to Gitee +jobs: + run: + name: Run + runs-on: ubuntu-latest + steps: + - name: Checkout source code + uses: actions/checkout@v1 + - name: Mirror Github to Gitee + uses: Yikun/hub-mirror-action@v1.2 + with: + src: github/TarsCloud + dst: gitee/TarsCloud + dst_key: ${{ secrets.GITEE_PRIVATE_KEY }} + dst_token: ${{ secrets.GITEE_TOKEN }} + account_type: org + timeout: 600 + debug: true + force_update: true + static_list: "TarsJava" \ No newline at end of file diff --git a/.gitignore b/.gitignore index 125aafc3..b3723d64 100644 --- a/.gitignore +++ b/.gitignore @@ -3,8 +3,12 @@ *.iml *.iws target/ +.gradle/ +**/build/ *.jar !.mvn/wrapper/* .settings/ .project .classpath +*.dat +examples/**/testapp/*.java diff --git a/Contributing.md b/Contributing.md new file mode 100644 index 00000000..70c4e1af --- /dev/null +++ b/Contributing.md @@ -0,0 +1,16 @@ +# Contributing + +If you contributed but cannot find your ID here, please submit PR and add your GitHub ID to both [Tars repo](https://github.com/TarsCloud/Tars/pulls) and [here](https://github.com/TarsCloud/TarsJava/pulls). + +## TarsJava + +- diracccc +- kahn +- LawlietLi +- LiuMenghan +- TimmyYu +- walkertest +- woodwind +- XenoAmess +- yukkiball +- Kongyuanyuan \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..36f4f9fa --- /dev/null +++ b/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2020, THE TARS FOUNDATION +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.md b/README.md index c8110e02..ccd633ba 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,525 @@ -[点我查看中文版](README.zh.md) +Tars Java - An RPC library and framework +======================================== +[![Latest release](https://img.shields.io/github/v/release/tarsCloud/TarsJava)](https://github.com/TarsCloud/TarsJava/releases/latest) -### This project is the source code of the Tars RPC framework Java language. ### +This project is the source code of the Tars RPC framework Java language. + + + + + + + + + +
Homepage:tarscloud.org
中文版:点我查看中文版
-| Directory | Features | -| ------------------ | ---------------- | -| net | Source code implementation of Java language net framework | -| core | Source code implementation of Java language rpc framework | -| tools | Source code implementation of framework tools, maven plug-ins, etc | -| examples | Sample code for the Java language framework | -| distributedContext | Source code implementation of Java language framework's distributed context | -| protobuf | Source code implementation of pb protocol support | -| spring | Source code implementation of spring framework support | +### Environmental dependence - -### Environmental dependence - JDK1.8 or above -- Maven 2.2.1 or above \ No newline at end of file +- Maven 3.5 or above + +### + +## TarsFramework deployment by Docker + +This guide uses Docker to complete the deployment of Tars.[Macos、 Linux] + +** Start TarsFramework in Docker** + +```bash +docker pull tarscloud/framework:latest +docker pull tarscloud/tars-node:latest +docker pull mysql:5.6 +docker network create -d bridge --subnet=172.25.0.0/16 --gateway=172.25.0.1 tars +docker run -d \ +--net=tars \ +-e MYSQL_ROOT_PASSWORD="root@appinside" \ +--ip="172.25.0.2" \ +--name=tars-mysql \ +mysql:5.6 +sleep 30s +docker run -d \ +--net=tars \ +-e MYSQL_HOST=172.25.0.2 \ +-e MYSQL_ROOT_PASSWORD='root@appinside' \ +-eREBUILD=false -eSLAVE=false \ +-e INET=eth0 \ +--ip="172.25.0.4" \ +-p 3000-3001:3000-3001 \ +tarscloud/framework +sleep 60s +docker run -d --net=tars --ip="172.25.0.3" -eWEB_HOST=http://172.25.0.4:3000 tarscloud/tars-node +``` + +**Note: - P 18600-18700:18600-18700 parameter opens 18600-18700 port for application. You can add more ports if +necessary** + +# Quick Start To TarsServer(Provider) + +This guide gives you a quick introduction to Tars in Java through simple +server [example server](./examples/tars-spring-boot-server) + +#### Project structure + +```text +├── pom.xml +└── src + └── main + ├── java + │ └── tars + │ └── testapp + │ ├── HelloServant.java + │ ├── QuickStartApplication.java + │ └── impl + │ └── HelloServantImpl.java + └── resources + └── hello.tars + +``` + +#### Dependency configuration + +The following configuration needs to be added in pom.xml: + +**Spring boot and Tars framework dependency** + +```xml + + + 2.3.5.RELEASE + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + com.tencent.tars + tars-spring-boot-starter + 2.0.0 + + +``` + +**Plugin dependency** + +```xml + + + com.tencent.tars + tars-maven-plugin + 2.0.0 + + + + + ${basedir}/src/main/resources/hello.tars + + + UTF-8 + + true + + UTF-8 + + ${basedir}/src/main/java + + com.qq.tars.quickstart.server. + + + + + +org.apache.maven.plugins +maven-jar-plugin +2.6 + + + + conf/ + + + + + +org.springframework.boot +spring-boot-maven-plugin + + + com.qq.tars.quickstart.server.QuickStartApplication + + + + + repackage + + + +``` + +#### Service development + +##### Tars interface file definition + +Tars has its own interface file format. First, we need to define the Tars interface file. Create a new hello.tars file +in the resources directory with the following content: + +```text +module TestApp +{ + interface Hello + { + string hello(int no, string name); + }; +}; +``` + +##### Interface file compilation + +Then we need to convert the Tars interface file to the server interface code using the tars-maven-plugin. In the project +root directory, execute `mvn tars: tars2java` to get HelloServant.java, the content is as follows: + +```java + +@Servant +public interface HelloServant { + + public String hello(int no, String name); +} +``` + +##### Interface implementation + +Next we need to implement the generated server interface. Create a new HelloServantImpl.java file, implement the +HelloServant.java interface, and expose the service through the @TarsServant annotation, where 'HelloObj' is the servant +name, corresponding to the name in the web management platform. + +```java + +@TarsServant("HelloObj") +public class HelloServantImpl implements HelloServant { + + @Override + public String hello(int no, String name) { + return String.format("hello no=%s, name=%s, time=%s", no, name, System.currentTimeMillis()); + } +} +``` + +##### Tars service enabling + +Finally, add @EnableTarsServer annotation in the spring boot startup class QuickStartApplication to enable Tars service: + +```java + +@SpringBootApplication +@EnableTarsServer +public class QuickStartApplication { + public static void main(String[] args) { + SpringApplication.run(QuickStartApplication.class, args); + } +} +``` + +Using spring-boot-maven-plugin, execute `mvn package` in the root directory to package it into a jar. + +### Client(Consumer) development + +This guide gives you a quick introduction to Tars in Java through simple +client [example client](./examples/tars-spring-boot-server) + +#### Project structure + +```text +├── pom.xml +└── src + └── main + ├── java + │ └── tars + │ └── testapp + │ ├── HelloPrx.java + │ ├── HelloPrxCallback.java + │ ├── App.java + │ └── impl + │ └── ClientServantImpl.java + └── resources + ├── hello.tars + └── client.tars + +``` + +#### Dependency configuration + +The following configuration needs to be added in pom.xml: + +**Spring boot and Tars framework dependency** + +```xml + + + 2.0.3.RELEASE + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + com.tencent.tars + tars-spring-boot-starter + 2.0.0 + + +``` + +**Plugin dependency** + +```xml + + + com.tencent.tars + tars-maven-plugin + 2.0.0 + + + + + ${basedir}/src/main/resources/hello.tars + + + UTF-8 + + false + + UTF-8 + + ${basedir}/src/main/java + + com.tencent.tars.client. + + + + + +org.apache.maven.plugins +maven-jar-plugin +2.6 + + + + conf/ + + + + + +org.springframework.boot +spring-boot-maven-plugin + + + com.tencent.tars.App + + + + + repackage + + + +``` + +#### Service development + +##### Server interface file compilation + +After the server service development is completed, we first need to obtain the client interface code of the server +service. Copy the hello.tars file on the server side to the resources directory, and execute `mvn tars: tars2java` in +the project root directory to get HelloPrx.java. At this time, the proxy interface of the server service is obtained, +and three calling methods are provided, namely synchronous call, asynchronous call and promise call. + +```java + +@Servant +public interface HelloPrx { + + String hello(int no, String name); + + CompletableFuture promise_hello(int no, String name); + + String hello(int no, String name, @TarsContext java.util.Map ctx); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); +} +``` + +The promise call is a new feature of Tars v2.0.0. For specific use, please refer to +the [Tars file reference](./docs-en/tars-reference.md). + +##### Client interface file definition + +Then define the interface file of the client service. Create a new client.tars file in the resources directory with the +following content: + +```text +module TestApp +{ + interface Client + { + string rpcHello(int no, string name); + }; +}; +``` + +##### Client interface file compilation + +Next, we need to use the tars-maven-plugin to generate client service interface code. Modify the tars2java plugin +dependency of pom.xml as follows. Note that ` ` is set to true. + +```xml + + + com.tencent.tars + tars-maven-plugin + 2.0.0 + + + + + ${basedir}/src/main/resources/client.tars + + + UTF-8 + + true + + UTF-8 + + ${basedir}/src/main/java + + com.tencent.tars.client. + + + +``` + +In the root directory of the project, execute `mvn tars: tars2java` again to get ClientServant.java. The contents are as +follows: + +```java + +@Servant +public interface ClientServant { + public String rpcHello(int no, String name); +} +``` + +##### Interface implementation + +We need to implement the generated client service interface. Create a new ClientServantImpl.java file, implement the +HelloServant.java interface, and expose the service through the @TarsServant annotation, where 'HelloObj' is the servant +name, corresponding to the name in the web management platform. + +By adding the @TarsClient annotation to the client properties, the corresponding service can be automatically injected. +If only the Obj name is filled, the default value is used to inject the client. In addition, the client configuration +can be customized in the annotation, such as setting the synchronous call timeout time. + +```java + +@TarsServant("ClientObj") +public class ClientServantImpl implements ClientServant { + @TarsClient("TestServer.HelloServer.HelloObj") + HelloPrx helloPrx; + + String res = ""; + + @Override + public String rpcHello(int no, String name) { + //sync call + String syncres = helloPrx.hello(1000, "Hello World"); + res += "sync_res: " + syncres + " "; + //async call + helloPrx.async_hello(new HelloPrxCallback() { + + @Override + public void callback_expired() { + } + + @Override + public void callback_exception(Throwable ex) { + } + + @Override + public void callback_hello(String ret) { + res += "async_res: " + ret + " "; + + } + }, 1000, "HelloWorld"); + //promise call + helloPrx.promise_hello(1000, "hello world").thenCompose(x -> { + res += "promise_res: " + x; + return CompletableFuture.completedFuture(0); + }); + return res; + } +} + +``` + +##### Tars service enabling + +Finally, add @EnableTarsServer annotation in the spring boot startup class App to enable Tars service: + +```java + +@SpringBootApplication +@EnableTarsServer +public class App { + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } +} +``` + +##### Service packaging + +Using spring-boot-maven-plugin, execute `mvn package` in the root directory to package it into a jar. + +### Function description + +Tars-java is compatible with the Spring Cloud system, users can integrate the Tars-java into Spring Cloud. + +| Directory |Features | +| :----- | :----- | +| net | Source code implementation of Java language net framework | +| core | Source code implementation of Java language rpc framework | +| tools | Source code implementation of framework tools, maven plug-ins, etc | +| examples | Sample code for the Java language framework | +| distributedContext | Source code implementation of Java language framework's distributed context | +| protobuf | Source code implementation of pb protocol support | +| spring | Source code implementation of spring framework support | + + + + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..d6bc1b23 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,122 @@ +import java.time.Instant + +plugins { + java + `maven-publish` + signing +} + +val tarsVersion = "2.0.0" + +allprojects { + group = "com.tencent.tars" + version = tarsVersion + + repositories { + mavenCentral() + mavenLocal() + } +} + +subprojects { + apply(plugin = "java") + apply(plugin = "maven-publish") + apply(plugin = "signing") + + java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + withSourcesJar() + withJavadocJar() + } + + tasks.withType { + options.encoding = "UTF-8" + } + + tasks.withType { + options { + (this as StandardJavadocDocletOptions).addStringOption("Xdoclint:none", "-quiet") + } + } + + tasks.withType { + manifest { + attributes["Built-By"] = "gradle" + attributes["Built-Time"] = Instant.now().toString() + } + } + + publishing { + publications { + create("mavenJava") { + from(components["java"]) + + pom { + name.set(project.name) + description.set("Tars Java - High performance RPC framework") + url.set("https://github.com/TarsCloud/TarsJava") + + licenses { + license { + name.set("The BSD 3-Clause License") + url.set("https://opensource.org/licenses/BSD-3-Clause") + } + } + + developers { + developer { + name.set("tencent") + email.set("tars@tencent.com") + organization.set("Tencent") + organizationUrl.set("https://github.com/TarsCloud") + } + } + + scm { + connection.set("scm:git:https://github.com/TarsCloud/TarsJava.git") + developerConnection.set("scm:git:https://github.com/TarsCloud/TarsJava.git") + url.set("https://github.com/TarsCloud/TarsJava") + } + } + } + } + + repositories { + maven { + name = "sonatype" + val releasesRepoUrl = uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/") + val snapshotsRepoUrl = uri("https://oss.sonatype.org/content/repositories/snapshots/") + url = if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl + + credentials { + username = findProperty("ossrhUsername")?.toString() ?: System.getenv("OSSRH_USERNAME") + password = findProperty("ossrhPassword")?.toString() ?: System.getenv("OSSRH_PASSWORD") + } + } + } + } + + signing { + setRequired { + !version.toString().endsWith("SNAPSHOT") && gradle.taskGraph.hasTask("publish") + } + sign(publishing.publications["mavenJava"]) + } + + tasks.withType { + useJUnit() + } +} + +// Skip publishing for parent/aggregation modules +listOf("tars-parent", "tars-spring-parent", "tars-tools", "tars-examples").forEach { moduleName -> + project.subprojects.find { it.name == moduleName }?.afterEvaluate { + tasks.withType { + enabled = false + } + tasks.withType { + enabled = false + } + } +} diff --git a/core/build.gradle.kts b/core/build.gradle.kts new file mode 100644 index 00000000..beddd7b0 --- /dev/null +++ b/core/build.gradle.kts @@ -0,0 +1,24 @@ +plugins { + `java-library` +} + +description = "Tars Core - Core RPC Framework" + +dependencies { + api(project(":tars-common-api")) + api(project(":tars-netty")) + + implementation(libs.servlet.api) + implementation(libs.httpcore) + implementation(libs.gson) + + // Tracing dependencies + implementation(libs.zipkin.sender.kafka) + implementation(libs.zipkin.sender.urlconnection) + implementation(libs.brave.opentracing) + implementation(libs.opentelemetry.sdk) + implementation(libs.opentelemetry.exporter.otlp) + implementation(libs.opentelemetry.opentracing.shim) + + testImplementation(libs.junit) +} diff --git a/core/client.pom.xml b/core/client.pom.xml deleted file mode 100644 index 7d22b910..00000000 --- a/core/client.pom.xml +++ /dev/null @@ -1,113 +0,0 @@ - - - 4.0.0 - - com.tencent.tars - tars-parent - 1.6.1 - - tars-client - ${project.artifactId} - jar - - - UTF-8 - 5.1.0 - 0.31.1 - 2.7.4 - - - - - com.tencent.tars - tars-net - ${project.parent.version} - - - com.tencent.tars - tars-context - ${project.parent.version} - - - javax.servlet - javax.servlet-api - 3.0.1 - - - junit - junit - 3.8.1 - test - - - io.zipkin.reporter2 - zipkin-sender-kafka11 - ${zipkin-reporter.version} - - - io.opentracing.brave - brave-opentracing - ${brave-opentracing.version} - - - io.zipkin.reporter2 - zipkin-sender-kafka08 - ${zipkin-reporter.version} - - - io.zipkin.reporter2 - zipkin-sender-urlconnection - ${zipkin-reporter.version} - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - com/qq/tars/client/** - com/qq/tars/common/** - com/qq/tars/protocol/** - com/qq/tars/rpc/** - com/qq/tars/register/** - com/qq/tars/support/query/** - com/qq/tars/support/stat/** - com/qq/tars/support/log/** - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - attach-sources - verify - - jar-no-fork - - - - - - com/qq/tars/client/** - com/qq/tars/common/** - com/qq/tars/protocol/** - com/qq/tars/rpc/** - com/qq/tars/register/** - com/qq/tars/support/query/** - com/qq/tars/support/stat/** - com/qq/tars/support/log/** - - - - - - diff --git a/core/pom.xml b/core/pom.xml deleted file mode 100644 index 0f9636ee..00000000 --- a/core/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - 4.0.0 - - com.tencent.tars - tars-parent - 1.6.1 - - tars-core - ${project.artifactId} - jar - - - UTF-8 - 5.1.0 - 0.31.1 - 2.7.4 - - - - - com.tencent.tars - tars-net - ${project.parent.version} - - - javax.servlet - javax.servlet-api - 3.0.1 - - - com.tencent.tars - tars-context - ${project.parent.version} - - - io.zipkin.reporter2 - zipkin-sender-kafka11 - ${zipkin-reporter.version} - - - io.opentracing.brave - brave-opentracing - ${brave-opentracing.version} - - - io.zipkin.reporter2 - zipkin-sender-kafka08 - ${zipkin-reporter.version} - - - io.zipkin.reporter2 - zipkin-sender-urlconnection - ${zipkin-reporter.version} - - - diff --git a/core/server.pom.xml b/core/server.pom.xml deleted file mode 100644 index 8988240e..00000000 --- a/core/server.pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - 4.0.0 - - com.tencent.tars - tars-parent - 1.6.1 - - tars-server - ${project.artifactId} - jar - - - UTF-8 - 5.1.0 - 0.31.1 - 2.7.4 - - - - - com.tencent.tars - tars-client - ${project.parent.version} - - - javax.servlet - javax.servlet-api - 3.0.1 - - - junit - junit - 3.8.1 - test - - - io.zipkin.reporter2 - zipkin-sender-kafka11 - ${zipkin-reporter.version} - - - io.opentracing.brave - brave-opentracing - ${brave-opentracing.version} - - - io.zipkin.reporter2 - zipkin-sender-kafka08 - ${zipkin-reporter.version} - - - io.zipkin.reporter2 - zipkin-sender-urlconnection - ${zipkin-reporter.version} - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - com/qq/tars/server/** - com/qq/tars/common/** - com/qq/tars/protocol/** - com/qq/tars/register/** - com/qq/tars/support/log/** - com/qq/tars/support/om/** - com/qq/tars/support/trace/** - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - verify - - jar-no-fork - - - - - - com/qq/tars/server/** - com/qq/tars/common/** - com/qq/tars/protocol/** - com/qq/tars/register/** - com/qq/tars/support/log/** - com/qq/tars/support/om/** - com/qq/tars/support/trace/** - - - - - - diff --git a/core/src/main/java/com/qq/tars/client/Communicator.java b/core/src/main/java/com/qq/tars/client/Communicator.java index a30efc52..d15d2432 100644 --- a/core/src/main/java/com/qq/tars/client/Communicator.java +++ b/core/src/main/java/com/qq/tars/client/Communicator.java @@ -17,10 +17,8 @@ package com.qq.tars.client; import com.qq.tars.client.support.ClientPoolManager; -import com.qq.tars.client.util.ClientLogger; import com.qq.tars.common.support.ScheduledExecutorManager; import com.qq.tars.common.util.StringUtils; -import com.qq.tars.net.client.ticket.TicketManager; import com.qq.tars.rpc.common.LoadBalance; import com.qq.tars.rpc.common.ProtocolInvoker; import com.qq.tars.rpc.exc.CommunicatorConfigException; @@ -64,22 +62,28 @@ public T stringToProxy(Class clazz, String objName, String setDivision) t return stringToProxy(clazz, objName, setDivision, null, null, null); } - public T stringToProxy(Class clazz, ServantProxyConfig servantProxyConfig) throws CommunicatorConfigException { - return stringToProxy(clazz, servantProxyConfig.getObjectName(), servantProxyConfig.getSetDivision(), servantProxyConfig, null, null); + public T stringToProxy(Class clazz, ServantProxyConfig servantProxyConfig) + throws CommunicatorConfigException { + return stringToProxy(clazz, servantProxyConfig.getObjectName(), servantProxyConfig.getSetDivision(), + servantProxyConfig, null, null); } @Deprecated - public T stringToProxy(Class clazz, ServantProxyConfig servantProxyConfig, LoadBalance loadBalance) throws CommunicatorConfigException { - return stringToProxy(clazz, servantProxyConfig.getObjectName(), servantProxyConfig.getSetDivision(), servantProxyConfig, loadBalance, null); + public T stringToProxy(Class clazz, ServantProxyConfig servantProxyConfig, LoadBalance loadBalance) + throws CommunicatorConfigException { + return stringToProxy(clazz, servantProxyConfig.getObjectName(), servantProxyConfig.getSetDivision(), + servantProxyConfig, loadBalance, null); } @SuppressWarnings("unchecked") - private T stringToProxy(Class clazz, String objName, String setDivision, ServantProxyConfig servantProxyConfig, - LoadBalance loadBalance, ProtocolInvoker protocolInvoker) throws CommunicatorConfigException { + private T stringToProxy(Class clazz, String objName, String setDivision, + ServantProxyConfig servantProxyConfig, LoadBalance loadBalance, ProtocolInvoker protocolInvoker) + throws CommunicatorConfigException { if (!inited.get()) { throw new CommunicatorConfigException("communicator uninitialized!"); } - return (T) getServantProxyFactory().getServantProxy(clazz, objName, setDivision, servantProxyConfig, loadBalance, protocolInvoker); + return (T) getServantProxyFactory().getServantProxy(clazz, objName, setDivision, servantProxyConfig, + loadBalance, protocolInvoker); } @Deprecated @@ -90,8 +94,7 @@ public void initialize(CommunicatorConfig config) throws CommunicatorConfigExcep public void shutdown() { this.threadPoolExecutor.shutdownNow(); ScheduledExecutorManager.getInstance().shutdownNow(); - TicketManager.shutdown(); - for (Iterator it = servantProxyFactory.getProxyIterator(); it.hasNext(); ) { + for (Iterator it = servantProxyFactory.getProxyIterator(); it.hasNext();) { Object proxy = it.next(); ((ObjectProxy) Proxy.getInvocationHandler(proxy)).destroy(); } @@ -105,7 +108,6 @@ private void initCommunicator(CommunicatorConfig config) throws CommunicatorConf try { if (!inited.get()) { try { - ClientLogger.init(config.getLogPath(), config.getLogLevel()); if (StringUtils.isEmpty(config.getLocator())) { this.id = UUID.randomUUID().toString().replaceAll("-", ""); } else { diff --git a/core/src/main/java/com/qq/tars/client/CommunicatorFactory.java b/core/src/main/java/com/qq/tars/client/CommunicatorFactory.java index da2bae09..4089f15b 100644 --- a/core/src/main/java/com/qq/tars/client/CommunicatorFactory.java +++ b/core/src/main/java/com/qq/tars/client/CommunicatorFactory.java @@ -1,3 +1,4 @@ + /** * Tencent is pleased to support the open source community by making Tars available. * @@ -16,15 +17,18 @@ package com.qq.tars.client; -import java.util.concurrent.ConcurrentHashMap; - import com.qq.tars.client.util.ParseTools; +import javax.annotation.concurrent.ThreadSafe; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@ThreadSafe public final class CommunicatorFactory { private final static CommunicatorFactory instance = new CommunicatorFactory(); - private volatile ConcurrentHashMap CommunicatorMap = new ConcurrentHashMap(); + private final Map communicatorMap = new ConcurrentHashMap<>(); private volatile Communicator communicator = null; @@ -43,7 +47,7 @@ void setCommunicator(Communicator communicator) { } public Communicator getCommunicator(String locator) { - Communicator communicator = CommunicatorMap.get(locator); + Communicator communicator = communicatorMap.get(locator); if (communicator != null) { return communicator; } @@ -52,16 +56,16 @@ public Communicator getCommunicator(String locator) { config = new CommunicatorConfig(); config.setLocator(locator); } - CommunicatorMap.putIfAbsent(locator, new Communicator(config)); - return CommunicatorMap.get(locator); + communicatorMap.putIfAbsent(locator, new Communicator(config)); + return communicatorMap.get(locator); } public Communicator getCommunicator(CommunicatorConfig config) { - Communicator communicator = CommunicatorMap.get(config); + Communicator communicator = communicatorMap.get(config); if (communicator != null) { return communicator; } - CommunicatorMap.putIfAbsent(config, new Communicator(config)); - return CommunicatorMap.get(config); + communicatorMap.putIfAbsent(config, new Communicator(config)); + return communicatorMap.get(config); } } diff --git a/core/src/main/java/com/qq/tars/client/ObjectProxy.java b/core/src/main/java/com/qq/tars/client/ObjectProxy.java index f0e5f1de..e4e5b6dd 100644 --- a/core/src/main/java/com/qq/tars/client/ObjectProxy.java +++ b/core/src/main/java/com/qq/tars/client/ObjectProxy.java @@ -17,17 +17,24 @@ package com.qq.tars.client; import com.qq.tars.client.support.ServantCacheManager; -import com.qq.tars.client.util.ClientLogger; import com.qq.tars.client.util.ParseTools; import com.qq.tars.common.support.ScheduledExecutorManager; import com.qq.tars.common.util.StringUtils; import com.qq.tars.register.RegisterManager; -import com.qq.tars.rpc.common.*; +import com.qq.tars.rpc.common.InvokeContext; +import com.qq.tars.rpc.common.Invoker; +import com.qq.tars.rpc.common.LoadBalance; +import com.qq.tars.rpc.common.ProtocolInvoker; +import com.qq.tars.rpc.common.Url; import com.qq.tars.rpc.common.exc.NoInvokerException; import com.qq.tars.rpc.exc.ClientException; import com.qq.tars.rpc.exc.NoConnectionException; +import com.qq.tars.support.log.LoggerFactory; import com.qq.tars.support.stat.InvokeStatHelper; +import java.util.logging.Level; +import java.util.logging.Logger; + import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Random; @@ -35,9 +42,10 @@ import java.util.concurrent.TimeUnit; public final class ObjectProxy implements ServantProxy, InvocationHandler { + private static final Logger logger = LoggerFactory.getClientLogger(); private final Class api; - //private final String objName; + // private final String objName; private final Communicator communicator; private final ServantCacheManager servantCacheManager = ServantCacheManager.getInstance(); @@ -54,9 +62,9 @@ public final class ObjectProxy implements ServantProxy, InvocationHandler { private final Random random = new Random(System.currentTimeMillis() / 1000); public ObjectProxy(Class api, ServantProxyConfig servantProxyConfig, LoadBalance loadBalance, - ProtocolInvoker protocolInvoker, Communicator communicator) { + ProtocolInvoker protocolInvoker, Communicator communicator) { this.api = api; -// this.objName = objName; + // this.objName = objName; this.communicator = communicator; this.servantProxyConfig = servantProxyConfig; this.loadBalancer = loadBalance; @@ -94,8 +102,9 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl return invoker.invoke(context); } catch (Throwable e) { e.printStackTrace(); - if (ClientLogger.getLogger().isDebugEnabled()) { - ClientLogger.getLogger().debug(servantProxyConfig.getSimpleObjectName() + " error occurred on invoke|" + e.getLocalizedMessage(), e); + if (logger.isLoggable(Level.FINE)) { + logger.log(Level.FINE, servantProxyConfig.getSimpleObjectName() + " error occurred on invoke|" + + e.getLocalizedMessage(), e); } if (e instanceof NoInvokerException) { throw new NoConnectionException(servantProxyConfig.getSimpleObjectName(), e.getLocalizedMessage(), e); @@ -118,7 +127,7 @@ public String getObjectName() { public void refresh() { synchronized (refreshLock) { - registryStatReproter(); + registryStatReporter(); registryServantNodeRefresher(); protocolInvoker.refresh(); loadBalancer.refresh(protocolInvoker.getInvokers()); @@ -140,22 +149,24 @@ public ServantProxyConfig getConfig() { private void initialize() { loadBalancer.refresh(protocolInvoker.getInvokers()); - if (StringUtils.isNotEmpty(this.servantProxyConfig.getLocator()) && !StringUtils.isEmpty(this.servantProxyConfig.getStat())) { - this.registryStatReproter(); + if (StringUtils.isNotEmpty(this.servantProxyConfig.getLocator()) + && !StringUtils.isEmpty(this.servantProxyConfig.getStat())) { + this.registryStatReporter(); } if (!servantProxyConfig.isDirectConnection()) { this.registryServantNodeRefresher(); } } - private void registryStatReproter() { + private void registryStatReporter() { if (this.statReportFuture != null && !this.statReportFuture.isCancelled()) { this.statReportFuture.cancel(false); } if (!StringUtils.isEmpty(communicator.getCommunicatorConfig().getStat())) { int interval = servantProxyConfig.getReportInterval(); int initialDelay = interval + (random.nextInt(30) * 1000); - this.statReportFuture = ScheduledExecutorManager.getInstance().scheduleAtFixedRate(new ServantStatReproter(), initialDelay, interval, TimeUnit.MILLISECONDS); + this.statReportFuture = ScheduledExecutorManager.getInstance() + .scheduleAtFixedRate(new ServantStatReporter(), initialDelay, interval, TimeUnit.MILLISECONDS); } } @@ -166,7 +177,8 @@ private void registryServantNodeRefresher() { if (!servantProxyConfig.isDirectConnection()) { int interval = servantProxyConfig.getRefreshInterval(); int initialDelay = interval + (random.nextInt(30) * 1000); - this.queryRefreshFuture = ScheduledExecutorManager.getInstance().scheduleAtFixedRate(new ServantNodeRefresher(), initialDelay, interval, TimeUnit.MILLISECONDS); + this.queryRefreshFuture = ScheduledExecutorManager.getInstance() + .scheduleAtFixedRate(new ServantNodeRefresher(), initialDelay, interval, TimeUnit.MILLISECONDS); } } @@ -177,36 +189,44 @@ public void run() { try { String nodes; if (RegisterManager.getInstance().getHandler() != null) { - nodes = ParseTools.parse(RegisterManager.getInstance().getHandler().query(servantProxyConfig.getSimpleObjectName()), + nodes = ParseTools.parse( + RegisterManager.getInstance().getHandler().query(servantProxyConfig.getSimpleObjectName()), servantProxyConfig.getSimpleObjectName()); } else { nodes = communicator.getQueryHelper().getServerNodes(servantProxyConfig); } if (nodes != null && !nodes.equals(servantProxyConfig.getObjectName())) { - servantCacheManager.save(communicator.getId(), servantProxyConfig.getSimpleObjectName(), nodes, communicator.getCommunicatorConfig().getDataPath()); + servantCacheManager.save(communicator.getId(), servantProxyConfig.getSimpleObjectName(), nodes, + communicator.getCommunicatorConfig().getDataPath()); servantProxyConfig.setObjectName(nodes); refresh(); } - ClientLogger.getLogger().debug(servantProxyConfig.getSimpleObjectName() + " sync server|" + nodes); + logger.log(Level.FINE, "{0} sync server|{1}", new Object[]{servantProxyConfig.getSimpleObjectName(), nodes}); } catch (Throwable e) { - ClientLogger.getLogger().error(servantProxyConfig.getSimpleObjectName() + " error sync server", e); + logger.log(Level.SEVERE, servantProxyConfig.getSimpleObjectName() + " error sync server", e); } finally { - ClientLogger.getLogger().info("ServantNodeRefresher run(" + servantProxyConfig.getSimpleObjectName() + "), use: " + (System.currentTimeMillis() - begin)); + logger.log(Level.INFO, "ServantNodeRefresher run({0}), use: {1}", new Object[]{servantProxyConfig.getSimpleObjectName(), + (System.currentTimeMillis() - begin)}); } } } - private class ServantStatReproter implements Runnable { + private class ServantStatReporter implements Runnable { public void run() { long begin = System.currentTimeMillis(); try { - communicator.getStatHelper().report(InvokeStatHelper.getInstance().getProxyStat(servantProxyConfig.getSimpleObjectName()), true); + communicator.getStatHelper().report( + InvokeStatHelper.getInstance().getProxyStat(servantProxyConfig.getSimpleObjectName()), true); } catch (Exception e) { - ClientLogger.getLogger().error("report stat worker error|" + servantProxyConfig.getSimpleObjectName(), e); + logger.log(Level.SEVERE, "report stat worker error|" + servantProxyConfig.getSimpleObjectName(), e); } finally { - ClientLogger.getLogger().info("ServantStatReproter run(), use: " + (System.currentTimeMillis() - begin)); + logger.info("ServantStatReproter run(), use: " + (System.currentTimeMillis() - begin)); } } } -} \ No newline at end of file + + public static void main(String[] args) { + System.out.println("hello world"); + } +} diff --git a/core/src/main/java/com/qq/tars/client/ObjectProxyFactory.java b/core/src/main/java/com/qq/tars/client/ObjectProxyFactory.java index 4629fd88..3d62bea5 100644 --- a/core/src/main/java/com/qq/tars/client/ObjectProxyFactory.java +++ b/core/src/main/java/com/qq/tars/client/ObjectProxyFactory.java @@ -19,7 +19,6 @@ import com.qq.tars.client.rpc.loadbalance.DefaultLoadBalance; import com.qq.tars.client.rpc.tars.TarsProtocolInvoker; import com.qq.tars.client.support.ServantCacheManager; -import com.qq.tars.client.util.ClientLogger; import com.qq.tars.client.util.ParseTools; import com.qq.tars.common.util.StringUtils; import com.qq.tars.protocol.annotation.Servant; @@ -30,12 +29,17 @@ import com.qq.tars.rpc.exc.ClientException; import com.qq.tars.rpc.exc.CommunicatorConfigException; import com.qq.tars.rpc.protocol.Codec; -import com.qq.tars.rpc.protocol.ServantProtocolFactory; -import com.qq.tars.rpc.protocol.tars.TarsCodec; +import com.qq.tars.rpc.protocol.tars.TarsClientCodec; +import com.qq.tars.support.log.LoggerFactory; + +import java.util.logging.Level; +import java.util.logging.Logger; import java.lang.reflect.Constructor; class ObjectProxyFactory { + private static final Logger logger = LoggerFactory.getClientLogger(); + private final Communicator communicator; @@ -51,10 +55,9 @@ public ObjectProxy getObjectProxy(Class api, String objName, String se servantProxyConfig.setCommunicatorId(communicator.getId()); servantProxyConfig.setModuleName(communicator.getCommunicatorConfig().getModuleName(), communicator.getCommunicatorConfig().isEnableSet(), communicator.getCommunicatorConfig().getSetDivision()); servantProxyConfig.setLocator(communicator.getCommunicatorConfig().getLocator()); - if (setDivision != null) { - servantProxyConfig.setEnableSet(true); - servantProxyConfig.setSetDivision(setDivision); - } + addSetDivisionInfo(servantProxyConfig, setDivision); + servantProxyConfig.setRefreshInterval(communicator.getCommunicatorConfig().getRefreshEndpointInterval()); + servantProxyConfig.setReportInterval(communicator.getCommunicatorConfig().getReportInterval()); } updateServantEndpoints(servantProxyConfig); @@ -75,12 +78,12 @@ private ProtocolInvoker createProtocolInvoker(Class api, Codec codec = createCodec(api, servantProxyConfig); if (api.isAnnotationPresent(Servant.class)) { if (codec == null) { - codec = new TarsCodec(servantProxyConfig.getCharsetName()); + codec = new TarsClientCodec(servantProxyConfig.getCharsetName()); } servantProxyConfig.setProtocol(codec.getProtocol()); - protocolInvoker = new TarsProtocolInvoker(api, servantProxyConfig, new ServantProtocolFactory(codec), communicator.getThreadPoolExecutor()); + protocolInvoker = new TarsProtocolInvoker(api, servantProxyConfig); } else { - throw new ClientException(servantProxyConfig.getSimpleObjectName(), "unkonw protocol servant invoker", null); + throw new ClientException(servantProxyConfig.getSimpleObjectName(), "unknown protocol servant invoker", null); } return protocolInvoker; } @@ -110,27 +113,36 @@ private Codec createCodec(Class api, ServantProxyConfig servantProxyConfi private ServantProxyConfig createServantProxyConfig(String objName, String setDivision) throws CommunicatorConfigException { CommunicatorConfig communicatorConfig = communicator.getCommunicatorConfig(); ServantProxyConfig cfg = new ServantProxyConfig(communicator.getId(), communicatorConfig.getLocator(), objName); - cfg.setModuleName(communicatorConfig.getModuleName(), communicatorConfig.isEnableSet(), communicatorConfig.getSetDivision()); - if (setDivision != null) { - cfg.setEnableSet(true); - cfg.setSetDivision(setDivision); - } cfg.setAsyncTimeout(communicatorConfig.getAsyncInvokeTimeout()); cfg.setSyncTimeout(communicatorConfig.getSyncInvokeTimeout()); - + addSetDivisionInfo(cfg, setDivision); + cfg.setModuleName(communicatorConfig.getModuleName(), communicatorConfig.isEnableSet(), communicatorConfig.getSetDivision()); cfg.setStat(communicatorConfig.getStat()); cfg.setCharsetName(communicatorConfig.getCharsetName()); cfg.setConnections(communicatorConfig.getConnections()); + cfg.setRefreshInterval(communicatorConfig.getRefreshEndpointInterval()); + cfg.setReportInterval(communicator.getCommunicatorConfig().getReportInterval()); return cfg; } + public void addSetDivisionInfo(ServantProxyConfig cfg, String setDivision) { + CommunicatorConfig communicatorConfig = communicator.getCommunicatorConfig(); + if (StringUtils.isNotEmpty(communicatorConfig.getSetDivision()) && communicatorConfig.isEnableSet()) { + cfg.setSetDivision(communicatorConfig.getSetDivision()); + } + //Custom priority + if (StringUtils.isNotEmpty(setDivision)) { + cfg.setSetDivision(setDivision); + } + } + private void updateServantEndpoints(ServantProxyConfig cfg) { CommunicatorConfig communicatorConfig = communicator.getCommunicatorConfig(); String endpoints = null; if (!ParseTools.hasServerNode(cfg.getObjectName()) && !cfg.isDirectConnection() && !communicatorConfig.getLocator().startsWith(cfg.getSimpleObjectName())) { try { - /** 从主控拉取server node */ + /** query server nodes from registerServer */ if (RegisterManager.getInstance().getHandler() != null) { endpoints = ParseTools.parse(RegisterManager.getInstance().getHandler().query(cfg.getSimpleObjectName()), cfg.getSimpleObjectName()); @@ -142,9 +154,9 @@ private void updateServantEndpoints(ServantProxyConfig cfg) { } ServantCacheManager.getInstance().save(communicator.getId(), cfg.getSimpleObjectName(), endpoints, communicatorConfig.getDataPath()); } catch (CommunicatorConfigException e) { - /** 如果失败,从本地绶存文件中拉取 */ + /** If it fails, pull it from the local cache file */ endpoints = ServantCacheManager.getInstance().get(communicator.getId(), cfg.getSimpleObjectName(), communicatorConfig.getDataPath()); - ClientLogger.getLogger().error(cfg.getSimpleObjectName() + " error occurred on get by registry, use by local cache=" + endpoints + "|" + e.getLocalizedMessage(), e); + logger.log(Level.SEVERE, cfg.getSimpleObjectName() + " error occurred on get by registry, use by local cache=" + endpoints + "|" + e.getLocalizedMessage(), e); } if (StringUtils.isEmpty(endpoints)) { diff --git a/core/src/main/java/com/qq/tars/client/ServantProxyFactory.java b/core/src/main/java/com/qq/tars/client/ServantProxyFactory.java index 8dc22e74..830038f3 100644 --- a/core/src/main/java/com/qq/tars/client/ServantProxyFactory.java +++ b/core/src/main/java/com/qq/tars/client/ServantProxyFactory.java @@ -42,10 +42,13 @@ public Object getServantProxy(Class clazz, String objName, String setDivi if (proxy == null) { lock.lock(); try { + /** + * forbid to computeIfAbsent because of deadlock bug in jdk8*/ proxy = cache.get(key); if (proxy == null) { - ObjectProxy objectProxy = communicator.getObjectProxyFactory().getObjectProxy(clazz, objName, setDivision, servantProxyConfig, loadBalance, protocolInvoker); - cache.putIfAbsent(key, createProxy(clazz, objectProxy)); + ObjectProxy objectProxy = communicator.getObjectProxyFactory().getObjectProxy( + clazz, objName, setDivision, servantProxyConfig, loadBalance, protocolInvoker); + cache.put(key, createProxy(clazz, objectProxy)); proxy = cache.get(key); } } finally { diff --git a/core/src/main/java/com/qq/tars/client/cluster/DefaultLoadBalance.java b/core/src/main/java/com/qq/tars/client/cluster/DefaultLoadBalance.java index dbcc1ff3..04a7691e 100644 --- a/core/src/main/java/com/qq/tars/client/cluster/DefaultLoadBalance.java +++ b/core/src/main/java/com/qq/tars/client/cluster/DefaultLoadBalance.java @@ -16,25 +16,28 @@ package com.qq.tars.client.cluster; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - import com.qq.tars.client.ServantProxyConfig; -import com.qq.tars.client.util.ClientLogger; import com.qq.tars.common.util.Constants; import com.qq.tars.common.util.StringUtils; import com.qq.tars.rpc.common.InvokeContext; import com.qq.tars.rpc.common.Invoker; -import com.qq.tars.rpc.common.LoadBalance; import com.qq.tars.rpc.common.exc.NoInvokerException; +import com.qq.tars.support.log.LoggerFactory; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; @Deprecated public class DefaultLoadBalance { + private static final Logger logger = LoggerFactory.getClientLogger(); + private final AtomicInteger sequence = new AtomicInteger(); private volatile ServantProxyConfig config; @@ -45,8 +48,9 @@ public DefaultLoadBalance(ServantProxyConfig config) { } public Invoker select(Collection> invokers, InvokeContext context) throws NoInvokerException { - if (ClientLogger.getLogger().isDebugEnabled()) { - ClientLogger.getLogger().debug(config.getSimpleObjectName() + " try to select active invoker, size=" + (invokers == null || invokers.isEmpty() ? 0 : invokers.size())); + if (logger.isLoggable(Level.FINE)) { + logger.log(Level.FINE, "{0} try to select active invoker, size= {1} ", new Object[]{config.getSimpleObjectName(), + (invokers == null || invokers.isEmpty() ? 0 : invokers.size())}); } if (invokers == null || invokers.isEmpty()) { throw new NoInvokerException("no such active connection invoker"); @@ -54,8 +58,9 @@ public Invoker select(Collection> invokers, InvokeContext cont List> list = new ArrayList>(); for (Invoker invoker : invokers) { if (!invoker.isAvailable()) { - ServantInvokerAliveStat stat = ServantnvokerAliveChecker.get(invoker.getUrl()); - if (stat.isAlive() || (stat.getLastRetryTime() + (config.getTryTimeInterval() * 1000)) < System.currentTimeMillis()) { + ServantInvokerAliveStat stat = ServantInvokerAliveChecker.get(invoker.getUrl()); + if (stat.isAlive() || (stat.getLastRetryTime() + (config.getTryTimeInterval() * 1000)) < System + .currentTimeMillis()) { list.add(invoker); } } else { @@ -63,19 +68,20 @@ public Invoker select(Collection> invokers, InvokeContext cont } } if (list.isEmpty()) { - throw new NoInvokerException(config.getSimpleObjectName() + " try to select active invoker, size=" + invokers.size() + ", no such active connection invoker"); + throw new NoInvokerException(config.getSimpleObjectName() + " try to select active invoker, size=" + + invokers.size() + ", no such active connection invoker"); } Invoker invoker = null; - long hash = Math.abs(StringUtils.convertLong(context.getAttachment(Constants.TARS_HASH), 0)); + long hash = Math.abs(StringUtils.convertLong(context.getAttachment(Constants.TARS_HASH).toString(), 0)); if (hash > 0) { - Collections.sort(list, comparator); + list.sort(comparator); invoker = list.get((int) (hash % list.size())); } else { invoker = list.get((sequence.getAndIncrement() & Integer.MAX_VALUE) % list.size()); } if (!invoker.isAvailable()) { - ClientLogger.getLogger().info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); - ServantnvokerAliveChecker.get(invoker.getUrl()).setLastRetryTime(System.currentTimeMillis()); + logger.info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); + ServantInvokerAliveChecker.get(invoker.getUrl()).setLastRetryTime(System.currentTimeMillis()); } return invoker; } diff --git a/core/src/main/java/com/qq/tars/client/cluster/ServantnvokerAliveChecker.java b/core/src/main/java/com/qq/tars/client/cluster/ServantInvokerAliveChecker.java similarity index 93% rename from core/src/main/java/com/qq/tars/client/cluster/ServantnvokerAliveChecker.java rename to core/src/main/java/com/qq/tars/client/cluster/ServantInvokerAliveChecker.java index 0d545233..e7485d6c 100644 --- a/core/src/main/java/com/qq/tars/client/cluster/ServantnvokerAliveChecker.java +++ b/core/src/main/java/com/qq/tars/client/cluster/ServantInvokerAliveChecker.java @@ -21,7 +21,7 @@ import com.qq.tars.client.ServantProxyConfig; import com.qq.tars.rpc.common.Url; -public class ServantnvokerAliveChecker { +public class ServantInvokerAliveChecker { private static final ConcurrentHashMap cache = new ConcurrentHashMap(); @@ -30,9 +30,8 @@ public static ServantInvokerAliveStat get(Url url) { ServantInvokerAliveStat stat = cache.get(identity); if (stat == null) { cache.putIfAbsent(identity, new ServantInvokerAliveStat(identity)); - stat = cache.get(identity); } - return stat; + return cache.get(identity); } public static boolean isAlive(Url url, ServantProxyConfig config, int ret) { diff --git a/core/src/main/java/com/qq/tars/client/cluster/ServantInvokerAliveStat.java b/core/src/main/java/com/qq/tars/client/cluster/ServantInvokerAliveStat.java index c9aee4ec..4da5c2c7 100644 --- a/core/src/main/java/com/qq/tars/client/cluster/ServantInvokerAliveStat.java +++ b/core/src/main/java/com/qq/tars/client/cluster/ServantInvokerAliveStat.java @@ -16,24 +16,28 @@ package com.qq.tars.client.cluster; +import com.qq.tars.client.ServantProxyConfig; +import com.qq.tars.common.util.Constants; +import com.qq.tars.support.log.LoggerFactory; + +import java.util.logging.Level; +import java.util.logging.Logger; + import java.math.BigDecimal; import java.util.Date; import java.util.concurrent.atomic.AtomicBoolean; -import com.qq.tars.client.ServantProxyConfig; -import com.qq.tars.client.util.ClientLogger; -import com.qq.tars.common.util.Constants; - public class ServantInvokerAliveStat { + private static final Logger logger = LoggerFactory.getClientLogger(); private final String identity; - private AtomicBoolean lastCallSucess = new AtomicBoolean(true); + private final AtomicBoolean lastCallSuccess = new AtomicBoolean(true); private long timeout_startTime = 0; - private long frequenceFailInvoke = 0; - private long frequenceFailInvoke_startTime = 0; + private long frequencyFailInvoke = 0; + private long frequencyFailInvoke_startTime = 0; private long timeoutCount = 0; private long failedCount = 0; - private long succCount = 0; + private long successCount = 0; private boolean netConnectTimeout = false; private boolean alive = true; private long lastRetryTime = 0; @@ -48,28 +52,28 @@ public boolean isAlive() { public synchronized void onCallFinished(int ret, ServantProxyConfig config) { if (ret == Constants.INVOKE_STATUS_SUCC) { - frequenceFailInvoke = 0; - frequenceFailInvoke_startTime = 0; - lastCallSucess.set(true); + frequencyFailInvoke = 0; + frequencyFailInvoke_startTime = 0; + lastCallSuccess.set(true); netConnectTimeout = false; - succCount++; + successCount++; } else if (ret == Constants.INVOKE_STATUS_TIMEOUT) { - if (!lastCallSucess.get()) { - frequenceFailInvoke++; + if (!lastCallSuccess.get()) { + frequencyFailInvoke++; } else { - lastCallSucess.set(false); - frequenceFailInvoke = 1; - frequenceFailInvoke_startTime = System.currentTimeMillis(); + lastCallSuccess.set(false); + frequencyFailInvoke = 1; + frequencyFailInvoke_startTime = System.currentTimeMillis(); } netConnectTimeout = false; timeoutCount++; } else if (ret == Constants.INVOKE_STATUS_EXEC) { - if (!lastCallSucess.get()) { - frequenceFailInvoke++; + if (!lastCallSuccess.get()) { + frequencyFailInvoke++; } else { - lastCallSucess.set(false); - frequenceFailInvoke = 1; - frequenceFailInvoke_startTime = System.currentTimeMillis(); + lastCallSuccess.set(false); + frequencyFailInvoke = 1; + frequencyFailInvoke_startTime = System.currentTimeMillis(); } netConnectTimeout = false; failedCount++; @@ -80,31 +84,34 @@ public synchronized void onCallFinished(int ret, ServantProxyConfig config) { if ((timeout_startTime + config.getCheckInterval()) < System.currentTimeMillis()) { timeoutCount = 0; failedCount = 0; - succCount = 0; + successCount = 0; timeout_startTime = System.currentTimeMillis(); } if (alive) { - long totalCount = timeoutCount + failedCount + succCount; + long totalCount = timeoutCount + failedCount + successCount; if (timeoutCount >= config.getMinTimeoutInvoke()) { double radio = div(timeoutCount, totalCount, 2); if (radio > config.getFrequenceFailRadio()) { alive = false; - ClientLogger.getLogger().info(identity + "|alive=false|radio=" + radio + "|" + toString()); + lastRetryTime = System.currentTimeMillis(); + logger.info(identity + "|alive=false|radio=" + radio + "|" + toString()); } } if (alive) { - if (frequenceFailInvoke >= config.getFrequenceFailInvoke() && (frequenceFailInvoke_startTime + 5000) > System.currentTimeMillis()) { + if (frequencyFailInvoke >= config.getFrequenceFailInvoke() && (frequencyFailInvoke_startTime + 5000) > System.currentTimeMillis()) { alive = false; - ClientLogger.getLogger().info(identity + "|alive=false|frequenceFailInvoke=" + frequenceFailInvoke + "|" + toString()); + lastRetryTime = System.currentTimeMillis(); + logger.log(Level.INFO, "{0}|alive=false|frequenceFailInvoke={1}|{2}", new Object[]{identity, frequencyFailInvoke, toString()}); } } if (alive) { if (netConnectTimeout) { alive = false; - ClientLogger.getLogger().info(identity + "|alive=false|netConnectTimeout" + "|" + toString()); + lastRetryTime = System.currentTimeMillis(); + logger.log(Level.INFO, "{0}|alive=false|netConnectTimeout|{1}", new Object[]{identity, toString()}); } } } else { @@ -124,16 +131,16 @@ public void setLastRetryTime(long lastRetryTime) { public String toString() { StringBuilder build = new StringBuilder(); - build.append("lastCallSucc:").append(lastCallSucess.get()).append("|"); + build.append("lastCallSucc:").append(lastCallSuccess.get()).append("|"); build.append("timeoutCount:").append(timeoutCount).append("|"); build.append("failedCount:").append(failedCount).append("|"); - build.append("succCount:").append(succCount).append("|"); + build.append("succCount:").append(successCount).append("|"); build.append("available:").append(alive).append("|"); build.append("netConnectTimeout:").append(netConnectTimeout).append("|"); build.append("timeout_startTime:").append(new Date(timeout_startTime)).append("|"); - build.append("frequenceFailInvoke:").append(frequenceFailInvoke).append("|"); - build.append("frequenceFailInvoke_startTime:").append(new Date(frequenceFailInvoke_startTime)).append("|"); + build.append("frequenceFailInvoke:").append(frequencyFailInvoke).append("|"); + build.append("frequenceFailInvoke_startTime:").append(new Date(frequencyFailInvoke_startTime)).append("|"); build.append("lastRetryTime:").append(new Date(lastRetryTime)); return build.toString(); } diff --git a/core/src/main/java/com/qq/tars/client/rpc/ServantClient.java b/core/src/main/java/com/qq/tars/client/rpc/ServantClient.java deleted file mode 100644 index 10b5707a..00000000 --- a/core/src/main/java/com/qq/tars/client/rpc/ServantClient.java +++ /dev/null @@ -1,272 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.client.rpc; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.channels.DatagramChannel; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import com.qq.tars.client.util.ClientLogger; -import com.qq.tars.net.client.Callback; -import com.qq.tars.net.client.FutureImpl; -import com.qq.tars.net.client.ticket.Ticket; -import com.qq.tars.net.client.ticket.TicketManager; -import com.qq.tars.net.core.Session; -import com.qq.tars.net.core.Request.InvokeStatus; -import com.qq.tars.net.core.Session.SessionStatus; -import com.qq.tars.net.core.nio.SelectorManager; -import com.qq.tars.net.core.nio.TCPSession; -import com.qq.tars.net.core.nio.UDPSession; -import com.qq.tars.rpc.exc.NotConnectedException; -import com.qq.tars.rpc.exc.TimeoutException; -import com.qq.tars.rpc.protocol.ServantRequest; -import com.qq.tars.rpc.protocol.ServantResponse; - -public class ServantClient { - - private Session session = null; - private String host = null; - private int port = -1; - private SelectorManager selectorManager = null; - private long asyncTimeout = 1000; - private long syncTimeout = 1000; - private long connectTimeout = 200; - private boolean udpMode = false; - private int tc = INVALID_TRAFFIC_CLASS_VALUE; - private int bufferSize = 1024 * 4; - private boolean tcpNoDelay = false; - private static final int INVALID_TRAFFIC_CLASS_VALUE = -1; - - public ServantClient(String ip, int port, SelectorManager selectorManager, boolean udpMode) { - this.host = ip; - this.port = port; - this.udpMode = udpMode; - this.selectorManager = selectorManager; - } - - protected synchronized void reConnect() throws IOException { - if (isNotConnected()) { - SocketAddress server = new InetSocketAddress(this.host, this.port); - SelectableChannel channel = null; - Session temp = null; - int event; - - if (this.udpMode) { - channel = DatagramChannel.open(); - channel.configureBlocking(false); - - temp = new UDPSession(this.selectorManager); - ((UDPSession) temp).setBufferSize(bufferSize); - ((UDPSession) temp).setTarget(server); - event = SelectionKey.OP_READ; - temp.setStatus(SessionStatus.CLIENT_CONNECTED); - } else { - channel = SocketChannel.open(); - channel.configureBlocking(false); - try { - if (this.tc != INVALID_TRAFFIC_CLASS_VALUE) { - ((SocketChannel) channel).socket().setTrafficClass(this.tc); - } - } catch (Exception ex) { - ClientLogger.getLogger().error(ex.getLocalizedMessage()); - } - ((SocketChannel) channel).connect(server); - - temp = new TCPSession(this.selectorManager); - ((TCPSession) temp).setTcpNoDelay(this.tcpNoDelay); - event = SelectionKey.OP_CONNECT; - } - - temp.setChannel(channel); - temp.setKeepAlive(selectorManager.isKeepAlive()); - - this.selectorManager.nextReactor().registerChannel(channel, event, temp); - - if (!this.udpMode) { - if (!temp.waitToConnect(this.connectTimeout)) { - temp.asyncClose(); - throw new TimeoutException("connect " + this.connectTimeout + "ms timed out to " + this.getAddress()); - } - - if (temp.getStatus() == SessionStatus.NOT_CONNECTED) { - temp.asyncClose(); - throw new NotConnectedException("connect failed to " + this.getAddress()); - } else if (temp.getStatus() == SessionStatus.CLOSED) { - throw new NotConnectedException("connect failed to " + this.getAddress()); - } - } - this.session = temp; - } - } - - public void ensureConnected() throws IOException { - if (isNotConnected()) { - reConnect(); - } - } - - public T invokeWithSync(ServantRequest request) throws IOException { - Ticket ticket = null; - T response = null; - try { - ensureConnected(); - request.setInvokeStatus(InvokeStatus.SYNC_CALL); - ticket = TicketManager.createTicket(request, session, this.syncTimeout); - - Session current = session; - current.write(request); - if (!ticket.await(this.syncTimeout, TimeUnit.MILLISECONDS)) { - if (current != null && current.getStatus() != SessionStatus.CLIENT_CONNECTED) { - throw new IOException("Connection reset by peer|" + this.getAddress()); - } else { - throw new TimeoutException("the operation has timeout, " + this.syncTimeout + "ms|" + this.getAddress()); - } - } - response = ticket.response(); - if (response == null) { - throw new IOException("the operation is failed."); - } - return response; - } catch (InterruptedException e) { - ClientLogger.getLogger().error(e.getLocalizedMessage()); - } finally { - if (ticket != null) { - TicketManager.removeTicket(ticket.getTicketNumber()); - } - } - return response; - } - - public void invokeWithAsync(ServantRequest request, Callback callback) throws IOException { - Ticket ticket = null; - - try { - ensureConnected(); - request.setInvokeStatus(InvokeStatus.ASYNC_CALL); - ticket = TicketManager.createTicket(request, session, this.asyncTimeout, callback); - - Session current = session; - current.write(request); - } catch (Exception ex) { - if (ticket != null) { - TicketManager.removeTicket(ticket.getTicketNumber()); - } - throw new IOException("error occurred on invoker with async", ex); - } - } - - public Future invokeWithFuture(ServantRequest request) throws IOException { - Ticket ticket = null; - try { - ensureConnected(); - request.setInvokeStatus(InvokeStatus.FUTURE_CALL); - ticket = TicketManager.createTicket(request, session, this.syncTimeout); - - Session current = session; - current.write(request); - return new FutureImpl(ticket); - } catch (Exception ex) { - if (ticket != null) { - TicketManager.removeTicket(ticket.getTicketNumber()); - } - throw new IOException("error occurred on invoker with future", ex); - } - } - - private synchronized void shutdown() throws IOException { - if (this.session != null) { - this.session.asyncClose(); - } - } - - public void setBufferSize(int bufferSize) { - this.bufferSize = bufferSize; - } - - public Session getIoSession() { - return this.session; - } - - public int getTrafficClass() { - return tc; - } - - public void setTrafficClass(int tc) { - if (this.session != null && this.session instanceof TCPSession) { - try { - ((SocketChannel) ((TCPSession) this.session).getChannel()).socket().setTrafficClass(tc); - } catch (Exception ex) { - ClientLogger.getLogger().error(ex.getLocalizedMessage()); - } - } - this.tc = tc; - } - - public void setTcpNoDelay(boolean on) { - this.tcpNoDelay = on; - - if (this.session != null && this.session instanceof TCPSession) { - try { - ((SocketChannel) ((TCPSession) this.session).getChannel()).socket().setTcpNoDelay(on); - } catch (Exception ex) { - ClientLogger.getLogger().error(ex.getLocalizedMessage()); - } - } - } - - public long getConnectTimeout() { - return connectTimeout; - } - - public void setConnectTimeout(long connectTimeout) { - this.connectTimeout = connectTimeout; - } - - public long getSyncTimeout() { - return syncTimeout; - } - - public void setSyncTimeout(long syncTimeout) { - this.syncTimeout = syncTimeout; - } - - public void setAsyncTimeout(long asyncTimeout) { - this.asyncTimeout = asyncTimeout; - } - - public void close() throws IOException { - this.shutdown(); - } - - private boolean isNotConnected() { - return session == null || session.getStatus() == SessionStatus.CLOSED || session.getStatus() == SessionStatus.NOT_CONNECTED; - } - - public String getAddress() { - return host + ":" + port; - } - - public String toString() { - return "ServantClient [client=" + getAddress() + "]"; - } -} diff --git a/core/src/main/java/com/qq/tars/client/rpc/ServantInvokeContext.java b/core/src/main/java/com/qq/tars/client/rpc/ServantInvokeContext.java index c6c4f135..8d21163f 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/ServantInvokeContext.java +++ b/core/src/main/java/com/qq/tars/client/rpc/ServantInvokeContext.java @@ -16,23 +16,24 @@ package com.qq.tars.client.rpc; +import com.qq.tars.protocol.util.TarsHelper; +import com.qq.tars.rpc.common.InvokeContext; +import com.qq.tars.rpc.common.Invoker; + import java.io.Serializable; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; -import com.qq.tars.rpc.common.InvokeContext; -import com.qq.tars.rpc.common.Invoker; - @SuppressWarnings("serial") public class ServantInvokeContext implements InvokeContext, Serializable { - private Invoker invoker; - private String methodName; private Object[] arguments; private Class[] parameterTypes; - + private final boolean isAsync; + private final boolean isPromiseFuture; + private final boolean isNormal; private Map attachments; public ServantInvokeContext(Method method, Object[] arguments, Map attachments) { @@ -49,6 +50,17 @@ public ServantInvokeContext(Method method, Object[] arguments, Map getInvoker() { @@ -88,7 +100,7 @@ public void setArguments(Object[] arguments) { } public void setAttachments(Map attachments) { - this.attachments = attachments == null ? new HashMap() : attachments; + this.attachments = attachments == null ? new HashMap<>() : attachments; } public void setAttachment(String key, String value) { @@ -114,15 +126,28 @@ public void addAttachmentsIfAbsent(Map attachments) { } } - public String getAttachment(String key) { + public Object getAttachment(String key) { return attachments.get(key); } - public String getAttachment(String key, String defaultValue) { - String value = attachments.get(key); + public Object getAttachment(String key, String defaultValue) { + Object value = attachments.get(key); if (value == null) { return defaultValue; } return value; } + + @Override + public String toString() { + return "ServantInvokeContext{" + + "methodName='" + methodName + '\'' + + ", isAsync=" + isAsync + + ", isPromiseFuture=" + isPromiseFuture + + '}'; + } + + public boolean isNormal() { + return isNormal; + } } diff --git a/core/src/main/java/com/qq/tars/client/rpc/ServantInvoker.java b/core/src/main/java/com/qq/tars/client/rpc/ServantInvoker.java index 88e9ce09..f1947f10 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/ServantInvoker.java +++ b/core/src/main/java/com/qq/tars/client/rpc/ServantInvoker.java @@ -16,24 +16,29 @@ package com.qq.tars.client.rpc; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.ReentrantLock; - import com.qq.tars.client.ServantProxyConfig; -import com.qq.tars.client.util.ClientLogger; import com.qq.tars.rpc.common.InvokeContext; import com.qq.tars.rpc.common.Url; import com.qq.tars.rpc.common.support.AbstractInvoker; +import com.qq.tars.support.log.LoggerFactory; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.ReentrantLock; public abstract class ServantInvoker extends AbstractInvoker { + private static final Logger logger = LoggerFactory.getClientLogger(); + protected final String objName; protected final ServantProxyConfig config; - protected final ServantClient[] clients; + protected final RPCClient[] clients; protected final AtomicInteger index = new AtomicInteger(); protected final ReentrantLock destroyLock = new ReentrantLock(); - public ServantInvoker(ServantProxyConfig config, Class api, Url url, ServantClient[] clients) { + public ServantInvoker(ServantProxyConfig config, Class api, Url url, RPCClient[] clients) { super(api, url); this.config = config; this.objName = config.getSimpleObjectName(); @@ -56,13 +61,13 @@ public void destroy() { return; } super.destroy(); - for (ServantClient client : clients) { + for (RPCClient client : clients) { try { - ClientLogger.getLogger().info("try to close client " + client); + logger.info("try to close client " + client); client.close(); - ClientLogger.getLogger().info("closed client " + client); + logger.info("closed client " + client); } catch (Throwable t) { - ClientLogger.getLogger().error("error in close " + client, t); + logger.log(Level.SEVERE, "error in close " + client, t); } } } finally { diff --git a/core/src/main/java/com/qq/tars/client/rpc/ServantProtocolInvoker.java b/core/src/main/java/com/qq/tars/client/rpc/ServantProtocolInvoker.java index 48a2dd64..fbe9e1e4 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/ServantProtocolInvoker.java +++ b/core/src/main/java/com/qq/tars/client/rpc/ServantProtocolInvoker.java @@ -16,42 +16,35 @@ package com.qq.tars.client.rpc; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ThreadPoolExecutor; - import com.qq.tars.client.ServantProxyConfig; -import com.qq.tars.client.support.ClientPoolManager; -import com.qq.tars.client.util.ClientLogger; import com.qq.tars.client.util.ParseTools; +import com.qq.tars.common.support.ScheduledExecutorManager; import com.qq.tars.common.util.Constants; -import com.qq.tars.net.core.nio.SelectorManager; -import com.qq.tars.net.protocol.ProtocolFactory; import com.qq.tars.rpc.common.Invoker; import com.qq.tars.rpc.common.ProtocolInvoker; import com.qq.tars.rpc.common.Url; import com.qq.tars.rpc.common.util.concurrent.ConcurrentHashSet; import com.qq.tars.rpc.exc.ClientException; +import com.qq.tars.support.log.LoggerFactory; -public abstract class ServantProtocolInvoker implements ProtocolInvoker { +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +public abstract class ServantProtocolInvoker implements ProtocolInvoker { + private static final Logger logger = LoggerFactory.getClientLogger(); protected final Class api; protected final ServantProxyConfig servantProxyConfig; - protected final ThreadPoolExecutor threadPoolExecutor; - protected final ProtocolFactory protocolFactory; - protected volatile SelectorManager selectorManager = null; - protected final ConcurrentHashSet> allInvoker = new ConcurrentHashSet>(); + protected volatile ConcurrentHashSet> allInvoker = new ConcurrentHashSet<>(); + - public ServantProtocolInvoker(Class api, ServantProxyConfig config, ProtocolFactory protocolFactory, - ThreadPoolExecutor threadPoolExecutor) { + public ServantProtocolInvoker(Class api, ServantProxyConfig config) { this.api = api; this.servantProxyConfig = config; - this.threadPoolExecutor = threadPoolExecutor; - this.protocolFactory = protocolFactory; - this.initInvoker(); + this.allInvoker = this.initInvoker(); } public abstract Invoker create(Class api, Url url) throws Exception; @@ -62,83 +55,95 @@ public Collection> getInvokers() { public void destroy() { destroy(allInvoker); - this.selectorManager.stop(); } public void refresh() { - ClientLogger.getLogger().info("try to refresh " + servantProxyConfig.getSimpleObjectName()); - List> invokers = new ArrayList>(); + logger.info("try to refresh " + servantProxyConfig.getSimpleObjectName()); + Set currentUrls = new HashSet<>(ParseTools.parse(servantProxyConfig)); + Map> prevUrlInvokerMap = new HashMap<>(allInvoker.size()); + List> brokenInvokers = new ArrayList<>(); for (Invoker invoker : allInvoker) { - invokers.add(invoker); + Url url = invoker.getUrl(); + prevUrlInvokerMap.put(url, invoker); + if (!currentUrls.contains(url)) { + brokenInvokers.add(invoker); + } + } + List newUrls = new ArrayList<>(currentUrls.size()); + for (Url url : currentUrls) { + if (!prevUrlInvokerMap.containsKey(url)) { + newUrls.add(url); + } } - this.initInvoker(); - destroy(invokers); + + addInvokers(newUrls); + // only destroy broken invokers + ScheduledExecutorManager.getInstance().schedule(() -> destroy(brokenInvokers), Math.max(servantProxyConfig.getAsyncTimeout(), servantProxyConfig.getSyncTimeout()), TimeUnit.MILLISECONDS); } - protected ServantClient[] getClients(Url url) throws IOException { - int connections = url.getParameter(Constants.TARS_CLIENT_CONNECTIONS, Constants.default_connections); - ServantClient[] clients = new ServantClient[connections]; + protected RPCClient[] getClients(Url url) { + int connections = url.getParameter(Constants.TARS_CLIENT_CONNECTIONS, Constants.DEFAULT_CONNECTION); + RPCClient[] clients = new RPCClient[connections]; for (int i = 0; i < clients.length; i++) { clients[i] = initClient(url); } return clients; } - protected ServantClient initClient(Url url) { - ServantClient client = null; + protected RPCClient initClient(Url url) { try { - boolean tcpNoDelay = url.getParameter(Constants.TARS_CLIENT_TCPNODELAY, false); - long connectTimeout = url.getParameter(Constants.TARS_CLIENT_CONNECTTIMEOUT, Constants.default_connect_timeout); - long syncTimeout = url.getParameter(Constants.TARS_CLIENT_SYNCTIMEOUT, Constants.default_sync_timeout); - long asyncTimeout = url.getParameter(Constants.TARS_CLIENT_ASYNCTIMEOUT, Constants.default_async_timeout); - boolean udpMode = url.getParameter(Constants.TARS_CLIENT_UDPMODE, false); - - if (this.selectorManager == null) { - this.selectorManager = ClientPoolManager.getSelectorManager(this.protocolFactory, this.threadPoolExecutor, true, udpMode, this.servantProxyConfig); - } - - client = new ServantClient(url.getHost(), url.getPort(), this.selectorManager, udpMode); - client.setConnectTimeout(connectTimeout); - client.setSyncTimeout(syncTimeout); - client.setAsyncTimeout(asyncTimeout); - client.setTcpNoDelay(tcpNoDelay); + return TransporterAbstractFactory.getInstance().getTransporterFactory().connect(url, servantProxyConfig); } catch (Throwable e) { throw new ClientException(servantProxyConfig.getSimpleObjectName(), "Fail to create client|" + url.toIdentityString() + "|" + e.getLocalizedMessage(), e); } - return client; } - protected void initInvoker() { + protected ConcurrentHashSet> initInvoker() { try { - ClientLogger.getLogger().info("try to init invoker|conf=" + servantProxyConfig.toString()); - List list = ParseTools.parse(servantProxyConfig); - for (Url url : list) { - try { - boolean active = url.getParameter(Constants.TARS_CLIENT_ACTIVE, false); - if (active) { - ClientLogger.getLogger().info("try to init invoker|active=" + active + "|" + url.toIdentityString()); - allInvoker.add(create(api, url)); - } else { - ClientLogger.getLogger().info("inactive invoker can`t to init|active=" + active + "|" + url.toIdentityString()); - } - } catch (Throwable e) { - ClientLogger.getLogger().error("error occurred on init invoker|" + url.toIdentityString(), e); + logger.info("try to init invoker|conf={}" + servantProxyConfig.toString()); + final List list = ParseTools.parse(servantProxyConfig); + return createInvokers(list); + } catch (Throwable t) { + logger.log(Level.SEVERE, "error occurred on init invoker|" + servantProxyConfig.getObjectName(), t); + } + return new ConcurrentHashSet<>(); + } + + private void addInvokers(Collection urls) { + logger.log(Level.INFO, "try to add invokers|url={0}", urls.stream().map(Url::toIdentityString).collect(Collectors.toList())); + ConcurrentHashSet> invokers = createInvokers(urls); + if (!invokers.isEmpty()) { + allInvoker.addAll(invokers); + } + } + + private ConcurrentHashSet> createInvokers(Collection list) { + final ConcurrentHashSet> invokers = new ConcurrentHashSet<>(); + for (Url url : list) { + try { + boolean active = url.getParameter(Constants.TARS_CLIENT_ACTIVE, false); + if (active) { + logger.log(Level.INFO, "try to init invoker|active={0} |{1}", new Object[]{active, url.toIdentityString()}); + invokers.add(create(api, url)); + } else { + logger.log(Level.INFO, "inactive invoker can't to init|active={0}|{1}", new Object[]{active, url.toIdentityString()}); } + } catch (Throwable e) { + logger.log(Level.SEVERE, "error occurred on init invoker|" + url.toIdentityString(), e); } - } catch (Throwable t) { - ClientLogger.getLogger().error("error occurred on init invoker|" + servantProxyConfig.getObjectName(), t); } + return invokers; } private void destroy(Collection> invokers) { for (Invoker invoker : invokers) { if (invoker != null) { - ClientLogger.getLogger().info("destroy reference|" + invoker); + logger.info("destroy reference|" + invoker); try { allInvoker.remove(invoker); invoker.destroy(); } catch (Throwable t) { - ClientLogger.getLogger().error("error occurred on destroy invoker|" + invoker, t); + logger.log(Level.SEVERE, "error occurred on destroy invoker|" + invoker, t); } } } diff --git a/core/src/main/java/com/qq/tars/client/rpc/TransporterAbstractFactory.java b/core/src/main/java/com/qq/tars/client/rpc/TransporterAbstractFactory.java new file mode 100644 index 00000000..201cefcb --- /dev/null +++ b/core/src/main/java/com/qq/tars/client/rpc/TransporterAbstractFactory.java @@ -0,0 +1,27 @@ +package com.qq.tars.client.rpc; + +/** + * Abstract factory for transporter. + * Used to load different transporter implementation(such as netty, reactor, + * restTemplate, etc) through + * SPI:{@code com.qq.tars.client.rpc.TransporterFactory} + * + * @author kongyuanyuan + */ +public class TransporterAbstractFactory { + + private static final TransporterAbstractFactory INSTANCE = new TransporterAbstractFactory(); + private final TransporterFactory defaultTransporterFactory; + + private TransporterAbstractFactory() { + defaultTransporterFactory = new com.qq.tars.rpc.netty.NettyTransporterFactory(); + } + + public static TransporterAbstractFactory getInstance() { + return INSTANCE; + } + + public TransporterFactory getTransporterFactory() { + return defaultTransporterFactory; + } +} diff --git a/net/src/main/java/com/qq/tars/net/util/Utils.java b/core/src/main/java/com/qq/tars/client/rpc/Utils.java similarity index 93% rename from net/src/main/java/com/qq/tars/net/util/Utils.java rename to core/src/main/java/com/qq/tars/client/rpc/Utils.java index 1180c2b1..1417dc99 100644 --- a/net/src/main/java/com/qq/tars/net/util/Utils.java +++ b/core/src/main/java/com/qq/tars/client/rpc/Utils.java @@ -14,7 +14,7 @@ * specific language governing permissions and limitations under the License. */ -package com.qq.tars.net.util; +package com.qq.tars.client.rpc; import java.io.File; import java.io.FileInputStream; @@ -30,11 +30,6 @@ public class Utils { - public static int getSelectorPoolSize() { - int processors = Runtime.getRuntime().availableProcessors(); - return processors > 8 ? 4 + (processors * 5 / 8) : processors + 1; - } - public static String getLocalIp() { try { Pattern pattern = Pattern.compile("(172|10)\\.[0-9]+\\.[0-9]+\\.[0-9]+"); @@ -60,7 +55,8 @@ public static String getLocalIp() { } public static void setQosFlag(Socket socket) { - if (NETWORK_QOS_FLAG == null || socket == null) return; + if (NETWORK_QOS_FLAG == null || socket == null) + return; try { if ("B1_REAL_TIME_QOS".equals(NETWORK_QOS_FLAG)) { diff --git a/core/src/main/java/com/qq/tars/client/rpc/loadbalance/ConsistentHashLoadBalance.java b/core/src/main/java/com/qq/tars/client/rpc/loadbalance/ConsistentHashLoadBalance.java index 4594240f..0e8f3c06 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/loadbalance/ConsistentHashLoadBalance.java +++ b/core/src/main/java/com/qq/tars/client/rpc/loadbalance/ConsistentHashLoadBalance.java @@ -17,20 +17,29 @@ package com.qq.tars.client.rpc.loadbalance; import com.qq.tars.client.ServantProxyConfig; +import com.qq.tars.client.cluster.ServantInvokerAliveChecker; import com.qq.tars.client.cluster.ServantInvokerAliveStat; -import com.qq.tars.client.cluster.ServantnvokerAliveChecker; import com.qq.tars.client.rpc.InvokerComparator; -import com.qq.tars.client.util.ClientLogger; +import com.qq.tars.common.util.CollectionUtils; import com.qq.tars.common.util.Constants; import com.qq.tars.common.util.StringUtils; import com.qq.tars.rpc.common.InvokeContext; import com.qq.tars.rpc.common.Invoker; import com.qq.tars.rpc.common.LoadBalance; import com.qq.tars.rpc.common.exc.NoInvokerException; +import com.qq.tars.support.log.LoggerFactory; -import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.SortedMap; +import java.util.TreeMap; public class ConsistentHashLoadBalance implements LoadBalance { + private static final Logger logger = LoggerFactory.getClientLogger(); private final ServantProxyConfig config; private final InvokerComparator comparator = new InvokerComparator(); @@ -44,12 +53,12 @@ public ConsistentHashLoadBalance(ServantProxyConfig config) { @Override public Invoker select(InvokeContext invocation) throws NoInvokerException { - long consistentHash = Math.abs(StringUtils.convertLong(invocation.getAttachment(Constants.TARS_CONSISTENT_HASH), 0)); - //hash空间是0 ~ 2^32-1 + long consistentHash = Math.abs(StringUtils.convertLong(invocation.getAttachment(Constants.TARS_CONSISTENT_HASH).toString(), 0)); + //hash range is 0 ~ 2^32-1 consistentHash = consistentHash & 0xFFFFFFFFL; TreeMap> conHashInvokers = conHashInvokersCache; - //使用一致性hash + //Consistent hash if (conHashInvokers != null && !conHashInvokers.isEmpty()) { if (!conHashInvokers.containsKey(consistentHash)) { SortedMap> tailMap = conHashInvokers.tailMap(consistentHash); @@ -63,20 +72,20 @@ public Invoker select(InvokeContext invocation) throws NoInvokerException { Invoker invoker = conHashInvokers.get(consistentHash); if (invoker.isAvailable()) return invoker; - ServantInvokerAliveStat stat = ServantnvokerAliveChecker.get(invoker.getUrl()); + ServantInvokerAliveStat stat = ServantInvokerAliveChecker.get(invoker.getUrl()); if (stat.isAlive() || (stat.getLastRetryTime() + (config.getTryTimeInterval() * 1000)) < System.currentTimeMillis()) { - //屏敝后尝试重新调用 - ClientLogger.getLogger().info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); + //Shield then call + logger.info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); stat.setLastRetryTime(System.currentTimeMillis()); return invoker; } } - if (ClientLogger.getLogger().isDebugEnabled()) { - ClientLogger.getLogger().debug(config.getSimpleObjectName() + " can't find active invoker using consistent hash loadbalance. try to use normal hash"); + if (logger.isLoggable(Level.FINE)) { + logger.fine(config.getSimpleObjectName() + " can't find active invoker using consistent hash loadbalance. try to use normal hash"); } - //使用普通hash + //use normal hash List> sortedInvokers = sortedInvokersCache; if (sortedInvokers == null || sortedInvokers.isEmpty()) { throw new NoInvokerException("no such active connection invoker"); @@ -85,10 +94,8 @@ public Invoker select(InvokeContext invocation) throws NoInvokerException { List> list = new ArrayList>(); for (Invoker invoker : sortedInvokers) { if (!invoker.isAvailable()) { - /** - * 屏敝后尝试重新调用 - */ - ServantInvokerAliveStat stat = ServantnvokerAliveChecker.get(invoker.getUrl()); + //Shield then call + ServantInvokerAliveStat stat = ServantInvokerAliveChecker.get(invoker.getUrl()); if (stat.isAlive() || (stat.getLastRetryTime() + (config.getTryTimeInterval() * 1000)) < System.currentTimeMillis()) { list.add(invoker); } @@ -96,7 +103,7 @@ public Invoker select(InvokeContext invocation) throws NoInvokerException { list.add(invoker); } } - // TODO 如果全死,是否需要随机取一个尝试? + //TODO When all is not available. Whether to randomly extract one if (list.isEmpty()) { throw new NoInvokerException(config.getSimpleObjectName() + " try to select active invoker, size=" + sortedInvokers.size() + ", no such active connection invoker"); } @@ -104,29 +111,29 @@ public Invoker select(InvokeContext invocation) throws NoInvokerException { Invoker invoker = list.get((int) (consistentHash % list.size())); if (!invoker.isAvailable()) { - //屏敝后尝试重新调用 - ClientLogger.getLogger().info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); - ServantnvokerAliveChecker.get(invoker.getUrl()).setLastRetryTime(System.currentTimeMillis()); + //When all is not available. Whether to randomly extract one + logger.info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); + ServantInvokerAliveChecker.get(invoker.getUrl()).setLastRetryTime(System.currentTimeMillis()); } return invoker; } @Override public void refresh(Collection> invokers) { - ClientLogger.getLogger().info(config.getSimpleObjectName() + " try to refresh ConsistentHashLoadBalance's invoker cache, size=" + (invokers == null || invokers.isEmpty() ? 0 : invokers.size())); - if (invokers == null || invokers.isEmpty()) { + logger.info(config.getSimpleObjectName() + " try to refresh ConsistentHashLoadBalance's invoker cache, size=" + (invokers == null || invokers.isEmpty() ? 0 : invokers.size())); + if (CollectionUtils.isEmpty(invokers)) { sortedInvokersCache = null; conHashInvokersCache = null; return; } - List> sortedInvokersTmp = new ArrayList>(invokers); - Collections.sort(sortedInvokersTmp, comparator); + List> sortedInvokersTmp = new ArrayList<>(invokers); + sortedInvokersTmp.sort(comparator); sortedInvokersCache = sortedInvokersTmp; conHashInvokersCache = LoadBalanceHelper.buildConsistentHashCircle(sortedInvokersTmp, config); - ClientLogger.getLogger().info(config.getSimpleObjectName() + " refresh ConsistentHashLoadBalance's invoker cache done, conHashInvokersCache size=" + (conHashInvokersCache == null || conHashInvokersCache.isEmpty() ? 0 : conHashInvokersCache.size()) + ", sortedInvokersCache size=" + (sortedInvokersCache == null || sortedInvokersCache.isEmpty() ? 0 : sortedInvokersCache.size())); + logger.info(config.getSimpleObjectName() + " refresh ConsistentHashLoadBalance's invoker cache done, conHashInvokersCache size=" + (conHashInvokersCache == null || conHashInvokersCache.isEmpty() ? 0 : conHashInvokersCache.size()) + ", sortedInvokersCache size=" + (sortedInvokersCache == null || sortedInvokersCache.isEmpty() ? 0 : sortedInvokersCache.size())); } } diff --git a/core/src/main/java/com/qq/tars/client/rpc/loadbalance/DefaultLoadBalance.java b/core/src/main/java/com/qq/tars/client/rpc/loadbalance/DefaultLoadBalance.java index 4b1ece45..2215a431 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/loadbalance/DefaultLoadBalance.java +++ b/core/src/main/java/com/qq/tars/client/rpc/loadbalance/DefaultLoadBalance.java @@ -46,8 +46,14 @@ public DefaultLoadBalance(ServantProxyConfig config) { @Override public Invoker select(InvokeContext invocation) throws NoInvokerException { - long hash = Math.abs(StringUtils.convertLong(invocation.getAttachment(Constants.TARS_HASH), 0)); - long consistentHash = Math.abs(StringUtils.convertLong(invocation.getAttachment(Constants.TARS_CONSISTENT_HASH), 0)); + long hash = 0; + if (invocation.getAttachment(Constants.TARS_HASH) != null) { + hash = Math.abs(StringUtils.convertLong(invocation.getAttachment(Constants.TARS_HASH).toString(), 0)); + } + long consistentHash = 0; + if (invocation.getAttachment(Constants.TARS_CONSISTENT_HASH) != null) { + consistentHash = Math.abs(StringUtils.convertLong(invocation.getAttachment(Constants.TARS_CONSISTENT_HASH).toString(), 0)); + } if (consistentHash > 0) { if (consistentHashLoadBalance == null) { diff --git a/core/src/main/java/com/qq/tars/client/rpc/loadbalance/HashLoadBalance.java b/core/src/main/java/com/qq/tars/client/rpc/loadbalance/HashLoadBalance.java index b3e14a23..7559826f 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/loadbalance/HashLoadBalance.java +++ b/core/src/main/java/com/qq/tars/client/rpc/loadbalance/HashLoadBalance.java @@ -18,16 +18,20 @@ import com.qq.tars.client.ServantProxyConfig; +import com.qq.tars.client.cluster.ServantInvokerAliveChecker; import com.qq.tars.client.cluster.ServantInvokerAliveStat; -import com.qq.tars.client.cluster.ServantnvokerAliveChecker; import com.qq.tars.client.rpc.InvokerComparator; -import com.qq.tars.client.util.ClientLogger; +import com.qq.tars.common.util.CollectionUtils; import com.qq.tars.common.util.Constants; import com.qq.tars.common.util.StringUtils; import com.qq.tars.rpc.common.InvokeContext; import com.qq.tars.rpc.common.Invoker; import com.qq.tars.rpc.common.LoadBalance; import com.qq.tars.rpc.common.exc.NoInvokerException; +import com.qq.tars.support.log.LoggerFactory; + +import java.util.logging.Level; +import java.util.logging.Logger; import java.util.ArrayList; import java.util.Collection; @@ -35,9 +39,10 @@ import java.util.List; /** - * hash负载均衡策略 + * hash Load balancing strategy */ public class HashLoadBalance implements LoadBalance { + private static final Logger logger = LoggerFactory.getClientLogger(); private final ServantProxyConfig config; private final InvokerComparator comparator = new InvokerComparator(); @@ -50,24 +55,21 @@ public HashLoadBalance(ServantProxyConfig config) { } public Invoker select(InvokeContext invocation) throws NoInvokerException { - long hash = Math.abs(StringUtils.convertLong(invocation.getAttachment(Constants.TARS_HASH), 0)); + long hash = Math.abs(StringUtils.convertLong(invocation.getAttachment(Constants.TARS_HASH).toString(), 0)); List> staticWeightInvokers = staticWeightInvokersCache; - //使用带权重的hash if (staticWeightInvokers != null && !staticWeightInvokers.isEmpty()) { Invoker invoker = staticWeightInvokers.get((int) (hash % staticWeightInvokers.size())); if (invoker.isAvailable()) return invoker; - ServantInvokerAliveStat stat = ServantnvokerAliveChecker.get(invoker.getUrl()); + ServantInvokerAliveStat stat = ServantInvokerAliveChecker.get(invoker.getUrl()); if (stat.isAlive() || (stat.getLastRetryTime() + (config.getTryTimeInterval() * 1000)) < System.currentTimeMillis()) { - //屏敝后尝试重新调用 - ClientLogger.getLogger().info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); + logger.info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); stat.setLastRetryTime(System.currentTimeMillis()); return invoker; } } - //使用不带权重的hash List> sortedInvokers = sortedInvokersCache; if (sortedInvokers == null || sortedInvokers.isEmpty()) { throw new NoInvokerException("no such active connection invoker"); @@ -76,10 +78,7 @@ public Invoker select(InvokeContext invocation) throws NoInvokerException { List> list = new ArrayList>(); for (Invoker invoker : sortedInvokers) { if (!invoker.isAvailable()) { - /** - * 屏敝后尝试重新调用 - */ - ServantInvokerAliveStat stat = ServantnvokerAliveChecker.get(invoker.getUrl()); + ServantInvokerAliveStat stat = ServantInvokerAliveChecker.get(invoker.getUrl()); if (stat.isAlive() || (stat.getLastRetryTime() + (config.getTryTimeInterval() * 1000)) < System.currentTimeMillis()) { list.add(invoker); } @@ -87,7 +86,7 @@ public Invoker select(InvokeContext invocation) throws NoInvokerException { list.add(invoker); } } - // TODO 如果全死,是否需要随机取一个尝试? + //TODO When all is not available. Whether to randomly extract one if (list.isEmpty()) { throw new NoInvokerException(config.getSimpleObjectName() + " try to select active invoker, size=" + sortedInvokers.size() + ", no such active connection invoker"); } @@ -95,16 +94,15 @@ public Invoker select(InvokeContext invocation) throws NoInvokerException { Invoker invoker = list.get((int) (hash % list.size())); if (!invoker.isAvailable()) { - //屏敝后尝试重新调用 - ClientLogger.getLogger().info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); - ServantnvokerAliveChecker.get(invoker.getUrl()).setLastRetryTime(System.currentTimeMillis()); + logger.info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); + ServantInvokerAliveChecker.get(invoker.getUrl()).setLastRetryTime(System.currentTimeMillis()); } return invoker; } @Override public void refresh(Collection> invokers) { - ClientLogger.getLogger().info(config.getSimpleObjectName() + " try to refresh HashLoadBalance's invoker cache, size=" + (invokers == null || invokers.isEmpty() ? 0 : invokers.size())); + logger.log(Level.INFO, "{0} try to refresh RoundRobinLoadBalance''s invoker cache, size= {1} ", new Object[]{config.getSimpleObjectName(), CollectionUtils.isEmpty(invokers) ? 0 : invokers.size()}); if (invokers == null || invokers.isEmpty()) { sortedInvokersCache = null; staticWeightInvokersCache = null; @@ -117,7 +115,7 @@ public void refresh(Collection> invokers) { sortedInvokersCache = sortedInvokersTmp; staticWeightInvokersCache = LoadBalanceHelper.buildStaticWeightList(sortedInvokersTmp, config); - ClientLogger.getLogger().info(config.getSimpleObjectName() + " refresh HashLoadBalance's invoker cache done, staticWeightInvokersCache size=" + (staticWeightInvokersCache == null || staticWeightInvokersCache.isEmpty() ? 0 : staticWeightInvokersCache.size()) + ", sortedInvokersCache size=" + (sortedInvokersCache == null || sortedInvokersCache.isEmpty() ? 0 : sortedInvokersCache.size())); + logger.info(config.getSimpleObjectName() + " refresh HashLoadBalance's invoker cache done, staticWeightInvokersCache size=" + (staticWeightInvokersCache == null || staticWeightInvokersCache.isEmpty() ? 0 : staticWeightInvokersCache.size()) + ", sortedInvokersCache size=" + (sortedInvokersCache == null || sortedInvokersCache.isEmpty() ? 0 : sortedInvokersCache.size())); } } diff --git a/core/src/main/java/com/qq/tars/client/rpc/loadbalance/LoadBalanceHelper.java b/core/src/main/java/com/qq/tars/client/rpc/loadbalance/LoadBalanceHelper.java index 7a843468..a89d6870 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/loadbalance/LoadBalanceHelper.java +++ b/core/src/main/java/com/qq/tars/client/rpc/loadbalance/LoadBalanceHelper.java @@ -17,18 +17,31 @@ package com.qq.tars.client.rpc.loadbalance; import com.qq.tars.client.ServantProxyConfig; -import com.qq.tars.client.util.ClientLogger; import com.qq.tars.client.util.Pair; import com.qq.tars.common.util.Constants; import com.qq.tars.rpc.common.Invoker; +import com.qq.tars.support.log.LoggerFactory; + +import java.util.logging.Level; +import java.util.logging.Logger; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.TreeSet; public class LoadBalanceHelper { + private static final Logger logger = LoggerFactory.getClientLogger(); + public static List> buildStaticWeightList(Collection> invokers, ServantProxyConfig config) { List> weightInvokers = new ArrayList>(); @@ -43,8 +56,8 @@ public static List> buildStaticWeightList(Collection> return null; } - if (ClientLogger.getLogger().isDebugEnabled()) { - ClientLogger.getLogger().debug("[buildStaticWeightList]: weightInvokers size: " + weightInvokers.size()); + if (logger.isLoggable(Level.FINE)) { + logger.fine("[buildStaticWeightList]: weightInvokers size: " + weightInvokers.size()); } int minWeight = Integer.MAX_VALUE; @@ -73,8 +86,8 @@ public static List> buildStaticWeightList(Collection> totalWeight += weight; weightToInvoker.add(new Pair>(weight, invoker)); invokerToWeight.put(invoker, weight); - if (ClientLogger.getLogger().isDebugEnabled()) { - ClientLogger.getLogger().debug("[buildStaticWeightList]: invoker: " + invoker.hashCode() + ", weight: " + weight + ", host: " + invoker.getUrl().getHost() + ", port: " + invoker.getUrl().getPort()); + if (logger.isLoggable(Level.FINE)) { + logger.fine("[buildStaticWeightList]: invoker: " + invoker.hashCode() + ", weight: " + weight + ", host: " + invoker.getUrl().getHost() + ", port: " + invoker.getUrl().getPort()); } } @@ -89,8 +102,8 @@ public static List> buildStaticWeightList(Collection> first = false; result.add(pair.second); weightToInvokerTmp.add(new Pair>(pair.first - totalWeight + invokerToWeight.get(pair.second), pair.second)); -/* if (ClientLogger.getLogger().isDebugEnabled()) { - ClientLogger.getLogger().debug("[buildStaticWeightList]: select: " + pair.getFirst() + ", " + pair.getSecond().hashCode()); +/* if (logger.isDebugEnabled()) { + logger.debug("[buildStaticWeightList]: select: " + pair.getFirst() + ", " + pair.getSecond().hashCode()); }*/ } else { weightToInvokerTmp.add(new Pair>(pair.first + invokerToWeight.get(pair.second), pair.second)); @@ -142,15 +155,15 @@ public static TreeMap> buildConsistentHashCircle(Collection } } -// if (ClientLogger.getLogger().isDebugEnabled()) { +// if (logger.isDebugEnabled()) { // StringBuilder sb = new StringBuilder("consistent hash circle:"); // for (Entry> entry : result.entrySet()) { // sb.append(entry.getKey()).append("-").append(entry.getValue().getUrl().toIdentityString()).append(", "); // } -// ClientLogger.getLogger().debug(sb.toString()); +// logger.debug(sb.toString()); // } } catch (Exception e) { - ClientLogger.getLogger().error("build consistent hash circle err. ", e); + logger.log(Level.SEVERE, "build consistent hash circle err. ", e); return null; } return result; diff --git a/core/src/main/java/com/qq/tars/client/rpc/loadbalance/RoundRobinLoadBalance.java b/core/src/main/java/com/qq/tars/client/rpc/loadbalance/RoundRobinLoadBalance.java index 9e372340..7ee1e4b8 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/loadbalance/RoundRobinLoadBalance.java +++ b/core/src/main/java/com/qq/tars/client/rpc/loadbalance/RoundRobinLoadBalance.java @@ -18,14 +18,18 @@ package com.qq.tars.client.rpc.loadbalance; import com.qq.tars.client.ServantProxyConfig; +import com.qq.tars.client.cluster.ServantInvokerAliveChecker; import com.qq.tars.client.cluster.ServantInvokerAliveStat; -import com.qq.tars.client.cluster.ServantnvokerAliveChecker; import com.qq.tars.client.rpc.InvokerComparator; -import com.qq.tars.client.util.ClientLogger; +import com.qq.tars.common.util.CollectionUtils; import com.qq.tars.rpc.common.InvokeContext; import com.qq.tars.rpc.common.Invoker; import com.qq.tars.rpc.common.LoadBalance; import com.qq.tars.rpc.common.exc.NoInvokerException; +import com.qq.tars.support.log.LoggerFactory; + +import java.util.logging.Level; +import java.util.logging.Logger; import java.util.ArrayList; import java.util.Collection; @@ -34,9 +38,11 @@ import java.util.concurrent.atomic.AtomicInteger; /** - * 轮询负载均衡策略 + * Load balancer strategy */ public class RoundRobinLoadBalance implements LoadBalance { + private static final Logger logger = LoggerFactory.getClientLogger(); + private final AtomicInteger sequence = new AtomicInteger(); private final AtomicInteger staticWeightSequence = new AtomicInteger(); @@ -54,23 +60,23 @@ public RoundRobinLoadBalance(ServantProxyConfig config) { public Invoker select(InvokeContext invocation) throws NoInvokerException { List> staticWeightInvokers = staticWeightInvokersCache; - //使用带权重的轮询 + //polling use weights if (staticWeightInvokers != null && !staticWeightInvokers.isEmpty()) { Invoker invoker = staticWeightInvokers.get((staticWeightSequence.getAndIncrement() & Integer.MAX_VALUE) % staticWeightInvokers.size()); if (invoker.isAvailable()) return invoker; - ServantInvokerAliveStat stat = ServantnvokerAliveChecker.get(invoker.getUrl()); + ServantInvokerAliveStat stat = ServantInvokerAliveChecker.get(invoker.getUrl()); if (stat.isAlive() || (stat.getLastRetryTime() + (config.getTryTimeInterval() * 1000)) < System.currentTimeMillis()) { - //屏敝后尝试重新调用 - ClientLogger.getLogger().info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); + //Try to recall after blocking + logger.info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); stat.setLastRetryTime(System.currentTimeMillis()); return invoker; } } - //使用不带权重的轮询 + //polling without weights List> sortedInvokers = sortedInvokersCache; - if (sortedInvokers == null || sortedInvokers.isEmpty()) { + if (CollectionUtils.isEmpty(sortedInvokers)) { throw new NoInvokerException("no such active connection invoker"); } @@ -78,9 +84,9 @@ public Invoker select(InvokeContext invocation) throws NoInvokerException { for (Invoker invoker : sortedInvokers) { if (!invoker.isAvailable()) { /** - * 屏敝后尝试重新调用 + * Try to recall after blocking */ - ServantInvokerAliveStat stat = ServantnvokerAliveChecker.get(invoker.getUrl()); + ServantInvokerAliveStat stat = ServantInvokerAliveChecker.get(invoker.getUrl()); if (stat.isAlive() || (stat.getLastRetryTime() + (config.getTryTimeInterval() * 1000)) < System.currentTimeMillis()) { list.add(invoker); } @@ -88,7 +94,7 @@ public Invoker select(InvokeContext invocation) throws NoInvokerException { list.add(invoker); } } - // TODO 如果全死,是否需要随机取一个尝试? + //TODO When all is not available. Whether to randomly extract one if (list.isEmpty()) { throw new NoInvokerException(config.getSimpleObjectName() + " try to select active invoker, size=" + sortedInvokers.size() + ", no such active connection invoker"); } @@ -96,29 +102,30 @@ public Invoker select(InvokeContext invocation) throws NoInvokerException { Invoker invoker = list.get((sequence.getAndIncrement() & Integer.MAX_VALUE) % list.size()); if (!invoker.isAvailable()) { - //屏敝后尝试重新调用 - ClientLogger.getLogger().info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); - ServantnvokerAliveChecker.get(invoker.getUrl()).setLastRetryTime(System.currentTimeMillis()); + //Try to recall after blocking + logger.info("try to use inactive invoker|" + invoker.getUrl().toIdentityString()); + ServantInvokerAliveChecker.get(invoker.getUrl()).setLastRetryTime(System.currentTimeMillis()); } return invoker; } @Override public void refresh(Collection> invokers) { - ClientLogger.getLogger().info(config.getSimpleObjectName() + " try to refresh RoundRobinLoadBalance's invoker cache, size=" + (invokers == null || invokers.isEmpty() ? 0 : invokers.size())); - if (invokers == null || invokers.isEmpty()) { + logger.log(Level.INFO, "{0} try to refresh RoundRobinLoadBalance''s invoker cache, size= {1} ", new Object[]{config.getSimpleObjectName(), CollectionUtils.isEmpty(invokers) ? 0 : invokers.size()}); + if (CollectionUtils.isEmpty(invokers)) { sortedInvokersCache = null; staticWeightInvokersCache = null; return; } - - List> sortedInvokersTmp = new ArrayList>(invokers); + final List> sortedInvokersTmp = new ArrayList>(invokers); Collections.sort(sortedInvokersTmp, comparator); - sortedInvokersCache = sortedInvokersTmp; staticWeightInvokersCache = LoadBalanceHelper.buildStaticWeightList(sortedInvokersTmp, config); - - ClientLogger.getLogger().info(config.getSimpleObjectName() + " refresh RoundRobinLoadBalance's invoker cache done, staticWeightInvokersCache size=" + (staticWeightInvokersCache == null || staticWeightInvokersCache.isEmpty() ? 0 : staticWeightInvokersCache.size()) + ", sortedInvokersCache size=" + (sortedInvokersCache == null || sortedInvokersCache.isEmpty() ? 0 : sortedInvokersCache.size())); + logger.log(Level.INFO, "{0} refresh RoundRobinLoadBalance''s invoker cache done, staticWeightInvokersCache size= {1}, sortedInvokersCache size={2}", + new Object[]{config.getSimpleObjectName(), + (staticWeightInvokersCache == null || staticWeightInvokersCache.isEmpty() ? 0 : staticWeightInvokersCache.size()), + (sortedInvokersCache == null || sortedInvokersCache.isEmpty() ? 0 : sortedInvokersCache.size())}) + ; } } diff --git a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsCallbackFilterChain.java b/core/src/main/java/com/qq/tars/client/rpc/tars/TarsCallbackFilterChain.java deleted file mode 100644 index 96feba4b..00000000 --- a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsCallbackFilterChain.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.qq.tars.client.rpc.tars; - -import java.util.List; - -import com.qq.tars.common.AbstractFilterChain; -import com.qq.tars.common.Filter; -import com.qq.tars.common.FilterKind; -import com.qq.tars.net.client.Callback; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.protocol.util.TarsHelper; -import com.qq.tars.rpc.exc.ServerException; -import com.qq.tars.rpc.exc.TarsException; -import com.qq.tars.rpc.protocol.tars.TarsServantRequest; -import com.qq.tars.rpc.protocol.tars.TarsServantResponse; - -public class TarsCallbackFilterChain extends AbstractFilterChain> { - - private int expireFlag; - - public TarsCallbackFilterChain(List filters, String servant, - FilterKind kind, Callback target, int expireFlag) { - super(filters, servant, kind, target); - this.expireFlag = expireFlag; - } - - @Override - protected void doRealInvoke(Request request, Response response) - throws Throwable { - if (request instanceof TarsServantRequest) { - TarsServantResponse tarsServantResponse = (TarsServantResponse)response; - if (expireFlag == 0) { - try { - if (tarsServantResponse.getCause() != null) { - throw new TarsException(tarsServantResponse.getCause()); - } - if (tarsServantResponse.getRet() != TarsHelper.SERVERSUCCESS) { - throw ServerException.makeException(tarsServantResponse.getRet()); - } - if (target != null) { - this.target.onCompleted(tarsServantResponse); - } - } catch (Throwable ex) { - if (target != null) { - target.onException(ex); - } - throw ex; - } - } else if (expireFlag == 1) { - if (target != null) { - this.target.onExpired(); - } - } - } - - } - -} diff --git a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsCallbackWrapper.java b/core/src/main/java/com/qq/tars/client/rpc/tars/TarsCallbackWrapper.java deleted file mode 100644 index f5519cb8..00000000 --- a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsCallbackWrapper.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - *

- * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - *

- * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - *

- * https://opensource.org/licenses/BSD-3-Clause - *

- * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.client.rpc.tars; - -import com.qq.tars.client.ServantProxyConfig; -import com.qq.tars.client.cluster.ServantnvokerAliveChecker; -import com.qq.tars.client.util.ClientLogger; -import com.qq.tars.common.Filter; -import com.qq.tars.common.FilterChain; -import com.qq.tars.common.FilterKind; -import com.qq.tars.common.util.Constants; -import com.qq.tars.common.util.DyeingSwitch; -import com.qq.tars.context.DistributedContextManager; -import com.qq.tars.net.client.Callback; -import com.qq.tars.protocol.util.TarsHelper; -import com.qq.tars.rpc.exc.TimeoutException; -import com.qq.tars.rpc.protocol.tars.TarsServantRequest; -import com.qq.tars.rpc.protocol.tars.TarsServantResponse; -import com.qq.tars.server.core.AppContextManager; -import com.qq.tars.support.stat.InvokeStatHelper; - -import java.util.List; - -public class TarsCallbackWrapper implements Callback { - - private final String objName; - private final ServantProxyConfig config; - private final String methodName; - private final String remoteIp; - private final int remotePort; - private final long bornTime; - private final TarsServantRequest request; - private final TarsInvoker invoker; - private final Callback callback; - private List filters; - - public TarsCallbackWrapper(ServantProxyConfig config, String methodName, String remoteIp, int remotePort, - long bornTime, TarsServantRequest request, Callback callback, TarsInvoker invoker) { - this.callback = callback; - this.config = config; - this.objName = config.getSimpleObjectName(); - - this.methodName = methodName; - this.remoteIp = remoteIp; - this.remotePort = remotePort; - this.bornTime = bornTime; - this.request = request; - this.filters = AppContextManager.getInstance().getAppContext() == null ? null : AppContextManager.getInstance().getAppContext().getFilters(FilterKind.CALLBACK); - this.invoker = invoker; - } - - public void onCompleted(TarsServantResponse response) { - int ret = response.getRet() == TarsHelper.SERVERSUCCESS ? Constants.INVOKE_STATUS_SUCC : Constants.INVOKE_STATUS_EXEC; - boolean available = ServantnvokerAliveChecker.isAlive(invoker.getUrl(), config, ret); - invoker.setAvailable(available); - try { - beforeCallback(); - FilterChain filterChain = new TarsCallbackFilterChain(filters, objName, FilterKind.CALLBACK, callback, 0); - filterChain.doFilter(request, response); - } catch (Throwable ex) { - ret = Constants.INVOKE_STATUS_EXEC; - ClientLogger.getLogger().error("error occurred on callback completed", ex); - onException(ex); - } finally { - afterCallback(); - InvokeStatHelper.getInstance().addProxyStat(objName).addInvokeTimeByClient(config.getModuleName(), config.getSlaveName(), config.getSlaveSetName(), config.getSlaveSetArea(), config.getSlaveSetID(), methodName, remoteIp, remotePort, ret, System.currentTimeMillis() - bornTime); - } - } - - public void onException(Throwable e) { - try { - if (callback != null) { - this.callback.onException(e); - } - } catch (Throwable ex) { - ClientLogger.getLogger().error("error occurred on callback exception", ex); - } - } - - public void onExpired() { - int ret = Constants.INVOKE_STATUS_TIMEOUT; - invoker.setAvailable(ServantnvokerAliveChecker.isAlive(invoker.getUrl(), config, ret)); - try { - beforeCallback(); - FilterChain filterChain = new TarsCallbackFilterChain(filters, objName, FilterKind.CALLBACK, callback, 1); - TarsServantResponse response = new TarsServantResponse(request.getIoSession()); - response.setRequest(request); - response.setTicketNumber(request.getTicketNumber()); - response.setCause(new TimeoutException("async call timeout")); - filterChain.doFilter(request, response); - } catch (Throwable ex) { - ClientLogger.getLogger().error("error occurred on callback expired", ex); - } finally { - afterCallback(); - InvokeStatHelper.getInstance().addProxyStat(objName).addInvokeTimeByClient(config.getModuleName(), config.getSlaveName(), config.getSlaveSetName(), config.getSlaveSetArea(), config.getSlaveSetID(), methodName, remoteIp, remotePort, ret, System.currentTimeMillis() - bornTime); - } - } - - private void beforeCallback() { - if (isDyeingReq()) { - DyeingSwitch.enableUnactiveDyeing(request.getStatus().get(DyeingSwitch.STATUS_DYED_KEY), request.getStatus().get(DyeingSwitch.STATUS_DYED_FILENAME)); - } - - } - - private void afterCallback() { - DistributedContextManager.releaseDistributedContext(); - } - - private boolean isDyeingReq() { - return ((request.getMessageType() & TarsHelper.MESSAGETYPEDYED) == TarsHelper.MESSAGETYPEDYED) ? true : false; - } -} diff --git a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsClientFilterChain.java b/core/src/main/java/com/qq/tars/client/rpc/tars/TarsClientFilterChain.java index 66c6bf64..fec52598 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsClientFilterChain.java +++ b/core/src/main/java/com/qq/tars/client/rpc/tars/TarsClientFilterChain.java @@ -1,64 +1,54 @@ package com.qq.tars.client.rpc.tars; -import java.util.List; -import java.util.concurrent.Future; - -import com.qq.tars.client.rpc.ServantClient; +import com.qq.tars.client.rpc.RPCClient; +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; import com.qq.tars.common.AbstractFilterChain; import com.qq.tars.common.Filter; import com.qq.tars.common.FilterKind; -import com.qq.tars.common.util.BeanAccessor; -import com.qq.tars.net.client.Callback; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.rpc.protocol.ServantRequest; import com.qq.tars.rpc.protocol.tars.TarsServantRequest; -import com.qq.tars.rpc.protocol.tars.TarsServantResponse; -public class TarsClientFilterChain extends AbstractFilterChain { - - private int type; - - private Callback callback; - - private volatile Future future; - - public TarsClientFilterChain(List filters, String servant, - FilterKind kind, ServantClient target, int type, Callback callback) { - super(filters, servant, kind, target); - this.type = type; - this.callback = callback; - } - - - public Future getFuture() { - return future; - } +import java.util.List; +import java.util.concurrent.CompletableFuture; + +public class TarsClientFilterChain extends AbstractFilterChain { + + private Request.InvokeStatus type; + + public TarsClientFilterChain(List filters, String servant, + FilterKind kind, RPCClient target, Request.InvokeStatus type) { + super(filters, servant, kind, target); + this.type = type; + + } + + + @Override + protected CompletableFuture doRealInvoke(Request request) throws Throwable { + if (request instanceof TarsServantRequest && target != null) { + return target.send(request); + } else { + throw new RuntimeException("[tars] tarsClient Filterchian invoke error!"); + } + + } + + @Override + protected void doRealInvoke(Request request, Response response) throws Throwable { + if (request instanceof TarsServantRequest && target != null) { + target.send(request); + } else { + throw new RuntimeException("[tars] tarsClient Filterchian invoke error!"); + } + } + - @Override - protected void doRealInvoke(Request request, Response response) throws Throwable { - if (request instanceof TarsServantRequest && target != null) { - TarsServantResponse tarsServantResponse = (TarsServantResponse)response; - if (type == 0) { - try { - TarsServantResponse result = target.invokeWithSync((ServantRequest) request); - BeanAccessor.setBeanValue(tarsServantResponse, "cause", result.getCause()); - BeanAccessor.setBeanValue(tarsServantResponse, "result", result.getResult()); - BeanAccessor.setBeanValue(tarsServantResponse, "ret", result.getRet()); - } catch (Exception e) { - BeanAccessor.setBeanValue(tarsServantResponse, "cause", e); - throw e; - } - return; - } - if (type == 1) { - target.invokeWithAsync((ServantRequest)request, callback); - return; - } - if (type == 2) { - future = target.invokeWithFuture((ServantRequest) request); - } - } - } + public CompletableFuture doFilter(Request request) throws Throwable { + if (request instanceof TarsServantRequest && target != null) { + return target.send(request); + } else { + throw new RuntimeException("[tars] tarsClient FilterChain invoke error!"); + } + } -} +} \ No newline at end of file diff --git a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsInvokeContext.java b/core/src/main/java/com/qq/tars/client/rpc/tars/TarsInvokeContext.java index a2419cb2..6753132b 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsInvokeContext.java +++ b/core/src/main/java/com/qq/tars/client/rpc/tars/TarsInvokeContext.java @@ -16,13 +16,13 @@ package com.qq.tars.client.rpc.tars; +import com.qq.tars.client.rpc.ServantInvokeContext; +import com.qq.tars.protocol.util.TarsHelper; + import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Map; -import com.qq.tars.client.rpc.ServantInvokeContext; -import com.qq.tars.protocol.util.TarsHelper; - @SuppressWarnings("serial") public class TarsInvokeContext extends ServantInvokeContext { diff --git a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsInvoker.java b/core/src/main/java/com/qq/tars/client/rpc/tars/TarsInvoker.java index 8acd4a87..52e592d2 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsInvoker.java +++ b/core/src/main/java/com/qq/tars/client/rpc/tars/TarsInvoker.java @@ -17,8 +17,10 @@ package com.qq.tars.client.rpc.tars; import com.qq.tars.client.ServantProxyConfig; -import com.qq.tars.client.cluster.ServantnvokerAliveChecker; -import com.qq.tars.client.rpc.ServantClient; +import com.qq.tars.client.cluster.ServantInvokerAliveChecker; +import com.qq.tars.client.rpc.RPCClient; +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; import com.qq.tars.client.rpc.ServantInvokeContext; import com.qq.tars.client.rpc.ServantInvoker; import com.qq.tars.common.Filter; @@ -26,16 +28,13 @@ import com.qq.tars.common.FilterKind; import com.qq.tars.common.util.Constants; import com.qq.tars.common.util.DyeingSwitch; -import com.qq.tars.context.DistributedContext; -import com.qq.tars.context.DistributedContextManager; -import com.qq.tars.net.client.Callback; -import com.qq.tars.net.core.Request.InvokeStatus; +import com.qq.tars.context.TarsContext; import com.qq.tars.protocol.tars.support.TarsMethodInfo; -import com.qq.tars.protocol.tars.support.TarsMethodParameterInfo; import com.qq.tars.protocol.util.TarsHelper; import com.qq.tars.rpc.common.Url; import com.qq.tars.rpc.exc.NotConnectedException; import com.qq.tars.rpc.exc.ServerException; +import com.qq.tars.rpc.exc.TarsException; import com.qq.tars.rpc.exc.TimeoutException; import com.qq.tars.rpc.protocol.tars.TarsServantRequest; import com.qq.tars.rpc.protocol.tars.TarsServantResponse; @@ -47,36 +46,39 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; public class TarsInvoker extends ServantInvoker { - List filters; + final List filters; - public TarsInvoker(ServantProxyConfig config, Class api, Url url, ServantClient[] clients) { + public TarsInvoker(ServantProxyConfig config, Class api, Url url, RPCClient[] clients) { super(config, api, url, clients); + System.out.println(AppContextManager.getInstance().getAppContext() == null); filters = AppContextManager.getInstance().getAppContext() == null ? null : AppContextManager.getInstance().getAppContext().getFilters(FilterKind.CLIENT); } @Override - protected void setAvailable(boolean available) { + public void setAvailable(boolean available) { super.setAvailable(available); } protected Object doInvokeServant(final ServantInvokeContext inv) throws Throwable { - long begin = System.currentTimeMillis(); - + final long begin = System.currentTimeMillis(); int ret = Constants.INVOKE_STATUS_SUCC; - boolean isAsync = TarsHelper.isAsync(inv.getMethodName()); try { Method method = getApi().getMethod(inv.getMethodName(), inv.getParameterTypes()); - if (isAsync) { - invokeWithAsync(method, inv.getArguments(), inv.getAttachments()); - return null; + if (inv.isPromiseFuture()) { + return invokeWithPromiseFuture(method, inv.getArguments(), inv.getAttachments());// return Future Result } else { TarsServantResponse response = invokeWithSync(method, inv.getArguments(), inv.getAttachments()); ret = response.getRet() == TarsHelper.SERVERSUCCESS ? Constants.INVOKE_STATUS_SUCC : Constants.INVOKE_STATUS_EXEC; if (response.getRet() != TarsHelper.SERVERSUCCESS) { - throw ServerException.makeException(response.getRet()); + throw ServerException.makeException(response.getRet(), response.getRemark()); + } + if (response.getCause() != null) { + throw new TarsException(response.getCause()); } return response.getResult(); } @@ -90,20 +92,22 @@ protected Object doInvokeServant(final ServantInvokeContext inv) throws Throwabl } throw e; } finally { - if (!isAsync) { - setAvailable(ServantnvokerAliveChecker.isAlive(getUrl(), config, ret)); - InvokeStatHelper.getInstance().addProxyStat(objName).addInvokeTimeByClient(config.getMasterName(), config.getSlaveName(), config.getSlaveSetName(), config.getSlaveSetArea(), config.getSlaveSetID(), inv.getMethodName(), getUrl().getHost(), getUrl().getPort(), ret, System.currentTimeMillis() - begin); + if (inv.isNormal()) { + setAvailable(ServantInvokerAliveChecker.isAlive(getUrl(), config, ret)); + InvokeStatHelper.getInstance().addProxyStat(objName) + .addInvokeTimeByClient(config.getMasterName(), config.getSlaveName(), config.getSlaveSetName(), config.getSlaveSetArea(), + config.getSlaveSetID(), inv.getMethodName(), getUrl().getHost(), getUrl().getPort(), ret, System.currentTimeMillis() - begin); } } } - private ServantClient getClient() { + private RPCClient getClient() { return clients.length == 1 ? clients[0] : clients[(index.getAndIncrement() & Integer.MAX_VALUE) % clients.length]; } private TarsServantResponse invokeWithSync(Method method, Object args[], Map context) throws Throwable { - ServantClient client = getClient(); - TarsServantRequest request = new TarsServantRequest(client.getIoSession()); + RPCClient client = getClient(); + TarsServantRequest request = new TarsServantRequest(); request.setVersion(TarsHelper.VERSION); request.setMessageType(isHashInvoke(context) ? TarsHelper.MESSAGETYPEHASH : TarsHelper.MESSAGETYPENULL); request.setPacketType(TarsHelper.NORMAL); @@ -113,84 +117,65 @@ private TarsServantResponse invokeWithSync(Method method, Object args[], Map status = new HashMap(); - String routeKey = distributedContext.get(DyeingSwitch.DYEINGKEY); - String fileName = distributedContext.get(DyeingSwitch.FILENAME); + HashMap status = new HashMap<>(); + String routeKey = ctx.get(TarsContext.DYEING_KEY); + String fileName = ctx.get(TarsContext.DYEING_FILENAME); status.put(DyeingSwitch.STATUS_DYED_KEY, routeKey == null ? "" : routeKey); status.put(DyeingSwitch.STATUS_DYED_FILENAME, fileName == null ? "" : fileName); request.setStatus(status); - } - FilterChain filterChain = new TarsClientFilterChain(filters, objName, FilterKind.CLIENT, client, 0, null); - filterChain.doFilter(request, response); - return response; + FilterChain filterChain = new TarsClientFilterChain(filters, objName, FilterKind.CLIENT, client, Request.InvokeStatus.SYNC_CALL); + CompletableFuture responseCompletableFuture = filterChain.doFilter(request); + return (TarsServantResponse) responseCompletableFuture.get(request.getTimeout(), TimeUnit.MILLISECONDS); } - @SuppressWarnings("unchecked") - private void invokeWithAsync(Method method, Object args[], Map context) throws Throwable { - ServantClient client = getClient(); - TarsServantRequest request = new TarsServantRequest(client.getIoSession()); + /** + * promise call + * @param method + * @param args + * @param context + */ + private CompletableFuture invokeWithPromiseFuture(Method method, Object args[], Map context) throws Throwable { + final RPCClient client = getClient(); + final TarsServantRequest request = new TarsServantRequest(); request.setVersion(TarsHelper.VERSION); request.setMessageType(isHashInvoke(context) ? TarsHelper.MESSAGETYPEHASH : TarsHelper.MESSAGETYPENULL); request.setPacketType(TarsHelper.NORMAL); request.setServantName(objName); - request.setFunctionName(method.getName().replaceAll("async_", "")); + request.setFunctionName(method.getName().replaceAll(Constants.TARS_METHOD_PROMISE_START_WITH, "")); request.setContext(context); - - TarsMethodInfo methodInfo = AnalystManager.getInstance().getMethodMap(super.getApi()).get(method); + request.setMethodParameters(args); //completableFuture send Callback + final TarsMethodInfo methodInfo = AnalystManager.getInstance().getMethodMap(super.getApi()).get(method); + request.setInvokeStatus(Request.InvokeStatus.FUTURE_CALL); request.setApi(super.getApi()); request.setMethodInfo(methodInfo); - request.setMethodParameters(args); - request.setInvokeStatus(InvokeStatus.ASYNC_CALL); - Callback callback = null; - List parameterInfoList = methodInfo.getParametersList(); - for (TarsMethodParameterInfo parameterInfo : parameterInfoList) { - if (TarsHelper.isCallback(parameterInfo.getAnnotations())) { - callback = (Callback) args[parameterInfo.getOrder()]; - break; - } - } - - if (callback == null) { - request.setPacketType(TarsHelper.ONEWAY); - } - - TarsServantResponse response = new TarsServantResponse(client.getIoSession()); - - DistributedContext distributedContext = DistributedContextManager.getDistributedContext(); - Boolean bDyeing = distributedContext.get(DyeingSwitch.BDYEING); + TarsContext ctx = TarsContext.current(); + Boolean bDyeing = ctx.get(TarsContext.DYEING); if (bDyeing != null && bDyeing == true) { request.setMessageType(request.getMessageType() | TarsHelper.MESSAGETYPEDYED); - HashMap status = new HashMap(); - String routeKey = distributedContext.get(DyeingSwitch.DYEINGKEY); - String fileName = distributedContext.get(DyeingSwitch.FILENAME); + HashMap status = new HashMap<>(); + String routeKey = ctx.get(TarsContext.DYEING_KEY); + String fileName = ctx.get(TarsContext.DYEING_FILENAME); status.put(DyeingSwitch.STATUS_DYED_KEY, routeKey == null ? "" : routeKey); status.put(DyeingSwitch.STATUS_DYED_FILENAME, fileName == null ? "" : fileName); request.setStatus(status); - } - FilterChain filterChain = new TarsClientFilterChain(filters, objName, FilterKind.CLIENT, client, 1, - new TarsCallbackWrapper(config, request.getFunctionName(), getUrl().getHost(), getUrl().getPort(), request.getBornTime(), request, callback, this)); - filterChain.doFilter(request, response); + //sync call all filter + final FilterChain filterChain = new TarsClientFilterChain(filters, objName, FilterKind.CLIENT, client, Request.InvokeStatus.FUTURE_CALL); + CompletableFuture tarsResponse = filterChain.doFilter(request); + return tarsResponse.thenCompose(tarsresponseObj -> { + TarsServantResponse tarsServantResponse = (TarsServantResponse) tarsresponseObj; + if (tarsServantResponse != null) { + tarsResponse.completeExceptionally(tarsServantResponse.getCause()); + } + return CompletableFuture.completedFuture((V) tarsServantResponse.getResult()); + }); } private boolean isHashInvoke(Map context) { diff --git a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsProtocolInvoker.java b/core/src/main/java/com/qq/tars/client/rpc/tars/TarsProtocolInvoker.java index 3367e1e1..a0445bb5 100644 --- a/core/src/main/java/com/qq/tars/client/rpc/tars/TarsProtocolInvoker.java +++ b/core/src/main/java/com/qq/tars/client/rpc/tars/TarsProtocolInvoker.java @@ -16,22 +16,19 @@ package com.qq.tars.client.rpc.tars; -import java.lang.reflect.Method; -import java.util.concurrent.ThreadPoolExecutor; - import com.qq.tars.client.ServantProxyConfig; import com.qq.tars.client.rpc.ServantProtocolInvoker; -import com.qq.tars.net.protocol.ProtocolFactory; import com.qq.tars.rpc.common.InvokeContext; import com.qq.tars.rpc.common.Invoker; import com.qq.tars.rpc.common.Url; import com.qq.tars.rpc.protocol.tars.support.AnalystManager; +import java.lang.reflect.Method; + public class TarsProtocolInvoker extends ServantProtocolInvoker { - public TarsProtocolInvoker(Class api, ServantProxyConfig config, ProtocolFactory protocolFactory, - ThreadPoolExecutor threadPoolExecutor) { - super(api, config, protocolFactory, threadPoolExecutor); + public TarsProtocolInvoker(Class api, ServantProxyConfig config) { + super(api, config); AnalystManager.getInstance().registry(api, servantProxyConfig.getSimpleObjectName()); } diff --git a/core/src/main/java/com/qq/tars/client/support/ClientPoolManager.java b/core/src/main/java/com/qq/tars/client/support/ClientPoolManager.java index 16eaff01..e7705684 100644 --- a/core/src/main/java/com/qq/tars/client/support/ClientPoolManager.java +++ b/core/src/main/java/com/qq/tars/client/support/ClientPoolManager.java @@ -16,29 +16,28 @@ package com.qq.tars.client.support; -import java.io.IOException; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - import com.qq.tars.client.CommunicatorConfig; -import com.qq.tars.client.ServantProxyConfig; -import com.qq.tars.client.rpc.ServantClient; +import com.qq.tars.client.rpc.RPCClient; import com.qq.tars.common.util.concurrent.TaskQueue; import com.qq.tars.common.util.concurrent.TaskThreadFactory; import com.qq.tars.common.util.concurrent.TaskThreadPoolExecutor; -import com.qq.tars.net.core.nio.SelectorManager; -import com.qq.tars.net.protocol.ProtocolFactory; +import com.qq.tars.support.log.LoggerFactory; -public class ClientPoolManager { +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +public class ClientPoolManager { + private static final Logger logger = LoggerFactory.getClientLogger(); private final static ConcurrentHashMap clientThreadPoolMap = new ConcurrentHashMap(); - private final static ConcurrentHashMap selectorsMap = new ConcurrentHashMap(); public static ThreadPoolExecutor getClientThreadPoolExecutor(CommunicatorConfig communicatorConfig) { ThreadPoolExecutor clientPoolExecutor = clientThreadPoolMap.get(communicatorConfig); if (clientPoolExecutor == null) { - synchronized (ServantClient.class) { + synchronized (RPCClient.class) { clientPoolExecutor = clientThreadPoolMap.get(communicatorConfig); if (clientPoolExecutor == null) { clientThreadPoolMap.put(communicatorConfig, createThreadPool(communicatorConfig)); @@ -55,30 +54,13 @@ private static ThreadPoolExecutor createThreadPool(CommunicatorConfig communicat int keepAliveTime = communicatorConfig.getKeepAliveTime(); int queueSize = communicatorConfig.getQueueSize(); TaskQueue taskqueue = new TaskQueue(queueSize); - String namePrefix = "tars-client-executor-"; + logger.log(Level.INFO, "create client thread pool, communicator config is {0}", communicatorConfig.toString()); TaskThreadPoolExecutor executor = new TaskThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, taskqueue, new TaskThreadFactory(namePrefix)); taskqueue.setParent(executor); return executor; } - public static SelectorManager getSelectorManager(ProtocolFactory protocolFactory, - ThreadPoolExecutor threadPoolExecutor, boolean keepAlive, - boolean udpMode, ServantProxyConfig servantProxyConfig) throws IOException { - SelectorManager selector = selectorsMap.get(servantProxyConfig); - if (selector == null) { - synchronized (selectorsMap) { - selector = selectorsMap.get(servantProxyConfig); - if (selector == null) { - int selectorPoolSize = convertInt(System.getProperty("com.qq.tars.net.client.selectorPoolSize"), 2); - selector = new SelectorManager(selectorPoolSize, protocolFactory, threadPoolExecutor, null, keepAlive, "servant-proxy-" + servantProxyConfig.getCommunicatorId(), udpMode); - selector.start(); - selectorsMap.put(servantProxyConfig, selector); - } - } - } - return selector; - } private static int convertInt(String value, int defaults) { if (value == null) { diff --git a/core/src/main/java/com/qq/tars/client/support/ClientThreadPoolManager.java b/core/src/main/java/com/qq/tars/client/support/ClientThreadPoolManager.java index 17cd0c52..85541f20 100644 --- a/core/src/main/java/com/qq/tars/client/support/ClientThreadPoolManager.java +++ b/core/src/main/java/com/qq/tars/client/support/ClientThreadPoolManager.java @@ -16,16 +16,16 @@ package com.qq.tars.client.support; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - import com.qq.tars.client.CommunicatorConfig; -import com.qq.tars.client.rpc.ServantClient; +import com.qq.tars.client.rpc.RPCClient; import com.qq.tars.common.util.concurrent.TaskQueue; import com.qq.tars.common.util.concurrent.TaskThreadFactory; import com.qq.tars.common.util.concurrent.TaskThreadPoolExecutor; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + public class ClientThreadPoolManager { private static ConcurrentHashMap clientThreadPoolMap = new ConcurrentHashMap(); @@ -34,7 +34,7 @@ public static ThreadPoolExecutor getClientThreadPoolExecutor(CommunicatorConfig String contextIdentity = resolveCurrentContextIdentity(); ThreadPoolExecutor clientPoolExecutor = clientThreadPoolMap.get(contextIdentity); if (clientPoolExecutor == null) { - synchronized (ServantClient.class) { + synchronized (RPCClient.class) { clientPoolExecutor = clientThreadPoolMap.get(contextIdentity); if (clientPoolExecutor == null) { clientThreadPoolMap.put(contextIdentity, createThreadPool(communicatorConfig)); @@ -59,10 +59,10 @@ private static ThreadPoolExecutor createThreadPool(CommunicatorConfig communicat } private static String resolveCurrentContextIdentity() { - Object slefClassLoader = ClientThreadPoolManager.class.getClassLoader(); + Object selfClassLoader = ClientThreadPoolManager.class.getClassLoader(); Object contextClassLoader = Thread.currentThread().getContextClassLoader(); String contextIdentity = ClientThreadPoolManager.class.getName(); - if (slefClassLoader != null && contextClassLoader != null && slefClassLoader != contextClassLoader) { + if (selfClassLoader != null && contextClassLoader != null && selfClassLoader != contextClassLoader) { contextIdentity = contextClassLoader.toString(); } return contextIdentity; diff --git a/core/src/main/java/com/qq/tars/client/support/ServantCacheManager.java b/core/src/main/java/com/qq/tars/client/support/ServantCacheManager.java index 180128c9..7e1cd523 100644 --- a/core/src/main/java/com/qq/tars/client/support/ServantCacheManager.java +++ b/core/src/main/java/com/qq/tars/client/support/ServantCacheManager.java @@ -16,6 +16,14 @@ package com.qq.tars.client.support; +import com.qq.tars.common.util.Constants; +import com.qq.tars.common.util.Loader; +import com.qq.tars.common.util.StringUtils; +import com.qq.tars.support.log.LoggerFactory; + +import java.util.logging.Level; +import java.util.logging.Logger; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -27,17 +35,14 @@ import java.net.URL; import java.util.ArrayList; import java.util.Date; +import java.util.List; import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; -import com.qq.tars.client.util.ClientLogger; -import com.qq.tars.common.util.Constants; -import com.qq.tars.common.util.Loader; -import com.qq.tars.common.util.StringUtils; - public final class ServantCacheManager { + private static final Logger LOGGER = LoggerFactory.getClientLogger(); private final static ServantCacheManager instance = new ServantCacheManager(); @@ -68,7 +73,7 @@ public void save(String CommunicatorId, String objName, String endpointList, Str props.put(makeKey(CommunicatorId, objName), endpointList); saveToLocal(dataPath); } catch (Throwable e) { - ClientLogger.getLogger().error("", e); + LOGGER.log(Level.SEVERE, "", e); } } @@ -103,9 +108,9 @@ private void saveToLocal(String dataPath) { } out = new BufferedOutputStream(new FileOutputStream(file)); props.store(out, (new Date()).toString()); - ClientLogger.getLogger().info("save " + file.getAbsolutePath()); + LOGGER.info("save " + file.getAbsolutePath()); } catch (Exception e) { - ClientLogger.getLogger().error("save " + Constants.SERVER_NODE_CACHE_FILENAME + " failed", e); + LOGGER.log(Level.SEVERE, "save " + Constants.SERVER_NODE_CACHE_FILENAME + " failed", e); } finally { if (null != out) { try { @@ -130,7 +135,7 @@ private void loadCacheData(String dataPath) { } in = new BufferedInputStream(new FileInputStream(file)); props.load(in); - ArrayList removeKey = new ArrayList(); + List removeKey = new ArrayList<>(); for (Entry entry : props.entrySet()) { if (entry.getKey().toString().startsWith("<")) { removeKey.add(entry.getKey().toString()); @@ -139,9 +144,9 @@ private void loadCacheData(String dataPath) { for (String key : removeKey) { props.remove(key); } - ClientLogger.getLogger().info("load " + Constants.SERVER_NODE_CACHE_FILENAME); + LOGGER.log(Level.INFO, "load {0}", Constants.SERVER_NODE_CACHE_FILENAME); } catch (Throwable e) { - ClientLogger.getLogger().error("read file " + Constants.SERVER_NODE_CACHE_FILENAME + " error.", e); + LOGGER.log(Level.SEVERE, "read file " + Constants.SERVER_NODE_CACHE_FILENAME + " error.", e); } finally { if (null != in) { try { diff --git a/core/src/main/java/com/qq/tars/client/util/Pair.java b/core/src/main/java/com/qq/tars/client/util/Pair.java index 19da6ee4..7fa5a532 100644 --- a/core/src/main/java/com/qq/tars/client/util/Pair.java +++ b/core/src/main/java/com/qq/tars/client/util/Pair.java @@ -17,6 +17,7 @@ package com.qq.tars.client.util; import java.io.Serializable; +import java.util.Objects; public final class Pair implements Serializable { @@ -33,7 +34,7 @@ public Pair(F f, S s) { } private static boolean eq(T o1, T o2) { - return o1 == null ? o2 == null : o1.equals(o2); + return Objects.equals(o1, o2); } public boolean equals(Object o) { diff --git a/core/src/main/java/com/qq/tars/common/AbstractFilterChain.java b/core/src/main/java/com/qq/tars/common/AbstractFilterChain.java index 7d7648c7..67074eef 100644 --- a/core/src/main/java/com/qq/tars/common/AbstractFilterChain.java +++ b/core/src/main/java/com/qq/tars/common/AbstractFilterChain.java @@ -1,54 +1,60 @@ package com.qq.tars.common; +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; + import java.util.Iterator; import java.util.List; - -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; +import java.util.concurrent.CompletableFuture; public abstract class AbstractFilterChain implements FilterChain { - private List filters; - - protected String servant; - - protected FilterKind kind; - - protected T target; - - private Iterator iteator; - - public AbstractFilterChain(List filters, String servant, FilterKind kind, T target) { - this.filters = filters; - this.servant = servant; - this.kind = kind; - this.target = target; - } - - @Override - public void doFilter(Request request, Response response) throws Throwable { - Filter filter = getFilter(); - if (filter != null) { - filter.doFilter(request, response, this); - } else { - doRealInvoke(request, response); - } - - } - - private Filter getFilter() { - if (filters == null || filters.isEmpty()) { - return null; - } - if (iteator == null) { - iteator = filters.iterator(); - } - if (iteator.hasNext()) { - return iteator.next(); - } - return null; - } - - protected abstract void doRealInvoke(Request request, Response response) throws Throwable; + protected String servant; + protected FilterKind kind; + protected T target; + private Iterator iterator; + + public AbstractFilterChain(List filters, String servant, FilterKind kind, T target) { + this.servant = servant; + this.kind = kind; + this.target = target; + if (filters != null) { + this.iterator = filters.iterator(); + } + } + + @Override + public CompletableFuture doFilter(Request request) throws Throwable { + Filter filter = getFilter(); + if (filter != null) { + return filter.doFilter(request, this); + } else { + return doRealInvoke(request); + } + + } + + private Filter getFilter() { + return iterator != null && iterator.hasNext() ? iterator.next() : null; + } + + + @Override + public void doFilter(Request request, Response response) throws Throwable { + Filter filter = getFilter(); + if (filter != null) { + filter.doFilter(request, response, this); + return; + } else { + doRealInvoke(request, response); + return; + } + + } + + protected abstract CompletableFuture doRealInvoke(Request request) throws Throwable; + + protected abstract void doRealInvoke(Request request, Response response) throws Throwable; + } diff --git a/core/src/main/java/com/qq/tars/common/Filter.java b/core/src/main/java/com/qq/tars/common/Filter.java index 86e78e55..aec7c777 100644 --- a/core/src/main/java/com/qq/tars/common/Filter.java +++ b/core/src/main/java/com/qq/tars/common/Filter.java @@ -1,14 +1,19 @@ package com.qq.tars.common; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; + +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; + +import java.util.concurrent.CompletableFuture; public interface Filter { - - public void init(); - - public void doFilter(Request request, Response response, FilterChain chain) throws Throwable; - - public void destroy(); + + void init(); + + void doFilter(Request request, Response response, FilterChain chain) throws Throwable; + + CompletableFuture doFilter(Request request, FilterChain chain) throws Throwable; + + void destroy(); } diff --git a/core/src/main/java/com/qq/tars/common/FilterChain.java b/core/src/main/java/com/qq/tars/common/FilterChain.java index 2177ed36..2402f847 100644 --- a/core/src/main/java/com/qq/tars/common/FilterChain.java +++ b/core/src/main/java/com/qq/tars/common/FilterChain.java @@ -1,9 +1,29 @@ package com.qq.tars.common; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; + +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; + +import java.util.concurrent.CompletableFuture; public interface FilterChain { - - public void doFilter(Request request, Response response) throws Throwable; + + + /*** + * + * @param request + * @return + * @throws Throwable + */ + CompletableFuture doFilter(Request request) throws Throwable; + + /*** + * + * @param request + * @param response + * @throws Throwable + */ + void doFilter(Request request, Response response) throws Throwable; + + } diff --git a/core/src/main/java/com/qq/tars/common/support/ScheduledExecutorManager.java b/core/src/main/java/com/qq/tars/common/support/ScheduledExecutorManager.java index d6167953..56183566 100644 --- a/core/src/main/java/com/qq/tars/common/support/ScheduledExecutorManager.java +++ b/core/src/main/java/com/qq/tars/common/support/ScheduledExecutorManager.java @@ -16,6 +16,9 @@ package com.qq.tars.common.support; +import com.qq.tars.common.util.Constants; +import com.qq.tars.common.util.concurrent.TaskThreadFactory; + import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; @@ -30,9 +33,6 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -import com.qq.tars.common.util.Constants; -import com.qq.tars.common.util.concurrent.TaskThreadFactory; - public final class ScheduledExecutorManager implements ScheduledExecutorService { private final static ScheduledExecutorManager instance = new ScheduledExecutorManager(); diff --git a/core/src/main/java/com/qq/tars/common/util/DyeingSwitch.java b/core/src/main/java/com/qq/tars/common/util/DyeingSwitch.java index bf25ed97..1f95872c 100644 --- a/core/src/main/java/com/qq/tars/common/util/DyeingSwitch.java +++ b/core/src/main/java/com/qq/tars/common/util/DyeingSwitch.java @@ -15,40 +15,33 @@ */ package com.qq.tars.common.util; -import com.qq.tars.context.DistributedContext; -import com.qq.tars.context.DistributedContextManager; +import com.qq.tars.context.TarsContext; public class DyeingSwitch { - - public static final String BDYEING = "bDyeing"; - public static final String DYEINGKEY = "dyeingKey"; - public static final String SERVANT = "servantName"; - public static final String FILENAME = "dyeFileName"; - public static final String REQ = "request"; - public static final String RES = "response"; + public static final String STATUS_DYED_KEY = "STATUS_DYED_KEY"; public static final String STATUS_DYED_FILENAME = "STATUS_DYED_FILENAME"; - + public static void enableActiveDyeing(final String servant) { - DistributedContext context = DistributedContextManager.getDistributedContext(); - context.put(BDYEING, true); - context.put(DYEINGKEY, null); - context.put(FILENAME, servant == null ? "default" : servant); + TarsContext ctx = TarsContext.current(); + ctx.set(TarsContext.DYEING, true); + ctx.set(TarsContext.DYEING_KEY, null); + ctx.set(TarsContext.DYEING_FILENAME, servant == null ? "default" : servant); } - + public static void enableUnactiveDyeing(final String sDyeingKey, final String servant) { - DistributedContext context = DistributedContextManager.getDistributedContext(); - context.put(BDYEING, true); - context.put(DYEINGKEY, sDyeingKey); - context.put(FILENAME, servant); + TarsContext ctx = TarsContext.current(); + ctx.set(TarsContext.DYEING, true); + ctx.set(TarsContext.DYEING_KEY, sDyeingKey); + ctx.set(TarsContext.DYEING_FILENAME, servant); } - + public static void closeActiveDyeing() { - DistributedContext context = DistributedContextManager.getDistributedContext(); - context.put(BDYEING, false); - context.put(DYEINGKEY, null); - context.put(FILENAME, null); + TarsContext ctx = TarsContext.current(); + ctx.set(TarsContext.DYEING, false); + ctx.set(TarsContext.DYEING_KEY, null); + ctx.set(TarsContext.DYEING_FILENAME, null); } } diff --git a/core/src/main/java/com/qq/tars/common/util/FileUtil.java b/core/src/main/java/com/qq/tars/common/util/FileUtil.java index b4ac5444..04e778e7 100644 --- a/core/src/main/java/com/qq/tars/common/util/FileUtil.java +++ b/core/src/main/java/com/qq/tars/common/util/FileUtil.java @@ -16,6 +16,8 @@ package com.qq.tars.common.util; +import com.qq.tars.rpc.exc.TarsException; + import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; @@ -26,8 +28,6 @@ import java.io.StringWriter; import java.util.List; -import com.qq.tars.rpc.exc.TarsException; - public class FileUtil { public static String readFileToString(String fileName, String charset) { diff --git a/core/src/main/java/com/qq/tars/common/util/Loader.java b/core/src/main/java/com/qq/tars/common/util/Loader.java index b9f6a136..7076c5f5 100644 --- a/core/src/main/java/com/qq/tars/common/util/Loader.java +++ b/core/src/main/java/com/qq/tars/common/util/Loader.java @@ -16,10 +16,10 @@ package com.qq.tars.common.util; -import java.net.URL; - import com.qq.tars.rpc.exc.TarsException; +import java.net.URL; + public class Loader { public static URL getResource(String resource) { diff --git a/core/src/main/java/com/qq/tars/common/util/TableUtil.java b/core/src/main/java/com/qq/tars/common/util/TableUtil.java index 02e859ff..f7f9188c 100644 --- a/core/src/main/java/com/qq/tars/common/util/TableUtil.java +++ b/core/src/main/java/com/qq/tars/common/util/TableUtil.java @@ -39,8 +39,7 @@ public V get(R rowKey, C columnKey) { if (columns == null) { return null; } - V value = columns.get(columnKey); - return value; + return columns.get(columnKey); } public void set(R rowKey, C columnKey, V value) { @@ -50,7 +49,7 @@ public void set(R rowKey, C columnKey, V value) { Map columns = table.get(rowKey); if (columns == null) { columns = new LinkedHashMap(); - table.put(rowKey, columns); + table.putIfAbsent(rowKey, columns); } columns.put(columnKey, value); } diff --git a/core/src/main/java/com/qq/tars/context/TarsContext.java b/core/src/main/java/com/qq/tars/context/TarsContext.java new file mode 100644 index 00000000..406fc4e9 --- /dev/null +++ b/core/src/main/java/com/qq/tars/context/TarsContext.java @@ -0,0 +1,73 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.qq.tars.context; + +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; + +import java.util.HashMap; +import java.util.Map; + +public final class TarsContext { + + public static final class Key { + private final String name; + + private Key(String name) { + this.name = name; + } + + public static Key named(String name) { + return new Key<>(name); + } + + @Override + public String toString() { + return name; + } + } + + // Dyeing keys + public static final Key DYEING = Key.named("dyeing"); + public static final Key DYEING_KEY = Key.named("dyeingKey"); + public static final Key DYEING_FILENAME = Key.named("dyeFileName"); + + // Request processing keys + public static final Key REQUEST = Key.named("request"); + public static final Key RESPONSE = Key.named("response"); + public static final Key SERVANT_NAME = Key.named("servantName"); + + private static final ThreadLocal CURRENT = ThreadLocal.withInitial(TarsContext::new); + + private final Map, Object> values = new HashMap<>(); + + public static TarsContext current() { + return CURRENT.get(); + } + + public static void release() { + CURRENT.remove(); + } + + @SuppressWarnings("unchecked") + public T get(Key key) { + return (T) values.get(key); + } + + public void set(Key key, T value) { + values.put(key, value); + } +} diff --git a/core/src/main/java/com/qq/tars/register/RegisterHandler.java b/core/src/main/java/com/qq/tars/register/RegisterHandler.java index 1fd41619..4231ecc0 100644 --- a/core/src/main/java/com/qq/tars/register/RegisterHandler.java +++ b/core/src/main/java/com/qq/tars/register/RegisterHandler.java @@ -16,18 +16,14 @@ package com.qq.tars.register; -import com.qq.tars.client.Communicator; -import com.qq.tars.client.CommunicatorConfig; -import com.qq.tars.client.Communicator; -import com.qq.tars.server.config.ServerConfig; import com.qq.tars.support.query.prx.EndpointF; import java.util.List; public interface RegisterHandler { - public void register(String appName, String serviceName); + void register(String appName, String serviceName); - public List query(String name); + List query(String name); } diff --git a/core/src/main/java/com/qq/tars/register/RegisterManager.java b/core/src/main/java/com/qq/tars/register/RegisterManager.java index e75d0e9c..795d4be5 100644 --- a/core/src/main/java/com/qq/tars/register/RegisterManager.java +++ b/core/src/main/java/com/qq/tars/register/RegisterManager.java @@ -16,7 +16,6 @@ package com.qq.tars.register; -import com.qq.tars.rpc.exc.ServiceNotFoundException; import java.util.ServiceLoader; public class RegisterManager { diff --git a/core/src/main/java/com/qq/tars/rpc/common/InvokeContext.java b/core/src/main/java/com/qq/tars/rpc/common/InvokeContext.java index 95d33299..a8342c39 100644 --- a/core/src/main/java/com/qq/tars/rpc/common/InvokeContext.java +++ b/core/src/main/java/com/qq/tars/rpc/common/InvokeContext.java @@ -30,9 +30,9 @@ public interface InvokeContext { Class[] getParameterTypes(); - String getAttachment(String key); + Object getAttachment(String key); - String getAttachment(String key, String defaultValue); + Object getAttachment(String key, String defaultValue); Map getAttachments(); } diff --git a/core/src/main/java/com/qq/tars/rpc/common/LoadBalance.java b/core/src/main/java/com/qq/tars/rpc/common/LoadBalance.java index f4db6f25..a4ed1769 100644 --- a/core/src/main/java/com/qq/tars/rpc/common/LoadBalance.java +++ b/core/src/main/java/com/qq/tars/rpc/common/LoadBalance.java @@ -16,15 +16,14 @@ package com.qq.tars.rpc.common; -import java.util.Collection; - import com.qq.tars.rpc.common.exc.NoInvokerException; +import java.util.Collection; + public interface LoadBalance { /** - * 根据负载均衡策略,挑选invoker - * + * Use load balancing to select invoker * @param invokeContext * @return * @throws NoInvokerException @@ -32,7 +31,7 @@ public interface LoadBalance { Invoker select(InvokeContext invokeContext) throws NoInvokerException; /** - * 通知invoker列表的更新 + * Refresh local invoker * @param invokers */ void refresh(Collection> invokers); diff --git a/core/src/main/java/com/qq/tars/rpc/common/exc/NoInvokerException.java b/core/src/main/java/com/qq/tars/rpc/common/exc/NoInvokerException.java index 4853a064..58f59859 100644 --- a/core/src/main/java/com/qq/tars/rpc/common/exc/NoInvokerException.java +++ b/core/src/main/java/com/qq/tars/rpc/common/exc/NoInvokerException.java @@ -19,6 +19,8 @@ @SuppressWarnings("serial") public class NoInvokerException extends RuntimeException { + private static final long serialVersionUID = 6881131005776499222L; + public NoInvokerException() { super(); } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/CommunicatorConfigException.java b/core/src/main/java/com/qq/tars/rpc/exc/CommunicatorConfigException.java index 3f003b57..c6434341 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/CommunicatorConfigException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/CommunicatorConfigException.java @@ -19,6 +19,8 @@ @SuppressWarnings("serial") public class CommunicatorConfigException extends ClientException { + private static final long serialVersionUID = -561177612910425984L; + public CommunicatorConfigException(String message) { super(message); } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/NoConnectionException.java b/core/src/main/java/com/qq/tars/rpc/exc/NoConnectionException.java index 55a49555..8824f692 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/NoConnectionException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/NoConnectionException.java @@ -19,6 +19,8 @@ @SuppressWarnings("serial") public class NoConnectionException extends ClientException { + private static final long serialVersionUID = -2244573531255176500L; + public NoConnectionException(String message) { super(message); } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/NotConnectedException.java b/core/src/main/java/com/qq/tars/rpc/exc/NotConnectedException.java index 507444b5..749fb20a 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/NotConnectedException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/NotConnectedException.java @@ -20,6 +20,8 @@ @SuppressWarnings("serial") public class NotConnectedException extends TarsException { + private static final long serialVersionUID = 7973911084718606368L; + public NotConnectedException() { super(); } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/NotImplementedException.java b/core/src/main/java/com/qq/tars/rpc/exc/NotImplementedException.java index d65832b5..e0a7777f 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/NotImplementedException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/NotImplementedException.java @@ -19,7 +19,9 @@ @SuppressWarnings("serial") public class NotImplementedException extends UnsupportedOperationException { + private static final String DEFAULT_MESSAGE = "Not implemented"; + private static final long serialVersionUID = 3269390385274778049L; public NotImplementedException() { super(DEFAULT_MESSAGE); diff --git a/core/src/main/java/com/qq/tars/rpc/exc/ServerDecodeException.java b/core/src/main/java/com/qq/tars/rpc/exc/ServerDecodeException.java index 8d4d3d5d..78f61c26 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/ServerDecodeException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/ServerDecodeException.java @@ -19,6 +19,8 @@ @SuppressWarnings("serial") public class ServerDecodeException extends ServerException { + private static final long serialVersionUID = 4753766342873601126L; + public ServerDecodeException(int ret) { super(ret); } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/ServerEncodeException.java b/core/src/main/java/com/qq/tars/rpc/exc/ServerEncodeException.java index 7df00a60..e6a5a88c 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/ServerEncodeException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/ServerEncodeException.java @@ -19,6 +19,8 @@ @SuppressWarnings("serial") public class ServerEncodeException extends ServerException { + private static final long serialVersionUID = 1423222503492781998L; + public ServerEncodeException(int ret) { super(ret); } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/ServerException.java b/core/src/main/java/com/qq/tars/rpc/exc/ServerException.java index 27b164e7..ca64d6e3 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/ServerException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/ServerException.java @@ -21,7 +21,8 @@ @SuppressWarnings("serial") public class ServerException extends TarsException { - private int ret; + private static final long serialVersionUID = 5930969532642083140L; + private final int ret; public ServerException(int ret) { super("server error code " + ret); @@ -54,6 +55,10 @@ public static TarsException makeException(int ret, String message) { return new ServerQueueTimeoutException(ret, message); } else if (ret == SERVERRESETGRID) { return new ServerResetGridException(ret, message); + } else if (ret == SERVEROVERLOAD) { + return new ServerOverloadException(ret, message); + } else if (ret == SERVERUNCATCHEDERR) { + return new ServerImpException(ret, message); } else { return new ServerUnknownException(ret, message); } diff --git a/net/src/main/java/com/qq/tars/net/core/SessionEvent.java b/core/src/main/java/com/qq/tars/rpc/exc/ServerImpException.java similarity index 71% rename from net/src/main/java/com/qq/tars/net/core/SessionEvent.java rename to core/src/main/java/com/qq/tars/rpc/exc/ServerImpException.java index 66b05fe9..3806c743 100644 --- a/net/src/main/java/com/qq/tars/net/core/SessionEvent.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/ServerImpException.java @@ -14,16 +14,17 @@ * specific language governing permissions and limitations under the License. */ -package com.qq.tars.net.core; +package com.qq.tars.rpc.exc; @SuppressWarnings("serial") -public class SessionEvent extends java.util.EventObject { +public class ServerImpException extends ServerException { + private static final long serialVersionUID = 1801985076523243391L; - public SessionEvent(Session source) { - super(source); + public ServerImpException(int ret) { + super(ret); } - public Session getSession() { - return (Session) super.getSource(); + public ServerImpException(int ret, String message) { + super(ret, message); } } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/ServerNoFuncException.java b/core/src/main/java/com/qq/tars/rpc/exc/ServerNoFuncException.java index 70e50d3a..41733c3c 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/ServerNoFuncException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/ServerNoFuncException.java @@ -19,6 +19,8 @@ @SuppressWarnings("serial") public class ServerNoFuncException extends ServerException { + private static final long serialVersionUID = 2293765485015262512L; + public ServerNoFuncException(int ret) { super(ret); } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/ServerNoServantException.java b/core/src/main/java/com/qq/tars/rpc/exc/ServerNoServantException.java index c51245a7..f039a637 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/ServerNoServantException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/ServerNoServantException.java @@ -19,6 +19,9 @@ @SuppressWarnings("serial") public class ServerNoServantException extends ServerException { + + private static final long serialVersionUID = 6855179702862436955L; + public ServerNoServantException(int ret) { super(ret); } diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/ext/ExtendedServantRequest.java b/core/src/main/java/com/qq/tars/rpc/exc/ServerOverloadException.java similarity index 70% rename from core/src/main/java/com/qq/tars/rpc/protocol/ext/ExtendedServantRequest.java rename to core/src/main/java/com/qq/tars/rpc/exc/ServerOverloadException.java index a7a1d6bf..444a0415 100644 --- a/core/src/main/java/com/qq/tars/rpc/protocol/ext/ExtendedServantRequest.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/ServerOverloadException.java @@ -14,15 +14,17 @@ * specific language governing permissions and limitations under the License. */ -package com.qq.tars.rpc.protocol.ext; - -import com.qq.tars.net.core.Session; -import com.qq.tars.rpc.protocol.ServantRequest; +package com.qq.tars.rpc.exc; @SuppressWarnings("serial") -public class ExtendedServantRequest extends ServantRequest implements java.io.Serializable { +public class ServerOverloadException extends ServerException { + + private static final long serialVersionUID = 4753766342873601126L; + public ServerOverloadException(int ret) { + super(ret); + } - public ExtendedServantRequest(Session session) { - super(session); + public ServerOverloadException(int ret, String message) { + super(ret, message); } } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/ServerQueueTimeoutException.java b/core/src/main/java/com/qq/tars/rpc/exc/ServerQueueTimeoutException.java index bcf4cc2c..799fa043 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/ServerQueueTimeoutException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/ServerQueueTimeoutException.java @@ -19,6 +19,8 @@ @SuppressWarnings("serial") public class ServerQueueTimeoutException extends ServerException { + private static final long serialVersionUID = 4284666926468891967L; + public ServerQueueTimeoutException(int ret) { super(ret); } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/ServerResetGridException.java b/core/src/main/java/com/qq/tars/rpc/exc/ServerResetGridException.java index 558b3b24..acb88af6 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/ServerResetGridException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/ServerResetGridException.java @@ -19,6 +19,8 @@ @SuppressWarnings("serial") public class ServerResetGridException extends ServerException { + private static final long serialVersionUID = 7866797885484717537L; + public ServerResetGridException(int ret) { super(ret); } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/ServerUnknownException.java b/core/src/main/java/com/qq/tars/rpc/exc/ServerUnknownException.java index 8ae03d5d..e57c2eb0 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/ServerUnknownException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/ServerUnknownException.java @@ -19,6 +19,9 @@ @SuppressWarnings("serial") public class ServerUnknownException extends ServerException { + + private static final long serialVersionUID = -1801985076523243390L; + public ServerUnknownException(int ret) { super(ret); } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/ServiceNotFoundException.java b/core/src/main/java/com/qq/tars/rpc/exc/ServiceNotFoundException.java index 0be2845f..38d887f3 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/ServiceNotFoundException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/ServiceNotFoundException.java @@ -16,6 +16,9 @@ package com.qq.tars.rpc.exc; public class ServiceNotFoundException extends TarsException { + + private static final long serialVersionUID = 7206643109167131022L; + public ServiceNotFoundException(String msg) { super(msg); } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/TimeoutException.java b/core/src/main/java/com/qq/tars/rpc/exc/TimeoutException.java index f7320074..7bd7e770 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/TimeoutException.java +++ b/core/src/main/java/com/qq/tars/rpc/exc/TimeoutException.java @@ -20,6 +20,8 @@ @SuppressWarnings("serial") public class TimeoutException extends TarsException { + private static final long serialVersionUID = 6628411140248998251L; + public TimeoutException() { super(); } diff --git a/core/src/main/java/com/qq/tars/rpc/ext/ExtendedProtocolCodecWrapper.java b/core/src/main/java/com/qq/tars/rpc/ext/ExtendedProtocolCodecWrapper.java deleted file mode 100644 index 4524c4c2..00000000 --- a/core/src/main/java/com/qq/tars/rpc/ext/ExtendedProtocolCodecWrapper.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.ext; - -import com.qq.tars.net.core.IoBuffer; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; -import com.qq.tars.net.protocol.ProtocolDecoder; -import com.qq.tars.net.protocol.ProtocolEncoder; -import com.qq.tars.net.protocol.ProtocolException; -import com.qq.tars.rpc.protocol.Codec; - -public class ExtendedProtocolCodecWrapper implements ProtocolEncoder, ProtocolDecoder { - - protected Codec codec = null; - - public ExtendedProtocolCodecWrapper(Codec codec) { - this.codec = codec; - } - - @Override - public IoBuffer encodeResponse(Response response, Session session) throws ProtocolException { - return codec.encodeResponse(response, session); - } - - @Override - public Request decodeRequest(IoBuffer buffer, Session session) throws ProtocolException { - return codec.decodeRequest(buffer, session); - } - - @Override - public Response decodeResponse(IoBuffer buff, Session session) throws ProtocolException { - return codec.decodeResponse(buff, session); - } - - @Override - public IoBuffer encodeRequest(Request request, Session session) throws ProtocolException { - return codec.encodeRequest(request, session); - } -} diff --git a/core/src/main/java/com/qq/tars/rpc/ext/ExtendedProtocolFactory.java b/core/src/main/java/com/qq/tars/rpc/ext/ExtendedProtocolFactory.java deleted file mode 100644 index 61f3cd81..00000000 --- a/core/src/main/java/com/qq/tars/rpc/ext/ExtendedProtocolFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.ext; - -import com.qq.tars.net.protocol.ProtocolDecoder; -import com.qq.tars.net.protocol.ProtocolEncoder; -import com.qq.tars.net.protocol.ProtocolFactory; -import com.qq.tars.rpc.protocol.Codec; - -public class ExtendedProtocolFactory implements ProtocolFactory { - - private ExtendedProtocolCodecWrapper codecWrapper = null; - - private static ExtendedProtocolFactory instance = null; - - public static final ExtendedProtocolFactory getInstance() { - return instance; - } - - public static final void registerExtendedCodecImpl(Codec codec, String contextName) { - if (instance == null) { - instance = buildExtendedProtocolFactory(codec); - } else { - if (instance.codecWrapper.codec.getClass() != codec.getClass()) { - throw new RuntimeException("Found too many codec implementation classes."); - } - } - } - - public static final ExtendedProtocolFactory buildExtendedProtocolFactory(Codec codec) { - return new ExtendedProtocolFactory(codec); - } - - private ExtendedProtocolFactory(Codec codec) { - this.codecWrapper = new ExtendedProtocolCodecWrapper(codec); - } - - public ProtocolDecoder getDecoder() { - return this.codecWrapper; - } - - public ProtocolEncoder getEncoder() { - return this.codecWrapper; - } -} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/Codec.java b/core/src/main/java/com/qq/tars/rpc/protocol/Codec.java deleted file mode 100644 index 62694af4..00000000 --- a/core/src/main/java/com/qq/tars/rpc/protocol/Codec.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.protocol; - -import com.qq.tars.common.util.Constants; -import com.qq.tars.net.protocol.ProtocolDecoder; -import com.qq.tars.net.protocol.ProtocolEncoder; -import com.qq.tars.net.protocol.ProtocolException; -import com.qq.tars.rpc.protocol.tars.TarsServantResponse; - -import java.lang.reflect.InvocationTargetException; - -public abstract class Codec implements ProtocolEncoder, ProtocolDecoder { - - protected String charsetName = Constants.default_charset_name; - - public Codec(String charsetName) { - this.setCharsetName(charsetName); - } - - public String getCharsetName() { - return charsetName; - } - - public void setCharsetName(String charsetName) { - this.charsetName = charsetName; - } - - public abstract String getProtocol(); -} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/ServantRequest.java b/core/src/main/java/com/qq/tars/rpc/protocol/ServantRequest.java deleted file mode 100644 index 26faa007..00000000 --- a/core/src/main/java/com/qq/tars/rpc/protocol/ServantRequest.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.protocol; - -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Session; - -public abstract class ServantRequest extends Request { - - protected String servantName; - protected String functionName; - - public ServantRequest(Session session) { - super(session); - } - - public String getServantName() { - return servantName; - } - - public void setServantName(String servantName) { - this.servantName = servantName; - } - - public String getFunctionName() { - return functionName; - } - - public void setFunctionName(String functionName) { - this.functionName = functionName; - } -} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/ServantResponse.java b/core/src/main/java/com/qq/tars/rpc/protocol/ServantResponse.java deleted file mode 100644 index 174edd36..00000000 --- a/core/src/main/java/com/qq/tars/rpc/protocol/ServantResponse.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.protocol; - -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; - -public abstract class ServantResponse extends Response { - - public ServantResponse(Session session) { - super(session); - } -} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/exception/ProtocolException.java b/core/src/main/java/com/qq/tars/rpc/protocol/exception/ProtocolException.java new file mode 100644 index 00000000..343bb1e1 --- /dev/null +++ b/core/src/main/java/com/qq/tars/rpc/protocol/exception/ProtocolException.java @@ -0,0 +1,5 @@ +package com.qq.tars.rpc.protocol.exception; + +public class ProtocolException extends Exception { + +} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/ext/ExtendedServant.java b/core/src/main/java/com/qq/tars/rpc/protocol/ext/ExtendedServant.java deleted file mode 100644 index 78e4888f..00000000 --- a/core/src/main/java/com/qq/tars/rpc/protocol/ext/ExtendedServant.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.protocol.ext; - -import com.qq.tars.protocol.annotation.Servant; - -@Servant -public interface ExtendedServant { - - public void process(Res request, Resp response); - -} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/ext/ExtendedServantResponse.java b/core/src/main/java/com/qq/tars/rpc/protocol/ext/ExtendedServantResponse.java deleted file mode 100644 index 465e80dc..00000000 --- a/core/src/main/java/com/qq/tars/rpc/protocol/ext/ExtendedServantResponse.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.protocol.ext; - -import com.qq.tars.net.core.Session; -import com.qq.tars.rpc.protocol.ServantResponse; - -@SuppressWarnings("serial") -public class ExtendedServantResponse extends ServantResponse implements java.io.Serializable { - - private Throwable throwable = null; - - public ExtendedServantResponse(Session session) { - super(session); - } - - public Throwable getThrowable() { - return throwable; - } - - public void setThrowable(Throwable throwable) { - this.throwable = throwable; - } -} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsClientCodec.java b/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsClientCodec.java new file mode 100644 index 00000000..587b4be4 --- /dev/null +++ b/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsClientCodec.java @@ -0,0 +1,35 @@ +package com.qq.tars.rpc.protocol.tars; + +import com.qq.tars.rpc.protocol.Codec; +import io.netty.buffer.ByteBuf; +import io.netty.channel.Channel; + +import java.io.IOException; +import java.nio.charset.Charset; + +public class TarsClientCodec implements Codec { + + public TarsClientCodec(String charsetName) { + + } + + @Override + public void encode(Channel channel, ByteBuf channelBuffer, Object message) throws IOException { + + } + + @Override + public Object decode(Channel channel, ByteBuf buffer) throws IOException { + return null; + } + + @Override + public String getProtocol() { + return null; + } + + @Override + public Charset getCharset() { + return null; + } +} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsCodec.java b/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsCodec.java deleted file mode 100644 index 21f73f05..00000000 --- a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsCodec.java +++ /dev/null @@ -1,547 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - *

- * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - *

- * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - *

- * https://opensource.org/licenses/BSD-3-Clause - *

- * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.protocol.tars; - -import com.qq.tars.common.support.ClassLoaderManager; -import com.qq.tars.common.support.Holder; -import com.qq.tars.common.util.CommonUtils; -import com.qq.tars.common.util.Constants; -import com.qq.tars.common.util.StringUtils; -import com.qq.tars.net.core.IoBuffer; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; -import com.qq.tars.net.protocol.ProtocolException; -import com.qq.tars.protocol.tars.TarsInputStream; -import com.qq.tars.protocol.tars.TarsOutputStream; -import com.qq.tars.protocol.tars.support.TarsMethodInfo; -import com.qq.tars.protocol.tars.support.TarsMethodParameterInfo; -import com.qq.tars.protocol.util.TarsHelper; -import com.qq.tars.protocol.util.TarsUtil; -import com.qq.tars.rpc.protocol.Codec; -import com.qq.tars.rpc.protocol.ServantRequest; -import com.qq.tars.rpc.protocol.ServantResponse; -import com.qq.tars.rpc.protocol.tars.support.AnalystManager; -import com.qq.tars.rpc.protocol.tup.UniAttribute; - -import java.lang.reflect.Method; -import java.nio.ByteBuffer; -import java.util.*; - -public class TarsCodec extends Codec { - - public TarsCodec(String charsetName) { - super(charsetName); - } - - public IoBuffer encodeResponse(Response resp, Session session) throws ProtocolException { - TarsServantResponse response = (TarsServantResponse) resp; - if (response.getPacketType() == TarsHelper.ONEWAY) { - return null; - } - - TarsOutputStream jos = new TarsOutputStream(); - jos.setServerEncoding(charsetName); - try { - jos.getByteBuffer().putInt(0); - jos.write(response.getVersion(), 1); - jos.write(response.getPacketType(), 2); - - if (response.getVersion() == TarsHelper.VERSION) { - jos.write(response.getRequestId(), 3); - jos.write(response.getMessageType(), 4); - jos.write(response.getRet(), 5); - jos.write(encodeResult(response, charsetName), 6); - if (response.getStatus() != null) { - jos.write(response.getStatus(), 7); - } - if (response.getRet() != TarsHelper.SERVERSUCCESS) { - jos.write(StringUtils.isEmpty(response.getRemark()) ? "" : response.getRemark(), 8); - } - } else if (TarsHelper.VERSION2 == response.getVersion() || TarsHelper.VERSION3 == response.getVersion()) { - jos.write(response.getMessageType(), 3); - jos.write(response.getTicketNumber(), 4); - String servantName = response.getRequest().getServantName(); - jos.write(servantName, 5); - jos.write(response.getRequest().getFunctionName(), 6); - jos.write(encodeWupResult(response, charsetName), 7); - jos.write(response.getTimeout(), 8); - if (response.getContext() != null) { - jos.write(response.getContext(), 9); - } - if (response.getStatus() != null) { - jos.write(response.getStatus(), 10); - } - } else { - response.setRet(TarsHelper.SERVERENCODEERR); - System.err.println("un supported protocol, ver=" + response.getVersion()); - } - } catch (Exception ex) { - if (response.getRet() == TarsHelper.SERVERSUCCESS) { - response.setRet(TarsHelper.SERVERENCODEERR); - } - } - ByteBuffer buffer = jos.getByteBuffer(); - int datalen = buffer.position(); - buffer.position(0); - buffer.putInt(datalen); - buffer.position(datalen); - return IoBuffer.wrap(jos.toByteArray()); - } - - protected byte[] encodeResult(TarsServantResponse response, String charsetName) { - TarsServantRequest request = response.getRequest(); - if (TarsHelper.isPing(request.getFunctionName())) { - return new byte[]{}; - } - - TarsOutputStream ajos = new TarsOutputStream(); - ajos.setServerEncoding(charsetName); - - int ret = response.getRet(); - Map methodInfoMap = AnalystManager.getInstance().getMethodMapByName(request.getServantName()); - if (ret == TarsHelper.SERVERSUCCESS && methodInfoMap != null) { - TarsMethodInfo methodInfo = methodInfoMap.get(request.getFunctionName()); - TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); - if (returnInfo != null && returnInfo.getType() != Void.TYPE && response.getResult() != null) { - try { - ajos.write(response.getResult(), methodInfo.getReturnInfo().getOrder()); - } catch (Exception e) { - System.err.println("server encodec response result:" + response.getResult() + " with ex:" + e); - } - } - - Object value = null; - List parametersList = methodInfo.getParametersList(); - for (TarsMethodParameterInfo parameterInfo : parametersList) { - if (TarsHelper.isHolder(parameterInfo.getAnnotations())) { - value = request.getMethodParameters()[parameterInfo.getOrder() - 1]; - if (value != null) { - try { - ajos.write(TarsHelper.getHolderValue(value), parameterInfo.getOrder()); - } catch (Exception e) { - System.err.println("server encodec response holder:" + value + " with ex:" + e); - } - } - } - } - } - return ajos.toByteArray(); - } - - protected byte[] encodeWupResult(TarsServantResponse response, String charsetName) { - TarsServantRequest request = response.getRequest(); - UniAttribute unaOut = new UniAttribute(); - unaOut.setEncodeName(charsetName); - if (response.getVersion() == TarsHelper.VERSION3) { - unaOut.useVersion3(); - } - - int ret = response.getRet(); - Map methodInfoMap = AnalystManager.getInstance().getMethodMapByName(request.getServantName()); - if (ret == TarsHelper.SERVERSUCCESS && methodInfoMap != null) { - TarsMethodInfo methodInfo = methodInfoMap.get(request.getFunctionName()); - TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); - if (returnInfo != null && returnInfo.getType() != Void.TYPE && response.getResult() != null) { - unaOut.put(TarsHelper.STAMP_STRING, response.getResult()); - } - - Object value = null; - List parametersList = methodInfo.getParametersList(); - for (TarsMethodParameterInfo parameterInfo : parametersList) { - if (TarsHelper.isHolder(parameterInfo.getAnnotations())) { - value = request.getMethodParameters()[parameterInfo.getOrder() - 1]; - if (value != null) { - try { - String holderName = TarsHelper.getHolderName(parameterInfo.getAnnotations()); - if (!StringUtils.isEmpty(holderName)) { - unaOut.put(holderName, TarsHelper.getHolderValue(value)); - } - } catch (Exception e) { - System.err.println("server encodec response holder:" + value + " with ex:" + e); - } - } - } - } - } - return unaOut.encode(); - } - - public IoBuffer encodeRequest(Request req, Session session) throws ProtocolException { - TarsServantRequest request = (TarsServantRequest) req; - request.setCharsetName(charsetName); - TarsOutputStream os = new TarsOutputStream(); - os.setServerEncoding(charsetName); - - os.getByteBuffer().putInt(0); - os.write(request.getVersion(), 1); - os.write(request.getPacketType(), 2); - os.write(request.getMessageType(), 3); - os.write(request.getTicketNumber(), 4); - os.write(request.getServantName(), 5); - os.write(request.getFunctionName(), 6); - os.write(encodeRequestParams(request, charsetName), 7); - os.write(request.getTimeout(), 8); - os.write(request.getContext(), 9); - os.write(request.getStatus(), 10); - - os.getByteBuffer().flip(); - - int length = os.getByteBuffer().remaining(); - - os.getByteBuffer().duplicate().putInt(0, length); - if (length > TarsHelper.PACKAGE_MAX_LENGTH || length <= 0) { - throw new ProtocolException("the length header of the package must be between 0~10M bytes. data length:" + Integer.toHexString(length)); - } - return IoBuffer.wrap(os.getByteBuffer()); - } - - protected byte[] encodeRequestParams(TarsServantRequest request, String charsetName) throws ProtocolException { - TarsOutputStream os = new TarsOutputStream(0); - os.setServerEncoding(charsetName); - - TarsMethodInfo methodInfo = request.getMethodInfo(); - List parameterInfoList = methodInfo.getParametersList(); - - Object value = null; - Object[] parameter = request.getMethodParameters(); - for (TarsMethodParameterInfo parameterInfo : parameterInfoList) { - if (TarsHelper.isContext(parameterInfo.getAnnotations()) || TarsHelper.isCallback(parameterInfo.getAnnotations())) { - continue; - } - - value = parameter[request.isAsync() ? parameterInfo.getOrder() : parameterInfo.getOrder() - 1]; - if (TarsHelper.isHolder(parameterInfo.getAnnotations()) && value != null) { - try { - value = TarsHelper.getHolderValue(value); - } catch (Exception e) { - throw new ProtocolException(e); - } - if (value != null) { - os.write(value, parameterInfo.getOrder()); - } - } else if (value != null) { - os.write(value, parameterInfo.getOrder()); - } - } - return os.toByteArray(); - } - - public Request decodeRequest(IoBuffer buffer, Session session) throws ProtocolException { - if (buffer.remaining() < 4) { - return null; - } - int length = buffer.getInt() - TarsHelper.HEAD_SIZE; - if (length > TarsHelper.PACKAGE_MAX_LENGTH || length <= 0) { - throw new ProtocolException("the length header of the package must be between 0~10M bytes. data length:" + Integer.toHexString(length)); - } - if (buffer.remaining() < length) { - return null; - } - - byte[] reads = new byte[length]; - buffer.get(reads); - TarsInputStream jis = new TarsInputStream(reads); - TarsServantRequest request = new TarsServantRequest(session); - try { - short version = jis.read(TarsHelper.STAMP_SHORT.shortValue(), 1, true); - byte packetType = jis.read(TarsHelper.STAMP_BYTE.byteValue(), 2, true); - int messageType = jis.read(TarsHelper.STAMP_INT.intValue(), 3, true); - int requestId = jis.read(TarsHelper.STAMP_INT.intValue(), 4, true); - String servantName = jis.readString(5, true); - String methodName = jis.readString(6, true); - request.setVersion(version); - request.setPacketType(packetType); - request.setMessageType(messageType); - request.setRequestId(requestId); - request.setServantName(servantName); - request.setFunctionName(methodName); - request.setInputStream(jis); - request.setCharsetName(charsetName); - } catch (Exception e) { - System.err.println(e); - request.setRet(TarsHelper.SERVERDECODEERR); - } - return request; - } - - public ServantRequest decodeRequestBody(ServantRequest req) { - TarsServantRequest request = (TarsServantRequest) req; - if (request.getRet() != TarsHelper.SERVERSUCCESS) { - return request; - } - if (TarsHelper.isPing(request.getFunctionName())) { - return request; - } - - TarsInputStream jis = request.getInputStream(); - ClassLoader oldClassLoader = null; - try { - oldClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(resolveProtocolClassLoader()); - String methodName = request.getFunctionName(); - byte[] data = jis.read(TarsHelper.STAMP_BYTE_ARRAY, 7, true);//数据 - int timeout = jis.read(TarsHelper.STAMP_INT.intValue(), 8, true);//超时时间 - Map context = (Map) jis.read(TarsHelper.STAMP_MAP, 9, true);//Map context - Map status = (Map) jis.read(TarsHelper.STAMP_MAP, 10, true); - - request.setTimeout(timeout); - request.setContext(context); - request.setStatus(status); - - String servantName = request.getServantName(); - Map methodInfoMap = AnalystManager.getInstance().getMethodMapByName(servantName); - - if (methodInfoMap == null || methodInfoMap.isEmpty()) { - request.setRet(TarsHelper.SERVERNOSERVANTERR); - throw new ProtocolException("no found methodInfo, the context[ROOT], serviceName[" + servantName + "], methodName[" + methodName + "]"); - } - TarsMethodInfo methodInfo = methodInfoMap.get(methodName); - if (methodInfo == null) { - request.setRet(TarsHelper.SERVERNOFUNCERR); - throw new ProtocolException("no found methodInfo, the context[ROOT], serviceName[" + servantName + "], methodName[" + methodName + "]"); - } - - request.setMethodInfo(methodInfo); - List parametersList = methodInfo.getParametersList(); - if (!CommonUtils.isEmptyCollection(parametersList)) { - Object[] parameters = new Object[parametersList.size()]; - int i = 0; - if (TarsHelper.VERSION == request.getVersion()) {//request - parameters = decodeRequestBody(data, request.getCharsetName(), methodInfo); - } else if (TarsHelper.VERSION2 == request.getVersion() || TarsHelper.VERSION3 == request.getVersion()) { - //wup request - UniAttribute unaIn = new UniAttribute(); - unaIn.setEncodeName(request.getCharsetName()); - - if (request.getVersion() == TarsHelper.VERSION2) { - unaIn.decodeVersion2(data); - } else if (request.getVersion() == TarsHelper.VERSION3) { - unaIn.decodeVersion3(data); - } - - Object value = null; - for (TarsMethodParameterInfo parameterInfo : parametersList) { - if (TarsHelper.isHolder(parameterInfo.getAnnotations())) { - String holderName = TarsHelper.getHolderName(parameterInfo.getAnnotations()); - if (!StringUtils.isEmpty(holderName)) { - value = new Holder(unaIn.getByClass(holderName, parameterInfo.getStamp())); - } else { - value = new Holder(); - } - } else { - value = unaIn.getByClass(parameterInfo.getName(), parameterInfo.getStamp()); - } - parameters[i++] = value; - } - } else { - request.setRet(TarsHelper.SERVERDECODEERR); - System.err.println("un supported protocol, ver=" + request.getVersion()); - } - request.setMethodParameters(parameters); - } - } catch (Throwable ex) { - if (request.getRet() == TarsHelper.SERVERSUCCESS) { - request.setRet(TarsHelper.SERVERDECODEERR); - } - System.err.println(TarsUtil.getHexdump(jis.getBs())); - } finally { - if (oldClassLoader != null) { - Thread.currentThread().setContextClassLoader(oldClassLoader); - } - } - return request; - } - - protected Object[] decodeRequestBody(byte[] data, String charset, TarsMethodInfo methodInfo) throws Exception { - TarsInputStream jis = new TarsInputStream(data); - List parametersList = methodInfo.getParametersList(); - Object[] parameters = new Object[parametersList.size()]; - int i = 0; - - jis.setServerEncoding(charset);//set decode charset name - Object value = null; - for (TarsMethodParameterInfo parameterInfo : parametersList) { - if (TarsHelper.isHolder(parameterInfo.getAnnotations())) { - value = new Holder(jis.read(parameterInfo.getStamp(), parameterInfo.getOrder(), false)); - } else { - value = jis.read(parameterInfo.getStamp(), parameterInfo.getOrder(), false); - } - parameters[i++] = value; - } - - return parameters; - } - - public Response decodeResponse(IoBuffer buffer, Session session) throws ProtocolException { - if (buffer.remaining() < TarsHelper.HEAD_SIZE) { - return null; - } - - int length = buffer.getInt() - TarsHelper.HEAD_SIZE; - if (length > TarsHelper.PACKAGE_MAX_LENGTH || length <= 0) { - throw new ProtocolException("the length header of the package must be between 0~10M bytes. data length:" + Integer.toHexString(length)); - } - if (buffer.remaining() < length) { - return null; - } - - byte[] bytes = new byte[length]; - buffer.get(bytes); - - TarsServantResponse response = new TarsServantResponse(session); - response.setCharsetName(charsetName); - - TarsInputStream is = new TarsInputStream(bytes); - is.setServerEncoding(charsetName); - - response.setVersion(is.read((short) 0, 1, true)); - response.setPacketType(is.read((byte) 0, 2, true)); - response.setRequestId(is.read((int) 0, 3, true)); - response.setMessageType(is.read((int) 0, 4, true)); - response.setRet(is.read((int) 0, 5, true)); - if (response.getRet() == TarsHelper.SERVERSUCCESS) { - response.setInputStream(is); - } - - return response; - } - - public void decodeResponseBody(ServantResponse resp) throws ProtocolException { - TarsServantResponse response = (TarsServantResponse) resp; - - TarsServantRequest request = response.getRequest(); - if (request.isAsync()) { - return; - } - TarsInputStream is = response.getInputStream(); - - byte[] data = is.read(new byte[]{}, 6, true); - TarsInputStream jis = new TarsInputStream(data); - jis.setServerEncoding(response.getCharsetName()); - - TarsMethodInfo methodInfo = request.getMethodInfo(); - TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); - - Object[] results; - try { - results = decodeResponseBody(data, response.getCharsetName(), methodInfo); - } catch (Exception e) { - throw new ProtocolException(e); - } - - int i = 0; - if (returnInfo != null && Void.TYPE != returnInfo.getType()) { - response.setResult(results[i++]); - } - - List list = methodInfo.getParametersList(); - for (TarsMethodParameterInfo info : list) { - if (!TarsHelper.isHolder(info.getAnnotations())) { - continue; - } - try { - TarsHelper.setHolderValue(request.getMethodParameters()[info.getOrder() - 1], results[i++]); - } catch (Exception e) { - throw new ProtocolException(e); - } - } - response.setStatus((HashMap) is.read(TarsHelper.STAMP_MAP, 7, false)); - } - - protected Object[] decodeResponseBody(byte[] data, String charset, TarsMethodInfo methodInfo) throws Exception { - TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); - List values = new ArrayList(); - - TarsInputStream jis = new TarsInputStream(data); - jis.setServerEncoding(charset); - - if (returnInfo != null && Void.TYPE != returnInfo.getType()) { - values.add(jis.read(returnInfo.getStamp(), returnInfo.getOrder(), true)); - } - - List list = methodInfo.getParametersList(); - for (TarsMethodParameterInfo info : list) { - if (!TarsHelper.isHolder(info.getAnnotations())) { - continue; - } - try { - values.add(jis.read(info.getStamp(), info.getOrder(), true)); - } catch (Exception e) { - throw new ProtocolException(e); - } - } - return values.toArray(); - } - - public Object[] decodeCallbackArgs(TarsServantResponse response) throws ProtocolException { - byte[] data = response.getInputStream().read(new byte[]{}, 6, true); - - TarsServantRequest request = response.getRequest(); - - TarsMethodInfo methodInfo = null; - Map map = AnalystManager.getInstance().getMethodMap(request.getApi()); - for (Iterator> it = map.entrySet().iterator(); it.hasNext(); ) { - Map.Entry entry = it.next(); - if (entry.getKey().getName().equals(request.getFunctionName())) { - methodInfo = entry.getValue(); - } - } - - try { - return decodeCallbackArgs(data, response.getCharsetName(), methodInfo); - } catch (Exception e) { - throw new ProtocolException(e); - } - } - - protected Object[] decodeCallbackArgs(byte[] data, String charset, TarsMethodInfo methodInfo) throws ProtocolException, NoSuchMethodException, Exception { - TarsInputStream jis = new TarsInputStream(data); - jis.setServerEncoding(charset); - - List list = new ArrayList(); - TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); - if (returnInfo != null && Void.TYPE != returnInfo.getType()) { - list.add(jis.read(returnInfo.getStamp(), returnInfo.getOrder(), true)); - } - - List parameterInfoList = methodInfo.getParametersList(); - for (TarsMethodParameterInfo info : parameterInfoList) { - if (TarsHelper.isContext(info.getAnnotations()) || TarsHelper.isCallback(info.getAnnotations())) { - continue; - } - - if (TarsHelper.isHolder(info.getAnnotations())) { - list.add(jis.read(info.getStamp(), info.getOrder(), false)); - } - } - - return list.toArray(); - } - - protected ClassLoader resolveProtocolClassLoader() { - ClassLoader classLoader = ClassLoaderManager.getInstance().getClassLoader(""); - if (classLoader == null) { - classLoader = Thread.currentThread().getContextClassLoader(); - } - return classLoader; - } - - public String getProtocol() { - return Constants.TARS_PROTOCOL; - } -} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsCodecHelper.java b/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsCodecHelper.java index 4b15cbfb..c2cd4407 100644 --- a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsCodecHelper.java +++ b/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsCodecHelper.java @@ -16,39 +16,66 @@ package com.qq.tars.rpc.protocol.tars; -import java.lang.reflect.Method; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import com.qq.tars.common.support.ClassLoaderManager; -import com.qq.tars.common.support.Holder; +import com.qq.tars.common.util.BeanAccessor; import com.qq.tars.common.util.CommonUtils; -import com.qq.tars.common.util.StringUtils; -import com.qq.tars.net.core.IoBuffer; -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; -import com.qq.tars.net.protocol.ProtocolException; import com.qq.tars.protocol.tars.TarsInputStream; import com.qq.tars.protocol.tars.TarsOutputStream; import com.qq.tars.protocol.tars.support.TarsMethodInfo; import com.qq.tars.protocol.tars.support.TarsMethodParameterInfo; import com.qq.tars.protocol.util.TarsHelper; -import com.qq.tars.protocol.util.TarsUtil; +import com.qq.tars.rpc.protocol.exception.ProtocolException; import com.qq.tars.rpc.protocol.tars.support.AnalystManager; -import com.qq.tars.rpc.protocol.tup.UniAttribute; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; @SuppressWarnings("unchecked") public class TarsCodecHelper { + TarsOutputStream os = new TarsOutputStream(); + + + public static Object decodePromiseResult(TarsServantResponse response) throws ProtocolException { + TarsInputStream is = response.getInputStream(); + TarsInputStream jis = new TarsInputStream(is.read(new byte[]{}, 6, true)); + jis.setServerEncoding(response.getCharsetName()); + + response.setStatus((HashMap) is.read(TarsHelper.STAMP_MAP, 7, false)); + response.setRemark(is.readString(8, false)); + response.setContext((HashMap) is.read(TarsHelper.STAMP_MAP, 9, false)); + + TarsServantRequest request = (TarsServantRequest) response.getRequest(); + + Map map = AnalystManager.getInstance().getMethodMapByName(request.getServantName()); + TarsMethodInfo methodInfo = map.get(request.getFunctionName()); + TarsMethodInfo futureMethodInfo = request.getMethodInfo(); + Object result = CommonUtils.newInstance(futureMethodInfo.getReturnInfo().getStamp().getClass()); + + //response data + TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); + if (returnInfo != null && Void.TYPE != returnInfo.getType()) { + Object obj = jis.read(returnInfo.getStamp(), returnInfo.getOrder(), true); + BeanAccessor.setBeanValue(result, futureMethodInfo.getReturnInfo().getName(), obj); + } + + //read holder + List parameterInfoList = methodInfo.getParametersList(); + for (TarsMethodParameterInfo info : parameterInfoList) { + if (TarsHelper.isContext(info.getAnnotations()) || TarsHelper.isCallback(info.getAnnotations())) { + continue; + } + + if (TarsHelper.isHolder(info.getAnnotations())) { + Object obj = jis.read(info.getStamp(), info.getOrder(), false); + BeanAccessor.setBeanValue(result, info.getName(), obj); + } + } + return result; + } /* public static IoBuffer encodeRequest(TarsServantRequest request, Session session, String charsetName) throws ProtocolException { request.setCharsetName(charsetName); - TarsOutputStream os = new TarsOutputStream(); os.setServerEncoding(charsetName); os.getByteBuffer().putInt(0); diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServerCodec.java b/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServerCodec.java new file mode 100644 index 00000000..1db8af56 --- /dev/null +++ b/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServerCodec.java @@ -0,0 +1,37 @@ +package com.qq.tars.rpc.protocol.tars; + +import com.qq.tars.rpc.protocol.Codec; +import io.netty.buffer.ByteBuf; +import io.netty.channel.Channel; + +import java.io.IOException; +import java.nio.charset.Charset; + +public class TarsServerCodec implements Codec { + + private String charsetName; + + public TarsServerCodec(String charsetName) { + this.charsetName = charsetName; + } + + @Override + public void encode(Channel channel, ByteBuf channelBuffer, Object message) throws IOException { + + } + + @Override + public Object decode(Channel channel, ByteBuf buffer) throws IOException { + return null; + } + + @Override + public String getProtocol() { + return null; + } + + @Override + public Charset getCharset() { + return null; + } +} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tars/support/TarsAbstractCallback.java b/core/src/main/java/com/qq/tars/rpc/protocol/tars/support/TarsAbstractCallback.java deleted file mode 100644 index 52840bb0..00000000 --- a/core/src/main/java/com/qq/tars/rpc/protocol/tars/support/TarsAbstractCallback.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.protocol.tars.support; - -import java.lang.reflect.Method; - -import com.qq.tars.protocol.tars.annotation.TarsCallback; -import com.qq.tars.rpc.exc.ClientException; -import com.qq.tars.rpc.protocol.Codec; -import com.qq.tars.rpc.protocol.tars.TarsCodec; -import com.qq.tars.rpc.protocol.tars.TarsCodecHelper; -import com.qq.tars.rpc.protocol.tars.TarsServantRequest; -import com.qq.tars.rpc.protocol.tars.TarsServantResponse; - -@TarsCallback(comment = "Callback") -public abstract class TarsAbstractCallback implements com.qq.tars.net.client.Callback { - - @Override - public final void onCompleted(TarsServantResponse response) { - TarsServantRequest request = response.getRequest(); - try { - Method callback = getCallbackMethod("callback_".concat(request.getFunctionName())); - callback.setAccessible(true); - callback.invoke(this, ((TarsCodec) response.getSession().getProtocolFactory().getDecoder()).decodeCallbackArgs(response)); - } catch (Throwable ex) { - throw new ClientException(ex); - } - } - - private Method getCallbackMethod(String methodName) throws NoSuchMethodException { - Method[] methods = getClass().getDeclaredMethods(); - for (Method method : methods) { - if (methodName.equals(method.getName())) { - return method; - } - } - throw new NoSuchMethodException("no such method " + methodName); - } - - @Override - public final void onException(Throwable ex) { - callback_exception(ex); - } - - @Override - public final void onExpired() { - callback_expired(); - } - - public abstract void callback_exception(Throwable ex); - - public abstract void callback_expired(); -} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tup/BasicClassTypeUtil.java b/core/src/main/java/com/qq/tars/rpc/protocol/tup/BasicClassTypeUtil.java deleted file mode 100644 index 0b5ae7b0..00000000 --- a/core/src/main/java/com/qq/tars/rpc/protocol/tup/BasicClassTypeUtil.java +++ /dev/null @@ -1,333 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.protocol.tup; - -import java.lang.reflect.Array; -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class BasicClassTypeUtil { - - private static void addType(ArrayList list, String type) { - int point = type.length(); - while (type.charAt(point - 1) == '>') { - point--; - if (point == 0) { - break; - } - } - list.add(0, uni2JavaType(type.substring(0, point))); - } - - public static ArrayList getTypeList(String fullType) { - ArrayList type = new ArrayList(); - int point = 0; - int splitPoint = fullType.indexOf("<"); - int mapPoint = -1; - while (point < splitPoint) { - addType(type, fullType.substring(point, splitPoint)); - point = splitPoint + 1; - splitPoint = fullType.indexOf("<", point); - mapPoint = fullType.indexOf(",", point); - if (splitPoint == -1) { - splitPoint = mapPoint; - } - if (mapPoint != -1 && mapPoint < splitPoint) { - splitPoint = mapPoint; - } - } - addType(type, fullType.substring(point, fullType.length())); - return type; - } - - public static void main(String[] args) { - ArrayList src = new ArrayList(); - src.add("char"); - src.add("list"); - src.add("list>"); - src.add("map"); - src.add("map>>"); - src.add("map>"); - src.add("map"); - - for (String ss : src) { - ArrayList list = getTypeList(ss); - for (String s : list) { - System.out.println(s); - } - Collections.reverse(list); - System.out.println("-------------finished " + transTypeList(list)); - } - } - - public static String transTypeList(ArrayList listTpye) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < listTpye.size(); i++) { - listTpye.set(i, java2UniType(listTpye.get(i))); - } - Collections.reverse(listTpye); - for (int i = 0; i < listTpye.size(); i++) { - String type = listTpye.get(i); - if (type.equals("list")) { - listTpye.set(i - 1, "<" + listTpye.get(i - 1)); - listTpye.set(0, listTpye.get(0) + ">"); - } else if (type.equals("map")) { - listTpye.set(i - 1, "<" + listTpye.get(i - 1) + ","); - listTpye.set(0, listTpye.get(0) + ">"); - } else if (type.equals("Array")) { - listTpye.set(i - 1, "<" + listTpye.get(i - 1)); - listTpye.set(0, listTpye.get(0) + ">"); - } - } - Collections.reverse(listTpye); - for (String s : listTpye) { - sb.append(s); - } - return sb.toString(); - } - - public static Object createClassByUni(String className) throws ObjectCreateException { - ArrayList list = getTypeList(className); - Object last = null; - Object last2 = null; - Object returnObject = null; - for (String name : list) { - returnObject = createClassByName(name); - - if (returnObject instanceof String) { - if ("Array".equals((String) (returnObject))) { - if (last == null) { - returnObject = Array.newInstance(Byte.class, 0); - } - } else if ("?".equals((String) (returnObject))) { - - } else { - if (last == null) { - last = returnObject; - } else { - last2 = last; - last = returnObject; - } - } - } else if (returnObject instanceof List) { - if (null != last && last instanceof Byte) { - returnObject = Array.newInstance(Byte.class, 1); - Array.set(returnObject, 0, last); - } else { - if (last != null) { - ((List) returnObject).add(last); - } else { - - } - last = null; - } - } else if (returnObject instanceof Map) { - if (last != null & last2 != null) { - ((Map) returnObject).put(last, last2); - } else { - - } - last = null; - last2 = null; - } else { - if (last == null) { - last = returnObject; - } else { - last2 = last; - last = returnObject; - } - } - } - return returnObject; - } - - public static Object createClassByName(String name) throws ObjectCreateException { - if (name.equals("java.lang.Integer")) { - return 0; - } else if (name.equals("java.lang.Boolean")) { - return false; - } else if (name.equals("java.lang.Byte")) { - return (byte) 0; - } else if (name.equals("java.lang.Double")) { - return (double) 0; - } else if (name.equals("java.lang.Float")) { - return (float) 0; - } else if (name.equals("java.lang.Long")) { - return (long) 0; - } else if (name.equals("java.lang.Short")) { - return (short) 0; - } else if (name.equals("java.lang.Character")) { - throw new java.lang.IllegalArgumentException("can not support java.lang.Character"); - } else if (name.equals("java.lang.String")) { - return ""; - } else if (name.equals("java.util.List")) { - return new ArrayList(); - } else if (name.equals("java.util.Map")) { - return new HashMap(); - } else if (name.equals("Array")) { - return "Array"; - } else if (name.equals("?")) { - return name; - } else { - try { - Class newoneClass = Class.forName(name); - Constructor cons = newoneClass.getConstructor(); - return cons.newInstance(); - } catch (Exception e) { - throw new ObjectCreateException(e); - } - } - } - - public static String java2UniType(String srcType) { - if (srcType.equals("java.lang.Integer") || srcType.equals("int")) { - return "int32"; - } else if (srcType.equals("java.lang.Boolean") || srcType.equals("boolean")) { - return "bool"; - } else if (srcType.equals("java.lang.Byte") || srcType.equals("byte")) { - return "char"; - } else if (srcType.equals("java.lang.Double") || srcType.equals("double")) { - return "double"; - } else if (srcType.equals("java.lang.Float") || srcType.equals("float")) { - return "float"; - } else if (srcType.equals("java.lang.Long") || srcType.equals("long")) { - return "int64"; - } else if (srcType.equals("java.lang.Short") || srcType.equals("short")) { - return "short"; - } else if (srcType.equals("java.lang.Character")) { - throw new java.lang.IllegalArgumentException("can not support java.lang.Character"); - } else if (srcType.equals("java.lang.String")) { - return "string"; - } else if (srcType.equals("java.util.List")) { - return "list"; - } else if (srcType.equals("java.util.Map")) { - return "map"; - } else { - return srcType; - } - } - - public static String uni2JavaType(String srcType) { - if (srcType.equals("int32")) { - return "java.lang.Integer"; - } else if (srcType.equals("bool")) { - return "java.lang.Boolean"; - } else if (srcType.equals("char")) { - return "java.lang.Byte"; - } else if (srcType.equals("double")) { - return "java.lang.Double"; - } else if (srcType.equals("float")) { - return "java.lang.Float"; - } else if (srcType.equals("int64")) { - return "java.lang.Long"; - } else if (srcType.equals("short")) { - return "java.lang.Short"; - } else if (srcType.equals("string")) { - return "java.lang.String"; - } else if (srcType.equals("list")) { - return "java.util.List"; - } else if (srcType.equals("map")) { - return "java.util.Map"; - } else { - return srcType; - } - } - - public static boolean isBasicType(String name) { - if (name.equals("int")) { - return true; - } else if (name.equals("boolean")) { - return true; - } else if (name.equals("byte")) { - return true; - } else if (name.equals("double")) { - return true; - } else if (name.equals("float")) { - return true; - } else if (name.equals("long")) { - return true; - } else if (name.equals("short")) { - return true; - } else if (name.equals("char")) { - return true; - } else if (name.equals("Integer")) { - return true; - } else if (name.equals("Boolean")) { - return true; - } else if (name.equals("Byte")) { - return true; - } else if (name.equals("Double")) { - return true; - } else if (name.equals("Float")) { - return true; - } else if (name.equals("Long")) { - return true; - } else if (name.equals("Short")) { - return true; - } else if (name.equals("Char")) { - return true; - } - return false; - } - - public static String getClassTransName(String name) { - if (name.equals("int")) { - name = "Integer"; - } else if (name.equals("boolean")) { - name = "Boolean"; - } else if (name.equals("byte")) { - name = "Byte"; - } else if (name.equals("double")) { - name = "Double"; - } else if (name.equals("float")) { - name = "Float"; - } else if (name.equals("long")) { - name = "Long"; - } else if (name.equals("short")) { - name = "Short"; - } else if (name.equals("char")) { - name = "Character"; - } - return name; - } - - public static String getVariableInit(String name, String type) { - if (type.equals("int")) { - return type + " " + name + "=0 ;\n"; - } else if (type.equals("boolean")) { - return type + " " + name + "=false ;\n"; - } else if (type.equals("byte")) { - return type + " " + name + " ;\n"; - } else if (type.equals("double")) { - return type + " " + name + "=0 ;\n"; - } else if (type.equals("float")) { - return type + " " + name + "=0 ;\n"; - } else if (type.equals("long")) { - return type + " " + name + "=0 ;\n"; - } else if (type.equals("short")) { - return type + " " + name + "=0 ;\n"; - } else if (type.equals("char")) { - return type + " " + name + " ;\n"; - } else { - return type + " " + name + " = null ;\n"; - } - } -} diff --git a/core/src/main/java/com/qq/tars/server/apps/BaseAppContext.java b/core/src/main/java/com/qq/tars/server/apps/BaseAppContext.java index f482beba..d7e4e656 100644 --- a/core/src/main/java/com/qq/tars/server/apps/BaseAppContext.java +++ b/core/src/main/java/com/qq/tars/server/apps/BaseAppContext.java @@ -18,36 +18,49 @@ import com.qq.tars.common.Filter; import com.qq.tars.common.FilterKind; -import com.qq.tars.rpc.protocol.ext.ExtendedServant; import com.qq.tars.rpc.protocol.tars.support.AnalystManager; import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.server.config.ServantAdapterConfig; import com.qq.tars.server.config.ServerConfig; -import com.qq.tars.server.core.*; -import com.qq.tars.support.admin.AdminFServant; +import com.qq.tars.server.core.Adapter; +import com.qq.tars.server.core.AppContext; +import com.qq.tars.server.core.AppContextListener; +import com.qq.tars.server.core.AppContextManager; +import com.qq.tars.server.core.AppService; +import com.qq.tars.server.core.ServantAdapter; +import com.qq.tars.server.core.ServantHomeSkeleton; import com.qq.tars.support.admin.impl.AdminFServantImpl; +import com.qq.tars.support.admin.AdminFServant; import com.qq.tars.support.om.OmConstants; import com.qq.tars.support.trace.TraceCallbackFilter; import com.qq.tars.support.trace.TraceClientFilter; import com.qq.tars.support.trace.TraceServerFilter; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public abstract class BaseAppContext implements AppContext { boolean ready = true; - ConcurrentHashMap skeletonMap = new ConcurrentHashMap(); - ConcurrentHashMap servantAdapterMap = new ConcurrentHashMap(); + public ConcurrentHashMap skeletonMap = new ConcurrentHashMap<>(); + public ConcurrentHashMap servantAdapterMap = new ConcurrentHashMap<>(); + + HashMap contextParams = new HashMap<>(); - HashMap contextParams = new HashMap(); + Set listeners = new HashSet<>(4); - Set listeners = new HashSet(4); - - Map> filters = new HashMap>(); + Map> filters = new HashMap<>(); - BaseAppContext() { + protected BaseAppContext() { + this.filters.put(FilterKind.SERVER, new LinkedList<>()); + this.filters.put(FilterKind.CLIENT, new LinkedList<>()); + this.filters.put(FilterKind.CALLBACK, new LinkedList<>()); } @Override @@ -62,7 +75,7 @@ public void init() { } catch (Exception ex) { ready = false; ex.printStackTrace(); - System.out.println("[SERVER] failed to start the applicaton."); + System.out.println("[SERVER] failed to start the application."); } } @@ -78,7 +91,8 @@ public void stop() { void injectAdminServant() { try { String skeletonName = OmConstants.AdminServant; - ServantHomeSkeleton skeleton = new ServantHomeSkeleton(skeletonName, new AdminFServantImpl(), AdminFServant.class, null, null, -1); + ServantHomeSkeleton skeleton = new ServantHomeSkeleton(skeletonName, + new AdminFServantImpl(), AdminFServant.class, -1); skeleton.setAppContext(this); ServerConfig serverCfg = ConfigurationManager.getInstance().getServerConfig(); @@ -88,7 +102,7 @@ void injectAdminServant() { servantAdapterMap.put(skeletonName, servantAdapter); skeletonMap.put(skeletonName, skeleton); - } catch (Exception e) { + } catch (Throwable e) { System.err.println("init om service failed:context=[]"); e.printStackTrace(); } @@ -105,9 +119,6 @@ void initServants() { ServantHomeSkeleton skeleton = skeletonMap.get(skeletonName); Class api = skeleton.getApiClass(); try { - if (api.isAssignableFrom(ExtendedServant.class)) { - continue; - } AnalystManager.getInstance().registry(name(), api, skeleton.name()); } catch (Exception e) { System.err.println("app[] init servant[" + api.getName() + "] failed"); @@ -115,26 +126,22 @@ void initServants() { } } } - + void loadDefaultFilter() { - filters.put(FilterKind.SERVER, new LinkedList()); - filters.put(FilterKind.CLIENT, new LinkedList()); - filters.put(FilterKind.CALLBACK, new LinkedList()); - - List serverFilters = filters.get(FilterKind.SERVER); - Filter traceServerFilter = new TraceServerFilter(); - traceServerFilter.init(); - serverFilters.add(traceServerFilter); - - List clientFilters = filters.get(FilterKind.CLIENT); - Filter traceClientFilter = new TraceClientFilter(); - traceClientFilter.init(); - clientFilters.add(traceClientFilter); - - List callbackFilters = filters.get(FilterKind.CALLBACK); - Filter traceCallbackFilter = new TraceCallbackFilter(); - traceCallbackFilter.init(); - callbackFilters.add(traceCallbackFilter); + List serverFilters = filters.get(FilterKind.SERVER); + Filter traceServerFilter = new TraceServerFilter(); + traceServerFilter.init(); + serverFilters.add(traceServerFilter); + + List clientFilters = filters.get(FilterKind.CLIENT); + Filter traceClientFilter = new TraceClientFilter(); + traceClientFilter.init(); + clientFilters.add(traceClientFilter); + + List callbackFilters = filters.get(FilterKind.CALLBACK); + Filter traceCallbackFilter = new TraceCallbackFilter(); + traceCallbackFilter.init(); + callbackFilters.add(traceCallbackFilter); } void appContextStarted() { @@ -147,11 +154,6 @@ void setAppContext() { AppContextManager.getInstance().setAppContext(this); } - @Override - public String getInitParameter(String name) { - return contextParams.get(name); - } - @Override public String name() { return ""; @@ -164,12 +166,18 @@ public ServantHomeSkeleton getCapHomeSkeleton(String homeName) { } return skeletonMap.get(homeName); } - + @Override public List getFilters(FilterKind kind) { if (!ready) { throw new RuntimeException("The application isn't started."); } - return filters.get(kind); + return filters.get(kind); + } + + @Override + public void addFilter(FilterKind kind, Filter filter) { + List filters = this.filters.get(kind); + filters.add(filter); } } diff --git a/core/src/main/java/com/qq/tars/server/apps/XmlAppContext.java b/core/src/main/java/com/qq/tars/server/apps/XmlAppContext.java deleted file mode 100644 index 571e87d1..00000000 --- a/core/src/main/java/com/qq/tars/server/apps/XmlAppContext.java +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.server.apps; - -import com.qq.tars.common.util.StringUtils; -import com.qq.tars.net.core.Processor; -import com.qq.tars.protocol.annotation.Servant; -import com.qq.tars.protocol.util.TarsHelper; -import com.qq.tars.rpc.protocol.Codec; -import com.qq.tars.server.common.XMLConfigElement; -import com.qq.tars.server.common.XMLConfigFile; -import com.qq.tars.server.config.ConfigurationManager; -import com.qq.tars.server.config.ServantAdapterConfig; -import com.qq.tars.server.config.ServerConfig; -import com.qq.tars.server.core.AppContextListener; -import com.qq.tars.server.core.ServantAdapter; -import com.qq.tars.server.core.ServantHomeSkeleton; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; - -public class XmlAppContext extends BaseAppContext { - public XmlAppContext() { - } - - @Override - protected void loadServants() throws Exception { - XMLConfigFile cfg = new XMLConfigFile(); - cfg.parse(getClass().getClassLoader().getResource("servants.xml").openStream()); - XMLConfigElement root = cfg.getRootElement(); - ArrayList elements = root.getChildList(); - - loadInitParams(root.getChildListByName("context-param")); - - loadAppContextListeners(elements); - - loadAppServants(elements); - - loadDefaultFilter(); - - loadAppFilters(elements); - - } - - private void loadInitParams(ArrayList list) { - if (list == null || list.isEmpty()) return; - for (XMLConfigElement e : list) { - String name = getChildNodeValue(e, "param-name"); - String value = getChildNodeValue(e, "param-value"); - if (!StringUtils.isEmpty(name)) contextParams.put(name, value); - } - } - - private void loadAppContextListeners(ArrayList elements) { - for (XMLConfigElement element : elements) { - if ("listener".equals(element.getName())) { - String listenerClass = getChildNodeValue(element, "listener-class"); - AppContextListener listener; - - try { - listener = (AppContextListener) Class.forName(listenerClass).newInstance(); - listeners.add(listener); - } catch (ClassNotFoundException e) { - System.err.println("invalid listener config|ClassNotFoundException:" + listenerClass); - } catch (ClassCastException e) { - System.err.println("invalid listener config|It is NOT a ContextListener:" + listenerClass); - } catch (Exception e) { - System.err.println("create listener instance failed."); - } - } - } - } - private void loadAppFilters(ArrayList list) { - - } - - private void loadAppServants(ArrayList elements) throws ClassNotFoundException, InstantiationException, IllegalAccessException { - for (XMLConfigElement element : elements) { - if ("servant".equals(element.getName())) { - try { - ServantHomeSkeleton skeleton = loadServant(element); - skeletonMap.put(skeleton.name(), skeleton); - appServantStarted(skeleton); - } catch (Exception e) { - System.err.println("init a service failed:context=[]"); - } - } - } - } - - @SuppressWarnings("unchecked") - private ServantHomeSkeleton loadServant(XMLConfigElement element) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException { - String homeName = null, homeApiName = null, homeClassName = null, processorClazzName = null, - codecClazzName = null; - Class homeApiClazz = null; - Class codecClazz = null; - Class processorClazz = null; - Object homeClassImpl = null; - ServantHomeSkeleton skeleton = null; - int maxLoadLimit = -1; - - ServerConfig serverCfg = ConfigurationManager.getInstance().getServerConfig(); - - homeName = element.getStringAttribute("name"); - if (StringUtils.isEmpty(homeName)) { - throw new RuntimeException("servant name is null."); - } - homeName = String.format("%s.%s.%s", serverCfg.getApplication(), serverCfg.getServerName(), homeName); - homeApiName = getChildNodeValue(element, "home-api"); - homeClassName = getChildNodeValue(element, "home-class"); - processorClazzName = getChildNodeValue(element, "home-processor-class"); - codecClazzName = getChildNodeValue(element, "home-codec-class"); - - homeApiClazz = Class.forName(homeApiName); - homeClassImpl = Class.forName(homeClassName).newInstance(); - codecClazz = (Class) (StringUtils.isEmpty(codecClazzName) ? null : Class.forName(codecClazzName)); - processorClazz = (Class) (StringUtils.isEmpty(processorClazzName) ? null : Class.forName(processorClazzName)); - - if (TarsHelper.isServant(homeApiClazz)) { - String servantName = homeApiClazz.getAnnotation(Servant.class).name(); - if (!StringUtils.isEmpty(servantName) && servantName.matches("^[\\w]+\\.[\\w]+\\.[\\w]+$")) { - homeName = servantName; - } - } - - ServantAdapterConfig servantAdapterConfig = serverCfg.getServantAdapterConfMap().get(homeName); - - ServantAdapter ServerAdapter = new ServantAdapter(servantAdapterConfig); - skeleton = new ServantHomeSkeleton(homeName, homeClassImpl, homeApiClazz, codecClazz, processorClazz, maxLoadLimit); - skeleton.setAppContext(this); - ServerAdapter.bind(skeleton); - servantAdapterMap.put(homeName, ServerAdapter); - return skeleton; - } - - private String getChildNodeValue(XMLConfigElement element, String nodeName) { - if (element == null) return null; - - XMLConfigElement childElement = element.getChildByName(nodeName); - - if (childElement == null) return null; - - return StringUtils.trim(childElement.getContent()); - } - -} diff --git a/core/src/main/java/com/qq/tars/server/common/ServerLogger.java b/core/src/main/java/com/qq/tars/server/common/ServerLogger.java deleted file mode 100644 index 70afba4a..00000000 --- a/core/src/main/java/com/qq/tars/server/common/ServerLogger.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.server.common; - -import java.io.PrintStream; - -import com.qq.tars.support.log.Logger; -import com.qq.tars.support.log.LoggingOutputStream; - -public final class ServerLogger { - - private static final String STDOUT_log_NAME = "stdout.log"; - private static final String STDERR_LOG_NAME = "stderr.log"; - private static final String SERVER_LOG_NAME = "tarsserver.log"; - - public static void init() { - System.setOut(new PrintStream(new LoggingOutputStream(Logger.getLogger(STDOUT_log_NAME)), true)); - System.setErr(new PrintStream(new LoggingOutputStream(Logger.getLogger(STDERR_LOG_NAME)), true)); - } - - public static void initNamiCoreLog(String logPath, String logLevel) { - } - - public static Logger stdout() { - return Logger.getLogger(STDOUT_log_NAME); - } - - public static Logger stderr() { - return Logger.getLogger(STDERR_LOG_NAME); - } - - public static Logger flow() { - return Logger.getLogger(SERVER_LOG_NAME); - } -} diff --git a/core/src/main/java/com/qq/tars/server/common/XMLConfigElement.java b/core/src/main/java/com/qq/tars/server/common/XMLConfigElement.java index 1cae5d76..6fb3d68a 100644 --- a/core/src/main/java/com/qq/tars/server/common/XMLConfigElement.java +++ b/core/src/main/java/com/qq/tars/server/common/XMLConfigElement.java @@ -16,13 +16,12 @@ package com.qq.tars.server.common; -import java.util.ArrayList; - +import com.qq.tars.common.util.StringUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import com.qq.tars.common.util.StringUtils; +import java.util.ArrayList; public class XMLConfigElement { diff --git a/core/src/main/java/com/qq/tars/server/common/XMLConfigFile.java b/core/src/main/java/com/qq/tars/server/common/XMLConfigFile.java index c84c357c..a0219a23 100644 --- a/core/src/main/java/com/qq/tars/server/common/XMLConfigFile.java +++ b/core/src/main/java/com/qq/tars/server/common/XMLConfigFile.java @@ -16,20 +16,19 @@ package com.qq.tars.server.common; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; + public class XMLConfigFile { private Document doc; diff --git a/core/src/main/java/com/qq/tars/server/core/Adapter.java b/core/src/main/java/com/qq/tars/server/core/Adapter.java index 60c3c1cd..9f3ae2b8 100644 --- a/core/src/main/java/com/qq/tars/server/core/Adapter.java +++ b/core/src/main/java/com/qq/tars/server/core/Adapter.java @@ -17,6 +17,7 @@ package com.qq.tars.server.core; public interface Adapter { - public void bind(AppService appService) throws Exception; - public void stop(); + void bind(AppService appService) throws Throwable; + + void stop(); } diff --git a/core/src/main/java/com/qq/tars/server/core/AppContext.java b/core/src/main/java/com/qq/tars/server/core/AppContext.java index 357bc3f8..73bcf5a6 100644 --- a/core/src/main/java/com/qq/tars/server/core/AppContext.java +++ b/core/src/main/java/com/qq/tars/server/core/AppContext.java @@ -16,24 +16,23 @@ package com.qq.tars.server.core; -import java.util.List; - import com.qq.tars.common.Filter; -import com.qq.tars.common.FilterChain; import com.qq.tars.common.FilterKind; +import java.util.List; + public interface AppContext { - public String getInitParameter(String name); + String name(); + + void stop(); - public abstract String name(); + ServantHomeSkeleton getCapHomeSkeleton(String homeName); - public void stop(); + List getFilters(FilterKind kind); - public ServantHomeSkeleton getCapHomeSkeleton(String homeName); - - public List getFilters(FilterKind kind); + void addFilter(FilterKind kind, Filter filter); - public void init(); + void init(); } diff --git a/core/src/main/java/com/qq/tars/server/core/AppContextListener.java b/core/src/main/java/com/qq/tars/server/core/AppContextListener.java index ca76be53..8b2bf120 100644 --- a/core/src/main/java/com/qq/tars/server/core/AppContextListener.java +++ b/core/src/main/java/com/qq/tars/server/core/AppContextListener.java @@ -18,8 +18,8 @@ public interface AppContextListener { - public void appContextStarted(AppContextEvent event); + void appContextStarted(AppContextEvent event); - public void appServantStarted(AppServantEvent event); + void appServantStarted(AppServantEvent event); } diff --git a/core/src/main/java/com/qq/tars/server/core/AsyncContext.java b/core/src/main/java/com/qq/tars/server/core/AsyncContext.java index dc13195d..99a18a9b 100644 --- a/core/src/main/java/com/qq/tars/server/core/AsyncContext.java +++ b/core/src/main/java/com/qq/tars/server/core/AsyncContext.java @@ -19,8 +19,7 @@ import com.qq.tars.protocol.util.TarsHelper; import com.qq.tars.rpc.protocol.tars.TarsServantRequest; import com.qq.tars.rpc.protocol.tars.TarsServantResponse; -import com.qq.tars.support.log.Logger; -import com.qq.tars.support.log.Logger.LogType; +import java.util.logging.Logger; import java.io.IOException; @@ -28,7 +27,7 @@ public final class AsyncContext { public static final String PORTAL_CAP_ASYNC_CONTEXT_ATTRIBUTE = "internal.asynccontext"; private Context context = null; - private Logger flowLogger = Logger.getLogger("tarsserver.log", LogType.ALL); + private static final Logger flowLogger = Logger.getLogger("tarsserver"); public static AsyncContext startAsync() throws IOException { Context context = ContextManager.getContext(); @@ -59,7 +58,7 @@ public T getAttribute(String name, T defaultValue) { public void setAttribute(String name, T value) { this.context.setAttribute(name, value); } - + public Context getContext() { return this.context; } @@ -73,7 +72,7 @@ public void writeException(Throwable ex) throws IOException { getCapHomeSkeleton().postInvokeCapHomeSkeleton(); Long startTime = this.context.getAttribute(Context.INTERNAL_START_TIME); - TarsServantProcessor.printServiceFlowLog(flowLogger, this.context.request(), response.getRet(), (System.currentTimeMillis() - startTime.longValue()), ex.toString()); + TarsServantProcessor.printServiceFlowLog(flowLogger, this.context.request(), response.getRet(), (System.currentTimeMillis() - startTime), ex.toString()); } @@ -86,6 +85,6 @@ public void writeResult(Object result) throws IOException { getCapHomeSkeleton().postInvokeCapHomeSkeleton(); Long startTime = this.context.getAttribute(Context.INTERNAL_START_TIME); - TarsServantProcessor.printServiceFlowLog(flowLogger, this.context.request(), response.getRet(), (System.currentTimeMillis() - startTime.longValue()), ""); + TarsServantProcessor.printServiceFlowLog(flowLogger, this.context.request(), response.getRet(), (System.currentTimeMillis() - startTime), ""); } } diff --git a/core/src/main/java/com/qq/tars/server/core/Context.java b/core/src/main/java/com/qq/tars/server/core/Context.java index 120a8c49..624aca11 100644 --- a/core/src/main/java/com/qq/tars/server/core/Context.java +++ b/core/src/main/java/com/qq/tars/server/core/Context.java @@ -16,12 +16,13 @@ package com.qq.tars.server.core; + +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; + import java.util.HashMap; import java.util.Map; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; - public final class Context { private REQ request = null; diff --git a/core/src/main/java/com/qq/tars/server/core/ContextManager.java b/core/src/main/java/com/qq/tars/server/core/ContextManager.java index be26799b..2f2e3f5c 100644 --- a/core/src/main/java/com/qq/tars/server/core/ContextManager.java +++ b/core/src/main/java/com/qq/tars/server/core/ContextManager.java @@ -16,8 +16,9 @@ package com.qq.tars.server.core; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; + +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; public final class ContextManager { diff --git a/core/src/main/java/com/qq/tars/server/core/ExtendedServantProcessor.java b/core/src/main/java/com/qq/tars/server/core/ExtendedServantProcessor.java index cd881712..d1fe6da4 100644 --- a/core/src/main/java/com/qq/tars/server/core/ExtendedServantProcessor.java +++ b/core/src/main/java/com/qq/tars/server/core/ExtendedServantProcessor.java @@ -16,19 +16,18 @@ package com.qq.tars.server.core; -import java.lang.reflect.Method; - -import com.qq.tars.net.core.Processor; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; import com.qq.tars.rpc.exc.TarsException; -import com.qq.tars.rpc.protocol.ext.ExtendedServantRequest; -import com.qq.tars.rpc.protocol.ext.ExtendedServantResponse; +import com.qq.tars.rpc.protocol.tars.TarsServantRequest; +import com.qq.tars.rpc.protocol.tars.TarsServantResponse; import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.support.om.OmServiceMngr; +import io.netty.channel.Channel; + +import java.lang.reflect.Method; -public abstract class ExtendedServantProcessor extends Processor { +public abstract class ExtendedServantProcessor implements Processor { private final ServantAdapter servantAdapter; @@ -37,7 +36,7 @@ public ExtendedServantProcessor(ServantAdapter servantAdapter) { } @Override - public Response process(Request req, Session session) { + public Response process(Request req, Channel session) { RES request = null; RESP response = null; @@ -50,7 +49,7 @@ public Response process(Request req, Session session) { oldClassLoader = Thread.currentThread().getContextClassLoader(); request = (RES) req; response = createResponse(request, session); - response.setTicketNumber(req.getTicketNumber()); + response.setRequestId(req.getRequestId()); String servantName = servantAdapter.getServantAdapterConfig().getServant(); request.setServantName(servantAdapter.getServantAdapterConfig().getServant()); @@ -66,7 +65,7 @@ public Response process(Request req, Session session) { if (appContext == null) throw new RuntimeException("failed to find the application named:[ROOT]"); Context context = ContextManager.registerContext(request, response); context.setAttribute(Context.INTERNAL_START_TIME, startTime); - context.setAttribute(Context.INTERNAL_CLIENT_IP, session.getRemoteIp()); + context.setAttribute(Context.INTERNAL_CLIENT_IP, session.remoteAddress().toString()); context.setAttribute(Context.INTERNAL_APP_NAME, appContext.name()); context.setAttribute(Context.INTERNAL_SERVICE_NAME, request.getServantName()); context.setAttribute(Context.INTERNAL_METHOD_NAME, request.getFunctionName()); @@ -85,7 +84,7 @@ public Response process(Request req, Session session) { } else { cause.printStackTrace(); } - response.setThrowable(cause); + response.setCause(cause); } finally { if (oldClassLoader != null) { Thread.currentThread().setContextClassLoader(oldClassLoader); @@ -96,5 +95,5 @@ public Response process(Request req, Session session) { return response; } - protected abstract RESP createResponse(RES request, Session session); + protected abstract RESP createResponse(RES request, Channel channel); } diff --git a/core/src/main/java/com/qq/tars/server/core/ServantAdapter.java b/core/src/main/java/com/qq/tars/server/core/ServantAdapter.java index 38b26057..b7c44f95 100644 --- a/core/src/main/java/com/qq/tars/server/core/ServantAdapter.java +++ b/core/src/main/java/com/qq/tars/server/core/ServantAdapter.java @@ -16,116 +16,36 @@ package com.qq.tars.server.core; -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.net.DatagramSocket; -import java.net.InetSocketAddress; -import java.nio.channels.DatagramChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.ServerSocketChannel; -import java.util.concurrent.Executor; - +import com.qq.tars.client.rpc.TransporterServer; import com.qq.tars.common.support.Endpoint; -import com.qq.tars.net.core.Processor; -import com.qq.tars.net.core.nio.SelectorManager; -import com.qq.tars.net.util.Utils; -import com.qq.tars.protocol.annotation.ServantCodec; import com.qq.tars.rpc.exc.TarsException; -import com.qq.tars.rpc.protocol.Codec; -import com.qq.tars.rpc.protocol.ServantProtocolFactory; -import com.qq.tars.rpc.protocol.tars.TarsCodec; -import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.server.config.ServantAdapterConfig; import com.qq.tars.server.config.ServerConfig; public class ServantAdapter implements Adapter { - - private SelectorManager selectorManager = null; - private final ServantAdapterConfig servantAdapterConfig; - private ServantHomeSkeleton skeleton; + private TransporterServer transporterServer; public ServantAdapter(ServantAdapterConfig servantAdapterConfig) { this.servantAdapterConfig = servantAdapterConfig; } - public void bind() throws IOException { - ServerConfig serverCfg = ConfigurationManager.getInstance().getServerConfig(); - - boolean keepAlive = true; - Codec codec = new TarsCodec(serverCfg.getCharsetName()); - Processor processor = new TarsServantProcessor(); - Executor threadPool = ServantThreadPoolManager.get(servantAdapterConfig); - - Endpoint endpoint = this.servantAdapterConfig.getEndpoint(); - if (endpoint.type().equals("tcp")) { - this.selectorManager = new SelectorManager(Utils.getSelectorPoolSize(), new ServantProtocolFactory(codec), threadPool, processor, keepAlive, "server-tcp-reactor", false); - this.selectorManager.setTcpNoDelay(serverCfg.isTcpNoDelay()); - this.selectorManager.start(); - - System.out.println("[SERVER] server starting at " + endpoint + "..."); - ServerSocketChannel serverChannel = ServerSocketChannel.open(); - serverChannel.socket().bind(new InetSocketAddress(endpoint.host(), endpoint.port()), 1024); - serverChannel.configureBlocking(false); - - selectorManager.getReactor(0).registerChannel(serverChannel, SelectionKey.OP_ACCEPT); - - System.out.println("[SERVER] server started at " + endpoint + "..."); - - } else if (endpoint.type().equals("udp")) { - - this.selectorManager = new SelectorManager(1, new ServantProtocolFactory(codec), threadPool, processor, false, "server-udp-reactor", true); - this.selectorManager.start(); - - System.out.println("[SERVER] server starting at " + endpoint + "..."); - DatagramChannel serverChannel = DatagramChannel.open(); - DatagramSocket socket = serverChannel.socket(); - socket.bind(new InetSocketAddress(endpoint.host(), endpoint.port())); - serverChannel.configureBlocking(false); - - this.selectorManager.getReactor(0).registerChannel(serverChannel, SelectionKey.OP_READ); - System.out.println("[SERVER] servant started at " + endpoint + "..."); - } - } - - public void bind(AppService appService) throws IOException { + public void bind(AppService appService) { this.skeleton = (ServantHomeSkeleton) appService; - ServerConfig serverCfg = ConfigurationManager.getInstance().getServerConfig(); + bind(); - boolean keepAlive = true; - Codec codec = createCodec(serverCfg); - Processor processor = createProcessor(serverCfg); - Executor threadPool = ServantThreadPoolManager.get(servantAdapterConfig); + } + public void bind() { + Processor processor = createProcessor(this.servantAdapterConfig.getServerConfig()); Endpoint endpoint = this.servantAdapterConfig.getEndpoint(); if (endpoint.type().equals("tcp")) { - this.selectorManager = new SelectorManager(Utils.getSelectorPoolSize(), new ServantProtocolFactory(codec), threadPool, processor, keepAlive, "server-tcp-reactor", false); - this.selectorManager.setTcpNoDelay(serverCfg.isTcpNoDelay()); - this.selectorManager.start(); - System.out.println("[SERVER] server starting at " + endpoint + "..."); - ServerSocketChannel serverChannel = ServerSocketChannel.open(); - serverChannel.socket().bind(new InetSocketAddress(endpoint.host(), endpoint.port()), 1024); - serverChannel.configureBlocking(false); - - selectorManager.getReactor(0).registerChannel(serverChannel, SelectionKey.OP_ACCEPT); - + transporterServer = new com.qq.tars.rpc.netty.NettyTransporterFactory() + .getTransporterServer(servantAdapterConfig, processor); + transporterServer.bind(); System.out.println("[SERVER] server started at " + endpoint + "..."); - - } else if (endpoint.type().equals("udp")) { - - this.selectorManager = new SelectorManager(1, new ServantProtocolFactory(codec), threadPool, processor, false, "server-udp-reactor", true); - this.selectorManager.start(); - - System.out.println("[SERVER] server starting at " + endpoint + "..."); - DatagramChannel serverChannel = DatagramChannel.open(); - DatagramSocket socket = serverChannel.socket(); - socket.bind(new InetSocketAddress(endpoint.host(), endpoint.port())); - serverChannel.configureBlocking(false); - - this.selectorManager.getReactor(0).registerChannel(serverChannel, SelectionKey.OP_READ); - System.out.println("[SERVER] servant started at " + endpoint + "..."); } } @@ -138,53 +58,12 @@ public ServantHomeSkeleton getSkeleton() { } private Processor createProcessor(ServerConfig serverCfg) throws TarsException { - Processor processor = null; - Class processorClass = skeleton.getProcessorClass(); - if (processorClass == null) { - return new TarsServantProcessor(); - } - - if (processorClass != null) { - Constructor constructor; - try { - constructor = processorClass.getConstructor(new Class[] { ServantAdapter.class }); - processor = constructor.newInstance(this); - } catch (Exception e) { - throw new TarsException("error occurred on create codec, codec=" + processorClass.getName()); - } - } - return processor; - } - - private Codec createCodec(ServerConfig serverCfg) throws TarsException { - Codec codec = null; - Class codecClass = skeleton.getCodecClass(); - if (codecClass == null) { - ServantCodec servantCodec = skeleton.getApiClass().getAnnotation(ServantCodec.class); - if (servantCodec != null) { - codecClass = servantCodec.codec(); - } - } - - if (codecClass == null) { - codecClass = TarsCodec.class; - } - - if (codecClass != null) { - Constructor constructor; - try { - constructor = codecClass.getConstructor(new Class[] { String.class }); - codec = constructor.newInstance(serverCfg.getCharsetName()); - } catch (Exception e) { - throw new TarsException("error occurred on create codec, codec=" + codecClass.getName()); - } - } - return codec; + return new TarsServantProcessor(); } public void stop() { - if (selectorManager != null) { - selectorManager.stop(); + if (transporterServer != null) { + transporterServer.stop(); } } } diff --git a/core/src/main/java/com/qq/tars/server/core/ServantHomeSkeleton.java b/core/src/main/java/com/qq/tars/server/core/ServantHomeSkeleton.java index 3475f39d..d3547b0c 100644 --- a/core/src/main/java/com/qq/tars/server/core/ServantHomeSkeleton.java +++ b/core/src/main/java/com/qq/tars/server/core/ServantHomeSkeleton.java @@ -18,24 +18,16 @@ import java.lang.reflect.Method; -import com.qq.tars.net.core.Processor; -import com.qq.tars.rpc.protocol.Codec; - public class ServantHomeSkeleton extends AppService { private String name = null; private Object servantImpl = null; private Class apiClass = null; - private Class codecClazz = null; - private Class processorClazz = null; - public ServantHomeSkeleton(String name, Object servantImpl, Class apiClass, Class codecClazz, - Class processorClazz, int loadLimit) { + public ServantHomeSkeleton(String name, Object servantImpl, Class apiClass, int loadLimit) { this.name = name; this.servantImpl = servantImpl; this.apiClass = apiClass; - this.codecClazz = codecClazz; - this.processorClazz = processorClazz; } public Object getServant() { @@ -69,17 +61,17 @@ private Object[] fixParamValueType(Method method, Object args[]) { return args; } - private final Object fixValueDataType(Class dataType, Object value) { + private Object fixValueDataType(Class dataType, Object value) { Object dataValue = value; if (dataType != null && dataValue != null) { - if ("short" == dataType.getName()) { + if ("short".equals(dataType.getName())) { dataValue = Short.valueOf(dataValue.toString()); - } else if ("byte" == dataType.getName()) { + } else if ("byte".equals(dataType.getName())) { dataValue = Byte.valueOf(dataValue.toString()); } else if (char.class == dataType) { dataValue = ((String) value).charAt(0); - } else if ("float" == dataType.getName()) { + } else if ("float".equals(dataType.getName())) { dataValue = Float.valueOf(dataValue.toString()); } } @@ -97,17 +89,11 @@ public Class getApiClass() { return this.apiClass; } - public Class getProcessorClass() { - return processorClazz; - } public String name() { return this.name; } - public Class getCodecClass() { - return codecClazz; - } private AppContext appContext; diff --git a/core/src/main/java/com/qq/tars/server/core/ServantProcessor.java b/core/src/main/java/com/qq/tars/server/core/ServantProcessor.java index 6a3661f2..f0e585a9 100644 --- a/core/src/main/java/com/qq/tars/server/core/ServantProcessor.java +++ b/core/src/main/java/com/qq/tars/server/core/ServantProcessor.java @@ -16,25 +16,31 @@ package com.qq.tars.server.core; -import com.qq.tars.net.core.Processor; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; + +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; import com.qq.tars.rpc.protocol.tars.TarsServantRequest; +import io.netty.channel.Channel; -public class ServantProcessor extends Processor { +public class ServantProcessor implements Processor { - private TarsServantProcessor processor = new TarsServantProcessor(); + private final TarsServantProcessor processor = new TarsServantProcessor(); @Override - public Response process(Request request, Session session) { + public Response process(Request request, Channel channel) { Response response = null; if (request instanceof TarsServantRequest) { - response = processor.process(request, session); + response = processor.process(request, channel); } else { throw new IllegalArgumentException("unknown request type."); } return response; } + + @Override + public void overload(Request request, Channel session) { + + } + } diff --git a/core/src/main/java/com/qq/tars/server/core/ServantThreadPoolManager.java b/core/src/main/java/com/qq/tars/server/core/ServantThreadPoolManager.java index 3867fb7f..bfe0b275 100644 --- a/core/src/main/java/com/qq/tars/server/core/ServantThreadPoolManager.java +++ b/core/src/main/java/com/qq/tars/server/core/ServantThreadPoolManager.java @@ -16,21 +16,21 @@ package com.qq.tars.server.core; -import java.util.HashMap; -import java.util.concurrent.Executor; -import java.util.concurrent.TimeUnit; - import com.qq.tars.common.util.concurrent.TaskQueue; import com.qq.tars.common.util.concurrent.TaskThreadFactory; import com.qq.tars.common.util.concurrent.TaskThreadPoolExecutor; import com.qq.tars.server.config.ServantAdapterConfig; +import java.util.HashMap; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; + public final class ServantThreadPoolManager { private final static HashMap threadExecutors = new HashMap(); public static Executor get(ServantAdapterConfig config) { - return getAndcreateExecutor(config); + return getAndCreateExecutor(config); } private static synchronized Executor createDefaultExecutor(String key) { @@ -49,7 +49,7 @@ private static synchronized Executor createDefaultExecutor(String key) { return pool; } - private static synchronized Executor getAndcreateExecutor(ServantAdapterConfig config) { + private static synchronized Executor getAndCreateExecutor(ServantAdapterConfig config) { String key = config.getHandleGroup(); Executor executor = null; diff --git a/core/src/main/java/com/qq/tars/server/core/Server.java b/core/src/main/java/com/qq/tars/server/core/Server.java index 53be1b2a..c74dcef5 100644 --- a/core/src/main/java/com/qq/tars/server/core/Server.java +++ b/core/src/main/java/com/qq/tars/server/core/Server.java @@ -1,13 +1,13 @@ /** * Tencent is pleased to support the open source community by making Tars available. - * + *

* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * + *

* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at - * + *

* https://opensource.org/licenses/BSD-3-Clause - * + *

* 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 @@ -16,50 +16,55 @@ package com.qq.tars.server.core; -import java.io.IOException; -import java.util.Map.Entry; - import com.qq.tars.client.Communicator; import com.qq.tars.client.CommunicatorConfig; import com.qq.tars.client.CommunicatorFactory; import com.qq.tars.common.util.BeanAccessor; -import com.qq.tars.common.util.StringUtils; -import com.qq.tars.net.core.SessionManager; -import com.qq.tars.register.RegisterManager; -import com.qq.tars.server.common.ServerLogger; import com.qq.tars.server.config.ConfigurationManager; -import com.qq.tars.server.config.ServantAdapterConfig; import com.qq.tars.server.config.ServerConfig; -import com.qq.tars.server.ha.ConnectionSessionListener; -import com.qq.tars.support.log.LogConfCacheMngr; -import com.qq.tars.support.log.LoggerFactory; -import com.qq.tars.support.om.OmConstants; import com.qq.tars.support.om.OmServiceMngr; +import java.io.IOException; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; + public class Server { private AppContext appContext = null; private ServerConfig serverConfig; + private static final Server INSTANCE = new Server(); + private static final AtomicBoolean INITIALIZED = new AtomicBoolean(false); - public Server(ServerConfig config) { - this.serverConfig = config; + private Server() { } - public void startUp(AppContext appContext) { - try { + /** + * init the server config + */ + public void init() { + if (!INITIALIZED.getAndSet(true)) { + System.out.println("[TARS] start server initializing"); + loadServerConfig(); + initCommunicator(); + startManagerService(); + } else { + throw new IllegalStateException("Server has already been initialized"); + } + } -// initCommunicator(); -// -// configLogger(); -// -// startManagerService(); + public static Server getInstance() { + return INSTANCE; + } - startAppContext(appContext); + public ServerConfig getServerConfig() { + return serverConfig; + } + public void startUp(AppContext appContext) { + try { + startAppContext(appContext); startSessionManager(); - registerServerHook(); - System.out.println("[SERVER] server is ready..."); } catch (Throwable ex) { System.out.println("[SERVER] failed to start server..."); @@ -76,82 +81,46 @@ private void startAppContext(AppContext appContext) throws Exception { appContext.init(); } - public static void startManagerService() { + private void startManagerService() { OmServiceMngr.getInstance().initAndStartOmService(); } - public static void initCommunicator() { + private void initCommunicator() { CommunicatorConfig config = ConfigurationManager.getInstance().getServerConfig().getCommunicatorConfig(); Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(config); BeanAccessor.setBeanValue(CommunicatorFactory.getInstance(), "communicator", communicator); } - public static void configLogger() { - String objName = ConfigurationManager.getInstance().getServerConfig().getLog(); - String appName = ConfigurationManager.getInstance().getServerConfig().getApplication(); - String serviceName = ConfigurationManager.getInstance().getServerConfig().getServerName(); - - String defaultLevel = ConfigurationManager.getInstance().getServerConfig().getLogLevel(); - String defaultRoot = ConfigurationManager.getInstance().getServerConfig().getLogPath(); - String dataPath = ConfigurationManager.getInstance().getServerConfig().getDataPath(); - - LoggerFactory.config(CommunicatorFactory.getInstance().getCommunicator() - , objName, appName, serviceName, defaultLevel, defaultRoot); - - LogConfCacheMngr.getInstance().init(dataPath); - if (StringUtils.isNotEmpty(LogConfCacheMngr.getInstance().getLevel())) { - LoggerFactory.setDefaultLoggerLevel(LogConfCacheMngr.getInstance().getLevel()); - } - - ServerLogger.init(); - } - - public static void loadServerConfig() { + private void loadServerConfig() { try { - ConfigurationManager.getInstance().init(); - - ServerConfig cfg = ConfigurationManager.getInstance().getServerConfig(); - ServerLogger.initNamiCoreLog(cfg.getLogPath(), cfg.getLogLevel()); + ConfigurationManager configurationManager = ConfigurationManager.getInstance(); + if (configurationManager.getServerConfig() == null) { + configurationManager.init(); + } + ServerConfig cfg = configurationManager.getServerConfig(); System.setProperty("com.qq.nami.server.udp.bufferSize", String.valueOf(cfg.getUdpBufferSize())); System.setProperty("server.root", cfg.getBasePath()); + this.serverConfig = cfg; } catch (Throwable ex) { ex.printStackTrace(System.err); - System.err.println("The exception occured at load server config"); + System.err.println("The exception occurred at load server config"); System.exit(2); } } private void startSessionManager() throws IOException { - SessionManager sessionManager = SessionManager.getSessionManager(); - sessionManager.setTimeout(serverConfig.getSessionTimeOut()); - sessionManager.setCheckInterval(serverConfig.getSessionCheckInterval()); - - int connCount = 0; - for (Entry adapterConfigEntry : ConfigurationManager.getInstance().getServerConfig().getServantAdapterConfMap().entrySet()) { - if (OmConstants.AdminServant.equals(adapterConfigEntry.getKey())) { - continue; - } - connCount += adapterConfigEntry.getValue().getMaxConns(); - } - ConnectionSessionListener sessionListener = new ConnectionSessionListener(connCount); - sessionManager.addSessionListener(sessionListener); - sessionManager.start(); } private void registerServerHook() { - Runtime.getRuntime().addShutdownHook(new Thread() { - - @Override - public void run() { - try { - if (appContext != null) { - appContext.stop(); - } - } catch (Exception ex) { - System.err.println("The exception occured at stopping server..."); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { + if (appContext != null) { + appContext.stop(); } + } catch (Exception ex) { + System.err.println("The exception occurred at stopping server..."); } - }); + })); } } diff --git a/core/src/main/java/com/qq/tars/server/core/ServerThreadPoolDispatcher.java b/core/src/main/java/com/qq/tars/server/core/ServerThreadPoolDispatcher.java deleted file mode 100644 index f38a07f9..00000000 --- a/core/src/main/java/com/qq/tars/server/core/ServerThreadPoolDispatcher.java +++ /dev/null @@ -1,139 +0,0 @@ -///** -// * Tencent is pleased to support the open source community by making Tars available. -// * -// * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. -// * -// * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except -// * in compliance with the License. You may obtain a copy of the License at -// * -// * https://opensource.org/licenses/BSD-3-Clause -// * -// * Unless required by applicable law or agreed to in writing, software distributed -// * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// * CONDITIONS OF ANY KIND, either express or implied. See the License for the -// * specific language governing permissions and limitations under the License. -// */ -// -//package com.qq.tars.server.core; -// -//import java.util.HashMap; -//import java.util.concurrent.Executor; -//import java.util.concurrent.TimeUnit; -// -//import com.qq.tars.common.util.concurrent.TaskQueue; -//import com.qq.tars.common.util.concurrent.TaskThreadFactory; -//import com.qq.tars.common.util.concurrent.TaskThreadPoolExecutor; -//import com.qq.tars.net.core.Request; -//import com.qq.tars.net.core.nio.WorkThread; -//import com.qq.tars.rpc.protocol.tars.TarsServantRequest; -//import com.qq.tars.server.apps.AppContextImpl; -// -//public class ServerThreadPoolDispatcher implements Executor { -// -// private final static HashMap threadExecutors = new HashMap(); -// -// public void execute(Runnable command) { -// getExecutor(command).execute(command); -// } -// -// private static Executor getExecutor(Runnable command) { -// TarsServantRequest request = getPortalServiceRequest(command); -// -// if (request == null) return getDefaultExecutor(); -// -// return getExecutor(request); -// } -// -// private static Executor getDefaultExecutor() { -// Executor executor = threadExecutors.get(null); -// -// if (executor == null) { -// executor = createExecutor(null); -// } -// -// return executor; -// } -// -// private static Executor getExecutor(TarsServantRequest request) { -// String service = request.getServantName(); -// -// Executor executor = threadExecutors.get(service); -// -// if (executor == null) { -// executor = createExecutor(request); -// } -// -// return executor; -// } -// -// private static synchronized Executor createDefaultExecutor(String key) { -// Executor executor = threadExecutors.get(null); -// -// if (executor != null) { -// threadExecutors.put(key, executor); -// return executor; -// } -// -// TaskQueue taskqueue = new TaskQueue(20000); -// TaskThreadPoolExecutor pool = new TaskThreadPoolExecutor(5, 512, 120, TimeUnit.SECONDS, taskqueue, new TaskThreadFactory("taserverThreadPool-exec-")); -// taskqueue.setParent(pool); -// threadExecutors.put(null, pool); -// threadExecutors.put(key, pool); -// -// return pool; -// } -// -// private static synchronized Executor createExecutor(TarsServantRequest request) { -// String key = null, contextName = null, serviceName = null; -// Executor executor = null; -// -// if (request == null) return createDefaultExecutor(null); -// -//// contextName = request.getWebappContext(); -// serviceName = request.getServantName(); -// key = contextName + '_' + serviceName; -// -// executor = threadExecutors.get(key); -// if (executor != null) return executor; -// -// int minPoolSize = -1, maxPoolSize = -1, queueSize = -1; -// AppContainer container = ContainerManager.getContainer(AppContainer.class); -// AppContextImpl context = container.getDefaultAppContext(); -// -// // 客户端请求错误的app或service时,返回默认的executor. -// if (context == null) { -// return getDefaultExecutor(); -// } -// ServantHomeSkeleton service = context.getCapHomeSkeleton(serviceName); -// if (service == null) { -// return getDefaultExecutor(); -// } -// -// minPoolSize = service.getMinThreadPoolSize(); -// maxPoolSize = service.getMaxThreadPoolSize(); -// queueSize = service.getQueueSize(); -// -// if (minPoolSize < 0 || maxPoolSize < 0 || queueSize < 0) { -// return createDefaultExecutor(key); -// } -// -// // ---------------------------------- -// TaskQueue taskqueue = new TaskQueue(queueSize); -// TaskThreadPoolExecutor pool = new TaskThreadPoolExecutor(minPoolSize, maxPoolSize, 120, TimeUnit.SECONDS, taskqueue, new TaskThreadFactory("taserverThreadPool-exec-" + contextName + '.' + serviceName + '-')); -// taskqueue.setParent(pool); -// threadExecutors.put(key, pool); -// -// return pool; -// } -// -// private static TarsServantRequest getPortalServiceRequest(Runnable command) { -// if (!(command instanceof WorkThread)) return null; -// -// WorkThread workThread = (WorkThread) command; -// Request req = workThread.getRequest(); -// -// if (!(req instanceof TarsServantRequest)) return null; -// -// return (TarsServantRequest) req; -// } -//} diff --git a/core/src/main/java/com/qq/tars/server/core/TarsServantProcessor.java b/core/src/main/java/com/qq/tars/server/core/TarsServantProcessor.java index c00762fa..1d3a4704 100644 --- a/core/src/main/java/com/qq/tars/server/core/TarsServantProcessor.java +++ b/core/src/main/java/com/qq/tars/server/core/TarsServantProcessor.java @@ -17,6 +17,8 @@ package com.qq.tars.server.core; import com.qq.tars.client.CommunicatorConfig; +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; import com.qq.tars.common.Filter; import com.qq.tars.common.FilterChain; import com.qq.tars.common.FilterKind; @@ -24,34 +26,36 @@ import com.qq.tars.common.util.Constants; import com.qq.tars.common.util.DyeingKeyCache; import com.qq.tars.common.util.DyeingSwitch; -import com.qq.tars.context.DistributedContext; -import com.qq.tars.context.DistributedContextManager; -import com.qq.tars.net.core.Processor; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; +import com.qq.tars.context.TarsContext; import com.qq.tars.protocol.tars.support.TarsMethodInfo; import com.qq.tars.protocol.util.TarsHelper; -import com.qq.tars.rpc.exc.TarsException; +import com.qq.tars.rpc.exc.ServerDecodeException; +import com.qq.tars.rpc.exc.ServerException; +import com.qq.tars.rpc.exc.ServerNoServantException; +import com.qq.tars.rpc.exc.ServerQueueTimeoutException; import com.qq.tars.rpc.protocol.tars.TarsServantRequest; import com.qq.tars.rpc.protocol.tars.TarsServantResponse; import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.server.config.ServantAdapterConfig; import com.qq.tars.server.config.ServerConfig; -import com.qq.tars.support.log.Logger; -import com.qq.tars.support.log.Logger.LogType; import com.qq.tars.support.om.OmServiceMngr; import com.qq.tars.support.stat.InvokeStatHelper; -import com.qq.tars.support.trace.TraceManager; +import io.netty.channel.Channel; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.lang.reflect.InvocationTargetException; +import java.net.InetSocketAddress; +import java.nio.charset.Charset; import java.util.List; import java.util.Random; -public class TarsServantProcessor extends Processor { +public class TarsServantProcessor implements Processor { + private static final Logger logger = Logger.getLogger(TarsServantProcessor.class.getName()); private static final String FLOW_SEP_FLAG = "|"; private static final Random rand = new Random(System.currentTimeMillis()); - private Logger flowLogger = Logger.getLogger("tarsserver.log", LogType.LOCAL); + private static final Logger flowLogger = Logger.getLogger("tarsserver"); public static void printServiceFlowLog(Logger logger, TarsServantRequest request, int status, long cost, String remark) { @@ -62,7 +66,6 @@ public static void printServiceFlowLog(Logger logger, TarsServantRequest request int len = 25; sb.append(FLOW_SEP_FLAG); - sb.append(request.getIoSession().getRemoteIp()).append(FLOW_SEP_FLAG); sb.append(request.getFunctionName()).append(FLOW_SEP_FLAG); if (null != args) { @@ -87,7 +90,7 @@ public static void printServiceFlowLog(Logger logger, TarsServantRequest request logger.info(sb.toString()); } - private static boolean isFlowLogEnable() { + public static boolean isFlowLogEnable() { return ConfigurationManager.getInstance().getServerConfig().getLogRate() - rand.nextInt(100) > 0; } @@ -103,55 +106,59 @@ private static String encodeStringParam(String longParam, int len) { } @Override - public Response process(Request req, Session session) { -// AppContainer container = null; + public Response process(Request req, Channel clientChannel) { TarsServantRequest request = null; TarsServantResponse response = null; ServantHomeSkeleton skeleton = null; - Object value = null; AppContext appContext = null; ClassLoader oldClassLoader = null; int waitingTime = -1; - long startTime = req.getProcessTime(); + long startTime = req.getBornTime(); String remark = ""; - try { oldClassLoader = Thread.currentThread().getContextClassLoader(); request = (TarsServantRequest) req; - response = createResponse(request, session); - response.setTicketNumber(req.getTicketNumber()); - - if (response.getRet() != TarsHelper.SERVERSUCCESS || TarsHelper.isPing(request.getFunctionName())) { + response = (TarsServantResponse) createResponse(request, clientChannel); + response.setRequestId(request.getRequestId()); + if (TarsHelper.isPing(request.getFunctionName())) { return response; } + + if (response.getRet() != TarsHelper.SERVERSUCCESS) { + throw new ServerDecodeException(response.getRet(), "decode error."); + } + int maxWaitingTimeInQueue = ConfigurationManager.getInstance().getServerConfig().getServantAdapterConfMap().get(request.getServantName()).getQueueTimeout(); + waitingTime = (int) (startTime - req.getBornTime()); + + logger.log(Level.FINE, "waittime:queu_time{0},{1},{2},{3}", new Object[]{waitingTime, maxWaitingTimeInQueue, startTime, req.getBornTime()}); + if (waitingTime > maxWaitingTimeInQueue) { - throw new TarsException("Wait too long, server busy."); + throw new ServerQueueTimeoutException(TarsHelper.SERVERQUEUETIMEOUT, "queue timeout."); } -// container = ContainerManager.getContainer(AppContainer.class); Context context = ContextManager.registerContext(request, response); context.setAttribute(Context.INTERNAL_START_TIME, startTime); - context.setAttribute(Context.INTERNAL_CLIENT_IP, session.getRemoteIp()); -// context.setAttribute(Context.INTERNAL_APP_NAME, container.getDefaultAppContext().name()); + context.setAttribute(Context.INTERNAL_CLIENT_IP, clientChannel.remoteAddress().toString()); context.setAttribute(Context.INTERNAL_SERVICE_NAME, request.getServantName()); context.setAttribute(Context.INTERNAL_METHOD_NAME, request.getFunctionName()); - context.setAttribute(Context.INTERNAL_SESSION_DATA, session); - - DistributedContext distributedContext = DistributedContextManager.getDistributedContext(); - distributedContext.put(DyeingSwitch.REQ, request); - distributedContext.put(DyeingSwitch.RES, response); - distributedContext.put(TraceManager.INTERNAL_SERVANT_NAME, request.getServantName()); + context.setAttribute(Context.INTERNAL_SESSION_DATA, clientChannel); + TarsContext tarsContext = TarsContext.current(); + tarsContext.set(TarsContext.REQUEST, request); + tarsContext.set(TarsContext.RESPONSE, response); + tarsContext.set(TarsContext.SERVANT_NAME, request.getServantName()); appContext = AppContextManager.getInstance().getAppContext(); - if (appContext == null) throw new RuntimeException("failed to find the application named:[ROOT]"); + if (appContext == null) { + throw new ServerNoServantException(TarsHelper.SERVERNOSERVANTERR, "empty appContext."); + } -// Thread.currentThread().setContextClassLoader(appContext.getAppContextClassLoader()); preInvokeSkeleton(); skeleton = appContext.getCapHomeSkeleton(request.getServantName()); - if (skeleton == null) - throw new RuntimeException("failed to find the servant named[" + request.getServantName() + "]"); + if (skeleton == null) { + throw new ServerNoServantException(TarsHelper.SERVERNOSERVANTERR, "empty servantImp."); + } List filters = AppContextManager.getInstance().getAppContext().getFilters(FilterKind.SERVER); FilterChain filterChain = new TarsServerFilterChain(filters, request.getServantName(), FilterKind.SERVER, skeleton); filterChain.doFilter(request, response); @@ -159,6 +166,16 @@ public Response process(Request req, Session session) { cause.printStackTrace(); System.err.println("ERROR: " + cause.getMessage()); + // 错误码 + int errCode = TarsHelper.SERVERUNKNOWNERR; + if (cause instanceof ServerException) { + errCode = ((ServerException) cause).getRet(); + } else if (cause instanceof InvocationTargetException) { + errCode = TarsHelper.SERVERUNCATCHEDERR; + } else if (cause instanceof IllegalArgumentException) { + errCode = TarsHelper.SERVERDECODEERR; + } + if (response.isAsyncMode()) { try { Context context = ContextManager.getContext(); @@ -170,7 +187,7 @@ public Response process(Request req, Session session) { } else { response.setResult(null); response.setCause(cause); - response.setRet(TarsHelper.SERVERUNKNOWNERR); + response.setRet(errCode); remark = cause.toString(); } } finally { @@ -183,20 +200,36 @@ public Response process(Request req, Session session) { } postInvokeSkeleton(); OmServiceMngr.getInstance().reportWaitingTimeProperty(waitingTime); - reportServerStat(request, response, startTime); + reportServerStat(clientChannel, request, response, startTime); } return response; } - private void reportServerStat(TarsServantRequest request, TarsServantResponse response, long startTime) { + @Override + public void overload(Request req, Channel session) { + TarsServantRequest request = (TarsServantRequest) req; + TarsServantResponse response = (TarsServantResponse) createResponse(request, session); + if (!TarsHelper.isPing(request.getFunctionName())) { + if (response.getRet() == TarsHelper.SERVERSUCCESS) { + response.setRet(TarsHelper.SERVEROVERLOAD); + } + } + try { + session.writeAndFlush(response); + } catch (Throwable ex) { + ex.printStackTrace(); + } + } + + private void reportServerStat(Channel channel, TarsServantRequest request, TarsServantResponse response, long startTime) { if (request.getVersion() == TarsHelper.VERSION2 || request.getVersion() == TarsHelper.VERSION3) { - reportServerStat(Constants.TARS_TUP_CLIENT, request, response, startTime); + reportServerStat(channel, Constants.TARS_TUP_CLIENT, request, response, startTime); } else if (request.getMessageType() == TarsHelper.ONEWAY) { - reportServerStat(Constants.TARS_ONE_WAY_CLIENT, request, response, startTime); + reportServerStat(channel, Constants.TARS_ONE_WAY_CLIENT, request, response, startTime); } } - private void reportServerStat(String moduleName, TarsServantRequest request, TarsServantResponse response, + private void reportServerStat(Channel channel, String moduleName, TarsServantRequest request, TarsServantResponse response, long startTime) { ServerConfig serverConfig = ConfigurationManager.getInstance().getServerConfig(); ServantAdapterConfig servantAdapterConfig = serverConfig.getServantAdapterConfMap().get(request.getServantName()); @@ -205,28 +238,27 @@ private void reportServerStat(String moduleName, TarsServantRequest request, Tar } CommunicatorConfig communicatorConfig = serverConfig.getCommunicatorConfig(); Endpoint serverEndpoint = servantAdapterConfig.getEndpoint(); - String masterIp = request.getIoSession().getRemoteIp(); + String masterIp = ((InetSocketAddress) channel.remoteAddress()).getHostString(); int result = response.getRet() == TarsHelper.SERVERSUCCESS ? Constants.INVOKE_STATUS_SUCC : Constants.INVOKE_STATUS_EXEC; InvokeStatHelper.getInstance().addProxyStat(request.getServantName()).addInvokeTimeByServer(moduleName, serverConfig.getApplication(), serverConfig.getServerName(), communicatorConfig.getSetName(), communicatorConfig.getSetArea(), communicatorConfig.getSetID(), request.getFunctionName(), (masterIp == null ? "0.0.0.0" : masterIp), serverEndpoint.host(), serverEndpoint.port(), result, (System.currentTimeMillis() - startTime)); } - private TarsServantResponse createResponse(TarsServantRequest request, Session session) { - TarsServantResponse response = new TarsServantResponse(session); + private Response createResponse(TarsServantRequest request, Channel channel) { + TarsServantResponse response = new TarsServantResponse(request.getRequestId()); response.setRet(request.getRet()); response.setVersion(request.getVersion()); response.setPacketType(request.getPacketType()); response.setMessageType(request.getMessageType()); response.setStatus(request.getStatus()); response.setRequest(request); - response.setCharsetName(request.getCharsetName()); + response.setCharsetName(Charset.forName(request.getCharsetName())); response.setTimeout(request.getTimeout()); response.setContext(request.getContext()); return response; } public void preInvokeSkeleton() { - DistributedContext distributedContext = DistributedContextManager.getDistributedContext(); - Request request = distributedContext.get(DyeingSwitch.REQ); + Request request = TarsContext.current().get(TarsContext.REQUEST); if (request instanceof TarsServantRequest) { TarsServantRequest tarsServantRequest = (TarsServantRequest) request; initDyeing(tarsServantRequest); @@ -234,8 +266,7 @@ public void preInvokeSkeleton() { } public void postInvokeSkeleton() { - DistributedContext distributedContext = DistributedContextManager.getDistributedContext(); - distributedContext.clear(); + TarsContext.release(); } private void initDyeing(TarsServantRequest request) { @@ -256,8 +287,8 @@ private void initDyeing(TarsServantRequest request) { } TarsMethodInfo methodInfo = request.getMethodInfo(); if (methodInfo.getRouteKeyIndex() != -1) { - Object[] paramters = request.getMethodParameters(); - Object value = paramters[methodInfo.getRouteKeyIndex()]; + Object[] parameters = request.getMethodParameters(); + Object value = parameters[methodInfo.getRouteKeyIndex()]; if (cache_routeKey.equals(value.toString())) { routeKey = cache_routeKey; fileName = ConfigurationManager.getInstance().getServerConfig().getServerName(); diff --git a/core/src/main/java/com/qq/tars/server/core/TarsServerFilterChain.java b/core/src/main/java/com/qq/tars/server/core/TarsServerFilterChain.java index 1a0598b3..8e39dbc6 100644 --- a/core/src/main/java/com/qq/tars/server/core/TarsServerFilterChain.java +++ b/core/src/main/java/com/qq/tars/server/core/TarsServerFilterChain.java @@ -1,31 +1,49 @@ package com.qq.tars.server.core; -import java.util.List; - +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; import com.qq.tars.common.AbstractFilterChain; import com.qq.tars.common.Filter; import com.qq.tars.common.FilterKind; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; import com.qq.tars.rpc.protocol.tars.TarsServantRequest; import com.qq.tars.rpc.protocol.tars.TarsServantResponse; +import java.util.List; +import java.util.concurrent.CompletableFuture; + public class TarsServerFilterChain extends AbstractFilterChain { - - public TarsServerFilterChain(List filters, String servant, - FilterKind kind, ServantHomeSkeleton target) { - super(filters, servant, kind, target); - } - @Override - protected void doRealInvoke(Request request, Response response) - throws Throwable { - if (request instanceof TarsServantRequest && target != null) { - TarsServantRequest tarsServantRequest = (TarsServantRequest)request; - Object value = target.invoke(tarsServantRequest.getMethodInfo().getMethod(), tarsServantRequest.getMethodParameters()); - TarsServantResponse tarsServantResponse = (TarsServantResponse) response; - tarsServantResponse.setResult(value); - } - } + public TarsServerFilterChain(List filters, String servant, + FilterKind kind, ServantHomeSkeleton target) { + super(filters, servant, kind, target); + } + + @Override + protected void doRealInvoke(Request request, Response response) + throws Throwable { + if (request instanceof TarsServantRequest && target != null) { + TarsServantRequest tarsServantRequest = (TarsServantRequest) request; + Object value = target.invoke(tarsServantRequest.getMethodInfo().getMethod(), tarsServantRequest.getMethodParameters()); + TarsServantResponse tarsServantResponse = (TarsServantResponse) response; + tarsServantResponse.setResult(value); + } + } + + @Override + protected CompletableFuture doRealInvoke(Request request) throws Throwable { + return null; + } + @Override + public CompletableFuture doFilter(Request request) throws Throwable { + if (request instanceof TarsServantRequest && target != null) { + TarsServantRequest tarsServantRequest = (TarsServantRequest) request; + Object value = target.invoke(tarsServantRequest.getMethodInfo().getMethod(), tarsServantRequest.getMethodParameters()); + TarsServantResponse tarsServantResponse = new TarsServantResponse(request.getRequestId()); + tarsServantResponse.setResult(value); + return CompletableFuture.completedFuture(tarsServantResponse); + } else { + throw new RuntimeException("[Tars] invoke error!"); + } + } } diff --git a/core/src/main/java/com/qq/tars/server/ha/ConnectionSessionListener.java b/core/src/main/java/com/qq/tars/server/ha/ConnectionSessionListener.java deleted file mode 100644 index b76c751e..00000000 --- a/core/src/main/java/com/qq/tars/server/ha/ConnectionSessionListener.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.server.ha; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicInteger; - -import com.qq.tars.net.core.SessionEvent; -import com.qq.tars.net.core.SessionListener; -import com.qq.tars.net.core.Session.SessionStatus; - -public class ConnectionSessionListener implements SessionListener { - - private final AtomicInteger connStat = new AtomicInteger(0); - - private final int MaxConnCount; - - public ConnectionSessionListener(int connCount) { - MaxConnCount = connCount; - System.out.println("MaxConnCount=" + MaxConnCount); - } - - @Override - public synchronized void onSessionCreated(SessionEvent se) { - if (connStat.get() >= MaxConnCount) { - try { - System.out.println("reached the max connection threshold, close the session."); - se.getSession().close(); - } catch (IOException e) { - } - return; - } - - System.out.println("onSessionCreated: " + connStat.incrementAndGet()); - } - - @Override - public synchronized void onSessionDestoryed(SessionEvent se) { - if ((se.getSession() == null || se.getSession().getStatus() == SessionStatus.CLOSED) && connStat.get() > 0) { - System.out.println("onSessionDestoryed: " + connStat.decrementAndGet()); - } - } -} diff --git a/core/src/main/java/com/qq/tars/server/startup/Main.java b/core/src/main/java/com/qq/tars/server/startup/Main.java deleted file mode 100644 index 6cb171cb..00000000 --- a/core/src/main/java/com/qq/tars/server/startup/Main.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.server.startup; - -import com.qq.tars.rpc.exc.TarsException; -import com.qq.tars.server.apps.XmlAppContext; -import com.qq.tars.server.config.ConfigurationManager; -import com.qq.tars.server.core.AppContext; -import com.qq.tars.server.core.Server; - -import java.io.File; -import java.net.URL; - -public class Main { - - public static void main(String[] args) throws Exception { - Server.loadServerConfig(); - Server.initCommunicator(); - Server.configLogger(); - Server.startManagerService(); - - AppContext context = null; - URL servantXML = Main.class.getClassLoader().getResource("servants.xml"); - if (servantXML != null) { - context = new XmlAppContext(); - } else if (Main.class.getClassLoader().getResource("servants-spring.xml") != null){ - System.out.println("[SERVER] find servants-spring.xml, use Spring mode."); - Class clazz = Class.forName("com.qq.tars.server.apps.SpringAppContext"); - context = (AppContext) clazz.newInstance(); - } else { - System.out.println("[SERVER] servants profile does not exist, start failed."); - throw new TarsException("servants profile does not exist"); - } - new Server(ConfigurationManager.getInstance().getServerConfig()).startUp(context); - } -} diff --git a/core/src/main/java/com/qq/tars/support/admin/AdminFServant.java b/core/src/main/java/com/qq/tars/support/admin/AdminFServant.java index 9305188c..f199bc4c 100644 --- a/core/src/main/java/com/qq/tars/support/admin/AdminFServant.java +++ b/core/src/main/java/com/qq/tars/support/admin/AdminFServant.java @@ -20,18 +20,17 @@ package com.qq.tars.support.admin; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.annotation.*; -import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; @Servant public interface AdminFServant { - /** - * 关闭服务 - */ - public void shutdown(); - /** - * 通知服务 - */ - public String notify(String command); + /** + * close Server + */ + void shutdown(); + + /** + * notify Server + */ + String notify(String command); } diff --git a/core/src/main/java/com/qq/tars/support/admin/CustemCommandHelper.java b/core/src/main/java/com/qq/tars/support/admin/CustomCommandHelper.java similarity index 72% rename from core/src/main/java/com/qq/tars/support/admin/CustemCommandHelper.java rename to core/src/main/java/com/qq/tars/support/admin/CustomCommandHelper.java index 0ddd647a..0b23c817 100644 --- a/core/src/main/java/com/qq/tars/support/admin/CustemCommandHelper.java +++ b/core/src/main/java/com/qq/tars/support/admin/CustomCommandHelper.java @@ -19,28 +19,28 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -public final class CustemCommandHelper { +public final class CustomCommandHelper { - private static final CustemCommandHelper Instance = new CustemCommandHelper(); + private static final CustomCommandHelper Instance = new CustomCommandHelper(); - private Map custemHandlerMap = new ConcurrentHashMap(); + private Map customHandlerMap = new ConcurrentHashMap(); - private CustemCommandHelper() { + private CustomCommandHelper() { } - public static CustemCommandHelper getInstance() { + public static CustomCommandHelper getInstance() { return Instance; } - public boolean registerCustemHandler(String cmdName, CommandHandler handler) { + public boolean registerCustomHandler(String cmdName, CommandHandler handler) { if (com.qq.tars.common.util.StringUtils.isEmpty(cmdName) || handler == null) { return false; } - custemHandlerMap.put(cmdName, handler); + customHandlerMap.put(cmdName, handler); return true; } public CommandHandler getCommandHandler(String cmdName) { - return custemHandlerMap.get(cmdName); + return customHandlerMap.get(cmdName); } } diff --git a/core/src/main/java/com/qq/tars/support/admin/impl/AdminFServantImpl.java b/core/src/main/java/com/qq/tars/support/admin/impl/AdminFServantImpl.java index 79761a26..de713c4d 100644 --- a/core/src/main/java/com/qq/tars/support/admin/impl/AdminFServantImpl.java +++ b/core/src/main/java/com/qq/tars/support/admin/impl/AdminFServantImpl.java @@ -25,16 +25,19 @@ import com.qq.tars.server.config.ServerConfig; import com.qq.tars.support.admin.AdminFServant; import com.qq.tars.support.admin.CommandHandler; -import com.qq.tars.support.admin.CustemCommandHelper; +import com.qq.tars.support.admin.CustomCommandHelper; import com.qq.tars.support.config.ConfigHelper; +import com.qq.tars.support.log.LoggerFactory; import com.qq.tars.support.node.NodeHelper; import com.qq.tars.support.notify.NotifyHelper; import com.qq.tars.support.om.OmConstants; -import com.qq.tars.support.om.OmLogger; import java.util.Map.Entry; +import java.util.logging.Level; +import java.util.logging.Logger; public class AdminFServantImpl implements AdminFServant { + private static final Logger omLogger = LoggerFactory.getOmLogger(); private static final String CMD_LOAD_CONFIG = "tars.loadconfig"; @@ -58,7 +61,7 @@ public void shutdown() { System.out.println(ConfigurationManager.getInstance().getServerConfig().getApplication() + "." + ConfigurationManager.getInstance().getServerConfig().getServerName() + " is stopped."); NotifyHelper.getInstance().syncReport("[alarm] server is stopped."); } catch (Exception e) { - OmLogger.record("shutdown error", e); + omLogger.log(Level.SEVERE, "shutdown error", e); } System.exit(0); @@ -80,40 +83,49 @@ public String notify(String command) { StringBuilder result = new StringBuilder(); result.append("\n"); - if (CMD_VIEW_STATUS.equals(comm)) { - result.append(viewStatus() + "\n"); - } else if (CMD_VIEW_CONN.equals(comm)) { - result.append(viewConn() + "\n"); - } else if (CMD_SET_LEVEL.equals(comm)) { - result.append(setLoggerLevel(params) + "\n"); - } else if (CMD_LOAD_CONFIG.equals(comm)) { - result.append(loadConfig(params) + "\n"); - } else if (CMD_LOAD_LOCATOR.equals(comm)) { - result.append(loadLocator() + "\n"); - } else if (CMD_VIEW_VERSION.equals(comm)) { - result.append(reportServerVersion() + "\n"); - } else if (CMD_SET_DYEING.equals(comm)) { - result.append(loadDyeing(params) + "\n"); - } else { - final CommandHandler handler = CustemCommandHelper.getInstance().getCommandHandler(comm); - final String cmdName = comm; - final String cmdParam = params; - - if (handler != null) { - Thread handleThread = new Thread(new Runnable() { - - @Override - public void run() { - handler.handle(cmdName, cmdParam); - } - }); - - handleThread.start(); - - result.append("custem command: cmdName=" + cmdName + ", params=" + cmdParam + "\n"); - } else { - result.append("invalid command.\n"); - } + switch (comm) { + case CMD_VIEW_STATUS: + result.append(viewStatus()).append("\n"); + break; + case CMD_VIEW_CONN: + result.append(viewConn()).append("\n"); + break; + case CMD_SET_LEVEL: + result.append(setLoggerLevel(params)).append("\n"); + break; + case CMD_LOAD_CONFIG: + result.append(loadConfig(params)).append("\n"); + break; + case CMD_LOAD_LOCATOR: + result.append(loadLocator()).append("\n"); + break; + case CMD_VIEW_VERSION: + result.append(reportServerVersion()).append("\n"); + break; + case CMD_SET_DYEING: + result.append(loadDyeing(params)).append("\n"); + break; + default: + final CommandHandler handler = CustomCommandHelper.getInstance().getCommandHandler(comm); + final String cmdName = comm; + final String cmdParam = params; + + if (handler != null) { + Thread handleThread = new Thread(new Runnable() { + + @Override + public void run() { + handler.handle(cmdName, cmdParam); + } + }); + + handleThread.start(); + + result.append("custom command: cmdName=").append(cmdName).append(", params=").append(cmdParam).append("\n"); + } else { + result.append("invalid command.\n"); + } + break; } NotifyHelper.getInstance().syncReport(command); @@ -122,20 +134,35 @@ public void run() { private String setLoggerLevel(String level) { String result = null; - if (StringUtils.isEmpty(level)) { result = "set log level failed, level is empty"; } else { - level = level.trim(); - com.qq.tars.support.log.LoggerFactory.setDefaultLoggerLevel(level); - com.qq.tars.support.log.LogConfCacheMngr.getInstance().updateLevel(level); - + level = level.trim().toUpperCase(); + Level julLevel = parseLevel(level); + Logger.getLogger("").setLevel(julLevel); result = "set log level [" + level + "] ok"; } return result; } + private static Level parseLevel(String name) { + switch (name) { + case "TRACE": + case "DEBUG": + return Level.FINE; + case "INFO": + return Level.INFO; + case "WARN": + return Level.WARNING; + case "ERROR": + case "FATAL": + return Level.SEVERE; + default: + return Level.SEVERE; + } + } + private String viewConn() { StringBuilder builder = new StringBuilder(128); String adminConnInfo = String.format(ADATER_CONN, "Admin", 128); @@ -168,7 +195,7 @@ private String makeAdapterConfigInfo() { builder.append("name \t AdminAdapter\n"); builder.append("servant \t AdminObj\n"); - builder.append("endpoint \t tcp -h 127.0.0.1 -p " + ConfigurationManager.getInstance().getServerConfig().getLocalPort() + " -t 3000" + "\n"); + builder.append("endpoint \t tcp -h 127.0.0.1 -p ").append(ConfigurationManager.getInstance().getServerConfig().getLocalPort()).append(" -t 3000").append("\n"); builder.append("maxconns \t 128\n"); builder.append("queuecap \t 128\n"); builder.append("queuetimeout \t 3000\n"); @@ -185,16 +212,16 @@ private String makeAdapterConfigInfo() { } ServantAdapterConfig adapterConfig = adapterConfigEntry.getValue(); - builder.append("name \t" + adapterConfigEntry.getKey() + "Adapter\n"); - builder.append("servant \t" + adapterConfig.getServant() + "\n"); - builder.append("endpoint \t" + adapterConfig.getEndpoint() + "\n"); - builder.append("maxconns \t" + adapterConfig.getMaxConns() + "\n"); - builder.append("queuecap \t" + adapterConfig.getQueueCap() + "\n"); - builder.append("queuetimeout \t" + adapterConfig.getQueueTimeout() + "\n"); - builder.append("connections \t" + adapterConfig.getMaxConns() + "\n"); - builder.append("protocol \t" + adapterConfig.getProtocol() + "\n"); - builder.append("handlegroup \t" + adapterConfigEntry.getKey() + "\n"); - builder.append("handlethread \t" + adapterConfig.getThreads() + "\n"); + builder.append("name \t").append(adapterConfigEntry.getKey()).append("Adapter\n"); + builder.append("servant \t").append(adapterConfig.getServant()).append("\n"); + builder.append("endpoint \t").append(adapterConfig.getEndpoint()).append("\n"); + builder.append("maxconns \t").append(adapterConfig.getMaxConns()).append("\n"); + builder.append("queuecap \t").append(adapterConfig.getQueueCap()).append("\n"); + builder.append("queuetimeout \t").append(adapterConfig.getQueueTimeout()).append("\n"); + builder.append("connections \t").append(adapterConfig.getMaxConns()).append("\n"); + builder.append("protocol \t").append(adapterConfig.getProtocol()).append("\n"); + builder.append("handlegroup \t").append(adapterConfigEntry.getKey()).append("\n"); + builder.append("handlethread \t").append(adapterConfig.getThreads()).append("\n"); builder.append("--------------------------------------------------\n"); } @@ -206,18 +233,19 @@ private String makeServerConfigInfo() { StringBuilder builder = new StringBuilder(1024); ServerConfig serverConfig = ConfigurationManager.getInstance().getServerConfig(); builder.append("[server config]:\n"); - builder.append("Application \t" + serverConfig.getApplication() + "\n"); - builder.append("ServerName \t" + serverConfig.getServerName() + "\n"); - builder.append("BasePath \t" + serverConfig.getBasePath() + "\n"); - builder.append("DataPath \t" + serverConfig.getDataPath() + "\n"); - builder.append("LocalIp \t" + serverConfig.getLocalIP() + "\n"); - builder.append("Local \ttcp -h 127.0.0.1 -p " + serverConfig.getLocalPort() + " -t 3000" + "\n"); - builder.append("LogPath \t" + serverConfig.getLogPath() + "\n"); - builder.append("Log \t" + serverConfig.getLog() + "\n"); - builder.append("Node \t" + serverConfig.getNode() + "\n"); - builder.append("Config \t" + serverConfig.getConfig() + "\n"); - builder.append("Notify \t" + serverConfig.getNotify() + "\n"); - builder.append("logLevel \t" + serverConfig.getLogLevel() + "\n"); + builder.append("Application \t").append(serverConfig.getApplication()).append("\n"); + builder.append("ServerName \t").append(serverConfig.getServerName()).append("\n"); + builder.append("BasePath \t").append(serverConfig.getBasePath()).append("\n"); + builder.append("DataPath \t").append(serverConfig.getDataPath()).append("\n"); + builder.append("LocalIp \t").append(serverConfig.getLocalIP()).append("\n"); + builder.append("Local \ttcp -h 127.0.0.1 -p ").append(serverConfig.getLocalPort()).append(" -t 3000").append( + "\n"); + builder.append("LogPath \t").append(serverConfig.getLogPath()).append("\n"); + builder.append("Log \t").append(serverConfig.getLog()).append("\n"); + builder.append("Node \t").append(serverConfig.getNode()).append("\n"); + builder.append("Config \t").append(serverConfig.getConfig()).append("\n"); + builder.append("Notify \t").append(serverConfig.getNotify()).append("\n"); + builder.append("logLevel \t").append(serverConfig.getLogLevel()).append("\n"); return builder.toString(); } @@ -226,20 +254,20 @@ private String makeProxyConfigInfo() { StringBuilder builder = new StringBuilder(1024); CommunicatorConfig commConfig = ConfigurationManager.getInstance().getServerConfig().getCommunicatorConfig(); builder.append("[proxy config]:\n"); - builder.append("locator \t" + commConfig.getLocator() + "\n"); - builder.append("sync-invoke-timeout \t" + commConfig.getSyncInvokeTimeout() + "\n"); - builder.append("async-invoke-timeout \t" + commConfig.getAsyncInvokeTimeout() + "\n"); - builder.append("refresh-endpoint-interval \t" + commConfig.getRefreshEndpointInterval() + "\n"); - builder.append("stat \t" + commConfig.getStat() + "\n"); - builder.append("property \t" + commConfig.getProperty() + "\n"); - builder.append("report-interval \t" + commConfig.getReportInterval() + "\n"); - builder.append("sample-rate \t" + commConfig.getSampleRate() + "\n"); - builder.append("max-sample-count \t" + commConfig.getMaxSampleCount() + "\n"); - builder.append("recvthread \t" + commConfig.getRecvThread() + "\n"); - builder.append("asyncthread \t" + commConfig.getAsyncThread() + "\n"); - builder.append("modulename \t" + commConfig.getModuleName() + "\n"); - builder.append("enableset \t" + commConfig.isEnableSet() + "\n"); - builder.append("setdivision \t" + commConfig.getSetDivision() + "\n"); + builder.append("locator \t").append(commConfig.getLocator()).append("\n"); + builder.append("sync-invoke-timeout \t").append(commConfig.getSyncInvokeTimeout()).append("\n"); + builder.append("async-invoke-timeout \t").append(commConfig.getAsyncInvokeTimeout()).append("\n"); + builder.append("refresh-endpoint-interval \t").append(commConfig.getRefreshEndpointInterval()).append("\n"); + builder.append("stat \t").append(commConfig.getStat()).append("\n"); + builder.append("property \t").append(commConfig.getProperty()).append("\n"); + builder.append("report-interval \t").append(commConfig.getReportInterval()).append("\n"); + builder.append("sample-rate \t").append(commConfig.getSampleRate()).append("\n"); + builder.append("max-sample-count \t").append(commConfig.getMaxSampleCount()).append("\n"); + builder.append("recvthread \t").append(commConfig.getRecvThread()).append("\n"); + builder.append("asyncthread \t").append(commConfig.getAsyncThread()).append("\n"); + builder.append("modulename \t").append(commConfig.getModuleName()).append("\n"); + builder.append("enableset \t").append(commConfig.isEnableSet()).append("\n"); + builder.append("setdivision \t").append(commConfig.getSetDivision()).append("\n"); return builder.toString(); } @@ -255,9 +283,9 @@ private String loadLocator() { try { result = "execute success."; - OmLogger.record("Reload locator success."); + omLogger.info("Reload locator success."); } catch (Exception e) { - OmLogger.record("Reload locator failed.", e); + omLogger.log(Level.SEVERE, "Reload locator failed.", e); result = "execute exception: " + e.getMessage(); } diff --git a/core/src/main/java/com/qq/tars/support/config/ConfigHelper.java b/core/src/main/java/com/qq/tars/support/config/ConfigHelper.java index ec6010b7..362a96c6 100644 --- a/core/src/main/java/com/qq/tars/support/config/ConfigHelper.java +++ b/core/src/main/java/com/qq/tars/support/config/ConfigHelper.java @@ -16,10 +16,6 @@ package com.qq.tars.support.config; -import java.io.File; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import com.qq.tars.client.Communicator; import com.qq.tars.common.support.Holder; import com.qq.tars.common.util.FileUtil; @@ -27,9 +23,16 @@ import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.support.config.prx.ConfigInfo; import com.qq.tars.support.config.prx.ConfigPrx; -import com.qq.tars.support.om.OmLogger; +import com.qq.tars.support.log.LoggerFactory; +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.io.File; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; public class ConfigHelper { + private static final Logger omLogger = LoggerFactory.getOmLogger(); private static final ConfigHelper Instance = new ConfigHelper(); private Communicator comm; @@ -86,10 +89,10 @@ private synchronized boolean loadConfig(String fileName, boolean appConfigOnly) } localRename(newFile, fullFileName); } catch (TarsException e) { - OmLogger.record("Config|load config failed: " + fileName, e); + omLogger.log(Level.SEVERE, "Config|load config failed: " + fileName, e); throw e; } catch (Exception e) { - OmLogger.record("Config|load config failed: " + fileName, e); + omLogger.log(Level.SEVERE, "Config|load config failed: " + fileName, e); throw new TarsException("Config|load config failed: " + fileName, e); } diff --git a/core/src/main/java/com/qq/tars/support/config/prx/ConfigInfo.java b/core/src/main/java/com/qq/tars/support/config/prx/ConfigInfo.java index 8561254c..a38a5218 100644 --- a/core/src/main/java/com/qq/tars/support/config/prx/ConfigInfo.java +++ b/core/src/main/java/com/qq/tars/support/config/prx/ConfigInfo.java @@ -20,10 +20,11 @@ package com.qq.tars.support.config.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class ConfigInfo { diff --git a/core/src/main/java/com/qq/tars/support/config/prx/ConfigPrx.java b/core/src/main/java/com/qq/tars/support/config/prx/ConfigPrx.java index 9797669f..fccaf95a 100644 --- a/core/src/main/java/com/qq/tars/support/config/prx/ConfigPrx.java +++ b/core/src/main/java/com/qq/tars/support/config/prx/ConfigPrx.java @@ -20,9 +20,11 @@ package com.qq.tars.support.config.prx; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.annotation.*; import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsCallback; +import com.qq.tars.protocol.tars.annotation.TarsContext; +import com.qq.tars.protocol.tars.annotation.TarsHolder; /** * config obj to load server's system config. @@ -30,219 +32,117 @@ @Servant public interface ConfigPrx { /** - * 读取配置文件列表 + * Read the configuration file list * @param app, app name * @param server, server name * @param vf, config file name **/ public int ListConfig(String app, String server, @TarsHolder Holder> vf); /** - * 读取配置文件列表 + * Read the configuration file list * @param app, app name * @param server, server name * @param vf, config file name **/ public int ListConfig(String app, String server, @TarsHolder Holder> vf, @TarsContext java.util.Map ctx); + /** - * 读取配置文件列表 - * @param app, app name - * @param server, server name - * @param vf, config file name - **/ - public void async_ListConfig(@TarsCallback ConfigPrxCallback callback, String app, String server); - /** - * 读取配置文件列表 - * @param app, app name - * @param server, server name - * @param vf, config file name - **/ - public void async_ListConfig(@TarsCallback ConfigPrxCallback callback, String app, String server, @TarsContext java.util.Map ctx); - /** - * 读取配置文件 + * Read the configuration file list * @param app, app name * @param server, server name * @param filename, config file name - * @param config, 配置文件内容 + * @param config, Configuration file content **/ public int loadConfig(String app, String server, String filename, @TarsHolder Holder config); /** - * 读取配置文件 + * Read the configuration file list * @param app, app name * @param server, server name * @param filename, config file name - * @param config, 配置文件内容 + * @param config, Configuration file content **/ public int loadConfig(String app, String server, String filename, @TarsHolder Holder config, @TarsContext java.util.Map ctx); + /** - * 读取配置文件 - * @param app, app name - * @param server, server name - * @param filename, config file name - * @param config, 配置文件内容 - **/ - public void async_loadConfig(@TarsCallback ConfigPrxCallback callback, String app, String server, String filename); - /** - * 读取配置文件 - * @param app, app name - * @param server, server name - * @param filename, config file name - * @param config, 配置文件内容 - **/ - public void async_loadConfig(@TarsCallback ConfigPrxCallback callback, String app, String server, String filename, @TarsContext java.util.Map ctx); - /** - * 根据host读取文件 - * @param appSerever, app.server + * Read file according to host + * @param appServer, app.server * @param filename, config file name * @param host, ip - * @param config, 配置文件内容 + * @param config, Configuration file content **/ public int loadConfigByHost(String appServerName, String filename, String host, @TarsHolder Holder config); /** - * 根据host读取文件 - * @param appSerever, app.server + * Read file according to host + * @param appServer, app.server * @param filename, config file name * @param host, ip - * @param config, 配置文件内容 + * @param config, Configuration file content **/ public int loadConfigByHost(String appServerName, String filename, String host, @TarsHolder Holder config, @TarsContext java.util.Map ctx); + /** - * 根据host读取文件 - * @param appSerever, app.server - * @param filename, config file name - * @param host, ip - * @param config, 配置文件内容 - **/ - public void async_loadConfigByHost(@TarsCallback ConfigPrxCallback callback, String appServerName, String filename, String host); - /** - * 根据host读取文件 - * @param appSerever, app.server - * @param filename, config file name - * @param host, ip - * @param config, 配置文件内容 - **/ - public void async_loadConfigByHost(@TarsCallback ConfigPrxCallback callback, String appServerName, String filename, String host, @TarsContext java.util.Map ctx); - /** - * 检查配置文件是否服务TC_Config格式 - * @param appSerever, app.server + * Check whether the configuration file conforms to the TC_Config format + * @param appServer, app.server * @param filename, config file name * @param host, ip - * @param result, 提示 - * @return int 0: 合法, -1:非法 + * @param result, prompt + * @return int 0: legal, -1:illegal **/ public int checkConfig(String appServerName, String filename, String host, @TarsHolder Holder result); /** - * 检查配置文件是否服务TC_Config格式 - * @param appSerever, app.server - * @param filename, config file name - * @param host, ip - * @param result, 提示 - * @return int 0: 合法, -1:非法 - **/ - public int checkConfig(String appServerName, String filename, String host, @TarsHolder Holder result, @TarsContext java.util.Map ctx); - /** - * 检查配置文件是否服务TC_Config格式 - * @param appSerever, app.server + * Check whether the configuration file conforms to the TC_Config format + * @param appServer, app.server * @param filename, config file name * @param host, ip - * @param result, 提示 - * @return int 0: 合法, -1:非法 + * @param result, prompt + * @return int 0: legal, -1:illegal **/ - public void async_checkConfig(@TarsCallback ConfigPrxCallback callback, String appServerName, String filename, String host); - /** - * 检查配置文件是否服务TC_Config格式 - * @param appSerever, app.server - * @param filename, config file name - * @param host, ip - * @param result, 提示 - * @return int 0: 合法, -1:非法 - **/ - public void async_checkConfig(@TarsCallback ConfigPrxCallback callback, String appServerName, String filename, String host, @TarsContext java.util.Map ctx); + /** - * 读取服务所在节点的配置文件列表 + * Read the configuration file list of the node where the service is located * - * @param configInfo, ConfigInfo 配置文件信息,如果没有set分组信息,请设置setdivision为空"" + * @param configInfo, ConfigInfo: Configuration file information, if there is no set group information, please set setdivision is empty "" * @param vf, config file name - * @return int 0: 成功, -1:失败 + * @return int 0: success, -1:failure **/ public int ListConfigByInfo(ConfigInfo configInfo, @TarsHolder Holder> vf); /** - * 读取服务所在节点的配置文件列表 + * Read the configuration file list of the node where the service is located * - * @param configInfo, ConfigInfo 配置文件信息,如果没有set分组信息,请设置setdivision为空"" + * @param configInfo, ConfigInfo: Configuration file information, if there is no set group information, please set setdivision is empty "" * @param vf, config file name - * @return int 0: 成功, -1:失败 + * @return int 0: success, -1:failure **/ public int ListConfigByInfo(ConfigInfo configInfo, @TarsHolder Holder> vf, @TarsContext java.util.Map ctx); + /** - * 读取服务所在节点的配置文件列表 - * - * @param configInfo, ConfigInfo 配置文件信息,如果没有set分组信息,请设置setdivision为空"" - * @param vf, config file name - * @return int 0: 成功, -1:失败 - **/ - public void async_ListConfigByInfo(@TarsCallback ConfigPrxCallback callback, ConfigInfo configInfo); - /** - * 读取服务所在节点的配置文件列表 - * - * @param configInfo, ConfigInfo 配置文件信息,如果没有set分组信息,请设置setdivision为空"" - * @param vf, config file name - * @return int 0: 成功, -1:失败 - **/ - public void async_ListConfigByInfo(@TarsCallback ConfigPrxCallback callback, ConfigInfo configInfo, @TarsContext java.util.Map ctx); - /** - * 读取配置文件 - * @param configInfo, ConfigInfo 配置文件信息 - * @param config, 配置文件内容 - * @return int 0: 成功, -1:失败 + * Read configuration file + * @param configInfo, ConfigInfo: Configuration file information + * @param config, Configuration file content + * @return int 0: success, -1:failure **/ public int loadConfigByInfo(ConfigInfo configInfo, @TarsHolder Holder config); /** - * 读取配置文件 - * @param configInfo, ConfigInfo 配置文件信息 - * @param config, 配置文件内容 - * @return int 0: 成功, -1:失败 + * Read configuration file + * @param configInfo, ConfigInfo: Configuration file information + * @param config, Configuration file content + * @return int 0: success, -1:failure **/ public int loadConfigByInfo(ConfigInfo configInfo, @TarsHolder Holder config, @TarsContext java.util.Map ctx); + /** - * 读取配置文件 - * @param configInfo, ConfigInfo 配置文件信息 - * @param config, 配置文件内容 - * @return int 0: 成功, -1:失败 - **/ - public void async_loadConfigByInfo(@TarsCallback ConfigPrxCallback callback, ConfigInfo configInfo); - /** - * 读取配置文件 - * @param configInfo, ConfigInfo 配置文件信息 - * @param config, 配置文件内容 - * @return int 0: 成功, -1:失败 - **/ - public void async_loadConfigByInfo(@TarsCallback ConfigPrxCallback callback, ConfigInfo configInfo, @TarsContext java.util.Map ctx); - /** - * 检查配置文件是否符合TC_Config格式 - * @param configInfo, ConfigInfo 配置文件信息 - * @param result, 提示 - * @return int 0: 合法, -1:非法 + * Check whether the configuration file conforms to the TC_Config format + * @param configInfo, ConfigInfo: Configuration file information + * @param result, prompt + * @return int 0: legal, -1:illegal **/ public int checkConfigByInfo(ConfigInfo configInfo, @TarsHolder Holder result); /** - * 检查配置文件是否符合TC_Config格式 - * @param configInfo, ConfigInfo 配置文件信息 - * @param result, 提示 - * @return int 0: 合法, -1:非法 + * Check whether the configuration file conforms to the TC_Config format + * @param configInfo, ConfigInfo: Configuration file information + * @param result, prompt + * @return int 0: legal, -1:illegal **/ public int checkConfigByInfo(ConfigInfo configInfo, @TarsHolder Holder result, @TarsContext java.util.Map ctx); - /** - * 检查配置文件是否符合TC_Config格式 - * @param configInfo, ConfigInfo 配置文件信息 - * @param result, 提示 - * @return int 0: 合法, -1:非法 - **/ - public void async_checkConfigByInfo(@TarsCallback ConfigPrxCallback callback, ConfigInfo configInfo); - /** - * 检查配置文件是否符合TC_Config格式 - * @param configInfo, ConfigInfo 配置文件信息 - * @param result, 提示 - * @return int 0: 合法, -1:非法 - **/ - public void async_checkConfigByInfo(@TarsCallback ConfigPrxCallback callback, ConfigInfo configInfo, @TarsContext java.util.Map ctx); + } diff --git a/core/src/main/java/com/qq/tars/support/config/prx/ConfigPrxCallback.java b/core/src/main/java/com/qq/tars/support/config/prx/ConfigPrxCallback.java deleted file mode 100644 index 876469d3..00000000 --- a/core/src/main/java/com/qq/tars/support/config/prx/ConfigPrxCallback.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ -// ********************************************************************** -// This file was generated by a TARS parser! -// TARS version 1.0.1. -// ********************************************************************** - -package com.qq.tars.support.config.prx; - -import com.qq.tars.rpc.protocol.tars.support.TarsAbstractCallback; - -/** - * config obj to load server's system config. - **/ -public abstract class ConfigPrxCallback extends TarsAbstractCallback { - - public abstract void callback_ListConfig(int ret, java.util.List vf); - - public abstract void callback_loadConfig(int ret, String config); - - public abstract void callback_loadConfigByHost(int ret, String config); - - public abstract void callback_checkConfig(int ret, String result); - - public abstract void callback_ListConfigByInfo(int ret, java.util.List vf); - - public abstract void callback_loadConfigByInfo(int ret, String config); - - public abstract void callback_checkConfigByInfo(int ret, String result); - -} diff --git a/core/src/main/java/com/qq/tars/support/config/prx/GetConfigListInfo.java b/core/src/main/java/com/qq/tars/support/config/prx/GetConfigListInfo.java index b793671b..7c9e8167 100644 --- a/core/src/main/java/com/qq/tars/support/config/prx/GetConfigListInfo.java +++ b/core/src/main/java/com/qq/tars/support/config/prx/GetConfigListInfo.java @@ -20,10 +20,11 @@ package com.qq.tars.support.config.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class GetConfigListInfo { diff --git a/core/src/main/java/com/qq/tars/support/log/ArrayWriter.java b/core/src/main/java/com/qq/tars/support/log/ArrayWriter.java deleted file mode 100644 index 6ec722b5..00000000 --- a/core/src/main/java/com/qq/tars/support/log/ArrayWriter.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.support.log; - -import java.io.PrintWriter; -import java.io.Writer; -import java.util.ArrayList; - -final class ArrayWriter extends PrintWriter { - - private ArrayList alist; - - public ArrayWriter() { - super(new NullWriter()); - alist = new ArrayList(); - } - - @Override - public void print(Object o) { - alist.add(o.toString()); - } - - @Override - public void print(char[] chars) { - alist.add(new String(chars)); - } - - @Override - public void print(String s) { - alist.add(s); - } - - @Override - public void println(Object o) { - alist.add(o.toString()); - } - - @Override - public void println(char[] chars) { - alist.add(new String(chars)); - } - - @Override - public void println(String s) { - alist.add(s); - } - - @Override - public void write(char[] chars) { - alist.add(new String(chars)); - } - - @Override - public void write(char[] chars, int off, int len) { - alist.add(new String(chars, off, len)); - } - - @Override - public void write(String s, int off, int len) { - alist.add(s.substring(off, off + len)); - } - - @Override - public void write(String s) { - alist.add(s); - } - - public String[] toStringArray() { - int len = alist.size(); - String[] result = new String[len]; - for (int i = 0; i < len; i++) { - result[i] = alist.get(i); - } - return result; - } -} - -class NullWriter extends Writer { - - @Override - public void close() { - } - - @Override - public void flush() { - } - - @Override - public void write(char[] cbuf, int off, int len) { - } -} diff --git a/core/src/main/java/com/qq/tars/support/log/LogConfCacheMngr.java b/core/src/main/java/com/qq/tars/support/log/LogConfCacheMngr.java deleted file mode 100644 index 4f26bd96..00000000 --- a/core/src/main/java/com/qq/tars/support/log/LogConfCacheMngr.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.support.log; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Date; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.qq.tars.common.util.StringUtils; - -public class LogConfCacheMngr { - - private final static String LOG_CACHE_FILE = "log_conf.dat"; - private final static String KEY_LOG_LEVEL = "level"; - - private final static LogConfCacheMngr instance = new LogConfCacheMngr(); - - private final Properties props = new Properties(); - private final AtomicBoolean propsInited = new AtomicBoolean(); - - private String dataPath; - - private LogConfCacheMngr() { - } - - public static LogConfCacheMngr getInstance() { - return instance; - } - - public void init(String theDataPath) { - System.out.println("init dataPath=" + theDataPath); - this.dataPath = theDataPath; - loadCacheData(); - } - - public String get(String key) { - loadCacheData(); - return props.getProperty(key); - } - - public String getLevel() { - loadCacheData(); - String level = props.getProperty(KEY_LOG_LEVEL); - System.out.println("level=" + level); - return level; - } - - public void set(String key, String value) { - loadCacheData(); - props.setProperty(key, value); - } - - public void updateLevel(String level) { - loadCacheData(); - props.setProperty(KEY_LOG_LEVEL, level); - saveToLocal(); - } - - private File getCacheFile() throws Exception { - if (StringUtils.isEmpty(dataPath)) { - System.out.println("dataPath is null"); - return null; - } - File f = new File(dataPath, LOG_CACHE_FILE); - if (!f.exists()) { - f.createNewFile(); - } - return f; - } - - private void saveToLocal() { - OutputStream out = null; - try { - File file = getCacheFile(); - if (file == null) { - return; - } - out = new BufferedOutputStream(new FileOutputStream(file)); - props.store(out, (new Date()).toString()); - } catch (Exception e) { - System.out.println("FATAL j4log | save j4log cache file failed: " + e.getMessage()); - e.printStackTrace(System.out); - } finally { - if (null != out) { - try { - out.close(); - } catch (IOException e) { - } - } - } - } - - private void loadCacheData() { - if (propsInited.get()) { - return; - } - - if (StringUtils.isEmpty(dataPath)) { - return; - } - - if (propsInited.compareAndSet(false, true)) { - InputStream in = null; - try { - File file = getCacheFile(); - if (file == null) { - return; - } - in = new BufferedInputStream(new FileInputStream(file)); - props.load(in); - - System.out.println("prop=" + props.toString()); - } catch (Exception e) { - System.out.println("FATAL j4log | load j4log cache file failed: " + e.getMessage()); - e.printStackTrace(System.out); - } finally { - if (null != in) { - try { - in.close(); - } catch (IOException e) { - } - } - } - } - } -} diff --git a/core/src/main/java/com/qq/tars/support/log/LogItem.java b/core/src/main/java/com/qq/tars/support/log/LogItem.java deleted file mode 100644 index 8c442640..00000000 --- a/core/src/main/java/com/qq/tars/support/log/LogItem.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.support.log; - -import com.qq.tars.support.log.Logger.Level; -import com.qq.tars.support.log.util.Utils; - -public final class LogItem { - - private long time; - - private Level level; - - private String str; - - private boolean dyeFlag; - - private String dyeFileName; - - private String dyeServantName; - - private ThrowableInfo throwInfo = null; - - public LogItem(Level level, String str, boolean dyeFlag, String dyeFileName, String dyeServantName, Throwable th) { - this.time = System.currentTimeMillis(); - this.level = level; - this.str = str; - this.dyeFlag = dyeFlag; - this.dyeFileName = dyeFileName; - this.dyeServantName = dyeServantName; - if (th != null) { - this.throwInfo = new ThrowableInfo(th); - } - } - - public long getTime() { - return this.time; - } - - public String getStr() { - return this.str; - } - - public boolean getDyeFlag() { - return this.dyeFlag; - } - - public String getDyeFileName() { - return this.dyeFileName; - } - - public String getDyeServantName() { - return this.dyeServantName; - } - - public ThrowableInfo getThrowInfo() { - return this.throwInfo; - } - - String toStringNoEndReturn() { - StringBuilder strBuf = new StringBuilder(); - strBuf.append(Utils.getDateAllInfo(this.time)).append("\t"); - strBuf.append(this.level.name()).append("\t"); - strBuf.append(this.str); - if (this.throwInfo != null) { - strBuf.append(this.throwInfo.getThrowableStr()); - } - - return strBuf.toString(); - } - - public String toDyeingString() { - StringBuilder strBuf = new StringBuilder(); - strBuf.append(this.dyeServantName).append("|"); - strBuf.append(Utils.getDateAllInfo(this.time)).append("\t"); - strBuf.append(this.level.name()).append("\t"); - strBuf.append(this.str).append("\n"); - if (this.throwInfo != null) { - strBuf.append(this.throwInfo.getThrowableStr()); - } - return strBuf.toString(); - } - - @Override - public String toString() { - StringBuilder strBuf = new StringBuilder(); - strBuf.append(Utils.getDateAllInfo(this.time)).append("\t"); - strBuf.append(this.level.name()).append("\t"); - strBuf.append(this.str).append("\n"); - if (this.throwInfo != null) { - strBuf.append(this.throwInfo.getThrowableStr()); - } - return strBuf.toString(); - } -} diff --git a/core/src/main/java/com/qq/tars/support/log/LogWorkThread.java b/core/src/main/java/com/qq/tars/support/log/LogWorkThread.java deleted file mode 100644 index d2bea375..00000000 --- a/core/src/main/java/com/qq/tars/support/log/LogWorkThread.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.support.log; - -import java.util.Collection; - -import com.qq.tars.support.log.Logger.LogType; - -final class LogWorkThread implements Runnable { - - private LogType logType; - - public LogWorkThread(LogType logType) { - this.logType = logType; - } - - @Override - public void run() { - while (!Thread.interrupted()) { - try { - Thread.sleep(500); - - Collection coll = LoggerFactory.getLoggerMap().values(); - for (Logger logger : coll) { - if (this.logType.getValue() == logger.getLogType().getValue()) { - try { - logger.doWriteLog(); - } catch (Exception e) { - } - } - } - } catch (InterruptedException e) { - break; - } catch (Exception e) { - e.printStackTrace(); - } - } - } - -} diff --git a/core/src/main/java/com/qq/tars/support/log/Logger.java b/core/src/main/java/com/qq/tars/support/log/Logger.java deleted file mode 100644 index 800c9bc6..00000000 --- a/core/src/main/java/com/qq/tars/support/log/Logger.java +++ /dev/null @@ -1,689 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.support.log; - -import java.io.BufferedWriter; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.nio.channels.FileLock; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; -import java.util.Queue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.atomic.AtomicInteger; - -import com.qq.tars.common.util.DyeingSwitch; -import com.qq.tars.context.DistributedContext; -import com.qq.tars.context.DistributedContextManager; -import com.qq.tars.server.config.ConfigurationManager; -import com.qq.tars.server.config.ServerConfig; -import com.qq.tars.support.log.prx.LogInfo; -import com.qq.tars.support.log.prx.LogPrx; -import com.qq.tars.support.log.util.Utils; - -public class Logger { - - public static Logger getLogger(String name) { - return LoggerFactory.getLogger(name); - } - - public static Logger getLogger(String name, LogType logType) { - return LoggerFactory.getLogger(name, logType); - } - - public static enum LogType { - LOCAL(0), REMOTE(1), ALL(2); - - private int value; - - private LogType(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - } - - public static enum Level { - DEBUG(0), INFO(1), WARN(2), ERROR(3), FATAL(4); - - private int value; - - private Level(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - - } - - private static final int MAX_BATCH_SIZE = 1024 * 1024; - - private static final String STDOUT_LOG = "stdout.log"; - - private LogType logType = LogType.LOCAL; - - private String failLogPath; - - private AtomicInteger failedCount = new AtomicInteger(0); - - private static final int failedThreshold = 50; - - protected final String name; - - protected String logPath; - - protected Level level = null; - - protected final LinkedBlockingQueue logQueue = new LinkedBlockingQueue(50000); - - protected final ConcurrentHashMap> dyeLogQueue = new ConcurrentHashMap>(); - - Logger(String name) { - this(name, Level.INFO, null, null); - } - - Logger(String name, Level level, String filePath) { - this.name = name; - this.level = level; - this.logPath = filePath; - } - - // Logger(String name, Level level, String path, String pattern) - // { - // this(name, level, path, null, pattern); - // } - - Logger(String name, Level level, String filePath, String failLogPath) { - this(name, level, filePath); - this.failLogPath = failLogPath; - - // if (StringUtil.isEmpty(pattern)) - // { - // formatter = new PatternFormatter(); - // } - // else - // { - // formatter = new PatternFormatter(pattern); - // } - } - - Logger(String name, Level level, LogType logType, String localPath, String failLogPath) { - this(name, level, localPath); - this.logType = logType; - this.failLogPath = failLogPath; - } - - public boolean isDebugEnabled() { - return Level.DEBUG.value >= this.level.value; - } - - public boolean isInfoEnabled() { - return Level.INFO.value >= this.level.value; - } - - public void debug(String str) { - debug(str, null, null); - } - - public void debug(String str, Throwable th) { - debug(str, th, null); - - } - - protected void debug(String format, Throwable th, Object[] arguments) { - if (isDebugEnabled()) { - // formatLogMsg(Level.DEBUG, format, arguments, th); - log(Level.DEBUG, format, th); - } - } - - public void info(String str) { - info(str, null, null); - } - - public void info(String str, Throwable th) { - info(str, th, null); - } - - protected void info(String format, Throwable th, Object[] arguments) { - if (this.isInfoEnabled()) { - // formatLogMsg(Level.INFO, format, arguments, th); - log(Level.INFO, format, th); - } - } - - public void warn(String str) { - warn(str, null, null); - } - - public void warn(String str, Throwable th) { - warn(str, th, null); - } - - protected void warn(String format, Throwable th, Object[] arguments) { - // formatLogMsg(Level.WARN, format, arguments, th); - log(Level.WARN, format, th); - } - - public void error(String str) { - error(str, null, null); - } - - public void error(String str, Throwable th) { - error(str, th, null); - } - - protected void error(String format, Throwable th, Object[] arguments) { - // formatLogMsg(Level.ERROR, format, arguments, th); - log(Level.ERROR, format, th); - } - - public void fatal(String str) { - fatal(str, null, null); - } - - public void fatal(String str, Throwable th) { - fatal(str, th, null); - } - - protected void fatal(String format, Throwable th, Object[] arguments) { - // formatLogMsg(Level.FATAL, format, arguments, th); - log(Level.FATAL, format, th); - } - - protected void log(Level level, String str, Throwable th) { - if (LoggerFactory.isNoneEnabled()) { - return; - } - - if (str == null) { - str = ""; - } - - Boolean dyeFlag = false; - String dyeFileName = null; - String dyeServantName = null; - DistributedContext distributedContext = DistributedContextManager.getDistributedContext(); - if (null != distributedContext.get(DyeingSwitch.BDYEING)) { - dyeFlag = distributedContext.get(DyeingSwitch.BDYEING); - dyeFileName = distributedContext.get(DyeingSwitch.FILENAME); - ServerConfig config = ConfigurationManager.getInstance().getServerConfig(); - dyeServantName = config == null ? "no Tars" : config.getServerName(); - } - - if (isNeedLocal() && this.logPath == null) { - putLogToDefault(level, str, th); - return; - } - - LogItem logItem = new LogItem(level, str, dyeFlag, dyeFileName, dyeServantName, th); - boolean result = getQueue().offer(logItem); - - if (dyeFlag == true) { - LinkedBlockingQueue subItems = dyeLogQueue.get(dyeFileName); - if (subItems == null) { - subItems = new LinkedBlockingQueue(); - dyeLogQueue.putIfAbsent(dyeFileName, subItems); - subItems = dyeLogQueue.get(dyeFileName); - } - subItems.offer(logItem); - } - - if (!result) { - putLogToDefault(level, str, th); - if (isNeedRemote()) { - failedCount.getAndIncrement(); - } - } else if (failedCount.get() > 0) { - failedCount.set(0); - } - } - - private void putLogToDefault(Level level, String str, Throwable th) { - if (!LoggerFactory.getDefaultLog().equals(this.name)) { - Logger.getLogger(LoggerFactory.getDefaultLog()).log(level, this.name + "\t" + str, th); - } - } - - protected void doWriteLog() { - if (logQueue.isEmpty()) { - return; - } - - if (LogType.LOCAL.value == this.logType.value) { - writeAllToLocal(logPath); - writeDyeToLocal(false); - } else if (LogType.REMOTE.value == this.logType.value) { - writeRemoteLog(); - writeDyeToRemote(); - } else { - writeLocalAndRemoteLog(); - writeDyeLocalAndRemoteLog(); - } - } - - private void writeDyeToLocal(boolean isLost) { - if (dyeLogQueue == null || dyeLogQueue.isEmpty()) { - return; - } - BufferedWriter bw = null; - FileLock lock = null; - Iterator>> iterator = dyeLogQueue.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry> entry = iterator.next(); - try { - if (!entry.getValue().isEmpty()) { - String fileName = isLost == true ? entry.getKey() + "_dyeing.lost." : entry.getKey() + "_dyeing."; - FileOutputStream outputStream = new FileOutputStream(LoggerFactory.dyeingLogRoot + fileName + - Utils.getDateSimpleInfo(System.currentTimeMillis()), true); - do { - lock = outputStream.getChannel().tryLock(); - } while (lock == null); - - bw = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); - LogItem item = null; - while ((item = entry.getValue().poll()) != null) { - bw.write(item.toDyeingString()); - } - } - } catch (IOException ex) { - - } finally { - if (lock != null) { - try { - lock.release(); - lock = null; - } catch (IOException e) { - } - } - if (bw != null) { - try { - bw.close(); - } catch (IOException e) { - } - } - } - } - } - - private void writeDyeToRemote() { - if (dyeLogQueue == null || dyeLogQueue.isEmpty()) { - return; - } - - LogPrx proxy = LoggerFactory.getLoggerPrxHelper(); - if (proxy == null) { - writeDyeToLocal(true); - return; - } - Iterator>> iterator = dyeLogQueue.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry> entry = iterator.next(); - - if (proxy != null) { - boolean succ = false; - LogInfo logInfo = getDyeingInfo(entry.getKey()); - while (!entry.getValue().isEmpty()) { - ArrayList logs = new ArrayList(); - getDyeingLogsBySize(entry.getKey(), logs); - try { - proxy.loggerbyInfo(logInfo, logs); - succ = true; - } catch (Exception e) { - succ = false; - } finally { - if (succ == false) { - writeDyeToLocal(logs, LoggerFactory.dyeingLogRoot + entry.getKey() + "_dyeing.lost"); - } - } - } - } - } - } - - private void writeDyeLocalAndRemoteLog() { - if (dyeLogQueue == null || dyeLogQueue.isEmpty()) { - return; - } - - LogPrx proxy = LoggerFactory.getLoggerPrxHelper(); - if (proxy == null) { - writeDyeToLocal(false); - return; - } - Iterator>> iterator = dyeLogQueue.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry> entry = iterator.next(); - boolean succ = false; - LogInfo logInfo = getDyeingInfo(entry.getKey()); - while (!entry.getValue().isEmpty()) { - ArrayList logs = new ArrayList(); - getDyeingLogsBySize(entry.getKey(), logs); - try { - writeDyeToLocal(logs, LoggerFactory.dyeingLogRoot + entry.getKey() + "_dyeing"); - proxy.loggerbyInfo(logInfo, logs); - succ = true; - } catch (Exception e) { - succ = false; - } finally { - if (!succ) { - writeDyeToLocal(false); - } - } - } - } - } - - private void writeAllToLocal(String file) { - boolean succ = false; - if (file != null) { - BufferedWriter bw = null; - try { - if (!logQueue.isEmpty()) { - bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file + "." + Utils.getDateSimpleInfo(System.currentTimeMillis()), true), "UTF-8")); - LogItem item = null; - while ((item = logQueue.poll()) != null) { - bw.write(item.toString()); - } - } - succ = true; - } catch (IOException ex) { - - } finally { - if (bw != null) { - try { - bw.close(); - } catch (IOException e) { - } - } - } - } - if (!succ) { - LogItem item = null; - while ((item = logQueue.poll()) != null && !STDOUT_LOG.equals(name)) { - System.out.print("\t" + item.toString()); - } - } - } - - private void writeLocalAndRemoteLog() { - if (isReachedFailedThreshold()) { - writeAllToLocal(getLogPath()); - return; - } - - LogPrx proxy = LoggerFactory.getLoggerPrxHelper(); - if (proxy != null) { - boolean succ = false; - LogInfo loginfo = getLogInfo(); - - while (!getQueue().isEmpty()) { - ArrayList logs = new ArrayList(); - getLogsBySize(logs); - - try { - writeToLocal(logs, getLogPath()); - proxy.loggerbyInfo(loginfo, logs); - succ = true; - } catch (Exception e) { - succ = false; - } finally { - if (!succ && getLogPath() != null) { - writeAllToLocal(getLogPath()); - } - } - } - } else { - writeAllToLocal(getLogPath()); - } - } - - private LogInfo getLogInfo() { - LogInfo loginfo = null; - if (!getQueue().isEmpty()) { - loginfo = new LogInfo(); - loginfo.setAppname(LoggerFactory.getAppName()); - loginfo.setServername(LoggerFactory.getServiceNameName()); - loginfo.setSFilename(this.name); - loginfo.setSFormat("%Y%m%d%H"); - } - return loginfo; - } - - private LogInfo getDyeingInfo(String name) { - LogInfo loginfo = null; - if (dyeLogQueue.get(name) != null && !dyeLogQueue.get(name).isEmpty()) { - loginfo = new LogInfo(); - loginfo.setAppname("tars_dyeing"); - loginfo.setServername("dyeing"); - loginfo.setSFilename(name + "_dyeing"); - loginfo.setSFormat("%Y%m%d%H"); - } - return loginfo; - } - - private void writeDyeToLocal(ArrayList content, String file) { - Writer bw = null; - FileLock lock = null; - try { - FileOutputStream os = null; - try { - os = new FileOutputStream(file + "." + Utils.getDateSimpleInfo(System.currentTimeMillis()), true); - do { - lock = os.getChannel().tryLock(); - } while (null == lock); - - bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); - for (String s : content) { - bw.write(s); - } - bw.flush(); - return; - } catch (Exception e) { - } - } finally { - if (lock != null) { - try { - lock.release(); - lock = null; - } catch (IOException e) { - } - } - if (bw != null) { - try { - bw.close(); - } catch (IOException e) { - } - } - } - } - - private void writeRemoteLog() { - if (isReachedFailedThreshold()) { - writeAllToLocal(getLogPath()); - return; - } - - LogPrx proxy = LoggerFactory.getLoggerPrxHelper(); - if (proxy != null) { - boolean succ = false; - LogInfo loginfo = getLogInfo(); - - while (!getQueue().isEmpty()) { - ArrayList logs = new ArrayList(); - getLogsBySize(logs); - - try { - try { - proxy.loggerbyInfo(loginfo, logs); - succ = true; - } catch (Exception e) { - succ = false; - } - //retry one - if (!succ) { - proxy.loggerbyInfo(loginfo, logs); - succ = true; - } - } catch (Exception e) { - succ = false; - } finally { - if (!succ && getFailLogPath() != null) { - writeToLocal(logs, getFailLogPath()); - } - } - } - } else { - writeAllToLocal(getFailLogPath()); - } - } - - private boolean isReachedFailedThreshold() { - return failedCount.get() > failedThreshold; - } - - private void getLogsBySize(ArrayList logs) { - int size = 0; - String logContent; - while (size < MAX_BATCH_SIZE && !getQueue().isEmpty()) { - logContent = getQueue().poll().toString(); - logs.add(logContent); - - try { - size += logContent.getBytes("UTF-8").length; - } catch (UnsupportedEncodingException e) { - } - } - } - - private void getDyeingLogsBySize(String fileName, ArrayList logs) { - int size = 0; - String logContent; - LinkedBlockingQueue subItems = dyeLogQueue.get(fileName); - while (size < MAX_BATCH_SIZE && subItems != null && !subItems.isEmpty()) { - LogItem item = subItems.poll(); - logContent = item.toDyeingString(); - logs.add(logContent); - try { - size += logContent.getBytes("UTF-8").length; - } catch (UnsupportedEncodingException e) { - } - } - } - - private void writeToLocal(ArrayList content, String file) { - Writer bw = null; - try { - OutputStream os = null; - try { - os = new FileOutputStream(file + "." + Utils.getDateSimpleInfo(System.currentTimeMillis()), true); - bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); - for (String s : content) { - bw.write(s); - } - bw.flush(); - return; - } catch (Exception e) { - } - } finally { - if (bw != null) { - try { - bw.close(); - } catch (IOException e) { - } - } - } - } - - boolean isNeedLocal() { - return LogType.LOCAL.value == this.logType.value || LogType.ALL.value == this.logType.value; - } - - boolean isNeedRemote() { - return LogType.REMOTE.value == this.logType.value || LogType.ALL.value == this.logType.value; - } - - boolean isLocalLog() { - return LogType.LOCAL.value == this.logType.value; - } - - boolean isRemoteLog() { - return LogType.REMOTE.value == this.logType.value; - } - - boolean isAllLog() { - return LogType.ALL.value == this.logType.value; - } - - Level getLevel() { - return level; - } - - String getName() { - return name; - } - - String getLogPath() { - return logPath; - } - - void setLogPath(String logPath) { - this.logPath = logPath; - } - - String getFailLogPath() { - return failLogPath; - } - - Queue getQueue() { - return logQueue; - } - - void setFailLogPath(String path) { - this.failLogPath = path; - } - - void setLevel(Level level) { - if (level == null) { - throw new NullPointerException("Logger Level is null."); - } - this.level = level; - } - - LogType getLogType() { - return logType; - } - - void setLogType(LogType logType) { - this.logType = logType; - } - - @Override - public String toString() { - return "Logger [name=" + name + ", level=" + level + ", logType=" + logType + ", logPath=" + logPath + ", failLogPath=" + failLogPath + "]"; - } -} diff --git a/core/src/main/java/com/qq/tars/support/log/LoggerFactory.java b/core/src/main/java/com/qq/tars/support/log/LoggerFactory.java deleted file mode 100644 index 92903e2f..00000000 --- a/core/src/main/java/com/qq/tars/support/log/LoggerFactory.java +++ /dev/null @@ -1,343 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.support.log; - -import java.io.File; -import java.io.IOException; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.qq.tars.client.Communicator; -import com.qq.tars.common.util.StringUtils; -import com.qq.tars.support.log.Logger.Level; -import com.qq.tars.support.log.Logger.LogType; -import com.qq.tars.support.log.prx.LogPrx; -import com.qq.tars.support.log.util.Utils; - -public class LoggerFactory { - - private static final String LEVEL_NONE = "NONE"; - - private static volatile boolean isInit = false; - - private static volatile boolean isNone = false; - - protected static String defaultLogRoot; - - protected static String dyeingLogRoot; - - protected static Level defaultLogLevel = Level.INFO; - - private static final String DEFAULT_LOG = "_default"; - - private static String appName = ""; - - private static String serviceName = ""; - - private static String objName = ""; - - private volatile static Communicator communicator = null; - - private static final ConcurrentHashMap loggerMap = new ConcurrentHashMap(128); - - private static Thread th; - - private static Thread thRemote; - - private static Thread threadAll; - - static { - loadLogConfCache(); - start(); - } - - private static void loadLogConfCache() { - String cacheLevel = LogConfCacheMngr.getInstance().getLevel(); - if (StringUtils.isEmpty(cacheLevel)) { - return; - } - - loadCacheLevel(cacheLevel, false); - } - - private static void loadCacheLevel(String cacheLevel, boolean isNeedFreshMap) { - if (LEVEL_NONE.equals(cacheLevel)) { - isNone = true; - System.out.println("INFO tars-log | reset tars-log default level=NONE"); - return; - } - - if (defaultLogLevel.toString().equals(cacheLevel)) { - return; - } - - defaultLogLevel = Level.valueOf(cacheLevel); - if (isNeedFreshMap) { - refreshLoggerLevel(); - } - - System.out.println("INFO tars-log | reset tars-log default level=" + defaultLogLevel); - } - - static Logger getLogger(String name) { - Logger logger = loggerMap.get(name); - if (logger == null) { - synchronized (LoggerFactory.class) { - logger = loggerMap.get(name); - if (logger == null) { - logger = new Logger(name, defaultLogLevel, null); - addDefaultLocalLog(logger); - getLogger(name); - } - } - } - return logger; - } - - static Logger getLogger(String name, LogType type) { - Logger logger = getLogger(name); - logger.setLogType(type); - retouchRemoteLog(logger); - return logger; - } - - static Map getLoggerMap() { - return Collections.unmodifiableMap(loggerMap); - } - - static LogPrx getLoggerPrxHelper() { - if (communicator == null) { - return null; - } - return communicator.stringToProxy(LogPrx.class, objName); - - } - - private static void start() { - try { - th = new Thread(new LogWorkThread(LogType.LOCAL), "LocalJ4logThread"); - th.start(); - thRemote = new Thread(new LogWorkThread(LogType.REMOTE), "RemoteJ4logThread"); - thRemote.start(); - threadAll = new Thread(new LogWorkThread(LogType.ALL), "AllJ4logThread"); - threadAll.start(); - } catch (Exception e) { - System.out.println("FATAL tars-log | init failed:" + e.getMessage()); - e.printStackTrace(System.out); - } - - } - - public static void stop() { - try { - th.interrupt(); - thRemote.interrupt(); - threadAll.interrupt(); - } catch (Exception e) { - System.out.println("FATAL j4log | init failed:" + e.getMessage()); - e.printStackTrace(System.out); - } - - } - - public synchronized static void config(Communicator communicator, String objName, String appName, - String serviceName, String defaultLevel, String defaultRoot) { - if (isInit) { - return; - } - - if (communicator == null || StringUtils.isEmpty(objName)) { - System.out.println("ERROR tars-log | config error: locator and objName can't be empty."); - } else { - LoggerFactory.communicator = communicator; - LoggerFactory.objName = objName; - } - - LoggerFactory.appName = appName; - LoggerFactory.serviceName = serviceName; - - configDefaultRootAndLevel(defaultLevel, defaultRoot); - - isInit = true; - } - - public synchronized static void config(String defaultLevel, String defaultRoot) { - configDefaultRootAndLevel(defaultLevel, defaultRoot); - - } - - public synchronized static void setDefaultLoggerLevel(String level) { - if (StringUtils.isEmpty(level)) { - System.out.println("ERROR tars-log | reset tars-log default level error, level is empty."); - return; - } - - loadCacheLevel(level, true); - } - - private static void refreshLoggerLevel() { - for (java.util.Map.Entry loggerEntry : loggerMap.entrySet()) { - Logger logger = loggerEntry.getValue(); - logger.setLevel(defaultLogLevel); - } - } - - private static void configDefaultRootAndLevel(String defaultLevel, String defaultRoot) { - if (StringUtils.isNotEmpty(defaultLevel)) { - defaultLogLevel = Level.valueOf(defaultLevel.trim().toUpperCase()); - } - - System.out.println("INFO tars-log | set tars-log default level=" + defaultLogLevel); - - String logRootStr = selectLogRoot(defaultRoot); - if (logRootStr != null) { - defaultLogRoot = formatPath(logRootStr); - System.out.println("INFO tars-log | set tars-log defaultRoot=" + defaultLogRoot); - } else { - System.out.println("ERROR tars-log | config error, set tars-log defaultRoot=" + defaultLogRoot); - } - dyeingLogRoot = defaultLogRoot + "/tars_dyeing/"; - File logRoot = new File(dyeingLogRoot); - if (!logRoot.exists()) { - logRoot.mkdir(); - } - } - - private static String selectLogRoot(String defaultRoot) { - if (StringUtils.isNotEmpty(defaultRoot)) { - File logRoot = new File(defaultRoot); - if (logRoot.isDirectory() && logRoot.canWrite()) { - return defaultRoot; - } - } - - if (StringUtils.isNotEmpty(defaultLogRoot)) { - return null; - } - - System.out.println("INFO tars-log | try to set tars-log.root from java system property (server.root)"); - String serverRoot = System.getProperty("server.root", ""); - serverRoot = serverRoot.trim() + File.separator + "log"; - File logRoot = new File(serverRoot); - if (!logRoot.exists()) { - logRoot.mkdir(); - } - if (logRoot.isDirectory() && logRoot.canWrite()) { - return serverRoot; - } - - return null; - } - - static String formatPath(String path) { - if (path != null) { - path = path.replaceAll("[/]+", "/"); - path = path.replaceAll("[/]+$", ""); - path = path.replaceAll("[\\\\]+$", ""); - } - - return path + File.separatorChar; - } - - static boolean testFile(String filePath) { - if (filePath == null || filePath.trim().isEmpty() || !filePath.contains("/") && !filePath.contains("\\")) { - return false; - } - try { - File f = new File(filePath + "." + Utils.getDateSimpleInfo(System.currentTimeMillis())); - f.createNewFile(); - if (!f.canWrite()) { - return false; - } - - if (f.length() == 0) { - f.delete(); - } - } catch (IOException e) { - return false; - } - return true; - } - - private static void addDefaultLocalLog(Logger log) { - retouchLocalLog(log); - updateLoggerMap(log); - } - - static void retouchLocalLog(Logger log) { - if (log.getLevel() == null) { - log.setLevel(defaultLogLevel); - } - if (log.getLogPath() == null || !testFile(log.getLogPath())) { - String path = defaultLogRoot + log.getName(); - log.setLogPath(path); - if (!testFile(path)) { - log.setLogPath(null); - System.out.println("ERROR tars-log | set logger(" + log.getName() + ")local log path to default path(" + path + ") failed"); - } - } - } - - private static void retouchRemoteLog(Logger logger) { - if (logger.getLogType() == LogType.LOCAL) { - return; - } - - if (logger.getFailLogPath() == null || !testFile(logger.getFailLogPath())) { - String failPath = defaultLogRoot + logger.getName() + ".lost"; - logger.setFailLogPath(failPath); - if (!testFile(failPath)) { - logger.setFailLogPath(null); - - } - } - } - - private static synchronized void updateLoggerMap(Logger logger) { - Logger log = loggerMap.get(logger.getName()); - - if (log == null) { - loggerMap.put(logger.getName(), logger); - } else { - log.setLevel(logger.getLevel()); - log.setLogType(logger.getLogType()); - log.setLogPath(logger.getLogPath()); - log.setFailLogPath(logger.getFailLogPath()); - } - } - - static String getAppName() { - return appName; - } - - static String getServiceNameName() { - return serviceName; - } - - static String getObjName() { - return objName; - } - - static String getDefaultLog() { - return DEFAULT_LOG; - } - - static boolean isNoneEnabled() { - return isNone; - } -} diff --git a/core/src/main/java/com/qq/tars/support/log/LoggingOutputStream.java b/core/src/main/java/com/qq/tars/support/log/LoggingOutputStream.java deleted file mode 100644 index 5fff063f..00000000 --- a/core/src/main/java/com/qq/tars/support/log/LoggingOutputStream.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.support.log; - -import java.io.IOException; -import java.io.OutputStream; - -public class LoggingOutputStream extends OutputStream { - - protected static final String LINE_SEPERATOR = System.getProperty("line.separator"); - - protected boolean hasBeenClosed = false; - - protected byte[] buf; - - protected int count; - - private int bufLength; - - private Logger output = null; - - public static final int DEFAULT_BUFFER_LENGTH = 2048; - - public LoggingOutputStream(Logger output) { - this.output = output; - this.bufLength = DEFAULT_BUFFER_LENGTH; - this.buf = new byte[DEFAULT_BUFFER_LENGTH]; - this.count = 0; - } - - public void close() { - _flush(true); - hasBeenClosed = true; - } - - public void flush() { - _flush(false); - } - - private void reset() { - count = 0; - } - - @Override - public void write(int b) throws IOException { - if (hasBeenClosed) { - throw new IOException("The stream has been closed."); - } - - if (b == 0) return; - - if (count == bufLength) { - final int newBufLength = bufLength + DEFAULT_BUFFER_LENGTH; - final byte[] newBuf = new byte[newBufLength]; - System.arraycopy(buf, 0, newBuf, 0, bufLength); - buf = newBuf; - bufLength = newBufLength; - } - - buf[count] = (byte) b; - count++; - - } - - private void _flush(boolean writeToFile) { - if (count == 0) { - if (writeToFile) doWriteLog(); - return; - } - - if (count == LINE_SEPERATOR.length()) { - if (((char) buf[0]) == LINE_SEPERATOR.charAt(0) && ((count == 1) || ((count == 2) && ((char) buf[1]) == LINE_SEPERATOR.charAt(1)))) { - reset(); - return; - } - } - - final byte[] theBytes = new byte[count]; - System.arraycopy(buf, 0, theBytes, 0, count); - this.output.info(new String(theBytes)); - - if (writeToFile) doWriteLog(); - - reset(); - } - - private void doWriteLog() { - try { - this.output.doWriteLog(); - } catch (Exception ex) { - }; - } -} diff --git a/core/src/main/java/com/qq/tars/support/log/ThrowableInfo.java b/core/src/main/java/com/qq/tars/support/log/ThrowableInfo.java deleted file mode 100644 index b7faee64..00000000 --- a/core/src/main/java/com/qq/tars/support/log/ThrowableInfo.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.support.log; - -final class ThrowableInfo { - - private transient Throwable throwable; - private String[] rep; - - public ThrowableInfo(Throwable throwable) { - this.throwable = throwable; - } - - public Throwable getThrowable() { - return throwable; - } - - public String[] getThrowableStrArr() { - if (throwable == null) { - return null; - } - - if (rep != null) { - return rep.clone(); - } else { - ArrayWriter aw = new ArrayWriter(); - throwable.printStackTrace(aw); - rep = aw.toStringArray(); - return rep; - } - } - - public String getThrowableStr() { - String[] arr = getThrowableStrArr(); - if (arr == null) { - return ""; - } - - StringBuilder strBuf = new StringBuilder(); - for (int i = 0; i < arr.length; i++) { - strBuf.append(arr[i]).append("\n"); - } - return strBuf.toString(); - } -} diff --git a/core/src/main/java/com/qq/tars/support/log/prx/LogInfo.java b/core/src/main/java/com/qq/tars/support/log/prx/LogInfo.java index f6c578a1..9da103ff 100644 --- a/core/src/main/java/com/qq/tars/support/log/prx/LogInfo.java +++ b/core/src/main/java/com/qq/tars/support/log/prx/LogInfo.java @@ -20,10 +20,11 @@ package com.qq.tars.support.log.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class LogInfo { diff --git a/core/src/main/java/com/qq/tars/support/log/prx/LogPrx.java b/core/src/main/java/com/qq/tars/support/log/prx/LogPrx.java index 2ee57a8b..2ea416bc 100644 --- a/core/src/main/java/com/qq/tars/support/log/prx/LogPrx.java +++ b/core/src/main/java/com/qq/tars/support/log/prx/LogPrx.java @@ -20,70 +20,46 @@ package com.qq.tars.support.log.prx; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.annotation.*; -import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsContext; + +import java.util.concurrent.CompletableFuture; @Servant public interface LogPrx { - /** - * 记录远程日志 - * @param app, 应用名称 - * @param server, 服务名称 - * @param file, 文件名称 - * @param format, 日志时间格式(%Y%m%d) - * @param buffer, 日志内容 - */ - public void logger(String app, String server, String file, String format, java.util.List buffer); - /** - * 记录远程日志 - * @param app, 应用名称 - * @param server, 服务名称 - * @param file, 文件名称 - * @param format, 日志时间格式(%Y%m%d) - * @param buffer, 日志内容 - */ - public void logger(String app, String server, String file, String format, java.util.List buffer, @TarsContext java.util.Map ctx); - /** - * 记录远程日志 - * @param app, 应用名称 - * @param server, 服务名称 - * @param file, 文件名称 - * @param format, 日志时间格式(%Y%m%d) - * @param buffer, 日志内容 - */ - public void async_logger(@TarsCallback LogPrxCallback callback, String app, String server, String file, String format, java.util.List buffer); - /** - * 记录远程日志 - * @param app, 应用名称 - * @param server, 服务名称 - * @param file, 文件名称 - * @param format, 日志时间格式(%Y%m%d) - * @param buffer, 日志内容 - */ - public void async_logger(@TarsCallback LogPrxCallback callback, String app, String server, String file, String format, java.util.List buffer, @TarsContext java.util.Map ctx); - /** - * 记录远程日志 - * @param info, LogInfo - * @param buffer, 日志内容 - */ - public void loggerbyInfo(LogInfo info, java.util.List buffer); - /** - * 记录远程日志 - * @param info, LogInfo - * @param buffer, 日志内容 - */ - public void loggerbyInfo(LogInfo info, java.util.List buffer, @TarsContext java.util.Map ctx); - /** - * 记录远程日志 - * @param info, LogInfo - * @param buffer, 日志内容 - */ - public void async_loggerbyInfo(@TarsCallback LogPrxCallback callback, LogInfo info, java.util.List buffer); - /** - * 记录远程日志 - * @param info, LogInfo - * @param buffer, 日志内容 - */ - public void async_loggerbyInfo(@TarsCallback LogPrxCallback callback, LogInfo info, java.util.List buffer, @TarsContext java.util.Map ctx); + /** + * Record remote logs + * @param app, Application Name + * @param server, Service name + * @param file, File name + * @param format, Log time format(%Y%m%d) + * @param buffer, Log contents + */ + public void logger(String app, String server, String file, String format, java.util.List buffer); + + /** + * Record remote logs + * @param app, Application Name + * @param server, Service name + * @param file, File name + * @param format, Log time format(%Y%m%d) + * @param buffer, Log contents + */ + public void logger(String app, String server, String file, String format, java.util.List buffer, @TarsContext java.util.Map ctx); + + /** + * Record remote logs + * @param info, LogInfo + * @param buffer, Log contents + */ + public void loggerbyInfo(LogInfo info, java.util.List buffer); + + CompletableFuture promise_loggerbyInfo(LogInfo info, java.util.List buffer); + + /** + * Record remote logs + * @param info, LogInfo + * @param buffer, Log contents + */ + public void loggerbyInfo(LogInfo info, java.util.List buffer, @TarsContext java.util.Map ctx); } diff --git a/core/src/main/java/com/qq/tars/support/log/prx/LogPrxCallback.java b/core/src/main/java/com/qq/tars/support/log/prx/LogPrxCallback.java deleted file mode 100644 index 66b26e69..00000000 --- a/core/src/main/java/com/qq/tars/support/log/prx/LogPrxCallback.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ -// ********************************************************************** -// This file was generated by a TARS parser! -// TARS version 1.0.1. -// ********************************************************************** - -package com.qq.tars.support.log.prx; - -import com.qq.tars.rpc.protocol.tars.support.TarsAbstractCallback; - -public abstract class LogPrxCallback extends TarsAbstractCallback { - - public abstract void callback_logger(); - - public abstract void callback_loggerbyInfo(); - -} diff --git a/core/src/main/java/com/qq/tars/support/log/util/Utils.java b/core/src/main/java/com/qq/tars/support/log/util/Utils.java deleted file mode 100644 index de2baa16..00000000 --- a/core/src/main/java/com/qq/tars/support/log/util/Utils.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.support.log.util; - -import java.util.Calendar; -import java.util.Date; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class Utils { - - public static String getFilePath(String path) { - if (path == null) return ""; - String r = "\\$\\{[^${}]*\\}"; - Pattern p = Pattern.compile(r); - Matcher m = p.matcher(path); - while (m.find()) { - int startIndex = m.start(); // index of start - int endIndex = m.end(); // index of end + 1 - String currentMatch = path.substring(startIndex, endIndex); - String property = System.getProperty(path.substring(startIndex + 2, endIndex - 1).trim()); - System.out.println("|tars-log|DEBUG|read java system property :" + currentMatch + "=" + property); - if (property == null) { - return ""; - } - path = replaceAll(path, currentMatch, property); - m = p.matcher(path); - } - return path; - } - - private static String replaceAll(String s, String src, String dest) { - if (s == null || src == null || dest == null || src.length() == 0) return s; - int pos = s.indexOf(src); - if (pos < 0) return s; - int capacity = dest.length() > src.length() ? s.length() * 2 : s.length(); - StringBuilder sb = new StringBuilder(capacity); - int writen = 0; - for (; pos >= 0;) { - sb.append(s, writen, pos); - sb.append(dest); - writen = pos + src.length(); - pos = s.indexOf(src, writen); - } - sb.append(s, writen, s.length()); - return sb.toString(); - } - - public static final String getDateSimpleInfo(long time) { - Date date = new Date(time); - Calendar ca = Calendar.getInstance(); - ca.setTime(date); - int month = 1 + ca.get(Calendar.MONTH); - String monthStr = String.valueOf(month); - if (month < 10) { - monthStr = "0" + monthStr; - } - int day = ca.get(Calendar.DAY_OF_MONTH); - String dayStr = String.valueOf(day); - if (day < 10) { - dayStr = "0" + dayStr; - } - String result = ca.get(Calendar.YEAR) + "-" + monthStr + "-" + dayStr; - return result; - } - - public static final String getDateAllInfo(long time) { - Date date = new Date(time); - Calendar ca = Calendar.getInstance(); - ca.setTime(date); - int month = 1 + ca.get(Calendar.MONTH); - String monthStr = String.valueOf(month); - if (month < 10) { - monthStr = "0" + monthStr; - } - int day = ca.get(Calendar.DAY_OF_MONTH); - String dayStr = String.valueOf(day); - if (day < 10) { - dayStr = "0" + dayStr; - } - int hour = ca.get(Calendar.HOUR_OF_DAY); - String hourStr = String.valueOf(hour); - if (hour < 10) { - hourStr = "0" + hourStr; - } - int minute = ca.get(Calendar.MINUTE); - String minuteStr = String.valueOf(minute); - if (minute < 10) { - minuteStr = "0" + minuteStr; - } - int second = ca.get(Calendar.SECOND); - String secondStr = String.valueOf(second); - if (second < 10) { - secondStr = "0" + second; - } - - StringBuilder strBuf = new StringBuilder(); - strBuf.append(ca.get(Calendar.YEAR)).append("-").append(monthStr).append("-").append(dayStr); - strBuf.append(" ").append(hourStr).append(":").append(minuteStr).append(":").append(secondStr).append(".").append(ca.get(Calendar.MILLISECOND)); - return strBuf.toString(); - } -} diff --git a/core/src/main/java/com/qq/tars/support/node/NodeHelper.java b/core/src/main/java/com/qq/tars/support/node/NodeHelper.java index ca9be875..d199e3e1 100644 --- a/core/src/main/java/com/qq/tars/support/node/NodeHelper.java +++ b/core/src/main/java/com/qq/tars/support/node/NodeHelper.java @@ -16,17 +16,20 @@ package com.qq.tars.support.node; -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; - import com.qq.tars.client.Communicator; import com.qq.tars.common.util.StringUtils; import com.qq.tars.server.config.ConfigurationManager; +import com.qq.tars.support.log.LoggerFactory; import com.qq.tars.support.node.prx.ServerFPrx; import com.qq.tars.support.node.prx.ServerInfo; -import com.qq.tars.support.om.OmLogger; +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; public class NodeHelper { + private static final Logger omLogger = LoggerFactory.getLogger("omLogger"); private static final NodeHelper Instance = new NodeHelper(); private Communicator communicator; @@ -54,9 +57,9 @@ public void keepAlive() { return; } ServerFPrx nodePrx = communicator.stringToProxy(ServerFPrx.class, node); - nodePrx.async_keepAlive(null, si); + nodePrx.promise_keepAlive(si); } catch (Throwable t) { - OmLogger.record("NodeHelper|keepAlive|error", t); + omLogger.log(Level.SEVERE, "NodeHelper|keepAlive|error", t); } } @@ -70,9 +73,9 @@ public void reportVersion(String version) { return; } ServerFPrx nodePrx = communicator.stringToProxy(ServerFPrx.class, node); - nodePrx.async_reportVersion(null, si.application, si.serverName, version); + nodePrx.promise_reportVersion(si.application, si.serverName, version); } catch (Throwable t) { - OmLogger.record("NodeHelper|reportVersion|error", t); + omLogger.log(Level.SEVERE, "NodeHelper|reportVersion|error", t); } } diff --git a/core/src/main/java/com/qq/tars/support/node/prx/ServerFPrx.java b/core/src/main/java/com/qq/tars/support/node/prx/ServerFPrx.java index 11dc9b17..d0b486ad 100644 --- a/core/src/main/java/com/qq/tars/support/node/prx/ServerFPrx.java +++ b/core/src/main/java/com/qq/tars/support/node/prx/ServerFPrx.java @@ -20,58 +20,37 @@ package com.qq.tars.support.node.prx; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.annotation.*; -import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsContext; + +import java.util.concurrent.CompletableFuture; @Servant public interface ServerFPrx { - /** - * 向node定时上报serverInfo - * @param serverInfo 服务状态 - * @return int - */ - public int keepAlive(ServerInfo serverInfo); - /** - * 向node定时上报serverInfo - * @param serverInfo 服务状态 - * @return int - */ - public int keepAlive(ServerInfo serverInfo, @TarsContext java.util.Map ctx); - /** - * 向node定时上报serverInfo - * @param serverInfo 服务状态 - * @return int - */ - public void async_keepAlive(@TarsCallback ServerFPrxCallback callback, ServerInfo serverInfo); - /** - * 向node定时上报serverInfo - * @param serverInfo 服务状态 - * @return int - */ - public void async_keepAlive(@TarsCallback ServerFPrxCallback callback, ServerInfo serverInfo, @TarsContext java.util.Map ctx); - /** - * 向node上报TARS版本信息 - * @param string 版本信息 - * @return int - */ - public int reportVersion(String app, String serverName, String version); - /** - * 向node上报TARS版本信息 - * @param string 版本信息 - * @return int - */ - public int reportVersion(String app, String serverName, String version, @TarsContext java.util.Map ctx); - /** - * 向node上报TARS版本信息 - * @param string 版本信息 - * @return int - */ - public void async_reportVersion(@TarsCallback ServerFPrxCallback callback, String app, String serverName, String version); - /** - * 向node上报TARS版本信息 - * @param string 版本信息 - * @return int - */ - public void async_reportVersion(@TarsCallback ServerFPrxCallback callback, String app, String serverName, String version, @TarsContext java.util.Map ctx); + /** + * Report serverInfo to node regularly + * @param serverInfo Service status + * @return int + */ + public int keepAlive(ServerInfo serverInfo); + + CompletableFuture promise_keepAlive(ServerInfo serverInfo); + + /** + * Report serverInfo to node regularly + * @param serverInfo Service status + * @return int + */ + public int keepAlive(ServerInfo serverInfo, @TarsContext java.util.Map ctx); + + public int reportVersion(String app, String serverName, String version); + + CompletableFuture promise_reportVersion(String app, String serverName, String version); + + /** + * Report TARS version information to node + * @param string Version information + * @return int + */ + public int reportVersion(String app, String serverName, String version, @TarsContext java.util.Map ctx); } diff --git a/core/src/main/java/com/qq/tars/support/node/prx/ServerFPrxCallback.java b/core/src/main/java/com/qq/tars/support/node/prx/ServerFPrxCallback.java deleted file mode 100644 index b7c109c3..00000000 --- a/core/src/main/java/com/qq/tars/support/node/prx/ServerFPrxCallback.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ -// ********************************************************************** -// This file was generated by a TARS parser! -// TARS version 1.0.1. -// ********************************************************************** - -package com.qq.tars.support.node.prx; - -import com.qq.tars.rpc.protocol.tars.support.TarsAbstractCallback; - -public abstract class ServerFPrxCallback extends TarsAbstractCallback { - - public abstract void callback_keepAlive(int ret); - - public abstract void callback_reportVersion(int ret); - -} diff --git a/core/src/main/java/com/qq/tars/support/node/prx/ServerInfo.java b/core/src/main/java/com/qq/tars/support/node/prx/ServerInfo.java index 3e3a85f3..45b39322 100644 --- a/core/src/main/java/com/qq/tars/support/node/prx/ServerInfo.java +++ b/core/src/main/java/com/qq/tars/support/node/prx/ServerInfo.java @@ -20,10 +20,11 @@ package com.qq.tars.support.node.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class ServerInfo { diff --git a/core/src/main/java/com/qq/tars/support/notify/NotifyHelper.java b/core/src/main/java/com/qq/tars/support/notify/NotifyHelper.java index ddc65317..f64683c8 100644 --- a/core/src/main/java/com/qq/tars/support/notify/NotifyHelper.java +++ b/core/src/main/java/com/qq/tars/support/notify/NotifyHelper.java @@ -18,12 +18,15 @@ import com.qq.tars.client.Communicator; import com.qq.tars.server.config.ConfigurationManager; +import com.qq.tars.support.log.LoggerFactory; import com.qq.tars.support.notify.prx.NOTIFYLEVEL; import com.qq.tars.support.notify.prx.NotifyPrx; -import com.qq.tars.support.om.OmLogger; +import java.util.logging.Level; +import java.util.logging.Logger; public class NotifyHelper { + private static final Logger omLogger = LoggerFactory.getOmLogger(); private static final NotifyHelper Instance = new NotifyHelper(); private Communicator communicator; private String app; @@ -47,9 +50,9 @@ private void notify(NOTIFYLEVEL level, String message) { } NotifyPrx notifyPrx = communicator.stringToProxy(NotifyPrx.class, ConfigurationManager.getInstance().getServerConfig().getNotify()); - notifyPrx.async_notifyServer(null, app + "." + server, level.value(), message); + notifyPrx.promise_notifyServer(app + "." + server, level.value(), message); } catch (Exception e) { - OmLogger.record("RemoteNotify|notify error", e); + omLogger.log(Level.SEVERE, "RemoteNotify|notify error", e); } } @@ -78,12 +81,11 @@ private void report(String result, boolean sync) { if (communicator == null) { return; } - NotifyPrx notifyPrx = communicator.stringToProxy(NotifyPrx.class, ConfigurationManager.getInstance().getServerConfig().getNotify()); if (sync) notifyPrx.reportServer(app + "." + server, Thread.currentThread().getId() + "", result); - else notifyPrx.async_reportServer(null, app + "." + server, Thread.currentThread().getId() + "", result); + else notifyPrx.promise_reportServer(app + "." + server, Thread.currentThread().getId() + "", result); } catch (Exception e) { - OmLogger.record("RemoteNotify|report error", e); + omLogger.log(Level.SEVERE, "RemoteNotify|report error", e); } } diff --git a/core/src/main/java/com/qq/tars/support/notify/prx/NOTIFYLEVEL.java b/core/src/main/java/com/qq/tars/support/notify/prx/NOTIFYLEVEL.java index 282aac71..cd7d5b78 100644 --- a/core/src/main/java/com/qq/tars/support/notify/prx/NOTIFYLEVEL.java +++ b/core/src/main/java/com/qq/tars/support/notify/prx/NOTIFYLEVEL.java @@ -21,7 +21,7 @@ package com.qq.tars.support.notify.prx; /** - * 定义上报信息的等级 + * Define the level of reported information */ public enum NOTIFYLEVEL { diff --git a/core/src/main/java/com/qq/tars/support/notify/prx/NotifyInfo.java b/core/src/main/java/com/qq/tars/support/notify/prx/NotifyInfo.java index 3fa40962..a35199fe 100644 --- a/core/src/main/java/com/qq/tars/support/notify/prx/NotifyInfo.java +++ b/core/src/main/java/com/qq/tars/support/notify/prx/NotifyInfo.java @@ -20,13 +20,14 @@ package com.qq.tars.support.notify.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; /** - * 上报的信息分页记录 + * Report information paging record */ @TarsStruct public class NotifyInfo { diff --git a/core/src/main/java/com/qq/tars/support/notify/prx/NotifyItem.java b/core/src/main/java/com/qq/tars/support/notify/prx/NotifyItem.java index 10c249d8..8332eb3f 100644 --- a/core/src/main/java/com/qq/tars/support/notify/prx/NotifyItem.java +++ b/core/src/main/java/com/qq/tars/support/notify/prx/NotifyItem.java @@ -20,13 +20,14 @@ package com.qq.tars.support.notify.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; /** - * 上报信息的单条内容 + * A single item of reported information */ @TarsStruct public class NotifyItem { diff --git a/core/src/main/java/com/qq/tars/support/notify/prx/NotifyKey.java b/core/src/main/java/com/qq/tars/support/notify/prx/NotifyKey.java index d099a94d..c365bdad 100644 --- a/core/src/main/java/com/qq/tars/support/notify/prx/NotifyKey.java +++ b/core/src/main/java/com/qq/tars/support/notify/prx/NotifyKey.java @@ -20,13 +20,14 @@ package com.qq.tars.support.notify.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; /** - * notify信息的键值 + * Key value of notify information */ @TarsStruct public class NotifyKey { diff --git a/core/src/main/java/com/qq/tars/support/notify/prx/NotifyPrx.java b/core/src/main/java/com/qq/tars/support/notify/prx/NotifyPrx.java index dfc0c3f9..f2fa377f 100644 --- a/core/src/main/java/com/qq/tars/support/notify/prx/NotifyPrx.java +++ b/core/src/main/java/com/qq/tars/support/notify/prx/NotifyPrx.java @@ -20,102 +20,32 @@ package com.qq.tars.support.notify.prx; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.annotation.*; import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsContext; +import com.qq.tars.protocol.tars.annotation.TarsHolder; + +import java.util.concurrent.CompletableFuture; @Servant public interface NotifyPrx { - /** - * 框架上报的信息, 保存于数据库中 - * @param sServerName, server name - * @param sThreadId, server current thread id - * @param sMessage, message - **/ - public void reportServer(String sServerName, String sThreadId, String sMessage); - /** - * 框架上报的信息, 保存于数据库中 - * @param sServerName, server name - * @param sThreadId, server current thread id - * @param sMessage, message - **/ - public void reportServer(String sServerName, String sThreadId, String sMessage, @TarsContext java.util.Map ctx); - /** - * 框架上报的信息, 保存于数据库中 - * @param sServerName, server name - * @param sThreadId, server current thread id - * @param sMessage, message - **/ - public void async_reportServer(@TarsCallback NotifyPrxCallback callback, String sServerName, String sThreadId, String sMessage); - /** - * 框架上报的信息, 保存于数据库中 - * @param sServerName, server name - * @param sThreadId, server current thread id - * @param sMessage, message - **/ - public void async_reportServer(@TarsCallback NotifyPrxCallback callback, String sServerName, String sThreadId, String sMessage, @TarsContext java.util.Map ctx); - /** - * 业务上报的信息, 用于报警 - * @param sServerName, server name - * @param level, notify level - * @param sMessage, message - **/ - public void notifyServer(String sServerName, int level, String sMessage); - /** - * 业务上报的信息, 用于报警 - * @param sServerName, server name - * @param level, notify level - * @param sMessage, message - **/ - public void notifyServer(String sServerName, int level, String sMessage, @TarsContext java.util.Map ctx); - /** - * 业务上报的信息, 用于报警 - * @param sServerName, server name - * @param level, notify level - * @param sMessage, message - **/ - public void async_notifyServer(@TarsCallback NotifyPrxCallback callback, String sServerName, int level, String sMessage); - /** - * 业务上报的信息, 用于报警 - * @param sServerName, server name - * @param level, notify level - * @param sMessage, message - **/ - public void async_notifyServer(@TarsCallback NotifyPrxCallback callback, String sServerName, int level, String sMessage, @TarsContext java.util.Map ctx); - /** - * 获取上报信息 - * @param sServerName, server name - * @param out , notify info detail - * @return int 0=success, others=failed - **/ - public int getNotifyInfo(NotifyKey stKey, @TarsHolder Holder stInfo); - /** - * 获取上报信息 - * @param sServerName, server name - * @param out , notify info detail - * @return int 0=success, others=failed - **/ - public int getNotifyInfo(NotifyKey stKey, @TarsHolder Holder stInfo, @TarsContext java.util.Map ctx); - /** - * 获取上报信息 - * @param sServerName, server name - * @param out , notify info detail - * @return int 0=success, others=failed - **/ - public void async_getNotifyInfo(@TarsCallback NotifyPrxCallback callback, NotifyKey stKey); - /** - * 获取上报信息 - * @param sServerName, server name - * @param out , notify info detail - * @return int 0=success, others=failed - **/ - public void async_getNotifyInfo(@TarsCallback NotifyPrxCallback callback, NotifyKey stKey, @TarsContext java.util.Map ctx); - public void reportNotifyInfo(ReportInfo info); + public void reportServer(String sServerName, String sThreadId, String sMessage); + CompletableFuture promise_reportServer(String sServerName, String sThreadId, String sMessage); + + public void reportServer(String sServerName, String sThreadId, String sMessage, @TarsContext java.util.Map ctx); + + public void notifyServer(String sServerName, int level, String sMessage); + + CompletableFuture promise_notifyServer(String sServerName, int level, String sMessage); + + public void notifyServer(String sServerName, int level, String sMessage, @TarsContext java.util.Map ctx); + + public int getNotifyInfo(NotifyKey stKey, @TarsHolder Holder stInfo); - public void reportNotifyInfo(ReportInfo info, @TarsContext java.util.Map ctx); + public int getNotifyInfo(NotifyKey stKey, @TarsHolder Holder stInfo, @TarsContext java.util.Map ctx); - public void async_reportNotifyInfo(@TarsCallback NotifyPrxCallback callback, ReportInfo info); + public void reportNotifyInfo(ReportInfo info); - public void async_reportNotifyInfo(@TarsCallback NotifyPrxCallback callback, ReportInfo info, @TarsContext java.util.Map ctx); + public void reportNotifyInfo(ReportInfo info, @TarsContext java.util.Map ctx); } diff --git a/core/src/main/java/com/qq/tars/support/notify/prx/ReportInfo.java b/core/src/main/java/com/qq/tars/support/notify/prx/ReportInfo.java index e56e2db7..ff272eeb 100644 --- a/core/src/main/java/com/qq/tars/support/notify/prx/ReportInfo.java +++ b/core/src/main/java/com/qq/tars/support/notify/prx/ReportInfo.java @@ -20,10 +20,11 @@ package com.qq.tars.support.notify.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class ReportInfo { diff --git a/core/src/main/java/com/qq/tars/support/om/OmServiceMngr.java b/core/src/main/java/com/qq/tars/support/om/OmServiceMngr.java index 8b8c890b..ed233adf 100644 --- a/core/src/main/java/com/qq/tars/support/om/OmServiceMngr.java +++ b/core/src/main/java/com/qq/tars/support/om/OmServiceMngr.java @@ -24,10 +24,15 @@ import com.qq.tars.support.node.NodeHelper; import com.qq.tars.support.notify.NotifyHelper; import com.qq.tars.support.property.CommonPropertyPolicy; -import com.qq.tars.support.property.JvmPropertyPolicy.*; +import com.qq.tars.support.property.JvmPropertyPolicy.GCNumCount; +import com.qq.tars.support.property.JvmPropertyPolicy.GCTimeSum; +import com.qq.tars.support.property.JvmPropertyPolicy.MemoryHeapCommittedAvg; +import com.qq.tars.support.property.JvmPropertyPolicy.MemoryHeapMaxAvg; +import com.qq.tars.support.property.JvmPropertyPolicy.MemoryHeapUsedAvg; +import com.qq.tars.support.property.JvmPropertyPolicy.ThreadNumAvg; import com.qq.tars.support.property.PropertyReportHelper; import com.qq.tars.support.property.PropertyReportHelper.Policy; -import com.qq.tars.support.trace.TarsTraceZipkinConfiguration; +import com.qq.tars.support.trace.spi.TraceInitializerManager; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; @@ -50,7 +55,7 @@ public void initAndStartOmService() { ConfigHelper.getInstance().setConfigInfo(communicator, app, serverName, basePath); NodeHelper.getInstance().setNodeInfo(communicator, app, serverName); NotifyHelper.getInstance().setNotifyInfo(communicator, app, serverName); - PropertyReportHelper.getInstance().setPropertyInfo(communicator, modualName); + PropertyReportHelper.getInstance().init(communicator, modualName); NodeHelper.getInstance().reportVersion(ClientVersion.getVersion()); Policy avgPolicy = new CommonPropertyPolicy.Avg(); @@ -67,7 +72,7 @@ public void initAndStartOmService() { } ServerStatHelper.getInstance().init(communicator); - TarsTraceZipkinConfiguration.getInstance().init(); + TraceInitializerManager.getInstance().init(); ScheduledServiceMngr.getInstance().start(); } diff --git a/core/src/main/java/com/qq/tars/support/om/ScheduledServiceMngr.java b/core/src/main/java/com/qq/tars/support/om/ScheduledServiceMngr.java index dcc8af9c..fb01a5c4 100644 --- a/core/src/main/java/com/qq/tars/support/om/ScheduledServiceMngr.java +++ b/core/src/main/java/com/qq/tars/support/om/ScheduledServiceMngr.java @@ -16,15 +16,15 @@ package com.qq.tars.support.om; -import java.util.List; -import java.util.Random; -import java.util.concurrent.TimeUnit; - import com.qq.tars.common.support.ScheduledExecutorManager; import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.support.node.NodeHelper; import com.qq.tars.support.property.PropertyReportHelper; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; + public class ScheduledServiceMngr { private final static ScheduledServiceMngr Instance = new ScheduledServiceMngr(); diff --git a/core/src/main/java/com/qq/tars/support/om/ServerStatHelper.java b/core/src/main/java/com/qq/tars/support/om/ServerStatHelper.java index 91576f82..50117a96 100644 --- a/core/src/main/java/com/qq/tars/support/om/ServerStatHelper.java +++ b/core/src/main/java/com/qq/tars/support/om/ServerStatHelper.java @@ -20,12 +20,16 @@ import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.server.config.ServantAdapterConfig; import com.qq.tars.server.config.ServerConfig; +import com.qq.tars.support.log.LoggerFactory; import com.qq.tars.support.stat.InvokeStatHelper; +import java.util.logging.Level; +import java.util.logging.Logger; import java.util.LinkedHashMap; import java.util.concurrent.atomic.AtomicBoolean; public class ServerStatHelper { + private static final Logger omLogger = LoggerFactory.getOmLogger(); private static final ServerStatHelper instance = new ServerStatHelper(); private final AtomicBoolean inited = new AtomicBoolean(false); @@ -62,7 +66,7 @@ public void report() { communicator.getStatHelper().report(InvokeStatHelper.getInstance().getProxyStat(servantCfg.getServant()), false); } } catch (Exception e) { - OmLogger.record("ServerStatHelper|ReportThread error", e); + omLogger.log(Level.SEVERE, "ServerStatHelper|ReportThread error", e); } } } diff --git a/core/src/main/java/com/qq/tars/support/property/CommonPropertyPolicy.java b/core/src/main/java/com/qq/tars/support/property/CommonPropertyPolicy.java index 817a8c60..2b5d326e 100644 --- a/core/src/main/java/com/qq/tars/support/property/CommonPropertyPolicy.java +++ b/core/src/main/java/com/qq/tars/support/property/CommonPropertyPolicy.java @@ -16,14 +16,14 @@ package com.qq.tars.support.property; +import com.qq.tars.rpc.exc.TarsException; +import com.qq.tars.support.property.PropertyReportHelper.Policy; + import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import com.qq.tars.rpc.exc.TarsException; -import com.qq.tars.support.property.PropertyReportHelper.Policy; - public class CommonPropertyPolicy { public static class Sum implements Policy { @@ -108,7 +108,7 @@ public static class Distr implements Policy { public Distr(List list) { if (list == null || list.size() == 0) { - throw new TarsException("ProperyReport|Distr initial list object can not be empty"); + throw new TarsException("PropertyReport|Distr initial list object can not be empty"); } this.data = new HashSet(list).toArray(II); diff --git a/core/src/main/java/com/qq/tars/support/property/PropertyReportHelper.java b/core/src/main/java/com/qq/tars/support/property/PropertyReportHelper.java index 09398c79..f8b2c7b1 100644 --- a/core/src/main/java/com/qq/tars/support/property/PropertyReportHelper.java +++ b/core/src/main/java/com/qq/tars/support/property/PropertyReportHelper.java @@ -16,31 +16,36 @@ package com.qq.tars.support.property; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import com.qq.tars.client.Communicator; +import com.qq.tars.client.CommunicatorConfig; +import com.qq.tars.client.rpc.Utils; import com.qq.tars.rpc.exc.TarsException; import com.qq.tars.server.config.ConfigurationManager; -import com.qq.tars.support.om.OmLogger; +import com.qq.tars.support.log.LoggerFactory; import com.qq.tars.support.property.prx.PropertyFPrx; import com.qq.tars.support.property.prx.StatPropInfo; import com.qq.tars.support.property.prx.StatPropMsgBody; import com.qq.tars.support.property.prx.StatPropMsgHead; +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; public class PropertyReportHelper { + private static final Logger omLogger = LoggerFactory.getOmLogger(); - public static interface Policy { + public interface Policy { - public String desc(); + String desc(); - public String get(); + String get(); - public void set(int value); + void set(int value); } @@ -64,8 +69,20 @@ public static class PropertyReporter { private Collection policies; private String propRptName; private String moduleName; + private String ip = ""; + private String setName = ""; + private String setArea = ""; + private String setID = ""; public PropertyReporter(String moduleName, String propRptName, Policy[] policies) { + CommunicatorConfig config = ConfigurationManager.getInstance().getServerConfig().getCommunicatorConfig(); + + this.moduleName = !config.isEnableSet() ? moduleName : String.format("%s.%s%s%s", moduleName, config.getSetName(), config.getSetArea(), config.getSetID()); + if (config.isEnableSet()) { + this.setName = config.getSetName(); + this.setArea = config.getSetArea(); + this.setID = config.getSetID(); + } this.propRptName = propRptName; if (ConfigurationManager.getInstance().getCommunicatorConfig().isEnableSet()) { @@ -74,13 +91,18 @@ public PropertyReporter(String moduleName, String propRptName, Policy[] policies } else { this.moduleName = moduleName; } + this.ip = ConfigurationManager.getInstance().getServerConfig().getLocalIP(); Map map = new HashMap(); for (Policy policy : policies) map.put(policy.desc(), policy); this.policies = map.values(); + + this.ip = Utils.getLocalIp(); + } + public void report(int value) { for (Policy policy : policies) policy.set(value); @@ -88,11 +110,11 @@ public void report(int value) { public ReportData getReportData() { int len = 0; - StatPropMsgHead head = new StatPropMsgHead(moduleName, "", propRptName, null, null, null, null, 1); + StatPropMsgHead head = new StatPropMsgHead(moduleName, this.ip, propRptName, setName, setArea, setID, null, 1); len += moduleName.length() + propRptName.length(); int size = policies.size(); len += PROPERTY_PROTOCOL_LEN + size; - List statPropInfos = new ArrayList(); + List statPropInfos = new ArrayList(policies.size()); for (Policy policy : policies) { String desc = policy.desc(); String value = policy.get(); @@ -111,11 +133,11 @@ public ReportData getReportData() { private Map reporters; private Communicator communicator; private String moduleName; - private boolean configed; + private volatile boolean initialized; private PropertyReportHelper() { - reporters = new ConcurrentHashMap(); - configed = false; + reporters = new ConcurrentHashMap<>(); + initialized = false; } public static PropertyReportHelper getInstance() { @@ -123,13 +145,18 @@ public static PropertyReportHelper getInstance() { } public synchronized void setPropertyInfo(Communicator comm, String moduleName) { - if (configed) { - throw new TarsException("PropertyReporter|setPropertyInfo method should be called once at most"); + init(comm, moduleName); + } + + public synchronized void init(Communicator comm, String moduleName) { + if (initialized) { + omLogger.warning("PropertyReporter|setPropertyInfo method should be called once at most"); + return; } this.communicator = comm; this.moduleName = moduleName; - configed = true; + initialized = true; } public synchronized void createPropertyReporter(String propRptName, Policy... policies) { @@ -154,7 +181,7 @@ public void reportPropertyValue(String propRptName, int value) { public void report() { try { - if (!configed) { + if (!initialized) { return; } @@ -168,7 +195,7 @@ public void report() { sendData.put(data.head, data.body); sendLen += data.len; } else { - propertyFPrx.async_reportPropMsg(null, sendData); + propertyFPrx.promise_reportPropMsg(sendData); sendData.clear(); sendData.put(data.head, data.body); sendLen = data.len; @@ -176,10 +203,10 @@ public void report() { } if (sendData.size() != 0) { - propertyFPrx.async_reportPropMsg(null, sendData); + propertyFPrx.promise_reportPropMsg(sendData); } } catch (Throwable t) { - OmLogger.record("PropertyReporter|ReportThread error", t); + omLogger.log(Level.SEVERE, "PropertyReporter|ReportThread error", t); } } } diff --git a/core/src/main/java/com/qq/tars/support/property/prx/PropertyFPrx.java b/core/src/main/java/com/qq/tars/support/property/prx/PropertyFPrx.java index 328386f4..431efa20 100644 --- a/core/src/main/java/com/qq/tars/support/property/prx/PropertyFPrx.java +++ b/core/src/main/java/com/qq/tars/support/property/prx/PropertyFPrx.java @@ -20,39 +20,29 @@ package com.qq.tars.support.property.prx; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.annotation.*; -import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsContext; + +import java.util.concurrent.CompletableFuture; /** - * - * 上报服务的接口 - * + * Reporting service interface **/ @Servant public interface PropertyFPrx { - /** - * 上报属性统计信息 Prop = property - * @param statmsg, 上报信息 - * @return int, 返回0表示成功 - */ - public int reportPropMsg(java.util.Map statmsg); - /** - * 上报属性统计信息 Prop = property - * @param statmsg, 上报信息 - * @return int, 返回0表示成功 - */ - public int reportPropMsg(java.util.Map statmsg, @TarsContext java.util.Map ctx); - /** - * 上报属性统计信息 Prop = property - * @param statmsg, 上报信息 - * @return int, 返回0表示成功 - */ - public void async_reportPropMsg(@TarsCallback PropertyFPrxCallback callback, java.util.Map statmsg); - /** - * 上报属性统计信息 Prop = property - * @param statmsg, 上报信息 - * @return int, 返回0表示成功 - */ - public void async_reportPropMsg(@TarsCallback PropertyFPrxCallback callback, java.util.Map statmsg, @TarsContext java.util.Map ctx); + /** + * Report attribute statistics information Prop = property + * @param statmsg, Report information + * @return int, Return 0 means success + */ + int reportPropMsg(java.util.Map statmsg); + + CompletableFuture promise_reportPropMsg(java.util.Map statmsg); + + /** + * Report attribute statistics information Prop = property + * @param statmsg, Report information + * @return int, Return 0 means success + */ + int reportPropMsg(java.util.Map statmsg, @TarsContext java.util.Map ctx); } diff --git a/core/src/main/java/com/qq/tars/support/property/prx/PropertyFPrxCallback.java b/core/src/main/java/com/qq/tars/support/property/prx/PropertyFPrxCallback.java deleted file mode 100644 index 2ee71e93..00000000 --- a/core/src/main/java/com/qq/tars/support/property/prx/PropertyFPrxCallback.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ -// ********************************************************************** -// This file was generated by a TARS parser! -// TARS version 1.0.1. -// ********************************************************************** - -package com.qq.tars.support.property.prx; - -import com.qq.tars.rpc.protocol.tars.support.TarsAbstractCallback; - -/** - * - * 上报服务的接口 - * - **/ -public abstract class PropertyFPrxCallback extends TarsAbstractCallback { - - public abstract void callback_reportPropMsg(int ret); - -} diff --git a/core/src/main/java/com/qq/tars/support/property/prx/StatPropInfo.java b/core/src/main/java/com/qq/tars/support/property/prx/StatPropInfo.java index e29ee89c..5764706f 100644 --- a/core/src/main/java/com/qq/tars/support/property/prx/StatPropInfo.java +++ b/core/src/main/java/com/qq/tars/support/property/prx/StatPropInfo.java @@ -20,10 +20,11 @@ package com.qq.tars.support.property.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class StatPropInfo { diff --git a/core/src/main/java/com/qq/tars/support/property/prx/StatPropMsgBody.java b/core/src/main/java/com/qq/tars/support/property/prx/StatPropMsgBody.java index 6bce29bb..94239319 100644 --- a/core/src/main/java/com/qq/tars/support/property/prx/StatPropMsgBody.java +++ b/core/src/main/java/com/qq/tars/support/property/prx/StatPropMsgBody.java @@ -20,10 +20,11 @@ package com.qq.tars.support.property.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class StatPropMsgBody { diff --git a/core/src/main/java/com/qq/tars/support/property/prx/StatPropMsgHead.java b/core/src/main/java/com/qq/tars/support/property/prx/StatPropMsgHead.java index 25215e6b..f7ec7fd0 100644 --- a/core/src/main/java/com/qq/tars/support/property/prx/StatPropMsgHead.java +++ b/core/src/main/java/com/qq/tars/support/property/prx/StatPropMsgHead.java @@ -20,10 +20,11 @@ package com.qq.tars.support.property.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class StatPropMsgHead implements Comparable { diff --git a/core/src/main/java/com/qq/tars/support/query/QueryHelper.java b/core/src/main/java/com/qq/tars/support/query/QueryHelper.java index 1779ea8f..f878befe 100644 --- a/core/src/main/java/com/qq/tars/support/query/QueryHelper.java +++ b/core/src/main/java/com/qq/tars/support/query/QueryHelper.java @@ -16,19 +16,19 @@ package com.qq.tars.support.query; -import com.qq.tars.client.util.ParseTools; -import java.util.ArrayList; -import java.util.List; - import com.qq.tars.client.Communicator; import com.qq.tars.client.ServantProxyConfig; +import com.qq.tars.client.util.ParseTools; import com.qq.tars.common.support.Holder; import com.qq.tars.common.util.Constants; -import com.qq.tars.common.util.StringUtils; import com.qq.tars.protocol.util.TarsHelper; import com.qq.tars.support.query.prx.EndpointF; import com.qq.tars.support.query.prx.QueryFPrx; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + public final class QueryHelper { private final Communicator communicator; @@ -42,8 +42,7 @@ public List findObjectById(String objName) { } private QueryFPrx getPrx() { - QueryFPrx prx = communicator.stringToProxy(QueryFPrx.class, communicator.getCommunicatorConfig().getLocator()); - return prx; + return communicator.stringToProxy(QueryFPrx.class, communicator.getCommunicatorConfig().getLocator()); } public String getServerNodes(ServantProxyConfig config) { @@ -61,7 +60,7 @@ public String getServerNodes(ServantProxyConfig config) { if (ret != TarsHelper.SERVERSUCCESS) { return null; } - + Collections.sort(activeEp.getValue()); StringBuilder value = new StringBuilder(); if (activeEp.value != null && !activeEp.value.isEmpty()) { for (EndpointF endpointF : activeEp.value) { diff --git a/core/src/main/java/com/qq/tars/support/query/prx/QueryFPrx.java b/core/src/main/java/com/qq/tars/support/query/prx/QueryFPrx.java deleted file mode 100644 index 59e9cb68..00000000 --- a/core/src/main/java/com/qq/tars/support/query/prx/QueryFPrx.java +++ /dev/null @@ -1,224 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ -// ********************************************************************** -// This file was generated by a TARS parser! -// TARS version 1.0.1. -// ********************************************************************** - -package com.qq.tars.support.query.prx; - -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.annotation.*; -import com.qq.tars.common.support.Holder; - -/** - * 获取对象endpoint的query接口 - */ -@Servant -public interface QueryFPrx { - /** 根据id获取对象 - * - * @param id 对象名称 - * - * @return 返回所有该对象的活动endpoint列表 - */ - public java.util.List findObjectById(String id); - /** 根据id获取对象 - * - * @param id 对象名称 - * - * @return 返回所有该对象的活动endpoint列表 - */ - public java.util.List findObjectById(String id, @TarsContext java.util.Map ctx); - /** 根据id获取对象 - * - * @param id 对象名称 - * - * @return 返回所有该对象的活动endpoint列表 - */ - public void async_findObjectById(@TarsCallback QueryFPrxCallback callback, String id); - /** 根据id获取对象 - * - * @param id 对象名称 - * - * @return 返回所有该对象的活动endpoint列表 - */ - public void async_findObjectById(@TarsCallback QueryFPrxCallback callback, String id, @TarsContext java.util.Map ctx); - /**根据id获取所有对象,包括活动和非活动对象 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public int findObjectById4Any(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp); - /**根据id获取所有对象,包括活动和非活动对象 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public int findObjectById4Any(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp, @TarsContext java.util.Map ctx); - /**根据id获取所有对象,包括活动和非活动对象 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public void async_findObjectById4Any(@TarsCallback QueryFPrxCallback callback, String id); - /**根据id获取所有对象,包括活动和非活动对象 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public void async_findObjectById4Any(@TarsCallback QueryFPrxCallback callback, String id, @TarsContext java.util.Map ctx); - /** 根据id获取对象所有endpoint列表,功能同findObjectByIdInSameGroup - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public int findObjectById4All(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp); - /** 根据id获取对象所有endpoint列表,功能同findObjectByIdInSameGroup - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public int findObjectById4All(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp, @TarsContext java.util.Map ctx); - /** 根据id获取对象所有endpoint列表,功能同findObjectByIdInSameGroup - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public void async_findObjectById4All(@TarsCallback QueryFPrxCallback callback, String id); - /** 根据id获取对象所有endpoint列表,功能同findObjectByIdInSameGroup - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public void async_findObjectById4All(@TarsCallback QueryFPrxCallback callback, String id, @TarsContext java.util.Map ctx); - /** 根据id获取对象同组endpoint列表 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public int findObjectByIdInSameGroup(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp); - /** 根据id获取对象同组endpoint列表 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public int findObjectByIdInSameGroup(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp, @TarsContext java.util.Map ctx); - /** 根据id获取对象同组endpoint列表 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public void async_findObjectByIdInSameGroup(@TarsCallback QueryFPrxCallback callback, String id); - /** 根据id获取对象同组endpoint列表 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public void async_findObjectByIdInSameGroup(@TarsCallback QueryFPrxCallback callback, String id, @TarsContext java.util.Map ctx); - /** 根据id获取对象指定归属地的endpoint列表 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public int findObjectByIdInSameStation(String id, String sStation, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp); - /** 根据id获取对象指定归属地的endpoint列表 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public int findObjectByIdInSameStation(String id, String sStation, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp, @TarsContext java.util.Map ctx); - /** 根据id获取对象指定归属地的endpoint列表 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public void async_findObjectByIdInSameStation(@TarsCallback QueryFPrxCallback callback, String id, String sStation); - /** 根据id获取对象指定归属地的endpoint列表 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public void async_findObjectByIdInSameStation(@TarsCallback QueryFPrxCallback callback, String id, String sStation, @TarsContext java.util.Map ctx); - /** 根据id获取对象同组endpoint列表 - * - * @param id 对象名称 - * @param setId set全称,格式为setname.setarea.setgroup - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public int findObjectByIdInSameSet(String id, String setId, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp); - /** 根据id获取对象同组endpoint列表 - * - * @param id 对象名称 - * @param setId set全称,格式为setname.setarea.setgroup - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public int findObjectByIdInSameSet(String id, String setId, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp, @TarsContext java.util.Map ctx); - /** 根据id获取对象同组endpoint列表 - * - * @param id 对象名称 - * @param setId set全称,格式为setname.setarea.setgroup - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public void async_findObjectByIdInSameSet(@TarsCallback QueryFPrxCallback callback, String id, String setId); - /** 根据id获取对象同组endpoint列表 - * - * @param id 对象名称 - * @param setId set全称,格式为setname.setarea.setgroup - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - public void async_findObjectByIdInSameSet(@TarsCallback QueryFPrxCallback callback, String id, String setId, @TarsContext java.util.Map ctx); -} diff --git a/core/src/main/java/com/qq/tars/support/query/prx/QueryFPrxCallback.java b/core/src/main/java/com/qq/tars/support/query/prx/QueryFPrxCallback.java deleted file mode 100644 index 89d68a6c..00000000 --- a/core/src/main/java/com/qq/tars/support/query/prx/QueryFPrxCallback.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ -// ********************************************************************** -// This file was generated by a TARS parser! -// TARS version 1.0.1. -// ********************************************************************** - -package com.qq.tars.support.query.prx; - -import com.qq.tars.rpc.protocol.tars.support.TarsAbstractCallback; - -/** - * 获取对象endpoint的query接口 - */ -public abstract class QueryFPrxCallback extends TarsAbstractCallback { - - public abstract void callback_findObjectById(java.util.List ret); - - public abstract void callback_findObjectById4Any(int ret, java.util.List activeEp, java.util.List inactiveEp); - - public abstract void callback_findObjectById4All(int ret, java.util.List activeEp, java.util.List inactiveEp); - - public abstract void callback_findObjectByIdInSameGroup(int ret, java.util.List activeEp, java.util.List inactiveEp); - - public abstract void callback_findObjectByIdInSameStation(int ret, java.util.List activeEp, java.util.List inactiveEp); - - public abstract void callback_findObjectByIdInSameSet(int ret, java.util.List activeEp, java.util.List inactiveEp); - -} diff --git a/core/src/main/java/com/qq/tars/support/stat/InvokeStatHelper.java b/core/src/main/java/com/qq/tars/support/stat/InvokeStatHelper.java index e0039581..fe0ed7bc 100644 --- a/core/src/main/java/com/qq/tars/support/stat/InvokeStatHelper.java +++ b/core/src/main/java/com/qq/tars/support/stat/InvokeStatHelper.java @@ -41,11 +41,10 @@ public CopyOnWriteArrayList getStatIntervals() { public ProxyStat addProxyStat(String objectName) { ProxyStat statTool = proxyStats.get(objectName); - if (statTool == null) { + if (statTool == null){ proxyStats.putIfAbsent(objectName, new ProxyStat()); - statTool = proxyStats.get(objectName); } - return statTool; + return proxyStats.get(objectName); } public ProxyStat getProxyStat(String objectName) { diff --git a/core/src/main/java/com/qq/tars/support/stat/ProxyStat.java b/core/src/main/java/com/qq/tars/support/stat/ProxyStat.java index 725f2e26..0537a107 100644 --- a/core/src/main/java/com/qq/tars/support/stat/ProxyStat.java +++ b/core/src/main/java/com/qq/tars/support/stat/ProxyStat.java @@ -16,6 +16,7 @@ package com.qq.tars.support.stat; +import com.qq.tars.common.ClientVersion; import com.qq.tars.common.util.Constants; import java.util.ArrayList; @@ -52,11 +53,10 @@ public void setTimeStatInterval(ProxyStatHead head, List timeStatInterv private ProxyStatBody getStatBody(ProxyStatHead head) { ProxyStatBody body = stat.get(head); - if (body == null) { + if (body == null){ stat.putIfAbsent(head, new ProxyStatBody(DEFAULT_TIME_STAT_INTERVAL)); - body = stat.get(head); } - return body; + return stat.get(head); } public void addInvokeTime(ProxyStatHead head, long costTimeMill, int result) { @@ -78,7 +78,7 @@ public void addInvokeTimeByClient(String masterName, String slaveName, String sl public void addInvokeTimeByServer(String masterName, String application, String server, String slaveSetName, String slaveSetArea, String slaveSetID, String methodName, String masterIp, String slaveIp, int slavePort, int result, long costTimeMill) { String slaveName = slaveSetName != null ? String.format("%s.%s.%s%s%s", application, server, slaveSetName, slaveSetArea, slaveSetID) : String.format("%s.%s", application, server); - ProxyStatHead head = new ProxyStatHead(masterName, slaveName, methodName, masterIp, slaveIp, slavePort, result, slaveSetName, slaveSetArea, slaveSetID, ""); + ProxyStatHead head = new ProxyStatHead(masterName, slaveName, methodName, masterIp, slaveIp, slavePort, result, slaveSetName, slaveSetArea, slaveSetID, ClientVersion.getVersion()); addInvokeTime(head, costTimeMill, result); } diff --git a/core/src/main/java/com/qq/tars/support/stat/ProxyStatBody.java b/core/src/main/java/com/qq/tars/support/stat/ProxyStatBody.java index 7723726e..ee2efd0c 100644 --- a/core/src/main/java/com/qq/tars/support/stat/ProxyStatBody.java +++ b/core/src/main/java/com/qq/tars/support/stat/ProxyStatBody.java @@ -16,6 +16,8 @@ package com.qq.tars.support.stat; +import com.qq.tars.common.util.Constants; + import java.util.List; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; @@ -24,8 +26,6 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantReadWriteLock; -import com.qq.tars.common.util.Constants; - public class ProxyStatBody { private AtomicInteger count = new AtomicInteger(); diff --git a/core/src/main/java/com/qq/tars/support/stat/StatHelper.java b/core/src/main/java/com/qq/tars/support/stat/StatHelper.java index d9e4bc93..112c2cf5 100644 --- a/core/src/main/java/com/qq/tars/support/stat/StatHelper.java +++ b/core/src/main/java/com/qq/tars/support/stat/StatHelper.java @@ -17,17 +17,20 @@ package com.qq.tars.support.stat; import com.qq.tars.client.Communicator; -import com.qq.tars.client.util.ClientLogger; import com.qq.tars.common.util.StringUtils; +import com.qq.tars.support.log.LoggerFactory; import com.qq.tars.support.stat.prx.StatFPrx; import com.qq.tars.support.stat.prx.StatMicMsgBody; import com.qq.tars.support.stat.prx.StatMicMsgHead; +import java.util.logging.Level; +import java.util.logging.Logger; import java.util.HashMap; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicInteger; public final class StatHelper { + private static final Logger logger = LoggerFactory.getClientLogger(); private final static int BATCH_REPORTS = 10; @@ -46,61 +49,61 @@ private StatFPrx getPrx() { return prx; } + public void report(ProxyStat proxyStat, boolean bFromClient) { StatFPrx statFProxy = getPrx(); if (statFProxy == null) { - ClientLogger.getLogger().info("no config stat obj to report"); + logger.info("no config stat obj to report"); return; } if (proxyStat.isEmpty()) { - ClientLogger.getLogger().info("no stat need to report"); + logger.info("no stat need to report"); return; } long start = System.currentTimeMillis(); int i = 0, errorCount = 0, successCount = 0; try { - HashMap reprotMap = new HashMap(); + HashMap reportMap = new HashMap<>(); for (Entry statHead : proxyStat.getStats().entrySet()) { - ProxyStatHead head = statHead.getKey(); ProxyStatBody body = statHead.getValue(); - - HashMap intervalCount = new HashMap(); + HashMap intervalCount = new HashMap<>(); for (Entry interval : body.intervalCount.entrySet()) { intervalCount.put(interval.getKey(), interval.getValue().get()); } StatMicMsgBody mbody = new StatMicMsgBody(body.getCount(), body.getTimeoutCount(), body.getExecCount(), intervalCount, body.getTotalRspTime(), body.getMaxRspTime(), body.getMinRspTime()); body.clear(); - StatMicMsgHead mHead = new StatMicMsgHead(head.getMasterName(), head.getSlaveName(), head.getInterfaceName(), head.getMasterIp(), head.getSlaveIp(), head.getSlavePort(), head.getReturnValue(), head.getSlaveSetName(), head.getSlaveSetArea(), head.getSlaveSetID(), head.getTafVersion()); - reprotMap.put(mHead, mbody); - - ClientLogger.getLogger().info("report call|" + statHead.getKey().masterName + "|" + statHead.getKey().slaveIp + ":" + statHead.getKey().slavePort + "|" + statHead.getKey().slaveName + "." + statHead.getKey().interfaceName + "_" + statHead.getKey().getReturnValue() + "(" + statHead.getKey().slaveSetName + "." + statHead.getKey().slaveSetArea + "." + statHead.getKey().slaveSetID + "):" + mbody.count + "_" + mbody.execCount + "_" + mbody.timeoutCount + "_" + mbody.totalRspTime + "_" + mbody.maxRspTime + "_" + mbody.minRspTime); + reportMap.put(mHead, mbody); + logger.info("report call|" + + statHead.getKey().masterName + "|" + statHead.getKey().slaveIp + ":" + + statHead.getKey().slavePort + "|" + statHead.getKey().slaveName + "." + + statHead.getKey().interfaceName + "_" + statHead.getKey().getReturnValue() + + "(" + statHead.getKey().slaveSetName + "." + statHead.getKey().slaveSetArea + "." + statHead.getKey().slaveSetID + "):" + mbody.count + "_" + mbody.execCount + "_" + mbody.timeoutCount + "_" + mbody.totalRspTime + "_" + mbody.maxRspTime + "_" + mbody.minRspTime); i++; if (i % BATCH_REPORTS == 0) { try { - statFProxy.reportMicMsg(reprotMap, bFromClient); - ++successCount; + statFProxy.promise_reportMicMsg(reportMap, bFromClient); } catch (Exception e) { - ClientLogger.getLogger().error("error occurred on report proxy stat", e); + logger.log(Level.SEVERE, "error occurred on report proxy stat", e); ++errorCount; } - reprotMap = new HashMap(); + reportMap = new HashMap<>(); } } - if (reprotMap.size() > 0) { + if (reportMap.size() > 0) { try { - statFProxy.reportMicMsg(reprotMap, bFromClient); + statFProxy.promise_reportMicMsg(reportMap, bFromClient); successCount++; } catch (Exception e) { errorCount++; - ClientLogger.getLogger().error("error occurred on report proxy stat", e); + logger.log(Level.SEVERE, "error occurred on report proxy stat", e); } } } catch (Exception e) { - ClientLogger.getLogger().error("error occurred on report proxy stat", e); + logger.log(Level.SEVERE, "error occurred on report proxy stat", e); } finally { - ClientLogger.getLogger().info("report success:" + successCount + " fail:" + errorCount + " costTime:" + (System.currentTimeMillis() - start)); + logger.info("report success:" + successCount + " fail:" + errorCount + " costTime:" + (System.currentTimeMillis() - start)); } } } diff --git a/core/src/main/java/com/qq/tars/support/stat/prx/ProxyInfo.java b/core/src/main/java/com/qq/tars/support/stat/prx/ProxyInfo.java index 01b96e65..c2ee76af 100644 --- a/core/src/main/java/com/qq/tars/support/stat/prx/ProxyInfo.java +++ b/core/src/main/java/com/qq/tars/support/stat/prx/ProxyInfo.java @@ -20,10 +20,11 @@ package com.qq.tars.support.stat.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class ProxyInfo { diff --git a/core/src/main/java/com/qq/tars/support/stat/prx/StatFPrx.java b/core/src/main/java/com/qq/tars/support/stat/prx/StatFPrx.java index caf16e56..30a63fe4 100644 --- a/core/src/main/java/com/qq/tars/support/stat/prx/StatFPrx.java +++ b/core/src/main/java/com/qq/tars/support/stat/prx/StatFPrx.java @@ -20,67 +20,48 @@ package com.qq.tars.support.stat.prx; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.annotation.*; -import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsCallback; +import com.qq.tars.protocol.tars.annotation.TarsContext; + +import java.util.concurrent.CompletableFuture; /** - * - * 上报服务的接口 - * + * Interface to the report service **/ @Servant public interface StatFPrx { - /** - * 上报模块间调用信息 Mic = module interval call - * @param statmsg, 上报信息 - * @param bFromServer, 上报源 bFromClient: true 客户端发起的上报 false 服务端发起上报 - * @return int, 返回0表示成功 - */ - public int reportMicMsg(java.util.Map msg, boolean bFromClient); - /** - * 上报模块间调用信息 Mic = module interval call - * @param statmsg, 上报信息 - * @param bFromServer, 上报源 bFromClient: true 客户端发起的上报 false 服务端发起上报 - * @return int, 返回0表示成功 - */ - public int reportMicMsg(java.util.Map msg, boolean bFromClient, @TarsContext java.util.Map ctx); - /** - * 上报模块间调用信息 Mic = module interval call - * @param statmsg, 上报信息 - * @param bFromServer, 上报源 bFromClient: true 客户端发起的上报 false 服务端发起上报 - * @return int, 返回0表示成功 - */ - public void async_reportMicMsg(@TarsCallback StatFPrxCallback callback, java.util.Map msg, boolean bFromClient); - /** - * 上报模块间调用信息 Mic = module interval call - * @param statmsg, 上报信息 - * @param bFromServer, 上报源 bFromClient: true 客户端发起的上报 false 服务端发起上报 - * @return int, 返回0表示成功 - */ - public void async_reportMicMsg(@TarsCallback StatFPrxCallback callback, java.util.Map msg, boolean bFromClient, @TarsContext java.util.Map ctx); - /** - * 上报模块间调用采样信息 Mic = module interval call - * @param msg, 上报信息 - * @return int, 返回0表示成功 - */ - public int reportSampleMsg(java.util.List msg); - /** - * 上报模块间调用采样信息 Mic = module interval call - * @param msg, 上报信息 - * @return int, 返回0表示成功 - */ - public int reportSampleMsg(java.util.List msg, @TarsContext java.util.Map ctx); - /** - * 上报模块间调用采样信息 Mic = module interval call - * @param msg, 上报信息 - * @return int, 返回0表示成功 - */ - public void async_reportSampleMsg(@TarsCallback StatFPrxCallback callback, java.util.List msg); - /** - * 上报模块间调用采样信息 Mic = module interval call - * @param msg, 上报信息 - * @return int, 返回0表示成功 - */ - public void async_reportSampleMsg(@TarsCallback StatFPrxCallback callback, java.util.List msg, @TarsContext java.util.Map ctx); + /** + * Report calling information between modules Mic = module interval call + * @param statmsg, Report information + * @param bFromServer, Report source bFromClient: true (Reporting initiated by the client) false (Reporting initiated by the server) + * @return int, Return 0 means success + */ + public int reportMicMsg(java.util.Map msg, boolean bFromClient); + + /** + * Report calling information between modules Mic = module interval call + * @param statmsg, Report information + * @param bFromServer, Report source bFromClient: true (Reporting initiated by the client) false (Reporting initiated by the server) + * @return int, Return 0 means success + */ + public int reportMicMsg(java.util.Map msg, boolean bFromClient, @TarsContext java.util.Map ctx); + + + CompletableFuture promise_reportMicMsg(java.util.Map msg, boolean bFromClient); + + /** + * 上报模块间调用采样信息 Mic = module interval call + * @param msg, Report information + * @return int, Return 0 means success + */ + public int reportSampleMsg(java.util.List msg); + + /** + * 上报模块间调用采样信息 Mic = module interval call + * @param msg, Report information + * @return int, Return 0 means success + */ + public int reportSampleMsg(java.util.List msg, @TarsContext java.util.Map ctx); + } diff --git a/core/src/main/java/com/qq/tars/support/stat/prx/StatFPrxCallback.java b/core/src/main/java/com/qq/tars/support/stat/prx/StatFPrxCallback.java deleted file mode 100644 index ac479b2a..00000000 --- a/core/src/main/java/com/qq/tars/support/stat/prx/StatFPrxCallback.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ -// ********************************************************************** -// This file was generated by a TARS parser! -// TARS version 1.0.1. -// ********************************************************************** - -package com.qq.tars.support.stat.prx; - -import com.qq.tars.rpc.protocol.tars.support.TarsAbstractCallback; - -/** - * - * 上报服务的接口 - * - **/ -public abstract class StatFPrxCallback extends TarsAbstractCallback { - - public abstract void callback_reportMicMsg(int ret); - - public abstract void callback_reportSampleMsg(int ret); - -} diff --git a/core/src/main/java/com/qq/tars/support/stat/prx/StatMicMsgBody.java b/core/src/main/java/com/qq/tars/support/stat/prx/StatMicMsgBody.java index 0bb5d636..1d423c40 100644 --- a/core/src/main/java/com/qq/tars/support/stat/prx/StatMicMsgBody.java +++ b/core/src/main/java/com/qq/tars/support/stat/prx/StatMicMsgBody.java @@ -20,10 +20,11 @@ package com.qq.tars.support.stat.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class StatMicMsgBody { diff --git a/core/src/main/java/com/qq/tars/support/stat/prx/StatMicMsgHead.java b/core/src/main/java/com/qq/tars/support/stat/prx/StatMicMsgHead.java index def50548..0b47197e 100644 --- a/core/src/main/java/com/qq/tars/support/stat/prx/StatMicMsgHead.java +++ b/core/src/main/java/com/qq/tars/support/stat/prx/StatMicMsgHead.java @@ -20,10 +20,11 @@ package com.qq.tars.support.stat.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class StatMicMsgHead implements Comparable { diff --git a/core/src/main/java/com/qq/tars/support/stat/prx/StatSampleMsg.java b/core/src/main/java/com/qq/tars/support/stat/prx/StatSampleMsg.java index 9b660550..01137152 100644 --- a/core/src/main/java/com/qq/tars/support/stat/prx/StatSampleMsg.java +++ b/core/src/main/java/com/qq/tars/support/stat/prx/StatSampleMsg.java @@ -20,10 +20,11 @@ package com.qq.tars.support.stat.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; @TarsStruct public class StatSampleMsg { diff --git a/core/src/main/java/com/qq/tars/support/trace/TarsTraceZipkinConfiguration.java b/core/src/main/java/com/qq/tars/support/trace/TarsTraceZipkinConfiguration.java index a49f4899..e1c8af82 100644 --- a/core/src/main/java/com/qq/tars/support/trace/TarsTraceZipkinConfiguration.java +++ b/core/src/main/java/com/qq/tars/support/trace/TarsTraceZipkinConfiguration.java @@ -1,91 +1,33 @@ package com.qq.tars.support.trace; -import io.opentracing.Tracer; - -import java.util.HashMap; -import java.util.Map; - -import zipkin2.codec.Encoding; -import zipkin2.reporter.AsyncReporter; -import zipkin2.reporter.Reporter; -import zipkin2.reporter.Sender; -import zipkin2.reporter.urlconnection.URLConnectionSender; -import brave.Tracing; -import brave.opentracing.BraveTracer; - import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.server.config.ServerConfig; -import com.qq.tars.support.om.OmConstants; -import com.qq.tars.support.trace.exc.NotSupportedSuchSampleEncodeingException; -import com.qq.tars.support.trace.exc.NotSupportedSuchSampleTypeException; +import com.qq.tars.support.trace.spi.ZipkinTraceInitializer; +@Deprecated public class TarsTraceZipkinConfiguration { - - private ServerConfig serverConfig = ConfigurationManager.getInstance().getServerConfig(); - - private volatile boolean isTrace = false; - - private Sender sender; - - private Reporter reporter; - - private static final TarsTraceZipkinConfiguration instance = new TarsTraceZipkinConfiguration(); - - private TarsTraceZipkinConfiguration() {} - - public static TarsTraceZipkinConfiguration getInstance() { - return instance; - } - - public void init() { - isTrace = serverConfig.getSampleRate() > 0; - if (isTrace) { - try { - createSender(); - reporter = AsyncReporter.builder(sender).build(); - Map traces = new HashMap(); - for (String servant : serverConfig.getServantAdapterConfMap().keySet()) { - if (!servant.equals(OmConstants.AdminServant)) { - Tracing tracing = Tracing.newBuilder().localServiceName(servant) - .spanReporter(reporter).sampler(brave.sampler.Sampler.create(serverConfig.getSampleRate())).build(); - Tracer tracer = BraveTracer.create(tracing); - traces.put(servant, tracer); - } - } - TraceManager.getInstance().putTracers(traces); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - private void createSender() throws NotSupportedSuchSampleTypeException, NotSupportedSuchSampleEncodeingException { - if ("http".equals(serverConfig.getSampleType())) { - String baseurl = serverConfig.getSampleAddress(); - String url = baseurl + (baseurl.endsWith("/") ? "" : "/") + "api/v2/spans"; - Encoding codec = createCodec(); - sender = URLConnectionSender.newBuilder().encoding(codec).endpoint(url).build(); - } else if ("kafka08".equals(serverConfig.getSampleType())) { - Encoding codec = createCodec(); - sender = zipkin2.reporter.kafka08.KafkaSender.newBuilder().encoding(codec) - .bootstrapServers(serverConfig.getSampleAddress()).build(); - } else if ("kafka".equals(serverConfig.getSampleType())) { - Encoding codec = createCodec(); - sender = zipkin2.reporter.kafka11.KafkaSender.newBuilder().encoding(codec) - .bootstrapServers(serverConfig.getSampleAddress()).build(); - } else { - throw new NotSupportedSuchSampleTypeException("unsupported sample type"); - } - } - - private Encoding createCodec() throws NotSupportedSuchSampleEncodeingException { - if ("json".endsWith(serverConfig.getSampleEncoding())) { - return Encoding.JSON; - } - if ("proto".endsWith(serverConfig.getSampleEncoding())) { - return Encoding.PROTO3; - } - throw new NotSupportedSuchSampleEncodeingException("unsupported sample encoding"); - } + private static final TarsTraceZipkinConfiguration INSTANCE = new TarsTraceZipkinConfiguration(); + + private final ZipkinTraceInitializer zipkinTraceInitializer = new ZipkinTraceInitializer(); + + private TarsTraceZipkinConfiguration() { + } + + public static TarsTraceZipkinConfiguration getInstance() { + return INSTANCE; + } + + public void init() { + ServerConfig serverConfig = ConfigurationManager.getInstance().getServerConfig(); + if (serverConfig == null || !zipkinTraceInitializer.supports(serverConfig)) { + return; + } + + try { + zipkinTraceInitializer.init(serverConfig); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/core/src/main/java/com/qq/tars/support/trace/TraceCallbackFilter.java b/core/src/main/java/com/qq/tars/support/trace/TraceCallbackFilter.java index 3aeb470f..0daf16a9 100644 --- a/core/src/main/java/com/qq/tars/support/trace/TraceCallbackFilter.java +++ b/core/src/main/java/com/qq/tars/support/trace/TraceCallbackFilter.java @@ -1,61 +1,69 @@ package com.qq.tars.support.trace; -import io.opentracing.Scope; -import io.opentracing.Span; -import io.opentracing.Tracer; - +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; import com.qq.tars.client.util.Pair; import com.qq.tars.common.Filter; import com.qq.tars.common.FilterChain; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; import com.qq.tars.rpc.exc.TimeoutException; import com.qq.tars.rpc.protocol.tars.TarsServantRequest; import com.qq.tars.rpc.protocol.tars.TarsServantResponse; import com.qq.tars.server.config.ConfigurationManager; +import io.opentracing.Scope; +import io.opentracing.Span; +import io.opentracing.Tracer; + +import java.util.concurrent.CompletableFuture; public class TraceCallbackFilter implements Filter { - - private boolean isTrace = false; - - @Override - public void init() { - isTrace = ConfigurationManager.getInstance().getServerConfig().getSampleRate() > 0; - } - - @Override - public void doFilter(Request request, Response response, FilterChain chain) - throws Throwable { - if (!isTrace) { - chain.doFilter(request, response); - return; - } - if (response == null || !(request instanceof TarsServantRequest) || !TraceUtil.checkServant(((TarsServantRequest)request).getServantName())) { - chain.doFilter(request, response); - return; - } - Pair entry = TraceManager.getInstance().getCurrentSpan(response.getTicketNumber()); - if (entry != null && entry.getFirst() != null && entry.getSecond() != null) { - try (Scope scope = entry.getFirst().scopeManager().activate(entry.getSecond(), true)) { - TarsServantResponse tarsServantResponse = (TarsServantResponse)response; - if (tarsServantResponse.getCause() instanceof TimeoutException) { - scope.span().log(tarsServantResponse.getCause().getMessage()); - } else { - scope.span().setTag("tars.retcode", tarsServantResponse.getRet()); - } - - } - TraceManager.getInstance().removeSpan(response.getTicketNumber()); - } - - chain.doFilter(request, response); - } - - @Override - public void destroy() { - - - } + + private boolean isTrace = false; + + @Override + public void init() { + isTrace = ConfigurationManager.getInstance().getServerConfig().getSampleRate() > 0; + } + + @Override + public void doFilter(Request request, Response response, FilterChain chain) + throws Throwable { + if (!isTrace) { + chain.doFilter(request, response); + return; + } + if (response == null || !(request instanceof TarsServantRequest) || !TraceUtil.checkServant(((TarsServantRequest) request).getServantName())) { + chain.doFilter(request, response); + return; + } + Pair entry = TraceManager.getInstance().getCurrentSpan(response.getRequestId()); + if (entry != null && entry.getFirst() != null && entry.getSecond() != null) { + Span span = entry.getSecond(); + try (Scope scope = entry.getFirst().activateSpan(span)) { + TarsServantResponse tarsServantResponse = (TarsServantResponse) response; + if (tarsServantResponse.getCause() instanceof TimeoutException) { + span.log(tarsServantResponse.getCause().getMessage()); + } else { + span.setTag("tars.retcode", tarsServantResponse.getRet()); + } + } finally { + span.finish(); + } + TraceManager.getInstance().removeSpan(response.getRequestId()); + } + + chain.doFilter(request, response); + } + + @Override + public CompletableFuture doFilter(Request request, FilterChain chain) throws Throwable { + return null; + } + + @Override + public void destroy() { + + + } } diff --git a/core/src/main/java/com/qq/tars/support/trace/TraceClientFilter.java b/core/src/main/java/com/qq/tars/support/trace/TraceClientFilter.java index 9b5fbfd6..ca792f5e 100644 --- a/core/src/main/java/com/qq/tars/support/trace/TraceClientFilter.java +++ b/core/src/main/java/com/qq/tars/support/trace/TraceClientFilter.java @@ -1,112 +1,120 @@ package com.qq.tars.support.trace; -import java.util.HashMap; -import java.util.Map; - -import io.opentracing.Scope; -import io.opentracing.Tracer; -import io.opentracing.propagation.Format; -import io.opentracing.propagation.TextMapInjectAdapter; -import io.opentracing.tag.Tags; - +import com.google.common.collect.Maps; +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; import com.qq.tars.common.ClientVersion; import com.qq.tars.common.Filter; import com.qq.tars.common.FilterChain; import com.qq.tars.common.util.Constants; -import com.qq.tars.context.DistributedContext; -import com.qq.tars.context.DistributedContextManager; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Request.InvokeStatus; -import com.qq.tars.net.core.Response; +import com.qq.tars.context.TarsContext; import com.qq.tars.rpc.protocol.tars.TarsServantRequest; import com.qq.tars.rpc.protocol.tars.TarsServantResponse; import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.server.config.ServerConfig; +import io.opentracing.Scope; +import io.opentracing.Span; +import io.opentracing.Tracer; +import io.opentracing.propagation.Format; +import io.opentracing.propagation.TextMapInjectAdapter; +import io.opentracing.tag.Tags; + +import java.util.Map; +import java.util.concurrent.CompletableFuture; public class TraceClientFilter implements Filter { - private boolean isTrace = false; + private boolean isTrace = false; + + @Override + public void init() { + isTrace = ConfigurationManager.getInstance().getServerConfig().getSampleRate() > 0; + } - @Override - public void init() { - isTrace = ConfigurationManager.getInstance().getServerConfig().getSampleRate() > 0; - } + @Override + public void doFilter(Request request, Response response, FilterChain chain) throws Throwable { + if (!isTrace) { + chain.doFilter(request, response); + return; + } + if (!(request instanceof TarsServantRequest) || !TraceUtil.checkServant(((TarsServantRequest) request).getServantName())) { + chain.doFilter(request, response); + return; + } + ServerConfig config = ConfigurationManager.getInstance().getServerConfig(); + String servantName = TarsContext.current().get(TarsContext.SERVANT_NAME); + Tracer tracer = TraceContext.getInstance().getCurrentTracer(); - @Override - public void doFilter(Request request, Response response, FilterChain chain) throws Throwable { - if (!isTrace) { - chain.doFilter(request, response); - return; - } - if (!(request instanceof TarsServantRequest) || !TraceUtil.checkServant(((TarsServantRequest)request).getServantName())) { - chain.doFilter(request, response); - return; - } - ServerConfig config = ConfigurationManager.getInstance().getServerConfig(); - DistributedContext context = DistributedContextManager.getDistributedContext(); - String servantName = context.get(TraceManager.INTERNAL_SERVANT_NAME); - Tracer tracer = TraceContext.getIntance().getCurrentTracer(); - if (tracer == null) { - chain.doFilter(request, response); + chain.doFilter(request, response); } else { - TarsServantRequest tarsServantRequest = (TarsServantRequest)request; - boolean isSync = tarsServantRequest.getInvokeStatus() == InvokeStatus.SYNC_CALL - || tarsServantRequest.getInvokeStatus() == InvokeStatus.FUTURE_CALL; - - String protocol = Constants.TARS_PROTOCOL; - Map requestContext = tarsServantRequest.getContext(); - if (requestContext != null && !requestContext.isEmpty()) { - protocol = requestContext.get(TraceManager.PROTOCOL); - requestContext.remove(TraceManager.PROTOCOL); - } - try(Scope scope = tracer.buildSpan(tarsServantRequest.getFunctionName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).startActive(isSync)) { - Map status = tarsServantRequest.getStatus(); - if (status == null) { - tarsServantRequest.setStatus(new HashMap()); - status = tarsServantRequest.getStatus(); - } - tracer.inject(scope.span().context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(status)); - scope.span().setTag("client.ipv4", config.getLocalIP()); - scope.span().setTag("client.port", config.getServantAdapterConfMap().get(servantName).getEndpoint().port()); - scope.span().setTag("tars.interface", getObjName(servantName)); - scope.span().setTag("tars.method", tarsServantRequest.getFunctionName()); - scope.span().setTag("tars.protocol", protocol); - scope.span().setTag("tars.client.version", ClientVersion.getVersion()); - - - TarsServantResponse tarsServantResponse = (TarsServantResponse)response; - try { - chain.doFilter(request, response); - if (isSync) { - scope.span().setTag("tars.retcode", Integer.toString(tarsServantResponse.getRet())); - } else { - TraceManager.getInstance().putSpan(request.getTicketNumber(), tracer, scope.span()); - } - } catch (Exception e) { - scope.span().log(e.getMessage()); - throw e; - } - - - } + TarsServantRequest tarsServantRequest = (TarsServantRequest) request; + boolean isSync = tarsServantRequest.getInvokeStatus() == Request.InvokeStatus.SYNC_CALL + || tarsServantRequest.getInvokeStatus() == Request.InvokeStatus.FUTURE_CALL; + + String protocol = Constants.TARS_PROTOCOL; + Map requestContext = tarsServantRequest.getContext(); + if (requestContext != null && !requestContext.isEmpty()) { + protocol = requestContext.get(TraceManager.PROTOCOL).toString(); + requestContext.remove(TraceManager.PROTOCOL); + } + Span span = tracer.buildSpan(tarsServantRequest.getFunctionName()) + .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT) + .start(); + try (Scope scope = tracer.activateSpan(span)) { + Map status = tarsServantRequest.getStatus(); + if (status == null) { + tarsServantRequest.setStatus(Maps.newHashMap()); + status = tarsServantRequest.getStatus(); + } + tracer.inject(span.context(), Format.Builtin.TEXT_MAP_INJECT, new TextMapInjectAdapter(status)); + span.setTag("client.ipv4", config.getLocalIP()); + span.setTag("client.port", config.getServantAdapterConfMap().get(servantName).getEndpoint().port()); + span.setTag("tars.interface", getObjName(servantName)); + span.setTag("tars.method", tarsServantRequest.getFunctionName()); + span.setTag("tars.protocol", protocol); + span.setTag("tars.client.version", ClientVersion.getVersion()); + + + TarsServantResponse tarsServantResponse = (TarsServantResponse) response; + try { + chain.doFilter(request, response); + if (isSync) { + span.setTag("tars.retcode", Integer.toString(tarsServantResponse.getRet())); + } else { + TraceManager.getInstance().putSpan(request.getRequestId(), tracer, span); + } + } catch (Exception e) { + span.log(e.getMessage()); + throw e; + } finally { + if (isSync) { + span.finish(); + } + } + } } - } + } + + @Override + public CompletableFuture doFilter(Request request, FilterChain chain) throws Throwable { + return null; + } - @Override - public void destroy() { + @Override + public void destroy() { - } - - private String getObjName(String fullName) { - if (fullName == null || fullName.length() == 0) { - return null; - } - String[] parts = fullName.split("\\."); - if (parts.length < 3) { - return fullName; - } - return parts[2]; - } + } + + private String getObjName(String fullName) { + if (fullName == null || fullName.length() == 0) { + return null; + } + String[] parts = fullName.split("\\."); + if (parts.length < 3) { + return fullName; + } + return parts[2]; + } } diff --git a/core/src/main/java/com/qq/tars/support/trace/TraceContext.java b/core/src/main/java/com/qq/tars/support/trace/TraceContext.java index efd53feb..e784cd11 100644 --- a/core/src/main/java/com/qq/tars/support/trace/TraceContext.java +++ b/core/src/main/java/com/qq/tars/support/trace/TraceContext.java @@ -1,6 +1,6 @@ package com.qq.tars.support.trace; -import io.opentracing.Scope; +import io.opentracing.Span; import io.opentracing.Tracer; import java.io.Closeable; @@ -14,7 +14,7 @@ public class TraceContext implements Closeable { private TraceContext() {} - public static TraceContext getIntance() { + public static TraceContext getInstance() { return instance; } @@ -39,9 +39,9 @@ public Tracer getCurrentTracer() { public void tag(String key, String value) { Tracer tracer = currentTracer.get(); if (tracer != null) { - Scope scope = tracer.scopeManager().active(); - if (scope != null) { - scope.span().setTag(key, value); + Span span = tracer.activeSpan(); + if (span != null) { + span.setTag(key, value); } } } @@ -49,9 +49,9 @@ public void tag(String key, String value) { public void log(String event, long timestamp) { Tracer tracer = currentTracer.get(); if (tracer != null) { - Scope scope = tracer.scopeManager().active(); - if (scope != null) { - scope.span().log(timestamp, event); + Span span = tracer.activeSpan(); + if (span != null) { + span.log(timestamp, event); } } } @@ -59,9 +59,9 @@ public void log(String event, long timestamp) { public void log(String event) { Tracer tracer = currentTracer.get(); if (tracer != null) { - Scope scope = tracer.scopeManager().active(); - if (scope != null) { - scope.span().log(event); + Span span = tracer.activeSpan(); + if (span != null) { + span.log(event); } } } diff --git a/core/src/main/java/com/qq/tars/support/trace/TraceManager.java b/core/src/main/java/com/qq/tars/support/trace/TraceManager.java index 1fdb752e..0dc1f016 100644 --- a/core/src/main/java/com/qq/tars/support/trace/TraceManager.java +++ b/core/src/main/java/com/qq/tars/support/trace/TraceManager.java @@ -1,51 +1,50 @@ package com.qq.tars.support.trace; +import com.qq.tars.client.util.Pair; import io.opentracing.Span; import io.opentracing.Tracer; -import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import com.qq.tars.client.util.Pair; - public class TraceManager { - - public static final String INTERNAL_SERVANT_NAME = "internal_servant"; - - public static final String PROTOCOL = "protocol"; - - private Map traces = new HashMap(); - - private static final ConcurrentHashMap> spanMap = new ConcurrentHashMap>(); - - private static final TraceManager instance = new TraceManager(); - - private TraceManager() {} - - public static TraceManager getInstance() { - return instance; - } - - public Tracer getCurrentTracer(String servant) { - return traces.get(servant); - } - - public void putTracers(Map _traces) { - traces.putAll(_traces); - } - - public Pair getCurrentSpan(int ticketNum) { - return spanMap.get(ticketNum); - } - - public void putSpan(int ticketNum, Tracer tracer, Span span) { - Pair pair = new Pair(tracer, span); - spanMap.put(ticketNum, pair); - } - - public void removeSpan(int ticketNum) { - spanMap.remove(ticketNum); - } + + public static final String INTERNAL_SERVANT_NAME = "internal_servant"; + + public static final String PROTOCOL = "protocol"; + + private Map traces = new ConcurrentHashMap<>(); + + private static final ConcurrentHashMap> spanMap = new ConcurrentHashMap>(); + + private static final TraceManager instance = new TraceManager(); + + private TraceManager() { + } + + public static TraceManager getInstance() { + return instance; + } + + public Tracer getCurrentTracer(String servant) { + return traces.get(servant); + } + + public void putTracers(Map _traces) { + traces.putAll(_traces); + } + + public Pair getCurrentSpan(int ticketNum) { + return spanMap.get(ticketNum); + } + + public void putSpan(int ticketNum, Tracer tracer, Span span) { + Pair pair = new Pair(tracer, span); + spanMap.put(ticketNum, pair); + } + + public void removeSpan(int ticketNum) { + spanMap.remove(ticketNum); + } } diff --git a/core/src/main/java/com/qq/tars/support/trace/TraceServerFilter.java b/core/src/main/java/com/qq/tars/support/trace/TraceServerFilter.java index e1a0e3fa..ec1ff77f 100644 --- a/core/src/main/java/com/qq/tars/support/trace/TraceServerFilter.java +++ b/core/src/main/java/com/qq/tars/support/trace/TraceServerFilter.java @@ -1,77 +1,79 @@ package com.qq.tars.support.trace; -import java.util.Map; - +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; import com.qq.tars.common.ClientVersion; -import io.opentracing.Scope; -import io.opentracing.Tracer; -import io.opentracing.propagation.Format; -import io.opentracing.propagation.TextMapExtractAdapter; -import io.opentracing.tag.Tags; - import com.qq.tars.common.Filter; import com.qq.tars.common.FilterChain; import com.qq.tars.common.support.Endpoint; import com.qq.tars.common.util.StringUtils; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; import com.qq.tars.rpc.protocol.tars.TarsServantRequest; -import com.qq.tars.rpc.protocol.tars.TarsServantResponse; import com.qq.tars.server.config.ConfigurationManager; +import io.opentracing.Scope; +import io.opentracing.Span; +import io.opentracing.Tracer; +import io.opentracing.propagation.Format; +import io.opentracing.propagation.TextMapExtractAdapter; +import io.opentracing.tag.Tags; + +import java.util.Map; +import java.util.concurrent.CompletableFuture; public class TraceServerFilter implements Filter { - - private volatile boolean isTrace = false; - - @Override - public void init() { - isTrace = ConfigurationManager.getInstance().getServerConfig().getSampleRate() > 0; - } - @Override - public void doFilter(Request request, Response response, FilterChain chain) - throws Throwable { - if (!isTrace || !(request instanceof TarsServantRequest)) { - chain.doFilter(request, response); - } else { - - TarsServantRequest tarsServantRequest = (TarsServantRequest)request; - - try(TraceContext traceContext = TraceContext.getIntance().initCurrentTrace(tarsServantRequest.getServantName())) { - Tracer tracer = TraceContext.getIntance().getCurrentTracer(); - Map status = tarsServantRequest.getStatus(); - if (tracer == null || status == null || status.isEmpty()) { - chain.doFilter(request, response); - return; - } - try (Scope scope = tracer.buildSpan(tarsServantRequest.getFunctionName()) - .asChildOf(tracer.extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(status))) - .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).startActive(true)) { - Endpoint endpoint = ConfigurationManager.getInstance().getServerConfig().getServantAdapterConfMap().get(tarsServantRequest.getServantName()).getEndpoint(); - scope.span().setTag("server.ipv4", ConfigurationManager.getInstance().getServerConfig().getLocalIP()); - if (endpoint != null) { - scope.span().setTag("server.port", endpoint.port()); - if (StringUtils.isNotEmpty(endpoint.setDivision())) { - scope.span().setTag("tars.set_division", endpoint.setDivision()); - } - scope.span().setTag("tars.server.version", ClientVersion.getVersion()); - } - chain.doFilter(request, response); - TarsServantResponse tarsServantResponse = (TarsServantResponse)response; - if (response != null && tarsServantResponse.getCause() != null && tarsServantResponse.getCause().getMessage() != null) { - scope.span().log(tarsServantResponse.getCause().getMessage()); - } - - } - } - } + private volatile boolean isTrace = false; + + @Override + public void init() { + isTrace = ConfigurationManager.getInstance().getServerConfig().getSampleRate() > 0; + } + + @Override + public void doFilter(Request request, Response response, FilterChain chain) throws Throwable { + + } + + @Override + public CompletableFuture doFilter(Request request, FilterChain chain) + throws Throwable { + if (!isTrace || !(request instanceof TarsServantRequest)) { + return chain.doFilter(request); + } else { + TarsServantRequest tarsServantRequest = (TarsServantRequest) request; + try (TraceContext traceContext = TraceContext.getInstance().initCurrentTrace(tarsServantRequest.getServantName())) { + Tracer tracer = TraceContext.getInstance().getCurrentTracer(); + Map status = tarsServantRequest.getStatus(); + if (tracer == null || status == null || status.isEmpty()) { + return chain.doFilter(request); + } + Span span = tracer.buildSpan(tarsServantRequest.getFunctionName()) + .asChildOf(tracer.extract(Format.Builtin.TEXT_MAP_EXTRACT, new TextMapExtractAdapter(status))) + .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER) + .start(); + try (Scope scope = tracer.activateSpan(span)) { + Endpoint endpoint = ConfigurationManager.getInstance().getServerConfig() + .getServantAdapterConfMap().get(tarsServantRequest.getServantName()).getEndpoint(); + span.setTag("server.ipv4", ConfigurationManager.getInstance().getServerConfig().getLocalIP()); + if (endpoint != null) { + span.setTag("server.port", endpoint.port()); + if (StringUtils.isNotEmpty(endpoint.setDivision())) { + span.setTag("tars.set_division", endpoint.setDivision()); + } + span.setTag("tars.server.version", ClientVersion.getVersion()); + } + return chain.doFilter(request); + } finally { + span.finish(); + } + } + } + + } - } + @Override + public void destroy() { - @Override - public void destroy() { - - } + } } diff --git a/core/src/main/java/com/qq/tars/support/trace/exc/NotSupportedSuchSampleEncodeingException.java b/core/src/main/java/com/qq/tars/support/trace/exc/NotSupportedSuchSampleEncodeingException.java deleted file mode 100644 index 2d1b395c..00000000 --- a/core/src/main/java/com/qq/tars/support/trace/exc/NotSupportedSuchSampleEncodeingException.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.qq.tars.support.trace.exc; - -@SuppressWarnings("serial") -public class NotSupportedSuchSampleEncodeingException extends Exception { - - public NotSupportedSuchSampleEncodeingException(String message) { - super(message); - } - -} diff --git a/core/src/main/java/com/qq/tars/support/trace/exc/NotSupportedSuchSampleEncodingException.java b/core/src/main/java/com/qq/tars/support/trace/exc/NotSupportedSuchSampleEncodingException.java new file mode 100644 index 00000000..c73ca0a3 --- /dev/null +++ b/core/src/main/java/com/qq/tars/support/trace/exc/NotSupportedSuchSampleEncodingException.java @@ -0,0 +1,10 @@ +package com.qq.tars.support.trace.exc; + +@SuppressWarnings("serial") +public class NotSupportedSuchSampleEncodingException extends Exception { + + public NotSupportedSuchSampleEncodingException(String message) { + super(message); + } + +} diff --git a/core/src/main/java/com/qq/tars/support/trace/spi/SkywalkingTraceInitializer.java b/core/src/main/java/com/qq/tars/support/trace/spi/SkywalkingTraceInitializer.java new file mode 100644 index 00000000..f91802c2 --- /dev/null +++ b/core/src/main/java/com/qq/tars/support/trace/spi/SkywalkingTraceInitializer.java @@ -0,0 +1,115 @@ +package com.qq.tars.support.trace.spi; + +import com.qq.tars.server.config.ServerConfig; +import com.qq.tars.support.om.OmConstants; +import com.qq.tars.support.trace.TraceManager; +import io.opentracing.Tracer; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; +import io.opentelemetry.opentracingshim.OpenTracingShim; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import io.opentelemetry.sdk.trace.samplers.Sampler; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public class SkywalkingTraceInitializer implements TraceInitializer { + + @Override + public String name() { + return "skywalking"; + } + + @Override + public boolean supports(ServerConfig serverConfig) { + if (serverConfig == null || serverConfig.getSampleType() == null) { + return false; + } + + String sampleType = serverConfig.getSampleType().trim().toLowerCase(Locale.ROOT); + return "skywalking".equals(sampleType) + || "sw".equals(sampleType) + || "sw8".equals(sampleType); + } + + @Override + public void init(ServerConfig serverConfig) { + if (serverConfig.getSampleRate() <= 0) { + return; + } + + String endpoint = normalizeEndpoint(serverConfig.getSampleAddress(), useHttpExporter(serverConfig.getSampleEncoding())); + SpanExporter spanExporter = createSpanExporter(endpoint, serverConfig.getSampleEncoding()); + + Map traces = new HashMap<>(); + for (String servant : serverConfig.getServantAdapterConfMap().keySet()) { + if (OmConstants.AdminServant.equals(servant)) { + continue; + } + + Resource resource = Resource.getDefault().toBuilder() + .put(AttributeKey.stringKey("service.name"), servant) + .build(); + + SdkTracerProvider tracerProvider = SdkTracerProvider.builder() + .setResource(resource) + .setSampler(Sampler.traceIdRatioBased(serverConfig.getSampleRate())) + .addSpanProcessor(BatchSpanProcessor.builder(spanExporter).build()) + .build(); + + OpenTelemetrySdk openTelemetrySdk = OpenTelemetrySdk.builder() + .setTracerProvider(tracerProvider) + .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance())) + .build(); + + traces.put(servant, OpenTracingShim.createTracerShim(openTelemetrySdk)); + } + + TraceManager.getInstance().putTracers(traces); + } + + private SpanExporter createSpanExporter(String endpoint, String sampleEncoding) { + if (useHttpExporter(sampleEncoding)) { + return OtlpHttpSpanExporter.builder().setEndpoint(endpoint).build(); + } + return OtlpGrpcSpanExporter.builder().setEndpoint(endpoint).build(); + } + + private boolean useHttpExporter(String sampleEncoding) { + if (sampleEncoding == null) { + return false; + } + + String encoding = sampleEncoding.trim().toLowerCase(Locale.ROOT); + return "http".equals(encoding) || "otlp_http".equals(encoding); + } + + private String normalizeEndpoint(String sampleAddress, boolean useHttpExporter) { + if (sampleAddress == null || sampleAddress.trim().isEmpty()) { + throw new IllegalArgumentException("sampleAddress is required for skywalking tracing"); + } + + String endpoint = sampleAddress.trim(); + if (!endpoint.contains("://")) { + endpoint = "http://" + endpoint; + } + + if (!useHttpExporter) { + return endpoint; + } + + if (endpoint.endsWith("/v1/traces")) { + return endpoint; + } + + return endpoint + (endpoint.endsWith("/") ? "v1/traces" : "/v1/traces"); + } +} diff --git a/core/src/main/java/com/qq/tars/support/trace/spi/TraceInitializer.java b/core/src/main/java/com/qq/tars/support/trace/spi/TraceInitializer.java new file mode 100644 index 00000000..9716b73f --- /dev/null +++ b/core/src/main/java/com/qq/tars/support/trace/spi/TraceInitializer.java @@ -0,0 +1,12 @@ +package com.qq.tars.support.trace.spi; + +import com.qq.tars.server.config.ServerConfig; + +public interface TraceInitializer { + + String name(); + + boolean supports(ServerConfig serverConfig); + + void init(ServerConfig serverConfig) throws Exception; +} diff --git a/core/src/main/java/com/qq/tars/support/trace/spi/TraceInitializerManager.java b/core/src/main/java/com/qq/tars/support/trace/spi/TraceInitializerManager.java new file mode 100644 index 00000000..a64c2e0b --- /dev/null +++ b/core/src/main/java/com/qq/tars/support/trace/spi/TraceInitializerManager.java @@ -0,0 +1,77 @@ +package com.qq.tars.support.trace.spi; + +import com.qq.tars.server.config.ConfigurationManager; +import com.qq.tars.server.config.ServerConfig; +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.ServiceLoader; + +public class TraceInitializerManager { + + private static final Logger logger = Logger.getLogger(TraceInitializerManager.class.getName()); + + private static final TraceInitializerManager INSTANCE = new TraceInitializerManager(loadInitializers()); + + private final List traceInitializers; + + TraceInitializerManager(List traceInitializers) { + if (traceInitializers == null || traceInitializers.isEmpty()) { + this.traceInitializers = Collections.emptyList(); + return; + } + this.traceInitializers = Collections.unmodifiableList(new ArrayList<>(traceInitializers)); + } + + public static TraceInitializerManager getInstance() { + return INSTANCE; + } + + public void init() { + ServerConfig serverConfig = ConfigurationManager.getInstance().getServerConfig(); + if (serverConfig == null) { + logger.warning("Skip trace initialization because server config is null"); + return; + } + init(serverConfig); + } + + boolean init(ServerConfig serverConfig) { + if (serverConfig.getSampleRate() <= 0) { + return false; + } + + for (TraceInitializer traceInitializer : traceInitializers) { + if (!traceInitializer.supports(serverConfig)) { + continue; + } + try { + traceInitializer.init(serverConfig); + logger.log(Level.INFO, "Initialized trace provider: {0}", traceInitializer.name()); + return true; + } catch (Exception e) { + logger.log(Level.SEVERE, "Failed to initialize trace provider: " + traceInitializer.name(), e); + return false; + } + } + + logger.log(Level.WARNING, "No trace initializer supports sampleType={0}.", serverConfig.getSampleType()); + return false; + } + + static List loadInitializers() { + ServiceLoader loaders = ServiceLoader.load(TraceInitializer.class); + List initializers = new ArrayList<>(); + for (TraceInitializer initializer : loaders) { + initializers.add(initializer); + } + return initializers; + } + + List getTraceInitializers() { + return traceInitializers; + } +} diff --git a/core/src/main/java/com/qq/tars/support/trace/spi/ZipkinTraceInitializer.java b/core/src/main/java/com/qq/tars/support/trace/spi/ZipkinTraceInitializer.java new file mode 100644 index 00000000..77f00def --- /dev/null +++ b/core/src/main/java/com/qq/tars/support/trace/spi/ZipkinTraceInitializer.java @@ -0,0 +1,110 @@ +package com.qq.tars.support.trace.spi; + +import brave.Tracing; +import brave.opentracing.BraveTracer; +import com.qq.tars.server.config.ServerConfig; +import com.qq.tars.support.om.OmConstants; +import com.qq.tars.support.trace.TraceManager; +import com.qq.tars.support.trace.exc.NotSupportedSuchSampleEncodingException; +import com.qq.tars.support.trace.exc.NotSupportedSuchSampleTypeException; +import io.opentracing.Tracer; +import zipkin2.reporter.AsyncReporter; +import zipkin2.reporter.Encoding; +import zipkin2.reporter.Reporter; +import zipkin2.reporter.Sender; +import zipkin2.reporter.urlconnection.URLConnectionSender; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public class ZipkinTraceInitializer implements TraceInitializer { + + @Override + public String name() { + return "zipkin"; + } + + @Override + public boolean supports(ServerConfig serverConfig) { + if (serverConfig == null || serverConfig.getSampleType() == null) { + return false; + } + + String sampleType = serverConfig.getSampleType().trim().toLowerCase(Locale.ROOT); + return "http".equals(sampleType) + || "kafka08".equals(sampleType) + || "kafka11".equals(sampleType) + || "kafka".equals(sampleType); + } + + @Override + public void init(ServerConfig serverConfig) throws Exception { + if (serverConfig.getSampleRate() <= 0) { + return; + } + + Sender sender = createSender(serverConfig); + Reporter reporter = AsyncReporter.builder(sender).build(); + + Map traces = new HashMap<>(); + for (String servant : serverConfig.getServantAdapterConfMap().keySet()) { + if (!OmConstants.AdminServant.equals(servant)) { + Tracing tracing = Tracing.newBuilder() + .localServiceName(servant) + .spanReporter(reporter) + .sampler(brave.sampler.Sampler.create(serverConfig.getSampleRate())) + .build(); + traces.put(servant, BraveTracer.create(tracing)); + } + } + + TraceManager.getInstance().putTracers(traces); + } + + private Sender createSender(ServerConfig serverConfig) + throws NotSupportedSuchSampleTypeException, NotSupportedSuchSampleEncodingException { + String sampleType = serverConfig.getSampleType().trim().toLowerCase(Locale.ROOT); + String sampleAddress = requireSampleAddress(serverConfig.getSampleAddress()); + Encoding codec = createCodec(serverConfig); + + if ("http".equals(sampleType)) { + String baseurl = normalizeHttpBaseAddress(sampleAddress); + String url = baseurl + (baseurl.endsWith("/") ? "" : "/") + "api/v2/spans"; + return URLConnectionSender.newBuilder().encoding(codec).endpoint(url).build(); + } + + if ("kafka08".equals(sampleType) || "kafka11".equals(sampleType) || "kafka".equals(sampleType)) { + return zipkin2.reporter.kafka.KafkaSender.newBuilder().encoding(codec) + .bootstrapServers(sampleAddress) + .build(); + } + + throw new NotSupportedSuchSampleTypeException("unsupported sample type"); + } + + private String requireSampleAddress(String sampleAddress) { + if (sampleAddress == null || sampleAddress.trim().isEmpty()) { + throw new IllegalArgumentException("sampleAddress is required for zipkin tracing"); + } + return sampleAddress.trim(); + } + + private String normalizeHttpBaseAddress(String sampleAddress) { + if (sampleAddress.contains("://")) { + return sampleAddress; + } + return "http://" + sampleAddress; + } + + private Encoding createCodec(ServerConfig serverConfig) throws NotSupportedSuchSampleEncodingException { + String sampleEncoding = serverConfig.getSampleEncoding(); + if (sampleEncoding == null || sampleEncoding.trim().isEmpty() || "json".equalsIgnoreCase(sampleEncoding)) { + return Encoding.JSON; + } + if ("proto".equalsIgnoreCase(sampleEncoding) || "proto3".equalsIgnoreCase(sampleEncoding)) { + return Encoding.PROTO3; + } + throw new NotSupportedSuchSampleEncodingException("unsupported sample encoding"); + } +} diff --git a/core/src/main/resources/AdminF.tars b/core/src/main/resources/AdminF.tars index 93ea6fbd..d94f0b52 100644 --- a/core/src/main/resources/AdminF.tars +++ b/core/src/main/resources/AdminF.tars @@ -13,19 +13,19 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ - + module tars { interface AdminF { /** - * 关闭服务 - */ + * Close service + */ void shutdown(); /** - * 通知服务 - */ + * Notification service + */ string notify(string command); }; }; diff --git a/core/src/main/resources/ConfigF.tars b/core/src/main/resources/ConfigF.tars index 63d91d1d..841084ed 100644 --- a/core/src/main/resources/ConfigF.tars +++ b/core/src/main/resources/ConfigF.tars @@ -13,48 +13,48 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ - + module tars { - struct ConfigInfo - { - //业务名称 - 0 require string appname; - //服务名称 - 1 require string servername; - //配置文件名称 - 2 require string filename; - //是否只获取应用配置,默认为false,如果为true则servername可以为空 - 3 require bool bAppOnly=false; - //服务所在节点(ip) - 4 optional string host; - //set分组名称 - 5 optional string setdivision; - }; - - struct GetConfigListInfo - { - //业务名称 - 0 require string appname; - //服务名称 - 1 optional string servername; - //是否只获取应用配置,默认为false,如果为true只拉取应用级别的列表,其它级别无效 - 2 optional bool bAppOnly=false; - //服务所在节点(ip),要机器级别的,请赋值 - 3 optional string host=""; - //set分组名称,需要拉取set级别的,请赋值 - 4 optional string setdivision=""; - //容器级别,需要拉取容器级别的,请赋值 - 5 optional string containername=""; - }; - + struct ConfigInfo + { + //Application name + 0 require string appname; + //Service name + 1 require string servername; + //Profile name + 2 require string filename; + //Whether to only get the application configuration, the default is false, if true, servername can be empty + 3 require bool bAppOnly = false; + //Service node(ip) + 4 optional string host; + //Set group name + 5 optional string setdivision; + }; + + struct GetConfigListInfo + { + //Application name + 0 require string appname; + //Service name + 1 optional string servername; + //Whether to only get the application configuration, the default is false, if true, only pull the application level list, other levels are invalid + 2 optional bool bAppOnly = false; + //Service node(ip),if you want the machine level, please assign a value + 3 optional string host = ""; + //Set group name, if you want to pull the set level, please assign a value + 4 optional string setdivision = ""; + //Container level, if you want to pull the container level, please assign a value + 5 optional string containername = ""; + }; + /** * config obj to load server's system config. **/ interface Config { /** - * 读取配置文件列表 + * Read configuration file list * @param app, app name * @param server, server name * @param vf, config file name @@ -62,57 +62,57 @@ module tars int ListConfig(string app, string server, out vector vf); /** - * 读取配置文件 + * Read configuration file * @param app, app name * @param server, server name * @param filename, config file name - * @param config, 配置文件内容 + * @param config, Configuration file content **/ int loadConfig(string app, string server, string filename, out string config); /** - * 根据host读取文件 - * @param appSerever, app.server + * Read file according to host + * @param appServer, app.server * @param filename, config file name * @param host, ip - * @param config, 配置文件内容 + * @param config, Configuration file content **/ int loadConfigByHost(string appServerName, string filename, string host, out string config); /** - * 检查配置文件是否服务TC_Config格式 - * @param appSerever, app.server + * Check whether the configuration file conforms to the TC_Config format + * @param appServer, app.server * @param filename, config file name * @param host, ip - * @param result, 提示 - * @return int 0: 合法, -1:非法 + * @param result, prompt + * @return int 0: valid, -1:invalid **/ int checkConfig(string appServerName, string filename, string host, out string result); - /** - * 读取服务所在节点的配置文件列表 - * - * @param configInfo, ConfigInfo 配置文件信息,如果没有set分组信息,请设置setdivision为空"" - * @param vf, config file name - * @return int 0: 成功, -1:失败 - **/ - int ListConfigByInfo(ConfigInfo configInfo, out vector vf); + /** + * Read the configuration file list of the node where the service is located + * + * @param configInfo, ConfigInfo: Profile information. If there is no set group information, please set setdivision is empty "" + * @param vf, config file name + * @return int 0: success, -1:failure + **/ + int ListConfigByInfo(ConfigInfo configInfo, out vector vf); - /** - * 读取配置文件 - * @param configInfo, ConfigInfo 配置文件信息 - * @param config, 配置文件内容 - * @return int 0: 成功, -1:失败 - **/ - int loadConfigByInfo(ConfigInfo configInfo, out string config); + /** + * Read configuration file + * @param configInfo, ConfigInfo: Profile information + * @param config, Configuration file content + * @return int 0: success, -1:failure + **/ + int loadConfigByInfo(ConfigInfo configInfo, out string config); - /** - * 检查配置文件是否符合TC_Config格式 - * @param configInfo, ConfigInfo 配置文件信息 - * @param result, 提示 - * @return int 0: 合法, -1:非法 - **/ - int checkConfigByInfo(ConfigInfo configInfo, out string result); + /** + * Check whether the configuration file conforms to the TC_Config format + * @param configInfo, ConfigInfo: Profile information + * @param result, prompt + * @return int 0: valid, -1:invalid + **/ + int checkConfigByInfo(ConfigInfo configInfo, out string result); }; }; diff --git a/core/src/main/resources/EndpointF.tars b/core/src/main/resources/EndpointF.tars index a8e8c63a..f2685159 100644 --- a/core/src/main/resources/EndpointF.tars +++ b/core/src/main/resources/EndpointF.tars @@ -17,22 +17,22 @@ module tars { /** - * 端口信息 + * Port information */ struct EndpointF { - 0 require string host; - 1 require int port; - 2 require int timeout; - 3 require int istcp; - 4 require int grid; - 5 optional int groupworkid; - 6 optional int grouprealid; - 7 optional string setId; - 8 optional int qos; - 9 optional int bakFlag; - 11 optional int weight; - 12 optional int weightType; + 0 require string host; + 1 require int port; + 2 require int timeout; + 3 require int istcp; + 4 require int grid; + 5 optional int groupworkid; + 6 optional int grouprealid; + 7 optional string setId; + 8 optional int qos; + 9 optional int bakFlag; + 11 optional int weight; + 12 optional int weightType; }; key[EndpointF, host, port, timeout, istcp, grid, qos, weight, weightType]; }; diff --git a/core/src/main/resources/LogF.tars b/core/src/main/resources/LogF.tars index 80b8c485..5b52001e 100644 --- a/core/src/main/resources/LogF.tars +++ b/core/src/main/resources/LogF.tars @@ -16,48 +16,48 @@ module tars { - struct LogInfo - { - //业务名称 - 0 require string appname; - //服务名称 - 1 require string servername; - //日志文件名称 - 2 require string sFilename; - //时间格式 - 3 require string sFormat; - //set分组名称 - 4 optional string setdivision; - // 日志文件名是否带.log后缀 - 5 optional bool bHasSufix=true; - // 是否允许框架在日志文件名上增加业务相关的标识 - 6 optional bool bHasAppNamePrefix=true; - // 框架内部的日期和时间部分是否加上[]符号 - 7 optional bool bHasSquareBracket=false; - // 日志文件名中用户自定义字符与日期字符间的连接符,默认是"_" - 8 optional string sConcatStr="_"; - // 日志内容项之间的分隔符,默认是"|" - 9 optional string sSepar="|"; - //按天/小时/分钟输出日志时的记录类型,例如,按一天:day或者1day;按两小时:2hour;按10分钟:10minute - 10 optional string sLogType = ""; - }; + struct LogInfo + { + //Application name + 0 require string appname; + //Service name + 1 require string servername; + //Log file name + 2 require string sFilename; + //Time format + 3 require string sFormat; + //Set group name + 4 optional string setdivision; + // Whether the log file name has a .log suffix + 5 optional bool bHasSufix = true; + // Whether to allow the framework to add business-related identifiers to log file names + 6 optional bool bHasAppNamePrefix = true; + // Whether the [] symbol added to the date and time part of the framework + 7 optional bool bHasSquareBracket = false; + // The connector between the user-defined character and the date character in the log file name, the default is "_" + 8 optional string sConcatStr = "_"; + // The separator between log content items, the default is "|" + 9 optional string sSepar = "|"; + // Record type when outputting logs by day / hour / minute, for example, by one day: day or 1day; by two hours: 2hour; by 10 minutes: 10minute + 10 optional string sLogType = ""; + }; interface Log { /** - * 记录远程日志 - * @param app, 应用名称 - * @param server, 服务名称 - * @param file, 文件名称 - * @param format, 日志时间格式(%Y%m%d) - * @param buffer, 日志内容 - */ - void logger(string app, string server, string file, string format, vector buffer); + * Record remote logs + * @param app, Application Name + * @param server, Service name + * @param file, File name + * @param format, Log time format(%Y%m%d) + * @param buffer, Log content + */ + void loggerInnerImpl(string app, string server, string file, string format, vector buffer); - /** - * 记录远程日志 - * @param info, LogInfo - * @param buffer, 日志内容 - */ + /** + * Record remote logs + * @param info, LogInfo + * @param buffer, Log content + */ void loggerbyInfo(LogInfo info, vector buffer); }; }; diff --git a/core/src/main/resources/META-INF/services/com.qq.tars.support.trace.spi.TraceInitializer b/core/src/main/resources/META-INF/services/com.qq.tars.support.trace.spi.TraceInitializer new file mode 100644 index 00000000..4a5d5d23 --- /dev/null +++ b/core/src/main/resources/META-INF/services/com.qq.tars.support.trace.spi.TraceInitializer @@ -0,0 +1,2 @@ +com.qq.tars.support.trace.spi.SkywalkingTraceInitializer +com.qq.tars.support.trace.spi.ZipkinTraceInitializer diff --git a/core/src/main/resources/QueryF.tars b/core/src/main/resources/QueryF.tars index 5011a6de..4cee9d59 100644 --- a/core/src/main/resources/QueryF.tars +++ b/core/src/main/resources/QueryF.tars @@ -18,66 +18,66 @@ module tars { - /** - * 获取对象endpoint的query接口 + /** + * Get the query interface of the object endpoint */ interface QueryF { - /** 根据id获取对象 + /** Get object by id * - * @param id 对象名称 + * @param id Object name * - * @return 返回所有该对象的活动endpoint列表 + * @return Returns a list of all active endpoints for this object */ vector findObjectById(string id); - - /**根据id获取所有对象,包括活动和非活动对象 - * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 + + /**Get all objects by id, including active and inactive objects + * + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure */ - int findObjectById4Any(string id, out vector activeEp, out vector inactiveEp); + int findObjectById4Any(string id, out vector activeEp, out vector inactiveEp); - /** 根据id获取对象所有endpoint列表,功能同findObjectByIdInSameGroup + /** Get all endpoint lists of objects according to id, the function is the same as findObjectByIdInSameGroup * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure */ int findObjectById4All(string id, out vector activeEp, out vector inactiveEp); - - /** 根据id获取对象同组endpoint列表 + + /** Get the same group endpoint list of objects according to id * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure */ int findObjectByIdInSameGroup(string id, out vector activeEp, out vector inactiveEp); - /** 根据id获取对象指定归属地的endpoint列表 + /** Get the endpoint list of the specified home location of the object according to id * - * @param id 对象名称 - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure */ int findObjectByIdInSameStation(string id, string sStation, out vector activeEp, out vector inactiveEp); - - /** 根据id获取对象同组endpoint列表 - * - * @param id 对象名称 - * @param setId set全称,格式为setname.setarea.setgroup - * @param activeEp 存活endpoint列表 - * @param inactiveEp 非存活endpoint列表 - * @return: 0-成功 others-失败 - */ - int findObjectByIdInSameSet(string id, string setId, out vector activeEp, out vector inactiveEp); + + /** Get the same group endpoint list of objects according to id + * + * @param id Object name + * @param setId The full name of set, the format is setname.setarea.setgroup + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure + */ + int findObjectByIdInSameSet(string id, string setId, out vector activeEp, out vector inactiveEp); }; diff --git a/core/src/main/resources/StatF.tars b/core/src/main/resources/StatF.tars index 87df2129..0b2298b9 100644 --- a/core/src/main/resources/StatF.tars +++ b/core/src/main/resources/StatF.tars @@ -17,76 +17,76 @@ module tars { -//模块间调用包头 Mic = module interval call -struct StatMicMsgHead -{ - 0 require string masterName; //主调模块name - 1 require string slaveName; //被调模块name - 2 require string interfaceName; //被调模块接口name - 3 require string masterIp; //主调ip - 4 require string slaveIp; //被调ip - 5 require int slavePort; //被调端口 - 6 require int returnValue; //返回值 - 7 optional string slaveSetName; //被调set名 - 8 optional string slaveSetArea; //被调set地区名 - 9 optional string slaveSetID; //被调set组名 - 10 optional string tarsVersion; //主调tars版本 -}; + //Calling package headers between modules Mic = module interval call + struct StatMicMsgHead + { + 0 require string masterName; //Main calling module name + 1 require string slaveName; //The name of the called module + 2 require string interfaceName; //The interface name of the called module + 3 require string masterIp; //Main calling module ip + 4 require string slaveIp; //The ip of the called module + 5 require int slavePort; //The port of the called module + 6 require int returnValue; //return value + 7 optional string slaveSetName; //The set name of the called module + 8 optional string slaveSetArea; //The set area name of the called module + 9 optional string slaveSetID; //The set group name of the called module + 10 optional string tarsVersion; //Main calling module tars version + }; -key[StatMicMsgHead, masterName, slaveName,interfaceName,masterIp,slaveIp,slavePort,returnValue, slaveSetName, slaveSetArea, slaveSetID, tarsVersion]; - -//模块间调用包体协议 -struct StatMicMsgBody -{ - 0 require int count; //成功调用量 - 1 require int timeoutCount; //超时调用量 - 2 require int execCount; //异常调用量 - //以下字段针对成功调用量所作统计 - 3 require map intervalCount; //时间间隔内调用量 - 4 require long totalRspTime; //调用总时间用来计算平均时间 - 5 require int maxRspTime; //最大响应时间 - 6 require int minRspTime; //最小响应时间 -}; + key[StatMicMsgHead, masterName, slaveName, interfaceName, masterIp, slaveIp, slavePort, returnValue, slaveSetName, slaveSetArea, slaveSetID, tarsVersion]; -//模块间调用采样信息 -struct StatSampleMsg -{ - 0 require string unid; //唯一id值 - 1 require string masterName; //主调模块name - 2 require string slaveName; //被调模块name - 3 require string interfaceName; //被调模块接口name - 4 require string masterIp; //主调ip - 5 require string slaveIp; //被调ip - 6 require int depth; //深度值 - 7 require int width; //广度值 - 8 require int parentWidth; //父节点广度值 -}; + //Inter module call package body protocol + struct StatMicMsgBody + { + 0 require int count; //Successful call count + 1 require int timeoutCount; //Timeout call count + 2 require int execCount; //Exception call count + //The following fields are used for statistics for successful calls + 3 require map intervalCount; //Call count in time interval + 4 require long totalRspTime; //The total response time is used to calculate the average time + 5 require int maxRspTime; //Maximum response time + 6 require int minRspTime; //Minimum response time + }; -struct ProxyInfo -{ - 0 require bool bFromClient;//是否来自客户端 -}; -/** - * - * 上报服务的接口 - * - **/ -interface StatF -{ - /** - * 上报模块间调用信息 Mic = module interval call - * @param statmsg, 上报信息 - * @param bFromServer, 上报源 bFromClient: true 客户端发起的上报 false 服务端发起上报 - * @return int, 返回0表示成功 - */ - int reportMicMsg( map msg, bool bFromClient); - - /** - * 上报模块间调用采样信息 Mic = module interval call - * @param msg, 上报信息 - * @return int, 返回0表示成功 - */ - int reportSampleMsg(vector msg); -}; + //Call sampling information between modules + struct StatSampleMsg + { + 0 require string unid; //Unique id value + 1 require string masterName; //Main calling module name + 2 require string slaveName; //The name of the called module + 3 require string interfaceName; //The interface name of the called module + 4 require string masterIp; //Main calling module ip + 5 require string slaveIp; //The ip of the called module + 6 require int depth; //Depth value + 7 require int width; //Breadth value + 8 require int parentWidth; //Parent node breadth value + }; + + struct ProxyInfo + { + 0 require bool bFromClient; //Whether from the client + }; + /** + * + * Interface to the report service + * + **/ + interface StatF + { + /** + * Report calling information between modules Mic = module interval call + * @param statmsg, Report information + * @param bFromServer, Report source bFromClient: true (Reporting initiated by the client) false (Reporting initiated by the server) + * @return int, Return 0 means success + */ + int reportMicMsg(map msg, bool bFromClient); + + /** + * Report sampling information between modules Mic = module interval call + * @param msg, Report information + * @return int, Return 0 means success + */ + int reportSampleMsg(vector msg); + }; }; diff --git a/core/src/test/java/com/qq/tars/Condition.java b/core/src/test/java/com/qq/tars/Condition.java new file mode 100644 index 00000000..204f25cc --- /dev/null +++ b/core/src/test/java/com/qq/tars/Condition.java @@ -0,0 +1,122 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars; + +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; + +@TarsStruct +public class Condition { + + @TarsStructProperty(order = 0, isRequire = true) + public String field = ""; + @TarsStructProperty(order = 1, isRequire = true) + public int op = 0; + @TarsStructProperty(order = 2, isRequire = true) + public String val = ""; + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } + + public int getOp() { + return op; + } + + public void setOp(int op) { + this.op = op; + } + + public String getVal() { + return val; + } + + public void setVal(String val) { + this.val = val; + } + + public Condition() { + } + + public Condition(String field, int op, String val) { + this.field = field; + this.op = op; + this.val = val; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + TarsUtil.hashCode(field); + result = prime * result + TarsUtil.hashCode(op); + result = prime * result + TarsUtil.hashCode(val); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof Condition)) { + return false; + } + Condition other = (Condition) obj; + return ( + TarsUtil.equals(field, other.field) && + TarsUtil.equals(op, other.op) && + TarsUtil.equals(val, other.val) + ); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("Condition("); + sb.append("field:"); + if (this.field == null) { + sb.append("null"); + } else { + sb.append(this.field); + } + sb.append(", "); + sb.append("op:"); + sb.append(this.op); + sb.append(", "); + sb.append("val:"); + if (this.val == null) { + sb.append("null"); + } else { + sb.append(this.val); + } + sb.append(")"); + return sb.toString(); + } + + public void writeTo(TarsOutputStream _os) { + _os.write(field, 0); + _os.write(op, 1); + _os.write(val, 2); + } + + + public void readFrom(TarsInputStream _is) { + this.field = _is.readString(0, true); + this.op = _is.read(op, 1, true); + this.val = _is.readString(2, true); + } + +} diff --git a/core/src/test/java/com/qq/tars/DateType.java b/core/src/test/java/com/qq/tars/DateType.java new file mode 100644 index 00000000..c2ff75fd --- /dev/null +++ b/core/src/test/java/com/qq/tars/DateType.java @@ -0,0 +1,40 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars; + +public enum DateType { + + SECONDS(0), + MINIUES(1), + HOUR(2), + DAY(3), + MONTH(4), + YEAR(5); + + private final int value; + + private DateType(int value) { + this.value = value; + } + + public int value() { + return this.value; + } + + @Override + public String toString() { + return this.name() + ":" + this.value; + } + + public static DateType convert(int value) { + for(DateType v : values()) { + if(v.value() == value) { + return v; + } + } + return null; + } +} diff --git a/core/src/test/java/com/qq/tars/DecoderTest.java b/core/src/test/java/com/qq/tars/DecoderTest.java new file mode 100644 index 00000000..8c259aad --- /dev/null +++ b/core/src/test/java/com/qq/tars/DecoderTest.java @@ -0,0 +1,32 @@ +package com.qq.tars; + +import com.google.common.collect.ImmutableList; +import com.qq.tars.protocol.tars.TarsOutputStream; +import org.junit.Test; + +public class DecoderTest { + + + @Test + public void testForDecoder() { + + MonitorQueryReq request = new MonitorQueryReq(); + request.dateType = DateType.MINIUES.value(); + request.method = "query"; + request.setDataid("tars_stat"); + request.intervalTime = 1; + request.setConditions(ImmutableList.of(new Condition("slave_name", 5, "tars.tarsstat"))); + request.indexs = ImmutableList.of("succ_count", "timeout_count", "exce_count", "total_time"); + request.setGroupby(ImmutableList.of("f_tflag")); + request.startTime = 1606060800L; + request.endTime = 1606147199L; + + + TarsOutputStream tarsOutputStream = new TarsOutputStream(); + request.writeTo(tarsOutputStream); + + + byte[] bytesArray = tarsOutputStream.toByteArray(); + + } +} diff --git a/core/src/test/java/com/qq/tars/MonitorQueryPrx.java b/core/src/test/java/com/qq/tars/MonitorQueryPrx.java new file mode 100644 index 00000000..88ffff32 --- /dev/null +++ b/core/src/test/java/com/qq/tars/MonitorQueryPrx.java @@ -0,0 +1,21 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars; + +import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsHolder; +import com.qq.tars.protocol.tars.annotation.TarsMethodParameter; + +import java.util.concurrent.CompletableFuture; + +@Servant +public interface MonitorQueryPrx { + int query(@TarsMethodParameter(name = "req") MonitorQueryReq req, @TarsHolder(name = "rsp") Holder rsp); + + CompletableFuture promise_query(@TarsMethodParameter(name = "req") MonitorQueryReq req, @TarsHolder(name = "rsp") Holder rsp); + +} diff --git a/core/src/test/java/com/qq/tars/MonitorQueryReq.java b/core/src/test/java/com/qq/tars/MonitorQueryReq.java new file mode 100644 index 00000000..12df4bfb --- /dev/null +++ b/core/src/test/java/com/qq/tars/MonitorQueryReq.java @@ -0,0 +1,348 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars; + +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; + +@TarsStruct +public class MonitorQueryReq { + + @TarsStructProperty(order = 0, isRequire = true) + public String uid = ""; + @TarsStructProperty(order = 1, isRequire = true) + public String method = "query"; + @TarsStructProperty(order = 2, isRequire = true) + public String dataid = ""; + @TarsStructProperty(order = 3, isRequire = true) + public String date = ""; + @TarsStructProperty(order = 4, isRequire = true) + public String tflag1 = ""; + @TarsStructProperty(order = 5, isRequire = true) + public String tflag2 = ""; + @TarsStructProperty(order = 6, isRequire = true) + public java.util.List conditions = null; + @TarsStructProperty(order = 7, isRequire = true) + public java.util.List indexs = null; + @TarsStructProperty(order = 8, isRequire = true) + public java.util.List groupby = null; + @TarsStructProperty(order = 9, isRequire = false) + public int intervalTime = 5; + @TarsStructProperty(order = 10, isRequire = false) + public int dateType = 0; + @TarsStructProperty(order = 11, isRequire = false) + public long startTime = 0L; + @TarsStructProperty(order = 12, isRequire = false) + public long endTime = 0L; + + public String getUid() { + return uid; + } + + public void setUid(String uid) { + this.uid = uid; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public String getDataid() { + return dataid; + } + + public void setDataid(String dataid) { + this.dataid = dataid; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public String getTflag1() { + return tflag1; + } + + public void setTflag1(String tflag1) { + this.tflag1 = tflag1; + } + + public String getTflag2() { + return tflag2; + } + + public void setTflag2(String tflag2) { + this.tflag2 = tflag2; + } + + public java.util.List getConditions() { + return conditions; + } + + public void setConditions(java.util.List conditions) { + this.conditions = conditions; + } + + public java.util.List getIndexs() { + return indexs; + } + + public void setIndexs(java.util.List indexs) { + this.indexs = indexs; + } + + public java.util.List getGroupby() { + return groupby; + } + + public void setGroupby(java.util.List groupby) { + this.groupby = groupby; + } + + public int getIntervalTime() { + return intervalTime; + } + + public void setIntervalTime(int intervalTime) { + this.intervalTime = intervalTime; + } + + public int getDateType() { + return dateType; + } + + public void setDateType(int dateType) { + this.dateType = dateType; + } + + public long getStartTime() { + return startTime; + } + + public void setStartTime(long startTime) { + this.startTime = startTime; + } + + public long getEndTime() { + return endTime; + } + + public void setEndTime(long endTime) { + this.endTime = endTime; + } + + public MonitorQueryReq() { + } + + public MonitorQueryReq(String uid, String method, String dataid, String date, String tflag1, String tflag2, java.util.List conditions, java.util.List indexs, java.util.List groupby, int intervalTime, int dateType, long startTime, long endTime) { + this.uid = uid; + this.method = method; + this.dataid = dataid; + this.date = date; + this.tflag1 = tflag1; + this.tflag2 = tflag2; + this.conditions = conditions; + this.indexs = indexs; + this.groupby = groupby; + this.intervalTime = intervalTime; + this.dateType = dateType; + this.startTime = startTime; + this.endTime = endTime; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + TarsUtil.hashCode(uid); + result = prime * result + TarsUtil.hashCode(method); + result = prime * result + TarsUtil.hashCode(dataid); + result = prime * result + TarsUtil.hashCode(date); + result = prime * result + TarsUtil.hashCode(tflag1); + result = prime * result + TarsUtil.hashCode(tflag2); + result = prime * result + TarsUtil.hashCode(conditions); + result = prime * result + TarsUtil.hashCode(indexs); + result = prime * result + TarsUtil.hashCode(groupby); + result = prime * result + TarsUtil.hashCode(intervalTime); + result = prime * result + TarsUtil.hashCode(dateType); + result = prime * result + TarsUtil.hashCode(startTime); + result = prime * result + TarsUtil.hashCode(endTime); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof MonitorQueryReq)) { + return false; + } + MonitorQueryReq other = (MonitorQueryReq) obj; + return ( + TarsUtil.equals(uid, other.uid) && + TarsUtil.equals(method, other.method) && + TarsUtil.equals(dataid, other.dataid) && + TarsUtil.equals(date, other.date) && + TarsUtil.equals(tflag1, other.tflag1) && + TarsUtil.equals(tflag2, other.tflag2) && + TarsUtil.equals(conditions, other.conditions) && + TarsUtil.equals(indexs, other.indexs) && + TarsUtil.equals(groupby, other.groupby) && + TarsUtil.equals(intervalTime, other.intervalTime) && + TarsUtil.equals(dateType, other.dateType) && + TarsUtil.equals(startTime, other.startTime) && + TarsUtil.equals(endTime, other.endTime) + ); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("MonitorQueryReq("); + sb.append("uid:"); + if (this.uid == null) { + sb.append("null"); + } else { + sb.append(this.uid); + } + sb.append(", "); + sb.append("method:"); + if (this.method == null) { + sb.append("null"); + } else { + sb.append(this.method); + } + sb.append(", "); + sb.append("dataid:"); + if (this.dataid == null) { + sb.append("null"); + } else { + sb.append(this.dataid); + } + sb.append(", "); + sb.append("date:"); + if (this.date == null) { + sb.append("null"); + } else { + sb.append(this.date); + } + sb.append(", "); + sb.append("tflag1:"); + if (this.tflag1 == null) { + sb.append("null"); + } else { + sb.append(this.tflag1); + } + sb.append(", "); + sb.append("tflag2:"); + if (this.tflag2 == null) { + sb.append("null"); + } else { + sb.append(this.tflag2); + } + sb.append(", "); + sb.append("conditions:"); + if (this.conditions == null) { + sb.append("null"); + } else { + sb.append(this.conditions); + } + sb.append(", "); + sb.append("indexs:"); + if (this.indexs == null) { + sb.append("null"); + } else { + sb.append(this.indexs); + } + sb.append(", "); + sb.append("groupby:"); + if (this.groupby == null) { + sb.append("null"); + } else { + sb.append(this.groupby); + } + sb.append(", "); + sb.append("intervalTime:"); + sb.append(this.intervalTime); + sb.append(", "); + sb.append("dateType:"); + sb.append(this.dateType); + sb.append(", "); + sb.append("startTime:"); + sb.append(this.startTime); + sb.append(", "); + sb.append("endTime:"); + sb.append(this.endTime); + sb.append(")"); + return sb.toString(); + } + + public void writeTo(TarsOutputStream _os) { + _os.write(uid, 0); + _os.write(method, 1); + _os.write(dataid, 2); + _os.write(date, 3); + _os.write(tflag1, 4); + _os.write(tflag2, 5); + _os.write(conditions, 6); + _os.write(indexs, 7); + _os.write(groupby, 8); + _os.write(intervalTime, 9); + _os.write(dateType, 10); + _os.write(startTime, 11); + _os.write(endTime, 12); + } + + static java.util.List cache_conditions; + static { + cache_conditions = new java.util.ArrayList(); + Condition var_1 = new Condition(); + cache_conditions.add(var_1); + } + static java.util.List cache_indexs; + static { + cache_indexs = new java.util.ArrayList(); + String var_2 = ""; + cache_indexs.add(var_2); + } + static java.util.List cache_groupby; + static { + cache_groupby = new java.util.ArrayList(); + String var_3 = ""; + cache_groupby.add(var_3); + } + + public void readFrom(TarsInputStream _is) { + this.uid = _is.readString(0, true); + this.method = _is.readString(1, true); + this.dataid = _is.readString(2, true); + this.date = _is.readString(3, true); + this.tflag1 = _is.readString(4, true); + this.tflag2 = _is.readString(5, true); + this.conditions = (java.util.List) _is.read(cache_conditions, 6, true); + this.indexs = (java.util.List) _is.read(cache_indexs, 7, true); + this.groupby = (java.util.List) _is.read(cache_groupby, 8, true); + this.intervalTime = _is.read(intervalTime, 9, false); + this.dateType = _is.read(dateType, 10, false); + this.startTime = _is.read(startTime, 11, false); + this.endTime = _is.read(endTime, 12, false); + } + +} diff --git a/core/src/test/java/com/qq/tars/MonitorQueryRsp.java b/core/src/test/java/com/qq/tars/MonitorQueryRsp.java new file mode 100644 index 00000000..d7447207 --- /dev/null +++ b/core/src/test/java/com/qq/tars/MonitorQueryRsp.java @@ -0,0 +1,257 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars; + +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; + +@TarsStruct +public class MonitorQueryRsp { + + @TarsStructProperty(order = 0, isRequire = true) + public int ret = 0; + @TarsStructProperty(order = 1, isRequire = false) + public String msg = ""; + @TarsStructProperty(order = 2, isRequire = true) + public String lastTime = ""; + @TarsStructProperty(order = 3, isRequire = true) + public int activeDb = 0; + @TarsStructProperty(order = 4, isRequire = true) + public int totalDb = 0; + @TarsStructProperty(order = 5, isRequire = true) + public java.util.List retThreads = null; + @TarsStructProperty(order = 6, isRequire = false) + public java.util.Map> result = null; + @TarsStructProperty(order = 7, isRequire = false) + public int intervalTime = 5; + @TarsStructProperty(order = 8, isRequire = false) + public int dateType = 0; + + public int getRet() { + return ret; + } + + public void setRet(int ret) { + this.ret = ret; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public String getLastTime() { + return lastTime; + } + + public void setLastTime(String lastTime) { + this.lastTime = lastTime; + } + + public int getActiveDb() { + return activeDb; + } + + public void setActiveDb(int activeDb) { + this.activeDb = activeDb; + } + + public int getTotalDb() { + return totalDb; + } + + public void setTotalDb(int totalDb) { + this.totalDb = totalDb; + } + + public java.util.List getRetThreads() { + return retThreads; + } + + public void setRetThreads(java.util.List retThreads) { + this.retThreads = retThreads; + } + + public java.util.Map> getResult() { + return result; + } + + public void setResult(java.util.Map> result) { + this.result = result; + } + + public int getIntervalTime() { + return intervalTime; + } + + public void setIntervalTime(int intervalTime) { + this.intervalTime = intervalTime; + } + + public int getDateType() { + return dateType; + } + + public void setDateType(int dateType) { + this.dateType = dateType; + } + + public MonitorQueryRsp() { + } + + public MonitorQueryRsp(int ret, String msg, String lastTime, int activeDb, int totalDb, java.util.List retThreads, java.util.Map> result, int intervalTime, int dateType) { + this.ret = ret; + this.msg = msg; + this.lastTime = lastTime; + this.activeDb = activeDb; + this.totalDb = totalDb; + this.retThreads = retThreads; + this.result = result; + this.intervalTime = intervalTime; + this.dateType = dateType; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + TarsUtil.hashCode(ret); + result = prime * result + TarsUtil.hashCode(msg); + result = prime * result + TarsUtil.hashCode(lastTime); + result = prime * result + TarsUtil.hashCode(activeDb); + result = prime * result + TarsUtil.hashCode(totalDb); + result = prime * result + TarsUtil.hashCode(retThreads); + result = prime * result + TarsUtil.hashCode(result); + result = prime * result + TarsUtil.hashCode(intervalTime); + result = prime * result + TarsUtil.hashCode(dateType); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof MonitorQueryRsp)) { + return false; + } + MonitorQueryRsp other = (MonitorQueryRsp) obj; + return ( + TarsUtil.equals(ret, other.ret) && + TarsUtil.equals(msg, other.msg) && + TarsUtil.equals(lastTime, other.lastTime) && + TarsUtil.equals(activeDb, other.activeDb) && + TarsUtil.equals(totalDb, other.totalDb) && + TarsUtil.equals(retThreads, other.retThreads) && + TarsUtil.equals(result, other.result) && + TarsUtil.equals(intervalTime, other.intervalTime) && + TarsUtil.equals(dateType, other.dateType) + ); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("MonitorQueryRsp("); + sb.append("ret:"); + sb.append(this.ret); + sb.append(", "); + sb.append("msg:"); + if (this.msg == null) { + sb.append("null"); + } else { + sb.append(this.msg); + } + sb.append(", "); + sb.append("lastTime:"); + if (this.lastTime == null) { + sb.append("null"); + } else { + sb.append(this.lastTime); + } + sb.append(", "); + sb.append("activeDb:"); + sb.append(this.activeDb); + sb.append(", "); + sb.append("totalDb:"); + sb.append(this.totalDb); + sb.append(", "); + sb.append("retThreads:"); + if (this.retThreads == null) { + sb.append("null"); + } else { + sb.append(this.retThreads); + } + sb.append(", "); + sb.append("result:"); + if (this.result == null) { + sb.append("null"); + } else { + sb.append(this.result); + } + sb.append(", "); + sb.append("intervalTime:"); + sb.append(this.intervalTime); + sb.append(", "); + sb.append("dateType:"); + sb.append(this.dateType); + sb.append(")"); + return sb.toString(); + } + + public void writeTo(TarsOutputStream _os) { + _os.write(ret, 0); + if (null != msg) { + _os.write(msg, 1); + } + _os.write(lastTime, 2); + _os.write(activeDb, 3); + _os.write(totalDb, 4); + _os.write(retThreads, 5); + if (null != result) { + _os.write(result, 6); + } + _os.write(intervalTime, 7); + _os.write(dateType, 8); + } + + static java.util.List cache_retThreads; + static { + cache_retThreads = new java.util.ArrayList(); + int var_4 = 0; + cache_retThreads.add(var_4); + } + static java.util.Map> cache_result; + static { + cache_result = new java.util.HashMap>(); + String var_5 = ""; + java.util.List var_6 = new java.util.ArrayList(); + double var_7 = 0D; + var_6.add(var_7); + cache_result.put(var_5 ,var_6); + } + + public void readFrom(TarsInputStream _is) { + this.ret = _is.read(ret, 0, true); + this.msg = _is.readString(1, false); + this.lastTime = _is.readString(2, true); + this.activeDb = _is.read(activeDb, 3, true); + this.totalDb = _is.read(totalDb, 4, true); + this.retThreads = (java.util.List) _is.read(cache_retThreads, 5, true); + this.result = (java.util.Map>) _is.read(cache_result, 6, false); + this.intervalTime = _is.read(intervalTime, 7, false); + this.dateType = _is.read(dateType, 8, false); + } + +} diff --git a/core/src/test/java/com/qq/tars/MonitorQueryServant.java b/core/src/test/java/com/qq/tars/MonitorQueryServant.java new file mode 100644 index 00000000..a3ebae40 --- /dev/null +++ b/core/src/test/java/com/qq/tars/MonitorQueryServant.java @@ -0,0 +1,17 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars; + +import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsHolder; +import com.qq.tars.protocol.tars.annotation.TarsMethodParameter; + +@Servant +public interface MonitorQueryServant { + + int query(@TarsMethodParameter(name="req") MonitorQueryReq req, @TarsHolder(name="rsp") Holder rsp); +} diff --git a/core/src/test/java/com/qq/tars/TestForGenericType.java b/core/src/test/java/com/qq/tars/TestForGenericType.java new file mode 100644 index 00000000..3ca1c021 --- /dev/null +++ b/core/src/test/java/com/qq/tars/TestForGenericType.java @@ -0,0 +1,37 @@ +package com.qq.tars; + +import junit.framework.Assert; +import org.junit.Test; +import java.lang.reflect.ParameterizedType; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +public class TestForGenericType { + public static class TestsMethod { + public CompletableFuture> getFuture() { + return new CompletableFuture<>(); + } + } + + @Test + public void testGenerictype() throws InvocationTargetException, IllegalAccessException, InstantiationException { + CompletableFuture completableFuture = new CompletableFuture<>(); + Method[] methods = TestsMethod.class.getMethods(); + Method method = methods[0]; + Type type = method.getGenericReturnType(); + Type type2 = method.getReturnType(); + Assert.assertEquals(type2, CompletableFuture.class); + ParameterizedType parameterizedType = (ParameterizedType) method.getGenericReturnType(); + Assert.assertEquals(parameterizedType.getActualTypeArguments()[0].getTypeName(), + "java.util.List"); + System.out.println(parameterizedType.getActualTypeArguments()[0].getTypeName()); + System.out.println("get inner type is " + parameterizedType.getActualTypeArguments()[0]); + System.out.println("return type is " + method.getGenericReturnType()); + System.out.println(methods[0].invoke(TestsMethod.class.newInstance())); + System.out.println(completableFuture.getClass().getName()); + } +} diff --git a/core/src/test/java/com/qq/tars/TestForTarsOutputStream.java b/core/src/test/java/com/qq/tars/TestForTarsOutputStream.java new file mode 100644 index 00000000..a6368006 --- /dev/null +++ b/core/src/test/java/com/qq/tars/TestForTarsOutputStream.java @@ -0,0 +1,21 @@ +package com.qq.tars; + +import com.qq.tars.common.util.HexUtil; +import com.qq.tars.protocol.tars.TarsOutputStream; +import io.netty.buffer.ByteBuf; +import org.junit.Test; + +import java.util.Arrays; + +public class TestForTarsOutputStream { + @Test + public void maxcapcity() { + TarsOutputStream os = new TarsOutputStream(); + long n = 0x1234567890012345L; + os.write(n, 0); + ByteBuf bs = os.getByteBuffer().duplicate(); + System.out.println(HexUtil.bytes2HexStr(bs.array())); + System.out.println(Arrays.toString(os.toByteArray())); + + } +} diff --git a/core/src/test/java/com/qq/tars/TestTarsRecursive.java b/core/src/test/java/com/qq/tars/TestTarsRecursive.java new file mode 100644 index 00000000..d8a57cf0 --- /dev/null +++ b/core/src/test/java/com/qq/tars/TestTarsRecursive.java @@ -0,0 +1,27 @@ +package com.qq.tars; + +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.quickstart.server.testapp.TestRecursive; +import org.junit.Test; +import java.util.ArrayList; +import java.util.List; + +public class TestTarsRecursive { + + @Test + public void testRecursiveReproduce() { + + TestRecursive testRecursive = new TestRecursive(); + testRecursive.value = 1; + TestRecursive testRecursive2 = new TestRecursive(); + testRecursive2.value =2; + testRecursive.testRecursive = testRecursive2; +// System.out.println(testRecursive.testRecursive.getValue()); + + TarsOutputStream tafOutputStream = new TarsOutputStream(); + System.out.println("begin to write."); + testRecursive.writeTo(tafOutputStream); + System.out.println("write end."); + + } +} diff --git a/core/src/test/java/com/qq/tars/client/rpc/TransporterAbstractFactoryTest.java b/core/src/test/java/com/qq/tars/client/rpc/TransporterAbstractFactoryTest.java new file mode 100644 index 00000000..8d551132 --- /dev/null +++ b/core/src/test/java/com/qq/tars/client/rpc/TransporterAbstractFactoryTest.java @@ -0,0 +1,20 @@ +package com.qq.tars.client.rpc; + +import com.qq.tars.rpc.netty.NettyTransporterFactory; +import org.junit.Assert; +import org.junit.Test; + +public class TransporterAbstractFactoryTest { + + @Test + public void testSingletonInstance() { + Assert.assertSame(TransporterAbstractFactory.getInstance(), TransporterAbstractFactory.getInstance()); + } + + @Test + public void testUseNettyTransporterFactory() { + TransporterFactory transporterFactory = TransporterAbstractFactory.getInstance().getTransporterFactory(); + Assert.assertNotNull(transporterFactory); + Assert.assertEquals(NettyTransporterFactory.class, transporterFactory.getClass()); + } +} diff --git a/core/src/test/java/com/qq/tars/netty/Condition.java b/core/src/test/java/com/qq/tars/netty/Condition.java new file mode 100644 index 00000000..107938d4 --- /dev/null +++ b/core/src/test/java/com/qq/tars/netty/Condition.java @@ -0,0 +1,122 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars.netty; + +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; + +@TarsStruct +public class Condition { + + @TarsStructProperty(order = 0, isRequire = true) + public String field = ""; + @TarsStructProperty(order = 1, isRequire = true) + public int op = 0; + @TarsStructProperty(order = 2, isRequire = true) + public String val = ""; + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } + + public int getOp() { + return op; + } + + public void setOp(int op) { + this.op = op; + } + + public String getVal() { + return val; + } + + public void setVal(String val) { + this.val = val; + } + + public Condition() { + } + + public Condition(String field, int op, String val) { + this.field = field; + this.op = op; + this.val = val; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + TarsUtil.hashCode(field); + result = prime * result + TarsUtil.hashCode(op); + result = prime * result + TarsUtil.hashCode(val); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof Condition)) { + return false; + } + Condition other = (Condition) obj; + return ( + TarsUtil.equals(field, other.field) && + TarsUtil.equals(op, other.op) && + TarsUtil.equals(val, other.val) + ); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("Condition("); + sb.append("field:"); + if (this.field == null) { + sb.append("null"); + } else { + sb.append(this.field); + } + sb.append(", "); + sb.append("op:"); + sb.append(this.op); + sb.append(", "); + sb.append("val:"); + if (this.val == null) { + sb.append("null"); + } else { + sb.append(this.val); + } + sb.append(")"); + return sb.toString(); + } + + public void writeTo(TarsOutputStream _os) { + _os.write(field, 0); + _os.write(op, 1); + _os.write(val, 2); + } + + + public void readFrom(TarsInputStream _is) { + this.field = _is.readString(0, true); + this.op = _is.read(op, 1, true); + this.val = _is.readString(2, true); + } + +} diff --git a/core/src/test/java/com/qq/tars/netty/DateType.java b/core/src/test/java/com/qq/tars/netty/DateType.java new file mode 100644 index 00000000..18f27316 --- /dev/null +++ b/core/src/test/java/com/qq/tars/netty/DateType.java @@ -0,0 +1,40 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars.netty; + +public enum DateType { + + SECONDS(0), + MINIUES(1), + HOUR(2), + DAY(3), + MONTH(4), + YEAR(5); + + private final int value; + + private DateType(int value) { + this.value = value; + } + + public int value() { + return this.value; + } + + @Override + public String toString() { + return this.name() + ":" + this.value; + } + + public static DateType convert(int value) { + for(DateType v : values()) { + if(v.value() == value) { + return v; + } + } + return null; + } +} diff --git a/core/src/test/java/com/qq/tars/netty/MonitorQueryPrx.java b/core/src/test/java/com/qq/tars/netty/MonitorQueryPrx.java new file mode 100644 index 00000000..69909bbd --- /dev/null +++ b/core/src/test/java/com/qq/tars/netty/MonitorQueryPrx.java @@ -0,0 +1,21 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars.netty; + +import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsHolder; +import com.qq.tars.protocol.tars.annotation.TarsMethodParameter; + +import java.util.concurrent.CompletableFuture; + +@Servant +public interface MonitorQueryPrx { + int query(@TarsMethodParameter(name = "req") MonitorQueryReq req, @TarsHolder(name = "rsp") Holder rsp); + + CompletableFuture promise_query(@TarsMethodParameter(name = "req") MonitorQueryReq req, @TarsHolder(name = "rsp") Holder rsp); + +} diff --git a/core/src/test/java/com/qq/tars/netty/MonitorQueryReq.java b/core/src/test/java/com/qq/tars/netty/MonitorQueryReq.java new file mode 100644 index 00000000..86041afb --- /dev/null +++ b/core/src/test/java/com/qq/tars/netty/MonitorQueryReq.java @@ -0,0 +1,353 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars.netty; + +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; + +@TarsStruct +public class MonitorQueryReq { + + @TarsStructProperty(order = 0, isRequire = true) + public String uid = ""; + @TarsStructProperty(order = 1, isRequire = true) + public String method = "query"; + @TarsStructProperty(order = 2, isRequire = true) + public String dataid = ""; + @TarsStructProperty(order = 3, isRequire = true) + public String date = ""; + @TarsStructProperty(order = 4, isRequire = true) + public String tflag1 = ""; + @TarsStructProperty(order = 5, isRequire = true) + public String tflag2 = ""; + @TarsStructProperty(order = 6, isRequire = true) + public java.util.List conditions = null; + @TarsStructProperty(order = 7, isRequire = true) + public java.util.List indexs = null; + @TarsStructProperty(order = 8, isRequire = true) + public java.util.List groupby = null; + @TarsStructProperty(order = 9, isRequire = false) + public int intervalTime = 5; + @TarsStructProperty(order = 10, isRequire = false) + public int dateType = 0; + @TarsStructProperty(order = 11, isRequire = false) + public long startTime = 0L; + @TarsStructProperty(order = 12, isRequire = false) + public long endTime = 0L; + + public String getUid() { + return uid; + } + + public void setUid(String uid) { + this.uid = uid; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public String getDataid() { + return dataid; + } + + public void setDataid(String dataid) { + this.dataid = dataid; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public String getTflag1() { + return tflag1; + } + + public void setTflag1(String tflag1) { + this.tflag1 = tflag1; + } + + public String getTflag2() { + return tflag2; + } + + public void setTflag2(String tflag2) { + this.tflag2 = tflag2; + } + + public java.util.List getConditions() { + return conditions; + } + + public void setConditions(java.util.List conditions) { + this.conditions = conditions; + } + + public java.util.List getIndexs() { + return indexs; + } + + public void setIndexs(java.util.List indexs) { + this.indexs = indexs; + } + + public java.util.List getGroupby() { + return groupby; + } + + public void setGroupby(java.util.List groupby) { + this.groupby = groupby; + } + + public int getIntervalTime() { + return intervalTime; + } + + public void setIntervalTime(int intervalTime) { + this.intervalTime = intervalTime; + } + + public int getDateType() { + return dateType; + } + + public void setDateType(int dateType) { + this.dateType = dateType; + } + + public long getStartTime() { + return startTime; + } + + public void setStartTime(long startTime) { + this.startTime = startTime; + } + + public long getEndTime() { + return endTime; + } + + public void setEndTime(long endTime) { + this.endTime = endTime; + } + + public MonitorQueryReq() { + } + + public MonitorQueryReq(String uid, String method, String dataid, String date, String tflag1, String tflag2, java.util.List conditions, java.util.List indexs, java.util.List groupby, int intervalTime, int dateType, long startTime, long endTime) { + this.uid = uid; + this.method = method; + this.dataid = dataid; + this.date = date; + this.tflag1 = tflag1; + this.tflag2 = tflag2; + this.conditions = conditions; + this.indexs = indexs; + this.groupby = groupby; + this.intervalTime = intervalTime; + this.dateType = dateType; + this.startTime = startTime; + this.endTime = endTime; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + TarsUtil.hashCode(uid); + result = prime * result + TarsUtil.hashCode(method); + result = prime * result + TarsUtil.hashCode(dataid); + result = prime * result + TarsUtil.hashCode(date); + result = prime * result + TarsUtil.hashCode(tflag1); + result = prime * result + TarsUtil.hashCode(tflag2); + result = prime * result + TarsUtil.hashCode(conditions); + result = prime * result + TarsUtil.hashCode(indexs); + result = prime * result + TarsUtil.hashCode(groupby); + result = prime * result + TarsUtil.hashCode(intervalTime); + result = prime * result + TarsUtil.hashCode(dateType); + result = prime * result + TarsUtil.hashCode(startTime); + result = prime * result + TarsUtil.hashCode(endTime); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof MonitorQueryReq)) { + return false; + } + MonitorQueryReq other = (MonitorQueryReq) obj; + return ( + TarsUtil.equals(uid, other.uid) && + TarsUtil.equals(method, other.method) && + TarsUtil.equals(dataid, other.dataid) && + TarsUtil.equals(date, other.date) && + TarsUtil.equals(tflag1, other.tflag1) && + TarsUtil.equals(tflag2, other.tflag2) && + TarsUtil.equals(conditions, other.conditions) && + TarsUtil.equals(indexs, other.indexs) && + TarsUtil.equals(groupby, other.groupby) && + TarsUtil.equals(intervalTime, other.intervalTime) && + TarsUtil.equals(dateType, other.dateType) && + TarsUtil.equals(startTime, other.startTime) && + TarsUtil.equals(endTime, other.endTime) + ); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("MonitorQueryReq("); + sb.append("uid:"); + if (this.uid == null) { + sb.append("null"); + } else { + sb.append(this.uid); + } + sb.append(", "); + sb.append("method:"); + if (this.method == null) { + sb.append("null"); + } else { + sb.append(this.method); + } + sb.append(", "); + sb.append("dataid:"); + if (this.dataid == null) { + sb.append("null"); + } else { + sb.append(this.dataid); + } + sb.append(", "); + sb.append("date:"); + if (this.date == null) { + sb.append("null"); + } else { + sb.append(this.date); + } + sb.append(", "); + sb.append("tflag1:"); + if (this.tflag1 == null) { + sb.append("null"); + } else { + sb.append(this.tflag1); + } + sb.append(", "); + sb.append("tflag2:"); + if (this.tflag2 == null) { + sb.append("null"); + } else { + sb.append(this.tflag2); + } + sb.append(", "); + sb.append("conditions:"); + if (this.conditions == null) { + sb.append("null"); + } else { + sb.append(this.conditions); + } + sb.append(", "); + sb.append("indexs:"); + if (this.indexs == null) { + sb.append("null"); + } else { + sb.append(this.indexs); + } + sb.append(", "); + sb.append("groupby:"); + if (this.groupby == null) { + sb.append("null"); + } else { + sb.append(this.groupby); + } + sb.append(", "); + sb.append("intervalTime:"); + sb.append(this.intervalTime); + sb.append(", "); + sb.append("dateType:"); + sb.append(this.dateType); + sb.append(", "); + sb.append("startTime:"); + sb.append(this.startTime); + sb.append(", "); + sb.append("endTime:"); + sb.append(this.endTime); + sb.append(")"); + return sb.toString(); + } + + public void writeTo(TarsOutputStream _os) { + _os.write(uid, 0); + _os.write(method, 1); + _os.write(dataid, 2); + _os.write(date, 3); + _os.write(tflag1, 4); + _os.write(tflag2, 5); + _os.write(conditions, 6); + _os.write(indexs, 7); + _os.write(groupby, 8); + _os.write(intervalTime, 9); + _os.write(dateType, 10); + _os.write(startTime, 11); + _os.write(endTime, 12); + } + + static java.util.List cache_conditions; + + static { + cache_conditions = new java.util.ArrayList(); + Condition var_1 = new Condition(); + cache_conditions.add(var_1); + } + + static java.util.List cache_indexs; + + static { + cache_indexs = new java.util.ArrayList(); + String var_2 = ""; + cache_indexs.add(var_2); + } + + static java.util.List cache_groupby; + + static { + cache_groupby = new java.util.ArrayList(); + String var_3 = ""; + cache_groupby.add(var_3); + } + + public void readFrom(TarsInputStream _is) { + this.uid = _is.readString(0, true); + this.method = _is.readString(1, true); + this.dataid = _is.readString(2, true); + this.date = _is.readString(3, true); + this.tflag1 = _is.readString(4, true); + this.tflag2 = _is.readString(5, true); + this.conditions = (java.util.List) _is.read(cache_conditions, 6, true); + this.indexs = (java.util.List) _is.read(cache_indexs, 7, true); + this.groupby = (java.util.List) _is.read(cache_groupby, 8, true); + this.intervalTime = _is.read(intervalTime, 9, false); + this.dateType = _is.read(dateType, 10, false); + this.startTime = _is.read(startTime, 11, false); + this.endTime = _is.read(endTime, 12, false); + } + +} diff --git a/core/src/test/java/com/qq/tars/netty/MonitorQueryRsp.java b/core/src/test/java/com/qq/tars/netty/MonitorQueryRsp.java new file mode 100644 index 00000000..fd5b2d31 --- /dev/null +++ b/core/src/test/java/com/qq/tars/netty/MonitorQueryRsp.java @@ -0,0 +1,260 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars.netty; + +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; + +@TarsStruct +public class MonitorQueryRsp { + + @TarsStructProperty(order = 0, isRequire = true) + public int ret = 0; + @TarsStructProperty(order = 1, isRequire = false) + public String msg = ""; + @TarsStructProperty(order = 2, isRequire = true) + public String lastTime = ""; + @TarsStructProperty(order = 3, isRequire = true) + public int activeDb = 0; + @TarsStructProperty(order = 4, isRequire = true) + public int totalDb = 0; + @TarsStructProperty(order = 5, isRequire = true) + public java.util.List retThreads = null; + @TarsStructProperty(order = 6, isRequire = false) + public java.util.Map> result = null; + @TarsStructProperty(order = 7, isRequire = false) + public int intervalTime = 5; + @TarsStructProperty(order = 8, isRequire = false) + public int dateType = 0; + + public int getRet() { + return ret; + } + + public void setRet(int ret) { + this.ret = ret; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public String getLastTime() { + return lastTime; + } + + public void setLastTime(String lastTime) { + this.lastTime = lastTime; + } + + public int getActiveDb() { + return activeDb; + } + + public void setActiveDb(int activeDb) { + this.activeDb = activeDb; + } + + public int getTotalDb() { + return totalDb; + } + + public void setTotalDb(int totalDb) { + this.totalDb = totalDb; + } + + public java.util.List getRetThreads() { + return retThreads; + } + + public void setRetThreads(java.util.List retThreads) { + this.retThreads = retThreads; + } + + public java.util.Map> getResult() { + return result; + } + + public void setResult(java.util.Map> result) { + this.result = result; + } + + public int getIntervalTime() { + return intervalTime; + } + + public void setIntervalTime(int intervalTime) { + this.intervalTime = intervalTime; + } + + public int getDateType() { + return dateType; + } + + public void setDateType(int dateType) { + this.dateType = dateType; + } + + public MonitorQueryRsp() { + } + + public MonitorQueryRsp(int ret, String msg, String lastTime, int activeDb, int totalDb, java.util.List retThreads, java.util.Map> result, int intervalTime, int dateType) { + this.ret = ret; + this.msg = msg; + this.lastTime = lastTime; + this.activeDb = activeDb; + this.totalDb = totalDb; + this.retThreads = retThreads; + this.result = result; + this.intervalTime = intervalTime; + this.dateType = dateType; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + TarsUtil.hashCode(ret); + result = prime * result + TarsUtil.hashCode(msg); + result = prime * result + TarsUtil.hashCode(lastTime); + result = prime * result + TarsUtil.hashCode(activeDb); + result = prime * result + TarsUtil.hashCode(totalDb); + result = prime * result + TarsUtil.hashCode(retThreads); + result = prime * result + TarsUtil.hashCode(result); + result = prime * result + TarsUtil.hashCode(intervalTime); + result = prime * result + TarsUtil.hashCode(dateType); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof MonitorQueryRsp)) { + return false; + } + MonitorQueryRsp other = (MonitorQueryRsp) obj; + return ( + TarsUtil.equals(ret, other.ret) && + TarsUtil.equals(msg, other.msg) && + TarsUtil.equals(lastTime, other.lastTime) && + TarsUtil.equals(activeDb, other.activeDb) && + TarsUtil.equals(totalDb, other.totalDb) && + TarsUtil.equals(retThreads, other.retThreads) && + TarsUtil.equals(result, other.result) && + TarsUtil.equals(intervalTime, other.intervalTime) && + TarsUtil.equals(dateType, other.dateType) + ); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("MonitorQueryRsp("); + sb.append("ret:"); + sb.append(this.ret); + sb.append(", "); + sb.append("msg:"); + if (this.msg == null) { + sb.append("null"); + } else { + sb.append(this.msg); + } + sb.append(", "); + sb.append("lastTime:"); + if (this.lastTime == null) { + sb.append("null"); + } else { + sb.append(this.lastTime); + } + sb.append(", "); + sb.append("activeDb:"); + sb.append(this.activeDb); + sb.append(", "); + sb.append("totalDb:"); + sb.append(this.totalDb); + sb.append(", "); + sb.append("retThreads:"); + if (this.retThreads == null) { + sb.append("null"); + } else { + sb.append(this.retThreads); + } + sb.append(", "); + sb.append("result:"); + if (this.result == null) { + sb.append("null"); + } else { + sb.append(this.result); + } + sb.append(", "); + sb.append("intervalTime:"); + sb.append(this.intervalTime); + sb.append(", "); + sb.append("dateType:"); + sb.append(this.dateType); + sb.append(")"); + return sb.toString(); + } + + public void writeTo(TarsOutputStream _os) { + _os.write(ret, 0); + if (null != msg) { + _os.write(msg, 1); + } + _os.write(lastTime, 2); + _os.write(activeDb, 3); + _os.write(totalDb, 4); + _os.write(retThreads, 5); + if (null != result) { + _os.write(result, 6); + } + _os.write(intervalTime, 7); + _os.write(dateType, 8); + } + + static java.util.List cache_retThreads; + + static { + cache_retThreads = new java.util.ArrayList(); + int var_4 = 0; + cache_retThreads.add(var_4); + } + + static java.util.Map> cache_result; + + static { + cache_result = new java.util.HashMap>(); + String var_5 = ""; + java.util.List var_6 = new java.util.ArrayList(); + double var_7 = 0D; + var_6.add(var_7); + cache_result.put(var_5, var_6); + } + + public void readFrom(TarsInputStream _is) { + this.ret = _is.read(ret, 0, true); + this.msg = _is.readString(1, false); + this.lastTime = _is.readString(2, true); + this.activeDb = _is.read(activeDb, 3, true); + this.totalDb = _is.read(totalDb, 4, true); + this.retThreads = (java.util.List) _is.read(cache_retThreads, 5, true); + this.result = (java.util.Map>) _is.read(cache_result, 6, false); + this.intervalTime = _is.read(intervalTime, 7, false); + this.dateType = _is.read(dateType, 8, false); + } + +} diff --git a/core/src/test/java/com/qq/tars/netty/MonitorQueryServant.java b/core/src/test/java/com/qq/tars/netty/MonitorQueryServant.java new file mode 100644 index 00000000..86817b3f --- /dev/null +++ b/core/src/test/java/com/qq/tars/netty/MonitorQueryServant.java @@ -0,0 +1,17 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.7.2. +// ********************************************************************** + +package com.qq.tars.netty; + +import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsHolder; +import com.qq.tars.protocol.tars.annotation.TarsMethodParameter; + +@Servant +public interface MonitorQueryServant { + + int query(@TarsMethodParameter(name = "req") MonitorQueryReq req, @TarsHolder(name = "rsp") Holder rsp); +} diff --git a/core/src/test/java/com/qq/tars/netty/TestForNettyTransporterServer.java b/core/src/test/java/com/qq/tars/netty/TestForNettyTransporterServer.java new file mode 100644 index 00000000..817563cd --- /dev/null +++ b/core/src/test/java/com/qq/tars/netty/TestForNettyTransporterServer.java @@ -0,0 +1,127 @@ +package com.qq.tars.netty; + +import com.google.common.collect.Maps; +import com.qq.tars.client.rpc.ChannelHandler; +import com.qq.tars.common.support.Endpoint; +import com.qq.tars.common.support.Holder; +import com.qq.tars.rpc.netty.NettyTransporterServer; +import com.qq.tars.rpc.protocol.tars.support.AnalystManager; +import com.qq.tars.server.apps.BaseAppContext; +import com.qq.tars.server.config.ConfigurationManager; +import com.qq.tars.server.config.ServantAdapterConfig; +import com.qq.tars.server.config.ServerConfig; +import com.qq.tars.server.core.AppContextManager; +import com.qq.tars.server.core.ServantAdapter; +import com.qq.tars.server.core.ServantHomeSkeleton; +import io.netty.channel.Channel; +import org.junit.Ignore; +import org.junit.Test; + +import java.util.ArrayList; + +public class TestForNettyTransporterServer { + + @Test + @Ignore + public void testForServer() throws InterruptedException { + ChannelHandler channelHandlerer = new ChannelHandler() { + @Override + public void connected(Channel channel) { + + System.out.println("connect from client" + channel); + } + + @Override + public void disconnected(Channel channel) { + + } + + @Override + public void send(Channel channel, Object message) { + + } + + @Override + public void received(Channel channel, Object message) { + + } + + @Override + public void caught(Channel channel, Throwable exception) { + + } + + @Override + public void destroy() { + + } + }; + Endpoint endpoint = Endpoint.parseString("tcp -h 127.0.0.1 -t 60000 -p 60000"); + ServantAdapterConfig servantAdapterConfig = ServantAdapterConfig.makeServantAdapterConfig(endpoint, + "servantConfig", null); + NettyTransporterServer nettyTransporterServer = new NettyTransporterServer(servantAdapterConfig, + channelHandlerer); + try { + nettyTransporterServer.bind(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + + Thread.sleep(50000); + } + + @Test + public void testForAdapter() throws Throwable { + Endpoint endpoint = Endpoint.parseString("tcp -h 127.0.0.1 -t 60000 -p 60000"); + + AnalystManager.getInstance().registry("", MonitorQueryServant.class, "tars.tarsquerystat.QueryObj"); + ServerConfig serverConfig = new ServerConfig(); + + ConfigurationManager.getInstance().setServerConfig(serverConfig); + ServantAdapterConfig serverAdapterConfig = ServantAdapterConfig.makeServantAdapterConfig(endpoint, + "tars.tarsquerystat.QueryObj", serverConfig); + ServantAdapter servantAdapter = new ServantAdapter(serverAdapterConfig); + ServantHomeSkeleton servantHomeSkeleton = new ServantHomeSkeleton("tars.tarsquerystat.QueryObj", + new MonitorQuerySeravntImpl(), + MonitorQueryServant.class, + 0); + BaseAppContext baseAppContext = (new BaseAppContext() { + @Override + protected void loadServants() throws Exception { + + } + }); + baseAppContext.skeletonMap.put("tars.tarsquerystat.QueryObj", servantHomeSkeleton); + + System.out.println(baseAppContext.getCapHomeSkeleton("tars.tarsquerystat.QueryObj")); + servantHomeSkeleton.setAppContext(baseAppContext); + servantHomeSkeleton.getAppContext().getCapHomeSkeleton("tars.tarsquerystat.QueryObj"); + AppContextManager.getInstance().setAppContext(servantHomeSkeleton.getAppContext()); + System.out.println(AppContextManager.getInstance().getAppContext() == null); + + serverConfig.getServantAdapterConfMap().put("tars.tarsquerystat.QueryObj", serverAdapterConfig); + + servantAdapter.bind(servantHomeSkeleton); + + // Wait briefly to ensure server is up, then shut it down + Thread.sleep(500); + + // Test is successful if server binds without exception + // Shutdown the server to avoid hanging + servantAdapter.stop(); + } + + public static class MonitorQuerySeravntImpl implements MonitorQueryServant { + + @Override + public int query(MonitorQueryReq req, Holder rsp) { + rsp.setValue(new MonitorQueryRsp()); + rsp.getValue().setResult(Maps.newHashMap()); + rsp.getValue().setRetThreads(new ArrayList<>()); + rsp.getValue().setMsg("'"); + System.out.println("receive data " + req.toString()); + System.out.println("receive from client "); + return 0; + } + } +} diff --git a/core/src/test/java/com/qq/tars/netty/TransportTest.java b/core/src/test/java/com/qq/tars/netty/TransportTest.java new file mode 100644 index 00000000..d781a293 --- /dev/null +++ b/core/src/test/java/com/qq/tars/netty/TransportTest.java @@ -0,0 +1,183 @@ +package com.qq.tars.netty; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Maps; +import com.qq.tars.client.CommunicatorConfig; +import com.qq.tars.client.CommunicatorFactory; +import com.qq.tars.client.ServantProxyConfig; +import com.qq.tars.client.rpc.*; +import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.util.TarsHelper; +import com.qq.tars.rpc.common.Url; +import com.qq.tars.rpc.protocol.tars.TarsServantRequest; +import com.qq.tars.rpc.protocol.tars.TarsServantResponse; +import com.qq.tars.rpc.protocol.tars.support.AnalystManager; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.Channel; +import org.junit.Ignore; +import org.junit.Test; + +import java.lang.reflect.Method; +import java.util.concurrent.CompletableFuture; + +public class TransportTest { + @Test + @Ignore + public void testForConnection() throws Exception { + + ChannelHandler channelHandler = new ChannelHandler() { + @Override + public void connected(Channel channel) { + System.out.println("channel header connect"); + + } + + @Override + public void disconnected(Channel channel) { + + } + + @Override + public void send(Channel channel, Object message) { + System.out.println(message); + + } + + @Override + public void received(Channel channel, Object message) { + System.out.println("receive message " + ((TarsServantResponse) message).getResult()); + + } + + @Override + public void caught(Channel channel, Throwable exception) { + + } + + @Override + public void destroy() { + + } + }; + ServantProxyConfig servantProxyConfig = new ServantProxyConfig("test"); + + AnalystManager.getInstance().registry(MonitorQueryPrx.class, "tars.tarsquerystat.QueryObj"); + //Url(String protocol, String host, int port, String path, Map parameters) { + //tcp -h 10.172.0.111 -t 60000 -p 18393 + Url url = new Url("tcp", "10.172.0.111", 18393); + long startTime = System.nanoTime(); + RPCClient client = TransporterAbstractFactory.getInstance().getTransporterFactory().connect(url, servantProxyConfig, channelHandler); + System.out.println("init channel time " + ((System.nanoTime() - startTime) / 1000)); + for (int i = 0; i < 100; i++) { + MonitorQueryReq monitorQueryReq = new MonitorQueryReq(); + monitorQueryReq.dateType = DateType.MINIUES.value(); + monitorQueryReq.method = "query"; + monitorQueryReq.setDataid("tars_stat"); + monitorQueryReq.intervalTime = 1; + monitorQueryReq.setConditions(ImmutableList.of(new Condition("slave_name", 5, "tars.tarsstat"))); + monitorQueryReq.indexs = ImmutableList.of("succ_count", "timeout_count", "exce_count", "total_time"); + monitorQueryReq.setGroupby(ImmutableList.of("f_tflag")); + monitorQueryReq.startTime = 1609171222L; + monitorQueryReq.endTime = 1609221622L; + TarsServantRequest tarsServantRequest = new TarsServantRequest(); + Method method = MonitorQueryPrx.class.getMethod("query", MonitorQueryReq.class, Holder.class); + System.out.println(method); + tarsServantRequest.setMethodInfo(AnalystManager.getInstance().getMethodMap(MonitorQueryPrx.class).get(method)); + tarsServantRequest.setCharsetName("UTF-8"); + tarsServantRequest.setServantName("tars.tarsquerystat.QueryObj"); + tarsServantRequest.setInvokeStatus(Request.InvokeStatus.SYNC_CALL); + Holder response = new Holder<>(); + tarsServantRequest.setMethodParameters(new Object[]{monitorQueryReq, response}); + tarsServantRequest.setCharsetName("UTF-8"); + tarsServantRequest.setApi(MonitorQueryPrx.class); + tarsServantRequest.setFunctionName("query"); + tarsServantRequest.setMessageType(TarsHelper.MESSAGETYPENULL); + tarsServantRequest.setVersion(TarsHelper.VERSION); + tarsServantRequest.setContext(Maps.newHashMap()); + tarsServantRequest.setStatus(Maps.newHashMap()); + tarsServantRequest.setPacketType(TarsHelper.NORMAL); + System.out.println("client connection is " + client.getChannel().isActive()); + System.out.println("client connection is " + client.getChannel().isOpen()); + System.out.println("client connection is " + client.getChannel().isWritable()); + long startTimeNano = System.currentTimeMillis(); + CompletableFuture responseCompletableFuture = client.send(tarsServantRequest).whenComplete((x, y) -> { + System.out.print(System.currentTimeMillis() - startTimeNano + "::"); + System.out.println(response); + }); + } + System.out.println("client connection is " + client.getChannel().isActive()); + System.out.println("client connection is " + client.getChannel().isOpen()); + System.out.println("client connection is " + client.getChannel().isWritable()); + + + Thread.sleep(10000); + } + + + @Test + public void testForEncoder() { + MonitorQueryReq monitorQueryReq = new MonitorQueryReq(); + monitorQueryReq.dateType = DateType.MINIUES.value(); + monitorQueryReq.method = "query"; + monitorQueryReq.setDataid("tars_stat"); + monitorQueryReq.intervalTime = 1; + monitorQueryReq.setConditions(ImmutableList.of(new Condition("slave_name", 5, "tars.tarsstat"))); + monitorQueryReq.indexs = ImmutableList.of("succ_count", "timeout_count", "exce_count", "total_time"); + monitorQueryReq.setGroupby(ImmutableList.of("f_tflag")); + monitorQueryReq.startTime = 1609171222L; + monitorQueryReq.endTime = 1609221622L; + TarsOutputStream tarsOutputStream = new TarsOutputStream(); + monitorQueryReq.writeTo(tarsOutputStream); + byte[] bytearrsy = tarsOutputStream.toByteArray(); + MonitorQueryReq request2 = new MonitorQueryReq(); + request2.readFrom(new TarsInputStream(bytearrsy)); + System.out.println(monitorQueryReq.getMethod()); + System.out.println(monitorQueryReq.getIndexs()); + System.out.println(monitorQueryReq.getConditions()); + System.out.println("request2" + request2); + + } + + + @Test + public void maxCappcity() { + ByteBuf buffer = Unpooled.directBuffer(); + buffer.writeInt(2014); + buffer.writeInt(2014); + buffer.writeInt(2014); + buffer.writeInt(2014); + buffer.writeInt(2014); + System.out.println(buffer.getInt(4 * 5)); + } + + + @Test + @Ignore("requires external tars query service at 127.0.0.1:60000") + public void testForQuery() { + CommunicatorConfig config = new CommunicatorConfig(); + MonitorQueryPrx queryPrx = CommunicatorFactory.getInstance().getCommunicator(config).stringToProxy(MonitorQueryPrx.class, + "tars.tarsquerystat.QueryObj@tcp -h 127.0.0.1 -t 60000 -p 60000"); + MonitorQueryReq request = new MonitorQueryReq(); + request.dateType = DateType.MINIUES.value(); + request.method = "query"; + request.setDataid("tars_stat"); + request.intervalTime = 1; + request.setConditions(ImmutableList.of(new Condition("slave_name", 5, "tars.tarsstat"))); + request.indexs = ImmutableList.of("succ_count", "timeout_count", "exce_count", "total_time"); + request.setGroupby(ImmutableList.of("f_tflag")); + request.startTime = 1606060800L; + request.endTime = 1606147199L; + System.out.println(request); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < 10000; i++) { + Holder holder = new Holder<>(); + queryPrx.query(request, holder); + } + + System.out.println(System.currentTimeMillis() - startTime); + } + +} diff --git a/core/src/test/java/com/qq/tars/quickstart/server/testapp/TestRecursive.java b/core/src/test/java/com/qq/tars/quickstart/server/testapp/TestRecursive.java new file mode 100644 index 00000000..48a7331a --- /dev/null +++ b/core/src/test/java/com/qq/tars/quickstart/server/testapp/TestRecursive.java @@ -0,0 +1,90 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.0.1. +// ********************************************************************** + +package com.qq.tars.quickstart.server.testapp; + +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; + +@TarsStruct +public class TestRecursive { + + @TarsStructProperty(order = 0, isRequire = false) + public int value = 0; + @TarsStructProperty(order = 1, isRequire = false) + public TestRecursive testRecursive = null; + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public TestRecursive getTestRecursive() { + return testRecursive; + } + + public void setTestRecursive(TestRecursive testRecursive) { + this.testRecursive = testRecursive; + } + + public TestRecursive() { + } + + public TestRecursive(int value, TestRecursive testRecursive) { + this.value = value; + this.testRecursive = testRecursive; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + TarsUtil.hashCode(value); + result = prime * result + TarsUtil.hashCode(testRecursive); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof TestRecursive)) { + return false; + } + TestRecursive other = (TestRecursive) obj; + return ( + TarsUtil.equals(value, other.value) && + TarsUtil.equals(testRecursive, other.testRecursive) + ); + } + + public void writeTo(TarsOutputStream _os) { + _os.write(value, 0); + if (null != testRecursive) { + _os.write(testRecursive, 1); + } + } + + static TestRecursive cache_testRecursive; + static { + cache_testRecursive = new TestRecursive(); + } + + public void readFrom(TarsInputStream _is) { + this.value = _is.read(value, 0, false); + this.testRecursive = (TestRecursive) _is.read(cache_testRecursive, 1, false); + } + +} diff --git a/core/src/test/java/com/qq/tars/rpc/protocol/tup/UniAttributeTest.java b/core/src/test/java/com/qq/tars/rpc/protocol/tup/UniAttributeTest.java new file mode 100644 index 00000000..477c1334 --- /dev/null +++ b/core/src/test/java/com/qq/tars/rpc/protocol/tup/UniAttributeTest.java @@ -0,0 +1,118 @@ +package com.qq.tars.rpc.protocol.tup; + +import com.qq.tars.common.util.HexUtil; +import com.qq.tars.support.log.prx.LogInfo; +import org.junit.Ignore; +import org.junit.Test; + +import java.nio.charset.StandardCharsets; + +/** + * @description: add your desc + * @author: walker + * @create: 2020-02-18 19:38 + **/ + +public class UniAttributeTest { + public LogInfo getLogInfo() { + LogInfo logInfo = new LogInfo(); + logInfo.appname = "appname"; + logInfo.servername = "servName"; + logInfo.sFilename = "filename"; + return logInfo; + } + + /** + * reproduce the problem: decode data is null. + * user the old version + */ + @Test + @Ignore + public void reproduceDecodeProblem() { + //tup version=2 encode + String version2HexByteStr = encodeVersion2Fix(); + System.out.println(version2HexByteStr); + + //devocode tup version=2 now. + LogInfo logInfo = decodeVersionV2Now(version2HexByteStr); + printLogInfo(logInfo); + } + + /** + * reproduce the problem: encode tup version=2. + * user the old version. + * the tupProxy client will see:com.huya.taf.protocol.taf.exc.TafDecodeException: type mismatch + */ + public void reproduceEncodeProblem() { + //use tup version=2 encode now. + String version2HexByteStr = encodeVersion2Now(); + + //user the tupVersion=2 decode. + LogInfo logInfo = decodeVersionV2Fix(version2HexByteStr); + printLogInfo(logInfo); + } + + /** + * fix decode tup version=2 problem. + */ + @Test + public void fixDecodeProblem() { + //version2 wup encode. + String version2HexByteStr = encodeVersion2Fix(); + System.out.println(version2HexByteStr); + + LogInfo logInfo = decodeVersionV2Fix(version2HexByteStr); + printLogInfo(logInfo); + } + + @Test + public void fixEncodeProblem() { + String version2HexByteStr = encodeVersion2Fix(); + + LogInfo logInfo = decodeVersionV2Fix(version2HexByteStr); + printLogInfo(logInfo); + } + + public String encodeVersion2Fix() { + UniAttribute unaIn = new UniAttribute(); + unaIn.setNewDataNull(); + LogInfo logInfo = getLogInfo(); + unaIn.put("tReq", logInfo); + byte[] byteArray = unaIn.encode(); + String byteStr = HexUtil.bytes2HexStr(byteArray); + return byteStr; + } + + public void printLogInfo(LogInfo logInfo) { + System.out.println("logInfo.appName:" + logInfo.appname); + } + + + public String encodeVersion2Now() { + LogInfo logInfo = getLogInfo(); + UniAttribute unaIn = new UniAttribute(); + unaIn.put("tReq", logInfo); + byte[] byteArray = unaIn.encode(); + String byteStr = HexUtil.bytes2HexStr(byteArray); + return byteStr; + } + + private LogInfo decodeVersionV2Now(String hexBytes) { + byte[] data = HexUtil.hexStr2Bytes(hexBytes); + UniAttribute unaIn = new UniAttribute(); + unaIn.setEncodeName(StandardCharsets.UTF_8); + unaIn.decodeVersion2(data); + LogInfo logInfo = unaIn.getByClass("tReq", new LogInfo()); + return logInfo; + } + + private LogInfo decodeVersionV2Fix(String hexBytes) { + byte[] data = HexUtil.hexStr2Bytes(hexBytes); + UniAttribute unaIn = new UniAttribute(); + unaIn.setNewDataNull(); + unaIn.setEncodeName(StandardCharsets.UTF_8); + unaIn.decodeVersion2(data); + LogInfo logInfo = unaIn.getByClass("tReq", new LogInfo()); + return logInfo; + } +} diff --git a/core/src/test/java/com/qq/tars/server/core/ServantAdapterTest.java b/core/src/test/java/com/qq/tars/server/core/ServantAdapterTest.java new file mode 100644 index 00000000..907669d9 --- /dev/null +++ b/core/src/test/java/com/qq/tars/server/core/ServantAdapterTest.java @@ -0,0 +1,12 @@ +package com.qq.tars.server.core; + +import org.junit.Test; + +public class ServantAdapterTest { + + @Test + public void testStopWithoutBind() { + ServantAdapter adapter = new ServantAdapter(null); + adapter.stop(); + } +} diff --git a/core/src/test/java/com/qq/tars/support/trace/spi/SkywalkingTraceInitializerTest.java b/core/src/test/java/com/qq/tars/support/trace/spi/SkywalkingTraceInitializerTest.java new file mode 100644 index 00000000..1e953b3d --- /dev/null +++ b/core/src/test/java/com/qq/tars/support/trace/spi/SkywalkingTraceInitializerTest.java @@ -0,0 +1,48 @@ +package com.qq.tars.support.trace.spi; + +import com.qq.tars.server.config.ServerConfig; +import com.qq.tars.support.om.OmConstants; +import com.qq.tars.support.trace.TraceManager; +import org.junit.Assert; +import org.junit.Test; + +import java.util.LinkedHashMap; + +public class SkywalkingTraceInitializerTest { + + @Test + public void shouldSupportSkywalkingSampleType() { + SkywalkingTraceInitializer initializer = new SkywalkingTraceInitializer(); + + ServerConfig serverConfig = new ServerConfig(); + serverConfig.setSampleType("skywalking"); + Assert.assertTrue(initializer.supports(serverConfig)); + + serverConfig.setSampleType("sw"); + Assert.assertTrue(initializer.supports(serverConfig)); + + serverConfig.setSampleType("http"); + Assert.assertFalse(initializer.supports(serverConfig)); + } + + @Test + public void shouldRegisterTracerForBusinessServant() { + SkywalkingTraceInitializer initializer = new SkywalkingTraceInitializer(); + String servantName = "TestApp.TestServer.SkywalkingObj" + System.nanoTime(); + + ServerConfig serverConfig = new ServerConfig(); + serverConfig.setSampleType("skywalking"); + serverConfig.setSampleRate(1); + serverConfig.setSampleEncoding("grpc"); + serverConfig.setSampleAddress("127.0.0.1:11800"); + + LinkedHashMap servantMap = new LinkedHashMap<>(); + servantMap.put(servantName, null); + servantMap.put(OmConstants.AdminServant, null); + serverConfig.setServantAdapterConfMap(servantMap); + + initializer.init(serverConfig); + + Assert.assertNotNull(TraceManager.getInstance().getCurrentTracer(servantName)); + } +} diff --git a/core/src/test/java/com/qq/tars/support/trace/spi/TraceInitializerManagerTest.java b/core/src/test/java/com/qq/tars/support/trace/spi/TraceInitializerManagerTest.java new file mode 100644 index 00000000..7260bde4 --- /dev/null +++ b/core/src/test/java/com/qq/tars/support/trace/spi/TraceInitializerManagerTest.java @@ -0,0 +1,72 @@ +package com.qq.tars.support.trace.spi; + +import com.qq.tars.server.config.ServerConfig; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.concurrent.atomic.AtomicInteger; + +public class TraceInitializerManagerTest { + + @Test + public void shouldSelectTheFirstSupportedInitializer() { + MockTraceInitializer unsupported = new MockTraceInitializer("unsupported", false); + MockTraceInitializer supported = new MockTraceInitializer("supported", true); + MockTraceInitializer fallback = new MockTraceInitializer("fallback", true); + + TraceInitializerManager manager = new TraceInitializerManager(Arrays.asList(unsupported, supported, fallback)); + ServerConfig serverConfig = new ServerConfig(); + serverConfig.setSampleRate(1); + serverConfig.setSampleType("skywalking"); + + boolean initialized = manager.init(serverConfig); + + Assert.assertTrue(initialized); + Assert.assertEquals(0, unsupported.initCounter.get()); + Assert.assertEquals(1, supported.initCounter.get()); + Assert.assertEquals(0, fallback.initCounter.get()); + } + + @Test + public void shouldSkipInitializationWhenSampleRateIsDisabled() { + MockTraceInitializer supported = new MockTraceInitializer("supported", true); + + TraceInitializerManager manager = new TraceInitializerManager(Arrays.asList(supported)); + ServerConfig serverConfig = new ServerConfig(); + serverConfig.setSampleRate(0); + serverConfig.setSampleType("skywalking"); + + boolean initialized = manager.init(serverConfig); + + Assert.assertFalse(initialized); + Assert.assertEquals(0, supported.initCounter.get()); + } + + private static class MockTraceInitializer implements TraceInitializer { + + private final String name; + private final boolean supported; + private final AtomicInteger initCounter = new AtomicInteger(0); + + private MockTraceInitializer(String name, boolean supported) { + this.name = name; + this.supported = supported; + } + + @Override + public String name() { + return name; + } + + @Override + public boolean supports(ServerConfig serverConfig) { + return supported; + } + + @Override + public void init(ServerConfig serverConfig) { + initCounter.incrementAndGet(); + } + } +} diff --git a/core/src/test/java/com/qq/tars/support/trace/spi/TraceInitializerSpiTest.java b/core/src/test/java/com/qq/tars/support/trace/spi/TraceInitializerSpiTest.java new file mode 100644 index 00000000..72ce3060 --- /dev/null +++ b/core/src/test/java/com/qq/tars/support/trace/spi/TraceInitializerSpiTest.java @@ -0,0 +1,23 @@ +package com.qq.tars.support.trace.spi; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashSet; +import java.util.ServiceLoader; +import java.util.Set; + +public class TraceInitializerSpiTest { + + @Test + public void shouldLoadBuiltInTraceInitializersFromSpi() { + ServiceLoader loaders = ServiceLoader.load(TraceInitializer.class); + Set providerNames = new HashSet<>(); + for (TraceInitializer initializer : loaders) { + providerNames.add(initializer.name()); + } + + Assert.assertTrue(providerNames.contains("zipkin")); + Assert.assertTrue(providerNames.contains("skywalking")); + } +} diff --git a/core/src/test/java/com/qq/tars/support/trace/spi/ZipkinTraceInitializerTest.java b/core/src/test/java/com/qq/tars/support/trace/spi/ZipkinTraceInitializerTest.java new file mode 100644 index 00000000..ca86ca76 --- /dev/null +++ b/core/src/test/java/com/qq/tars/support/trace/spi/ZipkinTraceInitializerTest.java @@ -0,0 +1,48 @@ +package com.qq.tars.support.trace.spi; + +import com.qq.tars.server.config.ServerConfig; +import com.qq.tars.support.om.OmConstants; +import com.qq.tars.support.trace.TraceManager; +import org.junit.Assert; +import org.junit.Test; + +import java.util.LinkedHashMap; + +public class ZipkinTraceInitializerTest { + + @Test + public void shouldSupportZipkinSampleTypes() { + ZipkinTraceInitializer initializer = new ZipkinTraceInitializer(); + + ServerConfig serverConfig = new ServerConfig(); + serverConfig.setSampleType("http"); + Assert.assertTrue(initializer.supports(serverConfig)); + + serverConfig.setSampleType("kafka"); + Assert.assertTrue(initializer.supports(serverConfig)); + + serverConfig.setSampleType("skywalking"); + Assert.assertFalse(initializer.supports(serverConfig)); + } + + @Test + public void shouldRegisterTracerForBusinessServant() throws Exception { + ZipkinTraceInitializer initializer = new ZipkinTraceInitializer(); + String servantName = "TestApp.TestServer.ZipkinObj" + System.nanoTime(); + + ServerConfig serverConfig = new ServerConfig(); + serverConfig.setSampleType("http"); + serverConfig.setSampleRate(1); + serverConfig.setSampleEncoding("json"); + serverConfig.setSampleAddress("http://127.0.0.1:9411"); + + LinkedHashMap servantMap = new LinkedHashMap<>(); + servantMap.put(servantName, null); + servantMap.put(OmConstants.AdminServant, null); + serverConfig.setServantAdapterConfMap(servantMap); + + initializer.init(serverConfig); + + Assert.assertNotNull(TraceManager.getInstance().getCurrentTracer(servantName)); + } +} diff --git a/core/src/main/java/com/qq/tars/support/notify/prx/NotifyPrxCallback.java b/core/src/test/java/com/qq/tars/testapp/HelloPrx.java similarity index 68% rename from core/src/main/java/com/qq/tars/support/notify/prx/NotifyPrxCallback.java rename to core/src/test/java/com/qq/tars/testapp/HelloPrx.java index ed0483b3..e59bb113 100644 --- a/core/src/main/java/com/qq/tars/support/notify/prx/NotifyPrxCallback.java +++ b/core/src/test/java/com/qq/tars/testapp/HelloPrx.java @@ -18,18 +18,19 @@ // TARS version 1.0.1. // ********************************************************************** -package com.qq.tars.support.notify.prx; +package com.qq.tars.testapp; -import com.qq.tars.rpc.protocol.tars.support.TarsAbstractCallback; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsContext; -public abstract class NotifyPrxCallback extends TarsAbstractCallback { +import java.util.concurrent.CompletableFuture; - public abstract void callback_reportServer(); +@Servant +public interface HelloPrx { - public abstract void callback_notifyServer(); + public String hello(int no, String name); - public abstract void callback_getNotifyInfo(int ret, NotifyInfo stInfo); - - public abstract void callback_reportNotifyInfo(); + CompletableFuture promise_hello(int no, String name); + public String hello(int no, String name, @TarsContext java.util.Map ctx); } diff --git a/distributedContext/README.md b/distributedContext/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/distributedContext/pom.xml b/distributedContext/pom.xml deleted file mode 100644 index 03e52ac7..00000000 --- a/distributedContext/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - 4.0.0 - - com.tencent.tars - tars-parent - 1.6.1 - - - tars-context - ${project.artifactId} - jar - - diff --git a/distributedContext/src/main/java/com/qq/tars/context/DistributedContextCodec.java b/distributedContext/src/main/java/com/qq/tars/context/DistributedContextCodec.java deleted file mode 100644 index 0e1676a9..00000000 --- a/distributedContext/src/main/java/com/qq/tars/context/DistributedContextCodec.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.context; - -import java.util.Map; - -public interface DistributedContextCodec { - - /** - * - * @param context - * @return - */ - public byte[] context2Bytes(Map context); - - /** - * - * @param context - * @param src - */ - public Map loadBytes(byte[] src); - - /** - * - * @param context - * @param src - * @param offset - * @param length - */ - public Map loadBytes(byte[] src, int offset, int length); - - /** - * - * @param context - * @return - */ - public String context2String(Map context); - - /** - * - * @param context - * @param src - */ - public Map loadString(String src); - -} diff --git a/distributedContext/src/main/java/com/qq/tars/context/DistributedContextManager.java b/distributedContext/src/main/java/com/qq/tars/context/DistributedContextManager.java deleted file mode 100644 index a927ac6a..00000000 --- a/distributedContext/src/main/java/com/qq/tars/context/DistributedContextManager.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.context; - -import java.util.Map; - -import com.qq.tars.context.exc.CodecException; -import com.qq.tars.context.impl.DistributedContextImpl; - -public class DistributedContextManager { - - private static final DistributedContext context = new DistributedContextImpl(); - - private static DistributedContextCodec _codec; - - private static boolean canCodec() { - return _codec == null ? false : true; - } - - public static final DistributedContext getDistributedContext() { - return context; - } - - public static final void releaseDistributedContext() { - getDistributedContext().clear(); - } - - public static void setDistributedContextCodec(DistributedContextCodec codec) { - _codec = codec; - } - - public static byte[] serializeContext2Bytes() throws CodecException { - if (canCodec()) { - return _codec.context2Bytes(getDistributedContext().getAttrbuites()); - } else { - throw new CodecException("codec is null"); - } - } - - public static void deserializeBytes2Context(byte[] src) throws CodecException { - if (canCodec()) { - Map attributes = _codec.loadBytes(src); - for (Map.Entry attribute : attributes.entrySet()) { - getDistributedContext().put(attribute.getKey(), attribute.getValue()); - } - } else { - throw new CodecException("codec is null"); - } - } - - public static String seriallizeContext2String() throws CodecException { - if (canCodec()) { - return _codec.context2String(getDistributedContext().getAttrbuites()); - } else { - throw new CodecException("codec is null"); - } - } - - public static void deserializeString2Context(String src) throws CodecException { - if (canCodec()) { - Map attributes = _codec.loadString(src); - for (Map.Entry attribute : attributes.entrySet()) { - getDistributedContext().put(attribute.getKey(), attribute.getValue()); - } - } else { - throw new CodecException("codec is null"); - } - } - -} diff --git a/distributedContext/src/main/java/com/qq/tars/context/exc/CodecException.java b/distributedContext/src/main/java/com/qq/tars/context/exc/CodecException.java deleted file mode 100644 index 5f04e296..00000000 --- a/distributedContext/src/main/java/com/qq/tars/context/exc/CodecException.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.context.exc; - -@SuppressWarnings("serial") -public class CodecException extends Exception { - - public CodecException() { - super(); - } - - public CodecException(String message) { - super(message); - } - - public CodecException(Throwable cause) { - super(cause); - } - - public CodecException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/distributedContext/src/main/java/com/qq/tars/context/impl/ContextItem.java b/distributedContext/src/main/java/com/qq/tars/context/impl/ContextItem.java deleted file mode 100644 index 695366d3..00000000 --- a/distributedContext/src/main/java/com/qq/tars/context/impl/ContextItem.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.context.impl; - -import java.util.HashMap; -import java.util.Map; - -public class ContextItem { - - private Map attributes = new HashMap(); - - @SuppressWarnings("unchecked") - public T getAttribute(String name) { - return (T) getAttribute(name, null); - } - - @SuppressWarnings("unchecked") - public T getAttribute(String name, T defaultValue) { - Object value = null; - value = attributes.get(name); - if (value == null) return defaultValue; - return (T)value; - } - - public void setAttribute(String name, T value) { - this.attributes.put(name, value); - } - - public Map getMap() { - return attributes; - } - -} diff --git a/distributedContext/src/main/java/com/qq/tars/context/impl/DistributedContextImpl.java b/distributedContext/src/main/java/com/qq/tars/context/impl/DistributedContextImpl.java deleted file mode 100644 index 1cefce51..00000000 --- a/distributedContext/src/main/java/com/qq/tars/context/impl/DistributedContextImpl.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.context.impl; - -import java.util.Map; -import java.util.Set; - -import com.qq.tars.context.DistributedContext; - -public class DistributedContextImpl implements DistributedContext { - - private static ThreadLocal contexts = new ThreadLocal() { - protected ContextItem initialValue() { - return new ContextItem(); - } - }; - - public void clear() { - contexts.remove(); - } - - @SuppressWarnings("unchecked") - public T get(String name) { - try { - ContextItem item = getItem(); - Object value = item.getAttribute(name); - return value != null ? (T)value : null; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public Set keySet() { - return getItem().getMap().keySet(); - } - - public void put(String name, T value) { - getItem().setAttribute(name, value); - } - - public int size() { - return getItem().getMap().size(); - } - - private ContextItem getItem() { - ContextItem item = contexts.get(); - if (item == null) { - item = new ContextItem(); - contexts.set(item); - } - return item; - } - - public Map getAttrbuites() { - return getItem().getMap(); - } - -} diff --git a/docs-en/images/Logback-config.png b/docs-en/images/Logback-config.png new file mode 100644 index 00000000..9e88c644 Binary files /dev/null and b/docs-en/images/Logback-config.png differ diff --git a/docs-en/images/docker-hello-world.png b/docs-en/images/docker-hello-world.png new file mode 100644 index 00000000..9b4a50c2 Binary files /dev/null and b/docs-en/images/docker-hello-world.png differ diff --git a/docs-en/images/eureka-tars-java.png b/docs-en/images/eureka-tars-java.png new file mode 100644 index 00000000..6350fde2 Binary files /dev/null and b/docs-en/images/eureka-tars-java.png differ diff --git a/docs-en/images/tars-deployment-client.png b/docs-en/images/tars-deployment-client.png new file mode 100644 index 00000000..32d4c548 Binary files /dev/null and b/docs-en/images/tars-deployment-client.png differ diff --git a/docs-en/images/tars-deployment-http.png b/docs-en/images/tars-deployment-http.png new file mode 100644 index 00000000..3adecc38 Binary files /dev/null and b/docs-en/images/tars-deployment-http.png differ diff --git a/docs-en/images/tars-deployment.png b/docs-en/images/tars-deployment.png new file mode 100644 index 00000000..7a372cfd Binary files /dev/null and b/docs-en/images/tars-deployment.png differ diff --git a/docs-en/images/tars-en.png b/docs-en/images/tars-en.png new file mode 100644 index 00000000..51a29d52 Binary files /dev/null and b/docs-en/images/tars-en.png differ diff --git a/docs-en/images/tars-http-call.png b/docs-en/images/tars-http-call.png new file mode 100644 index 00000000..879470d0 Binary files /dev/null and b/docs-en/images/tars-http-call.png differ diff --git a/docs-en/images/tars-pubjar-client.png b/docs-en/images/tars-pubjar-client.png new file mode 100644 index 00000000..fc316021 Binary files /dev/null and b/docs-en/images/tars-pubjar-client.png differ diff --git a/docs-en/images/tars-pubjar.png b/docs-en/images/tars-pubjar.png new file mode 100644 index 00000000..101a9b6d Binary files /dev/null and b/docs-en/images/tars-pubjar.png differ diff --git a/docs-en/images/tars-publication.png b/docs-en/images/tars-publication.png new file mode 100644 index 00000000..ac19047c Binary files /dev/null and b/docs-en/images/tars-publication.png differ diff --git a/docs-en/images/tars-state-client.png b/docs-en/images/tars-state-client.png new file mode 100644 index 00000000..e141b8d5 Binary files /dev/null and b/docs-en/images/tars-state-client.png differ diff --git a/docs-en/images/tars-state.png b/docs-en/images/tars-state.png new file mode 100644 index 00000000..3fdb1591 Binary files /dev/null and b/docs-en/images/tars-state.png differ diff --git a/docs-en/images/tars-tarstest-client.png b/docs-en/images/tars-tarstest-client.png new file mode 100644 index 00000000..0cf09867 Binary files /dev/null and b/docs-en/images/tars-tarstest-client.png differ diff --git a/docs-en/images/tars-tarstest.png b/docs-en/images/tars-tarstest.png new file mode 100644 index 00000000..9f33c0bd Binary files /dev/null and b/docs-en/images/tars-tarstest.png differ diff --git a/docs-en/images/tars-test-client.png b/docs-en/images/tars-test-client.png new file mode 100644 index 00000000..9897ce53 Binary files /dev/null and b/docs-en/images/tars-test-client.png differ diff --git a/docs-en/images/tars-test.png b/docs-en/images/tars-test.png new file mode 100644 index 00000000..af10825d Binary files /dev/null and b/docs-en/images/tars-test.png differ diff --git a/docs-en/images/tars-testclient.png b/docs-en/images/tars-testclient.png new file mode 100644 index 00000000..58ae7f54 Binary files /dev/null and b/docs-en/images/tars-testclient.png differ diff --git a/docs-en/images/tars-testserver.png b/docs-en/images/tars-testserver.png new file mode 100644 index 00000000..63788150 Binary files /dev/null and b/docs-en/images/tars-testserver.png differ diff --git a/docs-en/images/tars-uploadjar.png b/docs-en/images/tars-uploadjar.png new file mode 100644 index 00000000..520a1f50 Binary files /dev/null and b/docs-en/images/tars-uploadjar.png differ diff --git a/docs-en/images/tars-uploadjarclient.png b/docs-en/images/tars-uploadjarclient.png new file mode 100644 index 00000000..74cf70a7 Binary files /dev/null and b/docs-en/images/tars-uploadjarclient.png differ diff --git a/docs-en/images/tars-uploadtars-client.png b/docs-en/images/tars-uploadtars-client.png new file mode 100644 index 00000000..40c89827 Binary files /dev/null and b/docs-en/images/tars-uploadtars-client.png differ diff --git a/docs-en/images/tars-uploadtars.png b/docs-en/images/tars-uploadtars.png new file mode 100644 index 00000000..cb98e0ca Binary files /dev/null and b/docs-en/images/tars-uploadtars.png differ diff --git a/docs-en/images/tarsjavastart-info.png b/docs-en/images/tarsjavastart-info.png new file mode 100644 index 00000000..9e20d768 Binary files /dev/null and b/docs-en/images/tarsjavastart-info.png differ diff --git a/docs-en/tars-http-server.md b/docs-en/tars-http-server.md new file mode 100644 index 00000000..2f20d492 --- /dev/null +++ b/docs-en/tars-http-server.md @@ -0,0 +1,199 @@ +# HTTP Service Tutorials + +## Function Description + +The Tars platform supports the deployment of HTTP services. You can use the @TarsHttpService annotation to mark the service as an HTTP service. After the HTTP service is published to the platform, it can be called directly using the HTTP request. + + + +## Demo + +[tars-spring-boot-http-server](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-boot-http-server) + + + +## Service Development + +### Project structure + +```text +├── pom.xml +└── src + └── main + ├── java + │ └── com.tecent.tars + | ├── App.java + │ ├── client.testapp + │ | ├── HelloPrx.java + │ | └── HelloPrxCallback.java + │ | + | └──http.server + │ └── HelloController.java + └── resources + └── hello.tars +``` + + + +### Dependency configuration + +The following configuration needs to be added in pom.xml: + +**Spring boot and Tars framework dependency** + +```xml + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + com.tencent.tars + tars-spring-boot-starter + 1.7.0 + + +``` + +**Plugin dependency** + +```xml + + + com.tencent.tars + tars-maven-plugin + 1.7.0 + + + + + ${basedir}/src/main/resources/hello.tars + + + UTF-8 + + false + + UTF-8 + + ${basedir}/src/main/java + + com.tencent.tars.client. + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + conf/ + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.tencent.tars.App + + + + + repackage + + + +``` + + + +### Server interface file compilation + +After the server service development is completed, we first need to obtain the client interface code of the server service. Copy the hello.tars file on the server side to the resources directory, and execute `mvn tars: tars2java` in the project root directory to get HelloPrx.java. At this time, the proxy interface of the server service is obtained, and three calling methods are provided, namely synchronous call, asynchronous call and promise call. + +```java +@Servant +public interface HelloPrx { + + String hello(int no, String name); + + CompletableFuture promise_hello(int no, String name); + + String hello(int no, String name, @TarsContext java.util.Map ctx); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); +} +``` + + + +### Create controller + +Then we need to create a controller. Create a new HelloController.java and use the @TarsHttpService annotation to enable the Tars HTTP service. + +```java +@TarsHttpService("HttpObj") +@RestController +public class HelloController { + @TarsClient("TestServer.HelloServer.HelloObj") + HelloPrx helloPrx; + + @RequestMapping("/hello") + public String testHello(@RequestParam Integer no){ + String ret = helloPrx.hello(no, "Hello World"); + return ret; + } +} +``` + + + +### Tars service enabling + +Finally, add @EnableTarsServer annotation in the spring boot startup class App to enable Tars service: + +```java +@SpringBootApplication +@EnableTarsServer +public class App { + public static void main( String[] args ){ + SpringApplication.run(App.class, args); + } +} +``` + + + +### Service packaging + +Using spring-boot-maven-plugin, execute `mvn package` in the root directory to package it into a jar. + + + +## Service release + +The process of HTTP service release is similar to that of [Tars service release](dev/tarsjava/tars-quick-start.md). The difference is that when the service is deployed, the protocol selects a non-TARS protocol. The specific settings are shown in the following figure: + +![tars-deployment-http](images/tars-deployment-http.png) + + + +## Service call + +After the service is published successfully, you can call the service through http call. **Note that the IP address is the public IP, not the set internal IP**: + +![tars-http-call](images/tars-http-call.png) \ No newline at end of file diff --git a/docs-en/tars-java-start.md b/docs-en/tars-java-start.md new file mode 100644 index 00000000..ff401aaa --- /dev/null +++ b/docs-en/tars-java-start.md @@ -0,0 +1,54 @@ +# TarsJava scaffolding tool +This tool provides TarsJava scaffolding. + +With this tool, you can generate TarsJava scaffolding for the server and client, and quickly start the development of the Tars service. + +## 1. Environmental requirements +- JDK1.8 or above + +## 2. Installation and usage +### Installation + +Directly copy tars-java-tools-1.0.0.jar in the jar folder to the project directory and use it, or compile it yourself as follows: + +- Clone the project: `git clone https://github.com/TarsCloud/TarsJavaStart.git` + + Environmental requirements + + - JDK1.8 or above + - Maven 3.5 or above + + - Spring Boot 4.0 or above + +- Execute maven packaging in the project root directory: `mvn package` + +- Enter the target directory and copy the generated jar package to the project directory + +### Scaffolding generation + +Run the following command in the project directory: + +```text +java -jar tars-java-start-1.0.0.jar --springboot.version=2.0.3 --maven.group=com.tencent.tars --maven.artifact=test-server --maven.name=TestServer --packagename=com.tencent.tars.server --jdk.version=1.8 --type=server +``` + +The parameters are as follows: + +- springboot.version: SpringBoot version, default is 2.0.3 +- maven.group: maven groupId, default is com.tencent.tars +- maven.artifact: maven artifactId, default is test-server +- maven.name: maven Name, default is TestServer +- packagename: package name, default is com.tencent.tars.server +- jdk.version: jdk version, default is 1.8 +- type: provide server and client options, default is server + +After the command is executed, relevant information will be displayed. When 'Generating Complete!' appears, it means the generation is successful. + +![tarsjavastart-info](images/tarsjavastart-info.png) + + + +### Development and publishing + +For server and client development, please refer to Tars-Spring-Boot Service Development in [Tars Service Tutorials](https://github.com/TarsCloud/TarsDocs_en/blob/master/dev/tarsjava/tars-tutorials.md). For publishing, please refer to the publishing process in [Quick Start To Tars](https://github.com/TarsCloud/TarsDocs_en/blob/master/dev/tarsjava/tars-quick-start.md). + diff --git a/docs-en/tars-quick-start.md b/docs-en/tars-quick-start.md new file mode 100644 index 00000000..82d17993 --- /dev/null +++ b/docs-en/tars-quick-start.md @@ -0,0 +1,262 @@ +# Quick Start To Tars + +This guide gives you a quick introduction to Tars in Java through simple server and client examples. + +## Tars deployment by Docker + +This guide uses Docker to complete the deployment of Tars. + +### Docker installation + +Taking Ubuntu for example, the installation process of Docker is as follows: + +**1. Update package index** + +```text +sudo apt-get update +``` + +**2. Allow installation via HTTPS** + +``` +sudo apt-get install apt-transport-https ca-certificates curl software-properties-common +``` + +**3. Add Docker's official GPG key** + +``` +curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add +``` + +Chinese users can use Tencent cloud source: + +```text +curl -fsSL https://mirrors.cloud.tencent.com/docker-ce/linux/ubuntu/gpg | sudo apt-key add - +``` + +**4. Set version library type** + +``` +sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" +``` + +Chinese users can use Tencent cloud source: + +```text +sudo add-apt-repository "deb [arch=amd64] https://mirrors.cloud.tencent.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable" +``` + +**5. Update package index again** + +```text +sudo apt-get update +``` + +**6. Install Docker-ce** + +``` +sudo apt-get install docker-ce +``` + +**7. Test whether the installation is successful** + +``` +docker run hello-world +``` + +![docker-hello-world](images/docker-hello-world.png) + +The above interface appears to indicate that docker has been installed successfully. + + + +### Tars deployment + +**1. Create a Docker virtual network** + +```text +# Create a bridge virtual network named tars with a gateway of 172.25.0.1 and a network segment of 172.25.0.0 +docker network create -d bridge --subnet=172.25.0.0/16 --gateway=172.25.0.1 tars +``` + +**2. Start MySQL in Docker** + +```text +docker run -d \ + --net=tars \ + -e MYSQL_ROOT_PASSWORD="123456" \ + --ip="172.25.0.2" \ + -v /data/framework-mysql:/var/lib/mysql \ + -v /etc/localtime:/etc/localtime \ + --name=tars-mysql \ + mysql:5.6 +``` + +**3. Deploy using tarscloud/tars:java image** + +Pull the container image: + +```text +docker pull tarscloud/tars:java +``` + +Start the container: + +```text +docker run -d -it --name tars_java \ + --net=tars \ + --env DBIP=172.25.0.2 \ + --env DBPort=3306 \ + --env DBUser=root \ + --env DBPassword=123456 \ + -e INET=eth0 \ + --ip="172.25.0.3" \ + -p 3000:3000 \ + -p 18600-18700:18600-18700 \ + -v /data/tars_data:/data \ + tarscloud/tars:java +``` + +**Note: - P 18600-18700:18600-18700 parameter opens 18600-18700 port for application. You can add more ports if necessary** + + + +After the container is started, access `http://${your_machine_IP}:3000` to open the web management platform. The interface is as follows: + +![tars-en](images/tars-en.png) + + + +## Service release + +### Download the example and package it into a jar + +Run the following commands: + +```text +# Clone the repository to get the example code: +git clone https://github.com/TarsCloud/TarsJava.git +# Enter server code directory +cd TarsJava/examples/tars-spring-boot-server +# package the server example into a jar +mvn package +# Enter client code directory +cd TarsJava/examples/tars-spring-boot-client +# package the client example into a jar +mvn package +``` + + + +### Service deployment + +Enter the web management platform, select the operation tab and configure the server and client services respectively according to the following figure. Some parameters are as follows: + +- **Application Name**: a collection of services +- **Service Name**: the name of the process providing the service +- **OBJ**: interface which provides the specific service + +The system defines the routing name of the service in the system through application name + service name + OBJ, for example, TestServer.HelloServer.HelloObj + +- **Service type**: tars_java +- **Template**: tars.springboot +- **Node**: select the active Tars node IP +- **Port**: choose open ports + +**server:** + +![tars-deployment](images/tars-deployment.png) + +**client:** + +![tars-deployment-client](images/tars-deployment-client.png) + + + +### Node publication + +After the service is successfully deployed, you can see the two newly added services after refreshing the main page, namely the HelloServer service on the server side and the HelloClient service on the client side. + +![tars-testclient](images/tars-testclient.png) + + + +Select the HelloServer service and the HelloClient service respectively, switch to Publish tag, select the node to publish, and click the publish node button. + +![tars-publication](images/tars-publication.png) + + + +Click the upload release package button, and upload the jar. + +**server:** + +![tars-uploadjar](images/tars-uploadjar.png) + +**client:** + +![tars-uploadjarclient](images/tars-uploadjarclient.png) + + + +After the upload is completed, a version number with a time stamp will be automatically generated. Select the version and click the publish button: + +**server:** + +![tars-pubjar](images/tars-pubjar.png) + +**client:** + +![tars-pubjar-client](images/tars-pubjar-client.png) + + + +Back to the Services tab, you can see that the status is Active, which means success. + +**server:** + +![tars-state](images/tars-state.png) + +**client:** + +![tars-state-client](images/tars-state-client.png) + + + +### Interface debugging + +Switch to Interface Debugger tag,click the add button and upload the hello.tars file in the resources directory in the HelloServer service, and upload the client.tars file in the HelloClient service. + +**server:** + +![tars-uploadtars](images/tars-uploadtars.png) + +**client:** + +![tars-uploadtars-client](images/tars-uploadtars-client.png) + + + +After the upload is completed, the newly added service will be displayed in the Tars file list. Then click the debug button. + +**server:** + +![tars-tarstest](images/tars-tarstest.png) + +**client:** + +![tars-tarstest-client](images/tars-tarstest-client.png) + + + +Select the function to be debugged, input the input parameter, and click the debug button to obtain the output parameter. + +**server:** + +![tars-test](images/tars-test.png) + +**client:** + +![tars-test-client](images/tars-test-client.png) + +So far, the deployment of server and client is completed. diff --git a/docs-en/tars-reference.md b/docs-en/tars-reference.md new file mode 100644 index 00000000..01e6a83b --- /dev/null +++ b/docs-en/tars-reference.md @@ -0,0 +1,177 @@ +# Tars File Reference + +Tars protocol is a protocol based on IDL. Similar to Protocol Buffer, it is language-independent and is a C ++-like identifier language which is used to generate specific service interface files. At the same time, as a binary protocol, compared with common text protocols such as JSON, it has higher encoding and decoding efficiency and smaller network packet space. + +The Tars file uses .tars as the extension. For each service in the .tars file, a Java interface will be generated when generating the code. If the server interface code is generated, the Servant suffix will be added. If the code is generated for the client, the Prx suffix will be added. For the grammar rules of Tars language, please refer to [Tars protocol](https://github.com/TarsCloud/TarsDocs_en/blob/master/base/tars-protocol.md). + + + +## Tars-maven-plugin + +Tars-maven-plugin needs to add related dependencies in the pom.xml file: + +```xml + + + com.tencent.tars + tars-maven-plugin + 1.7.0 + + + + + ${basedir}/src/main/resources/hello.tars + + + UTF-8 + + false + + UTF-8 + + ${basedir}/src/main/java + + com.tencent.tars.client. + + + +``` + +Some of the configurations are as follows: + +- tarsFiles: Indicate the location of the .tars file +- tarsFileCharset: Source file encoding format +- servant: true means to generate server code and Servant suffix interface, false means to generate client code and Prx suffix interface +- charset: The encoding format of the generated source code +- srcPath: Generated source code directory +- packagePrefixName: The package prefix of the generated source code + + + +## Server Tars file + +Take hello.tars on the server side in tars-quick-start as an example: + +```text +module TestApp +{ + interface Hello + { + string hello(int no, string name); + }; +}; +``` + +TestApp is the namespace, and all structs and interfaces must be in the namespace. + +When generating the server code, you need to set the servant tag in the tars-maven-plugin dependency in the pom.xml file to true and then run the `mvn tars: tars2java` command in the root directory of the project to obtain the interface file with the suffix Servant, HelloServant.java: + +```java +@Servant +public interface HelloServant { + + public String hello(int no, String name); +} +``` + +After that, the interface can be implemented according to the business logic. + + + +## Client Tars file + +When making a service call on the client, you first need to obtain the tars file on the server side, and then you need to set the servant tag in the tars-maven-plugin dependency in the pom.xml file to false when generating the client code. Finally run the `mvn tars: tars2java` command in the root directory of the project to obtain the interface file with the suffix Prx, HelloPrx.java: + +```java +@Servant +public interface HelloPrx { + + String hello(int no, String name); + + CompletableFuture promise_hello(int no, String name); + + String hello(int no, String name, @TarsContext java.util.Map ctx); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); +} +``` + +The interface provides three calling modes: + +- Synchronous call +- Asynchronous call +- Promise call + +### Synchronous invoke + +This is a blocking invoke method, the client will block until the server returns. + +### Asynchronous invoke + +In addition, HelloPrxCallback.java is also generated when the client code is generated, which is an abstract class for ordinary asynchronous callback processing: + +```java +public abstract class HelloPrxCallback extends TarsAbstractCallback { + + public abstract void callback_hello(String ret); + +} +``` + +This class extends the abstract class TarsAbstractCallback: + +```java +@TarsCallback(comment = "Callback") +public abstract class TarsAbstractCallback implements com.qq.tars.net.client.Callback { + + @Override + public final void onCompleted(TarsServantResponse response) { + TarsServantRequest request = response.getRequest(); + try { + Method callback = getCallbackMethod("callback_".concat(request.getFunctionName())); + callback.setAccessible(true); + callback.invoke(this, ((TarsCodec) response.getSession().getProtocolFactory().getDecoder()).decodeCallbackArgs(response)); + } catch (Throwable ex) { + throw new ClientException(ex); + } + } + + private Method getCallbackMethod(String methodName) throws NoSuchMethodException { + Method[] methods = getClass().getDeclaredMethods(); + for (Method method : methods) { + if (methodName.equals(method.getName())) { + return method; + } + } + throw new NoSuchMethodException("no such method " + methodName); + } + + @Override + public final void onException(Throwable ex) { + callback_exception(ex); + } + + @Override + public final void onExpired() { + callback_expired(); + } + + public abstract void callback_exception(Throwable ex); + + public abstract void callback_expired(); +} + +``` + +By implementing the callback_exception, callback_expired and callback_hello functions, the corresponding callback logic can be executed. + +- When receiving the return from the server, HelloPrxCallback's callback_hello will be responded. +- If the call returns an exception or timeout, then callback_exception will be called. + +### Promise invoke + +The asynchronous promise call is a new feature of Tars v1.7.0. This method returns a CompletableFuture object. CompletableFuture is a newly added class in jdk1.8. It implements the Future \ and CompletionStage \ interfaces and provides very powerful asynchronous programming functions. Before jdk1.8, we mainly used Future or registered callback function to complete asynchronous programming. However, these two methods have certain defects. When Future invokes get() to get the result, if the operation is not completed, it will wait all the time, which may cause a waste of CPU time. Furthermore, Future cannot complete chained calls, and cannot perform further operations on the results obtained from the previous Future. For the callback method, with the continuous nesting of callback functions, it will cause the phenomenon of callback pyramid. Therefore, CompletableFuture was introduced in Tars v1.7.0, which can perform a series of subsequent operations in a callback manner by registering triggers. + +The API of CompletabileFuture generally has two forms: the one with Async suffix and the one without Async suffix. The method without the Async suffix will be executed by the current calling thread, and the method with the Async suffix is divided into two cases. If Executor is passed in the parameter, a thread will be obtained from the Executor to execute the task. Otherwise, a thread obtained from the global ForkJoinPool.commonPool () will perform these tasks. diff --git a/docs-en/tars-tutorials.md b/docs-en/tars-tutorials.md new file mode 100644 index 00000000..54305bee --- /dev/null +++ b/docs-en/tars-tutorials.md @@ -0,0 +1,781 @@ +# Tars Service Tutorials + +This tutorial provides Java developers with basic development guidelines for Spring, Spring Boot and Spring Cloud of Tars, including the following aspects: + +- Add Tars dependency configuration. +- Define Tars interface file. +- Generate interface code using the tars-maven-plugin. +- Use Tars to write simple server and client services. + + + +## Tars-Spring instructions + +### Function Description + +Tars supports the use of Spring to configure servant, which needs to depend on the tars-spring.jar package, as well as the spring 4 and above. You can use your servant as a Spring bean, and you can use the function of Spring freely. Finally, you only need to tell Tars which bean is servant through the label provided by the Tars. + + + +### Demo + +[tars-spring-server](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-server) + + + +### Dependency configuration + +Using this function requires adding a dependency jar package and adding the following configuration in pom.xml: + +```xml + + com.tencent.tars + tars-spring + 1.6.1 + +``` + + + +### Service exposure configuration + +Using the spring configuration mode, you need to change the tars original configuration file servants.xml to servants-spring.xml under the resources directory.If all two configuration files exist, the spring mode will not be enabled if the servant.xml will be read first. + +#### Servant configuration + +In the Spring mode, servants-spring.xml is spring configuration file. The Tars's XSD file needs to be introduced first in the configuration file as follow: + +```xml + + + +``` + +Multiple spring tags are defined in Tars. When configuring servant, you need to define servant as a bean, and then define it as servant by the Tars tag. + +```xml + + +``` + +The servant tag specifies the name of the servant through the name. Ref specifies the corresponding bean name, and interface specifies the corresponding interface name. Of course, you can also get bean by adding a @Component tag and then bean is obtained by spring automatic scanning, as well as configuring a corresponding bean name: + +```xml + + +``` + +#### Listener configuration + +The configuration of listener is the same as that of the servant configuration, and you need to define your Listener as bean, and then the corresponding bean is specified as Listener through the Tars tag. + +```xml + + +``` + + + +### 1.3.0 Version update Guide + +If you need new functions like tars-spring, you need to upgrade the tars to the 1.3.0 version and the above version. As the change is relatively large, the version update guide is as follows: + +1. The management platform needs to be recompiled and upgraded. +2. Tars-node needs to be upgraded to a new version. +3. Modifying the classpath configuration item of the tars.tarsjava.default template in the template management to the following code: + +> classpath=${basepath}/conf:${basepath}/WEB-INF/classes:${basepath}/WEB-INF/lib + +4. When building a tars-java project, servants.xml needs to be placed under the resources directory. + + + +## Tars-Spring-Boot instructions + +### Function Description + +Tars supports writing tars services using spring boot. To use this function, you need to rely on the tars-spring-boot-starter.jar package, and Spring Boot 4.0 or above. You can use your servant as a Spring bean, and the annotation exposes the spring bean. + + + +### Demo + +[tars-spring-boot-server](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-boot-server) + +[tars-spring-boot-client](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-boot-client) + + + +### Environmental requirements + +- JDK1.8 or above + +- Maven 3.5 or above + +- Spring Boot 4.0 or above + + + +### Server development + +#### Project structure + +```text +├── pom.xml +└── src + └── main + ├── java + │ └── tars + │ └── testapp + │ ├── HelloServant.java + │ ├── QuickStartApplication.java + │ └── impl + │ └── HelloServantImpl.java + └── resources + └── hello.tars + +``` + + + +#### Dependency configuration + +The following configuration needs to be added in pom.xml: + +**Spring boot and Tars framework dependency** + +```xml + + 2.0.3.RELEASE + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + com.tencent.tars + tars-spring-boot-starter + 1.7.0 + + +``` + +**Plugin dependency** + +```xml + + + com.tencent.tars + tars-maven-plugin + 1.7.0 + + + + + ${basedir}/src/main/resources/hello.tars + + + UTF-8 + + true + + UTF-8 + + ${basedir}/src/main/java + + com.qq.tars.quickstart.server. + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + conf/ + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.qq.tars.quickstart.server.QuickStartApplication + + + + + repackage + + + +``` + + + +#### Service development + +##### Tars interface file definition + +Tars has its own interface file format. First, we need to define the Tars interface file. Create a new hello.tars file in the resources directory with the following content: + +```text +module TestApp +{ + interface Hello + { + string hello(int no, string name); + }; +}; +``` + +##### Interface file compilation + +Then we need to convert the Tars interface file to the server interface code using the tars-maven-plugin. In the project root directory, execute `mvn tars: tars2java` to get HelloServant.java, the content is as follows: + +```java +@Servant +public interface HelloServant { + + public String hello(int no, String name); +} +``` + +##### Interface implementation + +Next we need to implement the generated server interface. Create a new HelloServantImpl.java file, implement the HelloServant.java interface, and expose the service through the @TarsServant annotation, where 'HelloObj' is the servant name, corresponding to the name in the web management platform. + +```java +@TarsServant("HelloObj") +public class HelloServantImpl implements HelloServant { + + @Override + public String hello(int no, String name) { + return String.format("hello no=%s, name=%s, time=%s", no, name, System.currentTimeMillis()); + } +} +``` + +##### Tars service enabling + +Finally, add @EnableTarsServer annotation in the spring boot startup class QuickStartApplication to enable Tars service: + +```java +@SpringBootApplication +@EnableTarsServer +public class QuickStartApplication { + public static void main(String[] args) { + SpringApplication.run(QuickStartApplication.class, args); + } +} +``` + +##### Service packaging + +Using spring-boot-maven-plugin, execute `mvn package` in the root directory to package it into a jar. + + + +### Client development + +#### Project structure + +```text +├── pom.xml +└── src + └── main + ├── java + │ └── tars + │ └── testapp + │ ├── HelloPrx.java + │ ├── HelloPrxCallback.java + │ ├── App.java + │ └── impl + │ └── ClientServantImpl.java + └── resources + ├── hello.tars + └── client.tars + +``` + + + +#### Dependency configuration + +The following configuration needs to be added in pom.xml: + +**Spring boot and Tars framework dependency** + +```xml + + 2.0.3.RELEASE + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + com.tencent.tars + tars-spring-boot-starter + 1.7.0 + + +``` + +**Plugin dependency** + +```xml + + + com.tencent.tars + tars-maven-plugin + 1.7.0 + + + + + ${basedir}/src/main/resources/hello.tars + + + UTF-8 + + false + + UTF-8 + + ${basedir}/src/main/java + + com.tencent.tars.client. + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + conf/ + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.tencent.tars.App + + + + + repackage + + + +``` + + + +#### Service development + +##### Server interface file compilation + +After the server service development is completed, we first need to obtain the client interface code of the server service. Copy the hello.tars file on the server side to the resources directory, and execute `mvn tars: tars2java` in the project root directory to get HelloPrx.java. At this time, the proxy interface of the server service is obtained, and three calling methods are provided, namely synchronous call, asynchronous call and promise call. + +```java +@Servant +public interface HelloPrx { + + String hello(int no, String name); + + CompletableFuture promise_hello(int no, String name); + + String hello(int no, String name, @TarsContext java.util.Map ctx); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); +} +``` + +The promise call is a new feature of Tars v1.7.0. For specific use, please refer to the [Tars file reference](./tars-reference.md). + +##### Client interface file definition + +Then define the interface file of the client service. Create a new client.tars file in the resources directory with the following content: + +```text +module TestApp +{ + interface Client + { + string rpcHello(int no, string name); + }; +}; +``` + +##### Client interface file compilation + +Next, we need to use the tars-maven-plugin to generate client service interface code. Modify the tars2java plugin dependency of pom.xml as follows. Note that ` ` is set to true. + +```xml + + + com.tencent.tars + tars-maven-plugin + 1.7.0 + + + + + ${basedir}/src/main/resources/client.tars + + + UTF-8 + + true + + UTF-8 + + ${basedir}/src/main/java + + com.tencent.tars.client. + + + +``` + +In the root directory of the project, execute `mvn tars: tars2java` again to get ClientServant.java. The contents are as follows: + +```java +@Servant +public interface ClientServant { + public String rpcHello(int no, String name); +} +``` + +##### Interface implementation + +We need to implement the generated client service interface. Create a new ClientServantImpl.java file, implement the HelloServant.java interface, and expose the service through the @TarsServant annotation, where 'HelloObj' is the servant name, corresponding to the name in the web management platform. + +By adding the @TarsClient annotation to the client properties, the corresponding service can be automatically injected. If only the Obj name is filled, the default value is used to inject the client. In addition, the client configuration can be customized in the annotation, such as setting the synchronous call timeout time. + +```java +@TarsServant("ClientObj") +public class ClientServantImpl implements ClientServant { + @TarsClient("TestServer.HelloServer.HelloObj") + HelloPrx helloPrx; + + String res = ""; + + @Override + public String rpcHello(int no, String name) { + //sync call + String syncres = helloPrx.hello(1000, "Hello World"); + res += "sync_res: " + syncres + " "; + //async call + helloPrx.async_hello(new HelloPrxCallback() { + + @Override + public void callback_expired() { + } + + @Override + public void callback_exception(Throwable ex) { + } + + @Override + public void callback_hello(String ret) { + res += "async_res: " + ret + " "; + + } + }, 1000, "HelloWorld"); + //promise call + helloPrx.promise_hello(1000, "hello world").thenCompose(x -> { + res += "promise_res: " + x; + return CompletableFuture.completedFuture(0); + }); + return res; + } +} + +``` + +Configuration provided by annotation: + +```java +@Target({ ElementType.FIELD }) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface TarsClient { + @AliasFor("name") + String value() default ""; + + @AliasFor("value") + String name() default ""; + + String setDivision() default ""; + + int connections() default Constants.default_connections; + + int connectTimeout() default Constants.default_connect_timeout; + + int syncTimeout() default Constants.default_sync_timeout; + + int asyncTimeout() default Constants.default_async_timeout; + + boolean enableSet() default false; + + boolean tcpNoDelay() default false; + + String charsetName() default "UTF-8"; +} +``` + +##### Tars service enabling + +Finally, add @EnableTarsServer annotation in the spring boot startup class App to enable Tars service: + +```java +@SpringBootApplication +@EnableTarsServer +public class App { + public static void main( String[] args ){ + SpringApplication.run(App.class, args); + } +} +``` + +##### Service packaging + +Using spring-boot-maven-plugin, execute `mvn package` in the root directory to package it into a jar. + + + +## Tars Spring-Cloud instructions + +### Function description + +Tars-java is compatible with the Spring Cloud system, users can integrate the Tars-java into Spring Cloud. + + + +### Demo + +[Spring Cloud Server](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-cloud-server) + +[Spring Cloud Client](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-cloud-client) + + + +### Environmental dependence + +The following requirements should be met before operation. + +- JDK 1.8 or above. + +- If you want to use the discovery feature, you need an Eureka Server instance that has already run Spring Cloud. For details on how to start the configuration, please refer to the Spring Cloud related tutorial. + + + +### Service release + +Here are the steps to create and publish a service: + +- First, create a maven project and add dependency configuration to the project's pom.xml: + +```xml + + com.tencent.tars + tars-spring-cloud-starter + 1.6.1 + +``` + +- Write the Tars file and generate the server interface code. For the specific operation process, please refer to the service development part of the tars_java_quickstart.md document: + +```java +@Servant +public interface HelloServant { + + public String hello(int no, String name); +} +``` + +- After the interface code is generated, the interface needs to be implemented. Then add the @TarsServant annotation to the entire implementation class, indicating that the modified class is a Tars Servant, don't forget to identify the Servant name in the annotation as the client calls the Servant identifier. According to the Tars specification, the servant name should end with "Obj": + +```java +@TarsServant(name="HelloObj") +public class HelloServantImpl implements HelloServant { + + @Override + public String hello(int no, String name) { + return String.format("hello no=%s, name=%s, time=%s", no, name, System.currentTimeMillis()); + } +} +``` + +- Write the startup-class of service, using the spring boot startup method, and indicate that this is a Tars-java service by annotating @EnableTarsConfiguration and try to register the service into the Spring Cloud: + +```java +@SpringBootApplication +@EnableTarsConfiguration +public class Application { + + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} +``` + +- To write a Spring Cloud configuration file, you need to specify the address of the service registry and the information of the service itself in the configuration file. Create the configuration file application.yml in the resources directory. The example is as follows: + +```yml +eureka: + client: + serviceUrl: + #Service registry address + defaultZone: http://localhost:8761/eureka/ + +#The configuration under this tab is unique to Tars-java +tars: + #Server configuration + server: + #Server port + port: 18601 + #Application name, The specific meaning refers to the service naming chapter of tars_java_quickstart.md + application: TestApp + #Server name, The specific meaning refers to the service naming chapter of tars_java_quickstart.md + server-name: HelloJavaServer + #Specify the service log path, whichever is the case + log-path: /usr/local/tars-eureka-test/bin/log + #Specify data file path, whichever is the case + data-path: /usr/local/tars-eureka-test/data + #Client configuration + client: + async-invoke-timeout: 10000 + #Service discovery center address, generally the same as the registration center address, can be left blank + locator: http://localhost:8761/eureka/ +``` + +- Start the Application class, open the registry address [http://localhost:8761](http://localhost:8761/)(Based on your actual situation, this is the default address of Eureka), you can see that the Tars service is already registered on Eureka: + +![eureka-tars-java.png](images/eureka-tars-java.png) + + TESTAPP.HELLOJAVASERVER is the service we just registered, where TESTAPP corresponds to the application name in the configuration file(attributes corresponding to tars.server.application), HELLOJAVASERVER corresponds to the server name in the configuration file(attributes corresponding to tars.server.server-name). The name registered on Eureka is the application name of the configuration file plus the service name, separated by a '.'. The service name displayed on the Eureka page is all uppercase, but it is actually the name filled in our configuration file. + Eureka. + +So far, a service has been developed. + + + +### Access service + +Here's how to discover and access a service. + +- First create a maven project and add the following dependency configuration to the project's pom.xml file: + +```xml + + com.tencent.tars + tars-spring-cloud-starter + 1.6.1 + +``` + + +- Use the Tars file on the server to generate the client access interface. For details, refer to the client development part of the tars_java_quickstart.md file: + + +```java +@Servant +public interface HelloPrx { + + String hello(int no, String name); + + String hello(int no, String name, @TarsContext java.util.Map ctx); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); +} +``` + +- Write a startup class that uses spring boot as the startup method: + +```java +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + //use service... + } +} +``` + +- Write the configuration file application.yml and add the master related information: + +``` +eureka: + client: + serviceUrl: + #Service center address + defaultZone: http://localhost:8761/eureka/ + #The client does not need to register with the spring cloud master + register-with-eureka: false +``` + + ​ + +- By annotating @TarsClient to make the system automatically load clients to access the interface, you need to specify the name of the Obj object to be accessed by the name attribute of the annotation. The name consists of the application name + "." + service name + "." + servant name. The name in the example is the servant registered by the service above. The class holding the variable needs to be registered as a spring bean: + +```java +@Component +public class Client { + @TarsClient(name = "TestApp.HelloJavaServer.HelloObj") + private HelloPrx proxy; +} +``` + +- Call target method + + +```java +proxy.hello(10, "hello"); +``` + diff --git a/docs-en/tars_java_quickstart.md b/docs-en/tars_java_quickstart.md index 0aa32c43..d1246e03 100644 --- a/docs-en/tars_java_quickstart.md +++ b/docs-en/tars_java_quickstart.md @@ -1,9 +1,9 @@ # Contents # -> * [Environment construction] (#main-chapter-1) -> * [Service development] (#main-chapter-2) -> * [Management system] (#main-chapter-3) -> * [Service naming] (#main-chapter-4) -> * [Service deployment] (#main-chapter-5) +> * [Environment construction](#main-chapter-1) +> * [Service development](#main-chapter-2) +> * [Management system](#main-chapter-3) +> * [Service naming](#main-chapter-4) +> * [Service deployment](#main-chapter-5) # Quick start to the framework @@ -48,7 +48,7 @@ Add a dependency jar package by modifying pom.xml com.tencent.tars tars-server - 1.6.1 + 2.0.0 jar ``` @@ -59,7 +59,7 @@ Add a dependency jar package by modifying pom.xml com.tencent.tars tars-maven-plugin - 1.6.1 + 2.0.0 @@ -102,7 +102,7 @@ Tars provides plugins to compile and generate java code, only need to add java f com.tencent.tars tars-maven-plugin - 1.6.1 + 2.0.0 @@ -179,7 +179,7 @@ Execute "mvn package" in the project root directory to generate the war package, com.tencent.tars tars-client - 1.6.1 + 2.0.0 jar ``` @@ -190,7 +190,7 @@ Execute "mvn package" in the project root directory to generate the war package, com.tencent.tars tars-maven-plugin - 1.6.1 + 2.0.0 @@ -233,9 +233,13 @@ public interface HelloPrx { ```java public static void main(String[] args) { - CommunicatorConfig cfg = new CommunicatorConfig(); - //building a communicator + // startup from local + CommunicatorConfig cfg = new CommunicatorConfig(); + // use local communcator Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(cfg); + //Start from the Tars platform, using the following apis + //com.qq.tars.server.startup.Main(args); + //Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(); //generate proxy objects through the communicator HelloPrx proxy = communicator.stringToProxy(HelloPrx.class, "TestApp.HelloServer.HelloObj"); String ret = proxy.hello(1000, "HelloWorld"); @@ -246,9 +250,13 @@ public static void main(String[] args) { ``` public static void main(String[] args) { - CommunicatorConfig cfg = new CommunicatorConfig(); - //building a communicator + //Startup from local + CommunicatorConfig cfg = new CommunicatorConfig(); + //Use local communcator Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(cfg); + //Start from the Tars platform, using the following apis + //com.qq.tars.server.startup.Main(args); + //Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(); //generate proxy objects through the communicator HelloPrx proxy = communicator.stringToProxy(HelloPrx.class, "TestApp.HelloServer.HelloObj"); proxy.async_hello(new HelloPrxCallback() { diff --git a/docs-en/tars_java_spring.md b/docs-en/tars_java_spring.md index 1218ab00..a6b5d969 100644 --- a/docs-en/tars_java_spring.md +++ b/docs-en/tars_java_spring.md @@ -12,7 +12,7 @@ Using this function requires adding a dependency jar package and adding the foll com.tencent.tars tars-spring - 1.6.1 + 2.0.0 ``` diff --git a/docs-en/tars_java_spring_cloud.md b/docs-en/tars_java_spring_cloud.md index 1e6c048d..3ab63610 100644 --- a/docs-en/tars_java_spring_cloud.md +++ b/docs-en/tars_java_spring_cloud.md @@ -21,7 +21,7 @@ Here are the steps to create and publish a service: com.tencent.tars tars-spring-cloud-starter - 1.6.1 + 2.0.0 ``` @@ -109,7 +109,7 @@ Here's how to discover and access a service. com.tencent.tars tars-spring-cloud-starter - 1.6.1 + 2.0.0 ``` @@ -121,13 +121,13 @@ Here's how to discover and access a service. @Servant public interface HelloPrx { - public String hello(int no, String name); + String hello(int no, String name); - public String hello(int no, String name, @TarsContext java.util.Map ctx); + String hello(int no, String name, @TarsContext java.util.Map ctx); - public void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); - public void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); } ``` diff --git a/docs-en/tars_java_user_guide.md b/docs-en/tars_java_user_guide.md index 248b03e9..18741f03 100644 --- a/docs-en/tars_java_user_guide.md +++ b/docs-en/tars_java_user_guide.md @@ -21,7 +21,7 @@ Add dependent jar packages in the build project **pom.xml** com.tencent.tars tars-server - 1.6.1 + 2.0.0 jar ``` @@ -30,7 +30,7 @@ Add dependent jar packages in the build project **pom.xml** com.tencent.tars tars-maven-plugin - 1.6.1 + 2.0.0 @@ -65,7 +65,7 @@ Provide plug-in compile to generate java code, add java file configuration in ta com.tencent.tars tars-maven-plugin - 1.6.1 + 2.0.0 @@ -309,13 +309,13 @@ Asynchronous nesting represents the following: Normally, after receiving the request, B needs to return to A after the interface is processed, so it cannot be implemented if B also initiates an asynchronous request to C in the interface Therefore, it is necessary to declare startup asynchronism in the implementation interface method to achieve asynchronous calls across services. ​ - //Declarations start asynchronous context - AsyncContext context = AsyncContext.startAsync(); - //Interface implementation - ... - - //Back packet after asynchronous processing - context.writeResult(...); +​ //Declarations start asynchronous context +​ AsyncContext context = AsyncContext.startAsync(); +​ //Interface implementation +​ ... +​ +​ //Back packet after asynchronous processing +​ context.writeResult(...); ## Client development @@ -499,6 +499,12 @@ Note: > * When the server returns, the callback_hello of HelloPrxCallback will be responded. > * If the call returns an exception or timeout, the callback_exception will be called, and the value of RET is defined as follows. +#### Promise invoke + +The asynchronous promise call is a new feature of Tars v1.7.0. This method returns a CompletableFuture object. CompletableFuture is a newly added class in jdk1.8. It implements the Future \ and CompletionStage \ interfaces and provides very powerful asynchronous programming functions. Before jdk1.8, we mainly used Future or registered callback function to complete asynchronous programming. However, these two methods have certain defects. When Future calls get() to get the result, if the operation is not completed, it will wait all the time, which may cause a waste of CPU time. Furthermore, Future cannot complete chained calls, and cannot perform further operations on the results obtained from the previous Future. For the callback method, with the continuous nesting of callback functions, it will cause the phenomenon of callback pyramid. Therefore, CompletableFuture was introduced in Tars v1.7.0, which can perform a series of subsequent operations in a callback manner by registering triggers. + +The API of CompletabileFuture generally has two forms: the one with Async suffix and the one without Async suffix. The method without the Async suffix will be executed by the current calling thread, and the method with the Async suffix is divided into two cases. If Executor is passed in the parameter, a thread will be obtained from the Executor to execute the task. Otherwise, a thread obtained from the global ForkJoinPool.commonPool () will perform these tasks. + #### Set mode invoke At present, the framework has already supported the deployment of business in set mode. After set deployment, the calls between businesses are transparent to the business deveploment. But because some services have special needs, after deploying set, the client can specify the set name to invoke the server, so the framework increases the function of the client to specify the set name to invoke the service on the basis of the set deployment. @@ -566,6 +572,211 @@ Illustration: remote log service must be pre applied before long log. > * LogType.REMOTE: Only print remote logs > * LogType.All : Print local and remote logs +### Logback log system + +After TarsJava v1.7, Logback was used as the Tars log system. The configuration of Logback is very flexible and can provide users with more powerful log functions. + +#### Architecture + +Logback log system consists of three parts, namely Logger, Appender, Layout: + +- Logger: Each Logger is attached to a LoggerContext, which is used to generate Loggers and arrange them into a tree-like hierarchy. Logger is a named entity. Their names are case sensitive and follow hierarchical naming rules: + + > Named Hierarchy + > + > A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger. + + Loggers can be assigned different levels, namely TRACE, DEBUG, INFO, WARN and ERROR. If the effective level of the Logger is q and the request level of the log record is p, the log request will be executed only when p≥q. The default effective level of root Logger is DEBUG. + + > Level rules: TRACE < DEBUG < INFO < WARN < ERROR + +If no level is set for the Logger, then it will inherit an assigned level from its closest ancestor. A simple example is as follows: + +| Logger name | Assigned level | Effective level | +| ----------- | -------------- | --------------- | +| root | DEBUG | DEBUG | +| X | INFO | INFO | +| X.Y | none | INFO | +| X.Y.Z | none | INFO | + +- Appender: The component for writing log events, you can specify the log output to the console, files, remote servers, and databases. +- Layout: Format and output log information. + +#### Configuration + +Logback will first look for *logback-test.xml* and *logback.xml* configuration files in the class path. If it is not found, the default *BasicConfigurator* will be used. The basic structure of the configuration file can be described as, \ element, containing zero or more \ elements, followed by zero or more \ elements, followed by at most one \ element. The official document gives the structure of the configuration file as follows: + +![Logback-config](../docs/images/Logback-config.png) + +A typical logback.xml configuration file format is as follows: + +```xml + + + ${Logname} + + + + ··· + + + + ··· + + + + ··· + + +``` + +1. \ + +It provides three configuration options: + +- scan:true means that when the configuration file changes, the configuration file will be reloaded automatically, the default value is true. +- scanPeriod:The time interval for scanning the configuration file for changes. The default time unit is milliseconds. You can set the unit to milliseconds, seconds, minutes, or hours. +- debug:true means to print Logback internal log information, the default value is false. + +```xml + + ... + +``` + +2. \ + +It is used to set the name of LoggerContext. The default context name is "default". Once set, the context name cannot be changed. + +```xml +myAppName +``` + +3. \ + +You can use this variable to define variables in the configuration file, or you can load them in batches from external property files or external resources. The variable can then be used in the form of $ {variable name}. + +```xml + +``` + +4. \ + +The components responsible for writing log events. There are several common types + +- ConsoleAppender: Output log to console + + ```xml + + + %-4relative [%thread] %-5level %logger{35} - %msg %n + + + ``` + +- FileAppender: Output log to file + + ```xml + + + testFile.log + + true + + true + + %-4relative [%thread] %-5level %logger{35} - %msg%n + + + ``` + +- RollingFileAppender: You can first output the log to a specified file, and once a certain condition is met, then log to another file. (extends FileAppender class) + + ```xml + + logFile.log + + + logFile.%d{yyyy-MM-dd}.log + + + 30 + 3GB + + + + + %-4relative [%thread] %-5level %logger{35} - %msg%n + + + ``` + + In addition to the above time rolling strategy, there is also a **FixedWindowRollingPolicy**。 + +5. \ + +You can set the log printing level of a certain package or a specific class, and add appender. + +- name:Make a package or a class of logger constraints +- level:Assign print level +- addtivity:Whether to pass the print information to the superior logger, the default is true +- \:Add this appender to logger + +```xml + + + +``` + +6. \ + +It is also the \ element. Only the level attribute is used to set the print level, and you can also use to add appenders. + +```xml + + + +``` + +A complete logback.xml configuration is as follows: + +```xml + + + + myApp.log + + %date %level [%thread] %logger{10} [%file:%line] %msg%n + + + + + + %msg%n + + + + + + + + + + + +``` + +#### Logback usage + +You can obtain the corresponding logger by calling the LoggerFactory.getLogger method, and then use the logger to complete the log recording. + +```java +Logger logger = LoggerFactory.getLogger("name"); +logger.info("Hello World!"); +``` + +For more information on the use of Logback, please refer to [Logback Official Document](http://logback.qos.ch/manual/index.html). + ## Service management The service framework can support dynamic receiving commands to handle related business logic, such as dynamic update configuration, etc. @@ -588,7 +799,7 @@ The custom command sending mode of the service is sent through the custom comman Just register related commands and command processing classes, as follows: ```java -CustemCommandHelper.getInstance().registerCustemHandler("cmdName",new CommandHandler() { +CustomCommandHelper.getInstance().registerCustomHandler("cmdName",new CommandHandler() { ``` ```java @@ -645,14 +856,14 @@ There are two ways to dye logs: active opening and passive opening. - Active staining: > - If the requested client explicitly invokes the dyed opening interface in the framework, the intermediate logs are printed as the dyed logs from the opening switch to the dyed off interface in the explicit call frame. -> - When the dyeing function is opened, all the initiated TAF requests automatically pass the dyeing state, and the log generated after the request is received will also be printed as a dyed log. After the request is completed, the dyed switch of the transferred service will be automatically closed. +> - When the dyeing function is opened, all the initiated tars requests automatically pass the dyeing state, and the log generated after the request is received will also be printed as a dyed log. After the request is completed, the dyed switch of the transferred service will be automatically closed. The example code is as follows: ``` DyeingSwitch.enableActiveDyeing("helloServer"); //Open the switch interface automatically, and the parameter indicates the name of the dyed log. ...Business processing -logger.info("hello world"); //At this time, because of the color opening state, the log will print an extra copy to the dyed log. +loggerInnerImpl.info("hello world"); //At this time, because of the color opening state, the log will print an extra copy to the dyed log. ...Business processing DyeingSwitch.closeActiveDyeing(); //Active closure of dyed switch interface ``` @@ -662,6 +873,37 @@ Illustration: > - When the dyed log is opened, the parameter passed is recommended to fill in the service name. If it is null, the default name is default. > - The log level and log type of the dyed log are the same as the original log. If the original log is only local, the dyed log is only local, and the original log will be remote to play the long distance dyed log. +Logback is used as the logging system in the new version of TarsJava, so MDC can be used to dye the logs. MDC is a technology provided by Logback to record logs in multiple threads. It holds a ThreadLocal object inside which stores a Map, so users can add key-value pairs to it as needed. By implementing Filter and using MDC, dyeing of logs can be achieved: + +```java +public class MyFilter implements Filter { + private static final String TRACE_ID = "traceId"; + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + ... + boolean success = putMDC(...); + ... + try { + chain.doFilter(request, response); + } finally { + if(success) { + MDC.remove(TRACE_ID); + } + } + } + + private boolean putMDC(...) { + if (...){ + String traceId = ... + MDC.put(TRACE_ID, traceId); + return true; + } + return false; + } +``` + + + - Passive staining: > - When the requesting server presupposes the coloring condition, if the received request satisfies the dyeing condition, the server framework will automatically open the dye switch. diff --git a/docs-en/tars_tracing.md b/docs-en/tars_tracing.md index 9fd5b78c..e2a1862f 100644 --- a/docs-en/tars_tracing.md +++ b/docs-en/tars_tracing.md @@ -93,7 +93,7 @@ The integrated zipkin system is built in the framework, users can query call cha ## Tars-java Usage -At present, tars-java supports the call chain from version 1.6.1, and the cpp version is about to be released. The following is an example of integrated zipkin. +At present, tars-java supports the call chain from version 2.0.0, and the cpp version is about to be released. The following is an example of integrated zipkin. ### Enable the call chain @@ -137,7 +137,7 @@ Notes: > > com.tencent.tars > tars-core -> 1.6.1 +> 2.0.0 > > > org.apache.kafka diff --git a/docs/images/Logback-config.png b/docs/images/Logback-config.png new file mode 100644 index 00000000..9e88c644 Binary files /dev/null and b/docs/images/Logback-config.png differ diff --git a/docs/images/docker-hello-world.png b/docs/images/docker-hello-world.png new file mode 100644 index 00000000..9b4a50c2 Binary files /dev/null and b/docs/images/docker-hello-world.png differ diff --git a/docs/images/tars-chinese.png b/docs/images/tars-chinese.png new file mode 100644 index 00000000..f7bf81f5 Binary files /dev/null and b/docs/images/tars-chinese.png differ diff --git a/docs/images/tars-deployment-client.png b/docs/images/tars-deployment-client.png new file mode 100644 index 00000000..6e34d26b Binary files /dev/null and b/docs/images/tars-deployment-client.png differ diff --git a/docs/images/tars-deployment-http.png b/docs/images/tars-deployment-http.png new file mode 100644 index 00000000..6df55e12 Binary files /dev/null and b/docs/images/tars-deployment-http.png differ diff --git a/docs/images/tars-deployment.png b/docs/images/tars-deployment.png new file mode 100644 index 00000000..4830af33 Binary files /dev/null and b/docs/images/tars-deployment.png differ diff --git a/docs/images/tars-http-call.png b/docs/images/tars-http-call.png new file mode 100644 index 00000000..f345488e Binary files /dev/null and b/docs/images/tars-http-call.png differ diff --git a/docs/images/tars-pubjar-client.png b/docs/images/tars-pubjar-client.png new file mode 100644 index 00000000..cb499595 Binary files /dev/null and b/docs/images/tars-pubjar-client.png differ diff --git a/docs/images/tars-pubjar.png b/docs/images/tars-pubjar.png new file mode 100644 index 00000000..c28dcf12 Binary files /dev/null and b/docs/images/tars-pubjar.png differ diff --git a/docs/images/tars-publication.png b/docs/images/tars-publication.png new file mode 100644 index 00000000..bbfe2094 Binary files /dev/null and b/docs/images/tars-publication.png differ diff --git a/docs/images/tars-state-client.png b/docs/images/tars-state-client.png new file mode 100644 index 00000000..426047f6 Binary files /dev/null and b/docs/images/tars-state-client.png differ diff --git a/docs/images/tars-state.png b/docs/images/tars-state.png new file mode 100644 index 00000000..04899757 Binary files /dev/null and b/docs/images/tars-state.png differ diff --git a/docs/images/tars-tarstest-client.png b/docs/images/tars-tarstest-client.png new file mode 100644 index 00000000..44d00cb4 Binary files /dev/null and b/docs/images/tars-tarstest-client.png differ diff --git a/docs/images/tars-tarstest.png b/docs/images/tars-tarstest.png new file mode 100644 index 00000000..3e6a26db Binary files /dev/null and b/docs/images/tars-tarstest.png differ diff --git a/docs/images/tars-test-client.png b/docs/images/tars-test-client.png new file mode 100644 index 00000000..60eaebbc Binary files /dev/null and b/docs/images/tars-test-client.png differ diff --git a/docs/images/tars-test.png b/docs/images/tars-test.png new file mode 100644 index 00000000..894578cd Binary files /dev/null and b/docs/images/tars-test.png differ diff --git a/docs/images/tars-testclient.png b/docs/images/tars-testclient.png new file mode 100644 index 00000000..58ae7f54 Binary files /dev/null and b/docs/images/tars-testclient.png differ diff --git a/docs/images/tars-testserver.png b/docs/images/tars-testserver.png new file mode 100644 index 00000000..63788150 Binary files /dev/null and b/docs/images/tars-testserver.png differ diff --git a/docs/images/tars-uploadjar.png b/docs/images/tars-uploadjar.png new file mode 100644 index 00000000..20b79075 Binary files /dev/null and b/docs/images/tars-uploadjar.png differ diff --git a/docs/images/tars-uploadjarclient.png b/docs/images/tars-uploadjarclient.png new file mode 100644 index 00000000..ab476f33 Binary files /dev/null and b/docs/images/tars-uploadjarclient.png differ diff --git a/docs/images/tars-uploadtars-client.png b/docs/images/tars-uploadtars-client.png new file mode 100644 index 00000000..050c07c2 Binary files /dev/null and b/docs/images/tars-uploadtars-client.png differ diff --git a/docs/images/tars-uploadtars.png b/docs/images/tars-uploadtars.png new file mode 100644 index 00000000..0e78061a Binary files /dev/null and b/docs/images/tars-uploadtars.png differ diff --git a/docs/images/tarsjavastart-info.png b/docs/images/tarsjavastart-info.png new file mode 100644 index 00000000..9e20d768 Binary files /dev/null and b/docs/images/tarsjavastart-info.png differ diff --git a/docs/tars-http-server.md b/docs/tars-http-server.md new file mode 100644 index 00000000..9eb023a2 --- /dev/null +++ b/docs/tars-http-server.md @@ -0,0 +1,201 @@ +# Tars HTTP服务开发教程 + +## 功能说明 + +Tars平台支持HTTP服务的部署,使用@TarsHttpService注解即可将服务标记为HTTP服务。HTTP服务发布到平台后可以直接使用http请求来调用。 + + + +## 示例工程 + +[tars-spring-boot-http-server](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-boot-http-server) + + + +## 服务开发 + +### 工程目录 + +```text +├── pom.xml +└── src + └── main + ├── java + │ └── com.tecent.tars + | ├── App.java + │ ├── client.testapp + │ | ├── HelloPrx.java + │ | └── HelloPrxCallback.java + │ | + | └──http.server + │ └── HelloController.java + └── resources + └── hello.tars +``` + + + +### 依赖配置 + +在pom.xml文件中需要添加如下配置: + +**Spring Boot及Tars框架依赖** + +```xml + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + com.tencent.tars + tars-spring-boot-starter + 2.0.0 + + +``` + +**插件依赖** + +```xml + + + com.tencent.tars + tars-maven-plugin + 2.0.0 + + + + + ${basedir}/src/main/resources/hello.tars + + + UTF-8 + + false + + UTF-8 + + ${basedir}/src/main/java + + com.tencent.tars.client. + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + conf/ + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.tencent.tars.App + + + + + repackage + + + +``` + + + +### 服务开发 + +#### 使用插件生成服务端服务接口代码 + +服务端服务开发完成后,在客户端我们首先需要获得服务端服务的客户端接口代码。将服务端的hello.tars文件复制到resources目录下,并在工程根目录下,执行mvn tars:tars2java,即可得到HelloPrx.java。此时得到的是服务端服务的代理接口,并且提供了三种调用方式,分别为同步调用、异步调用和promise调用,具体内容如下: + +```java +@Servant +public interface HelloPrx { + + String hello(int no, String name); + + CompletableFuture promise_hello(int no, String name); + + String hello(int no, String name, @TarsContext java.util.Map ctx); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); +} +``` + + + +#### 编写Controller + +之后,编写Controller类来实现控制器。新建HelloController.java,并使用@TarsHttpService注解开启Tars HTTP服务。 + +```java +@TarsHttpService("HttpObj") +@RestController +public class HelloController { + @TarsClient("TestServer.HelloServer.HelloObj") + HelloPrx helloPrx; + + @RequestMapping("/hello") + public String testHello(@RequestParam Integer no){ + String ret = helloPrx.hello(no, "Hello World"); + return ret; + } +} +``` + + + +#### 开启Tars服务 + +最后,在Spring Boot启动类App中添加@EnableTarsServer注解来开启Tars服务: + +```java +@SpringBootApplication +@EnableTarsServer +public class App { + public static void main( String[] args ){ + SpringApplication.run(App.class, args); + } +} +``` + + + +#### 服务打包 + +通过spring-boot-maven-plugin,在根目录下执行mvn package即可打包为jar包进行部署。 + + + +## 服务发布 + +HTTP服务发布的的流程和[Tars服务发布](dev/tarsjava/tars-quick-start.md)的流程类似,区别在于服务部署的时候,协议选择非TARS协议,具体设置如下图所示: + +![tars-deployment-http](images/tars-deployment-http.png) + + + +## 服务调用 + +服务发布成功之后,即可通过http调用的方式来调用该服务,**注意IP地址为公网IP,非设置的内网的IP**: + +![tars-http-call](images/tars-http-call.png) \ No newline at end of file diff --git a/docs/tars-java-start.md b/docs/tars-java-start.md new file mode 100644 index 00000000..d1e8a234 --- /dev/null +++ b/docs/tars-java-start.md @@ -0,0 +1,52 @@ +# TarsJava脚手架自动生成工具 +此工具提供了TarsJava脚手架自动生成的功能。 + +通过此工具,可以生成服务端和客户端的TarsJava脚手架,快速开始Tars服务的开发。 + +## 1. 环境需求 +- JDK 1.8或以上版本 + +## 2. 安装与使用 +### 安装 + +直接将jar文件夹下的tars-java-tools-1.0.0.jar复制至工程目录即可使用,也可以按照如下步骤自行编译: + +- 将项目克隆至本地:`git clone https://github.com/TarsCloud/TarsJavaStart.git` + + 环境需求: + + - JDK 1.8或以上版本 + - Maven 3.5或以上版本 + - Spring Boot 4.0或以上版本 + +- 在项目根目录下执行maven打包:`mvn package` + +- 进入target目录后,将生成的jar包拷贝至工程目录 + +### 脚手架生成 + +在工程目录执行如下命令: + +```text +java -jar tars-java-start-1.0.0.jar --springboot.version=2.0.3 --maven.group=com.tencent.tars --maven.artifact=test-server --maven.name=TestServer --packagename=com.tencent.tars.server --jdk.version=1.8 --type=server +``` + +其中的参数为: + +- springboot.version:SpringBoot版本,默认值为2.0.3 +- maven.group:maven的项目groupId,默认值为com.tencent.tars +- maven.artifact:maven项目的artifactId,默认值为test-server +- maven.name:maven项目的Name,默认值为TestServer +- packagename:生成的包名,默认值为com.tencent.tars.server +- jdk.version:jdk版本,默认值为1.8 +- type:生成服务端/客户端脚手架,提供server和client选项,默认值为server + +命令执行后,会显示相关信息,出现Generating Complete则表示生成成功。 + +![tarsjavastart-info](images/tarsjavastart-info.png) + + + + +### 开发与发布 +服务端和客户端的开发可以参考[Tars服务开发指南](https://github.com/TarsCloud/TarsDocs/blob/master/dev/tarsjava/tars-tutorials.md)中的Tars-Spring-Boot服务开发,发布可参考[Tars快速入门](https://github.com/TarsCloud/TarsDocs/blob/master/dev/tarsjava/tars-quick-start.md)中的发布流程。 diff --git a/docs/tars-quick-start.md b/docs/tars-quick-start.md new file mode 100644 index 00000000..d662e104 --- /dev/null +++ b/docs/tars-quick-start.md @@ -0,0 +1,265 @@ +# Tars快速入门 + +本指南通过简单的服务端和客户端示例,使您快速入门Java中的Tars。 + +## Docker部署Tars + +本指南主要采用 Docker 来完成Tars的部署。 + +### 安装Docker + +ubuntu上安装docker流程如下: + +**1. 更新包索引** + +```text +sudo apt-get update +``` + +**2. 允许通过https安装** + +``` +sudo apt-get install apt-transport-https ca-certificates curl software-properties-common +``` + +**3. 添加Docker官方的GPG密钥:** + +``` +curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add +``` + +国内用户可使用腾讯云源: + +```text +curl -fsSL https://mirrors.cloud.tencent.com/docker-ce/linux/ubuntu/gpg | sudo apt-key add - +``` + +**4. 设置版本库类型** + +``` +sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" +``` + +国内用户可使用腾讯云源: + +```text +sudo add-apt-repository "deb [arch=amd64] https://mirrors.cloud.tencent.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable" +``` + +**5. 再次更新包索引** + +```text +sudo apt-get update +``` + +**6. 安装docker-ce** + +``` +sudo apt-get install docker-ce +``` + +**7. 测试是否安装成功** + +``` +docker run hello-world +``` + +![docker-hello-world](images/docker-hello-world.png) + +出现如上界面表示docker安装成功。 + + + +### 部署Tars + +**1. 创建Docker虚拟网络** + +```text +# 创建一个名为tars的桥接(bridge)虚拟网络,网关172.25.0.1,网段为172.25.0.0 +docker network create -d bridge --subnet=172.25.0.0/16 --gateway=172.25.0.1 tars +``` + +**2. Docker中启动MySQL** + +```text +docker run -d \ + --net=tars \ + -e MYSQL_ROOT_PASSWORD="123456" \ + --ip="172.25.0.2" \ + -v /data/framework-mysql:/var/lib/mysql \ + -v /etc/localtime:/etc/localtime \ + --name=tars-mysql \ + mysql:5.6 +``` + +**3. 使用tarscloud/tars:java部署** + +拉取容器镜像: + +```text +docker pull tarscloud/tars:java +``` + +启动容器: + +```text +docker run -d -it --name tars_java \ + --net=tars \ + --env DBIP=172.25.0.2 \ + --env DBPort=3306 \ + --env DBUser=root \ + --env DBPassword=123456 \ + -e INET=eth0 \ + --ip="172.25.0.3" \ + -p 3000:3000 \ + -p 18600-18700:18600-18700 \ + -v /data/tars_data:/data \ + tarscloud/tars:java +``` + +**注意:-p 18600-18700:18600-18700参数开放了 18600-18700 端口供应用使用,不够可自行添加。** + + + +容器启动后, 访问 `http://${你的机器IP}:3000` 即可打开 web管理平台,界面如下: + +![tars-chinese](images/tars-chinese.png) + +## 服务发布 + +### 下载示例并打包 + +依次执行以下命令: + +```text +# 克隆示例代码 +git clone https://github.com/TarsCloud/TarsJava.git +# 进入服务端目录 +cd TarsJava/examples/tars-spring-boot-server +# 打包服务端服务为jar包 +mvn package +# 进入客户端目录 +cd TarsJava/examples/tars-spring-boot-client +# 打包客户端服务为jar包 +mvn package +``` + + + +### 服务部署 + + 进入web管理平台,选择运维管理标签,分别对服务端和客户端服务如下图进行配置,一些参数如下: + +- 应用名:表示一组服务的集合 +- 服务名称:提供服务的进程名称 +- OBJ:提供具体服务的接口 + +系统通过应用名+服务名称+OBJ来定义服务在系统中的路由名称,例如TestServer.HelloServer.HelloObj + +- 服务类型:tars_java +- 模板:tars.springboot +- 节点:选择启动的Tars节点IP +- 端口:选择对外开放的端口 + +之后点击确定即可进行服务部署。 + +**服务端:** + +![tars-deployment](images/tars-deployment.png) + +**客户端:** + +![tars-deployment-client](images/tars-deployment-client.png) + + + +### 发布节点 + +服务部署成功后,刷新主页面后可以看到新增的两个服务,分别为服务端的HelloServer服务和客户端的HelloClient服务。 + +![tars-testclient](images/tars-testclient.png) + + + + + +分别选择服务端和客户端服务,进入发布管理,选中需要发布的节点,点击发布选中节点。 + +![tars-publication](images/tars-publication.png) + + + +之后点击上传发布包,并把对应的jar包上传。 + +**服务端:** + +![tars-uploadjar](images/tars-uploadjar.png) + +**客户端:** + +![tars-uploadjarclient](images/tars-uploadjarclient.png) + + + +上传完成后,会自动生成一个带有时间戳的版本号,选择该版本,点击发布。 + +**服务端:** + +![tars-pubjar](images/tars-pubjar.png) + +**客户端:** + +![tars-pubjar-client](images/tars-pubjar-client.png) + + + +发布成功后,回到服务管理界面可以看到当前状态为Active,即表示成功。 + +**服务端:** + +![tars-state](images/tars-state.png) + +**客户端:** + +![tars-state-client](images/tars-state-client.png) + + + +### 接口调试 + +进入接口调试界面,点击添加,在HelloServer服务中上传resources目录下的hello.tars文件,在HelloClient服务中上传client.tars文件。 + +**服务端:** + +![tars-uploadtar](images/tars-uploadtars.png) + +**客户端:** + +![tars-uploadtars-client](images/tars-uploadtars-client.png) + + + +上传完成后,在tars文件列表中会显示新增的服务,点击调试。 + +**服务端:** + +![tars-tarstest](images/tars-tarstest.png) + +**客户端:** + +![tars-tarstest-client](images/tars-tarstest-client.png) + + + +选择需要调试的方法,并输入入参,点击调试,即可获得方法出参。 + +**服务端:** + +![tars-test](images/tars-test.png) + +**客户端:** + +![tars-test-client](images/tars-test-client.png) + +至此,服务端和客户端部署完毕。 + diff --git a/docs/tars-reference.md b/docs/tars-reference.md new file mode 100644 index 00000000..1bcf54bc --- /dev/null +++ b/docs/tars-reference.md @@ -0,0 +1,177 @@ +# Tars接口文件 + +Tars协议是一种基于 IDL 实现的协议,与 Protocol Buffer 类似,它与语言无关,是一种类 C++ 标识符的语言,用于生成具体的服务接口文件。同时,作为一种二进制协议,相较于常见的 JSON 等文本协议,它的编解码效率更高、网络包占用空间更小。 + +Tars文件使用.tars作为扩展名,对于.tars文件中的每个服务,生成代码时都会对应产生一个Java接口,若为服务端接口代码生成时会加上Servant后缀,若为客户端接口则会加上Prx后缀。Tars语言的语法规则请参考[Tars协议](https://github.com/TarsCloud/TarsDocs/blob/master/base/tars-protocol.md) + + + +## Tars插件 + +Tars的maven插件需要在pom.xml文件中添加相关依赖: + +```xml + + + com.tencent.tars + tars-maven-plugin + 1.7.0 + + + + + ${basedir}/src/main/resources/hello.tars + + + UTF-8 + + true + + UTF-8 + + ${basedir}/src/main/java + + com.qq.tars.quickstart.server. + + + +``` + +其中的一些配置项如下: + +- tarsFiles:用于指示.tars文件的位置 +- tarsFileCharset:源文件的编码格式 +- servant:true表示生成服务端代码,即生成Servant为后缀的接口,false表示生成客户端代码,即生成Prx为后缀的接口 +- charset:生成的源代码的编码格式 +- srcPath:生成的源代码目录 +- packagePrefixName:生成的源代码的包前缀 + + + +## 服务端Tars文件 + +以tars-quick-start中服务端的hello.tars为例: + +```text +module TestApp +{ + interface Hello + { + string hello(int no, string name); + }; +}; +``` + +其中TestApp为名称空间,所有的struct,interface必须在名字空间中。 + +服务端代码生成时需要设置pom.xml文件中的tars-maven-plugin依赖的servant项为true,之后在工程的根目录下执行`mvn tars:tars2java`命令即可获得Servant为后缀的接口文件,HelloServant.java: + +```java +@Servant +public interface HelloServant { + + public String hello(int no, String name); +} +``` + +之后,根据业务逻辑来实现接口即可。 + + + +## 客户端Tars文件 + +在客户端进行服务调用时,首先需要获取服务端的tars文件,之后在客户端代码生成时需要设置pom.xml文件中的tars-maven-plugin依赖的servant项为false,之后在工程的根目录下执行`mvn tars:tars2java`命令即可获得Prx为后缀的接口文件,HelloPrx.java: + +```java +@Servant +public interface HelloPrx { + + String hello(int no, String name); + + CompletableFuture promise_hello(int no, String name); + + String hello(int no, String name, @TarsContext java.util.Map ctx); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); +} +``` + +接口提供了三种调用方式: + +- 同步调用 +- 异步调用 +- promise调用 + +### 同步调用 + +阻塞式的调用方式,客户端会一直阻塞至服务端结果返回。 + +### 异步调用 + +在客户端代码生成时还生成了HelloPrxCallback.java,这是一个普通异步回调处理的抽象类: + +```java +public abstract class HelloPrxCallback extends TarsAbstractCallback { + + public abstract void callback_hello(String ret); + +} +``` + +该类继承了TarsAbstractCallback这个抽象类: + +```java +@TarsCallback(comment = "Callback") +public abstract class TarsAbstractCallback implements com.qq.tars.net.client.Callback { + + @Override + public final void onCompleted(TarsServantResponse response) { + TarsServantRequest request = response.getRequest(); + try { + Method callback = getCallbackMethod("callback_".concat(request.getFunctionName())); + callback.setAccessible(true); + callback.invoke(this, ((TarsCodec) response.getSession().getProtocolFactory().getDecoder()).decodeCallbackArgs(response)); + } catch (Throwable ex) { + throw new ClientException(ex); + } + } + + private Method getCallbackMethod(String methodName) throws NoSuchMethodException { + Method[] methods = getClass().getDeclaredMethods(); + for (Method method : methods) { + if (methodName.equals(method.getName())) { + return method; + } + } + throw new NoSuchMethodException("no such method " + methodName); + } + + @Override + public final void onException(Throwable ex) { + callback_exception(ex); + } + + @Override + public final void onExpired() { + callback_expired(); + } + + public abstract void callback_exception(Throwable ex); + + public abstract void callback_expired(); +} + +``` + +通过实现callback_exception,callback_expired和callback_hello方法,可以执行相应的回调逻辑。 + +- 当接收到服务端返回时,HelloPrxCallback的callback_hello会被响应。 +- 如果调用返回异常或超时,则callback_exception会被调用。 + +### promise调用 + +异步的promise调用方式是Tars v1.7.0新增的功能,该方法返回了一个CompletableFuture对象。CompletableFuture是jdk1.8中新加入的类,它实现了Future\, CompletionStage\两个接口,提供了十分强大的异步编程功能。在jdk1.8之前主要采用Future或注册CallBack函数来完成异步编程,这两种方式均存在一定的缺陷。Future在调用get方法获取结果时,若操作尚未完成会一直进行等待,此时可能造成CPU时间的浪费。并且Future无法组合完成链式调用,不能为上一个Future获得的结果执行更进一步的操作。而CallBack方式随着回调函数的不断嵌套,则会造成回调金字塔的现象。因此,在Tars v1.7.0版本中引入了CompletableFuture,可以通过注册触发器以回调的方式执行一系列的后续操作。 + +CompletableFuture的API一般会有带Async后缀和不带Async后缀两种形式,不带Async后缀的方法会由当前的调用线程来执行任务,而带Async后缀的方法则分为两种情况,若在参数中传入了Executor,则会从传入的线程池获取一个线程去执行任务,否则从全局的 ForkJoinPool.commonPool()中获取一个线程中执行这些任务。 diff --git a/docs/tars-tutorials.md b/docs/tars-tutorials.md new file mode 100644 index 00000000..4dd3542b --- /dev/null +++ b/docs/tars-tutorials.md @@ -0,0 +1,777 @@ +# Tars服务开发教程 + +本教程为Java开发者提供了Tars的Spring、Spring Boot以及Spring Cloud的基本开发指南,主要包括以下几个方面: + +- 添加Tars依赖配置 +- 定义Tars接口文件 +- 使用Tars插件生成接口代码 +- 使用Tars编写简单的服务端和客户端服务 + + + +## Tars-Spring 使用说明 + +### 功能说明 + +Tars支持使用Spring配置servant,使用此功能需要依赖tars-spring.jar包,以及spring 4及以上版本。你可以将你的servant作为一个Spring bean,你可以自由的使用Spring的功能最后只需要通过Tars提供的标签告知Tars哪些些bean是servant即可。 + + + +### 示例工程 + +[tars-spring-server](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-server) + + + +### 依赖配置 + +使用此功能需要添加依赖jar包,在pom.xml中添加如下配置: + +```text + + com.tencent.tars + tars-spring + 1.7.0 + +``` + + + +### 服务暴露配置 + +使用spring配置模式需要在resources目录下将tars原版配置文件servants.xml改为servants-spring.xml,如果两种配置文件均存在会优先读取servant.xml则不会启用spring模式。 + + + +#### Servant配置 + +在Spring模式下,servants-spring.xml为spring配置文件,在配置文件中需要先引入Tars的xsd文件: + +```text + + + +``` + +Tars中自定义了多个spring标签,配置servant时需要先将servant定义为一个bean,然后通过Tars标签定义为servant: + +```text + + +``` + +servant标签通过name指定servant名称,ref指定对应的bean名,通过interface指定对应的接口名。当然你也可以通过添加@Component标签然后通过spring自动扫描获取到bean,同样只需要配置对应bean名即可: + +```text + + +``` + + + +#### Listener配置 + +listener的配置与servant配置相同,也需要将你的Listener定义为bean,然后通过tars标签将对应的bean指定为Listener: + +```text + + +``` + + + +### 1.3.0版本升级指南 + +如需使用tars-spring等新功能需要将tars升级到1.3.0版本及以上版本,本次改动相对较大,附上版本升级指南: + +1. 管理平台需要重新编译升级。 +2. tars-node需要升级到新版本。 +3. 在模版管理中修改tars.tarsjava.default模版的classpath配置项,修改为 + +> classpath=${basepath}/conf:${basepath}/WEB-INF/classes:${basepath}/WEB-INF/lib + +1. 在构建tars-java项目时servants.xml需要放在resources目录下 + + + +## Tars-Spring-Boot服务开发 + +### 功能说明 + +Tars支持使用通过spring boot的方式编写Tars服务,使用此功能需要依赖tars-spring-boot-starter.jar包,以及Spring Boot 4.0及以上版本。你可以将你的servant作为一个Spring bean,注解暴露spring bean即可。 + + + +### 示例工程 + +[tars-spring-boot-server](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-boot-server) + +[tars-spring-boot-client](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-boot-client) + + + +### 环境需求 + +- JDK 1.8或以上版本 +- Maven 3.5或以上版本 +- Spring Boot 4.0或以上版本 + + + +### 服务端开发 + +#### 工程目录 + +```text +├── pom.xml +└── src + └── main + ├── java + │ └── tars + │ └── testapp + │ ├── HelloServant.java + │ ├── QuickStartApplication.java + │ └── impl + │ └── HelloServantImpl.java + └── resources + └── hello.tars + +``` + + + +#### 依赖配置 + +在pom.xml文件中需要添加如下配置: + +**spring boot及框架依赖** + +```xml + + 2.0.3.RELEASE + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + com.tencent.tars + tars-spring-boot-starter + 1.7.0 + + +``` + +**插件依赖** + +```xml + + + com.tencent.tars + tars-maven-plugin + 1.7.0 + + + + + ${basedir}/src/main/resources/hello.tars + + + UTF-8 + + true + + UTF-8 + + ${basedir}/src/main/java + + com.qq.tars.quickstart.server. + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + conf/ + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.qq.tars.quickstart.server.QuickStartApplication + + + + + repackage + + + +``` + + + +#### 服务开发 + +##### Tars接口文件定义 + +Tars有自己的接口文件格式,首先我们需要定义Tars接口文件,在resources目录下新建hello.tars文件,内容如下: + +```text +module TestApp +{ + interface Hello + { + string hello(int no, string name); + }; +}; +``` + +##### 使用插件生成接口代码 + +然后我们需要通过Tars插件将Tars接口文件转换为服务端接口代码。在工程根目录下,执行mvn tars:tars2java,即可得到HelloServant.java,内容如下: + +```java +@Servant +public interface HelloServant { + + public String hello(int no, String name); +} +``` + +##### 实现接口 + +接着我们需要实现生成的服务端接口。新建HelloServantImpl.java文件,实现HelloServant.java接口,并通过@TarsServant注解来暴露服务,其中HelloObj为servant名称,与web管理平台中的名称对应。 + +```java +@TarsServant("HelloObj") +public class HelloServantImpl implements HelloServant { + + @Override + public String hello(int no, String name) { + return String.format("hello no=%s, name=%s, time=%s", no, name, System.currentTimeMillis()); + } +} +``` + +##### 开启Tars服务 + +最后,在Spring Boot启动类QuickStartApplication中添加@EnableTarsServer注解来开启Tars服务: + +```java +@SpringBootApplication +@EnableTarsServer +public class QuickStartApplication { + public static void main(String[] args) { + SpringApplication.run(QuickStartApplication.class, args); + } +} +``` + +##### 服务打包 + +通过spring-boot-maven-plugin,在根目录下执行mvn package即可打包为jar包进行部署。 + + + +### 客户端开发 + +#### 工程目录 + +```text +├── pom.xml +└── src + └── main + ├── java + │ └── tars + │ └── testapp + │ ├── HelloPrx.java + │ ├── HelloPrxCallback.java + │ ├── App.java + │ └── impl + │ └── ClientServantImpl.java + └── resources + ├── hello.tars + └── client.tars + +``` + + + +#### 依赖配置 + +在pom.xml文件中需要添加如下配置: + +**spring boot及框架依赖** + +```xml + + 2.0.3.RELEASE + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + com.tencent.tars + tars-spring-boot-starter + 1.7.0 + + +``` + +**插件依赖** + +```xml + + + com.tencent.tars + tars-maven-plugin + 1.7.0 + + + + + ${basedir}/src/main/resources/hello.tars + + + UTF-8 + + false + + UTF-8 + + ${basedir}/src/main/java + + com.tencent.tars.client. + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + conf/ + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.tencent.tars.App + + + + + repackage + + + +``` + + + +#### 服务开发 + +##### 使用插件生成服务端服务接口代码 + +服务端服务开发完成后,在客户端我们首先需要获得服务端服务的客户端接口代码。将服务端的hello.tars文件复制到resources目录下,并在工程根目录下,执行mvn tars:tars2java,即可得到HelloPrx.java。此时得到的是服务端服务的代理接口,并且提供了三种调用方式,分别为同步调用、异步调用和promise调用,具体内容如下: + +```java +@Servant +public interface HelloPrx { + + String hello(int no, String name); + + CompletableFuture promise_hello(int no, String name); + + String hello(int no, String name, @TarsContext java.util.Map ctx); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); +} +``` + +异步的promise调用方式是Tars v1.7.0新增的功能,具体使用可以参考[Tars接口文件](./tars-reference.md)。 + +##### Tars客户端接口文件定义 + +然后对客户端服务进行接口文件的定义。在resources目录下新建client.tars文件,内容如下: + +```text +module TestApp +{ + interface Client + { + string rpcHello(int no, string name); + }; +}; +``` + +##### 使用插件生成客户端服务接口代码 + +接着,使用Tars的maven插件生成客户端服务接口代码。修改pom.xml的tars2java插件依赖为,注意将``这一项设置为true。 + +```xml + + + com.tencent.tars + tars-maven-plugin + 1.7.0 + + + + + ${basedir}/src/main/resources/client.tars + + + UTF-8 + + true + + UTF-8 + + ${basedir}/src/main/java + + com.tencent.tars.client. + + + +``` + +在工程根目录下,重新执行mvn tars:tars2java,即可得到ClientServant.java,内容如下: + +```java +@Servant +public interface ClientServant { + public String rpcHello(int no, String name); +} +``` + +##### 实现接口 + +我们需要对生成的客户端服务接口进行实现。新建ClientServantImpl.java文件,实现ClientServant.java接口,并通过@TarsServant注解来暴露客户端服务,其中ClientObj为servant名称,与web管理平台中的名称对应。 + +通过给客户端属性添加@TarsClient注解,可以自动注入对应服务,如果只填写Obj名称则采用默认值注入客户端,此外也可以在注解中自定义客户端配置,例如设置同步调用超时时间等。 + +```java +@TarsServant("ClientObj") +public class ClientServantImpl implements ClientServant { + @TarsClient("TestServer.HelloServer.HelloObj") + HelloPrx helloPrx; + + String res = ""; + + @Override + public String rpcHello(int no, String name) { + //同步调用 + String syncres = helloPrx.hello(1000, "Hello World"); + res += "sync_res: " + syncres + " "; + //异步调用 + helloPrx.async_hello(new HelloPrxCallback() { + + @Override + public void callback_expired() { + } + + @Override + public void callback_exception(Throwable ex) { + } + + @Override + public void callback_hello(String ret) { + res += "async_res: " + ret + " "; + + } + }, 1000, "HelloWorld"); + //promise调用 + helloPrx.promise_hello(1000, "hello world").thenCompose(x -> { + res += "promise_res: " + x; + return CompletableFuture.completedFuture(0); + }); + return res; + } +} + +``` + +注解提供的配置项: + +```java +@Target({ ElementType.FIELD }) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface TarsClient { + @AliasFor("name") + String value() default ""; + + @AliasFor("value") + String name() default ""; + + String setDivision() default ""; + + int connections() default Constants.default_connections; + + int connectTimeout() default Constants.default_connect_timeout; + + int syncTimeout() default Constants.default_sync_timeout; + + int asyncTimeout() default Constants.default_async_timeout; + + boolean enableSet() default false; + + boolean tcpNoDelay() default false; + + String charsetName() default "UTF-8"; +} +``` + +##### 开启Tars服务 + +最后,在Spring Boot启动类App中添加@EnableTarsServer注解来开启Tars服务: + +```java +@SpringBootApplication +@EnableTarsServer +public class App { + public static void main( String[] args ){ + SpringApplication.run(App.class, args); + } +} +``` + +##### 服务打包 + +通过spring-boot-maven-plugin,在根目录下执行mvn package即可打包为jar包进行部署。 + + + +## Tars-Spring-Cloud 使用说明 + +### 功能说明 + + Tars-java支持兼容Spring Cloud系统,用户可以将Tars-Java框架融入Spring Cloud。 + + + +### 示例工程 + +[tars-spring-cloud-server](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-cloud-server) + +[tars-spring-cloud-client](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-cloud-client) + + + +### 环境依赖 + + 在操作前需要满足以下条件: + +* JDK 1.8或以上 +* 如果要想使用服务发现功能,需要已运行Spring Cloud的Eureka Server实例,具体配置启动方法请参考Spring Cloud相关教程。 + + + +### 发布服务 + +下面展示如何创建并发布一个服务。 + +* 首先添加创建一个maven工程,在项目的pom.xml文件中添加依赖配置: + +```text + + com.tencent.tars + tars-spring-cloud-starter + 1.6.1 + +``` + +* 编写接口Tars文件,生成服务端接口代码,具体操作过程参考tars\_java\_quickstart.md文档的服务开发部分。 + +```text +@Servant +public interface HelloServant { + + public String hello(int no, String name); +} +``` + +* 生成接口后需要对接口进行实现。实现接口中的方法,之后对整个实现类添加@TarsServant注解,该注解表明被修饰的类是一个Tars Servant,并需要在注解中表明该Servant名称,作为客户端调用Servant的标识,按照Tars规范,servant名称采用"Obj"结尾。 + +```text +@TarsServant(name="HelloObj") +public class HelloServantImpl implements HelloServant { + + @Override + public String hello(int no, String name) { + return String.format("hello no=%s, name=%s, time=%s", no, name, System.currentTimeMillis()); + } +} +``` + +* 编写服务启动类,采用spring boot的启动方式,并且通过注解@EnableTarsConfiguration表明Tars-Java服务,并会尝试向Spring Cloud注册中心注册服务。 + +```text +@SpringBootApplication +@EnableTarsConfiguration +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} +``` + +* 编写Spring Cloud配置文件,需要在配置文件中注明服务注册中心的地址和服务自身的信息等,在resources目录下的添加配置文件application.yml,示例如下: + +```text +eureka: + client: + serviceUrl: + #服务注册中心的地址 + defaultZone: http://localhost:8761/eureka/ + +#此标签下的都是tars-java特有的配置 +tars: + #服务端配置 + server: + #服务端口 + port: 18601 + #应用名称,具体含义参考tars_java_quickstart.md的服务命名章节 + application: TestApp + #服务名称,具体含义参考tars_java_quickstart.md的服务命名章节 + server-name: HelloJavaServer + #指定服务日志路径,以实际情况为准 + log-path: /usr/local/tars-eureka-test/bin/log + #指定数据文件路径,以实际情况为准 + data-path: /usr/local/tars-eureka-test/data + #客户端配置 + client: + async-invoke-timeout: 10000 + #服务发现中心地址,一般同注册中心地址,可不填 + locator: http://localhost:8761/eureka/ +``` + +* 启动Application类,打开注册中心地址[http://localhost:8761](http://localhost:8761/)(以自己的实际情况为准,这是Eureka默认地址),可以看到Tars服务已经注册在Eureka上了: + +![eureka-tars-java](images/eureka-tars-java.png) + +TESTAPP.HELLOJAVASERVER就是我们刚才注册的服务,其中TESTAPP对应配置文件中的应用名称(tars.server.application对应的属性),HELLOJAVASERVER对应配置文件中的服务名称(tars.server.server-name对应的属性)。Eureka上注册的名称为配置文件的应用名称加上服务名称,中间使用'.'号分割。Eureka页面上显示的服务名称为全部大写,但实际上还是我们配置文件中填写的名称。。 + +至此便开发完成了一个服务。 + + + +### 消费服务 + +下面展示如何发现并访问一个服务: + +* 首先添加创建一个maven工程,在项目的pom.xml文件中添加依赖配置 + + ```text + + com.tencent.tars + tars-spring-cloud-starter + 1.6.1 + + ``` + +* 使用服务端接口Tars文件生成客户端访问接口,具体操作过程参考tars\_java\_quickstart.md文档的客户端开发部分。 + +```text +@Servant +public interface HelloPrx { + + public String hello(int no, String name); + + public String hello(int no, String name, @TarsContext java.util.Map ctx); + + public void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + + public void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); +} +``` + +* 编写启动类,采用spring boot的启动方式。 + + ```text + @SpringBootApplication + public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + //消费服务... + } + } + ``` + +* 编写配置文件application.yml,添加主控相关信息: + + ```text + eureka: + client: + serviceUrl: + #服务注册中心的地址 + defaultZone: http://localhost:8761/eureka/ + #客户端不需要向spring cloud主控注册 + register-with-eureka: false + ``` + + + +* 通过注解@TarsClient来自动加载客户端访问接口,需要通过注解的name属性指定要访问的Obj对象名称,名称由访问目标servant的应用名+“.”+服务名+"."+servant名称三段组成。示例中的名称就是上面服务注册的servant。持有该变量的类需要注册为spring bean: + +```text +@Component +public class Client { + @TarsClient(name = "TestApp.HelloJavaServer.HelloObj") + private HelloPrx proxy; +} +``` + +* 调用目标方法 + +```text +proxy.hello(10, "hello"); +``` + diff --git a/docs/tars_java_quickstart.md b/docs/tars_java_quickstart.md index 9b410939..e526e4c0 100644 --- a/docs/tars_java_quickstart.md +++ b/docs/tars_java_quickstart.md @@ -46,7 +46,7 @@ com.tencent.tars tars-server - 1.6.1 + 2.0.0 jar ``` @@ -55,7 +55,7 @@ com.tencent.tars tars-maven-plugin - 1.6.1 + 2.0.0 @@ -91,7 +91,7 @@ module TestApp com.tencent.tars tars-maven-plugin - 1.6.1 + 2.0.0 @@ -159,7 +159,7 @@ public class HelloServantImpl implements HelloServant { com.tencent.tars tars-client - 1.6.1 + 2.0.0 jar ``` @@ -168,7 +168,7 @@ public class HelloServantImpl implements HelloServant { com.tencent.tars tars-maven-plugin - 1.6.1 + 2.0.0 @@ -207,9 +207,14 @@ public interface HelloPrx { - 同步调用 ```java public static void main(String[] args) { - CommunicatorConfig cfg = new CommunicatorConfig(); - //构建通信器 + // 从本地启动的配置 + CommunicatorConfig cfg = new CommunicatorConfig(); + // 从本地启动的Communcator Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(cfg); + //若是部署在tars平台启动的项目, 平台的communcator只能使用CommunicatorFactory.getInstance().getCommunicator()构造函数获取communcator + //且需要保证平台的框架都执行完成后(com.qq.tars.server.startup.Main) + //才可以得到平台构造的communcator + //Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(); //通过通信器,生成代理对象 HelloPrx proxy = communicator.stringToProxy(HelloPrx.class, "TestApp.HelloServer.HelloObj"); String ret = proxy.hello(1000, "HelloWorld"); @@ -219,9 +224,14 @@ public static void main(String[] args) { - 异步调用 ```java public static void main(String[] args) { - CommunicatorConfig cfg = new CommunicatorConfig(); - //构建通信器 + // 从本地启动的配置 + CommunicatorConfig cfg = new CommunicatorConfig(); + // 从本地启动的Communcator Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(cfg); + //若是部署在tars平台启动的项目, 平台的communcator只能使用CommunicatorFactory.getInstance().getCommunicator()构造函数获取communcator + //且需要保证平台的框架都执行完成后(com.qq.tars.server.startup.Main) + //才可以得到平台构造的communcator + //Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(); //通过通信器,生成代理对象 HelloPrx proxy = communicator.stringToProxy(HelloPrx.class, "TestApp.HelloServer.HelloObj"); proxy.async_hello(new HelloPrxCallback() { @@ -289,7 +299,8 @@ public static void main(String[] args) { -“服务类型”指你的服务程序用什么语言写的,例如:java的选择“tars_java”。 -“模版“ 指你的服务程序在启动时,设置的配置文件的名称,默认用”tars.tarsjavadefault“即可。 -“节点“ 指服务部署的机器IP。 - -“Set分组“ 指设置服务的Set分组信息,Set信息包括3部分:Set名、Set地区、Set组名。 + -“Set分组“ 指设置服务的Set分组信息,Set信息包括3部分:Set名、Set地区、Set组名。### 服务发布 + -“OBJ名称“ 指Servant的名称。 -“OBJ绑定IP“ 指服务绑定的机器IP,一般与节点一样。 -“端口“ 指OBJ要绑定的端口。 @@ -306,7 +317,6 @@ public static void main(String[] args) { 在管理系统上的部署暂时先到这里,到此为止,只是使你的服务在管理系统上占了个位置,真实程序尚未发布。 -### 服务发布 在管理系统的菜单树下,找到你部署的服务,点击进入服务页面。 diff --git a/docs/tars_java_spring.md b/docs/tars_java_spring.md index 55a013ac..78f56069 100644 --- a/docs/tars_java_spring.md +++ b/docs/tars_java_spring.md @@ -12,7 +12,7 @@ Tars支持使用Spring配置servant,使用此功能需要依赖tars-spring.jar com.tencent.tars tars-spring - 1.6.1 + 2.0.0 ``` diff --git a/docs/tars_java_spring_boot.md b/docs/tars_java_spring_boot.md index ae7d9957..3d036968 100644 --- a/docs/tars_java_spring_boot.md +++ b/docs/tars_java_spring_boot.md @@ -5,7 +5,7 @@ Tars支持使用通过spring boot的方式编写tars服务,使用此功能需要依赖tars-spring-boot-starter.jar包,以及spring boot 2.0及以上版本。你可以将你的servant作为一个Spring bean,注解暴露spring bean即可。 ## demo工程 -demo工程参考[demo工程](https://github.com/Tencent/Tars/tree/master/java/examples/tars-spring-boot-server) +demo工程参考[demo工程](https://github.com/TarsCloud/TarsJava/tree/master/examples/tars-spring-boot-server) ## 依赖配置 @@ -31,7 +31,7 @@ demo工程参考[demo工程](https://github.com/Tencent/Tars/tree/master/java/ex com.tencent.tars tars-spring-boot-starter - 1.6.1 + 2.0.0 ``` @@ -83,7 +83,7 @@ public class HelloServantImpl implements HelloServant { 接口的实现类通过注解@TarsServant来暴露服务,其中填写的'HelloObj'为servant名,该名称与管理平台上的名称对应即可。 ## 编写一个Http服务 -此外如果你想使用spring-boot来编写一个http服务,而不使用taf接口的话也是可以的: +此外如果你想使用spring-boot来编写一个http服务,而不使用tars接口的话也是可以的: ```java @SpringBootApplication @EnableTarsServer @@ -167,7 +167,7 @@ public @interface TarsClient { ## 版本升级指南 -如需使用tars-spring-boot的新功能需要将tars升级到1.6.1版本及以上版本,本次改动相对较大,附上版本升级指南: +如需使用tars-spring-boot的新功能需要将tars升级到 1.6.0版本及以上版本,本次改动相对较大,附上版本升级指南: 1. 管理平台需要重新编译升级。 2. tars-node需要升级到新版本。 3. 模板选择需要选tars.tarsjava.springboot模版。如果不是重新搭建环境可自行添加模板,父模板选择tars.tarsjava.default,内容如下: diff --git a/docs/tars_java_spring_cloud.md b/docs/tars_java_spring_cloud.md index c342461c..6cafc8ee 100644 --- a/docs/tars_java_spring_cloud.md +++ b/docs/tars_java_spring_cloud.md @@ -22,7 +22,7 @@ com.tencent.tars tars-spring-cloud-starter - 1.6.1 + 2.0.0 ``` @@ -110,7 +110,7 @@ tars: com.tencent.tars tars-spring-cloud-starter - 1.6.1 + 2.0.0 ``` diff --git a/docs/tars_java_user_guide.md b/docs/tars_java_user_guide.md index d3c9634b..f783a742 100644 --- a/docs/tars_java_user_guide.md +++ b/docs/tars_java_user_guide.md @@ -21,7 +21,7 @@ com.tencent.tars tars-server - 1.6.1 + 2.0.0 jar ``` @@ -30,7 +30,7 @@ com.tencent.tars tars-maven-plugin - 1.6.1 + 2.0.0 @@ -65,7 +65,7 @@ module TestApp com.tencent.tars tars-maven-plugin - 1.6.1 + 2.0.0 @@ -497,6 +497,12 @@ prx.async_hello(new HelloPrxCallback() { > * 当接收到服务端返回时,HelloPrxCallback的callback_hello会被响应。 > * 如果调用返回异常或超时,则callback_exception会被调用,ret的值定义如下: +#### promise调用 + +异步的promise调用方式是Tars v1.7.0新增的功能,该方法返回了一个CompletableFuture对象。CompletableFuture是jdk1.8中新加入的类,它实现了Future\, CompletionStage\两个接口,提供了十分强大的异步编程功能。在jdk1.8之前主要采用Future或注册CallBack函数来完成异步编程,这两种方式均存在一定的缺陷。Future在调用get方法获取结果时,若操作尚未完成会一直进行等待,此时可能造成CPU时间的浪费。并且Future无法组合完成链式调用,不能为上一个Future获得的结果执行更进一步的操作。而CallBack方式随着回调函数的不断嵌套,则会造成回调金字塔的现象。因此,在Tars v1.7.0版本中引入了CompletableFuture,可以通过注册触发器以回调的方式执行一系列的后续操作。 + +CompletableFuture的API一般会有带Async后缀和不带Async后缀两种形式,不带Async后缀的方法会由当前的调用线程来执行任务,而带Async后缀的方法则分为两种情况,若在参数中传入了Executor,则会从传入的线程池获取一个线程去执行任务,否则从全局的 ForkJoinPool.commonPool()中获取一个线程中执行这些任务。 + #### set方式调用 目前框架已经支持业务按set方式进行部署,按set部署之后,各个业务之间的调用对开业务发来说是透明的。但是由于有些业务有特殊需求,需要在按set部署之后,客户端可以指定set名称来调用服务端,因此框架则按set部署的基础上增加了客户端可以指定set名称去调用业务服务的功能。 @@ -564,6 +570,210 @@ private final static Logger FLOW_LOGGER = Logger.getLogger("flow", LogType.LOCAL > * LogType.REMOTE只打远程日志 > * LogType.All 打本地和远程日志 +#### Logback日志系统 + +TarsJava 1.7版本之后使用了Logback作为日志系统,Logback提供了十分灵活的配置项,可以为用户提供更加强大的日志功能。 + +##### 日志系统结构 + +Logback日志系统由三部分组成,分别是Logger, Appender, Layout: + +- Logger:日志记录器,每个Logger会附加到一个LoggerContext中,后者用于生成Logger,并将它们排列成树状层次结构。Logger是命名实体。它们的名称区分大小写,并且遵循分层命名规则: + + > 命名层次结构:如果一个记录器的名称后有一个点,则该记录器是另一个记录器的祖先,该记录器的名称是该子记录器名称的前缀。如果记录器与子记录器之间没有祖先,则称该记录器为子记录器的父级 + + Logger可以设置不同级别,分别是TRACE、DEBUG、INFO、WARN 和 ERROR。若Logger的有效级别为q,日志记录的请求级别为p,只有当p≥q时,该日志请求才会被执行。(root Logger 默认有效级别是 DEBUG) + + > 级别排序规则: TRACE < DEBUG < INFO < WARN < ERROR + + 如果没有为Logger设置一个级别,那么它将从其最接近的祖先那里继承一个已分配的级别,一个简单的示例如下: + + | Logger name | Assigned level | Effective level | + | ----------- | -------------- | --------------- | + | root | DEBUG | DEBUG | + | X | INFO | INFO | + | X.Y | none | INFO | + | X.Y.Z | none | INFO | + +- Appender:用于编写日志事件的组件,可以指定日志输出到控制台、文件、远程服务器以及数据库等。 + +- Layout:将日志信息进行格式化输出 + +##### 配置文件 + +Logback会首先会在类路径下寻找*logback-test.xml*和*logback.xml*配置文件,若没有找到,则会使用默认的*BasicConfigurator*。配置文件的基本结构为\元素中包含多个\和\元素和最多一个\元素,官方文档中给出了配置文件的结构图如下: + +![Logback-config](images/Logback-config.png) + +一个典型的logback.xml配置文件格式如下: + +```xml + + + ${Logname} + + + + ··· + + + + ··· + + + + ··· + + +``` + +1. \ + +\标签提供了三个配置选项: + +- scan:true表示当配置文件更改时,会自动重新加载配置文件,默认值为true +- scanPeriod:扫描配置文件是否发生更改的时间间隔,默认时间单位为毫秒,可以自行设置单位为毫秒、秒、分钟或者小时 +- debug:true表示打印Logback内部日志信息,默认值为false + +```xml + + ... + +``` + +2. \ + +用于设置LoggerContext的名称,默认的上下文名称为"default",一旦设置之后,上下文名字不能再被更改。 + +```xml +myAppName +``` + +3. \ + +使用该变量可以在配置文件中定义变量,也可以从外部属性文件或者外部资源中批量加载。之后通过${变量名}的形式可以调用该变量。 + +```xml + +``` + +4. \ + +负责写日志任务的组件,常用的有以下几类: + +- ConsoleAppender:将日志输出到控制台 + + ```xml + + + %-4relative [%thread] %-5level %logger{35} - %msg %n + + + ``` + +- FileAppender:将日志输出到文件 + + ```xml + + + testFile.log + + true + + true + + %-4relative [%thread] %-5level %logger{35} - %msg%n + + + ``` + +- RollingFileAppender:可以先将日志输出到指定文件,一旦满足某个条件时,再将日志记录到另一个文件。(FileAppender的子类) + + ```xml + + logFile.log + + + logFile.%d{yyyy-MM-dd}.log + + + 30 + 3GB + + + + + %-4relative [%thread] %-5level %logger{35} - %msg%n + + + ``` + + 除上述的时间滚动策略以外,还有固定窗口滚动策略**FixedWindowRollingPolicy**。 + +5. \ + +可以设置某一个包或者具体的某一个类的日志打印级别,并添加appender。 + +- name:制定logger约束的某一个包或某一个类 +- level:设置打印级别 +- addtivity:是否向上级logger传递打印信息,默认为true +- \:添加这个appender到logger + +```xml + + + +``` + +6. \ + +也是\元素,是根logger,仅有level一个属性用于设置打印级别,同时也可以使用来添加appender。 + +```xml + + + +``` + +一个完整的logback.xml配置如下: + +```xml + + + + myApp.log + + %date %level [%thread] %logger{10} [%file:%line] %msg%n + + + + + + %msg%n + + + + + + + + + + + +``` + +##### 日志使用 + +通过调用LoggerFactory.getLogger方法即可获取相应的日志记录器,之后使用记录器来完成来完成日志的记录。 + +```java +Logger logger = LoggerFactory.getLogger("name"); +logger.info("Hello World!"); +``` + +更多关于Logback的使用,请参考[Logback官方文档](http://logback.qos.ch/manual/index.html)。 + ## 服务管理 服务框架可以支持动态接收命令,来处理相关的业务逻辑,例如:动态更新配置等。 @@ -586,7 +796,7 @@ TARS服务框架目前内置命令: 只需注册相关命令以及命令处理类,如下 ```java -CustemCommandHelper.getInstance().registerCustemHandler("cmdName",new CommandHandler() { +CustomCommandHelper.getInstance().registerCustomHandler("cmdName",new CommandHandler() { ``` ```java @@ -644,14 +854,14 @@ NotifyHelper.getInstance().notifyError(info); - 主动染色: > - 在发起请求的客户端显式调用框架中的染色开启接口,从打开开关到显式调用框架中染色关闭接口,中间的日志都会额外打印为染色日志。 -> - 在开启染色功能时,所有的发起的taf请求都会自动传递染色状态,被调服务接收到请求后产生的日志也会打印为染色日志,在该请求处理完成后,会自动关闭被调服务的染色开关。 +> - 在开启染色功能时,所有的发起的tars请求都会自动传递染色状态,被调服务接收到请求后产生的日志也会打印为染色日志,在该请求处理完成后,会自动关闭被调服务的染色开关。 示例代码如下: ``` DyeingSwitch.enableActiveDyeing("helloServer"); //主动打开开关接口,参数表示染色日志名称 ...业务处理 -logger.info("hello world"); //此时出于染色开启状态,该条日志会额外打印一份到染色日志中 +loggerInnerImpl.info("hello world"); //此时出于染色开启状态,该条日志会额外打印一份到染色日志中 ...业务处理 DyeingSwitch.closeActiveDyeing(); //主动关闭染色开关接口 ``` @@ -661,6 +871,37 @@ DyeingSwitch.closeActiveDyeing(); //主动关闭染色开关接口 > - 开启染色日志时传递的参数推荐填写服务名,如果填写为null则默认名称为default; > - 染色日志的日志级别和日志类型与原本日志相同,如果原本日志只打本地,那么染色日志也只打本地,原本日志要打远程染色日志才会打远程; +在新版的TarsJava中使用了Logback作为日志系统,因此可以使用MDC来实现对日志的染色。MDC是Logback提供的在多线程中记录日志的一种技术,它的内部持有一个ThreadLocal对象,其中存储了一个Map,因此用户可以根据需要向其中添加键值对。通过实现Filter,配合MDC可以实现对日志的染色: + +```java +public class MyFilter implements Filter { + private static final String TRACE_ID = "traceId"; + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + ... + boolean success = putMDC(...); + ... + try { + chain.doFilter(request, response); + } finally { + if(success) { + MDC.remove(TRACE_ID); + } + } + } + + private boolean putMDC(...) { + if (...){ + String traceId = ... + MDC.put(TRACE_ID, traceId); + return true; + } + return false; + } +``` + + + - 被动染色: > - 在请求的服务端预设预先设定染色条件,如果接收到的请求满足染色条件,那么服务端框架层会自动打开染色开关; diff --git a/docs/tars_tracing.md b/docs/tars_tracing.md index ebabcc85..f4d03583 100644 --- a/docs/tars_tracing.md +++ b/docs/tars_tracing.md @@ -92,7 +92,7 @@ tars框架内部采用opentracing api来封装调用链数据采集功能,并 ## tars-java 使用方法 -目前tars -java从1.6.1版本开始支持调用链,cpp 版本即将放出,下面以集成zipkin为例介绍。 +目前tars -java从 2.0.0版本开始支持调用链,cpp 版本即将放出,下面以集成zipkin为例介绍。 ### 开启调用链 @@ -136,7 +136,7 @@ tars框架内部采用opentracing api来封装调用链数据采集功能,并 > > com.tencent.tars > tars-core -> 1.6.1 +> 2.0.0 > > > org.apache.kafka diff --git a/examples/build.gradle.kts b/examples/build.gradle.kts new file mode 100644 index 00000000..86372e63 --- /dev/null +++ b/examples/build.gradle.kts @@ -0,0 +1,36 @@ +// Parent module for examples +description = "Tars Examples - Example projects demonstrating Tars usage" + +// This is just a parent module, no source code +tasks.withType { + enabled = false +} + +tasks.withType { + enabled = false +} + +subprojects { + // Examples should not be published + tasks.withType { + enabled = false + } + tasks.withType { + enabled = false + } + + // Native examples need compilation enabled + val nativeProjects = listOf("tars-native-server", "tars-native-client") + if (project.name !in nativeProjects) { + // Disable compilation for old examples (they depend on generated code from .tars files) + tasks.withType { + enabled = false + } + tasks.withType { + enabled = false + } + tasks.withType { + enabled = false + } + } +} diff --git a/examples/pom.xml b/examples/pom.xml deleted file mode 100644 index d4fddea4..00000000 --- a/examples/pom.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - 4.0.0 - - com.tencent.tars - tars-parent - 1.6.1 - - tars-examples - ${project.artifactId} - pom - - - quickstart-client - quickstart-server - tars-spring-cloud-client - tars-spring-cloud-server - tars-spring-boot-server - tars-spring-server - - - - - junit - junit - 3.8.1 - test - - - \ No newline at end of file diff --git a/examples/quickstart-client/build.gradle.kts b/examples/quickstart-client/build.gradle.kts new file mode 100644 index 00000000..e5407e51 --- /dev/null +++ b/examples/quickstart-client/build.gradle.kts @@ -0,0 +1,12 @@ +plugins { + java +} + +description = "Tars Quickstart Client Example" + +dependencies { + implementation(project(":tars-core")) + implementation(project(":tars-netty")) + + testImplementation(libs.junit) +} diff --git a/examples/quickstart-client/pom.xml b/examples/quickstart-client/pom.xml deleted file mode 100644 index dc4674b7..00000000 --- a/examples/quickstart-client/pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - 4.0.0 - - com.tencent.tars - tars-parent - 1.6.1 - - tars-quickstart-client - ${project.artifactId} - war - - UTF-8 - - - - com.tencent.tars - tars-client - ${project.parent.version} - - - - webapp - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.1 - - 1.6 - 1.6 - UTF8 - - - - org.codehaus.plexus - plexus-compiler-javac - 1.8.1 - - - - - org.apache.maven.plugins - maven-war-plugin - 2.4 - - - - com.tencent.tars - tars-maven-plugin - ${project.parent.version} - - - - ${basedir}/src/main/resources/hello.tars - - UTF-8 - false - ${basedir}/src/main/java - UTF-8 - com.qq.tars.quickstart.client. - - - - - - diff --git a/examples/quickstart-client/src/main/java/com/qq/tars/quickstart/client/testapp/HelloPrx.java b/examples/quickstart-client/src/main/java/com/qq/tars/quickstart/client/testapp/HelloPrx.java index a482e7f4..4fd4c7fc 100644 --- a/examples/quickstart-client/src/main/java/com/qq/tars/quickstart/client/testapp/HelloPrx.java +++ b/examples/quickstart-client/src/main/java/com/qq/tars/quickstart/client/testapp/HelloPrx.java @@ -20,18 +20,22 @@ package com.qq.tars.quickstart.client.testapp; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.annotation.*; -import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsCallback; +import com.qq.tars.protocol.tars.annotation.TarsContext; + +import java.util.concurrent.CompletableFuture; @Servant public interface HelloPrx { - public String hello(int no, String name); + public String hello(int no, String name); + + CompletableFuture promise_hello(int no, String name); - public String hello(int no, String name, @TarsContext java.util.Map ctx); + public String hello(int no, String name, @TarsContext java.util.Map ctx); - public void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + public void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); - public void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); + public void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); } diff --git a/examples/quickstart-client/src/main/java/com/qq/tars/quickstart/domain/Main.java b/examples/quickstart-client/src/main/java/com/qq/tars/quickstart/domain/Main.java index ef55f64c..f9b76ef7 100644 --- a/examples/quickstart-client/src/main/java/com/qq/tars/quickstart/domain/Main.java +++ b/examples/quickstart-client/src/main/java/com/qq/tars/quickstart/domain/Main.java @@ -20,21 +20,30 @@ import com.qq.tars.client.CommunicatorFactory; import com.qq.tars.quickstart.client.testapp.HelloPrx; import com.qq.tars.quickstart.client.testapp.HelloPrxCallback; +import java.util.concurrent.CompletableFuture; +import java.util.logging.Level; +import java.util.logging.Logger; public class Main { - public static void main(String[] args) { + private static final Logger logger = Logger.getLogger(Main.class.getName()); + + public static void main(String[] args) throws InterruptedException { + // Start configuration locally CommunicatorConfig cfg = new CommunicatorConfig(); + // Start communicator locally Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(cfg); + //warn If the deployment is started on the tars, you can only use the following constructor to get the communicator + //Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(); HelloPrx proxy = communicator.stringToProxy(HelloPrx.class, "TestApp.HelloServer.HelloObj@tcp -h 127.0.0.1 -p 18601 -t 60000"); - //同步调用 + //Synchronous call String ret = proxy.hello(1000, "Hello World"); System.out.println(ret); - //单向调用 + //One-way call proxy.async_hello(null, 1000, "Hello World"); - //异步调用 + //Asynchronous call proxy.async_hello(new HelloPrxCallback() { @Override @@ -47,8 +56,16 @@ public void callback_exception(Throwable ex) { @Override public void callback_hello(String ret) { - System.out.println(ret); + Main.logger.log(Level.INFO, "invoke use async {0}", ret); + } }, 1000, "Hello World"); + + proxy.promise_hello(1000, "hello world").thenCompose(x -> { + logger.log(Level.INFO, "invoke use promise {0}", x); + return CompletableFuture.completedFuture(0); + }); + + Thread.sleep(1000l); } } diff --git a/examples/quickstart-server/build.gradle.kts b/examples/quickstart-server/build.gradle.kts new file mode 100644 index 00000000..3c3b4138 --- /dev/null +++ b/examples/quickstart-server/build.gradle.kts @@ -0,0 +1,13 @@ +plugins { + java + war +} + +description = "Tars Quickstart Server Example" + +dependencies { + implementation(project(":tars-core")) + implementation(project(":tars-netty")) + + testImplementation(libs.junit) +} diff --git a/examples/quickstart-server/pom.xml b/examples/quickstart-server/pom.xml deleted file mode 100644 index c9f80440..00000000 --- a/examples/quickstart-server/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - 4.0.0 - - com.tencent.tars - tars-parent - 1.6.1 - - tars-quickstart-server - ${project.artifactId} - war - - UTF-8 - 2.2.1 - 3.2 - - - - com.tencent.tars - tars-core - ${project.parent.version} - jar - - - - webapp - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.1 - - 1.6 - 1.6 - UTF8 - - - - org.codehaus.plexus - plexus-compiler-javac - 1.8.1 - - - - - org.apache.maven.plugins - maven-war-plugin - 2.4 - - - - com.tencent.tars - tars-maven-plugin - ${project.parent.version} - - - - ${basedir}/src/main/resources/hello.tars - - UTF-8 - true - ${basedir}/src/main/java - UTF-8 - com.qq.tars.quickstart.server. - - - - - - diff --git a/examples/quickstart-server/src/main/java/com/qq/tars/quickstart/server/testapp/HelloServant.java b/examples/quickstart-server/src/main/java/com/qq/tars/quickstart/server/testapp/HelloServant.java index 9a3971ae..d0c2cf6b 100644 --- a/examples/quickstart-server/src/main/java/com/qq/tars/quickstart/server/testapp/HelloServant.java +++ b/examples/quickstart-server/src/main/java/com/qq/tars/quickstart/server/testapp/HelloServant.java @@ -1,18 +1,3 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ // ********************************************************************** // This file was generated by a TARS parser! // TARS version 1.0.1. @@ -20,12 +5,9 @@ package com.qq.tars.quickstart.server.testapp; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.annotation.*; -import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; @Servant public interface HelloServant { - - public String hello(int no, String name); + public String hello(int no, String name); } diff --git a/examples/quickstart-server/src/main/resources/hello.tars b/examples/quickstart-server/src/main/resources/hello.tars index da273654..3f39a64f 100644 --- a/examples/quickstart-server/src/main/resources/hello.tars +++ b/examples/quickstart-server/src/main/resources/hello.tars @@ -16,8 +16,42 @@ module TestApp { + enum ENUM_TYPE { + ET_A, + ET_B, + }; + + struct TestInfo + { + 0 optional byte c = 1; + 1 optional short i1 = 2; + 2 optional int i2 = 3; + 3 optional long l = 4; + 4 optional float f = 5.0f; + 5 optional double d = 6.1d; + 6 optional string s = "test"; + 7 optional vector vs; + 8 optional map ms; + 9 optional vector vd; + 10 optional map mfd; + 11 optional ENUM_TYPE et; + 12 optional bool b = true; + 13 optional bool is = false; + 14 optional bool isBool = true; + 15 optional bool isbool = false; + 16 require string rstr; + }; + + struct TestInfoEx + { + 0 optional TestInfo bi; + 1 optional vector vbi; + 2 optional map mbi; + }; + interface Hello { string hello(int no, string name); + int helloJson(TestInfo tie, out TestInfoEx otie); }; -}; \ No newline at end of file +}; diff --git a/examples/quickstart-server/src/main/resources/logback.xml b/examples/quickstart-server/src/main/resources/logback.xml new file mode 100644 index 00000000..81d92dfa --- /dev/null +++ b/examples/quickstart-server/src/main/resources/logback.xml @@ -0,0 +1,149 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + ${LOG_HOME}/info.%d{yyyy-MM-dd}.log + 30 + + + INFO + ACCEPT + DENY + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + ${LOG_HOME}/warn.%d{yyyy-MM-dd}.log + 30 + + + WARN + ACCEPT + DENY + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + + ERROR + ACCEPT + DENY + + + ${LOG_HOME}/error.%d{yyyy-MM-dd}.log + 30 + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + + DEBUG + ACCEPT + DENY + + + ${LOG_HOME}/debug.%d{yyyy-MM-dd}.log + 30 + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + DEBUG + ACCEPT + DENY + + + ${LOG_HOME}/tars_client.%d{yyyy-MM-dd}.log + 30 + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + DEBUG + ACCEPT + DENY + + + ${LOG_HOME}/tars_om_client.%d{yyyy-MM-dd}.log + 30 + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + 30 + 512 + + + + 30 + 512 + + + + 30 + 512 + + + + 30 + 512 + + + + 30 + 512 + + + + 30 + 512 + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/stress-server/build.gradle.kts b/examples/stress-server/build.gradle.kts new file mode 100644 index 00000000..edda7bf2 --- /dev/null +++ b/examples/stress-server/build.gradle.kts @@ -0,0 +1,12 @@ +plugins { + java + war +} + +description = "Tars Stress Server Example" + +dependencies { + implementation(project(":tars-core")) + + testImplementation(libs.junit) +} diff --git a/examples/stress-server/pom.xml b/examples/stress-server/pom.xml deleted file mode 100644 index 1a884c40..00000000 --- a/examples/stress-server/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - 4.0.0 - - com.tencent.tars - tars-parent - 1.6.1 - - tars-stress-server - ${project.artifactId} - war - - UTF-8 - 2.2.1 - 3.2 - - - - com.tencent.tars - tars-server - ${project.parent.version} - jar - - - - webapp - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.1 - - 1.6 - 1.6 - UTF-8 - - - - org.codehaus.plexus - plexus-compiler-javac - 1.8.1 - - - - - org.apache.maven.plugins - maven-war-plugin - 2.4 - - - - com.tencent.tars - tars-maven-plugin - ${project.parent.version} - - - - ${basedir}/src/main/resources/stress.tars - - UTF-8 - true - ${basedir}/src/main/java - UTF-8 - com.qq.tars.stress.server. - - - - - - diff --git a/examples/tars-native-client/build.gradle.kts b/examples/tars-native-client/build.gradle.kts new file mode 100644 index 00000000..abaec57b --- /dev/null +++ b/examples/tars-native-client/build.gradle.kts @@ -0,0 +1,31 @@ +plugins { + java + application + id("org.graalvm.buildtools.native") +} + +description = "Tars Native Client Example - GraalVM Native Image" + +application { + mainClass.set("com.qq.tars.example.native_client.NativeClientMain") +} + +dependencies { + implementation(project(":tars-core")) + implementation(project(":tars-netty")) + + testImplementation(libs.junit) +} + +graalvmNative { + binaries { + named("main") { + mainClass.set("com.qq.tars.example.native_client.NativeClientMain") + buildArgs.addAll( + "--no-fallback", + "-H:+ReportExceptionStackTraces", + "-H:+AddAllCharsets" + ) + } + } +} diff --git a/examples/tars-native-client/src/main/java/com/qq/tars/example/native_client/HelloPrx.java b/examples/tars-native-client/src/main/java/com/qq/tars/example/native_client/HelloPrx.java new file mode 100644 index 00000000..9a20157e --- /dev/null +++ b/examples/tars-native-client/src/main/java/com/qq/tars/example/native_client/HelloPrx.java @@ -0,0 +1,36 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + */ +package com.qq.tars.example.native_client; + +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsMethodParameter; + +/** + * Hello服务代理接口 - 用于GraalVM Native Image演示 + */ +@Servant +public interface HelloPrx { + + /** + * 简单的hello方法 + * @param name 名称 + * @return 问候语 + */ + String hello(@TarsMethodParameter(name = "name") String name); + + /** + * 加法运算 + * @param a 第一个数 + * @param b 第二个数 + * @return 两数之和 + */ + int add(@TarsMethodParameter(name = "a") int a, @TarsMethodParameter(name = "b") int b); +} diff --git a/examples/tars-native-client/src/main/java/com/qq/tars/example/native_client/NativeClientMain.java b/examples/tars-native-client/src/main/java/com/qq/tars/example/native_client/NativeClientMain.java new file mode 100644 index 00000000..5bf0dde3 --- /dev/null +++ b/examples/tars-native-client/src/main/java/com/qq/tars/example/native_client/NativeClientMain.java @@ -0,0 +1,71 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + */ +package com.qq.tars.example.native_client; + +import com.qq.tars.client.Communicator; +import com.qq.tars.client.CommunicatorConfig; +import com.qq.tars.client.CommunicatorFactory; + +/** + * GraalVM Native Image 客户端示例 + * + * 编译命令: + * ./gradlew :examples:tars-native-client:nativeCompile + * + * 运行: + * ./examples/tars-native-client/build/native/nativeCompile/tars-native-client + */ +public class NativeClientMain { + + private static final String SERVER_HOST = "127.0.0.1"; + private static final int SERVER_PORT = 18601; + + public static void main(String[] args) { + System.out.println("========================================"); + System.out.println("Tars Native Client Starting..."); + System.out.println("Server: " + SERVER_HOST + ":" + SERVER_PORT); + System.out.println("========================================"); + + try { + // 创建通信器配置 + CommunicatorConfig config = new CommunicatorConfig(); + + // 创建通信器 + Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(config); + + // 构建服务地址 + String objectName = "TestApp.HelloServer.HelloObj@tcp -h " + SERVER_HOST + " -p " + SERVER_PORT; + + // 创建代理 + HelloPrx helloPrx = communicator.stringToProxy(HelloPrx.class, objectName); + + System.out.println("========================================"); + System.out.println("Calling remote methods..."); + System.out.println("========================================"); + + // 调用hello方法 + String helloResult = helloPrx.hello("GraalVM Native"); + System.out.println("hello('GraalVM Native') = " + helloResult); + + // 调用add方法 + int addResult = helloPrx.add(100, 200); + System.out.println("add(100, 200) = " + addResult); + + System.out.println("========================================"); + System.out.println("All tests passed!"); + System.out.println("========================================"); + + } catch (Exception e) { + System.err.println("Error: " + e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/examples/tars-native-client/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-client/native-image.properties b/examples/tars-native-client/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-client/native-image.properties new file mode 100644 index 00000000..ee4fe3b9 --- /dev/null +++ b/examples/tars-native-client/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-client/native-image.properties @@ -0,0 +1,7 @@ +Args = --initialize-at-build-time=com.google.common \ + --initialize-at-build-time=io.netty \ + --initialize-at-run-time=io.netty.channel.epoll \ + --initialize-at-run-time=io.netty.channel.kqueue \ + --initialize-at-run-time=io.netty.channel.unix \ + --initialize-at-run-time=io.netty.handler.ssl \ + --initialize-at-run-time=io.netty.internal.tcnative diff --git a/examples/tars-native-client/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-client/proxy-config.json b/examples/tars-native-client/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-client/proxy-config.json new file mode 100644 index 00000000..6b2c2ec0 --- /dev/null +++ b/examples/tars-native-client/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-client/proxy-config.json @@ -0,0 +1,8 @@ +[ + { + "interfaces": [ + "com.qq.tars.example.native_client.HelloPrx", + "com.qq.tars.client.ServantProxy" + ] + } +] diff --git a/examples/tars-native-client/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-client/reflect-config.json b/examples/tars-native-client/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-client/reflect-config.json new file mode 100644 index 00000000..f7070c1c --- /dev/null +++ b/examples/tars-native-client/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-client/reflect-config.json @@ -0,0 +1,99 @@ +[ + { + "name": "com.qq.tars.example.native_client.HelloPrx", + "allDeclaredConstructors": true, + "allDeclaredMethods": true, + "allPublicMethods": true + }, + { + "name": "com.qq.tars.example.native_client.NativeClientMain", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + + { + "name": "com.qq.tars.rpc.netty.NettyClientHandler", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.rpc.netty.NettyServerHandler", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.rpc.netty.TarsDecoder", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.rpc.netty.TarsEncoder", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + + { + "name": "io.netty.channel.ChannelHandlerAdapter", + "allDeclaredMethods": true + }, + { + "name": "io.netty.channel.ChannelInboundHandlerAdapter", + "allDeclaredMethods": true + }, + { + "name": "io.netty.channel.ChannelOutboundHandlerAdapter", + "allDeclaredMethods": true + }, + { + "name": "io.netty.channel.ChannelDuplexHandler", + "allDeclaredMethods": true + }, + { + "name": "io.netty.handler.codec.ByteToMessageDecoder", + "allDeclaredMethods": true + }, + { + "name": "io.netty.handler.codec.MessageToByteEncoder", + "allDeclaredMethods": true + }, + { + "name": "io.netty.handler.timeout.IdleStateHandler", + "allDeclaredMethods": true + }, + + { + "name": "com.qq.tars.protocol.annotation.Servant", + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.protocol.tars.annotation.TarsMethodParameter", + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.protocol.tars.annotation.TarsMethod", + "allDeclaredMethods": true + }, + + { + "name": "com.qq.tars.rpc.protocol.tars.TarsServantRequest", + "allDeclaredConstructors": true, + "allDeclaredMethods": true, + "allDeclaredFields": true + }, + { + "name": "com.qq.tars.rpc.protocol.tars.TarsServantResponse", + "allDeclaredConstructors": true, + "allDeclaredMethods": true, + "allDeclaredFields": true + }, + { + "name": "com.qq.tars.client.ServantProxy", + "allDeclaredMethods": true, + "allPublicMethods": true + }, + { + "name": "com.qq.tars.client.ObjectProxy", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + } +] diff --git a/examples/tars-native-server/build.gradle.kts b/examples/tars-native-server/build.gradle.kts new file mode 100644 index 00000000..6bf43b7f --- /dev/null +++ b/examples/tars-native-server/build.gradle.kts @@ -0,0 +1,31 @@ +plugins { + java + application + id("org.graalvm.buildtools.native") +} + +description = "Tars Native Server Example - GraalVM Native Image" + +application { + mainClass.set("com.qq.tars.example.native_server.NativeServerMain") +} + +dependencies { + implementation(project(":tars-core")) + implementation(project(":tars-netty")) + + testImplementation(libs.junit) +} + +graalvmNative { + binaries { + named("main") { + mainClass.set("com.qq.tars.example.native_server.NativeServerMain") + buildArgs.addAll( + "--no-fallback", + "-H:+ReportExceptionStackTraces", + "-H:+AddAllCharsets" + ) + } + } +} diff --git a/examples/tars-native-server/src/main/java/com/qq/tars/example/native_server/HelloServant.java b/examples/tars-native-server/src/main/java/com/qq/tars/example/native_server/HelloServant.java new file mode 100644 index 00000000..96c16e69 --- /dev/null +++ b/examples/tars-native-server/src/main/java/com/qq/tars/example/native_server/HelloServant.java @@ -0,0 +1,36 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + */ +package com.qq.tars.example.native_server; + +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsMethodParameter; + +/** + * Hello服务接口 - 用于GraalVM Native Image演示 + */ +@Servant +public interface HelloServant { + + /** + * 简单的hello方法 + * @param name 名称 + * @return 问候语 + */ + String hello(@TarsMethodParameter(name = "name") String name); + + /** + * 加法运算 + * @param a 第一个数 + * @param b 第二个数 + * @return 两数之和 + */ + int add(@TarsMethodParameter(name = "a") int a, @TarsMethodParameter(name = "b") int b); +} diff --git a/examples/tars-native-server/src/main/java/com/qq/tars/example/native_server/HelloServantImpl.java b/examples/tars-native-server/src/main/java/com/qq/tars/example/native_server/HelloServantImpl.java new file mode 100644 index 00000000..b65b773d --- /dev/null +++ b/examples/tars-native-server/src/main/java/com/qq/tars/example/native_server/HelloServantImpl.java @@ -0,0 +1,27 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + */ +package com.qq.tars.example.native_server; + +/** + * Hello服务实现 - 用于GraalVM Native Image演示 + */ +public class HelloServantImpl implements HelloServant { + + @Override + public String hello(String name) { + return "Hello, " + name + "! (from native server)"; + } + + @Override + public int add(int a, int b) { + return a + b; + } +} diff --git a/examples/tars-native-server/src/main/java/com/qq/tars/example/native_server/NativeServerMain.java b/examples/tars-native-server/src/main/java/com/qq/tars/example/native_server/NativeServerMain.java new file mode 100644 index 00000000..4e5a0cf9 --- /dev/null +++ b/examples/tars-native-server/src/main/java/com/qq/tars/example/native_server/NativeServerMain.java @@ -0,0 +1,193 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + */ +package com.qq.tars.example.native_server; + +import com.qq.tars.client.rpc.ChannelHandler; +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; +import com.qq.tars.client.rpc.TransporterServer; +import com.qq.tars.common.support.Endpoint; +import com.qq.tars.protocol.util.TarsHelper; +import com.qq.tars.rpc.netty.NettyTransporterServer; +import com.qq.tars.rpc.protocol.tars.TarsServantRequest; +import com.qq.tars.rpc.protocol.tars.TarsServantResponse; +import com.qq.tars.rpc.protocol.tars.support.AnalystManager; +import com.qq.tars.server.config.ServantAdapterConfig; +import com.qq.tars.server.core.Processor; +import io.netty.channel.Channel; + +import java.nio.charset.Charset; + +/** + * GraalVM Native Image 服务端示例 + * + * 编译命令: + * ./gradlew :examples:tars-native-server:nativeCompile + * + * 运行: + * ./examples/tars-native-server/build/native/nativeCompile/tars-native-server + */ +public class NativeServerMain { + + private static final String HOST = "0.0.0.0"; + private static final int PORT = 18601; + + public static void main(String[] args) throws Exception { + System.out.println("========================================"); + System.out.println("Tars Native Server Starting..."); + System.out.println("Host: " + HOST); + System.out.println("Port: " + PORT); + System.out.println("========================================"); + + // 创建服务实现 + HelloServant servant = new HelloServantImpl(); + + // 注册Servant方法信息到AnalystManager,供TarsDecoder/TarsEncoder使用 + String objName = "TestApp.HelloServer.HelloObj"; + AnalystManager.getInstance().registry(objName, HelloServant.class, objName); + + // 创建Endpoint + Endpoint endpoint = new Endpoint("tcp", HOST, PORT, 60000, 0, 0, null); + + // 创建服务端配置 + ServantAdapterConfig config = new ServantAdapterConfig(endpoint, objName, null); + + // 创建处理器 + SimpleProcessor processor = new SimpleProcessor(servant); + + // 创建并启动服务 + ChannelHandler handler = new SimpleServerHandler(processor); + TransporterServer server = new NettyTransporterServer(config, handler); + server.bind(); + + System.out.println("========================================"); + System.out.println("Tars Native Server Started!"); + System.out.println("Listening on " + HOST + ":" + PORT); + System.out.println("Press Ctrl+C to stop"); + System.out.println("========================================"); + + // 保持运行 + Thread.currentThread().join(); + } + + /** + * 简单的请求处理器 - 不使用反射,直接调用方法 + */ + static class SimpleProcessor implements Processor { + private final HelloServant servant; + + public SimpleProcessor(HelloServant servant) { + this.servant = servant; + } + + @Override + public Response process(Request request, Channel channel) { + TarsServantRequest tarsRequest = (TarsServantRequest) request; + TarsServantResponse response = new TarsServantResponse(tarsRequest.getRequestId()); + response.setRequestId(tarsRequest.getRequestId()); + response.setRequest(tarsRequest); + response.setVersion(tarsRequest.getVersion()); + response.setPacketType(tarsRequest.getPacketType()); + response.setMessageType(tarsRequest.getMessageType()); + response.setCharsetName(Charset.forName(tarsRequest.getCharsetName())); + + try { + String methodName = tarsRequest.getFunctionName(); + Object[] args = tarsRequest.getMethodParameters(); + + System.out.println("Received request: " + methodName + ", args: " + java.util.Arrays.toString(args)); + + Object result = null; + // 直接调用方法,避免反射 + switch (methodName) { + case "hello": + String name = args != null && args.length > 0 ? (String) args[0] : "World"; + result = servant.hello(name); + break; + case "add": + int a = args != null && args.length > 0 ? ((Number) args[0]).intValue() : 0; + int b = args != null && args.length > 1 ? ((Number) args[1]).intValue() : 0; + result = servant.add(a, b); + break; + default: + response.setRet(TarsHelper.SERVERNOFUNCERR); + response.setRemark("Method not found: " + methodName); + return response; + } + + response.setResult(result); + response.setRet(TarsHelper.SERVERSUCCESS); + System.out.println("Response: " + result); + } catch (Exception e) { + e.printStackTrace(); + response.setRet(TarsHelper.SERVERUNKNOWNERR); + response.setRemark(e.getMessage()); + } + + return response; + } + + @Override + public void overload(Request request, Channel clientChannel) { + // 过载处理 + TarsServantRequest tarsRequest = (TarsServantRequest) request; + TarsServantResponse response = new TarsServantResponse(tarsRequest.getRequestId()); + response.setRequestId(tarsRequest.getRequestId()); + response.setRet(TarsHelper.SERVEROVERLOAD); + response.setRemark("Server overload"); + if (clientChannel.isWritable()) { + clientChannel.writeAndFlush(response); + } + } + } + + /** + * 简单的服务端Channel处理器 + */ + static class SimpleServerHandler implements ChannelHandler { + private final Processor processor; + + public SimpleServerHandler(Processor processor) { + this.processor = processor; + } + + @Override + public void connected(Channel channel) { + System.out.println("Client connected: " + channel.remoteAddress()); + } + + @Override + public void disconnected(Channel channel) { + System.out.println("Client disconnected: " + channel.remoteAddress()); + } + + @Override + public void send(Channel channel, Object message) { + } + + @Override + public void received(Channel channel, Object message) { + Response response = processor.process((Request) message, channel); + if (!response.isAsyncMode() && channel.isWritable()) { + channel.writeAndFlush(response); + } + } + + @Override + public void caught(Channel channel, Throwable exception) { + exception.printStackTrace(); + } + + @Override + public void destroy() { + } + } +} diff --git a/examples/tars-native-server/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-server/native-image.properties b/examples/tars-native-server/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-server/native-image.properties new file mode 100644 index 00000000..ee4fe3b9 --- /dev/null +++ b/examples/tars-native-server/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-server/native-image.properties @@ -0,0 +1,7 @@ +Args = --initialize-at-build-time=com.google.common \ + --initialize-at-build-time=io.netty \ + --initialize-at-run-time=io.netty.channel.epoll \ + --initialize-at-run-time=io.netty.channel.kqueue \ + --initialize-at-run-time=io.netty.channel.unix \ + --initialize-at-run-time=io.netty.handler.ssl \ + --initialize-at-run-time=io.netty.internal.tcnative diff --git a/examples/tars-native-server/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-server/reflect-config.json b/examples/tars-native-server/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-server/reflect-config.json new file mode 100644 index 00000000..c77fda5f --- /dev/null +++ b/examples/tars-native-server/src/main/resources/META-INF/native-image/com.tencent.tars/tars-native-server/reflect-config.json @@ -0,0 +1,105 @@ +[ + { + "name": "com.qq.tars.example.native_server.HelloServant", + "allDeclaredConstructors": true, + "allDeclaredMethods": true, + "allPublicMethods": true + }, + { + "name": "com.qq.tars.example.native_server.HelloServantImpl", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.example.native_server.NativeServerMain", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.example.native_server.NativeServerMain$SimpleProcessor", + "allDeclaredConstructors": true, + "allDeclaredMethods": true, + "allDeclaredFields": true + }, + { + "name": "com.qq.tars.example.native_server.NativeServerMain$SimpleServerHandler", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + + { + "name": "com.qq.tars.rpc.netty.NettyServerHandler", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.rpc.netty.NettyClientHandler", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.rpc.netty.TarsDecoder", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.rpc.netty.TarsEncoder", + "allDeclaredConstructors": true, + "allDeclaredMethods": true + }, + + { + "name": "io.netty.channel.ChannelHandlerAdapter", + "allDeclaredMethods": true + }, + { + "name": "io.netty.channel.ChannelInboundHandlerAdapter", + "allDeclaredMethods": true + }, + { + "name": "io.netty.channel.ChannelOutboundHandlerAdapter", + "allDeclaredMethods": true + }, + { + "name": "io.netty.channel.ChannelDuplexHandler", + "allDeclaredMethods": true + }, + { + "name": "io.netty.handler.codec.ByteToMessageDecoder", + "allDeclaredMethods": true + }, + { + "name": "io.netty.handler.codec.MessageToByteEncoder", + "allDeclaredMethods": true + }, + { + "name": "io.netty.handler.timeout.IdleStateHandler", + "allDeclaredMethods": true + }, + + { + "name": "com.qq.tars.protocol.annotation.Servant", + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.protocol.tars.annotation.TarsMethodParameter", + "allDeclaredMethods": true + }, + { + "name": "com.qq.tars.protocol.tars.annotation.TarsMethod", + "allDeclaredMethods": true + }, + + { + "name": "com.qq.tars.rpc.protocol.tars.TarsServantRequest", + "allDeclaredConstructors": true, + "allDeclaredMethods": true, + "allDeclaredFields": true + }, + { + "name": "com.qq.tars.rpc.protocol.tars.TarsServantResponse", + "allDeclaredConstructors": true, + "allDeclaredMethods": true, + "allDeclaredFields": true + } +] diff --git a/examples/tars-spring-boot-client/build.gradle.kts b/examples/tars-spring-boot-client/build.gradle.kts new file mode 100644 index 00000000..d3e9e060 --- /dev/null +++ b/examples/tars-spring-boot-client/build.gradle.kts @@ -0,0 +1,11 @@ +plugins { + java +} + +description = "Tars Spring Boot Client Example" + +dependencies { + implementation(project(":spring:tars-spring-boot-starter")) + + testImplementation(libs.junit) +} diff --git a/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/App.java b/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/App.java new file mode 100644 index 00000000..6e081b14 --- /dev/null +++ b/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/App.java @@ -0,0 +1,14 @@ +package com.tencent.tars; + +import com.qq.tars.spring.annotation.EnableTarsServer; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +@SpringBootApplication +@EnableTarsServer +public class App { + public static void main( String[] args ){ + SpringApplication.run(App.class, args); + } +} diff --git a/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/client/testapp/ClientServant.java b/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/client/testapp/ClientServant.java new file mode 100644 index 00000000..eb4d4c46 --- /dev/null +++ b/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/client/testapp/ClientServant.java @@ -0,0 +1,9 @@ +package com.tencent.tars.client.testapp; + +import com.qq.tars.protocol.annotation.Servant; + + +@Servant +public interface ClientServant { + String rpcHello(int no, String name); +} diff --git a/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/client/testapp/HelloPrx.java b/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/client/testapp/HelloPrx.java new file mode 100644 index 00000000..7e490131 --- /dev/null +++ b/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/client/testapp/HelloPrx.java @@ -0,0 +1,21 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.0.1. +// ********************************************************************** + +package com.tencent.tars.client.testapp; + +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsContext; + +import java.util.concurrent.CompletableFuture; + +@Servant +public interface HelloPrx { + + String hello(int no, String name); + + CompletableFuture promise_hello(int no, String name); + + String hello(int no, String name, @TarsContext java.util.Map ctx); +} diff --git a/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/client/testapp/impl/ClientServantImpl.java b/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/client/testapp/impl/ClientServantImpl.java new file mode 100644 index 00000000..97a05aa4 --- /dev/null +++ b/examples/tars-spring-boot-client/src/main/java/com/tencent/tars/client/testapp/impl/ClientServantImpl.java @@ -0,0 +1,31 @@ +package com.tencent.tars.client.testapp.impl; + +import com.qq.tars.spring.annotation.TarsClient; +import com.qq.tars.spring.annotation.TarsServant; +import com.tencent.tars.client.testapp.ClientServant; +import com.tencent.tars.client.testapp.HelloPrx; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.CompletableFuture; + + +@TarsServant("ClientObj") +public class ClientServantImpl implements ClientServant { + private static final Logger LOGGER = LoggerFactory.getLogger(ClientServantImpl.class); + @TarsClient("TestServer.HelloServer.HelloObj") + HelloPrx helloPrx; + + @Override + public String rpcHello(int no, String name) { + String syncResult = helloPrx.hello(1000, name); + LOGGER.info("sync Result {}", syncResult); + //promise调用 + helloPrx.promise_hello(1000, name).thenCompose(x -> { + String res = "promise_result: " + x; + LOGGER.info("promise result :{}", res); + return CompletableFuture.completedFuture(0); + }); + return syncResult; + } +} diff --git a/net/src/main/java/com/qq/tars/net/protocol/ProtocolFactory.java b/examples/tars-spring-boot-client/src/main/resources/client.tars similarity index 82% rename from net/src/main/java/com/qq/tars/net/protocol/ProtocolFactory.java rename to examples/tars-spring-boot-client/src/main/resources/client.tars index 902bf2e4..2db73ce2 100644 --- a/net/src/main/java/com/qq/tars/net/protocol/ProtocolFactory.java +++ b/examples/tars-spring-boot-client/src/main/resources/client.tars @@ -14,11 +14,10 @@ * specific language governing permissions and limitations under the License. */ -package com.qq.tars.net.protocol; - -public interface ProtocolFactory { - - public ProtocolEncoder getEncoder(); - - public ProtocolDecoder getDecoder(); -} +module TestApp +{ + interface Client + { + string rpcHello(int no, string name); + }; +}; \ No newline at end of file diff --git a/net/src/main/java/com/qq/tars/net/core/SessionListener.java b/examples/tars-spring-boot-client/src/main/resources/hello.tars similarity index 80% rename from net/src/main/java/com/qq/tars/net/core/SessionListener.java rename to examples/tars-spring-boot-client/src/main/resources/hello.tars index 3ba4f644..da273654 100644 --- a/net/src/main/java/com/qq/tars/net/core/SessionListener.java +++ b/examples/tars-spring-boot-client/src/main/resources/hello.tars @@ -14,12 +14,10 @@ * specific language governing permissions and limitations under the License. */ -package com.qq.tars.net.core; - -public interface SessionListener { - - public void onSessionCreated(SessionEvent se); - - public void onSessionDestoryed(SessionEvent se); - -} +module TestApp +{ + interface Hello + { + string hello(int no, string name); + }; +}; \ No newline at end of file diff --git a/examples/tars-spring-boot-http-server/build.gradle.kts b/examples/tars-spring-boot-http-server/build.gradle.kts new file mode 100644 index 00000000..c0802219 --- /dev/null +++ b/examples/tars-spring-boot-http-server/build.gradle.kts @@ -0,0 +1,11 @@ +plugins { + java +} + +description = "Tars Spring Boot HTTP Server Example" + +dependencies { + implementation(project(":spring:tars-http-extension")) + + testImplementation(libs.junit) +} diff --git a/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/App.java b/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/App.java new file mode 100644 index 00000000..46406432 --- /dev/null +++ b/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/App.java @@ -0,0 +1,14 @@ +package com.tencent.tars; + +import com.qq.tars.spring.annotation.EnableTarsServer; +import com.qq.tars.spring.annotation.TarsHttpService; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableTarsServer +public class App { + public static void main( String[] args ) { + SpringApplication.run(App.class, args); + } +} diff --git a/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/client/testapp/HelloPrx.java b/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/client/testapp/HelloPrx.java new file mode 100644 index 00000000..0cd46638 --- /dev/null +++ b/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/client/testapp/HelloPrx.java @@ -0,0 +1,25 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.0.1. +// ********************************************************************** + +package com.tencent.tars.client.testapp; + +import com.qq.tars.protocol.annotation.*; +import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.common.support.Holder; +import java.util.concurrent.CompletableFuture; + +@Servant +public interface HelloPrx { + + String hello(int no, String name); + + CompletableFuture promise_hello(int no, String name); + + String hello(int no, String name, @TarsContext java.util.Map ctx); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name); + + void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map ctx); +} diff --git a/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/client/testapp/HelloPrxCallback.java b/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/client/testapp/HelloPrxCallback.java new file mode 100644 index 00000000..6be5f986 --- /dev/null +++ b/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/client/testapp/HelloPrxCallback.java @@ -0,0 +1,13 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.0.1. +// ********************************************************************** + +package com.tencent.tars.client.testapp; + + +public abstract class HelloPrxCallback { + + public abstract void callback_hello(String ret); + +} diff --git a/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/http/server/HelloController.java b/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/http/server/HelloController.java new file mode 100644 index 00000000..ac57e420 --- /dev/null +++ b/examples/tars-spring-boot-http-server/src/main/java/com/tencent/tars/http/server/HelloController.java @@ -0,0 +1,21 @@ +package com.tencent.tars.http.server; + +import com.qq.tars.spring.annotation.TarsClient; +import com.qq.tars.spring.annotation.TarsHttpService; +import com.tencent.tars.client.testapp.HelloPrx; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@TarsHttpService("HttpObj") +@RestController +public class HelloController { + @TarsClient("TestServer.HelloServer.HelloObj") + HelloPrx helloPrx; + + @RequestMapping("/hello") + public String testHello(@RequestParam Integer no){ + String ret = helloPrx.hello(no, "Hello World"); + return ret; + } +} diff --git a/net/src/main/java/com/qq/tars/net/client/Callback.java b/examples/tars-spring-boot-http-server/src/main/resources/hello.tars similarity index 79% rename from net/src/main/java/com/qq/tars/net/client/Callback.java rename to examples/tars-spring-boot-http-server/src/main/resources/hello.tars index 5f019fa7..da273654 100644 --- a/net/src/main/java/com/qq/tars/net/client/Callback.java +++ b/examples/tars-spring-boot-http-server/src/main/resources/hello.tars @@ -14,13 +14,10 @@ * specific language governing permissions and limitations under the License. */ -package com.qq.tars.net.client; - -public interface Callback { - - public void onCompleted(T result); - - public void onException(Throwable ex); - - public void onExpired(); -} +module TestApp +{ + interface Hello + { + string hello(int no, string name); + }; +}; \ No newline at end of file diff --git a/examples/tars-spring-boot-server/build.gradle.kts b/examples/tars-spring-boot-server/build.gradle.kts new file mode 100644 index 00000000..77ba66ce --- /dev/null +++ b/examples/tars-spring-boot-server/build.gradle.kts @@ -0,0 +1,11 @@ +plugins { + java +} + +description = "Tars Spring Boot Server Example" + +dependencies { + implementation(project(":spring:tars-spring-boot-starter")) + + testImplementation(libs.junit) +} diff --git a/examples/tars-spring-boot-server/pom.xml b/examples/tars-spring-boot-server/pom.xml deleted file mode 100644 index b9c848b1..00000000 --- a/examples/tars-spring-boot-server/pom.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - tars-examples - com.tencent.tars - 1.6.1 - - 4.0.0 - - tars-spring-boot-server - - - 2.0.3.RELEASE - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - - - com.tencent.tars - tars-spring-boot-starter - 1.6.1 - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.6 - - - - conf/ - - - - - - org.springframework.boot - spring-boot-maven-plugin - - com.qq.tars.quickstart.server.QuickStartApplication - - - - - repackage - - - - - - - \ No newline at end of file diff --git a/examples/tars-spring-boot-server/src/main/java/com/qq/tars/quickstart/server/testapp/HelloServant.java b/examples/tars-spring-boot-server/src/main/java/com/qq/tars/quickstart/server/testapp/HelloServant.java index 649ccb56..be341470 100644 --- a/examples/tars-spring-boot-server/src/main/java/com/qq/tars/quickstart/server/testapp/HelloServant.java +++ b/examples/tars-spring-boot-server/src/main/java/com/qq/tars/quickstart/server/testapp/HelloServant.java @@ -1,29 +1,16 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ // ********************************************************************** // This file was generated by a TARS parser! -// TARS version 1.0.1. +// TARS version 1.7.2. // ********************************************************************** package com.qq.tars.quickstart.server.testapp; -import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.annotation.*; +import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.common.support.Holder; @Servant public interface HelloServant { - public String hello(int no, String name); + String hello(@TarsMethodParameter(name="no")int no, @TarsMethodParameter(name="name")String name); } diff --git a/examples/tars-spring-boot-server/src/main/resources/logback.xml b/examples/tars-spring-boot-server/src/main/resources/logback.xml new file mode 100644 index 00000000..416b6084 --- /dev/null +++ b/examples/tars-spring-boot-server/src/main/resources/logback.xml @@ -0,0 +1,142 @@ + + + + + + ${LOG_HOME}/client_log.%d{yyyy-MM-dd}.log + 30 + + + INFO + ACCEPT + DENY + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + ${LOG_HOME}/tars_clent_om_log.%d{yyyy-MM-dd}.log + 30 + + + INFO + ACCEPT + DENY + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + + ${LOG_HOME}/info.%d{yyyy-MM-dd}.log + 30 + + + INFO + ACCEPT + DENY + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + + + ${LOG_HOME}/warn.%d{yyyy-MM-dd}.log + 30 + + + WARN + ACCEPT + DENY + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + + ERROR + ACCEPT + DENY + + + ${LOG_HOME}/error.%d{yyyy-MM-dd}.log + 30 + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + + DEBUG + ACCEPT + DENY + + + ${LOG_HOME}/debug.%d{yyyy-MM-dd}.log + 30 + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + 30 + 512 + + + + 30 + 512 + + + + 30 + 512 + + + + 30 + 512 + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/tars-spring-cloud-client/build.gradle.kts b/examples/tars-spring-cloud-client/build.gradle.kts new file mode 100644 index 00000000..8681f74d --- /dev/null +++ b/examples/tars-spring-cloud-client/build.gradle.kts @@ -0,0 +1,12 @@ +plugins { + java +} + +description = "Tars Spring Cloud Client Example" + +dependencies { + implementation(project(":spring:tars-spring-cloud-starter")) + implementation(project(":tars-core")) + + testImplementation(libs.junit) +} diff --git a/examples/tars-spring-cloud-client/pom.xml b/examples/tars-spring-cloud-client/pom.xml deleted file mode 100644 index a4804591..00000000 --- a/examples/tars-spring-cloud-client/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - 4.0.0 - - com.tencent.tars - tars-spring-cloud-client - 1.6.1 - war - - tars-spring-cloud-client - - - UTF-8 - - - - - junit - junit - 3.8.1 - test - - - com.tencent.tars - tars-core - 1.6.1 - - - com.tencent.tars - tars-spring - 1.6.1 - - - com.tencent.tars - tars-protobuf - 1.6.1 - - - com.tencent.tars - tars-spring-cloud-starter - 1.6.1 - - - diff --git a/examples/tars-spring-cloud-server/build.gradle.kts b/examples/tars-spring-cloud-server/build.gradle.kts new file mode 100644 index 00000000..34a3ee57 --- /dev/null +++ b/examples/tars-spring-cloud-server/build.gradle.kts @@ -0,0 +1,14 @@ +plugins { + java + war +} + +description = "Tars Spring Cloud Server Example" + +dependencies { + implementation(project(":spring:tars-spring-cloud-starter")) + implementation(project(":spring:tars-spring")) + implementation(project(":tars-core")) + + testImplementation(libs.junit) +} diff --git a/examples/tars-spring-cloud-server/pom.xml b/examples/tars-spring-cloud-server/pom.xml deleted file mode 100644 index f311b542..00000000 --- a/examples/tars-spring-cloud-server/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - 4.0.0 - com.tencent.tars - tars-spring-cloud-server - war - 1.6.1 - - tars-spring-cloud-server - http://maven.apache.org - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-war-plugin - - src\main\webapp\WEB-INF\web.xml - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - - junit - junit - 3.8.1 - test - - - com.tencent.tars - tars-core - 1.6.1 - - - com.tencent.tars - tars-spring - 1.6.1 - - - com.tencent.tars - tars-protobuf - 1.6.1 - - - com.tencent.tars - tars-spring-cloud-starter - 1.6.1 - - - - diff --git a/examples/tars-spring-server/build.gradle.kts b/examples/tars-spring-server/build.gradle.kts new file mode 100644 index 00000000..287c57e3 --- /dev/null +++ b/examples/tars-spring-server/build.gradle.kts @@ -0,0 +1,13 @@ +plugins { + java + war +} + +description = "Tars Spring Server Example" + +dependencies { + implementation(project(":spring:tars-spring")) + implementation(project(":tars-core")) + + testImplementation(libs.junit) +} diff --git a/examples/tars-spring-server/pom.xml b/examples/tars-spring-server/pom.xml deleted file mode 100644 index 4f01b242..00000000 --- a/examples/tars-spring-server/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - tars-examples - com.tencent.tars - 1.6.1 - - 4.0.0 - war - - tars-spring-server - - - - com.tencent.tars - tars-core - ${project.parent.version} - - - com.tencent.tars - tars-spring - ${project.parent.version} - - - - \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 00000000..89ccb813 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,135 @@ +[versions] +# Project version +tars = "2.0.0" + +# Java +java = "21" + +# Core dependencies +netty = "4.2.10.Final" +netty-tcnative = "2.0.75.Final" +guava = "33.5.0-jre" +gson = "2.13.2" +slf4j = "2.0.17" + +# Logging +logback = "1.5.32" + +# Spring +spring = "7.0.5" +spring-boot = "4.0.3" + +# Spring Cloud +eureka-client = "2.0.5" +spring-cloud-netflix-eureka = "5.0.1" +spring-cloud-commons = "5.0.1" + +# Tracing +brave = "6.3.0" +brave-opentracing = "1.0.1" +zipkin-reporter-kafka = "3.5.1" +zipkin-reporter-urlconnection = "3.5.1" +opentelemetry = "1.59.0" + +# Apache Commons +commons-lang = "2.6" +commons-io = "2.21.0" +commons-codec = "1.21.0" +commons-cli = "1.11.0" +commons-compress = "1.28.0" + +# Testing +junit = "4.13.2" +hamcrest = "1.3" +assertj = "3.27.7" + +# Servlet +servlet-api = "6.1.0" + +# HTTP +httpcore = "4.4.16" + +# Jakarta +jakarta-annotation = "3.0.0" + +# ANTLR (for tars-gradle-plugin) +antlr = "3.5.3" + +# Plexus +plexus-utils = "4.0.2" +plexus-interpolation = "1.29" + +# Misc +jsr305 = "3.0.2" + +# GraalVM +graalvm-native = "0.10.6" + +[libraries] +# Netty +netty-all = { module = "io.netty:netty-all", version.ref = "netty" } +netty-tcnative = { module = "io.netty:netty-tcnative", version.ref = "netty-tcnative" } + +# Guava & Gson +guava = { module = "com.google.guava:guava", version.ref = "guava" } +gson = { module = "com.google.code.gson:gson", version.ref = "gson" } + +# Logging +slf4j-api = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } +logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" } + +# Spring Boot +spring-boot-starter = { module = "org.springframework.boot:spring-boot-starter", version.ref = "spring-boot" } +spring-boot-configuration-processor = { module = "org.springframework.boot:spring-boot-configuration-processor", version.ref = "spring-boot" } +spring-boot-starter-web = { module = "org.springframework.boot:spring-boot-starter-web", version.ref = "spring-boot" } + +# Spring Cloud +eureka-client = { module = "com.netflix.eureka:eureka-client", version.ref = "eureka-client" } +spring-cloud-netflix-eureka-client = { module = "org.springframework.cloud:spring-cloud-netflix-eureka-client", version.ref = "spring-cloud-netflix-eureka" } +spring-cloud-commons = { module = "org.springframework.cloud:spring-cloud-commons", version.ref = "spring-cloud-commons" } + +# Tracing +zipkin-sender-kafka = { module = "io.zipkin.reporter2:zipkin-sender-kafka", version.ref = "zipkin-reporter-kafka" } +zipkin-sender-urlconnection = { module = "io.zipkin.reporter2:zipkin-sender-urlconnection", version.ref = "zipkin-reporter-urlconnection" } +brave-opentracing = { module = "io.opentracing.brave:brave-opentracing", version.ref = "brave-opentracing" } +opentelemetry-sdk = { module = "io.opentelemetry:opentelemetry-sdk", version.ref = "opentelemetry" } +opentelemetry-exporter-otlp = { module = "io.opentelemetry:opentelemetry-exporter-otlp", version.ref = "opentelemetry" } +opentelemetry-opentracing-shim = { module = "io.opentelemetry:opentelemetry-opentracing-shim", version.ref = "opentelemetry" } + +# Apache Commons +commons-lang = { module = "commons-lang:commons-lang", version.ref = "commons-lang" } +commons-io = { module = "commons-io:commons-io", version.ref = "commons-io" } +commons-codec = { module = "commons-codec:commons-codec", version.ref = "commons-codec" } +commons-cli = { module = "commons-cli:commons-cli", version.ref = "commons-cli" } +commons-compress = { module = "org.apache.commons:commons-compress", version.ref = "commons-compress" } + +# Servlet +servlet-api = { module = "jakarta.servlet:jakarta.servlet-api", version.ref = "servlet-api" } + +# HTTP +httpcore = { module = "org.apache.httpcomponents:httpcore", version.ref = "httpcore" } + +# Jakarta +jakarta-annotation-api = { module = "jakarta.annotation:jakarta.annotation-api", version.ref = "jakarta-annotation" } + +# Testing +junit = { module = "junit:junit", version.ref = "junit" } +hamcrest-all = { module = "org.hamcrest:hamcrest-all", version.ref = "hamcrest" } +assertj-core = { module = "org.assertj:assertj-core", version.ref = "assertj" } + +# ANTLR +antlr = { module = "org.antlr:antlr", version.ref = "antlr" } + +# Plexus +plexus-utils = { module = "org.codehaus.plexus:plexus-utils", version.ref = "plexus-utils" } +plexus-interpolation = { module = "org.codehaus.plexus:plexus-interpolation", version.ref = "plexus-interpolation" } + +# Misc +jsr305 = { module = "com.google.code.findbugs:jsr305", version.ref = "jsr305" } + +[bundles] +tracing = ["zipkin-sender-kafka", "zipkin-sender-urlconnection", "brave-opentracing"] +commons = ["commons-lang", "commons-io", "commons-codec", "commons-cli", "commons-compress"] + +[plugins] +graalvm-native = { id = "org.graalvm.buildtools.native", version.ref = "graalvm-native" } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..1af9e093 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..1aa94a42 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..93e3f59f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/net/README.md b/net/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/net/pom.xml b/net/pom.xml deleted file mode 100644 index 018c3cbd..00000000 --- a/net/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - 4.0.0 - - com.tencent.tars - tars-parent - 1.6.1 - - tars-net - jar - ${project.artifactId} - - - - junit - junit - 3.8.1 - test - - - diff --git a/net/src/main/java/com/qq/tars/net/client/Client.java b/net/src/main/java/com/qq/tars/net/client/Client.java deleted file mode 100644 index f1915516..00000000 --- a/net/src/main/java/com/qq/tars/net/client/Client.java +++ /dev/null @@ -1,364 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.client; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.channels.DatagramChannel; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import com.qq.tars.net.client.ticket.Ticket; -import com.qq.tars.net.client.ticket.TicketManager; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; -import com.qq.tars.net.core.Request.InvokeStatus; -import com.qq.tars.net.core.Session.SessionStatus; -import com.qq.tars.net.core.nio.SelectorManager; -import com.qq.tars.net.core.nio.TCPSession; -import com.qq.tars.net.core.nio.UDPSession; -import com.qq.tars.net.protocol.ProtocolFactory; - -public final class Client { - - private Session session = null; - - private String host = null; - - private int port = -1; - - private SelectorManager selectorManager = null; - - private int minPoolSize = 5; - - private int maxPoolSize = 10; - - private int queueSize = 20000; - - private long readTimeout = 1000; - - private long connectTimeout = 200; - - private boolean keepAlive = true; - - private int selectorPoolSize = 2; - - private boolean udpMode = false; - - private int tc = INVALID_TRAFFIC_CLASS_VALUE; - - private int bufferSize = 1024 * 4; - - private boolean tcpNoDelay = false; - - private static final int INVALID_TRAFFIC_CLASS_VALUE = -1; - - protected static final ConcurrentHashMap selectors = new ConcurrentHashMap(); - - public Client(String ip, int port, ProtocolFactory protocolFactory) { - this(ip, port, protocolFactory, false); - } - - public Client(String ip, int port, ProtocolFactory protocolFactory, boolean udpMode) { - this(ip, port, protocolFactory, null, udpMode); - } - - public Client(String ip, int port, ProtocolFactory protocolFactory, ThreadPoolExecutor threadPoolExecutor, - boolean udpMode) { - try { - this.host = ip; - this.port = port; - this.udpMode = udpMode; - this.selectorManager = initSelectorManager(protocolFactory, threadPoolExecutor); - reConnect(); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - protected void ensureConnected() throws IOException { - if (isNotConnected()) reConnect(); - } - - protected synchronized void reConnect() throws IOException { - //0. Don't send connect request if it is connecting. - if (isNotConnected()) { - SocketAddress server = new InetSocketAddress(this.host, this.port); - SelectableChannel channel = null; - Session session2 = null; - int event; - - if (this.udpMode) { - //1. Create socket channel - channel = DatagramChannel.open(); - channel.configureBlocking(false); - - //2. Create NioSession for each client connection - session2 = new UDPSession(this.selectorManager); - ((UDPSession) session2).setBufferSize(bufferSize); - ((UDPSession) session2).setTarget(server); - event = SelectionKey.OP_READ; - session2.setStatus(SessionStatus.CLIENT_CONNECTED); - } else { - //1. Create socket channel - channel = SocketChannel.open(); - channel.configureBlocking(false); - try { - if (this.tc != INVALID_TRAFFIC_CLASS_VALUE) ((SocketChannel) channel).socket().setTrafficClass(this.tc); - } catch (Exception ex) { - ex.printStackTrace(); - } - ((SocketChannel) channel).connect(server); - - //2. Create NioSession for each client connection - session2 = new TCPSession(this.selectorManager); - ((TCPSession) session2).setTcpNoDelay(this.tcpNoDelay); - event = SelectionKey.OP_CONNECT; - } - - session2.setChannel(channel); - session2.setKeepAlive(selectorManager.isKeepAlive()); - - //3. Register event - this.selectorManager.nextReactor().registerChannel(channel, event, session2); - - if (!this.udpMode) { - //4. Wait to connect - if (!session2.waitToConnect(this.connectTimeout)) { - session2.asyncClose(); - throw new IOException("connect timed out to " + this.host + ":" + this.port); - } - - //5. Handle exception - if (session2.getStatus() == SessionStatus.NOT_CONNECTED) { - session2.asyncClose(); - throw new IOException("connect failed to " + this.host + ":" + this.port); - } else if (session2.getStatus() == SessionStatus.CLOSED) { //Already closed - throw new IOException("connect failed to " + this.host + ":" + this.port); //Please see stderr.log for more details. - } - } - - this.session = session2; - } - } - - public void setBufferSize(int bufferSize) { - this.bufferSize = bufferSize; - } - - public RES invokeWithSync(REQ request) throws IOException { - Ticket ticket = null; - RES response = null; - - try { - ensureConnected(); - request.setInvokeStatus(InvokeStatus.SYNC_CALL); - ticket = TicketManager.createTicket(request, session, this.getReadTimeout()); - Session session2 = session; - session2.write(request); - if (!ticket.await(this.readTimeout, TimeUnit.MILLISECONDS)) { - if (session2 != null && session2.getStatus() != SessionStatus.CLIENT_CONNECTED) { - throw new IOException("Connection reset by peer"); - } else { - throw new IOException("The operation has timed out."); - } - } - response = ticket.response(); - if (response == null) throw new IOException("The operation is failed."); - return response; - } catch (InterruptedException e) { - e.printStackTrace(); - } finally { - if (ticket != null) TicketManager.removeTicket(ticket.getTicketNumber()); - } - - return response; - } - - public void invokeWithAsync(REQ request, Callback callback) throws IOException { - Ticket ticket = null; - - try { - ensureConnected(); - request.setInvokeStatus(InvokeStatus.ASYNC_CALL); - ticket = TicketManager.createTicket(request, session, this.getReadTimeout(), callback); - session.write(request); - } catch (Exception ex) { - if (ticket != null) TicketManager.removeTicket(ticket.getTicketNumber()); - throw new IOException("invokeWithAsync error:", ex); - } - } - - @SuppressWarnings("unchecked") - public Future invokeWithFuture(REQ request) throws IOException { - Ticket ticket = null; - - try { - ensureConnected(); - request.setInvokeStatus(InvokeStatus.FUTURE_CALL); - ticket = TicketManager.createTicket(request, session, this.getReadTimeout()); - session.write(request); - return new FutureImpl(ticket); - } catch (IOException ex) { - if (ticket != null) TicketManager.removeTicket(ticket.getTicketNumber()); - throw ex; - } - } - - public synchronized void shutdown() throws IOException { - this.session.asyncClose(); - } - - public Session getIoSession() { - return this.session; - } - - public long getReadTimeout() { - return readTimeout; - } - - public void setReadTimeout(long readTimeout) { - this.readTimeout = readTimeout; - } - - public int getTrafficClass() { - return tc; - } - - public void setTrafficClass(int tc) { - if (this.session != null && this.session instanceof TCPSession) { - try { - ((SocketChannel) ((TCPSession) this.session).getChannel()).socket().setTrafficClass(tc); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - this.tc = tc; - - } - - public void setTcpNoDelay(boolean on) { - this.tcpNoDelay = on; - - if (this.session != null && this.session instanceof TCPSession) { - try { - ((SocketChannel) ((TCPSession) this.session).getChannel()).socket().setTcpNoDelay(on); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - public long getConnectTimeout() { - return connectTimeout; - } - - public void setConnectTimeout(long connectTimeout) { - this.connectTimeout = connectTimeout; - } - - public String getAddress() { - return host + ":" + port; - } - - private boolean isNotConnected() { - if (session == null || session.getStatus() == SessionStatus.CLOSED || session.getStatus() == SessionStatus.NOT_CONNECTED) { - return true; - } - - return false; - } - - private SelectorManager initSelectorManager(ProtocolFactory protocolFactory, ThreadPoolExecutor threadPoolExecutor) throws IOException { - String protocolFactoryName = resolveProtocolFactoryName(protocolFactory); - String currentContextIdentity = resolveCurrentContextIdentity(); - String key = protocolFactoryName + "-" + currentContextIdentity; - ThreadPoolExecutor threadPool = null; - - SelectorManager selector = selectors.get(key); - - if (selector == null) { - synchronized (selectors) { - selector = selectors.get(key); - if (selector == null) { //Double-Checked Locking - selectorPoolSize = convertInt(System.getProperty("com.qq.nami.client.selectorPoolSize"), selectorPoolSize); - minPoolSize = convertInt(System.getProperty("com.qq.nami.client.minPoolSize"), minPoolSize); - maxPoolSize = convertInt(System.getProperty("com.qq.nami.client.maxPoolSize"), maxPoolSize); - queueSize = convertInt(System.getProperty("com.qq.nami.client.queueSize"), queueSize); - - if (threadPoolExecutor == null) { - threadPool = new ThreadPoolExecutor(minPoolSize, maxPoolSize, 120, TimeUnit.SECONDS, new LinkedBlockingQueue(queueSize)); - } else { - threadPool = threadPoolExecutor; - } - selector = new SelectorManager(selectorPoolSize, protocolFactory, threadPool, null, keepAlive, "taserver-proxy", this.udpMode); - selector.start(); - selectors.put(key, selector); - } - } - } - - return selector; - } - - private String resolveProtocolFactoryName(ProtocolFactory protocolFactory) { - String protocolFactoryName = null; - - try { - protocolFactoryName = protocolFactory.getClass().getName(); - Method method = protocolFactory.getClass().getMethod("getProtocolName", new Class[] {}); - protocolFactoryName = (String) method.invoke(protocolFactory, new Object[] {}); - } catch (Exception ex) { - } - - return protocolFactoryName; - } - - private String resolveCurrentContextIdentity() { - String contextIdentity = ""; - - Object slefClassLoader = this.getClass().getClassLoader(); - Object contextClassLoader = Thread.currentThread().getContextClassLoader(); - - if (slefClassLoader != null && contextClassLoader != null && slefClassLoader != contextClassLoader) { - contextIdentity = contextClassLoader.toString(); - } - - return contextIdentity; - } - - private int convertInt(String str, int defaults) { - if (str == null) { - return defaults; - } - try { - return Integer.parseInt(str); - } catch (Exception e) { - return defaults; - } - } -} diff --git a/net/src/main/java/com/qq/tars/net/client/FutureImpl.java b/net/src/main/java/com/qq/tars/net/client/FutureImpl.java deleted file mode 100644 index 8cd8c9e4..00000000 --- a/net/src/main/java/com/qq/tars/net/client/FutureImpl.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.client; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import com.qq.tars.net.client.ticket.Ticket; - -public final class FutureImpl implements Future { - - private Ticket ticket = null; - - public FutureImpl(Ticket ticket) { - this.ticket = ticket; - } - - public boolean cancel(boolean mayInterruptIfRunning) { - return false; - } - - public V get() throws InterruptedException, ExecutionException { - this.ticket.await(); - return this.ticket.response(); - } - - public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { - this.ticket.await(timeout, unit); - return this.ticket.response(); - } - - public boolean isCancelled() { - return false; - } - - public boolean isDone() { - return ticket.isDone(); - } -} diff --git a/net/src/main/java/com/qq/tars/net/client/ticket/Ticket.java b/net/src/main/java/com/qq/tars/net/client/ticket/Ticket.java deleted file mode 100644 index d8d5cce9..00000000 --- a/net/src/main/java/com/qq/tars/net/client/ticket/Ticket.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.client.ticket; - -import java.io.IOException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import com.qq.tars.net.client.Callback; -import com.qq.tars.net.core.Request; - -public class Ticket { - - public static final int DEFAULT_TICKET_NUMBER = -1; - private CountDownLatch latch = new CountDownLatch(1); - - private T response = null; - private Request request = null; - private volatile boolean expired = false; - protected long timeout = 1000; - public long startTime = System.currentTimeMillis(); - private Callback callback = null; - private int ticketNumber = -1; - private static TicketListener ticketListener = null; - - public Ticket(Request request, long timeout) { - this.request = request; - this.ticketNumber = request.getTicketNumber(); - this.timeout = timeout; - } - - public Request request() { - return this.request; - } - - public boolean await(long timeout, TimeUnit unit) throws InterruptedException { - boolean status = this.latch.await(timeout, unit); - checkExpired(); - return status; - } - - public void await() throws InterruptedException { - this.latch.await(); - checkExpired(); - } - - public void expired() { - this.expired = true; - if (callback != null) callback.onExpired(); - this.countDown(); - if (ticketListener != null) ticketListener.onResponseExpired(this); - } - - public void countDown() { - this.latch.countDown(); - } - - public boolean isDone() { - return this.latch.getCount() == 0; - } - - public void notifyResponse(T response) { - this.response = response; - if (this.callback != null) this.callback.onCompleted(response); - if (ticketListener != null) ticketListener.onResponseReceived(this); - } - - public T response() { - return this.response; - } - - public Callback getCallback() { - return callback; - } - - public void setCallback(Callback callback) { - this.callback = callback; - } - - public int getTicketNumber() { - return this.ticketNumber; - } - - protected void checkExpired() { - if (this.expired) throw new RuntimeException("", new IOException("The operation has timed out.")); - } - - public static void setTicketListener(TicketListener listener) { - ticketListener = listener; - } -} diff --git a/net/src/main/java/com/qq/tars/net/client/ticket/TicketManager.java b/net/src/main/java/com/qq/tars/net/client/ticket/TicketManager.java deleted file mode 100644 index 547f5efe..00000000 --- a/net/src/main/java/com/qq/tars/net/client/ticket/TicketManager.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.client.ticket; - -import java.util.Collection; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import com.qq.tars.net.client.Callback; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Session; - -public class TicketManager { - - private static ConcurrentHashMap> tickets = new ConcurrentHashMap>(); - - private static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - - static { - executor.scheduleAtFixedRate(new Runnable() { - - long currentTime = -1; - - public void run() { - Collection> values = tickets.values(); - currentTime = System.currentTimeMillis(); - for (Ticket t : values) { - if ((currentTime - t.startTime) > t.timeout) { - removeTicket(t.getTicketNumber()); - t.expired(); - } - } - } - - }, 500, 500, TimeUnit.MILLISECONDS); - } - - public static void shutdown() { - executor.shutdownNow(); - } - - @SuppressWarnings("unchecked") - public static Ticket getTicket(int seq) { - return (Ticket) tickets.get(seq); - } - - public static Ticket createTicket(Request req, Session session, long timeout) { - return createTicket(req, session, timeout, null); - } - - public static Ticket createTicket(Request req, Session session, long timeout, Callback callback) { - if (req.getTicketNumber() == Ticket.DEFAULT_TICKET_NUMBER) { - req.setTicketNumber(session.hashCode()); - } - - Ticket ticket = new Ticket(req, timeout); - ticket.setCallback(callback); - - if (tickets.putIfAbsent(ticket.getTicketNumber(), ticket) != null) { - throw new IllegalArgumentException("duplicate ticket number."); - } - - return ticket; - } - - public static void removeTicket(int ticketNumber) { - tickets.remove(ticketNumber); - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/IoBuffer.java b/net/src/main/java/com/qq/tars/net/core/IoBuffer.java deleted file mode 100644 index 0fcdb1ba..00000000 --- a/net/src/main/java/com/qq/tars/net/core/IoBuffer.java +++ /dev/null @@ -1,176 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core; - -import java.nio.ByteBuffer; - -public final class IoBuffer { - - private ByteBuffer buf = null; - - private IoBuffer(ByteBuffer buf) { - this.buf = buf; - } - - public static IoBuffer wrap(ByteBuffer buf) { - return new IoBuffer(buf); - } - - public static IoBuffer wrap(byte[] buf) { - return new IoBuffer(ByteBuffer.wrap(buf)); - } - - public static IoBuffer allocate(int capacity) { - return new IoBuffer(ByteBuffer.allocate(capacity)); - } - - public static IoBuffer allocateDirect(int capacity) { - return new IoBuffer(ByteBuffer.allocateDirect(capacity)); - } - - public byte get() { - return this.buf.get(); - } - - public IoBuffer get(byte[] dst) { - this.buf.get(dst); - return this; - } - - public IoBuffer get(byte[] dst, int offset, int length) { - this.buf.get(dst, offset, length); - return this; - } - - public short getShort() { - return this.buf.getShort(); - } - - public int getInt() { - return this.buf.getInt(); - } - - public IoBuffer put(byte value) { - return put(new byte[] { value }); - } - - public IoBuffer put(byte[] src) { - return put(src, 0, src.length); - } - - public IoBuffer put(byte[] src, int offset, int length) { - autoExpand(src.length, offset, length); - this.buf.put(src, offset, length); - return this; - } - - public IoBuffer put(char c) { - this.buf.putChar(c); - return this; - } - - public IoBuffer putShort(short value) { - this.buf.putShort(value); - return this; - } - - public IoBuffer put(int value) { - this.buf.putInt(value); - return this; - } - - public final IoBuffer flip() { - this.buf.flip(); - return this; - } - - public final byte get(int index) { - return this.buf.get(index); - } - - public final IoBuffer unflip() { - buf.position(buf.limit()); - if (buf.limit() != buf.capacity()) buf.limit(buf.capacity()); - return this; - } - - public final IoBuffer rewind() { - this.buf.rewind(); - return this; - } - - public final int remaining() { - return this.buf.remaining(); - } - - public final IoBuffer mark() { - this.buf.mark(); - return this; - } - - public final IoBuffer reset() { - this.buf.reset(); - return this; - } - - public final int position() { - return this.buf.position(); - } - - public final IoBuffer position(int newPosition) { - this.buf.position(newPosition); - return this; - } - - public final IoBuffer duplicate() { - return IoBuffer.wrap(this.buf.duplicate()); - } - - public final IoBuffer compact() { - this.buf.compact(); - return this; - } - - public final ByteBuffer buf() { - return this.buf; - } - - private void autoExpand(int size, int offset, int length) { - int newCapacity = this.buf.capacity(); - int newSize = this.buf.position() + length; - ByteBuffer newBuffer = null; - - if (size < length) throw new IndexOutOfBoundsException(); - - while (newSize > newCapacity) { - newCapacity = newCapacity * 2; - } - - if (newCapacity != this.buf.capacity()) { - if (this.buf.isDirect()) { - newBuffer = ByteBuffer.allocateDirect(newCapacity); - } else { - newBuffer = ByteBuffer.allocate(newCapacity); - } - - newBuffer.put(this.buf.array()); - newBuffer.position(this.buf.position()); - - this.buf = newBuffer; - } - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/Server.java b/net/src/main/java/com/qq/tars/net/core/Server.java deleted file mode 100644 index aa577964..00000000 --- a/net/src/main/java/com/qq/tars/net/core/Server.java +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.channels.DatagramChannel; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.ServerSocketChannel; -import java.util.Properties; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.Executor; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import com.qq.tars.net.core.nio.SelectorManager; -import com.qq.tars.net.protocol.ProtocolFactory; -import com.qq.tars.net.util.Utils; - -public abstract class Server { - - private String host = null; - - private int port = DEFAULT_MAIN_PORT; - - private static final int DEFAULT_MAIN_PORT = 9000; - - private ProtocolFactory protocolFactory = null; - - private SelectorManager selectorManager = null; - - private Processor processor = null; - - private Executor threadPool = null; - - private Properties props = new Properties(); - - private int minPoolSize = 10; - - private int maxPoolSize = 128; - - private boolean keepAlive = true; - - private boolean udpMode = false; - - public enum ServerConf { - SERVER_LOCAL_IP, SERVER_BIND_PORT, SERVER_THREAD_POOL_MAX, SERVER_THREAD_POOL_MIN, SERVER_KEEP_ALIVE - } - - public Server(String ip, int port) throws IOException { - this(ip, port, null, null, false); - } - - public Server(String ip, int port, boolean udpMode) throws IOException { - this(ip, port, null, null, udpMode); - } - - public Server(String ip, int port, ProtocolFactory protocolFactory, Processor processor, boolean udpMode) throws IOException { - initServerConfig(); - - this.host = ip; - this.port = port; - this.udpMode = udpMode; - this.protocolFactory = protocolFactory; - this.processor = processor; - this.threadPool = new ThreadPoolExecutor(minPoolSize, maxPoolSize, 120, TimeUnit.SECONDS, new ArrayBlockingQueue(20000)); - this.selectorManager = new SelectorManager(Utils.getSelectorPoolSize(), protocolFactory, threadPool, processor, keepAlive, "server", this.udpMode); - } - - public void startUp(String args[]) throws Exception { - startNIOServer(); - - if (!this.udpMode) SessionManager.getSessionManager().start(); - } - - protected void startNIOServer() throws Exception { - SelectableChannel server = null; - int interestKey; - - //1. Start reactor service - selectorManager.start(); - - //2. Start server on the specified port - if (this.udpMode) { - server = DatagramChannel.open(); - ((DatagramChannel) server).socket().bind(new InetSocketAddress(host, port)); - interestKey = SelectionKey.OP_READ; - } else { - server = ServerSocketChannel.open(); - ((ServerSocketChannel) server).socket().bind(new InetSocketAddress(host, port), 1024); - interestKey = SelectionKey.OP_ACCEPT; - - } - - server.configureBlocking(false); - - //3. Choose one reactor to handle NIO event - selectorManager.getReactor(0).registerChannel(server, interestKey); - System.out.println("INFO: NAMI Server started on port " + String.valueOf(port) + "..."); - - } - - protected void initServerConfig() { - try { - props.load(Utils.loadConfigFile("server.properties", Server.class)); - minPoolSize = Integer.valueOf(props.getProperty("nami_min_thread", "10")); - maxPoolSize = Integer.valueOf(props.getProperty("nami_max_thread", "128")); - keepAlive = Boolean.valueOf(props.getProperty("nami_keep_alive", "true")); - } catch (Exception ex) { - System.out.println("ERROR: Failed to init server config file..."); - ex.printStackTrace(); - } - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public ProtocolFactory getProtocolFactory() { - return protocolFactory; - } - - public void setProtocolFactory(ProtocolFactory protocolFactory) { - this.protocolFactory = protocolFactory; - } - - public Processor getProcessor() { - return processor; - } - - public void setProcessor(Processor processor) { - this.processor = processor; - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/Session.java b/net/src/main/java/com/qq/tars/net/core/Session.java deleted file mode 100644 index 7123f7f5..00000000 --- a/net/src/main/java/com/qq/tars/net/core/Session.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core; - -import java.io.IOException; -import java.nio.channels.SelectableChannel; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import com.qq.tars.net.protocol.ProtocolFactory; - -public abstract class Session { - - protected SessionStatus status = SessionStatus.NOT_CONNECTED; - - protected long lastOperationTime = System.currentTimeMillis(); - - protected boolean keepAlive = true; - - protected CountDownLatch connectLatch = new CountDownLatch(1); - - public static enum SessionStatus { - NOT_CONNECTED, CLIENT_CONNECTED, SERVER_CONNECTED, CLOSED - } - - public abstract void close() throws IOException; - - public abstract void asyncClose() throws IOException; - - protected abstract void read() throws IOException; - - protected abstract void accept() throws IOException; - - public abstract void write(Request request) throws IOException; - - public abstract void write(Response response) throws IOException; - - public abstract void setChannel(SelectableChannel channel) throws IOException; - - public abstract String getRemoteIp(); - - public abstract int getRemotePort(); - - public abstract ProtocolFactory getProtocolFactory(); - - public SessionStatus getStatus() { - return status; - } - - public void setStatus(SessionStatus status) { - this.status = status; - } - - public void finishConnect() { - this.connectLatch.countDown(); - } - - public boolean waitToConnect(long connectTimeout) { - try { - return this.connectLatch.await(connectTimeout, TimeUnit.MILLISECONDS); - } catch (Exception ex) { - ex.printStackTrace(); - } - return false; - } - - public void updateLastOperationTime() { - this.lastOperationTime = System.currentTimeMillis(); - } - - public long getLastOperationTime() { - return this.lastOperationTime; - } - - public void setKeepAlive(boolean keepAlive) { - this.keepAlive = keepAlive; - } - - public boolean isKeepAlive() { - return this.keepAlive; - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/SessionManager.java b/net/src/main/java/com/qq/tars/net/core/SessionManager.java deleted file mode 100644 index 76a7c99d..00000000 --- a/net/src/main/java/com/qq/tars/net/core/SessionManager.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core; - -import com.qq.tars.net.core.nio.SessionManagerImpl; - -public abstract class SessionManager { - - private static SessionManager manager = new SessionManagerImpl(); - - public abstract void registerSession(Session session); - - public abstract void unregisterSession(Session session); - - public abstract void addSessionListener(SessionListener listener); - - public abstract void setTimeout(long timeout); - - public abstract void setCheckInterval(long interval); - - public abstract void start(); - - public static SessionManager getSessionManager() { - return manager; - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/nio/Acceptor.java b/net/src/main/java/com/qq/tars/net/core/nio/Acceptor.java deleted file mode 100644 index 81fa4402..00000000 --- a/net/src/main/java/com/qq/tars/net/core/nio/Acceptor.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core.nio; - -import java.io.IOException; -import java.nio.channels.SelectionKey; - -public abstract class Acceptor { - - protected SelectorManager selectorManager = null; - - public Acceptor(SelectorManager selectorManager) { - this.selectorManager = selectorManager; - } - - public abstract void handleConnectEvent(SelectionKey key) throws IOException; - - public abstract void handleAcceptEvent(SelectionKey key) throws IOException; - - public abstract void handleReadEvent(SelectionKey key) throws IOException; - - public abstract void handleWriteEvent(SelectionKey key) throws IOException; - -} diff --git a/net/src/main/java/com/qq/tars/net/core/nio/Reactor.java b/net/src/main/java/com/qq/tars/net/core/nio/Reactor.java deleted file mode 100644 index 7a38cb46..00000000 --- a/net/src/main/java/com/qq/tars/net/core/nio/Reactor.java +++ /dev/null @@ -1,188 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core.nio; - -import java.io.IOException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.SocketChannel; -import java.util.Iterator; -import java.util.Queue; -import java.util.concurrent.LinkedBlockingQueue; - -import com.qq.tars.net.core.Session; - -public final class Reactor extends Thread { - - protected volatile Selector selector = null; - - private volatile boolean crashed = false; - - private final Queue register = new LinkedBlockingQueue(); - - private final Queue unregister = new LinkedBlockingQueue(); - - private Acceptor acceptor = null; - - public Reactor(SelectorManager selectorManager, String name) throws IOException { - this(selectorManager, name, false); - } - - public Reactor(SelectorManager selectorManager, String name, boolean udpMode) throws IOException { - super(name); - - if (udpMode) { - this.acceptor = new UDPAcceptor(selectorManager); - } else { - this.acceptor = new TCPAcceptor(selectorManager); - } - - this.selector = Selector.open(); - } - - public void registerChannel(SelectableChannel channel, int ops) throws IOException { - registerChannel(channel, ops, null); - } - - public void unRegisterChannel(Session session) { - if (this.unregister.contains(session)) return; - this.unregister.add(session); - this.selector.wakeup(); - } - - public void registerChannel(SelectableChannel channel, int ops, Object attachment) throws IOException { - if (crashed) { - throw new IOException("The reactor thread carsh.... "); - } - - if (Thread.currentThread() == this) { - SelectionKey key = channel.register(this.selector, ops, attachment); - - if (attachment instanceof TCPSession) { - ((TCPSession) attachment).setKey(key); - } - } else { - this.register.offer(new Object[] { channel, ops, attachment }); - this.selector.wakeup(); - } - } - - public void run() { - try { - while (!Thread.interrupted()) { - selector.select(); - processRegister(); - Iterator iter = selector.selectedKeys().iterator(); - while (iter.hasNext()) { - SelectionKey key = iter.next(); - iter.remove(); - - if (!key.isValid()) continue; - - try { - //1. Update the last operation time - if (key.attachment() != null && key.attachment() instanceof Session) { - ((Session) key.attachment()).updateLastOperationTime(); - } - - //2. Dispatch I/O event - dispatchEvent(key); - - } catch (Throwable ex) { - disConnectWithException(key, ex); - } - } - processUnRegister(); - } - } catch (Throwable e) { - crashed = true; - e.printStackTrace(); - } finally { - try { - selector.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - private void disConnectWithException(final SelectionKey key, final Throwable ex) { - try { - Session session = (Session) key.attachment(); - - if (session == null) { - if (key.channel() instanceof SocketChannel) key.channel().close(); - } else { - session.close(); - } - - ex.printStackTrace(); - } catch (Throwable e2) { - ex.printStackTrace(); - } - } - - private void processUnRegister() { - Session session = null; - - while ((session = this.unregister.poll()) != null) { - try { - ((TCPSession) session).close(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - private void processRegister() { - Object[] object = null; - SelectableChannel channel = null; - int ops = -1; - Object attachment = null; - - while ((object = this.register.poll()) != null) { - try { - channel = (SelectableChannel) object[0]; - ops = (Integer) object[1]; - attachment = object[2]; - - if (!channel.isOpen()) continue; - - SelectionKey key = channel.register(this.selector, ops, attachment); - - if (attachment instanceof TCPSession) { - ((TCPSession) attachment).setKey(key); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - private void dispatchEvent(final SelectionKey key) throws IOException { - if (key.isConnectable()) { - acceptor.handleConnectEvent(key); - } else if (key.isAcceptable()) { - acceptor.handleAcceptEvent(key); - } else if (key.isReadable()) { - acceptor.handleReadEvent(key); - } else if (key.isValid() && key.isWritable()) { - acceptor.handleWriteEvent(key); - } - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/nio/SelectorManager.java b/net/src/main/java/com/qq/tars/net/core/nio/SelectorManager.java deleted file mode 100644 index 64e37607..00000000 --- a/net/src/main/java/com/qq/tars/net/core/nio/SelectorManager.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core.nio; - -import java.io.IOException; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.util.concurrent.Executor; -import java.util.concurrent.atomic.AtomicLong; - -import com.qq.tars.net.core.Processor; -import com.qq.tars.net.protocol.ProtocolFactory; - -public final class SelectorManager { - - private final AtomicLong sets = new AtomicLong(0); - - private final Reactor[] reactorSet; - - private ProtocolFactory protocolFactory = null; - - private Executor threadPool = null; - - private Processor processor = null; - - private final int selectorPoolSize; - - private volatile boolean started; - - private boolean keepAlive; - - private boolean isTcpNoDelay = false; - - public SelectorManager(int selectorPoolSize, ProtocolFactory protocolFactory, Executor threadPool, - Processor processor, boolean keepAlive, String reactorNamePrefix) throws IOException { - this(selectorPoolSize, protocolFactory, threadPool, processor, keepAlive, reactorNamePrefix, false); - } - - public SelectorManager(int selectorPoolSize, ProtocolFactory protocolFactory, Executor threadPool, - Processor processor, boolean keepAlive, String reactorNamePrefix, boolean udpMode) throws IOException { - if (udpMode) selectorPoolSize = 1; - - this.selectorPoolSize = selectorPoolSize; - this.protocolFactory = protocolFactory; - this.threadPool = threadPool; - this.processor = processor; - this.keepAlive = keepAlive; - - reactorSet = new Reactor[selectorPoolSize]; - - for (int i = 0; i < reactorSet.length; i++) { - reactorSet[i] = new Reactor(this, reactorNamePrefix + "-" + protocolFactory.getClass().getSimpleName().toLowerCase() + "-" + String.valueOf(i), udpMode); - } - } - - public synchronized void start() { - if (this.started) { - return; - } - - this.started = true; - for (Reactor reactor : this.reactorSet) { - reactor.start(); - } - } - - public synchronized void stop() { - if (!this.started) return; - - this.started = false; - for (Reactor reactor : this.reactorSet) { - reactor.interrupt(); - } - } - - public Reactor getReactor(int index) { - if (index < 0 || index > this.reactorSet.length - 1) { - throw new IllegalArgumentException("failed to get one reactor thread..."); - } - - return this.reactorSet[index]; - } - - public final Reactor nextReactor() { - return this.reactorSet[(int) (this.sets.incrementAndGet() % this.selectorPoolSize)]; - } - - public final Reactor getReactor(SelectionKey key) { - Reactor reactor = null; - Selector selector = key.selector(); - - for (int i = 0; i < this.reactorSet.length; i++) { - reactor = this.reactorSet[i]; - if (reactor.selector == selector) { - return reactor; - } - } - - return null; - } - - public ProtocolFactory getProtocolFactory() { - return protocolFactory; - } - - public void setProtocolFactory(ProtocolFactory protocolFactory) { - this.protocolFactory = protocolFactory; - } - - public Processor getProcessor() { - return processor; - } - - public void setProcessor(Processor processor) { - this.processor = processor; - } - - public Executor getThreadPool() { - return threadPool; - } - - public void setThreadPool(Executor threadPool) { - this.threadPool = threadPool; - } - - public boolean isKeepAlive() { - return keepAlive; - } - - public boolean isTcpNoDelay() { - return isTcpNoDelay; - } - - public void setTcpNoDelay(boolean on) { - this.isTcpNoDelay = on; - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/nio/SessionManagerImpl.java b/net/src/main/java/com/qq/tars/net/core/nio/SessionManagerImpl.java deleted file mode 100644 index 0f394677..00000000 --- a/net/src/main/java/com/qq/tars/net/core/nio/SessionManagerImpl.java +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core.nio; - -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import com.qq.tars.net.core.Session; -import com.qq.tars.net.core.SessionEvent; -import com.qq.tars.net.core.SessionListener; -import com.qq.tars.net.core.SessionManager; - -public class SessionManagerImpl extends SessionManager { - - private long timeout = 1000 * 60 * 1; - - private long interval = 1000 * 30; - - private List listeners = new LinkedList(); - - private CopyOnWriteArrayList sessionList = new CopyOnWriteArrayList(); - - private volatile boolean started = false; - - public void registerSession(Session session) { - sessionList.add(session); - notifySessionCreated(session); - } - - public void unregisterSession(Session session) { - sessionList.remove(session); - notifySessionDestory(session); - } - - @Override - public void addSessionListener(SessionListener listener) { - this.listeners.add(listener); - } - - private void notifySessionCreated(Session newSession) { - for (SessionListener listener : listeners) { - try { - listener.onSessionCreated(new SessionEvent(newSession)); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - private void notifySessionDestory(Session oldSession) { - for (SessionListener listener : listeners) { - try { - listener.onSessionDestoryed(new SessionEvent(oldSession)); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - public synchronized void start() { - if (started) return; - - new Thread(new Runnable() { - - public void run() { - System.out.println("The session manager service started..."); - - long lastUpdateOperationTime = -1; - - while (true) { - try { - for (Session session : sessionList) { - lastUpdateOperationTime = session.getLastOperationTime(); - if ((System.currentTimeMillis() - lastUpdateOperationTime) > timeout) { - String s = "The session has timed out. [from ip: " + session.getRemoteIp() + " port: " + session.getRemotePort() + "]"; - System.out.println(s); - session.asyncClose(); -// unregisterSession(session); - } - } - - Thread.sleep(interval); - } catch (Exception ex) { - } - } - } - - }, "SessionManageImpl Thread").start(); - - started = true; - } - - public void setCheckInterval(long interval) { - this.interval = interval; - } - - public void setTimeout(long timeout) { - this.timeout = timeout; - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/nio/TCPAcceptor.java b/net/src/main/java/com/qq/tars/net/core/nio/TCPAcceptor.java deleted file mode 100644 index 0a6e7d4c..00000000 --- a/net/src/main/java/com/qq/tars/net/core/nio/TCPAcceptor.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core.nio; - -import java.io.IOException; -import java.nio.channels.SelectionKey; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; - -import com.qq.tars.net.core.SessionManager; -import com.qq.tars.net.core.Session.SessionStatus; -import com.qq.tars.net.util.Utils; - -public class TCPAcceptor extends Acceptor { - - public TCPAcceptor(SelectorManager selectorManager) { - super(selectorManager); - } - - public void handleConnectEvent(SelectionKey key) throws IOException { - //1. Get the client channel - SocketChannel client = (SocketChannel) key.channel(); - - //2. Set the session status - TCPSession session = (TCPSession) key.attachment(); - if (session == null) throw new RuntimeException("The session is null when connecting to ..."); - - //3. Connect to server - try { - client.finishConnect(); - key.interestOps(SelectionKey.OP_READ); - session.setStatus(SessionStatus.CLIENT_CONNECTED); - } finally { - session.finishConnect(); - } - } - - public void handleAcceptEvent(SelectionKey key) throws IOException { - //1. Accept TCP request - ServerSocketChannel server = (ServerSocketChannel) key.channel(); - SocketChannel channel = server.accept(); - channel.socket().setTcpNoDelay(selectorManager.isTcpNoDelay()); - channel.configureBlocking(false); - Utils.setQosFlag(channel.socket()); - - //2. Create NioSession for each TCP connection - TCPSession session = new TCPSession(selectorManager); - session.setChannel(channel); - session.setStatus(SessionStatus.SERVER_CONNECTED); - session.setKeepAlive(selectorManager.isKeepAlive()); - session.setTcpNoDelay(selectorManager.isTcpNoDelay()); - - //3. Register session - SessionManager.getSessionManager().registerSession(session); - - //4. Register channel with the specified session - selectorManager.nextReactor().registerChannel(channel, SelectionKey.OP_READ, session); - } - - public void handleReadEvent(SelectionKey key) throws IOException { - TCPSession session = (TCPSession) key.attachment(); - if (session == null) throw new RuntimeException("The session is null when reading data..."); - session.read(); - } - - public void handleWriteEvent(SelectionKey key) throws IOException { - TCPSession session = (TCPSession) key.attachment(); - if (session == null) throw new RuntimeException("The session is null when writing data..."); - session.doWrite(); - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/nio/TCPSession.java b/net/src/main/java/com/qq/tars/net/core/nio/TCPSession.java deleted file mode 100644 index 848334c9..00000000 --- a/net/src/main/java/com/qq/tars/net/core/nio/TCPSession.java +++ /dev/null @@ -1,336 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core.nio; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; -import java.util.Queue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.atomic.AtomicInteger; - -import com.qq.tars.net.client.ticket.Ticket; -import com.qq.tars.net.core.IoBuffer; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; -import com.qq.tars.net.core.SessionManager; -import com.qq.tars.net.protocol.ProtocolException; -import com.qq.tars.net.protocol.ProtocolFactory; - -public class TCPSession extends Session { - - private SelectionKey key = null; - - private SelectableChannel channel = null; - - private SelectorManager selectorManager = null; - - private int bufferSize = 1024 * 4; - - private IoBuffer readBuffer = null; - - private boolean tcpNoDelay = false; - - private Queue queue = new LinkedBlockingQueue(1024 * 8); - - private static final AtomicInteger hashCodeGenerator = new AtomicInteger(); - - private int hashCode = 0; - - public TCPSession(SelectorManager selectorManager) { - this.selectorManager = selectorManager; - this.hashCode = hashCodeGenerator.incrementAndGet(); - } - - public void asyncClose() throws IOException { - if (this.key == null) return; //Already closed if the key is null. - - Reactor reactor = selectorManager.getReactor(this.key); - - if (reactor != null) { - reactor.unRegisterChannel(this); - } else { - throw new IOException("failed to find the selector for this session."); - } - } - - public void close() throws IOException { - if (this.status == SessionStatus.CLOSED) return; - - this.status = SessionStatus.CLOSED; - try { - if (channel != null) channel.close(); - if (key != null) key.cancel(); - }catch(IOException e){ - /*ignore IOException ,when client first clost connection,it cannot be fast unregisterSession*/ - } - - this.key = null; - this.channel = null; - - SessionManager.getSessionManager().unregisterSession(this); - } - - protected void read() throws IOException { - int ret = readChannel(); - - if (this.status == SessionStatus.CLIENT_CONNECTED) { - readResponse(); - } else if (this.status == SessionStatus.SERVER_CONNECTED) { - readRequest(); - } else { - throw new IllegalStateException("The current session status is invalid. [status:" + this.status + "]"); - } - - if (ret < 0) { - close(); - return; - } - } - - public void readRequest() throws IOException { - Request request = null; - IoBuffer tempBuffer = null; - - try { - tempBuffer = readBuffer.duplicate().flip(); - - while (true) { - tempBuffer.mark(); - - if (tempBuffer.remaining() > 0) { - request = selectorManager.getProtocolFactory().getDecoder().decodeRequest(tempBuffer, this); - } else { - request = null; - } - - if (request != null) { - try { - request.resetBornTime(); - selectorManager.getThreadPool().execute(new WorkThread(request, selectorManager)); - } catch (Exception ex) { - ex.printStackTrace(); - } - } else { - tempBuffer.reset(); - readBuffer = resetIoBuffer(tempBuffer); - break; - } - } - } catch (ProtocolException ex) { - close(); - ex.printStackTrace(); - } - } - - public void readResponse() throws IOException { - Response response = null; - IoBuffer tempBuffer = null; - - try { - tempBuffer = readBuffer.duplicate().flip(); - - while (true) { - tempBuffer.mark(); - - if (tempBuffer.remaining() > 0) { - response = selectorManager.getProtocolFactory().getDecoder().decodeResponse(tempBuffer, this); - } else { - response = null; - } - - if (response != null) { - try { - if (response.getTicketNumber() == Ticket.DEFAULT_TICKET_NUMBER) response.setTicketNumber(response.getSession().hashCode()); - selectorManager.getThreadPool().execute(new WorkThread(response, selectorManager)); - } catch (Exception ex) { - ex.printStackTrace(); - } - } else { - tempBuffer.reset(); - readBuffer = resetIoBuffer(tempBuffer); - break; - } - } - - } catch (ProtocolException ex) { - close(); - ex.printStackTrace(); - } - } - - public void write(Request request) throws IOException { - try { - IoBuffer buffer = selectorManager.getProtocolFactory().getEncoder().encodeRequest(request, this); - write(buffer); - } catch (ProtocolException ex) { - throw new IOException("protocol error:", ex); - } - } - - public void write(Response response) throws IOException { - try { - IoBuffer buffer = selectorManager.getProtocolFactory().getEncoder().encodeResponse(response, this); - write(buffer); - } catch (ProtocolException ex) { - throw new IOException("protocol error:", ex); - } - } - - public String getRemoteIp() { - if (this.status != SessionStatus.CLOSED) { - return ((SocketChannel) this.channel).socket().getInetAddress().getHostAddress(); - } - - return null; - } - - public int getRemotePort() { - if (this.status != SessionStatus.CLOSED) { - return ((SocketChannel) this.channel).socket().getPort(); - } - - return -1; - } - - public void accept() throws IOException { - } - - protected void write(IoBuffer buffer) throws IOException { - if (buffer == null) return; - - if (channel == null || key == null) throw new IOException("Connection is closed"); - - if (!this.queue.offer(buffer.buf())) { - throw new IOException("The session queue is full. [ queue size:" + queue.size() + " ]"); - } - - if (key != null) { - key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); - key.selector().wakeup(); - } - } - - protected synchronized int doWrite() throws IOException { - int writeBytes = 0; - - while (true) { - ByteBuffer wBuf = queue.peek(); - - if (wBuf == null) { - key.interestOps(SelectionKey.OP_READ); - - if (queue.peek() != null) { - key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); - } - - key.selector().wakeup(); - break; - } - - int bytesWritten = ((SocketChannel) channel).write(wBuf); - - if (bytesWritten == 0 && wBuf.remaining() > 0) // Socket buffer is full. - { - key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); - key.selector().wakeup(); - break; - } - - if (wBuf.remaining() == 0) { - writeBytes++; - queue.remove(); - continue; - } else { - return -1; - } - } - - if (!isKeepAlive()) close(); - - return writeBytes; - } - - protected IoBuffer resetIoBuffer(IoBuffer buffer) { - IoBuffer newBuffer = null; - - if (buffer != null && buffer.remaining() > 0) { - int len = buffer.remaining(); - byte[] bb = new byte[len]; - buffer.get(bb); - newBuffer = IoBuffer.wrap(bb); - newBuffer.position(len); - } - - return newBuffer; - } - - public SelectionKey getKey() { - return key; - } - - public void setKey(SelectionKey key) { - this.key = key; - } - - public boolean isTcpNoDelay() { - return tcpNoDelay; - } - - public void setTcpNoDelay(boolean on) { - this.tcpNoDelay = on; - } - - public SelectableChannel getChannel() { - return channel; - } - - public void setChannel(SelectableChannel channel) { - this.channel = channel; - } - - public ProtocolFactory getProtocolFactory() { - return this.selectorManager.getProtocolFactory(); - } - - private int readChannel() throws IOException { - int readBytes = 0, ret = 0; - - ByteBuffer data = ByteBuffer.allocate(1024 * 2); - - if (readBuffer == null) { - readBuffer = IoBuffer.allocate(bufferSize); - } - - while ((ret = ((SocketChannel) channel).read(data)) > 0) { - data.flip(); - readBytes += data.remaining(); - readBuffer.put(data.array(), data.position(), data.remaining()); - data.clear(); - } - - return ret < 0 ? ret : readBytes; - } - - @Override - public int hashCode() { - return this.hashCode; - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/nio/UDPAcceptor.java b/net/src/main/java/com/qq/tars/net/core/nio/UDPAcceptor.java deleted file mode 100644 index be503f30..00000000 --- a/net/src/main/java/com/qq/tars/net/core/nio/UDPAcceptor.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core.nio; - -import java.io.IOException; -import java.nio.channels.SelectionKey; - -import com.qq.tars.net.core.Session.SessionStatus; - -public class UDPAcceptor extends Acceptor { - - private int bufferSize; - - public UDPAcceptor(SelectorManager selectorManager) { - super(selectorManager); - String s = System.getProperty("com.qq.nami.server.udp.bufferSize", "4096"); - try { - bufferSize = Integer.parseInt(s); - } catch (NumberFormatException e) { - bufferSize = 4096; - } - } - - @Override - public void handleConnectEvent(SelectionKey key) throws IOException { - throw new IllegalStateException("UDP can't handle OP_CONNECT event"); - } - - @Override - public void handleAcceptEvent(SelectionKey key) throws IOException { - throw new IllegalStateException("UDP can't handle OP_ACCEPT event"); - } - - @Override - public void handleReadEvent(SelectionKey key) throws IOException { - UDPSession session = null; - - if (key.attachment() == null) // server side - { - session = new UDPSession(this.selectorManager); - session.setBufferSize(bufferSize); - session.setChannel(key.channel()); - session.setStatus(SessionStatus.SERVER_CONNECTED); - } else // client side - { - session = (UDPSession) key.attachment(); - } - - session.read(); - - } - - @Override - public void handleWriteEvent(SelectionKey key) throws IOException { - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/nio/UDPSession.java b/net/src/main/java/com/qq/tars/net/core/nio/UDPSession.java deleted file mode 100644 index 10b6e09b..00000000 --- a/net/src/main/java/com/qq/tars/net/core/nio/UDPSession.java +++ /dev/null @@ -1,174 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core.nio; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.DatagramChannel; -import java.nio.channels.SelectableChannel; - -import com.qq.tars.net.client.ticket.Ticket; -import com.qq.tars.net.core.IoBuffer; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; -import com.qq.tars.net.protocol.ProtocolEncoder; -import com.qq.tars.net.protocol.ProtocolException; -import com.qq.tars.net.protocol.ProtocolFactory; - -public class UDPSession extends Session { - - private int bufferSize = 1024 * 4; - - private SelectorManager selectorManager = null; - - private SelectableChannel channel = null; - - private SocketAddress target = null; - - public UDPSession(SelectorManager selectorManager) { - this.selectorManager = selectorManager; - } - - public SelectableChannel getChannel() { - return channel; - } - - public void setBufferSize(int size) { - if (size <= 0 || size > 1024 * 64) return; - this.bufferSize = size; - } - - public void setChannel(SelectableChannel channel) { - this.channel = channel; - } - - @Override - protected void accept() throws IOException { - throw new IllegalStateException("Can't handle accept method."); - } - - @Override - public void asyncClose() throws IOException { - close(); - } - - @Override - public void close() throws IOException { - } - - @Override - public String getRemoteIp() { - if (this.target != null) { - return ((InetSocketAddress) target).getAddress().getHostAddress(); - } - - return null; - } - - @Override - public int getRemotePort() { - if (this.channel != null) { - return ((InetSocketAddress) target).getPort(); - } - - return 0; - } - - public ProtocolFactory getProtocolFactory() { - return this.selectorManager.getProtocolFactory(); - } - - public final void setTarget(SocketAddress address) { - if (address != null) this.target = address; - } - - @Override - protected void read() throws IOException { - ByteBuffer buffer = doRead(); - selectorManager.getThreadPool().execute(new WorkThread(this, buffer, selectorManager)); - } - - public void write(Request request) throws IOException { - try { - ProtocolFactory factory = selectorManager.getProtocolFactory(); - ProtocolEncoder encoder = factory.getEncoder(); - IoBuffer buffer = encoder.encodeRequest(request, this); - int size = ((DatagramChannel) this.channel).send(buffer.buf(), target); - if (size <= 0) throw new IOException("failed to send data. {target=" + target + "}"); - - } catch (ProtocolException ex) { - throw new IOException("protocol error:", ex); - } - } - - @Override - public void write(Response response) throws IOException { - try { - IoBuffer buffer = selectorManager.getProtocolFactory().getEncoder().encodeResponse(response, this); - int size = ((DatagramChannel) this.channel).send(buffer.buf(), target); - if (size <= 0) throw new IOException("failed to send data. {target=" + target + "}"); - } catch (ProtocolException ex) { - throw new IOException("protocol error:", ex); - } - } - - public ByteBuffer doRead() throws IOException { - ByteBuffer data = ByteBuffer.allocate(bufferSize); - SocketAddress address = ((DatagramChannel) this.channel).receive(data); - data.flip(); - if (data.remaining() >= bufferSize) { - throw new IOException("package size CAN NOT >= " + bufferSize); - } - if (this.target == null) setTarget(address); - return data; - } - - Object parseDatagramPacket(ByteBuffer data) throws IOException { - try { - if (this.status == SessionStatus.CLIENT_CONNECTED) { - return readResponse(data); - } else if (this.status == SessionStatus.SERVER_CONNECTED) { - return readRequest(data); - } else { - throw new IllegalStateException("The current session status is invalid. [status:" + this.status + "]"); - } - } catch (ProtocolException ex) { - ex.printStackTrace(); - } - return null; - } - - private Response readResponse(ByteBuffer data) throws IOException, ProtocolException { - Response response = selectorManager.getProtocolFactory().getDecoder().decodeResponse(IoBuffer.wrap(data), this); - - if (response != null) { - if (response.getTicketNumber() == Ticket.DEFAULT_TICKET_NUMBER) response.setTicketNumber(response.getSession().hashCode()); - } - - return response; - } - - private Request readRequest(ByteBuffer data) throws IOException, ProtocolException { - Request request = selectorManager.getProtocolFactory().getDecoder().decodeRequest(IoBuffer.wrap(data), this); - if (request == null) throw new ProtocolException("failed to decode udp packet."); - request.resetBornTime(); - return request; - } -} diff --git a/net/src/main/java/com/qq/tars/net/core/nio/WorkThread.java b/net/src/main/java/com/qq/tars/net/core/nio/WorkThread.java deleted file mode 100644 index 56f765ba..00000000 --- a/net/src/main/java/com/qq/tars/net/core/nio/WorkThread.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.core.nio; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.Map; - -import com.qq.tars.net.client.ticket.Ticket; -import com.qq.tars.net.client.ticket.TicketManager; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; - -public final class WorkThread implements Runnable { - - private Request req; - - private Response resp; - - private SelectorManager selectorManager = null; - - public Request getRequest() { - return req; - } - - WorkThread(Response resp, SelectorManager selectorManager) { - this.resp = resp; - udpSession = null; - } - - WorkThread(Request req, SelectorManager selectorManager) { - this.req = req; - udpSession = null; - this.selectorManager = selectorManager; - } - - private final UDPSession udpSession; - - private ByteBuffer udpBuffer; - - WorkThread(UDPSession session, ByteBuffer buffer, SelectorManager selectorManager) { - this.udpSession = session; - this.udpBuffer = buffer; - this.selectorManager = selectorManager; - } - - private void parseDatagramPacket() throws IOException { - Object obj = this.udpSession.parseDatagramPacket(udpBuffer); - if (obj instanceof Request) { - this.req = (Request) obj; - } else if (obj instanceof Response) { - this.resp = (Response) obj; - } - } - - public void run() { - try { - if (udpSession != null) { - parseDatagramPacket(); - udpBuffer = null; - } - - if (req != null) { - req.setProcessTime(System.currentTimeMillis()); - req.init(); - Response res = selectorManager.getProcessor().process(req, req.getIoSession()); - if (!res.isAsyncMode()) req.getIoSession().write(res); - } else if (resp != null) { - resp.init(); - Ticket ticket = TicketManager.getTicket(resp.getTicketNumber()); - if (ticket == null) { - String s = "failed to fetch request for this response. [from:" + resp.getSession().getRemoteIp() + ":" + resp.getSession().getRemotePort() + "]"; - System.out.println(s); - return; - } - fillDitributedContext(ticket.request().getDistributedContext()); - ticket.notifyResponse(resp); - ticket.countDown(); - TicketManager.removeTicket(ticket.getTicketNumber()); - } - } catch (Exception ex) { - ex.printStackTrace(); - } finally { - clearDistributedContext(); - } - } - - private void fillDitributedContext(Map data) { - } - - private void clearDistributedContext() { - } -} diff --git a/net/src/main/java/com/qq/tars/net/protocol/ProtocolDecoder.java b/net/src/main/java/com/qq/tars/net/protocol/ProtocolDecoder.java deleted file mode 100644 index 314c13db..00000000 --- a/net/src/main/java/com/qq/tars/net/protocol/ProtocolDecoder.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.protocol; - -import com.qq.tars.net.core.IoBuffer; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; - -public interface ProtocolDecoder { - - public Request decodeRequest(IoBuffer buff, Session session) throws ProtocolException; - - public Response decodeResponse(IoBuffer buff, Session session) throws ProtocolException; -} diff --git a/net/src/main/java/com/qq/tars/net/protocol/ProtocolEncoder.java b/net/src/main/java/com/qq/tars/net/protocol/ProtocolEncoder.java deleted file mode 100644 index 3052f3b8..00000000 --- a/net/src/main/java/com/qq/tars/net/protocol/ProtocolEncoder.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.net.protocol; - -import com.qq.tars.net.core.IoBuffer; -import com.qq.tars.net.core.Request; -import com.qq.tars.net.core.Response; -import com.qq.tars.net.core.Session; - -public interface ProtocolEncoder { - - public IoBuffer encodeResponse(Response response, Session session) throws ProtocolException; - - public IoBuffer encodeRequest(Request request, Session session) throws ProtocolException; -} diff --git a/pom.xml b/pom.xml deleted file mode 100644 index b9042883..00000000 --- a/pom.xml +++ /dev/null @@ -1,198 +0,0 @@ - - - 4.0.0 - - org.sonatype.oss - oss-parent - 9 - - - com.tencent.tars - tars-parent - 1.6.1 - pom - Tars - Super POM For Projects - - https://github.com/TarsCloud/Tars - - - The BSD 3-Clause License - https://opensource.org/licenses/BSD-3-Clause - - - - - tencent - tars@tencent.com - - developer - - - - - - https://github.com/TarsCloud/Tars - scm:git:https://github.com/TarsCloud/TarsJava.git - scm:git:https://github.com/TarsCloud/TarsJava.git - HEAD - - - - net - distributedContext - core - tools - protobuf - spring - - - - 1.8 - 1.8 - UTF-8 - - 3.7.0 - 3.0.1 - 2.9 - 3.1.0 - 3.2.2 - 2.5.2 - 2.8.2 - 2.5.3 - - - - - - org.apache.maven.plugins - maven-source-plugin - ${maven_source_plugin_version} - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven_javadoc_plugin_version} - - - - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven_jar_plugin_version} - - - - mvn - ${maven.build.timestamp} - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven_javadoc_plugin_version} - - - attach-javadocs - - jar - - - -Xdoclint:none - - - - - - org.apache.maven.plugins - maven-source-plugin - ${maven_source_plugin_version} - - - attach-sources - - jar-no-fork - - - - - true - - - mvn - ${maven.build.timestamp} - - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven_war_plugin_version} - - - - org.apache.maven.plugins - maven-install-plugin - ${maven_install_plugin_version} - - - - org.apache.maven.plugins - maven-deploy-plugin - ${maven_deploy_plugin_version} - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven_compiler_plugin_version} - - ${java_source_version} - ${java_target_version} - ${file_encoding} - - - - org.apache.maven.plugins - maven-release-plugin - ${maven_release_plugin_version} - - true - false - release - deploy - ${arguments} - - - - - - - - release - - - - org.apache.maven.plugins - maven-gpg-plugin - - - verify - - sign - - - - - - - - - \ No newline at end of file diff --git a/protobuf/README.md b/protobuf/README.md deleted file mode 100644 index 5d78e1c8..00000000 --- a/protobuf/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# Tars框架Protobuf支持依赖 - -## 使用方法 -安装Tars-java后,在pom.xml中添加tars-proto依赖: -```xml - - com.tencent.tars - tars-protobuf - 1.6.1 - -``` -然后使用java-protobuf-plugin插件配合pb生成代码,详细使用方式参见 -> plugins/java-protobuf-plugin \ No newline at end of file diff --git a/protobuf/pom.xml b/protobuf/pom.xml deleted file mode 100644 index 379f59ae..00000000 --- a/protobuf/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - tars-parent - com.tencent.tars - 1.6.1 - - 4.0.0 - - tars-protobuf - jar - ${project.artifactId} - - - - com.tencent.tars - tars-core - ${project.parent.version} - - - com.google.protobuf - protobuf-java - 2.6.1 - - - \ No newline at end of file diff --git a/protobuf/src/main/java/com/qq/tars/rpc/protocol/proto/MethodCache.java b/protobuf/src/main/java/com/qq/tars/rpc/protocol/proto/MethodCache.java deleted file mode 100644 index 1e1cbd19..00000000 --- a/protobuf/src/main/java/com/qq/tars/rpc/protocol/proto/MethodCache.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.protocol.proto; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.concurrent.ConcurrentHashMap; - -public class MethodCache { - private ConcurrentHashMap cache = new ConcurrentHashMap(); - - private static final MethodCache instance = new MethodCache(); - - public static MethodCache getInstance() { - return instance; - } - - private MethodCache() {} - - public Object parseFrom(Class clazz, byte[] data) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { - Method method = this.cache.get(clazz); - if (method == null) { - method = clazz.getMethod("parseFrom", byte[].class); - method.setAccessible(true); - this.cache.putIfAbsent(clazz, method); - method = this.cache.get(clazz); - } - return method.invoke(null, data); - } -} diff --git a/protobuf/src/main/java/com/qq/tars/rpc/protocol/proto/ProtoCodec.java b/protobuf/src/main/java/com/qq/tars/rpc/protocol/proto/ProtoCodec.java deleted file mode 100644 index 834d1570..00000000 --- a/protobuf/src/main/java/com/qq/tars/rpc/protocol/proto/ProtoCodec.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.rpc.protocol.proto; - -import com.google.protobuf.GeneratedMessage; -import com.qq.tars.common.util.Constants; -import com.qq.tars.net.protocol.ProtocolException; -import com.qq.tars.protocol.tars.support.TarsMethodInfo; -import com.qq.tars.protocol.tars.support.TarsMethodParameterInfo; -import com.qq.tars.protocol.util.TarsHelper; -import com.qq.tars.rpc.protocol.tars.TarsCodec; -import com.qq.tars.rpc.protocol.tars.TarsServantRequest; -import com.qq.tars.rpc.protocol.tars.TarsServantResponse; - -import java.util.List; - -public class ProtoCodec extends TarsCodec { - public ProtoCodec(String charsetName) { - super(charsetName); - } - - @Override - protected byte[] encodeResult(TarsServantResponse response, String charsetName) { - TarsServantRequest request = response.getRequest(); - byte[] result = new byte[] {}; - if (TarsHelper.isPing(request.getFunctionName())) { - return result; - } - - result = ((GeneratedMessage) response.getResult()).toByteArray(); - return result; - } - - @Override - protected byte[] encodeRequestParams(TarsServantRequest request, String charsetName) throws ProtocolException { - Object[] parameter = request.getMethodParameters(); - if (TarsHelper.isCallback(request.getMethodInfo().getParametersList().get(0).getAnnotations())) { - return ((GeneratedMessage) parameter[1]).toByteArray(); - } - return ((GeneratedMessage) parameter[0]).toByteArray(); - } - - @Override - protected Object[] decodeRequestBody(byte[] data, String charset, TarsMethodInfo methodInfo) throws Exception { - List parametersList = methodInfo.getParametersList(); - return new Object[]{MethodCache.getInstance().parseFrom((Class) parametersList.get(0).getStamp(), data)}; - } - - @Override - protected Object[] decodeResponseBody(byte[] data, String charset, TarsMethodInfo methodInfo) throws Exception { - TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); - return new Object[]{MethodCache.getInstance().parseFrom((Class) returnInfo.getStamp(), data)}; - } - - @Override - protected Object[] decodeCallbackArgs(byte[] data, String charset, TarsMethodInfo methodInfo) throws Exception { - TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); - return new Object[]{MethodCache.getInstance().parseFrom((Class) returnInfo.getStamp(), data)}; - } - - public String getProtocol() { - return Constants.PROTO_PROTOCOL; - } -} diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 00000000..d618bc43 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,47 @@ +pluginManagement { + plugins { + id("org.graalvm.buildtools.native") version "0.10.6" + } +} + +rootProject.name = "tars-parent" + +// Enable version catalog +enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") + +// Core modules +include("tars-common-api") +include("tars-netty") +include("core") +project(":core").name = "tars-core" +include("tars-plugins") + +// Spring modules +include("spring") +project(":spring").name = "tars-spring-parent" +include("spring:tars-spring") +include("spring:tars-spring-boot-starter") +include("spring:tars-spring-cloud-starter") +include("spring:tars-http-extension") + +// Native image support +include("tars-native") + +// Aggregation module +include("tars-all") + +// Examples +include("examples") +project(":examples").name = "tars-examples" +include("examples:quickstart-client") +include("examples:quickstart-server") +include("examples:stress-server") +include("examples:tars-spring-boot-client") +include("examples:tars-spring-boot-http-server") +include("examples:tars-spring-boot-server") +include("examples:tars-spring-cloud-client") +include("examples:tars-spring-cloud-server") +include("examples:tars-spring-server") +include("examples:tars-native-server") +include("examples:tars-native-client") + diff --git a/spring/build.gradle.kts b/spring/build.gradle.kts new file mode 100644 index 00000000..f296bad5 --- /dev/null +++ b/spring/build.gradle.kts @@ -0,0 +1,11 @@ +// Parent module for Spring integrations +description = "Tars Spring Parent - Parent module for Spring integrations" + +// This is just a parent module, no source code +tasks.withType { + enabled = false +} + +tasks.withType { + enabled = false +} diff --git a/spring/pom.xml b/spring/pom.xml deleted file mode 100644 index 0751ac21..00000000 --- a/spring/pom.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - tars-parent - com.tencent.tars - 1.6.1 - - 4.0.0 - - tars-spring-parent - pom - - tars-spring - tars-spring-cloud-starter - tars-spring-boot-starter - - - \ No newline at end of file diff --git a/spring/tars-http-extension/build.gradle.kts b/spring/tars-http-extension/build.gradle.kts new file mode 100644 index 00000000..50b0dbcd --- /dev/null +++ b/spring/tars-http-extension/build.gradle.kts @@ -0,0 +1,14 @@ +plugins { + `java-library` +} + +description = "Tars HTTP Extension - HTTP extension for Spring Boot" + +dependencies { + api(project(":spring:tars-spring-boot-starter")) + + implementation(libs.spring.boot.starter.web) + implementation(libs.commons.lang) + + testImplementation(libs.junit) +} diff --git a/spring/tars-http-extension/src/main/java/com/qq/tars/http/WebConfiguration.java b/spring/tars-http-extension/src/main/java/com/qq/tars/http/WebConfiguration.java new file mode 100644 index 00000000..7736438e --- /dev/null +++ b/spring/tars-http-extension/src/main/java/com/qq/tars/http/WebConfiguration.java @@ -0,0 +1,18 @@ +package com.qq.tars.http; + +import com.qq.tars.http.interceptor.HttpSvrTarsReportInterceptor; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * addInterceptor + */ +@Configuration +public class WebConfiguration implements WebMvcConfigurer { + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new HttpSvrTarsReportInterceptor()); + } +} \ No newline at end of file diff --git a/spring/tars-http-extension/src/main/java/com/qq/tars/http/interceptor/HttpSvrTarsReportInterceptor.java b/spring/tars-http-extension/src/main/java/com/qq/tars/http/interceptor/HttpSvrTarsReportInterceptor.java new file mode 100644 index 00000000..de277e96 --- /dev/null +++ b/spring/tars-http-extension/src/main/java/com/qq/tars/http/interceptor/HttpSvrTarsReportInterceptor.java @@ -0,0 +1,159 @@ +package com.qq.tars.http.interceptor; + + +import com.qq.tars.client.CommunicatorConfig; +import com.qq.tars.common.support.Endpoint; +import com.qq.tars.common.util.Constants; +import com.qq.tars.protocol.util.TarsHelper; +import com.qq.tars.server.config.ConfigurationManager; +import com.qq.tars.server.config.ServantAdapterConfig; +import com.qq.tars.server.config.ServerConfig; +import com.qq.tars.server.core.TarsServantProcessor; +import com.qq.tars.support.om.OmConstants; +import com.qq.tars.support.stat.InvokeStatHelper; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.lang.Nullable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.LinkedHashMap; +import java.util.Map; + +/* +taf的http的被调的请求拦截器,做日志上报 +服务名、接口名、耗时、错误码、主调ip(nginx的ip)、被调ip、被调set信息. +打印请求的流水日志/做上报 + */ +public class HttpSvrTarsReportInterceptor implements HandlerInterceptor { + + static Logger log = LoggerFactory.getLogger(HttpSvrTarsReportInterceptor.class); + + public static final String METHOD_START_TIME = "methodStartTime"; + public static final String ARGU = "argu"; //argu占位符 + private static final String DEFAULT_HOST = "0.0.0.0";// + + String servantName = StringUtils.EMPTY; + ServantAdapterConfig servantAdapterConfig = null; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + long startTime = System.currentTimeMillis(); + request.setAttribute(METHOD_START_TIME, startTime); + return true; + } + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) { + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) { + try { + if (!(handler instanceof HandlerMethod)) { //可能会有一些跨域的预请求,不做处理.PreFlightHandler + return; + } + String funcName = getFuncName(request, handler); + long cost = getCost(request); + int result = getResult(ex); + String masterIp = request.getRemoteAddr(); //主调方的ip(nginx) + String remark = ""; //暂定为空,实际上应该表示框架异常的错误码. + printFlowLog(masterIp, funcName, cost, result, remark); + + if (StringUtils.isBlank(funcName)) { + return; + } + + //report http的被调指标 + ServerConfig serverConfig = ConfigurationManager.getInstance().getServerConfig(); + if (StringUtils.isBlank(servantName)) { + findReportConstant(serverConfig); + if (servantAdapterConfig == null) { + log.debug("servantAdapterConfig is null. please check"); + return; + } + } + + String masterName = Constants.TARS_NOT_CLIENT; + CommunicatorConfig communicatorConfig = serverConfig.getCommunicatorConfig(); + Endpoint serverEndpoint = servantAdapterConfig.getEndpoint(); + InvokeStatHelper.getInstance().addProxyStat(servantName).addInvokeTimeByServer(masterName, serverConfig.getApplication(), serverConfig.getServerName(), communicatorConfig.getSetName(), + communicatorConfig.getSetArea(), communicatorConfig.getSetID(), funcName, DEFAULT_HOST, serverEndpoint.host(), serverEndpoint.port(), result, cost); + } catch (Throwable e) { + log.error("httpSvr stat report exMsg:{}", e.getMessage(), e); + } + } + + public int getResult(@Nullable Exception ex) { + int result = Constants.INVOKE_STATUS_SUCC; //默认为成功. + if (ex != null) { + log.info("req has exception. exMsg:{}", ex.getMessage(), ex); + result = Constants.INVOKE_STATUS_EXEC; + } + return result; + } + + public long getCost(HttpServletRequest request) { + long endTime = System.currentTimeMillis(); + long startTime = (long) request.getAttribute(METHOD_START_TIME); + return endTime - startTime; + } + + /* + * 几种获取方法名的方式:从requestMapping注解中获取/从请求头的request.getRequestURI()中获取/用代理的方法的方法名. + * 最终选择从requestMappings中获取. + * request.getRequestURI() 会有restful的请求,会导致func非常多,taf的监控上接口维度会非常多. + * 代理方法的方法名,可能会重复,规则上没有限制. + */ + private String getFuncName(HttpServletRequest request, Object handler) { + String uri = ""; + HandlerMethod method = (HandlerMethod) handler; + if (method.hasMethodAnnotation(RequestMapping.class)) { + //找到类的mapping + String controllerUri = ""; + String methodUri = ""; + RequestMapping controllerMapping = AnnotationUtils.findAnnotation(((HandlerMethod) handler).getBeanType(), RequestMapping.class); + if (null != controllerMapping && controllerMapping.value() != null && controllerMapping.value().length > 0) { + controllerUri = controllerMapping.value()[0]; + } + + RequestMapping requestMapping = method.getMethodAnnotation(RequestMapping.class); + String[] values = requestMapping.value(); + if (requestMapping != null && requestMapping.value() != null && requestMapping.value().length > 0) { + methodUri = values[0]; + } else { //一些不存在的接口,会默认转到/error + log.info("requestMethod not found.requestUri:{}", request.getRequestURI()); + return StringUtils.EMPTY; + } + uri = new StringBuilder().append(controllerUri).append(methodUri).toString(); + } + + String funcName = (uri.replaceFirst("/", "").replaceAll("/", "_")); + return funcName; + } + + public void findReportConstant(ServerConfig serverConfig) { + LinkedHashMap servantAdapterConfigLinkedHashMap = serverConfig.getServantAdapterConfMap(); + for (Map.Entry entry : servantAdapterConfigLinkedHashMap.entrySet()) { //取servant的ObjName作为上报的servant. + if (!entry.getKey().equalsIgnoreCase(OmConstants.AdminServant)) { + servantName = entry.getKey(); + servantAdapterConfig = entry.getValue(); + log.info("report servantName:{}", servantName); + break; + } + } + } + + //|主调方ip|接口名|请求参数|状态码|耗时|remark + public static void printFlowLog(String masterIp, String funcName, long cost, int result, String remark) { + if (result == TarsHelper.SERVERSUCCESS && (!TarsServantProcessor.isFlowLogEnable())) return; + log.info("|{}|{}|{}|{}|{}|{}|", + masterIp, funcName, ARGU, result, cost, remark); + } +} diff --git a/spring/tars-http-extension/src/main/resources/META-INF/spring.factories b/spring/tars-http-extension/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..58ce2ee8 --- /dev/null +++ b/spring/tars-http-extension/src/main/resources/META-INF/spring.factories @@ -0,0 +1 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.qq.tars.http.WebConfiguration \ No newline at end of file diff --git a/spring/tars-spring-boot-starter/build.gradle.kts b/spring/tars-spring-boot-starter/build.gradle.kts new file mode 100644 index 00000000..bbf63d49 --- /dev/null +++ b/spring/tars-spring-boot-starter/build.gradle.kts @@ -0,0 +1,15 @@ +plugins { + `java-library` +} + +description = "Tars Spring Boot Starter - Spring Boot starter for Tars" + +dependencies { + api(project(":spring:tars-spring")) + + implementation(libs.spring.boot.starter) + implementation(libs.spring.boot.starter.web) + compileOnly(libs.spring.boot.configuration.processor) + + testImplementation(libs.junit) +} diff --git a/spring/tars-spring-boot-starter/pom.xml b/spring/tars-spring-boot-starter/pom.xml deleted file mode 100644 index 0fa35b00..00000000 --- a/spring/tars-spring-boot-starter/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - tars-spring-parent - com.tencent.tars - 1.6.1 - - 4.0.0 - - tars-spring-boot-starter - - - 2.0.3.RELEASE - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - - - com.tencent.tars - tars-spring - ${project.parent.version} - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-configuration-processor - true - - - \ No newline at end of file diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/server/apps/SpringBootAppContext.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/server/apps/SpringBootAppContext.java index 590c4a56..0ad990c2 100644 --- a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/server/apps/SpringBootAppContext.java +++ b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/server/apps/SpringBootAppContext.java @@ -17,7 +17,6 @@ package com.qq.tars.server.apps; import com.qq.tars.common.util.StringUtils; -import com.qq.tars.net.core.Processor; import com.qq.tars.protocol.annotation.Servant; import com.qq.tars.protocol.util.TarsHelper; import com.qq.tars.rpc.protocol.Codec; @@ -25,10 +24,13 @@ import com.qq.tars.server.config.ServantAdapterConfig; import com.qq.tars.server.config.ServerConfig; import com.qq.tars.server.core.AppContextListener; +import com.qq.tars.server.core.Processor; import com.qq.tars.server.core.ServantAdapter; import com.qq.tars.server.core.ServantHomeSkeleton; import com.qq.tars.spring.annotation.TarsListener; import com.qq.tars.spring.annotation.TarsServant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.aop.framework.Advised; import org.springframework.context.ApplicationContext; import org.springframework.core.annotation.AnnotationUtils; @@ -36,6 +38,9 @@ import java.util.Map; public class SpringBootAppContext extends BaseAppContext { + + private static final Logger logger = LoggerFactory.getLogger(SpringBootAppContext.class); + private ApplicationContext applicationContext; public SpringBootAppContext(ApplicationContext applicationContext) { @@ -47,6 +52,7 @@ public SpringBootAppContext(ApplicationContext applicationContext) { protected void loadServants() { loadAppContextListeners(); loadAppServants(); + loadDefaultFilter(); } private void loadAppContextListeners() { @@ -71,17 +77,19 @@ private void loadAppServants() { for (Map.Entry entry : servantMap.entrySet()) { try { ServantHomeSkeleton skeleton = loadServant(entry.getValue()); + if(skeleton == null) { + continue; + } skeletonMap.put(skeleton.name(), skeleton); appServantStarted(skeleton); - } catch (Exception e) { - System.err.println("init a Servant failed"); - e.printStackTrace(); + } catch (Throwable e) { + logger.error("init a Servant failed exMsg:{}", e.getMessage(), e); } } } - private ServantHomeSkeleton loadServant(Object bean) throws Exception { + private ServantHomeSkeleton loadServant(Object bean) throws Throwable { String homeName = null; Class homeApiClazz = null; Class codecClazz = null; @@ -123,12 +131,16 @@ private ServantHomeSkeleton loadServant(Object bean) throws Exception { } ServantAdapterConfig servantAdapterConfig = serverCfg.getServantAdapterConfMap().get(homeName); + if(servantAdapterConfig == null) { + logger.warn("servant:{} 's servantAdapterConfig is null, not start this servant. If u need this servant, please config in tarsAdmin.",homeName); + return null; + } - ServantAdapter ServerAdapter = new ServantAdapter(servantAdapterConfig); - skeleton = new ServantHomeSkeleton(homeName, homeClassImpl, homeApiClazz, codecClazz, processorClazz, maxLoadLimit); + ServantAdapter servantAdapter = new ServantAdapter(servantAdapterConfig); + skeleton = new ServantHomeSkeleton(homeName, homeClassImpl, homeApiClazz, maxLoadLimit); skeleton.setAppContext(this); - ServerAdapter.bind(skeleton); - servantAdapterMap.put(homeName, ServerAdapter); + servantAdapter.bind(skeleton); + servantAdapterMap.put(homeName, servantAdapter); return skeleton; } } diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/TarsManageServiceConfiguration.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/TarsManageServiceConfiguration.java deleted file mode 100644 index d15280c1..00000000 --- a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/TarsManageServiceConfiguration.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.spring; - -import com.qq.tars.client.Communicator; -import com.qq.tars.client.CommunicatorFactory; -import com.qq.tars.spring.bean.CommunicatorBeanPostProcessor; -import com.qq.tars.spring.bean.ServletContainerCustomizer; -import com.qq.tars.support.config.ConfigHelper; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class TarsManageServiceConfiguration { - @Bean - public Communicator communicator() { - return CommunicatorFactory.getInstance().getCommunicator(); - } - - @Bean - public CommunicatorBeanPostProcessor communicatorBeanPostProcessor(Communicator communicator) { - return new CommunicatorBeanPostProcessor(communicator); - } - - @Bean - public ConfigHelper configHelper() { - return ConfigHelper.getInstance(); - } - - @Bean - public ServletContainerCustomizer servletContainerCustomizer() { - return new ServletContainerCustomizer(); - } -} diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/TarsServerConfiguration.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/TarsServerConfiguration.java index 6002808c..712c73a2 100644 --- a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/TarsServerConfiguration.java +++ b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/TarsServerConfiguration.java @@ -1,13 +1,13 @@ /** * Tencent is pleased to support the open source community by making Tars available. - * + *

* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * + *

* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at - * + *

* https://opensource.org/licenses/BSD-3-Clause - * + *

* 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 @@ -16,19 +16,46 @@ package com.qq.tars.spring; -import com.qq.tars.server.config.ConfigurationManager; +import com.qq.tars.client.Communicator; +import com.qq.tars.client.CommunicatorFactory; import com.qq.tars.server.core.Server; +import com.qq.tars.spring.bean.CommunicatorBeanPostProcessor; +import com.qq.tars.spring.bean.ServletContainerCustomizer; import com.qq.tars.spring.bean.TarsServerStartLifecycle; +import com.qq.tars.spring.condition.ConditionalOnTars; +import com.qq.tars.support.config.ConfigHelper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; @Configuration -@Import(TarsManageServiceConfiguration.class) +@ConditionalOnTars public class TarsServerConfiguration { + + private final Server server = Server.getInstance(); + @Bean public Server server() { - return new Server(ConfigurationManager.getInstance().getServerConfig()); + return this.server; + } + + @Bean + public Communicator communicator() { + return CommunicatorFactory.getInstance().getCommunicator(); + } + + @Bean + public CommunicatorBeanPostProcessor communicatorBeanPostProcessor(Communicator communicator) { + return new CommunicatorBeanPostProcessor(communicator); + } + + @Bean + public ConfigHelper configHelper() { + return ConfigHelper.getInstance(); + } + + @Bean + public ServletContainerCustomizer servletContainerCustomizer() { + return new ServletContainerCustomizer(); } @Bean diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/annotation/RemoteConfigSource.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/annotation/RemoteConfigSource.java new file mode 100644 index 00000000..7e25577e --- /dev/null +++ b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/annotation/RemoteConfigSource.java @@ -0,0 +1,10 @@ +package com.qq.tars.spring.annotation; + +import java.lang.annotation.*; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface RemoteConfigSource { + String[] value(); +} diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/CommunicatorBeanPostProcessor.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/CommunicatorBeanPostProcessor.java index d2a5aff9..6c468aac 100644 --- a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/CommunicatorBeanPostProcessor.java +++ b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/CommunicatorBeanPostProcessor.java @@ -57,27 +57,29 @@ private void processFields(Object bean, Field[] declaredFields) { } if (field.getType().getAnnotation(Servant.class) == null) { - throw new RuntimeException("[TARS] autoware client failed: target field is not TAF client"); + throw new RuntimeException("[TARS] autowire client failed: target field is not tars client"); } String objName = annotation.name(); if (StringUtils.isEmpty(annotation.value())) { - throw new RuntimeException("[TARS] autoware client failed: objName is empty"); + throw new RuntimeException("[TARS] autowire client failed: objName is empty"); } ServantProxyConfig config = new ServantProxyConfig(objName); CommunicatorConfig communicatorConfig = ConfigurationManager.getInstance().getServerConfig().getCommunicatorConfig(); config.setModuleName(communicatorConfig.getModuleName(), communicatorConfig.isEnableSet(), communicatorConfig.getSetDivision()); - if (annotation.setDivision() != null) { - config.setEnableSet(true); + if (StringUtils.isNotEmpty(communicatorConfig.getSetDivision())) { + config.setSetDivision(communicatorConfig.getSetDivision()); + } + if (StringUtils.isNotEmpty(annotation.setDivision())) { + config.setSetDivision(communicatorConfig.getSetDivision()); + config.setEnableSet(annotation.enableSet()); } - config.setSetDivision(annotation.setDivision()); config.setConnections(annotation.connections()); config.setConnectTimeout(annotation.connectTimeout()); config.setSyncTimeout(annotation.syncTimeout()); config.setAsyncTimeout(annotation.asyncTimeout()); - config.setEnableSet(annotation.enableSet()); config.setTcpNoDelay(annotation.tcpNoDelay()); config.setCharsetName(annotation.charsetName()); diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/ManageServiceListener.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/ManageServiceListener.java deleted file mode 100644 index 8aae51ae..00000000 --- a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/ManageServiceListener.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.spring.bean; - -import com.qq.tars.server.core.Server; -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; -import org.springframework.context.ApplicationListener; - -public class ManageServiceListener implements ApplicationListener { - @Override - public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { - System.out.println("[TARS] init manage service"); - - Server.loadServerConfig(); - Server.initCommunicator(); - Server.configLogger(); - Server.startManagerService(); - } -} diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/PropertiesListener.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/PropertiesListener.java deleted file mode 100644 index 315db9c4..00000000 --- a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/PropertiesListener.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.qq.tars.spring.bean; - -import com.qq.tars.server.config.ConfigurationManager; -import com.qq.tars.spring.annotation.RemotePropertySource; -import com.qq.tars.support.config.ConfigHelper; -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.core.env.PropertiesPropertySource; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Properties; - -public class PropertiesListener implements ApplicationListener { - @Override - public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { - RemotePropertySource sources = event.getSpringApplication() - .getMainApplicationClass().getAnnotation(RemotePropertySource.class); - - String configPath = ConfigurationManager.getInstance().getserverConfig().getBasePath() + "/conf/"; - if (sources != null) { - for (String name : sources.value()) { - try { - ConfigHelper.getInstance().loadConfig(name); - File config = new File(configPath + name); - - if (config.exists()) { - Properties properties = new Properties(); - properties.load(new FileInputStream(config)); - event.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource(name, properties)); - } else { - throw new RuntimeException("[TARS] load config failed file not exists"); - } - } catch (IOException e) { - System.err.println("[TARS] load config failed: " + name); - e.printStackTrace(); - } - } - } - } -} diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/ServletContainerCustomizer.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/ServletContainerCustomizer.java index db9fd662..d579c478 100644 --- a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/ServletContainerCustomizer.java +++ b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/ServletContainerCustomizer.java @@ -16,13 +16,16 @@ package com.qq.tars.spring.bean; +import com.qq.tars.rpc.exc.TarsException; import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.server.config.ServantAdapterConfig; import com.qq.tars.server.config.ServerConfig; import com.qq.tars.spring.annotation.TarsHttpService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.boot.web.server.WebServerFactoryCustomizer; -import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; +import org.springframework.boot.web.server.servlet.ConfigurableServletWebServerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.annotation.AnnotationUtils; @@ -32,6 +35,7 @@ import java.util.Map; public class ServletContainerCustomizer implements WebServerFactoryCustomizer, ApplicationContextAware { + private static final Logger logger = LoggerFactory.getLogger(ServletContainerCustomizer.class); private ApplicationContext applicationContext; @Override @@ -44,7 +48,7 @@ public void customize(ConfigurableServletWebServerFactory factory) { Map beans = applicationContext.getBeansWithAnnotation(TarsHttpService.class); int port = 8080; String host = null; - ServerConfig serverCfg = ConfigurationManager.getInstance().getserverConfig(); + ServerConfig serverCfg = ConfigurationManager.getInstance().getServerConfig(); try { for (Object bean : beans.values()) { @@ -53,7 +57,9 @@ public void customize(ConfigurableServletWebServerFactory factory) { ServantAdapterConfig adapterConfig = ConfigurationManager.getInstance() .getServerConfig().getServantAdapterConfMap().get(homeName); - + if (adapterConfig.getProtocol().equals("tars")) { + throw new TarsException("[TARS] http servant can not use tars protocol"); + } port = adapterConfig.getEndpoint().port(); host = adapterConfig.getEndpoint().host(); } diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/TarsServerStartLifecycle.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/TarsServerStartLifecycle.java index 29e2e113..2ad776c1 100644 --- a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/TarsServerStartLifecycle.java +++ b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/bean/TarsServerStartLifecycle.java @@ -67,7 +67,7 @@ public boolean isAutoStartup() { @Override public void stop(Runnable runnable) { - + runnable.run(); } @Override diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/condition/ConditionalOnNonTars.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/condition/ConditionalOnNonTars.java new file mode 100644 index 00000000..3765c5d9 --- /dev/null +++ b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/condition/ConditionalOnNonTars.java @@ -0,0 +1,50 @@ +package com.qq.tars.spring.condition; + +import org.springframework.context.annotation.Conditional; + +import java.lang.annotation.*; + +/** + * Match only on non-tars environment. Such as local, CI/CD, test case, etc. + *

+ * public class Main {
+ *     public static void main(String[] args) {
+ *         ConfigurableApplicationContext run = SpringApplication.run(Main.class, args);
+ *         Map beansOfType = run.getBeansOfType(TestBean.class);
+ *         TestBean candidate = beansOfType.values().stream().findFirst().get();
+ *         log.info("loaded bean: candidate:{}", candidate.getClass().getCanonicalName());
+ *     }
+ *
+ *     public interface TestBean {
+ *     }
+ *
+ *     @Component
+ *     @ConditionalOnTars
+ *     public static class TarsBean implements TestBean {
+ *         public TarsBean() {
+ *             log.info("initializing tars bean");
+ *         }
+ *     }
+ *
+ *     @Component
+ *     @ConditionalOnNonTars
+ *     public static class NonTarsBean implements TestBean {
+ *         public NoTarsBean() {
+ *             log.info("initializing non-tars bean");
+ *         }
+ *     }
+ * }
+ * 
+ * When running on tars platform, {@code initializing tars bean, loaded bean: candidate:TarsBean} will be shown in info log, + * while running on non-tars platform(local, CI/CD, test case, etc.), {@code initializing non-tars bean, loaded bean: candidate:NonTarsBean} will be shown in info log. + * + * @author kongyuanyuan + * @see ConditionalOnTars + * @see OnTarsCondition + */ +@Conditional(OnTarsCondition.class) +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +@Documented +public @interface ConditionalOnNonTars { +} diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/condition/ConditionalOnTars.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/condition/ConditionalOnTars.java new file mode 100644 index 00000000..5e0986fe --- /dev/null +++ b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/condition/ConditionalOnTars.java @@ -0,0 +1,50 @@ +package com.qq.tars.spring.condition; + +import org.springframework.context.annotation.Conditional; + +import java.lang.annotation.*; + +/** + * Match only on non-tars environment. Such as local, CI/CD, test case, etc. + *
+ * public class Main {
+ *     public static void main(String[] args) {
+ *         ConfigurableApplicationContext run = SpringApplication.run(Main.class, args);
+ *         Map beansOfType = run.getBeansOfType(TestBean.class);
+ *         TestBean candidate = beansOfType.values().stream().findFirst().get();
+ *         log.info("loaded bean: candidate:{}", candidate.getClass().getCanonicalName());
+ *     }
+ *
+ *     public interface TestBean {
+ *     }
+ *
+ *     @Component
+ *     @ConditionalOnTars
+ *     public static class TarsBean implements TestBean {
+ *         public TarsBean() {
+ *             log.info("initializing tars bean");
+ *         }
+ *     }
+ *
+ *     @Component
+ *     @ConditionalOnNonTars
+ *     public static class NonTarsBean implements TestBean {
+ *         public NoTarsBean() {
+ *             log.info("initializing non-tars bean");
+ *         }
+ *     }
+ * }
+ * 
+ * When running on tars platform, {@code initializing tars bean, loaded bean: candidate:TarsBean} will be shown in info log, + * while running on non-tars platform(local, CI/CD, test case, etc.), {@code initializing non-tars bean, loaded bean: candidate:NonTarsBean} will be shown in info log. + * + * @author kongyuanyuan + * @see ConditionalOnNonTars + * @see OnTarsCondition + */ +@Conditional(OnTarsCondition.class) +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +@Documented +public @interface ConditionalOnTars { +} diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/condition/OnTarsCondition.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/condition/OnTarsCondition.java new file mode 100644 index 00000000..366c0eef --- /dev/null +++ b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/condition/OnTarsCondition.java @@ -0,0 +1,80 @@ +package com.qq.tars.spring.condition; + +import com.qq.tars.server.config.ConfigurationManager; +import org.springframework.boot.autoconfigure.condition.ConditionOutcome; +import org.springframework.boot.autoconfigure.condition.SpringBootCondition; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.core.type.AnnotatedTypeMetadata; +import org.springframework.core.type.AnnotationMetadata; +import org.springframework.core.type.MethodMetadata; +import org.springframework.util.StringUtils; + +/** + * Tars-environment condition used with environment-aware classes. + * + * @author kongyuanyuan + * @see ConditionalOnTars + * @see ConditionalOnNonTars + */ +public class OnTarsCondition extends SpringBootCondition { + private final boolean hasConfigProperty; + private final boolean isTars; + + public OnTarsCondition() { + String config = System.getProperty("config"); + hasConfigProperty = StringUtils.hasText(config); + isTars = hasConfigProperty + && ConfigurationManager.getInstance().getServerConfig() != null; + } + + /** + * Get the match result. + * + * @param context the condition context + * @param metadata the metadata of the {@link AnnotationMetadata class} + * or {@link MethodMetadata method} being checked + * @return {@code true} if the condition matches and the component can be registered, + * or {@code false} to veto the annotated component's registration + */ + @Override + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + return buildConditionOutcome(metadata, isTars, hasConfigProperty); + } + + /** + * Match with condition. + * + * @param metadata metadata with annotation + * @param isTars is in tars environment + * @param hasConfigProperty has config system property + * @return match result + */ + private static ConditionOutcome buildConditionOutcome(AnnotatedTypeMetadata metadata, boolean isTars, boolean hasConfigProperty) { + if (metadata.isAnnotated(ConditionalOnTars.class.getName())) { + //match only when running in tars environment + if (isTars) { + return ConditionOutcome.match("System has property 'config' and ConfigurationManager has been successfully loaded"); + } + String message; + if (!hasConfigProperty) { + message = "System does not have property 'config'"; + } else { + message = "ConfigurationManager hasn't been loaded"; + } + return ConditionOutcome.noMatch(message); + } else { + //match only when running in non-tars environment, such as local, ci/cd, test case, etc. + if (!isTars) { + return ConditionOutcome.match("System does not have property 'config' and ConfigurationManager hasn't been loaded"); + } + //in tars environment, return noMatch + String message; + if (!hasConfigProperty) { + message = "ConfigurationManager has been loaded"; + } else { + message = "System does have property 'config'"; + } + return ConditionOutcome.noMatch(message); + } + } +} diff --git a/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/listener/TarsGenericApplicationListener.java b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/listener/TarsGenericApplicationListener.java new file mode 100644 index 00000000..03987cd0 --- /dev/null +++ b/spring/tars-spring-boot-starter/src/main/java/com/qq/tars/spring/listener/TarsGenericApplicationListener.java @@ -0,0 +1,298 @@ +package com.qq.tars.spring.listener; + +import com.qq.tars.rpc.exc.TarsException; +import com.qq.tars.server.core.Server; +import com.qq.tars.spring.annotation.RemoteConfigSource; +import com.qq.tars.spring.annotation.RemotePropertySource; +import com.qq.tars.support.config.ConfigHelper; +import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; +import org.springframework.boot.context.event.ApplicationFailedEvent; +import org.springframework.boot.context.event.ApplicationStartingEvent; +import org.springframework.boot.logging.AbstractLoggingSystem; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.event.GenericApplicationListener; +import org.springframework.core.ResolvableType; +import org.springframework.core.env.PropertiesPropertySource; +import org.springframework.lang.NonNull; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; + +/** + * tars generic application listener + *
    + *
  1. Init tars config and load remote config when application is starting, make sure Spring environment will load properties appropriately, including logging system.
  2. + *
  3. Inject the properties when the environment for application is prepared.
  4. + *
  5. Stop the whole process when the application start failed.
  6. + *
+ * + * @author kongyuanyuan + */ +public class TarsGenericApplicationListener implements GenericApplicationListener { + /** + * properties to be injected into the environment + */ + private final Map propertiesMap = new LinkedHashMap<>(); + /** + * is {@code System.getProperty("config")} presented + * + * @see Server#init() + */ + private final boolean hasConfigProperty; + /** + * config path for tars + */ + private String configPath; + + public TarsGenericApplicationListener() { + this.hasConfigProperty = StringUtils.hasText(System.getProperty("config")); + if (hasConfigProperty) { + //init tars config + Server server = Server.getInstance(); + server.init(); + //set config path + configPath = server.getServerConfig().getBasePath() + "/conf/"; + } else { + //running in non-tars environment, notice it + System.out.println("[TARS] Running in non-tars environment. Be careful to use the communicator."); + } + } + + @Override + public void onApplicationEvent(@NonNull ApplicationEvent applicationEvent) { + if (!hasConfigProperty) { + //non-tars environment, ignore all event + return; + } + if (applicationEvent instanceof ApplicationStartingEvent) { + //Init tars config and load remote config when application is starting, + // make sure Spring environment will load properties appropriately, including logging system. + //inject default properties, let spring do its job + handleApplicationStartingEvent((ApplicationStartingEvent) applicationEvent); + } else if (applicationEvent instanceof ApplicationEnvironmentPreparedEvent) { + //the environment is prepared, inject properties + handleApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) applicationEvent); + } else if (applicationEvent instanceof ApplicationFailedEvent) { + //application start failed + handleApplicationFailedEvent((ApplicationFailedEvent) applicationEvent); + } + } + + /** + * handle application starting event. + *
    + *
  1. load remote config for {@link RemotePropertySource} and {@link RemoteConfigSource}
  2. + *
  3. Inject default properties.
  4. + *
+ * + * @param applicationEvent ApplicationStartingEvent + */ + private void handleApplicationStartingEvent(ApplicationStartingEvent applicationEvent) { + //delete legacy config + deleteLegacyConfig(); + //load remote config file for injection + loadRemotePropertiesConfig(applicationEvent.getSpringApplication().getMainApplicationClass()); + //load remote config without injection + loadRemoteConfig(applicationEvent.getSpringApplication().getMainApplicationClass()); + //set default config + configDefaultProperties(applicationEvent); + } + + /** + * load remote config file for injection + * + * @param mainClass mainClas + */ + private void loadRemotePropertiesConfig(Class mainClass) { + RemotePropertySource sources = mainClass.getAnnotation(RemotePropertySource.class); + if (sources == null) { + //nothing to load + return; + } + loadRemoteConfig(sources.value(), true); + } + + /** + * load remote config without injection + * + * @param mainClass mainClass + */ + private void loadRemoteConfig(Class mainClass) { + RemoteConfigSource sources = mainClass.getAnnotation(RemoteConfigSource.class); + if (sources == null) { + //nothing to do + return; + } + loadRemoteConfig(sources.value(), false); + } + + /** + * load remote config file for injection + * + * @param filenameList file name list + * @param inject need to inject into the environment + */ + private void loadRemoteConfig(final String[] filenameList, final boolean inject) { + for (String name : filenameList) { + Assert.state(StringUtils.hasText(name), "[TARS] The value property of @RemoteConfigSource/@RemotePropertySource cannot be empty"); + //load config from remote + Assert.state(ConfigHelper.getInstance().loadConfig(name), "[TARS] failed to load config: " + name + ", probably due to failed to execute UpdateConfigCallback"); + System.out.println("[TARS] load config: " + name); + if (inject) { + //load config successfully, inject into properties + File config = new File(configPath + name); + Assert.state(config.exists(), "[TARS] read config file failed: file does not exist, filename:" + config.getAbsolutePath()); + Properties properties = new Properties(); + try (FileInputStream inStream = new FileInputStream(config)) { + properties.load(inStream); + } catch (IOException exception) { + throw new TarsException("[TARS] read config file failed: IO exception:" + exception + ", filename:" + config.getAbsolutePath()); + } + //put properties to map, which will be injected to the environment later + propertiesMap.put(name, properties); + } + } + } + + /** + * application start failed + *

+ * halt the application, don't report heartbeat + * + * @param applicationEvent ApplicationFailedEvent + */ + private void handleApplicationFailedEvent(ApplicationFailedEvent applicationEvent) { + Throwable exception = applicationEvent.getException(); + System.out.println("[TARS] start application fail. exception:"); + exception.printStackTrace(); + //halt, stop all threads + System.exit(-1); + } + + /** + * handle environment prepared event + * + * @param applicationEvent ApplicationEnvironmentPreparedEvent + */ + private void handleApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent applicationEvent) { + //inject properties into the environment + injectPropertySource(applicationEvent); + } + + /** + * delete legacy config + */ + private void deleteLegacyConfig() { + Path path = Paths.get(configPath); + File configDirectory = path.toFile(); + if (configDirectory.isDirectory()) { + File[] files = configDirectory.listFiles(); + if (files != null) { + for (File file : files) { + try { + Files.delete(file.toPath()); + } catch (IOException exception) { + throw new TarsException("[TARS] delete legacy config failed: " + file.getName(), exception); + } + } + } + } + } + + /** + * set default properties + * + * @param applicationEvent ApplicationStartingEvent + */ + private void configDefaultProperties(ApplicationStartingEvent applicationEvent) { + Map defaultProperties = new LinkedHashMap<>(); + //set the config file location, let spring load the remote config + defaultProperties.put("spring.config.additional-location", configPath); + //config the logging system + //the first logging config found will be used as default logging system config. + for (String configName : getConventionLoggingConfig()) { + Properties logbackConfig = propertiesMap.get(configName); + if (logbackConfig != null) { + defaultProperties.put("logging.config", configPath + configName); + break; + } + } + applicationEvent.getSpringApplication().setDefaultProperties(defaultProperties); + } + + /** + * inject the properties into the environment + * + * @param applicationEvent ApplicationEnvironmentPreparedEvent + */ + private void injectPropertySource(ApplicationEnvironmentPreparedEvent applicationEvent) { + propertiesMap.entrySet().stream() + .map(entry -> new PropertiesPropertySource(entry.getKey(), entry.getValue())) + .forEach(applicationEvent.getEnvironment().getPropertySources()::addFirst); + } + + /** + * get some convention logging config. + * + * @return logging config file name + * @see org.springframework.boot.logging.LoggingSystem + * @see AbstractLoggingSystem#initialize + */ + private static String[] getConventionLoggingConfig() { + return new String[]{"logback.groovy", "logback.xml", + "log4j2.properties", "log4j2.yaml", "log4j2.yml", "log4j2.json", "log4j2.jsn", "log4j2.xml", + "logging.properties"}; + } + + /** + * Determine whether this listener actually supports the given event type. + * + * @param eventType the event type (never {@code null}) + */ + @Override + public boolean supportsEventType(ResolvableType eventType) { + Class type = eventType.getRawClass(); + if (type == null) { + return false; + } + return ApplicationStartingEvent.class.isAssignableFrom(type) + || ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(type) + || ApplicationFailedEvent.class.isAssignableFrom(type); + } + + /** + * Determine whether this listener actually supports the given source type. + * + * @param sourceType sourceType + */ + @Override + public boolean supportsSourceType(Class sourceType) { + return true; + } + + /** + * Get the order value of this object. + *

Higher values are interpreted as lower priority. As a consequence, + * the object with the lowest value has the highest priority (somewhat + * analogous to Servlet {@code load-on-startup} values). + *

Same order values will result in arbitrary sort positions for the + * affected objects. + * + * @return the order value + * @see #HIGHEST_PRECEDENCE + * @see #LOWEST_PRECEDENCE + */ + @Override + public int getOrder() { + return 0; + } +} \ No newline at end of file diff --git a/spring/tars-spring-boot-starter/src/main/resources/META-INF/spring.factories b/spring/tars-spring-boot-starter/src/main/resources/META-INF/spring.factories index b5d2c28a..e0db2d7d 100644 --- a/spring/tars-spring-boot-starter/src/main/resources/META-INF/spring.factories +++ b/spring/tars-spring-boot-starter/src/main/resources/META-INF/spring.factories @@ -1,3 +1,2 @@ org.springframework.context.ApplicationListener=\ -com.qq.tars.spring.bean.ManageServiceListener,\ -com.qq.tars.spring.bean.PropertiesListener +com.qq.tars.spring.listener.TarsGenericApplicationListener \ No newline at end of file diff --git a/spring/tars-spring-cloud-starter/build.gradle.kts b/spring/tars-spring-cloud-starter/build.gradle.kts new file mode 100644 index 00000000..cd96e996 --- /dev/null +++ b/spring/tars-spring-cloud-starter/build.gradle.kts @@ -0,0 +1,17 @@ +plugins { + `java-library` +} + +description = "Tars Spring Cloud Starter - Spring Cloud integration for Tars" + +dependencies { + api(project(":spring:tars-spring")) + api(project(":tars-core")) + + implementation(libs.spring.boot.starter) + implementation(libs.eureka.client) + implementation(libs.spring.cloud.netflix.eureka.client) + implementation(libs.spring.cloud.commons) + + testImplementation(libs.junit) +} diff --git a/spring/tars-spring-cloud-starter/pom.xml b/spring/tars-spring-cloud-starter/pom.xml deleted file mode 100644 index a7f8d0c9..00000000 --- a/spring/tars-spring-cloud-starter/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - 4.0.0 - - - tars-spring-parent - com.tencent.tars - 1.6.1 - - - tars-spring-cloud-starter - jar - - tars-spring-cloud-starter - - - UTF-8 - 1.4.9 - 1.3.1.RELEASE - 1.2.2.RELEASE - - - - - com.netflix.eureka - eureka-client - ${eureka-client.version} - - - org.springframework.cloud - spring-cloud-netflix-eureka-client - ${spring-cloud-netflix-eureka-client.version} - - - org.springframework.cloud - spring-cloud-commons - ${spring-cloud-commons.version} - - - com.tencent.tars - tars-spring - ${project.parent.version} - - - com.tencent.tars - tars-core - ${project.parent.version} - - - diff --git a/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/EurekaRegisterHandler.java b/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/EurekaRegisterHandler.java index b2ad020a..617abae8 100644 --- a/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/EurekaRegisterHandler.java +++ b/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/EurekaRegisterHandler.java @@ -49,7 +49,7 @@ public class EurekaRegisterHandler implements RegisterHandler { @Autowired private TarsClientProperties clientProperties; - private AtomicBoolean isRegisted = new AtomicBoolean(false); + private AtomicBoolean isRegistered = new AtomicBoolean(false); public EurekaRegisterHandler(EurekaClient client, TarsEurekaInstance instanceConfig, HealthCheckHandler healthCheckHandler, ApplicationInfoManager applicationInfoManager) { @@ -71,7 +71,7 @@ public void onApplicationEvent(ContextStoppedEvent ev) { } public void start() { - if (isRegisted.compareAndSet(false, true)) { + if (isRegistered.compareAndSet(false, true)) { if (instanceConfig.getNonSecurePort() > 0) { client.getApplications(); applicationInfoManager.setInstanceStatus(instanceConfig.getInitialStatus()); diff --git a/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/TarsEurekaAutoConfiguration.java b/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/TarsEurekaAutoConfiguration.java index c5638131..16cc1dc8 100644 --- a/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/TarsEurekaAutoConfiguration.java +++ b/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/TarsEurekaAutoConfiguration.java @@ -18,66 +18,36 @@ import com.qq.tars.spring.TarsConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.SearchStrategy; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration; -import org.springframework.cloud.netflix.eureka.InstanceInfoFactory; -import org.springframework.cloud.netflix.eureka.config.EurekaClientConfigServerAutoConfiguration; -import org.springframework.cloud.netflix.eureka.config.EurekaDiscoveryClientConfigServiceAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.eureka.RibbonEurekaAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.DiscoveryClient; -import com.netflix.discovery.DiscoveryClient.DiscoveryClientOptionalArgs; import com.netflix.discovery.EurekaClient; import com.qq.tars.register.RegisterHandler; @Configuration @EnableConfigurationProperties({ TarsEurekaClientConfig.class, TarsEurekaInstance.class }) @ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true) -@AutoConfigureAfter({ TarsConfiguration.class }) -@AutoConfigureBefore({ EurekaClientAutoConfiguration.class, EurekaClientConfigServerAutoConfiguration.class, RibbonEurekaAutoConfiguration.class, EurekaDiscoveryClientConfigServiceAutoConfiguration.class }) +@AutoConfigureAfter({ TarsConfiguration.class, EurekaClientAutoConfiguration.class }) public class TarsEurekaAutoConfiguration { - @Bean - @ConditionalOnMissingBean(value = DiscoveryClientOptionalArgs.class, search = SearchStrategy.CURRENT) - public DiscoveryClientOptionalArgs discoveryClientOptionalArgs() { - return new DiscoveryClientOptionalArgs(); - } - @Bean @ConditionalOnMissingBean(value = HealthCheckHandler.class, search = SearchStrategy.CURRENT) public HealthCheckHandler HealthCheckHandler() { return new TarsEurekaHealthCheckHandler(); } - @Bean - @ConditionalOnMissingBean(value = ApplicationInfoManager.class, search = SearchStrategy.CURRENT) - public ApplicationInfoManager applicationInfoManager(EurekaInstanceConfig config) { - InstanceInfo instanceInfo = new InstanceInfoFactory().create(config); - ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(config, instanceInfo); - applicationInfoManager.registerStatusChangeListener(new TarsStatusChangeListener()); - return applicationInfoManager; - } - - @Bean(destroyMethod = "shutdown") - public EurekaClient eurekaClient(ApplicationInfoManager applicationInfoManager, TarsEurekaClientConfig config, - DiscoveryClientOptionalArgs optionalArgs) { - return new DiscoveryClient(applicationInfoManager, config, optionalArgs); - } - @Bean public RegisterHandler registryHandler(EurekaClient client, TarsEurekaInstance instanceConfig, HealthCheckHandler healthCheckHandler, ApplicationInfoManager applicationInfoManager) { + applicationInfoManager.registerStatusChangeListener(new TarsStatusChangeListener()); return new EurekaRegisterHandler(client, instanceConfig, healthCheckHandler, applicationInfoManager); } diff --git a/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/TarsEurekaInstance.java b/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/TarsEurekaInstance.java index ba1a4d75..7a6c026c 100644 --- a/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/TarsEurekaInstance.java +++ b/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/register/eureka/TarsEurekaInstance.java @@ -16,22 +16,21 @@ package com.qq.tars.register.eureka; -import javax.annotation.PostConstruct; - import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.InitializingBean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.commons.util.InetUtils; import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; @ConfigurationProperties(prefix = TarsEurekaInstance.PREFIX) -public class TarsEurekaInstance extends EurekaInstanceConfigBean { +public class TarsEurekaInstance extends EurekaInstanceConfigBean implements InitializingBean { public static final String PREFIX = "eureka.instance"; @Value("${tars.server.application:unknown}") private String appname = "unknown"; - @Value("${tars.server.server-name:unkonwn}") + @Value("${tars.server.server-name:unknown}") private String servicename = "unknown"; @Value("${tars.server.port:80}") @@ -53,13 +52,14 @@ public TarsEurekaInstance(InetUtils inetUtils) { super(inetUtils); } - @PostConstruct - public void init() { + @Override + public void afterPropertiesSet() { getMetadataMap().put("isTcp", String.valueOf(isTcp)); getMetadataMap().put("timeOut", String.valueOf(timeOut)); getMetadataMap().put("weight", String.valueOf(weight)); getMetadataMap().put("weightType", String.valueOf(weightType)); - getMetadataMap().put("instanceId", getIpAddress() + ":" + (isNonSecurePortEnabled() ? tarsPort : getSecurePort())); + getMetadataMap().put("instanceId", + getIpAddress() + ":" + (isNonSecurePortEnabled() ? tarsPort : getSecurePort())); } public String getAppname() { diff --git a/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/server/apps/TarsStartLifecycle.java b/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/server/apps/TarsStartLifecycle.java index b06613f8..f5264f1b 100644 --- a/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/server/apps/TarsStartLifecycle.java +++ b/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/server/apps/TarsStartLifecycle.java @@ -16,13 +16,10 @@ package com.qq.tars.server.apps; -import com.qq.tars.client.Communicator; -import com.qq.tars.client.CommunicatorFactory; import com.qq.tars.common.support.Endpoint; import com.qq.tars.common.util.StringUtils; import com.qq.tars.protocol.annotation.Servant; import com.qq.tars.protocol.util.TarsHelper; -import com.qq.tars.server.common.ServerLogger; import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.server.config.ServantAdapterConfig; import com.qq.tars.server.config.ServerConfig; @@ -31,9 +28,7 @@ import com.qq.tars.spring.annotation.TarsServant; import com.qq.tars.spring.config.TarsClientProperties; import com.qq.tars.spring.config.TarsServerProperties; -import com.qq.tars.support.log.LogConfCacheMngr; -import com.qq.tars.support.log.LoggerFactory; -import com.qq.tars.support.trace.TarsTraceZipkinConfiguration; +import com.qq.tars.support.trace.spi.TraceInitializerManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; @@ -83,15 +78,13 @@ public void stop(Runnable runnable) { public void start() { try { log.info("Start init TarsServer"); - initConfig(); - configLogger(); loadAppServants(); initServants(); appContextStarted(); startServantAdapter(); setAppContext(); - + loadDefaultFilter(); this.isRunning = true; } catch (IOException e) { e.printStackTrace(); @@ -124,15 +117,14 @@ private void initConfig() { ConfigurationManager.getInstance().setServerConfig(this.serverProperties); ConfigurationManager.getInstance().setCommunicatorConfig(this.clientProperties); - servantAdapterConfig = new ServantAdapterConfig(); - servantAdapterConfig.setEndpoint(new Endpoint(serverProperties.isUdp() ? "udp" : "tcp", StringUtils.isEmpty(serverProperties.getLocalIP()) ? "0.0.0.0" : serverProperties.getLocalIP(), serverProperties.getPort(), 0, 0, 0, null)); - servantAdapterConfig.setHandleGroup("default"); - servantAdapterConfig.setMaxConns(serverProperties.getMaxConns()); - servantAdapterConfig.setThreads(serverProperties.getThreads()); - servantAdapterConfig.setQueueCap(serverProperties.getQueueCap()); - servantAdapterConfig.setQueueTimeout(serverProperties.getQueueTimeout()); - - TarsTraceZipkinConfiguration.getInstance().init(); + + Endpoint endpoint = new Endpoint(serverProperties.isUdp() ? "udp" : "tcp", + StringUtils.isEmpty(serverProperties.getLocalIP()) ? "0.0.0.0" : serverProperties.getLocalIP(), + serverProperties.getPort(), 0, 0, 0, null); + servantAdapterConfig = ServantAdapterConfig.makeServantAdapterConfig(endpoint, "", serverProperties); + + + TraceInitializerManager.getInstance().init(); } private void loadAppServants() { @@ -143,7 +135,8 @@ private void loadAppServants() { skeletonMap.put(skeleton.name(), skeleton); appServantStarted(skeleton); } catch (Exception e) { - log.error("load servant faild", e); + log.error("load servant failed", e); + throw new RuntimeException("load servant failed ", e); } } @@ -180,7 +173,7 @@ private ServantHomeSkeleton loadServant(Object bean) throws Exception { } } - skeleton = new ServantHomeSkeleton(homeName, homeClassImpl, homeApiClazz, null, null, maxLoadLimit); + skeleton = new ServantHomeSkeleton(homeName, homeClassImpl, homeApiClazz, maxLoadLimit); skeleton.setAppContext(this); ConfigurationManager.getInstance().getServerConfig().getServantAdapterConfMap().put(homeName, servantAdapterConfig); @@ -190,28 +183,11 @@ private ServantHomeSkeleton loadServant(Object bean) throws Exception { private void startServantAdapter() throws IOException { ServantAdapter ServerAdapter = new ServantAdapter(servantAdapterConfig); - - ServerAdapter.bind(); - servantAdapterMap.put("", ServerAdapter); - } - - private void configLogger() { - Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(); - - String objName = ConfigurationManager.getInstance().getServerConfig().getLog(); - String appName = ConfigurationManager.getInstance().getServerConfig().getApplication(); - String serviceName = ConfigurationManager.getInstance().getServerConfig().getServerName(); - - String defaultLevel = ConfigurationManager.getInstance().getServerConfig().getLogLevel(); - String defaultRoot = ConfigurationManager.getInstance().getServerConfig().getLogPath(); - String dataPath = ConfigurationManager.getInstance().getServerConfig().getDataPath(); - - LoggerFactory.config(communicator, objName, appName, serviceName, defaultLevel, defaultRoot); - - LogConfCacheMngr.getInstance().init(dataPath); - if (StringUtils.isNotEmpty(LogConfCacheMngr.getInstance().getLevel())) { - LoggerFactory.setDefaultLoggerLevel(LogConfCacheMngr.getInstance().getLevel()); + try { + ServerAdapter.bind(); + } catch (Throwable throwable) { + throw new IOException(throwable); } - ServerLogger.init(); + servantAdapterMap.put("", ServerAdapter); } } diff --git a/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/spring/bean/TarsClientBeanPostProcessor.java b/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/spring/bean/TarsClientBeanPostProcessor.java index 66300aec..d7430f27 100644 --- a/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/spring/bean/TarsClientBeanPostProcessor.java +++ b/spring/tars-spring-cloud-starter/src/main/java/com/qq/tars/spring/bean/TarsClientBeanPostProcessor.java @@ -17,10 +17,15 @@ package com.qq.tars.spring.bean; import com.qq.tars.client.Communicator; +import com.qq.tars.client.CommunicatorConfig; import com.qq.tars.client.CommunicatorFactory; +import com.qq.tars.client.ServantProxyConfig; import com.qq.tars.common.util.BeanAccessor; +import com.qq.tars.common.util.StringUtils; +import com.qq.tars.protocol.annotation.Servant; import com.qq.tars.register.RegisterHandler; import com.qq.tars.register.RegisterManager; +import com.qq.tars.server.config.ConfigurationManager; import com.qq.tars.spring.annotation.TarsClient; import com.qq.tars.spring.config.TarsClientProperties; import org.springframework.beans.BeansException; @@ -75,7 +80,33 @@ private void processFields(Object bean, Field[] declaredFields) { continue; } - Object proxy = communicator.stringToProxy(field.getType(), annotation.name()); + if (field.getType().getAnnotation(Servant.class) == null) { + throw new RuntimeException("[TARS] autoware client failed: target field is not tars client"); + } + + String objName = annotation.name(); + + if (StringUtils.isEmpty(annotation.value())) { + throw new RuntimeException("[TARS] autoware client failed: objName is empty"); + } + + ServantProxyConfig config = new ServantProxyConfig(objName); + CommunicatorConfig communicatorConfig = ConfigurationManager.getInstance().getServerConfig().getCommunicatorConfig(); + config.setModuleName(communicatorConfig.getModuleName(), communicatorConfig.isEnableSet(), communicatorConfig.getSetDivision()); + config.setEnableSet(annotation.enableSet()); + config.setSetDivision(annotation.setDivision()); + if (StringUtils.isNotEmpty(annotation.setDivision())) { + config.setEnableSet(true); + config.setSetDivision(annotation.setDivision()); + } + config.setConnections(annotation.connections()); + config.setConnectTimeout(annotation.connectTimeout()); + config.setSyncTimeout(annotation.syncTimeout()); + config.setAsyncTimeout(annotation.asyncTimeout()); + config.setTcpNoDelay(annotation.tcpNoDelay()); + config.setCharsetName(annotation.charsetName()); + + Object proxy = communicator.stringToProxy(field.getType(), config); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, proxy); diff --git a/spring/tars-spring-cloud-starter/src/test/java/com/qq/tars/register/eureka/TarsEurekaInstanceTest.java b/spring/tars-spring-cloud-starter/src/test/java/com/qq/tars/register/eureka/TarsEurekaInstanceTest.java new file mode 100644 index 00000000..7284c6c5 --- /dev/null +++ b/spring/tars-spring-cloud-starter/src/test/java/com/qq/tars/register/eureka/TarsEurekaInstanceTest.java @@ -0,0 +1,42 @@ +package com.qq.tars.register.eureka; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.cloud.commons.util.InetUtils; +import org.springframework.cloud.commons.util.InetUtilsProperties; + +import java.lang.reflect.Field; + +public class TarsEurekaInstanceTest { + + @Test + public void testAfterPropertiesSetWillPopulateMetadata() throws Exception { + TarsEurekaInstance instance = new TarsEurekaInstance(new InetUtils(new InetUtilsProperties())); + instance.setNonSecurePort(18601); + setField(instance, "isTcp", 1); + setField(instance, "timeOut", 7000); + setField(instance, "weight", 18); + setField(instance, "weightType", 2); + + instance.afterPropertiesSet(); + + Assert.assertEquals("1", instance.getMetadataMap().get("isTcp")); + Assert.assertEquals("7000", instance.getMetadataMap().get("timeOut")); + Assert.assertEquals("18", instance.getMetadataMap().get("weight")); + Assert.assertEquals("2", instance.getMetadataMap().get("weightType")); + Assert.assertEquals(instance.getIpAddress() + ":18601", instance.getMetadataMap().get("instanceId")); + } + + @Test + public void testSetAppnameWithAppAndServer() { + TarsEurekaInstance instance = new TarsEurekaInstance(new InetUtils(new InetUtilsProperties())); + instance.setAppname("DemoApp.DemoServer"); + Assert.assertEquals("DemoApp.DemoServer", instance.getAppname()); + } + + private static void setField(Object target, String fieldName, Object value) throws Exception { + Field field = TarsEurekaInstance.class.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(target, value); + } +} diff --git a/spring/tars-spring/build.gradle.kts b/spring/tars-spring/build.gradle.kts new file mode 100644 index 00000000..a7b9c76b --- /dev/null +++ b/spring/tars-spring/build.gradle.kts @@ -0,0 +1,15 @@ +plugins { + `java-library` +} + +description = "Tars Spring - Spring integration for Tars" + +dependencies { + api(project(":tars-core")) + api(project(":tars-netty")) + + implementation(libs.spring.boot.starter) + compileOnly(libs.spring.boot.configuration.processor) + + testImplementation(libs.junit) +} diff --git a/spring/tars-spring/pom.xml b/spring/tars-spring/pom.xml deleted file mode 100644 index 85f1d4ea..00000000 --- a/spring/tars-spring/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - tars-spring-parent - com.tencent.tars - 1.6.1 - - 4.0.0 - - tars-spring - jar - ${project.artifactId} - - - 4.2.9.RELEASE - 1.5.8.RELEASE - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - - - com.tencent.tars - tars-core - ${project.parent.version} - - - org.springframework.boot - spring-boot-starter - ${spring-boot.version} - - - org.springframework.boot - spring-boot-configuration-processor - true - ${spring-boot.version} - - - junit - junit - 4.12 - - - \ No newline at end of file diff --git a/spring/tars-spring/src/main/java/com/qq/tars/server/apps/SpringAppContext.java b/spring/tars-spring/src/main/java/com/qq/tars/server/apps/SpringAppContext.java index 0c3a0ab2..1d7f3a45 100644 --- a/spring/tars-spring/src/main/java/com/qq/tars/server/apps/SpringAppContext.java +++ b/spring/tars-spring/src/main/java/com/qq/tars/server/apps/SpringAppContext.java @@ -17,12 +17,14 @@ package com.qq.tars.server.apps; import com.qq.tars.common.util.StringUtils; -import com.qq.tars.net.core.Processor; import com.qq.tars.protocol.annotation.Servant; import com.qq.tars.protocol.util.TarsHelper; import com.qq.tars.rpc.protocol.Codec; -import com.qq.tars.server.config.*; +import com.qq.tars.server.config.ConfigurationManager; +import com.qq.tars.server.config.ServantAdapterConfig; +import com.qq.tars.server.config.ServerConfig; import com.qq.tars.server.core.AppContextListener; +import com.qq.tars.server.core.Processor; import com.qq.tars.server.core.ServantAdapter; import com.qq.tars.server.core.ServantHomeSkeleton; import com.qq.tars.spring.config.ListenerConfig; @@ -66,18 +68,18 @@ private void loadAppServants(ApplicationContext applicationContext) { ServantHomeSkeleton skeleton = loadServant(entry.getValue()); skeletonMap.put(skeleton.name(), skeleton); appServantStarted(skeleton); - } catch (Exception e) { + } catch (Throwable throwable) { System.err.println("init a service failed"); - e.printStackTrace(); + throwable.printStackTrace(); } } } private void loadAppFilters(ApplicationContext applicationContext) { - + } - private ServantHomeSkeleton loadServant(ServantConfig servantConfig) throws Exception { + private ServantHomeSkeleton loadServant(ServantConfig servantConfig) throws Throwable { String homeName = null, homeApiName = null; Class homeApiClazz = null; Class codecClazz = null; @@ -108,7 +110,7 @@ private ServantHomeSkeleton loadServant(ServantConfig servantConfig) throws Exce ServantAdapterConfig servantAdapterConfig = serverCfg.getServantAdapterConfMap().get(homeName); ServantAdapter ServerAdapter = new ServantAdapter(servantAdapterConfig); - skeleton = new ServantHomeSkeleton(homeName, homeClassImpl, homeApiClazz, codecClazz, processorClazz, maxLoadLimit); + skeleton = new ServantHomeSkeleton(homeName, homeClassImpl, homeApiClazz, maxLoadLimit); skeleton.setAppContext(this); ServerAdapter.bind(skeleton); servantAdapterMap.put(homeName, ServerAdapter); diff --git a/spring/tars-spring/src/main/java/com/qq/tars/spring/annotation/TarsClient.java b/spring/tars-spring/src/main/java/com/qq/tars/spring/annotation/TarsClient.java index a48cc925..d04ac23f 100644 --- a/spring/tars-spring/src/main/java/com/qq/tars/spring/annotation/TarsClient.java +++ b/spring/tars-spring/src/main/java/com/qq/tars/spring/annotation/TarsClient.java @@ -25,7 +25,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -@Target({ ElementType.FIELD }) +@Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface TarsClient { @@ -37,17 +37,17 @@ String setDivision() default ""; - int connections() default Constants.default_connections; + int connections() default Constants.DEFAULT_CONNECTION; - int connectTimeout() default Constants.default_connect_timeout; + int connectTimeout() default Constants.DEFAULT_CONNECTION_TIMEOUT; - int syncTimeout() default Constants.default_sync_timeout; + int syncTimeout() default Constants.DEFAULT_SYNC_TIME; - int asyncTimeout() default Constants.default_async_timeout; + int asyncTimeout() default Constants.DEFAULT_ASYNC_TIME; boolean enableSet() default false; boolean tcpNoDelay() default false; - String charsetName() default "UTF-8"; + String charsetName() default Constants.DEFAULT_CHARSET_STRING; } diff --git a/tars-all/build.gradle.kts b/tars-all/build.gradle.kts new file mode 100644 index 00000000..421987df --- /dev/null +++ b/tars-all/build.gradle.kts @@ -0,0 +1,12 @@ +plugins { + `java-library` +} + +description = "Tars All - Aggregation module including all core Tars dependencies" + +dependencies { + api(project(":tars-common-api")) + api(project(":tars-core")) + + testImplementation(libs.junit) +} diff --git a/tars-common-api/build.gradle.kts b/tars-common-api/build.gradle.kts new file mode 100644 index 00000000..40e853e5 --- /dev/null +++ b/tars-common-api/build.gradle.kts @@ -0,0 +1,15 @@ +plugins { + `java-library` +} + +description = "Tars Common API" + +dependencies { + api(libs.guava) + api(libs.netty.all) + api(libs.gson) + api(libs.jsr305) + + implementation(libs.assertj.core) + testImplementation(libs.junit) +} diff --git a/core/src/main/java/com/qq/tars/client/CommunicatorConfig.java b/tars-common-api/src/main/java/com/qq/tars/client/CommunicatorConfig.java similarity index 87% rename from core/src/main/java/com/qq/tars/client/CommunicatorConfig.java rename to tars-common-api/src/main/java/com/qq/tars/client/CommunicatorConfig.java index 50d4293c..6559e87f 100644 --- a/core/src/main/java/com/qq/tars/client/CommunicatorConfig.java +++ b/tars-common-api/src/main/java/com/qq/tars/client/CommunicatorConfig.java @@ -18,9 +18,11 @@ import com.qq.tars.common.util.Config; import com.qq.tars.common.util.Constants; +import com.qq.tars.common.util.StringUtils; import java.io.FileNotFoundException; import java.io.IOException; +import java.util.Objects; public class CommunicatorConfig { @@ -39,7 +41,7 @@ public class CommunicatorConfig { private int sendThread = 1; private int recvThread = 1; private int asyncThread = 1; - private String moduleName = Constants.default_modulename; + private String moduleName = Constants.DEFAULT_MODULE_NAME; private boolean enableSet = false; private String setDivision = null; @@ -47,13 +49,13 @@ public class CommunicatorConfig { private String setArea; private String setID; - private int connections = Constants.default_connections; - private int connectTimeout = Constants.default_connect_timeout; - private int corePoolSize = Constants.default_core_pool_size; - private int maxPoolSize = Constants.default_max_pool_size; - private int keepAliveTime = Constants.default_keep_alive_time; - private int queueSize = Constants.default_queue_size; - private String charsetName = Constants.default_charset_name; + private int connections = Constants.DEFAULT_CONNECTION; + private int connectTimeout = Constants.DEFAULT_CONNECTION_TIMEOUT; + private int corePoolSize = Constants.DEFAULT_CORE_POOL_SIZE; + private int maxPoolSize = Constants.DEFAULT_MAX_POOL_SIZE; + private int keepAliveTime = Constants.DEFAULT_KEEPALIVE_TIME; + private int queueSize = Constants.DEFAULT_QUEUE_SIZE; + private String charsetName = Constants.DEFAULT_CHARSET.name(); private String logPath; private String logLevel = "INFO"; @@ -88,7 +90,7 @@ public CommunicatorConfig load(Config conf) { sendThread = conf.getInt("/tars/application/client", 1); recvThread = conf.getInt("/tars/application/client", 1); asyncThread = conf.getInt("/tars/application/client", 1); - moduleName = conf.get("/tars/application/client", Constants.default_modulename); + moduleName = conf.get("/tars/application/client", Constants.DEFAULT_MODULE_NAME); String enableSetStr = conf.get("/tars/application"); setDivision = conf.get("/tars/application"); if ("Y".equalsIgnoreCase(enableSetStr)) { @@ -97,22 +99,16 @@ public CommunicatorConfig load(Config conf) { enableSet = false; setDivision = null; } - - if (enableSet && setDivision != null) { - String[] tmp = setDivision.split("\\."); - setName = tmp[0]; - setArea = tmp[1]; - setID = tmp[2]; + this.setSetDivision(setDivision); } - - connections = conf.getInt("/tars/application/client", Constants.default_connections); - connectTimeout = conf.getInt("/tars/application/client", Constants.default_connect_timeout); - corePoolSize = conf.getInt("/tars/application/client", Constants.default_core_pool_size); - maxPoolSize = conf.getInt("/tars/application/client", Constants.default_max_pool_size); - keepAliveTime = conf.getInt("/tars/application/client", Constants.default_keep_alive_time); - queueSize = conf.getInt("/tars/application/client", Constants.default_queue_size); - charsetName = conf.get("/tars/application/client", Constants.default_charset_name); + connections = conf.getInt("/tars/application/client", Constants.DEFAULT_CONNECTION); + connectTimeout = conf.getInt("/tars/application/client", Constants.DEFAULT_CONNECTION_TIMEOUT); + corePoolSize = conf.getInt("/tars/application/client", Constants.DEFAULT_CORE_POOL_SIZE); + maxPoolSize = conf.getInt("/tars/application/client", Constants.DEFAULT_MAX_POOL_SIZE); + keepAliveTime = conf.getInt("/tars/application/client", Constants.DEFAULT_KEEPALIVE_TIME); + queueSize = conf.getInt("/tars/application/client", Constants.DEFAULT_QUEUE_SIZE); + charsetName = conf.get("/tars/application/client", Constants.DEFAULT_CHARSET.name()); return this; } @@ -254,11 +250,19 @@ public String getSetDivision() { public CommunicatorConfig setSetDivision(String setDivision) { this.setDivision = setDivision; - if (setDivision != null) { - String[] tmp = setDivision.split("."); - setName = tmp[0]; - setArea = tmp[1]; - setID = tmp[2]; + if (StringUtils.isNotEmpty(setDivision)) { + String[] tmp = StringUtils.split(setDivision, "."); + if (tmp != null && tmp.length == 3) { + setName = tmp[0]; + setArea = tmp[1]; + setID = tmp[2]; + enableSet = true; + } else { + setName = ""; + setArea = ""; + setID = ""; + enableSet = false; + } } return this; } @@ -380,13 +384,10 @@ public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; CommunicatorConfig other = (CommunicatorConfig) obj; - if (locator == null) { - if (other.locator != null) return false; - } else if (!locator.equals(other.locator)) return false; - if (moduleName == null) { - if (other.moduleName != null) return false; - } else if (!moduleName.equals(other.moduleName)) return false; - return true; + if (!Objects.equals(this.locator, other.locator)) { + return false; + } + return Objects.equals(this.moduleName, other.moduleName); } @Override diff --git a/core/src/main/java/com/qq/tars/client/ServantProxy.java b/tars-common-api/src/main/java/com/qq/tars/client/ServantProxy.java similarity index 82% rename from core/src/main/java/com/qq/tars/client/ServantProxy.java rename to tars-common-api/src/main/java/com/qq/tars/client/ServantProxy.java index 0cd1ff0b..a03df15c 100644 --- a/core/src/main/java/com/qq/tars/client/ServantProxy.java +++ b/tars-common-api/src/main/java/com/qq/tars/client/ServantProxy.java @@ -18,13 +18,13 @@ public interface ServantProxy { - public Class getApi(); + Class getApi(); - public String getObjectName(); + String getObjectName(); - public void refresh(); + void refresh(); - public void destroy(); + void destroy(); - public ServantProxyConfig getConfig(); + ServantProxyConfig getConfig(); } diff --git a/core/src/main/java/com/qq/tars/client/ServantProxyConfig.java b/tars-common-api/src/main/java/com/qq/tars/client/ServantProxyConfig.java similarity index 85% rename from core/src/main/java/com/qq/tars/client/ServantProxyConfig.java rename to tars-common-api/src/main/java/com/qq/tars/client/ServantProxyConfig.java index 6766a989..7c2451b9 100644 --- a/core/src/main/java/com/qq/tars/client/ServantProxyConfig.java +++ b/tars-common-api/src/main/java/com/qq/tars/client/ServantProxyConfig.java @@ -20,6 +20,8 @@ import com.qq.tars.common.ClientVersion; import com.qq.tars.common.util.Constants; import com.qq.tars.common.util.StringUtils; +import com.qq.tars.protocol.util.TarsHelper; +import org.assertj.core.util.Preconditions; public final class ServantProxyConfig { @@ -34,17 +36,17 @@ public final class ServantProxyConfig { private volatile String simpleObjectName; private String masterName; private volatile String slaveName; - private String moduleName = Constants.default_modulename; + private String moduleName = Constants.DEFAULT_MODULE_NAME; private boolean enableSet = false; private volatile String setDivision = ""; private volatile String slaveSetName; private volatile String slaveSetArea; private volatile String slaveSetID; - private int connections = Constants.default_connections; - private int connectTimeout = Constants.default_connect_timeout; - private int syncTimeout = Constants.default_sync_timeout; - private int asyncTimeout = Constants.default_async_timeout; + private int connections = Constants.DEFAULT_CONNECTION; + private int connectTimeout = Constants.DEFAULT_CONNECTION_TIMEOUT; + private int syncTimeout = Constants.DEFAULT_SYNC_TIME; + private int asyncTimeout = Constants.DEFAULT_ASYNC_TIME; private int refreshInterval = Constants.default_refresh_interval; @@ -57,7 +59,7 @@ public final class ServantProxyConfig { private float frequenceFailRadio = 0.5f; private boolean tcpNoDelay = false; - private String charsetName = Constants.default_charset_name; + private String charsetName = Constants.DEFAULT_CHARSET.name(); private boolean directConnection = false; @@ -65,6 +67,45 @@ public final class ServantProxyConfig { private int maxStaticWeightLimit = 100; private int defaultConHashVirtualNodes = 100; + + private int maxPackageSize = TarsHelper.PACKAGE_MAX_LENGTH; + + public void setSimpleObjectName(String simpleObjectName) { + this.simpleObjectName = simpleObjectName; + } + + public void setMasterName(String masterName) { + this.masterName = masterName; + } + + public void setSlaveName(String slaveName) { + this.slaveName = slaveName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + + public void setSlaveSetName(String slaveSetName) { + this.slaveSetName = slaveSetName; + } + + public void setSlaveSetArea(String slaveSetArea) { + this.slaveSetArea = slaveSetArea; + } + + public void setSlaveSetID(String slaveSetID) { + this.slaveSetID = slaveSetID; + } + + public int getMaxPackageSize() { + return maxPackageSize; + } + + public void setMaxPackageSize(int maxPackageSize) { + this.maxPackageSize = maxPackageSize; + } + public ServantProxyConfig(String objectName) { this(null, null, objectName); } @@ -74,6 +115,7 @@ public ServantProxyConfig(String objectName) { } private ServantProxyConfig(String communicatorId, String locator, String objectName, boolean directConnection) { + Preconditions.checkNotNullOrEmpty(objectName, "objectName"); this.setCommunicatorId(communicatorId); this.setLocator(locator); this.setObjectName(objectName); @@ -196,11 +238,22 @@ public String getSetDivision() { } public void setSetDivision(String setDivision) { + if (StringUtils.isEmpty(setDivision)) { + return; + } this.setDivision = setDivision; String[] tmp = StringUtils.split(setDivision, "."); - this.slaveSetName = tmp[0]; - this.slaveSetArea = tmp[1]; - this.slaveSetID = tmp[2]; + if (tmp != null && tmp.length >= 3) { + this.slaveSetName = tmp[0]; + this.slaveSetArea = tmp[1]; + this.slaveSetID = tmp[2]; + this.setEnableSet(true); + } else { + this.slaveSetName = ""; + this.slaveSetArea = ""; + this.slaveSetID = ""; + this.setEnableSet(false); + } this.updateSlaveName(); } @@ -397,6 +450,7 @@ public String toString() { ", minStaticWeightLimit=" + minStaticWeightLimit + ", maxStaticWeightLimit=" + maxStaticWeightLimit + ", defaultConHashVirtualNodes=" + defaultConHashVirtualNodes + + ", maxPackageSize=" + maxPackageSize + '}'; } } diff --git a/tars-common-api/src/main/java/com/qq/tars/client/rpc/ChannelHandler.java b/tars-common-api/src/main/java/com/qq/tars/client/rpc/ChannelHandler.java new file mode 100644 index 00000000..bbb08725 --- /dev/null +++ b/tars-common-api/src/main/java/com/qq/tars/client/rpc/ChannelHandler.java @@ -0,0 +1,35 @@ +package com.qq.tars.client.rpc; + +import io.netty.channel.Channel; + +public interface ChannelHandler { + void connected(Channel channel); + + /** + * @param channel + */ + void disconnected(Channel channel); + + /** + * @param channel + * @param message + */ + void send(Channel channel, Object message); + + /** + * @param channel + * @param message + */ + void received(Channel channel, Object message); + + /** + * @param channel + * @param exception + */ + void caught(Channel channel, Throwable exception); + + /** + * + */ + void destroy(); +} diff --git a/net/src/main/java/com/qq/tars/net/protocol/ProtocolException.java b/tars-common-api/src/main/java/com/qq/tars/client/rpc/ProtocolException.java similarity index 91% rename from net/src/main/java/com/qq/tars/net/protocol/ProtocolException.java rename to tars-common-api/src/main/java/com/qq/tars/client/rpc/ProtocolException.java index 6747abb1..a5b82b20 100644 --- a/net/src/main/java/com/qq/tars/net/protocol/ProtocolException.java +++ b/tars-common-api/src/main/java/com/qq/tars/client/rpc/ProtocolException.java @@ -13,12 +13,15 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ +package com.qq.tars.client.rpc; -package com.qq.tars.net.protocol; @SuppressWarnings("serial") public class ProtocolException extends Exception { + + private static final long serialVersionUID = 5220984844274406112L; + public ProtocolException() { super(); } diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantProtocolFactory.java b/tars-common-api/src/main/java/com/qq/tars/client/rpc/RPCClient.java similarity index 56% rename from core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantProtocolFactory.java rename to tars-common-api/src/main/java/com/qq/tars/client/rpc/RPCClient.java index 60a22921..0208e59c 100644 --- a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantProtocolFactory.java +++ b/tars-common-api/src/main/java/com/qq/tars/client/rpc/RPCClient.java @@ -13,26 +13,31 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ +package com.qq.tars.client.rpc; -package com.qq.tars.rpc.protocol.tars; +import io.netty.channel.Channel; -import com.qq.tars.net.protocol.ProtocolDecoder; -import com.qq.tars.net.protocol.ProtocolEncoder; -import com.qq.tars.net.protocol.ProtocolFactory; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; -public class TarsServantProtocolFactory implements ProtocolFactory { - private TarsCodec codec = null; +public interface RPCClient { + /** + * send object + * @param request tarsServantRequest Object + * @return response Future + * @throws IOException + */ + CompletableFuture send(Request request) throws IOException; - public TarsServantProtocolFactory(TarsCodec codec) { - this.codec = codec; - } + /** + * @return return ioChannel + */ + Channel getChannel(); - public ProtocolEncoder getEncoder() { - return this.codec; - } + /** + * @throws IOException when close Exception + */ + void close() throws IOException; - public ProtocolDecoder getDecoder() { - return this.codec; - } } diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/model/ClasspathElement.java b/tars-common-api/src/main/java/com/qq/tars/client/rpc/Request.java similarity index 59% rename from tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/model/ClasspathElement.java rename to tars-common-api/src/main/java/com/qq/tars/client/rpc/Request.java index 826820d7..d05f8605 100644 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/model/ClasspathElement.java +++ b/tars-common-api/src/main/java/com/qq/tars/client/rpc/Request.java @@ -13,25 +13,43 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ -package com.qq.tars.maven.model; -@SuppressWarnings("all") -public class ClasspathElement implements java.io.Serializable { +package com.qq.tars.client.rpc; - private String relativePath; +import java.util.Map; - public ClasspathElement() { +public interface Request { + enum InvokeStatus { + SYNC_CALL, ASYNC_CALL, FUTURE_CALL } - public ClasspathElement(String relativePath) { - this.relativePath = relativePath; - } + /*** + * + * @return + */ + int getRequestId(); - public String getRelativePath() { - return this.relativePath; - } + /*** + * + * @return + */ + String getServantName(); + + /*** + * + * @return + */ + String getFunctionName(); + + /*** + * + * @return + */ + Map getDistributedContext(); + + + long getProcessTime(); + + long getBornTime(); - public void setRelativePath(String relativePath) { - this.relativePath = relativePath; - } } diff --git a/distributedContext/src/main/java/com/qq/tars/context/DistributedContext.java b/tars-common-api/src/main/java/com/qq/tars/client/rpc/Response.java similarity index 63% rename from distributedContext/src/main/java/com/qq/tars/context/DistributedContext.java rename to tars-common-api/src/main/java/com/qq/tars/client/rpc/Response.java index 310f47b6..2f2a0c3d 100644 --- a/distributedContext/src/main/java/com/qq/tars/context/DistributedContext.java +++ b/tars-common-api/src/main/java/com/qq/tars/client/rpc/Response.java @@ -13,23 +13,41 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ -package com.qq.tars.context; -import java.util.Map; -import java.util.Set; +package com.qq.tars.client.rpc; -public interface DistributedContext { - - public void clear(); +public interface Response { - public T get(String name); + /*** + * + * @return + */ + boolean isAsyncMode(); - public Set keySet(); + /*** + * + * @return + */ + int getRequestId(); - public void put(String name, T value); + /*** + * + */ + void asyncCallStart(); - public int size(); - - public Map getAttrbuites(); + /*** + * + */ + void asyncCallEnd(); + /*** + * + * @return + */ + Request getRequest(); + + /*** + * + */ + void ensureNotCommitted(); } diff --git a/tars-common-api/src/main/java/com/qq/tars/client/rpc/TicketFeature.java b/tars-common-api/src/main/java/com/qq/tars/client/rpc/TicketFeature.java new file mode 100644 index 00000000..06eeb73d --- /dev/null +++ b/tars-common-api/src/main/java/com/qq/tars/client/rpc/TicketFeature.java @@ -0,0 +1,89 @@ +package com.qq.tars.client.rpc; + +import com.qq.tars.rpc.protocol.tars.TarsServantResponse; +import io.netty.channel.Channel; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Future; + +public class TicketFeature extends CompletableFuture { + public static final int DEFAULT_TICKET_NUMBER = -1; + private Response response = null; + private final Request request; + private final Channel channel; + private final int id; + protected long timeout = 1000; + private static final Map featureMap = new ConcurrentHashMap<>(); + Future timeoutFuture; + + public Future getTimeoutFuture() { + return timeoutFuture; + } + + public void setTimeoutFuture(Future timeoutFuture) { + this.timeoutFuture = timeoutFuture; + } + + + public TicketFeature(Channel channel, Request request, long timeout) { + this.request = request; + this.timeout = timeout; + this.channel = channel; + this.id = request.getRequestId(); + featureMap.put(request.getRequestId(), this); + } + + + public static TicketFeature createFeature(Channel channel, Request request, int timeout) { + TicketFeature ticketFeature = new TicketFeature(channel, request, timeout); + return ticketFeature; + } + + public static TicketFeature getFeature(int requestId) { + return featureMap.get(requestId); + } + + public void received(Response response) { + if (response == null) { + throw new RuntimeException("response is null!"); + } + + TarsServantResponse tarsResponse = (TarsServantResponse) response; + this.complete(tarsResponse); + + } + + public Response getResponse() { + return response; + } + + public void setResponse(Response response) { + this.response = response; + } + + public Request getRequest() { + return request; + } + + public Channel getChannel() { + return channel; + } + + public int getId() { + return id; + } + + public long getTimeout() { + return timeout; + } + + public void setTimeout(long timeout) { + this.timeout = timeout; + } + + + public void cancel() { + this.cancel(true); + } +} diff --git a/tars-common-api/src/main/java/com/qq/tars/client/rpc/TransporterFactory.java b/tars-common-api/src/main/java/com/qq/tars/client/rpc/TransporterFactory.java new file mode 100644 index 00000000..ac3dc296 --- /dev/null +++ b/tars-common-api/src/main/java/com/qq/tars/client/rpc/TransporterFactory.java @@ -0,0 +1,43 @@ +package com.qq.tars.client.rpc; + +import com.qq.tars.client.ServantProxyConfig; +import com.qq.tars.rpc.common.Url; +import com.qq.tars.server.config.ServantAdapterConfig; +import com.qq.tars.server.core.Processor; + +/** + * Abstract factory for creating servers and clients in transportation。 + * + * @author kongyuanyuan + */ +public interface TransporterFactory { + + /** + * Connect with a server node using the given servant config. + * + * @param url server node url + * @param servantProxyConfig servant config + * @return rpc client instance + */ + RPCClient connect(Url url, ServantProxyConfig servantProxyConfig); + + /** + * Connect with a server node using the given servant config and channel handler. + * + * @param url server node url + * @param servantProxyConfig servant config + * @param channelHandler custom channel handler. Can be used in unit tests. + * @return rpc client instance + */ + RPCClient connect(Url url, ServantProxyConfig servantProxyConfig, ChannelHandler channelHandler); + + /** + * Get the server instance for transportation which can be used to bind ip/port with {@link TransporterServer#bind()} method. + * + * @param servantAdapterConfig the servant adapter config which is provided by the platform. + * @param processor the request processor. + * @return transporter server instance + * @see com.qq.tars.server.core.Processor + */ + TransporterServer getTransporterServer(ServantAdapterConfig servantAdapterConfig, Processor processor); +} diff --git a/tars-common-api/src/main/java/com/qq/tars/client/rpc/TransporterServer.java b/tars-common-api/src/main/java/com/qq/tars/client/rpc/TransporterServer.java new file mode 100644 index 00000000..926ab257 --- /dev/null +++ b/tars-common-api/src/main/java/com/qq/tars/client/rpc/TransporterServer.java @@ -0,0 +1,18 @@ +package com.qq.tars.client.rpc; + +/** + * 传输层服务器。需要实现{@code bind}方法来绑定服务地址与端口号。 + * + * @author kongyuanyuan + */ +public interface TransporterServer { + /** + * 执行绑定动作。 + */ + void bind(); + + /** + * 停止服务器。 + */ + void stop(); +} diff --git a/core/src/main/java/com/qq/tars/client/util/ParseTools.java b/tars-common-api/src/main/java/com/qq/tars/client/util/ParseTools.java similarity index 88% rename from core/src/main/java/com/qq/tars/client/util/ParseTools.java rename to tars-common-api/src/main/java/com/qq/tars/client/util/ParseTools.java index cb15b673..9d704c94 100644 --- a/core/src/main/java/com/qq/tars/client/util/ParseTools.java +++ b/tars-common-api/src/main/java/com/qq/tars/client/util/ParseTools.java @@ -122,20 +122,28 @@ private static Url parse(String objectName, String content, ServantProxyConfig c int weightType = 0; int weight = 0; for (int i = 0; i < items.length; i++) { - if (items[i].equals("-h")) { - host = items[i + 1]; - } else if (items[i].equals("-p")) { - port = Integer.parseInt(items[i + 1]); - } else if (items[i].equals("-a")) { - active = Integer.parseInt(items[i + 1]); - } else if (items[i].equals("-s")) { - setDivision = items[i + 1]; - } else if (items[i].equals("-e")) { - enableAuth = items[i + 1]; - } else if (items[i].equals("-v")) { - weightType = Integer.parseInt(items[i + 1]); - } else if (items[i].equals("-w")) { - weight = Integer.parseInt(items[i + 1]); + switch (items[i]) { + case "-h": + host = items[i + 1]; + break; + case "-p": + port = Integer.parseInt(items[i + 1]); + break; + case "-a": + active = Integer.parseInt(items[i + 1]); + break; + case "-s": + setDivision = items[i + 1]; + break; + case "-e": + enableAuth = items[i + 1]; + break; + case "-v": + weightType = Integer.parseInt(items[i + 1]); + break; + case "-w": + weight = Integer.parseInt(items[i + 1]); + break; } } if (StringUtils.isEmpty(host) || port == -1) { @@ -155,7 +163,6 @@ private static Url parse(String objectName, String content, ServantProxyConfig c parameters.put(Constants.TARS_CLIENT_ENABLEAUTH, enableAuth); parameters.put(Constants.TARS_CLIENT_WEIGHT_TYPE, String.valueOf(weightType)); parameters.put(Constants.TARS_CLIENT_WEIGHT, String.valueOf(weight)); - return new Url(conf.getProtocol(), host, port, objectName, parameters); } } diff --git a/core/src/main/java/com/qq/tars/common/ClientVersion.java b/tars-common-api/src/main/java/com/qq/tars/common/ClientVersion.java similarity index 78% rename from core/src/main/java/com/qq/tars/common/ClientVersion.java rename to tars-common-api/src/main/java/com/qq/tars/common/ClientVersion.java index 03794249..6a6bef9a 100644 --- a/core/src/main/java/com/qq/tars/common/ClientVersion.java +++ b/tars-common-api/src/main/java/com/qq/tars/common/ClientVersion.java @@ -18,15 +18,13 @@ public final class ClientVersion { -// public static final String major = "1"; -// public static final String minor = "6"; -// public static final String build = "1"; + // public static final String major = "1"; + // public static final String minor = "6"; + // public static final String build = "1"; - public static String getVersion() { - return "1.6.1"; - } + public static final String CLIENT_VERSION = "2.0.0"; - public String toString() { - return getVersion(); + public static String getVersion() { + return CLIENT_VERSION; } } diff --git a/core/src/main/java/com/qq/tars/common/support/ClassLoaderManager.java b/tars-common-api/src/main/java/com/qq/tars/common/support/ClassLoaderManager.java similarity index 100% rename from core/src/main/java/com/qq/tars/common/support/ClassLoaderManager.java rename to tars-common-api/src/main/java/com/qq/tars/common/support/ClassLoaderManager.java diff --git a/core/src/main/java/com/qq/tars/common/support/Endpoint.java b/tars-common-api/src/main/java/com/qq/tars/common/support/Endpoint.java similarity index 87% rename from core/src/main/java/com/qq/tars/common/support/Endpoint.java rename to tars-common-api/src/main/java/com/qq/tars/common/support/Endpoint.java index efe4ca14..f6d89a6a 100644 --- a/core/src/main/java/com/qq/tars/common/support/Endpoint.java +++ b/tars-common-api/src/main/java/com/qq/tars/common/support/Endpoint.java @@ -16,20 +16,19 @@ package com.qq.tars.common.support; -public class Endpoint { +import javax.annotation.concurrent.Immutable; +import java.util.Objects; +@Immutable +public final class Endpoint { private final String type; - private final String host; - private final int port; - + private final String host; + private final int port; private final int timeout; - private final int grid; - private final int qos; - private final String setDivision; - - private int hash; - - public static final Endpoint VOID_ENDPOINT = new Endpoint("tcp", "0.0.0.0", 0, 0, 0, 0, null); + private final int grid; + private final int qos; + private final String setDivision; + public static final Endpoint NULL_ENDPOINT = new Endpoint("tcp", "0.0.0.0", 0, 0, 0, 0, null); public Endpoint(String type, String host, int port, int timeout, int grid, int qos, String setDivision) { this.type = type; @@ -71,15 +70,7 @@ public String setDivision() { @Override public int hashCode() { - int h = hash; - if (h == 0) { - h = 1; - h = 31 * h + type.hashCode(); - h = 31 * h + host.hashCode(); - h = 31 * h + port; - hash = h; - } - return h; + return Objects.hash(type, host, port, timeout, grid, qos, setDivision); } @Override @@ -88,12 +79,9 @@ public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; Endpoint other = (Endpoint) obj; - if (host == null) { - if (other.host != null) return false; - } else if (!host.equals(other.host)) return false; if (port != other.port) return false; if (type != other.type) return false; - return true; + return Objects.equals(this.host, other.host); } @Override diff --git a/core/src/main/java/com/qq/tars/common/support/Holder.java b/tars-common-api/src/main/java/com/qq/tars/common/support/Holder.java similarity index 90% rename from core/src/main/java/com/qq/tars/common/support/Holder.java rename to tars-common-api/src/main/java/com/qq/tars/common/support/Holder.java index 3c2ab5e4..3a9e78c5 100644 --- a/core/src/main/java/com/qq/tars/common/support/Holder.java +++ b/tars-common-api/src/main/java/com/qq/tars/common/support/Holder.java @@ -16,6 +16,8 @@ package com.qq.tars.common.support; +import java.util.Objects; + public class Holder { public T value; @@ -46,10 +48,7 @@ public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; Holder other = (Holder) obj; - if (value == null) { - if (other.value != null) return false; - } else if (!value.equals(other.value)) return false; - return true; + return Objects.equals(this.value, other.value); } @Override diff --git a/core/src/main/java/com/qq/tars/common/util/BeanAccessor.java b/tars-common-api/src/main/java/com/qq/tars/common/util/BeanAccessor.java similarity index 96% rename from core/src/main/java/com/qq/tars/common/util/BeanAccessor.java rename to tars-common-api/src/main/java/com/qq/tars/common/util/BeanAccessor.java index 086817d6..3ddfb990 100644 --- a/core/src/main/java/com/qq/tars/common/util/BeanAccessor.java +++ b/tars-common-api/src/main/java/com/qq/tars/common/util/BeanAccessor.java @@ -16,20 +16,20 @@ package com.qq.tars.common.util; +import sun.misc.Unsafe; + import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; -import sun.misc.Unsafe; - public class BeanAccessor { private static Unsafe unsafe; private static Map, Map> beaninfoMap; private static Map, Map> beanFieldOffsetMap; - public static String SERIALVERSIONUID = "serialVersionUID"; + public static String SERIAL_VERSION_UID = "serialVersionUID"; public static String FINAL = "final"; public static String STATIC = "static"; @@ -112,7 +112,7 @@ public static long getBeanFieldOffset(Class clazz, String fieldName) { for (String key : fieldMap.keySet()) { Field field = fieldMap.get(key); String modifiers = Modifier.toString(field.getModifiers()); - if (field.getName().equals(SERIALVERSIONUID) || modifiers.contains(FINAL) || modifiers.contains(STATIC)) { + if (field.getName().equals(SERIAL_VERSION_UID) || modifiers.contains(FINAL) || modifiers.contains(STATIC)) { continue; } long offset = getUnsafeInstance().objectFieldOffset(field); @@ -124,7 +124,7 @@ public static long getBeanFieldOffset(Class clazz, String fieldName) { } Long result = offsetMap == null ? null : offsetMap.get(fieldName); - return result == null ? -1 : result.longValue(); + return result == null ? -1 : result; } public static Object getBeanValue(Object bean, String fieldName) { diff --git a/tars-common-api/src/main/java/com/qq/tars/common/util/CollectionUtils.java b/tars-common-api/src/main/java/com/qq/tars/common/util/CollectionUtils.java new file mode 100644 index 00000000..8a5f6455 --- /dev/null +++ b/tars-common-api/src/main/java/com/qq/tars/common/util/CollectionUtils.java @@ -0,0 +1,25 @@ +package com.qq.tars.common.util; + +import java.util.Collection; + +public class CollectionUtils { + private CollectionUtils() { + + } + + public static boolean isEmpty(Collection collction) { + if (collction == null || collction.isEmpty()) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + public static boolean isNotEmpty(Collection collction) { + return !isEmpty(collction); + } + + + + +} diff --git a/core/src/main/java/com/qq/tars/common/util/CommonUtils.java b/tars-common-api/src/main/java/com/qq/tars/common/util/CommonUtils.java similarity index 83% rename from core/src/main/java/com/qq/tars/common/util/CommonUtils.java rename to tars-common-api/src/main/java/com/qq/tars/common/util/CommonUtils.java index 317c8ef1..b99cedf4 100644 --- a/core/src/main/java/com/qq/tars/common/util/CommonUtils.java +++ b/tars-common-api/src/main/java/com/qq/tars/common/util/CommonUtils.java @@ -16,7 +16,9 @@ package com.qq.tars.common.util; +import java.net.InetSocketAddress; import java.util.Collection; +import java.util.HashMap; import java.util.Map; @SuppressWarnings("unchecked") @@ -70,4 +72,16 @@ public static int getPoolSize() { int processors = Runtime.getRuntime().availableProcessors(); return processors > 8 ? 4 + (processors * 5 / 8) : processors + 1; } + + public static String getIPAndPort(InetSocketAddress remoteAddress) { + return String.format("%s:%s", remoteAddress.getHostString(), remoteAddress.getPort()); + } + + public static Map convertMap(Map strMap) { + Map hashmap = new HashMap<>(); + for (Map.Entry entry : strMap.entrySet()) { + hashmap.put(entry.getKey(), entry.getValue()); + } + return hashmap; + } } diff --git a/core/src/main/java/com/qq/tars/common/util/Config.java b/tars-common-api/src/main/java/com/qq/tars/common/util/Config.java similarity index 100% rename from core/src/main/java/com/qq/tars/common/util/Config.java rename to tars-common-api/src/main/java/com/qq/tars/common/util/Config.java diff --git a/core/src/main/java/com/qq/tars/common/util/Constants.java b/tars-common-api/src/main/java/com/qq/tars/common/util/Constants.java similarity index 79% rename from core/src/main/java/com/qq/tars/common/util/Constants.java rename to tars-common-api/src/main/java/com/qq/tars/common/util/Constants.java index 542313b5..f49af35e 100644 --- a/core/src/main/java/com/qq/tars/common/util/Constants.java +++ b/tars-common-api/src/main/java/com/qq/tars/common/util/Constants.java @@ -16,6 +16,9 @@ package com.qq.tars.common.util; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + public interface Constants { String SERVER_NODE_CACHE_FILENAME = "tarsnodes.dat"; @@ -28,25 +31,25 @@ public interface Constants { int default_max_sample_count = 200; int default_sample_rate = 1000; - String default_modulename = "tars-client"; + String DEFAULT_MODULE_NAME = "tars-client"; String default_stat = "tars.tarsstat.StatObj"; - int default_connections = 4; - int default_connect_timeout = 3000; - int default_sync_timeout = 3000; - int default_async_timeout = 3000; + int DEFAULT_CONNECTION = 4; + int DEFAULT_CONNECTION_TIMEOUT = 3000; + int DEFAULT_SYNC_TIME = 3000; + int DEFAULT_ASYNC_TIME = 3000; int default_refresh_interval = 60 * 1000; int default_report_interval = 60 * 1000; int default_background_queuesize = 20000; - String default_charset_name = "UTF-8"; - - int default_queue_size = 20000; - int default_core_pool_size = Runtime.getRuntime().availableProcessors(); - int default_max_pool_size = Runtime.getRuntime().availableProcessors() * 2; - int default_keep_alive_time = 120; + Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; + String DEFAULT_CHARSET_STRING = "UTF-8"; + int DEFAULT_QUEUE_SIZE = 20000; + int DEFAULT_CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors(); + int DEFAULT_MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2; + int DEFAULT_KEEPALIVE_TIME = 120; int default_check_interval = 60 * 1000; int default_try_time_interval = 30; @@ -82,4 +85,7 @@ public interface Constants { String TARS_CLIENT_WEIGHT_TYPE = "weightType"; String TARS_CLIENT_WEIGHT = "weight"; String TARS_CLIENT_GRAYFLAG = "taf.framework.GrayFlag"; + + String TARS_METHOD_ASYNC_START_WITH = "async_"; + String TARS_METHOD_PROMISE_START_WITH = "promise_"; } diff --git a/core/src/main/java/com/qq/tars/common/util/HexUtil.java b/tars-common-api/src/main/java/com/qq/tars/common/util/HexUtil.java similarity index 100% rename from core/src/main/java/com/qq/tars/common/util/HexUtil.java rename to tars-common-api/src/main/java/com/qq/tars/common/util/HexUtil.java diff --git a/tars-common-api/src/main/java/com/qq/tars/common/util/JsonProvider.java b/tars-common-api/src/main/java/com/qq/tars/common/util/JsonProvider.java new file mode 100644 index 00000000..edde8388 --- /dev/null +++ b/tars-common-api/src/main/java/com/qq/tars/common/util/JsonProvider.java @@ -0,0 +1,29 @@ +package com.qq.tars.common.util; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; + +import java.lang.reflect.Type; + +public class JsonProvider { + private static final Gson gson = new Gson(); + + + public static String toJson(final Object obj) { + return gson.toJson(obj); + } + + public static T fromJson(final String str, Class cls) { + return gson.fromJson(str, cls); + } + + + public static JsonElement toJsonTree(final Object obj) { + return gson.toJsonTree(obj); + } + + + public static T fromJson(final String str, Type type) { + return gson.fromJson(str, type); + } +} diff --git a/core/src/main/java/com/qq/tars/common/util/StringUtils.java b/tars-common-api/src/main/java/com/qq/tars/common/util/StringUtils.java similarity index 89% rename from core/src/main/java/com/qq/tars/common/util/StringUtils.java rename to tars-common-api/src/main/java/com/qq/tars/common/util/StringUtils.java index ceee4cb2..c3d91ad4 100644 --- a/core/src/main/java/com/qq/tars/common/util/StringUtils.java +++ b/tars-common-api/src/main/java/com/qq/tars/common/util/StringUtils.java @@ -26,6 +26,9 @@ import java.util.Date; public class StringUtils { + private StringUtils() { + + } public static final String ENC_UTF8 = "UTF-8"; @@ -57,22 +60,14 @@ public static String formatDate(String dateStr, String format) { inputFormat = "yyyy-MM-dd HH:mm:ss.SSS"; } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}:\\d{1,2}")) { inputFormat = "yyyy-MM-dd HH:mm:ss"; - } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}:\\d{1,2}")) { - inputFormat = "yyyy-MM-dd HH:mm"; } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}")) { inputFormat = "yyyy-MM-dd HH"; - } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}")) { - inputFormat = "yyyy-MM-dd"; } else if (dateStr.matches("\\d{1,4}/\\d{1,2}/\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}")) { inputFormat = "yyyy/MM/dd HH:mm:ss.SSS"; } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}:\\d{1,2}")) { inputFormat = "yyyy/MM/dd HH:mm:ss"; - } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}:\\d{1,2}")) { - inputFormat = "yyyy/MM/dd HH:mm"; } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}")) { inputFormat = "yyyy/MM/dd HH"; - } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}")) { - inputFormat = "yyyy/MM/dd"; } resultStr = formatDate(dateStr, inputFormat, format); return resultStr; @@ -157,19 +152,19 @@ public static boolean convertBoolean(String str, boolean defaults) { } } - public static String[] split(String line, String seperator) { - if (line == null || seperator == null || seperator.length() == 0) return null; + public static String[] split(String line, String separator) { + if (line == null || separator == null || separator.length() == 0) return null; ArrayList list = new ArrayList(); int pos1 = 0; int pos2; for (;;) { - pos2 = line.indexOf(seperator, pos1); + pos2 = line.indexOf(separator, pos1); if (pos2 < 0) { list.add(line.substring(pos1)); break; } list.add(line.substring(pos1, pos2)); - pos1 = pos2 + seperator.length(); + pos1 = pos2 + separator.length(); } for (int i = list.size() - 1; i >= 0 && list.get(i).length() == 0; --i) { list.remove(i); @@ -177,8 +172,8 @@ public static String[] split(String line, String seperator) { return list.toArray(new String[0]); } - public static int[] splitInt(String line, String seperator, int def) { - String[] ss = split(line, seperator); + public static int[] splitInt(String line, String separator, int def) { + String[] ss = split(line, separator); int[] r = new int[ss.length]; for (int i = 0; i < r.length; ++i) { r[i] = convertInt(ss[i], def); @@ -186,8 +181,8 @@ public static int[] splitInt(String line, String seperator, int def) { return r; } - public static long[] splitLong(String line, String seperator, long def) { - String[] ss = split(line, seperator); + public static long[] splitLong(String line, String separator, long def) { + String[] ss = split(line, separator); long[] r = new long[ss.length]; for (int i = 0; i < r.length; ++i) { r[i] = convertLong(ss[i], def); @@ -244,14 +239,14 @@ public static String replaceAll(String s, String src, String dest) { if (pos < 0) return s; int capacity = dest.length() > src.length() ? s.length() * 2 : s.length(); StringBuilder sb = new StringBuilder(capacity); - int writen = 0; + int written = 0; for (; pos >= 0;) { - sb.append(s, writen, pos); + sb.append(s, written, pos); sb.append(dest); - writen = pos + src.length(); - pos = s.indexOf(src, writen); + written = pos + src.length(); + pos = s.indexOf(src, written); } - sb.append(s, writen, s.length()); + sb.append(s, written, s.length()); return sb.toString(); } diff --git a/tars-common-api/src/main/java/com/qq/tars/common/util/VirtualThreadSupport.java b/tars-common-api/src/main/java/com/qq/tars/common/util/VirtualThreadSupport.java new file mode 100644 index 00000000..41f93d5b --- /dev/null +++ b/tars-common-api/src/main/java/com/qq/tars/common/util/VirtualThreadSupport.java @@ -0,0 +1,107 @@ +package com.qq.tars.common.util; + +import java.lang.reflect.Method; +import java.util.Objects; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.RejectedExecutionException; +import java.util.logging.Level; +import java.util.logging.Logger; + +public final class VirtualThreadSupport { + private static final Logger logger = Logger.getLogger(VirtualThreadSupport.class.getName()); + + public static final String VTHREAD_ENABLED_KEY = "tars.virtual.threads.enabled"; + public static final String SERVER_VTHREAD_ENABLED_KEY = "tars.virtual.threads.server.enabled"; + + private static volatile ExecutorService serverVirtualExecutor; + private static volatile boolean unsupportedLogged = false; + + private VirtualThreadSupport() { + } + + public static boolean isVirtualThreadSupported() { + try { + Method factoryMethod = Thread.class.getMethod("ofVirtual"); + return factoryMethod != null; + } catch (NoSuchMethodException e) { + return false; + } + } + + public static boolean isServerVirtualThreadEnabled() { + String serverEnabled = System.getProperty(SERVER_VTHREAD_ENABLED_KEY); + if (serverEnabled != null) { + return Boolean.parseBoolean(serverEnabled); + } + return Boolean.parseBoolean(System.getProperty(VTHREAD_ENABLED_KEY, "false")); + } + + public static boolean executeServerTask(Runnable task) { + Objects.requireNonNull(task, "task"); + if (!isServerVirtualThreadEnabled()) { + return false; + } + if (!isVirtualThreadSupported()) { + logUnsupportedOnce(); + return false; + } + + ExecutorService executor = getOrCreateServerExecutor(); + if (executor == null) { + return false; + } + try { + executor.execute(task); + return true; + } catch (RejectedExecutionException e) { + logger.log(Level.WARNING, "[tars] submit virtual thread task failed, {0}", e.getMessage()); + return false; + } + } + + static void shutdownForTest() { + ExecutorService executor = serverVirtualExecutor; + serverVirtualExecutor = null; + if (executor != null) { + executor.shutdownNow(); + } + } + + private static ExecutorService getOrCreateServerExecutor() { + ExecutorService executor = serverVirtualExecutor; + if (executor != null) { + return executor; + } + synchronized (VirtualThreadSupport.class) { + executor = serverVirtualExecutor; + if (executor != null) { + return executor; + } + serverVirtualExecutor = createVirtualThreadExecutor(); + return serverVirtualExecutor; + } + } + + private static ExecutorService createVirtualThreadExecutor() { + try { + Method method = java.util.concurrent.Executors.class.getMethod("newVirtualThreadPerTaskExecutor"); + return (ExecutorService) method.invoke(null); + } catch (Throwable e) { + logger.log(Level.WARNING, "[tars] create virtual thread executor failed, {0}", e.getMessage()); + return null; + } + } + + private static void logUnsupportedOnce() { + if (unsupportedLogged) { + return; + } + synchronized (VirtualThreadSupport.class) { + if (unsupportedLogged) { + return; + } + unsupportedLogged = true; + logger.warning("[tars] virtual threads are enabled but current JDK does not support them"); + } + } +} diff --git a/core/src/main/java/com/qq/tars/protocol/annotation/Servant.java b/tars-common-api/src/main/java/com/qq/tars/protocol/annotation/Servant.java similarity index 100% rename from core/src/main/java/com/qq/tars/protocol/annotation/Servant.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/annotation/Servant.java diff --git a/core/src/main/java/com/qq/tars/protocol/annotation/ServantCodec.java b/tars-common-api/src/main/java/com/qq/tars/protocol/annotation/ServantCodec.java similarity index 100% rename from core/src/main/java/com/qq/tars/protocol/annotation/ServantCodec.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/annotation/ServantCodec.java index 0d5498f2..a46408cd 100644 --- a/core/src/main/java/com/qq/tars/protocol/annotation/ServantCodec.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/annotation/ServantCodec.java @@ -16,13 +16,13 @@ package com.qq.tars.protocol.annotation; +import com.qq.tars.rpc.protocol.Codec; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import com.qq.tars.rpc.protocol.Codec; - @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ServantCodec { diff --git a/core/src/main/java/com/qq/tars/protocol/tars/TarsInputStream.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsInputStream.java similarity index 88% rename from core/src/main/java/com/qq/tars/protocol/tars/TarsInputStream.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsInputStream.java index a13e74cc..da9535ac 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/TarsInputStream.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsInputStream.java @@ -16,26 +16,29 @@ package com.qq.tars.protocol.tars; -import java.io.UnsupportedEncodingException; + +import com.qq.tars.common.util.HexUtil; +import com.qq.tars.protocol.tars.exc.TarsDecodeException; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; + import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; -import com.qq.tars.common.util.HexUtil; -import com.qq.tars.protocol.tars.exc.TarsDecodeException; - public final class TarsInputStream { - - private ByteBuffer bs; // 缓冲区 + //private ByteBuffer bs; // 缓冲区 + private ByteBuf bs; public static class HeadData { - public byte type; public int tag; @@ -49,17 +52,18 @@ public TarsInputStream() { } - public TarsInputStream(ByteBuffer bs) { + public TarsInputStream(ByteBuf bs) { + bs.resetReaderIndex(); this.bs = bs; } public TarsInputStream(byte[] bs) { - this.bs = ByteBuffer.wrap(bs); + this.bs = Unpooled.copiedBuffer(bs); } public TarsInputStream(byte[] bs, int pos) { - this.bs = ByteBuffer.wrap(bs); - this.bs.position(pos); + this.bs = Unpooled.copiedBuffer(bs); + this.bs.readerIndex(pos); } public void warp(byte[] bs) { @@ -67,15 +71,16 @@ public void warp(byte[] bs) { } public void wrap(byte[] bs) { - this.bs = ByteBuffer.wrap(bs); + //this.bs = ByteBuffer.wrap(bs); + this.bs = Unpooled.wrappedBuffer(bs); } - public static int readHead(HeadData hd, ByteBuffer bb) { - byte b = bb.get(); + public static int readHead(HeadData hd, ByteBuf bb) { + byte b = bb.readByte(); hd.type = (byte) (b & 15); hd.tag = ((b & (15 << 4)) >> 4); if (hd.tag == 15) { - hd.tag = (bb.get() & 0x00ff); + hd.tag = (bb.readByte() & 0x00ff); return 2; } return 1; @@ -90,7 +95,8 @@ private int peakHead(HeadData hd) { } private void skip(int len) { - bs.position(bs.position() + len); + //bs.position(bs.position() + len); + bs.readerIndex(bs.readerIndex() + len); } public boolean skipToTag(int tag) { @@ -105,8 +111,7 @@ public boolean skipToTag(int tag) { skip(len); skipField(hd.type); } - } catch (TarsDecodeException e) { - } catch (BufferUnderflowException e) { + } catch (TarsDecodeException | BufferUnderflowException | IndexOutOfBoundsException e) { } return false; } @@ -146,13 +151,14 @@ private void skipField(byte type) { skip(8); break; case TarsStructBase.STRING1: { - int len = bs.get(); + //int len = bs.get(); + int len = bs.readByte(); if (len < 0) len += 256; skip(len); break; } case TarsStructBase.STRING4: { - skip(bs.getInt()); + skip(bs.readInt()); break; } case TarsStructBase.MAP: { @@ -202,7 +208,7 @@ public byte read(byte c, int tag, boolean isRequire) { c = 0x0; break; case TarsStructBase.BYTE: - c = bs.get(); + c = bs.readByte(); break; default: throw new TarsDecodeException("type mismatch."); @@ -222,10 +228,10 @@ public short read(short n, int tag, boolean isRequire) { n = 0; break; case TarsStructBase.BYTE: - n = (short) bs.get(); + n = (short) bs.readByte(); break; case TarsStructBase.SHORT: - n = bs.getShort(); + n = bs.readShort(); break; default: throw new TarsDecodeException("type mismatch."); @@ -245,13 +251,13 @@ public int read(int n, int tag, boolean isRequire) { n = 0; break; case TarsStructBase.BYTE: - n = bs.get(); + n = bs.readByte(); break; case TarsStructBase.SHORT: - n = bs.getShort(); + n = bs.readShort(); break; case TarsStructBase.INT: - n = bs.getInt(); + n = bs.readInt(); break; default: throw new TarsDecodeException("type mismatch."); @@ -271,16 +277,16 @@ public long read(long n, int tag, boolean isRequire) { n = 0; break; case TarsStructBase.BYTE: - n = bs.get(); + n = bs.readByte(); break; case TarsStructBase.SHORT: - n = bs.getShort(); + n = bs.readShort(); break; case TarsStructBase.INT: - n = bs.getInt(); + n = bs.readInt(); break; case TarsStructBase.LONG: - n = bs.getLong(); + n = bs.readLong(); break; default: throw new TarsDecodeException("type mismatch."); @@ -300,7 +306,7 @@ public float read(float n, int tag, boolean isRequire) { n = 0; break; case TarsStructBase.FLOAT: - n = bs.getFloat(); + n = bs.readFloat(); break; default: throw new TarsDecodeException("type mismatch."); @@ -320,10 +326,10 @@ public double read(double n, int tag, boolean isRequire) { n = 0; break; case TarsStructBase.FLOAT: - n = bs.getFloat(); + n = bs.readFloat(); break; case TarsStructBase.DOUBLE: - n = bs.getDouble(); + n = bs.readDouble(); break; default: throw new TarsDecodeException("type mismatch."); @@ -340,21 +346,23 @@ public String readByteString(String s, int tag, boolean isRequire) { readHead(hd); switch (hd.type) { case TarsStructBase.STRING1: { - int len = bs.get(); + int len = bs.readByte(); if (len < 0) len += 256; byte[] ss = new byte[len]; - bs.get(ss); + //bs.get(ss); + bs.readBytes(ss); s = HexUtil.bytes2HexStr(ss); } - break; + break; case TarsStructBase.STRING4: { - int len = bs.getInt(); - if (len > TarsStructBase.MAX_STRING_LENGTH || len < 0) throw new TarsDecodeException("String too long: " + len); + int len = bs.readInt(); + if (len > TarsStructBase.MAX_STRING_LENGTH || len < 0) + throw new TarsDecodeException("String too long: " + len); byte[] ss = new byte[len]; - bs.get(ss); + bs.readBytes(ss); s = HexUtil.bytes2HexStr(ss); } - break; + break; default: throw new TarsDecodeException("type mismatch."); } @@ -370,29 +378,23 @@ public String read(String s, int tag, boolean isRequire) { readHead(hd); switch (hd.type) { case TarsStructBase.STRING1: { - int len = bs.get(); + int len = bs.readByte(); if (len < 0) len += 256; byte[] ss = new byte[len]; - bs.get(ss); - try { - s = new String(ss, sServerEncoding); - } catch (UnsupportedEncodingException e) { - s = new String(ss); - } + bs.readBytes(ss); + s = new String(ss, sServerEncoding); } - break; + break; case TarsStructBase.STRING4: { - int len = bs.getInt(); - if (len > TarsStructBase.MAX_STRING_LENGTH || len < 0) throw new TarsDecodeException("String too long: " + len); + int len = bs.readInt(); + if (len > TarsStructBase.MAX_STRING_LENGTH || len < 0) + throw new TarsDecodeException("String too long: " + len); byte[] ss = new byte[len]; - bs.get(ss); - try { - s = new String(ss, sServerEncoding); - } catch (UnsupportedEncodingException e) { - s = new String(ss); - } + //bs.get(ss); + bs.readBytes(ss); + s = new String(ss, sServerEncoding); } - break; + break; default: throw new TarsDecodeException("type mismatch."); } @@ -409,29 +411,24 @@ public String readString(int tag, boolean isRequire) { readHead(hd); switch (hd.type) { case TarsStructBase.STRING1: { - int len = bs.get(); + int len = bs.readByte(); if (len < 0) len += 256; byte[] ss = new byte[len]; - bs.get(ss); - try { - s = new String(ss, sServerEncoding); - } catch (UnsupportedEncodingException e) { - s = new String(ss); - } + //bs.get(ss); + bs.readBytes(ss); + s = new String(ss, sServerEncoding); } - break; + break; case TarsStructBase.STRING4: { - int len = bs.getInt(); - if (len > TarsStructBase.MAX_STRING_LENGTH || len < 0) throw new TarsDecodeException("String too long: " + len); + int len = bs.readInt(); + if (len > TarsStructBase.MAX_STRING_LENGTH || len < 0) + throw new TarsDecodeException("String too long: " + len); byte[] ss = new byte[len]; - bs.get(ss); - try { - s = new String(ss, sServerEncoding); - } catch (UnsupportedEncodingException e) { - s = new String(ss); - } + //bs.get(ss); + bs.readBytes(ss); + s = new String(ss, sServerEncoding); } - break; + break; default: throw new TarsDecodeException("type mismatch."); } @@ -460,7 +457,7 @@ public Map readStringMap(int tag, boolean isRequire) { mr.put(k, v); } } - break; + break; default: throw new TarsDecodeException("type mismatch."); } @@ -474,7 +471,7 @@ public HashMap readMap(Map m, int tag, boolean isRequire) { return (HashMap) readMap(new HashMap(), m, tag, isRequire); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) private Map readMap(Map mr, Map m, int tag, boolean isRequire) { if (m == null || m.isEmpty()) { return new HashMap(); @@ -498,7 +495,7 @@ private Map readMap(Map mr, Map m, int tag, boolean isR mr.put(k, v); } } - break; + break; default: throw new TarsDecodeException("type mismatch."); } @@ -508,7 +505,7 @@ private Map readMap(Map mr, Map m, int tag, boolean isR return mr; } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public List readList(int tag, boolean isRequire) { List lr = new ArrayList(); if (skipToTag(tag)) { @@ -541,23 +538,23 @@ public List readList(int tag, boolean isRequire) { skip(8); break; case TarsStructBase.STRING1: { - int len = bs.get(); + int len = bs.readByte(); if (len < 0) len += 256; skip(len); } - break; + break; case TarsStructBase.STRING4: { - skip(bs.getInt()); + skip(bs.readInt()); } - break; + break; case TarsStructBase.MAP: { } - break; + break; case TarsStructBase.LIST: { } - break; + break; case TarsStructBase.STRUCT_BEGIN: try { Class newoneClass = Class.forName(TarsStructBase.class.getName()); @@ -578,7 +575,7 @@ public List readList(int tag, boolean isRequire) { } } } - break; + break; default: throw new TarsDecodeException("type mismatch."); } @@ -624,9 +621,11 @@ public byte[] read(byte[] l, int tag, boolean isRequire) { throw new TarsDecodeException("type mismatch, tag: " + tag + ", type: " + hd.type + ", " + hh.type); } int size = read(0, 0, true); - if (size < 0) throw new TarsDecodeException("invalid size, tag: " + tag + ", type: " + hd.type + ", " + hh.type + ", size: " + size); + if (size < 0) + throw new TarsDecodeException("invalid size, tag: " + tag + ", type: " + hd.type + ", " + hh.type + ", size: " + size); lr = new byte[size]; - bs.get(lr); + //bs.get(lr); + bs.readBytes(lr); break; } case TarsStructBase.LIST: { @@ -772,9 +771,7 @@ public List readArray(List l, int tag, boolean isRequire) { } T[] tt = readArrayImpl(l.get(0), tag, isRequire); if (tt == null) return null; - ArrayList ll = new ArrayList(); - for (int i = 0; i < tt.length; ++i) - ll.add(tt[i]); + ArrayList ll = new ArrayList(Arrays.asList(tt)); return ll; } @@ -895,18 +892,22 @@ public Object read(T o, int tag, boolean isRequire) { } } - protected String sServerEncoding = "GBK"; + protected Charset sServerEncoding = StandardCharsets.UTF_8; - public int setServerEncoding(String se) { + public int setServerEncoding(Charset se) { sServerEncoding = se; return 0; } - public static void main(String[] args) { + public ByteBuf getBs() { + return this.bs; } - public ByteBuffer getBs() { - return bs; + public byte[] toByteArray() { + final byte[] byteArrays = new byte[bs.readableBytes()]; + bs.readBytes(byteArrays); + return byteArrays; } } + diff --git a/core/src/main/java/com/qq/tars/protocol/tars/TarsInputStreamExt.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsInputStreamExt.java similarity index 96% rename from core/src/main/java/com/qq/tars/protocol/tars/TarsInputStreamExt.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsInputStreamExt.java index 9ccca7cf..173afc99 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/TarsInputStreamExt.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsInputStreamExt.java @@ -16,9 +16,8 @@ package com.qq.tars.protocol.tars; -import java.util.List; - import com.qq.tars.common.util.BeanAccessor; +import com.qq.tars.common.util.CollectionUtils; import com.qq.tars.common.util.CommonUtils; import com.qq.tars.protocol.tars.TarsInputStream.HeadData; import com.qq.tars.protocol.tars.exc.TarsDecodeException; @@ -26,6 +25,8 @@ import com.qq.tars.protocol.tars.support.TarsStrutPropertyInfo; import com.qq.tars.protocol.util.TarsHelper; +import java.util.List; + @SuppressWarnings("unchecked") public class TarsInputStreamExt { @@ -46,7 +47,7 @@ public static T read(T e, int tag, boolean isRequire, TarsInputStream jis) { T result = (T) CommonUtils.newInstance(e.getClass()); List list = info.getPropertyList(); - if (!CommonUtils.isEmptyCollection(list)) { + if (CollectionUtils.isNotEmpty(list)) { for (TarsStrutPropertyInfo propertyInfo : list) { Object value = jis.read(propertyInfo.getStamp(), propertyInfo.getOrder(), propertyInfo.isRequire()); BeanAccessor.setBeanValue(result, propertyInfo.getName(), value); diff --git a/core/src/main/java/com/qq/tars/protocol/tars/TarsOutputStream.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsOutputStream.java similarity index 77% rename from core/src/main/java/com/qq/tars/protocol/tars/TarsOutputStream.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsOutputStream.java index ab425c7e..19715d88 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/TarsOutputStream.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsOutputStream.java @@ -16,60 +16,62 @@ package com.qq.tars.protocol.tars; -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.util.Arrays; +import com.qq.tars.common.util.Constants; +import com.qq.tars.common.util.HexUtil; +import com.qq.tars.protocol.tars.exc.TarsEncodeException; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; + +import java.nio.charset.Charset; import java.util.Collection; import java.util.List; import java.util.Map; -import com.qq.tars.common.util.HexUtil; -import com.qq.tars.protocol.tars.exc.TarsEncodeException; - public class TarsOutputStream { + protected Charset sServerEncoding = Constants.DEFAULT_CHARSET; - private ByteBuffer bs; + public int setServerEncoding(Charset se) { + this.sServerEncoding = se; + return 0; + } + + private ByteBuf bs; - public TarsOutputStream(ByteBuffer bs) { + public TarsOutputStream(ByteBuf bs) { this.bs = bs; } public TarsOutputStream(int capacity) { - bs = ByteBuffer.allocate(capacity); + bs = Unpooled.buffer(capacity); } public TarsOutputStream() { this(128); } - public ByteBuffer getByteBuffer() { + public ByteBuf getByteBuffer() { return bs; } public byte[] toByteArray() { - byte[] newBytes = new byte[bs.position()]; - System.arraycopy(bs.array(), 0, newBytes, 0, bs.position()); + //byte[] newBytes = new byte[bs.position()]; + byte[] newBytes = new byte[bs.readableBytes()]; + bs.getBytes(0, newBytes); return newBytes; } - public void reserve(int len) { - if (bs.remaining() < len) { - int n = (bs.capacity() + len) * 2; - ByteBuffer bs2 = ByteBuffer.allocate(n); - bs2.put(bs.array(), 0, bs.position()); - bs = bs2; - bs2 = null; - } - } public void writeHead(byte type, int tag) { if (tag < 15) { byte b = (byte) ((tag << 4) | type); - bs.put(b); + //bs.put(b); + bs.writeByte(b); } else if (tag < 256) { byte b = (byte) ((15 << 4) | type); - bs.put(b); - bs.put((byte) tag); + //bs.put(b); + bs.writeByte(b); + //bs.put((byte) tag); + bs.writeByte((byte) tag); } else { throw new TarsEncodeException("tag is too large: " + tag); } @@ -81,106 +83,99 @@ public void write(boolean b, int tag) { } public void write(byte b, int tag) { - reserve(3); if (b == 0) { writeHead(TarsStructBase.ZERO_TAG, tag); } else { writeHead(TarsStructBase.BYTE, tag); - bs.put(b); + //bs.put(b); + bs.writeByte(b); } } public void write(short n, int tag) { - reserve(4); if (n >= Byte.MIN_VALUE && n <= Byte.MAX_VALUE) { write((byte) n, tag); } else { writeHead(TarsStructBase.SHORT, tag); - bs.putShort(n); + bs.writeShort(n); } } public void write(int n, int tag) { - reserve(6); if (n >= Short.MIN_VALUE && n <= Short.MAX_VALUE) { write((short) n, tag); } else { writeHead(TarsStructBase.INT, tag); - bs.putInt(n); + bs.writeInt(n); } } public void write(long n, int tag) { - reserve(10); if (n >= Integer.MIN_VALUE && n <= Integer.MAX_VALUE) { write((int) n, tag); } else { writeHead(TarsStructBase.LONG, tag); - bs.putLong(n); + bs.writeLong(n); } } public void write(float n, int tag) { - reserve(6); writeHead(TarsStructBase.FLOAT, tag); - bs.putFloat(n); + bs.writeFloat(n); } public void write(double n, int tag) { - reserve(10); writeHead(TarsStructBase.DOUBLE, tag); - bs.putDouble(n); + bs.writeDouble(n); } public void writeStringByte(String s, int tag) { byte[] by = HexUtil.hexStr2Bytes(s); - reserve(10 + by.length); if (by.length > 255) { writeHead(TarsStructBase.STRING4, tag); - bs.putInt(by.length); - bs.put(by); + //bs.putInt(by.length); + //bs.put(by); + bs.writeInt(by.length); + bs.writeBytes(by); + } else { writeHead(TarsStructBase.STRING1, tag); - bs.put((byte) by.length); - bs.put(by); + //bs.put((byte) by.length); + //bs.put(by); + bs.writeByte((byte) by.length); + bs.writeBytes(by); } } public void writeByteString(String s, int tag) { - reserve(10 + s.length()); byte[] by = HexUtil.hexStr2Bytes(s); if (by.length > 255) { writeHead(TarsStructBase.STRING4, tag); - bs.putInt(by.length); - bs.put(by); + bs.writeInt(by.length); + bs.writeBytes(by); } else { writeHead(TarsStructBase.STRING1, tag); - bs.put((byte) by.length); - bs.put(by); + bs.writeByte((byte) by.length); + bs.writeBytes(by); } } public void write(String s, int tag) { byte[] by; - try { - by = s.getBytes(sServerEncoding); - } catch (UnsupportedEncodingException e) { - by = s.getBytes(); - } - reserve(10 + by.length); + by = s.getBytes(sServerEncoding); if (by.length > 255) { writeHead(TarsStructBase.STRING4, tag); - bs.putInt(by.length); - bs.put(by); + bs.writeInt(by.length); + bs.writeBytes(by); + } else { writeHead(TarsStructBase.STRING1, tag); - bs.put((byte) by.length); - bs.put(by); + bs.writeByte((byte) by.length); + bs.writeBytes(by); } } public void write(Map m, int tag) { - reserve(8); writeHead(TarsStructBase.MAP, tag); write(m == null ? 0 : m.size(), 0); if (m != null) { @@ -192,7 +187,6 @@ public void write(Map m, int tag) { } public void write(boolean[] l, int tag) { - reserve(8); writeHead(TarsStructBase.LIST, tag); write(l.length, 0); for (boolean e : l) @@ -200,15 +194,26 @@ public void write(boolean[] l, int tag) { } public void write(byte[] l, int tag) { - reserve(8 + l.length); writeHead(TarsStructBase.SIMPLE_LIST, tag); writeHead(TarsStructBase.BYTE, 0); write(l.length, 0); - bs.put(l); + bs.writeBytes(l); } + public void write(ByteBuf l, int tag) { + writeHead(TarsStructBase.SIMPLE_LIST, tag); + writeHead(TarsStructBase.BYTE, 0); + write(l.readableBytes(), 0); + bs.writeBytes(l); + } + public void writBodyeHead(ByteBuf l, int tag) { + writeHead(TarsStructBase.SIMPLE_LIST, tag); + writeHead(TarsStructBase.BYTE, 0); + write(l.readableBytes(), 0); + } + + public void write(short[] l, int tag) { - reserve(8); writeHead(TarsStructBase.LIST, tag); write(l.length, 0); for (short e : l) @@ -216,7 +221,6 @@ public void write(short[] l, int tag) { } public void write(int[] l, int tag) { - reserve(8); writeHead(TarsStructBase.LIST, tag); write(l.length, 0); for (int e : l) @@ -224,7 +228,6 @@ public void write(int[] l, int tag) { } public void write(long[] l, int tag) { - reserve(8); writeHead(TarsStructBase.LIST, tag); write(l.length, 0); for (long e : l) @@ -232,7 +235,6 @@ public void write(long[] l, int tag) { } public void write(float[] l, int tag) { - reserve(8); writeHead(TarsStructBase.LIST, tag); write(l.length, 0); for (float e : l) @@ -240,7 +242,6 @@ public void write(float[] l, int tag) { } public void write(double[] l, int tag) { - reserve(8); writeHead(TarsStructBase.LIST, tag); write(l.length, 0); for (double e : l) @@ -252,7 +253,6 @@ public void write(T[] l, int tag) { } private void writeArray(Object[] l, int tag) { - reserve(8); writeHead(TarsStructBase.LIST, tag); write(l.length, 0); for (Object e : l) @@ -260,7 +260,6 @@ private void writeArray(Object[] l, int tag) { } public void write(Collection l, int tag) { - reserve(8); writeHead(TarsStructBase.LIST, tag); write(l == null ? 0 : l.size(), 0); if (l != null) { @@ -270,10 +269,9 @@ public void write(Collection l, int tag) { } public void write(TarsStructBase o, int tag) { - reserve(2); writeHead(TarsStructBase.STRUCT_BEGIN, tag); o.writeTo(this); - reserve(2); + //o.writeTo(new com.qq.tars.protocol.tars.TarsOutputStream()); writeHead(TarsStructBase.STRUCT_END, 0); } @@ -351,19 +349,5 @@ public void write(Object o, int tag) { } } - protected String sServerEncoding = "UTF-8"; - - public int setServerEncoding(String se) { - sServerEncoding = se; - return 0; - } - public static void main(String[] args) { - TarsOutputStream os = new TarsOutputStream(); - long n = 0x1234567890012345L; - os.write(n, 0); - ByteBuffer bs = os.getByteBuffer(); - System.out.println(HexUtil.bytes2HexStr(bs.array())); - System.out.println(Arrays.toString(os.toByteArray())); - } } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/TarsOutputStreamExt.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsOutputStreamExt.java similarity index 89% rename from core/src/main/java/com/qq/tars/protocol/tars/TarsOutputStreamExt.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsOutputStreamExt.java index 6c9249e6..310dc6b2 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/TarsOutputStreamExt.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsOutputStreamExt.java @@ -16,8 +16,6 @@ package com.qq.tars.protocol.tars; -import java.util.List; - import com.qq.tars.common.util.BeanAccessor; import com.qq.tars.common.util.CommonUtils; import com.qq.tars.protocol.tars.exc.TarsEncodeException; @@ -25,6 +23,8 @@ import com.qq.tars.protocol.tars.support.TarsStrutPropertyInfo; import com.qq.tars.protocol.util.TarsHelper; +import java.util.List; + public class TarsOutputStreamExt { public static void write(Object e, int tag, TarsOutputStream jos) { @@ -32,12 +32,10 @@ public static void write(Object e, int tag, TarsOutputStream jos) { if (info == null) { throw new TarsEncodeException("the JavaBean[" + e.getClass().getSimpleName() + "] no annotation Struct"); } - - jos.reserve(2); jos.writeHead(TarsStructBase.STRUCT_BEGIN, tag); - List propertysList = info.getPropertyList(); - if (!CommonUtils.isEmptyCollection(propertysList)) { - for (TarsStrutPropertyInfo propertyInfo : propertysList) { + List propertyList = info.getPropertyList(); + if (!CommonUtils.isEmptyCollection(propertyList)) { + for (TarsStrutPropertyInfo propertyInfo : propertyList) { Object value = null; try { value = BeanAccessor.getBeanValue(e, propertyInfo.getName()); @@ -54,8 +52,6 @@ public static void write(Object e, int tag, TarsOutputStream jos) { } } } - - jos.reserve(2); jos.writeHead(TarsStructBase.STRUCT_END, 0); } } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/TarsStructBase.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsStructBase.java similarity index 96% rename from core/src/main/java/com/qq/tars/protocol/tars/TarsStructBase.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsStructBase.java index 4578eb01..652c9135 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/TarsStructBase.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/TarsStructBase.java @@ -16,6 +16,8 @@ package com.qq.tars.protocol.tars; +import java.nio.charset.Charset; + @SuppressWarnings("serial") public abstract class TarsStructBase implements java.io.Serializable { @@ -50,7 +52,7 @@ public TarsStructBase newInit() { return null; } - public void recyle() { + public void recycle() { } @@ -71,7 +73,7 @@ public byte[] toByteArray() { return os.toByteArray(); } - public byte[] toByteArray(String encoding) { + public byte[] toByteArray(Charset encoding) { TarsOutputStream os = new TarsOutputStream(); os.setServerEncoding(encoding); writeTo(os); diff --git a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsCallback.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsCallback.java similarity index 79% rename from core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsCallback.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsCallback.java index b0268be8..b8a51848 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsCallback.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsCallback.java @@ -16,16 +16,12 @@ package com.qq.tars.protocol.tars.annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; @Inherited @Target({ ElementType.PARAMETER, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface TarsCallback { - public String comment() default ""; + String comment() default ""; } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsContext.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsContext.java similarity index 96% rename from core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsContext.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsContext.java index 33ac4f95..70673cec 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsContext.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsContext.java @@ -25,5 +25,5 @@ @Retention(RetentionPolicy.RUNTIME) public @interface TarsContext { - public String comment() default ""; + String comment() default ""; } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsHolder.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsHolder.java similarity index 93% rename from core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsHolder.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsHolder.java index e0483588..6a4c5fba 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsHolder.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsHolder.java @@ -25,7 +25,7 @@ @Retention(RetentionPolicy.RUNTIME) public @interface TarsHolder { - public String name() default ""; + String name() default ""; - public String comment() default ""; + String comment() default ""; } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethod.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethod.java similarity index 96% rename from core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethod.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethod.java index a6d9e03d..c6678b4e 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethod.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethod.java @@ -25,5 +25,5 @@ @Retention(RetentionPolicy.RUNTIME) public @interface TarsMethod { - public String comment() default ""; + String comment() default ""; } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethodParameter.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethodParameter.java similarity index 96% rename from core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethodParameter.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethodParameter.java index ee9490ce..f1d1b094 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethodParameter.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsMethodParameter.java @@ -25,5 +25,5 @@ @Retention(RetentionPolicy.RUNTIME) public @interface TarsMethodParameter { - public String name() default ""; + String name() default ""; } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsRouteKey.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsRouteKey.java similarity index 89% rename from core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsRouteKey.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsRouteKey.java index 7b660fda..1c8781a1 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsRouteKey.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsRouteKey.java @@ -9,5 +9,5 @@ @Retention(RetentionPolicy.RUNTIME) public @interface TarsRouteKey { - public String comment() default ""; + String comment() default ""; } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStruct.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStruct.java similarity index 96% rename from core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStruct.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStruct.java index 4240a659..df7ece7e 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStruct.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStruct.java @@ -25,5 +25,5 @@ @Retention(RetentionPolicy.RUNTIME) public @interface TarsStruct { - public String comment() default ""; + String comment() default ""; } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStructProperty.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStructProperty.java similarity index 90% rename from core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStructProperty.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStructProperty.java index 727c8c44..cae3f621 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStructProperty.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/annotation/TarsStructProperty.java @@ -25,9 +25,9 @@ @Retention(RetentionPolicy.RUNTIME) public @interface TarsStructProperty { - public int order(); + int order(); - public boolean isRequire() default false; + boolean isRequire() default false; - public String comment() default ""; + String comment() default ""; } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/exc/TarsDecodeException.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/exc/TarsDecodeException.java similarity index 92% rename from core/src/main/java/com/qq/tars/protocol/tars/exc/TarsDecodeException.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/exc/TarsDecodeException.java index ab8d4eff..918e28e2 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/exc/TarsDecodeException.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/exc/TarsDecodeException.java @@ -19,6 +19,9 @@ @SuppressWarnings("serial") public class TarsDecodeException extends RuntimeException { + + private static final long serialVersionUID = 6149236324136577031L; + public TarsDecodeException(String string) { super(string); } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/exc/TarsEncodeException.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/exc/TarsEncodeException.java similarity index 92% rename from core/src/main/java/com/qq/tars/protocol/tars/exc/TarsEncodeException.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/exc/TarsEncodeException.java index 54351537..9ce2a934 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/exc/TarsEncodeException.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/exc/TarsEncodeException.java @@ -19,6 +19,8 @@ @SuppressWarnings("serial") public class TarsEncodeException extends RuntimeException { + private static final long serialVersionUID = -8604058763674947433L; + public TarsEncodeException(String string) { super(string); } diff --git a/core/src/main/java/com/qq/tars/protocol/tars/support/TarsMethodInfo.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/support/TarsMethodInfo.java similarity index 100% rename from core/src/main/java/com/qq/tars/protocol/tars/support/TarsMethodInfo.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/support/TarsMethodInfo.java diff --git a/core/src/main/java/com/qq/tars/protocol/tars/support/TarsMethodParameterInfo.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/support/TarsMethodParameterInfo.java similarity index 89% rename from core/src/main/java/com/qq/tars/protocol/tars/support/TarsMethodParameterInfo.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/support/TarsMethodParameterInfo.java index 01e6eb74..73f27635 100644 --- a/core/src/main/java/com/qq/tars/protocol/tars/support/TarsMethodParameterInfo.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/support/TarsMethodParameterInfo.java @@ -26,6 +26,15 @@ public class TarsMethodParameterInfo { private Object stamp; private Type type; private Annotation[] annotations; + private Type innerType = null; + + public Type getInnerType() { + return innerType; + } + + public void setInnerType(Type innerType) { + this.innerType = innerType; + } public String getName() { return name; diff --git a/core/src/main/java/com/qq/tars/protocol/tars/support/TarsStructInfo.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/support/TarsStructInfo.java similarity index 100% rename from core/src/main/java/com/qq/tars/protocol/tars/support/TarsStructInfo.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/support/TarsStructInfo.java diff --git a/core/src/main/java/com/qq/tars/protocol/tars/support/TarsStrutPropertyInfo.java b/tars-common-api/src/main/java/com/qq/tars/protocol/tars/support/TarsStrutPropertyInfo.java similarity index 100% rename from core/src/main/java/com/qq/tars/protocol/tars/support/TarsStrutPropertyInfo.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/tars/support/TarsStrutPropertyInfo.java diff --git a/core/src/main/java/com/qq/tars/protocol/util/TarsDisplayer.java b/tars-common-api/src/main/java/com/qq/tars/protocol/util/TarsDisplayer.java similarity index 99% rename from core/src/main/java/com/qq/tars/protocol/util/TarsDisplayer.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/util/TarsDisplayer.java index 3bfcf85f..e9031a82 100644 --- a/core/src/main/java/com/qq/tars/protocol/util/TarsDisplayer.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/util/TarsDisplayer.java @@ -16,14 +16,14 @@ package com.qq.tars.protocol.util; -import java.util.Collection; -import java.util.List; -import java.util.Map; - import com.qq.tars.common.util.HexUtil; import com.qq.tars.protocol.tars.TarsStructBase; import com.qq.tars.protocol.tars.exc.TarsEncodeException; +import java.util.Collection; +import java.util.List; +import java.util.Map; + public final class TarsDisplayer { private StringBuilder sb; @@ -615,7 +615,7 @@ public TarsDisplayer display(T o, String fieldName) { } else if (o.getClass().isArray()) { display((Object[]) o, fieldName); } else { - throw new TarsEncodeException("write object error: unsupport type."); + throw new TarsEncodeException("write object error: unsupported type."); } return this; } @@ -663,7 +663,7 @@ public TarsDisplayer displaySimple(T o, boolean bSep) { } else if (o.getClass().isArray()) { displaySimple((Object[]) o, bSep); } else { - throw new TarsEncodeException("write object error: unsupport type."); + throw new TarsEncodeException("write object error: unsupported type."); } return this; } diff --git a/core/src/main/java/com/qq/tars/protocol/util/TarsHelper.java b/tars-common-api/src/main/java/com/qq/tars/protocol/util/TarsHelper.java similarity index 69% rename from core/src/main/java/com/qq/tars/protocol/util/TarsHelper.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/util/TarsHelper.java index 1d6aa6c5..090948e7 100644 --- a/core/src/main/java/com/qq/tars/protocol/util/TarsHelper.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/util/TarsHelper.java @@ -16,24 +16,11 @@ package com.qq.tars.protocol.util; -import java.lang.annotation.Annotation; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.common.collect.ImmutableMap; import com.qq.tars.common.support.Holder; import com.qq.tars.common.util.BeanAccessor; import com.qq.tars.common.util.CommonUtils; +import com.qq.tars.common.util.Constants; import com.qq.tars.protocol.annotation.Servant; import com.qq.tars.protocol.tars.annotation.TarsCallback; import com.qq.tars.protocol.tars.annotation.TarsContext; @@ -48,43 +35,58 @@ import com.qq.tars.protocol.tars.support.TarsStructInfo; import com.qq.tars.protocol.tars.support.TarsStrutPropertyInfo; +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + public class TarsHelper { public final static int PACKAGE_MAX_LENGTH = 10 * 1024 * 1024; public final static int HEAD_SIZE = 4; + //////////////////////////////////////////////////////////////// + // 定义协议的版本号 public static final short VERSION = 0x01; - public static final short VERSION2 = 0x02; - public static final short VERSION3 = 0x03; + public static final short VERSIONJSON = 0x05; + //////////////////////////////////////////////////////////////// + // 定义消息的类型 public static final byte NORMAL = 0x00; - public static final byte ONEWAY = 0x01; + //////////////////////////////////////////////////////////////// + // TARS定义的返回码 public final static int SERVERSUCCESS = 0; - public final static int SERVERDECODEERR = -1; - public final static int SERVERENCODEERR = -2; - public final static int SERVERNOFUNCERR = -3; - public final static int SERVERNOSERVANTERR = -4; - public final static int SERVERRESETGRID = -5; - public final static int SERVERQUEUETIMEOUT = -6; - public final static int ASYNCCALLTIMEOUT = -7; - + public final static int INVOKETIMEOUT = -7; public final static int PROXYCONNECTERR = -8; - public static final int SERVEROVERLOAD = -9; + public static final int ADAPTERNULL = -10; + public final static int SERVERUNCATCHEDERR = -98; public final static int SERVERUNKNOWNERR = -99; + ///////////////////////////////////////////////////////////////// + // 定义按位的消息状态类型,可复合 public static final int MESSAGETYPENULL = 0x00; public static final int MESSAGETYPEHASH = 0x01; public static final int MESSAGETYPEGRID = 0x02; @@ -93,17 +95,18 @@ public class TarsHelper { public static final int MESSAGETYPEASYNC = 0x10; public static final int MESSAGETYPELOADED = 0x20; - public static final String STATUS_RESULT_CODE = "STATUS_RESULT_CODE"; + ///////////////////////////////////////////////////////////////// + public static final String STATUS_RESULT_CODE = "STATUS_RESULT_CODE"; public static final String STATUS_RESULT_DESC = "STATUS_RESULT_DESC"; public static final Boolean STAMP_BOOLEAN = Boolean.TRUE; - public static final Byte STAMP_BYTE = Byte.valueOf((byte) 0); - public static final Short STAMP_SHORT = Short.valueOf((short) 0); - public static final Float STAMP_FLOAT = Float.valueOf(0); - public static final Integer STAMP_INT = Integer.valueOf(0); - public static final Long STAMP_LONG = Long.valueOf(0); - public static final Double STAMP_DOUBLE = Double.valueOf(0); + public static final Byte STAMP_BYTE = (byte) 0; + public static final Short STAMP_SHORT = (short) 0; + public static final Float STAMP_FLOAT = (float) 0; + public static final Integer STAMP_INT = 0; + public static final Long STAMP_LONG = 0L; + public static final Double STAMP_DOUBLE = (double) 0; public static final String STAMP_STRING = ""; public static final boolean[] STAMP_BOOLEAN_ARRAY = new boolean[] { true }; @@ -113,25 +116,18 @@ public class TarsHelper { public static final long[] STAMP_LONG_ARRAY = new long[] { 0 }; public static final float[] STAMP_FLOAT_ARRAY = new float[] { 0 }; public static final double[] STAMP_DOUBLE_ARRAY = new double[] { 0 }; - public static final Map STAMP_MAP = new HashMap(); - - static { - STAMP_MAP.put("", ""); - } + public static final Map STAMP_MAP = ImmutableMap.of("", ""); private static Map, TarsStructInfo> tarsStructCache = new HashMap, TarsStructInfo>(); - private static Comparator tarsStructFieldsListComparator = new Comparator() { - - @Override - public int compare(Field one, Field other) { - TarsStructProperty oneProperty = one.getAnnotation(TarsStructProperty.class); - TarsStructProperty otherProperty = other.getAnnotation(TarsStructProperty.class); - if (oneProperty.order() == otherProperty.order()) { - throw new RuntimeException("Field[" + one.getName() + "] , Field[" + other.getName() + "] order is:" + oneProperty.order()); - } - return oneProperty.order() - otherProperty.order(); + private static Comparator tarsStructFieldsListComparator = (one, other) -> { + TarsStructProperty oneProperty = one.getAnnotation(TarsStructProperty.class); + TarsStructProperty otherProperty = other.getAnnotation(TarsStructProperty.class); + if (oneProperty.order() == otherProperty.order()) { + throw new RuntimeException( + "Field[" + one.getName() + "] , Field[" + other.getName() + "] order is:" + oneProperty.order()); } + return oneProperty.order() - otherProperty.order(); }; private static Map, Object> stampCache = new HashMap, Object>(); @@ -205,7 +201,8 @@ public static Object getParameterStamp(Type type) { return getJavaBaseOrArrayOrJavaBeanStamp((Class) type); } else { return clazz; -// throw new RuntimeException("the class: " + clazz + " not a exact class, please check it."); + // throw new RuntimeException("the class: " + clazz + " not a exact class, + // please check it."); } } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; @@ -234,7 +231,8 @@ public static Object getParameterStamp(Type type) { if (Holder.class == clazz) { return getParameterStamp(types[0]); } else { - throw new RuntimeException("getStamp for Holder Not Implement Yet, parameterizedType=" + parameterizedType); + throw new RuntimeException( + "getStamp for Holder Not Implement Yet, parameterizedType=" + parameterizedType); } } } else if (type instanceof GenericArrayType) { @@ -248,6 +246,56 @@ public static Object getParameterStamp(Type type) { throw new RuntimeException("Generic Type: " + type + " no permission, please check it."); } + public static Object getNewParameterStamp(Type type) { + if (type instanceof Class) { + Class clazz = (Class) type; + if (CommonUtils.isJavaBase(clazz) || clazz.isArray() || isStruct(clazz)) { + return getNewJavaBaseOrArrayOrJavaBeanStamp((Class) type); + } else { + return clazz; + } + } else if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) type; + Class clazz = (Class) parameterizedType.getRawType(); + if (isStruct(clazz)) { + return getNewJavaBaseOrArrayOrJavaBeanStamp((Class) type); + } else if (isMap(clazz)) { + Type[] types = parameterizedType.getActualTypeArguments(); + Type keyType = types[0]; + Type valueType = types[1]; + + Object key = getNewParameterStamp(keyType); + Object value = getNewParameterStamp(valueType); + Map map = new HashMap(1); + map.put(key, value); + return map; + } else if (isCollection(clazz)) { + Type[] types = parameterizedType.getActualTypeArguments(); + Type valueType = types[0]; + Object e = getNewParameterStamp(valueType); + List list = new ArrayList(1); + list.add(e); + return list; + } else if (isHolder(clazz)) { + Type[] types = parameterizedType.getActualTypeArguments(); + if (Holder.class == clazz) { + return getNewParameterStamp(types[0]); + } else { + throw new RuntimeException( + "getStamp for Holder Not Implement Yet, parameterizedType=" + parameterizedType); + } + } + } else if (type instanceof GenericArrayType) { + GenericArrayType genericArrayType = (GenericArrayType) type; + Type componentType = genericArrayType.getGenericComponentType(); + Object component = getNewParameterStamp(componentType); + Object[] array = (Object[]) Array.newInstance(component.getClass(), 1); + array[0] = component; + return array; + } + throw new RuntimeException("Generic Type: " + type + " no permission, please check it."); + } + public static TarsMethodParameterInfo createParameterInfo(Type genericParameterType) { if (genericParameterType == null) { throw new NullPointerException("genericParameterType is null."); @@ -259,6 +307,54 @@ public static TarsMethodParameterInfo createParameterInfo(Type genericParameterT return parameterInfo; } + public static Object getNewJavaBaseOrArrayOrJavaBeanStamp(Class clazz) { + if (clazz == boolean.class || clazz == Boolean.class) { + return new Boolean(true); + } else if (clazz == byte.class || clazz == Byte.class) { + return Byte.valueOf((byte) 0); + } else if (clazz == short.class || clazz == Short.class) { + return Short.valueOf((short) 0); + } else if (clazz == int.class || clazz == Integer.class) { + return Integer.valueOf(0); + } else if (clazz == long.class || clazz == Long.class) { + return Long.valueOf(0); + } else if (clazz == float.class || clazz == Float.class) { + return Float.valueOf(0); + } else if (clazz == double.class || clazz == Double.class) { + return Double.valueOf(0); + } else if (clazz == String.class) { + return new String(""); + } else if (clazz == boolean[].class) { + return new boolean[] { true }; + } else if (clazz == byte[].class) { + return new byte[] { 0 }; + } else if (clazz == short[].class) { + return new short[] { 0 }; + } else if (clazz == int[].class) { + return new int[] { 0 }; + } else if (clazz == long[].class) { + return new long[] { 0 }; + } else if (clazz == float[].class) { + return new float[] { 0 }; + } else if (clazz == double[].class) { + return new double[] { 0 }; + } + + Object stamp = null; + if (stamp == null) { + if (clazz.isArray()) { + Class componentType = clazz.getComponentType(); + Object[] array = (Object[]) Array.newInstance(componentType, 1); + Object e = getNewJavaBaseOrArrayOrJavaBeanStamp(componentType); + array[0] = e; + stamp = array; + } else { + stamp = CommonUtils.newInstance(clazz); + } + } + return stamp; + } + public static TarsStructInfo getStructInfo(Class clazz) { TarsStructInfo tarsStructInfo = tarsStructCache.get(clazz); if (tarsStructInfo == null) { @@ -271,16 +367,20 @@ public static TarsStructInfo getStructInfo(Class clazz) { List fieldList = new ArrayList(fields.length); for (Field field : fields) { - if (field.isAnnotationPresent(TarsStructProperty.class)) fieldList.add(field); + if (field.isAnnotationPresent(TarsStructProperty.class)) + fieldList.add(field); } try { - Collections.sort(fieldList, tarsStructFieldsListComparator); + fieldList.sort(tarsStructFieldsListComparator); } catch (Exception e) { - throw new RuntimeException("class[" + clazz + "] , Annotation StructProperty order error: " + e.getMessage(), e); + throw new RuntimeException( + "class[" + clazz + "] , Annotation StructProperty order error: " + e.getMessage(), + e); } - List propertyList = new ArrayList(fieldList.size()); + List propertyList = new ArrayList( + fieldList.size()); int order = 0; Object bean = CommonUtils.newInstance(clazz); for (Field field : fieldList) { @@ -290,7 +390,8 @@ public static TarsStructInfo getStructInfo(Class clazz) { try { stamp = getParameterStamp(type); } catch (Exception e) { - throw new RuntimeException("class[" + clazz + "] , Field[" + field.getName() + "] create stamp failed:" + e.getMessage(), e); + throw new RuntimeException("class[" + clazz + "] , Field[" + field.getName() + + "] create stamp failed:" + e.getMessage(), e); } propertyInfo.setStamp(stamp); propertyInfo.setName(field.getName()); @@ -301,7 +402,8 @@ public static TarsStructInfo getStructInfo(Class clazz) { propertyInfo.setRequire(propertyAnnotation.isRequire()); propertyInfo.setComment(propertyAnnotation.comment()); - propertyInfo.setDefaultValue(getPropertyDefaultValue(BeanAccessor.getBeanValue(bean, field.getName()))); + propertyInfo.setDefaultValue( + getPropertyDefaultValue(BeanAccessor.getBeanValue(bean, field.getName()))); propertyList.add(propertyInfo); } @@ -352,7 +454,8 @@ public static TarsMethodInfo getMethodInfo(Class api, Method method, String o if (tarsMethod != null && !CommonUtils.isEmpty(tarsMethod.comment())) { methodInfo.setComment(tarsMethod.comment()); } - List parametersList = new ArrayList(genericParameterTypes.length); + List parametersList = new ArrayList( + genericParameterTypes.length); methodInfo.setParametersList(parametersList); int order = 0; Annotation[][] allParameterAnnotations = method.getParameterAnnotations(); @@ -364,35 +467,55 @@ public static TarsMethodInfo getMethodInfo(Class api, Method method, String o TarsMethodParameterInfo parameterInfo = new TarsMethodParameterInfo(); parametersList.add(parameterInfo); try { + parameterInfo.setType(genericParameterType); parameterInfo.setName(name); parameterInfo.setOrder(isAsync(method.getName()) ? order : order + 1); parameterInfo.setAnnotations(allParameterAnnotations[order]); if (!isCallback(allParameterAnnotations[order])) { parameterInfo.setStamp(TarsHelper.getParameterStamp(genericParameterType)); } - + if (isRoutekey(allParameterAnnotations[order])) { - methodInfo.setRouteKeyIndex(order); + methodInfo.setRouteKeyIndex(order); } } catch (Exception e) { throw new RuntimeException("failed to create parameter info:" + method + ", index=[" + order + "]", e); } order++; } - Type returnType = method.getGenericReturnType(); - if (returnType != void.class) { + Type returnOriginType = method.getReturnType(); + + if (returnOriginType == CompletableFuture.class) { + ParameterizedType parameterizedType = (ParameterizedType) method.getGenericReturnType(); + TarsMethodParameterInfo returnInfo = new TarsMethodParameterInfo(); + returnInfo.setStamp(TarsHelper.getParameterStamp(parameterizedType.getActualTypeArguments()[0]));// CompletableFuture + // use + // gengeric + // inner + // type + // class + returnInfo.setName("result"); + returnInfo.setOrder(0); + returnInfo.setType(returnType); + methodInfo.setReturnInfo(returnInfo); + } else if (returnType != void.class) { TarsMethodParameterInfo returnInfo = new TarsMethodParameterInfo(); returnInfo.setStamp(TarsHelper.getParameterStamp(returnType)); returnInfo.setName("result"); returnInfo.setOrder(0); + returnInfo.setType(returnType); methodInfo.setReturnInfo(returnInfo); } return methodInfo; } public static boolean isAsync(String methodName) { - return methodName != null && methodName.startsWith("async_"); + return methodName != null && methodName.startsWith(Constants.TARS_METHOD_ASYNC_START_WITH); + } + + public static boolean isPromiseFuture(String methodName) { + return methodName != null && methodName.startsWith(Constants.TARS_METHOD_PROMISE_START_WITH); } public static boolean isPing(String methodName) { @@ -456,24 +579,24 @@ public static boolean isContext(Annotation[] annotations) { } return false; } - + public static boolean isRoutekey(Annotation[] annotations) { - if (annotations == null || annotations.length < 0) { - return false; - } - for (Annotation annotation : annotations) { - if (annotation.annotationType() ==TarsRouteKey.class) { - return true; - } - } - return false; + if (annotations == null || annotations.length < 0) { + return false; + } + for (Annotation annotation : annotations) { + if (annotation.annotationType() == TarsRouteKey.class) { + return true; + } + } + return false; } public static boolean isStruct(Class clazz) { boolean isStruct = clazz.isAnnotationPresent(TarsStruct.class); - if (isStruct) { - getStructInfo(clazz); - } + // if (isStruct) { + // getStructInfo(clazz); + // } return isStruct; } @@ -562,7 +685,7 @@ public static Object getPropertyDefaultValue(Object value) { return value; } else if (value instanceof Byte && ((Byte) value).intValue() != 0) { return value; - } else if (value instanceof Boolean && ((Boolean) value).booleanValue() != false) { + } else if (value instanceof Boolean && ((Boolean) value).booleanValue()) { return value; } else if (value instanceof String) { return value; @@ -577,4 +700,5 @@ public static void setHolderValue(Object holder, Object value) throws Exception public static Object getHolderValue(Object holder) throws Exception { return BeanAccessor.getBeanValue(holder, "value"); } + } diff --git a/core/src/main/java/com/qq/tars/protocol/util/TarsUtil.java b/tars-common-api/src/main/java/com/qq/tars/protocol/util/TarsUtil.java similarity index 93% rename from core/src/main/java/com/qq/tars/protocol/util/TarsUtil.java rename to tars-common-api/src/main/java/com/qq/tars/protocol/util/TarsUtil.java index 993a6769..face79c2 100644 --- a/core/src/main/java/com/qq/tars/protocol/util/TarsUtil.java +++ b/tars-common-api/src/main/java/com/qq/tars/protocol/util/TarsUtil.java @@ -16,11 +16,13 @@ package com.qq.tars.protocol.util; +import com.qq.tars.protocol.tars.TarsStructBase; +import io.netty.buffer.ByteBuf; + import java.nio.ByteBuffer; import java.util.Iterator; import java.util.List; - -import com.qq.tars.protocol.tars.TarsStructBase; +import java.util.Objects; public final class TarsUtil { @@ -61,39 +63,39 @@ public static boolean equals(double l, double r) { } public static boolean equals(Object l, Object r) { - return (l == null && r == null) || (l != null && l.equals(r)); + return Objects.equals(l, r); } public static int compareTo(boolean l, boolean r) { - return (l ? 1 : 0) - (r ? 1 : 0); + return l == r ? 0 : l ? 1 : -1; } public static int compareTo(byte l, byte r) { - return l < r ? -1 : (l > r ? 1 : 0); + return Byte.compare(l, r); } public static int compareTo(char l, char r) { - return l < r ? -1 : (l > r ? 1 : 0); + return Character.compare(l, r); } public static int compareTo(short l, short r) { - return l < r ? -1 : (l > r ? 1 : 0); + return Short.compare(l, r); } public static int compareTo(int l, int r) { - return l < r ? -1 : (l > r ? 1 : 0); + return Integer.compare(l, r); } public static int compareTo(long l, long r) { - return l < r ? -1 : (l > r ? 1 : 0); + return Long.compare(l, r); } public static int compareTo(float l, float r) { - return l < r ? -1 : (l > r ? 1 : 0); + return Float.compare(l, r); } public static int compareTo(double l, double r) { - return l < r ? -1 : (l > r ? 1 : 0); + return Double.compare(l, r); } public static > int compareTo(T l, T r) { @@ -102,7 +104,7 @@ public static > int compareTo(T l, T r) { public static > int compareTo(List l, List r) { Iterator li = l.iterator(), ri = r.iterator(); - for (; li.hasNext() && ri.hasNext();) { + for (; li.hasNext() && ri.hasNext(); ) { int n = li.next().compareTo(ri.next()); if (n != 0) return n; } @@ -355,9 +357,9 @@ public static int hashCode(Object object) { } } - public static byte[] getBufArray(ByteBuffer buffer) { - byte[] bytes = new byte[buffer.position()]; - System.arraycopy(buffer.array(), 0, bytes, 0, bytes.length); + public static byte[] getBufArray(ByteBuf buffer) { + final byte[] bytes = new byte[buffer.readableBytes()]; + buffer.readBytes(bytes, 0, buffer.readableBytes()); return bytes; } @@ -366,7 +368,7 @@ public static byte[] getBufArray(ByteBuffer buffer) { private static final byte[] lowDigits; static { - final byte[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + final byte[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; int i; byte[] high = new byte[256]; diff --git a/core/src/main/java/com/qq/tars/rpc/common/Url.java b/tars-common-api/src/main/java/com/qq/tars/rpc/common/Url.java similarity index 83% rename from core/src/main/java/com/qq/tars/rpc/common/Url.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/common/Url.java index b10e3da2..bc92ac69 100644 --- a/core/src/main/java/com/qq/tars/rpc/common/Url.java +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/common/Url.java @@ -20,6 +20,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Objects; @SuppressWarnings("serial") public final class Url implements Comparable, Serializable { @@ -145,33 +146,33 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; Url other = (Url) obj; - if (host == null) { - if (other.host != null) return false; - } else if (!host.equals(other.host)) return false; - if (parameters == null) { - if (other.parameters != null) return false; - } else if (!parameters.equals(other.parameters)) return false; - if (path == null) { - if (other.path != null) return false; - } else if (!path.equals(other.path)) return false; - if (port != other.port) return false; - if (protocol == null) { - if (other.protocol != null) return false; - } else if (!protocol.equals(other.protocol)) return false; - return true; + if (!Objects.equals(this.host, other.host)) { + return false; + } + if (!Objects.equals(this.parameters, other.parameters)) { + return false; + } + if (!Objects.equals(this.path, other.path)) { + return false; + } + if (!Objects.equals(this.port, other.port)) { + return false; + } + return Objects.equals(this.protocol, other.protocol); } @Override public int compareTo(Url url) { int i = this.host.compareTo(url.host); if (i == 0) { - int thisVal = this.port; - int anotherVal = url.port; - i = (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1)); + i = Integer.compare(this.port, url.port); } return i; } diff --git a/core/src/main/java/com/qq/tars/rpc/exc/ClientException.java b/tars-common-api/src/main/java/com/qq/tars/rpc/exc/ClientException.java similarity index 95% rename from core/src/main/java/com/qq/tars/rpc/exc/ClientException.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/exc/ClientException.java index 919a0f67..c7d91481 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/ClientException.java +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/exc/ClientException.java @@ -20,6 +20,8 @@ @SuppressWarnings("serial") public class ClientException extends TarsException { + + private static final long serialVersionUID = -2448067965000958261L; private String objectName; public ClientException(String message) { diff --git a/core/src/main/java/com/qq/tars/rpc/exc/TarsException.java b/tars-common-api/src/main/java/com/qq/tars/rpc/exc/TarsException.java similarity index 93% rename from core/src/main/java/com/qq/tars/rpc/exc/TarsException.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/exc/TarsException.java index 6da2eb2c..0dd3fa25 100644 --- a/core/src/main/java/com/qq/tars/rpc/exc/TarsException.java +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/exc/TarsException.java @@ -19,6 +19,9 @@ @SuppressWarnings("serial") public class TarsException extends RuntimeException { + + private static final long serialVersionUID = 7630144928237498707L; + public TarsException() { super(); } diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/ServantProtocolFactory.java b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/Codec.java similarity index 52% rename from core/src/main/java/com/qq/tars/rpc/protocol/ServantProtocolFactory.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/protocol/Codec.java index 4e68d361..dd3bcb8a 100644 --- a/core/src/main/java/com/qq/tars/rpc/protocol/ServantProtocolFactory.java +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/Codec.java @@ -16,23 +16,40 @@ package com.qq.tars.rpc.protocol; -import com.qq.tars.net.protocol.ProtocolDecoder; -import com.qq.tars.net.protocol.ProtocolEncoder; -import com.qq.tars.net.protocol.ProtocolFactory; +import io.netty.buffer.ByteBuf; +import io.netty.channel.Channel; -public class ServantProtocolFactory implements ProtocolFactory { +import java.io.IOException; +import java.nio.charset.Charset; - private Codec codec = null; +public interface Codec { + /*** + * + * @param channel + * @param channelBuffer + * @param message + * @throws IOException + */ + void encode(Channel channel, ByteBuf channelBuffer, Object message) throws IOException; - public ServantProtocolFactory(Codec codec) { - this.codec = codec; - } + /*** + * + * @param channel + * @param buffer + * @return + * @throws IOException + */ + Object decode(Channel channel, ByteBuf buffer) throws IOException; - public ProtocolDecoder getDecoder() { - return this.codec; - } + /*** + * + * @return + */ + String getProtocol(); - public ProtocolEncoder getEncoder() { - return this.codec; - } + /*** + * + * @return + */ + Charset getCharset(); } diff --git a/net/src/main/java/com/qq/tars/net/core/Request.java b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/ServantRequest.java similarity index 63% rename from net/src/main/java/com/qq/tars/net/core/Request.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/protocol/ServantRequest.java index 9f5b2f6e..dff0a8ef 100644 --- a/net/src/main/java/com/qq/tars/net/core/Request.java +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/ServantRequest.java @@ -14,45 +14,48 @@ * specific language governing permissions and limitations under the License. */ -package com.qq.tars.net.core; +package com.qq.tars.rpc.protocol; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - -import com.qq.tars.net.client.ticket.Ticket; -import com.qq.tars.net.protocol.ProtocolException; -public abstract class Request { +import com.qq.tars.client.rpc.Request; - private int ticketNum = Ticket.DEFAULT_TICKET_NUMBER; - - private static final AtomicInteger ticketGenerator = new AtomicInteger(); +import java.util.HashMap; +import java.util.Map; - protected transient Session session = null; +public abstract class ServantRequest implements Request { + protected int requestId; + protected String servantName; + protected String functionName; - protected transient InvokeStatus status = null; + protected transient Request.InvokeStatus status = null; + private transient HashMap distributedContext = new HashMap<>(8); + private transient long bornTime; + private transient long processTime; - private transient HashMap distributedContext = new HashMap(8); + public ServantRequest(int requestid) { + this.requestId = requestid; + this.bornTime = System.currentTimeMillis(); + exportDistributedContext(distributedContext); - private transient long bornTime; + } - private transient long processTime; + public String getServantName() { + return servantName; + } - public static enum InvokeStatus { - SYNC_CALL, ASYNC_CALL, FUTURE_CALL + public void setServantName(String servantName) { + this.servantName = servantName; } - public Request(Session session) { - this.bornTime = System.currentTimeMillis(); - this.session = session; - this.ticketNum = ticketGenerator.incrementAndGet(); - exportDistributedContext(distributedContext); + public String getFunctionName() { + return functionName; } - public void init() throws ProtocolException { + public void setFunctionName(String functionName) { + this.functionName = functionName; } + private void exportDistributedContext(Map map) { } @@ -65,23 +68,20 @@ public void setDistributedContext(HashMap map) { else this.distributedContext.clear(); } - public Session getIoSession() { - return this.session; - } - public int getTicketNumber() { - return ticketNum; + public int getRequestId() { + return requestId; } - public void setTicketNumber(int ticketNum) { - this.ticketNum = ticketNum; + public void setRequestId(int requestId) { + this.requestId = requestId; } - public void setInvokeStatus(InvokeStatus status) { + public void setInvokeStatus(Request.InvokeStatus status) { this.status = status; } - public InvokeStatus getInvokeStatus() { + public Request.InvokeStatus getInvokeStatus() { return this.status; } @@ -100,4 +100,6 @@ public long getProcessTime() { public void setProcessTime(long processTime) { this.processTime = processTime; } + + } diff --git a/net/src/main/java/com/qq/tars/net/core/Response.java b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/ServantResponse.java similarity index 50% rename from net/src/main/java/com/qq/tars/net/core/Response.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/protocol/ServantResponse.java index 98359318..e80dcd3d 100644 --- a/net/src/main/java/com/qq/tars/net/core/Response.java +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/ServantResponse.java @@ -14,58 +14,39 @@ * specific language governing permissions and limitations under the License. */ -package com.qq.tars.net.core; +package com.qq.tars.rpc.protocol; -import java.io.IOException; -import com.qq.tars.net.client.ticket.Ticket; -import com.qq.tars.net.protocol.ProtocolException; - -public abstract class Response { - - private int ticketNum = Ticket.DEFAULT_TICKET_NUMBER; - - protected transient Session session = null; +import com.qq.tars.client.rpc.Response; +public abstract class ServantResponse implements Response { protected transient boolean asyncMode = false; + private volatile boolean committed = false; - private volatile boolean commited = false; - - public Response(Session session) { - this.session = session; - } - - public void init() throws ProtocolException { - } + private int requestId; - public Session getSession() { - return this.session; + public ServantResponse(int requestId) { + this.requestId = requestId; } public boolean isAsyncMode() { return asyncMode; } - public void asyncCallStart() throws IOException { + + public abstract int getRequestId(); + + public void asyncCallStart() { this.asyncMode = true; } - public void asyncCallEnd() throws IOException { + public void asyncCallEnd() { if (!this.asyncMode) throw new IllegalStateException("The response is not async mode."); ensureNotCommitted(); - session.write(this); - } - - public void setTicketNumber(int ticketNum) { - this.ticketNum = ticketNum; - } - - public int getTicketNumber() { - return this.ticketNum; } - private synchronized void ensureNotCommitted() { - if (commited) throw new IllegalStateException("Not allowed after response has committed."); - this.commited = true; + public synchronized void ensureNotCommitted() { + if (committed) throw new IllegalStateException("Not allowed after response has committed."); + this.committed = true; } } diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantRequest.java b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantRequest.java similarity index 74% rename from core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantRequest.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantRequest.java index 62c413b2..d2784129 100644 --- a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantRequest.java +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantRequest.java @@ -16,24 +16,26 @@ package com.qq.tars.rpc.protocol.tars; -import com.qq.tars.net.core.Session; +import com.qq.tars.common.util.HexUtil; import com.qq.tars.protocol.tars.TarsInputStream; import com.qq.tars.protocol.tars.support.TarsMethodInfo; import com.qq.tars.protocol.util.TarsHelper; import com.qq.tars.rpc.protocol.ServantRequest; +import java.util.Arrays; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; public class TarsServantRequest extends ServantRequest implements java.io.Serializable { - + private static final AtomicInteger INVOKE_REQUEST_ID = new AtomicInteger(0); private static final long serialVersionUID = 1L; - private short version; private byte packetType; private int messageType; private String servantName; private String functionName; - private int timeout; // iTimeout + private byte[] data; + private int timeout = 3000; // iTimeout private Map status; private Map context; @@ -47,18 +49,12 @@ public class TarsServantRequest extends ServantRequest implements java.io.Serial private int ret; - public TarsServantRequest(Session session) { - super(session); - } - - public TarsServantRequest(Session session, int ret) { - super(session); - this.ret = ret; + public TarsServantRequest(int requestId) { + super(requestId); } - public void init() { - ((TarsCodec) this.session.getProtocolFactory().getDecoder()).decodeRequestBody(this); -// TarsCodecHelper.decodeRequestBody(this); + public TarsServantRequest() { + super(INVOKE_REQUEST_ID.incrementAndGet()); } public TarsInputStream getInputStream() { @@ -109,12 +105,17 @@ public void setFunctionName(String functionName) { this.functionName = functionName; } - public int getRequestId() { - return getTicketNumber(); - } public void setRequestId(int requestId) { - this.setTicketNumber(requestId); + this.requestId = requestId; + } + + public byte[] getData() { + return data; + } + + public void setData(byte[] data) { + this.data = data; } public int getTimeout() { @@ -184,4 +185,25 @@ public Class getApi() { public void setApi(Class api) { this.api = api; } + + @Override + public String toString() { + return "TarsServantRequest{" + + "version=" + version + + ", packetType=" + packetType + + ", messageType=" + messageType + + ", servantName='" + servantName + '\'' + + ", functionName='" + functionName + '\'' + + ", data=" + HexUtil.bytes2HexStr(data) + + ", timeout=" + timeout + + ", status=" + status + + ", context=" + context + + ", api=" + api + + ", methodInfo=" + methodInfo + + ", methodParameters=" + Arrays.toString(methodParameters) + + ", inputStream=" + inputStream + + ", charsetName='" + charsetName + '\'' + + ", ret=" + ret + + '}'; + } } diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantResponse.java b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantResponse.java similarity index 75% rename from core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantResponse.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantResponse.java index af4a9207..62660a5f 100644 --- a/core/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantResponse.java +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tars/TarsServantResponse.java @@ -16,20 +16,15 @@ package com.qq.tars.rpc.protocol.tars; -import java.util.Map; - -import com.qq.tars.net.client.ticket.Ticket; -import com.qq.tars.net.client.ticket.TicketManager; -import com.qq.tars.net.core.Session; -import com.qq.tars.net.protocol.ProtocolException; +import com.qq.tars.client.rpc.Request; import com.qq.tars.protocol.tars.TarsInputStream; -import com.qq.tars.rpc.protocol.Codec; import com.qq.tars.rpc.protocol.ServantResponse; -public class TarsServantResponse extends ServantResponse implements java.io.Serializable { +import java.nio.charset.Charset; +import java.util.Map; +public class TarsServantResponse extends ServantResponse implements java.io.Serializable { private static final long serialVersionUID = 3163555867604946654L; - private short version; private byte packetType; private int messageType; @@ -43,30 +38,17 @@ public class TarsServantResponse extends ServantResponse implements java.io.Seri private Object result; - private String charsetName; + private Charset charsetName; private TarsInputStream inputStream; private TarsServantRequest request; private Throwable cause = null; - public TarsServantResponse(Session session) { - super(session); + public TarsServantResponse(int requestId) { + super(requestId); } - public void init() throws ProtocolException { - if (inputStream == null) { - return; - } - Ticket ticket = TicketManager.getTicket(getRequestId()); - if (ticket == null) { - return; - } - this.setRequest((TarsServantRequest) ticket.request()); - try { - ((TarsCodec) this.session.getProtocolFactory().getDecoder()).decodeResponseBody(this); -// TarsCodecHelper.decodeResponseBody(this); - } catch (Throwable e) { - this.setCause(e); - } + public TarsServantResponse() { + super(0); } public short getVersion() { @@ -94,12 +76,11 @@ public void setMessageType(int messageType) { } public int getRequestId() { - return getTicketNumber(); + return requestId; } public void setRequestId(int requestId) { this.requestId = requestId; - this.setTicketNumber(requestId); } public int getRet() { @@ -134,10 +115,12 @@ public void setInputStream(TarsInputStream inputStream) { this.inputStream = inputStream; } - public TarsServantRequest getRequest() { - return request; + @Override + public Request getRequest() { + return this.request; } + public void setRequest(TarsServantRequest request) { this.request = request; } @@ -150,11 +133,11 @@ public void setCause(Throwable cause) { this.cause = cause; } - public String getCharsetName() { + public Charset getCharsetName() { return charsetName; } - public void setCharsetName(String charsetName) { + public void setCharsetName(Charset charsetName) { this.charsetName = charsetName; } @@ -181,4 +164,6 @@ public Map getContext() { public void setContext(Map context) { this.context = context; } + + } diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tars/support/AnalystManager.java b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tars/support/AnalystManager.java similarity index 88% rename from core/src/main/java/com/qq/tars/rpc/protocol/tars/support/AnalystManager.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tars/support/AnalystManager.java index a7cebb32..fdee8385 100644 --- a/core/src/main/java/com/qq/tars/rpc/protocol/tars/support/AnalystManager.java +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tars/support/AnalystManager.java @@ -27,14 +27,15 @@ public final class AnalystManager { - private final static AnalystManager instance = new AnalystManager(); - private ConcurrentHashMap> cache = new ConcurrentHashMap>(); - private ConcurrentHashMap> context_cache = new ConcurrentHashMap>(); + private Map> cache = new ConcurrentHashMap<>(); + private Map> context_cache = new ConcurrentHashMap>(); public static AnalystManager getInstance() { return instance; } + private final static AnalystManager instance = new AnalystManager(); + public Map getMethodMap(Class api) { return cache.get(api.getName()); } diff --git a/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tup/BasicClassTypeUtil.java b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tup/BasicClassTypeUtil.java new file mode 100644 index 00000000..59245a98 --- /dev/null +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tup/BasicClassTypeUtil.java @@ -0,0 +1,330 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.qq.tars.rpc.protocol.tup; + +import java.lang.reflect.Array; +import java.lang.reflect.Constructor; +import java.util.*; + +public class BasicClassTypeUtil { + + private static void addType(ArrayList list, String type) { + int point = type.length(); + while (type.charAt(point - 1) == '>') { + point--; + if (point == 0) { + break; + } + } + list.add(0, uni2JavaType(type.substring(0, point))); + } + + public static ArrayList getTypeList(String fullType) { + ArrayList type = new ArrayList(); + int point = 0; + int splitPoint = fullType.indexOf("<"); + int mapPoint = -1; + while (point < splitPoint) { + addType(type, fullType.substring(point, splitPoint)); + point = splitPoint + 1; + splitPoint = fullType.indexOf("<", point); + mapPoint = fullType.indexOf(",", point); + if (splitPoint == -1) { + splitPoint = mapPoint; + } + if (mapPoint != -1 && mapPoint < splitPoint) { + splitPoint = mapPoint; + } + } + addType(type, fullType.substring(point, fullType.length())); + return type; + } + + public static void main(String[] args) { + ArrayList src = new ArrayList(); + src.add("char"); + src.add("list"); + src.add("list>"); + src.add("map"); + src.add("map>>"); + src.add("map>"); + src.add("map"); + + for (String ss : src) { + ArrayList list = getTypeList(ss); + for (String s : list) { + System.out.println(s); + } + Collections.reverse(list); + System.out.println("-------------finished " + transTypeList(list)); + } + } + + public static String transTypeList(ArrayList listType) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < listType.size(); i++) { + listType.set(i, java2UniType(listType.get(i))); + } + Collections.reverse(listType); + for (int i = 0; i < listType.size(); i++) { + String type = listType.get(i); + switch (type) { + case "list": + listType.set(i - 1, "<" + listType.get(i - 1)); + listType.set(0, listType.get(0) + ">"); + break; + case "map": + listType.set(i - 1, "<" + listType.get(i - 1) + ","); + listType.set(0, listType.get(0) + ">"); + break; + case "Array": + listType.set(i - 1, "<" + listType.get(i - 1)); + listType.set(0, listType.get(0) + ">"); + break; + } + } + Collections.reverse(listType); + for (String s : listType) { + sb.append(s); + } + return sb.toString(); + } + + public static Object createClassByUni(String className) throws ObjectCreateException { + ArrayList list = getTypeList(className); + Object last = null; + Object last2 = null; + Object returnObject = null; + for (String name : list) { + returnObject = createClassByName(name); + + if (returnObject instanceof String) { + if ("Array".equals((String) (returnObject))) { + if (last == null) { + returnObject = Array.newInstance(Byte.class, 0); + } + } else if ("?".equals((String) (returnObject))) { + + } else { + if (last == null) { + last = returnObject; + } else { + last2 = last; + last = returnObject; + } + } + } else if (returnObject instanceof List) { + if (null != last && last instanceof Byte) { + returnObject = Array.newInstance(Byte.class, 1); + Array.set(returnObject, 0, last); + } else { + if (last != null) { + ((List) returnObject).add(last); + } else { + + } + last = null; + } + } else if (returnObject instanceof Map) { + if (last != null & last2 != null) { + ((Map) returnObject).put(last, last2); + } else { + + } + last = null; + last2 = null; + } else { + if (last == null) { + last = returnObject; + } else { + last2 = last; + last = returnObject; + } + } + } + return returnObject; + } + + public static Object createClassByName(String name) throws ObjectCreateException { + switch (name) { + case "java.lang.Integer": + return 0; + case "java.lang.Boolean": + return false; + case "java.lang.Byte": + return (byte) 0; + case "java.lang.Double": + return (double) 0; + case "java.lang.Float": + return (float) 0; + case "java.lang.Long": + return (long) 0; + case "java.lang.Short": + return (short) 0; + case "java.lang.Character": + throw new java.lang.IllegalArgumentException("can not support java.lang.Character"); + case "java.lang.String": + return ""; + case "java.util.List": + return new ArrayList(); + case "java.util.Map": + return new HashMap(); + case "Array": + return "Array"; + case "?": + return name; + default: + Object result = null; + try { + Class newoneClass = Class.forName(name); + Constructor cons = newoneClass.getConstructor(); + result = cons.newInstance(); + } catch (Exception e) { + throw new ObjectCreateException(e); + } + return result; + } + } + + public static String java2UniType(String srcType) { + switch (srcType) { + case "java.lang.Integer": + case "int": + return "int32"; + case "java.lang.Boolean": + case "boolean": + return "bool"; + case "java.lang.Byte": + case "byte": + return "char"; + case "java.lang.Double": + case "double": + return "double"; + case "java.lang.Float": + case "float": + return "float"; + case "java.lang.Long": + case "long": + return "int64"; + case "java.lang.Short": + case "short": + return "short"; + case "java.lang.Character": + throw new java.lang.IllegalArgumentException("can not support java.lang.Character"); + case "java.lang.String": + return "string"; + case "java.util.List": + return "list"; + case "java.util.Map": + return "map"; + default: + return srcType; + } + } + + public static String uni2JavaType(String srcType) { + switch (srcType) { + case "int32": + return "java.lang.Integer"; + case "bool": + return "java.lang.Boolean"; + case "char": + return "java.lang.Byte"; + case "double": + return "java.lang.Double"; + case "float": + return "java.lang.Float"; + case "int64": + return "java.lang.Long"; + case "short": + return "java.lang.Short"; + case "string": + return "java.lang.String"; + case "list": + return "java.util.List"; + case "map": + return "java.util.Map"; + default: + return srcType; + } + } + + public static boolean isBasicType(String name) { + switch (name) { + case "int": + case "boolean": + case "byte": + case "double": + case "float": + case "long": + case "short": + case "char": + case "Integer": + case "Boolean": + case "Byte": + case "Double": + case "Float": + case "Long": + case "Short": + case "Char": + return true; + default: + return false; + } + } + + public static String getClassTransName(String name) { + switch (name) { + case "int": + return "Integer"; + case "boolean": + return "Boolean"; + case "byte": + return "Byte"; + case "double": + return "Double"; + case "float": + return "Float"; + case "long": + return "Long"; + case "short": + return "Short"; + case "char": + return "Character"; + default: + return name; + } + } + + public static String getVariableInit(String name, String type) { + switch (type) { + case "int": + case "double": + case "float": + case "long": + case "short": + return type + " " + name + "=0 ;\n"; + case "boolean": + return type + " " + name + "=false ;\n"; + case "byte": + case "char": + return type + " " + name + " ;\n"; + default: + return type + " " + name + " = null ;\n"; + } + } +} diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tup/ObjectCreateException.java b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tup/ObjectCreateException.java similarity index 100% rename from core/src/main/java/com/qq/tars/rpc/protocol/tup/ObjectCreateException.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tup/ObjectCreateException.java diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tup/OldUniAttribute.java b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tup/OldUniAttribute.java similarity index 86% rename from core/src/main/java/com/qq/tars/rpc/protocol/tup/OldUniAttribute.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tup/OldUniAttribute.java index ffd8f52a..c9288aec 100644 --- a/core/src/main/java/com/qq/tars/rpc/protocol/tup/OldUniAttribute.java +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tup/OldUniAttribute.java @@ -16,7 +16,14 @@ package com.qq.tars.rpc.protocol.tup; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.TarsStructBase; +import com.qq.tars.protocol.util.TarsUtil; + import java.lang.reflect.Array; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -26,27 +33,22 @@ import java.util.Map.Entry; import java.util.Set; -import com.qq.tars.protocol.tars.TarsInputStream; -import com.qq.tars.protocol.tars.TarsOutputStream; -import com.qq.tars.protocol.tars.TarsStructBase; -import com.qq.tars.protocol.util.TarsUtil; - class OldUniAttribute { - protected HashMap> _data = new HashMap>(); + protected Map> _data = new HashMap>(); - protected HashMap cachedClassName = new HashMap(); - private HashMap cachedData = new HashMap(); + protected Map cachedClassName = new HashMap(); + private Map cachedData = new HashMap(); - protected String encodeName = "UTF-8"; + protected Charset encodeName = StandardCharsets.UTF_8; TarsInputStream _is = new TarsInputStream(); - public String getEncodeName() { + public Charset getEncodeName() { return encodeName; } - public void setEncodeName(String encodeName) { + public void setEncodeName(Charset encodeName) { this.encodeName = encodeName; } @@ -84,10 +86,10 @@ public void put(String name, T t) { _out.setServerEncoding(encodeName); _out.write(t, 0); byte[] _sBuffer = TarsUtil.getBufArray(_out.getByteBuffer()); - HashMap pair = new HashMap(1); - ArrayList listTpye = new ArrayList(1); - checkObjectType(listTpye, t); - String className = BasicClassTypeUtil.transTypeList(listTpye); + HashMap pair = new HashMap<>(1); + ArrayList listType = new ArrayList<>(1); + checkObjectType(listType, t); + String className = BasicClassTypeUtil.transTypeList(listType); pair.put(className, _sBuffer); cachedData.remove(name); _data.put(name, pair); @@ -218,43 +220,43 @@ public T remove(String name) throws ObjectCreateException { } @SuppressWarnings("unchecked") - private void checkObjectType(ArrayList listTpye, Object o) { + private void checkObjectType(ArrayList listType, Object o) { if (o.getClass().isArray()) { if (!o.getClass().getComponentType().toString().equals("byte")) { throw new IllegalArgumentException("only byte[] is supported"); } if (Array.getLength(o) > 0) { - listTpye.add("java.util.List"); - checkObjectType(listTpye, Array.get(o, 0)); + listType.add("java.util.List"); + checkObjectType(listType, Array.get(o, 0)); } else { - listTpye.add("Array"); - listTpye.add("?"); + listType.add("Array"); + listType.add("?"); } } else if (o instanceof Array) { throw new java.lang.IllegalArgumentException("can not support Array, please use List"); } else if (o instanceof List) { - listTpye.add("java.util.List"); + listType.add("java.util.List"); List list = (List) o; if (list.size() > 0) { - checkObjectType(listTpye, list.get(0)); + checkObjectType(listType, list.get(0)); } else { - listTpye.add("?"); + listType.add("?"); } } else if (o instanceof Map) { - listTpye.add("java.util.Map"); + listType.add("java.util.Map"); Map map = (Map) o; if (map.size() > 0) { Iterator it = map.keySet().iterator(); Object key = it.next(); Object value = map.get(key); - listTpye.add(key.getClass().getName()); - checkObjectType(listTpye, value); + listType.add(key.getClass().getName()); + checkObjectType(listType, value); } else { - listTpye.add("?"); - listTpye.add("?"); + listType.add("?"); + listType.add("?"); } } else { - listTpye.add(o.getClass().getName()); + listType.add(o.getClass().getName()); } } diff --git a/core/src/main/java/com/qq/tars/rpc/protocol/tup/UniAttribute.java b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tup/UniAttribute.java similarity index 98% rename from core/src/main/java/com/qq/tars/rpc/protocol/tup/UniAttribute.java rename to tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tup/UniAttribute.java index 27b37cb5..2d11fb86 100644 --- a/core/src/main/java/com/qq/tars/rpc/protocol/tup/UniAttribute.java +++ b/tars-common-api/src/main/java/com/qq/tars/rpc/protocol/tup/UniAttribute.java @@ -16,15 +16,15 @@ package com.qq.tars.rpc.protocol.tup; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.util.TarsUtil; + import java.util.Collections; import java.util.HashMap; import java.util.Map.Entry; import java.util.Set; -import com.qq.tars.protocol.tars.TarsInputStream; -import com.qq.tars.protocol.tars.TarsOutputStream; -import com.qq.tars.protocol.util.TarsUtil; - public class UniAttribute extends OldUniAttribute { protected HashMap _newData = new HashMap(); @@ -41,6 +41,10 @@ public void clearCacheData() { cachedData.clear(); } + public void setNewDataNull() { + _newData = null; + } + public Set getKeySet() { if (null != _newData) { return Collections.unmodifiableSet(_newData.keySet()); @@ -213,8 +217,7 @@ public T get(String name, T proxy, Object defaultValue) { private Object decodeData(byte[] data, Object proxy) { _is.warp(data); _is.setServerEncoding(encodeName); - Object o = _is.read(proxy, 0, true); - return o; + return _is.read(proxy, 0, true); } private void saveDataCache(String name, Object o) { @@ -295,6 +298,7 @@ public void decodeVersion3(byte[] buffer) { public void decodeVersion2(byte[] buffer) { super.decode(buffer); + setNewDataNull(); } public void decode(byte[] buffer) { diff --git a/core/src/main/java/com/qq/tars/server/config/ConfigurationException.java b/tars-common-api/src/main/java/com/qq/tars/server/config/ConfigurationException.java similarity index 100% rename from core/src/main/java/com/qq/tars/server/config/ConfigurationException.java rename to tars-common-api/src/main/java/com/qq/tars/server/config/ConfigurationException.java diff --git a/core/src/main/java/com/qq/tars/server/config/ConfigurationManager.java b/tars-common-api/src/main/java/com/qq/tars/server/config/ConfigurationManager.java similarity index 97% rename from core/src/main/java/com/qq/tars/server/config/ConfigurationManager.java rename to tars-common-api/src/main/java/com/qq/tars/server/config/ConfigurationManager.java index 08dac7bc..ce099768 100644 --- a/core/src/main/java/com/qq/tars/server/config/ConfigurationManager.java +++ b/tars-common-api/src/main/java/com/qq/tars/server/config/ConfigurationManager.java @@ -26,6 +26,9 @@ public class ConfigurationManager { private static final ConfigurationManager instance = new ConfigurationManager(); + private ConfigurationManager() { + } + private volatile ServerConfig serverConfig; private volatile CommunicatorConfig communicatorConfig; @@ -34,11 +37,6 @@ public static ConfigurationManager getInstance() { return instance; } - @Deprecated - public ServerConfig getserverConfig() { - return serverConfig; - } - public ServerConfig getServerConfig() { return serverConfig; } diff --git a/core/src/main/java/com/qq/tars/server/config/ServantAdapterConfig.java b/tars-common-api/src/main/java/com/qq/tars/server/config/ServantAdapterConfig.java similarity index 55% rename from core/src/main/java/com/qq/tars/server/config/ServantAdapterConfig.java rename to tars-common-api/src/main/java/com/qq/tars/server/config/ServantAdapterConfig.java index 4e583f2b..8c734894 100644 --- a/core/src/main/java/com/qq/tars/server/config/ServantAdapterConfig.java +++ b/tars-common-api/src/main/java/com/qq/tars/server/config/ServantAdapterConfig.java @@ -19,19 +19,25 @@ import com.qq.tars.common.support.Endpoint; import com.qq.tars.common.util.Config; -public class ServantAdapterConfig { - - private Endpoint endpoint = null; - private int maxConns = 128; - private int queueCap = 1024; - private int queueTimeout = 10000; - private String servant = null; - private String protocol = "tars"; - private int threads = 1; - private String handleGroup = null; - - public ServantAdapterConfig load(Config conf, String adapterName) { - String path = "/tars/application/server/" + adapterName; +import javax.annotation.concurrent.Immutable; + +@Immutable +public final class ServantAdapterConfig { + + private final Endpoint endpoint; + private final int maxConns; + private final int queueCap; + private final int queueTimeout; + private final String servant; + private final String protocol; + private final int threads; + private final String handleGroup; + + private ServerConfig serverConfig; + + public ServantAdapterConfig(Config conf, String adapterName, ServerConfig serverConfig) { + this.serverConfig = serverConfig; + final String path = "/tars/application/server/" + adapterName; endpoint = Endpoint.parseString(conf.get(path + "")); handleGroup = conf.get(path + "", null); protocol = conf.get(path + "", "tars"); @@ -40,78 +46,75 @@ public ServantAdapterConfig load(Config conf, String adapterName) { queueTimeout = conf.getInt(path + "", 10000); servant = conf.get(path + ""); threads = conf.getInt(path + "", 1); - return this; } - public Endpoint getEndpoint() { - return endpoint; + + + public static ServantAdapterConfig makeServantAdapterConfig(Endpoint endpoint, String servantName, ServerConfig serverConfig) { + return new ServantAdapterConfig(endpoint, servantName, serverConfig); } - public ServantAdapterConfig setEndpoint(Endpoint endpoint) { + public static ServantAdapterConfig makeServantAdapterConfig(Config conf, String adapterName, ServerConfig serverConfig) { + return new ServantAdapterConfig(conf, adapterName, serverConfig); + } + + + public ServantAdapterConfig(Endpoint endpoint, String servantName, ServerConfig serverConfig) { + this.serverConfig = serverConfig; this.endpoint = endpoint; - return this; + this.handleGroup = null; + this.protocol = "tars"; + this.maxConns = 128; + this.queueCap = 1024; + this.queueTimeout = 10000; + this.servant = servantName; + this.threads = 2; } - public int getMaxConns() { - return maxConns; + public Endpoint getEndpoint() { + return endpoint; } - public ServantAdapterConfig setMaxConns(int maxConns) { - this.maxConns = maxConns; - return this; + + public int getMaxConns() { + return maxConns; } public int getQueueCap() { return queueCap; } - public ServantAdapterConfig setQueueCap(int queueCap) { - this.queueCap = queueCap; - return this; - } - public int getQueueTimeout() { return queueTimeout; } - public ServantAdapterConfig setQueueTimeout(int queueTimeout) { - this.queueTimeout = queueTimeout; - return this; - } public String getServant() { return servant; } - public ServantAdapterConfig setServant(String servant) { - this.servant = servant; - return this; - } public int getThreads() { return threads; } - public ServantAdapterConfig setThreads(int threads) { - this.threads = threads; - return this; - } public String getProtocol() { return protocol; } - public ServantAdapterConfig setProtocol(String protocol) { - this.protocol = protocol; - return this; - } - public String getHandleGroup() { return handleGroup; } - public ServantAdapterConfig setHandleGroup(String handleGroup) { - this.handleGroup = handleGroup; - return this; + + public ServerConfig getServerConfig() { + return serverConfig; } + + public void setServerConfig(ServerConfig serverConfig) { + this.serverConfig = serverConfig; + } + + } diff --git a/core/src/main/java/com/qq/tars/server/config/ServerConfig.java b/tars-common-api/src/main/java/com/qq/tars/server/config/ServerConfig.java similarity index 75% rename from core/src/main/java/com/qq/tars/server/config/ServerConfig.java rename to tars-common-api/src/main/java/com/qq/tars/server/config/ServerConfig.java index d139b96e..2d8b2598 100644 --- a/core/src/main/java/com/qq/tars/server/config/ServerConfig.java +++ b/tars-common-api/src/main/java/com/qq/tars/server/config/ServerConfig.java @@ -19,14 +19,16 @@ import com.qq.tars.client.CommunicatorConfig; import com.qq.tars.common.support.Endpoint; import com.qq.tars.common.util.Config; +import com.qq.tars.common.util.Constants; import com.qq.tars.support.om.OmConstants; import java.io.File; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.List; public class ServerConfig { - private String application; private String serverName; private Endpoint local; @@ -44,30 +46,37 @@ public class ServerConfig { private String sampleType; private String sampleAddress; private String sampleEncoding; - private int sessionTimeOut = 120000; private int sessionCheckInterval = 60000; private boolean tcpNoDelay = false; private int udpBufferSize = 4096; + private int logMaxHistry = 15; + + public int getLogMaxHistry() { + return logMaxHistry; + } - private String charsetName = "UTF-8"; + public void setLogMaxHistry(int logMaxHistry) { + this.logMaxHistry = logMaxHistry; + } + private Charset charsetName = StandardCharsets.UTF_8; private LinkedHashMap servantAdapterConfMap; private CommunicatorConfig communicatorConfig; + public ServerConfig load(Config conf) { application = conf.get("/tars/application/server", "UNKNOWN"); serverName = conf.get("/tars/application/server", null); - String localStr = conf.get("/tars/application/server"); local = localStr == null || localStr.length() <= 0 ? null : Endpoint .parseString(localStr); node = conf.get("/tars/application/server"); basePath = conf.get("/tars/application/server"); dataPath = conf.get("/tars/application/server"); + logMaxHistry = conf.getInt("/tars/application/server", 15); - charsetName = conf - .get("/tars/application/server", "UTF-8"); + charsetName = Charset.forName(conf.get("/tars/application/server", Constants.DEFAULT_CHARSET_STRING)); config = conf.get("/tars/application/server"); notify = conf.get("/tars/application/server"); @@ -92,19 +101,18 @@ public ServerConfig load(Config conf) { 4096); tcpNoDelay = conf.getBool("/tars/application/server", false); - servantAdapterConfMap = new LinkedHashMap(); + servantAdapterConfMap = new LinkedHashMap<>(); List adapterNameList = conf.getSubTags("/tars/application/server"); if (adapterNameList != null) { for (String adapterName : adapterNameList) { - ServantAdapterConfig config = new ServantAdapterConfig(); - config.load(conf, adapterName); + ServantAdapterConfig config = ServantAdapterConfig.makeServantAdapterConfig(conf, adapterName, this); servantAdapterConfMap.put(config.getServant(), config); } } - - ServantAdapterConfig adminServantAdapterConfig = new ServantAdapterConfig(); - adminServantAdapterConfig.setEndpoint(local); - adminServantAdapterConfig.setServant(String.format("%s.%s.%s", application, serverName, OmConstants.AdminServant)); + final ServantAdapterConfig adminServantAdapterConfig = + ServantAdapterConfig.makeServantAdapterConfig(local, + String.format("%s.%s.%s", application, serverName, OmConstants.AdminServant), + this); servantAdapterConfMap.put(OmConstants.AdminServant, adminServantAdapterConfig); if (application != null && serverName != null && logPath != null) { @@ -119,6 +127,23 @@ public ServerConfig load(Config conf) { return this; } + public ServerConfig() { + application = "UNKNOWN"; + serverName = ""; + String localStr = ""; + logMaxHistry = 15; + + charsetName = Constants.DEFAULT_CHARSET; + logRate = 5; + + + sessionTimeOut = 120000; + sessionCheckInterval = 60000; + udpBufferSize = 4096; + tcpNoDelay =false; + servantAdapterConfMap = new LinkedHashMap<>(); + } + public String getApplication() { return application; } @@ -292,11 +317,11 @@ public ServerConfig setUdpBufferSize(int udpBufferSize) { return this; } - public String getCharsetName() { + public Charset getCharsetName() { return charsetName; } - public ServerConfig setCharsetName(String charsetName) { + public ServerConfig setCharsetName(Charset charsetName) { this.charsetName = charsetName; return this; } @@ -337,4 +362,35 @@ public void setSampleEncoding(String sampleEncoding) { this.sampleEncoding = sampleEncoding; } + + @Override + public String toString() { + return "ServerConfig{" + + "application='" + application + '\'' + + ", serverName='" + serverName + '\'' + + ", local=" + local + + ", node='" + node + '\'' + + ", basePath='" + basePath + '\'' + + ", config='" + config + '\'' + + ", notify='" + notify + '\'' + + ", log='" + log + '\'' + + ", logPath='" + logPath + '\'' + + ", logLevel='" + logLevel + '\'' + + ", logRate=" + logRate + + ", dataPath='" + dataPath + '\'' + + ", localIP='" + localIP + '\'' + + ", sampleRate=" + sampleRate + + ", sampleType='" + sampleType + '\'' + + ", sampleAddress='" + sampleAddress + '\'' + + ", sampleEncoding='" + sampleEncoding + '\'' + + ", sessionTimeOut=" + sessionTimeOut + + ", sessionCheckInterval=" + sessionCheckInterval + + ", tcpNoDelay=" + tcpNoDelay + + ", udpBufferSize=" + udpBufferSize + + ", logMaxHistry=" + logMaxHistry + + ", charsetName='" + charsetName + '\'' + + ", servantAdapterConfMap=" + servantAdapterConfMap + + ", communicatorConfig=" + communicatorConfig + + '}'; + } } diff --git a/tars-common-api/src/main/java/com/qq/tars/server/core/Processor.java b/tars-common-api/src/main/java/com/qq/tars/server/core/Processor.java new file mode 100644 index 00000000..4f323455 --- /dev/null +++ b/tars-common-api/src/main/java/com/qq/tars/server/core/Processor.java @@ -0,0 +1,20 @@ +package com.qq.tars.server.core; + +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; +import io.netty.channel.Channel; + +public interface Processor { + /** + * @param request + * @param clientChannel + * @return + */ + Response process(Request request, Channel clientChannel); + + /** + * @param request + * @param clientChannel + */ + void overload(Request request, Channel clientChannel); +} diff --git a/tars-common-api/src/main/java/com/qq/tars/support/log/LoggerFactory.java b/tars-common-api/src/main/java/com/qq/tars/support/log/LoggerFactory.java new file mode 100644 index 00000000..4ffaceb1 --- /dev/null +++ b/tars-common-api/src/main/java/com/qq/tars/support/log/LoggerFactory.java @@ -0,0 +1,48 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.qq.tars.support.log; + +import java.util.logging.Logger; + +public final class LoggerFactory { + private static final String CLIENT_LOG_NAME = "TARS_CLIENT_LOGGER"; + private static final String OM_LOG_NAME = "OM_LOGGER"; + private static final String TRANSPORTER_LOG_NAME = "TARS_TRANSPORTER_LOGGER"; + + private LoggerFactory() { + } + + public static Logger getLogger(String name) { + return Logger.getLogger(name); + } + + public static Logger getLogger(Class clazz) { + return Logger.getLogger(clazz.getName()); + } + + public static Logger getOmLogger() { + return Logger.getLogger(OM_LOG_NAME); + } + + public static Logger getClientLogger() { + return Logger.getLogger(CLIENT_LOG_NAME); + } + + public static Logger getTransporterLogger() { + return Logger.getLogger(TRANSPORTER_LOG_NAME); + } +} diff --git a/core/src/main/java/com/qq/tars/support/om/OmConstants.java b/tars-common-api/src/main/java/com/qq/tars/support/om/OmConstants.java similarity index 100% rename from core/src/main/java/com/qq/tars/support/om/OmConstants.java rename to tars-common-api/src/main/java/com/qq/tars/support/om/OmConstants.java diff --git a/core/src/main/java/com/qq/tars/support/query/prx/EndpointF.java b/tars-common-api/src/main/java/com/qq/tars/support/query/prx/EndpointF.java similarity index 95% rename from core/src/main/java/com/qq/tars/support/query/prx/EndpointF.java rename to tars-common-api/src/main/java/com/qq/tars/support/query/prx/EndpointF.java index 53e3c062..733bbbbb 100644 --- a/core/src/main/java/com/qq/tars/support/query/prx/EndpointF.java +++ b/tars-common-api/src/main/java/com/qq/tars/support/query/prx/EndpointF.java @@ -20,13 +20,14 @@ package com.qq.tars.support.query.prx; -import com.qq.tars.protocol.util.*; -import com.qq.tars.protocol.annotation.*; -import com.qq.tars.protocol.tars.*; -import com.qq.tars.protocol.tars.annotation.*; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.annotation.TarsStruct; +import com.qq.tars.protocol.tars.annotation.TarsStructProperty; +import com.qq.tars.protocol.util.TarsUtil; /** - * 端口信息 + * Port information */ @TarsStruct public class EndpointF implements Comparable { diff --git a/tars-common-api/src/main/java/com/qq/tars/support/query/prx/QueryFPrx.java b/tars-common-api/src/main/java/com/qq/tars/support/query/prx/QueryFPrx.java new file mode 100644 index 00000000..23040031 --- /dev/null +++ b/tars-common-api/src/main/java/com/qq/tars/support/query/prx/QueryFPrx.java @@ -0,0 +1,136 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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. + */ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 1.0.1. +// ********************************************************************** + +package com.qq.tars.support.query.prx; + +import com.qq.tars.common.support.Holder; +import com.qq.tars.protocol.annotation.Servant; +import com.qq.tars.protocol.tars.annotation.TarsCallback; +import com.qq.tars.protocol.tars.annotation.TarsContext; +import com.qq.tars.protocol.tars.annotation.TarsHolder; + +/** + * Get the query interface of the object endpoint + */ +@Servant +public interface QueryFPrx { + /** Get the object by id + * + * @param id Object name + * + * @return Returns a list of all active endpoints for this object + */ + public java.util.List findObjectById(String id); + /** Get the object by id + * + * @param id Object name + * + * @return Returns a list of all active endpoints for this object + */ + public java.util.List findObjectById(String id, @TarsContext java.util.Map ctx); + + /**Gets all objects by id, both active and inactive + * + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure + */ + public int findObjectById4Any(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp); + /**Gets all objects by id, both active and inactive + * + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure + */ + public int findObjectById4Any(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp, @TarsContext java.util.Map ctx); + + /** Get all endpoint lists of objects according to id, the function is the same as findObjectByIdInSameGroup + * + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure + */ + public int findObjectById4All(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp); + /** Get all endpoint lists of objects according to id, the function is the same as findObjectByIdInSameGroup + * + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure + */ + public int findObjectById4All(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp, @TarsContext java.util.Map ctx); + + /** Get the same group endpoint list of objects according to id + * + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure + */ + public int findObjectByIdInSameGroup(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp); + /** Get the same group endpoint list of objects according to id + * + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure + */ + public int findObjectByIdInSameGroup(String id, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp, @TarsContext java.util.Map ctx); + + /** Get the endpoint list of the specified home location of the object according to id + * + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure + */ + public int findObjectByIdInSameStation(String id, String sStation, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp); + /** Get the endpoint list of the specified home location of the object according to id + * + * @param id Object name + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure + */ + public int findObjectByIdInSameStation(String id, String sStation, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp, @TarsContext java.util.Map ctx); + + /** Get the same group endpoint list of objects according to id + * + * @param id Object name + * @param setId The full name of set, the format is setname.setarea.setgroup + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure + */ + public int findObjectByIdInSameSet(String id, String setId, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp); + /** Get the same group endpoint list of objects according to id + * + * @param id Object name + * @param setId The full name of set, the format is setname.setarea.setgroup + * @param activeEp List of live endpoints + * @param inactiveEp List of non-live endpoints + * @return: 0-success others-failure + */ + public int findObjectByIdInSameSet(String id, String setId, @TarsHolder Holder> activeEp, @TarsHolder Holder> inactiveEp, @TarsContext java.util.Map ctx); + +} diff --git a/tars-common-api/src/test/java/com/qq/tars/common/util/VirtualThreadSupportTest.java b/tars-common-api/src/test/java/com/qq/tars/common/util/VirtualThreadSupportTest.java new file mode 100644 index 00000000..ce016dea --- /dev/null +++ b/tars-common-api/src/test/java/com/qq/tars/common/util/VirtualThreadSupportTest.java @@ -0,0 +1,74 @@ +package com.qq.tars.common.util; + +import org.junit.Assert; +import org.junit.Test; + +import java.lang.reflect.Method; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +public class VirtualThreadSupportTest { + + @Test + public void testExecuteServerTaskDisabledByDefault() { + String originGlobal = System.getProperty(VirtualThreadSupport.VTHREAD_ENABLED_KEY); + String originServer = System.getProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY); + try { + System.clearProperty(VirtualThreadSupport.VTHREAD_ENABLED_KEY); + System.clearProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY); + VirtualThreadSupport.shutdownForTest(); + Assert.assertFalse(VirtualThreadSupport.executeServerTask(() -> { + })); + } finally { + restoreProperty(VirtualThreadSupport.VTHREAD_ENABLED_KEY, originGlobal); + restoreProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY, originServer); + VirtualThreadSupport.shutdownForTest(); + } + } + + @Test + public void testExecuteServerTaskWithVirtualThreadWhenEnabled() throws Exception { + String originGlobal = System.getProperty(VirtualThreadSupport.VTHREAD_ENABLED_KEY); + String originServer = System.getProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY); + try { + System.setProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY, "true"); + VirtualThreadSupport.shutdownForTest(); + + CountDownLatch latch = new CountDownLatch(1); + AtomicReference executedThread = new AtomicReference<>(); + boolean executed = VirtualThreadSupport.executeServerTask(() -> { + executedThread.set(Thread.currentThread()); + latch.countDown(); + }); + + if (VirtualThreadSupport.isVirtualThreadSupported()) { + Assert.assertTrue(executed); + Assert.assertTrue(latch.await(3, TimeUnit.SECONDS)); + Assert.assertTrue(isVirtualThread(executedThread.get())); + } else { + Assert.assertFalse(executed); + } + } finally { + restoreProperty(VirtualThreadSupport.VTHREAD_ENABLED_KEY, originGlobal); + restoreProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY, originServer); + VirtualThreadSupport.shutdownForTest(); + } + } + + private static boolean isVirtualThread(Thread thread) throws Exception { + if (thread == null) { + return false; + } + Method method = Thread.class.getMethod("isVirtual"); + return (Boolean) method.invoke(thread); + } + + private static void restoreProperty(String key, String value) { + if (value == null) { + System.clearProperty(key); + } else { + System.setProperty(key, value); + } + } +} diff --git a/tars-native/build.gradle.kts b/tars-native/build.gradle.kts new file mode 100644 index 00000000..e4e3d39c --- /dev/null +++ b/tars-native/build.gradle.kts @@ -0,0 +1,9 @@ +plugins { + `java-library` +} + +description = "Tars Native - GraalVM Native Image AOT Support" + +dependencies { + api(project(":tars-common-api")) +} diff --git a/tars-native/src/main/java/com/qq/tars/aot/NativeDetector.java b/tars-native/src/main/java/com/qq/tars/aot/NativeDetector.java new file mode 100644 index 00000000..0531e651 --- /dev/null +++ b/tars-native/src/main/java/com/qq/tars/aot/NativeDetector.java @@ -0,0 +1,20 @@ +package com.qq.tars.aot; + +/** + * Detects whether the current runtime is a GraalVM native image. + */ +public final class NativeDetector { + + private static final boolean IN_NATIVE_IMAGE = + System.getProperty("org.graalvm.nativeimage.imagecode") != null; + + private NativeDetector() { + } + + /** + * Returns {@code true} if running inside a GraalVM native image. + */ + public static boolean inNativeImage() { + return IN_NATIVE_IMAGE; + } +} diff --git a/tars-native/src/main/java/com/qq/tars/aot/api/JdkProxyDescriber.java b/tars-native/src/main/java/com/qq/tars/aot/api/JdkProxyDescriber.java new file mode 100644 index 00000000..4cf90ce5 --- /dev/null +++ b/tars-native/src/main/java/com/qq/tars/aot/api/JdkProxyDescriber.java @@ -0,0 +1,19 @@ +package com.qq.tars.aot.api; + +import java.util.List; + +/** + * Describes a JDK dynamic proxy that requires registration for GraalVM native image. + */ +public class JdkProxyDescriber { + + private final List interfaces; + + public JdkProxyDescriber(List interfaces) { + this.interfaces = List.copyOf(interfaces); + } + + public List getInterfaces() { + return interfaces; + } +} diff --git a/tars-native/src/main/java/com/qq/tars/aot/api/NativeDescriberRegistrar.java b/tars-native/src/main/java/com/qq/tars/aot/api/NativeDescriberRegistrar.java new file mode 100644 index 00000000..b36c6992 --- /dev/null +++ b/tars-native/src/main/java/com/qq/tars/aot/api/NativeDescriberRegistrar.java @@ -0,0 +1,34 @@ +package com.qq.tars.aot.api; + +import java.util.Collections; +import java.util.List; + +/** + * SPI interface for modules to declare their GraalVM native image metadata. + * + *

Implementations are discovered via {@link java.util.ServiceLoader} and + * contribute reflection, proxy, and resource configuration entries.

+ */ +public interface NativeDescriberRegistrar { + + /** + * Returns types that need reflection registration. + */ + default List getTypeDescribers() { + return Collections.emptyList(); + } + + /** + * Returns JDK dynamic proxy configurations. + */ + default List getProxyDescribers() { + return Collections.emptyList(); + } + + /** + * Returns resource patterns to include. + */ + default List getResourceDescribers() { + return Collections.emptyList(); + } +} diff --git a/tars-native/src/main/java/com/qq/tars/aot/api/ResourceDescriber.java b/tars-native/src/main/java/com/qq/tars/aot/api/ResourceDescriber.java new file mode 100644 index 00000000..bda3d055 --- /dev/null +++ b/tars-native/src/main/java/com/qq/tars/aot/api/ResourceDescriber.java @@ -0,0 +1,17 @@ +package com.qq.tars.aot.api; + +/** + * Describes a resource pattern that must be included in the GraalVM native image. + */ +public class ResourceDescriber { + + private final String pattern; + + public ResourceDescriber(String pattern) { + this.pattern = pattern; + } + + public String getPattern() { + return pattern; + } +} diff --git a/tars-native/src/main/java/com/qq/tars/aot/api/TypeDescriber.java b/tars-native/src/main/java/com/qq/tars/aot/api/TypeDescriber.java new file mode 100644 index 00000000..81cf28c6 --- /dev/null +++ b/tars-native/src/main/java/com/qq/tars/aot/api/TypeDescriber.java @@ -0,0 +1,36 @@ +package com.qq.tars.aot.api; + +/** + * Describes a type that requires reflection registration for GraalVM native image. + */ +public class TypeDescriber { + + private final String className; + private final boolean allDeclaredConstructors; + private final boolean allDeclaredMethods; + private final boolean allDeclaredFields; + + public TypeDescriber(String className, boolean allDeclaredConstructors, + boolean allDeclaredMethods, boolean allDeclaredFields) { + this.className = className; + this.allDeclaredConstructors = allDeclaredConstructors; + this.allDeclaredMethods = allDeclaredMethods; + this.allDeclaredFields = allDeclaredFields; + } + + public String getClassName() { + return className; + } + + public boolean isAllDeclaredConstructors() { + return allDeclaredConstructors; + } + + public boolean isAllDeclaredMethods() { + return allDeclaredMethods; + } + + public boolean isAllDeclaredFields() { + return allDeclaredFields; + } +} diff --git a/tars-native/src/main/java/com/qq/tars/aot/generate/NativeConfigWriter.java b/tars-native/src/main/java/com/qq/tars/aot/generate/NativeConfigWriter.java new file mode 100644 index 00000000..d85e1bb2 --- /dev/null +++ b/tars-native/src/main/java/com/qq/tars/aot/generate/NativeConfigWriter.java @@ -0,0 +1,81 @@ +package com.qq.tars.aot.generate; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.qq.tars.aot.api.JdkProxyDescriber; +import com.qq.tars.aot.api.ResourceDescriber; +import com.qq.tars.aot.api.TypeDescriber; + +import java.io.IOException; +import java.io.Writer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Serialises {@link TypeDescriber}, {@link JdkProxyDescriber} and + * {@link ResourceDescriber} lists into GraalVM native-image JSON config files. + */ +public final class NativeConfigWriter { + + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + private NativeConfigWriter() { + } + + /** + * Writes {@code reflect-config.json}. + */ + public static void writeReflectConfig(List types, Path outputDir) throws IOException { + List> entries = new ArrayList<>(); + for (TypeDescriber td : types) { + Map entry = new HashMap<>(); + entry.put("name", td.getClassName()); + if (td.isAllDeclaredConstructors()) entry.put("allDeclaredConstructors", true); + if (td.isAllDeclaredMethods()) entry.put("allDeclaredMethods", true); + if (td.isAllDeclaredFields()) entry.put("allDeclaredFields", true); + entries.add(entry); + } + writeJson(entries, outputDir.resolve("reflect-config.json")); + } + + /** + * Writes {@code proxy-config.json}. + */ + public static void writeProxyConfig(List proxies, Path outputDir) throws IOException { + List> entries = new ArrayList<>(); + for (JdkProxyDescriber pd : proxies) { + Map entry = new HashMap<>(); + entry.put("interfaces", pd.getInterfaces()); + entries.add(entry); + } + writeJson(entries, outputDir.resolve("proxy-config.json")); + } + + /** + * Writes {@code resource-config.json}. + */ + public static void writeResourceConfig(List resources, Path outputDir) throws IOException { + List> patterns = new ArrayList<>(); + for (ResourceDescriber rd : resources) { + Map p = new HashMap<>(); + p.put("pattern", rd.getPattern()); + patterns.add(p); + } + Map includes = new HashMap<>(); + includes.put("includes", patterns); + Map root = new HashMap<>(); + root.put("resources", includes); + writeJson(root, outputDir.resolve("resource-config.json")); + } + + private static void writeJson(Object obj, Path file) throws IOException { + Files.createDirectories(file.getParent()); + try (Writer writer = Files.newBufferedWriter(file)) { + GSON.toJson(obj, writer); + } + } +} diff --git a/tars-netty/README.md b/tars-netty/README.md new file mode 100644 index 00000000..12c414a5 --- /dev/null +++ b/tars-netty/README.md @@ -0,0 +1,49 @@ +# tars-netty + +The netty implementation for tars transporter layer. + +Usage +------ + +1. Use `tars-core` directly. In this case, you need to import `tars-netty` manually. + +```xml + + + + com.tencent.tars + tars-core + 2.0.0 + + + com.tencent.tars + tars-netty + 2.0.0 + + +``` + +2. Use `tars-spring` or `tars-spring-boot-starter`. `tars-netty` will be imported automatically, so no need to change + your pom.xml. + +```xml + + + + com.tencent.tars + tars-spring-boot-starter + 2.0.0 + + +``` + +Implementation Details +------ + +`TransporterAbstractFactory` in tars-core use **SPI** to load the implementation for `TransporterFactory`, which will be +used to connect to a tars server node(client-side) or start listening the ip:port(server-side). + +`tars-netty` provides three core classes: `NettyTransporterFactory`, `NettyTransporterServer` and `NettyServantClient`, +which are used to adapt **netty** and **tars**. + +For more details, please refer to the javadoc. \ No newline at end of file diff --git a/tars-netty/build.gradle.kts b/tars-netty/build.gradle.kts new file mode 100644 index 00000000..9abac45c --- /dev/null +++ b/tars-netty/build.gradle.kts @@ -0,0 +1,30 @@ +plugins { + `java-library` +} + +description = "Tars Netty - Netty-based Transport Layer" + +val nettyVersion = libs.netty.all.get().versionConstraint.requiredVersion +val osName = System.getProperty("os.name").lowercase() +val archName = System.getProperty("os.arch").lowercase() +val nettyArch = when (archName) { + "x86_64", "amd64" -> "x86_64" + "aarch64", "arm64" -> "aarch_64" + else -> null +} + +dependencies { + api(project(":tars-common-api")) + + implementation(libs.netty.all) + implementation(libs.netty.tcnative) + + if (nettyArch != null && osName.contains("linux")) { + runtimeOnly("io.netty:netty-transport-native-epoll:$nettyVersion:linux-$nettyArch") + } else if (nettyArch != null && (osName.contains("mac") || osName.contains("darwin"))) { + runtimeOnly("io.netty:netty-transport-native-kqueue:$nettyVersion:osx-$nettyArch") + runtimeOnly("io.netty:netty-resolver-dns-native-macos:$nettyVersion:osx-$nettyArch") + } + + testImplementation(libs.junit) +} diff --git a/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyChannel.java b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyChannel.java new file mode 100644 index 00000000..89bfedbb --- /dev/null +++ b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyChannel.java @@ -0,0 +1,31 @@ +package com.qq.tars.rpc.netty; + +import com.qq.tars.client.ServantProxyConfig; +import io.netty.channel.Channel; + +public class NettyChannel { + private final Channel channel; + private final ServantProxyConfig servantProxyConfig; + + public NettyChannel(Channel channel, ServantProxyConfig servantProxyConfig) { + this.channel = channel; + this.servantProxyConfig = servantProxyConfig; + + } + + public Channel getChannel() { + return channel; + } + + public ServantProxyConfig getServantProxyConfig() { + return servantProxyConfig; + } + + @Override + public String toString() { + return "NettyTarsChannel{" + + "channel=" + channel + + ", servantProxyConfig=" + servantProxyConfig + + '}'; + } +} diff --git a/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyClientHandler.java b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyClientHandler.java new file mode 100644 index 00000000..f7486b59 --- /dev/null +++ b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyClientHandler.java @@ -0,0 +1,120 @@ +package com.qq.tars.rpc.netty; + +import com.google.common.collect.Maps; +import com.qq.tars.client.ServantProxyConfig; +import com.qq.tars.client.rpc.ChannelHandler; +import com.qq.tars.client.rpc.TicketFeature; +import com.qq.tars.rpc.protocol.tars.TarsServantResponse; +import io.netty.channel.Channel; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.util.Map; + +@Sharable +public class NettyClientHandler extends ChannelDuplexHandler { + private static final Logger logger = Logger.getLogger(NettyClientHandler.class.getName()); + private static final Map CHANNEL_MAP = Maps.newConcurrentMap(); + + public static NettyChannel getOrAddChannel(Channel ioChannel, ServantProxyConfig config) { + if (ioChannel == null) { + return null; + } + NettyChannel channel = CHANNEL_MAP.get(ioChannel); + if (channel == null) { + NettyChannel nettyChannel = new NettyChannel(ioChannel, config); + channel = CHANNEL_MAP.putIfAbsent(ioChannel, nettyChannel); + if (channel == null) { + return nettyChannel; + } + } + return channel; + } + + public static void removeBrokenChannel(Channel channel) { + if (channel != null && !channel.isActive()) { + final NettyChannel nettyChannel = CHANNEL_MAP.remove(channel); + if (null != nettyChannel) { + logger.info("Remove channel [" + nettyChannel + "] from NettyChannelManager"); + } else { + logger.info("the channel [" + nettyChannel + "] already removed"); + } + } + + } + + private final ServantProxyConfig servantProxyConfig; + private final ChannelHandler channelHeader; + + public NettyClientHandler(ChannelHandler handler, ServantProxyConfig servantProxyConfig) { + this.channelHeader = handler; + this.servantProxyConfig = servantProxyConfig; + } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + try { + NettyChannel channel = getOrAddChannel(ctx.channel(), servantProxyConfig); + channelHeader.connected(channel.getChannel()); + } finally { + removeBrokenChannel(ctx.channel()); + } + } + + /** + * 这里收到了消息 + */ + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + try { + NettyChannel nettyChannel = getOrAddChannel(ctx.channel(), servantProxyConfig); + TarsServantResponse response = (TarsServantResponse) msg; + if (logger.isLoggable(Level.FINE)) { + System.out.println(); + logger.fine("[tars]netty receive message id is " + response.getRequestId()); + } + TicketFeature.getFeature(response.getRequestId()).complete(msg); + channelHeader.received(nettyChannel.getChannel(), msg); + } finally { + removeBrokenChannel(ctx.channel()); + } + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + try { + cause.printStackTrace(); + NettyChannel channel = getOrAddChannel(ctx.channel(), servantProxyConfig); + channelHeader.caught(channel.getChannel(), cause); + } finally { + removeBrokenChannel(ctx.channel()); + } + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + NettyChannel channel = getOrAddChannel(ctx.channel(), servantProxyConfig); + try { + channelHeader.disconnected(channel.getChannel()); + } finally { + removeBrokenChannel(ctx.channel()); + } + } + + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) + throws Exception { + super.write(ctx, msg, promise); + NettyChannel channel = getOrAddChannel(ctx.channel(), servantProxyConfig); + channelHeader.send(channel.getChannel(), msg); + } + + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + } + +} diff --git a/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyNativeTransportSelector.java b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyNativeTransportSelector.java new file mode 100644 index 00000000..fe1c13d7 --- /dev/null +++ b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyNativeTransportSelector.java @@ -0,0 +1,42 @@ +package com.qq.tars.rpc.netty; + +import io.netty.channel.epoll.Epoll; +import io.netty.channel.kqueue.KQueue; + +final class NettyNativeTransportSelector { + + enum Transport { + EPOLL, + KQUEUE, + NIO + } + + private NettyNativeTransportSelector() { + } + + static Transport select(boolean epollAvailable, boolean kqueueAvailable) { + if (epollAvailable) { + return Transport.EPOLL; + } + if (kqueueAvailable) { + return Transport.KQUEUE; + } + return Transport.NIO; + } + + static Transport current() { + return select(Epoll.isAvailable(), KQueue.isAvailable()); + } + + static String unavailableCause() { + Throwable epollCause = Epoll.unavailabilityCause(); + if (epollCause != null) { + return "epoll unavailable: " + epollCause.getMessage(); + } + Throwable kqueueCause = KQueue.unavailabilityCause(); + if (kqueueCause != null) { + return "kqueue unavailable: " + kqueueCause.getMessage(); + } + return "native transport unavailable"; + } +} diff --git a/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyServantClient.java b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyServantClient.java new file mode 100644 index 00000000..75e1f811 --- /dev/null +++ b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyServantClient.java @@ -0,0 +1,194 @@ +package com.qq.tars.rpc.netty; + +import com.qq.tars.client.ServantProxyConfig; +import com.qq.tars.client.rpc.ChannelHandler; +import com.qq.tars.client.rpc.*; +import com.qq.tars.rpc.common.Url; +import com.qq.tars.rpc.protocol.tars.TarsServantResponse; +import io.netty.bootstrap.Bootstrap; +import io.netty.buffer.PooledByteBufAllocator; +import io.netty.channel.*; +import io.netty.channel.epoll.Epoll; +import io.netty.channel.epoll.EpollEventLoopGroup; +import io.netty.channel.epoll.EpollSocketChannel; +import io.netty.channel.kqueue.KQueue; +import io.netty.channel.kqueue.KQueueEventLoopGroup; +import io.netty.channel.kqueue.KQueueSocketChannel; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.timeout.IdleStateHandler; +import io.netty.util.concurrent.DefaultThreadFactory; +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicBoolean; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +public class NettyServantClient implements RPCClient { + private static final Logger logger = Logger.getLogger(NettyServantClient.class.getName()); + private volatile Channel channel; + private final ServantProxyConfig servantProxyConfig; + private final Url url; + private volatile AtomicBoolean isClosed = new AtomicBoolean(false); + private static final int DEFAULT_IO_THREADS = Math.min(Runtime.getRuntime().availableProcessors() + 8, 32); + private static final NettyNativeTransportSelector.Transport TRANSPORT = NettyNativeTransportSelector.current(); + private static final EventLoopGroup EVENT_LOOP_GROUP = createEventLoopGroup(TRANSPORT); + private Bootstrap bootstrap; + private final ChannelHandler channelHandler; + + public NettyServantClient(Url url, ServantProxyConfig servantProxyConfig, ChannelHandler clientHandler) { + this.channelHandler = clientHandler; + this.servantProxyConfig = servantProxyConfig; + this.url = url; + init(); + connect(); + } + + + private static EventLoopGroup createEventLoopGroup(NettyNativeTransportSelector.Transport transport) { + ThreadFactory threadFactory = new DefaultThreadFactory("netty-client-worker", true); + switch (transport) { + case EPOLL: + return new EpollEventLoopGroup(DEFAULT_IO_THREADS, threadFactory); + case KQUEUE: + return new KQueueEventLoopGroup(DEFAULT_IO_THREADS, threadFactory); + default: + return new NioEventLoopGroup(DEFAULT_IO_THREADS, threadFactory); + } + } + + public void init() { + bootstrap = new Bootstrap(); + bootstrap.group(EVENT_LOOP_GROUP); + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "[tars] client transport={0}", TRANSPORT); + if (TRANSPORT == NettyNativeTransportSelector.Transport.NIO) { + logger.log(Level.INFO, "[tars] fallback to NIO, {0}", NettyNativeTransportSelector.unavailableCause()); + } + } + switch (TRANSPORT) { + case EPOLL: + bootstrap.channelFactory(() -> new EpollSocketChannel()); + break; + case KQUEUE: + bootstrap.channelFactory(() -> new KQueueSocketChannel()); + break; + default: + bootstrap.channelFactory(() -> new NioSocketChannel()); + break; + } + bootstrap.option(ChannelOption.SO_KEEPALIVE, true) + .option(ChannelOption.TCP_NODELAY, NettyServantClient.this.servantProxyConfig.isTcpNoDelay()) + .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, servantProxyConfig.getConnectTimeout()); + + bootstrap.handler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) throws Exception { + IdleStateHandler clientIdleHandler = + new IdleStateHandler(0, servantProxyConfig.getConnectTimeout(), 0, MILLISECONDS); + ChannelPipeline p = ch.pipeline(); + p.addLast("encoder", new TarsEncoder(Charset.forName(servantProxyConfig.getCharsetName()))) + .addLast("decoder", new TarsDecoder(Charset.forName(servantProxyConfig.getCharsetName()))) + .addLast("idle", clientIdleHandler) + .addLast("handler", new NettyClientHandler(NettyServantClient.this.channelHandler, servantProxyConfig)) + ; + } + }); + } + + + public NettyServantClient connect() { + ChannelFuture ioChannelFuture = bootstrap.connect(url.getHost(), url.getPort()); + try { + boolean ret = ioChannelFuture.awaitUninterruptibly(this.servantProxyConfig.getConnectTimeout(), MILLISECONDS); + if (ret && ioChannelFuture.isSuccess()) { + Channel newChannel = ioChannelFuture.channel(); + try { + final Channel oldChannel = NettyServantClient.this.channel; + if (oldChannel != null) { + try { + if (logger.isLoggable(Level.INFO)) { + logger.info("[Tars] reconnect new channel"); + } + oldChannel.close(); + } finally { + NettyClientHandler.removeBrokenChannel(oldChannel); + } + } + } finally { + if (NettyServantClient.this.isClosed.get()) { + try { + if (logger.isLoggable(Level.INFO)) { + logger.info("[tars]close channel"); + } + newChannel.close(); + } finally { + NettyServantClient.this.channel = null; + NettyClientHandler.removeBrokenChannel(newChannel); + } + } else { + NettyServantClient.this.channel = newChannel; + } + } + } else if (ioChannelFuture.cause() != null) { + throw new RuntimeException("[tars]cannot connect server"); + } else { + throw new RuntimeException("[tars] invoke timeout"); + } + } finally { + // just add new valid channel to NettyChannel's cache + if (!isConnected()) { + //future.cancel(true); + } + } + return this; + } + + public boolean isConnected() { + Channel channel = getChannel(); + if (channel == null) { + return false; + } + return isClosed.get(); + } + + public void reConnect() throws IOException { + if (!channel.isActive()) { + channel.isOpen(); + } + + } + + public void close() throws IOException { + this.isClosed.set(true); + this.channel.close(); + } + + @Override + public Channel getChannel() { + return this.channel; + } + + public void ensureConnected() throws IOException { + if (!this.channel.isOpen() || !this.channel.isActive()) { + throw new IOException("[Tars] channel is closed!" + this.channel); + } + + } + + + public CompletableFuture send(Request request) { + TicketFeature ticketFeature = TicketFeature.createFeature(this.channel, request, servantProxyConfig.getSyncTimeout()); + this.channel.writeAndFlush(request); + return ticketFeature.thenCompose(obj -> CompletableFuture.completedFuture((TarsServantResponse) obj)); + + } + +} diff --git a/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyServerChannel.java b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyServerChannel.java new file mode 100644 index 00000000..74e8d8c2 --- /dev/null +++ b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyServerChannel.java @@ -0,0 +1,54 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.qq.tars.rpc.netty; + +import com.qq.tars.client.rpc.ChannelHandler; +import com.qq.tars.server.config.ServantAdapterConfig; +import io.netty.channel.Channel; + +public class NettyServerChannel { + private final Channel channel; + private final ServantAdapterConfig servantProxyConfig; + private final ChannelHandler channelHandler; + + public NettyServerChannel(Channel channel, ServantAdapterConfig servantProxyConfig, ChannelHandler channelHandler) { + this.channel = channel; + this.servantProxyConfig = servantProxyConfig; + this.channelHandler = channelHandler; + + } + + public Channel getChannel() { + return channel; + } + + public ServantAdapterConfig getServantProxyConfig() { + return servantProxyConfig; + } + + public ChannelHandler getChannelHandler() { + return channelHandler; + } + + @Override + public String toString() { + return "NettyTarsChannel{" + + "channel=" + channel + + ", servantProxyConfig=" + servantProxyConfig + + '}'; + } + +} diff --git a/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyServerHandler.java b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyServerHandler.java new file mode 100644 index 00000000..5ff0a831 --- /dev/null +++ b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyServerHandler.java @@ -0,0 +1,141 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.qq.tars.rpc.netty; + +import com.google.common.collect.Maps; +import com.qq.tars.client.rpc.ChannelHandler; +import com.qq.tars.common.util.CommonUtils; +import com.qq.tars.server.config.ServantAdapterConfig; +import io.netty.channel.Channel; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.handler.timeout.IdleStateEvent; +import java.util.logging.Logger; + +import java.net.InetSocketAddress; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Sharable +public class NettyServerHandler extends ChannelDuplexHandler { + private static final Logger logger = Logger.getLogger(NettyServerHandler.class.getName()); + private final Map channels = new ConcurrentHashMap<>(); + private static final Map CHANNEL_MAP = Maps.newConcurrentMap(); + private final ChannelHandler handler; + private final ServantAdapterConfig servantAdapterConfig; + + public Map getChannels() { + return channels; + } + + + public NettyServerHandler(ServantAdapterConfig servantAdapterConfig, ChannelHandler channelHandler) { + this.servantAdapterConfig = servantAdapterConfig; + this.handler = channelHandler; + } + + + static NettyServerChannel getOrAddChannel(Channel ioChannel, ServantAdapterConfig config, ChannelHandler handler) { + if (ioChannel == null) { + return null; + } + NettyServerChannel channel = CHANNEL_MAP.get(ioChannel); + if (channel == null) { + NettyServerChannel nettyChannel = new NettyServerChannel(ioChannel, config, handler); + channel = CHANNEL_MAP.putIfAbsent(ioChannel, nettyChannel); + if (channel == null) { + return nettyChannel; + } + } + return channel; + } + + public static void removeBrokenChannel(Channel channel) { + if (channel != null && !channel.isActive()) { + final NettyServerChannel nettyChannel = CHANNEL_MAP.remove(channel); + if (null != nettyChannel) { + logger.info(" channel " + nettyChannel + " removed"); + } else { + logger.info("the channel " + nettyChannel + " null!"); + } + } + + } + + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + NettyServerChannel channel = getOrAddChannel(ctx.channel(), servantAdapterConfig, handler); + if (channel != null) { + channels.put(CommonUtils.getIPAndPort((InetSocketAddress) ctx.channel().remoteAddress()), channel); + handler.connected(channel.getChannel()); + } + } + + + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + NettyServerChannel channel = getOrAddChannel(ctx.channel(), servantAdapterConfig, handler); + try { + channels.remove(CommonUtils.getIPAndPort((InetSocketAddress) ctx.channel().remoteAddress())); + handler.disconnected(channel.getChannel()); + } finally { + removeBrokenChannel(ctx.channel()); + } + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + NettyServerChannel channel = getOrAddChannel(ctx.channel(), servantAdapterConfig, handler); + handler.received(channel.getChannel(), msg); + } + + + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + super.write(ctx, msg, promise); + NettyServerChannel channel = getOrAddChannel(ctx.channel(), servantAdapterConfig, handler); + handler.send(channel.getChannel(), msg); + } + + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + if (evt instanceof IdleStateEvent) { + NettyServerChannel channel = getOrAddChannel(ctx.channel(), servantAdapterConfig, handler); + try { + channel.getChannel().close(); + } finally { + removeBrokenChannel(ctx.channel()); + } + } + super.userEventTriggered(ctx, evt); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) + throws Exception { + NettyServerChannel channel = getOrAddChannel(ctx.channel(), servantAdapterConfig, handler); + try { + handler.caught(channel.getChannel(), cause); + } finally { + removeBrokenChannel(ctx.channel()); + } + + } +} diff --git a/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyTransporterFactory.java b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyTransporterFactory.java new file mode 100644 index 00000000..ec267a8a --- /dev/null +++ b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyTransporterFactory.java @@ -0,0 +1,147 @@ +package com.qq.tars.rpc.netty; + +import com.qq.tars.client.ServantProxyConfig; +import com.qq.tars.client.rpc.*; +import com.qq.tars.common.util.VirtualThreadSupport; +import com.qq.tars.rpc.common.Url; +import com.qq.tars.rpc.protocol.tars.TarsServantResponse; +import com.qq.tars.server.config.ServantAdapterConfig; +import com.qq.tars.server.core.Processor; +import com.qq.tars.support.log.LoggerFactory; +import io.netty.channel.Channel; + +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * The netty implementation of TransporterFactory. + * Used to connect to a tars server node(client-side) or listen an ip:port(server-side) + * + * @author TimmyYu + * @author kongyuanyuan + */ +public class NettyTransporterFactory implements TransporterFactory { + /** + * Connect with a server node using the given servant config. + * + * @param url server node url + * @param servantProxyConfig servant config + * @return rpc client instance + */ + @Override + public RPCClient connect(Url url, ServantProxyConfig servantProxyConfig) { + return connect(url, servantProxyConfig, new InnerDefaultClientHandler()); + } + + /** + * Connect with a server node using the given servant config and channel handler. + * + * @param url server node url + * @param servantProxyConfig servant config + * @param channelHandler custom channel handler. Can be used in unit tests. + * @return rpc client instance + */ + @Override + public NettyServantClient connect(Url url, ServantProxyConfig servantProxyConfig, ChannelHandler channelHandler) { + return new NettyServantClient(url, servantProxyConfig, channelHandler); + } + + /** + * Get the server instance for transportation which can be used to bind ip/port with {@link TransporterServer#bind()} method. + * + * @param servantAdapterConfig the servant adapter config which is provided by the platform. + * @param processor the request processor. + * @return transporter server instance + * @see com.qq.tars.server.core.Processor + */ + @Override + public TransporterServer getTransporterServer(ServantAdapterConfig servantAdapterConfig, Processor processor) { + return new NettyTransporterServer(servantAdapterConfig, new InnerDefaultServerHandler(processor)); + } + + private static class InnerDefaultClientHandler implements ChannelHandler { + private static final Logger logger = LoggerFactory.getClientLogger(); + + @Override + public void connected(Channel channel) { + + } + + @Override + public void disconnected(Channel channel) { + + } + + @Override + public void send(Channel channel, Object message) { + + } + + @Override + public void received(Channel channel, Object message) { + TarsServantResponse response = (TarsServantResponse) message; + if (logger.isLoggable(Level.FINE)) { + logger.log(Level.FINE, "[tars]netty receive message id is {0}", response.getRequestId()); + } + TicketFeature.getFeature(response.getRequestId()).complete(response); + } + + @Override + public void caught(Channel channel, Throwable exception) { + + } + + @Override + public void destroy() { + + } + } + + private static class InnerDefaultServerHandler implements ChannelHandler { + + public final Processor processor; + + public InnerDefaultServerHandler(Processor processor) { + this.processor = processor; + } + + @Override + public void connected(Channel channel) { + + } + + @Override + public void disconnected(Channel channel) { + + } + + @Override + public void send(Channel channel, Object message) { + + } + + @Override + public void received(Channel channel, Object message) { + Runnable processTask = () -> { + Response response = processor.process((Request) message, channel); + if (!response.isAsyncMode() && channel.isWritable()) { + channel.writeAndFlush(response); + } + }; + boolean executedByVirtualThread = VirtualThreadSupport.executeServerTask(processTask); + if (!executedByVirtualThread) { + processTask.run(); + } + } + + @Override + public void caught(Channel channel, Throwable exception) { + + } + + @Override + public void destroy() { + + } + } +} diff --git a/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyTransporterServer.java b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyTransporterServer.java new file mode 100644 index 00000000..73d2ea4b --- /dev/null +++ b/tars-netty/src/main/java/com/qq/tars/rpc/netty/NettyTransporterServer.java @@ -0,0 +1,185 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.qq.tars.rpc.netty; + +import com.qq.tars.client.rpc.ChannelHandler; +import com.qq.tars.client.rpc.TransporterServer; +import com.qq.tars.common.util.CommonUtils; +import com.qq.tars.common.util.Constants; +import com.qq.tars.common.util.VirtualThreadSupport; +import com.qq.tars.server.config.ServantAdapterConfig; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.PooledByteBufAllocator; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.epoll.Epoll; +import io.netty.channel.epoll.EpollEventLoopGroup; +import io.netty.channel.epoll.EpollServerSocketChannel; +import io.netty.channel.kqueue.KQueue; +import io.netty.channel.kqueue.KQueueEventLoopGroup; +import io.netty.channel.kqueue.KQueueServerSocketChannel; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.timeout.IdleStateHandler; +import io.netty.util.concurrent.DefaultThreadFactory; +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.concurrent.ThreadFactory; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +public class NettyTransporterServer implements TransporterServer { + private static final Logger logger = Logger.getLogger(NettyTransporterServer.class.getName()); + private Map remoteChannels; + private ServerBootstrap bootstrap; + private io.netty.channel.Channel serverChannel; + + private EventLoopGroup bossGroup; + private EventLoopGroup workerGroup; + + private final ServantAdapterConfig servantAdapterConfig; + private final ChannelHandler channelHandler; + + private final InetSocketAddress serverInetSocketAddress; + + public NettyTransporterServer(ServantAdapterConfig servantAdapterConfig, ChannelHandler handler) { + this.servantAdapterConfig = servantAdapterConfig; + this.channelHandler = handler; + this.serverInetSocketAddress = new InetSocketAddress(this.servantAdapterConfig.getEndpoint().host(), + this.servantAdapterConfig.getEndpoint().port()); + } + + public void bind() { + bootstrap = new ServerBootstrap(); + final ThreadFactory threadFactoryBoss = new DefaultThreadFactory("NettyServerBoss", true); + final ThreadFactory threadFactoryWorker = new DefaultThreadFactory("NettyServerWorker", true); + NettyNativeTransportSelector.Transport transport = NettyNativeTransportSelector.current(); + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "[tars] server transport={0}", transport); + if (transport == NettyNativeTransportSelector.Transport.NIO) { + logger.log(Level.INFO, "[tars] fallback to NIO, {0}", NettyNativeTransportSelector.unavailableCause()); + } + if (VirtualThreadSupport.isServerVirtualThreadEnabled()) { + logger.info("[tars] server virtual thread mode enabled"); + } + } + switch (transport) { + case EPOLL: + bossGroup = new EpollEventLoopGroup(2, threadFactoryBoss); + workerGroup = new EpollEventLoopGroup(Constants.DEFAULT_CORE_POOL_SIZE, threadFactoryWorker); + bootstrap.channelFactory(() -> new EpollServerSocketChannel()); + break; + case KQUEUE: + bossGroup = new KQueueEventLoopGroup(2, threadFactoryBoss); + workerGroup = new KQueueEventLoopGroup(Constants.DEFAULT_CORE_POOL_SIZE, threadFactoryWorker); + bootstrap.channelFactory(() -> new KQueueServerSocketChannel()); + break; + default: + bossGroup = new NioEventLoopGroup(2, threadFactoryBoss); + workerGroup = new NioEventLoopGroup(Constants.DEFAULT_CORE_POOL_SIZE, threadFactoryWorker); + bootstrap.channelFactory(() -> new NioServerSocketChannel()); + break; + } + final NettyServerHandler nettyServerHandler = new NettyServerHandler(servantAdapterConfig, channelHandler); + remoteChannels = nettyServerHandler.getChannels(); + bootstrap.group(bossGroup, workerGroup) + .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE) + .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) + .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) throws Exception { + ch.pipeline() + .addLast("decoder", new TarsDecoder(StandardCharsets.UTF_8, Boolean.TRUE)) + .addLast("encoder", new TarsEncoder(StandardCharsets.UTF_8)) + .addLast("server-idle-handler", new IdleStateHandler(0, 0, 3000, MILLISECONDS)) + .addLast("handler", nettyServerHandler); + } + }); + ChannelFuture channelFuture = bootstrap.bind(serverInetSocketAddress); + channelFuture.syncUninterruptibly(); + serverChannel = channelFuture.channel(); + + } + + protected void shutdown() { + try { + if (serverChannel != null) { + serverChannel.close(); + } + } catch (Throwable e) { + logger.log(Level.WARNING, e.getMessage(), e); + } + try { + Collection channels = getChannels(); + if (channels != null && channels.size() > 0) { + for (NettyServerChannel channel : channels) { + try { + channel.getChannel().close(); + } catch (Throwable e) { + logger.log(Level.WARNING, e.getMessage(), e); + } + } + } + } catch (Throwable e) { + logger.log(Level.WARNING, e.getMessage(), e); + } + try { + if (bootstrap != null) { + bossGroup.shutdownGracefully().syncUninterruptibly(); + workerGroup.shutdownGracefully().syncUninterruptibly(); + } + } catch (Throwable e) { + logger.log(Level.WARNING, e.getMessage(), e); + } + } + + @Override + public void stop() { + shutdown(); + } + + public Collection getChannels() { + final Collection chs = new HashSet<>(); + for (NettyServerChannel channel : this.remoteChannels.values()) { + if (channel.getChannel().isActive()) { + chs.add(channel); + } else { + remoteChannels.remove(channel.getChannel().remoteAddress().toString()); + } + } + return chs; + } + + public NettyServerChannel getChannel(InetSocketAddress remoteAddress) { + return remoteChannels.get(CommonUtils.getIPAndPort(remoteAddress)); + } + + public boolean canHandleIdle() { + return true; + } + +} diff --git a/tars-netty/src/main/java/com/qq/tars/rpc/netty/TarsDecoder.java b/tars-netty/src/main/java/com/qq/tars/rpc/netty/TarsDecoder.java new file mode 100644 index 00000000..33b17cd1 --- /dev/null +++ b/tars-netty/src/main/java/com/qq/tars/rpc/netty/TarsDecoder.java @@ -0,0 +1,425 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.qq.tars.rpc.netty; + +import com.google.gson.JsonObject; +import com.qq.tars.client.rpc.ProtocolException; +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; +import com.qq.tars.client.rpc.TicketFeature; +import com.qq.tars.common.support.ClassLoaderManager; +import com.qq.tars.common.support.Holder; +import com.qq.tars.common.util.CollectionUtils; +import com.qq.tars.common.util.Constants; +import com.qq.tars.common.util.JsonProvider; +import com.qq.tars.protocol.tars.TarsInputStream; +import com.qq.tars.protocol.tars.support.TarsMethodInfo; +import com.qq.tars.protocol.tars.support.TarsMethodParameterInfo; +import com.qq.tars.protocol.util.TarsHelper; +import com.qq.tars.protocol.util.TarsUtil; +import com.qq.tars.rpc.protocol.Codec; +import com.qq.tars.rpc.protocol.ServantResponse; +import com.qq.tars.rpc.protocol.tars.TarsServantRequest; +import com.qq.tars.rpc.protocol.tars.TarsServantResponse; +import com.qq.tars.rpc.protocol.tars.support.AnalystManager; +import com.qq.tars.rpc.protocol.tup.UniAttribute; +import io.netty.buffer.ByteBuf; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TarsDecoder extends ByteToMessageDecoder implements Codec { + private static final Logger logger = Logger.getLogger(TarsDecoder.class.getName()); + private boolean isServer = false; + + public TarsDecoder(Charset charsetName, boolean isServer) { + this.charsetName = charsetName; + this.isServer = isServer; + } + + public TarsDecoder(Charset charsetName) { + this.charsetName = charsetName; + this.isServer = false; + } + + public Charset charsetName = Constants.DEFAULT_CHARSET; + + @Override + protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) throws Exception { + do { + int saveReaderIndex = byteBuf.readerIndex(); + + Object msg = null; + if (isServer) { + msg = decodeRequest(byteBuf); + } else { + + msg = decodeResponse(byteBuf); + } + if (msg == null) { + byteBuf.readerIndex(saveReaderIndex); + break; + } else { + //is it possible to go here ? + if (saveReaderIndex == byteBuf.readerIndex()) { + throw new IOException("Decode without read data."); + } + if (msg != null) { + list.add(msg); + } + } + } while (byteBuf.isReadable()); + } + + public Request decodeRequest(ByteBuf buffer) throws ProtocolException { + if (buffer.readableBytes() < TarsHelper.HEAD_SIZE) { + return null; + } + int length = buffer.readInt() - TarsHelper.HEAD_SIZE; + if (length > TarsHelper.PACKAGE_MAX_LENGTH || length <= 0) { + throw new ProtocolException("the length header of the package must be between 0~10M bytes. data length:" + Integer.toHexString(length)); + } + if (buffer.readableBytes() < length) { + return null; + } + TarsInputStream jis = new TarsInputStream(buffer); + TarsServantRequest request = new TarsServantRequest(); + try { + short version = jis.read(TarsHelper.STAMP_SHORT.shortValue(), 1, true); + byte packetType = jis.read(TarsHelper.STAMP_BYTE.byteValue(), 2, true); + int messageType = jis.read(TarsHelper.STAMP_INT.intValue(), 3, true); + int requestId = jis.read(TarsHelper.STAMP_INT.intValue(), 4, true); + String servantName = jis.readString(5, true); + String methodName = jis.readString(6, true); + byte[] data = jis.read(TarsHelper.STAMP_BYTE_ARRAY, 7, true); + int timeout = jis.read(TarsHelper.STAMP_INT.intValue(), 8, true);//超时时间 + Map context = (Map) jis.read(TarsHelper.STAMP_MAP, 9, true);//Map context + Map status = (Map) jis.read(TarsHelper.STAMP_MAP, 10, true); + request.setVersion(version); + request.setPacketType(packetType); + request.setMessageType(messageType); + request.setRequestId(requestId); + request.setServantName(servantName); + request.setFunctionName(methodName); + request.setData(data); + request.setTimeout(timeout); + request.setContext(context); + request.setStatus(status); + request.setInputStream(jis); + request.setCharsetName(charsetName.name()); + logger.log(Level.FINE, "[Decoder][server] decode request is {0}", request); + decodeRequestBody(request); + } catch (Exception e) { + e.printStackTrace(); + System.err.println(e); + request.setRet(TarsHelper.SERVERDECODEERR); + } + return request; + } + + + /*** + * + * @param req + */ + public void decodeRequestBody(Request req) { + TarsServantRequest request = (TarsServantRequest) req; + if (request.getRet() != TarsHelper.SERVERSUCCESS) { + return; + } + if (TarsHelper.isPing(request.getFunctionName())) { + return; + } + + TarsInputStream jis = request.getInputStream(); + ClassLoader oldClassLoader = null; + try { + oldClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(resolveProtocolClassLoader()); + String methodName = request.getFunctionName(); + + String servantName = request.getServantName(); + Map methodInfoMap = AnalystManager.getInstance().getMethodMapByName(servantName); + + if (methodInfoMap == null || methodInfoMap.isEmpty()) { + request.setRet(TarsHelper.SERVERNOSERVANTERR); + throw new ProtocolException("no found methodInfo, the context[ROOT], serviceName[" + servantName + "], methodName[" + methodName + "]"); + } + TarsMethodInfo methodInfo = methodInfoMap.get(methodName); + if (methodInfo == null) { + request.setRet(TarsHelper.SERVERNOFUNCERR); + throw new ProtocolException("no found methodInfo, the context[ROOT], serviceName[" + servantName + "], methodName[" + methodName + "]"); + } + request.setMethodInfo(methodInfo); + List parametersList = methodInfo.getParametersList(); + if (CollectionUtils.isNotEmpty(parametersList)) { + Object[] parameters = new Object[parametersList.size()]; + int i = 0; + if (TarsHelper.VERSION == request.getVersion()) {//request + parameters = decodeRequestBody(request.getData(), methodInfo); + } else if (TarsHelper.VERSION2 == request.getVersion() || TarsHelper.VERSION3 == request.getVersion()) { + parameters = decodeRequestWupBody(request.getData(), request.getVersion(), request.getCharsetName(), methodInfo); + } else if (TarsHelper.VERSIONJSON == request.getVersion()) { + parameters = decodeRequestJsonBody(request.getData(), request.getCharsetName(), methodInfo); + } else { + request.setRet(TarsHelper.SERVERDECODEERR); + System.err.println("un supported protocol, ver=" + request.getVersion()); + } + request.setMethodParameters(parameters); + } + } catch (Throwable ex) { + ex.printStackTrace(); + if (request.getRet() == TarsHelper.SERVERSUCCESS) { + request.setRet(TarsHelper.SERVERDECODEERR); + } + System.err.println(TarsUtil.getHexdump(jis.toByteArray())); + } finally { + if (oldClassLoader != null) { + Thread.currentThread().setContextClassLoader(oldClassLoader); + } + } + return; + } + + protected Object[] decodeRequestBody(byte[] data, TarsMethodInfo methodInfo) throws Exception { + TarsInputStream jis = new TarsInputStream(data); + List parametersList = methodInfo.getParametersList(); + Object[] parameters = new Object[parametersList.size()]; + int i = 0; + jis.setServerEncoding(charsetName);//set decode charset name + Object value = null; + for (TarsMethodParameterInfo parameterInfo : parametersList) { + if (TarsHelper.isHolder(parameterInfo.getAnnotations())) { + value = new Holder<>(jis.read(parameterInfo.getStamp(), parameterInfo.getOrder(), false)); + } else { + value = jis.read(parameterInfo.getStamp(), parameterInfo.getOrder(), false); + } + parameters[i++] = value; + } + return parameters; + } + + public Response decodeResponse(ByteBuf channelBuffer) throws ProtocolException { + + if (channelBuffer.readableBytes() < 4) { + return null; + } + int length = channelBuffer.readInt() - 4; + + if (length > 10 * 1024 * 1024 || length <= 0) { + throw new RuntimeException("the length header of the package must be between 0~10M bytes. data length:" + + Integer.toHexString(length)); + } + if (channelBuffer.readableBytes() < length) { + return null; + } + byte[] bytes = new byte[length]; + channelBuffer.readBytes(bytes); + TarsServantResponse response = new TarsServantResponse(); + response.setCharsetName(charsetName); + TarsInputStream is = new TarsInputStream(bytes); + is.setServerEncoding(charsetName); + response.setVersion(is.read((short) 0, 1, true)); + response.setPacketType(is.read((byte) 0, 2, true)); + response.setRequestId(is.read(0, 3, true)); + response.setMessageType(is.read(0, 4, true)); + response.setRet(is.read(0, 5, true)); + if (response.getRet() == 0) { + response.setInputStream(is); + decodeResponseBody(response); + return response; + } else { + throw new RuntimeException("server error!"); + } + } + + public void decodeResponseBody(ServantResponse resp) throws ProtocolException { + TarsServantResponse response = (TarsServantResponse) resp; + TarsServantRequest request = (TarsServantRequest) TicketFeature.getFeature(resp.getRequestId()).getRequest(); + if (request.isAsync()) { + return; + } + TarsInputStream is = response.getInputStream(); + + byte[] data = is.read(new byte[]{}, 6, true); + TarsInputStream jis = new TarsInputStream(data); + jis.setServerEncoding(response.getCharsetName()); + + TarsMethodInfo methodInfo = request.getMethodInfo(); + TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); + + Object[] results; + try { + results = decodeResponseBody(data, methodInfo); + } catch (Exception e) { + throw new ProtocolException(e); + } + int i = 0; + if (returnInfo != null && Void.TYPE != returnInfo.getType()) { + response.setResult(results[i++]); + } + + List list = methodInfo.getParametersList(); + for (TarsMethodParameterInfo info : list) { + if (!TarsHelper.isHolder(info.getAnnotations())) { + continue; + } + try { + TarsHelper.setHolderValue(request.getMethodParameters()[info.getOrder() - 1], results[i++]); + } catch (Exception e) { + throw new ProtocolException(e); + } + } + response.setStatus((HashMap) is.read(TarsHelper.STAMP_MAP, 7, false)); + } + + protected Object[] decodeResponseBody(byte[] data, TarsMethodInfo methodInfo) throws Exception { + TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); + List values = new ArrayList(); + TarsInputStream jis = new TarsInputStream(data); + jis.setServerEncoding(charsetName); + + if (returnInfo != null && Void.TYPE != returnInfo.getType()) { + values.add(jis.read(returnInfo.getStamp(), returnInfo.getOrder(), true)); + } + List list = methodInfo.getParametersList(); + for (TarsMethodParameterInfo info : list) { + if (!TarsHelper.isHolder(info.getAnnotations())) { + continue; + } + try { + values.add(jis.read(info.getStamp(), info.getOrder(), true)); + } catch (Exception e) { + throw new ProtocolException(e); + } + } + return values.toArray(); + } + + protected ClassLoader resolveProtocolClassLoader() { + ClassLoader classLoader = ClassLoaderManager.getInstance().getClassLoader(""); + if (classLoader == null) { + classLoader = Thread.currentThread().getContextClassLoader(); + } + return classLoader; + } + + @Override + public void encode(Channel channel, ByteBuf channelBuffer, Object message) throws IOException { + + } + + @Override + public Object decode(Channel channel, ByteBuf buffer) throws IOException { + return null; + } + + public String getProtocol() { + return Constants.TARS_PROTOCOL; + } + + @Override + public Charset getCharset() { + return this.charsetName; + } + + protected Object[] decodeRequestWupBody(byte[] data, int version, String charset, + TarsMethodInfo methodInfo) throws Exception { + //wup request + UniAttribute unaIn = new UniAttribute(); + unaIn.setEncodeName(charsetName); + + if (version == TarsHelper.VERSION2) { + unaIn.decodeVersion2(data); + } else if (version == TarsHelper.VERSION3) { + unaIn.decodeVersion3(data); + } + + List parametersList = methodInfo.getParametersList(); + Object[] parameters = new Object[parametersList.size()]; + + int i = 0; + Object value = null; + for (TarsMethodParameterInfo parameterInfo : parametersList) { + if (TarsHelper.isHolder(parameterInfo.getAnnotations())) { + String holderName = TarsHelper.getHolderName(parameterInfo.getAnnotations()); + if (unaIn.containsKey(holderName)) { + value = new Holder<>(unaIn.getByClass(holderName, parameterInfo.getStamp())); + } else { + // new a response + value = new Holder<>(TarsHelper.getNewParameterStamp(parameterInfo.getType())); + } + } else { + value = unaIn.getByClass(parameterInfo.getName(), parameterInfo.getStamp()); + } + parameters[i++] = value; + } + + return parameters; + } + + protected Object[] decodeRequestJsonBody(byte[] data, String charset, + TarsMethodInfo methodInfo) throws Exception { + // 解析json串 + JsonObject jsonObject = JsonProvider.fromJson(new String(data, charset), JsonObject.class); + + // 按字段反序列化 + int i = 0; + Object value = null; + + List parametersList = methodInfo.getParametersList(); + Object[] parameters = new Object[parametersList.size()]; + + for (TarsMethodParameterInfo parameterInfo : parametersList) { + if (TarsHelper.isHolder(parameterInfo.getAnnotations())) { + if (jsonObject.has(parameterInfo.getName())) { + String reqStr = jsonObject.get(parameterInfo.getName()).toString(); + // System.out.println("holder has " + parameterInfo.getName() + ", str: " + reqStr); + value = new Holder<>(JsonProvider.fromJson(reqStr, parameterInfo.getStamp().getClass())); + } else { + // System.out.println("holder has no " + parameterInfo.getName()); + // new response, can not use cache + value = new Holder<>(TarsHelper.getNewParameterStamp(parameterInfo.getType())); + } + } else { + if (jsonObject.has(parameterInfo.getName())) { + String reqStr = jsonObject.get(parameterInfo.getName()).toString(); + // System.out.println("request has " + parameterInfo.getName() + ", str: " + reqStr); + value = JsonProvider.fromJson(reqStr, parameterInfo.getType()); + } else { + System.out.println("request has no " + parameterInfo.getName() + ", exception."); + throw new ProtocolException("no found parameter, the context[ROOT], " + + "serviceName[" + methodInfo.getServiceName() + + "], methodName[" + methodInfo.getMethodName() + + "], parameter[" + parameterInfo.getName() + "]"); + } + } + parameters[i++] = value; + } + + return parameters; + } + +} diff --git a/tars-netty/src/main/java/com/qq/tars/rpc/netty/TarsEncoder.java b/tars-netty/src/main/java/com/qq/tars/rpc/netty/TarsEncoder.java new file mode 100644 index 00000000..6024dacf --- /dev/null +++ b/tars-netty/src/main/java/com/qq/tars/rpc/netty/TarsEncoder.java @@ -0,0 +1,361 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.qq.tars.rpc.netty; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.qq.tars.client.rpc.ProtocolException; +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; +import com.qq.tars.common.util.Constants; +import com.qq.tars.common.util.JsonProvider; +import com.qq.tars.common.util.StringUtils; +import com.qq.tars.protocol.tars.TarsOutputStream; +import com.qq.tars.protocol.tars.support.TarsMethodInfo; +import com.qq.tars.protocol.tars.support.TarsMethodParameterInfo; +import com.qq.tars.protocol.util.TarsHelper; +import com.qq.tars.rpc.protocol.tars.TarsServantRequest; +import com.qq.tars.rpc.protocol.tars.TarsServantResponse; +import com.qq.tars.rpc.protocol.tars.support.AnalystManager; +import com.qq.tars.rpc.protocol.tup.UniAttribute; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.CompositeByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToByteEncoder; +import io.netty.util.ReferenceCountUtil; +import java.util.logging.Level; +import java.util.logging.Logger; + +import java.nio.charset.Charset; +import java.util.List; +import java.util.Map; + +public class TarsEncoder extends MessageToByteEncoder { + private static final Logger logger = Logger.getLogger(TarsEncoder.class.getName()); + protected Charset charset = Constants.DEFAULT_CHARSET; + + public TarsEncoder(Charset charset) { + this.charset = charset; + } + + @Override + protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf out) throws Exception { + ByteBuf ioBuffer = null; + try { + if (o instanceof Request) { + try { + ioBuffer = encodeRequest(channelHandlerContext.alloc(), (TarsServantRequest) o); + if (logger.isLoggable(Level.FINE)) + logger.fine("[tars] write data size is " + ioBuffer.duplicate().getInt(0)); + + int length = ioBuffer.getInt(0); + if (length > ioBuffer.readableBytes()) { + throw new IndexOutOfBoundsException(); + } + out.ensureWritable(ioBuffer.readableBytes()); + out.writeBytes(ioBuffer); + } catch (Exception e) { + logger.log(Level.WARNING, e.getMessage(), e); + } + } else if (o instanceof Response) { + ioBuffer = encodeResponse(channelHandlerContext.alloc(), (Response) o); + if (logger.isLoggable(Level.FINE)) + logger.fine("[tars] write data size is " + ioBuffer.duplicate().getInt(0)); + int length = ioBuffer.getInt(0); + if (length > ioBuffer.readableBytes()) { + throw new IndexOutOfBoundsException(); + } + out.writeBytes(ioBuffer); + } else { + throw new ProtocolException("[tars] cannot support type"); + } + } finally { + if (ioBuffer != null) { + ReferenceCountUtil.release(ioBuffer); + } + } + } + + + public ByteBuf encodeRequest(ByteBufAllocator allocator, Request req) throws ProtocolException { + final TarsServantRequest request = (TarsServantRequest) req; + CompositeByteBuf compositeByteBuf = allocator.compositeBuffer(); + ByteBuf headBuffer = allocator.buffer(); + ByteBuf bodyBuffer = allocator.buffer(); + ByteBuf endBuffer = allocator.buffer(); + int length = 0; + try { + request.setCharsetName(this.charset.name()); + TarsOutputStream os = new TarsOutputStream(headBuffer); + os.setServerEncoding(this.charset); + os.getByteBuffer().writeInt(0); + os.write(request.getVersion(), 1); + os.write(request.getPacketType(), 2); + os.write(request.getMessageType(), 3); + os.write(request.getRequestId(), 4); + os.write(request.getServantName(), 5); + os.write(request.getFunctionName(), 6); + encodeRequestParams(bodyBuffer, request); + os.writBodyeHead(bodyBuffer, 7);// + TarsOutputStream endStream = new TarsOutputStream(endBuffer); + endStream.write(request.getTimeout(), 8); + endStream.write(request.getContext(), 9); + endStream.write(request.getStatus(), 10); + length = os.getByteBuffer().readableBytes() + bodyBuffer.readableBytes() + endStream.getByteBuffer().readableBytes(); + os.getByteBuffer().setInt(0, length); + compositeByteBuf.addComponents(true, headBuffer, bodyBuffer, endBuffer); + + } catch (Exception e) { + //when encode exception + ReferenceCountUtil.release(headBuffer); + ReferenceCountUtil.release(bodyBuffer); + ReferenceCountUtil.release(endBuffer); + if (length > TarsHelper.PACKAGE_MAX_LENGTH || length <= 0) { + throw new ProtocolException("the length header of the package must be between 0~10M bytes. data length:" + Integer.toHexString(length)); + } + } + return compositeByteBuf; + } + + protected void encodeRequestParams(ByteBuf byteBuf, TarsServantRequest request) throws ProtocolException { + TarsOutputStream os = new TarsOutputStream(byteBuf); + os.setServerEncoding(this.charset); + TarsMethodInfo methodInfo = request.getMethodInfo(); + List parameterInfoList = methodInfo.getParametersList(); + Object value = null; + Object[] parameter = request.getMethodParameters(); + for (TarsMethodParameterInfo parameterInfo : parameterInfoList) { + if (TarsHelper.isContext(parameterInfo.getAnnotations()) || TarsHelper.isCallback(parameterInfo.getAnnotations())) { + continue; + } + value = parameter[request.isAsync() ? parameterInfo.getOrder() : parameterInfo.getOrder() - 1]; + if (TarsHelper.isHolder(parameterInfo.getAnnotations()) && value != null) { + try { + value = TarsHelper.getHolderValue(value); + } catch (Exception e) { + throw new ProtocolException(e); + } + if (value != null) { + os.write(value, parameterInfo.getOrder()); + } + } else if (value != null) { + os.write(value, parameterInfo.getOrder()); + } + + } + } + + + public ByteBuf encodeResponse(ByteBufAllocator allocator, Response resp) throws ProtocolException { + TarsServantResponse response = (TarsServantResponse) resp; + if (response.getPacketType() == TarsHelper.ONEWAY) { + return null; + } + CompositeByteBuf compositeByteBuf = allocator.compositeBuffer(); + ByteBuf headBuffer = allocator.buffer(); + ByteBuf bodyBuffer = allocator.buffer(); + ByteBuf endBuffer = allocator.buffer(); + try { + TarsOutputStream jos = new TarsOutputStream(headBuffer); + jos.setServerEncoding(charset); + try { + jos.getByteBuffer().writeInt(0); + jos.write(response.getVersion(), 1); + jos.write(response.getPacketType(), 2); + + if (response.getVersion() == TarsHelper.VERSION) { + jos.write(response.getRequestId(), 3); + jos.write(response.getMessageType(), 4); + jos.write(response.getRet(), 5); + encodeResult(bodyBuffer, response); + jos.writBodyeHead(bodyBuffer, 6); + TarsOutputStream tarsOutputStream = new TarsOutputStream(endBuffer); + if (response.getStatus() != null) { + tarsOutputStream.write(response.getStatus(), 7); + } + if (response.getRet() != TarsHelper.SERVERSUCCESS) { + tarsOutputStream.write(StringUtils.isEmpty(response.getRemark()) ? "" : response.getRemark(), 8); + } + } else if (TarsHelper.VERSION2 == response.getVersion() || TarsHelper.VERSION3 == response.getVersion()) { + jos.write(response.getMessageType(), 3); + jos.write(response.getRequestId(), 4); + String servantName = response.getRequest().getServantName(); + jos.write(servantName, 5); + jos.write(response.getRequest().getFunctionName(), 6); + jos.write(encodeWupResult(response), 7); + jos.write(response.getTimeout(), 8); + if (response.getContext() != null) { + jos.write(response.getContext(), 9); + } + if (response.getStatus() != null) { + jos.write(response.getStatus(), 10); + } + } else if (response.getVersion() == TarsHelper.VERSIONJSON) { + jos.write(response.getRequestId(), 3); + jos.write(response.getMessageType(), 4); + jos.write(response.getRet(), 5); + jos.write(encodeJsonResult(response), 6); + if (response.getStatus() != null) { + jos.write(response.getStatus(), 7); + } + if (response.getRet() != TarsHelper.SERVERSUCCESS) { + jos.write(StringUtils.isEmpty(response.getRemark()) ? "" : response.getRemark(), 8); + } + } else { + response.setRet(TarsHelper.SERVERENCODEERR); + System.err.println("un supported protocol, ver=" + response.getVersion()); + } + } catch (Exception ex) { + if (response.getRet() == TarsHelper.SERVERSUCCESS) { + response.setRet(TarsHelper.SERVERENCODEERR); + } + } + final int dataLength = headBuffer.readableBytes() + bodyBuffer.readableBytes() + endBuffer.readableBytes(); + headBuffer.setInt(0, dataLength);//write real data length + compositeByteBuf.addComponents(true, headBuffer, bodyBuffer, endBuffer); + } catch (Exception e) { + //when encode exception + ReferenceCountUtil.release(headBuffer); + ReferenceCountUtil.release(bodyBuffer); + ReferenceCountUtil.release(endBuffer); + System.err.println("un supported protocol, ver=" + response.getVersion()); + } + return compositeByteBuf; + } + + protected void encodeResult(ByteBuf bytebuf, TarsServantResponse response) { + TarsServantRequest request = (TarsServantRequest) response.getRequest(); + if (TarsHelper.isPing(request.getFunctionName())) { + return; + } + TarsOutputStream ajos = new TarsOutputStream(bytebuf); + ajos.setServerEncoding(charset); + int ret = response.getRet(); + Map methodInfoMap = AnalystManager.getInstance().getMethodMapByName(request.getServantName()); + if (ret == TarsHelper.SERVERSUCCESS && methodInfoMap != null) { + TarsMethodInfo methodInfo = methodInfoMap.get(request.getFunctionName()); + TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); + if (returnInfo != null && returnInfo.getType() != Void.TYPE && response.getResult() != null) { + try { + ajos.write(response.getResult(), methodInfo.getReturnInfo().getOrder()); + } catch (Exception e) { + System.err.println("server encodec response result:" + response.getResult() + " with ex:" + e); + } + } + + Object value = null; + List parametersList = methodInfo.getParametersList(); + for (TarsMethodParameterInfo parameterInfo : parametersList) { + if (TarsHelper.isHolder(parameterInfo.getAnnotations())) { + value = request.getMethodParameters()[parameterInfo.getOrder() - 1]; + if (value != null) { + try { + ajos.write(TarsHelper.getHolderValue(value), parameterInfo.getOrder()); + } catch (Exception e) { + System.err.println("server encodec response holder:" + value + " with ex:" + e); + } + } + } + } + } + } + + protected byte[] encodeWupResult(TarsServantResponse response) { + TarsServantRequest request = (TarsServantRequest) response.getRequest(); + UniAttribute unaOut = new UniAttribute(); + unaOut.setEncodeName(charset); + if (response.getVersion() == TarsHelper.VERSION3) { + unaOut.useVersion3(); + } else if (response.getVersion() == TarsHelper.VERSION2) { + unaOut.setNewDataNull(); + } + + int ret = response.getRet(); + Map methodInfoMap = AnalystManager.getInstance().getMethodMapByName(request.getServantName()); + if (ret == TarsHelper.SERVERSUCCESS && methodInfoMap != null) { + TarsMethodInfo methodInfo = methodInfoMap.get(request.getFunctionName()); + TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); + if (returnInfo != null && returnInfo.getType() != Void.TYPE && response.getResult() != null) { + unaOut.put(TarsHelper.STAMP_STRING, response.getResult()); + } + + Object value = null; + List parametersList = methodInfo.getParametersList(); + for (TarsMethodParameterInfo parameterInfo : parametersList) { + if (TarsHelper.isHolder(parameterInfo.getAnnotations())) { + value = request.getMethodParameters()[parameterInfo.getOrder() - 1]; + if (value != null) { + try { + String holderName = TarsHelper.getHolderName(parameterInfo.getAnnotations()); + if (!StringUtils.isEmpty(holderName)) { + unaOut.put(holderName, TarsHelper.getHolderValue(value)); + } + } catch (Exception e) { + System.err.println("server encodec response holder:" + value + " with ex:" + e); + } + } + } + } + } + return unaOut.encode(); + } + + protected byte[] encodeJsonResult(TarsServantResponse response) { + TarsServantRequest request = (TarsServantRequest) response.getRequest(); + if (TarsHelper.isPing(request.getFunctionName())) { + return new byte[]{}; + } + JsonObject object = new JsonObject(); + int ret = response.getRet(); + Map methodInfoMap = AnalystManager.getInstance().getMethodMapByName(request.getServantName()); + if (ret == TarsHelper.SERVERSUCCESS && methodInfoMap != null) { + TarsMethodInfo methodInfo = methodInfoMap.get(request.getFunctionName()); + TarsMethodParameterInfo returnInfo = methodInfo.getReturnInfo(); + if (returnInfo != null && returnInfo.getType() != Void.TYPE && response.getResult() != null) { + try { + JsonElement jsonElement = JsonProvider.toJsonTree(response.getResult()); + // System.out.println("requestId: " + request.getRequestId() + ", charset: " + request.getCharsetName() + ", ret: " + jsonElement.toString()); + object.add("tars_ret", jsonElement); + } catch (Exception e) { + System.err.println("server encode json ret :" + response.getResult() + ", with ex:" + e); + } + } + Object value = null; + List parametersList = methodInfo.getParametersList(); + for (TarsMethodParameterInfo parameterInfo : parametersList) { + if (TarsHelper.isHolder(parameterInfo.getAnnotations())) { + value = request.getMethodParameters()[parameterInfo.getOrder() - 1]; + if (value != null) { + try { + JsonElement jsonElement = JsonProvider.toJsonTree(TarsHelper.getHolderValue(value)); + object.add(parameterInfo.getName(), jsonElement); + } catch (Exception e) { + System.err.println("server encode json holder :" + value + ", with ex:" + e); + } + } + } + } + } + String result = object.toString(); + return result.getBytes(charset); + } + +} + + + + diff --git a/tars-netty/src/main/resources/META-INF/services/com.qq.tars.client.rpc.TransporterFactory b/tars-netty/src/main/resources/META-INF/services/com.qq.tars.client.rpc.TransporterFactory new file mode 100644 index 00000000..9b779d9c --- /dev/null +++ b/tars-netty/src/main/resources/META-INF/services/com.qq.tars.client.rpc.TransporterFactory @@ -0,0 +1 @@ +com.qq.tars.rpc.netty.NettyTransporterFactory \ No newline at end of file diff --git a/tars-netty/src/test/java/com/qq/tars/rpc/netty/NettyDependencyVersionTest.java b/tars-netty/src/test/java/com/qq/tars/rpc/netty/NettyDependencyVersionTest.java new file mode 100644 index 00000000..b95fd710 --- /dev/null +++ b/tars-netty/src/test/java/com/qq/tars/rpc/netty/NettyDependencyVersionTest.java @@ -0,0 +1,22 @@ +package com.qq.tars.rpc.netty; + +import io.netty.util.Version; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Map; + +public class NettyDependencyVersionTest { + + @Test + public void testNettyRuntimeVersion() { + Map versions = Version.identify(); + Assert.assertFalse(versions.isEmpty()); + + boolean hasExpectedVersion = versions.values().stream() + .map(Version::artifactVersion) + .anyMatch(version -> version.startsWith("4.2.10")); + + Assert.assertTrue("expected netty 4.2.10 on classpath", hasExpectedVersion); + } +} diff --git a/tars-netty/src/test/java/com/qq/tars/rpc/netty/NettyNativeTransportSelectorTest.java b/tars-netty/src/test/java/com/qq/tars/rpc/netty/NettyNativeTransportSelectorTest.java new file mode 100644 index 00000000..14aa672a --- /dev/null +++ b/tars-netty/src/test/java/com/qq/tars/rpc/netty/NettyNativeTransportSelectorTest.java @@ -0,0 +1,41 @@ +package com.qq.tars.rpc.netty; + +import io.netty.channel.epoll.Epoll; +import io.netty.channel.kqueue.KQueue; +import org.junit.Assert; +import org.junit.Test; + +public class NettyNativeTransportSelectorTest { + + @Test + public void testSelectEpollFirst() { + Assert.assertEquals(NettyNativeTransportSelector.Transport.EPOLL, + NettyNativeTransportSelector.select(true, true)); + Assert.assertEquals(NettyNativeTransportSelector.Transport.EPOLL, + NettyNativeTransportSelector.select(true, false)); + } + + @Test + public void testSelectKQueueWhenEpollUnavailable() { + Assert.assertEquals(NettyNativeTransportSelector.Transport.KQUEUE, + NettyNativeTransportSelector.select(false, true)); + } + + @Test + public void testSelectNioFallback() { + Assert.assertEquals(NettyNativeTransportSelector.Transport.NIO, + NettyNativeTransportSelector.select(false, false)); + } + + @Test + public void testCurrentTransportShouldMatchRuntimeAvailability() { + NettyNativeTransportSelector.Transport expected = NettyNativeTransportSelector.select( + Epoll.isAvailable(), KQueue.isAvailable()); + NettyNativeTransportSelector.Transport current = NettyNativeTransportSelector.current(); + Assert.assertEquals(expected, current); + if (current == NettyNativeTransportSelector.Transport.NIO) { + Assert.assertNotNull(NettyNativeTransportSelector.unavailableCause()); + Assert.assertFalse(NettyNativeTransportSelector.unavailableCause().isEmpty()); + } + } +} diff --git a/tars-netty/src/test/java/com/qq/tars/rpc/netty/NettyTransporterFactoryVirtualThreadTest.java b/tars-netty/src/test/java/com/qq/tars/rpc/netty/NettyTransporterFactoryVirtualThreadTest.java new file mode 100644 index 00000000..650c6bdf --- /dev/null +++ b/tars-netty/src/test/java/com/qq/tars/rpc/netty/NettyTransporterFactoryVirtualThreadTest.java @@ -0,0 +1,170 @@ +package com.qq.tars.rpc.netty; + +import com.qq.tars.client.rpc.ChannelHandler; +import com.qq.tars.client.rpc.Request; +import com.qq.tars.client.rpc.Response; +import com.qq.tars.client.rpc.TransporterServer; +import com.qq.tars.common.support.Endpoint; +import com.qq.tars.common.util.VirtualThreadSupport; +import com.qq.tars.rpc.protocol.tars.TarsServantResponse; +import com.qq.tars.server.config.ServantAdapterConfig; +import com.qq.tars.server.core.Processor; +import io.netty.channel.embedded.EmbeddedChannel; +import org.junit.Assert; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +public class NettyTransporterFactoryVirtualThreadTest { + + @Test + public void testReceivedRunsInCallerThreadWhenVirtualThreadDisabled() throws Exception { + String oldGlobal = System.getProperty(VirtualThreadSupport.VTHREAD_ENABLED_KEY); + String oldServer = System.getProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY); + try { + System.clearProperty(VirtualThreadSupport.VTHREAD_ENABLED_KEY); + System.clearProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY); + + AtomicReference executedThread = new AtomicReference<>(); + CountDownLatch latch = new CountDownLatch(1); + ChannelHandler handler = createServerHandler(createProcessor(executedThread, latch)); + EmbeddedChannel channel = new EmbeddedChannel(); + Thread callerThread = Thread.currentThread(); + + handler.received(channel, new DummyRequest(10086)); + + Assert.assertTrue(latch.await(2, TimeUnit.SECONDS)); + Assert.assertSame(callerThread, executedThread.get()); + Assert.assertTrue(waitOutbound(channel, 1000) instanceof Response); + channel.finishAndReleaseAll(); + } finally { + restoreProperty(VirtualThreadSupport.VTHREAD_ENABLED_KEY, oldGlobal); + restoreProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY, oldServer); + } + } + + @Test + public void testReceivedCanRunOnVirtualThreadWhenEnabled() throws Exception { + String oldGlobal = System.getProperty(VirtualThreadSupport.VTHREAD_ENABLED_KEY); + String oldServer = System.getProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY); + try { + System.setProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY, "true"); + + AtomicReference executedThread = new AtomicReference<>(); + CountDownLatch latch = new CountDownLatch(1); + ChannelHandler handler = createServerHandler(createProcessor(executedThread, latch)); + EmbeddedChannel channel = new EmbeddedChannel(); + Thread callerThread = Thread.currentThread(); + + handler.received(channel, new DummyRequest(10010)); + + Assert.assertTrue(latch.await(2, TimeUnit.SECONDS)); + if (VirtualThreadSupport.isVirtualThreadSupported()) { + Assert.assertNotSame(callerThread, executedThread.get()); + Assert.assertTrue(isVirtualThread(executedThread.get())); + } else { + Assert.assertSame(callerThread, executedThread.get()); + } + Assert.assertTrue(waitOutbound(channel, 1000) instanceof Response); + channel.finishAndReleaseAll(); + } finally { + restoreProperty(VirtualThreadSupport.VTHREAD_ENABLED_KEY, oldGlobal); + restoreProperty(VirtualThreadSupport.SERVER_VTHREAD_ENABLED_KEY, oldServer); + } + } + + private static Processor createProcessor(AtomicReference executedThread, CountDownLatch latch) { + return new Processor() { + @Override + public Response process(Request request, io.netty.channel.Channel clientChannel) { + executedThread.set(Thread.currentThread()); + latch.countDown(); + return new TarsServantResponse(request.getRequestId()); + } + + @Override + public void overload(Request request, io.netty.channel.Channel clientChannel) { + } + }; + } + + private static ChannelHandler createServerHandler(Processor processor) throws Exception { + ServantAdapterConfig config = ServantAdapterConfig.makeServantAdapterConfig( + Endpoint.parseString("tcp -h 127.0.0.1 -p 18601 -t 60000"), + "TestApp.TestServer.TestObj", null); + TransporterServer transporterServer = new NettyTransporterFactory().getTransporterServer(config, processor); + Field channelHandlerField = NettyTransporterServer.class.getDeclaredField("channelHandler"); + channelHandlerField.setAccessible(true); + return (ChannelHandler) channelHandlerField.get(transporterServer); + } + + private static Object waitOutbound(EmbeddedChannel channel, long timeoutMillis) throws InterruptedException { + long deadline = System.currentTimeMillis() + timeoutMillis; + Object outbound = channel.readOutbound(); + while (outbound == null && System.currentTimeMillis() < deadline) { + Thread.sleep(10); + outbound = channel.readOutbound(); + } + return outbound; + } + + private static boolean isVirtualThread(Thread thread) throws Exception { + if (thread == null) { + return false; + } + Method method = Thread.class.getMethod("isVirtual"); + return (Boolean) method.invoke(thread); + } + + private static void restoreProperty(String key, String value) { + if (value == null) { + System.clearProperty(key); + } else { + System.setProperty(key, value); + } + } + + private static class DummyRequest implements Request { + private final int requestId; + + private DummyRequest(int requestId) { + this.requestId = requestId; + } + + @Override + public int getRequestId() { + return requestId; + } + + @Override + public String getServantName() { + return "TestApp.TestServer.TestObj"; + } + + @Override + public String getFunctionName() { + return "test"; + } + + @Override + public Map getDistributedContext() { + return Collections.emptyMap(); + } + + @Override + public long getProcessTime() { + return 0; + } + + @Override + public long getBornTime() { + return System.currentTimeMillis(); + } + } +} diff --git a/tars-plugins/build.gradle.kts b/tars-plugins/build.gradle.kts new file mode 100644 index 00000000..9d65aa55 --- /dev/null +++ b/tars-plugins/build.gradle.kts @@ -0,0 +1,14 @@ +plugins { + `java-library` +} + +description = "Tars Plugins - Plugin System for Tars" + +dependencies { + api(project(":tars-core")) + + compileOnly(libs.logback.classic) + + testImplementation(libs.junit) + testImplementation(libs.hamcrest.all) +} diff --git a/tars-plugins/src/main/java/com/tencent/logback/logserver/TarsLoggerServerAppender.java b/tars-plugins/src/main/java/com/tencent/logback/logserver/TarsLoggerServerAppender.java new file mode 100644 index 00000000..fa9d4504 --- /dev/null +++ b/tars-plugins/src/main/java/com/tencent/logback/logserver/TarsLoggerServerAppender.java @@ -0,0 +1,172 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.tencent.logback.logserver; + +import ch.qos.logback.core.Appender; +import ch.qos.logback.core.spi.AppenderAttachableImpl; +import com.qq.tars.client.CommunicatorConfig; +import com.qq.tars.client.CommunicatorFactory; +import com.qq.tars.support.log.prx.LogInfo; +import com.qq.tars.support.log.prx.LogPrx; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedQueue; + +public class TarsLoggerServerAppender extends TarsLoggerServerAppenderConfig { + private final AppenderAttachableImpl aai = new AppenderAttachableImpl<>(); + private final ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); + private LoggerServer loggerServer = null; + + public TarsLoggerServerAppender() { + } + + + @Override + public void doAppend(E e) { + ensureDeferredAppends(); + super.doAppend(e); + } + + @Override + public void start() { + if (!checkPrerequisites()) return; + + if (partition != null && partition < 0) { + partition = null; + } + + this.loggerServer = new LoggerServer(); + super.start(); + } + + @Override + public void stop() { + super.stop(); + } + + @Override + public void addAppender(Appender newAppender) { + aai.addAppender(newAppender); + } + + @Override + public Iterator> iteratorForAppenders() { + return aai.iteratorForAppenders(); + } + + @Override + public Appender getAppender(String name) { + return aai.getAppender(name); + } + + @Override + public boolean isAttached(Appender appender) { + return aai.isAttached(appender); + } + + @Override + public void detachAndStopAllAppenders() { + aai.detachAndStopAllAppenders(); + } + + @Override + public boolean detachAppender(Appender appender) { + return aai.detachAppender(appender); + } + + @Override + public boolean detachAppender(String name) { + return aai.detachAppender(name); + } + + + private LogInfo getLogInfo() { + final LogInfo loginfo = new LogInfo(); + loginfo.setAppname(getAppName()); + loginfo.setServername(getServiceName()); + loginfo.setSFilename(this.name); + loginfo.setSFormat("%Y%m%d%H"); + return loginfo; + } + + @Override + protected void append(E e) { + final byte[] payload = encoder.encode(e); + final LogPrx logPrx = loggerServer.get(); + if (logPrx != null) { + final List record = new ArrayList<>(1); + record.add(new String(payload, StandardCharsets.UTF_8) + "\n"); + try { + logPrx.promise_loggerbyInfo(getLogInfo(), record); + } catch (Exception e1) { + + e1.printStackTrace(); + } + } + } + + private void deferAppend(E event) { + queue.add(event); + } + + // drains queue events to super + private void ensureDeferredAppends() { + E event; + + while ((event = queue.poll()) != null) { + super.doAppend(event); + } + } + + /** + * Lazy initializer for producer, patterned after commons-lang. + * @see LazyInitializer + */ + private class LoggerServer { + + private volatile LogPrx logPrx = null; + + public LogPrx get() { + LogPrx result = this.logPrx; + if (result == null) { + synchronized (this) { + result = this.logPrx; + if (result == null) { + result = this.initialize(); + this.logPrx = result; + } + } + } + + return result; + } + + protected LogPrx initialize() { + try { + CommunicatorConfig communicatorConfig = new CommunicatorConfig(); + return CommunicatorFactory.getInstance().getCommunicator(communicatorConfig).stringToProxy(LogPrx.class, logserverObjname); + } catch (Exception e) { + e.printStackTrace(); + addError("error creating producer", e); + } + return null; + } + } + +} diff --git a/tars-plugins/src/main/java/com/tencent/logback/logserver/TarsLoggerServerAppenderConfig.java b/tars-plugins/src/main/java/com/tencent/logback/logserver/TarsLoggerServerAppenderConfig.java new file mode 100644 index 00000000..4a8b79f1 --- /dev/null +++ b/tars-plugins/src/main/java/com/tencent/logback/logserver/TarsLoggerServerAppenderConfig.java @@ -0,0 +1,79 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.tencent.logback.logserver; + +import ch.qos.logback.core.UnsynchronizedAppenderBase; +import ch.qos.logback.core.encoder.Encoder; +import ch.qos.logback.core.spi.AppenderAttachable; + +public abstract class TarsLoggerServerAppenderConfig extends UnsynchronizedAppenderBase implements AppenderAttachable { + protected Encoder encoder = null; + protected Integer partition = null; + protected boolean appendTimestamp = true; + protected String logserverObjname = null; + protected String appName = null; + protected String serviceName = null; + + public String getLogserverObjname() { + return logserverObjname; + } + + public void setLogserverObjname(String logserverObjname) { + this.logserverObjname = logserverObjname; + } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + protected boolean checkPrerequisites() { + boolean errorFree = true; + if (encoder == null) { + addError("No encoder set for the appender named [\"" + name + "\"]."); + errorFree = false; + } + return errorFree; + } + + public void setEncoder(Encoder encoder) { + this.encoder = encoder; + } + + public void setPartition(Integer partition) { + this.partition = partition; + } + + public boolean isAppendTimestamp() { + return appendTimestamp; + } + + public void setAppendTimestamp(boolean appendTimestamp) { + this.appendTimestamp = appendTimestamp; + } + +} diff --git a/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/ContextNameKeyingStrategy.java b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/ContextNameKeyingStrategy.java new file mode 100644 index 00000000..1ff21840 --- /dev/null +++ b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/ContextNameKeyingStrategy.java @@ -0,0 +1,44 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.tencent.logback.logserver.keying; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.Context; +import ch.qos.logback.core.CoreConstants; +import ch.qos.logback.core.spi.ContextAwareBase; + +import java.nio.ByteBuffer; + +public class ContextNameKeyingStrategy extends ContextAwareBase implements KeyingStrategy { + + private byte[] contextNameHash = null; + + @Override + public void setContext(Context context) { + super.setContext(context); + final String hostname = context.getProperty(CoreConstants.CONTEXT_NAME_KEY); + if (hostname == null) { + addError("Hostname could not be found in context. HostNamePartitioningStrategy will not work."); + } else { + contextNameHash = ByteBuffer.allocate(4).putInt(hostname.hashCode()).array(); + } + } + + @Override + public byte[] createKey(ILoggingEvent e) { + return contextNameHash; + } +} diff --git a/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/HostNameKeyingStrategy.java b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/HostNameKeyingStrategy.java new file mode 100644 index 00000000..76df093b --- /dev/null +++ b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/HostNameKeyingStrategy.java @@ -0,0 +1,59 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.tencent.logback.logserver.keying; + +import ch.qos.logback.core.Context; +import ch.qos.logback.core.CoreConstants; +import ch.qos.logback.core.spi.ContextAwareBase; + +import ch.qos.logback.core.spi.LifeCycle; +import java.nio.ByteBuffer; + +public class HostNameKeyingStrategy extends ContextAwareBase implements KeyingStrategy, LifeCycle { + + private byte[] hostnameHash = null; + private boolean errorWasShown = false; + + @Override + public void setContext(Context context) { + super.setContext(context); + final String hostname = context.getProperty(CoreConstants.HOSTNAME_KEY); + if (hostname == null) { + if (!errorWasShown) { + addError("Hostname could not be found in context. HostNamePartitioningStrategy will not work."); + errorWasShown = true; + } + } else { + hostnameHash = ByteBuffer.allocate(4).putInt(hostname.hashCode()).array(); + } + } + + @Override + public byte[] createKey(Object e) { + return hostnameHash; + } + + @Override + public void start() { } + + @Override + public void stop() { + errorWasShown = false; + } + + @Override + public boolean isStarted() { return true; } +} diff --git a/net/src/main/java/com/qq/tars/net/core/Processor.java b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/KeyingStrategy.java similarity index 84% rename from net/src/main/java/com/qq/tars/net/core/Processor.java rename to tars-plugins/src/main/java/com/tencent/logback/logserver/keying/KeyingStrategy.java index a2601a92..7fcc3d36 100644 --- a/net/src/main/java/com/qq/tars/net/core/Processor.java +++ b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/KeyingStrategy.java @@ -13,10 +13,11 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ +package com.tencent.logback.logserver.keying; -package com.qq.tars.net.core; -public abstract class Processor { +public interface KeyingStrategy { + + byte[] createKey(E e); - public abstract Response process(Request request, Session session); } diff --git a/core/src/main/java/com/qq/tars/client/util/ClientLogger.java b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/LoggerNameKeyingStrategy.java similarity index 59% rename from core/src/main/java/com/qq/tars/client/util/ClientLogger.java rename to tars-plugins/src/main/java/com/tencent/logback/logserver/keying/LoggerNameKeyingStrategy.java index 8a209797..b2df99a0 100644 --- a/core/src/main/java/com/qq/tars/client/util/ClientLogger.java +++ b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/LoggerNameKeyingStrategy.java @@ -13,24 +13,23 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ +package com.tencent.logback.logserver.keying; -package com.qq.tars.client.util; +import ch.qos.logback.classic.spi.ILoggingEvent; -import com.qq.tars.support.log.Logger; -import com.qq.tars.support.log.LoggerFactory; +import java.nio.ByteBuffer; -public final class ClientLogger { +public class LoggerNameKeyingStrategy implements KeyingStrategy { - private static final String CLIENT_LOG_NAME = "tars_client.log"; - - public static void init(String logPath, String logLevel) { - if (logLevel == null) { - logLevel = "INFO"; + @Override + public byte[] createKey(ILoggingEvent e) { + final String loggerName; + if (e.getLoggerName() == null) { + loggerName = ""; + } else { + loggerName = e.getLoggerName(); } - LoggerFactory.config(logLevel, logPath); + return ByteBuffer.allocate(4).putInt(loggerName.hashCode()).array(); } - public static Logger getLogger() { - return Logger.getLogger(CLIENT_LOG_NAME); - } } diff --git a/net/src/main/java/com/qq/tars/net/client/ticket/TicketListener.java b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/NoKeyKeyingStrategy.java similarity index 78% rename from net/src/main/java/com/qq/tars/net/client/ticket/TicketListener.java rename to tars-plugins/src/main/java/com/tencent/logback/logserver/keying/NoKeyKeyingStrategy.java index 6cd1d447..45abb30d 100644 --- a/net/src/main/java/com/qq/tars/net/client/ticket/TicketListener.java +++ b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/NoKeyKeyingStrategy.java @@ -13,12 +13,12 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ +package com.tencent.logback.logserver.keying; -package com.qq.tars.net.client.ticket; +public class NoKeyKeyingStrategy implements KeyingStrategy { -public interface TicketListener { - - public void onResponseExpired(Ticket ticket); - - public void onResponseReceived(Ticket ticket); + @Override + public byte[] createKey(Object e) { + return null; + } } diff --git a/core/src/main/java/com/qq/tars/support/om/OmLogger.java b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/ThreadNameKeyingStrategy.java similarity index 67% rename from core/src/main/java/com/qq/tars/support/om/OmLogger.java rename to tars-plugins/src/main/java/com/tencent/logback/logserver/keying/ThreadNameKeyingStrategy.java index 5f006cf8..d8c849e3 100644 --- a/core/src/main/java/com/qq/tars/support/om/OmLogger.java +++ b/tars-plugins/src/main/java/com/tencent/logback/logserver/keying/ThreadNameKeyingStrategy.java @@ -13,21 +13,16 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ +package com.tencent.logback.logserver.keying; -package com.qq.tars.support.om; +import ch.qos.logback.classic.spi.ILoggingEvent; -import com.qq.tars.support.log.Logger; +import java.nio.ByteBuffer; -public class OmLogger { +public class ThreadNameKeyingStrategy implements KeyingStrategy { - private static final Logger LOGGER = Logger.getLogger("tars_om_client.log"); - - public static void record(String str, Throwable t) { - LOGGER.error(str, t); - } - - public static void record(String str) { - LOGGER.info(str); + @Override + public byte[] createKey(ILoggingEvent e) { + return ByteBuffer.allocate(4).putInt(e.getThreadName().hashCode()).array(); } - } diff --git a/tars-plugins/src/main/resources/logback.xml b/tars-plugins/src/main/resources/logback.xml new file mode 100644 index 00000000..71a4ab15 --- /dev/null +++ b/tars-plugins/src/main/resources/logback.xml @@ -0,0 +1,25 @@ + + + + + %msg + + + tars.tarslog.LogObj@tcp -h 10.172.0.111 -t 3000 -p 18993 + test + hello + + + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + diff --git a/tools/README.md b/tools/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/tools/pom.xml b/tools/pom.xml deleted file mode 100644 index 291bb10a..00000000 --- a/tools/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - 4.0.0 - - com.tencent.tars - tars-parent - 1.6.1 - - tars-tools - ${project.artifactId} - pom - - - tars-maven-plugin - - - - - junit - junit - 3.8.1 - test - - - \ No newline at end of file diff --git a/tools/tars-maven-plugin/README.md b/tools/tars-maven-plugin/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/tools/tars-maven-plugin/pom.xml b/tools/tars-maven-plugin/pom.xml deleted file mode 100644 index cff2f20c..00000000 --- a/tools/tars-maven-plugin/pom.xml +++ /dev/null @@ -1,219 +0,0 @@ - - - 4.0.0 - - com.tencent.tars - tars-tools - 1.6.1 - - tars-maven-plugin - ${project.artifactId} - maven-plugin - - - 2.2.1 - 3.2 - - - - - org.apache.maven - maven-plugin-api - ${maven_version} - - - org.apache.maven - maven-project - ${maven_version} - - - org.apache.maven - maven-artifact - ${maven_version} - - - org.apache.maven - maven-model - ${maven_version} - - - org.apache.maven - maven-core - ${maven_version} - - - org.slf4j - slf4j-jdk14 - - - org.slf4j - slf4j-nop - - - - - org.apache.maven - maven-plugin-parameter-documenter - ${maven_version} - - - org.apache.maven - maven-repository-metadata - ${maven_version} - - - org.apache.maven - maven-error-diagnostics - ${maven_version} - - - org.apache.maven - maven-plugin-descriptor - ${maven_version} - - - org.apache.maven - maven-monitor - ${maven_version} - - - org.apache.maven - maven-settings - ${maven_version} - - - org.apache.maven - maven-archiver - 2.4.2 - - - org.apache.maven.plugin-tools - maven-plugin-annotations - ${maven_plugin_version} - provided - - - - org.apache.maven.shared - maven-filtering - 1.3 - - - org.apache.maven.shared - maven-mapping - 1.0 - - - org.apache.maven.shared - maven-dependency-tree - 2.2 - - - - org.antlr - antlr - 3.5 - - - - org.codehaus.plexus - plexus-utils - 3.0.20 - - - org.codehaus.plexus - plexus-interpolation - 1.21 - - - - commons-codec - commons-codec - 1.6 - - - commons-io - commons-io - 2.2 - - - commons-lang - commons-lang - 2.6 - - - commons-cli - commons-cli - 1.2 - - - org.apache.commons - commons-compress - 1.4.1 - - - - - - - org.apache.maven.plugins - maven-plugin-plugin - ${maven_plugin_version} - - tars - true - - - - mojo-descriptor - - descriptor - - - - - - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-plugin-plugin - - - [3.2,) - - - descriptor - - - - - - - - - - - - - - diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/Servant.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/Servant.java deleted file mode 100644 index 08075b43..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/Servant.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.gensrc; - -public class Servant { - - private String name; - private String port; - private String protocol; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getPort() { - return port; - } - - public void setPort(String port) { - this.port = port; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/Tars2JavaConfig.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/Tars2JavaConfig.java deleted file mode 100644 index 93d47aef..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/Tars2JavaConfig.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.gensrc; - -import org.apache.maven.plugins.annotations.Parameter; - -public class Tars2JavaConfig { - - @Parameter(defaultValue = "${basedir}/src/main/java", required = true) - public String srcPath; - - @Parameter(required = true) - public String[] tarsFiles; - - @Parameter(defaultValue = "UTF-8", required = true) - public String tarsFileCharset; - - @Parameter(defaultValue = "UTF-8") - public String charset; - - @Parameter(defaultValue = "", required = true) - public String packagePrefixName; - -// @Parameter -// public boolean forceArray; - - @Parameter - public boolean checkDefault; - - @Parameter - public boolean servant; - - @Parameter - public boolean tup; - - public String getSrcPath() { - return srcPath; - } - - public void setSrcPath(String srcPath) { - this.srcPath = srcPath; - } - - public String[] getTafFiles() { - return tarsFiles; - } - - public void setTafFiles(String[] tarsFiles) { - this.tarsFiles = tarsFiles; - } - - public String getTafFileCharset() { - return tarsFileCharset; - } - - public void setTafFileCharset(String tarsFileCharset) { - this.tarsFileCharset = tarsFileCharset; - } - - public String getCharset() { - return charset; - } - - public void setCharset(String charset) { - this.charset = charset; - } - - public String getPackagePrefixName() { - return packagePrefixName; - } - - public void setPackagePrefixName(String packagePrefixName) { - this.packagePrefixName = packagePrefixName; - } - -// public boolean isForceArray() { -// return forceArray; -// } -// -// public void setForceArray(boolean forceArray) { -// this.forceArray = forceArray; -// } - - public boolean isCheckDefault() { - return checkDefault; - } - - public void setCheckDefault(boolean checkDefault) { - this.checkDefault = checkDefault; - } - - public boolean isServant() { - return servant; - } - - public void setServant(boolean servant) { - this.servant = servant; - } - - public boolean isTup() { - return tup; - } - - public void setTup(boolean tup) { - this.tup = tup; - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/Tars2JavaMojo.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/Tars2JavaMojo.java deleted file mode 100644 index 21b0e818..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/Tars2JavaMojo.java +++ /dev/null @@ -1,901 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.gensrc; - -import java.io.File; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.atomic.AtomicInteger; - -import org.antlr.runtime.ANTLRFileStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.Token; -import org.antlr.runtime.tree.CommonTree; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; - -import com.qq.tars.maven.parse.TarsLexer; -import com.qq.tars.maven.parse.TarsParser; -import com.qq.tars.maven.parse.ast.TarsConst; -import com.qq.tars.maven.parse.ast.TarsCustomType; -import com.qq.tars.maven.parse.ast.TarsEnum; -import com.qq.tars.maven.parse.ast.TarsInterface; -import com.qq.tars.maven.parse.ast.TarsKey; -import com.qq.tars.maven.parse.ast.TarsMapType; -import com.qq.tars.maven.parse.ast.TarsNamespace; -import com.qq.tars.maven.parse.ast.TarsOperation; -import com.qq.tars.maven.parse.ast.TarsParam; -import com.qq.tars.maven.parse.ast.TarsPrimitiveType; -import com.qq.tars.maven.parse.ast.TarsPrimitiveType.PrimitiveType; -import com.qq.tars.maven.parse.ast.TarsRoot; -import com.qq.tars.maven.parse.ast.TarsStruct; -import com.qq.tars.maven.parse.ast.TarsStructMember; -import com.qq.tars.maven.parse.ast.TarsType; -import com.qq.tars.maven.parse.ast.TarsVectorType; - -@Mojo(name = "tars2java", threadSafe = true) -public class Tars2JavaMojo extends AbstractMojo { - - @Parameter(required = true) - private Tars2JavaConfig tars2JavaConfig; - - private AtomicInteger var = new AtomicInteger(0); - - public void execute() throws MojoExecutionException, MojoFailureException { - // 1. check configurations - if (!tars2JavaConfig.packagePrefixName.endsWith(".")) { - tars2JavaConfig.packagePrefixName += "."; - } - - if (tars2JavaConfig.tarsFiles.length == 0) { - getLog().error("configuration tarsFiles is missing..."); - return; - } - - Map> nsMap = new HashMap>(); - - // 2. parse tars files - for (String tarsFile : tars2JavaConfig.tarsFiles) { - try { - getLog().info("Parse " + tarsFile + " ..."); - TarsLexer tarsLexer = new TarsLexer(new ANTLRFileStream(tarsFile, tars2JavaConfig.tarsFileCharset)); - CommonTokenStream tokens = new CommonTokenStream(tarsLexer); - TarsParser tarsParser = new TarsParser(tokens); - TarsRoot root = (TarsRoot) tarsParser.start().getTree(); - root.setTokenStream(tokens); - for (TarsNamespace ns : root.namespaceList()) { - List list = nsMap.get(ns.namespace()); - if (list == null) { - list = new ArrayList(); - nsMap.put(ns.namespace(), list); - } - list.add(ns); - } - } catch (Throwable th) { - getLog().error("Parse " + tarsFile + " Error!", th); - } - } - - // 3. generate java files. - for (Entry> entry : nsMap.entrySet()) { - try { - getLog().info("generate code for namespace : " + entry.getKey() + " ..."); - genJava(entry.getKey(), entry.getValue(), nsMap); - } catch (Throwable th) { - getLog().error("generate code for namespace : " + entry.getKey() + " Error!", th); - } - } - } - - private String getDoc(CommonTree ast, String prefix) { - CommonTokenStream ts = ((TarsRoot) ast.getAncestor(TarsParser.TARS_ROOT)).getTokenStream(); - Token t = ts.get(ast.getTokenStartIndex() - 1); - if (t != null && t.getChannel() == Token.HIDDEN_CHANNEL) { - return prefix + t.getText().replaceAll("\n\\s*\\*", "\n" + prefix + " *"); - } else { - return ""; - } - } - - private void genJava(String nsName, List namespaces, Map> nsMap) throws Exception { - getLog().info("module " + nsName + " >>"); - - String packageName = packageName(tars2JavaConfig.packagePrefixName, nsName); - String dirPath = tars2JavaConfig.srcPath + '/' + packageName.replace('.', '/') + "/"; - new File(dirPath).mkdirs(); - - // generate Const - List allConst = new ArrayList(); - for (TarsNamespace namespace : namespaces) { - allConst.addAll(namespace.constList()); - } - if (!allConst.isEmpty()) { - genConst(dirPath, packageName, nsName, allConst); - } - - // generate Enum - for (TarsNamespace ns : namespaces) { - for (TarsEnum e : ns.enumList()) { - genEnum(dirPath, packageName, ns.namespace(), e); - } - } - - // generate Struct - for (TarsNamespace ns : namespaces) { - for (TarsStruct s : ns.structList()) { - genStruct(dirPath, packageName, ns.namespace(), s, ns.keyMap().get(s.structName()), nsMap); - } - } - - // generate interface Prx - for (TarsNamespace ns : namespaces) { - for (TarsInterface tarsInterface : ns.interfaceList()) { - if (tars2JavaConfig.servant) { - genServant(dirPath, packageName, ns.namespace(), tarsInterface, nsMap); - } else { - genPrx(dirPath, packageName, ns.namespace(), tarsInterface, nsMap); - genPrxCallback(dirPath, packageName, ns.namespace(), tarsInterface, nsMap); - } - } - } - getLog().info("module " + nsName + " <<"); - } - - private void printHead(PrintWriter out) { - out.println("// **********************************************************************"); - out.println("// This file was generated by a TARS parser!"); - out.println("// TARS version 1.0.1."); - out.println("// **********************************************************************"); - out.println(); - } - - private void printDoc(PrintWriter out, String doc) { - if (doc != null && doc.startsWith("/**") && doc.endsWith("*/")) { - out.println(doc.substring(0, doc.length())); - } - } - - private void genConst(String dirPath, String packageName, String namespace, List constList) throws Exception { - String constClass = firstUpStr(namespace) + "Const"; - PrintWriter out = new PrintWriter(dirPath + constClass + ".java", tars2JavaConfig.charset); - - printHead(out); - out.println("package " + packageName + ";"); - out.println(); - out.println("public interface " + constClass + " {"); - for (TarsConst cn : constList) { - out.println(getDoc(cn, "\t")); - out.println("\tpublic static final " + type(cn.constType(), null) + " " + cn.constName() + " = " + cn.constValue() + ";"); - } - out.println("}"); - out.close(); - - getLog().info("generate Const " + constClass); - } - - private void genEnum(String dirPath, String packageName, String namespace, TarsEnum e) throws Exception { - String enumClass = e.enumName(); - PrintWriter out = new PrintWriter(dirPath + enumClass + ".java", tars2JavaConfig.charset); - printHead(out); - out.println("package " + packageName + ";"); - out.println(); - printDoc(out, getDoc(e, "")); - out.println("public enum " + enumClass + " {"); - out.println(); - for (int i = 0; i < e.enumMemberList().size(); ++i) { - String item = e.enumMemberList().get(i); - String value = i < e.enumValueList().size() ? e.enumValueList().get(i) : String.valueOf(i); - out.print("\t" + item + "(" + value + ")"); - if (i < e.enumMemberList().size() - 1) { - out.println(","); - } else { - out.println(";"); - } - } - out.println(); - out.println("\tprivate final int value;"); - out.println(); - out.println("\tprivate " + e.enumName() + "(int value) {"); - out.println("\t\tthis.value = value;"); - out.println("\t}"); - out.println(); - out.println("\tpublic int value() {"); - out.println("\t\treturn this.value;"); - out.println("\t}"); - out.println(); - out.println("\t@Override"); - out.println("\tpublic String toString() {"); - out.println("\t\treturn this.name() + \":\" + this.value;"); - out.println("\t}"); - out.println(); - - out.println("\tpublic static " + e.enumName() + " convert(int value) {"); - out.println("\t\tfor(" + e.enumName() + " v : values()) {"); - out.println("\t\t\tif(v.value() == value) {"); - out.println("\t\t\t\treturn v;"); - out.println("\t\t\t}"); - out.println("\t\t}"); - out.println("\t\treturn null;"); - out.println("\t}"); - out.println("}"); - out.close(); - - getLog().info("generate Enum " + enumClass); - } - - private void genStruct(String dirPath, String packageName, String namespace, TarsStruct struct, TarsKey key, - Map> nsMap) throws Exception { - String structClass = struct.structName(); - PrintWriter out = new PrintWriter(dirPath + structClass + ".java", tars2JavaConfig.charset); - printHead(out); - out.println("package " + packageName + ";"); - out.println(); - - out.println("import com.qq.tars.protocol.util.*;"); - out.println("import com.qq.tars.protocol.annotation.*;"); - out.println("import com.qq.tars.protocol.tars.*;"); - out.println("import com.qq.tars.protocol.tars.annotation.*;"); - out.println(); - printDoc(out, getDoc(struct, "")); - out.println("@TarsStruct"); - if (key == null) { - out.println("public class " + struct.structName() + " {"); - } else { - out.println("public class " + struct.structName() + " implements Comparable<" + struct.structName() + "> {"); - } - out.println(); - - // 定义成员变量 - for (TarsStructMember m : struct.memberList()) { - out.println("\t@TarsStructProperty(order = " + m.tag() + ", isRequire = " + m.isRequire() + ")"); - out.println("\tpublic " + type(m.memberType(), nsMap) + " " + m.memberName() + " = " + (m.defaultValue() == null ? typeInit(m.memberType(), nsMap, false) : m.defaultValue()) + ";"); - } - out.println(); - - // 生成 getter setter - for (TarsStructMember m : struct.memberList()) { - out.println("\tpublic " + type(m.memberType(), nsMap) + " " + fieldGetter(m.memberName(), m.memberType()) + "() {"); - out.println("\t\treturn " + m.memberName() + ";"); - out.println("\t}"); - out.println(); - - out.println("\tpublic void " + fieldSetter(m.memberName(), m.memberType()) + "(" + type(m.memberType(), nsMap) + " " + m.memberName() + ") {"); - out.println("\t\tthis." + m.memberName() + " = " + m.memberName() + ";"); - out.println("\t}"); - out.println(); - } - - // 生成 constructor - out.println("\tpublic " + struct.structName() + "() {"); - out.println("\t}"); - out.println(); - out.print("\tpublic " + struct.structName() + "("); - for (int i = 0; i < struct.memberList().size(); ++i) { - TarsStructMember m = struct.memberList().get(i); - out.print(type(m.memberType(), nsMap) + " " + m.memberName()); - if (i < struct.memberList().size() - 1) { - out.print(", "); - } - } - out.println(") {"); - for (TarsStructMember m : struct.memberList()) { - out.println("\t\tthis." + m.memberName() + " = " + m.memberName() + ";"); - } - out.println("\t}"); - out.println(); - - // compareTo() - if (key != null) { - out.println("\t@Override"); - out.println("\tpublic int compareTo(" + struct.structName() + " o) {"); - out.println("\t\tint c = 0;"); - for (String k : key.keyList()) { - out.println("\t\tif((c = TarsUtil.compareTo(" + k + ", o." + k + ")) != 0 ) {"); - out.println("\t\t\treturn c;"); - out.println("\t\t}"); - } - out.println("\t\treturn 0;"); - out.println("\t}"); - out.println(); - } - - // hashCode() - if (key != null) { - out.println(); - out.println("\t@Override"); - out.println("\tpublic int hashCode() {"); - out.println("\t\tfinal int prime = 31;"); - out.println("\t\tint result = 1;"); - for (int i = 0; i < key.keyList().size(); ++i) { - String k = key.keyList().get(i); - out.println("\t\tresult = prime * result + TarsUtil.hashCode(" + k + ");"); - } - out.println("\t\treturn result;"); - out.println("\t}"); - out.println(); - } else { - out.println("\t@Override"); - out.println("\tpublic int hashCode() {"); - out.println("\t\tfinal int prime = 31;"); - out.println("\t\tint result = 1;"); - for (TarsStructMember m : struct.memberList()) { - out.println("\t\tresult = prime * result + TarsUtil.hashCode(" + m.memberName() + ");"); - } - out.println("\t\treturn result;"); - out.println("\t}"); - out.println(); - } - - // equals() - out.println("\t@Override"); - out.println("\tpublic boolean equals(Object obj) {"); - - out.println("\t\tif (this == obj) {"); - out.println("\t\t\treturn true;"); - out.println("\t\t}"); - out.println("\t\tif (obj == null) {"); - out.println("\t\t\treturn false;"); - out.println("\t\t}"); - out.println("\t\tif (!(obj instanceof " + struct.structName() + ")) {"); - out.println("\t\t\treturn false;"); - out.println("\t\t}"); - out.println("\t\t" + struct.structName() + " other = (" + struct.structName() + ") obj;"); - out.println("\t\treturn ("); - - if (key != null) { - for (int i = 0; i < key.keyList().size(); ++i) { - String k = key.keyList().get(i); - out.println("\t\t\tTarsUtil.equals(" + k + ", other." + k + ") " + (i < key.keyList().size() - 1 ? "&&" : "")); - } - } else { - for (int i = 0; i < struct.memberList().size(); ++i) { - String k = struct.memberList().get(i).memberName(); - out.println("\t\t\tTarsUtil.equals(" + k + ", other." + k + ") " + (i < struct.memberList().size() - 1 ? "&&" : "")); - } - } - out.println("\t\t);"); - out.println("\t}"); - out.println(); - - //writeTo - out.println("\tpublic void writeTo(TarsOutputStream _os) {"); - for (TarsStructMember m : struct.memberList()) { - if (!m.isRequire()) { - if (m.memberType().isPrimitive() || isEnum(m.memberType(), nsMap)) { - TarsPrimitiveType primitiveType = m.memberType().asPrimitive(); - if (primitiveType != null && primitiveType.primitiveType().equals(PrimitiveType.STRING)) { - out.println("\t\tif (null != " + m.memberName() + ") {"); - out.println("\t\t\t_os.write(" + m.memberName() + ", " + m.tag() + ");"); - out.println("\t\t}"); - } else { - out.println("\t\t_os.write(" + m.memberName() + ", " + m.tag() + ");"); - } - } else { - out.println("\t\tif (null != " + m.memberName() + ") {"); - out.println("\t\t\t_os.write(" + m.memberName() + ", " + m.tag() + ");"); - out.println("\t\t}"); - } - } else { - out.println("\t\t_os.write(" + m.memberName() + ", " + m.tag() + ");"); - } - } - out.println("\t}"); - out.println(); - - //cache var - for (TarsStructMember m : struct.memberList()) { - boolean isenum = isEnum(m.memberType(), nsMap); - if ((!isenum && m.memberType().isCustom()) || m.memberType().isMap() || (m.memberType().isVector())) { - String memberName = "cache_" + m.memberName(); - out.println("\tstatic " + type(m.memberType(), true, nsMap) + " " + memberName + ";"); - out.println("\tstatic { "); - genCacheVar(memberName, true, m.memberType(), nsMap, out); - out.println("\t}"); - } - } - out.println(); - - //readFrom - out.println("\tpublic void readFrom(TarsInputStream _is) {"); - for (TarsStructMember m : struct.memberList()) { - String type = null; - boolean isenum = isEnum(m.memberType(), nsMap); - if ((!isenum && m.memberType().isCustom()) || m.memberType().isMap() || (m.memberType().isVector())) { - type = type(m.memberType(), nsMap); - out.println("\t\tthis." + m.memberName() + " = " + (type == null ? "" : "(" + type + ") ") + "_is.read(cache_" + m.memberName() + ", " + m.tag() + ", " + m.isRequire() + ");"); - } else { - if (m.memberType().isPrimitive()) { - TarsPrimitiveType primitiveType = m.memberType().asPrimitive(); - if (primitiveType.primitiveType().equals(PrimitiveType.STRING)) { - out.println("\t\tthis." + m.memberName() + " = " + "_is.readString(" + m.tag() + ", " + m.isRequire() + ");"); - } else { - out.println("\t\tthis." + m.memberName() + " = " + (type == null ? "" : "(" + type + ") ") + "_is.read(" + m.memberName() + ", " + m.tag() + ", " + m.isRequire() + ");"); - } - } else { - out.println("\t\tthis." + m.memberName() + " = " + (type == null ? "" : "(" + type + ") ") + "_is.read(" + m.memberName() + ", " + m.tag() + ", " + m.isRequire() + ");"); - } - } - } - out.println("\t}"); - out.println(); - - out.println("}"); - out.close(); - - getLog().info("generate Struct " + structClass); - } - - private void genCacheVar(String memberName, boolean hasDeclare, TarsType type, - Map> nsMap, PrintWriter out) { - if (type.isCustom() && !isEnum(type, nsMap)) { - out.println("\t\t" + (hasDeclare ? memberName : (type(type, true, nsMap) + " " + memberName)) + " = new " + type(type, true, nsMap) + "();"); - } else if (type.isMap()) { - TarsMapType mapType = type.asMap(); - out.println("\t\t" + (hasDeclare ? memberName : (type(type, true, nsMap) + " " + memberName)) + " = new java.util.HashMap<" + type(mapType.keyType(), true, nsMap) + ", " + type(mapType.valueType(), true, nsMap) + ">();"); - - String varkey = "var_" + var.incrementAndGet(); - String varval = "var_" + var.incrementAndGet(); - - genCacheVar(varkey, false, mapType.keyType(), nsMap, out); - genCacheVar(varval, false, mapType.valueType(), nsMap, out); - - out.println("\t\t" + memberName + ".put(" + varkey + " ," + varval + ");"); - - } else if (type.isVector()) { - TarsVectorType v = type.asVector(); - String varType = "var_" + var.incrementAndGet(); - if (v.isByteArray()) { - out.println("\t\t" + (hasDeclare ? memberName : (type(type, false, nsMap) + " " + memberName)) + " = new " + type(v.subType(), false, nsMap) + "[1];"); - genCacheVar(varType, false, v.subType(), nsMap, out); - out.println("\t\t" + memberName + "[0] = " + varType + ";"); - } else { - out.println("\t\t" + (hasDeclare ? memberName : (type(type, true, nsMap) + " " + memberName)) + " = new java.util.ArrayList<" + type(v.subType(), true, nsMap) + ">();"); - genCacheVar(varType, false, v.subType(), nsMap, out); - out.println("\t\t" + memberName + ".add(" + varType + ");"); - } - } else if (type.isPrimitive()) { - out.println("\t\t" + (hasDeclare ? memberName : (type(type, false, nsMap) + " " + memberName)) + " = " + typeInit(type, nsMap, true) + ";"); - } else if (isEnum(type, nsMap)) { - out.println("\t\t" + (hasDeclare ? memberName : (type(type, false, nsMap) + " " + memberName)) + " = " + typeInit(type, nsMap, true) + ";"); - } - } - - public void genPrx(String dirPath, String packageName, String namespace, TarsInterface _interface, - Map> nsMap) throws Exception { - String prxClass = _interface.interfaceName() + "Prx"; - - PrintWriter out = new PrintWriter(dirPath + prxClass + ".java", tars2JavaConfig.charset); - - printHead(out); - // 1. print package and imports. - out.println("package " + packageName + ";"); - out.println(); - - out.println("import com.qq.tars.protocol.annotation.*;"); - out.println("import com.qq.tars.protocol.tars.annotation.*;"); - out.println("import com.qq.tars.common.support.Holder;"); - - out.println(); - - // 2. print comments and class line. - printDoc(out, getDoc(_interface, "")); - out.println("@Servant"); - out.println("public interface " + prxClass + " {"); - // out.println(); - - // 4. print tars methods and prototypes - for (TarsOperation op : _interface.operationList()) { - // 2 print sync method without context - out.println(getDoc(op, "\t")); - out.println("\tpublic " + type(op.retType(), nsMap) + " " + op.oprationName() + "(" + opertaionParams(null, op.paramList(), null, true, nsMap) + ");"); - - // 3 print sync method with context - out.println(getDoc(op, "\t")); - out.println("\tpublic " + type(op.retType(), nsMap) + " " + op.oprationName() + "(" + opertaionParams(null, op.paramList(), Arrays.asList("@TarsContext java.util.Map ctx"), true, nsMap) + ");"); - - // 4 print async method without context - out.println(getDoc(op, "\t")); - out.println("\tpublic void async_" + op.oprationName() + "(" + opertaionParams(Arrays.asList("@TarsCallback " + prxClass + "Callback callback"), op.paramList(), null, false, nsMap) + ");"); - - // 5 print async method with context - out.println(getDoc(op, "\t")); - out.println("\tpublic void async_" + op.oprationName() + "(" + opertaionParams(Arrays.asList("@TarsCallback " + prxClass + "Callback callback"), op.paramList(), Arrays.asList("@TarsContext java.util.Map ctx"), false, nsMap) + ");"); - } - - out.println("}"); - out.close(); - - getLog().info("generate Prx " + prxClass); - } - - public void genServant(String dirPath, String packageName, String namespace, TarsInterface _interface, - Map> nsMap) throws Exception { - String prxClass = _interface.interfaceName() + "Servant"; - - PrintWriter out = new PrintWriter(dirPath + prxClass + ".java", tars2JavaConfig.charset); - - printHead(out); - // 1. print package and imports. - out.println("package " + packageName + ";"); - out.println(); - - out.println("import com.qq.tars.protocol.annotation.*;"); - out.println("import com.qq.tars.protocol.tars.annotation.*;"); - out.println("import com.qq.tars.common.support.Holder;"); - out.println(); - - // 2. print comments and class line. - printDoc(out, getDoc(_interface, "")); - out.println("@Servant"); - out.println("public interface " + prxClass + " {"); - // out.println(); - - // 4. print tars methods and prototypes - for (TarsOperation op : _interface.operationList()) { - // 2 print sync method without context - out.println(getDoc(op, "\t")); - out.println("\tpublic " + type(op.retType(), nsMap) + " " + op.oprationName() + "(" + opertaionParams(null, op.paramList(), null, true, nsMap) + ");"); - } - - out.println("}"); - out.close(); - - getLog().info("generate Servant " + prxClass); - } - - public void genPrxCallback(String dirPath, String packageName, String namespace, TarsInterface tarsInterface, - Map> nsMap) throws Exception { - String prxClass = tarsInterface.interfaceName() + "PrxCallback"; - - PrintWriter out = new PrintWriter(dirPath + prxClass + ".java", tars2JavaConfig.charset); - printHead(out); - // 1. print package and imports. - out.println("package " + packageName + ";"); - out.println(); - out.println("import com.qq.tars.rpc.protocol.tars.support.TarsAbstractCallback;"); - out.println(); - - // 2. print comments and class line. - printDoc(out, getDoc(tarsInterface, "")); - out.println("public abstract class " + prxClass + " extends TarsAbstractCallback {"); - out.println(); - - // 4. print tars methods and prototypes - for (TarsOperation op : tarsInterface.operationList()) { - String type = type(op.retType(), false, nsMap); - if ("void".equals(type) || "Void".equals(type)) { - out.println("\tpublic abstract void callback_" + op.oprationName() + "(" + opertaionCallBackParams(null, op.paramList(), null, nsMap) + ");"); - } else { - out.println("\tpublic abstract void callback_" + op.oprationName() + "(" + opertaionCallBackParams(Arrays.asList(type + " ret"), op.paramList(), null, nsMap) + ");"); - } - - out.println(); - } - - out.println("}"); - out.close(); - - getLog().info("generate Prx " + prxClass); - } - - private String type(TarsType jt, Map> nsMap) { - return type(jt, false, nsMap); - } - - private String type(TarsType jt, boolean usePrimitiveWrapper, Map> nsMap) { - if (jt.isPrimitive()) { - TarsPrimitiveType p = jt.asPrimitive(); - if (!usePrimitiveWrapper) { - switch (p.primitiveType()) { - case VOID: - return "void"; - case BOOL: - return "boolean"; - case BYTE: - return "byte"; - case SHORT: - return "short"; - case INT: - return "int"; - case LONG: - return "long"; - case FLOAT: - return "float"; - case DOUBLE: - return "double"; - case STRING: - return "String"; - default: - return ""; - } - } else { - switch (p.primitiveType()) { - case VOID: - return "Void"; - case BOOL: - return "java.lang.Boolean"; - case BYTE: - return "java.lang.Byte"; - case SHORT: - return "java.lang.Short"; - case INT: - return "java.lang.Integer"; - case LONG: - return "java.lang.Long"; - case FLOAT: - return "java.lang.Float"; - case DOUBLE: - return "java.lang.Double"; - case STRING: - return "String"; - default: - return ""; - } - } - } else if (jt.isVector()) { - TarsVectorType v = jt.asVector(); - if (v.isByteArray()) { - return "byte[]"; - } else { - return "java.util.List<" + type(v.subType(), true, nsMap) + ">"; - } - } else if (jt.isMap()) { - TarsMapType m = jt.asMap(); - return "java.util.Map<" + type(m.keyType(), true, nsMap) + ", " + type(m.valueType(), true, nsMap) + ">"; - } else if (jt.isCustom()) { - TarsCustomType ct = jt.asCustom(); - - boolean isEnum = nsMap != null ? isEnum(jt, nsMap) : false; - if (isEnum) { - if (!usePrimitiveWrapper) - return "int"; - else - return "java.lang.Integer"; - } - if (ct.namespace() == null) { - return ct.typeName(); - } else { - return packageName(tars2JavaConfig.packagePrefixName, ct.namespace()) + "." + ct.typeName(); - } - } else { - return ""; - } - } - - private boolean isEnum(TarsType jt, Map> nsMap) { - List allEnum = new ArrayList(); - for (Entry> entry : nsMap.entrySet()) { - for (TarsNamespace namespace : entry.getValue()) { - allEnum.addAll(namespace.enumList()); - } - } - - if (!allEnum.isEmpty()) { - for (TarsEnum tarsEnum : allEnum) { - if (jt.typeName().equals(tarsEnum.enumName())) { - return true; - } - } - } - return false; - } - - private String typeInit(TarsType jt, Map> nsMap, boolean useDefault) { - if (!useDefault) { - if (jt.isPrimitive()) { - TarsPrimitiveType p = jt.asPrimitive(); - switch (p.primitiveType()) { - case VOID: - return ""; - case BOOL: - return "false"; - case BYTE: - return "(byte)0"; - case SHORT: - return "(short)0"; - case INT: - return "0"; - case LONG: - return "0L"; - case FLOAT: - return "0F"; - case DOUBLE: - return "0D"; - case STRING: - return "\"\""; - default: - return ""; - } - } else { - return nsMap != null && isEnum(jt, nsMap) ? "0" : "null"; - } - } else { - if (jt.isPrimitive()) { - TarsPrimitiveType p = jt.asPrimitive(); - switch (p.primitiveType()) { - case VOID: - return ""; - case BOOL: - return "false"; - case BYTE: - return "(byte)0"; - case SHORT: - return "(short)0"; - case INT: - return "0"; - case LONG: - return "0L"; - case FLOAT: - return "0F"; - case DOUBLE: - return "0D"; - case STRING: - return "\"\""; - default: - return ""; - } - } else if (jt.isVector()) { - TarsVectorType v = jt.asVector(); - if (v.isByteArray()) { - return "new byte[1]"; - } else { - return "new java.util.ArrayList<" + type(v.subType(), true, nsMap) + ">()"; - } - } else if (jt.isMap()) { - TarsMapType m = jt.asMap(); - return "new java.util.HashMap<" + type(m.keyType(), true, nsMap) + ", " + type(m.valueType(), true, nsMap) + ">()"; - } else if (jt.isCustom()) { - TarsCustomType ct = jt.asCustom(); - - boolean isEnum = nsMap != null ? isEnum(jt, nsMap) : false; - if (isEnum) { - return "0"; - } - if (ct.namespace() == null) { - return "new " + ct.typeName() + "()"; - } else { - return "new " + packageName(tars2JavaConfig.packagePrefixName, ct.namespace()) + "." + ct.typeName() + "()"; - } - } else { - return ""; - } - } - } - - public String opertaionCallBackParams(List beforeParams, List paramList, - List afterParams, Map> nsMap) { - StringBuilder sb = new StringBuilder(); - boolean isFirst = true; - if (beforeParams != null) { - for (String other : beforeParams) { - if (isFirst) { - isFirst = false; - } else { - sb.append(", "); - } - sb.append(other); - } - } - for (TarsParam p : paramList) { - if (!p.isOut()) { - continue; - } - sb.append(isFirst ? "" : ", "); - sb.append(type(p.paramType(), nsMap)).append(" ").append(p.paramName()); - if (isFirst) { - isFirst = false; - } - } - - if (afterParams != null) { - for (String other : afterParams) { - if (isFirst) { - isFirst = false; - } else { - sb.append(", "); - } - sb.append(other); - } - } - return sb.toString(); - } - - public String opertaionParams(List beforeParams, List paramList, List afterParams, - boolean isSync, Map> nsMap) { - StringBuilder sb = new StringBuilder(); - boolean isFirst = true; - if (beforeParams != null) { - for (String other : beforeParams) { - if (isFirst) { - isFirst = false; - } else { - sb.append(", "); - } - sb.append(other); - } - } - for (TarsParam p : paramList) { - if (!isSync && p.isOut()) { - continue; - } - if (p.isOut()) { - sb.append(isFirst ? "" : ", "); - if (tars2JavaConfig.isServant() && tars2JavaConfig.isTup()) { - sb.append("@TarsHolder(name=\"").append(p.paramName()).append("\") Holder<").append(type(p.paramType(), true, nsMap)).append("> ").append(p.paramName()); - } else { - sb.append("@TarsHolder Holder<").append(type(p.paramType(), true, nsMap)).append("> ").append(p.paramName()); - } - } else { - sb.append(isFirst ? "" : ", "); - if (tars2JavaConfig.isServant() && tars2JavaConfig.isTup()) { - sb.append("@TarsMethodParameter(name=\"").append(p.paramName()).append("\")").append(type(p.paramType(), nsMap)).append(" ").append(p.paramName()); - } else { - sb.append(type(p.paramType(), nsMap)).append(" ").append(p.paramName()); - } - } - if (isFirst) { - isFirst = false; - } - } - - if (afterParams != null) { - for (String other : afterParams) { - if (isFirst) { - isFirst = false; - } else { - sb.append(", "); - } - sb.append(other); - } - } - return sb.toString(); - } - - private static String firstUpStr(String str) { - if (str == null || str.length() < 1) { - return str; - } - return str.substring(0, 1).toUpperCase() + str.substring(1); - } - - private static String packageName(String packagePrefixName, String namespace) { - return packagePrefixName + namespace.toLowerCase(); - } - - public static String fieldGetter(String fieldName, TarsType type) { - if (type.isPrimitive() && (type.asPrimitive()).primitiveType() == TarsPrimitiveType.PrimitiveType.BOOL && fieldName.startsWith("is")) { - return fieldName; - } else { - return "get" + firstUpStr(fieldName); - } - } - - public static String fieldSetter(String fieldName, TarsType type) { - if (type.isPrimitive() && (type.asPrimitive()).primitiveType() == TarsPrimitiveType.PrimitiveType.BOOL && fieldName.startsWith("is")) { - return "set" + fieldName.substring(2); - } else { - return "set" + firstUpStr(fieldName); - } - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/TarsBuildMojo.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/TarsBuildMojo.java deleted file mode 100644 index 8cf1cb13..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/gensrc/TarsBuildMojo.java +++ /dev/null @@ -1,588 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.gensrc; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; -import java.util.regex.Pattern; - -import org.apache.commons.io.FileUtils; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DefaultArtifact; -import org.apache.maven.artifact.factory.ArtifactFactory; -import org.apache.maven.artifact.metadata.ArtifactMetadataSource; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; -import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; -import org.apache.maven.artifact.resolver.ArtifactCollector; -import org.apache.maven.artifact.resolver.ArtifactNotFoundException; -import org.apache.maven.artifact.resolver.ArtifactResolutionException; -import org.apache.maven.artifact.resolver.ArtifactResolver; -import org.apache.maven.artifact.resolver.filter.ArtifactFilter; -import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Component; -import org.apache.maven.plugins.annotations.Execute; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.MavenProjectBuilder; -import org.apache.maven.shared.dependency.tree.DependencyNode; -import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder; -import org.apache.maven.shared.mapping.MappingUtils; -import org.codehaus.plexus.PlexusConstants; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.archiver.ArchiverException; -import org.codehaus.plexus.archiver.UnArchiver; -import org.codehaus.plexus.archiver.manager.ArchiverManager; -import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.codehaus.plexus.context.Context; -import org.codehaus.plexus.context.ContextException; -import org.codehaus.plexus.interpolation.InterpolationException; -import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; -import org.codehaus.plexus.util.IOUtil; -import org.codehaus.plexus.util.InterpolationFilterReader; - -import com.qq.tars.maven.model.Dependency; -import com.qq.tars.maven.script.Platform; -import com.qq.tars.maven.util.ArchiveEntryUtils; -import com.qq.tars.maven.util.XMLConfigElement; -import com.qq.tars.maven.util.XMLConfigFile; - -@Mojo(name = "build", defaultPhase = LifecyclePhase.PACKAGE, requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true) -@Execute(phase = LifecyclePhase.PACKAGE) -public class TarsBuildMojo extends AbstractMojo implements Contextualizable { - - @Parameter(defaultValue = "${project}") - private MavenProject project; - - @Parameter(defaultValue = "${session}") - private MavenSession session; - - @Parameter(alias = "", defaultValue = "${project.build.directory}/${project.build.finalName}") - private File war; - - @Parameter - protected String outputFileNameMapping; - - @Parameter(defaultValue = "default") - protected String repositoryLayout; - - @Parameter(defaultValue = "false") - protected boolean useTimestampInSnapshotFileName; - - @Parameter(defaultValue = "${localRepository}", readonly = true, required = true) - protected ArtifactRepository localRepository; - - @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true) - protected List remoteRepositories; - - @Component - private ArtifactFactory artifactFactory; - @Component - protected ArtifactResolver artifactResolver; - @Component - protected ArtifactRepositoryFactory artifactRepositoryFactory; - @Component - protected ArtifactMetadataSource artifactMetadataSource; - @Component - protected MavenProjectBuilder mavenProjectBuilder; - @Component - protected DependencyTreeBuilder dependencyTreeBuilder; - @Component - protected ArtifactCollector artifactCollector; - @Component - protected ArchiverManager archiverManager; - - protected PlexusContainer container; - - @Parameter - private String platformName; - - @Parameter - private String tarsGroupId; - @Parameter - private String tarsArtifactId; - @Parameter - private String tarsVersion; - - private static final String TARS_PROTOCOL = "tars"; - private static final String TUP_PROTOCOL = "tup"; - private static final String MAIN_CLASS = "com.qq.tars.server.startup.Main"; - - // ----------------------------------------------------------------------- - // Plexus Implementation - // ----------------------------------------------------------------------- - /** - * {@inheritDoc} - */ - public void contextualize(Context context) throws ContextException { - container = (PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY); - } - - protected static final String SCOPE_DEFAULT_PATTERN = "^((?!test).)*$"; - private String includedScope = SCOPE_DEFAULT_PATTERN; - - private List dependencyList = new ArrayList(); - - private Pattern pattern; - - protected boolean includedScope(final String scope) { - if (pattern == null) { - pattern = Pattern.compile(includedScope, Pattern.CASE_INSENSITIVE); - } - return scope != null ? pattern.matcher(scope).matches() : Boolean.TRUE; - } - - public void execute() throws MojoExecutionException, MojoFailureException { - getLog().info("Start run build..."); - try { - if (platformName == null) { - String osName = System.getProperty("os.name"); - if (osName.toLowerCase().contains(Platform.WINDOWS_NAME)) { - platformName = Platform.WINDOWS_NAME; - } else { - platformName = Platform.UNIX_NAME; - } - } - - File targetDir = new File(project.getBuild().getDirectory()); - File tarsDir = new File(targetDir, "tars"); - if (tarsDir.exists()) { - FileUtils.forceDelete(tarsDir); - } - tarsDir.mkdir(); - - File binDir = new File(tarsDir, "bin"); - binDir.mkdir(); - - File confDir = new File(tarsDir, "conf"); - confDir.mkdir(); - - File dataDir = new File(tarsDir, "data"); - dataDir.mkdir(); - - File binAppsDir = new File(binDir, "apps" + File.separator + "ROOT"); - binAppsDir.mkdir(); - FileUtils.copyDirectory(war, binAppsDir); - - File binConfDir = new File(binDir, "conf"); - binConfDir.mkdir(); - - File binLogDir = new File(binDir, "log"); - binLogDir.mkdir(); - - File libDir = new File(binDir, "lib"); - libDir.mkdir(); - - String app = getApp(); - String server = getServer(); - - if (app == null || server == null) { - throw new MojoExecutionException("Failed to build app server is null."); - } - - String configFileName = String.format("%s.%s.%s", app, server, "config.conf"); - File configFile = new File(confDir, configFileName); - getLog().info(String.format("Create config file %s ", configFile.getCanonicalPath())); - createConfigScript(binDir, dataDir, binLogDir, configFile); - - installLibDependency(libDir); - - getLog().info(String.format("Create platform %s start script...", platformName)); - Platform platform = Platform.getInstance(platformName); - String binscript = createBinScript(platform, libDir, binDir, configFile); - getLog().info("Start Script in " + binscript); - } catch (Exception e) { - getLog().error(e); - throw new MojoExecutionException("Failed to tars build", e); - } - } - - private void installLibDependency(File libDir) throws Exception { - ArtifactRepository artifactRepository = getArtifactRepository(libDir.getAbsolutePath()); - - getLog().info("Install tars artifact..."); - Set projectDependency = project.getDependencyArtifacts(); - Artifact tarsArtifact = null; - for (Artifact artifact : projectDependency) { - if (artifact.getArtifactId().contains("tars")) { - getLog().info(String.format("Use tars artifact %s-%s-%s", artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion())); - tarsArtifact = artifact; - break; - } - } - - if (tarsArtifact == null) { - tarsArtifact = artifactFactory.createArtifact(tarsGroupId, tarsArtifactId, tarsVersion, Artifact.SCOPE_COMPILE, "jar"); - } - artifactResolver.resolve(tarsArtifact, remoteRepositories, localRepository); - installArtifact(tarsArtifact, libDir, artifactRepository, useTimestampInSnapshotFileName); - - MavenProject coreProject = mavenProjectBuilder.buildFromRepository(tarsArtifact, remoteRepositories, localRepository); - final ArtifactFilter artifactFilter = new ScopeArtifactFilter(DefaultArtifact.SCOPE_COMPILE) { - - @Override - public boolean include(Artifact artifact) { - return includedScope(artifact.getScope()); - } - }; - - final Set artifacts = new HashSet(); - final DependencyNode rootNode = dependencyTreeBuilder.buildDependencyTree(coreProject, localRepository, artifactFactory, artifactMetadataSource, artifactFilter, artifactCollector); - - for (final Iterator iterator = rootNode.getChildren().iterator(); iterator.hasNext();) { - final DependencyNode child = (DependencyNode) iterator.next(); - collect(child, artifacts); - } - if (artifacts == null || artifacts.isEmpty()) { - throw new MojoExecutionException("Unable to install tars artifact dependency."); - } - for (final Artifact artifact : artifacts) { - try { - artifactResolver.resolve(artifact, remoteRepositories, localRepository); - } catch (final ArtifactResolutionException e) { - throw new MojoExecutionException("Unable to resolve " + artifact, e); - } catch (final ArtifactNotFoundException e) { - throw new MojoExecutionException("Unable to resolve " + artifact, e); - } - installArtifact(artifact, libDir, artifactRepository, useTimestampInSnapshotFileName); - } - } - - /** - * extract specified artifact. - * - * @param destination destination folder - * @param artifactFile - * @throws NoSuchArchiverException - * @throws ArchiverException - * @throws MojoExecutionException - */ - private void unArchiveArtifact(final File destination, final File artifactFile) throws MojoExecutionException, IOException { - try { - final UnArchiver unArchiver = archiverManager.getUnArchiver(artifactFile); - unArchiver.setSourceFile(artifactFile); - unArchiver.setDestDirectory(destination); - unArchiver.setOverwrite(true); - unArchiver.extract(); - } catch (final NoSuchArchiverException e) { - throw new MojoExecutionException("Unable to unarchive " + artifactFile.getName(), e); - } catch (final ArchiverException e) { - throw new MojoExecutionException("Unable to unarchive " + artifactFile.getName(), e); - } - } - - private void collect(final DependencyNode root, final Set artifacts) { - Stack stack = new Stack(); - stack.push(root); - while (!stack.isEmpty()) { - DependencyNode node = stack.pop(); - if (node.getState() == DependencyNode.INCLUDED) { - final Artifact artifact = node.getArtifact(); - if (includedScope(artifact.getScope())) { - getLog().info("Adding Artefact: " + artifact.toString()); - artifacts.add(artifact); - // check children - if (!node.getChildren().isEmpty()) { - stack.addAll(node.getChildren()); - } - } - } - } - } - - private ArtifactRepository getArtifactRepository(final String outputDirectory) throws ArtifactNotFoundException, MojoFailureException { - return artifactRepositoryFactory.createDeploymentArtifactRepository("tars", "file://" + outputDirectory, getArtifactRepositoryLayout(), false); - } - - protected ArtifactRepositoryLayout getArtifactRepositoryLayout() throws MojoFailureException { - try { - ArtifactRepositoryLayout artifactRepositoryLayout = null; - artifactRepositoryLayout = (ArtifactRepositoryLayout) container.lookup("org.apache.maven.artifact." + "repository.layout.ArtifactRepositoryLayout", repositoryLayout); - if (artifactRepositoryLayout == null) { - throw new MojoFailureException("Unknown repository layout '" + repositoryLayout + "'."); - } - return artifactRepositoryLayout; - } catch (ComponentLookupException e) { - throw new MojoFailureException("Unable to lookup the repository layout component '" + repositoryLayout + "': " + e.getMessage()); - } - } - - protected void installArtifact(Artifact artifact, File libDir, ArtifactRepository artifactRepository, - boolean useTimestampInSnapshotFileName) throws MojoExecutionException { - if (artifact != null && artifact.getFile() != null) { - try { - File source = artifact.getFile(); - - File destination = libDir; // - - if (!source.isDirectory()) { - if (outputFileNameMapping != null) { - String fileName = MappingUtils.evaluateFileNameMapping(outputFileNameMapping, artifact); - destination = new File(destination, fileName); - } else { - destination = new File(destination, source.getName()); - } - - FileUtils.copyFile(source, destination); - Dependency dependency = new Dependency(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getClassifier()); - dependency.setRelativePath(destination.getCanonicalPath()); - dependencyList.add(dependency); - } - getLog().info("Installing artifact " + source.getPath() + " to " + destination); - } catch (IOException e) { - throw new MojoExecutionException("Failed to copy artifact.", e); - } catch (InterpolationException e) { - throw new MojoExecutionException("Failed to map file name.", e); - } - } - } - - private void createConfigScript(File binDir, File dataDir, File binLogDir, File configFile) throws Exception { - InputStream in = null; - FileWriter out = null; - try { - - File servicesXMLFile = new File(war, "WEB-INF" + File.separator + "servants.xml"); - if (!servicesXMLFile.exists()) { - throw new MojoExecutionException("failed to find WEB-INF/servants.xml, " + " servants will be disabled"); - } - - XMLConfigFile cfg = new XMLConfigFile(); - cfg.parse(new FileInputStream(servicesXMLFile)); - XMLConfigElement root = cfg.getRootElement(); - ArrayList elements = root.getChildList(); - - in = getConfigTemplate(); - InputStreamReader reader = new InputStreamReader(getConfigTemplate()); - - Map context = new HashMap(); - - context.put("LOCALIP", getLocalIp()); - context.put("APP", getApp()); - context.put("SERVER", getServer()); - context.put("BASEPATH", binDir.getCanonicalPath()); - context.put("DATAPATH", dataDir.getCanonicalFile()); - context.put("LOGPATH", binLogDir.getCanonicalPath()); - context.put("JVMPARAMS", getJvmParams()); - context.put("MAINCLASS", MAIN_CLASS); - - context.put("CONFIG", configFile.getAbsolutePath()); - - StringBuilder suf = new StringBuilder(); - for (XMLConfigElement element : elements) { - if ("servant".equals(element.getName())) { - if (suf.length() > 0) { - suf.append("\n"); - } - Servant servant = new Servant(); - servant.setName(element.getStringAttribute("name")); - servant.setProtocol(element.getStringAttribute("protocol", TARS_PROTOCOL)); - servant.setPort(element.getStringAttribute("port")); - suf.append(readServantScript(servant)); - if (servant.getProtocol() != null && isJceOrWup(servant.getProtocol())) { - context.put("ADMINPORT", servant.getPort()); - } - } - } - - context.put("SERVANTADAPTER", suf.toString()); - - InterpolationFilterReader interpolationFilterReader = new InterpolationFilterReader(reader, context, "$", "$"); - - out = new FileWriter(configFile); - IOUtil.copy(interpolationFilterReader, out); - } catch (FileNotFoundException e) { - throw new MojoExecutionException("Failed to get template for config file.", e); - } catch (IOException e) { - throw new MojoExecutionException("Failed to write config file.", e); - } finally { - IOUtil.close(out); - IOUtil.close(in); - } - } - - private String getLocalIp() throws UnknownHostException { - return System.getProperty("localIp", InetAddress.getLocalHost().getHostAddress()); - } - - private String getApp() { - return System.getProperty("app", null); - } - - private String getServer() { - return System.getProperty("server", null); - } - - private boolean isPackage() { - return Boolean.parseBoolean(System.getProperty("package", "false")); - } - - private String getJvmParams() { - return System.getProperty("jvmParams", "-Xms1024m -Xmx1024m"); - } - - private boolean isJceOrWup(String protocol) { - return TARS_PROTOCOL.equalsIgnoreCase(protocol) || TUP_PROTOCOL.equalsIgnoreCase(protocol); - } - - private String readServantScript(Servant servant) throws Exception { - InputStream in = null; - try { - in = getServantTemplate(); - Map context = new HashMap(); - context.put("LOCALIP", getLocalIp()); - context.put("APP", getApp()); - context.put("SERVER", getServer()); - context.put("SERVANTNAME", servant.getName()); - context.put("PORT", servant.getPort()); - context.put("PROTOCOL", servant.getProtocol() == null || isJceOrWup(servant.getProtocol()) ? "tars" : "no_tars"); - - InterpolationFilterReader interpolationFilterReader = new InterpolationFilterReader(new InputStreamReader(in), context, "$", "$"); - return IOUtil.toString(interpolationFilterReader); - } catch (FileNotFoundException e) { - throw new MojoExecutionException("Failed to get template for servant file.", e); - } catch (IOException e) { - throw new MojoExecutionException("Failed to write servant file.", e); - } finally { - IOUtil.close(in); - } - } - - private String createBinScript(Platform platform, File libDir, File binDir, File configFile) throws Exception { - - InputStream in = null; - - FileWriter out = null; - File binFile; - - try { - in = getScriptTemplate(platform.getName()); - - Map context = new HashMap(); - context.put("JVMPARAMS", getJvmParams()); - context.put("MAINCLASS", MAIN_CLASS); - context.put("CONFIG", configFile.getAbsolutePath()); - context.put("CLASSPATH", platform.getClassPath(dependencyList)); - if (platform.isShowConsoleWindow()) { - context.put("JAVA_BINARY", "java"); - context.put("UNIX_BACKGROUND", ""); - } else { - context.put("JAVA_BINARY", "start /min javaw"); - context.put("UNIX_BACKGROUND", " &"); - } - - String interpolationToken = platform.getInterpolationToken(); - InterpolationFilterReader interpolationFilterReader = new InterpolationFilterReader(new InputStreamReader(in), context, interpolationToken, interpolationToken); - - String programName = "tars_start"; - - FileUtils.forceMkdir(binDir); - binFile = new File(binDir, programName + platform.getBinFileExtension()); - if (Platform.UNIX_NAME.equals(platform.getName())) { - if (binFile.exists()) { - try { - ArchiveEntryUtils.chmod(binFile, 0777, getLog(), true); - } catch (ArchiverException ae) { - throw new MojoExecutionException("Failed to change permission for bin file.", ae); - } - } - } - - out = new FileWriter(binFile); - getLog().debug("Writing shell file for platform '" + platform.getName() + "' to '" + binFile.getAbsolutePath() + "'."); - - IOUtil.copy(interpolationFilterReader, out); - } catch (FileNotFoundException e) { - throw new MojoExecutionException("Failed to get template for bin file.", e); - } catch (IOException e) { - throw new MojoExecutionException("Failed to write bin file.", e); - } finally { - IOUtil.close(out); - IOUtil.close(in); - } - - if (Platform.UNIX_NAME.equals(platform.getName())) { - try { - ArchiveEntryUtils.chmod(binFile, 0777, getLog(), true); - } catch (ArchiverException ae) { - throw new MojoExecutionException("Failed to change permission for bin file.", ae); - } - } - return binFile.getCanonicalPath(); - } - - private InputStream getScriptTemplate(String platformName) throws MojoExecutionException { - InputStream is = null; - try { - is = Platform.class.getResourceAsStream(platformName + "BinTemplate"); - if (is == null) { - throw new MojoExecutionException("Unable to load internal template resource: " + platformName + "BinTemplate"); - } - } catch (Exception e) { - throw new MojoExecutionException("Unable to load external template file", e); - } - return is; - } - - private InputStream getConfigTemplate() throws MojoExecutionException { - InputStream is = null; - try { - is = Platform.class.getResourceAsStream("configTemplate"); - if (is == null) { - throw new MojoExecutionException("Unable to load internal template resource: configTemplate"); - } - } catch (Exception e) { - throw new MojoExecutionException("Unable to load external template file", e); - } - return is; - } - - private InputStream getServantTemplate() throws MojoExecutionException { - InputStream is = null; - try { - is = Platform.class.getResourceAsStream("servantTemplate"); - if (is == null) { - throw new MojoExecutionException("Unable to load internal template resource: configTemplate"); - } - } catch (Exception e) { - throw new MojoExecutionException("Unable to load external template file", e); - } - return is; - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/model/Dependency.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/model/Dependency.java deleted file mode 100644 index ae2c42fc..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/model/Dependency.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.model; - -@SuppressWarnings("all") -public class Dependency extends ClasspathElement implements java.io.Serializable { - - private String groupId; - private String artifactId; - private String version; - private String classifier; - - public Dependency() { - } - - public Dependency(String groupId, String artifactId, String version, String classifier) { - this.groupId = groupId; - this.artifactId = artifactId; - this.version = version; - this.classifier = classifier; - } - - public String getArtifactId() { - return this.artifactId; - } - - public String getClassifier() { - return this.classifier; - } - - public String getGroupId() { - return this.groupId; - } - - public String getVersion() { - return this.version; - } - - public void setArtifactId(String artifactId) { - this.artifactId = artifactId; - } - - public void setClassifier(String classifier) { - this.classifier = classifier; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - public void setVersion(String version) { - this.version = version; - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/model/Directory.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/model/Directory.java deleted file mode 100644 index a07eec40..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/model/Directory.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.model; - -@SuppressWarnings("all") -public class Directory extends ClasspathElement implements java.io.Serializable { - - public Directory() { - } - - public Directory(String relativePath) { - super(relativePath); - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/TarsLexer.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/TarsLexer.java deleted file mode 100644 index c292d5a1..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/TarsLexer.java +++ /dev/null @@ -1,2437 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse; - - -import org.antlr.runtime.*; -import java.util.Stack; -import java.util.List; -import java.util.ArrayList; - -@SuppressWarnings("all") -public class TarsLexer extends Lexer { - public static final int EOF=-1; - public static final int COLON=4; - public static final int COMMA=5; - public static final int COMMENT=6; - public static final int DOT=7; - public static final int EQ=8; - public static final int ESC_SEQ=9; - public static final int GT=10; - public static final int HEX_DIGIT=11; - public static final int LBRACE=12; - public static final int LBRACKET=13; - public static final int LPAREN=14; - public static final int LT=15; - public static final int OCTAL_ESC=16; - public static final int QUOTE=17; - public static final int RBRACE=18; - public static final int RBRACKET=19; - public static final int RPAREN=20; - public static final int SEMI=21; - public static final int TARS_BOOL=22; - public static final int TARS_BYTE=23; - public static final int TARS_CONST=24; - public static final int TARS_DOUBLE=25; - public static final int TARS_ENUM=26; - public static final int TARS_FALSE=27; - public static final int TARS_FLOAT=28; - public static final int TARS_FLOATING_POINT_LITERAL=29; - public static final int TARS_IDENTIFIER=30; - public static final int TARS_INCLUDE=31; - public static final int TARS_INT=32; - public static final int TARS_INTEGER_LITERAL=33; - public static final int TARS_INTERFACE=34; - public static final int TARS_KEY=35; - public static final int TARS_LONG=36; - public static final int TARS_MAP=37; - public static final int TARS_NAMESPACE=38; - public static final int TARS_OPTIONAL=39; - public static final int TARS_OUT=40; - public static final int TARS_REQUIRE=41; - public static final int TARS_ROUTE_KEY=42; - public static final int TARS_SHORT=43; - public static final int TARS_STRING=44; - public static final int TARS_STRING_LITERAL=45; - public static final int TARS_STRUCT=46; - public static final int TARS_TRUE=47; - public static final int TARS_UNSIGNED=48; - public static final int TARS_VECTOR=49; - public static final int TARS_VOID=50; - public static final int UNICODE_ESC=51; - public static final int WS=52; - - // delegates - // delegators - public Lexer[] getDelegates() { - return new Lexer[] {}; - } - - public TarsLexer() {} - public TarsLexer(CharStream input) { - this(input, new RecognizerSharedState()); - } - public TarsLexer(CharStream input, RecognizerSharedState state) { - super(input,state); - } - @Override public String getGrammarFileName() { return "TarsLexer.g"; } - - // $ANTLR start "TARS_VOID" - public final void mTARS_VOID() throws RecognitionException { - try { - int _type = TARS_VOID; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:8:2: ( 'void' ) - // TarsLexer.g:8:4: 'void' - { - match("void"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_VOID" - - // $ANTLR start "TARS_STRUCT" - public final void mTARS_STRUCT() throws RecognitionException { - try { - int _type = TARS_STRUCT; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:11:2: ( 'struct' ) - // TarsLexer.g:11:4: 'struct' - { - match("struct"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_STRUCT" - - // $ANTLR start "TARS_UNSIGNED" - public final void mTARS_UNSIGNED() throws RecognitionException { - try { - int _type = TARS_UNSIGNED; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:14:2: ( 'unsigned' ) - // TarsLexer.g:14:4: 'unsigned' - { - match("unsigned"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_UNSIGNED" - - // $ANTLR start "TARS_BOOL" - public final void mTARS_BOOL() throws RecognitionException { - try { - int _type = TARS_BOOL; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:17:2: ( 'bool' ) - // TarsLexer.g:17:4: 'bool' - { - match("bool"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_BOOL" - - // $ANTLR start "TARS_BYTE" - public final void mTARS_BYTE() throws RecognitionException { - try { - int _type = TARS_BYTE; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:20:2: ( 'byte' ) - // TarsLexer.g:20:4: 'byte' - { - match("byte"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_BYTE" - - // $ANTLR start "TARS_SHORT" - public final void mTARS_SHORT() throws RecognitionException { - try { - int _type = TARS_SHORT; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:23:2: ( 'short' ) - // TarsLexer.g:23:4: 'short' - { - match("short"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_SHORT" - - // $ANTLR start "TARS_INT" - public final void mTARS_INT() throws RecognitionException { - try { - int _type = TARS_INT; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:26:2: ( 'int' ) - // TarsLexer.g:26:4: 'int' - { - match("int"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_INT" - - // $ANTLR start "TARS_DOUBLE" - public final void mTARS_DOUBLE() throws RecognitionException { - try { - int _type = TARS_DOUBLE; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:29:2: ( 'double' ) - // TarsLexer.g:29:4: 'double' - { - match("double"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_DOUBLE" - - // $ANTLR start "TARS_FLOAT" - public final void mTARS_FLOAT() throws RecognitionException { - try { - int _type = TARS_FLOAT; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:32:2: ( 'float' ) - // TarsLexer.g:32:4: 'float' - { - match("float"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_FLOAT" - - // $ANTLR start "TARS_LONG" - public final void mTARS_LONG() throws RecognitionException { - try { - int _type = TARS_LONG; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:35:2: ( 'long' ) - // TarsLexer.g:35:4: 'long' - { - match("long"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_LONG" - - // $ANTLR start "TARS_STRING" - public final void mTARS_STRING() throws RecognitionException { - try { - int _type = TARS_STRING; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:38:2: ( 'string' ) - // TarsLexer.g:38:4: 'string' - { - match("string"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_STRING" - - // $ANTLR start "TARS_VECTOR" - public final void mTARS_VECTOR() throws RecognitionException { - try { - int _type = TARS_VECTOR; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:41:2: ( 'vector' ) - // TarsLexer.g:41:4: 'vector' - { - match("vector"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_VECTOR" - - // $ANTLR start "TARS_MAP" - public final void mTARS_MAP() throws RecognitionException { - try { - int _type = TARS_MAP; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:44:2: ( 'map' ) - // TarsLexer.g:44:4: 'map' - { - match("map"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_MAP" - - // $ANTLR start "TARS_KEY" - public final void mTARS_KEY() throws RecognitionException { - try { - int _type = TARS_KEY; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:47:2: ( 'key' ) - // TarsLexer.g:47:4: 'key' - { - match("key"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_KEY" - - // $ANTLR start "TARS_ROUTE_KEY" - public final void mTARS_ROUTE_KEY() throws RecognitionException { - try { - int _type = TARS_ROUTE_KEY; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:50:2: ( 'routekey' ) - // TarsLexer.g:50:4: 'routekey' - { - match("routekey"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_ROUTE_KEY" - - // $ANTLR start "TARS_INCLUDE" - public final void mTARS_INCLUDE() throws RecognitionException { - try { - int _type = TARS_INCLUDE; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:53:2: ( '#include' ) - // TarsLexer.g:53:4: '#include' - { - match("#include"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_INCLUDE" - - // $ANTLR start "TARS_NAMESPACE" - public final void mTARS_NAMESPACE() throws RecognitionException { - try { - int _type = TARS_NAMESPACE; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:56:2: ( 'module' ) - // TarsLexer.g:56:4: 'module' - { - match("module"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_NAMESPACE" - - // $ANTLR start "TARS_INTERFACE" - public final void mTARS_INTERFACE() throws RecognitionException { - try { - int _type = TARS_INTERFACE; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:59:2: ( 'interface' ) - // TarsLexer.g:59:4: 'interface' - { - match("interface"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_INTERFACE" - - // $ANTLR start "TARS_OUT" - public final void mTARS_OUT() throws RecognitionException { - try { - int _type = TARS_OUT; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:62:2: ( 'out' ) - // TarsLexer.g:62:4: 'out' - { - match("out"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_OUT" - - // $ANTLR start "TARS_REQUIRE" - public final void mTARS_REQUIRE() throws RecognitionException { - try { - int _type = TARS_REQUIRE; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:65:2: ( 'require' ) - // TarsLexer.g:65:4: 'require' - { - match("require"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_REQUIRE" - - // $ANTLR start "TARS_OPTIONAL" - public final void mTARS_OPTIONAL() throws RecognitionException { - try { - int _type = TARS_OPTIONAL; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:68:2: ( 'optional' ) - // TarsLexer.g:68:4: 'optional' - { - match("optional"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_OPTIONAL" - - // $ANTLR start "TARS_FALSE" - public final void mTARS_FALSE() throws RecognitionException { - try { - int _type = TARS_FALSE; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:71:2: ( 'false' ) - // TarsLexer.g:71:4: 'false' - { - match("false"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_FALSE" - - // $ANTLR start "TARS_TRUE" - public final void mTARS_TRUE() throws RecognitionException { - try { - int _type = TARS_TRUE; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:74:2: ( 'true' ) - // TarsLexer.g:74:4: 'true' - { - match("true"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_TRUE" - - // $ANTLR start "TARS_ENUM" - public final void mTARS_ENUM() throws RecognitionException { - try { - int _type = TARS_ENUM; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:77:2: ( 'enum' ) - // TarsLexer.g:77:4: 'enum' - { - match("enum"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_ENUM" - - // $ANTLR start "TARS_CONST" - public final void mTARS_CONST() throws RecognitionException { - try { - int _type = TARS_CONST; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:80:2: ( 'const' ) - // TarsLexer.g:80:4: 'const' - { - match("const"); - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_CONST" - - // $ANTLR start "TARS_IDENTIFIER" - public final void mTARS_IDENTIFIER() throws RecognitionException { - try { - int _type = TARS_IDENTIFIER; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:85:5: ( ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* ) - // TarsLexer.g:85:7: ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* - { - if ( (input.LA(1) >= 'A' && input.LA(1) <= 'Z')||input.LA(1)=='_'||(input.LA(1) >= 'a' && input.LA(1) <= 'z') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - // TarsLexer.g:85:31: ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* - loop1: - while (true) { - int alt1=2; - int LA1_0 = input.LA(1); - if ( ((LA1_0 >= '0' && LA1_0 <= '9')||(LA1_0 >= 'A' && LA1_0 <= 'Z')||LA1_0=='_'||(LA1_0 >= 'a' && LA1_0 <= 'z')) ) { - alt1=1; - } - - switch (alt1) { - case 1 : - // TarsLexer.g: - { - if ( (input.LA(1) >= '0' && input.LA(1) <= '9')||(input.LA(1) >= 'A' && input.LA(1) <= 'Z')||input.LA(1)=='_'||(input.LA(1) >= 'a' && input.LA(1) <= 'z') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - - default : - break loop1; - } - } - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_IDENTIFIER" - - // $ANTLR start "TARS_INTEGER_LITERAL" - public final void mTARS_INTEGER_LITERAL() throws RecognitionException { - try { - int _type = TARS_INTEGER_LITERAL; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:89:5: ( ( '0X' | '0x' ) ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' )+ | ( 'O' | 'o' ) ( '0' .. '7' )+ | ( '+' | '-' )? ( '0' .. '9' )+ ) - int alt7=3; - switch ( input.LA(1) ) { - case '0': - { - int LA7_1 = input.LA(2); - if ( (LA7_1=='X'||LA7_1=='x') ) { - alt7=1; - } - - else { - alt7=3; - } - - } - break; - case 'O': - case 'o': - { - alt7=2; - } - break; - case '+': - case '-': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - alt7=3; - } - break; - default: - NoViableAltException nvae = - new NoViableAltException("", 7, 0, input); - throw nvae; - } - switch (alt7) { - case 1 : - // TarsLexer.g:89:7: ( '0X' | '0x' ) ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' )+ - { - // TarsLexer.g:89:7: ( '0X' | '0x' ) - int alt2=2; - int LA2_0 = input.LA(1); - if ( (LA2_0=='0') ) { - int LA2_1 = input.LA(2); - if ( (LA2_1=='X') ) { - alt2=1; - } - else if ( (LA2_1=='x') ) { - alt2=2; - } - - else { - int nvaeMark = input.mark(); - try { - input.consume(); - NoViableAltException nvae = - new NoViableAltException("", 2, 1, input); - throw nvae; - } finally { - input.rewind(nvaeMark); - } - } - - } - - else { - NoViableAltException nvae = - new NoViableAltException("", 2, 0, input); - throw nvae; - } - - switch (alt2) { - case 1 : - // TarsLexer.g:89:8: '0X' - { - match("0X"); - - } - break; - case 2 : - // TarsLexer.g:89:13: '0x' - { - match("0x"); - - } - break; - - } - - // TarsLexer.g:89:18: ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' )+ - int cnt3=0; - loop3: - while (true) { - int alt3=2; - int LA3_0 = input.LA(1); - if ( ((LA3_0 >= '0' && LA3_0 <= '9')||(LA3_0 >= 'A' && LA3_0 <= 'F')||(LA3_0 >= 'a' && LA3_0 <= 'f')) ) { - alt3=1; - } - - switch (alt3) { - case 1 : - // TarsLexer.g: - { - if ( (input.LA(1) >= '0' && input.LA(1) <= '9')||(input.LA(1) >= 'A' && input.LA(1) <= 'F')||(input.LA(1) >= 'a' && input.LA(1) <= 'f') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - - default : - if ( cnt3 >= 1 ) break loop3; - EarlyExitException eee = new EarlyExitException(3, input); - throw eee; - } - cnt3++; - } - - } - break; - case 2 : - // TarsLexer.g:90:7: ( 'O' | 'o' ) ( '0' .. '7' )+ - { - if ( input.LA(1)=='O'||input.LA(1)=='o' ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - // TarsLexer.g:90:16: ( '0' .. '7' )+ - int cnt4=0; - loop4: - while (true) { - int alt4=2; - int LA4_0 = input.LA(1); - if ( ((LA4_0 >= '0' && LA4_0 <= '7')) ) { - alt4=1; - } - - switch (alt4) { - case 1 : - // TarsLexer.g: - { - if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - - default : - if ( cnt4 >= 1 ) break loop4; - EarlyExitException eee = new EarlyExitException(4, input); - throw eee; - } - cnt4++; - } - - } - break; - case 3 : - // TarsLexer.g:91:7: ( '+' | '-' )? ( '0' .. '9' )+ - { - // TarsLexer.g:91:7: ( '+' | '-' )? - int alt5=2; - int LA5_0 = input.LA(1); - if ( (LA5_0=='+'||LA5_0=='-') ) { - alt5=1; - } - switch (alt5) { - case 1 : - // TarsLexer.g: - { - if ( input.LA(1)=='+'||input.LA(1)=='-' ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - - } - - // TarsLexer.g:91:17: ( '0' .. '9' )+ - int cnt6=0; - loop6: - while (true) { - int alt6=2; - int LA6_0 = input.LA(1); - if ( ((LA6_0 >= '0' && LA6_0 <= '9')) ) { - alt6=1; - } - - switch (alt6) { - case 1 : - // TarsLexer.g: - { - if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - - default : - if ( cnt6 >= 1 ) break loop6; - EarlyExitException eee = new EarlyExitException(6, input); - throw eee; - } - cnt6++; - } - - } - break; - - } - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_INTEGER_LITERAL" - - // $ANTLR start "TARS_FLOATING_POINT_LITERAL" - public final void mTARS_FLOATING_POINT_LITERAL() throws RecognitionException { - try { - int _type = TARS_FLOATING_POINT_LITERAL; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:95:5: ( ( '+' | '-' )? ( '0' .. '9' )+ '.' ( '0' .. '9' )+ ) - // TarsLexer.g:95:9: ( '+' | '-' )? ( '0' .. '9' )+ '.' ( '0' .. '9' )+ - { - // TarsLexer.g:95:9: ( '+' | '-' )? - int alt8=2; - int LA8_0 = input.LA(1); - if ( (LA8_0=='+'||LA8_0=='-') ) { - alt8=1; - } - switch (alt8) { - case 1 : - // TarsLexer.g: - { - if ( input.LA(1)=='+'||input.LA(1)=='-' ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - - } - - // TarsLexer.g:95:20: ( '0' .. '9' )+ - int cnt9=0; - loop9: - while (true) { - int alt9=2; - int LA9_0 = input.LA(1); - if ( ((LA9_0 >= '0' && LA9_0 <= '9')) ) { - alt9=1; - } - - switch (alt9) { - case 1 : - // TarsLexer.g: - { - if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - - default : - if ( cnt9 >= 1 ) break loop9; - EarlyExitException eee = new EarlyExitException(9, input); - throw eee; - } - cnt9++; - } - - match('.'); - // TarsLexer.g:95:36: ( '0' .. '9' )+ - int cnt10=0; - loop10: - while (true) { - int alt10=2; - int LA10_0 = input.LA(1); - if ( ((LA10_0 >= '0' && LA10_0 <= '9')) ) { - alt10=1; - } - - switch (alt10) { - case 1 : - // TarsLexer.g: - { - if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - - default : - if ( cnt10 >= 1 ) break loop10; - EarlyExitException eee = new EarlyExitException(10, input); - throw eee; - } - cnt10++; - } - - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_FLOATING_POINT_LITERAL" - - // $ANTLR start "TARS_STRING_LITERAL" - public final void mTARS_STRING_LITERAL() throws RecognitionException { - try { - int _type = TARS_STRING_LITERAL; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:99:5: ( '\"' ( ESC_SEQ |~ ( '\\\\' | '\"' ) )* '\"' ) - // TarsLexer.g:99:7: '\"' ( ESC_SEQ |~ ( '\\\\' | '\"' ) )* '\"' - { - match('\"'); - // TarsLexer.g:99:11: ( ESC_SEQ |~ ( '\\\\' | '\"' ) )* - loop11: - while (true) { - int alt11=3; - int LA11_0 = input.LA(1); - if ( (LA11_0=='\\') ) { - alt11=1; - } - else if ( ((LA11_0 >= '\u0000' && LA11_0 <= '!')||(LA11_0 >= '#' && LA11_0 <= '[')||(LA11_0 >= ']' && LA11_0 <= '\uFFFF')) ) { - alt11=2; - } - - switch (alt11) { - case 1 : - // TarsLexer.g:99:13: ESC_SEQ - { - mESC_SEQ(); - - } - break; - case 2 : - // TarsLexer.g:99:23: ~ ( '\\\\' | '\"' ) - { - if ( (input.LA(1) >= '\u0000' && input.LA(1) <= '!')||(input.LA(1) >= '#' && input.LA(1) <= '[')||(input.LA(1) >= ']' && input.LA(1) <= '\uFFFF') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - - default : - break loop11; - } - } - - match('\"'); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "TARS_STRING_LITERAL" - - // $ANTLR start "LPAREN" - public final void mLPAREN() throws RecognitionException { - try { - int _type = LPAREN; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:103:5: ( '(' ) - // TarsLexer.g:103:9: '(' - { - match('('); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "LPAREN" - - // $ANTLR start "RPAREN" - public final void mRPAREN() throws RecognitionException { - try { - int _type = RPAREN; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:107:5: ( ')' ) - // TarsLexer.g:107:9: ')' - { - match(')'); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "RPAREN" - - // $ANTLR start "LBRACE" - public final void mLBRACE() throws RecognitionException { - try { - int _type = LBRACE; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:111:5: ( '{' ) - // TarsLexer.g:111:9: '{' - { - match('{'); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "LBRACE" - - // $ANTLR start "RBRACE" - public final void mRBRACE() throws RecognitionException { - try { - int _type = RBRACE; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:115:5: ( '}' ) - // TarsLexer.g:115:9: '}' - { - match('}'); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "RBRACE" - - // $ANTLR start "LBRACKET" - public final void mLBRACKET() throws RecognitionException { - try { - int _type = LBRACKET; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:119:5: ( '[' ) - // TarsLexer.g:119:9: '[' - { - match('['); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "LBRACKET" - - // $ANTLR start "RBRACKET" - public final void mRBRACKET() throws RecognitionException { - try { - int _type = RBRACKET; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:123:5: ( ']' ) - // TarsLexer.g:123:9: ']' - { - match(']'); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "RBRACKET" - - // $ANTLR start "SEMI" - public final void mSEMI() throws RecognitionException { - try { - int _type = SEMI; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:127:2: ( ';' ) - // TarsLexer.g:127:4: ';' - { - match(';'); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "SEMI" - - // $ANTLR start "COMMA" - public final void mCOMMA() throws RecognitionException { - try { - int _type = COMMA; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:131:2: ( ',' ) - // TarsLexer.g:131:4: ',' - { - match(','); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "COMMA" - - // $ANTLR start "QUOTE" - public final void mQUOTE() throws RecognitionException { - try { - int _type = QUOTE; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:135:2: ( '\"' ) - // TarsLexer.g:135:4: '\"' - { - match('\"'); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "QUOTE" - - // $ANTLR start "DOT" - public final void mDOT() throws RecognitionException { - try { - int _type = DOT; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:139:2: ( '.' ) - // TarsLexer.g:139:4: '.' - { - match('.'); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "DOT" - - // $ANTLR start "COLON" - public final void mCOLON() throws RecognitionException { - try { - int _type = COLON; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:143:5: ( ':' ) - // TarsLexer.g:143:9: ':' - { - match(':'); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "COLON" - - // $ANTLR start "EQ" - public final void mEQ() throws RecognitionException { - try { - int _type = EQ; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:147:2: ( '=' ) - // TarsLexer.g:147:4: '=' - { - match('='); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "EQ" - - // $ANTLR start "GT" - public final void mGT() throws RecognitionException { - try { - int _type = GT; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:151:2: ( '>' ) - // TarsLexer.g:151:4: '>' - { - match('>'); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "GT" - - // $ANTLR start "LT" - public final void mLT() throws RecognitionException { - try { - int _type = LT; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:155:2: ( '<' ) - // TarsLexer.g:155:4: '<' - { - match('<'); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "LT" - - // $ANTLR start "COMMENT" - public final void mCOMMENT() throws RecognitionException { - try { - int _type = COMMENT; - int _channel = DEFAULT_TOKEN_CHANNEL; - - boolean isDoc = false; - - // TarsLexer.g:162:5: ( '//' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' | '/*' ( options {greedy=false; } : . )* '*/' ) - int alt15=2; - int LA15_0 = input.LA(1); - if ( (LA15_0=='/') ) { - int LA15_1 = input.LA(2); - if ( (LA15_1=='/') ) { - alt15=1; - } - else if ( (LA15_1=='*') ) { - alt15=2; - } - - else { - int nvaeMark = input.mark(); - try { - input.consume(); - NoViableAltException nvae = - new NoViableAltException("", 15, 1, input); - throw nvae; - } finally { - input.rewind(nvaeMark); - } - } - - } - - else { - NoViableAltException nvae = - new NoViableAltException("", 15, 0, input); - throw nvae; - } - - switch (alt15) { - case 1 : - // TarsLexer.g:162:9: '//' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' - { - match("//"); - - // TarsLexer.g:162:14: (~ ( '\\n' | '\\r' ) )* - loop12: - while (true) { - int alt12=2; - int LA12_0 = input.LA(1); - if ( ((LA12_0 >= '\u0000' && LA12_0 <= '\t')||(LA12_0 >= '\u000B' && LA12_0 <= '\f')||(LA12_0 >= '\u000E' && LA12_0 <= '\uFFFF')) ) { - alt12=1; - } - - switch (alt12) { - case 1 : - // TarsLexer.g: - { - if ( (input.LA(1) >= '\u0000' && input.LA(1) <= '\t')||(input.LA(1) >= '\u000B' && input.LA(1) <= '\f')||(input.LA(1) >= '\u000E' && input.LA(1) <= '\uFFFF') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - - default : - break loop12; - } - } - - // TarsLexer.g:162:28: ( '\\r' )? - int alt13=2; - int LA13_0 = input.LA(1); - if ( (LA13_0=='\r') ) { - alt13=1; - } - switch (alt13) { - case 1 : - // TarsLexer.g:162:28: '\\r' - { - match('\r'); - } - break; - - } - - match('\n'); - skip(); - } - break; - case 2 : - // TarsLexer.g:163:9: '/*' ( options {greedy=false; } : . )* '*/' - { - match("/*"); - - - if((char)input.LA(1) == '*'){ - isDoc = true; - } - - // TarsLexer.g:169:9: ( options {greedy=false; } : . )* - loop14: - while (true) { - int alt14=2; - int LA14_0 = input.LA(1); - if ( (LA14_0=='*') ) { - int LA14_1 = input.LA(2); - if ( (LA14_1=='/') ) { - alt14=2; - } - else if ( ((LA14_1 >= '\u0000' && LA14_1 <= '.')||(LA14_1 >= '0' && LA14_1 <= '\uFFFF')) ) { - alt14=1; - } - - } - else if ( ((LA14_0 >= '\u0000' && LA14_0 <= ')')||(LA14_0 >= '+' && LA14_0 <= '\uFFFF')) ) { - alt14=1; - } - - switch (alt14) { - case 1 : - // TarsLexer.g:169:36: . - { - matchAny(); - } - break; - - default : - break loop14; - } - } - - match("*/"); - - - if(isDoc==true){ - _channel=HIDDEN; - } else{ - skip(); - } - - } - break; - - } - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "COMMENT" - - // $ANTLR start "WS" - public final void mWS() throws RecognitionException { - try { - int _type = WS; - int _channel = DEFAULT_TOKEN_CHANNEL; - // TarsLexer.g:180:5: ( ( ' ' | '\\t' | '\\r' | '\\n' ) ) - // TarsLexer.g:180:9: ( ' ' | '\\t' | '\\r' | '\\n' ) - { - if ( (input.LA(1) >= '\t' && input.LA(1) <= '\n')||input.LA(1)=='\r'||input.LA(1)==' ' ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - skip(); - } - - state.type = _type; - state.channel = _channel; - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "WS" - - // $ANTLR start "HEX_DIGIT" - public final void mHEX_DIGIT() throws RecognitionException { - try { - // TarsLexer.g:188:11: ( ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ) ) - // TarsLexer.g: - { - if ( (input.LA(1) >= '0' && input.LA(1) <= '9')||(input.LA(1) >= 'A' && input.LA(1) <= 'F')||(input.LA(1) >= 'a' && input.LA(1) <= 'f') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "HEX_DIGIT" - - // $ANTLR start "ESC_SEQ" - public final void mESC_SEQ() throws RecognitionException { - try { - // TarsLexer.g:192:5: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) | UNICODE_ESC | OCTAL_ESC ) - int alt16=3; - int LA16_0 = input.LA(1); - if ( (LA16_0=='\\') ) { - switch ( input.LA(2) ) { - case '\"': - case '\'': - case '\\': - case 'b': - case 'f': - case 'n': - case 'r': - case 't': - { - alt16=1; - } - break; - case 'u': - { - alt16=2; - } - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - { - alt16=3; - } - break; - default: - int nvaeMark = input.mark(); - try { - input.consume(); - NoViableAltException nvae = - new NoViableAltException("", 16, 1, input); - throw nvae; - } finally { - input.rewind(nvaeMark); - } - } - } - - else { - NoViableAltException nvae = - new NoViableAltException("", 16, 0, input); - throw nvae; - } - - switch (alt16) { - case 1 : - // TarsLexer.g:192:9: '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) - { - match('\\'); - if ( input.LA(1)=='\"'||input.LA(1)=='\''||input.LA(1)=='\\'||input.LA(1)=='b'||input.LA(1)=='f'||input.LA(1)=='n'||input.LA(1)=='r'||input.LA(1)=='t' ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - case 2 : - // TarsLexer.g:193:9: UNICODE_ESC - { - mUNICODE_ESC(); - - } - break; - case 3 : - // TarsLexer.g:194:9: OCTAL_ESC - { - mOCTAL_ESC(); - - } - break; - - } - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "ESC_SEQ" - - // $ANTLR start "OCTAL_ESC" - public final void mOCTAL_ESC() throws RecognitionException { - try { - // TarsLexer.g:199:5: ( '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ) - int alt17=3; - int LA17_0 = input.LA(1); - if ( (LA17_0=='\\') ) { - int LA17_1 = input.LA(2); - if ( ((LA17_1 >= '0' && LA17_1 <= '3')) ) { - int LA17_2 = input.LA(3); - if ( ((LA17_2 >= '0' && LA17_2 <= '7')) ) { - int LA17_4 = input.LA(4); - if ( ((LA17_4 >= '0' && LA17_4 <= '7')) ) { - alt17=1; - } - - else { - alt17=2; - } - - } - - else { - alt17=3; - } - - } - else if ( ((LA17_1 >= '4' && LA17_1 <= '7')) ) { - int LA17_3 = input.LA(3); - if ( ((LA17_3 >= '0' && LA17_3 <= '7')) ) { - alt17=2; - } - - else { - alt17=3; - } - - } - - else { - int nvaeMark = input.mark(); - try { - input.consume(); - NoViableAltException nvae = - new NoViableAltException("", 17, 1, input); - throw nvae; - } finally { - input.rewind(nvaeMark); - } - } - - } - - else { - NoViableAltException nvae = - new NoViableAltException("", 17, 0, input); - throw nvae; - } - - switch (alt17) { - case 1 : - // TarsLexer.g:199:9: '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) - { - match('\\'); - if ( (input.LA(1) >= '0' && input.LA(1) <= '3') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - case 2 : - // TarsLexer.g:200:9: '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) - { - match('\\'); - if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - case 3 : - // TarsLexer.g:201:9: '\\\\' ( '0' .. '7' ) - { - match('\\'); - if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { - input.consume(); - } - else { - MismatchedSetException mse = new MismatchedSetException(null,input); - recover(mse); - throw mse; - } - } - break; - - } - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "OCTAL_ESC" - - // $ANTLR start "UNICODE_ESC" - public final void mUNICODE_ESC() throws RecognitionException { - try { - // TarsLexer.g:206:5: ( '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ) - // TarsLexer.g:206:9: '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT - { - match('\\'); - match('u'); - mHEX_DIGIT(); - - mHEX_DIGIT(); - - mHEX_DIGIT(); - - mHEX_DIGIT(); - - } - - } - finally { - // do for sure before leaving - } - } - // $ANTLR end "UNICODE_ESC" - - @Override - public void mTokens() throws RecognitionException { - // TarsLexer.g:1:8: ( TARS_VOID | TARS_STRUCT | TARS_UNSIGNED | TARS_BOOL | TARS_BYTE | TARS_SHORT | TARS_INT | TARS_DOUBLE | TARS_FLOAT | TARS_LONG | TARS_STRING | TARS_VECTOR | TARS_MAP | TARS_KEY | TARS_ROUTE_KEY | TARS_INCLUDE | TARS_NAMESPACE | TARS_INTERFACE | TARS_OUT | TARS_REQUIRE | TARS_OPTIONAL | TARS_FALSE | TARS_TRUE | TARS_ENUM | TARS_CONST | TARS_IDENTIFIER | TARS_INTEGER_LITERAL | TARS_FLOATING_POINT_LITERAL | TARS_STRING_LITERAL | LPAREN | RPAREN | LBRACE | RBRACE | LBRACKET | RBRACKET | SEMI | COMMA | QUOTE | DOT | COLON | EQ | GT | LT | COMMENT | WS ) - int alt18=45; - alt18 = dfa18.predict(input); - switch (alt18) { - case 1 : - // TarsLexer.g:1:10: TARS_VOID - { - mTARS_VOID(); - - } - break; - case 2 : - // TarsLexer.g:1:20: TARS_STRUCT - { - mTARS_STRUCT(); - - } - break; - case 3 : - // TarsLexer.g:1:32: TARS_UNSIGNED - { - mTARS_UNSIGNED(); - - } - break; - case 4 : - // TarsLexer.g:1:46: TARS_BOOL - { - mTARS_BOOL(); - - } - break; - case 5 : - // TarsLexer.g:1:56: TARS_BYTE - { - mTARS_BYTE(); - - } - break; - case 6 : - // TarsLexer.g:1:66: TARS_SHORT - { - mTARS_SHORT(); - - } - break; - case 7 : - // TarsLexer.g:1:77: TARS_INT - { - mTARS_INT(); - - } - break; - case 8 : - // TarsLexer.g:1:86: TARS_DOUBLE - { - mTARS_DOUBLE(); - - } - break; - case 9 : - // TarsLexer.g:1:98: TARS_FLOAT - { - mTARS_FLOAT(); - - } - break; - case 10 : - // TarsLexer.g:1:109: TARS_LONG - { - mTARS_LONG(); - - } - break; - case 11 : - // TarsLexer.g:1:119: TARS_STRING - { - mTARS_STRING(); - - } - break; - case 12 : - // TarsLexer.g:1:131: TARS_VECTOR - { - mTARS_VECTOR(); - - } - break; - case 13 : - // TarsLexer.g:1:143: TARS_MAP - { - mTARS_MAP(); - - } - break; - case 14 : - // TarsLexer.g:1:152: TARS_KEY - { - mTARS_KEY(); - - } - break; - case 15 : - // TarsLexer.g:1:161: TARS_ROUTE_KEY - { - mTARS_ROUTE_KEY(); - - } - break; - case 16 : - // TarsLexer.g:1:176: TARS_INCLUDE - { - mTARS_INCLUDE(); - - } - break; - case 17 : - // TarsLexer.g:1:189: TARS_NAMESPACE - { - mTARS_NAMESPACE(); - - } - break; - case 18 : - // TarsLexer.g:1:204: TARS_INTERFACE - { - mTARS_INTERFACE(); - - } - break; - case 19 : - // TarsLexer.g:1:219: TARS_OUT - { - mTARS_OUT(); - - } - break; - case 20 : - // TarsLexer.g:1:228: TARS_REQUIRE - { - mTARS_REQUIRE(); - - } - break; - case 21 : - // TarsLexer.g:1:241: TARS_OPTIONAL - { - mTARS_OPTIONAL(); - - } - break; - case 22 : - // TarsLexer.g:1:255: TARS_FALSE - { - mTARS_FALSE(); - - } - break; - case 23 : - // TarsLexer.g:1:266: TARS_TRUE - { - mTARS_TRUE(); - - } - break; - case 24 : - // TarsLexer.g:1:276: TARS_ENUM - { - mTARS_ENUM(); - - } - break; - case 25 : - // TarsLexer.g:1:286: TARS_CONST - { - mTARS_CONST(); - - } - break; - case 26 : - // TarsLexer.g:1:297: TARS_IDENTIFIER - { - mTARS_IDENTIFIER(); - - } - break; - case 27 : - // TarsLexer.g:1:313: TARS_INTEGER_LITERAL - { - mTARS_INTEGER_LITERAL(); - - } - break; - case 28 : - // TarsLexer.g:1:334: TARS_FLOATING_POINT_LITERAL - { - mTARS_FLOATING_POINT_LITERAL(); - - } - break; - case 29 : - // TarsLexer.g:1:362: TARS_STRING_LITERAL - { - mTARS_STRING_LITERAL(); - - } - break; - case 30 : - // TarsLexer.g:1:382: LPAREN - { - mLPAREN(); - - } - break; - case 31 : - // TarsLexer.g:1:389: RPAREN - { - mRPAREN(); - - } - break; - case 32 : - // TarsLexer.g:1:396: LBRACE - { - mLBRACE(); - - } - break; - case 33 : - // TarsLexer.g:1:403: RBRACE - { - mRBRACE(); - - } - break; - case 34 : - // TarsLexer.g:1:410: LBRACKET - { - mLBRACKET(); - - } - break; - case 35 : - // TarsLexer.g:1:419: RBRACKET - { - mRBRACKET(); - - } - break; - case 36 : - // TarsLexer.g:1:428: SEMI - { - mSEMI(); - - } - break; - case 37 : - // TarsLexer.g:1:433: COMMA - { - mCOMMA(); - - } - break; - case 38 : - // TarsLexer.g:1:439: QUOTE - { - mQUOTE(); - - } - break; - case 39 : - // TarsLexer.g:1:445: DOT - { - mDOT(); - - } - break; - case 40 : - // TarsLexer.g:1:449: COLON - { - mCOLON(); - - } - break; - case 41 : - // TarsLexer.g:1:455: EQ - { - mEQ(); - - } - break; - case 42 : - // TarsLexer.g:1:458: GT - { - mGT(); - - } - break; - case 43 : - // TarsLexer.g:1:461: LT - { - mLT(); - - } - break; - case 44 : - // TarsLexer.g:1:464: COMMENT - { - mCOMMENT(); - - } - break; - case 45 : - // TarsLexer.g:1:472: WS - { - mWS(); - - } - break; - - } - } - - - protected DFA18 dfa18 = new DFA18(this); - static final String DFA18_eotS = - "\1\uffff\13\23\1\uffff\5\23\1\75\2\uffff\1\75\1\100\17\uffff\27\23\4\uffff"+ - "\7\23\1\140\4\23\1\145\1\23\1\147\2\23\1\152\4\23\1\157\5\23\1\165\1\166"+ - "\1\23\1\uffff\3\23\1\173\1\uffff\1\23\1\uffff\2\23\1\uffff\1\23\1\u0080"+ - "\1\u0081\1\23\1\uffff\3\23\1\u0086\1\23\2\uffff\2\23\1\u008a\1\u008b\1"+ - "\uffff\4\23\2\uffff\1\u0090\1\u0091\1\u0092\1\u0093\1\uffff\2\23\1\u0096"+ - "\2\uffff\1\u0097\3\23\4\uffff\2\23\2\uffff\1\23\1\u009e\1\23\1\u00a0\1"+ - "\23\1\u00a2\1\uffff\1\u00a3\1\uffff\1\u00a4\3\uffff"; - static final String DFA18_eofS = - "\u00a5\uffff"; - static final String DFA18_minS = - "\1\11\1\145\1\150\1\156\1\157\1\156\1\157\1\141\1\157\1\141\2\145\1\uffff"+ - "\1\60\1\162\1\156\1\157\1\60\1\56\1\uffff\1\60\1\56\1\0\17\uffff\1\151"+ - "\1\143\1\162\1\157\1\163\1\157\2\164\1\165\1\157\1\154\1\156\1\160\1\144"+ - "\1\171\1\165\1\161\2\164\1\60\2\165\1\156\4\uffff\1\144\1\164\1\151\1"+ - "\162\1\151\1\154\1\145\1\60\1\142\1\141\1\163\1\147\1\60\1\165\1\60\1"+ - "\164\1\165\1\60\1\151\1\145\1\155\1\163\1\60\1\157\1\143\1\156\1\164\1"+ - "\147\2\60\1\162\1\uffff\1\154\1\164\1\145\1\60\1\uffff\1\154\1\uffff\1"+ - "\145\1\151\1\uffff\1\157\2\60\1\164\1\uffff\1\162\1\164\1\147\1\60\1\156"+ - "\2\uffff\1\146\1\145\2\60\1\uffff\1\145\1\153\1\162\1\156\2\uffff\4\60"+ - "\1\uffff\1\145\1\141\1\60\2\uffff\1\60\2\145\1\141\4\uffff\1\144\1\143"+ - "\2\uffff\1\171\1\60\1\154\1\60\1\145\1\60\1\uffff\1\60\1\uffff\1\60\3"+ - "\uffff"; - static final String DFA18_maxS = - "\1\175\1\157\1\164\1\156\1\171\1\156\1\157\1\154\2\157\1\145\1\157\1\uffff"+ - "\1\165\1\162\1\156\1\157\1\67\1\71\1\uffff\2\71\1\uffff\17\uffff\1\151"+ - "\1\143\1\162\1\157\1\163\1\157\2\164\1\165\1\157\1\154\1\156\1\160\1\144"+ - "\1\171\1\165\1\161\2\164\1\67\2\165\1\156\4\uffff\1\144\1\164\1\165\1"+ - "\162\1\151\1\154\1\145\1\172\1\142\1\141\1\163\1\147\1\172\1\165\1\172"+ - "\1\164\1\165\1\172\1\151\1\145\1\155\1\163\1\172\1\157\1\143\1\156\1\164"+ - "\1\147\2\172\1\162\1\uffff\1\154\1\164\1\145\1\172\1\uffff\1\154\1\uffff"+ - "\1\145\1\151\1\uffff\1\157\2\172\1\164\1\uffff\1\162\1\164\1\147\1\172"+ - "\1\156\2\uffff\1\146\1\145\2\172\1\uffff\1\145\1\153\1\162\1\156\2\uffff"+ - "\4\172\1\uffff\1\145\1\141\1\172\2\uffff\1\172\2\145\1\141\4\uffff\1\144"+ - "\1\143\2\uffff\1\171\1\172\1\154\1\172\1\145\1\172\1\uffff\1\172\1\uffff"+ - "\1\172\3\uffff"; - static final String DFA18_acceptS = - "\14\uffff\1\20\6\uffff\1\32\3\uffff\1\36\1\37\1\40\1\41\1\42\1\43\1\44"+ - "\1\45\1\47\1\50\1\51\1\52\1\53\1\54\1\55\27\uffff\1\33\1\34\1\35\1\46"+ - "\37\uffff\1\7\4\uffff\1\15\1\uffff\1\16\2\uffff\1\23\4\uffff\1\1\5\uffff"+ - "\1\4\1\5\4\uffff\1\12\4\uffff\1\27\1\30\4\uffff\1\6\3\uffff\1\11\1\26"+ - "\4\uffff\1\31\1\14\1\2\1\13\2\uffff\1\10\1\21\6\uffff\1\24\1\uffff\1\3"+ - "\1\uffff\1\17\1\25\1\22"; - static final String DFA18_specialS = - "\26\uffff\1\0\u008e\uffff}>"; - static final String[] DFA18_transitionS = { - "\2\45\2\uffff\1\45\22\uffff\1\45\1\uffff\1\26\1\14\4\uffff\1\27\1\30"+ - "\1\uffff\1\24\1\36\1\24\1\37\1\44\1\22\11\25\1\40\1\35\1\43\1\41\1\42"+ - "\2\uffff\16\23\1\21\13\23\1\33\1\uffff\1\34\1\uffff\1\23\1\uffff\1\23"+ - "\1\4\1\20\1\6\1\17\1\7\2\23\1\5\1\23\1\12\1\10\1\11\1\23\1\15\2\23\1"+ - "\13\1\2\1\16\1\3\1\1\4\23\1\31\1\uffff\1\32", - "\1\47\11\uffff\1\46", - "\1\51\13\uffff\1\50", - "\1\52", - "\1\53\11\uffff\1\54", - "\1\55", - "\1\56", - "\1\60\12\uffff\1\57", - "\1\61", - "\1\62\15\uffff\1\63", - "\1\64", - "\1\66\11\uffff\1\65", - "", - "\10\71\70\uffff\1\70\4\uffff\1\67", - "\1\72", - "\1\73", - "\1\74", - "\10\71", - "\1\76\1\uffff\12\25", - "", - "\12\25", - "\1\76\1\uffff\12\25", - "\0\77", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "\1\101", - "\1\102", - "\1\103", - "\1\104", - "\1\105", - "\1\106", - "\1\107", - "\1\110", - "\1\111", - "\1\112", - "\1\113", - "\1\114", - "\1\115", - "\1\116", - "\1\117", - "\1\120", - "\1\121", - "\1\122", - "\1\123", - "\10\71", - "\1\124", - "\1\125", - "\1\126", - "", - "", - "", - "", - "\1\127", - "\1\130", - "\1\132\13\uffff\1\131", - "\1\133", - "\1\134", - "\1\135", - "\1\136", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\4\23\1\137\25\23", - "\1\141", - "\1\142", - "\1\143", - "\1\144", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\1\146", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\1\150", - "\1\151", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\1\153", - "\1\154", - "\1\155", - "\1\156", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\1\160", - "\1\161", - "\1\162", - "\1\163", - "\1\164", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\1\167", - "", - "\1\170", - "\1\171", - "\1\172", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "", - "\1\174", - "", - "\1\175", - "\1\176", - "", - "\1\177", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\1\u0082", - "", - "\1\u0083", - "\1\u0084", - "\1\u0085", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\1\u0087", - "", - "", - "\1\u0088", - "\1\u0089", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "", - "\1\u008c", - "\1\u008d", - "\1\u008e", - "\1\u008f", - "", - "", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "", - "\1\u0094", - "\1\u0095", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "", - "", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\1\u0098", - "\1\u0099", - "\1\u009a", - "", - "", - "", - "", - "\1\u009b", - "\1\u009c", - "", - "", - "\1\u009d", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\1\u009f", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "\1\u00a1", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "", - "\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff\32\23", - "", - "", - "" - }; - - static final short[] DFA18_eot = DFA.unpackEncodedString(DFA18_eotS); - static final short[] DFA18_eof = DFA.unpackEncodedString(DFA18_eofS); - static final char[] DFA18_min = DFA.unpackEncodedStringToUnsignedChars(DFA18_minS); - static final char[] DFA18_max = DFA.unpackEncodedStringToUnsignedChars(DFA18_maxS); - static final short[] DFA18_accept = DFA.unpackEncodedString(DFA18_acceptS); - static final short[] DFA18_special = DFA.unpackEncodedString(DFA18_specialS); - static final short[][] DFA18_transition; - - static { - int numStates = DFA18_transitionS.length; - DFA18_transition = new short[numStates][]; - for (int i=0; i= '\u0000' && LA18_22 <= '\uFFFF')) ) {s = 63;} - else s = 64; - if ( s>=0 ) return s; - break; - } - NoViableAltException nvae = - new NoViableAltException(getDescription(), 18, _s, input); - error(nvae); - throw nvae; - } - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/TarsParser.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/TarsParser.java deleted file mode 100644 index 3dfd5955..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/TarsParser.java +++ /dev/null @@ -1,3200 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse; -import com.qq.tars.maven.parse.ast.*; - - -import org.antlr.runtime.*; -import java.util.Stack; -import java.util.List; -import java.util.ArrayList; - -import org.antlr.runtime.tree.*; - - -@SuppressWarnings("all") -public class TarsParser extends Parser { - public static final String[] tokenNames = new String[] { - "", "", "", "", "COLON", "COMMA", "COMMENT", "DOT", - "EQ", "ESC_SEQ", "GT", "HEX_DIGIT", "LBRACE", "LBRACKET", "LPAREN", "LT", - "OCTAL_ESC", "QUOTE", "RBRACE", "RBRACKET", "RPAREN", "SEMI", "TARS_BOOL", - "TARS_BYTE", "TARS_CONST", "TARS_DOUBLE", "TARS_ENUM", "TARS_FALSE", "TARS_FLOAT", - "TARS_FLOATING_POINT_LITERAL", "TARS_IDENTIFIER", "TARS_INCLUDE", "TARS_INT", - "TARS_INTEGER_LITERAL", "TARS_INTERFACE", "TARS_KEY", "TARS_LONG", "TARS_MAP", - "TARS_NAMESPACE", "TARS_OPTIONAL", "TARS_OUT", "TARS_REQUIRE", "TARS_ROUTE_KEY", - "TARS_SHORT", "TARS_STRING", "TARS_STRING_LITERAL", "TARS_STRUCT", "TARS_TRUE", - "TARS_UNSIGNED", "TARS_VECTOR", "TARS_VOID", "UNICODE_ESC", "WS", "TARS_OPERATION", - "TARS_PARAM", "TARS_REF", "TARS_ROOT", "TARS_STRUCT_MEMBER" - }; - public static final int EOF=-1; - public static final int COLON=4; - public static final int COMMA=5; - public static final int COMMENT=6; - public static final int DOT=7; - public static final int EQ=8; - public static final int ESC_SEQ=9; - public static final int GT=10; - public static final int HEX_DIGIT=11; - public static final int LBRACE=12; - public static final int LBRACKET=13; - public static final int LPAREN=14; - public static final int LT=15; - public static final int OCTAL_ESC=16; - public static final int QUOTE=17; - public static final int RBRACE=18; - public static final int RBRACKET=19; - public static final int RPAREN=20; - public static final int SEMI=21; - public static final int TARS_BOOL=22; - public static final int TARS_BYTE=23; - public static final int TARS_CONST=24; - public static final int TARS_DOUBLE=25; - public static final int TARS_ENUM=26; - public static final int TARS_FALSE=27; - public static final int TARS_FLOAT=28; - public static final int TARS_FLOATING_POINT_LITERAL=29; - public static final int TARS_IDENTIFIER=30; - public static final int TARS_INCLUDE=31; - public static final int TARS_INT=32; - public static final int TARS_INTEGER_LITERAL=33; - public static final int TARS_INTERFACE=34; - public static final int TARS_KEY=35; - public static final int TARS_LONG=36; - public static final int TARS_MAP=37; - public static final int TARS_NAMESPACE=38; - public static final int TARS_OPTIONAL=39; - public static final int TARS_OUT=40; - public static final int TARS_REQUIRE=41; - public static final int TARS_ROUTE_KEY=42; - public static final int TARS_SHORT=43; - public static final int TARS_STRING=44; - public static final int TARS_STRING_LITERAL=45; - public static final int TARS_STRUCT=46; - public static final int TARS_TRUE=47; - public static final int TARS_UNSIGNED=48; - public static final int TARS_VECTOR=49; - public static final int TARS_VOID=50; - public static final int UNICODE_ESC=51; - public static final int WS=52; - public static final int TARS_OPERATION=53; - public static final int TARS_PARAM=54; - public static final int TARS_REF=55; - public static final int TARS_ROOT=56; - public static final int TARS_STRUCT_MEMBER=57; - - // delegates - public Parser[] getDelegates() { - return new Parser[] {}; - } - - // delegators - - - public TarsParser(TokenStream input) { - this(input, new RecognizerSharedState()); - } - public TarsParser(TokenStream input, RecognizerSharedState state) { - super(input, state); - } - - protected TreeAdaptor adaptor = new CommonTreeAdaptor(); - - public void setTreeAdaptor(TreeAdaptor adaptor) { - this.adaptor = adaptor; - } - public TreeAdaptor getTreeAdaptor() { - return adaptor; - } - @Override public String[] getTokenNames() { return TarsParser.tokenNames; } - @Override public String getGrammarFileName() { return "TarsParser.g"; } - - - public static class start_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "start" - // TarsParser.g:22:1: start : ( include_def )* ( namespace_def )+ -> ^( TARS_ROOT ( include_def )* ( namespace_def )+ ) ; - public final TarsParser.start_return start() throws RecognitionException { - TarsParser.start_return retval = new TarsParser.start_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - ParserRuleReturnScope include_def1 =null; - ParserRuleReturnScope namespace_def2 =null; - - RewriteRuleSubtreeStream stream_include_def=new RewriteRuleSubtreeStream(adaptor,"rule include_def"); - RewriteRuleSubtreeStream stream_namespace_def=new RewriteRuleSubtreeStream(adaptor,"rule namespace_def"); - - try { - // TarsParser.g:23:2: ( ( include_def )* ( namespace_def )+ -> ^( TARS_ROOT ( include_def )* ( namespace_def )+ ) ) - // TarsParser.g:23:4: ( include_def )* ( namespace_def )+ - { - // TarsParser.g:23:4: ( include_def )* - loop1: - while (true) { - int alt1=2; - int LA1_0 = input.LA(1); - if ( (LA1_0==TARS_INCLUDE) ) { - alt1=1; - } - - switch (alt1) { - case 1 : - // TarsParser.g:23:4: include_def - { - pushFollow(FOLLOW_include_def_in_start70); - include_def1=include_def(); - state._fsp--; - - stream_include_def.add(include_def1.getTree()); - } - break; - - default : - break loop1; - } - } - - // TarsParser.g:23:17: ( namespace_def )+ - int cnt2=0; - loop2: - while (true) { - int alt2=2; - int LA2_0 = input.LA(1); - if ( (LA2_0==TARS_NAMESPACE) ) { - alt2=1; - } - - switch (alt2) { - case 1 : - // TarsParser.g:23:17: namespace_def - { - pushFollow(FOLLOW_namespace_def_in_start73); - namespace_def2=namespace_def(); - state._fsp--; - - stream_namespace_def.add(namespace_def2.getTree()); - } - break; - - default : - if ( cnt2 >= 1 ) break loop2; - EarlyExitException eee = new EarlyExitException(2, input); - throw eee; - } - cnt2++; - } - - // AST REWRITE - // elements: include_def, namespace_def - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 24:3: -> ^( TARS_ROOT ( include_def )* ( namespace_def )+ ) - { - // TarsParser.g:24:6: ^( TARS_ROOT ( include_def )* ( namespace_def )+ ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsRoot(TARS_ROOT), root_1); - // TarsParser.g:24:28: ( include_def )* - while ( stream_include_def.hasNext() ) { - adaptor.addChild(root_1, stream_include_def.nextTree()); - } - stream_include_def.reset(); - - if ( !(stream_namespace_def.hasNext()) ) { - throw new RewriteEarlyExitException(); - } - while ( stream_namespace_def.hasNext() ) { - adaptor.addChild(root_1, stream_namespace_def.nextTree()); - } - stream_namespace_def.reset(); - - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "start" - - - public static class include_def_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "include_def" - // TarsParser.g:27:1: include_def : TARS_INCLUDE TARS_STRING_LITERAL -> ^( TARS_INCLUDE[$TARS_STRING_LITERAL.text] ) ; - public final TarsParser.include_def_return include_def() throws RecognitionException { - TarsParser.include_def_return retval = new TarsParser.include_def_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token TARS_INCLUDE3=null; - Token TARS_STRING_LITERAL4=null; - - Object TARS_INCLUDE3_tree=null; - Object TARS_STRING_LITERAL4_tree=null; - RewriteRuleTokenStream stream_TARS_STRING_LITERAL=new RewriteRuleTokenStream(adaptor,"token TARS_STRING_LITERAL"); - RewriteRuleTokenStream stream_TARS_INCLUDE=new RewriteRuleTokenStream(adaptor,"token TARS_INCLUDE"); - - try { - // TarsParser.g:28:2: ( TARS_INCLUDE TARS_STRING_LITERAL -> ^( TARS_INCLUDE[$TARS_STRING_LITERAL.text] ) ) - // TarsParser.g:28:4: TARS_INCLUDE TARS_STRING_LITERAL - { - TARS_INCLUDE3=(Token)match(input,TARS_INCLUDE,FOLLOW_TARS_INCLUDE_in_include_def102); - stream_TARS_INCLUDE.add(TARS_INCLUDE3); - - TARS_STRING_LITERAL4=(Token)match(input,TARS_STRING_LITERAL,FOLLOW_TARS_STRING_LITERAL_in_include_def104); - stream_TARS_STRING_LITERAL.add(TARS_STRING_LITERAL4); - - // AST REWRITE - // elements: TARS_INCLUDE - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 29:3: -> ^( TARS_INCLUDE[$TARS_STRING_LITERAL.text] ) - { - // TarsParser.g:29:6: ^( TARS_INCLUDE[$TARS_STRING_LITERAL.text] ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsInclude(TARS_INCLUDE, (TARS_STRING_LITERAL4!=null?TARS_STRING_LITERAL4.getText():null)), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "include_def" - - - public static class namespace_def_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "namespace_def" - // TarsParser.g:32:1: namespace_def : TARS_NAMESPACE TARS_IDENTIFIER LBRACE ( definition SEMI )+ RBRACE -> ^( TARS_NAMESPACE[$TARS_IDENTIFIER.text] ( definition )+ ) ; - public final TarsParser.namespace_def_return namespace_def() throws RecognitionException { - TarsParser.namespace_def_return retval = new TarsParser.namespace_def_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token TARS_NAMESPACE5=null; - Token TARS_IDENTIFIER6=null; - Token LBRACE7=null; - Token SEMI9=null; - Token RBRACE10=null; - ParserRuleReturnScope definition8 =null; - - Object TARS_NAMESPACE5_tree=null; - Object TARS_IDENTIFIER6_tree=null; - Object LBRACE7_tree=null; - Object SEMI9_tree=null; - Object RBRACE10_tree=null; - RewriteRuleTokenStream stream_TARS_NAMESPACE=new RewriteRuleTokenStream(adaptor,"token TARS_NAMESPACE"); - RewriteRuleTokenStream stream_TARS_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token TARS_IDENTIFIER"); - RewriteRuleTokenStream stream_RBRACE=new RewriteRuleTokenStream(adaptor,"token RBRACE"); - RewriteRuleTokenStream stream_SEMI=new RewriteRuleTokenStream(adaptor,"token SEMI"); - RewriteRuleTokenStream stream_LBRACE=new RewriteRuleTokenStream(adaptor,"token LBRACE"); - RewriteRuleSubtreeStream stream_definition=new RewriteRuleSubtreeStream(adaptor,"rule definition"); - - try { - // TarsParser.g:33:2: ( TARS_NAMESPACE TARS_IDENTIFIER LBRACE ( definition SEMI )+ RBRACE -> ^( TARS_NAMESPACE[$TARS_IDENTIFIER.text] ( definition )+ ) ) - // TarsParser.g:33:4: TARS_NAMESPACE TARS_IDENTIFIER LBRACE ( definition SEMI )+ RBRACE - { - TARS_NAMESPACE5=(Token)match(input,TARS_NAMESPACE,FOLLOW_TARS_NAMESPACE_in_namespace_def127); - stream_TARS_NAMESPACE.add(TARS_NAMESPACE5); - - TARS_IDENTIFIER6=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_namespace_def129); - stream_TARS_IDENTIFIER.add(TARS_IDENTIFIER6); - - LBRACE7=(Token)match(input,LBRACE,FOLLOW_LBRACE_in_namespace_def131); - stream_LBRACE.add(LBRACE7); - - // TarsParser.g:33:42: ( definition SEMI )+ - int cnt3=0; - loop3: - while (true) { - int alt3=2; - int LA3_0 = input.LA(1); - if ( (LA3_0==TARS_CONST||LA3_0==TARS_ENUM||(LA3_0 >= TARS_INTERFACE && LA3_0 <= TARS_KEY)||LA3_0==TARS_STRUCT) ) { - alt3=1; - } - - switch (alt3) { - case 1 : - // TarsParser.g:33:43: definition SEMI - { - pushFollow(FOLLOW_definition_in_namespace_def134); - definition8=definition(); - state._fsp--; - - stream_definition.add(definition8.getTree()); - SEMI9=(Token)match(input,SEMI,FOLLOW_SEMI_in_namespace_def136); - stream_SEMI.add(SEMI9); - - } - break; - - default : - if ( cnt3 >= 1 ) break loop3; - EarlyExitException eee = new EarlyExitException(3, input); - throw eee; - } - cnt3++; - } - - RBRACE10=(Token)match(input,RBRACE,FOLLOW_RBRACE_in_namespace_def140); - stream_RBRACE.add(RBRACE10); - - // AST REWRITE - // elements: definition, TARS_NAMESPACE - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 34:3: -> ^( TARS_NAMESPACE[$TARS_IDENTIFIER.text] ( definition )+ ) - { - // TarsParser.g:34:6: ^( TARS_NAMESPACE[$TARS_IDENTIFIER.text] ( definition )+ ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsNamespace(TARS_NAMESPACE, (TARS_IDENTIFIER6!=null?TARS_IDENTIFIER6.getText():null)), root_1); - if ( !(stream_definition.hasNext()) ) { - throw new RewriteEarlyExitException(); - } - while ( stream_definition.hasNext() ) { - adaptor.addChild(root_1, stream_definition.nextTree()); - } - stream_definition.reset(); - - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "namespace_def" - - - public static class definition_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "definition" - // TarsParser.g:37:1: definition : ( const_def | enum_def | struct_def | key_def | interface_def ); - public final TarsParser.definition_return definition() throws RecognitionException { - TarsParser.definition_return retval = new TarsParser.definition_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - ParserRuleReturnScope const_def11 =null; - ParserRuleReturnScope enum_def12 =null; - ParserRuleReturnScope struct_def13 =null; - ParserRuleReturnScope key_def14 =null; - ParserRuleReturnScope interface_def15 =null; - - - try { - // TarsParser.g:38:2: ( const_def | enum_def | struct_def | key_def | interface_def ) - int alt4=5; - switch ( input.LA(1) ) { - case TARS_CONST: - { - alt4=1; - } - break; - case TARS_ENUM: - { - alt4=2; - } - break; - case TARS_STRUCT: - { - alt4=3; - } - break; - case TARS_KEY: - { - alt4=4; - } - break; - case TARS_INTERFACE: - { - alt4=5; - } - break; - default: - NoViableAltException nvae = - new NoViableAltException("", 4, 0, input); - throw nvae; - } - switch (alt4) { - case 1 : - // TarsParser.g:38:4: const_def - { - root_0 = (Object)adaptor.nil(); - - - pushFollow(FOLLOW_const_def_in_definition167); - const_def11=const_def(); - state._fsp--; - - adaptor.addChild(root_0, const_def11.getTree()); - - } - break; - case 2 : - // TarsParser.g:39:6: enum_def - { - root_0 = (Object)adaptor.nil(); - - - pushFollow(FOLLOW_enum_def_in_definition174); - enum_def12=enum_def(); - state._fsp--; - - adaptor.addChild(root_0, enum_def12.getTree()); - - } - break; - case 3 : - // TarsParser.g:40:4: struct_def - { - root_0 = (Object)adaptor.nil(); - - - pushFollow(FOLLOW_struct_def_in_definition179); - struct_def13=struct_def(); - state._fsp--; - - adaptor.addChild(root_0, struct_def13.getTree()); - - } - break; - case 4 : - // TarsParser.g:41:4: key_def - { - root_0 = (Object)adaptor.nil(); - - - pushFollow(FOLLOW_key_def_in_definition184); - key_def14=key_def(); - state._fsp--; - - adaptor.addChild(root_0, key_def14.getTree()); - - } - break; - case 5 : - // TarsParser.g:42:4: interface_def - { - root_0 = (Object)adaptor.nil(); - - - pushFollow(FOLLOW_interface_def_in_definition189); - interface_def15=interface_def(); - state._fsp--; - - adaptor.addChild(root_0, interface_def15.getTree()); - - } - break; - - } - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "definition" - - - public static class const_def_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "const_def" - // TarsParser.g:45:1: const_def : TARS_CONST type_primitive TARS_IDENTIFIER EQ v= const_initializer -> ^( TARS_CONST[$TARS_IDENTIFIER.text, $v.text] type_primitive ) ; - public final TarsParser.const_def_return const_def() throws RecognitionException { - TarsParser.const_def_return retval = new TarsParser.const_def_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token TARS_CONST16=null; - Token TARS_IDENTIFIER18=null; - Token EQ19=null; - ParserRuleReturnScope v =null; - ParserRuleReturnScope type_primitive17 =null; - - Object TARS_CONST16_tree=null; - Object TARS_IDENTIFIER18_tree=null; - Object EQ19_tree=null; - RewriteRuleTokenStream stream_TARS_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token TARS_IDENTIFIER"); - RewriteRuleTokenStream stream_EQ=new RewriteRuleTokenStream(adaptor,"token EQ"); - RewriteRuleTokenStream stream_TARS_CONST=new RewriteRuleTokenStream(adaptor,"token TARS_CONST"); - RewriteRuleSubtreeStream stream_type_primitive=new RewriteRuleSubtreeStream(adaptor,"rule type_primitive"); - RewriteRuleSubtreeStream stream_const_initializer=new RewriteRuleSubtreeStream(adaptor,"rule const_initializer"); - - try { - // TarsParser.g:46:2: ( TARS_CONST type_primitive TARS_IDENTIFIER EQ v= const_initializer -> ^( TARS_CONST[$TARS_IDENTIFIER.text, $v.text] type_primitive ) ) - // TarsParser.g:46:4: TARS_CONST type_primitive TARS_IDENTIFIER EQ v= const_initializer - { - TARS_CONST16=(Token)match(input,TARS_CONST,FOLLOW_TARS_CONST_in_const_def202); - stream_TARS_CONST.add(TARS_CONST16); - - pushFollow(FOLLOW_type_primitive_in_const_def204); - type_primitive17=type_primitive(); - state._fsp--; - - stream_type_primitive.add(type_primitive17.getTree()); - TARS_IDENTIFIER18=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_const_def206); - stream_TARS_IDENTIFIER.add(TARS_IDENTIFIER18); - - EQ19=(Token)match(input,EQ,FOLLOW_EQ_in_const_def208); - stream_EQ.add(EQ19); - - pushFollow(FOLLOW_const_initializer_in_const_def212); - v=const_initializer(); - state._fsp--; - - stream_const_initializer.add(v.getTree()); - // AST REWRITE - // elements: type_primitive, TARS_CONST - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 47:3: -> ^( TARS_CONST[$TARS_IDENTIFIER.text, $v.text] type_primitive ) - { - // TarsParser.g:47:6: ^( TARS_CONST[$TARS_IDENTIFIER.text, $v.text] type_primitive ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsConst(TARS_CONST, (TARS_IDENTIFIER18!=null?TARS_IDENTIFIER18.getText():null), (v!=null?input.toString(v.start,v.stop):null)), root_1); - adaptor.addChild(root_1, stream_type_primitive.nextTree()); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "const_def" - - - public static class enum_def_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "enum_def" - // TarsParser.g:50:1: enum_def : ( TARS_ENUM n= TARS_IDENTIFIER LBRACE m+= TARS_IDENTIFIER ( COMMA m+= TARS_IDENTIFIER )* ( COMMA )? RBRACE -> ^( TARS_ENUM[$n.text] ( $m)+ ) | TARS_ENUM n= TARS_IDENTIFIER LBRACE m+= TARS_IDENTIFIER EQ v+= TARS_INTEGER_LITERAL ( COMMA m+= TARS_IDENTIFIER EQ v+= TARS_INTEGER_LITERAL )* ( COMMA )? RBRACE -> ^( TARS_ENUM[$n.text] ( $m)+ ( $v)+ ) ); - public final TarsParser.enum_def_return enum_def() throws RecognitionException { - TarsParser.enum_def_return retval = new TarsParser.enum_def_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token n=null; - Token TARS_ENUM20=null; - Token LBRACE21=null; - Token COMMA22=null; - Token COMMA23=null; - Token RBRACE24=null; - Token TARS_ENUM25=null; - Token LBRACE26=null; - Token EQ27=null; - Token COMMA28=null; - Token EQ29=null; - Token COMMA30=null; - Token RBRACE31=null; - Token m=null; - Token v=null; - List list_m=null; - List list_v=null; - - Object n_tree=null; - Object TARS_ENUM20_tree=null; - Object LBRACE21_tree=null; - Object COMMA22_tree=null; - Object COMMA23_tree=null; - Object RBRACE24_tree=null; - Object TARS_ENUM25_tree=null; - Object LBRACE26_tree=null; - Object EQ27_tree=null; - Object COMMA28_tree=null; - Object EQ29_tree=null; - Object COMMA30_tree=null; - Object RBRACE31_tree=null; - Object m_tree=null; - Object v_tree=null; - RewriteRuleTokenStream stream_TARS_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token TARS_IDENTIFIER"); - RewriteRuleTokenStream stream_TARS_ENUM=new RewriteRuleTokenStream(adaptor,"token TARS_ENUM"); - RewriteRuleTokenStream stream_RBRACE=new RewriteRuleTokenStream(adaptor,"token RBRACE"); - RewriteRuleTokenStream stream_EQ=new RewriteRuleTokenStream(adaptor,"token EQ"); - RewriteRuleTokenStream stream_COMMA=new RewriteRuleTokenStream(adaptor,"token COMMA"); - RewriteRuleTokenStream stream_TARS_INTEGER_LITERAL=new RewriteRuleTokenStream(adaptor,"token TARS_INTEGER_LITERAL"); - RewriteRuleTokenStream stream_LBRACE=new RewriteRuleTokenStream(adaptor,"token LBRACE"); - - try { - // TarsParser.g:51:2: ( TARS_ENUM n= TARS_IDENTIFIER LBRACE m+= TARS_IDENTIFIER ( COMMA m+= TARS_IDENTIFIER )* ( COMMA )? RBRACE -> ^( TARS_ENUM[$n.text] ( $m)+ ) | TARS_ENUM n= TARS_IDENTIFIER LBRACE m+= TARS_IDENTIFIER EQ v+= TARS_INTEGER_LITERAL ( COMMA m+= TARS_IDENTIFIER EQ v+= TARS_INTEGER_LITERAL )* ( COMMA )? RBRACE -> ^( TARS_ENUM[$n.text] ( $m)+ ( $v)+ ) ) - int alt9=2; - int LA9_0 = input.LA(1); - if ( (LA9_0==TARS_ENUM) ) { - int LA9_1 = input.LA(2); - if ( (LA9_1==TARS_IDENTIFIER) ) { - int LA9_2 = input.LA(3); - if ( (LA9_2==LBRACE) ) { - int LA9_3 = input.LA(4); - if ( (LA9_3==TARS_IDENTIFIER) ) { - int LA9_4 = input.LA(5); - if ( (LA9_4==EQ) ) { - alt9=2; - } - else if ( (LA9_4==COMMA||LA9_4==RBRACE) ) { - alt9=1; - } - - else { - int nvaeMark = input.mark(); - try { - for (int nvaeConsume = 0; nvaeConsume < 5 - 1; nvaeConsume++) { - input.consume(); - } - NoViableAltException nvae = - new NoViableAltException("", 9, 4, input); - throw nvae; - } finally { - input.rewind(nvaeMark); - } - } - - } - - else { - int nvaeMark = input.mark(); - try { - for (int nvaeConsume = 0; nvaeConsume < 4 - 1; nvaeConsume++) { - input.consume(); - } - NoViableAltException nvae = - new NoViableAltException("", 9, 3, input); - throw nvae; - } finally { - input.rewind(nvaeMark); - } - } - - } - - else { - int nvaeMark = input.mark(); - try { - for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { - input.consume(); - } - NoViableAltException nvae = - new NoViableAltException("", 9, 2, input); - throw nvae; - } finally { - input.rewind(nvaeMark); - } - } - - } - - else { - int nvaeMark = input.mark(); - try { - input.consume(); - NoViableAltException nvae = - new NoViableAltException("", 9, 1, input); - throw nvae; - } finally { - input.rewind(nvaeMark); - } - } - - } - - else { - NoViableAltException nvae = - new NoViableAltException("", 9, 0, input); - throw nvae; - } - - switch (alt9) { - case 1 : - // TarsParser.g:51:5: TARS_ENUM n= TARS_IDENTIFIER LBRACE m+= TARS_IDENTIFIER ( COMMA m+= TARS_IDENTIFIER )* ( COMMA )? RBRACE - { - TARS_ENUM20=(Token)match(input,TARS_ENUM,FOLLOW_TARS_ENUM_in_enum_def238); - stream_TARS_ENUM.add(TARS_ENUM20); - - n=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_enum_def242); - stream_TARS_IDENTIFIER.add(n); - - LBRACE21=(Token)match(input,LBRACE,FOLLOW_LBRACE_in_enum_def244); - stream_LBRACE.add(LBRACE21); - - m=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_enum_def248); - stream_TARS_IDENTIFIER.add(m); - - if (list_m==null) list_m=new ArrayList(); - list_m.add(m); - // TarsParser.g:51:59: ( COMMA m+= TARS_IDENTIFIER )* - loop5: - while (true) { - int alt5=2; - int LA5_0 = input.LA(1); - if ( (LA5_0==COMMA) ) { - int LA5_1 = input.LA(2); - if ( (LA5_1==TARS_IDENTIFIER) ) { - alt5=1; - } - - } - - switch (alt5) { - case 1 : - // TarsParser.g:51:60: COMMA m+= TARS_IDENTIFIER - { - COMMA22=(Token)match(input,COMMA,FOLLOW_COMMA_in_enum_def251); - stream_COMMA.add(COMMA22); - - m=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_enum_def255); - stream_TARS_IDENTIFIER.add(m); - - if (list_m==null) list_m=new ArrayList(); - list_m.add(m); - } - break; - - default : - break loop5; - } - } - - // TarsParser.g:51:87: ( COMMA )? - int alt6=2; - int LA6_0 = input.LA(1); - if ( (LA6_0==COMMA) ) { - alt6=1; - } - switch (alt6) { - case 1 : - // TarsParser.g:51:87: COMMA - { - COMMA23=(Token)match(input,COMMA,FOLLOW_COMMA_in_enum_def259); - stream_COMMA.add(COMMA23); - - } - break; - - } - - RBRACE24=(Token)match(input,RBRACE,FOLLOW_RBRACE_in_enum_def262); - stream_RBRACE.add(RBRACE24); - - // AST REWRITE - // elements: m, TARS_ENUM - // token labels: - // rule labels: retval - // token list labels: m - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleTokenStream stream_m=new RewriteRuleTokenStream(adaptor,"token m", list_m); - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 52:3: -> ^( TARS_ENUM[$n.text] ( $m)+ ) - { - // TarsParser.g:52:6: ^( TARS_ENUM[$n.text] ( $m)+ ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsEnum(TARS_ENUM, (n!=null?n.getText():null)), root_1); - if ( !(stream_m.hasNext()) ) { - throw new RewriteEarlyExitException(); - } - while ( stream_m.hasNext() ) { - adaptor.addChild(root_1, stream_m.nextNode()); - } - stream_m.reset(); - - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - case 2 : - // TarsParser.g:53:4: TARS_ENUM n= TARS_IDENTIFIER LBRACE m+= TARS_IDENTIFIER EQ v+= TARS_INTEGER_LITERAL ( COMMA m+= TARS_IDENTIFIER EQ v+= TARS_INTEGER_LITERAL )* ( COMMA )? RBRACE - { - TARS_ENUM25=(Token)match(input,TARS_ENUM,FOLLOW_TARS_ENUM_in_enum_def284); - stream_TARS_ENUM.add(TARS_ENUM25); - - n=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_enum_def288); - stream_TARS_IDENTIFIER.add(n); - - LBRACE26=(Token)match(input,LBRACE,FOLLOW_LBRACE_in_enum_def290); - stream_LBRACE.add(LBRACE26); - - m=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_enum_def294); - stream_TARS_IDENTIFIER.add(m); - - if (list_m==null) list_m=new ArrayList(); - list_m.add(m); - EQ27=(Token)match(input,EQ,FOLLOW_EQ_in_enum_def296); - stream_EQ.add(EQ27); - - v=(Token)match(input,TARS_INTEGER_LITERAL,FOLLOW_TARS_INTEGER_LITERAL_in_enum_def300); - stream_TARS_INTEGER_LITERAL.add(v); - - if (list_v==null) list_v=new ArrayList(); - list_v.add(v); - // TarsParser.g:53:85: ( COMMA m+= TARS_IDENTIFIER EQ v+= TARS_INTEGER_LITERAL )* - loop7: - while (true) { - int alt7=2; - int LA7_0 = input.LA(1); - if ( (LA7_0==COMMA) ) { - int LA7_1 = input.LA(2); - if ( (LA7_1==TARS_IDENTIFIER) ) { - alt7=1; - } - - } - - switch (alt7) { - case 1 : - // TarsParser.g:53:86: COMMA m+= TARS_IDENTIFIER EQ v+= TARS_INTEGER_LITERAL - { - COMMA28=(Token)match(input,COMMA,FOLLOW_COMMA_in_enum_def303); - stream_COMMA.add(COMMA28); - - m=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_enum_def307); - stream_TARS_IDENTIFIER.add(m); - - if (list_m==null) list_m=new ArrayList(); - list_m.add(m); - EQ29=(Token)match(input,EQ,FOLLOW_EQ_in_enum_def309); - stream_EQ.add(EQ29); - - v=(Token)match(input,TARS_INTEGER_LITERAL,FOLLOW_TARS_INTEGER_LITERAL_in_enum_def313); - stream_TARS_INTEGER_LITERAL.add(v); - - if (list_v==null) list_v=new ArrayList(); - list_v.add(v); - } - break; - - default : - break loop7; - } - } - - // TarsParser.g:53:140: ( COMMA )? - int alt8=2; - int LA8_0 = input.LA(1); - if ( (LA8_0==COMMA) ) { - alt8=1; - } - switch (alt8) { - case 1 : - // TarsParser.g:53:140: COMMA - { - COMMA30=(Token)match(input,COMMA,FOLLOW_COMMA_in_enum_def317); - stream_COMMA.add(COMMA30); - - } - break; - - } - - RBRACE31=(Token)match(input,RBRACE,FOLLOW_RBRACE_in_enum_def320); - stream_RBRACE.add(RBRACE31); - - // AST REWRITE - // elements: v, TARS_ENUM, m - // token labels: - // rule labels: retval - // token list labels: v, m - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleTokenStream stream_v=new RewriteRuleTokenStream(adaptor,"token v", list_v); - RewriteRuleTokenStream stream_m=new RewriteRuleTokenStream(adaptor,"token m", list_m); - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 54:3: -> ^( TARS_ENUM[$n.text] ( $m)+ ( $v)+ ) - { - // TarsParser.g:54:6: ^( TARS_ENUM[$n.text] ( $m)+ ( $v)+ ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsEnum(TARS_ENUM, (n!=null?n.getText():null)), root_1); - if ( !(stream_m.hasNext()) ) { - throw new RewriteEarlyExitException(); - } - while ( stream_m.hasNext() ) { - adaptor.addChild(root_1, stream_m.nextNode()); - } - stream_m.reset(); - - if ( !(stream_v.hasNext()) ) { - throw new RewriteEarlyExitException(); - } - while ( stream_v.hasNext() ) { - adaptor.addChild(root_1, stream_v.nextNode()); - } - stream_v.reset(); - - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - - } - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "enum_def" - - - public static class struct_def_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "struct_def" - // TarsParser.g:57:1: struct_def : TARS_STRUCT TARS_IDENTIFIER LBRACE ( struct_member SEMI )+ RBRACE -> ^( TARS_STRUCT[$TARS_IDENTIFIER.text] ( struct_member )+ ) ; - public final TarsParser.struct_def_return struct_def() throws RecognitionException { - TarsParser.struct_def_return retval = new TarsParser.struct_def_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token TARS_STRUCT32=null; - Token TARS_IDENTIFIER33=null; - Token LBRACE34=null; - Token SEMI36=null; - Token RBRACE37=null; - ParserRuleReturnScope struct_member35 =null; - - Object TARS_STRUCT32_tree=null; - Object TARS_IDENTIFIER33_tree=null; - Object LBRACE34_tree=null; - Object SEMI36_tree=null; - Object RBRACE37_tree=null; - RewriteRuleTokenStream stream_TARS_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token TARS_IDENTIFIER"); - RewriteRuleTokenStream stream_RBRACE=new RewriteRuleTokenStream(adaptor,"token RBRACE"); - RewriteRuleTokenStream stream_SEMI=new RewriteRuleTokenStream(adaptor,"token SEMI"); - RewriteRuleTokenStream stream_LBRACE=new RewriteRuleTokenStream(adaptor,"token LBRACE"); - RewriteRuleTokenStream stream_TARS_STRUCT=new RewriteRuleTokenStream(adaptor,"token TARS_STRUCT"); - RewriteRuleSubtreeStream stream_struct_member=new RewriteRuleSubtreeStream(adaptor,"rule struct_member"); - - try { - // TarsParser.g:58:2: ( TARS_STRUCT TARS_IDENTIFIER LBRACE ( struct_member SEMI )+ RBRACE -> ^( TARS_STRUCT[$TARS_IDENTIFIER.text] ( struct_member )+ ) ) - // TarsParser.g:58:4: TARS_STRUCT TARS_IDENTIFIER LBRACE ( struct_member SEMI )+ RBRACE - { - TARS_STRUCT32=(Token)match(input,TARS_STRUCT,FOLLOW_TARS_STRUCT_in_struct_def351); - stream_TARS_STRUCT.add(TARS_STRUCT32); - - TARS_IDENTIFIER33=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_struct_def353); - stream_TARS_IDENTIFIER.add(TARS_IDENTIFIER33); - - LBRACE34=(Token)match(input,LBRACE,FOLLOW_LBRACE_in_struct_def355); - stream_LBRACE.add(LBRACE34); - - // TarsParser.g:58:39: ( struct_member SEMI )+ - int cnt10=0; - loop10: - while (true) { - int alt10=2; - int LA10_0 = input.LA(1); - if ( (LA10_0==TARS_INTEGER_LITERAL) ) { - alt10=1; - } - - switch (alt10) { - case 1 : - // TarsParser.g:58:40: struct_member SEMI - { - pushFollow(FOLLOW_struct_member_in_struct_def358); - struct_member35=struct_member(); - state._fsp--; - - stream_struct_member.add(struct_member35.getTree()); - SEMI36=(Token)match(input,SEMI,FOLLOW_SEMI_in_struct_def360); - stream_SEMI.add(SEMI36); - - } - break; - - default : - if ( cnt10 >= 1 ) break loop10; - EarlyExitException eee = new EarlyExitException(10, input); - throw eee; - } - cnt10++; - } - - RBRACE37=(Token)match(input,RBRACE,FOLLOW_RBRACE_in_struct_def364); - stream_RBRACE.add(RBRACE37); - - // AST REWRITE - // elements: TARS_STRUCT, struct_member - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 59:3: -> ^( TARS_STRUCT[$TARS_IDENTIFIER.text] ( struct_member )+ ) - { - // TarsParser.g:59:6: ^( TARS_STRUCT[$TARS_IDENTIFIER.text] ( struct_member )+ ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsStruct(TARS_STRUCT, (TARS_IDENTIFIER33!=null?TARS_IDENTIFIER33.getText():null)), root_1); - if ( !(stream_struct_member.hasNext()) ) { - throw new RewriteEarlyExitException(); - } - while ( stream_struct_member.hasNext() ) { - adaptor.addChild(root_1, stream_struct_member.nextTree()); - } - stream_struct_member.reset(); - - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "struct_def" - - - public static class struct_member_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "struct_member" - // TarsParser.g:62:1: struct_member : TARS_INTEGER_LITERAL (r= TARS_REQUIRE |r= TARS_OPTIONAL ) type TARS_IDENTIFIER ( EQ v= const_initializer )? -> ^( TARS_STRUCT_MEMBER[$TARS_INTEGER_LITERAL.text, $r, $TARS_IDENTIFIER.text, $v.result] type ) ; - public final TarsParser.struct_member_return struct_member() throws RecognitionException { - TarsParser.struct_member_return retval = new TarsParser.struct_member_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token r=null; - Token TARS_INTEGER_LITERAL38=null; - Token TARS_IDENTIFIER40=null; - Token EQ41=null; - ParserRuleReturnScope v =null; - ParserRuleReturnScope type39 =null; - - Object r_tree=null; - Object TARS_INTEGER_LITERAL38_tree=null; - Object TARS_IDENTIFIER40_tree=null; - Object EQ41_tree=null; - RewriteRuleTokenStream stream_TARS_OPTIONAL=new RewriteRuleTokenStream(adaptor,"token TARS_OPTIONAL"); - RewriteRuleTokenStream stream_TARS_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token TARS_IDENTIFIER"); - RewriteRuleTokenStream stream_EQ=new RewriteRuleTokenStream(adaptor,"token EQ"); - RewriteRuleTokenStream stream_TARS_REQUIRE=new RewriteRuleTokenStream(adaptor,"token TARS_REQUIRE"); - RewriteRuleTokenStream stream_TARS_INTEGER_LITERAL=new RewriteRuleTokenStream(adaptor,"token TARS_INTEGER_LITERAL"); - RewriteRuleSubtreeStream stream_type=new RewriteRuleSubtreeStream(adaptor,"rule type"); - RewriteRuleSubtreeStream stream_const_initializer=new RewriteRuleSubtreeStream(adaptor,"rule const_initializer"); - - try { - // TarsParser.g:63:2: ( TARS_INTEGER_LITERAL (r= TARS_REQUIRE |r= TARS_OPTIONAL ) type TARS_IDENTIFIER ( EQ v= const_initializer )? -> ^( TARS_STRUCT_MEMBER[$TARS_INTEGER_LITERAL.text, $r, $TARS_IDENTIFIER.text, $v.result] type ) ) - // TarsParser.g:63:4: TARS_INTEGER_LITERAL (r= TARS_REQUIRE |r= TARS_OPTIONAL ) type TARS_IDENTIFIER ( EQ v= const_initializer )? - { - TARS_INTEGER_LITERAL38=(Token)match(input,TARS_INTEGER_LITERAL,FOLLOW_TARS_INTEGER_LITERAL_in_struct_member391); - stream_TARS_INTEGER_LITERAL.add(TARS_INTEGER_LITERAL38); - - // TarsParser.g:63:25: (r= TARS_REQUIRE |r= TARS_OPTIONAL ) - int alt11=2; - int LA11_0 = input.LA(1); - if ( (LA11_0==TARS_REQUIRE) ) { - alt11=1; - } - else if ( (LA11_0==TARS_OPTIONAL) ) { - alt11=2; - } - - else { - NoViableAltException nvae = - new NoViableAltException("", 11, 0, input); - throw nvae; - } - - switch (alt11) { - case 1 : - // TarsParser.g:63:26: r= TARS_REQUIRE - { - r=(Token)match(input,TARS_REQUIRE,FOLLOW_TARS_REQUIRE_in_struct_member396); - stream_TARS_REQUIRE.add(r); - - } - break; - case 2 : - // TarsParser.g:63:43: r= TARS_OPTIONAL - { - r=(Token)match(input,TARS_OPTIONAL,FOLLOW_TARS_OPTIONAL_in_struct_member402); - stream_TARS_OPTIONAL.add(r); - - } - break; - - } - - pushFollow(FOLLOW_type_in_struct_member405); - type39=type(); - state._fsp--; - - stream_type.add(type39.getTree()); - TARS_IDENTIFIER40=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_struct_member407); - stream_TARS_IDENTIFIER.add(TARS_IDENTIFIER40); - - // TarsParser.g:63:81: ( EQ v= const_initializer )? - int alt12=2; - int LA12_0 = input.LA(1); - if ( (LA12_0==EQ) ) { - alt12=1; - } - switch (alt12) { - case 1 : - // TarsParser.g:63:82: EQ v= const_initializer - { - EQ41=(Token)match(input,EQ,FOLLOW_EQ_in_struct_member410); - stream_EQ.add(EQ41); - - pushFollow(FOLLOW_const_initializer_in_struct_member414); - v=const_initializer(); - state._fsp--; - - stream_const_initializer.add(v.getTree()); - } - break; - - } - - // AST REWRITE - // elements: type - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 64:3: -> ^( TARS_STRUCT_MEMBER[$TARS_INTEGER_LITERAL.text, $r, $TARS_IDENTIFIER.text, $v.result] type ) - { - // TarsParser.g:64:6: ^( TARS_STRUCT_MEMBER[$TARS_INTEGER_LITERAL.text, $r, $TARS_IDENTIFIER.text, $v.result] type ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsStructMember(TARS_STRUCT_MEMBER, (TARS_INTEGER_LITERAL38!=null?TARS_INTEGER_LITERAL38.getText():null), r, (TARS_IDENTIFIER40!=null?TARS_IDENTIFIER40.getText():null), (v!=null?((TarsParser.const_initializer_return)v).result:null)), root_1); - adaptor.addChild(root_1, stream_type.nextTree()); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "struct_member" - - - public static class key_def_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "key_def" - // TarsParser.g:67:1: key_def : TARS_KEY LBRACKET n= TARS_IDENTIFIER ( COMMA k+= TARS_IDENTIFIER )+ RBRACKET -> ^( TARS_KEY[$n.text] ( $k)+ ) ; - public final TarsParser.key_def_return key_def() throws RecognitionException { - TarsParser.key_def_return retval = new TarsParser.key_def_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token n=null; - Token TARS_KEY42=null; - Token LBRACKET43=null; - Token COMMA44=null; - Token RBRACKET45=null; - Token k=null; - List list_k=null; - - Object n_tree=null; - Object TARS_KEY42_tree=null; - Object LBRACKET43_tree=null; - Object COMMA44_tree=null; - Object RBRACKET45_tree=null; - Object k_tree=null; - RewriteRuleTokenStream stream_LBRACKET=new RewriteRuleTokenStream(adaptor,"token LBRACKET"); - RewriteRuleTokenStream stream_TARS_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token TARS_IDENTIFIER"); - RewriteRuleTokenStream stream_RBRACKET=new RewriteRuleTokenStream(adaptor,"token RBRACKET"); - RewriteRuleTokenStream stream_COMMA=new RewriteRuleTokenStream(adaptor,"token COMMA"); - RewriteRuleTokenStream stream_TARS_KEY=new RewriteRuleTokenStream(adaptor,"token TARS_KEY"); - - try { - // TarsParser.g:68:2: ( TARS_KEY LBRACKET n= TARS_IDENTIFIER ( COMMA k+= TARS_IDENTIFIER )+ RBRACKET -> ^( TARS_KEY[$n.text] ( $k)+ ) ) - // TarsParser.g:68:5: TARS_KEY LBRACKET n= TARS_IDENTIFIER ( COMMA k+= TARS_IDENTIFIER )+ RBRACKET - { - TARS_KEY42=(Token)match(input,TARS_KEY,FOLLOW_TARS_KEY_in_key_def443); - stream_TARS_KEY.add(TARS_KEY42); - - LBRACKET43=(Token)match(input,LBRACKET,FOLLOW_LBRACKET_in_key_def445); - stream_LBRACKET.add(LBRACKET43); - - n=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_key_def449); - stream_TARS_IDENTIFIER.add(n); - - // TarsParser.g:68:41: ( COMMA k+= TARS_IDENTIFIER )+ - int cnt13=0; - loop13: - while (true) { - int alt13=2; - int LA13_0 = input.LA(1); - if ( (LA13_0==COMMA) ) { - alt13=1; - } - - switch (alt13) { - case 1 : - // TarsParser.g:68:42: COMMA k+= TARS_IDENTIFIER - { - COMMA44=(Token)match(input,COMMA,FOLLOW_COMMA_in_key_def452); - stream_COMMA.add(COMMA44); - - k=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_key_def456); - stream_TARS_IDENTIFIER.add(k); - - if (list_k==null) list_k=new ArrayList(); - list_k.add(k); - } - break; - - default : - if ( cnt13 >= 1 ) break loop13; - EarlyExitException eee = new EarlyExitException(13, input); - throw eee; - } - cnt13++; - } - - RBRACKET45=(Token)match(input,RBRACKET,FOLLOW_RBRACKET_in_key_def460); - stream_RBRACKET.add(RBRACKET45); - - // AST REWRITE - // elements: TARS_KEY, k - // token labels: - // rule labels: retval - // token list labels: k - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleTokenStream stream_k=new RewriteRuleTokenStream(adaptor,"token k", list_k); - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 69:3: -> ^( TARS_KEY[$n.text] ( $k)+ ) - { - // TarsParser.g:69:6: ^( TARS_KEY[$n.text] ( $k)+ ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsKey(TARS_KEY, (n!=null?n.getText():null)), root_1); - if ( !(stream_k.hasNext()) ) { - throw new RewriteEarlyExitException(); - } - while ( stream_k.hasNext() ) { - adaptor.addChild(root_1, stream_k.nextNode()); - } - stream_k.reset(); - - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "key_def" - - - public static class interface_def_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "interface_def" - // TarsParser.g:72:1: interface_def : TARS_INTERFACE TARS_IDENTIFIER LBRACE ( operation SEMI )+ RBRACE -> ^( TARS_INTERFACE[$TARS_IDENTIFIER.text] ( operation )+ ) ; - public final TarsParser.interface_def_return interface_def() throws RecognitionException { - TarsParser.interface_def_return retval = new TarsParser.interface_def_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token TARS_INTERFACE46=null; - Token TARS_IDENTIFIER47=null; - Token LBRACE48=null; - Token SEMI50=null; - Token RBRACE51=null; - ParserRuleReturnScope operation49 =null; - - Object TARS_INTERFACE46_tree=null; - Object TARS_IDENTIFIER47_tree=null; - Object LBRACE48_tree=null; - Object SEMI50_tree=null; - Object RBRACE51_tree=null; - RewriteRuleTokenStream stream_TARS_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token TARS_IDENTIFIER"); - RewriteRuleTokenStream stream_TARS_INTERFACE=new RewriteRuleTokenStream(adaptor,"token TARS_INTERFACE"); - RewriteRuleTokenStream stream_RBRACE=new RewriteRuleTokenStream(adaptor,"token RBRACE"); - RewriteRuleTokenStream stream_SEMI=new RewriteRuleTokenStream(adaptor,"token SEMI"); - RewriteRuleTokenStream stream_LBRACE=new RewriteRuleTokenStream(adaptor,"token LBRACE"); - RewriteRuleSubtreeStream stream_operation=new RewriteRuleSubtreeStream(adaptor,"rule operation"); - - try { - // TarsParser.g:73:2: ( TARS_INTERFACE TARS_IDENTIFIER LBRACE ( operation SEMI )+ RBRACE -> ^( TARS_INTERFACE[$TARS_IDENTIFIER.text] ( operation )+ ) ) - // TarsParser.g:73:4: TARS_INTERFACE TARS_IDENTIFIER LBRACE ( operation SEMI )+ RBRACE - { - TARS_INTERFACE46=(Token)match(input,TARS_INTERFACE,FOLLOW_TARS_INTERFACE_in_interface_def488); - stream_TARS_INTERFACE.add(TARS_INTERFACE46); - - TARS_IDENTIFIER47=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_interface_def490); - stream_TARS_IDENTIFIER.add(TARS_IDENTIFIER47); - - LBRACE48=(Token)match(input,LBRACE,FOLLOW_LBRACE_in_interface_def492); - stream_LBRACE.add(LBRACE48); - - // TarsParser.g:73:42: ( operation SEMI )+ - int cnt14=0; - loop14: - while (true) { - int alt14=2; - int LA14_0 = input.LA(1); - if ( ((LA14_0 >= TARS_BOOL && LA14_0 <= TARS_BYTE)||LA14_0==TARS_DOUBLE||LA14_0==TARS_FLOAT||LA14_0==TARS_IDENTIFIER||LA14_0==TARS_INT||(LA14_0 >= TARS_LONG && LA14_0 <= TARS_MAP)||(LA14_0 >= TARS_SHORT && LA14_0 <= TARS_STRING)||(LA14_0 >= TARS_UNSIGNED && LA14_0 <= TARS_VOID)) ) { - alt14=1; - } - - switch (alt14) { - case 1 : - // TarsParser.g:73:43: operation SEMI - { - pushFollow(FOLLOW_operation_in_interface_def495); - operation49=operation(); - state._fsp--; - - stream_operation.add(operation49.getTree()); - SEMI50=(Token)match(input,SEMI,FOLLOW_SEMI_in_interface_def497); - stream_SEMI.add(SEMI50); - - } - break; - - default : - if ( cnt14 >= 1 ) break loop14; - EarlyExitException eee = new EarlyExitException(14, input); - throw eee; - } - cnt14++; - } - - RBRACE51=(Token)match(input,RBRACE,FOLLOW_RBRACE_in_interface_def501); - stream_RBRACE.add(RBRACE51); - - // AST REWRITE - // elements: operation, TARS_INTERFACE - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 74:3: -> ^( TARS_INTERFACE[$TARS_IDENTIFIER.text] ( operation )+ ) - { - // TarsParser.g:74:6: ^( TARS_INTERFACE[$TARS_IDENTIFIER.text] ( operation )+ ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsInterface(TARS_INTERFACE, (TARS_IDENTIFIER47!=null?TARS_IDENTIFIER47.getText():null)), root_1); - if ( !(stream_operation.hasNext()) ) { - throw new RewriteEarlyExitException(); - } - while ( stream_operation.hasNext() ) { - adaptor.addChild(root_1, stream_operation.nextTree()); - } - stream_operation.reset(); - - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "interface_def" - - - public static class operation_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "operation" - // TarsParser.g:77:1: operation : type TARS_IDENTIFIER LPAREN ( param ( COMMA param )* )? RPAREN -> ^( TARS_OPERATION[$TARS_IDENTIFIER.text] type ( param )* ) ; - public final TarsParser.operation_return operation() throws RecognitionException { - TarsParser.operation_return retval = new TarsParser.operation_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token TARS_IDENTIFIER53=null; - Token LPAREN54=null; - Token COMMA56=null; - Token RPAREN58=null; - ParserRuleReturnScope type52 =null; - ParserRuleReturnScope param55 =null; - ParserRuleReturnScope param57 =null; - - Object TARS_IDENTIFIER53_tree=null; - Object LPAREN54_tree=null; - Object COMMA56_tree=null; - Object RPAREN58_tree=null; - RewriteRuleTokenStream stream_RPAREN=new RewriteRuleTokenStream(adaptor,"token RPAREN"); - RewriteRuleTokenStream stream_TARS_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token TARS_IDENTIFIER"); - RewriteRuleTokenStream stream_COMMA=new RewriteRuleTokenStream(adaptor,"token COMMA"); - RewriteRuleTokenStream stream_LPAREN=new RewriteRuleTokenStream(adaptor,"token LPAREN"); - RewriteRuleSubtreeStream stream_param=new RewriteRuleSubtreeStream(adaptor,"rule param"); - RewriteRuleSubtreeStream stream_type=new RewriteRuleSubtreeStream(adaptor,"rule type"); - - try { - // TarsParser.g:78:2: ( type TARS_IDENTIFIER LPAREN ( param ( COMMA param )* )? RPAREN -> ^( TARS_OPERATION[$TARS_IDENTIFIER.text] type ( param )* ) ) - // TarsParser.g:78:4: type TARS_IDENTIFIER LPAREN ( param ( COMMA param )* )? RPAREN - { - pushFollow(FOLLOW_type_in_operation528); - type52=type(); - state._fsp--; - - stream_type.add(type52.getTree()); - TARS_IDENTIFIER53=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_operation530); - stream_TARS_IDENTIFIER.add(TARS_IDENTIFIER53); - - LPAREN54=(Token)match(input,LPAREN,FOLLOW_LPAREN_in_operation532); - stream_LPAREN.add(LPAREN54); - - // TarsParser.g:78:32: ( param ( COMMA param )* )? - int alt16=2; - int LA16_0 = input.LA(1); - if ( ((LA16_0 >= TARS_BOOL && LA16_0 <= TARS_BYTE)||LA16_0==TARS_DOUBLE||LA16_0==TARS_FLOAT||LA16_0==TARS_IDENTIFIER||LA16_0==TARS_INT||(LA16_0 >= TARS_LONG && LA16_0 <= TARS_MAP)||LA16_0==TARS_OUT||(LA16_0 >= TARS_ROUTE_KEY && LA16_0 <= TARS_STRING)||(LA16_0 >= TARS_UNSIGNED && LA16_0 <= TARS_VOID)) ) { - alt16=1; - } - switch (alt16) { - case 1 : - // TarsParser.g:78:33: param ( COMMA param )* - { - pushFollow(FOLLOW_param_in_operation535); - param55=param(); - state._fsp--; - - stream_param.add(param55.getTree()); - // TarsParser.g:78:39: ( COMMA param )* - loop15: - while (true) { - int alt15=2; - int LA15_0 = input.LA(1); - if ( (LA15_0==COMMA) ) { - alt15=1; - } - - switch (alt15) { - case 1 : - // TarsParser.g:78:40: COMMA param - { - COMMA56=(Token)match(input,COMMA,FOLLOW_COMMA_in_operation538); - stream_COMMA.add(COMMA56); - - pushFollow(FOLLOW_param_in_operation540); - param57=param(); - state._fsp--; - - stream_param.add(param57.getTree()); - } - break; - - default : - break loop15; - } - } - - } - break; - - } - - RPAREN58=(Token)match(input,RPAREN,FOLLOW_RPAREN_in_operation547); - stream_RPAREN.add(RPAREN58); - - // AST REWRITE - // elements: param, type - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 79:3: -> ^( TARS_OPERATION[$TARS_IDENTIFIER.text] type ( param )* ) - { - // TarsParser.g:79:6: ^( TARS_OPERATION[$TARS_IDENTIFIER.text] type ( param )* ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsOperation(TARS_OPERATION, (TARS_IDENTIFIER53!=null?TARS_IDENTIFIER53.getText():null)), root_1); - adaptor.addChild(root_1, stream_type.nextTree()); - // TarsParser.g:79:66: ( param )* - while ( stream_param.hasNext() ) { - adaptor.addChild(root_1, stream_param.nextTree()); - } - stream_param.reset(); - - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "operation" - - - public static class param_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "param" - // TarsParser.g:82:1: param : ( TARS_ROUTE_KEY )? ( TARS_OUT )? type TARS_IDENTIFIER -> ^( TARS_PARAM[$TARS_IDENTIFIER.text, $TARS_OUT, $TARS_ROUTE_KEY] type ) ; - public final TarsParser.param_return param() throws RecognitionException { - TarsParser.param_return retval = new TarsParser.param_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token TARS_ROUTE_KEY59=null; - Token TARS_OUT60=null; - Token TARS_IDENTIFIER62=null; - ParserRuleReturnScope type61 =null; - - Object TARS_ROUTE_KEY59_tree=null; - Object TARS_OUT60_tree=null; - Object TARS_IDENTIFIER62_tree=null; - RewriteRuleTokenStream stream_TARS_ROUTE_KEY=new RewriteRuleTokenStream(adaptor,"token TARS_ROUTE_KEY"); - RewriteRuleTokenStream stream_TARS_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token TARS_IDENTIFIER"); - RewriteRuleTokenStream stream_TARS_OUT=new RewriteRuleTokenStream(adaptor,"token TARS_OUT"); - RewriteRuleSubtreeStream stream_type=new RewriteRuleSubtreeStream(adaptor,"rule type"); - - try { - // TarsParser.g:83:2: ( ( TARS_ROUTE_KEY )? ( TARS_OUT )? type TARS_IDENTIFIER -> ^( TARS_PARAM[$TARS_IDENTIFIER.text, $TARS_OUT, $TARS_ROUTE_KEY] type ) ) - // TarsParser.g:83:4: ( TARS_ROUTE_KEY )? ( TARS_OUT )? type TARS_IDENTIFIER - { - // TarsParser.g:83:4: ( TARS_ROUTE_KEY )? - int alt17=2; - int LA17_0 = input.LA(1); - if ( (LA17_0==TARS_ROUTE_KEY) ) { - alt17=1; - } - switch (alt17) { - case 1 : - // TarsParser.g:83:4: TARS_ROUTE_KEY - { - TARS_ROUTE_KEY59=(Token)match(input,TARS_ROUTE_KEY,FOLLOW_TARS_ROUTE_KEY_in_param576); - stream_TARS_ROUTE_KEY.add(TARS_ROUTE_KEY59); - - } - break; - - } - - // TarsParser.g:83:20: ( TARS_OUT )? - int alt18=2; - int LA18_0 = input.LA(1); - if ( (LA18_0==TARS_OUT) ) { - alt18=1; - } - switch (alt18) { - case 1 : - // TarsParser.g:83:20: TARS_OUT - { - TARS_OUT60=(Token)match(input,TARS_OUT,FOLLOW_TARS_OUT_in_param579); - stream_TARS_OUT.add(TARS_OUT60); - - } - break; - - } - - pushFollow(FOLLOW_type_in_param582); - type61=type(); - state._fsp--; - - stream_type.add(type61.getTree()); - TARS_IDENTIFIER62=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_param584); - stream_TARS_IDENTIFIER.add(TARS_IDENTIFIER62); - - // AST REWRITE - // elements: type - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 84:3: -> ^( TARS_PARAM[$TARS_IDENTIFIER.text, $TARS_OUT, $TARS_ROUTE_KEY] type ) - { - // TarsParser.g:84:6: ^( TARS_PARAM[$TARS_IDENTIFIER.text, $TARS_OUT, $TARS_ROUTE_KEY] type ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsParam(TARS_PARAM, (TARS_IDENTIFIER62!=null?TARS_IDENTIFIER62.getText():null), TARS_OUT60, TARS_ROUTE_KEY59), root_1); - adaptor.addChild(root_1, stream_type.nextTree()); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "param" - - - public static class const_initializer_return extends ParserRuleReturnScope { - public String result; - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "const_initializer" - // TarsParser.g:87:1: const_initializer returns [String result] : ( TARS_INTEGER_LITERAL | TARS_FLOATING_POINT_LITERAL | TARS_STRING_LITERAL | TARS_FALSE | TARS_TRUE ); - public final TarsParser.const_initializer_return const_initializer() throws RecognitionException { - TarsParser.const_initializer_return retval = new TarsParser.const_initializer_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token TARS_INTEGER_LITERAL63=null; - Token TARS_FLOATING_POINT_LITERAL64=null; - Token TARS_STRING_LITERAL65=null; - Token TARS_FALSE66=null; - Token TARS_TRUE67=null; - - Object TARS_INTEGER_LITERAL63_tree=null; - Object TARS_FLOATING_POINT_LITERAL64_tree=null; - Object TARS_STRING_LITERAL65_tree=null; - Object TARS_FALSE66_tree=null; - Object TARS_TRUE67_tree=null; - - try { - // TarsParser.g:88:2: ( TARS_INTEGER_LITERAL | TARS_FLOATING_POINT_LITERAL | TARS_STRING_LITERAL | TARS_FALSE | TARS_TRUE ) - int alt19=5; - switch ( input.LA(1) ) { - case TARS_INTEGER_LITERAL: - { - alt19=1; - } - break; - case TARS_FLOATING_POINT_LITERAL: - { - alt19=2; - } - break; - case TARS_STRING_LITERAL: - { - alt19=3; - } - break; - case TARS_FALSE: - { - alt19=4; - } - break; - case TARS_TRUE: - { - alt19=5; - } - break; - default: - NoViableAltException nvae = - new NoViableAltException("", 19, 0, input); - throw nvae; - } - switch (alt19) { - case 1 : - // TarsParser.g:88:4: TARS_INTEGER_LITERAL - { - root_0 = (Object)adaptor.nil(); - - - TARS_INTEGER_LITERAL63=(Token)match(input,TARS_INTEGER_LITERAL,FOLLOW_TARS_INTEGER_LITERAL_in_const_initializer613); - TARS_INTEGER_LITERAL63_tree = (Object)adaptor.create(TARS_INTEGER_LITERAL63); - adaptor.addChild(root_0, TARS_INTEGER_LITERAL63_tree); - - retval.result = (TARS_INTEGER_LITERAL63!=null?TARS_INTEGER_LITERAL63.getText():null); - } - break; - case 2 : - // TarsParser.g:89:4: TARS_FLOATING_POINT_LITERAL - { - root_0 = (Object)adaptor.nil(); - - - TARS_FLOATING_POINT_LITERAL64=(Token)match(input,TARS_FLOATING_POINT_LITERAL,FOLLOW_TARS_FLOATING_POINT_LITERAL_in_const_initializer620); - TARS_FLOATING_POINT_LITERAL64_tree = (Object)adaptor.create(TARS_FLOATING_POINT_LITERAL64); - adaptor.addChild(root_0, TARS_FLOATING_POINT_LITERAL64_tree); - - retval.result = (TARS_FLOATING_POINT_LITERAL64!=null?TARS_FLOATING_POINT_LITERAL64.getText():null); - } - break; - case 3 : - // TarsParser.g:90:4: TARS_STRING_LITERAL - { - root_0 = (Object)adaptor.nil(); - - - TARS_STRING_LITERAL65=(Token)match(input,TARS_STRING_LITERAL,FOLLOW_TARS_STRING_LITERAL_in_const_initializer627); - TARS_STRING_LITERAL65_tree = (Object)adaptor.create(TARS_STRING_LITERAL65); - adaptor.addChild(root_0, TARS_STRING_LITERAL65_tree); - - retval.result = (TARS_STRING_LITERAL65!=null?TARS_STRING_LITERAL65.getText():null); - } - break; - case 4 : - // TarsParser.g:91:4: TARS_FALSE - { - root_0 = (Object)adaptor.nil(); - - - TARS_FALSE66=(Token)match(input,TARS_FALSE,FOLLOW_TARS_FALSE_in_const_initializer634); - TARS_FALSE66_tree = (Object)adaptor.create(TARS_FALSE66); - adaptor.addChild(root_0, TARS_FALSE66_tree); - - retval.result = (TARS_FALSE66!=null?TARS_FALSE66.getText():null); - } - break; - case 5 : - // TarsParser.g:92:4: TARS_TRUE - { - root_0 = (Object)adaptor.nil(); - - - TARS_TRUE67=(Token)match(input,TARS_TRUE,FOLLOW_TARS_TRUE_in_const_initializer641); - TARS_TRUE67_tree = (Object)adaptor.create(TARS_TRUE67); - adaptor.addChild(root_0, TARS_TRUE67_tree); - - retval.result = (TARS_TRUE67!=null?TARS_TRUE67.getText():null); - } - break; - - } - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "const_initializer" - - - public static class type_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "type" - // TarsParser.g:95:1: type : ( type_primitive | type_vector | type_map | type_custom ); - public final TarsParser.type_return type() throws RecognitionException { - TarsParser.type_return retval = new TarsParser.type_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - ParserRuleReturnScope type_primitive68 =null; - ParserRuleReturnScope type_vector69 =null; - ParserRuleReturnScope type_map70 =null; - ParserRuleReturnScope type_custom71 =null; - - - try { - // TarsParser.g:96:2: ( type_primitive | type_vector | type_map | type_custom ) - int alt20=4; - switch ( input.LA(1) ) { - case TARS_BOOL: - case TARS_BYTE: - case TARS_DOUBLE: - case TARS_FLOAT: - case TARS_INT: - case TARS_LONG: - case TARS_SHORT: - case TARS_STRING: - case TARS_UNSIGNED: - case TARS_VOID: - { - alt20=1; - } - break; - case TARS_VECTOR: - { - alt20=2; - } - break; - case TARS_MAP: - { - alt20=3; - } - break; - case TARS_IDENTIFIER: - { - alt20=4; - } - break; - default: - NoViableAltException nvae = - new NoViableAltException("", 20, 0, input); - throw nvae; - } - switch (alt20) { - case 1 : - // TarsParser.g:96:4: type_primitive - { - root_0 = (Object)adaptor.nil(); - - - pushFollow(FOLLOW_type_primitive_in_type654); - type_primitive68=type_primitive(); - state._fsp--; - - adaptor.addChild(root_0, type_primitive68.getTree()); - - } - break; - case 2 : - // TarsParser.g:97:4: type_vector - { - root_0 = (Object)adaptor.nil(); - - - pushFollow(FOLLOW_type_vector_in_type659); - type_vector69=type_vector(); - state._fsp--; - - adaptor.addChild(root_0, type_vector69.getTree()); - - } - break; - case 3 : - // TarsParser.g:98:4: type_map - { - root_0 = (Object)adaptor.nil(); - - - pushFollow(FOLLOW_type_map_in_type664); - type_map70=type_map(); - state._fsp--; - - adaptor.addChild(root_0, type_map70.getTree()); - - } - break; - case 4 : - // TarsParser.g:99:4: type_custom - { - root_0 = (Object)adaptor.nil(); - - - pushFollow(FOLLOW_type_custom_in_type669); - type_custom71=type_custom(); - state._fsp--; - - adaptor.addChild(root_0, type_custom71.getTree()); - - } - break; - - } - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "type" - - - public static class type_primitive_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "type_primitive" - // TarsParser.g:102:1: type_primitive : ( TARS_VOID -> ^( TARS_VOID ) | TARS_BOOL -> ^( TARS_BOOL ) | TARS_BYTE -> ^( TARS_BYTE ) | TARS_SHORT -> ^( TARS_SHORT ) | TARS_INT -> ^( TARS_INT ) | TARS_LONG -> ^( TARS_LONG ) | TARS_FLOAT -> ^( TARS_FLOAT ) | TARS_DOUBLE -> ^( TARS_DOUBLE ) | TARS_STRING -> ^( TARS_STRING ) | TARS_UNSIGNED TARS_INT -> ^( TARS_LONG ) ); - public final TarsParser.type_primitive_return type_primitive() throws RecognitionException { - TarsParser.type_primitive_return retval = new TarsParser.type_primitive_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token TARS_VOID72=null; - Token TARS_BOOL73=null; - Token TARS_BYTE74=null; - Token TARS_SHORT75=null; - Token TARS_INT76=null; - Token TARS_LONG77=null; - Token TARS_FLOAT78=null; - Token TARS_DOUBLE79=null; - Token TARS_STRING80=null; - Token TARS_UNSIGNED81=null; - Token TARS_INT82=null; - - Object TARS_VOID72_tree=null; - Object TARS_BOOL73_tree=null; - Object TARS_BYTE74_tree=null; - Object TARS_SHORT75_tree=null; - Object TARS_INT76_tree=null; - Object TARS_LONG77_tree=null; - Object TARS_FLOAT78_tree=null; - Object TARS_DOUBLE79_tree=null; - Object TARS_STRING80_tree=null; - Object TARS_UNSIGNED81_tree=null; - Object TARS_INT82_tree=null; - RewriteRuleTokenStream stream_TARS_DOUBLE=new RewriteRuleTokenStream(adaptor,"token TARS_DOUBLE"); - RewriteRuleTokenStream stream_TARS_BYTE=new RewriteRuleTokenStream(adaptor,"token TARS_BYTE"); - RewriteRuleTokenStream stream_TARS_UNSIGNED=new RewriteRuleTokenStream(adaptor,"token TARS_UNSIGNED"); - RewriteRuleTokenStream stream_TARS_STRING=new RewriteRuleTokenStream(adaptor,"token TARS_STRING"); - RewriteRuleTokenStream stream_TARS_SHORT=new RewriteRuleTokenStream(adaptor,"token TARS_SHORT"); - RewriteRuleTokenStream stream_TARS_FLOAT=new RewriteRuleTokenStream(adaptor,"token TARS_FLOAT"); - RewriteRuleTokenStream stream_TARS_BOOL=new RewriteRuleTokenStream(adaptor,"token TARS_BOOL"); - RewriteRuleTokenStream stream_TARS_LONG=new RewriteRuleTokenStream(adaptor,"token TARS_LONG"); - RewriteRuleTokenStream stream_TARS_INT=new RewriteRuleTokenStream(adaptor,"token TARS_INT"); - RewriteRuleTokenStream stream_TARS_VOID=new RewriteRuleTokenStream(adaptor,"token TARS_VOID"); - - try { - // TarsParser.g:103:2: ( TARS_VOID -> ^( TARS_VOID ) | TARS_BOOL -> ^( TARS_BOOL ) | TARS_BYTE -> ^( TARS_BYTE ) | TARS_SHORT -> ^( TARS_SHORT ) | TARS_INT -> ^( TARS_INT ) | TARS_LONG -> ^( TARS_LONG ) | TARS_FLOAT -> ^( TARS_FLOAT ) | TARS_DOUBLE -> ^( TARS_DOUBLE ) | TARS_STRING -> ^( TARS_STRING ) | TARS_UNSIGNED TARS_INT -> ^( TARS_LONG ) ) - int alt21=10; - switch ( input.LA(1) ) { - case TARS_VOID: - { - alt21=1; - } - break; - case TARS_BOOL: - { - alt21=2; - } - break; - case TARS_BYTE: - { - alt21=3; - } - break; - case TARS_SHORT: - { - alt21=4; - } - break; - case TARS_INT: - { - alt21=5; - } - break; - case TARS_LONG: - { - alt21=6; - } - break; - case TARS_FLOAT: - { - alt21=7; - } - break; - case TARS_DOUBLE: - { - alt21=8; - } - break; - case TARS_STRING: - { - alt21=9; - } - break; - case TARS_UNSIGNED: - { - alt21=10; - } - break; - default: - NoViableAltException nvae = - new NoViableAltException("", 21, 0, input); - throw nvae; - } - switch (alt21) { - case 1 : - // TarsParser.g:103:4: TARS_VOID - { - TARS_VOID72=(Token)match(input,TARS_VOID,FOLLOW_TARS_VOID_in_type_primitive681); - stream_TARS_VOID.add(TARS_VOID72); - - // AST REWRITE - // elements: TARS_VOID - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 104:3: -> ^( TARS_VOID ) - { - // TarsParser.g:104:6: ^( TARS_VOID ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsPrimitiveType(stream_TARS_VOID.nextToken()), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - case 2 : - // TarsParser.g:105:4: TARS_BOOL - { - TARS_BOOL73=(Token)match(input,TARS_BOOL,FOLLOW_TARS_BOOL_in_type_primitive697); - stream_TARS_BOOL.add(TARS_BOOL73); - - // AST REWRITE - // elements: TARS_BOOL - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 106:3: -> ^( TARS_BOOL ) - { - // TarsParser.g:106:6: ^( TARS_BOOL ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsPrimitiveType(stream_TARS_BOOL.nextToken()), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - case 3 : - // TarsParser.g:107:4: TARS_BYTE - { - TARS_BYTE74=(Token)match(input,TARS_BYTE,FOLLOW_TARS_BYTE_in_type_primitive713); - stream_TARS_BYTE.add(TARS_BYTE74); - - // AST REWRITE - // elements: TARS_BYTE - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 108:3: -> ^( TARS_BYTE ) - { - // TarsParser.g:108:6: ^( TARS_BYTE ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsPrimitiveType(stream_TARS_BYTE.nextToken()), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - case 4 : - // TarsParser.g:109:4: TARS_SHORT - { - TARS_SHORT75=(Token)match(input,TARS_SHORT,FOLLOW_TARS_SHORT_in_type_primitive729); - stream_TARS_SHORT.add(TARS_SHORT75); - - // AST REWRITE - // elements: TARS_SHORT - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 110:3: -> ^( TARS_SHORT ) - { - // TarsParser.g:110:6: ^( TARS_SHORT ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsPrimitiveType(stream_TARS_SHORT.nextToken()), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - case 5 : - // TarsParser.g:111:4: TARS_INT - { - TARS_INT76=(Token)match(input,TARS_INT,FOLLOW_TARS_INT_in_type_primitive745); - stream_TARS_INT.add(TARS_INT76); - - // AST REWRITE - // elements: TARS_INT - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 112:3: -> ^( TARS_INT ) - { - // TarsParser.g:112:6: ^( TARS_INT ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsPrimitiveType(stream_TARS_INT.nextToken()), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - case 6 : - // TarsParser.g:113:4: TARS_LONG - { - TARS_LONG77=(Token)match(input,TARS_LONG,FOLLOW_TARS_LONG_in_type_primitive761); - stream_TARS_LONG.add(TARS_LONG77); - - // AST REWRITE - // elements: TARS_LONG - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 114:3: -> ^( TARS_LONG ) - { - // TarsParser.g:114:6: ^( TARS_LONG ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsPrimitiveType(stream_TARS_LONG.nextToken()), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - case 7 : - // TarsParser.g:115:4: TARS_FLOAT - { - TARS_FLOAT78=(Token)match(input,TARS_FLOAT,FOLLOW_TARS_FLOAT_in_type_primitive777); - stream_TARS_FLOAT.add(TARS_FLOAT78); - - // AST REWRITE - // elements: TARS_FLOAT - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 116:3: -> ^( TARS_FLOAT ) - { - // TarsParser.g:116:6: ^( TARS_FLOAT ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsPrimitiveType(stream_TARS_FLOAT.nextToken()), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - case 8 : - // TarsParser.g:117:4: TARS_DOUBLE - { - TARS_DOUBLE79=(Token)match(input,TARS_DOUBLE,FOLLOW_TARS_DOUBLE_in_type_primitive793); - stream_TARS_DOUBLE.add(TARS_DOUBLE79); - - // AST REWRITE - // elements: TARS_DOUBLE - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 118:3: -> ^( TARS_DOUBLE ) - { - // TarsParser.g:118:6: ^( TARS_DOUBLE ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsPrimitiveType(stream_TARS_DOUBLE.nextToken()), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - case 9 : - // TarsParser.g:119:4: TARS_STRING - { - TARS_STRING80=(Token)match(input,TARS_STRING,FOLLOW_TARS_STRING_in_type_primitive809); - stream_TARS_STRING.add(TARS_STRING80); - - // AST REWRITE - // elements: TARS_STRING - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 120:3: -> ^( TARS_STRING ) - { - // TarsParser.g:120:6: ^( TARS_STRING ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsPrimitiveType(stream_TARS_STRING.nextToken()), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - case 10 : - // TarsParser.g:121:4: TARS_UNSIGNED TARS_INT - { - TARS_UNSIGNED81=(Token)match(input,TARS_UNSIGNED,FOLLOW_TARS_UNSIGNED_in_type_primitive825); - stream_TARS_UNSIGNED.add(TARS_UNSIGNED81); - - TARS_INT82=(Token)match(input,TARS_INT,FOLLOW_TARS_INT_in_type_primitive827); - stream_TARS_INT.add(TARS_INT82); - - // AST REWRITE - // elements: - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 122:3: -> ^( TARS_LONG ) - { - // TarsParser.g:122:6: ^( TARS_LONG ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsPrimitiveType(TARS_LONG), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - - } - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "type_primitive" - - - public static class type_vector_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "type_vector" - // TarsParser.g:125:1: type_vector : TARS_VECTOR LT type GT -> ^( TARS_VECTOR type ) ; - public final TarsParser.type_vector_return type_vector() throws RecognitionException { - TarsParser.type_vector_return retval = new TarsParser.type_vector_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token TARS_VECTOR83=null; - Token LT84=null; - Token GT86=null; - ParserRuleReturnScope type85 =null; - - Object TARS_VECTOR83_tree=null; - Object LT84_tree=null; - Object GT86_tree=null; - RewriteRuleTokenStream stream_TARS_VECTOR=new RewriteRuleTokenStream(adaptor,"token TARS_VECTOR"); - RewriteRuleTokenStream stream_GT=new RewriteRuleTokenStream(adaptor,"token GT"); - RewriteRuleTokenStream stream_LT=new RewriteRuleTokenStream(adaptor,"token LT"); - RewriteRuleSubtreeStream stream_type=new RewriteRuleSubtreeStream(adaptor,"rule type"); - - try { - // TarsParser.g:126:2: ( TARS_VECTOR LT type GT -> ^( TARS_VECTOR type ) ) - // TarsParser.g:126:4: TARS_VECTOR LT type GT - { - TARS_VECTOR83=(Token)match(input,TARS_VECTOR,FOLLOW_TARS_VECTOR_in_type_vector849); - stream_TARS_VECTOR.add(TARS_VECTOR83); - - LT84=(Token)match(input,LT,FOLLOW_LT_in_type_vector851); - stream_LT.add(LT84); - - pushFollow(FOLLOW_type_in_type_vector853); - type85=type(); - state._fsp--; - - stream_type.add(type85.getTree()); - GT86=(Token)match(input,GT,FOLLOW_GT_in_type_vector855); - stream_GT.add(GT86); - - // AST REWRITE - // elements: type, TARS_VECTOR - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 127:3: -> ^( TARS_VECTOR type ) - { - // TarsParser.g:127:6: ^( TARS_VECTOR type ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsVectorType(stream_TARS_VECTOR.nextToken()), root_1); - adaptor.addChild(root_1, stream_type.nextTree()); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "type_vector" - - - public static class type_map_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "type_map" - // TarsParser.g:130:1: type_map : TARS_MAP LT type COMMA type GT -> ^( TARS_MAP type type ) ; - public final TarsParser.type_map_return type_map() throws RecognitionException { - TarsParser.type_map_return retval = new TarsParser.type_map_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token TARS_MAP87=null; - Token LT88=null; - Token COMMA90=null; - Token GT92=null; - ParserRuleReturnScope type89 =null; - ParserRuleReturnScope type91 =null; - - Object TARS_MAP87_tree=null; - Object LT88_tree=null; - Object COMMA90_tree=null; - Object GT92_tree=null; - RewriteRuleTokenStream stream_GT=new RewriteRuleTokenStream(adaptor,"token GT"); - RewriteRuleTokenStream stream_LT=new RewriteRuleTokenStream(adaptor,"token LT"); - RewriteRuleTokenStream stream_COMMA=new RewriteRuleTokenStream(adaptor,"token COMMA"); - RewriteRuleTokenStream stream_TARS_MAP=new RewriteRuleTokenStream(adaptor,"token TARS_MAP"); - RewriteRuleSubtreeStream stream_type=new RewriteRuleSubtreeStream(adaptor,"rule type"); - - try { - // TarsParser.g:131:2: ( TARS_MAP LT type COMMA type GT -> ^( TARS_MAP type type ) ) - // TarsParser.g:131:4: TARS_MAP LT type COMMA type GT - { - TARS_MAP87=(Token)match(input,TARS_MAP,FOLLOW_TARS_MAP_in_type_map879); - stream_TARS_MAP.add(TARS_MAP87); - - LT88=(Token)match(input,LT,FOLLOW_LT_in_type_map881); - stream_LT.add(LT88); - - pushFollow(FOLLOW_type_in_type_map883); - type89=type(); - state._fsp--; - - stream_type.add(type89.getTree()); - COMMA90=(Token)match(input,COMMA,FOLLOW_COMMA_in_type_map885); - stream_COMMA.add(COMMA90); - - pushFollow(FOLLOW_type_in_type_map887); - type91=type(); - state._fsp--; - - stream_type.add(type91.getTree()); - GT92=(Token)match(input,GT,FOLLOW_GT_in_type_map889); - stream_GT.add(GT92); - - // AST REWRITE - // elements: type, TARS_MAP, type - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 132:3: -> ^( TARS_MAP type type ) - { - // TarsParser.g:132:6: ^( TARS_MAP type type ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsMapType(stream_TARS_MAP.nextToken()), root_1); - adaptor.addChild(root_1, stream_type.nextTree()); - adaptor.addChild(root_1, stream_type.nextTree()); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "type_map" - - - public static class type_custom_return extends ParserRuleReturnScope { - Object tree; - @Override - public Object getTree() { return tree; } - }; - - - // $ANTLR start "type_custom" - // TarsParser.g:135:1: type_custom : ( TARS_IDENTIFIER -> ^( TARS_MAP[$TARS_IDENTIFIER.text] ) |ns= TARS_IDENTIFIER COLON COLON id= TARS_IDENTIFIER -> ^( TARS_REF[$ns.text,$id.text] ) ); - public final TarsParser.type_custom_return type_custom() throws RecognitionException { - TarsParser.type_custom_return retval = new TarsParser.type_custom_return(); - retval.start = input.LT(1); - - Object root_0 = null; - - Token ns=null; - Token id=null; - Token TARS_IDENTIFIER93=null; - Token COLON94=null; - Token COLON95=null; - - Object ns_tree=null; - Object id_tree=null; - Object TARS_IDENTIFIER93_tree=null; - Object COLON94_tree=null; - Object COLON95_tree=null; - RewriteRuleTokenStream stream_COLON=new RewriteRuleTokenStream(adaptor,"token COLON"); - RewriteRuleTokenStream stream_TARS_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token TARS_IDENTIFIER"); - - try { - // TarsParser.g:136:2: ( TARS_IDENTIFIER -> ^( TARS_MAP[$TARS_IDENTIFIER.text] ) |ns= TARS_IDENTIFIER COLON COLON id= TARS_IDENTIFIER -> ^( TARS_REF[$ns.text,$id.text] ) ) - int alt22=2; - int LA22_0 = input.LA(1); - if ( (LA22_0==TARS_IDENTIFIER) ) { - int LA22_1 = input.LA(2); - if ( (LA22_1==COLON) ) { - alt22=2; - } - else if ( (LA22_1==COMMA||LA22_1==GT||LA22_1==TARS_IDENTIFIER) ) { - alt22=1; - } - - else { - int nvaeMark = input.mark(); - try { - input.consume(); - NoViableAltException nvae = - new NoViableAltException("", 22, 1, input); - throw nvae; - } finally { - input.rewind(nvaeMark); - } - } - - } - - else { - NoViableAltException nvae = - new NoViableAltException("", 22, 0, input); - throw nvae; - } - - switch (alt22) { - case 1 : - // TarsParser.g:136:4: TARS_IDENTIFIER - { - TARS_IDENTIFIER93=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_type_custom916); - stream_TARS_IDENTIFIER.add(TARS_IDENTIFIER93); - - // AST REWRITE - // elements: - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 137:3: -> ^( TARS_MAP[$TARS_IDENTIFIER.text] ) - { - // TarsParser.g:137:6: ^( TARS_MAP[$TARS_IDENTIFIER.text] ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsCustomType(TARS_MAP, (TARS_IDENTIFIER93!=null?TARS_IDENTIFIER93.getText():null)), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - case 2 : - // TarsParser.g:138:4: ns= TARS_IDENTIFIER COLON COLON id= TARS_IDENTIFIER - { - ns=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_type_custom935); - stream_TARS_IDENTIFIER.add(ns); - - COLON94=(Token)match(input,COLON,FOLLOW_COLON_in_type_custom937); - stream_COLON.add(COLON94); - - COLON95=(Token)match(input,COLON,FOLLOW_COLON_in_type_custom939); - stream_COLON.add(COLON95); - - id=(Token)match(input,TARS_IDENTIFIER,FOLLOW_TARS_IDENTIFIER_in_type_custom943); - stream_TARS_IDENTIFIER.add(id); - - // AST REWRITE - // elements: - // token labels: - // rule labels: retval - // token list labels: - // rule list labels: - // wildcard labels: - retval.tree = root_0; - RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); - - root_0 = (Object)adaptor.nil(); - // 139:3: -> ^( TARS_REF[$ns.text,$id.text] ) - { - // TarsParser.g:139:6: ^( TARS_REF[$ns.text,$id.text] ) - { - Object root_1 = (Object)adaptor.nil(); - root_1 = (Object)adaptor.becomeRoot(new TarsCustomType(TARS_REF, (ns!=null?ns.getText():null), (id!=null?id.getText():null)), root_1); - adaptor.addChild(root_0, root_1); - } - - } - - - retval.tree = root_0; - - } - break; - - } - retval.stop = input.LT(-1); - - retval.tree = (Object)adaptor.rulePostProcessing(root_0); - adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); - - } - catch (RecognitionException re) { - reportError(re); - recover(input,re); - retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); - } - finally { - // do for sure before leaving - } - return retval; - } - // $ANTLR end "type_custom" - - // Delegated rules - - - - public static final BitSet FOLLOW_include_def_in_start70 = new BitSet(new long[]{0x0000004080000000L}); - public static final BitSet FOLLOW_namespace_def_in_start73 = new BitSet(new long[]{0x0000004000000002L}); - public static final BitSet FOLLOW_TARS_INCLUDE_in_include_def102 = new BitSet(new long[]{0x0000200000000000L}); - public static final BitSet FOLLOW_TARS_STRING_LITERAL_in_include_def104 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_NAMESPACE_in_namespace_def127 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_namespace_def129 = new BitSet(new long[]{0x0000000000001000L}); - public static final BitSet FOLLOW_LBRACE_in_namespace_def131 = new BitSet(new long[]{0x0000400C05000000L}); - public static final BitSet FOLLOW_definition_in_namespace_def134 = new BitSet(new long[]{0x0000000000200000L}); - public static final BitSet FOLLOW_SEMI_in_namespace_def136 = new BitSet(new long[]{0x0000400C05040000L}); - public static final BitSet FOLLOW_RBRACE_in_namespace_def140 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_const_def_in_definition167 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_enum_def_in_definition174 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_struct_def_in_definition179 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_key_def_in_definition184 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_interface_def_in_definition189 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_CONST_in_const_def202 = new BitSet(new long[]{0x0005181112C00000L}); - public static final BitSet FOLLOW_type_primitive_in_const_def204 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_const_def206 = new BitSet(new long[]{0x0000000000000100L}); - public static final BitSet FOLLOW_EQ_in_const_def208 = new BitSet(new long[]{0x0000A00228000000L}); - public static final BitSet FOLLOW_const_initializer_in_const_def212 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_ENUM_in_enum_def238 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_enum_def242 = new BitSet(new long[]{0x0000000000001000L}); - public static final BitSet FOLLOW_LBRACE_in_enum_def244 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_enum_def248 = new BitSet(new long[]{0x0000000000040020L}); - public static final BitSet FOLLOW_COMMA_in_enum_def251 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_enum_def255 = new BitSet(new long[]{0x0000000000040020L}); - public static final BitSet FOLLOW_COMMA_in_enum_def259 = new BitSet(new long[]{0x0000000000040000L}); - public static final BitSet FOLLOW_RBRACE_in_enum_def262 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_ENUM_in_enum_def284 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_enum_def288 = new BitSet(new long[]{0x0000000000001000L}); - public static final BitSet FOLLOW_LBRACE_in_enum_def290 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_enum_def294 = new BitSet(new long[]{0x0000000000000100L}); - public static final BitSet FOLLOW_EQ_in_enum_def296 = new BitSet(new long[]{0x0000000200000000L}); - public static final BitSet FOLLOW_TARS_INTEGER_LITERAL_in_enum_def300 = new BitSet(new long[]{0x0000000000040020L}); - public static final BitSet FOLLOW_COMMA_in_enum_def303 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_enum_def307 = new BitSet(new long[]{0x0000000000000100L}); - public static final BitSet FOLLOW_EQ_in_enum_def309 = new BitSet(new long[]{0x0000000200000000L}); - public static final BitSet FOLLOW_TARS_INTEGER_LITERAL_in_enum_def313 = new BitSet(new long[]{0x0000000000040020L}); - public static final BitSet FOLLOW_COMMA_in_enum_def317 = new BitSet(new long[]{0x0000000000040000L}); - public static final BitSet FOLLOW_RBRACE_in_enum_def320 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_STRUCT_in_struct_def351 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_struct_def353 = new BitSet(new long[]{0x0000000000001000L}); - public static final BitSet FOLLOW_LBRACE_in_struct_def355 = new BitSet(new long[]{0x0000000200000000L}); - public static final BitSet FOLLOW_struct_member_in_struct_def358 = new BitSet(new long[]{0x0000000000200000L}); - public static final BitSet FOLLOW_SEMI_in_struct_def360 = new BitSet(new long[]{0x0000000200040000L}); - public static final BitSet FOLLOW_RBRACE_in_struct_def364 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_INTEGER_LITERAL_in_struct_member391 = new BitSet(new long[]{0x0000028000000000L}); - public static final BitSet FOLLOW_TARS_REQUIRE_in_struct_member396 = new BitSet(new long[]{0x0007183152C00000L}); - public static final BitSet FOLLOW_TARS_OPTIONAL_in_struct_member402 = new BitSet(new long[]{0x0007183152C00000L}); - public static final BitSet FOLLOW_type_in_struct_member405 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_struct_member407 = new BitSet(new long[]{0x0000000000000102L}); - public static final BitSet FOLLOW_EQ_in_struct_member410 = new BitSet(new long[]{0x0000A00228000000L}); - public static final BitSet FOLLOW_const_initializer_in_struct_member414 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_KEY_in_key_def443 = new BitSet(new long[]{0x0000000000002000L}); - public static final BitSet FOLLOW_LBRACKET_in_key_def445 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_key_def449 = new BitSet(new long[]{0x0000000000000020L}); - public static final BitSet FOLLOW_COMMA_in_key_def452 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_key_def456 = new BitSet(new long[]{0x0000000000080020L}); - public static final BitSet FOLLOW_RBRACKET_in_key_def460 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_INTERFACE_in_interface_def488 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_interface_def490 = new BitSet(new long[]{0x0000000000001000L}); - public static final BitSet FOLLOW_LBRACE_in_interface_def492 = new BitSet(new long[]{0x0007183152C00000L}); - public static final BitSet FOLLOW_operation_in_interface_def495 = new BitSet(new long[]{0x0000000000200000L}); - public static final BitSet FOLLOW_SEMI_in_interface_def497 = new BitSet(new long[]{0x0007183152C40000L}); - public static final BitSet FOLLOW_RBRACE_in_interface_def501 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_type_in_operation528 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_operation530 = new BitSet(new long[]{0x0000000000004000L}); - public static final BitSet FOLLOW_LPAREN_in_operation532 = new BitSet(new long[]{0x00071D3152D00000L}); - public static final BitSet FOLLOW_param_in_operation535 = new BitSet(new long[]{0x0000000000100020L}); - public static final BitSet FOLLOW_COMMA_in_operation538 = new BitSet(new long[]{0x00071D3152C00000L}); - public static final BitSet FOLLOW_param_in_operation540 = new BitSet(new long[]{0x0000000000100020L}); - public static final BitSet FOLLOW_RPAREN_in_operation547 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_ROUTE_KEY_in_param576 = new BitSet(new long[]{0x0007193152C00000L}); - public static final BitSet FOLLOW_TARS_OUT_in_param579 = new BitSet(new long[]{0x0007183152C00000L}); - public static final BitSet FOLLOW_type_in_param582 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_param584 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_INTEGER_LITERAL_in_const_initializer613 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_FLOATING_POINT_LITERAL_in_const_initializer620 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_STRING_LITERAL_in_const_initializer627 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_FALSE_in_const_initializer634 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_TRUE_in_const_initializer641 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_type_primitive_in_type654 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_type_vector_in_type659 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_type_map_in_type664 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_type_custom_in_type669 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_VOID_in_type_primitive681 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_BOOL_in_type_primitive697 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_BYTE_in_type_primitive713 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_SHORT_in_type_primitive729 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_INT_in_type_primitive745 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_LONG_in_type_primitive761 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_FLOAT_in_type_primitive777 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_DOUBLE_in_type_primitive793 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_STRING_in_type_primitive809 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_UNSIGNED_in_type_primitive825 = new BitSet(new long[]{0x0000000100000000L}); - public static final BitSet FOLLOW_TARS_INT_in_type_primitive827 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_VECTOR_in_type_vector849 = new BitSet(new long[]{0x0000000000008000L}); - public static final BitSet FOLLOW_LT_in_type_vector851 = new BitSet(new long[]{0x0007183152C00000L}); - public static final BitSet FOLLOW_type_in_type_vector853 = new BitSet(new long[]{0x0000000000000400L}); - public static final BitSet FOLLOW_GT_in_type_vector855 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_MAP_in_type_map879 = new BitSet(new long[]{0x0000000000008000L}); - public static final BitSet FOLLOW_LT_in_type_map881 = new BitSet(new long[]{0x0007183152C00000L}); - public static final BitSet FOLLOW_type_in_type_map883 = new BitSet(new long[]{0x0000000000000020L}); - public static final BitSet FOLLOW_COMMA_in_type_map885 = new BitSet(new long[]{0x0007183152C00000L}); - public static final BitSet FOLLOW_type_in_type_map887 = new BitSet(new long[]{0x0000000000000400L}); - public static final BitSet FOLLOW_GT_in_type_map889 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_type_custom916 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_type_custom935 = new BitSet(new long[]{0x0000000000000010L}); - public static final BitSet FOLLOW_COLON_in_type_custom937 = new BitSet(new long[]{0x0000000000000010L}); - public static final BitSet FOLLOW_COLON_in_type_custom939 = new BitSet(new long[]{0x0000000040000000L}); - public static final BitSet FOLLOW_TARS_IDENTIFIER_in_type_custom943 = new BitSet(new long[]{0x0000000000000002L}); -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsConst.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsConst.java deleted file mode 100644 index 232c2609..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsConst.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.Tree; - -public class TarsConst extends CommonTree { - - private final String constName; - private final String constValue; - - private TarsPrimitiveType constType; - - public TarsConst(int tokenType, String constName, String constValue) { - super(new CommonToken(tokenType)); - this.constName = constName; - this.constValue = constValue; - } - - @Override - public void addChild(Tree child) { - super.addChild(child); - if (child instanceof TarsPrimitiveType) { - constType = (TarsPrimitiveType) child; - } - } - - public TarsPrimitiveType constType() { - return constType; - } - - public String constName() { - return constName; - } - - public String constValue() { - return constValue; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsCustomType.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsCustomType.java deleted file mode 100644 index f71b53c9..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsCustomType.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -public class TarsCustomType extends TarsType { - - private final String namespace; - - public TarsCustomType(int tokenType, String typeName) { - super(tokenType, typeName); - this.namespace = null; - } - - public TarsCustomType(int tokenType, String namespace, String typeName) { - super(tokenType, typeName); - this.namespace = namespace; - } - - @Override - public boolean isCustom() { - return true; - } - - @Override - public TarsCustomType asCustom() { - return this; - } - - public String namespace() { - return namespace; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsEnum.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsEnum.java deleted file mode 100644 index da4ab3ac..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsEnum.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import java.util.ArrayList; -import java.util.List; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.Tree; - -import static com.qq.tars.maven.parse.TarsLexer.*; - -public class TarsEnum extends CommonTree { - - private final String enumName; - private final List enumMemberList = new ArrayList(); - private final List enumValueList = new ArrayList(); - - public TarsEnum(int tokenType, String enumName) { - super(new CommonToken(tokenType)); - this.enumName = enumName; - } - - @Override - public void addChild(Tree child) { - super.addChild(child); - - if (child.getType() == TARS_IDENTIFIER) { - enumMemberList.add(child.getText()); - } else if (child.getType() == TARS_INTEGER_LITERAL) { - enumValueList.add(child.getText()); - } - } - - public String enumName() { - return enumName; - } - - public List enumMemberList() { - return enumMemberList; - } - - public List enumValueList() { - return enumValueList; - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsInclude.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsInclude.java deleted file mode 100644 index d701519a..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsInclude.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.tree.CommonTree; - -public class TarsInclude extends CommonTree { - - private final String fileName; - - public TarsInclude(int tokenType, String identifier) { - super(new CommonToken(tokenType)); - this.fileName = identifier + ".tars"; - } - - public String fileName() { - return fileName; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsInterface.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsInterface.java deleted file mode 100644 index ad145856..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsInterface.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import java.util.ArrayList; -import java.util.List; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.Tree; - -public class TarsInterface extends CommonTree { - - private final String interfaceName; - private final List operationList = new ArrayList(); - - public TarsInterface(int tokenType, String interfaceName) { - super(new CommonToken(tokenType)); - this.interfaceName = interfaceName; - } - - @Override - public void addChild(Tree child) { - super.addChild(child); - - if (child instanceof TarsOperation) { - operationList.add((TarsOperation) child); - } - } - - public String interfaceName() { - return interfaceName; - } - - public List operationList() { - return operationList; - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsKey.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsKey.java deleted file mode 100644 index 8e8edef8..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsKey.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import java.util.ArrayList; -import java.util.List; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.Tree; - -import static com.qq.tars.maven.parse.TarsLexer.*; - -public class TarsKey extends CommonTree { - - private final String structName; - private final List keyList = new ArrayList(); - - public TarsKey(int tokenType, String structName) { - super(new CommonToken(tokenType)); - this.structName = structName; - } - - @Override - public void addChild(Tree child) { - super.addChild(child); - if (child.getType() == TARS_IDENTIFIER) { - keyList.add(child.getText()); - } - } - - public String structName() { - return structName; - } - - public List keyList() { - return keyList; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsMapType.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsMapType.java deleted file mode 100644 index 2155eef1..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsMapType.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import org.antlr.runtime.Token; - -public class TarsMapType extends TarsType { - - public TarsMapType(Token token) { - super(token, "map"); - } - - @Override - public boolean isMap() { - return true; - } - - @Override - public TarsMapType asMap() { - return this; - } - - public TarsType keyType() { - return (TarsType) this.getChild(0); - } - - public TarsType valueType() { - return (TarsType) this.getChild(1); - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsNamespace.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsNamespace.java deleted file mode 100644 index 64744aa3..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsNamespace.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.Tree; - -public class TarsNamespace extends CommonTree { - - private final String namespace; - private final List structList = new ArrayList(); - private final List interfaceList = new ArrayList(); - private final List enumList = new ArrayList(); - private final List constList = new ArrayList(); - private final Map keyMap = new HashMap(); - - public TarsNamespace(int tokenType, String identifier) { - super(new CommonToken(tokenType)); - this.namespace = identifier; - } - - public String namespace() { - return namespace; - } - - @Override - public void addChild(Tree child) { - super.addChild(child); - - if (child instanceof TarsStruct) { - structList.add((TarsStruct) child); - } else if (child instanceof TarsInterface) { - interfaceList.add((TarsInterface) child); - } else if (child instanceof TarsEnum) { - enumList.add((TarsEnum) child); - } else if (child instanceof TarsConst) { - constList.add((TarsConst) child); - } else if (child instanceof TarsKey) { - TarsKey jk = (TarsKey) child; - keyMap.put(jk.structName(), jk); - } - } - - public List structList() { - return structList; - } - - public List interfaceList() { - return interfaceList; - } - - public List enumList() { - return enumList; - } - - public List constList() { - return constList; - } - - public Map keyMap() { - return keyMap; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsOperation.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsOperation.java deleted file mode 100644 index 0a5a865b..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsOperation.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import java.util.ArrayList; -import java.util.List; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.Tree; - -public class TarsOperation extends CommonTree { - - private TarsType retType; - private final String oprationName; - private final List paramList = new ArrayList(); - - public TarsOperation(int tokenType, String oprationName) { - super(new CommonToken(tokenType)); - this.oprationName = oprationName; - } - - @Override - public void addChild(Tree child) { - super.addChild(child); - - if (child instanceof TarsType) { - retType = (TarsType) child; - } else if (child instanceof TarsParam) { - paramList.add((TarsParam) child); - } - } - - public TarsType retType() { - return retType; - } - - public String oprationName() { - return oprationName; - } - - public List paramList() { - return paramList; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsParam.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsParam.java deleted file mode 100644 index aabf48ac..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsParam.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.Token; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.Tree; - -public class TarsParam extends CommonTree { - - private final boolean isOut; - private final boolean isRouteKey; - private TarsType paramType; - private final String paramName; - - public TarsParam(int tokenType, String paramName, Token isOut, Token isRouteKey) { - super(new CommonToken(tokenType)); - this.isOut = isOut != null; - this.isRouteKey = isRouteKey != null; - this.paramName = paramName; - } - - @Override - public void addChild(Tree child) { - super.addChild(child); - - if (child instanceof TarsType) { - paramType = (TarsType) child; - } - } - - public String paramName() { - return paramName; - } - - public TarsType paramType() { - return paramType; - } - - public boolean isOut() { - return isOut; - } - - public boolean isRouteKey() { - return isRouteKey; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsPrimitiveType.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsPrimitiveType.java deleted file mode 100644 index f6412418..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsPrimitiveType.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.Token; - -import static com.qq.tars.maven.parse.TarsLexer.*; - -public class TarsPrimitiveType extends TarsType { - - public static enum PrimitiveType { - VOID, BOOL, BYTE, SHORT, INT, LONG, FLOAT, DOUBLE, STRING - } - - private final PrimitiveType primitiveType; - - public TarsPrimitiveType(Token token) { - super(token, toPrimitiveType(token.getType()).name()); - this.primitiveType = toPrimitiveType(token.getType()); - } - - public TarsPrimitiveType(int type) { - this(new CommonToken(type)); - } - - @Override - public boolean isPrimitive() { - return true; - } - - @Override - public TarsPrimitiveType asPrimitive() { - return this; - } - - public PrimitiveType primitiveType() { - return primitiveType; - } - - public boolean isVoid() { - return primitiveType == PrimitiveType.VOID; - } - - private static PrimitiveType toPrimitiveType(int tokenType) { - PrimitiveType type = null; - switch (tokenType) { - case TARS_VOID: - type = PrimitiveType.VOID; - break; - case TARS_BOOL: - type = PrimitiveType.BOOL; - break; - case TARS_BYTE: - type = PrimitiveType.BYTE; - break; - case TARS_SHORT: - type = PrimitiveType.SHORT; - break; - case TARS_INT: - type = PrimitiveType.INT; - break; - case TARS_LONG: - type = PrimitiveType.LONG; - break; - case TARS_FLOAT: - type = PrimitiveType.FLOAT; - break; - case TARS_DOUBLE: - type = PrimitiveType.DOUBLE; - break; - case TARS_STRING: - type = PrimitiveType.STRING; - break; - } - return type; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsRoot.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsRoot.java deleted file mode 100644 index 7ed3356d..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsRoot.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import java.util.ArrayList; -import java.util.List; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.Tree; - -public class TarsRoot extends CommonTree { - - public TarsRoot(int tokenType) { - super(new CommonToken(tokenType)); - } - - private final List includeList = new ArrayList(); - private final List namespaceList = new ArrayList(); - - @Override - public void addChild(Tree child) { - super.addChild(child); - - if (child instanceof TarsInclude) { - includeList.add((TarsInclude) child); - } else if (child instanceof TarsNamespace) { - namespaceList.add((TarsNamespace) child); - } - } - - public List includeFileList() { - return includeList; - } - - public List namespaceList() { - return namespaceList; - } - - /* - * just for print doc - */ - - private CommonTokenStream tokenStream; - - public CommonTokenStream getTokenStream() { - return tokenStream; - } - - public void setTokenStream(CommonTokenStream tokenStream) { - this.tokenStream = tokenStream; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsStruct.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsStruct.java deleted file mode 100644 index f7da5d1f..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsStruct.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import java.util.ArrayList; -import java.util.List; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.Tree; - -public class TarsStruct extends CommonTree { - - private final String structName; - private final List memberList = new ArrayList(); - - public TarsStruct(int tokenType, String structName) { - super(new CommonToken(tokenType)); - this.structName = structName; - } - - @Override - public void addChild(Tree child) { - super.addChild(child); - if (child instanceof TarsStructMember) { - memberList.add((TarsStructMember) child); - } - } - - public String structName() { - return structName; - } - - public List memberList() { - return memberList; - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsStructMember.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsStructMember.java deleted file mode 100644 index 012c25a5..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsStructMember.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.Token; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.Tree; - -import static com.qq.tars.maven.parse.TarsLexer.*; - -public class TarsStructMember extends CommonTree { - - private final int tag; - private final boolean isRequire; - private final String memberName; - private final String defaultValue; - - private TarsType memberType; - - public TarsStructMember(int tokenType, String tag, Token isRequire, String memberName, String defaultValue) { - super(new CommonToken(tokenType)); - this.tag = Integer.parseInt(tag); - if (isRequire.getType() == TARS_REQUIRE) { - this.isRequire = true; - } else if (isRequire.getType() == TARS_OPTIONAL) { - this.isRequire = false; - } else { - throw new RuntimeException("Error Struct require/optional"); - } - this.memberName = memberName; - this.defaultValue = defaultValue; - } - - @Override - public void addChild(Tree child) { - super.addChild(child); - - if (child instanceof TarsType) { - memberType = (TarsType) child; - } - } - - public int tag() { - return tag; - } - - public boolean isRequire() { - return isRequire; - } - - public TarsType memberType() { - return memberType; - } - - public String memberName() { - return memberName; - } - - public String defaultValue() { - return defaultValue; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsType.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsType.java deleted file mode 100644 index 3f586cb2..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsType.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.Token; -import org.antlr.runtime.tree.CommonTree; - -public abstract class TarsType extends CommonTree { - - private final String typeName; - - public TarsType(int tokenType, String typeName) { - super(new CommonToken(tokenType)); - this.typeName = typeName; - } - - public TarsType(Token token, String typeName) { - super(token); - this.typeName = typeName; - } - - public String typeName() { - return typeName; - } - - public boolean isPrimitive() { - return false; - } - - public boolean isVector() { - return false; - } - - public boolean isMap() { - return false; - } - - public boolean isCustom() { - return false; - } - - public TarsPrimitiveType asPrimitive() { - return null; - } - - public TarsVectorType asVector() { - return null; - } - - public TarsMapType asMap() { - return null; - } - - public TarsCustomType asCustom() { - return null; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsVectorType.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsVectorType.java deleted file mode 100644 index 5fbf492a..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/parse/ast/TarsVectorType.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.parse.ast; - -import org.antlr.runtime.Token; -import org.antlr.runtime.tree.Tree; - -import com.qq.tars.maven.parse.ast.TarsPrimitiveType.PrimitiveType; - -public class TarsVectorType extends TarsType { - - private TarsType subType; - - public TarsVectorType(Token token) { - super(token, "vector"); - } - - @Override - public boolean isVector() { - return true; - } - - @Override - public TarsVectorType asVector() { - return this; - } - - @Override - public void addChild(Tree child) { - super.addChild(child); - if (child instanceof TarsType) { - subType = (TarsType) child; - } - } - - public TarsType subType() { - return subType; - } - - public boolean isByteArray() { - return subType.isPrimitive() && subType.asPrimitive().primitiveType() == PrimitiveType.BYTE; - } - -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/script/Platform.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/script/Platform.java deleted file mode 100644 index 7cce8c9b..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/script/Platform.java +++ /dev/null @@ -1,208 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.script; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.codehaus.plexus.util.StringUtils; - -import com.qq.tars.maven.model.ClasspathElement; -import com.qq.tars.maven.model.Dependency; -import com.qq.tars.maven.model.Directory; - -public class Platform { - - public static final String UNIX_NAME = "unix"; - - public static final String WINDOWS_NAME = "windows"; - - private static final Map ALL_PLATFORMS; - - private static final String DEFAULT_UNIX_BIN_FILE_EXTENSION = ""; - - private static final String DEFAULT_WINDOWS_BIN_FILE_EXTENSION = ".bat"; - - private String binFileExtension; - - private String name; - - private boolean isWindows; - - private boolean showConsoleWindow = true; - - static { - ALL_PLATFORMS = new HashMap(); - addPlatform(new Platform(UNIX_NAME, false, DEFAULT_UNIX_BIN_FILE_EXTENSION)); - addPlatform(new Platform(WINDOWS_NAME, true, DEFAULT_WINDOWS_BIN_FILE_EXTENSION)); - } - - private static Platform addPlatform(Platform platform) { - ALL_PLATFORMS.put(platform.name, platform); - return platform; - } - - public static Platform getInstance(String platformName) throws Exception { - Platform platform = ALL_PLATFORMS.get(platformName); - - if (platform == null) { - throw new Exception("Unknown platform name '" + platformName + "'"); - } - - return platform; - } - - public static Set getAllPlatformNames() { - return ALL_PLATFORMS.keySet(); - } - - public static Set getAllPlatforms() { - return new HashSet(ALL_PLATFORMS.values()); - } - - public static Set getPlatformSet(List platformList) throws Exception { - return getPlatformSet(platformList, new HashSet(ALL_PLATFORMS.values())); - } - - public static Set getPlatformSet(List platformList, Set allSet) throws Exception { - if (platformList == null) { - return allSet; - } - - if (platformList.size() == 1) { - String first = platformList.get(0); - - if ("all".equals(first)) { - return allSet; - } - throw new Exception("The special platform 'all' can only be used if it is the only element in the platform list."); - } - - Set platformSet = new HashSet(); - - for (String platformName : platformList) { - if (platformName.equals("all")) { - throw new Exception("The special platform 'all' can only be used if it is the only element in a platform list."); - } - platformSet.add(getInstance(platformName)); - } - - return platformSet; - } - - private Platform(String name, boolean isWindows, String binFileExtension) { - this.name = name; - - this.isWindows = isWindows; - - this.binFileExtension = binFileExtension; - } - - public String getInterpolationToken() { - return isWindows ? "#" : "@"; - } - - public String getBinFileExtension() { - return binFileExtension; - } - - public String getBasedir() { - return isWindows ? "\"%BASEDIR%\"" : "\"$BASEDIR\""; - } - - public String getRepo() { - return isWindows ? "\"%REPO%\"" : "\"$REPO\""; - } - - public String getSeparator() { - return isWindows ? "\\" : "/"; - } - - public String getPathSeparator() { - return isWindows ? ";" : ":"; - } - - public String getCommentPrefix() { - return isWindows ? "@REM " : "# "; - } - - public String getNewLine() { - return isWindows ? "\r\n" : "\n"; - } - - public String getClassPath(List classpath) throws Exception { - - StringBuilder classpathBuffer = new StringBuilder(); - - for (ClasspathElement classpathElement : classpath) { - if (classpathBuffer.length() > 0) { - classpathBuffer.append(getPathSeparator()); - } - - if (classpathElement instanceof Directory) { - Directory directory = (Directory) classpathElement; - if (directory.getRelativePath().charAt(0) != '/') { - classpathBuffer.append(getBasedir()).append(getSeparator()); - } - } else if (classpathElement instanceof Dependency) { - classpathBuffer.append(getSeparator()); - } else { - throw new Exception("Unknown classpath element type: " + classpathElement.getClass().getName()); - } - - classpathBuffer.append(StringUtils.replace(classpathElement.getRelativePath(), "/", getSeparator())); - } - - return classpathBuffer.toString(); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - Platform platform = (Platform) o; - - return name.equals(platform.name); - } - - public int hashCode() { - return name.hashCode(); - } - - public String getName() { - return name; - } - - public boolean isShowConsoleWindow() { - return showConsoleWindow; - } - - public void setBinFileExtension(String binFileExtension) { - if (binFileExtension == null) { - this.binFileExtension = ""; - } else { - this.binFileExtension = binFileExtension; - } - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/ArchiveEntryUtils.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/ArchiveEntryUtils.java deleted file mode 100644 index 87c6236d..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/ArchiveEntryUtils.java +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.util; - -import java.io.File; -import java.lang.reflect.Method; - -import org.apache.maven.plugin.logging.Log; -import org.codehaus.plexus.archiver.ArchiverException; -import org.codehaus.plexus.util.Os; -import org.codehaus.plexus.util.cli.CommandLineException; -import org.codehaus.plexus.util.cli.CommandLineUtils; -import org.codehaus.plexus.util.cli.Commandline; - -public final class ArchiveEntryUtils { - - public static boolean jvmFilePermAvailable = false; - - static { - try { - jvmFilePermAvailable = File.class.getMethod("setReadable", new Class[] { Boolean.TYPE }) != null; - } catch (final Exception e) { - } - } - - private ArchiveEntryUtils() { - } - - public static void chmod(final File file, final int mode, final Log logger, boolean useJvmChmod) throws ArchiverException { - if (!Os.isFamily(Os.FAMILY_UNIX)) { - return; - } - - final String m = Integer.toOctalString(mode & 0xfff); - - if (useJvmChmod && !jvmFilePermAvailable) { - logger.info("chmod it's not possible where your current jvm"); - useJvmChmod = false; - } - - if (useJvmChmod && jvmFilePermAvailable) { - applyPermissionsWithJvm(file, m, logger); - return; - } - - try { - final Commandline commandline = new Commandline(); - - commandline.setWorkingDirectory(file.getParentFile().getAbsolutePath()); - - if (logger.isDebugEnabled()) { - logger.debug(file + ": mode " + Integer.toOctalString(mode) + ", chmod " + m); - } - - commandline.setExecutable("chmod"); - - commandline.createArg().setValue(m); - - final String path = file.getAbsolutePath(); - - commandline.createArg().setValue(path); - - final CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer(); - - final CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer(); - - final int exitCode = CommandLineUtils.executeCommandLine(commandline, stderr, stdout); - - if (exitCode != 0) { - logger.warn("-------------------------------"); - logger.warn("Standard error:"); - logger.warn("-------------------------------"); - logger.warn(stderr.getOutput()); - logger.warn("-------------------------------"); - logger.warn("Standard output:"); - logger.warn("-------------------------------"); - logger.warn(stdout.getOutput()); - logger.warn("-------------------------------"); - - throw new ArchiverException("chmod exit code was: " + exitCode); - } - } catch (final CommandLineException e) { - throw new ArchiverException("Error while executing chmod.", e); - } - - } - - public static void chmod(final File file, final int mode, final Log logger) throws ArchiverException { - chmod(file, mode, logger, Boolean.getBoolean("useJvmChmod") && jvmFilePermAvailable); - } - - public static void applyPermissionsWithJvm(final File file, final String mode, final Log logger) { - final FilePermission filePermission = FilePermissionUtils.getFilePermissionFromMode(mode, logger); - - Method method; - try { - method = File.class.getMethod("setReadable", new Class[] { Boolean.TYPE, Boolean.TYPE }); - - method.invoke(file, new Object[] { Boolean.valueOf(filePermission.isReadable()), Boolean.valueOf(filePermission.isOwnerOnlyReadable()) }); - - method = File.class.getMethod("setExecutable", new Class[] { Boolean.TYPE, Boolean.TYPE }); - method.invoke(file, new Object[] { Boolean.valueOf(filePermission.isExecutable()), Boolean.valueOf(filePermission.isOwnerOnlyExecutable()) }); - - method = File.class.getMethod("setWritable", new Class[] { Boolean.TYPE, Boolean.TYPE }); - method.invoke(file, new Object[] { Boolean.valueOf(filePermission.isWritable()), Boolean.valueOf(filePermission.isOwnerOnlyWritable()) }); - } catch (final Exception e) { - logger.error("error calling dynamically file permissons with jvm " + e.getMessage(), e); - throw new RuntimeException("error calling dynamically file permissons with jvm " + e.getMessage(), e); - } - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/FilePermission.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/FilePermission.java deleted file mode 100644 index 0e9b50b1..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/FilePermission.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.util; - -public class FilePermission { - - private boolean executable; - - private boolean ownerOnlyExecutable; - - private boolean ownerOnlyReadable; - - private boolean readable; - - private boolean ownerOnlyWritable; - - private boolean writable; - - public FilePermission(boolean executable, boolean ownerOnlyExecutable, boolean ownerOnlyReadable, boolean readable, - boolean ownerOnlyWritable, boolean writable) { - this.executable = executable; - this.ownerOnlyExecutable = ownerOnlyExecutable; - this.ownerOnlyReadable = ownerOnlyReadable; - this.readable = readable; - this.ownerOnlyWritable = ownerOnlyWritable; - this.writable = writable; - } - - public boolean isExecutable() { - return executable; - } - - public void setExecutable(boolean executable) { - this.executable = executable; - } - - public boolean isOwnerOnlyExecutable() { - return ownerOnlyExecutable; - } - - public void setOwnerOnlyExecutable(boolean ownerOnlyExecutable) { - this.ownerOnlyExecutable = ownerOnlyExecutable; - } - - public boolean isOwnerOnlyReadable() { - return ownerOnlyReadable; - } - - public void setOwnerOnlyReadable(boolean ownerOnlyReadable) { - this.ownerOnlyReadable = ownerOnlyReadable; - } - - public boolean isReadable() { - return readable; - } - - public void setReadable(boolean readable) { - this.readable = readable; - } - - public boolean isOwnerOnlyWritable() { - return ownerOnlyWritable; - } - - public void setOwnerOnlyWritable(boolean ownerOnlyWritable) { - this.ownerOnlyWritable = ownerOnlyWritable; - } - - public boolean isWritable() { - return writable; - } - - public void setWritable(boolean writable) { - this.writable = writable; - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/FilePermissionUtils.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/FilePermissionUtils.java deleted file mode 100644 index ab01294b..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/FilePermissionUtils.java +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.util; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.maven.plugin.logging.Log; -import org.codehaus.plexus.util.StringUtils; - -public class FilePermissionUtils { - - private FilePermissionUtils() { - } - - public static FilePermission getFilePermissionFromMode(String mode, Log logger) { - if (StringUtils.isBlank(mode)) { - throw new IllegalArgumentException(" file mode cannot be empty"); - } - if (mode.length() != 3 && mode.length() != 4) { - throw new IllegalArgumentException(" file mode must be 3 or 4 characters"); - } - - List modes = new ArrayList(mode.length()); - for (int i = 0, size = mode.length(); i < size; i++) { - modes.add(String.valueOf(mode.charAt(i))); - } - - boolean executable = false, ownerOnlyExecutable = true, ownerOnlyReadable = true, readable = false, ownerOnlyWritable = true, writable = false; - - // handle user perm - try { - int userMode = Integer.valueOf((String) modes.get(mode.length() == 4 ? 1 : 0)).intValue(); - switch (userMode) { - case 0: - break; - case 1: - executable = true; - break; - case 2: - writable = true; - break; - case 3: - writable = true; - executable = true; - break; - case 4: - readable = true; - break; - case 5: - readable = true; - executable = true; - break; - case 6: - readable = true; - writable = true; - break; - case 7: - writable = true; - readable = true; - executable = true; - break; - default: - logger.warn("ignore file mode " + userMode); - } - } catch (NumberFormatException e) { - throw new IllegalArgumentException(" file mode must contains only number " + mode); - } - - try { - int allMode = Integer.valueOf((String) modes.get(mode.length() == 4 ? 3 : 2)).intValue(); - switch (allMode) { - case 0: - break; - case 1: - executable = true; - ownerOnlyExecutable = false; - break; - case 2: - writable = true; - ownerOnlyWritable = false; - break; - case 3: - writable = true; - executable = true; - ownerOnlyExecutable = false; - ownerOnlyWritable = false; - break; - case 4: - readable = true; - ownerOnlyReadable = false; - break; - case 5: - readable = true; - executable = true; - ownerOnlyReadable = false; - ownerOnlyExecutable = false; - break; - case 6: - readable = true; - ownerOnlyReadable = false; - writable = true; - ownerOnlyWritable = false; - break; - case 7: - writable = true; - readable = true; - executable = true; - ownerOnlyReadable = false; - ownerOnlyExecutable = false; - ownerOnlyWritable = false; - break; - default: - logger.warn("ignore file mode " + allMode); - } - } catch (NumberFormatException e) { - throw new IllegalArgumentException(" file mode must contains only number " + mode); - } - return new FilePermission(executable, ownerOnlyExecutable, ownerOnlyReadable, readable, ownerOnlyWritable, writable); - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/StringUtils.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/StringUtils.java deleted file mode 100644 index e4486e50..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/StringUtils.java +++ /dev/null @@ -1,369 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.util; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Iterator; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class StringUtils { - - public static String decodeNetUnicode(String str) { - if (str == null) return null; - String pStr = "&#(\\d+);"; - Pattern p = Pattern.compile(pStr); - Matcher m = p.matcher(str); - StringBuffer sb = new StringBuffer(); - while (m.find()) { - String mcStr = m.group(1); - int charValue = StringUtils.convertInt(mcStr, -1); - String s = charValue > 0 ? (char) charValue + "" : ""; - m.appendReplacement(sb, Matcher.quoteReplacement(s)); - } - m.appendTail(sb); - return sb.toString(); - } - - public static String formatDate(String dateStr, String inputFormat, String format) { - String resultStr = dateStr; - try { - Date date = new SimpleDateFormat(inputFormat).parse(dateStr); - resultStr = formatDate(date, format); - } catch (ParseException e) { - } - return resultStr; - } - - public static String formatDate(String dateStr, String format) { - String resultStr = dateStr; - String inputFormat = "yyyy-MM-dd HH:mm:ss"; - if (dateStr == null) { - return ""; - } - if (dateStr.matches("\\d{1,4}\\-\\d{1,2}\\-\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}")) { - inputFormat = "yyyy-MM-dd HH:mm:ss.SSS"; - } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}:\\d{1,2}")) { - inputFormat = "yyyy-MM-dd HH:mm:ss"; - } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}:\\d{1,2}")) { - inputFormat = "yyyy-MM-dd HH:mm"; - } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}")) { - inputFormat = "yyyy-MM-dd HH"; - } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}")) { - inputFormat = "yyyy-MM-dd"; - } else if (dateStr.matches("\\d{1,4}/\\d{1,2}/\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}")) { - inputFormat = "yyyy/MM/dd HH:mm:ss.SSS"; - } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}:\\d{1,2}")) { - inputFormat = "yyyy/MM/dd HH:mm:ss"; - } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}:\\d{1,2}")) { - inputFormat = "yyyy/MM/dd HH:mm"; - } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}")) { - inputFormat = "yyyy/MM/dd HH"; - } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}")) { - inputFormat = "yyyy/MM/dd"; - } - resultStr = formatDate(dateStr, inputFormat, format); - return resultStr; - } - - public static String formatDate(Date date, String format) { - SimpleDateFormat sdf = new SimpleDateFormat(format); - return sdf.format(date); - } - - public static String convertString(String str, String defaults) { - if (str == null) { - return defaults; - } else { - return str; - } - } - - public static int convertInt(String str, int defaults) { - if (str == null) { - return defaults; - } - try { - return Integer.parseInt(str); - } catch (Exception e) { - return defaults; - } - } - - public static long convertLong(String str, long defaults) { - if (str == null) { - return defaults; - } - try { - return Long.parseLong(str); - } catch (Exception e) { - return defaults; - } - } - - public static double convertDouble(String str, double defaults) { - if (str == null) { - return defaults; - } - try { - return Double.parseDouble(str); - } catch (Exception e) { - return defaults; - } - } - - public static short convertShort(String str, short defaults) { - if (str == null) { - return defaults; - } - try { - return Short.parseShort(str); - } catch (Exception e) { - return defaults; - } - } - - public static float convertFloat(String str, float defaults) { - if (str == null) { - return defaults; - } - try { - return Float.parseFloat(str); - } catch (Exception e) { - return defaults; - } - } - - public static boolean convertBoolean(String str, boolean defaults) { - if (str == null) { - return defaults; - } - try { - return Boolean.parseBoolean(str); - } catch (Exception e) { - return defaults; - } - } - - public static String[] split(String line, String seperator) { - if (line == null || seperator == null || seperator.length() == 0) return null; - ArrayList list = new ArrayList(); - int pos1 = 0; - int pos2; - for (;;) { - pos2 = line.indexOf(seperator, pos1); - if (pos2 < 0) { - list.add(line.substring(pos1)); - break; - } - list.add(line.substring(pos1, pos2)); - pos1 = pos2 + seperator.length(); - } - for (int i = list.size() - 1; i >= 0 && list.get(i).length() == 0; --i) { - list.remove(i); - } - return list.toArray(new String[0]); - } - - public static int[] splitInt(String line, String seperator, int def) { - String[] ss = split(line, seperator); - int[] r = new int[ss.length]; - for (int i = 0; i < r.length; ++i) { - r[i] = convertInt(ss[i], def); - } - return r; - } - - @SuppressWarnings("unchecked") - public static String join(String separator, Collection c) { - if (c.isEmpty()) return ""; - StringBuilder sb = new StringBuilder(); - Iterator i = c.iterator(); - sb.append(i.next()); - while (i.hasNext()) { - sb.append(separator); - sb.append(i.next()); - } - return sb.toString(); - } - - public static String join(String separator, String[] s) { - return joinArray(separator, s); - } - - public static String joinArray(String separator, Object[] s) { - if (s == null || s.length == 0) return ""; - StringBuilder sb = new StringBuilder(); - sb.append(s[0]); - for (int i = 1; i < s.length; ++i) { - if (s[i] != null) { - sb.append(separator); - sb.append(s[i].toString()); - } - } - return sb.toString(); - } - - public static String joinArray(String separator, int[] s) { - if (s == null || s.length == 0) return ""; - StringBuilder sb = new StringBuilder(); - sb.append(s[0]); - for (int i = 1; i < s.length; ++i) { - sb.append(separator); - sb.append(s[i]); - } - return sb.toString(); - } - - public static String join(String separator, Object... c) { - return joinArray(separator, c); - } - - public static String replaceAll(String s, String src, String dest) { - if (s == null || src == null || dest == null || src.length() == 0) return s; - int pos = s.indexOf(src); - if (pos < 0) return s; - int capacity = dest.length() > src.length() ? s.length() * 2 : s.length(); - StringBuilder sb = new StringBuilder(capacity); - int writen = 0; - for (; pos >= 0;) { - sb.append(s, writen, pos); - sb.append(dest); - writen = pos + src.length(); - pos = s.indexOf(src, writen); - } - sb.append(s, writen, s.length()); - return sb.toString(); - } - - public static String replaceFirst(String s, String src, String dest) { - if (s == null || src == null || dest == null || src.length() == 0) return s; - int pos = s.indexOf(src); - if (pos < 0) { - return s; - } - StringBuilder sb = new StringBuilder(s.length() - src.length() + dest.length()); - - sb.append(s, 0, pos); - sb.append(dest); - sb.append(s, pos + src.length(), s.length()); - return sb.toString(); - } - - public static boolean isEmpty(String s) { - if (s == null) return true; - return s.trim().isEmpty(); - } - - public static String trim(String s) { - if (s == null) return null; - return s.trim(); - } - - public static String removeAll(String s, String src) { - return replaceAll(s, src, ""); - } - - public static String abbreviate(String src, int maxlen, String replacement) { - - if (src == null) return ""; - - if (replacement == null) { - replacement = ""; - } - - StringBuilder dest = new StringBuilder(); - - try { - maxlen = maxlen - computeDisplayLen(replacement); - - if (maxlen < 0) { - return src; - } - - int i = 0; - for (; i < src.length() && maxlen > 0; ++i) { - char c = src.charAt(i); - if (c >= '\u0000' && c <= '\u00FF') { - maxlen = maxlen - 1; - } else { - maxlen = maxlen - 2; - } - if (maxlen >= 0) { - dest.append(c); - } - } - - if (i < src.length() - 1) { - dest.append(replacement); - } - return dest.toString(); - } catch (Throwable e) { - } - return src; - } - - public static String abbreviate(String src, int maxlen) { - return abbreviate(src, maxlen, ""); - } - - public static String toShort(String str, int maxLen, String replacement) { - if (str == null) { - return ""; - } - if (str.length() <= maxLen) { - return str; - } - StringBuilder dest = new StringBuilder(); - double len = 0; - for (int i = 0; i < str.length(); i++) { - char c = str.charAt(i); - if (c >= '\u0000' && c <= '\u00FF') { - len += 0.5; - } else { - len += 1; - } - if (len > maxLen) return dest.toString() + replacement; - else dest.append(c); - } - return dest.toString(); - } - - public static String toShort(String str, int maxLen) { - return toShort(str, maxLen, "..."); - } - - public static int computeDisplayLen(String s) { - int len = 0; - if (s == null) { - return len; - } - - for (int i = 0; i < s.length(); ++i) { - char c = s.charAt(i); - if (c >= '\u0000' && c <= '\u00FF') { - len = len + 1; - } else { - len = len + 2; - } - } - return len; - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/XMLConfigElement.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/XMLConfigElement.java deleted file mode 100644 index b112bf8e..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/XMLConfigElement.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.util; - -import java.util.ArrayList; - -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -public class XMLConfigElement { - - private Element e; - - XMLConfigElement(Element e) { - this.e = e; - } - - public boolean isValid() { - return e != null; - } - - public String getStringAttribute(String name) { - return e != null ? e.getAttribute(name) : null; - } - - public String getStringAttribute(String name, String def) { - String s = getStringAttribute(name); - return s != null && s.length() > 0 ? s : def; - } - - public boolean isExistAttribute(String name) { - return getStringAttribute(name) != null; - } - - public boolean getBooleanAttribute(String name, boolean def) { - String s = getStringAttribute(name); - if ("true".equalsIgnoreCase(s) || "yes".equalsIgnoreCase(s)) return true; - if ("false".equalsIgnoreCase(s) || "no".equalsIgnoreCase(s)) return false; - return StringUtils.convertBoolean(s, def); - } - - public int getIntAttribute(String name, int def) { - String s = getStringAttribute(name); - return StringUtils.convertInt(s, def); - } - - public double getDoubleAttribute(String name, double def) { - String s = getStringAttribute(name); - return StringUtils.convertDouble(s, def); - } - - public long getLongAttribute(String name, long def) { - String s = getStringAttribute(name); - return StringUtils.convertLong(s, def); - } - - public short getShortAttribute(String name, short def) { - String s = getStringAttribute(name); - return StringUtils.convertShort(s, def); - } - - public float getFloatAttribute(String name, float def) { - String s = getStringAttribute(name); - return StringUtils.convertFloat(s, def); - } - - public String getName() { - return e != null ? e.getNodeName() : null; - } - - public String getContent() { - return e != null ? e.getTextContent() : null; - } - - public XMLConfigElement getChildByName(String name) { - if (e == null) return this; - NodeList nl = e.getElementsByTagName(name); - for (int i = 0; i < nl.getLength(); ++i) { - Node n = nl.item(i); - Element ee = (Element) n; - if (ee != null) return new XMLConfigElement(ee); - } - return new XMLConfigElement(null); - } - - public ArrayList getChildListByName(String name) { - ArrayList list = new ArrayList(); - if (e == null) return list; - NodeList nl = e.getElementsByTagName(name); - for (int i = 0; i < nl.getLength(); ++i) { - Node n = nl.item(i); - Element ee = (Element) n; - if (ee != null) list.add(new XMLConfigElement(ee)); - } - return list; - } - - public ArrayList getChildList() { - ArrayList list = new ArrayList(); - if (e == null) return list; - NodeList nl = e.getChildNodes(); - for (int i = 0; i < nl.getLength(); ++i) { - Node n = nl.item(i); - if (n instanceof Element) { - Element ee = (Element) n; - list.add(new XMLConfigElement(ee)); - } - } - return list; - } -} diff --git a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/XMLConfigFile.java b/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/XMLConfigFile.java deleted file mode 100644 index f031dc61..00000000 --- a/tools/tars-maven-plugin/src/main/java/com/qq/tars/maven/util/XMLConfigFile.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Tars available. - * - * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.qq.tars.maven.util; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -public class XMLConfigFile { - - private Document doc; - - public void parse(InputStream is) throws SAXException, IOException, ParserConfigurationException { - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); - docBuilder.setEntityResolver(new EntityResolver() { - - public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { - if (systemId.contains("http://java.sun.com/dtd/web-app_2_3.dtd")) { - return new InputSource(new StringReader("")); - } else { - return null; - } - } - }); - - doc = docBuilder.parse(is); - } - - public XMLConfigElement getRootElement() { - Element root = doc.getDocumentElement(); - return new XMLConfigElement(root); - } -} diff --git a/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/configTemplate b/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/configTemplate deleted file mode 100644 index c42e60e5..00000000 --- a/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/configTemplate +++ /dev/null @@ -1,39 +0,0 @@ - - - enableset=N - setdivision=NULL - - locator= - sync-invoke-timeout=20000 - async-invoke-timeout=20000 - refresh-endpoint-interval=60000 - stat=tars.tarsstat.StatObj - property=tars.tarsproperty.PropertyObj - report-interval=60000 - modulename=$APP$.$SERVER$ - - - node= - app=$APP$ - server=$SERVER$ - localip=$LOCALIP$ - local=tcp -h 127.0.0.1 -p $ADMINPORT$ -t 3000 - basepath=$BASEPATH$ - datapath=$DATAPATH$ - logpath=$LOGPATH$ - loglevel=DEBUG - logsize=15M - log= - config=tars.tarsconfig.ConfigObj - notify=tars.tarsnotify.NotifyObj - mainclass=$MAINCLASS$ - jvmparams=$JVMPARAMS$ - sessiontimeout=120000 - sessioncheckinterval=60000 - tcpnodelay=true - udpbuffersize=8192 - charsetname=UTF-8 - $SERVANTADAPTER$ - - - \ No newline at end of file diff --git a/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/servantTemplate b/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/servantTemplate deleted file mode 100644 index 8feeea41..00000000 --- a/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/servantTemplate +++ /dev/null @@ -1,13 +0,0 @@ - <$APP$.$SERVER$.$SERVANTNAME$Adapter> - allow - endpoint=tcp -h $LOCALIP$ -p $PORT$ -t 60000 - handlegroup=$APP$.$SERVER$.$SERVANTNAME$Adapter - maxconns=200000 - protocol=$PROTOCOL$ - queuecap=10000 - queuetimeout=60000 - servant=$APP$.$SERVER$.$SERVANTNAME$ - shmcap=0 - shmkey=0 - threads=5 - \ No newline at end of file diff --git a/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/unixBinTemplate b/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/unixBinTemplate deleted file mode 100644 index 93a174d9..00000000 --- a/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/unixBinTemplate +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/sh - -# If a specific java binary isn't specified search for the standard 'java' binary -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD=`which java` - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." 1>&2 - echo " We cannot execute $JAVACMD" 1>&2 - exit 1 -fi - -CLASSPATH=@CLASSPATH@ -JVMPARAMS=@JVMPARAMS@ -CONFIG=@CONFIG@ -MAINCLASS=@MAINCLASS@ - -exec "$JAVACMD" "$JVMPARAMS" -classpath "$CLASSPATH" -Dconfig="CONFIG" "$MAINCLASS" diff --git a/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/windowsBinTemplate b/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/windowsBinTemplate deleted file mode 100644 index 425fb0a0..00000000 --- a/tools/tars-maven-plugin/src/main/resources/com/qq/tars/maven/script/windowsBinTemplate +++ /dev/null @@ -1,88 +0,0 @@ -@echo off - -set ERROR_CODE=0 - -:init -@REM Decide how to startup depending on the version of windows - -@REM -- Win98ME -if NOT "%OS%"=="Windows_NT" goto Win9xArg - -@REM set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" @setlocal - -@REM -- 4NT shell -if "%eval[2+2]" == "4" goto 4NTArgs - -@REM -- Regular WinNT shell -set CMD_LINE_ARGS=%* -goto WinNTGetScriptDir - -@REM The 4NT Shell from jp software -:4NTArgs -set CMD_LINE_ARGS=%$ -goto WinNTGetScriptDir - -:Win9xArg -@REM Slurp the command line arguments. This loop allows for an unlimited number -@REM of arguments (up to the command line limit, anyway). -set CMD_LINE_ARGS= -:Win9xApp -if %1a==a goto Win9xGetScriptDir -set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1 -shift -goto Win9xApp - -:Win9xGetScriptDir -set SAVEDIR=%CD% -%0\ -cd %0\..\.. -set BASEDIR=%CD% -cd %SAVEDIR% -set SAVE_DIR= -goto repoSetup - -:WinNTGetScriptDir -set BASEDIR=%~dp0\.. - -:repoSetup - -if "%JAVACMD%"=="" set JAVACMD=#JAVA_BINARY# - -set CLASSPATH=#CLASSPATH# -set JVMPARAMS=#JVMPARAMS# -set CONFIG=#CONFIG# -set MAINCLASS=#MAINCLASS# - -@REM Reaching here means variables are defined and arguments have been captured -:endInit - -%JAVACMD% %JVMPARAMS% -classpath %CLASSPATH% -Dconfig=%CONFIG% %MAINCLASS% -if %ERRORLEVEL% NEQ 0 goto error -goto end - -:error -if "%OS%"=="Windows_NT" @endlocal -set ERROR_CODE=%ERRORLEVEL% - -:end -@REM set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" goto endNT - -@REM For old DOS remove the set variables from ENV - we assume they were not set -@REM before we started - at least we don't leave any baggage around -set CMD_LINE_ARGS= -goto postExec - -:endNT -@REM If error code is set to 1 then the endlocal was done already in :error. -if %ERROR_CODE% EQU 0 @endlocal - - -:postExec - -if "%FORCE_EXIT_ON_ERROR%" == "on" ( - if %ERROR_CODE% NEQ 0 exit %ERROR_CODE% -) - -exit /B %ERROR_CODE%