diff --git a/.bazelrc b/.bazelrc new file mode 100644 index 00000000000..53485cb9743 --- /dev/null +++ b/.bazelrc @@ -0,0 +1 @@ +build --cxxopt=-std=c++17 --host_cxxopt=-std=c++17 diff --git a/.gemini/config.yaml b/.gemini/config.yaml new file mode 100644 index 00000000000..71adf793964 --- /dev/null +++ b/.gemini/config.yaml @@ -0,0 +1,13 @@ +have_fun: false +memory_config: + disabled: false +code_review: + disable: false + comment_severity_threshold: MEDIUM + max_review_comments: -1 + pull_request_opened: + help: false + summary: false + code_review: false + include_drafts: false +ignore_patterns: [] diff --git a/.gitattributes b/.gitattributes index 6d0661ec5a4..4343b9bd8ec 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,4 @@ -TestService.java.txt binary -TestServiceLite.java.txt binary -TestDeprecatedService.java.txt binary -TestDeprecatedServiceLite.java.txt binary +TestService.java.txt -text +TestServiceLite.java.txt -text +TestDeprecatedService.java.txt -text +TestDeprecatedServiceLite.java.txt -text diff --git a/.github/lock.yml b/.github/lock.yml deleted file mode 100644 index 119e4840bee..00000000000 --- a/.github/lock.yml +++ /dev/null @@ -1,2 +0,0 @@ -daysUntilLock: 90 -lockComment: false diff --git a/.github/workflows/branch-testing.yml b/.github/workflows/branch-testing.yml new file mode 100644 index 00000000000..ece8ec4cd58 --- /dev/null +++ b/.github/workflows/branch-testing.yml @@ -0,0 +1,41 @@ +name: GitHub Actions Branch Testing + +on: + push: + branches: + - master + - 'v1.*' + schedule: + - cron: '54 19 * * SUN' # weekly at a "random" time + +permissions: + contents: read + +jobs: + arm64: + runs-on: ubuntu-24.04-arm + strategy: + matrix: + jre: [17] + fail-fast: false # Should swap to true if we grow a large matrix + + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + java-version: ${{ matrix.jre }} + distribution: 'temurin' + + - name: Gradle cache + uses: actions/cache@v4 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} + restore-keys: | + ${{ runner.os }}-gradle- + + - name: Build + run: ./gradlew -Dorg.gradle.parallel=true -Dorg.gradle.jvmargs='-Xmx1g' -PskipAndroid=true -PskipCodegen=true -PerrorProne=false test + diff --git a/.github/workflows/gradle-wrapper-validation.yml b/.github/workflows/gradle-wrapper-validation.yml index 0bde8aeca18..da1e2fed114 100644 --- a/.github/workflows/gradle-wrapper-validation.yml +++ b/.github/workflows/gradle-wrapper-validation.yml @@ -1,10 +1,13 @@ name: "Validate Gradle Wrapper" on: [push, pull_request] +permissions: + contents: read + jobs: validation: name: "Gradle wrapper validation" runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: gradle/wrapper-validation-action@v1 + - uses: actions/checkout@v4 + - uses: gradle/actions/wrapper-validation@v4 diff --git a/.github/workflows/lock.yml b/.github/workflows/lock.yml new file mode 100644 index 00000000000..3070a1a2f7c --- /dev/null +++ b/.github/workflows/lock.yml @@ -0,0 +1,20 @@ +name: 'Lock Threads' + +on: + workflow_dispatch: + schedule: + - cron: '37 3 * * *' + +permissions: + issues: write + pull-requests: write + +jobs: + lock: + runs-on: ubuntu-latest + steps: + - uses: dessant/lock-threads@v5 + with: + github-token: ${{ github.token }} + issue-inactive-days: 90 + pr-inactive-days: 90 diff --git a/.github/workflows/testing.yml b/.github/workflows/testing.yml new file mode 100644 index 00000000000..8793cfb82fe --- /dev/null +++ b/.github/workflows/testing.yml @@ -0,0 +1,110 @@ +name: GitHub Actions Linux Testing + +on: + push: + branches: + - master + - 'v1.*' + pull_request: + schedule: + - cron: '54 19 * * SUN' # weekly at a "random" time + +permissions: + contents: read + +jobs: + tests: + runs-on: ubuntu-latest + strategy: + matrix: + jre: [8, 11, 17, 21] + fail-fast: false # Should swap to true if we grow a large matrix + + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + java-version: ${{ matrix.jre }} + distribution: 'temurin' + + - name: Gradle cache + uses: actions/cache@v4 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} + restore-keys: | + ${{ runner.os }}-gradle- + - name: Maven cache + uses: actions/cache@v4 + with: + path: | + ~/.m2/repository + !~/.m2/repository/io/grpc + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml', 'build.gradle') }} + restore-keys: | + ${{ runner.os }}-maven- + - name: Protobuf cache + uses: actions/cache@v4 + with: + path: /tmp/protobuf-cache + key: ${{ runner.os }}-maven-${{ hashFiles('buildscripts/make_dependencies.sh') }} + + - name: Build + run: buildscripts/kokoro/unix.sh + - name: Post Failure Upload Test Reports to Artifacts + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: Test Reports (JRE ${{ matrix.jre }}) + path: | + ./*/build/reports/tests/** + ./*/*/build/reports/tests/** + retention-days: 14 + - name: Check for modified codegen + run: test -z "$(git status --porcelain)" || (git status && echo Error Working directory is not clean. Forget to commit generated files? && false) + + - name: Coveralls + if: matrix.jre == 8 # Upload once, instead of for each job in the matrix + env: + COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }} + run: ./gradlew :grpc-all:coveralls -PskipAndroid=true -x compileJava + - name: Codecov + uses: codecov/codecov-action@v4 + with: + token: ${{ secrets.CODECOV_TOKEN }} + + bazel: + runs-on: ubuntu-latest + strategy: + matrix: + bzlmod: [true, false] + env: + USE_BAZEL_VERSION: 8.7.0 + + steps: + - uses: actions/checkout@v4 + + - name: Check versions match in MODULE.bazel and repositories.bzl + run: | + diff -u <(sed -n '/GRPC_DEPS_START/,/GRPC_DEPS_END/ {/GRPC_DEPS_/! p}' MODULE.bazel) \ + <(sed -n '/GRPC_DEPS_START/,/GRPC_DEPS_END/ {/GRPC_DEPS_/! p}' repositories.bzl) + + - name: Bazel cache + uses: actions/cache@v4 + with: + path: | + ~/.cache/bazel/*/cache + ~/.cache/bazelisk/downloads + key: ${{ runner.os }}-bazel-${{ env.USE_BAZEL_VERSION }}-${{ hashFiles('WORKSPACE', 'repositories.bzl') }} + + - name: Run bazel build + run: bazelisk build //... --enable_bzlmod=${{ matrix.bzlmod }} --enable_workspace=${{ !matrix.bzlmod }} + + - name: Run bazel test + run: bazelisk test //... --enable_bzlmod=${{ matrix.bzlmod }} --enable_workspace=${{ !matrix.bzlmod }} + + - name: Run example bazel build + run: bazelisk build //... --enable_bzlmod=${{ matrix.bzlmod }} --enable_workspace=${{ !matrix.bzlmod }} + working-directory: ./examples diff --git a/.gitignore b/.gitignore index afa204c2ccb..b078d891adf 100644 --- a/.gitignore +++ b/.gitignore @@ -15,12 +15,14 @@ bazel-genfiles bazel-grpc-java bazel-out bazel-testlogs +MODULE.bazel.lock # IntelliJ IDEA .idea *.iml *.ipr *.iws +.ijwb # Eclipse .classpath @@ -29,6 +31,9 @@ bazel-testlogs .gitignore bin +# VsCode +.vscode + # OS X .DS_Store @@ -38,3 +43,6 @@ bin # ARM tests qemu-arm-static + +# Temporary output dir for artifacts +mvn-artifacts diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 4a37defdafb..00000000000 --- a/.travis.yml +++ /dev/null @@ -1,65 +0,0 @@ -language: java - -env: - global: - - GRADLE_OPTS=-Xmx512m - - LDFLAGS=-L/tmp/protobuf/lib - - CXXFLAGS=-I/tmp/protobuf/include - - LD_LIBRARY_PATH=/tmp/protobuf/lib - -before_install: - - rm ~/.m2/settings.xml || true # Avoid repository.apache.org, which has QPS limits and is useless - - mkdir -p $HOME/.gradle/caches && - ln -s /tmp/gradle-caches-modules-2 $HOME/.gradle/caches/modules-2 - - mkdir -p $HOME/.gradle && - ln -s /tmp/gradle-wrapper $HOME/.gradle/wrapper - - buildscripts/make_dependencies.sh # build protoc into /tmp/protobuf - - mkdir -p $HOME/.gradle - - echo "checkstyle.ignoreFailures=false" >> $HOME/.gradle/gradle.properties - - echo "failOnWarnings=true" >> $HOME/.gradle/gradle.properties - - echo "errorProne=true" >> $HOME/.gradle/gradle.properties - - echo "skipAndroid=true" >> $HOME/.gradle/gradle.properties - -install: - - ./gradlew assemble syncGeneratedSources publishToMavenLocal - - pushd examples && ./gradlew build && popd - - pushd examples && mvn verify && popd - - pushd examples/example-alts && ../gradlew build && popd - - pushd examples/example-hostname && ../gradlew build && popd - - pushd examples/example-hostname && mvn verify && popd - - pushd examples/example-tls && ../gradlew clean build && popd - - pushd examples/example-xds && ../gradlew build && popd - -before_script: - - test -z "$(git status --porcelain)" || (git status && echo Error Working directory is not clean. Forget to commit generated files? && false) - -script: - - ./gradlew check :grpc-all:jacocoTestReport - -after_success: - # Upload to coveralls once, instead of for each job in the matrix - - if [[ "$TRAVIS_JOB_NUMBER" == *.1 ]]; then ./gradlew :grpc-all:coveralls; fi - - bash <(curl -s https://codecov.io/bash) - -os: - - linux - -dist: xenial - -jdk: - - openjdk8 - - openjdk11 - -notifications: - email: false - -cache: - directories: - - /tmp/protobuf-cache - - /tmp/gradle-caches-modules-2 - - /tmp/gradle-wrapper - -before_cache: - # The lock changes based on folder name; normally $HOME/.gradle/caches/modules-2/modules-2.lock - - rm /tmp/gradle-caches-modules-2/gradle-caches-modules-2.lock - - find $HOME/.gradle/wrapper -not -name "*-all.zip" -and -not -name "*-bin.zip" -delete diff --git a/BUILD.bazel b/BUILD.bazel index 4bf8cdbc9b5..27a99fb62eb 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -12,6 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +load("@com_google_protobuf//bazel:java_proto_library.bzl", "java_proto_library") +load("@rules_java//java:defs.bzl", "java_library", "java_plugin") +load("@rules_jvm_external//:defs.bzl", "artifact") load(":java_grpc_library.bzl", "java_grpc_library") java_proto_library( @@ -32,10 +35,9 @@ java_library( "//api", "//protobuf", "//stub", - "//stub:javax_annotation", - "@com_google_code_findbugs_jsr305//jar", - "@com_google_guava_guava//jar", "@com_google_protobuf//:protobuf_java", + artifact("com.google.code.findbugs:jsr305"), + artifact("com.google.guava:guava"), ], ) @@ -46,8 +48,24 @@ java_library( "//api", "//protobuf-lite", "//stub", - "//stub:javax_annotation", - "@com_google_code_findbugs_jsr305//jar", - "@com_google_guava_guava//jar", + artifact("com.google.code.findbugs:jsr305"), + artifact("com.google.guava:guava"), + ], +) + +java_plugin( + name = "auto_value", + generates_api = 1, + processor_class = "com.google.auto.value.processor.AutoValueProcessor", + deps = [artifact("com.google.auto.value:auto-value")], +) + +java_library( + name = "auto_value_annotations", + exported_plugins = [":auto_value"], + neverlink = 1, + visibility = ["//:__subpackages__"], + exports = [ + artifact("com.google.auto.value:auto-value-annotations"), ], ) diff --git a/COMPILING.md b/COMPILING.md index c37d45bda4b..b7df1319beb 100644 --- a/COMPILING.md +++ b/COMPILING.md @@ -15,6 +15,7 @@ Some parts of grpc-java depend on Android. Since many Java developers don't have the Android SDK installed and don't need to run or modify the Android components, the build can skip it. To skip, create the file `/gradle.properties` and add `skipAndroid=true`. +Otherwise, create the file `/gradle.properties` and add `android.useAndroidX=true`. Then, to build, run: ``` @@ -43,11 +44,11 @@ This section is only necessary if you are making changes to the code generation. Most users only need to use `skipCodegen=true` as discussed above. ### Build Protobuf -The codegen plugin is C++ code and requires protobuf 3.12.0 or later. +The codegen plugin is C++ code and requires protobuf 22.5 or later. For Linux, Mac and MinGW: ``` -$ PROTOBUF_VERSION=3.12.0 +$ PROTOBUF_VERSION=22.5 $ curl -LO https://github.com/protocolbuffers/protobuf/releases/download/v$PROTOBUF_VERSION/protobuf-all-$PROTOBUF_VERSION.tar.gz $ tar xzf protobuf-all-$PROTOBUF_VERSION.tar.gz $ cd protobuf-$PROTOBUF_VERSION @@ -67,7 +68,7 @@ For Visual C++, please refer to the [Protobuf README](https://github.com/google/ for how to compile Protobuf. gRPC-java assumes a Release build. #### Mac -Some versions of Mac OS X (e.g., 10.10) doesn't have ``/usr/local`` in the +Some versions of Mac OS X (e.g., 10.10) don't have ``/usr/local`` in the default search paths for header files and libraries. It will fail the build of the codegen. To work around this, you will need to set environment variables: ``` @@ -80,16 +81,16 @@ When building on Windows and VC++, you need to specify project properties for Gradle to find protobuf: ``` .\gradlew publishToMavenLocal ^ - -PvcProtobufInclude=C:\path\to\protobuf-3.12.0\src ^ - -PvcProtobufLibs=C:\path\to\protobuf-3.12.0\vsprojects\Release ^ + -PvcProtobufInclude=C:\path\to\protobuf\src ^ + -PvcProtobufLibs=C:\path\to\protobuf\vsprojects\Release ^ -PtargetArch=x86_32 ``` Since specifying those properties every build is bothersome, you can instead create ``\gradle.properties`` with contents like: ``` -vcProtobufInclude=C:\\path\\to\\protobuf-3.12.0\\src -vcProtobufLibs=C:\\path\\to\\protobuf-3.12.0\\vsprojects\\Release +vcProtobufInclude=C:\\path\\to\\protobuf\\src +vcProtobufLibs=C:\\path\\to\\protobuf\\vsprojects\\Release targetArch=x86_32 ``` @@ -131,23 +132,21 @@ of Android SDK being installed is shown at `Android SDK Location` at the same pa The default is `$HOME/Library/Android/sdk` for Mac OS and `$HOME/Android/Sdk` for Linux. You can change this to a custom location. -### Install via Android SDK Manager -Go to [Android SDK](https://developer.android.com/studio) and navigate to __Command line tools only__. -Download and unzip the package for your build machine OS into somewhere easy to find -(e.g., `$HOME/Android/sdk`). This will be your Android SDK home directory. -The Android SDK Manager tool is in `tools/bin/sdkmanager`. - -Run the `sdkmanager` tool: -``` -$ tools/bin/sdkmanager --update -$ tools/bin/sdkmanager "platforms;android-28" -``` -This installs Android SDK 28 into `platforms/android-28` of your Android SDK home directory. -More usage of `sdkmanager` can be found at [Android User Guide](https://developer.android.com/studio/command-line/sdkmanager). - - -After Android SDK is installed, you need to set the `ANDROID_HOME` environment variable to your -Android SDK home directory: -``` -$ export ANDROID_HOME= +### Install via Command line tools only +Go to [Android SDK](https://developer.android.com/studio#command-tools) and +download the commandlinetools package for your build machine OS. Decide where +you want the Android SDK to be stored. `$HOME/Library/Android/sdk` is typical on +Mac OS and `$HOME/Android/Sdk` for Linux. + +```sh +export ANDROID_HOME=$HOME/Android/Sdk # Adjust to your liking +mkdir $HOME/Android +mkdir $ANDROID_HOME +mkdir $ANDROID_HOME/cmdline-tools +unzip -d $ANDROID_HOME/cmdline-tools DOWNLOADS/commandlinetools-*.zip +mv $ANDROID_HOME/cmdline-tools/cmdline-tools $ANDROID_HOME/cmdline-tools/latest +# Android SDK is now ready. Now accept licenses so the build can auto-download packages +$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --licenses + +# Add 'export ANDROID_HOME=$HOME/Android/Sdk' to your .bashrc or equivalent ``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ea98a3d5bea..646a7d986fd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,56 +30,36 @@ style configurations are commonly useful. For IntelliJ 14, copy the style to `~/.IdeaIC14/config/codestyles/`, start IntelliJ, go to File > Settings > Code Style, and set the Scheme to `GoogleStyle`. -## Maintaining clean commit history - -We have few conventions for keeping history clean and making code reviews easier -for reviewers: - -* First line of commit messages should be in format of - - `package-name: summary of change` - - where the summary finishes the sentence: `This commit improves gRPC to ____________.` - - for example: - - `core,netty,interop-testing: add capacitive duractance to turbo encabulators` - -* Every time you receive a feedback on your pull request, push changes that - address it as a separate one or multiple commits with a descriptive commit - message (try avoid using vauge `addressed pr feedback` type of messages). - - Project maintainers are obligated to squash those commits into one when - merging. - -## Running tests - -### Jetty ALPN setup for IntelliJ - -The tests in interop-testing project require jetty-alpn agent running in the background -otherwise they'll fail. Here are instructions on how to setup IntellJ IDEA to enable running -those tests in IDE: - -* Settings -> Build Tools -> Gradle -> Runner -> select Gradle Test Runner -* View -> Tool Windows -> Gradle -> Edit Run Configuration -> Defaults -> JUnit -> Before lauch -> + -> Run Gradle task, enter the task in the build.gradle that sets the javaagent. - -Step 1 must be taken, otherwise by the default JUnit Test Runner running a single test in IDE will trigger all the tests. - ## Guidelines for Pull Requests How to get your contributions merged smoothly and quickly. - Create **small PRs** that are narrowly focused on **addressing a single concern**. We often times receive PRs that are trying to fix several things at a time, but only one fix is considered acceptable, nothing gets merged and both author's & review's time is wasted. Create more PRs to address different concerns and everyone will be happy. -- For speculative changes, consider opening an issue and discussing it first. If you are suggesting a behavioral or API change, consider starting with a [gRFC proposal](https://github.com/grpc/proposal). - -- Provide a good **PR description** as a record of **what** change is being made and **why** it was made. Link to a github issue if it exists. - -- Don't fix code style and formatting unless you are already changing that line to address an issue. PRs with irrelevant changes won't be merged. If you do want to fix formatting or style, do that in a separate PR. - -- Unless your PR is trivial, you should expect there will be reviewer comments that you'll need to address before merging. We expect you to be reasonably responsive to those comments, otherwise the PR will be closed after 2-3 weeks of inactivity. - -- Maintain **clean commit history** and use **meaningful commit messages**. See [maintaining clean commit history](#maintaining-clean-commit-history) for details. - +- For speculative changes, consider opening an issue and discussing it to avoid + wasting time on an inappropriate approach. If you are suggesting a behavioral + or API change, consider starting with a [gRFC + proposal](https://github.com/grpc/proposal). + +- Follow [typical Git commit message](https://cbea.ms/git-commit/#seven-rules) + structure. Have a good **commit description** as a record of **what** and + **why** the change is being made. Link to a GitHub issue if it exists. The + commit description makes a good PR description and is auto-copied by GitHub if + you have a single commit when creating the PR. + + If your change is mostly for a single module (e.g., other module changes are + trivial), prefix your commit summary with the module name changed. Instead of + "Add HTTP/2 faster-than-light support to gRPC Netty" it is more terse as + "netty: Add faster-than-light support". + +- Don't fix code style and formatting unless you are already changing that line + to address an issue. If you do want to fix formatting or style, do that in a + separate PR. + +- Unless your PR is trivial, you should expect there will be reviewer comments + that you'll need to address before merging. Address comments with additional + commits so the reviewer can review just the changes; do not squash reviewed + commits unless the reviewer agrees. PRs are squashed when merging. + - Keep your PR up to date with upstream/master (if there are merge conflicts, we can't really merge your change). - **All tests need to be passing** before your change can be merged. We recommend you **run tests locally** before creating your PR to catch breakages early on. Also, `./gradlew build` (`gradlew build` on Windows) **must not introduce any new warnings**. diff --git a/MAINTAINERS.md b/MAINTAINERS.md index 5ff2c5157b5..5048c7c5aca 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -8,22 +8,28 @@ See [CONTRIBUTING.md](https://github.com/grpc/grpc-community/blob/master/CONTRIB for general contribution guidelines. ## Maintainers (in alphabetical order) -- [creamsoup](https://github.com/creamsoup), Google LLC -- [dapengzhang0](https://github.com/dapengzhang0), Google LLC - [ejona86](https://github.com/ejona86), Google LLC -- [ericgribkoff](https://github.com/ericgribkoff), Google LLC -- [jiangtaoli2016](https://github.com/jiangtaoli2016), Google LLC +- [jdcormie](https://github.com/jdcormie), Google LLC +- [kannanjgithub](https://github.com/kannanjgithub), Google LLC - [ran-su](https://github.com/ran-su), Google LLC -- [sanjaypujare](https://github.com/sanjaypujare), Google LLC - [sergiitk](https://github.com/sergiitk), Google LLC -- [srini100](https://github.com/srini100), Google LLC -- [voidzcy](https://github.com/voidzcy), Google LLC +- [temawi](https://github.com/temawi), Google LLC +- [YifeiZhuang](https://github.com/YifeiZhuang), Google LLC - [zhangkun83](https://github.com/zhangkun83), Google LLC ## Emeritus Maintainers (in alphabetical order) -- [carl-mastrangelo](https://github.com/carl-mastrangelo), Google LLC -- [jtattermusch](https://github.com/jtattermusch), Google LLC -- [louiscryan](https://github.com/louiscryan), Google LLC -- [nicolasnoble](https://github.com/nicolasnoble), Google LLC -- [nmittler](https://github.com/nmittler), Google LLC -- [zpencer](https://github.com/zpencer), Google LLC +- [carl-mastrangelo](https://github.com/carl-mastrangelo) +- [creamsoup](https://github.com/creamsoup) +- [dapengzhang0](https://github.com/dapengzhang0) +- [ericgribkoff](https://github.com/ericgribkoff) +- [jiangtaoli2016](https://github.com/jiangtaoli2016) +- [jtattermusch](https://github.com/jtattermusch) +- [larry-safran](https://github.com/larry-safran) +- [louiscryan](https://github.com/louiscryan) +- [markb74](https://github.com/markb74) +- [nicolasnoble](https://github.com/nicolasnoble) +- [nmittler](https://github.com/nmittler) +- [sanjaypujare](https://github.com/sanjaypujare) +- [srini100](https://github.com/srini100) +- [voidzcy](https://github.com/voidzcy) +- [zpencer](https://github.com/zpencer) diff --git a/MODULE.bazel b/MODULE.bazel new file mode 100644 index 00000000000..50fd1f95d34 --- /dev/null +++ b/MODULE.bazel @@ -0,0 +1,160 @@ +module( + name = "grpc-java", + version = "1.82.0-SNAPSHOT", # CURRENT_GRPC_VERSION + repo_name = "io_grpc_grpc_java", +) + +# GRPC_DEPS_START +IO_GRPC_GRPC_JAVA_ARTIFACTS = [ + "com.google.android:annotations:4.1.1.4", + "com.google.api.grpc:proto-google-common-protos:2.64.1", + "com.google.auth:google-auth-library-credentials:1.42.1", + "com.google.auth:google-auth-library-oauth2-http:1.42.1", + "com.google.auto.value:auto-value-annotations:1.11.0", + "com.google.auto.value:auto-value:1.11.0", + "com.google.code.findbugs:jsr305:3.0.2", + "com.google.code.gson:gson:2.13.2", + "com.google.errorprone:error_prone_annotations:2.48.0", + "com.google.guava:failureaccess:1.0.1", + "com.google.guava:guava:33.5.0-android", + "com.google.re2j:re2j:1.8", + "com.google.s2a.proto.v2:s2a-proto:0.1.3", + "com.google.truth:truth:1.4.5", + "com.squareup.okhttp:okhttp:2.7.5", + "com.squareup.okio:okio:2.10.0", # 3.0+ needs swapping to -jvm; need work to avoid flag-day + "io.netty:netty-buffer:4.1.133.Final", + "io.netty:netty-codec-http2:4.1.133.Final", + "io.netty:netty-codec-http:4.1.133.Final", + "io.netty:netty-codec-socks:4.1.133.Final", + "io.netty:netty-codec:4.1.133.Final", + "io.netty:netty-common:4.1.133.Final", + "io.netty:netty-handler-proxy:4.1.133.Final", + "io.netty:netty-handler:4.1.133.Final", + "io.netty:netty-resolver:4.1.133.Final", + "io.netty:netty-tcnative-boringssl-static:2.0.75.Final", + "io.netty:netty-tcnative-classes:2.0.75.Final", + "io.netty:netty-transport-native-epoll:jar:linux-x86_64:4.1.133.Final", + "io.netty:netty-transport-native-unix-common:4.1.133.Final", + "io.netty:netty-transport:4.1.133.Final", + "io.opencensus:opencensus-api:0.31.0", + "io.opencensus:opencensus-contrib-grpc-metrics:0.31.0", + "io.perfmark:perfmark-api:0.27.0", + "junit:junit:4.13.2", + "org.mockito:mockito-core:4.4.0", + "org.checkerframework:checker-qual:3.49.5", + "org.codehaus.mojo:animal-sniffer-annotations:1.27", +] +# GRPC_DEPS_END + +bazel_dep(name = "abseil-cpp", version = "20250512.1") +bazel_dep(name = "bazel_jar_jar", version = "0.1.11.bcr.1") +bazel_dep(name = "bazel_skylib", version = "1.7.1") +bazel_dep(name = "googleapis", version = "0.0.0-20240326-1c8d509c5", repo_name = "com_google_googleapis") +bazel_dep(name = "grpc-proto", version = "0.0.0-20240627-ec30f58.bcr.1", repo_name = "io_grpc_grpc_proto") +bazel_dep(name = "protobuf", version = "33.4", repo_name = "com_google_protobuf") +bazel_dep(name = "rules_cc", version = "0.0.9") +bazel_dep(name = "rules_java", version = "9.1.0") +bazel_dep(name = "rules_jvm_external", version = "6.0") + +maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") +maven.install( + artifacts = IO_GRPC_GRPC_JAVA_ARTIFACTS, + repositories = [ + "https://repo.maven.apache.org/maven2/", + ], + strict_visibility = True, +) +use_repo(maven, "maven") + +maven.override( + coordinates = "com.google.protobuf:protobuf-java", + target = "@com_google_protobuf//:protobuf_java", +) +maven.override( + coordinates = "com.google.protobuf:protobuf-java-util", + target = "@com_google_protobuf//:protobuf_java_util", +) +maven.override( + coordinates = "com.google.protobuf:protobuf-javalite", + target = "@com_google_protobuf//:protobuf_javalite", +) +maven.override( + coordinates = "io.grpc:grpc-alts", + target = "@io_grpc_grpc_java//alts", +) +maven.override( + coordinates = "io.grpc:grpc-api", + target = "@io_grpc_grpc_java//api", +) +maven.override( + coordinates = "io.grpc:grpc-auth", + target = "@io_grpc_grpc_java//auth", +) +maven.override( + coordinates = "io.grpc:grpc-census", + target = "@io_grpc_grpc_java//census", +) +maven.override( + coordinates = "io.grpc:grpc-context", + target = "@io_grpc_grpc_java//context", +) +maven.override( + coordinates = "io.grpc:grpc-core", + target = "@io_grpc_grpc_java//core:core_maven", +) +maven.override( + coordinates = "io.grpc:grpc-googleapis", + target = "@io_grpc_grpc_java//googleapis", +) +maven.override( + coordinates = "io.grpc:grpc-grpclb", + target = "@io_grpc_grpc_java//grpclb", +) +maven.override( + coordinates = "io.grpc:grpc-inprocess", + target = "@io_grpc_grpc_java//inprocess", +) +maven.override( + coordinates = "io.grpc:grpc-netty", + target = "@io_grpc_grpc_java//netty", +) +maven.override( + coordinates = "io.grpc:grpc-netty-shaded", + target = "@io_grpc_grpc_java//netty:shaded_maven", +) +maven.override( + coordinates = "io.grpc:grpc-okhttp", + target = "@io_grpc_grpc_java//okhttp", +) +maven.override( + coordinates = "io.grpc:grpc-protobuf", + target = "@io_grpc_grpc_java//protobuf", +) +maven.override( + coordinates = "io.grpc:grpc-protobuf-lite", + target = "@io_grpc_grpc_java//protobuf-lite", +) +maven.override( + coordinates = "io.grpc:grpc-rls", + target = "@io_grpc_grpc_java//rls", +) +maven.override( + coordinates = "io.grpc:grpc-services", + target = "@io_grpc_grpc_java//services:services_maven", +) +maven.override( + coordinates = "io.grpc:grpc-stub", + target = "@io_grpc_grpc_java//stub", +) +maven.override( + coordinates = "io.grpc:grpc-testing", + target = "@io_grpc_grpc_java//testing", +) +maven.override( + coordinates = "io.grpc:grpc-xds", + target = "@io_grpc_grpc_java//xds:xds_maven", +) +maven.override( + coordinates = "io.grpc:grpc-util", + target = "@io_grpc_grpc_java//util", +) diff --git a/README.md b/README.md index db22e97c7dc..8e6620c927e 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,6 @@ gRPC-Java - An RPC library and framework ======================================== -gRPC-Java works with JDK 7. gRPC-Java clients are supported on Android API -levels 16 and up (Jelly Bean and later). Deploying gRPC servers on an Android -device is not supported. - -TLS usage typically requires using Java 8, or Play Services Dynamic Security -Provider on Android. Please see the [Security Readme](SECURITY.md). - @@ -20,10 +13,30 @@ Provider on Android. Please see the [Security Readme](SECURITY.md).
Homepage:
[![Join the chat at https://gitter.im/grpc/grpc](https://badges.gitter.im/grpc/grpc.svg)](https://gitter.im/grpc/grpc?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![Build Status](https://travis-ci.org/grpc/grpc-java.svg?branch=master)](https://travis-ci.org/grpc/grpc-java) +[![GitHub Actions Linux Testing](https://github.com/grpc/grpc-java/actions/workflows/testing.yml/badge.svg?branch=master)](https://github.com/grpc/grpc-java/actions/workflows/testing.yml?branch=master) [![Line Coverage Status](https://coveralls.io/repos/grpc/grpc-java/badge.svg?branch=master&service=github)](https://coveralls.io/github/grpc/grpc-java?branch=master) [![Branch-adjusted Line Coverage Status](https://codecov.io/gh/grpc/grpc-java/branch/master/graph/badge.svg)](https://codecov.io/gh/grpc/grpc-java) +Supported Platforms +------------------- + +gRPC-Java supports Java 8 and later. Android minSdkVersion 23 (Marshmallow) and +later are supported with [Java 8 language desugaring][android-java-8]. + +TLS usage on Android typically requires Play Services Dynamic Security Provider. +Please see the [Security Readme](SECURITY.md). + +Older Java versions are not directly supported, but a branch remains available +for fixes and releases. See [gRFC P5 JDK Version Support +Policy][P5-jdk-version-support]. + +Java version | gRPC Branch +------------ | ----------- +7 | 1.41.x + +[android-java-8]: https://developer.android.com/studio/write/java8-support#supported_features +[P5-jdk-version-support]: https://github.com/grpc/proposal/blob/master/P5-jdk-version-support.md#proposal + Getting Started --------------- @@ -31,8 +44,8 @@ For a guided tour, take a look at the [quick start guide](https://grpc.io/docs/languages/java/quickstart) or the more explanatory [gRPC basics](https://grpc.io/docs/languages/java/basics). -The [examples](https://github.com/grpc/grpc-java/tree/v1.36.0/examples) and the -[Android example](https://github.com/grpc/grpc-java/tree/v1.36.0/examples/android) +The [examples](https://github.com/grpc/grpc-java/tree/v1.81.0/examples) and the +[Android example](https://github.com/grpc/grpc-java/tree/v1.81.0/examples/android) are standalone projects that showcase the usage of gRPC. Download @@ -43,48 +56,45 @@ Download [the JARs][]. Or for Maven with non-Android, add to your `pom.xml`: io.grpc grpc-netty-shaded - 1.36.0 + 1.81.0 + runtime io.grpc grpc-protobuf - 1.36.0 + 1.81.0 io.grpc grpc-stub - 1.36.0 - - - org.apache.tomcat - annotations-api - 6.0.53 - provided + 1.81.0 ``` Or for Gradle with non-Android, add to your dependencies: ```gradle -implementation 'io.grpc:grpc-netty-shaded:1.36.0' -implementation 'io.grpc:grpc-protobuf:1.36.0' -implementation 'io.grpc:grpc-stub:1.36.0' -compileOnly 'org.apache.tomcat:annotations-api:6.0.53' // necessary for Java 9+ +runtimeOnly 'io.grpc:grpc-netty-shaded:1.81.0' +implementation 'io.grpc:grpc-protobuf:1.81.0' +implementation 'io.grpc:grpc-stub:1.81.0' ``` For Android client, use `grpc-okhttp` instead of `grpc-netty-shaded` and `grpc-protobuf-lite` instead of `grpc-protobuf`: ```gradle -implementation 'io.grpc:grpc-okhttp:1.36.0' -implementation 'io.grpc:grpc-protobuf-lite:1.36.0' -implementation 'io.grpc:grpc-stub:1.36.0' -compileOnly 'org.apache.tomcat:annotations-api:6.0.53' // necessary for Java 9+ +implementation 'io.grpc:grpc-okhttp:1.81.0' +implementation 'io.grpc:grpc-protobuf-lite:1.81.0' +implementation 'io.grpc:grpc-stub:1.81.0' ``` +For [Bazel](https://bazel.build), you can either +[use Maven](https://github.com/bazelbuild/rules_jvm_external) +(with the GAVs from above), or use `@io_grpc_grpc_java//api` et al (see below). + [the JARs]: -https://search.maven.org/search?q=g:io.grpc%20AND%20v:1.36.0 +https://search.maven.org/search?q=g:io.grpc%20AND%20v:1.81.0 Development snapshots are available in [Sonatypes's snapshot -repository](https://oss.sonatype.org/content/repositories/snapshots/). +repository](https://central.sonatype.com/repository/maven-snapshots/). Generated Code -------------- @@ -102,7 +112,7 @@ For protobuf-based codegen integrated with the Maven build system, you can use kr.motd.maven os-maven-plugin - 1.6.2 + 1.7.1 @@ -111,9 +121,9 @@ For protobuf-based codegen integrated with the Maven build system, you can use protobuf-maven-plugin 0.6.1 - com.google.protobuf:protoc:3.12.0:exe:${os.detected.classifier} + com.google.protobuf:protoc:3.25.8:exe:${os.detected.classifier} grpc-java - io.grpc:protoc-gen-grpc-java:1.36.0:exe:${os.detected.classifier} + io.grpc:protoc-gen-grpc-java:1.81.0:exe:${os.detected.classifier} @@ -134,16 +144,16 @@ For non-Android protobuf-based codegen integrated with the Gradle build system, you can use [protobuf-gradle-plugin][]: ```gradle plugins { - id 'com.google.protobuf' version '0.8.15' + id 'com.google.protobuf' version '0.9.5' } protobuf { protoc { - artifact = "com.google.protobuf:protoc:3.12.0" + artifact = "com.google.protobuf:protoc:3.25.8" } plugins { grpc { - artifact = 'io.grpc:protoc-gen-grpc-java:1.36.0' + artifact = 'io.grpc:protoc-gen-grpc-java:1.81.0' } } generateProtoTasks { @@ -160,23 +170,23 @@ The prebuilt protoc-gen-grpc-java binary uses glibc on Linux. If you are compiling on Alpine Linux, you may want to use the [Alpine grpc-java package][] which uses musl instead. -[Alpine grpc-java package]: https://pkgs.alpinelinux.org/package/edge/testing/x86_64/grpc-java +[Alpine grpc-java package]: https://pkgs.alpinelinux.org/package/edge/community/x86_64/grpc-java For Android protobuf-based codegen integrated with the Gradle build system, also use protobuf-gradle-plugin but specify the 'lite' options: ```gradle plugins { - id 'com.google.protobuf' version '0.8.15' + id 'com.google.protobuf' version '0.9.5' } protobuf { protoc { - artifact = "com.google.protobuf:protoc:3.12.0" + artifact = "com.google.protobuf:protoc:3.25.8" } plugins { grpc { - artifact = 'io.grpc:protoc-gen-grpc-java:1.36.0' + artifact = 'io.grpc:protoc-gen-grpc-java:1.81.0' } } generateProtoTasks { @@ -193,6 +203,11 @@ protobuf { ``` +For [Bazel](https://bazel.build), use the [`proto_library`](https://github.com/bazelbuild/rules_proto) +and the [`java_proto_library`](https://bazel.build/reference/be/java#java_proto_library) (no `load()` required) +and `load("@io_grpc_grpc_java//:java_grpc_library.bzl", "java_grpc_library")` (from this project), as in +[this example `BUILD.bazel`](https://github.com/grpc/grpc-java/blob/master/examples/BUILD.bazel). + API Stability ------------- @@ -242,12 +257,18 @@ wire. The interfaces to it are abstract just enough to allow plugging in of different implementations. Note the transport layer API is considered internal to gRPC and has weaker API guarantees than the core API under package `io.grpc`. -gRPC comes with three Transport implementations: +gRPC comes with multiple Transport implementations: -1. The Netty-based transport is the main transport implementation based on - [Netty](https://netty.io). It is for both the client and the server. -2. The OkHttp-based transport is a lightweight transport based on - [OkHttp](https://square.github.io/okhttp/). It is mainly for use on Android - and is for client only. +1. The Netty-based HTTP/2 transport is the main transport implementation based + on [Netty](https://netty.io). It is not officially supported on Android. + There is a "grpc-netty-shaded" version of this transport. It is generally + preferred over using the Netty-based transport directly as it requires less + dependency management and is easier to upgrade within many applications. +2. The OkHttp-based HTTP/2 transport is a lightweight transport based on + [Okio](https://square.github.io/okio/) and forked low-level parts of + [OkHttp](https://square.github.io/okhttp/). It is mainly for use on Android. 3. The in-process transport is for when a server is in the same process as the - client. It is useful for testing, while also being safe for production use. + client. It is used frequently for testing, while also being safe for + production use. +4. The Binder transport is for Android cross-process communication on a single + device. diff --git a/RELEASING.md b/RELEASING.md index a0852f4216d..c57829b8c25 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -10,45 +10,26 @@ We deploy GRPC to Maven Central under the following systems: Other systems may also work, but we haven't verified them. -Prerequisites -------------- - -### Set Up OSSRH Account - -If you haven't deployed artifacts to Maven Central before, you need to setup -your OSSRH (OSS Repository Hosting) account. -- Follow the instructions on [this - page](https://central.sonatype.org/pages/ossrh-guide.html) to set up an - account with OSSRH. - - You only need to create the account, not set up a new project - - Contact a gRPC maintainer to add your account after you have created it. - Common Variables ---------------- Many of the following commands expect release-specific variables to be set. Set them before continuing, and set them again when resuming. ```bash -$ MAJOR=1 MINOR=7 PATCH=0 # Set appropriately for new release -$ VERSION_FILES=( +MAJOR=1 MINOR=7 PATCH=0 # Set appropriately for new release +VERSION_FILES=( + MODULE.bazel build.gradle core/src/main/java/io/grpc/internal/GrpcUtil.java + examples/MODULE.bazel examples/build.gradle examples/pom.xml examples/android/clientcache/app/build.gradle examples/android/helloworld/app/build.gradle examples/android/routeguide/app/build.gradle examples/android/strictmode/app/build.gradle - examples/example-alts/build.gradle - examples/example-gauth/build.gradle - examples/example-gauth/pom.xml - examples/example-jwt-auth/build.gradle - examples/example-jwt-auth/pom.xml - examples/example-hostname/build.gradle - examples/example-hostname/pom.xml - examples/example-tls/build.gradle - examples/example-tls/pom.xml - examples/example-xds/build.gradle + examples/example-*/build.gradle + examples/example-*/pom.xml ) ``` @@ -61,35 +42,34 @@ convention of `v..x`, while the tags include the patch version `v..`. For example, the same branch `v1.7.x` would be used to create all `v1.7` tags (e.g. `v1.7.0`, `v1.7.1`). -1. For `master`, change root build files to the next minor snapshot (e.g. +1. Review the issues in the current release [milestone](https://github.com/grpc/grpc-java/milestones) + for issues that won't make the cut. Check if any of them can be + closed. Be aware of the issues with the [TODO:release blocker][] label. + Consider reaching out to the assignee for the status update. +2. For `master`, change root build files to the next minor snapshot (e.g. ``1.8.0-SNAPSHOT``). ```bash - $ git checkout -b bump-version master + git checkout -b bump-version master # Change version to next minor (and keep -SNAPSHOT) - $ sed -i 's/[0-9]\+\.[0-9]\+\.[0-9]\+\(.*CURRENT_GRPC_VERSION\)/'$MAJOR.$((MINOR+1)).0'\1/' \ + sed -i 's/[0-9]\+\.[0-9]\+\.[0-9]\+\(.*CURRENT_GRPC_VERSION\)/'$MAJOR.$((MINOR+1)).0'\1/' \ "${VERSION_FILES[@]}" - $ sed -i s/$MAJOR.$MINOR.$PATCH/$MAJOR.$((MINOR+1)).0/ \ + sed -i s/$MAJOR.$MINOR.$PATCH/$MAJOR.$((MINOR+1)).0/ \ compiler/src/test{,Lite}/golden/Test{,Deprecated}Service.java.txt - $ ./gradlew build - $ git commit -a -m "Start $MAJOR.$((MINOR+1)).0 development cycle" + ./gradlew build + git commit -a -m "Start $MAJOR.$((MINOR+1)).0 development cycle" ``` -2. Go through PR review and submit. -3. Create the release branch starting just before your commit and push it to GitHub: +3. Go through PR review and submit. +4. Create the release branch starting just before your commit and push it to GitHub: ```bash - $ git fetch upstream - $ git checkout -b v$MAJOR.$MINOR.x \ - $(git log --pretty=format:%H --grep "^Start $MAJOR.$((MINOR+1)).0 development cycle$" upstream/master)^ - $ git push upstream v$MAJOR.$MINOR.x + git fetch upstream + git checkout -b v$MAJOR.$MINOR.x \ + $(git log --pretty=format:%H --grep "^Start $MAJOR.$((MINOR+1)).0 development cycle" upstream/master)^ + git push upstream v$MAJOR.$MINOR.x ``` -4. Ask a project admin to go to [Travis CI settings](https://travis-ci.org/grpc/grpc-java/settings) - and add a _Cron Job_: - * Branch: `v$MAJOR.$MINOR.x` - * Interval: `weekly` - * Options: `Do not run if there has been a build in the last 24h` - * Click _Add_ button -5. Continue with Google-internal steps at go/grpc/java/releasing. +5. Continue with Google-internal steps at go/grpc-java/releasing, but stop + before `Auto releasing using kokoro`. 6. Create a milestone for the next release. 7. Move items out of the release milestone that didn't make the cut. Issues that may be backported should stay in the release milestone. Treat issues with the @@ -97,144 +77,176 @@ would be used to create all `v1.7` tags (e.g. `v1.7.0`, `v1.7.1`). 8. Begin compiling release notes. This produces a starting point: ```bash - $ echo "## gRPC Java $MAJOR.$MINOR.0 Release Notes" && echo && \ - git shortlog "$(git merge-base upstream/v$MAJOR.$((MINOR-1)).x upstream/v$MAJOR.$MINOR.x)"..upstream/v$MAJOR.$MINOR.x | cat && \ + echo "## gRPC Java $MAJOR.$MINOR.0 Release Notes" && echo && \ + git shortlog -e --format='%s (%h)' "$(git merge-base upstream/v$MAJOR.$((MINOR-1)).x upstream/v$MAJOR.$MINOR.x)"..upstream/v$MAJOR.$MINOR.x | cat && \ echo && echo && echo "Backported commits in previous release:" && \ - git cherry -v v$MAJOR.$((MINOR-1)).0 upstream/v$MAJOR.$MINOR.x | grep ^- + git log --oneline "$(git merge-base v$MAJOR.$((MINOR-1)).0 upstream/v$MAJOR.$MINOR.x)"..v$MAJOR.$((MINOR-1)).0^ ``` +[TODO:release blocker]: https://github.com/grpc/grpc-java/issues?q=label%3A%22TODO%3Arelease+blocker%22 +[TODO:backport]: https://github.com/grpc/grpc-java/issues?q=label%3ATODO%3Abackport + Tagging the Release ------------------- 1. Verify there are no open issues in the release milestone. Open issues should - either be deferred or resolved and the fix backported. -2. For vMajor.Minor.x branch, change `README.md` to refer to the next release + either be deferred or resolved and the fix backported. Verify there are no + [TODO:release blocker][] nor [TODO:backport][] issues (open or closed), or + that they are tracking an issue for a different branch. +2. Ensure that the Google-internal steps + at go/grpc-java/releasing#before-tagging-a-release are completed. +3. For vMajor.Minor.x branch, change `README.md` to refer to the next release version. _Also_ update the version numbers for protoc if the protobuf library version was updated since the last release. ```bash - $ git checkout v$MAJOR.$MINOR.x - $ git pull upstream v$MAJOR.$MINOR.x - $ git checkout -b release - # Bump documented versions. Don't forget protobuf version - $ ${EDITOR:-nano -w} README.md - $ ${EDITOR:-nano -w} documentation/android-channel-builder.md - $ ${EDITOR:-nano -w} cronet/README.md - $ git commit -a -m "Update README etc to reference $MAJOR.$MINOR.$PATCH" + git checkout v$MAJOR.$MINOR.x + git pull upstream v$MAJOR.$MINOR.x + git checkout -b release-v$MAJOR.$MINOR.$PATCH + + # Bump documented gRPC versions. + # Also update protoc version to match protobuf version in gradle/libs.versions.toml. + ${EDITOR:-nano -w} README.md + + git commit -a -m "Update README etc to reference $MAJOR.$MINOR.$PATCH" ``` -3. Change root build files to remove "-SNAPSHOT" for the next release version +4. Change root build files to remove "-SNAPSHOT" for the next release version (e.g. `0.7.0`). Commit the result and make a tag: ```bash # Change version to remove -SNAPSHOT - $ sed -i 's/-SNAPSHOT\(.*CURRENT_GRPC_VERSION\)/\1/' "${VERSION_FILES[@]}" - $ sed -i s/-SNAPSHOT// compiler/src/test{,Lite}/golden/Test{,Deprecated}Service.java.txt - $ ./gradlew build - $ git commit -a -m "Bump version to $MAJOR.$MINOR.$PATCH" - $ git tag -a v$MAJOR.$MINOR.$PATCH -m "Version $MAJOR.$MINOR.$PATCH" + sed -i 's/-SNAPSHOT\(.*CURRENT_GRPC_VERSION\)/\1/' "${VERSION_FILES[@]}" + sed -i s/-SNAPSHOT// compiler/src/test{,Lite}/golden/Test{,Deprecated}Service.java.txt + ./gradlew build + git commit -a -m "Bump version to $MAJOR.$MINOR.$PATCH" + git tag -a v$MAJOR.$MINOR.$PATCH -m "Version $MAJOR.$MINOR.$PATCH" ``` -4. Change root build files to the next snapshot version (e.g. `0.7.1-SNAPSHOT`). +5. Change root build files to the next snapshot version (e.g. `0.7.1-SNAPSHOT`). Commit the result: ```bash # Change version to next patch and add -SNAPSHOT - $ sed -i 's/[0-9]\+\.[0-9]\+\.[0-9]\+\(.*CURRENT_GRPC_VERSION\)/'$MAJOR.$MINOR.$((PATCH+1))-SNAPSHOT'\1/' \ + sed -i 's/[0-9]\+\.[0-9]\+\.[0-9]\+\(.*CURRENT_GRPC_VERSION\)/'$MAJOR.$MINOR.$((PATCH+1))-SNAPSHOT'\1/' \ "${VERSION_FILES[@]}" - $ sed -i s/$MAJOR.$MINOR.$PATCH/$MAJOR.$MINOR.$((PATCH+1))-SNAPSHOT/ \ + sed -i s/$MAJOR.$MINOR.$PATCH/$MAJOR.$MINOR.$((PATCH+1))-SNAPSHOT/ \ compiler/src/test{,Lite}/golden/Test{,Deprecated}Service.java.txt - $ ./gradlew build - $ git commit -a -m "Bump version to $MAJOR.$MINOR.$((PATCH+1))-SNAPSHOT" + ./gradlew build + git commit -a -m "Bump version to $MAJOR.$MINOR.$((PATCH+1))-SNAPSHOT" + git push -u origin release-v$MAJOR.$MINOR.$PATCH ``` -5. Go through PR review and push the release tag and updated release branch to - GitHub: + Raise a PR and set the base branch of the PR to v$MAJOR.$MINOR.x of the upstream grpc-java repo. +6. Go through PR review and push the release tag and updated release branch to + GitHub (DO NOT click the merge button on the GitHub page): ```bash - $ git checkout v$MAJOR.$MINOR.x - $ git merge --ff-only release - $ git push upstream v$MAJOR.$MINOR.x - $ git push upstream v$MAJOR.$MINOR.$PATCH + git checkout v$MAJOR.$MINOR.x + git merge --ff-only release-v$MAJOR.$MINOR.$PATCH + git push upstream v$MAJOR.$MINOR.x + git push upstream v$MAJOR.$MINOR.$PATCH ``` -6. Close the release milestone. - -Build Artifacts ---------------- - -Trigger build as described in "Auto releasing using kokoro" at -go/grpc/java/releasing. - -It runs three jobs on Kokoro, one on each platform. See their scripts: -`linux_artifacts.sh`, `windows.bat`, and `unix.sh` (called directly for OS X; -called within the Docker environment on Linux). The mvn-artifacts/ outputs of -each script is combined into a single folder and then processed by -`upload_artifacts.sh`, which signs the files and uploads to Sonatype. - -Releasing on Maven Central --------------------------- - -Once all of the artifacts have been pushed to the staging repository, the -repository should have been closed by `upload_artifacts.sh`. Closing triggers -several sanity checks on the repository. If this completes successfully, the -repository can then be `released`, which will begin the process of pushing the -new artifacts to Maven Central (the staging repository will be destroyed in the -process). You can see the complete process for releasing to Maven Central on the -[OSSRH site](https://central.sonatype.org/pages/releasing-the-deployment.html). - -Build interop container image ------------------------------ - -We have containers for each release to detect compatibility regressions with old -releases. Generate one for the new release by following the -[GCR image generation instructions](https://github.com/grpc/grpc/blob/master/tools/interop_matrix/README.md#step-by-step-instructions-for-adding-a-gcr-image-for-a-new-release-for-compatibility-test). - -Update README.md ----------------- -After waiting ~1 day and verifying that the release appears on [Maven -Central](https://search.maven.org/search?q=g:io.grpc), cherry-pick the commit -that updated the README into the master branch and go through review process. - -``` -$ git checkout -b bump-readme master -$ git cherry-pick v$MAJOR.$MINOR.$PATCH^ -``` - -Update version referenced by tutorials --------------------------------------- - -Update the `grpc_java_release_tag` in -[config.yaml](https://github.com/grpc/grpc.io/blob/master/config.yaml) -of the grpc.io repository. - -Notify the Community --------------------- -Finally, document and publicize the release. - -1. Add [Release Notes](https://github.com/grpc/grpc-java/releases) for the new tag. - The description should include any major fixes or features since the last release. - You may choose to add links to bugs, PRs, or commits if appropriate. -2. Post a release announcement to [grpc-io](https://groups.google.com/forum/#!forum/grpc-io) - (`grpc-io@googlegroups.com`). The title should be something that clearly identifies - the release (e.g.`GRPC-Java Released`). - 1. Check if JCenter has picked up the new release (https://jcenter.bintray.com/io/grpc/) - and include its availability in the release announcement email. JCenter should mirror - everything on Maven Central, but users have reported delays. - -Update Hosted Javadoc +7. Close the release milestone. + +8. Trigger build as described in "Auto releasing using kokoro" at + go/grpc-java/releasing. + + It runs three jobs on Kokoro, one on each platform. See their scripts: + `linux_artifacts.sh`, `windows.bat`, and `macos.sh`. The mvn-artifacts/ + outputs of each script is combined into a single folder and then processed + by `upload_artifacts.sh`, which signs the files and uploads to Sonatype. + +9. Once all of the artifacts have been pushed to the staging repository, the + repository should have been closed by `upload_artifacts.sh`. Closing triggers + several sanity checks on the repository. If this completes successfully, the + repository can then be `released`, which will begin the process of pushing + the new artifacts to Maven Central (the staging repository will be destroyed + in the process). You can see the complete process for releasing to Maven + Central on the [OSSRH site](https://central.sonatype.org/publish/publish-portal-ossrh-staging-api/#deploying). + +10. We have containers for each release to detect compatibility regressions with + old releases. Generate one for the new release by following the [GCR image + generation instructions][gcr-image]. Summary: + ```bash + # If you haven't previously configured docker: + gcloud auth configure-docker us-docker.pkg.dev + + # In main grpc repo, add the new version to matrix + ${EDITOR:-nano -w} tools/interop_matrix/client_matrix.py + tools/interop_matrix/create_matrix_images.py --git_checkout --release=v$MAJOR.$MINOR.$PATCH \ + --upload_images --language java + docker pull us-docker.pkg.dev/grpc-testing/testing-images-public/grpc_interop_java:v$MAJOR.$MINOR.$PATCH + docker_image=us-docker.pkg.dev/grpc-testing/testing-images-public/grpc_interop_java:v$MAJOR.$MINOR.$PATCH \ + tools/interop_matrix/testcases/java__master + + # Commit the changes + git commit --all -m "[interop] Add grpc-java $MAJOR.$MINOR.$PATCH to client_matrix.py" + + # Create a PR with the `release notes: no` label and run ad-hoc test against your PR + ``` +[gcr-image]: https://github.com/grpc/grpc/blob/master/tools/interop_matrix/README.md#step-by-step-instructions-for-adding-a-gcr-image-for-a-new-release-for-compatibility-test + +11. Update gh-pages with the new Javadoc. Generally the file is on repo1 + 15 minutes after publishing: + + ```bash + git checkout gh-pages + git pull --ff-only upstream gh-pages + rm -r javadoc/ + wget -O grpc-all-javadoc.jar "https://repo1.maven.org/maven2/io/grpc/grpc-all/$MAJOR.$MINOR.$PATCH/grpc-all-$MAJOR.$MINOR.$PATCH-javadoc.jar" + unzip -d javadoc grpc-all-javadoc.jar + patch -p1 < ga.patch + rm grpc-all-javadoc.jar + rm -r javadoc/META-INF/ + git add -A javadoc + git commit -m "Javadoc for $MAJOR.$MINOR.$PATCH" + git push upstream gh-pages + ``` + + Verify the current version is [live on grpc.io](https://grpc.io/grpc-java/javadoc/). + +12. Add [Release Notes](https://github.com/grpc/grpc-java/releases) for the new tag. + *Make sure that any backports are reflected in the release notes.* + +13. Notify the Community. Post a release announcement to + [grpc-io](https://groups.google.com/forum/#!forum/grpc-io) + (`grpc-io@googlegroups.com`) with the title `gRPC-Java v$MAJOR.$MINOR.$PATCH + Released`. The email content should link to the GitHub release notes and + include a copy of them. + +14. Update README.md. Cherry-pick the commit that updated the README.md into the + master branch. + + ```bash + git checkout -b bump-readme master + git cherry-pick v$MAJOR.$MINOR.$PATCH^ + git push --set-upstream origin bump-readme + ``` + + Create a PR and go through the review process + +15. Update version referenced by tutorials. Update `params.grpc_vers.java` in + [config.yaml](https://github.com/grpc/grpc.io/blob/master/config.yaml) of + the grpc.io repository. Create a PR and go through the review process. + +Post-release upgrades --------------------- +Upgrade dependencies after the release so they can be well-tested before the +next release. -Now we need to update gh-pages with the new Javadoc: +Upgrade the Gradle plugins in `settings.gradle` and the Gradle version in +`gradle/wrapper/gradle-wrapper.properties`. Make sure to read the release notes +for each dependency upgraded. Test by doing a regular build. + +Upgrade the regular dependencies in `gradle/libs.versions.toml`, except for +Netty and netty-tcnative. To find available upgrades: ```bash -git checkout gh-pages -git pull --ff-only upstream gh-pages -rm -r javadoc/ -wget -O grpc-all-javadoc.jar "http://search.maven.org/remotecontent?filepath=io/grpc/grpc-all/$MAJOR.$MINOR.$PATCH/grpc-all-$MAJOR.$MINOR.$PATCH-javadoc.jar" -unzip -d javadoc grpc-all-javadoc.jar -patch -p1 < ga.patch -rm grpc-all-javadoc.jar -rm -r javadoc/META-INF/ -git add -A javadoc -git commit -m "Javadoc for $MAJOR.$MINOR.$PATCH" +./gradlew checkForUpdates ``` -Push gh-pages to the main repository and verify the current version is [live -on grpc.io](https://grpc.io/grpc-java/javadoc/). +Test by doing a regular build. For each step, if a dependency cannot be +upgraded, add a comment. Create issues in other projects for breakages, and in +gRPC for things that will need a migration effort. + +When happy with the dependency upgrades, update the versions in `MODULE.bazel`, +`repositories.bzl`, and the various `pom.xml` and `build.gradle` files in +`examples/`. diff --git a/SECURITY.md b/SECURITY.md index 9bebf5b709d..e710ceaabe1 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,10 +1,16 @@ # Security Policy -For information on gRPC Security Policy and reporting potentional security issues, please see [gRPC CVE Process](https://github.com/grpc/proposal/blob/master/P4-grpc-cve-process.md). +For information on gRPC Security Policy and reporting potentional security +issues, please see [gRPC CVE Process][]. + +[gRPC CVE Process]: https://github.com/grpc/proposal/blob/master/P4-grpc-cve-process.md # Authentication -gRPC supports a number of different mechanisms for asserting identity between an client and server. This document provides code samples demonstrating how to provide SSL/TLS encryption support and identity assertions in Java, as well as passing OAuth2 tokens to services that support it. +gRPC supports a number of different mechanisms for asserting identity between an +client and server. This document provides code samples demonstrating how to +provide SSL/TLS encryption support and identity assertions in Java, as well as +passing OAuth2 tokens to services that support it. # Transport Security (TLS) @@ -19,25 +25,28 @@ BoringSSL](#tls-with-netty-tcnative-on-boringssl). ## TLS on Android On Android we recommend the use of the [Play Services Dynamic Security -Provider](https://www.appfoundry.be/blog/2014/11/18/Google-Play-Services-Dynamic-Security-Provider/) -to ensure your application has an up-to-date OpenSSL library with the necessary -cipher-suites and a reliable ALPN implementation. This requires [updating the -security provider at -runtime](https://developer.android.com/training/articles/security-gms-provider.html). +Provider][] to ensure your application has an up-to-date OpenSSL library with +the necessary cipher-suites and a reliable ALPN implementation. This requires +[updating the security provider at runtime][config-psdsp]. Although ALPN mostly works on newer Android releases (especially since 5.0), there are bugs and discovered security vulnerabilities that are only fixed by upgrading the security provider. Thus, we recommend using the Play Service Dynamic Security Provider for all Android versions. -*Note: The Dynamic Security Provider must be installed **before** creating a gRPC OkHttp channel. gRPC's OkHttpProtocolNegotiator statically initializes the security protocol(s) available to gRPC, which means that changes to the security provider after the first channel is created will not be picked up by gRPC.* +*Note: The Dynamic Security Provider must be installed **before** creating a +gRPC OkHttp channel. gRPC statically initializes the security protocol(s) +available, which means that changes to the security provider after the first +channel is created will not be noticed by gRPC.* + +[Play Services Dynamic Security Provider]: https://www.appfoundry.be/blog/2014/11/18/Google-Play-Services-Dynamic-Security-Provider/ +[config-psdsp]: https://developer.android.com/training/articles/security-gms-provider.html ### Bundling Conscrypt If depending on Play Services is not an option for your app, then you may bundle [Conscrypt](https://conscrypt.org) with your application. Binaries are available -on [Maven -Central](https://search.maven.org/#search%7Cga%7C1%7Cg%3Aorg.conscrypt%20a%3Aconscrypt-android). +on [Maven Central][conscrypt-maven]. Like the Play Services Dynamic Security Provider, you must still "install" Conscrypt before use. @@ -50,16 +59,22 @@ import java.security.Security; Security.insertProviderAt(Conscrypt.newProvider(), 1); ``` +[conscrypt-maven]: https://search.maven.org/#search%7Cga%7C1%7Cg%3Aorg.conscrypt%20a%3Aconscrypt-android + ## TLS on non-Android -JDK versions prior to Java 9 do not support ALPN and are either missing AES GCM -support or have 2% the performance of OpenSSL. +OpenJDK versions prior to Java 8u252 do not support ALPN. Java 8 has 10% the +performance of OpenSSL. We recommend most users use grpc-netty-shaded, which includes netty-tcnative on BoringSSL. It includes pre-built libraries for 64 bit Windows, OS X, and 64 bit Linux. For 32 bit Windows, Conscrypt is an option. For all other platforms, Java 9+ is required. +For users of xDS management protocol, the grpc-netty-shaded transport is +particularly appropriate since it is already used internally for the xDS +protocol and is a runtime dependency of grpc-xds. + For users of grpc-netty we recommend [netty-tcnative with BoringSSL](#tls-with-netty-tcnative-on-boringssl), although using the built-in JDK support in Java 9+, [Conscrypt](#tls-with-conscrypt), and [netty-tcnative @@ -69,7 +84,7 @@ with OpenSSL](#tls-with-netty-tcnative-on-openssl) are other valid options. [Apache Tomcat's tcnative](https://tomcat.apache.org/native-doc/) and is a JNI wrapper around OpenSSL/BoringSSL/LibreSSL. -We recommend BoringSSL for its simplicitly and low occurrence of security +We recommend BoringSSL for its simplicity and low occurrence of security vulnerabilities relative to OpenSSL. BoringSSL is used by Conscrypt as well. ### TLS with netty-tcnative on BoringSSL @@ -155,7 +170,7 @@ the dependency. kr.motd.maven os-maven-plugin - 1.6.2 + 1.7.1 @@ -239,37 +254,6 @@ import java.security.Security; Security.insertProviderAt(Conscrypt.newProvider(), 1); ``` -### TLS with Jetty ALPN - -**Please do not use Jetty ALPN** - -gRPC historically supported Jetty ALPN for ALPN on Java 8. While functional, it -suffers from poor performance and breakages when the JRE is upgraded. -When mis-matched to the JRE version, it can also produce unpredictable errors -that are hard to diagnose. When using it, it became common practice that any -time we saw a TLS failure that made no sense we would blame a Jetty ALPN/JRE -version mismatch and we were overwhelmingly correct. The Jetty ALPN agent makes -it much easier to use, but we still strongly discourage Jetty ALPN's use. - -When using Jetty ALPN with Java 8, realize that performance will be 2-10% that -of the other options due to a slow AES GCM implementation in Java. - -#### Configuring Jetty ALPN in Web Containers - -Some web containers, such as [Jetty](https://www.eclipse.org/jetty/documentation/current/jetty-classloading.html) restrict access to server classes for web applications. A gRPC client running within such a container must be properly configured to allow access to the ALPN classes. In Jetty, this is done by including a `WEB-INF/jetty-env.xml` file containing the following: - -```xml - - - - - - - - -org.eclipse.jetty.alpn. - - -``` ## Enabling TLS on a server To use TLS on the server, a certificate chain and private key need to be @@ -277,35 +261,36 @@ specified in PEM format. The standard TLS port is 443, but we use 8443 below to avoid needing extra permissions from the OS. ```java -Server server = ServerBuilder.forPort(8443) - // Enable TLS - .useTransportSecurity(certChainFile, privateKeyFile) +ServerCredentials creds = TlsServerCredentials.create(certChainFile, privateKeyFile); +Server server = Grpc.newServerBuilderForPort(8443, creds) .addService(serviceImplementation) - .build(); -server.start(); + .build() + .start(); ``` If the issuing certificate authority is not known to the client then a properly -configured SslContext or SSLSocketFactory should be provided to the -NettyChannelBuilder or OkHttpChannelBuilder, respectively. +configured trust manager should be provided to TlsChannelCredentials and used to +construct the channel. ## Mutual TLS [Mutual authentication][] (or "client-side authentication") configuration is similar to the server by providing truststores, a client certificate and private key to the client channel. The server must also be configured to request a certificate from clients, as well as truststores for which client certificates it should allow. ```java -Server server = NettyServerBuilder.forPort(8443) - .sslContext(GrpcSslContexts.forServer(certChainFile, privateKeyFile) - .trustManager(clientCAsFile) - .clientAuth(ClientAuth.REQUIRE) - .build()); +ServerCredentials creds = TlsServerCredentials.newBuilder() + .keyManager(certChainFile, privateKeyFile) + .trustManager(clientCAsFile) + .clientAuth(TlsServerCredentials.ClientAuth.REQUIRE) + .build(); ``` -Negotiated client certificates are available in the SSLSession, which is found in the `TRANSPORT_ATTR_SSL_SESSION` attribute of Grpc. A server interceptor can provide details in the current Context. +Negotiated client certificates are available in the SSLSession, which is found +in the `Grpc.TRANSPORT_ATTR_SSL_SESSION` attribute of the call. A server +interceptor can provide details in the current Context. ```java -// The application uses this in its handlers -public final static Context.Key SSL_SESSION_CONTEXT = Context.key("SSLSession"); +// The application uses this in its handlers. +public static final Context.Key SECURITY_INFO = Context.key("my.security.Info"); @Override public ServerCall.Listener interceptCall(ServerCall call, @@ -314,8 +299,12 @@ public ServerCall.Listener interceptCall(ServerCall subproject.javadoc.classpath }) @@ -44,24 +51,18 @@ javadoc { continue; } source subproject.javadoc.source - options.links subproject.javadoc.options.links.toArray(new String[0]) + options.linksOffline.addAll subproject.javadoc.options.linksOffline } } -task jacocoMerge(type: JacocoMerge) { - dependsOn(subprojects.jacocoTestReport.dependsOn) +tasks.named("jacocoTestReport").configure { mustRunAfter(subprojects.jacocoTestReport.mustRunAfter) - destinationFile = file("${buildDir}/jacoco/test.exec") - executionData = files(subprojects.jacocoTestReport.executionData) + mustRunAfter(project(':grpc-interop-testing').jacocoTestReport.mustRunAfter) + executionData.from files(subprojects.jacocoTestReport.executionData) .plus(project(':grpc-interop-testing').jacocoTestReport.executionData) - .filter { f -> f.exists() } -} - -jacocoTestReport { - dependsOn(jacocoMerge) reports { - xml.enabled = true - html.enabled = true + xml.required = true + html.required = true } subprojects.each { subproject -> @@ -75,4 +76,4 @@ coveralls { sourceDirs = subprojects.sourceSets.main.allSource.srcDirs.flatten() } -tasks.coveralls { dependsOn(jacocoTestReport) } +tasks.named("coveralls").configure { dependsOn tasks.named("jacocoTestReport") } diff --git a/alts/BUILD.bazel b/alts/BUILD.bazel index c99689bac11..f29df303fbe 100644 --- a/alts/BUILD.bazel +++ b/alts/BUILD.bazel @@ -1,4 +1,7 @@ -load("@rules_proto//proto:defs.bzl", "proto_library") +load("@com_google_protobuf//bazel:java_proto_library.bzl", "java_proto_library") +load("@com_google_protobuf//bazel:proto_library.bzl", "proto_library") +load("@rules_java//java:defs.bzl", "java_library") +load("@rules_jvm_external//:defs.bzl", "artifact") load("//:java_grpc_library.bzl", "java_grpc_library") java_library( @@ -11,19 +14,18 @@ java_library( ":handshaker_java_proto", "//api", "//core:internal", - "//grpclb", "//netty", "//stub", - "@com_google_code_findbugs_jsr305//jar", - "@com_google_guava_guava//jar", - "@com_google_j2objc_j2objc_annotations//jar", "@com_google_protobuf//:protobuf_java", "@com_google_protobuf//:protobuf_java_util", - "@io_netty_netty_buffer//jar", - "@io_netty_netty_codec//jar", - "@io_netty_netty_common//jar", - "@io_netty_netty_handler//jar", - "@io_netty_netty_transport//jar", + artifact("com.google.code.findbugs:jsr305"), + artifact("com.google.errorprone:error_prone_annotations"), + artifact("com.google.guava:guava"), + artifact("io.netty:netty-buffer"), + artifact("io.netty:netty-codec"), + artifact("io.netty:netty-common"), + artifact("io.netty:netty-handler"), + artifact("io.netty:netty-transport"), ], ) @@ -35,19 +37,18 @@ java_library( visibility = ["//visibility:public"], deps = [ ":alts_internal", - ":handshaker_java_proto", ":handshaker_java_grpc", + ":handshaker_java_proto", "//api", "//auth", "//core:internal", "//netty", - "@com_google_auth_google_auth_library_oauth2_http//jar", - "@com_google_code_findbugs_jsr305//jar", - "@com_google_guava_guava//jar", - "@com_google_j2objc_j2objc_annotations//jar", - "@io_netty_netty_common//jar", - "@io_netty_netty_handler//jar", - "@io_netty_netty_transport//jar", + artifact("com.google.auth:google-auth-library-oauth2-http"), + artifact("com.google.code.findbugs:jsr305"), + artifact("com.google.guava:guava"), + artifact("io.netty:netty-common"), + artifact("io.netty:netty-handler"), + artifact("io.netty:netty-transport"), ], ) diff --git a/alts/build.gradle b/alts/build.gradle index fa4dda2b790..c206a37bcef 100644 --- a/alts/build.gradle +++ b/alts/build.gradle @@ -2,74 +2,78 @@ plugins { id "java-library" id "maven-publish" - id "com.github.johnrengelman.shadow" id "com.google.protobuf" + id "com.gradleup.shadow" id "ru.vyarus.animalsniffer" } description = "gRPC: ALTS" -sourceCompatibility = 1.7 -targetCompatibility = 1.7 - dependencies { - api project(':grpc-core') + api project(':grpc-api') implementation project(':grpc-auth'), - project(':grpc-grpclb'), + project(':grpc-core'), + project(":grpc-context"), // Override google-auth dependency with our newer version project(':grpc-protobuf'), project(':grpc-stub'), - libraries.protobuf, - libraries.conscrypt + libraries.protobuf.java, + libraries.conscrypt, + libraries.google.auth.oauth2Http def nettyDependency = implementation project(':grpc-netty') - googleOauth2Dependency 'implementation' - guavaDependency 'implementation' - compileOnly libraries.javax_annotation shadow configurations.implementation.getDependencies().minus(nettyDependency) shadow project(path: ':grpc-netty-shaded', configuration: 'shadow') testImplementation project(':grpc-testing'), + testFixtures(project(':grpc-core')), + project(':grpc-inprocess'), project(':grpc-testing-proto'), libraries.guava, libraries.junit, - libraries.mockito, + libraries.mockito.core, libraries.truth - testImplementation (libraries.guava_testlib) { - exclude group: 'junit', module: 'junit' + testImplementation libraries.guava.testlib + testRuntimeOnly libraries.netty.tcnative, + libraries.netty.tcnative.classes + testRuntimeOnly (libraries.netty.transport.epoll) { + artifact { + classifier = "linux-x86_64" + } + } + signature (libraries.signature.java) { + artifact { + extension = "signature" + } } - testRuntimeOnly libraries.netty_tcnative, - libraries.netty_epoll - signature 'org.codehaus.mojo.signature:java17:1.0@signature' } configureProtoCompilation() import net.ltgt.gradle.errorprone.CheckSeverity -[compileJava, compileTestJava].each() { - // protobuf calls valueof. Will be fixed in next release (google/protobuf#4046) - it.options.compilerArgs += [ - "-Xlint:-deprecation" - ] +[tasks.named("compileJava"), tasks.named("compileTestJava")]*.configure { // ALTS returns a lot of futures that we mostly don't care about. - it.options.errorprone.check("FutureReturnValueIgnored", CheckSeverity.OFF) + options.errorprone.check("FutureReturnValueIgnored", CheckSeverity.OFF) } -javadoc { +tasks.named("javadoc").configure { exclude 'io/grpc/alts/internal/**' exclude 'io/grpc/alts/Internal*' } -jar { - // Must use a different classifier to avoid conflicting with shadowJar - classifier = 'original' +tasks.named("jar").configure { + // Must use a different archiveClassifier to avoid conflicting with shadowJar + archiveClassifier = 'original' + manifest { + attributes('Automatic-Module-Name': 'io.grpc.alts') + } } // We want to use grpc-netty-shaded instead of grpc-netty. But we also want our // source to work with Bazel, so we rewrite the code as part of the build. -shadowJar { - classifier = null +tasks.named("shadowJar").configure { + archiveClassifier = null dependencies { exclude(dependency {true}) } @@ -90,8 +94,7 @@ publishing { def dependencyNode = dependenciesNode.appendNode('dependency') dependencyNode.appendNode('groupId', dep.group) dependencyNode.appendNode('artifactId', dep.name) - def version = (dep.name == 'grpc-netty-shaded') ? '[' + dep.version + ']' : dep.version - dependencyNode.appendNode('version', version) + dependencyNode.appendNode('version', dep.version) dependencyNode.appendNode('scope', 'compile') } asNode().dependencies[0].replaceNode(dependenciesNode) diff --git a/alts/src/generated/main/grpc/io/grpc/alts/internal/HandshakerServiceGrpc.java b/alts/src/generated/main/grpc/io/grpc/alts/internal/HandshakerServiceGrpc.java index 3d78f15f767..07e4256eb75 100644 --- a/alts/src/generated/main/grpc/io/grpc/alts/internal/HandshakerServiceGrpc.java +++ b/alts/src/generated/main/grpc/io/grpc/alts/internal/HandshakerServiceGrpc.java @@ -4,14 +4,12 @@ /** */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/gcp/handshaker.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class HandshakerServiceGrpc { private HandshakerServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.gcp.HandshakerService"; + public static final java.lang.String SERVICE_NAME = "grpc.gcp.HandshakerService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public HandshakerServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new HandshakerServiceBlockingV2Stub(channel, callOptions); + } + }; + return HandshakerServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -91,7 +104,7 @@ public HandshakerServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.Call /** */ - public static abstract class HandshakerServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** *
@@ -103,27 +116,28 @@ public static abstract class HandshakerServiceImplBase implements io.grpc.Bindab
      * response before sending next request.
      * 
*/ - public io.grpc.stub.StreamObserver doHandshake( + default io.grpc.stub.StreamObserver doHandshake( io.grpc.stub.StreamObserver responseObserver) { return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getDoHandshakeMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service HandshakerService. + */ + public static abstract class HandshakerServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getDoHandshakeMethod(), - io.grpc.stub.ServerCalls.asyncBidiStreamingCall( - new MethodHandlers< - io.grpc.alts.internal.HandshakerReq, - io.grpc.alts.internal.HandshakerResp>( - this, METHODID_DO_HANDSHAKE))) - .build(); + return HandshakerServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service HandshakerService. */ - public static final class HandshakerServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class HandshakerServiceStub + extends io.grpc.stub.AbstractAsyncStub { private HandshakerServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -153,8 +167,44 @@ public io.grpc.stub.StreamObserver doHandsh } /** + * A stub to allow clients to do synchronous rpc calls to service HandshakerService. + */ + public static final class HandshakerServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private HandshakerServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected HandshakerServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new HandshakerServiceBlockingV2Stub(channel, callOptions); + } + + /** + *
+     * Handshaker service accepts a stream of handshaker request, returning a
+     * stream of handshaker response. Client is expected to send exactly one
+     * message with either client_start or server_start followed by one or more
+     * messages with next. Each time client sends a request, the handshaker
+     * service expects to respond. Client does not have to wait for service's
+     * response before sending next request.
+     * 
+ */ + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918") + public io.grpc.stub.BlockingClientCall + doHandshake() { + return io.grpc.stub.ClientCalls.blockingBidiStreamingCall( + getChannel(), getDoHandshakeMethod(), getCallOptions()); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service HandshakerService. */ - public static final class HandshakerServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class HandshakerServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private HandshakerServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -168,8 +218,10 @@ protected HandshakerServiceBlockingStub build( } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service HandshakerService. */ - public static final class HandshakerServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class HandshakerServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private HandshakerServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -189,10 +241,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final HandshakerServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(HandshakerServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -220,6 +272,18 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getDoHandshakeMethod(), + io.grpc.stub.ServerCalls.asyncBidiStreamingCall( + new MethodHandlers< + io.grpc.alts.internal.HandshakerReq, + io.grpc.alts.internal.HandshakerResp>( + service, METHODID_DO_HANDSHAKE))) + .build(); + } + private static abstract class HandshakerServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { HandshakerServiceBaseDescriptorSupplier() {} @@ -243,9 +307,9 @@ private static final class HandshakerServiceFileDescriptorSupplier private static final class HandshakerServiceMethodDescriptorSupplier extends HandshakerServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { - private final String methodName; + private final java.lang.String methodName; - HandshakerServiceMethodDescriptorSupplier(String methodName) { + HandshakerServiceMethodDescriptorSupplier(java.lang.String methodName) { this.methodName = methodName; } diff --git a/alts/src/main/java/io/grpc/alts/AltsChannelBuilder.java b/alts/src/main/java/io/grpc/alts/AltsChannelBuilder.java index 969cef9cc10..ca33f8b00b9 100644 --- a/alts/src/main/java/io/grpc/alts/AltsChannelBuilder.java +++ b/alts/src/main/java/io/grpc/alts/AltsChannelBuilder.java @@ -18,7 +18,7 @@ import com.google.common.annotations.VisibleForTesting; import io.grpc.ExperimentalApi; -import io.grpc.ForwardingChannelBuilder; +import io.grpc.ForwardingChannelBuilder2; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.internal.GrpcUtil; @@ -29,16 +29,16 @@ /** * ALTS version of {@code ManagedChannelBuilder}. This class sets up a secure and authenticated - * commmunication between two cloud VMs using ALTS. + * communication between two cloud VMs using ALTS. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4151") -public final class AltsChannelBuilder extends ForwardingChannelBuilder { +public final class AltsChannelBuilder extends ForwardingChannelBuilder2 { private final NettyChannelBuilder delegate; private final AltsChannelCredentials.Builder credentialsBuilder = new AltsChannelCredentials.Builder(); /** "Overrides" the static method in {@link ManagedChannelBuilder}. */ - public static final AltsChannelBuilder forTarget(String target) { + public static AltsChannelBuilder forTarget(String target) { return new AltsChannelBuilder(target); } diff --git a/alts/src/main/java/io/grpc/alts/AltsChannelCredentials.java b/alts/src/main/java/io/grpc/alts/AltsChannelCredentials.java index 7c603d31fcd..e12344f73d7 100644 --- a/alts/src/main/java/io/grpc/alts/AltsChannelCredentials.java +++ b/alts/src/main/java/io/grpc/alts/AltsChannelCredentials.java @@ -36,7 +36,7 @@ import java.util.logging.Logger; /** - * Provides secure and authenticated commmunication between two cloud VMs using ALTS. + * Provides secure and authenticated communication between two cloud VMs using ALTS. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4151") public final class AltsChannelCredentials { diff --git a/alts/src/main/java/io/grpc/alts/AltsContext.java b/alts/src/main/java/io/grpc/alts/AltsContext.java index f264ad112d7..7680de4160e 100644 --- a/alts/src/main/java/io/grpc/alts/AltsContext.java +++ b/alts/src/main/java/io/grpc/alts/AltsContext.java @@ -20,7 +20,6 @@ import io.grpc.alts.internal.AltsInternalContext; import io.grpc.alts.internal.HandshakerResult; import io.grpc.alts.internal.Identity; -import io.grpc.alts.internal.SecurityLevel; /** {@code AltsContext} contains security-related information on the ALTS channel. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/7864") diff --git a/alts/src/main/java/io/grpc/alts/AltsContextUtil.java b/alts/src/main/java/io/grpc/alts/AltsContextUtil.java index a5d7c0e3ff9..f45179bbd91 100644 --- a/alts/src/main/java/io/grpc/alts/AltsContextUtil.java +++ b/alts/src/main/java/io/grpc/alts/AltsContextUtil.java @@ -14,9 +14,10 @@ * limitations under the License. */ - package io.grpc.alts; +import io.grpc.Attributes; +import io.grpc.ClientCall; import io.grpc.ExperimentalApi; import io.grpc.ServerCall; import io.grpc.alts.internal.AltsInternalContext; @@ -26,17 +27,39 @@ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/7864") public final class AltsContextUtil { - private AltsContextUtil(){} + private AltsContextUtil() {} /** - * Creates a {@link AltsContext} from ALTS context information in the {@link ServerCall}. + * Creates an {@link AltsContext} from ALTS context information in the {@link ServerCall}. * * @param call the {@link ServerCall} containing the ALTS information * @return the created {@link AltsContext} * @throws IllegalArgumentException if the {@link ServerCall} has no ALTS information. */ - public static AltsContext createFrom(ServerCall call) { - Object authContext = call.getAttributes().get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY); + public static AltsContext createFrom(ServerCall call) { + return createFrom(call.getAttributes()); + } + + /** + * Creates an {@link AltsContext} from ALTS context information in the {@link ClientCall}. + * + * @param call the {@link ClientCall} containing the ALTS information + * @return the created {@link AltsContext} + * @throws IllegalArgumentException if the {@link ClientCall} has no ALTS information. + */ + public static AltsContext createFrom(ClientCall call) { + return createFrom(call.getAttributes()); + } + + /** + * Creates an {@link AltsContext} from ALTS context information in the {@link Attributes}. + * + * @param attributes the {@link Attributes} containing the ALTS information + * @return the created {@link AltsContext} + * @throws IllegalArgumentException if the {@link Attributes} has no ALTS information. + */ + public static AltsContext createFrom(Attributes attributes) { + Object authContext = attributes.get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY); if (!(authContext instanceof AltsInternalContext)) { throw new IllegalArgumentException("No ALTS context information found"); } @@ -49,8 +72,28 @@ public static AltsContext createFrom(ServerCall call) { * @param call the {@link ServerCall} to check * @return true, if the {@link ServerCall} contains ALTS information and false otherwise. */ - public static boolean check(ServerCall call) { - Object authContext = call.getAttributes().get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY); + public static boolean check(ServerCall call) { + return check(call.getAttributes()); + } + + /** + * Checks if the {@link ClientCall} contains ALTS information. + * + * @param call the {@link ClientCall} to check + * @return true, if the {@link ClientCall} contains ALTS information and false otherwise. + */ + public static boolean check(ClientCall call) { + return check(call.getAttributes()); + } + + /** + * Checks if the {@link Attributes} contains ALTS information. + * + * @param attributes the {@link Attributes} to check + * @return true, if the {@link Attributes} contains ALTS information and false otherwise. + */ + public static boolean check(Attributes attributes) { + Object authContext = attributes.get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY); return authContext instanceof AltsInternalContext; } } diff --git a/alts/src/main/java/io/grpc/alts/AltsServerBuilder.java b/alts/src/main/java/io/grpc/alts/AltsServerBuilder.java index 108b294e215..e307fd1c63a 100644 --- a/alts/src/main/java/io/grpc/alts/AltsServerBuilder.java +++ b/alts/src/main/java/io/grpc/alts/AltsServerBuilder.java @@ -20,6 +20,7 @@ import io.grpc.CompressorRegistry; import io.grpc.DecompressorRegistry; import io.grpc.ExperimentalApi; +import io.grpc.ForwardingServerBuilder; import io.grpc.HandlerRegistry; import io.grpc.Server; import io.grpc.ServerBuilder; @@ -38,7 +39,7 @@ * a production server on Google Cloud Platform. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4151") -public final class AltsServerBuilder extends ServerBuilder { +public final class AltsServerBuilder extends ForwardingServerBuilder { private final NettyServerBuilder delegate; private final AltsServerCredentials.Builder credentialsBuilder = new AltsServerCredentials.Builder(); @@ -68,6 +69,11 @@ public AltsServerBuilder setHandshakerAddressForTesting(String handshakerAddress return this; } + @Override + protected ServerBuilder delegate() { + return delegate; + } + /** {@inheritDoc} */ @Override public AltsServerBuilder handshakeTimeout(long timeout, TimeUnit unit) { diff --git a/alts/src/main/java/io/grpc/alts/AltsServerCredentials.java b/alts/src/main/java/io/grpc/alts/AltsServerCredentials.java index dd56e310cc1..36dc9f6a4ae 100644 --- a/alts/src/main/java/io/grpc/alts/AltsServerCredentials.java +++ b/alts/src/main/java/io/grpc/alts/AltsServerCredentials.java @@ -32,7 +32,7 @@ * gRPC secure server builder used for ALTS. This class adds on the necessary ALTS support to create * a production server on Google Cloud Platform. */ -@ExperimentalApi("https://github.com/grpc/grpc-java/issues/7621") +@ExperimentalApi("https://github.com/grpc/grpc-java/issues/4151") public final class AltsServerCredentials { private static final Logger logger = Logger.getLogger(AltsServerCredentials.class.getName()); @@ -46,7 +46,7 @@ public static Builder newBuilder() { return new Builder(); } - @ExperimentalApi("https://github.com/grpc/grpc-java/issues/7621") + @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4151") public static final class Builder { private ObjectPool handshakerChannelPool = SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL); diff --git a/alts/src/main/java/io/grpc/alts/ComputeEngineChannelBuilder.java b/alts/src/main/java/io/grpc/alts/ComputeEngineChannelBuilder.java index c8c0a08ed0a..b5ee6a8d362 100644 --- a/alts/src/main/java/io/grpc/alts/ComputeEngineChannelBuilder.java +++ b/alts/src/main/java/io/grpc/alts/ComputeEngineChannelBuilder.java @@ -35,7 +35,7 @@ private ComputeEngineChannelBuilder(String target) { } /** "Overrides" the static method in {@link ManagedChannelBuilder}. */ - public static final ComputeEngineChannelBuilder forTarget(String target) { + public static ComputeEngineChannelBuilder forTarget(String target) { return new ComputeEngineChannelBuilder(target); } @@ -45,6 +45,7 @@ public static ComputeEngineChannelBuilder forAddress(String name, int port) { } @Override + @SuppressWarnings("deprecation") // Not extending ForwardingChannelBuilder2 to preserve ABI. protected NettyChannelBuilder delegate() { return delegate; } diff --git a/alts/src/main/java/io/grpc/alts/ComputeEngineChannelCredentials.java b/alts/src/main/java/io/grpc/alts/ComputeEngineChannelCredentials.java index ff5bab6ec74..518642a675d 100644 --- a/alts/src/main/java/io/grpc/alts/ComputeEngineChannelCredentials.java +++ b/alts/src/main/java/io/grpc/alts/ComputeEngineChannelCredentials.java @@ -21,7 +21,6 @@ import io.grpc.CallCredentials; import io.grpc.ChannelCredentials; import io.grpc.CompositeChannelCredentials; -import io.grpc.ExperimentalApi; import io.grpc.Status; import io.grpc.alts.internal.AltsProtocolNegotiator.GoogleDefaultProtocolNegotiatorFactory; import io.grpc.auth.MoreCallCredentials; @@ -37,7 +36,6 @@ * class sets up a secure channel using ALTS if applicable and using TLS as fallback. It is a subset * of the functionality provided by {@link GoogleDefaultChannelCredentials}. */ -@ExperimentalApi("https://github.com/grpc/grpc-java/issues/7479") public final class ComputeEngineChannelCredentials { private ComputeEngineChannelCredentials() {} @@ -69,7 +67,6 @@ private static InternalProtocolNegotiator.ClientFactory createClientFactory() { return new GoogleDefaultProtocolNegotiatorFactory( /* targetServiceAccounts= */ ImmutableList.of(), SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL), - sslContext, - null); + sslContext); } } diff --git a/alts/src/main/java/io/grpc/alts/DualCallCredentials.java b/alts/src/main/java/io/grpc/alts/DualCallCredentials.java new file mode 100644 index 00000000000..08104712e65 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/DualCallCredentials.java @@ -0,0 +1,46 @@ +/* + * Copyright 2024 The gRPC 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import io.grpc.CallCredentials; +import java.util.concurrent.Executor; + +/** + * {@code CallCredentials} that will pick the right credentials based on whether the established + * connection is ALTS or TLS. + */ +final class DualCallCredentials extends CallCredentials { + private final CallCredentials tlsCallCredentials; + private final CallCredentials altsCallCredentials; + + public DualCallCredentials(CallCredentials tlsCallCreds, CallCredentials altsCallCreds) { + tlsCallCredentials = tlsCallCreds; + altsCallCredentials = altsCallCreds; + } + + @Override + public void applyRequestMetadata( + CallCredentials.RequestInfo requestInfo, + Executor appExecutor, + CallCredentials.MetadataApplier applier) { + if (AltsContextUtil.check(requestInfo.getTransportAttrs())) { + altsCallCredentials.applyRequestMetadata(requestInfo, appExecutor, applier); + } else { + tlsCallCredentials.applyRequestMetadata(requestInfo, appExecutor, applier); + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/FailingCallCredentials.java b/alts/src/main/java/io/grpc/alts/FailingCallCredentials.java index dbe0821abe9..3c59c5b6d09 100644 --- a/alts/src/main/java/io/grpc/alts/FailingCallCredentials.java +++ b/alts/src/main/java/io/grpc/alts/FailingCallCredentials.java @@ -38,7 +38,4 @@ public void applyRequestMetadata( CallCredentials.MetadataApplier applier) { applier.fail(status); } - - @Override - public void thisUsesUnstableApi() {} } diff --git a/alts/src/main/java/io/grpc/alts/GoogleDefaultChannelBuilder.java b/alts/src/main/java/io/grpc/alts/GoogleDefaultChannelBuilder.java index 4e006b60649..c78b94417c4 100644 --- a/alts/src/main/java/io/grpc/alts/GoogleDefaultChannelBuilder.java +++ b/alts/src/main/java/io/grpc/alts/GoogleDefaultChannelBuilder.java @@ -35,7 +35,7 @@ private GoogleDefaultChannelBuilder(String target) { } /** "Overrides" the static method in {@link ManagedChannelBuilder}. */ - public static final GoogleDefaultChannelBuilder forTarget(String target) { + public static GoogleDefaultChannelBuilder forTarget(String target) { return new GoogleDefaultChannelBuilder(target); } @@ -45,6 +45,7 @@ public static GoogleDefaultChannelBuilder forAddress(String name, int port) { } @Override + @SuppressWarnings("deprecation") // Not extending ForwardingChannelBuilder2 to preserve ABI. protected NettyChannelBuilder delegate() { return delegate; } diff --git a/alts/src/main/java/io/grpc/alts/GoogleDefaultChannelCredentials.java b/alts/src/main/java/io/grpc/alts/GoogleDefaultChannelCredentials.java index 41c6b998277..1b5880120a4 100644 --- a/alts/src/main/java/io/grpc/alts/GoogleDefaultChannelCredentials.java +++ b/alts/src/main/java/io/grpc/alts/GoogleDefaultChannelCredentials.java @@ -18,11 +18,9 @@ import com.google.auth.oauth2.GoogleCredentials; import com.google.common.collect.ImmutableList; -import io.grpc.Attributes; import io.grpc.CallCredentials; import io.grpc.ChannelCredentials; import io.grpc.CompositeChannelCredentials; -import io.grpc.ExperimentalApi; import io.grpc.Status; import io.grpc.alts.internal.AltsProtocolNegotiator.GoogleDefaultProtocolNegotiatorFactory; import io.grpc.auth.MoreCallCredentials; @@ -32,18 +30,13 @@ import io.grpc.netty.InternalProtocolNegotiator; import io.netty.handler.ssl.SslContext; import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; import javax.net.ssl.SSLException; /** * Credentials appropriate to contact Google services. This class sets up a secure channel using * ALTS if applicable and uses TLS as fallback. */ -@ExperimentalApi("https://github.com/grpc/grpc-java/issues/7479") public final class GoogleDefaultChannelCredentials { - private static Logger logger = Logger.getLogger(GoogleDefaultChannelCredentials.class.getName()); - private GoogleDefaultChannelCredentials() {} /** @@ -51,48 +44,75 @@ private GoogleDefaultChannelCredentials() {} * as fallback. */ public static ChannelCredentials create() { - ChannelCredentials nettyCredentials = - InternalNettyChannelCredentials.create(createClientFactory()); - CallCredentials callCredentials; - try { - callCredentials = MoreCallCredentials.from(GoogleCredentials.getApplicationDefault()); - } catch (IOException e) { - // TODO(ejona): Should this just throw? - callCredentials = new FailingCallCredentials( - Status.UNAUTHENTICATED - .withDescription("Failed to get Google default credentials") - .withCause(e)); - } - return CompositeChannelCredentials.create(nettyCredentials, callCredentials); + return newBuilder().build(); + } + + /** + * Returns a new instance of {@link Builder}. + * + * @since 1.43.0 + */ + public static Builder newBuilder() { + return new Builder(); } - @SuppressWarnings("unchecked") - private static InternalProtocolNegotiator.ClientFactory createClientFactory() { - SslContext sslContext; - try { - sslContext = GrpcSslContexts.forClient().build(); - } catch (SSLException e) { - throw new RuntimeException(e); + /** + * Builder for {@link GoogleDefaultChannelCredentials} instances. + * + * @since 1.43.0 + */ + public static final class Builder { + private CallCredentials callCredentials; + private CallCredentials altsCallCredentials; + + private Builder() {} + + /** Constructs GoogleDefaultChannelCredentials with a given call credential. */ + public Builder callCredentials(CallCredentials callCreds) { + callCredentials = callCreds; + return this; + } + + /** Constructs GoogleDefaultChannelCredentials with an ALTS-specific call credential. */ + public Builder altsCallCredentials(CallCredentials callCreds) { + altsCallCredentials = callCreds; + return this; } - Attributes.Key clusterNameAttrKey = null; - try { - Class klass = Class.forName("io.grpc.xds.InternalXdsAttributes"); - clusterNameAttrKey = - (Attributes.Key) klass.getField("ATTR_CLUSTER_NAME").get(null); - } catch (ClassNotFoundException e) { - logger.log(Level.FINE, - "Unable to load xDS endpoint cluster name key, this may be expected", e); - } catch (NoSuchFieldException e) { - logger.log(Level.FINE, - "Unable to load xDS endpoint cluster name key, this may be expected", e); - } catch (IllegalAccessException e) { - logger.log(Level.FINE, - "Unable to load xDS endpoint cluster name key, this may be expected", e); + + /** Builds a GoogleDefaultChannelCredentials instance. */ + public ChannelCredentials build() { + ChannelCredentials nettyCredentials = + InternalNettyChannelCredentials.create(createClientFactory()); + CallCredentials tlsCallCreds = callCredentials; + if (tlsCallCreds == null) { + try { + tlsCallCreds = MoreCallCredentials.from(GoogleCredentials.getApplicationDefault()); + } catch (IOException e) { + tlsCallCreds = + new FailingCallCredentials( + Status.UNAUTHENTICATED + .withDescription("Failed to get Google default credentials") + .withCause(e)); + } + } + CallCredentials callCreds = + altsCallCredentials == null + ? tlsCallCreds + : new DualCallCredentials(tlsCallCreds, altsCallCredentials); + return CompositeChannelCredentials.create(nettyCredentials, callCreds); + } + + private static InternalProtocolNegotiator.ClientFactory createClientFactory() { + SslContext sslContext; + try { + sslContext = GrpcSslContexts.forClient().build(); + } catch (SSLException e) { + throw new RuntimeException(e); + } + return new GoogleDefaultProtocolNegotiatorFactory( + /* targetServiceAccounts= */ ImmutableList.of(), + SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL), + sslContext); } - return new GoogleDefaultProtocolNegotiatorFactory( - /* targetServiceAccounts= */ ImmutableList.of(), - SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL), - sslContext, - clusterNameAttrKey); } } diff --git a/alts/src/main/java/io/grpc/alts/HandshakerServiceChannel.java b/alts/src/main/java/io/grpc/alts/HandshakerServiceChannel.java index 169afe3078c..5e32d22d901 100644 --- a/alts/src/main/java/io/grpc/alts/HandshakerServiceChannel.java +++ b/alts/src/main/java/io/grpc/alts/HandshakerServiceChannel.java @@ -21,12 +21,14 @@ import io.grpc.ClientCall; import io.grpc.ManagedChannel; import io.grpc.MethodDescriptor; +import io.grpc.internal.GrpcUtil; import io.grpc.internal.SharedResourceHolder.Resource; import io.grpc.netty.NettyChannelBuilder; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; +import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; /** @@ -35,15 +37,37 @@ * application will have at most one connection to the handshaker service. */ final class HandshakerServiceChannel { + // Port 8080 is necessary for ALTS handshake. + private static final int ALTS_PORT = 8080; + private static final String DEFAULT_TARGET = "metadata.google.internal.:8080"; static final Resource SHARED_HANDSHAKER_CHANNEL = - new ChannelResource("metadata.google.internal.:8080"); - + new ChannelResource(getHandshakerTarget(System.getenv("GCE_METADATA_HOST"))); + + /** + * Returns handshaker target. When GCE_METADATA_HOST is provided, it might contain port which we + * will discard and use ALTS_PORT instead. + */ + static String getHandshakerTarget(String envValue) { + if (envValue == null || envValue.isEmpty()) { + return DEFAULT_TARGET; + } + String host = envValue; + int portIndex = host.lastIndexOf(':'); + if (portIndex != -1) { + host = host.substring(0, portIndex); // Discard port if specified + } + return host + ":" + ALTS_PORT; // Utilize ALTS port in all cases + } + /** Returns a resource of handshaker service channel for testing only. */ static Resource getHandshakerChannelForTesting(String handshakerAddress) { return new ChannelResource(handshakerAddress); } + private static final boolean EXPERIMENTAL_ALTS_HANDSHAKER_KEEPALIVE_PARAMS = + GrpcUtil.getFlag("GRPC_EXPERIMENTAL_ALTS_HANDSHAKER_KEEPALIVE_PARAMS", false); + private static class ChannelResource implements Resource { private final String target; @@ -56,12 +80,16 @@ public Channel create() { /* Use its own event loop thread pool to avoid blocking. */ EventLoopGroup eventGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("handshaker pool", true)); - ManagedChannel channel = NettyChannelBuilder.forTarget(target) - .channelType(NioSocketChannel.class) + NettyChannelBuilder channelBuilder = + NettyChannelBuilder.forTarget(target) + .channelType(NioSocketChannel.class, InetSocketAddress.class) .directExecutor() .eventLoopGroup(eventGroup) - .usePlaintext() - .build(); + .usePlaintext(); + if (EXPERIMENTAL_ALTS_HANDSHAKER_KEEPALIVE_PARAMS) { + channelBuilder.keepAliveTime(10, TimeUnit.MINUTES).keepAliveTimeout(10, TimeUnit.SECONDS); + } + ManagedChannel channel = channelBuilder.build(); return new EventLoopHoldingChannel(channel, eventGroup); } diff --git a/alts/src/main/java/io/grpc/alts/InternalCheckGcpEnvironment.java b/alts/src/main/java/io/grpc/alts/InternalCheckGcpEnvironment.java index dc6b776e116..aae4a45d530 100644 --- a/alts/src/main/java/io/grpc/alts/InternalCheckGcpEnvironment.java +++ b/alts/src/main/java/io/grpc/alts/InternalCheckGcpEnvironment.java @@ -30,25 +30,22 @@ import java.util.logging.Logger; /** - * Class for checking if the system is running on Google Cloud Platform (GCP). - * This is intended for usage internal to the gRPC team. If you *really* think you need - * to use this, contact the gRPC team first. + * Class for checking if the system is running on Google Cloud Platform (GCP). This is intended for + * usage internal to the gRPC team. If you *really* think you need to use this, contact the gRPC + * team first. */ @Internal public final class InternalCheckGcpEnvironment { private static final Logger logger = Logger.getLogger(InternalCheckGcpEnvironment.class.getName()); - private static final String DMI_PRODUCT_NAME = "/sys/class/dmi/id/product_name"; private static final String WINDOWS_COMMAND = "powershell.exe"; private static Boolean cachedResult = null; // Construct me not! private InternalCheckGcpEnvironment() {} - /** - * Returns {@code true} if currently running on Google Cloud Platform (GCP). - */ + /** Returns {@code true} if currently running on Google Cloud Platform (GCP). */ public static synchronized boolean isOnGcp() { if (cachedResult == null) { cachedResult = isRunningOnGcp(); @@ -73,13 +70,14 @@ static boolean checkBiosDataOnWindows(BufferedReader reader) throws IOException } return false; } - + private static boolean isRunningOnGcp() { String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); try { if (osName.startsWith("linux")) { // Checks GCE residency on Linux platform. - return checkProductNameOnLinux(Files.newBufferedReader(Paths.get(DMI_PRODUCT_NAME), UTF_8)); + return checkProductNameOnLinux( + Files.newBufferedReader(Paths.get("/sys/class/dmi/id/product_name"), UTF_8)); } else if (osName.startsWith("windows")) { // Checks GCE residency on Windows platform. Process p = diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerClient.java b/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerClient.java index 3b6a0c69616..9eb07f3e86d 100644 --- a/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerClient.java +++ b/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerClient.java @@ -20,19 +20,17 @@ import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.protobuf.ByteString; +import io.grpc.ChannelLogger; +import io.grpc.ChannelLogger.ChannelLogLevel; import io.grpc.Status; import io.grpc.alts.internal.HandshakerServiceGrpc.HandshakerServiceStub; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; -import java.util.logging.Level; -import java.util.logging.Logger; /** An API for conducting handshakes via ALTS handshaker service. */ class AltsHandshakerClient { - private static final Logger logger = Logger.getLogger(AltsHandshakerClient.class.getName()); - private static final String APPLICATION_PROTOCOL = "grpc"; private static final String RECORD_PROTOCOL = "ALTSRP_GCM_AES128_REKEY"; private static final int KEY_LENGTH = AltsChannelCrypter.getKeyLength(); @@ -41,17 +39,22 @@ class AltsHandshakerClient { private final AltsHandshakerOptions handshakerOptions; private HandshakerResult result; private HandshakerStatus status; + private final ChannelLogger logger; /** Starts a new handshake interacting with the handshaker service. */ - AltsHandshakerClient(HandshakerServiceStub stub, AltsHandshakerOptions options) { + AltsHandshakerClient( + HandshakerServiceStub stub, AltsHandshakerOptions options, ChannelLogger logger) { handshakerStub = new AltsHandshakerStub(stub); handshakerOptions = options; + this.logger = logger; } @VisibleForTesting - AltsHandshakerClient(AltsHandshakerStub handshakerStub, AltsHandshakerOptions options) { + AltsHandshakerClient( + AltsHandshakerStub handshakerStub, AltsHandshakerOptions options, ChannelLogger logger) { this.handshakerStub = handshakerStub; handshakerOptions = options; + this.logger = logger; } static String getApplicationProtocol() { @@ -154,7 +157,7 @@ private void handleResponse(HandshakerResp resp) throws GeneralSecurityException } if (status.getCode() != Status.Code.OK.value()) { String error = "Handshaker service error: " + status.getDetails(); - logger.log(Level.INFO, error); + logger.log(ChannelLogLevel.DEBUG, error); close(); throw new GeneralSecurityException(error); } @@ -173,7 +176,9 @@ public ByteBuffer startClientHandshake() throws GeneralSecurityException { setStartClientFields(req); HandshakerResp resp; try { + logger.log(ChannelLogLevel.DEBUG, "Send ALTS handshake request to upstream"); resp = handshakerStub.send(req.build()); + logger.log(ChannelLogLevel.DEBUG, "Receive ALTS handshake response from upstream"); } catch (IOException | InterruptedException e) { throw new GeneralSecurityException(e); } @@ -223,7 +228,9 @@ public ByteBuffer next(ByteBuffer inBytes) throws GeneralSecurityException { .build()); HandshakerResp resp; try { + logger.log(ChannelLogLevel.DEBUG, "Send ALTS handshake request to upstream"); resp = handshakerStub.send(req.build()); + logger.log(ChannelLogLevel.DEBUG, "Receive ALTS handshake response from upstream"); } catch (IOException | InterruptedException e) { throw new GeneralSecurityException(e); } diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerStub.java b/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerStub.java index 61d9fd2f894..6c2748dcc9c 100644 --- a/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerStub.java +++ b/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerStub.java @@ -33,7 +33,7 @@ class AltsHandshakerStub { private final HandshakerServiceStub serviceStub; private final ArrayBlockingQueue> responseQueue = new ArrayBlockingQueue<>(1); - private final AtomicReference exceptionMessage = new AtomicReference<>(); + private final AtomicReference exceptionMessage = new AtomicReference<>(); private static final long HANDSHAKE_RPC_DEADLINE_SECS = 20; @@ -64,12 +64,18 @@ public HandshakerResp send(HandshakerReq req) throws InterruptedException, IOExc if (!responseQueue.isEmpty()) { throw new IOException("Received an unexpected response."); } + writer.onNext(req); Optional result = responseQueue.take(); - if (!result.isPresent()) { - maybeThrowIoException(); + if (result.isPresent()) { + return result.get(); + } + + if (exceptionMessage.get() != null) { + throw new IOException(exceptionMessage.get().info, exceptionMessage.get().throwable); + } else { + throw new IOException("No handshaker response received"); } - return result.get(); } /** Create a new writer if the writer is null. */ @@ -83,7 +89,7 @@ private void createWriterIfNull() { /** Throw exception if there is an outstanding exception. */ private void maybeThrowIoException() throws IOException { if (exceptionMessage.get() != null) { - throw new IOException(exceptionMessage.get()); + throw new IOException(exceptionMessage.get().info, exceptionMessage.get().throwable); } } @@ -102,7 +108,7 @@ public void onNext(HandshakerResp resp) { AltsHandshakerStub.this.responseQueue.add(Optional.of(resp)); } catch (IllegalStateException e) { AltsHandshakerStub.this.exceptionMessage.compareAndSet( - null, "Received an unexpected response."); + null, new ThrowableInfo(e, "Received an unexpected response.")); AltsHandshakerStub.this.close(); } } @@ -111,7 +117,7 @@ public void onNext(HandshakerResp resp) { @Override public void onError(Throwable t) { AltsHandshakerStub.this.exceptionMessage.compareAndSet( - null, "Received a terminating error: " + t.toString()); + null, new ThrowableInfo(t, "Received a terminating error.")); // Trigger the release of any blocked send. Optional result = Optional.absent(); AltsHandshakerStub.this.responseQueue.offer(result); @@ -120,10 +126,22 @@ public void onError(Throwable t) { /** Receive the closing message from the server. */ @Override public void onCompleted() { - AltsHandshakerStub.this.exceptionMessage.compareAndSet(null, "Response stream closed."); + AltsHandshakerStub.this.exceptionMessage.compareAndSet( + null, new ThrowableInfo(null, "Response stream closed.")); // Trigger the release of any blocked send. Optional result = Optional.absent(); AltsHandshakerStub.this.responseQueue.offer(result); } } + + private static class ThrowableInfo { + + private final Throwable throwable; + private final String info; + + private ThrowableInfo(Throwable throwable, String info) { + this.throwable = throwable; + this.info = info; + } + } } diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsProtocolNegotiator.java b/alts/src/main/java/io/grpc/alts/internal/AltsProtocolNegotiator.java index 0ea16248123..9c51cf6a053 100644 --- a/alts/src/main/java/io/grpc/alts/internal/AltsProtocolNegotiator.java +++ b/alts/src/main/java/io/grpc/alts/internal/AltsProtocolNegotiator.java @@ -23,13 +23,13 @@ import com.google.protobuf.Any; import io.grpc.Attributes; import io.grpc.Channel; +import io.grpc.ChannelLogger; import io.grpc.Grpc; import io.grpc.InternalChannelz.OtherSecurity; import io.grpc.InternalChannelz.Security; import io.grpc.SecurityLevel; import io.grpc.Status; import io.grpc.alts.internal.RpcProtocolVersionsUtil.RpcVersionsCheckResult; -import io.grpc.grpclb.GrpclbConstants; import io.grpc.internal.ObjectPool; import io.grpc.netty.GrpcHttp2ConnectionHandler; import io.grpc.netty.InternalProtocolNegotiator; @@ -38,8 +38,11 @@ import io.netty.channel.ChannelHandler; import io.netty.handler.ssl.SslContext; import io.netty.util.AsciiString; +import java.net.URI; +import java.net.URISyntaxException; import java.security.GeneralSecurityException; import java.util.List; +import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; @@ -50,19 +53,28 @@ // TODO(carl-mastrangelo): rename this AltsProtocolNegotiators. public final class AltsProtocolNegotiator { private static final Logger logger = Logger.getLogger(AltsProtocolNegotiator.class.getName()); - // Avoid performing too many handshakes in parallel, as it may cause queuing in the handshake - // server and cause unbounded blocking on the event loop (b/168808426). This is a workaround until - // there is an async TSI handshaking API to avoid the blocking. - private static final AsyncSemaphore handshakeSemaphore = new AsyncSemaphore(32); + + static final String ALTS_MAX_CONCURRENT_HANDSHAKES_ENV_VARIABLE = + "GRPC_ALTS_MAX_CONCURRENT_HANDSHAKES"; + @VisibleForTesting static final int DEFAULT_ALTS_MAX_CONCURRENT_HANDSHAKES = 32; + private static final AsyncSemaphore handshakeSemaphore = + new AsyncSemaphore(getAltsMaxConcurrentHandshakes()); @Grpc.TransportAttr - public static final Attributes.Key TSI_PEER_KEY = Attributes.Key.create("TSI_PEER"); + public static final Attributes.Key TSI_PEER_KEY = + Attributes.Key.create("internal:TSI_PEER"); @Grpc.TransportAttr public static final Attributes.Key AUTH_CONTEXT_KEY = - Attributes.Key.create("AUTH_CONTEXT_KEY"); + Attributes.Key.create("internal:AUTH_CONTEXT_KEY"); private static final AsciiString SCHEME = AsciiString.of("https"); + private static final String DIRECT_PATH_SERVICE_CFE_CLUSTER_PREFIX = "google_cfe_"; + private static final String CFE_CLUSTER_RESOURCE_NAME_PREFIX = + "/envoy.config.cluster.v3.Cluster/google_cfe_"; + private static final String CFE_CLUSTER_AUTHORITY_NAME = + "traffic-director-c2p.xds.googleapis.com"; + /** * ClientAltsProtocolNegotiatorFactory is a factory for doing client side negotiation of an ALTS * channel. @@ -111,12 +123,16 @@ public AsciiString scheme() { @Override public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) { - TsiHandshaker handshaker = handshakerFactory.newHandshaker(grpcHandler.getAuthority()); + ChannelLogger negotiationLogger = grpcHandler.getNegotiationLogger(); + TsiHandshaker handshaker = + handshakerFactory.newHandshaker(grpcHandler.getAuthority(), negotiationLogger); NettyTsiHandshaker nettyHandshaker = new NettyTsiHandshaker(handshaker); ChannelHandler gnh = InternalProtocolNegotiators.grpcNegotiationHandler(grpcHandler); ChannelHandler thh = new TsiHandshakeHandler( - gnh, nettyHandshaker, new AltsHandshakeValidator(), handshakeSemaphore); - ChannelHandler wuah = InternalProtocolNegotiators.waitUntilActiveHandler(thh); + gnh, nettyHandshaker, new AltsHandshakeValidator(), handshakeSemaphore, + negotiationLogger); + ChannelHandler wuah = InternalProtocolNegotiators.waitUntilActiveHandler(thh, + negotiationLogger); return wuah; } @@ -135,11 +151,13 @@ public static ProtocolNegotiator serverAltsProtocolNegotiator( final class ServerTsiHandshakerFactory implements TsiHandshakerFactory { @Override - public TsiHandshaker newHandshaker(@Nullable String authority) { + public TsiHandshaker newHandshaker( + @Nullable String authority, ChannelLogger negotiationLogger) { assert authority == null; return AltsTsiHandshaker.newServer( HandshakerServiceGrpc.newStub(lazyHandshakerChannel.get()), - new AltsHandshakerOptions(RpcProtocolVersionsUtil.getRpcProtocolVersions())); + new AltsHandshakerOptions(RpcProtocolVersionsUtil.getRpcProtocolVersions()), + negotiationLogger); } } @@ -166,12 +184,16 @@ public AsciiString scheme() { @Override public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) { - TsiHandshaker handshaker = handshakerFactory.newHandshaker(/* authority= */ null); + ChannelLogger negotiationLogger = grpcHandler.getNegotiationLogger(); + TsiHandshaker handshaker = + handshakerFactory.newHandshaker(/* authority= */ null, negotiationLogger); NettyTsiHandshaker nettyHandshaker = new NettyTsiHandshaker(handshaker); ChannelHandler gnh = InternalProtocolNegotiators.grpcNegotiationHandler(grpcHandler); ChannelHandler thh = new TsiHandshakeHandler( - gnh, nettyHandshaker, new AltsHandshakeValidator(), handshakeSemaphore); - ChannelHandler wuah = InternalProtocolNegotiators.waitUntilActiveHandler(thh); + gnh, nettyHandshaker, new AltsHandshakeValidator(), handshakeSemaphore, + negotiationLogger); + ChannelHandler wuah = InternalProtocolNegotiators.waitUntilActiveHandler(thh, + negotiationLogger); return wuah; } @@ -187,11 +209,12 @@ public void close() { */ public static final class GoogleDefaultProtocolNegotiatorFactory implements InternalProtocolNegotiator.ClientFactory { + @VisibleForTesting + @Nullable + static Attributes.Key clusterNameAttrKey = loadClusterNameAttrKey(); private final ImmutableList targetServiceAccounts; private final ObjectPool handshakerChannelPool; private final SslContext sslContext; - @Nullable - private final Attributes.Key clusterNameAttrKey; /** * Creates Negotiator Factory, which will either use the targetServiceAccounts and @@ -200,12 +223,10 @@ public static final class GoogleDefaultProtocolNegotiatorFactory public GoogleDefaultProtocolNegotiatorFactory( List targetServiceAccounts, ObjectPool handshakerChannelPool, - SslContext sslContext, - @Nullable Attributes.Key clusterNameAttrKey) { + SslContext sslContext) { this.targetServiceAccounts = ImmutableList.copyOf(targetServiceAccounts); this.handshakerChannelPool = checkNotNull(handshakerChannelPool, "handshakerChannelPool"); this.sslContext = checkNotNull(sslContext, "sslContext"); - this.clusterNameAttrKey = clusterNameAttrKey; } @Override @@ -221,6 +242,26 @@ public ProtocolNegotiator newNegotiator() { public int getDefaultPort() { return 443; } + + @SuppressWarnings("unchecked") + @Nullable + private static Attributes.Key loadClusterNameAttrKey() { + Attributes.Key key = null; + try { + Class klass = Class.forName("io.grpc.xds.InternalXdsAttributes"); + key = (Attributes.Key) klass.getField("ATTR_CLUSTER_NAME").get(null); + } catch (ClassNotFoundException e) { + logger.log(Level.FINE, + "Unable to load xDS endpoint cluster name key, this may be expected", e); + } catch (NoSuchFieldException e) { + logger.log(Level.FINE, + "Unable to load xDS endpoint cluster name key, this may be expected", e); + } catch (IllegalAccessException e) { + logger.log(Level.FINE, + "Unable to load xDS endpoint cluster name key, this may be expected", e); + } + return key; + } } private static final class GoogleDefaultProtocolNegotiator implements ProtocolNegotiator { @@ -250,29 +291,49 @@ public AsciiString scheme() { @Override public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) { ChannelHandler gnh = InternalProtocolNegotiators.grpcNegotiationHandler(grpcHandler); + ChannelLogger negotiationLogger = grpcHandler.getNegotiationLogger(); ChannelHandler securityHandler; boolean isXdsDirectPath = false; if (clusterNameAttrKey != null) { - String clusterName = grpcHandler.getEagAttributes().get(clusterNameAttrKey); - if (clusterName != null && !clusterName.equals("google_cfe")) { - isXdsDirectPath = true; - } + isXdsDirectPath = isDirectPathCluster( + grpcHandler.getEagAttributes().get(clusterNameAttrKey)); } - if (grpcHandler.getEagAttributes().get(GrpclbConstants.ATTR_LB_ADDR_AUTHORITY) != null - || grpcHandler.getEagAttributes().get(GrpclbConstants.ATTR_LB_PROVIDED_BACKEND) != null - || isXdsDirectPath) { - TsiHandshaker handshaker = handshakerFactory.newHandshaker(grpcHandler.getAuthority()); + if (isXdsDirectPath) { + TsiHandshaker handshaker = + handshakerFactory.newHandshaker(grpcHandler.getAuthority(), negotiationLogger); NettyTsiHandshaker nettyHandshaker = new NettyTsiHandshaker(handshaker); securityHandler = new TsiHandshakeHandler( - gnh, nettyHandshaker, new AltsHandshakeValidator(), handshakeSemaphore); + gnh, nettyHandshaker, new AltsHandshakeValidator(), handshakeSemaphore, + negotiationLogger); } else { securityHandler = InternalProtocolNegotiators.clientTlsHandler( - gnh, sslContext, grpcHandler.getAuthority()); + gnh, sslContext, grpcHandler.getAuthority(), negotiationLogger); } - ChannelHandler wuah = InternalProtocolNegotiators.waitUntilActiveHandler(securityHandler); + ChannelHandler wuah = InternalProtocolNegotiators.waitUntilActiveHandler(securityHandler, + negotiationLogger); return wuah; } + private boolean isDirectPathCluster(String clusterName) { + if (clusterName == null) { + return false; + } + if (clusterName.startsWith(DIRECT_PATH_SERVICE_CFE_CLUSTER_PREFIX)) { + return false; + } + if (!clusterName.startsWith("xdstp:")) { + return true; + } + try { + URI uri = new URI(clusterName); + // If authority AND path match our CFE checks, use TLS; otherwise use ALTS. + return !CFE_CLUSTER_AUTHORITY_NAME.equals(uri.getHost()) + || !uri.getPath().startsWith(CFE_CLUSTER_RESOURCE_NAME_PREFIX); + } catch (URISyntaxException e) { + return true; // Shouldn't happen, but assume ALTS. + } + } + @Override public void close() { logger.finest("ALTS Server ProtocolNegotiator Closed"); @@ -292,7 +353,8 @@ private static final class ClientTsiHandshakerFactory implements TsiHandshakerFa } @Override - public TsiHandshaker newHandshaker(@Nullable String authority) { + public TsiHandshaker newHandshaker( + @Nullable String authority, ChannelLogger negotiationLogger) { AltsClientOptions handshakerOptions = new AltsClientOptions.Builder() .setRpcProtocolVersions(RpcProtocolVersionsUtil.getRpcProtocolVersions()) @@ -300,7 +362,9 @@ public TsiHandshaker newHandshaker(@Nullable String authority) { .setTargetName(authority) .build(); return AltsTsiHandshaker.newClient( - HandshakerServiceGrpc.newStub(lazyHandshakerChannel.get()), handshakerOptions); + HandshakerServiceGrpc.newStub(lazyHandshakerChannel.get()), + handshakerOptions, + negotiationLogger); } } @@ -359,5 +423,30 @@ public SecurityDetails validatePeerObject(Object peerObject) throws GeneralSecur } } + @VisibleForTesting + static int getAltsMaxConcurrentHandshakes(String altsMaxConcurrentHandshakes) { + if (altsMaxConcurrentHandshakes == null) { + return DEFAULT_ALTS_MAX_CONCURRENT_HANDSHAKES; + } + try { + int effectiveMaxConcurrentHandshakes = Integer.parseInt(altsMaxConcurrentHandshakes); + if (effectiveMaxConcurrentHandshakes < 0) { + logger.warning( + "GRPC_ALTS_MAX_CONCURRENT_HANDSHAKES environment variable set to invalid value."); + return DEFAULT_ALTS_MAX_CONCURRENT_HANDSHAKES; + } + return effectiveMaxConcurrentHandshakes; + } catch (NumberFormatException e) { + logger.warning( + "GRPC_ALTS_MAX_CONCURRENT_HANDSHAKES environment variable set to invalid value."); + return DEFAULT_ALTS_MAX_CONCURRENT_HANDSHAKES; + } + } + + private static int getAltsMaxConcurrentHandshakes() { + return getAltsMaxConcurrentHandshakes( + System.getenv(ALTS_MAX_CONCURRENT_HANDSHAKES_ENV_VARIABLE)); + } + private AltsProtocolNegotiator() {} } diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsTsiHandshaker.java b/alts/src/main/java/io/grpc/alts/internal/AltsTsiHandshaker.java index cc750a72a7a..2d6c322c1b1 100644 --- a/alts/src/main/java/io/grpc/alts/internal/AltsTsiHandshaker.java +++ b/alts/src/main/java/io/grpc/alts/internal/AltsTsiHandshaker.java @@ -20,6 +20,8 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; +import io.grpc.ChannelLogger; +import io.grpc.ChannelLogger.ChannelLogLevel; import io.grpc.alts.internal.HandshakerServiceGrpc.HandshakerServiceStub; import io.netty.buffer.ByteBufAllocator; import java.nio.Buffer; @@ -27,14 +29,12 @@ import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; /** * Negotiates a grpc channel key to be used by the TsiFrameProtector, using ALTs handshaker service. */ public final class AltsTsiHandshaker implements TsiHandshaker { - private static final Logger logger = Logger.getLogger(AltsTsiHandshaker.class.getName()); + private final ChannelLogger logger; public static final String TSI_SERVICE_ACCOUNT_PEER_PROPERTY = "service_account"; @@ -45,15 +45,20 @@ public final class AltsTsiHandshaker implements TsiHandshaker { /** Starts a new TSI handshaker with client options. */ private AltsTsiHandshaker( - boolean isClient, HandshakerServiceStub stub, AltsHandshakerOptions options) { + boolean isClient, + HandshakerServiceStub stub, + AltsHandshakerOptions options, + ChannelLogger logger) { this.isClient = isClient; - handshaker = new AltsHandshakerClient(stub, options); + this.logger = logger; + handshaker = new AltsHandshakerClient(stub, options, logger); } @VisibleForTesting - AltsTsiHandshaker(boolean isClient, AltsHandshakerClient handshaker) { + AltsTsiHandshaker(boolean isClient, AltsHandshakerClient handshaker, ChannelLogger logger) { this.isClient = isClient; this.handshaker = handshaker; + this.logger = logger; } /** @@ -75,11 +80,12 @@ public boolean processBytesFromPeer(ByteBuffer bytes) throws GeneralSecurityExce return true; } int remaining = bytes.remaining(); - // Call handshaker service to proceess the bytes. + // Call handshaker service to process the bytes. if (outputFrame == null) { checkState(!isClient, "Client handshaker should not process any frame at the beginning."); outputFrame = handshaker.startServerHandshake(bytes); } else { + logger.log(ChannelLogLevel.DEBUG, "Receive ALTS handshake from downstream"); outputFrame = handshaker.next(bytes); } // If handshake has finished or we already have bytes to write, just return true. @@ -124,13 +130,15 @@ public Object extractPeerObject() throws GeneralSecurityException { } /** Creates a new TsiHandshaker for use by the client. */ - public static TsiHandshaker newClient(HandshakerServiceStub stub, AltsHandshakerOptions options) { - return new AltsTsiHandshaker(true, stub, options); + public static TsiHandshaker newClient( + HandshakerServiceStub stub, AltsHandshakerOptions options, ChannelLogger logger) { + return new AltsTsiHandshaker(true, stub, options, logger); } /** Creates a new TsiHandshaker for use by the server. */ - public static TsiHandshaker newServer(HandshakerServiceStub stub, AltsHandshakerOptions options) { - return new AltsTsiHandshaker(false, stub, options); + public static TsiHandshaker newServer( + HandshakerServiceStub stub, AltsHandshakerOptions options, ChannelLogger logger) { + return new AltsTsiHandshaker(false, stub, options, logger); } /** @@ -142,12 +150,14 @@ public static TsiHandshaker newServer(HandshakerServiceStub stub, AltsHandshaker public void getBytesToSendToPeer(ByteBuffer bytes) throws GeneralSecurityException { if (outputFrame == null) { // A null outputFrame indicates we haven't started the handshake. if (isClient) { + logger.log(ChannelLogLevel.DEBUG, "Initial ALTS handshake to downstream"); outputFrame = handshaker.startClientHandshake(); } else { // The server needs bytes to process before it can start the handshake. return; } } + logger.log(ChannelLogLevel.DEBUG, "Send ALTS request to downstream"); // Write as many bytes as we are able. ByteBuffer outputFrameAlias = outputFrame; if (outputFrame.remaining() > bytes.remaining()) { @@ -159,7 +169,7 @@ public void getBytesToSendToPeer(ByteBuffer bytes) throws GeneralSecurityExcepti } /** - * Returns true if and only if the handshake is still in progress + * Returns true if and only if the handshake is still in progress. * * @return true, if the handshake is still in progress, false otherwise. */ @@ -190,7 +200,7 @@ public TsiFrameProtector createFrameProtector(int maxFrameSize, ByteBufAllocator maxFrameSize = Math.min(peerMaxFrameSize, AltsTsiFrameProtector.getMaxFrameSize()); maxFrameSize = Math.max(AltsTsiFrameProtector.getMinFrameSize(), maxFrameSize); } - logger.log(Level.FINE, "Maximum frame size value is {0}.", maxFrameSize); + logger.log(ChannelLogLevel.INFO, "Maximum frame size value is {0}.", maxFrameSize); return new AltsTsiFrameProtector(maxFrameSize, new AltsChannelCrypter(key, isClient), alloc); } diff --git a/alts/src/main/java/io/grpc/alts/internal/AsyncSemaphore.java b/alts/src/main/java/io/grpc/alts/internal/AsyncSemaphore.java index 3ccdcfc763a..a8251c7fbd3 100644 --- a/alts/src/main/java/io/grpc/alts/internal/AsyncSemaphore.java +++ b/alts/src/main/java/io/grpc/alts/internal/AsyncSemaphore.java @@ -16,12 +16,12 @@ package io.grpc.alts.internal; +import com.google.errorprone.annotations.concurrent.GuardedBy; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import java.util.LinkedList; import java.util.Queue; -import javax.annotation.concurrent.GuardedBy; /** Provides a semaphore primitive, without blocking waiting on permits. */ final class AsyncSemaphore { diff --git a/alts/src/main/java/io/grpc/alts/internal/ChannelCrypterNetty.java b/alts/src/main/java/io/grpc/alts/internal/ChannelCrypterNetty.java index 4164560e7a0..e2e7d4046fb 100644 --- a/alts/src/main/java/io/grpc/alts/internal/ChannelCrypterNetty.java +++ b/alts/src/main/java/io/grpc/alts/internal/ChannelCrypterNetty.java @@ -21,8 +21,8 @@ import java.util.List; /** - * A @{code ChannelCrypterNetty} performs stateful encryption and decryption of independent input - * and output streams. Both decrypt and encrypt gather their input from a list of Netty @{link + * A {@code ChannelCrypterNetty} performs stateful encryption and decryption of independent input + * and output streams. Both decrypt and encrypt gather their input from a list of Netty {@link * ByteBuf} instances. * *

Note that we provide implementations of this interface that provide integrity only and diff --git a/alts/src/main/java/io/grpc/alts/internal/NettyTsiHandshaker.java b/alts/src/main/java/io/grpc/alts/internal/NettyTsiHandshaker.java index 5087123ab06..b91cfdad08c 100644 --- a/alts/src/main/java/io/grpc/alts/internal/NettyTsiHandshaker.java +++ b/alts/src/main/java/io/grpc/alts/internal/NettyTsiHandshaker.java @@ -99,7 +99,7 @@ boolean processBytesFromPeer(ByteBuf data) throws GeneralSecurityException { } /** - * Returns true if and only if the handshake is still in progress + * Returns true if and only if the handshake is still in progress. * * @return true, if the handshake is still in progress, false otherwise. */ diff --git a/alts/src/main/java/io/grpc/alts/internal/ProtectedPromise.java b/alts/src/main/java/io/grpc/alts/internal/ProtectedPromise.java index e204acdd5f9..871a51f1bea 100644 --- a/alts/src/main/java/io/grpc/alts/internal/ProtectedPromise.java +++ b/alts/src/main/java/io/grpc/alts/internal/ProtectedPromise.java @@ -78,7 +78,7 @@ public ChannelPromise doneAllocatingPromises() { if (!doneAllocating) { doneAllocating = true; if (successfulCount == expectedCount) { - trySuccessInternal(null); + trySuccessInternal(); return super.setSuccess(null); } } @@ -117,18 +117,18 @@ private boolean awaitingPromises() { } @Override - public ChannelPromise setSuccess(Void result) { - trySuccess(result); + public ChannelPromise setSuccess(Void unused) { + trySuccess(null); return this; } @Override - public boolean trySuccess(Void result) { + public boolean trySuccess(Void unused) { if (awaitingPromises()) { ++successfulCount; if (successfulCount == expectedCount && doneAllocating) { - trySuccessInternal(result); - return super.trySuccess(result); + trySuccessInternal(); + return super.trySuccess(null); } // TODO: We break the interface a bit here. // Multiple success events can be processed without issue because this is an aggregation. @@ -137,9 +137,9 @@ public boolean trySuccess(Void result) { return false; } - private void trySuccessInternal(Void result) { + private void trySuccessInternal() { for (int i = 0; i < unprotectedPromises.size(); ++i) { - unprotectedPromises.get(i).trySuccess(result); + unprotectedPromises.get(i).trySuccess(null); } } diff --git a/alts/src/main/java/io/grpc/alts/internal/TsiHandshakeHandler.java b/alts/src/main/java/io/grpc/alts/internal/TsiHandshakeHandler.java index f2e19d3dedb..7964b122f8c 100644 --- a/alts/src/main/java/io/grpc/alts/internal/TsiHandshakeHandler.java +++ b/alts/src/main/java/io/grpc/alts/internal/TsiHandshakeHandler.java @@ -22,13 +22,13 @@ import static io.grpc.alts.internal.AltsProtocolNegotiator.TSI_PEER_KEY; import io.grpc.Attributes; +import io.grpc.ChannelLogger; import io.grpc.ChannelLogger.ChannelLogLevel; import io.grpc.InternalChannelz.Security; import io.grpc.SecurityLevel; import io.grpc.alts.internal.TsiHandshakeHandler.HandshakeValidator.SecurityDetails; import io.grpc.internal.GrpcAttributes; import io.grpc.netty.InternalProtocolNegotiationEvent; -import io.grpc.netty.InternalProtocolNegotiators; import io.grpc.netty.ProtocolNegotiationEvent; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; @@ -87,13 +87,15 @@ public abstract SecurityDetails validatePeerObject(Object peerObject) private ProtocolNegotiationEvent pne; private boolean semaphoreAcquired; + private final ChannelLogger negotiationLogger; /** * Constructs a TsiHandshakeHandler. */ public TsiHandshakeHandler( - ChannelHandler next, NettyTsiHandshaker handshaker, HandshakeValidator handshakeValidator) { - this(next, handshaker, handshakeValidator, null); + ChannelHandler next, NettyTsiHandshaker handshaker, HandshakeValidator handshakeValidator, + ChannelLogger negotiationLogger) { + this(next, handshaker, handshakeValidator, null, negotiationLogger); } /** @@ -102,11 +104,12 @@ public TsiHandshakeHandler( */ public TsiHandshakeHandler( ChannelHandler next, NettyTsiHandshaker handshaker, HandshakeValidator handshakeValidator, - AsyncSemaphore semaphore) { + AsyncSemaphore semaphore, ChannelLogger negotiationLogger) { this.handshaker = checkNotNull(handshaker, "handshaker"); this.handshakeValidator = checkNotNull(handshakeValidator, "handshakeValidator"); this.next = checkNotNull(next, "next"); this.semaphore = semaphore; + this.negotiationLogger = negotiationLogger; } @Override @@ -155,8 +158,7 @@ public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) thro if (evt instanceof ProtocolNegotiationEvent) { checkState(pne == null, "negotiation already started"); pne = (ProtocolNegotiationEvent) evt; - InternalProtocolNegotiators.negotiationLogger(ctx) - .log(ChannelLogLevel.INFO, "TsiHandshake started"); + negotiationLogger.log(ChannelLogLevel.INFO, "TsiHandshake started"); ChannelFuture acquire = semaphoreAcquire(ctx); if (acquire.isSuccess()) { semaphoreAcquired = true; @@ -190,8 +192,7 @@ public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) thro private void fireProtocolNegotiationEvent( ChannelHandlerContext ctx, TsiPeer peer, Object authContext, SecurityDetails details) { checkState(pne != null, "negotiation not yet complete"); - InternalProtocolNegotiators.negotiationLogger(ctx) - .log(ChannelLogLevel.INFO, "TsiHandshake finished"); + negotiationLogger.log(ChannelLogLevel.INFO, "TsiHandshake finished"); ProtocolNegotiationEvent localPne = pne; Attributes.Builder attrs = InternalProtocolNegotiationEvent.getAttributes(localPne).toBuilder() .set(TSI_PEER_KEY, peer) diff --git a/alts/src/main/java/io/grpc/alts/internal/TsiHandshaker.java b/alts/src/main/java/io/grpc/alts/internal/TsiHandshaker.java index 35b945770d2..6580a4433c7 100644 --- a/alts/src/main/java/io/grpc/alts/internal/TsiHandshaker.java +++ b/alts/src/main/java/io/grpc/alts/internal/TsiHandshaker.java @@ -68,7 +68,7 @@ public interface TsiHandshaker { boolean processBytesFromPeer(ByteBuffer bytes) throws GeneralSecurityException; /** - * Returns true if and only if the handshake is still in progress + * Returns true if and only if the handshake is still in progress. * * @return true, if the handshake is still in progress, false otherwise. */ @@ -86,7 +86,7 @@ public interface TsiHandshaker { * * @return the extracted peer. */ - public Object extractPeerObject() throws GeneralSecurityException; + Object extractPeerObject() throws GeneralSecurityException; /** * Creates a frame protector from a completed handshake. No other methods may be called after the diff --git a/alts/src/main/java/io/grpc/alts/internal/TsiHandshakerFactory.java b/alts/src/main/java/io/grpc/alts/internal/TsiHandshakerFactory.java index 996bd003654..7d17a3954c8 100644 --- a/alts/src/main/java/io/grpc/alts/internal/TsiHandshakerFactory.java +++ b/alts/src/main/java/io/grpc/alts/internal/TsiHandshakerFactory.java @@ -16,11 +16,12 @@ package io.grpc.alts.internal; +import io.grpc.ChannelLogger; import javax.annotation.Nullable; /** Factory that manufactures instances of {@link TsiHandshaker}. */ public interface TsiHandshakerFactory { /** Creates a new handshaker. */ - TsiHandshaker newHandshaker(@Nullable String authority); + TsiHandshaker newHandshaker(@Nullable String authority, ChannelLogger logger); } diff --git a/alts/src/test/java/io/grpc/alts/AltsContextUtilTest.java b/alts/src/test/java/io/grpc/alts/AltsContextUtilTest.java index 6fd2d840d45..675fa29fc99 100644 --- a/alts/src/test/java/io/grpc/alts/AltsContextUtilTest.java +++ b/alts/src/test/java/io/grpc/alts/AltsContextUtilTest.java @@ -24,6 +24,7 @@ import static org.mockito.Mockito.when; import io.grpc.Attributes; +import io.grpc.ClientCall; import io.grpc.ServerCall; import io.grpc.alts.AltsContext.SecurityLevel; import io.grpc.alts.internal.AltsInternalContext; @@ -37,27 +38,38 @@ /** Unit tests for {@link AltsContextUtil}. */ @RunWith(JUnit4.class) public class AltsContextUtilTest { - - private final ServerCall call = mock(ServerCall.class); - @Test public void check_noAttributeValue() { - when(call.getAttributes()).thenReturn(Attributes.newBuilder().build()); + assertFalse(AltsContextUtil.check(Attributes.newBuilder().build())); + } - assertFalse(AltsContextUtil.check(call)); + @Test + public void check_unexpectedAttributeValueType() { + assertFalse(AltsContextUtil.check(Attributes.newBuilder() + .set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new Object()) + .build())); } @Test - public void contains_unexpectedAttributeValueType() { + public void check_altsInternalContext() { + assertTrue(AltsContextUtil.check(Attributes.newBuilder() + .set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, AltsInternalContext.getDefaultInstance()) + .build())); + } + + @Test + public void checkServer_altsInternalContext() { + ServerCall call = mock(ServerCall.class); when(call.getAttributes()).thenReturn(Attributes.newBuilder() - .set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new Object()) + .set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, AltsInternalContext.getDefaultInstance()) .build()); - assertFalse(AltsContextUtil.check(call)); + assertTrue(AltsContextUtil.check(call)); } @Test - public void contains_altsInternalContext() { + public void checkClient_altsInternalContext() { + ClientCall call = mock(ClientCall.class); when(call.getAttributes()).thenReturn(Attributes.newBuilder() .set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, AltsInternalContext.getDefaultInstance()) .build()); @@ -66,26 +78,57 @@ public void contains_altsInternalContext() { } @Test - public void from_altsInternalContext() { + public void createFrom_altsInternalContext() { HandshakerResult handshakerResult = HandshakerResult.newBuilder() .setPeerIdentity(Identity.newBuilder().setServiceAccount("remote@peer")) .setLocalIdentity(Identity.newBuilder().setServiceAccount("local@peer")) .build(); - when(call.getAttributes()).thenReturn(Attributes.newBuilder() - .set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new AltsInternalContext(handshakerResult)) - .build()); - AltsContext context = AltsContextUtil.createFrom(call); + AltsContext context = AltsContextUtil.createFrom(Attributes.newBuilder() + .set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new AltsInternalContext(handshakerResult)) + .build()); assertEquals("remote@peer", context.getPeerServiceAccount()); assertEquals("local@peer", context.getLocalServiceAccount()); assertEquals(SecurityLevel.INTEGRITY_AND_PRIVACY, context.getSecurityLevel()); } @Test(expected = IllegalArgumentException.class) - public void from_noAttributeValue() { - when(call.getAttributes()).thenReturn(Attributes.newBuilder().build()); + public void createFrom_noAttributeValue() { + AltsContextUtil.createFrom(Attributes.newBuilder().build()); + } - AltsContextUtil.createFrom(call); + @Test + public void createFromServer_altsInternalContext() { + HandshakerResult handshakerResult = + HandshakerResult.newBuilder() + .setPeerIdentity(Identity.newBuilder().setServiceAccount("remote@peer")) + .setLocalIdentity(Identity.newBuilder().setServiceAccount("local@peer")) + .build(); + + ServerCall call = mock(ServerCall.class); + when(call.getAttributes()).thenReturn(Attributes.newBuilder() + .set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new AltsInternalContext(handshakerResult)) + .build()); + + AltsContext context = AltsContextUtil.createFrom(call); + assertEquals("remote@peer", context.getPeerServiceAccount()); + } + + @Test + public void createFromClient_altsInternalContext() { + HandshakerResult handshakerResult = + HandshakerResult.newBuilder() + .setPeerIdentity(Identity.newBuilder().setServiceAccount("remote@peer")) + .setLocalIdentity(Identity.newBuilder().setServiceAccount("local@peer")) + .build(); + + ClientCall call = mock(ClientCall.class); + when(call.getAttributes()).thenReturn(Attributes.newBuilder() + .set(AltsProtocolNegotiator.AUTH_CONTEXT_KEY, new AltsInternalContext(handshakerResult)) + .build()); + + AltsContext context = AltsContextUtil.createFrom(call); + assertEquals("remote@peer", context.getPeerServiceAccount()); } } diff --git a/alts/src/test/java/io/grpc/alts/DualCallCredentialsTest.java b/alts/src/test/java/io/grpc/alts/DualCallCredentialsTest.java new file mode 100644 index 00000000000..29646191be1 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/DualCallCredentialsTest.java @@ -0,0 +1,109 @@ +/* + * Copyright 2024 The gRPC 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import io.grpc.Attributes; +import io.grpc.CallCredentials; +import io.grpc.CallCredentials.RequestInfo; +import io.grpc.MethodDescriptor; +import io.grpc.SecurityLevel; +import io.grpc.alts.internal.AltsInternalContext; +import io.grpc.alts.internal.AltsProtocolNegotiator; +import io.grpc.testing.TestMethodDescriptors; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; + +/** Unit tests for {@link DualCallCredentials}. */ +@RunWith(JUnit4.class) +public class DualCallCredentialsTest { + + @Rule public final MockitoRule mocks = MockitoJUnit.rule(); + + @Mock CallCredentials tlsCallCredentials; + + @Mock CallCredentials altsCallCredentials; + + private static final String AUTHORITY = "testauthority"; + private static final SecurityLevel SECURITY_LEVEL = SecurityLevel.PRIVACY_AND_INTEGRITY; + + @Test + public void invokeTlsCallCredentials() { + DualCallCredentials callCredentials = + new DualCallCredentials(tlsCallCredentials, altsCallCredentials); + RequestInfo requestInfo = new RequestInfoImpl(false); + callCredentials.applyRequestMetadata(requestInfo, null, null); + + verify(altsCallCredentials, never()).applyRequestMetadata(any(), any(), any()); + verify(tlsCallCredentials, times(1)).applyRequestMetadata(requestInfo, null, null); + } + + @Test + public void invokeAltsCallCredentials() { + DualCallCredentials callCredentials = + new DualCallCredentials(tlsCallCredentials, altsCallCredentials); + RequestInfo requestInfo = new RequestInfoImpl(true); + callCredentials.applyRequestMetadata(requestInfo, null, null); + + verify(altsCallCredentials, times(1)).applyRequestMetadata(requestInfo, null, null); + verify(tlsCallCredentials, never()).applyRequestMetadata(any(), any(), any()); + } + + private static final class RequestInfoImpl extends CallCredentials.RequestInfo { + private Attributes attrs; + + RequestInfoImpl(boolean hasAltsContext) { + attrs = + hasAltsContext + ? Attributes.newBuilder() + .set( + AltsProtocolNegotiator.AUTH_CONTEXT_KEY, + AltsInternalContext.getDefaultInstance()) + .build() + : Attributes.EMPTY; + } + + @Override + public MethodDescriptor getMethodDescriptor() { + return TestMethodDescriptors.voidMethod(); + } + + @Override + public SecurityLevel getSecurityLevel() { + return SECURITY_LEVEL; + } + + @Override + public String getAuthority() { + return AUTHORITY; + } + + @Override + public Attributes getTransportAttrs() { + return attrs; + } + } +} diff --git a/alts/src/test/java/io/grpc/alts/HandshakerServiceChannelTest.java b/alts/src/test/java/io/grpc/alts/HandshakerServiceChannelTest.java index dc297492fe3..221001157f1 100644 --- a/alts/src/test/java/io/grpc/alts/HandshakerServiceChannelTest.java +++ b/alts/src/test/java/io/grpc/alts/HandshakerServiceChannelTest.java @@ -46,7 +46,7 @@ public void unaryRpc(SimpleRequest request, StreamObserver so) { so.onCompleted(); } }) - .build()); + .build()); private Resource resource; @Before @@ -67,6 +67,24 @@ public void sharedChannel_authority() { } } + @Test + public void getHandshakerTarget_nullEnvVar() { + assertThat(HandshakerServiceChannel.getHandshakerTarget(null)) + .isEqualTo("metadata.google.internal.:8080"); + } + + @Test + public void getHandshakerTarget_envVarWithPort() { + assertThat(HandshakerServiceChannel.getHandshakerTarget("169.254.169.254:80")) + .isEqualTo("169.254.169.254:8080"); + } + + @Test + public void getHandshakerTarget_envVarWithHostOnly() { + assertThat(HandshakerServiceChannel.getHandshakerTarget("169.254.169.254")) + .isEqualTo("169.254.169.254:8080"); + } + @Test public void resource_works() { Channel channel = resource.create(); diff --git a/alts/src/test/java/io/grpc/alts/internal/AesGcmHkdfAeadCrypterTest.java b/alts/src/test/java/io/grpc/alts/internal/AesGcmHkdfAeadCrypterTest.java index d655a6e8358..06f2ff5365f 100644 --- a/alts/src/test/java/io/grpc/alts/internal/AesGcmHkdfAeadCrypterTest.java +++ b/alts/src/test/java/io/grpc/alts/internal/AesGcmHkdfAeadCrypterTest.java @@ -117,7 +117,7 @@ public void testVectorEncrypt() throws GeneralSecurityException { ByteBuffer.wrap(testVector.plaintext), ByteBuffer.wrap(testVector.aad), testVector.nonce); - String msg = "Failure for test vector " + i; + String msg = "Failure for test vector " + i + " " + testVector.comment; assertWithMessage(msg) .that(ciphertextBuffer.remaining()) .isEqualTo(bufferSize - testVector.ciphertext.length); @@ -142,7 +142,7 @@ public void testVectorDecrypt() throws GeneralSecurityException { ByteBuffer.wrap(testVector.ciphertext), ByteBuffer.wrap(testVector.aad), testVector.nonce); - String msg = "Failure for test vector " + i; + String msg = "Failure for test vector " + i + " " + testVector.comment; assertWithMessage(msg) .that(plaintextBuffer.remaining()) .isEqualTo(bufferSize - testVector.plaintext.length); diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerClientTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerClientTest.java index 27ad16ee2d3..5a41fc0fc4f 100644 --- a/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerClientTest.java +++ b/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerClientTest.java @@ -29,6 +29,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.ByteString; +import io.grpc.internal.TestUtils.NoopChannelLogger; import java.nio.Buffer; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; @@ -60,7 +61,8 @@ public void setUp() { .setTargetName(TEST_TARGET_NAME) .setTargetServiceAccounts(ImmutableList.of(TEST_TARGET_SERVICE_ACCOUNT)) .build(); - handshaker = new AltsHandshakerClient(mockStub, clientOptions); + NoopChannelLogger channelLogger = new NoopChannelLogger(); + handshaker = new AltsHandshakerClient(mockStub, clientOptions, channelLogger); } @Test @@ -266,7 +268,8 @@ public void setRpcVersions() throws Exception { .setTargetServiceAccounts(ImmutableList.of(TEST_TARGET_SERVICE_ACCOUNT)) .setRpcProtocolVersions(rpcVersions) .build(); - handshaker = new AltsHandshakerClient(mockStub, clientOptions); + NoopChannelLogger channelLogger = new NoopChannelLogger(); + handshaker = new AltsHandshakerClient(mockStub, clientOptions, channelLogger); handshaker.startClientHandshake(); diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerStubTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerStubTest.java index 2267a765a90..7a6018b5064 100644 --- a/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerStubTest.java +++ b/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerStubTest.java @@ -32,7 +32,7 @@ @RunWith(JUnit4.class) public class AltsHandshakerStubTest { /** Mock status of handshaker service. */ - private static enum Status { + private enum Status { OK, ERROR, COMPLETE @@ -68,6 +68,7 @@ private void sendAndExpectError() throws InterruptedException { fail("Exception expected"); } catch (IOException ex) { assertThat(ex).hasMessageThat().contains("Received a terminating error"); + assertThat(ex.getCause()).hasMessageThat().contains("Root cause message"); } } @@ -152,7 +153,7 @@ public void onNext(final HandshakerReq req) { reader.onNext(resp.setOutFrames(req.getNext().getInBytes()).build()); break; case ERROR: - reader.onError(new RuntimeException()); + reader.onError(new RuntimeException("Root cause message")); break; case COMPLETE: reader.onCompleted(); diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsProtocolNegotiatorTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsProtocolNegotiatorTest.java index 3cc8c9c3ff7..d47607ed90f 100644 --- a/alts/src/test/java/io/grpc/alts/internal/AltsProtocolNegotiatorTest.java +++ b/alts/src/test/java/io/grpc/alts/internal/AltsProtocolNegotiatorTest.java @@ -26,6 +26,7 @@ import io.grpc.Attributes; import io.grpc.Channel; +import io.grpc.ChannelLogger; import io.grpc.Grpc; import io.grpc.InternalChannelz; import io.grpc.ManagedChannel; @@ -37,6 +38,7 @@ import io.grpc.internal.FixedObjectPool; import io.grpc.internal.GrpcAttributes; import io.grpc.internal.ObjectPool; +import io.grpc.internal.TestUtils.NoopChannelLogger; import io.grpc.netty.GrpcHttp2ConnectionHandler; import io.grpc.netty.InternalProtocolNegotiationEvent; import io.grpc.netty.NettyChannelBuilder; @@ -130,8 +132,8 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E TsiHandshakerFactory handshakerFactory = new DelegatingTsiHandshakerFactory(FakeTsiHandshaker.clientHandshakerFactory()) { @Override - public TsiHandshaker newHandshaker(String authority) { - return new DelegatingTsiHandshaker(super.newHandshaker(authority)) { + public TsiHandshaker newHandshaker(String authority, ChannelLogger logger) { + return new DelegatingTsiHandshaker(super.newHandshaker(authority, logger)) { @Override public TsiPeer extractPeer() throws GeneralSecurityException { return mockedTsiPeer; @@ -200,8 +202,11 @@ public void operationComplete(ChannelFuture future) throws Exception { channel.flush(); // Capture the protected data written to the wire. - assertEquals(1, channel.outboundMessages().size()); - ByteBuf protectedData = channel.readOutbound(); + assertThat(channel.outboundMessages()).isNotEmpty(); + ByteBuf protectedData = channel.alloc().buffer(); + while (!channel.outboundMessages().isEmpty()) { + protectedData.writeBytes((ByteBuf) channel.readOutbound()); + } assertEquals(message.length(), writeCount.get()); // Read the protected message at the server and verify it matches the original message. @@ -325,16 +330,18 @@ public void doNotFlushEmptyBuffer() throws Exception { String message = "hello"; ByteBuf in = Unpooled.copiedBuffer(message, UTF_8); - assertEquals(0, protector.flushes.get()); + int flushes = protector.flushes.get(); Future done = channel.write(in); channel.flush(); + flushes++; done.get(5, TimeUnit.SECONDS); - assertEquals(1, protector.flushes.get()); + assertEquals(flushes, protector.flushes.get()); + // Flush does not propagate done = channel.write(Unpooled.EMPTY_BUFFER); channel.flush(); done.get(5, TimeUnit.SECONDS); - assertEquals(1, protector.flushes.get()); + assertEquals(flushes, protector.flushes.get()); } @Test @@ -352,6 +359,29 @@ public void peerPropagated() throws Exception { .isEqualTo(SecurityLevel.PRIVACY_AND_INTEGRITY); } + @Test + public void getAltsMaxConcurrentHandshakes_success() throws Exception { + assertThat(AltsProtocolNegotiator.getAltsMaxConcurrentHandshakes("10")).isEqualTo(10); + } + + @Test + public void getAltsMaxConcurrentHandshakes_envVariableNotSet() throws Exception { + assertThat(AltsProtocolNegotiator.getAltsMaxConcurrentHandshakes(null)) + .isEqualTo(AltsProtocolNegotiator.DEFAULT_ALTS_MAX_CONCURRENT_HANDSHAKES); + } + + @Test + public void getAltsMaxConcurrentHandshakes_envVariableNotANumber() throws Exception { + assertThat(AltsProtocolNegotiator.getAltsMaxConcurrentHandshakes("not-a-number")) + .isEqualTo(AltsProtocolNegotiator.DEFAULT_ALTS_MAX_CONCURRENT_HANDSHAKES); + } + + @Test + public void getAltsMaxConcurrentHandshakes_envVariableNegative() throws Exception { + assertThat(AltsProtocolNegotiator.getAltsMaxConcurrentHandshakes("-10")) + .isEqualTo(AltsProtocolNegotiator.DEFAULT_ALTS_MAX_CONCURRENT_HANDSHAKES); + } + private void doHandshake() throws Exception { // Capture the client frame and add to the server. assertEquals(1, channel.outboundMessages().size()); @@ -404,7 +434,7 @@ private CapturingGrpcHttp2ConnectionHandler( Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder, Http2Settings initialSettings) { - super(null, decoder, encoder, initialSettings); + super(null, decoder, encoder, initialSettings, new NoopChannelLogger()); } @Override @@ -426,8 +456,8 @@ private static class DelegatingTsiHandshakerFactory implements TsiHandshakerFact } @Override - public TsiHandshaker newHandshaker(String authority) { - return delegate.newHandshaker(authority); + public TsiHandshaker newHandshaker(String authority, ChannelLogger logger) { + return delegate.newHandshaker(authority, logger); } } diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsTsiHandshakerTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsTsiHandshakerTest.java index b0b2f8f9faa..ae1696401be 100644 --- a/alts/src/test/java/io/grpc/alts/internal/AltsTsiHandshakerTest.java +++ b/alts/src/test/java/io/grpc/alts/internal/AltsTsiHandshakerTest.java @@ -26,6 +26,7 @@ import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; +import io.grpc.internal.TestUtils.NoopChannelLogger; import java.nio.Buffer; import java.nio.ByteBuffer; import org.junit.Before; @@ -71,8 +72,9 @@ public class AltsTsiHandshakerTest { public void setUp() throws Exception { mockClient = mock(AltsHandshakerClient.class); mockServer = mock(AltsHandshakerClient.class); - handshakerClient = new AltsTsiHandshaker(true, mockClient); - handshakerServer = new AltsTsiHandshaker(false, mockServer); + NoopChannelLogger channelLogger = new NoopChannelLogger(); + handshakerClient = new AltsTsiHandshaker(true, mockClient, channelLogger); + handshakerServer = new AltsTsiHandshaker(false, mockServer, channelLogger); } private HandshakerResult getHandshakerResult(boolean isClient) { diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsTsiTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsTsiTest.java index a6832ad8de2..cb39abb9ddc 100644 --- a/alts/src/test/java/io/grpc/alts/internal/AltsTsiTest.java +++ b/alts/src/test/java/io/grpc/alts/internal/AltsTsiTest.java @@ -21,6 +21,7 @@ import com.google.common.testing.GcFinalization; import io.grpc.alts.internal.ByteBufTestUtils.RegisterRef; import io.grpc.alts.internal.TsiTest.Handshakers; +import io.grpc.internal.TestUtils.NoopChannelLogger; import io.netty.buffer.ByteBuf; import io.netty.util.ReferenceCounted; import io.netty.util.ResourceLeakDetector; @@ -61,8 +62,9 @@ public void setUp() throws Exception { AltsHandshakerOptions handshakerOptions = new AltsHandshakerOptions(null); MockAltsHandshakerStub clientStub = new MockAltsHandshakerStub(); MockAltsHandshakerStub serverStub = new MockAltsHandshakerStub(); - client = new AltsHandshakerClient(clientStub, handshakerOptions); - server = new AltsHandshakerClient(serverStub, handshakerOptions); + NoopChannelLogger channelLogger = new NoopChannelLogger(); + client = new AltsHandshakerClient(clientStub, handshakerOptions, channelLogger); + server = new AltsHandshakerClient(serverStub, handshakerOptions, channelLogger); } @After @@ -76,8 +78,9 @@ public void tearDown() { } private Handshakers newHandshakers() { - TsiHandshaker clientHandshaker = new AltsTsiHandshaker(true, client); - TsiHandshaker serverHandshaker = new AltsTsiHandshaker(false, server); + NoopChannelLogger channelLogger = new NoopChannelLogger(); + TsiHandshaker clientHandshaker = new AltsTsiHandshaker(true, client, channelLogger); + TsiHandshaker serverHandshaker = new AltsTsiHandshaker(false, server, channelLogger); return new Handshakers(clientHandshaker, serverHandshaker); } diff --git a/alts/src/test/java/io/grpc/alts/internal/FakeTsiHandshaker.java b/alts/src/test/java/io/grpc/alts/internal/FakeTsiHandshaker.java index fcc33681732..7a6119dc0be 100644 --- a/alts/src/test/java/io/grpc/alts/internal/FakeTsiHandshaker.java +++ b/alts/src/test/java/io/grpc/alts/internal/FakeTsiHandshaker.java @@ -19,7 +19,9 @@ import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.base.Preconditions; +import io.grpc.ChannelLogger; import io.grpc.alts.internal.TsiPeer.Property; +import io.grpc.internal.TestUtils.NoopChannelLogger; import io.netty.buffer.ByteBufAllocator; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; @@ -37,7 +39,7 @@ public class FakeTsiHandshaker implements TsiHandshaker { private static final TsiHandshakerFactory clientHandshakerFactory = new TsiHandshakerFactory() { @Override - public TsiHandshaker newHandshaker(String authority) { + public TsiHandshaker newHandshaker(String authority, ChannelLogger logger) { return new FakeTsiHandshaker(true); } }; @@ -45,7 +47,7 @@ public TsiHandshaker newHandshaker(String authority) { private static final TsiHandshakerFactory serverHandshakerFactory = new TsiHandshakerFactory() { @Override - public TsiHandshaker newHandshaker(String authority) { + public TsiHandshaker newHandshaker(String authority, ChannelLogger logger) { return new FakeTsiHandshaker(false); } }; @@ -66,6 +68,7 @@ enum State { SERVER_FINISHED; // Returns the next State. In order to advance to sendState=N, receiveState must be N-1. + @SuppressWarnings("EnumOrdinal") public State next() { if (ordinal() + 1 < values().length) { return values()[ordinal() + 1]; @@ -83,11 +86,13 @@ public static TsiHandshakerFactory serverHandshakerFactory() { } public static TsiHandshaker newFakeHandshakerClient() { - return clientHandshakerFactory.newHandshaker(null); + NoopChannelLogger channelLogger = new NoopChannelLogger(); + return clientHandshakerFactory.newHandshaker(null, channelLogger); } public static TsiHandshaker newFakeHandshakerServer() { - return serverHandshakerFactory.newHandshaker(null); + NoopChannelLogger channelLogger = new NoopChannelLogger(); + return serverHandshakerFactory.newHandshaker(null, channelLogger); } protected FakeTsiHandshaker(boolean isClient) { @@ -143,7 +148,7 @@ public void getBytesToSendToPeer(ByteBuffer bytes) throws GeneralSecurityExcepti return; } - // Prepare the next message, if neeeded. + // Prepare the next message, if needed. if (sendBuffer == null) { if (sendState.next() != receiveState) { // We're still waiting for bytes from the peer, so bail. diff --git a/alts/src/test/java/io/grpc/alts/internal/GoogleDefaultProtocolNegotiatorTest.java b/alts/src/test/java/io/grpc/alts/internal/GoogleDefaultProtocolNegotiatorTest.java index 5ac2669b3ab..14c19e554ae 100644 --- a/alts/src/test/java/io/grpc/alts/internal/GoogleDefaultProtocolNegotiatorTest.java +++ b/alts/src/test/java/io/grpc/alts/internal/GoogleDefaultProtocolNegotiatorTest.java @@ -17,14 +17,18 @@ package io.grpc.alts.internal; import static com.google.common.truth.Truth.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableList; import io.grpc.Attributes; import io.grpc.Channel; +import io.grpc.ChannelLogger; +import io.grpc.ChannelLogger.ChannelLogLevel; import io.grpc.ManagedChannel; -import io.grpc.grpclb.GrpclbConstants; import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.internal.ObjectPool; import io.grpc.netty.GrpcHttp2ConnectionHandler; @@ -51,6 +55,7 @@ public final class GoogleDefaultProtocolNegotiatorTest { @RunWith(JUnit4.class) public abstract static class HandlerSelectionTest { private ProtocolNegotiator googleProtocolNegotiator; + private Attributes.Key originalClusterNameAttrKey; private final ObjectPool handshakerChannelPool = new ObjectPool() { @Override @@ -68,30 +73,27 @@ public Channel returnObject(Object object) { @Before public void setUp() throws Exception { SslContext sslContext = GrpcSslContexts.forClient().build(); - + originalClusterNameAttrKey = + AltsProtocolNegotiator.GoogleDefaultProtocolNegotiatorFactory.clusterNameAttrKey; + AltsProtocolNegotiator.GoogleDefaultProtocolNegotiatorFactory.clusterNameAttrKey = + getClusterNameAttrKey(); googleProtocolNegotiator = new AltsProtocolNegotiator.GoogleDefaultProtocolNegotiatorFactory( ImmutableList.of(), handshakerChannelPool, - sslContext, - getClusterNameAttrKey()) + sslContext) .newNegotiator(); } @After public void tearDown() { googleProtocolNegotiator.close(); + AltsProtocolNegotiator.GoogleDefaultProtocolNegotiatorFactory.clusterNameAttrKey = + originalClusterNameAttrKey; } @Nullable abstract Attributes.Key getClusterNameAttrKey(); - @Test - public void altsHandler_lbProvidedBackend() { - Attributes attrs = - Attributes.newBuilder().set(GrpclbConstants.ATTR_LB_PROVIDED_BACKEND, true).build(); - subtest_altsHandler(attrs); - } - @Test public void tlsHandler_emptyAttributes() { subtest_tlsHandler(Attributes.EMPTY); @@ -100,6 +102,9 @@ public void tlsHandler_emptyAttributes() { void subtest_altsHandler(Attributes eagAttributes) { GrpcHttp2ConnectionHandler mockHandler = mock(GrpcHttp2ConnectionHandler.class); when(mockHandler.getEagAttributes()).thenReturn(eagAttributes); + ChannelLogger logger = mock(ChannelLogger.class); + doNothing().when(logger).log(any(ChannelLogLevel.class), anyString()); + when(mockHandler.getNegotiationLogger()).thenReturn(logger); final AtomicReference failure = new AtomicReference<>(); ChannelHandler exceptionCaught = new ChannelInboundHandlerAdapter() { @@ -125,6 +130,9 @@ void subtest_tlsHandler(Attributes eagAttributes) { GrpcHttp2ConnectionHandler mockHandler = mock(GrpcHttp2ConnectionHandler.class); when(mockHandler.getEagAttributes()).thenReturn(eagAttributes); when(mockHandler.getAuthority()).thenReturn("authority"); + ChannelLogger logger = mock(ChannelLogger.class); + doNothing().when(logger).log(any(ChannelLogLevel.class), anyString()); + when(mockHandler.getNegotiationLogger()).thenReturn(logger); ChannelHandler h = googleProtocolNegotiator.newHandler(mockHandler); EmbeddedChannel chan = new EmbeddedChannel(h); @@ -165,9 +173,51 @@ public void altsHandler_xdsCluster() { @Test public void tlsHandler_googleCfe() { - Attributes attrs = - Attributes.newBuilder().set(XDS_CLUSTER_NAME_ATTR_KEY, "google_cfe").build(); + Attributes attrs = Attributes.newBuilder().set( + XDS_CLUSTER_NAME_ATTR_KEY, "google_cfe_api.googleapis.com").build(); subtest_tlsHandler(attrs); } + + @Test + public void altsHandler_googleCfe_federation() { + Attributes attrs = Attributes.newBuilder().set( + XDS_CLUSTER_NAME_ATTR_KEY, "xdstp1://").build(); + subtest_altsHandler(attrs); + } + + @Test + public void tlsHanlder_googleCfe() { + Attributes attrs = Attributes.newBuilder().set( + XDS_CLUSTER_NAME_ATTR_KEY, + "xdstp://traffic-director-c2p.xds.googleapis.com/" + + "envoy.config.cluster.v3.Cluster/google_cfe_example/apis") + .build(); + subtest_tlsHandler(attrs); + } + + @Test + public void altsHanlder_nonGoogleCfe_authorityNotMatch() { + Attributes attrs = Attributes.newBuilder().set( + XDS_CLUSTER_NAME_ATTR_KEY, + "//example.com/envoy.config.cluster.v3.Cluster/google_cfe_") + .build(); + subtest_altsHandler(attrs); + } + + @Test + public void altsHanlder_nonGoogleCfe_pathNotMatch() { + Attributes attrs = Attributes.newBuilder().set( + XDS_CLUSTER_NAME_ATTR_KEY, + "//traffic-director-c2p.xds.googleapis.com/envoy.config.cluster.v3.Cluster/google_gfe") + .build(); + subtest_altsHandler(attrs); + } + + @Test + public void altsHandler_googleCfe_invalidUri() { + Attributes attrs = Attributes.newBuilder().set( + XDS_CLUSTER_NAME_ATTR_KEY, "//").build(); + subtest_altsHandler(attrs); + } } } diff --git a/alts/src/test/java/io/grpc/alts/internal/TsiTest.java b/alts/src/test/java/io/grpc/alts/internal/TsiTest.java index f677a44a754..0241182f2db 100644 --- a/alts/src/test/java/io/grpc/alts/internal/TsiTest.java +++ b/alts/src/test/java/io/grpc/alts/internal/TsiTest.java @@ -34,13 +34,13 @@ import java.util.List; import javax.crypto.AEADBadTagException; -/** Utility class that provides tests for implementations of @{link TsiHandshaker}. */ +/** Utility class that provides tests for implementations of {@link TsiHandshaker}. */ public final class TsiTest { - private static final String DECRYPTION_FAILURE_RE = "Tag mismatch!|BAD_DECRYPT"; + private static final String DECRYPTION_FAILURE_RE = "Tag mismatch|BAD_DECRYPT"; private TsiTest() {} - /** A @{code TsiHandshaker} pair for running tests. */ + /** A {@code TsiHandshaker} pair for running tests. */ public static class Handshakers { private final TsiHandshaker client; private final TsiHandshaker server; diff --git a/android-interop-testing/build.gradle b/android-interop-testing/build.gradle index 91e75fcfad8..b61d50a6763 100644 --- a/android-interop-testing/build.gradle +++ b/android-interop-testing/build.gradle @@ -7,10 +7,10 @@ description = 'gRPC: Android Integration Testing' repositories { google() - jcenter() } android { + namespace = 'io.grpc.android.integrationtest' sourceSets { main { java { @@ -25,16 +25,19 @@ android { } } } - compileSdkVersion 26 + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + compileSdkVersion 34 defaultConfig { applicationId "io.grpc.android.integrationtest" - minSdkVersion 16 - targetSdkVersion 26 + minSdkVersion 23 + targetSdkVersion 33 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - multiDexEnabled true } buildTypes { debug { minifyEnabled false } @@ -43,33 +46,42 @@ android { proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } - lintOptions { disable 'InvalidPackage', 'HardcodedText' } + lintOptions { + disable 'InvalidPackage', 'HardcodedText', 'UsingOnClickInXml', + 'MissingClass' // https://github.com/grpc/grpc-java/issues/8799 + } + packagingOptions { + exclude 'META-INF/INDEX.LIST' + exclude 'META-INF/io.netty.versions.properties' + } } dependencies { - implementation 'com.android.support:appcompat-v7:26.1.0' - implementation 'com.android.support:multidex:1.0.3' - implementation 'com.android.support:support-annotations:26.1.0' - implementation 'com.google.android.gms:play-services-base:16.1.0' + implementation 'androidx.appcompat:appcompat:1.3.0' + implementation libraries.androidx.annotation + implementation 'com.google.android.gms:play-services-base:18.0.1' - implementation project(':grpc-auth'), + implementation project(':grpc-android'), + project(':grpc-api'), + project(':grpc-core'), project(':grpc-census'), project(':grpc-okhttp'), project(':grpc-protobuf-lite'), project(':grpc-stub'), project(':grpc-testing'), libraries.junit, - libraries.truth + libraries.truth, + libraries.androidx.test.rules, + libraries.androidx.test.core, + libraries.opencensus.contrib.grpc.metrics - implementation (libraries.google_auth_oauth2_http) { - exclude group: 'org.apache.httpcomponents' + implementation (project(':grpc-services')) { + exclude group: 'com.google.protobuf' + exclude group: 'com.google.guava' } - censusGrpcMetricDependency 'implementation' - compileOnly libraries.javax_annotation - - androidTestImplementation 'androidx.test:rules:1.1.0-alpha1' - androidTestImplementation 'androidx.test:runner:1.1.0-alpha1' + androidTestImplementation libraries.androidx.test.ext.junit, + libraries.androidx.test.runner } // Checkstyle doesn't run automatically with android @@ -89,13 +101,46 @@ project.tasks['check'].dependsOn checkStyleMain, checkStyleTest import net.ltgt.gradle.errorprone.CheckSeverity -tasks.withType(JavaCompile) { +tasks.withType(JavaCompile).configureEach { options.compilerArgs += [ - "-Xlint:-cast" + "-Xlint:-cast", ] appendToProperty(it.options.errorprone.excludedPaths, ".*/R.java", "|") - // Reuses source code from grpc-interop-testing, which targets Java 7 (no method references) - options.errorprone.check("UnnecessaryAnonymousClass", CheckSeverity.OFF) + appendToProperty( + it.options.errorprone.excludedPaths, + ".*/src/generated/.*", + "|") +} + +// Workaround error seen with Gradle 8.14.3 and AGP 7.4.1 when building: +// ./gradlew clean :grpc-android-interop-testing:build -PskipAndroid=false \ +// -Pandroid.useAndroidX=true --no-build-cache +// +// Error message: +// +// Execution failed for task ':grpc-android-interop-testing:mergeExtDexDebug'. +// > Could not resolve all files for configuration ':grpc-android-interop-testing:debugRuntimeClasspath'. +// > Failed to transform opencensus-contrib-grpc-metrics-0.31.1.jar (io.opencensus:opencensus-contrib-grpc-metrics:0.31.1) to match attributes {artifactType=android-dex, asm-transformed-variant=NONE, dexing-enable-desugaring=true, dexing-enable-jacoco-instrumentation=false, dexing-is-debuggable=true, dexing-min-sdk=23, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}. +// > Could not resolve all files for configuration ':grpc-android-interop-testing:debugRuntimeClasspath'. +// > Failed to transform grpc-api-1.81.0-SNAPSHOT.jar (project :grpc-api) to match attributes {artifactType=android-classes-jar, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.jvm.version=8, org.gradle.libraryelements=jar, org.gradle.usage=java-runtime}. +// > Execution failed for IdentityTransform: grpc-java/api/build/libs/grpc-api-1.81.0-SNAPSHOT.jar. +// > File/directory does not exist: grpc-java/api/build/libs/grpc-api-1.81.0-SNAPSHOT.jar +tasks.configureEach { task -> + if (task.name.equals("mergeExtDexDebug")) { + dependsOn(':grpc-api:jar') + } +} + +afterEvaluate { + // Hack to workaround "Task ':grpc-android-interop-testing:extractIncludeDebugProto' uses this + // output of task ':grpc-context:jar' without declaring an explicit or implicit dependency." The + // issue started when grpc-context became empty. + tasks.named('extractIncludeDebugProto').configure { + dependsOn project(':grpc-context').tasks.named('jar') + } + tasks.named('extractIncludeReleaseProto').configure { + dependsOn project(':grpc-context').tasks.named('jar') + } } configureProtoCompilation() diff --git a/android-interop-testing/proguard-rules.pro b/android-interop-testing/proguard-rules.pro index 8af80352076..a9e696958b9 100644 --- a/android-interop-testing/proguard-rules.pro +++ b/android-interop-testing/proguard-rules.pro @@ -21,3 +21,7 @@ # Ignores: can't find referenced method from grpc-testing's compileOnly dependency on Truth -dontwarn io.grpc.testing.DeadlineSubject + +-keepclassmembers class io.grpc.testing.integration.Messages$* { + *; +} \ No newline at end of file diff --git a/android-interop-testing/src/androidTest/AndroidManifest.xml b/android-interop-testing/src/androidTest/AndroidManifest.xml index 916a1c04332..3cc0a29a85f 100644 --- a/android-interop-testing/src/androidTest/AndroidManifest.xml +++ b/android-interop-testing/src/androidTest/AndroidManifest.xml @@ -1,13 +1,11 @@ - + - - + diff --git a/android-interop-testing/src/androidTest/java/io/grpc/android/integrationtest/InteropInstrumentationTest.java b/android-interop-testing/src/androidTest/java/io/grpc/android/integrationtest/InteropInstrumentationTest.java index e6a2c85fda5..a5870063a87 100644 --- a/android-interop-testing/src/androidTest/java/io/grpc/android/integrationtest/InteropInstrumentationTest.java +++ b/android-interop-testing/src/androidTest/java/io/grpc/android/integrationtest/InteropInstrumentationTest.java @@ -16,21 +16,22 @@ package io.grpc.android.integrationtest; -import static junit.framework.Assert.assertEquals; +import static org.junit.Assert.assertEquals; import android.util.Log; -import androidx.test.InstrumentationRegistry; -import androidx.test.rule.ActivityTestRule; -import androidx.test.runner.AndroidJUnit4; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.security.ProviderInstaller; -import com.google.common.util.concurrent.SettableFuture; -import io.grpc.android.integrationtest.InteropTask.Listener; import java.io.InputStream; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -45,12 +46,7 @@ public class InteropInstrumentationTest { private String serverHostOverride; private boolean useTestCa; private String testCase; - - // Ensures Looper is initialized for tests running on API level 15. Otherwise instantiating an - // AsyncTask throws an exception. - @Rule - public ActivityTestRule activityRule = - new ActivityTestRule(TesterActivity.class); + private ExecutorService executor = Executors.newSingleThreadExecutor(); @Before public void setUp() throws Exception { @@ -67,7 +63,7 @@ public void setUp() throws Exception { if (useTls) { try { - ProviderInstaller.installIfNeeded(InstrumentationRegistry.getTargetContext()); + ProviderInstaller.installIfNeeded(ApplicationProvider.getApplicationContext()); } catch (GooglePlayServicesRepairableException e) { // The provider is helpful, but it is possible to succeed without it. // Hope that the system-provided libraries are new enough. @@ -108,26 +104,22 @@ public void interopTests() throws Exception { } private void runTest(String testCase) throws Exception { - final SettableFuture resultFuture = SettableFuture.create(); - InteropTask.Listener listener = - new Listener() { - @Override - public void onComplete(String result) { - resultFuture.set(result); - } - }; InputStream testCa; if (useTestCa) { - testCa = InstrumentationRegistry.getTargetContext().getResources().openRawResource(R.raw.ca); + testCa = ApplicationProvider.getApplicationContext().getResources().openRawResource(R.raw.ca); } else { testCa = null; } - new InteropTask( - listener, - TesterOkHttpChannelBuilder.build(host, port, serverHostOverride, useTls, testCa), - testCase) - .execute(); - String result = resultFuture.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - assertEquals(testCase + " failed", InteropTask.SUCCESS_MESSAGE, result); + + String result = null; + try { + result = executor.submit(new TestCallable( + TesterOkHttpChannelBuilder.build(host, port, serverHostOverride, useTls, testCa), + testCase)).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (ExecutionException | InterruptedException | TimeoutException e) { + Log.e(LOG_TAG, "Error while executing test case " + testCase, e); + result = e.getMessage(); + } + assertEquals(testCase + " failed", TestCallable.SUCCESS_MESSAGE, result); } } diff --git a/android-interop-testing/src/androidTest/java/io/grpc/android/integrationtest/UdsChannelInteropTest.java b/android-interop-testing/src/androidTest/java/io/grpc/android/integrationtest/UdsChannelInteropTest.java new file mode 100644 index 00000000000..5b98665ba29 --- /dev/null +++ b/android-interop-testing/src/androidTest/java/io/grpc/android/integrationtest/UdsChannelInteropTest.java @@ -0,0 +1,129 @@ +/* + * Copyright 2021 The gRPC 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.android.integrationtest; + +import static org.junit.Assert.assertEquals; + +import android.net.LocalSocketAddress.Namespace; +import androidx.test.ext.junit.rules.ActivityScenarioRule; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; +import io.grpc.Grpc; +import io.grpc.InsecureServerCredentials; +import io.grpc.Server; +import io.grpc.android.UdsChannelBuilder; +import io.grpc.testing.integration.TestServiceImpl; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** + * Tests for channels created with {@link UdsChannelBuilder}. The UDS Channel is only meant to talk + * to Unix Domain Socket endpoints on servers that are on-device, so a {@link LocalTestServer} is + * set up to expose a UDS endpoint. + */ +@RunWith(AndroidJUnit4.class) +public class UdsChannelInteropTest { + private static final int TIMEOUT_SECONDS = 150; + + private static final String UDS_PATH = "udspath"; + private String testCase; + + private Server server; + private UdsTcpEndpointConnector endpointConnector; + + private ScheduledExecutorService serverExecutor = Executors.newScheduledThreadPool(2); + private ExecutorService testExecutor = Executors.newSingleThreadExecutor(); + + // Ensures Looper is initialized for tests running on API level 15. Otherwise instantiating an + // AsyncTask throws an exception. + @Rule + public ActivityScenarioRule activityRule = + new ActivityScenarioRule<>(TesterActivity.class); + + @Before + public void setUp() throws IOException { + testCase = InstrumentationRegistry.getArguments().getString("test_case", "all"); + + // Start local server. + server = + Grpc.newServerBuilderForPort(0, InsecureServerCredentials.create()) + .maxInboundMessageSize(16 * 1024 * 1024) + .addService(new TestServiceImpl(serverExecutor)) + .build(); + server.start(); + + // Connect uds endpoint to server's endpoint. + endpointConnector = new UdsTcpEndpointConnector(UDS_PATH, "0.0.0.0", server.getPort()); + endpointConnector.start(); + } + + @After + public void teardown() { + server.shutdownNow(); + endpointConnector.shutDown(); + } + + @Test + public void interopTests() throws Exception { + if (testCase.equals("all")) { + runTest("empty_unary"); + runTest("large_unary"); + runTest("client_streaming"); + runTest("server_streaming"); + runTest("ping_pong"); + runTest("empty_stream"); + runTest("cancel_after_begin"); + runTest("cancel_after_first_response"); + runTest("full_duplex_call_should_succeed"); + runTest("half_duplex_call_should_succeed"); + runTest("server_streaming_should_be_flow_controlled"); + runTest("very_large_request"); + runTest("very_large_response"); + runTest("deadline_not_exceeded"); + runTest("deadline_exceeded"); + runTest("deadline_exceeded_server_streaming"); + runTest("unimplemented_method"); + runTest("timeout_on_sleeping_server"); + runTest("graceful_shutdown"); + } else { + runTest(testCase); + } + } + + private void runTest(String testCase) throws Exception { + String result = null; + try { + result = testExecutor.submit(new TestCallable( + UdsChannelBuilder.forPath(UDS_PATH, Namespace.ABSTRACT) + .maxInboundMessageSize(16 * 1024 * 1024) + .build(), + testCase)).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertEquals(testCase + " failed", TestCallable.SUCCESS_MESSAGE, result); + } catch (ExecutionException | InterruptedException e) { + result = e.getMessage(); + } + } +} diff --git a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/LoadBalancerStatsServiceGrpc.java b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/LoadBalancerStatsServiceGrpc.java index a685679a2e8..33b914bb4b3 100644 --- a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/LoadBalancerStatsServiceGrpc.java +++ b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/LoadBalancerStatsServiceGrpc.java @@ -7,14 +7,12 @@ * A service used to obtain stats for verifying LB behavior. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class LoadBalancerStatsServiceGrpc { private LoadBalancerStatsServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.LoadBalancerStatsService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.LoadBalancerStatsService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public LoadBalancerStatsServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new LoadBalancerStatsServiceBlockingV2Stub(channel, callOptions); + } + }; + return LoadBalancerStatsServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -126,14 +139,14 @@ public LoadBalancerStatsServiceFutureStub newStub(io.grpc.Channel channel, io.gr * A service used to obtain stats for verifying LB behavior. * */ - public static abstract class LoadBalancerStatsServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** *

      * Gets the backend distribution for RPCs sent by a test client.
      * 
*/ - public void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request, + default void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetClientStatsMethod(), responseObserver); } @@ -143,37 +156,34 @@ public void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStat * Gets the accumulated stats for RPCs sent by a test client. * */ - public void getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request, + default void getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetClientAccumulatedStatsMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service LoadBalancerStatsService. + *
+   * A service used to obtain stats for verifying LB behavior.
+   * 
+ */ + public static abstract class LoadBalancerStatsServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getGetClientStatsMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.LoadBalancerStatsRequest, - io.grpc.testing.integration.Messages.LoadBalancerStatsResponse>( - this, METHODID_GET_CLIENT_STATS))) - .addMethod( - getGetClientAccumulatedStatsMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest, - io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse>( - this, METHODID_GET_CLIENT_ACCUMULATED_STATS))) - .build(); + return LoadBalancerStatsServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service LoadBalancerStatsService. *
    * A service used to obtain stats for verifying LB behavior.
    * 
*/ - public static final class LoadBalancerStatsServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class LoadBalancerStatsServiceStub + extends io.grpc.stub.AbstractAsyncStub { private LoadBalancerStatsServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -209,11 +219,53 @@ public void getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadB } /** + * A stub to allow clients to do synchronous rpc calls to service LoadBalancerStatsService. *
    * A service used to obtain stats for verifying LB behavior.
    * 
*/ - public static final class LoadBalancerStatsServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class LoadBalancerStatsServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private LoadBalancerStatsServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected LoadBalancerStatsServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new LoadBalancerStatsServiceBlockingV2Stub(channel, callOptions); + } + + /** + *
+     * Gets the backend distribution for RPCs sent by a test client.
+     * 
+ */ + public io.grpc.testing.integration.Messages.LoadBalancerStatsResponse getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getGetClientStatsMethod(), getCallOptions(), request); + } + + /** + *
+     * Gets the accumulated stats for RPCs sent by a test client.
+     * 
+ */ + public io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getGetClientAccumulatedStatsMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service LoadBalancerStatsService. + *
+   * A service used to obtain stats for verifying LB behavior.
+   * 
+ */ + public static final class LoadBalancerStatsServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private LoadBalancerStatsServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -247,11 +299,13 @@ public io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service LoadBalancerStatsService. *
    * A service used to obtain stats for verifying LB behavior.
    * 
*/ - public static final class LoadBalancerStatsServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class LoadBalancerStatsServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private LoadBalancerStatsServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -294,10 +348,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final LoadBalancerStatsServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(LoadBalancerStatsServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -330,6 +384,25 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getGetClientStatsMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.LoadBalancerStatsRequest, + io.grpc.testing.integration.Messages.LoadBalancerStatsResponse>( + service, METHODID_GET_CLIENT_STATS))) + .addMethod( + getGetClientAccumulatedStatsMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest, + io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse>( + service, METHODID_GET_CLIENT_ACCUMULATED_STATS))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/MetricsServiceGrpc.java b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/MetricsServiceGrpc.java index 66cf6267be6..c99abcff7cb 100644 --- a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/MetricsServiceGrpc.java +++ b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/MetricsServiceGrpc.java @@ -4,14 +4,12 @@ /** */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/metrics.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class MetricsServiceGrpc { private MetricsServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.MetricsService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.MetricsService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public MetricsServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new MetricsServiceBlockingV2Stub(channel, callOptions); + } + }; + return MetricsServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -120,7 +133,7 @@ public MetricsServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOpt /** */ - public static abstract class MetricsServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** *
@@ -128,7 +141,7 @@ public static abstract class MetricsServiceImplBase implements io.grpc.BindableS
      * the service
      * 
*/ - public void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request, + default void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetAllGaugesMethod(), responseObserver); } @@ -138,34 +151,28 @@ public void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage reques * Returns the value of one gauge * */ - public void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request, + default void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetGaugeMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service MetricsService. + */ + public static abstract class MetricsServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getGetAllGaugesMethod(), - io.grpc.stub.ServerCalls.asyncServerStreamingCall( - new MethodHandlers< - io.grpc.testing.integration.Metrics.EmptyMessage, - io.grpc.testing.integration.Metrics.GaugeResponse>( - this, METHODID_GET_ALL_GAUGES))) - .addMethod( - getGetGaugeMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Metrics.GaugeRequest, - io.grpc.testing.integration.Metrics.GaugeResponse>( - this, METHODID_GET_GAUGE))) - .build(); + return MetricsServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service MetricsService. */ - public static final class MetricsServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class MetricsServiceStub + extends io.grpc.stub.AbstractAsyncStub { private MetricsServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -202,8 +209,50 @@ public void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request, } /** + * A stub to allow clients to do synchronous rpc calls to service MetricsService. + */ + public static final class MetricsServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private MetricsServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected MetricsServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new MetricsServiceBlockingV2Stub(channel, callOptions); + } + + /** + *
+     * Returns the values of all the gauges that are currently being maintained by
+     * the service
+     * 
+ */ + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918") + public io.grpc.stub.BlockingClientCall + getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request) { + return io.grpc.stub.ClientCalls.blockingV2ServerStreamingCall( + getChannel(), getGetAllGaugesMethod(), getCallOptions(), request); + } + + /** + *
+     * Returns the value of one gauge
+     * 
+ */ + public io.grpc.testing.integration.Metrics.GaugeResponse getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getGetGaugeMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service MetricsService. */ - public static final class MetricsServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class MetricsServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private MetricsServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -239,8 +288,10 @@ public io.grpc.testing.integration.Metrics.GaugeResponse getGauge(io.grpc.testin } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service MetricsService. */ - public static final class MetricsServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class MetricsServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private MetricsServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -272,10 +323,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final MetricsServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(MetricsServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -308,6 +359,25 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getGetAllGaugesMethod(), + io.grpc.stub.ServerCalls.asyncServerStreamingCall( + new MethodHandlers< + io.grpc.testing.integration.Metrics.EmptyMessage, + io.grpc.testing.integration.Metrics.GaugeResponse>( + service, METHODID_GET_ALL_GAUGES))) + .addMethod( + getGetGaugeMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Metrics.GaugeRequest, + io.grpc.testing.integration.Metrics.GaugeResponse>( + service, METHODID_GET_GAUGE))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/ReconnectServiceGrpc.java b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/ReconnectServiceGrpc.java index 32e8e5e40d1..fffcaad2df2 100644 --- a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/ReconnectServiceGrpc.java +++ b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/ReconnectServiceGrpc.java @@ -7,37 +7,35 @@ * A service used to control reconnect server. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class ReconnectServiceGrpc { private ReconnectServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.ReconnectService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.ReconnectService"; // Static method descriptors that strictly reflect the proto. - private static volatile io.grpc.MethodDescriptor getStartMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "Start", - requestType = io.grpc.testing.integration.EmptyProtos.Empty.class, + requestType = io.grpc.testing.integration.Messages.ReconnectParams.class, responseType = io.grpc.testing.integration.EmptyProtos.Empty.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) - public static io.grpc.MethodDescriptor getStartMethod() { - io.grpc.MethodDescriptor getStartMethod; + io.grpc.MethodDescriptor getStartMethod; if ((getStartMethod = ReconnectServiceGrpc.getStartMethod) == null) { synchronized (ReconnectServiceGrpc.class) { if ((getStartMethod = ReconnectServiceGrpc.getStartMethod) == null) { ReconnectServiceGrpc.getStartMethod = getStartMethod = - io.grpc.MethodDescriptor.newBuilder() + io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "Start")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller( - io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance())) + io.grpc.testing.integration.Messages.ReconnectParams.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller( io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance())) .build(); @@ -91,6 +89,21 @@ public ReconnectServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions return ReconnectServiceStub.newStub(factory, channel); } + /** + * Creates a new blocking-style stub that supports all types of calls on the service + */ + public static ReconnectServiceBlockingV2Stub newBlockingV2Stub( + io.grpc.Channel channel) { + io.grpc.stub.AbstractStub.StubFactory factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public ReconnectServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new ReconnectServiceBlockingV2Stub(channel, callOptions); + } + }; + return ReconnectServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -126,48 +139,45 @@ public ReconnectServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallO * A service used to control reconnect server. * */ - public static abstract class ReconnectServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** */ - public void start(io.grpc.testing.integration.EmptyProtos.Empty request, + default void start(io.grpc.testing.integration.Messages.ReconnectParams request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getStartMethod(), responseObserver); } /** */ - public void stop(io.grpc.testing.integration.EmptyProtos.Empty request, + default void stop(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getStopMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service ReconnectService. + *
+   * A service used to control reconnect server.
+   * 
+ */ + public static abstract class ReconnectServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getStartMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_START))) - .addMethod( - getStopMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.Messages.ReconnectInfo>( - this, METHODID_STOP))) - .build(); + return ReconnectServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service ReconnectService. *
    * A service used to control reconnect server.
    * 
*/ - public static final class ReconnectServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class ReconnectServiceStub + extends io.grpc.stub.AbstractAsyncStub { private ReconnectServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -181,7 +191,7 @@ protected ReconnectServiceStub build( /** */ - public void start(io.grpc.testing.integration.EmptyProtos.Empty request, + public void start(io.grpc.testing.integration.Messages.ReconnectParams request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getStartMethod(), getCallOptions()), request, responseObserver); @@ -197,11 +207,47 @@ public void stop(io.grpc.testing.integration.EmptyProtos.Empty request, } /** + * A stub to allow clients to do synchronous rpc calls to service ReconnectService. *
    * A service used to control reconnect server.
    * 
*/ - public static final class ReconnectServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class ReconnectServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private ReconnectServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected ReconnectServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new ReconnectServiceBlockingV2Stub(channel, callOptions); + } + + /** + */ + public io.grpc.testing.integration.EmptyProtos.Empty start(io.grpc.testing.integration.Messages.ReconnectParams request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getStartMethod(), getCallOptions(), request); + } + + /** + */ + public io.grpc.testing.integration.Messages.ReconnectInfo stop(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getStopMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service ReconnectService. + *
+   * A service used to control reconnect server.
+   * 
+ */ + public static final class ReconnectServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private ReconnectServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -215,7 +261,7 @@ protected ReconnectServiceBlockingStub build( /** */ - public io.grpc.testing.integration.EmptyProtos.Empty start(io.grpc.testing.integration.EmptyProtos.Empty request) { + public io.grpc.testing.integration.EmptyProtos.Empty start(io.grpc.testing.integration.Messages.ReconnectParams request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getStartMethod(), getCallOptions(), request); } @@ -229,11 +275,13 @@ public io.grpc.testing.integration.Messages.ReconnectInfo stop(io.grpc.testing.i } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service ReconnectService. *
    * A service used to control reconnect server.
    * 
*/ - public static final class ReconnectServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class ReconnectServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private ReconnectServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -248,7 +296,7 @@ protected ReconnectServiceFutureStub build( /** */ public com.google.common.util.concurrent.ListenableFuture start( - io.grpc.testing.integration.EmptyProtos.Empty request) { + io.grpc.testing.integration.Messages.ReconnectParams request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getStartMethod(), getCallOptions()), request); } @@ -270,10 +318,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final ReconnectServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(ReconnectServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -283,7 +331,7 @@ private static final class MethodHandlers implements public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { case METHODID_START: - serviceImpl.start((io.grpc.testing.integration.EmptyProtos.Empty) request, + serviceImpl.start((io.grpc.testing.integration.Messages.ReconnectParams) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_STOP: @@ -306,6 +354,25 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getStartMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.ReconnectParams, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_START))) + .addMethod( + getStopMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.Messages.ReconnectInfo>( + service, METHODID_STOP))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/TestServiceGrpc.java b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/TestServiceGrpc.java index 5f767f314c8..1d7805e3a3f 100644 --- a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/TestServiceGrpc.java +++ b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/TestServiceGrpc.java @@ -8,14 +8,12 @@ * performance with various types of payload. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class TestServiceGrpc { private TestServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.TestService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.TestService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public TestServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new TestServiceBlockingV2Stub(channel, callOptions); + } + }; + return TestServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -308,14 +321,14 @@ public TestServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOption * performance with various types of payload. * */ - public static abstract class TestServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** *
      * One empty request followed by one empty response.
      * 
*/ - public void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request, + default void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getEmptyCallMethod(), responseObserver); } @@ -325,7 +338,7 @@ public void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request, * One request followed by one response. * */ - public void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request, + default void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnaryCallMethod(), responseObserver); } @@ -337,7 +350,7 @@ public void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request * satisfy subsequent requests. * */ - public void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request, + default void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getCacheableUnaryCallMethod(), responseObserver); } @@ -348,7 +361,7 @@ public void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleReques * The server returns the payload with client desired type and sizes. * */ - public void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request, + default void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getStreamingOutputCallMethod(), responseObserver); } @@ -359,7 +372,7 @@ public void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOu * The server returns the aggregated size of client payload as the result. * */ - public io.grpc.stub.StreamObserver streamingInputCall( + default io.grpc.stub.StreamObserver streamingInputCall( io.grpc.stub.StreamObserver responseObserver) { return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getStreamingInputCallMethod(), responseObserver); } @@ -371,7 +384,7 @@ public io.grpc.stub.StreamObserver */ - public io.grpc.stub.StreamObserver fullDuplexCall( + default io.grpc.stub.StreamObserver fullDuplexCall( io.grpc.stub.StreamObserver responseObserver) { return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getFullDuplexCallMethod(), responseObserver); } @@ -384,7 +397,7 @@ public io.grpc.stub.StreamObserver */ - public io.grpc.stub.StreamObserver halfDuplexCall( + default io.grpc.stub.StreamObserver halfDuplexCall( io.grpc.stub.StreamObserver responseObserver) { return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getHalfDuplexCallMethod(), responseObserver); } @@ -395,80 +408,36 @@ public io.grpc.stub.StreamObserver */ - public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request, + default void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service TestService. + *
+   * A simple service to test the various types of RPCs and experiment with
+   * performance with various types of payload.
+   * 
+ */ + public static abstract class TestServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getEmptyCallMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_EMPTY_CALL))) - .addMethod( - getUnaryCallMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.SimpleRequest, - io.grpc.testing.integration.Messages.SimpleResponse>( - this, METHODID_UNARY_CALL))) - .addMethod( - getCacheableUnaryCallMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.SimpleRequest, - io.grpc.testing.integration.Messages.SimpleResponse>( - this, METHODID_CACHEABLE_UNARY_CALL))) - .addMethod( - getStreamingOutputCallMethod(), - io.grpc.stub.ServerCalls.asyncServerStreamingCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.StreamingOutputCallRequest, - io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( - this, METHODID_STREAMING_OUTPUT_CALL))) - .addMethod( - getStreamingInputCallMethod(), - io.grpc.stub.ServerCalls.asyncClientStreamingCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.StreamingInputCallRequest, - io.grpc.testing.integration.Messages.StreamingInputCallResponse>( - this, METHODID_STREAMING_INPUT_CALL))) - .addMethod( - getFullDuplexCallMethod(), - io.grpc.stub.ServerCalls.asyncBidiStreamingCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.StreamingOutputCallRequest, - io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( - this, METHODID_FULL_DUPLEX_CALL))) - .addMethod( - getHalfDuplexCallMethod(), - io.grpc.stub.ServerCalls.asyncBidiStreamingCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.StreamingOutputCallRequest, - io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( - this, METHODID_HALF_DUPLEX_CALL))) - .addMethod( - getUnimplementedCallMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_UNIMPLEMENTED_CALL))) - .build(); + return TestServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service TestService. *
    * A simple service to test the various types of RPCs and experiment with
    * performance with various types of payload.
    * 
*/ - public static final class TestServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class TestServiceStub + extends io.grpc.stub.AbstractAsyncStub { private TestServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -580,12 +549,133 @@ public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty requ } /** + * A stub to allow clients to do synchronous rpc calls to service TestService. + *
+   * A simple service to test the various types of RPCs and experiment with
+   * performance with various types of payload.
+   * 
+ */ + public static final class TestServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private TestServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected TestServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new TestServiceBlockingV2Stub(channel, callOptions); + } + + /** + *
+     * One empty request followed by one empty response.
+     * 
+ */ + public io.grpc.testing.integration.EmptyProtos.Empty emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getEmptyCallMethod(), getCallOptions(), request); + } + + /** + *
+     * One request followed by one response.
+     * 
+ */ + public io.grpc.testing.integration.Messages.SimpleResponse unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getUnaryCallMethod(), getCallOptions(), request); + } + + /** + *
+     * One request followed by one response. Response has cache control
+     * headers set such that a caching HTTP proxy (such as GFE) can
+     * satisfy subsequent requests.
+     * 
+ */ + public io.grpc.testing.integration.Messages.SimpleResponse cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getCacheableUnaryCallMethod(), getCallOptions(), request); + } + + /** + *
+     * One request followed by a sequence of responses (streamed download).
+     * The server returns the payload with client desired type and sizes.
+     * 
+ */ + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918") + public io.grpc.stub.BlockingClientCall + streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request) { + return io.grpc.stub.ClientCalls.blockingV2ServerStreamingCall( + getChannel(), getStreamingOutputCallMethod(), getCallOptions(), request); + } + + /** + *
+     * A sequence of requests followed by one response (streamed upload).
+     * The server returns the aggregated size of client payload as the result.
+     * 
+ */ + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918") + public io.grpc.stub.BlockingClientCall + streamingInputCall() { + return io.grpc.stub.ClientCalls.blockingClientStreamingCall( + getChannel(), getStreamingInputCallMethod(), getCallOptions()); + } + + /** + *
+     * A sequence of requests with each request served by the server immediately.
+     * As one request could lead to multiple responses, this interface
+     * demonstrates the idea of full duplexing.
+     * 
+ */ + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918") + public io.grpc.stub.BlockingClientCall + fullDuplexCall() { + return io.grpc.stub.ClientCalls.blockingBidiStreamingCall( + getChannel(), getFullDuplexCallMethod(), getCallOptions()); + } + + /** + *
+     * A sequence of requests followed by a sequence of responses.
+     * The server buffers all the client requests and then serves them in order. A
+     * stream of responses are returned to the client when the server starts with
+     * first request.
+     * 
+ */ + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918") + public io.grpc.stub.BlockingClientCall + halfDuplexCall() { + return io.grpc.stub.ClientCalls.blockingBidiStreamingCall( + getChannel(), getHalfDuplexCallMethod(), getCallOptions()); + } + + /** + *
+     * The test server will not implement this method. It will be used
+     * to test the behavior when clients call unimplemented methods.
+     * 
+ */ + public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getUnimplementedCallMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service TestService. *
    * A simple service to test the various types of RPCs and experiment with
    * performance with various types of payload.
    * 
*/ - public static final class TestServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class TestServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private TestServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -654,12 +744,14 @@ public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.t } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service TestService. *
    * A simple service to test the various types of RPCs and experiment with
    * performance with various types of payload.
    * 
*/ - public static final class TestServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class TestServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private TestServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -733,10 +825,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final TestServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(TestServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -790,6 +882,67 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getEmptyCallMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_EMPTY_CALL))) + .addMethod( + getUnaryCallMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.SimpleRequest, + io.grpc.testing.integration.Messages.SimpleResponse>( + service, METHODID_UNARY_CALL))) + .addMethod( + getCacheableUnaryCallMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.SimpleRequest, + io.grpc.testing.integration.Messages.SimpleResponse>( + service, METHODID_CACHEABLE_UNARY_CALL))) + .addMethod( + getStreamingOutputCallMethod(), + io.grpc.stub.ServerCalls.asyncServerStreamingCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.StreamingOutputCallRequest, + io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( + service, METHODID_STREAMING_OUTPUT_CALL))) + .addMethod( + getStreamingInputCallMethod(), + io.grpc.stub.ServerCalls.asyncClientStreamingCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.StreamingInputCallRequest, + io.grpc.testing.integration.Messages.StreamingInputCallResponse>( + service, METHODID_STREAMING_INPUT_CALL))) + .addMethod( + getFullDuplexCallMethod(), + io.grpc.stub.ServerCalls.asyncBidiStreamingCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.StreamingOutputCallRequest, + io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( + service, METHODID_FULL_DUPLEX_CALL))) + .addMethod( + getHalfDuplexCallMethod(), + io.grpc.stub.ServerCalls.asyncBidiStreamingCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.StreamingOutputCallRequest, + io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( + service, METHODID_HALF_DUPLEX_CALL))) + .addMethod( + getUnimplementedCallMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_UNIMPLEMENTED_CALL))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/UnimplementedServiceGrpc.java b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/UnimplementedServiceGrpc.java index 26870496f49..bec9b5a723a 100644 --- a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/UnimplementedServiceGrpc.java +++ b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/UnimplementedServiceGrpc.java @@ -8,14 +8,12 @@ * that case. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class UnimplementedServiceGrpc { private UnimplementedServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.UnimplementedService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.UnimplementedService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public UnimplementedServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new UnimplementedServiceBlockingV2Stub(channel, callOptions); + } + }; + return UnimplementedServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -98,38 +111,43 @@ public UnimplementedServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.C * that case. * */ - public static abstract class UnimplementedServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** *
      * A call that no server should implement
      * 
*/ - public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request, + default void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service UnimplementedService. + *
+   * A simple service NOT implemented at servers so clients can test for
+   * that case.
+   * 
+ */ + public static abstract class UnimplementedServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getUnimplementedCallMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_UNIMPLEMENTED_CALL))) - .build(); + return UnimplementedServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service UnimplementedService. *
    * A simple service NOT implemented at servers so clients can test for
    * that case.
    * 
*/ - public static final class UnimplementedServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class UnimplementedServiceStub + extends io.grpc.stub.AbstractAsyncStub { private UnimplementedServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -154,12 +172,45 @@ public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty requ } /** + * A stub to allow clients to do synchronous rpc calls to service UnimplementedService. + *
+   * A simple service NOT implemented at servers so clients can test for
+   * that case.
+   * 
+ */ + public static final class UnimplementedServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private UnimplementedServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected UnimplementedServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new UnimplementedServiceBlockingV2Stub(channel, callOptions); + } + + /** + *
+     * A call that no server should implement
+     * 
+ */ + public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getUnimplementedCallMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service UnimplementedService. *
    * A simple service NOT implemented at servers so clients can test for
    * that case.
    * 
*/ - public static final class UnimplementedServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class UnimplementedServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private UnimplementedServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -183,12 +234,14 @@ public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.t } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service UnimplementedService. *
    * A simple service NOT implemented at servers so clients can test for
    * that case.
    * 
*/ - public static final class UnimplementedServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class UnimplementedServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private UnimplementedServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -219,10 +272,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final UnimplementedServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(UnimplementedServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -251,6 +304,18 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getUnimplementedCallMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_UNIMPLEMENTED_CALL))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateClientConfigureServiceGrpc.java b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateClientConfigureServiceGrpc.java index 47293f3b172..3453b6c01be 100644 --- a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateClientConfigureServiceGrpc.java +++ b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateClientConfigureServiceGrpc.java @@ -7,14 +7,12 @@ * A service to dynamically update the configuration of an xDS test client. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class XdsUpdateClientConfigureServiceGrpc { private XdsUpdateClientConfigureServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.XdsUpdateClientConfigureService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.XdsUpdateClientConfigureService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public XdsUpdateClientConfigureServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new XdsUpdateClientConfigureServiceBlockingV2Stub(channel, callOptions); + } + }; + return XdsUpdateClientConfigureServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -96,37 +109,41 @@ public XdsUpdateClientConfigureServiceFutureStub newStub(io.grpc.Channel channel * A service to dynamically update the configuration of an xDS test client. * */ - public static abstract class XdsUpdateClientConfigureServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** *
      * Update the tes client's configuration.
      * 
*/ - public void configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request, + default void configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getConfigureMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service XdsUpdateClientConfigureService. + *
+   * A service to dynamically update the configuration of an xDS test client.
+   * 
+ */ + public static abstract class XdsUpdateClientConfigureServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getConfigureMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.ClientConfigureRequest, - io.grpc.testing.integration.Messages.ClientConfigureResponse>( - this, METHODID_CONFIGURE))) - .build(); + return XdsUpdateClientConfigureServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service XdsUpdateClientConfigureService. *
    * A service to dynamically update the configuration of an xDS test client.
    * 
*/ - public static final class XdsUpdateClientConfigureServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class XdsUpdateClientConfigureServiceStub + extends io.grpc.stub.AbstractAsyncStub { private XdsUpdateClientConfigureServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -151,11 +168,43 @@ public void configure(io.grpc.testing.integration.Messages.ClientConfigureReques } /** + * A stub to allow clients to do synchronous rpc calls to service XdsUpdateClientConfigureService. + *
+   * A service to dynamically update the configuration of an xDS test client.
+   * 
+ */ + public static final class XdsUpdateClientConfigureServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private XdsUpdateClientConfigureServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected XdsUpdateClientConfigureServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new XdsUpdateClientConfigureServiceBlockingV2Stub(channel, callOptions); + } + + /** + *
+     * Update the tes client's configuration.
+     * 
+ */ + public io.grpc.testing.integration.Messages.ClientConfigureResponse configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getConfigureMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service XdsUpdateClientConfigureService. *
    * A service to dynamically update the configuration of an xDS test client.
    * 
*/ - public static final class XdsUpdateClientConfigureServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class XdsUpdateClientConfigureServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private XdsUpdateClientConfigureServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -179,11 +228,13 @@ public io.grpc.testing.integration.Messages.ClientConfigureResponse configure(io } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service XdsUpdateClientConfigureService. *
    * A service to dynamically update the configuration of an xDS test client.
    * 
*/ - public static final class XdsUpdateClientConfigureServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class XdsUpdateClientConfigureServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private XdsUpdateClientConfigureServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -214,10 +265,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final XdsUpdateClientConfigureServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(XdsUpdateClientConfigureServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -246,6 +297,18 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getConfigureMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.ClientConfigureRequest, + io.grpc.testing.integration.Messages.ClientConfigureResponse>( + service, METHODID_CONFIGURE))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateHealthServiceGrpc.java b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateHealthServiceGrpc.java index 3ee2e416431..fb5f2cdebc7 100644 --- a/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateHealthServiceGrpc.java +++ b/android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateHealthServiceGrpc.java @@ -7,14 +7,12 @@ * A service to remotely control health status of an xDS test server. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class XdsUpdateHealthServiceGrpc { private XdsUpdateHealthServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.XdsUpdateHealthService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.XdsUpdateHealthService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public XdsUpdateHealthServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new XdsUpdateHealthServiceBlockingV2Stub(channel, callOptions); + } + }; + return XdsUpdateHealthServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -126,48 +139,45 @@ public XdsUpdateHealthServiceFutureStub newStub(io.grpc.Channel channel, io.grpc * A service to remotely control health status of an xDS test server. * */ - public static abstract class XdsUpdateHealthServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** */ - public void setServing(io.grpc.testing.integration.EmptyProtos.Empty request, + default void setServing(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSetServingMethod(), responseObserver); } /** */ - public void setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request, + default void setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSetNotServingMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service XdsUpdateHealthService. + *
+   * A service to remotely control health status of an xDS test server.
+   * 
+ */ + public static abstract class XdsUpdateHealthServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getSetServingMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_SET_SERVING))) - .addMethod( - getSetNotServingMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_SET_NOT_SERVING))) - .build(); + return XdsUpdateHealthServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service XdsUpdateHealthService. *
    * A service to remotely control health status of an xDS test server.
    * 
*/ - public static final class XdsUpdateHealthServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class XdsUpdateHealthServiceStub + extends io.grpc.stub.AbstractAsyncStub { private XdsUpdateHealthServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -197,11 +207,47 @@ public void setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request, } /** + * A stub to allow clients to do synchronous rpc calls to service XdsUpdateHealthService. *
    * A service to remotely control health status of an xDS test server.
    * 
*/ - public static final class XdsUpdateHealthServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class XdsUpdateHealthServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private XdsUpdateHealthServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected XdsUpdateHealthServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new XdsUpdateHealthServiceBlockingV2Stub(channel, callOptions); + } + + /** + */ + public io.grpc.testing.integration.EmptyProtos.Empty setServing(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getSetServingMethod(), getCallOptions(), request); + } + + /** + */ + public io.grpc.testing.integration.EmptyProtos.Empty setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getSetNotServingMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service XdsUpdateHealthService. + *
+   * A service to remotely control health status of an xDS test server.
+   * 
+ */ + public static final class XdsUpdateHealthServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private XdsUpdateHealthServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -229,11 +275,13 @@ public io.grpc.testing.integration.EmptyProtos.Empty setNotServing(io.grpc.testi } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service XdsUpdateHealthService. *
    * A service to remotely control health status of an xDS test server.
    * 
*/ - public static final class XdsUpdateHealthServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class XdsUpdateHealthServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private XdsUpdateHealthServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -270,10 +318,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final XdsUpdateHealthServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(XdsUpdateHealthServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -306,6 +354,25 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getSetServingMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_SET_SERVING))) + .addMethod( + getSetNotServingMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_SET_NOT_SERVING))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/LoadBalancerStatsServiceGrpc.java b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/LoadBalancerStatsServiceGrpc.java index a685679a2e8..33b914bb4b3 100644 --- a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/LoadBalancerStatsServiceGrpc.java +++ b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/LoadBalancerStatsServiceGrpc.java @@ -7,14 +7,12 @@ * A service used to obtain stats for verifying LB behavior. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class LoadBalancerStatsServiceGrpc { private LoadBalancerStatsServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.LoadBalancerStatsService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.LoadBalancerStatsService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public LoadBalancerStatsServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new LoadBalancerStatsServiceBlockingV2Stub(channel, callOptions); + } + }; + return LoadBalancerStatsServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -126,14 +139,14 @@ public LoadBalancerStatsServiceFutureStub newStub(io.grpc.Channel channel, io.gr * A service used to obtain stats for verifying LB behavior. * */ - public static abstract class LoadBalancerStatsServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** *
      * Gets the backend distribution for RPCs sent by a test client.
      * 
*/ - public void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request, + default void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetClientStatsMethod(), responseObserver); } @@ -143,37 +156,34 @@ public void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStat * Gets the accumulated stats for RPCs sent by a test client. * */ - public void getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request, + default void getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetClientAccumulatedStatsMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service LoadBalancerStatsService. + *
+   * A service used to obtain stats for verifying LB behavior.
+   * 
+ */ + public static abstract class LoadBalancerStatsServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getGetClientStatsMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.LoadBalancerStatsRequest, - io.grpc.testing.integration.Messages.LoadBalancerStatsResponse>( - this, METHODID_GET_CLIENT_STATS))) - .addMethod( - getGetClientAccumulatedStatsMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest, - io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse>( - this, METHODID_GET_CLIENT_ACCUMULATED_STATS))) - .build(); + return LoadBalancerStatsServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service LoadBalancerStatsService. *
    * A service used to obtain stats for verifying LB behavior.
    * 
*/ - public static final class LoadBalancerStatsServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class LoadBalancerStatsServiceStub + extends io.grpc.stub.AbstractAsyncStub { private LoadBalancerStatsServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -209,11 +219,53 @@ public void getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadB } /** + * A stub to allow clients to do synchronous rpc calls to service LoadBalancerStatsService. *
    * A service used to obtain stats for verifying LB behavior.
    * 
*/ - public static final class LoadBalancerStatsServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class LoadBalancerStatsServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private LoadBalancerStatsServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected LoadBalancerStatsServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new LoadBalancerStatsServiceBlockingV2Stub(channel, callOptions); + } + + /** + *
+     * Gets the backend distribution for RPCs sent by a test client.
+     * 
+ */ + public io.grpc.testing.integration.Messages.LoadBalancerStatsResponse getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getGetClientStatsMethod(), getCallOptions(), request); + } + + /** + *
+     * Gets the accumulated stats for RPCs sent by a test client.
+     * 
+ */ + public io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getGetClientAccumulatedStatsMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service LoadBalancerStatsService. + *
+   * A service used to obtain stats for verifying LB behavior.
+   * 
+ */ + public static final class LoadBalancerStatsServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private LoadBalancerStatsServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -247,11 +299,13 @@ public io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service LoadBalancerStatsService. *
    * A service used to obtain stats for verifying LB behavior.
    * 
*/ - public static final class LoadBalancerStatsServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class LoadBalancerStatsServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private LoadBalancerStatsServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -294,10 +348,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final LoadBalancerStatsServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(LoadBalancerStatsServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -330,6 +384,25 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getGetClientStatsMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.LoadBalancerStatsRequest, + io.grpc.testing.integration.Messages.LoadBalancerStatsResponse>( + service, METHODID_GET_CLIENT_STATS))) + .addMethod( + getGetClientAccumulatedStatsMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest, + io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse>( + service, METHODID_GET_CLIENT_ACCUMULATED_STATS))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/MetricsServiceGrpc.java b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/MetricsServiceGrpc.java index 66cf6267be6..c99abcff7cb 100644 --- a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/MetricsServiceGrpc.java +++ b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/MetricsServiceGrpc.java @@ -4,14 +4,12 @@ /** */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/metrics.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class MetricsServiceGrpc { private MetricsServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.MetricsService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.MetricsService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public MetricsServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new MetricsServiceBlockingV2Stub(channel, callOptions); + } + }; + return MetricsServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -120,7 +133,7 @@ public MetricsServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOpt /** */ - public static abstract class MetricsServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** *
@@ -128,7 +141,7 @@ public static abstract class MetricsServiceImplBase implements io.grpc.BindableS
      * the service
      * 
*/ - public void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request, + default void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetAllGaugesMethod(), responseObserver); } @@ -138,34 +151,28 @@ public void getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage reques * Returns the value of one gauge * */ - public void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request, + default void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetGaugeMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service MetricsService. + */ + public static abstract class MetricsServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getGetAllGaugesMethod(), - io.grpc.stub.ServerCalls.asyncServerStreamingCall( - new MethodHandlers< - io.grpc.testing.integration.Metrics.EmptyMessage, - io.grpc.testing.integration.Metrics.GaugeResponse>( - this, METHODID_GET_ALL_GAUGES))) - .addMethod( - getGetGaugeMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Metrics.GaugeRequest, - io.grpc.testing.integration.Metrics.GaugeResponse>( - this, METHODID_GET_GAUGE))) - .build(); + return MetricsServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service MetricsService. */ - public static final class MetricsServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class MetricsServiceStub + extends io.grpc.stub.AbstractAsyncStub { private MetricsServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -202,8 +209,50 @@ public void getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request, } /** + * A stub to allow clients to do synchronous rpc calls to service MetricsService. + */ + public static final class MetricsServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private MetricsServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected MetricsServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new MetricsServiceBlockingV2Stub(channel, callOptions); + } + + /** + *
+     * Returns the values of all the gauges that are currently being maintained by
+     * the service
+     * 
+ */ + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918") + public io.grpc.stub.BlockingClientCall + getAllGauges(io.grpc.testing.integration.Metrics.EmptyMessage request) { + return io.grpc.stub.ClientCalls.blockingV2ServerStreamingCall( + getChannel(), getGetAllGaugesMethod(), getCallOptions(), request); + } + + /** + *
+     * Returns the value of one gauge
+     * 
+ */ + public io.grpc.testing.integration.Metrics.GaugeResponse getGauge(io.grpc.testing.integration.Metrics.GaugeRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getGetGaugeMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service MetricsService. */ - public static final class MetricsServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class MetricsServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private MetricsServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -239,8 +288,10 @@ public io.grpc.testing.integration.Metrics.GaugeResponse getGauge(io.grpc.testin } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service MetricsService. */ - public static final class MetricsServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class MetricsServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private MetricsServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -272,10 +323,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final MetricsServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(MetricsServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -308,6 +359,25 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getGetAllGaugesMethod(), + io.grpc.stub.ServerCalls.asyncServerStreamingCall( + new MethodHandlers< + io.grpc.testing.integration.Metrics.EmptyMessage, + io.grpc.testing.integration.Metrics.GaugeResponse>( + service, METHODID_GET_ALL_GAUGES))) + .addMethod( + getGetGaugeMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Metrics.GaugeRequest, + io.grpc.testing.integration.Metrics.GaugeResponse>( + service, METHODID_GET_GAUGE))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/ReconnectServiceGrpc.java b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/ReconnectServiceGrpc.java index 32e8e5e40d1..fffcaad2df2 100644 --- a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/ReconnectServiceGrpc.java +++ b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/ReconnectServiceGrpc.java @@ -7,37 +7,35 @@ * A service used to control reconnect server. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class ReconnectServiceGrpc { private ReconnectServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.ReconnectService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.ReconnectService"; // Static method descriptors that strictly reflect the proto. - private static volatile io.grpc.MethodDescriptor getStartMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "Start", - requestType = io.grpc.testing.integration.EmptyProtos.Empty.class, + requestType = io.grpc.testing.integration.Messages.ReconnectParams.class, responseType = io.grpc.testing.integration.EmptyProtos.Empty.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) - public static io.grpc.MethodDescriptor getStartMethod() { - io.grpc.MethodDescriptor getStartMethod; + io.grpc.MethodDescriptor getStartMethod; if ((getStartMethod = ReconnectServiceGrpc.getStartMethod) == null) { synchronized (ReconnectServiceGrpc.class) { if ((getStartMethod = ReconnectServiceGrpc.getStartMethod) == null) { ReconnectServiceGrpc.getStartMethod = getStartMethod = - io.grpc.MethodDescriptor.newBuilder() + io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "Start")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller( - io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance())) + io.grpc.testing.integration.Messages.ReconnectParams.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller( io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance())) .build(); @@ -91,6 +89,21 @@ public ReconnectServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions return ReconnectServiceStub.newStub(factory, channel); } + /** + * Creates a new blocking-style stub that supports all types of calls on the service + */ + public static ReconnectServiceBlockingV2Stub newBlockingV2Stub( + io.grpc.Channel channel) { + io.grpc.stub.AbstractStub.StubFactory factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public ReconnectServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new ReconnectServiceBlockingV2Stub(channel, callOptions); + } + }; + return ReconnectServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -126,48 +139,45 @@ public ReconnectServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallO * A service used to control reconnect server. * */ - public static abstract class ReconnectServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** */ - public void start(io.grpc.testing.integration.EmptyProtos.Empty request, + default void start(io.grpc.testing.integration.Messages.ReconnectParams request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getStartMethod(), responseObserver); } /** */ - public void stop(io.grpc.testing.integration.EmptyProtos.Empty request, + default void stop(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getStopMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service ReconnectService. + *
+   * A service used to control reconnect server.
+   * 
+ */ + public static abstract class ReconnectServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getStartMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_START))) - .addMethod( - getStopMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.Messages.ReconnectInfo>( - this, METHODID_STOP))) - .build(); + return ReconnectServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service ReconnectService. *
    * A service used to control reconnect server.
    * 
*/ - public static final class ReconnectServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class ReconnectServiceStub + extends io.grpc.stub.AbstractAsyncStub { private ReconnectServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -181,7 +191,7 @@ protected ReconnectServiceStub build( /** */ - public void start(io.grpc.testing.integration.EmptyProtos.Empty request, + public void start(io.grpc.testing.integration.Messages.ReconnectParams request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getStartMethod(), getCallOptions()), request, responseObserver); @@ -197,11 +207,47 @@ public void stop(io.grpc.testing.integration.EmptyProtos.Empty request, } /** + * A stub to allow clients to do synchronous rpc calls to service ReconnectService. *
    * A service used to control reconnect server.
    * 
*/ - public static final class ReconnectServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class ReconnectServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private ReconnectServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected ReconnectServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new ReconnectServiceBlockingV2Stub(channel, callOptions); + } + + /** + */ + public io.grpc.testing.integration.EmptyProtos.Empty start(io.grpc.testing.integration.Messages.ReconnectParams request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getStartMethod(), getCallOptions(), request); + } + + /** + */ + public io.grpc.testing.integration.Messages.ReconnectInfo stop(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getStopMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service ReconnectService. + *
+   * A service used to control reconnect server.
+   * 
+ */ + public static final class ReconnectServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private ReconnectServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -215,7 +261,7 @@ protected ReconnectServiceBlockingStub build( /** */ - public io.grpc.testing.integration.EmptyProtos.Empty start(io.grpc.testing.integration.EmptyProtos.Empty request) { + public io.grpc.testing.integration.EmptyProtos.Empty start(io.grpc.testing.integration.Messages.ReconnectParams request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getStartMethod(), getCallOptions(), request); } @@ -229,11 +275,13 @@ public io.grpc.testing.integration.Messages.ReconnectInfo stop(io.grpc.testing.i } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service ReconnectService. *
    * A service used to control reconnect server.
    * 
*/ - public static final class ReconnectServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class ReconnectServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private ReconnectServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -248,7 +296,7 @@ protected ReconnectServiceFutureStub build( /** */ public com.google.common.util.concurrent.ListenableFuture start( - io.grpc.testing.integration.EmptyProtos.Empty request) { + io.grpc.testing.integration.Messages.ReconnectParams request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getStartMethod(), getCallOptions()), request); } @@ -270,10 +318,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final ReconnectServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(ReconnectServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -283,7 +331,7 @@ private static final class MethodHandlers implements public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { case METHODID_START: - serviceImpl.start((io.grpc.testing.integration.EmptyProtos.Empty) request, + serviceImpl.start((io.grpc.testing.integration.Messages.ReconnectParams) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_STOP: @@ -306,6 +354,25 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getStartMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.ReconnectParams, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_START))) + .addMethod( + getStopMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.Messages.ReconnectInfo>( + service, METHODID_STOP))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/TestServiceGrpc.java b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/TestServiceGrpc.java index 5f767f314c8..1d7805e3a3f 100644 --- a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/TestServiceGrpc.java +++ b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/TestServiceGrpc.java @@ -8,14 +8,12 @@ * performance with various types of payload. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class TestServiceGrpc { private TestServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.TestService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.TestService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public TestServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new TestServiceBlockingV2Stub(channel, callOptions); + } + }; + return TestServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -308,14 +321,14 @@ public TestServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOption * performance with various types of payload. * */ - public static abstract class TestServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** *
      * One empty request followed by one empty response.
      * 
*/ - public void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request, + default void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getEmptyCallMethod(), responseObserver); } @@ -325,7 +338,7 @@ public void emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request, * One request followed by one response. * */ - public void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request, + default void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnaryCallMethod(), responseObserver); } @@ -337,7 +350,7 @@ public void unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request * satisfy subsequent requests. * */ - public void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request, + default void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getCacheableUnaryCallMethod(), responseObserver); } @@ -348,7 +361,7 @@ public void cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleReques * The server returns the payload with client desired type and sizes. * */ - public void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request, + default void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getStreamingOutputCallMethod(), responseObserver); } @@ -359,7 +372,7 @@ public void streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOu * The server returns the aggregated size of client payload as the result. * */ - public io.grpc.stub.StreamObserver streamingInputCall( + default io.grpc.stub.StreamObserver streamingInputCall( io.grpc.stub.StreamObserver responseObserver) { return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getStreamingInputCallMethod(), responseObserver); } @@ -371,7 +384,7 @@ public io.grpc.stub.StreamObserver */ - public io.grpc.stub.StreamObserver fullDuplexCall( + default io.grpc.stub.StreamObserver fullDuplexCall( io.grpc.stub.StreamObserver responseObserver) { return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getFullDuplexCallMethod(), responseObserver); } @@ -384,7 +397,7 @@ public io.grpc.stub.StreamObserver */ - public io.grpc.stub.StreamObserver halfDuplexCall( + default io.grpc.stub.StreamObserver halfDuplexCall( io.grpc.stub.StreamObserver responseObserver) { return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getHalfDuplexCallMethod(), responseObserver); } @@ -395,80 +408,36 @@ public io.grpc.stub.StreamObserver */ - public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request, + default void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service TestService. + *
+   * A simple service to test the various types of RPCs and experiment with
+   * performance with various types of payload.
+   * 
+ */ + public static abstract class TestServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getEmptyCallMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_EMPTY_CALL))) - .addMethod( - getUnaryCallMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.SimpleRequest, - io.grpc.testing.integration.Messages.SimpleResponse>( - this, METHODID_UNARY_CALL))) - .addMethod( - getCacheableUnaryCallMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.SimpleRequest, - io.grpc.testing.integration.Messages.SimpleResponse>( - this, METHODID_CACHEABLE_UNARY_CALL))) - .addMethod( - getStreamingOutputCallMethod(), - io.grpc.stub.ServerCalls.asyncServerStreamingCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.StreamingOutputCallRequest, - io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( - this, METHODID_STREAMING_OUTPUT_CALL))) - .addMethod( - getStreamingInputCallMethod(), - io.grpc.stub.ServerCalls.asyncClientStreamingCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.StreamingInputCallRequest, - io.grpc.testing.integration.Messages.StreamingInputCallResponse>( - this, METHODID_STREAMING_INPUT_CALL))) - .addMethod( - getFullDuplexCallMethod(), - io.grpc.stub.ServerCalls.asyncBidiStreamingCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.StreamingOutputCallRequest, - io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( - this, METHODID_FULL_DUPLEX_CALL))) - .addMethod( - getHalfDuplexCallMethod(), - io.grpc.stub.ServerCalls.asyncBidiStreamingCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.StreamingOutputCallRequest, - io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( - this, METHODID_HALF_DUPLEX_CALL))) - .addMethod( - getUnimplementedCallMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_UNIMPLEMENTED_CALL))) - .build(); + return TestServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service TestService. *
    * A simple service to test the various types of RPCs and experiment with
    * performance with various types of payload.
    * 
*/ - public static final class TestServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class TestServiceStub + extends io.grpc.stub.AbstractAsyncStub { private TestServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -580,12 +549,133 @@ public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty requ } /** + * A stub to allow clients to do synchronous rpc calls to service TestService. + *
+   * A simple service to test the various types of RPCs and experiment with
+   * performance with various types of payload.
+   * 
+ */ + public static final class TestServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private TestServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected TestServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new TestServiceBlockingV2Stub(channel, callOptions); + } + + /** + *
+     * One empty request followed by one empty response.
+     * 
+ */ + public io.grpc.testing.integration.EmptyProtos.Empty emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getEmptyCallMethod(), getCallOptions(), request); + } + + /** + *
+     * One request followed by one response.
+     * 
+ */ + public io.grpc.testing.integration.Messages.SimpleResponse unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getUnaryCallMethod(), getCallOptions(), request); + } + + /** + *
+     * One request followed by one response. Response has cache control
+     * headers set such that a caching HTTP proxy (such as GFE) can
+     * satisfy subsequent requests.
+     * 
+ */ + public io.grpc.testing.integration.Messages.SimpleResponse cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getCacheableUnaryCallMethod(), getCallOptions(), request); + } + + /** + *
+     * One request followed by a sequence of responses (streamed download).
+     * The server returns the payload with client desired type and sizes.
+     * 
+ */ + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918") + public io.grpc.stub.BlockingClientCall + streamingOutputCall(io.grpc.testing.integration.Messages.StreamingOutputCallRequest request) { + return io.grpc.stub.ClientCalls.blockingV2ServerStreamingCall( + getChannel(), getStreamingOutputCallMethod(), getCallOptions(), request); + } + + /** + *
+     * A sequence of requests followed by one response (streamed upload).
+     * The server returns the aggregated size of client payload as the result.
+     * 
+ */ + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918") + public io.grpc.stub.BlockingClientCall + streamingInputCall() { + return io.grpc.stub.ClientCalls.blockingClientStreamingCall( + getChannel(), getStreamingInputCallMethod(), getCallOptions()); + } + + /** + *
+     * A sequence of requests with each request served by the server immediately.
+     * As one request could lead to multiple responses, this interface
+     * demonstrates the idea of full duplexing.
+     * 
+ */ + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918") + public io.grpc.stub.BlockingClientCall + fullDuplexCall() { + return io.grpc.stub.ClientCalls.blockingBidiStreamingCall( + getChannel(), getFullDuplexCallMethod(), getCallOptions()); + } + + /** + *
+     * A sequence of requests followed by a sequence of responses.
+     * The server buffers all the client requests and then serves them in order. A
+     * stream of responses are returned to the client when the server starts with
+     * first request.
+     * 
+ */ + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918") + public io.grpc.stub.BlockingClientCall + halfDuplexCall() { + return io.grpc.stub.ClientCalls.blockingBidiStreamingCall( + getChannel(), getHalfDuplexCallMethod(), getCallOptions()); + } + + /** + *
+     * The test server will not implement this method. It will be used
+     * to test the behavior when clients call unimplemented methods.
+     * 
+ */ + public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getUnimplementedCallMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service TestService. *
    * A simple service to test the various types of RPCs and experiment with
    * performance with various types of payload.
    * 
*/ - public static final class TestServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class TestServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private TestServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -654,12 +744,14 @@ public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.t } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service TestService. *
    * A simple service to test the various types of RPCs and experiment with
    * performance with various types of payload.
    * 
*/ - public static final class TestServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class TestServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private TestServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -733,10 +825,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final TestServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(TestServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -790,6 +882,67 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getEmptyCallMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_EMPTY_CALL))) + .addMethod( + getUnaryCallMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.SimpleRequest, + io.grpc.testing.integration.Messages.SimpleResponse>( + service, METHODID_UNARY_CALL))) + .addMethod( + getCacheableUnaryCallMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.SimpleRequest, + io.grpc.testing.integration.Messages.SimpleResponse>( + service, METHODID_CACHEABLE_UNARY_CALL))) + .addMethod( + getStreamingOutputCallMethod(), + io.grpc.stub.ServerCalls.asyncServerStreamingCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.StreamingOutputCallRequest, + io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( + service, METHODID_STREAMING_OUTPUT_CALL))) + .addMethod( + getStreamingInputCallMethod(), + io.grpc.stub.ServerCalls.asyncClientStreamingCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.StreamingInputCallRequest, + io.grpc.testing.integration.Messages.StreamingInputCallResponse>( + service, METHODID_STREAMING_INPUT_CALL))) + .addMethod( + getFullDuplexCallMethod(), + io.grpc.stub.ServerCalls.asyncBidiStreamingCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.StreamingOutputCallRequest, + io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( + service, METHODID_FULL_DUPLEX_CALL))) + .addMethod( + getHalfDuplexCallMethod(), + io.grpc.stub.ServerCalls.asyncBidiStreamingCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.StreamingOutputCallRequest, + io.grpc.testing.integration.Messages.StreamingOutputCallResponse>( + service, METHODID_HALF_DUPLEX_CALL))) + .addMethod( + getUnimplementedCallMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_UNIMPLEMENTED_CALL))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/UnimplementedServiceGrpc.java b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/UnimplementedServiceGrpc.java index 26870496f49..bec9b5a723a 100644 --- a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/UnimplementedServiceGrpc.java +++ b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/UnimplementedServiceGrpc.java @@ -8,14 +8,12 @@ * that case. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class UnimplementedServiceGrpc { private UnimplementedServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.UnimplementedService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.UnimplementedService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public UnimplementedServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new UnimplementedServiceBlockingV2Stub(channel, callOptions); + } + }; + return UnimplementedServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -98,38 +111,43 @@ public UnimplementedServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.C * that case. * */ - public static abstract class UnimplementedServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** *
      * A call that no server should implement
      * 
*/ - public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request, + default void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnimplementedCallMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service UnimplementedService. + *
+   * A simple service NOT implemented at servers so clients can test for
+   * that case.
+   * 
+ */ + public static abstract class UnimplementedServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getUnimplementedCallMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_UNIMPLEMENTED_CALL))) - .build(); + return UnimplementedServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service UnimplementedService. *
    * A simple service NOT implemented at servers so clients can test for
    * that case.
    * 
*/ - public static final class UnimplementedServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class UnimplementedServiceStub + extends io.grpc.stub.AbstractAsyncStub { private UnimplementedServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -154,12 +172,45 @@ public void unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty requ } /** + * A stub to allow clients to do synchronous rpc calls to service UnimplementedService. + *
+   * A simple service NOT implemented at servers so clients can test for
+   * that case.
+   * 
+ */ + public static final class UnimplementedServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private UnimplementedServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected UnimplementedServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new UnimplementedServiceBlockingV2Stub(channel, callOptions); + } + + /** + *
+     * A call that no server should implement
+     * 
+ */ + public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getUnimplementedCallMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service UnimplementedService. *
    * A simple service NOT implemented at servers so clients can test for
    * that case.
    * 
*/ - public static final class UnimplementedServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class UnimplementedServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private UnimplementedServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -183,12 +234,14 @@ public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.t } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service UnimplementedService. *
    * A simple service NOT implemented at servers so clients can test for
    * that case.
    * 
*/ - public static final class UnimplementedServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class UnimplementedServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private UnimplementedServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -219,10 +272,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final UnimplementedServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(UnimplementedServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -251,6 +304,18 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getUnimplementedCallMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_UNIMPLEMENTED_CALL))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/XdsUpdateClientConfigureServiceGrpc.java b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/XdsUpdateClientConfigureServiceGrpc.java index 47293f3b172..3453b6c01be 100644 --- a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/XdsUpdateClientConfigureServiceGrpc.java +++ b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/XdsUpdateClientConfigureServiceGrpc.java @@ -7,14 +7,12 @@ * A service to dynamically update the configuration of an xDS test client. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class XdsUpdateClientConfigureServiceGrpc { private XdsUpdateClientConfigureServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.XdsUpdateClientConfigureService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.XdsUpdateClientConfigureService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public XdsUpdateClientConfigureServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new XdsUpdateClientConfigureServiceBlockingV2Stub(channel, callOptions); + } + }; + return XdsUpdateClientConfigureServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -96,37 +109,41 @@ public XdsUpdateClientConfigureServiceFutureStub newStub(io.grpc.Channel channel * A service to dynamically update the configuration of an xDS test client. * */ - public static abstract class XdsUpdateClientConfigureServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** *
      * Update the tes client's configuration.
      * 
*/ - public void configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request, + default void configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getConfigureMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service XdsUpdateClientConfigureService. + *
+   * A service to dynamically update the configuration of an xDS test client.
+   * 
+ */ + public static abstract class XdsUpdateClientConfigureServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getConfigureMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.Messages.ClientConfigureRequest, - io.grpc.testing.integration.Messages.ClientConfigureResponse>( - this, METHODID_CONFIGURE))) - .build(); + return XdsUpdateClientConfigureServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service XdsUpdateClientConfigureService. *
    * A service to dynamically update the configuration of an xDS test client.
    * 
*/ - public static final class XdsUpdateClientConfigureServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class XdsUpdateClientConfigureServiceStub + extends io.grpc.stub.AbstractAsyncStub { private XdsUpdateClientConfigureServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -151,11 +168,43 @@ public void configure(io.grpc.testing.integration.Messages.ClientConfigureReques } /** + * A stub to allow clients to do synchronous rpc calls to service XdsUpdateClientConfigureService. + *
+   * A service to dynamically update the configuration of an xDS test client.
+   * 
+ */ + public static final class XdsUpdateClientConfigureServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private XdsUpdateClientConfigureServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected XdsUpdateClientConfigureServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new XdsUpdateClientConfigureServiceBlockingV2Stub(channel, callOptions); + } + + /** + *
+     * Update the tes client's configuration.
+     * 
+ */ + public io.grpc.testing.integration.Messages.ClientConfigureResponse configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getConfigureMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service XdsUpdateClientConfigureService. *
    * A service to dynamically update the configuration of an xDS test client.
    * 
*/ - public static final class XdsUpdateClientConfigureServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class XdsUpdateClientConfigureServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private XdsUpdateClientConfigureServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -179,11 +228,13 @@ public io.grpc.testing.integration.Messages.ClientConfigureResponse configure(io } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service XdsUpdateClientConfigureService. *
    * A service to dynamically update the configuration of an xDS test client.
    * 
*/ - public static final class XdsUpdateClientConfigureServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class XdsUpdateClientConfigureServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private XdsUpdateClientConfigureServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -214,10 +265,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final XdsUpdateClientConfigureServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(XdsUpdateClientConfigureServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -246,6 +297,18 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getConfigureMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.Messages.ClientConfigureRequest, + io.grpc.testing.integration.Messages.ClientConfigureResponse>( + service, METHODID_CONFIGURE))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/XdsUpdateHealthServiceGrpc.java b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/XdsUpdateHealthServiceGrpc.java index 3ee2e416431..fb5f2cdebc7 100644 --- a/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/XdsUpdateHealthServiceGrpc.java +++ b/android-interop-testing/src/generated/release/grpc/io/grpc/testing/integration/XdsUpdateHealthServiceGrpc.java @@ -7,14 +7,12 @@ * A service to remotely control health status of an xDS test server. * */ -@javax.annotation.Generated( - value = "by gRPC proto compiler", - comments = "Source: grpc/testing/test.proto") +@io.grpc.stub.annotations.GrpcGenerated public final class XdsUpdateHealthServiceGrpc { private XdsUpdateHealthServiceGrpc() {} - public static final String SERVICE_NAME = "grpc.testing.XdsUpdateHealthService"; + public static final java.lang.String SERVICE_NAME = "grpc.testing.XdsUpdateHealthService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor factory = + new io.grpc.stub.AbstractStub.StubFactory() { + @java.lang.Override + public XdsUpdateHealthServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new XdsUpdateHealthServiceBlockingV2Stub(channel, callOptions); + } + }; + return XdsUpdateHealthServiceBlockingV2Stub.newStub(factory, channel); + } + /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ @@ -126,48 +139,45 @@ public XdsUpdateHealthServiceFutureStub newStub(io.grpc.Channel channel, io.grpc * A service to remotely control health status of an xDS test server. * */ - public static abstract class XdsUpdateHealthServiceImplBase implements io.grpc.BindableService { + public interface AsyncService { /** */ - public void setServing(io.grpc.testing.integration.EmptyProtos.Empty request, + default void setServing(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSetServingMethod(), responseObserver); } /** */ - public void setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request, + default void setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSetNotServingMethod(), responseObserver); } + } + + /** + * Base class for the server implementation of the service XdsUpdateHealthService. + *
+   * A service to remotely control health status of an xDS test server.
+   * 
+ */ + public static abstract class XdsUpdateHealthServiceImplBase + implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - getSetServingMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_SET_SERVING))) - .addMethod( - getSetNotServingMethod(), - io.grpc.stub.ServerCalls.asyncUnaryCall( - new MethodHandlers< - io.grpc.testing.integration.EmptyProtos.Empty, - io.grpc.testing.integration.EmptyProtos.Empty>( - this, METHODID_SET_NOT_SERVING))) - .build(); + return XdsUpdateHealthServiceGrpc.bindService(this); } } /** + * A stub to allow clients to do asynchronous rpc calls to service XdsUpdateHealthService. *
    * A service to remotely control health status of an xDS test server.
    * 
*/ - public static final class XdsUpdateHealthServiceStub extends io.grpc.stub.AbstractAsyncStub { + public static final class XdsUpdateHealthServiceStub + extends io.grpc.stub.AbstractAsyncStub { private XdsUpdateHealthServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -197,11 +207,47 @@ public void setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request, } /** + * A stub to allow clients to do synchronous rpc calls to service XdsUpdateHealthService. *
    * A service to remotely control health status of an xDS test server.
    * 
*/ - public static final class XdsUpdateHealthServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub { + public static final class XdsUpdateHealthServiceBlockingV2Stub + extends io.grpc.stub.AbstractBlockingStub { + private XdsUpdateHealthServiceBlockingV2Stub( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected XdsUpdateHealthServiceBlockingV2Stub build( + io.grpc.Channel channel, io.grpc.CallOptions callOptions) { + return new XdsUpdateHealthServiceBlockingV2Stub(channel, callOptions); + } + + /** + */ + public io.grpc.testing.integration.EmptyProtos.Empty setServing(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getSetServingMethod(), getCallOptions(), request); + } + + /** + */ + public io.grpc.testing.integration.EmptyProtos.Empty setNotServing(io.grpc.testing.integration.EmptyProtos.Empty request) throws io.grpc.StatusException { + return io.grpc.stub.ClientCalls.blockingV2UnaryCall( + getChannel(), getSetNotServingMethod(), getCallOptions(), request); + } + } + + /** + * A stub to allow clients to do limited synchronous rpc calls to service XdsUpdateHealthService. + *
+   * A service to remotely control health status of an xDS test server.
+   * 
+ */ + public static final class XdsUpdateHealthServiceBlockingStub + extends io.grpc.stub.AbstractBlockingStub { private XdsUpdateHealthServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -229,11 +275,13 @@ public io.grpc.testing.integration.EmptyProtos.Empty setNotServing(io.grpc.testi } /** + * A stub to allow clients to do ListenableFuture-style rpc calls to service XdsUpdateHealthService. *
    * A service to remotely control health status of an xDS test server.
    * 
*/ - public static final class XdsUpdateHealthServiceFutureStub extends io.grpc.stub.AbstractFutureStub { + public static final class XdsUpdateHealthServiceFutureStub + extends io.grpc.stub.AbstractFutureStub { private XdsUpdateHealthServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); @@ -270,10 +318,10 @@ private static final class MethodHandlers implements io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final XdsUpdateHealthServiceImplBase serviceImpl; + private final AsyncService serviceImpl; private final int methodId; - MethodHandlers(XdsUpdateHealthServiceImplBase serviceImpl, int methodId) { + MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @@ -306,6 +354,25 @@ public io.grpc.stub.StreamObserver invoke( } } + public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getSetServingMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_SET_SERVING))) + .addMethod( + getSetNotServingMethod(), + io.grpc.stub.ServerCalls.asyncUnaryCall( + new MethodHandlers< + io.grpc.testing.integration.EmptyProtos.Empty, + io.grpc.testing.integration.EmptyProtos.Empty>( + service, METHODID_SET_NOT_SERVING))) + .build(); + } + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { diff --git a/android-interop-testing/src/main/AndroidManifest.xml b/android-interop-testing/src/main/AndroidManifest.xml index c3f35131ad4..08c139e5880 100644 --- a/android-interop-testing/src/main/AndroidManifest.xml +++ b/android-interop-testing/src/main/AndroidManifest.xml @@ -1,24 +1,32 @@ + xmlns:tools="http://schemas.android.com/tools"> + + + + + android:theme="@style/Base.V7.Theme.AppCompat.Light"> + android:exported="true"> + + + diff --git a/android-interop-testing/src/main/java/io/grpc/android/integrationtest/InteropTask.java b/android-interop-testing/src/main/java/io/grpc/android/integrationtest/InteropTask.java deleted file mode 100644 index 8beaea3ec9c..00000000000 --- a/android-interop-testing/src/main/java/io/grpc/android/integrationtest/InteropTask.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright 2018 The gRPC 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.grpc.android.integrationtest; - -import android.os.AsyncTask; -import android.util.Log; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.testing.integration.AbstractInteropTest; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.ref.WeakReference; -import org.junit.AssumptionViolatedException; - -/** AsyncTask for interop test cases. */ -final class InteropTask extends AsyncTask { - private static final String LOG_TAG = "GrpcInteropTask"; - - interface Listener { - void onComplete(String result); - } - - static final String SUCCESS_MESSAGE = "Success!"; - - private final WeakReference listenerReference; - private final String testCase; - private final Tester tester; - - InteropTask( - Listener listener, - ManagedChannel channel, - String testCase) { - this.listenerReference = new WeakReference(listener); - this.testCase = testCase; - this.tester = new Tester(channel); - } - - @Override - protected void onPreExecute() { - tester.setUp(); - } - - @SuppressWarnings("Finally") - @Override - protected String doInBackground(Void... ignored) { - try { - runTest(testCase); - return SUCCESS_MESSAGE; - } catch (Throwable t) { - // Print the stack trace to logcat. - t.printStackTrace(); - // Then print to the error message. - StringWriter sw = new StringWriter(); - t.printStackTrace(new PrintWriter(sw)); - return "Failed... : " + t.getMessage() + "\n" + sw; - } finally { - try { - tester.tearDown(); - } catch (RuntimeException ex) { - throw ex; - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - } - - private void runTest(String testCase) throws Exception { - Log.i(LOG_TAG, "Running test case: " + testCase); - if ("empty_unary".equals(testCase)) { - tester.emptyUnary(); - } else if ("large_unary".equals(testCase)) { - try { - tester.largeUnary(); - } catch (AssumptionViolatedException e) { - // This test case requires more memory than most Android devices have available - Log.w(LOG_TAG, "Skipping " + testCase + " due to assumption violation", e); - } - } else if ("client_streaming".equals(testCase)) { - tester.clientStreaming(); - } else if ("server_streaming".equals(testCase)) { - tester.serverStreaming(); - } else if ("ping_pong".equals(testCase)) { - tester.pingPong(); - } else if ("empty_stream".equals(testCase)) { - tester.emptyStream(); - } else if ("cancel_after_begin".equals(testCase)) { - tester.cancelAfterBegin(); - } else if ("cancel_after_first_response".equals(testCase)) { - tester.cancelAfterFirstResponse(); - } else if ("full_duplex_call_should_succeed".equals(testCase)) { - tester.fullDuplexCallShouldSucceed(); - } else if ("half_duplex_call_should_succeed".equals(testCase)) { - tester.halfDuplexCallShouldSucceed(); - } else if ("server_streaming_should_be_flow_controlled".equals(testCase)) { - tester.serverStreamingShouldBeFlowControlled(); - } else if ("very_large_request".equals(testCase)) { - try { - tester.veryLargeRequest(); - } catch (AssumptionViolatedException e) { - // This test case requires more memory than most Android devices have available - Log.w(LOG_TAG, "Skipping " + testCase + " due to assumption violation", e); - } - } else if ("very_large_response".equals(testCase)) { - try { - tester.veryLargeResponse(); - } catch (AssumptionViolatedException e) { - // This test case requires more memory than most Android devices have available - Log.w(LOG_TAG, "Skipping " + testCase + " due to assumption violation", e); - } - } else if ("deadline_not_exceeded".equals(testCase)) { - tester.deadlineNotExceeded(); - } else if ("deadline_exceeded".equals(testCase)) { - tester.deadlineExceeded(); - } else if ("deadline_exceeded_server_streaming".equals(testCase)) { - tester.deadlineExceededServerStreaming(); - } else if ("unimplemented_method".equals(testCase)) { - tester.unimplementedMethod(); - } else if ("timeout_on_sleeping_server".equals(testCase)) { - tester.timeoutOnSleepingServer(); - } else if ("graceful_shutdown".equals(testCase)) { - tester.gracefulShutdown(); - } else { - throw new IllegalArgumentException("Unimplemented/Unknown test case: " + testCase); - } - } - - @Override - protected void onPostExecute(String result) { - Listener listener = listenerReference.get(); - if (listener != null) { - listener.onComplete(result); - } - } - - private static class Tester extends AbstractInteropTest { - - private Tester(ManagedChannel channel) { - this.channel = channel; - } - - @Override - protected ManagedChannel createChannel() { - return channel; - } - - @Override - protected ManagedChannelBuilder createChannelBuilder() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean metricsExpected() { - return false; - } - } -} diff --git a/android-interop-testing/src/main/java/io/grpc/android/integrationtest/TestCallable.java b/android-interop-testing/src/main/java/io/grpc/android/integrationtest/TestCallable.java new file mode 100644 index 00000000000..56ea75bb657 --- /dev/null +++ b/android-interop-testing/src/main/java/io/grpc/android/integrationtest/TestCallable.java @@ -0,0 +1,149 @@ +/* + * Copyright 2023 The gRPC 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.android.integrationtest; + +import android.util.Log; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.testing.integration.AbstractInteropTest; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.concurrent.Callable; +import org.junit.AssumptionViolatedException; + +/** + * Used to run a single test case against a channel in a separate thread. + */ +public class TestCallable implements Callable { + private final ManagedChannel channel; + private final String testCase; + + private static final String LOG_TAG = "GrpcInteropTask"; + static final String SUCCESS_MESSAGE = "Success!"; + + public TestCallable(ManagedChannel channel, String testCase) { + this.channel = channel; + this.testCase = testCase; + } + + @Override + public String call() { + Tester tester = new Tester(channel); + tester.setUp(); + try { + runTest(tester, testCase); + return SUCCESS_MESSAGE; + } catch (Throwable t) { + // Print the stack trace to logcat. + t.printStackTrace(); + // Then print to the error message. + StringWriter sw = new StringWriter(); + t.printStackTrace(new PrintWriter(sw)); + return "Failed... : " + t.getMessage() + "\n" + sw; + } finally { + try { + tester.tearDown(); + } catch (RuntimeException ex) { + throw ex; + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + } + + private void runTest(Tester tester, String testCase) throws Exception { + Log.i(LOG_TAG, "Running test case: " + testCase); + if ("empty_unary".equals(testCase)) { + tester.emptyUnary(); + } else if ("large_unary".equals(testCase)) { + try { + tester.largeUnary(); + } catch (AssumptionViolatedException e) { + // This test case requires more memory than most Android devices have available + Log.w(LOG_TAG, "Skipping " + testCase + " due to assumption violation", e); + } + } else if ("client_streaming".equals(testCase)) { + tester.clientStreaming(); + } else if ("server_streaming".equals(testCase)) { + tester.serverStreaming(); + } else if ("ping_pong".equals(testCase)) { + tester.pingPong(); + } else if ("empty_stream".equals(testCase)) { + tester.emptyStream(); + } else if ("cancel_after_begin".equals(testCase)) { + tester.cancelAfterBegin(); + } else if ("cancel_after_first_response".equals(testCase)) { + tester.cancelAfterFirstResponse(); + } else if ("full_duplex_call_should_succeed".equals(testCase)) { + tester.fullDuplexCallShouldSucceed(); + } else if ("half_duplex_call_should_succeed".equals(testCase)) { + tester.halfDuplexCallShouldSucceed(); + } else if ("server_streaming_should_be_flow_controlled".equals(testCase)) { + tester.serverStreamingShouldBeFlowControlled(); + } else if ("very_large_request".equals(testCase)) { + try { + tester.veryLargeRequest(); + } catch (AssumptionViolatedException e) { + // This test case requires more memory than most Android devices have available + Log.w(LOG_TAG, "Skipping " + testCase + " due to assumption violation", e); + } + } else if ("very_large_response".equals(testCase)) { + try { + tester.veryLargeResponse(); + } catch (AssumptionViolatedException e) { + // This test case requires more memory than most Android devices have available + Log.w(LOG_TAG, "Skipping " + testCase + " due to assumption violation", e); + } + } else if ("deadline_not_exceeded".equals(testCase)) { + tester.deadlineNotExceeded(); + } else if ("deadline_exceeded".equals(testCase)) { + tester.deadlineExceeded(); + } else if ("deadline_exceeded_server_streaming".equals(testCase)) { + tester.deadlineExceededServerStreaming(); + } else if ("unimplemented_method".equals(testCase)) { + tester.unimplementedMethod(); + } else if ("timeout_on_sleeping_server".equals(testCase)) { + tester.timeoutOnSleepingServer(); + } else if ("graceful_shutdown".equals(testCase)) { + tester.gracefulShutdown(); + } else { + throw new IllegalArgumentException("Unimplemented/Unknown test case: " + testCase); + } + } + + private static class Tester extends AbstractInteropTest { + + private Tester(ManagedChannel channel) { + this.channel = channel; + } + + @Override + protected ManagedChannel createChannel() { + return channel; + } + + @Override + protected ManagedChannelBuilder createChannelBuilder() { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean metricsExpected() { + return false; + } + } +} diff --git a/android-interop-testing/src/main/java/io/grpc/android/integrationtest/TesterActivity.java b/android-interop-testing/src/main/java/io/grpc/android/integrationtest/TesterActivity.java index 004950e7380..17c7e24cbfa 100644 --- a/android-interop-testing/src/main/java/io/grpc/android/integrationtest/TesterActivity.java +++ b/android-interop-testing/src/main/java/io/grpc/android/integrationtest/TesterActivity.java @@ -18,8 +18,8 @@ import android.content.Context; import android.content.Intent; +import android.net.LocalSocketAddress.Namespace; import android.os.Bundle; -import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; @@ -28,22 +28,34 @@ import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; +import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.security.ProviderInstaller; import io.grpc.ManagedChannel; +import io.grpc.android.UdsChannelBuilder; +import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; public class TesterActivity extends AppCompatActivity - implements ProviderInstaller.ProviderInstallListener, InteropTask.Listener { + implements ProviderInstaller.ProviderInstallListener { private static final String LOG_TAG = "GrpcTesterActivity"; private List